Search is not available for this dataset
content
stringlengths
60
399M
max_stars_repo_name
stringlengths
6
110
<|start_filename|>win/platform.c<|end_filename|> /**************************************************************** platform.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #include "../gui/gui.h" #include "../toolkit/shared.h" #include "platform.h" #include <windows.h> #include <time.h> #include <stdio.h> /** Stolen from winuser.h since VS 6.0 does not declare any MIIM_STRING. **/ #ifndef MIIM_STRING #define MIIM_STRING 0x00000040 #endif /** Stolen from winbase.h since VS 6.0 does not declare any INVALID_SET_FILE_POINTER. **/ #ifndef INVALID_SET_FILE_POINTER #define INVALID_SET_FILE_POINTER ((DWORD)-1) #endif /** Globals **/ #ifndef NUMBER_WINDOWS #define NUMBER_WINDOWS 2 #define WINDOW_ONE 0 #define WINDOW_TWO 1 #endif #undef EARLIER_VERSION_STUDIO static n_int practical_number_windows; static n_int practical_window_dimension_x; static n_int practical_window_dimension_y; static HWND global_hwnd[NUMBER_WINDOWS]; static HBITMAP offscreen[NUMBER_WINDOWS]; static BITMAPINFO * bmp_info[NUMBER_WINDOWS]; static n_byte window_definition[NUMBER_WINDOWS] = {NUM_VIEW, NUM_TERRAIN}; static n_int firedown = -1; static unsigned char firecontrol = 0; static unsigned char dialog_up = 0; static HMENU hMenu, hMenuPopup[4]; static HANDLE current_file = NULL; static n_string_block current_file_name[MAX_PATH]; LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); /** Nobleape platform functions **/ static void plat_update(); static n_int plat_ourwind(HWND hwnd); static void plat_file_open(n_byte script); static unsigned char plat_file_save(); static unsigned char plat_file_save_as(); static unsigned char plat_initialized = 0; #define WINDOW_OFFSET_X 16 //6 #define WINDOW_OFFSET_Y (38) //(10+22) #define WINDOW_MENU_OFFSET (21) static void platform_menus(void) { hMenu = CreateMenu(); hMenuPopup[0] = CreateMenu(); AppendMenu(hMenuPopup[0], MF_STRING, FILE_NEW_HANDLE, TEXT("&New")); AppendMenu(hMenuPopup[0], MF_SEPARATOR, 0, NULL); AppendMenu(hMenuPopup[0], MF_STRING, FILE_OPEN_HANDLE, TEXT("&Open...")); AppendMenu(hMenuPopup[0], MF_STRING, FILE_OPEN_SCRIPT_HANDLE, TEXT("Open Script...")); AppendMenu(hMenuPopup[0], MF_SEPARATOR, 0, NULL); AppendMenu(hMenuPopup[0], MF_STRING, FILE_CLOSE_HANDLE, TEXT("&Close")); AppendMenu(hMenuPopup[0], MF_SEPARATOR, 0, NULL); AppendMenu(hMenuPopup[0], MF_STRING, FILE_SAVE_AS_HANDLE, TEXT("&Save As...")); AppendMenu(hMenuPopup[0], MF_SEPARATOR, 0, NULL); AppendMenu(hMenuPopup[0], MF_STRING, FILE_EXIT_HANDLE, TEXT("E&xit")); AppendMenu(hMenu, MF_POPUP | MF_STRING, (UINT)hMenuPopup[0], TEXT("&File")); hMenuPopup[1] = CreateMenu(); AppendMenu(hMenuPopup[1], MF_STRING, EDIT_UNDO_HANDLE, TEXT("&Undo")); AppendMenu(hMenuPopup[1], MF_SEPARATOR, 0, NULL); AppendMenu(hMenuPopup[1], MF_STRING, EDIT_CUT_HANDLE, TEXT("Cu&t")); AppendMenu(hMenuPopup[1], MF_STRING, EDIT_COPY_HANDLE, TEXT("&Copy")); AppendMenu(hMenuPopup[1], MF_STRING, EDIT_PASTE_HANDLE, TEXT("&Paste")); AppendMenu(hMenuPopup[1], MF_STRING, EDIT_CLEAR_HANDLE, TEXT("C&lear")); AppendMenu(hMenu, MF_POPUP | MF_STRING, (UINT)hMenuPopup[1], TEXT("&Edit")); hMenuPopup[2] = CreateMenu(); AppendMenu(hMenuPopup[2], MF_STRING, CONTROL_PAUSE_HANDLE, TEXT("&Pause")); AppendMenu(hMenuPopup[2], MF_SEPARATOR, 0, NULL); AppendMenu(hMenuPopup[2], MF_STRING, CONTROL_PREV_HANDLE, TEXT("P&revious Ape")); AppendMenu(hMenuPopup[2], MF_STRING, CONTROL_NEXT_HANDLE, TEXT ("&Next Ape")); AppendMenu(hMenuPopup[2], MF_SEPARATOR, 0, NULL); AppendMenu(hMenuPopup[2], MF_STRING, CONTROL_CLEAR_ERRORS, TEXT ("Clear Errors")); AppendMenu(hMenuPopup[2], MF_SEPARATOR, 0, NULL); AppendMenu(hMenuPopup[2], MF_STRING, CONTROL_WEATHER_HANDLE, TEXT("Draw &Weather")); AppendMenu(hMenuPopup[2], MF_STRING, CONTROL_BRAIN_HANDLE, TEXT("Draw Brain")); AppendMenu(hMenuPopup[2], MF_STRING, CONTROL_BRAINCODE_HANDLE, TEXT("Draw Brain Code")); AppendMenu(hMenuPopup[2], MF_STRING, CONTROL_TERRITORY_HANDLE, TEXT("Draw Territory")); AppendMenu(hMenuPopup[2], MF_STRING, CONTROL_DAYLIGHT_TIDES_HANDLE, TEXT("Draw Daylight Tides")); AppendMenu(hMenu, MF_POPUP | MF_STRING, (UINT)hMenuPopup[2], TEXT("&Control")); hMenuPopup[3] = CreateMenu(); AppendMenu(hMenuPopup[3], MF_STRING, HELP_ABOUT_HANDLE, TEXT("&About Noble Ape...")); AppendMenu(hMenu, MF_POPUP | MF_STRING, (UINT)hMenuPopup[3], TEXT("&Help")); /* can't close the meters window, it's also the menu window */ EnableMenuItem(hMenuPopup[0], FILE_CLOSE_HANDLE, MF_DISABLED | MF_GRAYED); CheckMenuItem(hMenuPopup[2], CONTROL_WEATHER_HANDLE, MF_CHECKED); CheckMenuItem(hMenuPopup[2], CONTROL_BRAIN_HANDLE, MF_CHECKED); } int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) { /** Create a window with 0 x, or y co-ord, and with the menu attached. **/ int loop = 0; static TCHAR szAppName[] = TEXT ( "NobleApe" ) ; unsigned short i = 0; unsigned short fit[256*3]; #define Y_DELTA 36 #define X_DELTA 20 int window_value[4] = {0, -300, 512, 512}; n_int dimensions[4]; shared_dimensions(dimensions); practical_number_windows = dimensions[0]; practical_window_dimension_x = dimensions[1]; practical_window_dimension_y = dimensions[2]; window_value[2] = practical_window_dimension_x; window_value[3] = practical_window_dimension_y; /** Locals specific to Windows... **/ MSG msg ; WNDCLASS wndclass ; HDC hdc[NUMBER_WINDOWS]; BOOL bReturn; int winOffset = 7; int winOffsetTop = 18; FILETIME ft; unsigned long tmpres = 0; GetSystemTimeAsFileTime(&ft); tmpres = ft.dwHighDateTime; tmpres ^= ft.dwLowDateTime; shared_color_8_bit_to_48_bit(fit); wndclass.style = CS_HREDRAW | CS_VREDRAW ; wndclass.lpfnWndProc = WndProc ; wndclass.cbClsExtra = 0 ; wndclass.cbWndExtra = 0 ; wndclass.hInstance = hInstance ; wndclass.hIcon = LoadIcon (NULL, IDI_APPLICATION) ; wndclass.hCursor = LoadCursor (NULL, IDC_ARROW) ; wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ; wndclass.lpszMenuName = NULL ; wndclass.lpszClassName = szAppName ; if (!RegisterClass (&wndclass)) { MessageBox (NULL, TEXT ("Program requires Windows NT!"), szAppName, MB_ICONERROR) ; return 0 ; } if (dimensions[3]) { platform_menus(); } else { hMenu = NULL; } window_value[1] += window_value[3] + Y_DELTA + 19 + 10; window_value[3] = practical_window_dimension_y; global_hwnd[WINDOW_ONE] = CreateWindow(szAppName, dimensions[3] ? TEXT ( "Noble Ape: Map" ) : TEXT ( "Mushroom Boy" ), WS_OVERLAPPED + WS_SYSMENU, window_value[0], window_value[1], window_value[2] + WINDOW_OFFSET_X, window_value[3] + WINDOW_OFFSET_Y + WINDOW_MENU_OFFSET, NULL, hMenu, hInstance, NULL) ; if (practical_number_windows > 1) { window_value[0] += practical_window_dimension_x + X_DELTA; window_value[2] = practical_window_dimension_x; window_value[3] = practical_window_dimension_y; global_hwnd[WINDOW_TWO] = CreateWindow(szAppName, TEXT ( "Noble Ape: Terrain" ), WS_OVERLAPPED, window_value[0], window_value[1], window_value[2] + WINDOW_OFFSET_X, window_value[3] + WINDOW_OFFSET_Y, NULL, NULL, hInstance, NULL) ; } loop = 0; while (loop < practical_number_windows) { window_definition[loop] = (n_byte)shared_init(window_definition[loop], tmpres); bmp_info[loop] = (LPBITMAPINFO) malloc(sizeof(BYTE) * (sizeof(BITMAPINFOHEADER) + (256 * sizeof(RGBQUAD)))); bmp_info[loop]->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmp_info[loop]->bmiHeader.biWidth = practical_window_dimension_x; bmp_info[loop]->bmiHeader.biHeight = (0 - practical_window_dimension_y) + loop; bmp_info[loop]->bmiHeader.biPlanes = 1; bmp_info[loop]->bmiHeader.biBitCount = 8; bmp_info[loop]->bmiHeader.biCompression = BI_RGB; bmp_info[loop]->bmiHeader.biSizeImage = 0; bmp_info[loop]->bmiHeader.biXPelsPerMeter = 0; bmp_info[loop]->bmiHeader.biYPelsPerMeter = 0; bmp_info[loop]->bmiHeader.biClrUsed = 0; bmp_info[loop]->bmiHeader.biClrImportant = 0; i = 0; while (i < 256) { bmp_info[loop]->bmiColors[i].rgbRed = (unsigned char)(fit[i * 3 + 0] >> 8); bmp_info[loop]->bmiColors[i].rgbGreen = (unsigned char)(fit[i * 3 + 1] >> 8); bmp_info[loop]->bmiColors[i].rgbBlue = (unsigned char)(fit[i * 3 + 2] >> 8); bmp_info[loop]->bmiColors[i].rgbReserved = 0; ++i; } hdc[loop] = GetDC(global_hwnd[loop]); offscreen[loop] = CreateDIBitmap(hdc[loop], (const struct tagBITMAPINFOHEADER *)bmp_info[loop], 0, NULL, NULL, DIB_RGB_COLORS); SetBitmapDimensionEx(offscreen[loop], practical_window_dimension_x, practical_window_dimension_y /*-loop*/, NULL); ShowWindow (global_hwnd[loop], iCmdShow) ; UpdateWindow (global_hwnd[loop]) ; InvalidateRect(global_hwnd[loop], NULL, TRUE); loop++; } plat_initialized = 1; while ( 1 ) { if ( (bReturn = PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) != 0) { if (msg.message == WM_QUIT) return 0; TranslateMessage (&msg) ; DispatchMessage (&msg) ; } } return msg.wParam ; } static int platform_check(int na_menu, int win_menu) { if (shared_menu(na_menu)) CheckMenuItem(hMenuPopup[2], win_menu, MF_CHECKED); else CheckMenuItem(hMenuPopup[2], win_menu, MF_UNCHECKED); return 0; } LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { int i = 0; WORD menu_handle; switch (message) { case WM_ERASEBKGND: return 1; case WM_PAINT: { n_uint local_time = (n_uint)time(0L); shared_cycle(local_time, NUM_VIEW); if (practical_number_windows > 1) { shared_cycle(local_time, NUM_TERRAIN); } } plat_update(); InvalidateRect(global_hwnd[0], NULL, TRUE); if (practical_number_windows > 1) { InvalidateRect(global_hwnd[1], NULL, TRUE); } return 0; case WM_LBUTTONUP: firedown = -1; shared_mouseUp(); return 0; case WM_LBUTTONDOWN: firedown = plat_ourwind(hwnd); case WM_MOUSEMOVE: if (firedown != -1) { shared_mouseOption(firecontrol); shared_mouseReceived(LOWORD(lParam), HIWORD(lParam), (n_byte)firedown); } return 0; case WM_KEYDOWN: { int windownum = plat_ourwind(hwnd); unsigned short response = 0; switch(wParam) { case VK_LEFT: response = 28; break; case VK_RIGHT: response = 29; break; case VK_UP: response = 30; break; case VK_DOWN: response = 31; break; case VK_CONTROL: firecontrol = 1; break; } if(response != 0) { if(firecontrol) { response |= 2048; } if (windownum != -1) { shared_keyReceived(response, windownum); } } } return 0; case WM_KEYUP: firecontrol = 0; /* if(wParam == VK_CONTROL) { firecontrol = 0; } */ shared_keyUp(); return 0; case WM_CLOSE: PostMessage(hwnd, WM_DESTROY, 0, 0); return 0; case WM_COMMAND: menu_handle = LOWORD(wParam); switch (menu_handle) { /** Help Menu... **/ case HELP_ABOUT_HANDLE: CheckMenuItem(hMenuPopup[2], CONTROL_PAUSE_HANDLE, MF_CHECKED); shared_about((unsigned char *)"Windows"); return 0; /** Control Menu... **/ case CONTROL_PAUSE_HANDLE: return platform_check(NA_MENU_PAUSE, CONTROL_PAUSE_HANDLE); case CONTROL_PREV_HANDLE: (void) shared_menu(NA_MENU_PREVIOUS_APE); return 0; case CONTROL_NEXT_HANDLE: (void) shared_menu(NA_MENU_NEXT_APE); return 0; case CONTROL_CLEAR_ERRORS: (void) shared_menu(NA_MENU_CLEAR_ERRORS); return 0; case CONTROL_WEATHER_HANDLE: return platform_check(NA_MENU_WEATHER, CONTROL_WEATHER_HANDLE); case CONTROL_BRAIN_HANDLE: return platform_check(NA_MENU_BRAIN, CONTROL_BRAIN_HANDLE); case CONTROL_BRAINCODE_HANDLE: return platform_check(NA_MENU_BRAINCODE, CONTROL_BRAINCODE_HANDLE); case CONTROL_TERRITORY_HANDLE: return platform_check(NA_MENU_TERRITORY, CONTROL_TERRITORY_HANDLE); case CONTROL_DAYLIGHT_TIDES_HANDLE: return platform_check(NA_MENU_TIDEDAYLIGHT, CONTROL_DAYLIGHT_TIDES_HANDLE); /** File Menu... **/ case FILE_NEW_HANDLE: { FILETIME ft; unsigned long tmpres = 0; GetSystemTimeAsFileTime(&ft); tmpres = ft.dwHighDateTime; tmpres ^= ft.dwLowDateTime; shared_new(tmpres); } return 0; case FILE_OPEN_HANDLE: dialog_up = 1; plat_file_open(0); dialog_up = 0; return 0; case FILE_OPEN_SCRIPT_HANDLE: dialog_up = 1; plat_file_open(1); dialog_up = 0; return 0; case FILE_CLOSE_HANDLE: return 0; case FILE_SAVE_AS_HANDLE: dialog_up = 1; plat_file_save_as(); dialog_up = 0; return 0; case FILE_EXIT_HANDLE: PostMessage(hwnd, WM_DESTROY, 0, 0); return 0; } return 0; case WM_DESTROY: DeleteObject(offscreen[0]); if (practical_number_windows > 1) { DeleteObject(offscreen[1]); } shared_close(); PostQuitMessage (0) ; return 0 ; } return DefWindowProc (hwnd, message, wParam, lParam) ; } static void plat_update() { PAINTSTRUCT ps[NUMBER_WINDOWS]; HDC hdc[NUMBER_WINDOWS]; unsigned char lp = 0; if (plat_initialized == 0) { return; } while (lp < practical_number_windows) { SIZE sz; HDC hdcMem; unsigned char * value = shared_legacy_draw(lp, practical_window_dimension_x, practical_window_dimension_y); hdc[lp] = BeginPaint(global_hwnd[lp], &ps[lp]); GetBitmapDimensionEx(offscreen[lp], &sz); hdcMem = CreateCompatibleDC(hdc[lp]); SetDIBits(hdcMem, offscreen[lp], 0, practical_window_dimension_x/*-lp*/, value, bmp_info[lp], DIB_RGB_COLORS); SelectObject(hdcMem, offscreen[lp]); BitBlt(hdc[lp], 0, 0, sz.cx, sz.cy, hdcMem, 0, 0, SRCCOPY); DeleteDC(hdcMem); EndPaint(global_hwnd[lp], &ps[lp]); lp++; } } static n_int plat_ourwind(HWND hwnd) { unsigned char lp = 0; while (lp < practical_number_windows) { if (hwnd == global_hwnd[lp]) return window_definition[lp]; lp++; } return -1; } static void plat_file_open(n_byte script) { char actual_file_name[MAX_PATH] = { 0 }; long file_return ; OPENFILENAME opf; ZeroMemory(&opf, sizeof(opf)); opf.lStructSize = sizeof(opf); opf.hwndOwner = global_hwnd[WINDOW_ONE]; opf.lpstrFilter = TEXT(NOBLE_APE_FILE_OPEN); opf.nFilterIndex = 1; opf.lpstrFile = (LPWSTR)(current_file_name); opf.nMaxFile = sizeof(current_file_name); opf.lpstrFileTitle = (LPWSTR)actual_file_name; opf.nMaxFileTitle = sizeof(actual_file_name); opf.lpstrInitialDir = NULL; opf.lpstrTitle = TEXT("Noble Ape File Open..."); opf.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; file_return = GetOpenFileName(&opf); if (file_return ) { if(shared_openFileName((n_string)current_file_name, script) == 0) { MessageBox(global_hwnd[0], TEXT("File processing failed"), TEXT("Noble Ape File Error"), MB_OK); CloseHandle(current_file); } CloseHandle(current_file); } } static unsigned char plat_file_save(n_file_out cfo) { unsigned long buff_len; unsigned char * buff = (*cfo)(&buff_len); DWORD seek_result; BOOL write_result; DWORD write_len; if ((current_file = CreateFile((LPCWSTR)&current_file_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) { MessageBox(global_hwnd[0], TEXT("Invalid file handle"), TEXT("Noble Ape File Error"), MB_OK); return 0; } if ((seek_result = SetFilePointer(current_file, 0, NULL, FILE_BEGIN)) == INVALID_SET_FILE_POINTER) { MessageBox(global_hwnd[0], TEXT("Unable to set file pointer"), TEXT("Noble Ape File Error"), MB_OK); CloseHandle(current_file); return 0; } if ((write_result = WriteFile(current_file, buff, buff_len, &write_len, NULL)) == 0) { MessageBox(global_hwnd[0], TEXT("Unable to write to file"), TEXT("Noble Ape File Error"), MB_OK); CloseHandle(current_file); return 0; } if ((write_result = SetEndOfFile(current_file)) == 0) { MessageBox(global_hwnd[0], TEXT("Unable to set EOF"), TEXT("Noble Ape File Error"), MB_OK); CloseHandle(current_file); return 0; } memory_free(&buff); CloseHandle(current_file); return 1; } static unsigned char plat_file_save_as(void) { BOOL save_result; char actual_file_name[MAX_PATH]; OPENFILENAME opf; ZeroMemory(&opf, sizeof(opf)); opf.lStructSize = sizeof(opf); opf.hwndOwner = global_hwnd[WINDOW_ONE]; opf.lpstrFilter = TEXT(NOBLE_APE_FILE_SAVE); opf.nFilterIndex = 1; opf.lpstrFile = (LPWSTR)current_file_name; opf.nMaxFile = sizeof(current_file_name); opf.lpstrFileTitle = (LPWSTR)actual_file_name; opf.nMaxFileTitle = sizeof(actual_file_name); opf.lpstrInitialDir = NULL; opf.lpstrTitle = TEXT("Noble Ape File Save..."); opf.Flags = OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT; save_result = GetSaveFileName(&opf); if (!save_result) { DWORD error = CommDlgExtendedError(); /** Cancel button pressed **/ if (error == 0) { return 0; } MessageBox(global_hwnd[WINDOW_ONE], TEXT("Unable to save file"), TEXT("Noble Ape File Error"), MB_OK); return 0; } shared_saveFileName(actual_file_name); return 1; } <|start_filename|>toolkit/toolkit.h<|end_filename|> /**************************************************************** toolkit.h ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /*! \file toolkit.h * \brief This is the interface between the ApeSDK toolkit and what consumes the ApeSDK toolkit. */ #ifndef _TOOLKIT_H_ #define _TOOLKIT_H_ /* Variable Definitions */ #include <signal.h> // for SIMULATED_APE_ASSERT #undef COMMAND_LINE_DEBUG /* Sends the debug output as printf output - added through command line build */ #define CHAR_SPACE (32) #define IS_RETURN(val) (((val) == 10) || ((val) == 13)) #define IS_SPACE(val) ((val) == CHAR_SPACE) #undef SIMULATED_APE_ASSERT #define PACKED_DATA_BLOCK (32*32*32*2) typedef double n_double; #define TWO_PI ((n_double)(6.2831853071795864769252867665590057683943)) #define SINE_MAXIMUM (26880) #define BIG_INTEGER (2147483647) #define BIG_NEGATIVE_INTEGER (0-2147483648) #define NOTHING (0L) typedef char n_char; /*! @typedef n_string @discussion This is the string format for the Simulated Ape development */ typedef n_char * n_string; typedef const n_char * n_constant_string; #define STRING_BLOCK_SIZE (2048) typedef n_char n_string_block[STRING_BLOCK_SIZE]; /*! @typedef n_byte @discussion This is a single byte data unit. */ typedef unsigned char n_byte; /*! @typedef n_byte2 @discussion This is a two byte data unit. There is no expectations on the byte ordering. */ typedef unsigned short n_byte2; typedef unsigned int n_byte4; typedef int n_c_int; #ifndef _WIN64 /*! @typedef n_uint @discussion This is a four byte data unit. Please note that this form may be shown as unsigned int on some 64-bit implementations. */ typedef unsigned long n_uint; /*! @typedef n_int @discussion This is the native integer data unit. It can be whatever length is specified by the implementation. */ typedef long n_int; #else typedef unsigned long long n_uint; typedef long long n_int; #endif typedef enum { FILE_TYPE_BYTE = 0x01, FILE_TYPE_BYTE2 = 0x02, FILE_TYPE_BYTE_EXT = 0x03, FILE_TYPE_PACKED = 0x05, FILE_TYPE_BYTE4 = 0x06 } file_element_type; #ifdef SIMULATED_APE_ASSERT #define NA_ASSERT(test, message) if(!(test)){io_assert(message, __FILE__, __LINE__); raise(SIGINT);} void io_assert(n_string message, n_string file_loc, n_int line); #else #define NA_ASSERT(test, message) /* test message */ #endif typedef union { struct { n_int x; n_int y; }; n_int data[2]; }n_vect2; typedef union { struct { n_vect2 top_left; n_vect2 bottom_right; }; n_int data[4]; } n_area2; typedef union { struct { n_double x; n_double y; n_double z; }; n_double data[3]; } n_vect3; typedef struct { n_byte r; n_byte g; n_byte b; n_byte a; }n_rgba; typedef union { n_rgba rgba; n_byte4 thirtytwo; }n_rgba32; typedef struct { n_vect2 * points; n_int no_of_points; n_int max_points; }n_points; typedef struct { n_byte4 date; n_byte2 location[2]; n_byte4 time; } n_spacetime; /*! @struct @field characters Characters that represent these values in the file. @field incl_kind Included type and the kind of value combined together. @field number Number of these values. @field location Byte location of the start of these values within the struct. @field what_is_it Provides a string output for HTML documentation for the user. @discussion This is the line by line definition of the Simulated Ape file types. */ typedef struct { n_byte characters[7]; n_byte incl_kind; n_uint number_entries; n_uint start_location; const n_string what_is_it; } simulated_file_entry; #define POPULATED(ch) ((ch[0] != 0) || (ch[1] != 0) || (ch[2] != 0) || (ch[3] != 0) || (ch[4] != 0) || (ch[5] != 0)) /* include externally, if needed */ #define FILE_COPYRIGHT 0x00 #define FILE_INCL(num) ((num) & 0xf0) #define FILE_KIND(num) ((num) & 0x0f) #define FILE_EOF 0x0100 #define ASCII_NUMBER(val) (((val) >= '0') && ((val) <= '9')) #define ASCII_LOWERCASE(val) (((val) >= 'a') && ((val) <= 'z')) #define ASCII_UPPERCASE(val) (((val) >= 'A') && ((val) <= 'Z')) #define FILE_OKAY 0x0000 #define FILE_ERROR (-1) typedef n_byte (n_pixel)(n_int px, n_int py, n_int dx, n_int dy, void * information); typedef n_int (n_memory_location)(n_int px, n_int py); typedef n_byte2 (n_patch)(n_byte2 * local); typedef n_int (n_file_in)(n_byte * buff, n_uint len); typedef n_byte * (n_file_out)(n_uint * len); /*! @struct @field pixel_draw The n_pixel function used to draw pixels into the window buffer. @field information This is the pointer information passed into the pixel_draw function. @discussion This drawing interface was designed to write to window buffer information where the window buffer could be either color or monochrome. The interface needed to be relatively independent to allow for text to be written into either a color window or a monochrome window or a line to be drawn through either window buffer without there being any difference in the implementation algorithm. Think of this method as a way of translating high-level drawing and low-level drawing. */ typedef struct { n_pixel * pixel_draw; void * information; } n_join; typedef struct { n_byte * screen; n_byte * background; } n_background8; typedef struct { n_byte * screen; n_byte color; } n_color8; /*! @struct @field size The size of the file in bytes. @field location The location of the accessing pointer within the file. This is useful for both input and output files. @field data The data stored in bytes. @discussion This is the primary file handling structure in the ApeSDK. It is used for both input and output files. It is the method used to pass file information from the platform layer into the platform independent layers of Simulated Ape. */ typedef struct { n_uint size; n_uint location; n_byte *data; } n_file; typedef void (n_file_specific)(n_string string, n_byte * reference); typedef struct { void * data; n_uint expected_bytes; n_uint hash; void * next; } n_file_chain; typedef enum { OBJECT_EMPTY = 0, OBJECT_STRING, OBJECT_NUMBER, OBJECT_OBJECT, OBJECT_ARRAY = 4, }n_object_type; typedef enum { OBJ_TYPE_EMPTY = 0, OBJ_TYPE_STRING_NOTATION, OBJ_TYPE_NUMBER, OBJ_TYPE_COLON, OBJ_TYPE_COMMA, OBJ_TYPE_OBJECT_OPEN, OBJ_TYPE_OBJECT_CLOSE, OBJ_TYPE_ARRAY_OPEN, OBJ_TYPE_ARRAY_CLOSE }n_object_stream_type; typedef struct { n_string data; void* next; n_object_type type; }n_array; typedef struct { n_array primitive; n_string name; n_uint name_hash; }n_object; n_file * obj_json(n_object * object); n_array * array_number(n_int set_number); n_array * array_string(n_string set_string); n_array * array_object(n_object * set_object); n_array * array_array(n_array * set_array); n_array * array_add(n_array * array, n_array * element); n_object * object_number(n_object * obj, n_string name, n_int number); n_object * object_string(n_object * obj, n_string name, n_string string); n_object * object_object(n_object * obj, n_string name, n_object * object); n_object * object_array(n_object * obj, n_string name, n_array * array); void object_top_object(n_file * file, n_object * top_level); n_object * object_file_to_tree(n_file * file); void obj_free(n_object ** object); n_string obj_contains(n_object* base, n_string name, n_object_type type); n_int obj_contains_number(n_object* base, n_string name, n_int *number); n_int obj_contains_array_numbers(n_object* base, n_string name, n_int *array_numbers, n_int size); n_int obj_contains_array_nbyte2(n_object* base, n_string name, n_byte2 *array_numbers, n_int size); n_array * obj_get_array(n_string array); n_object * obj_get_object(n_string object); n_int obj_get_number(n_string object); n_array * obj_array_next(n_array * array, n_array * element); n_int obj_array_count(n_array * array_obj); /** \brief sine and cosine conversation */ #define NEW_SD_MULTIPLE 26880 extern n_int draw_error(n_constant_string error_text, n_constant_string location, n_int line_number); #define SHOW_ERROR(val) (draw_error(val, __FILE__, __LINE__)) #define IO_LOWER_CHAR(value) if(ASCII_UPPERCASE(value)) (value) += 'a' - 'A' typedef n_int (execute_function)(void * general_data, void * read_data, void * write_data); typedef void (execute_thread_stub)(execute_function function, void * general_data, void * read_data, void * write_data); void execute_group(execute_function * function, void * general_data, void * read_data, n_int count, n_int size); void area2_add(n_area2 * area, n_vect2 * vect, n_byte first); n_int vect2_distance_under(n_vect2 * first, n_vect2 * second, n_int distance); void vect2_byte2(n_vect2 * converter, n_byte2 * input); void vect2_add(n_vect2 * equals, n_vect2 * initial, n_vect2 * second); void vect2_center(n_vect2 * center, n_vect2 * initial, n_vect2 * second); void vect2_subtract(n_vect2 * equals, n_vect2 * initial, n_vect2 * second); void vect2_divide(n_vect2 * equals, n_vect2 * initial, n_vect2 * second, n_int divisor); void vect2_multiplier( n_vect2 * equals, n_vect2 * initial, n_vect2 * second, n_int multiplier, n_int divisor); void vect2_d( n_vect2 * initial, n_vect2 * second, n_int multiplier, n_int divisor); n_int vect2_dot( n_vect2 * initial, n_vect2 * second, n_int multiplier, n_int divisor); void vect2_rotate90(n_vect2 * rotation); void vect2_direction(n_vect2 * initial, n_int direction, n_int divisor); void vect2_delta(n_vect2 * initial, n_vect2 * delta); void vect2_offset(n_vect2 * initial, n_int dx, n_int dy); void vect2_back_byte2(n_vect2 * converter, n_byte2 * output); void vect2_copy(n_vect2 * to, n_vect2 * from); void vect2_populate(n_vect2 * value, n_int x, n_int y); void vect2_rotation(n_vect2 * location, n_vect2 * rotation); void vect2_rotation_bitshift(n_vect2 * location, n_vect2 * rotation); n_int vect2_nonzero(n_vect2 * nonzero); n_vect2 * vect2_min_max_init(void); void vect2_min_max(n_vect2 * points, n_int number, n_vect2 * maxmin); void vect2_scalar_multiply(n_vect2 * value, n_int multiplier); void vect2_scalar_divide(n_vect2 * value, n_int divisor); void vect2_scalar_bitshiftdown(n_vect2 * value, n_int bitshiftdown); void vect3_double(n_vect3 * converter, n_double * input); void vect3_add(n_vect3 * equals, n_vect3 * initial, n_vect3 * second); void vect3_center(n_vect3 * center, n_vect3 * initial, n_vect3 * second); void vect3_subtract(n_vect3 * equals, n_vect3 * initial, n_vect3 * second); void vect3_divide(n_vect3 * equals, n_vect3 * initial, n_vect3 * second, n_double divisor); void vect3_multiplier(n_vect3 * equals, n_vect3 * initial, n_vect3 * second, n_double multiplier, n_double divisor); void vect3_d(n_vect3 * initial, n_vect3 * second, n_double multiplier, n_double divisor); n_double vect3_dot(n_vect3 * initial, n_vect3 * second, n_double multiplier, n_double divisor); void vect3_delta(n_vect3 * initial, n_vect3 * delta); void vect3_offset(n_vect3 * initial, n_double dx, n_double dy, n_double dz); void vect3_back_double(n_vect3 * converter, n_double * output); void vect3_copy(n_vect3 * to, n_vect3 * from); void vect3_populate(n_vect3 * value, n_double x, n_double y, n_double z); n_int vect3_nonzero(n_vect3 * nonzero); n_byte * math_general_allocation(n_byte * bc0, n_byte * bc1, n_int i); void math_general_execution(n_int instruction, n_int is_constant0, n_int is_constant1, n_byte * addr0, n_byte * addr1, n_int value0, n_int * i, n_int is_const0, n_int is_const1, n_byte * pspace, n_byte *bc0, n_byte *bc1, n_int braincode_min_loop); n_byte4 math_hash_fnv1(n_constant_string key); n_uint math_hash(n_byte * values, n_uint length); void math_bilinear_8_times(n_byte * side512, n_byte * data, n_byte double_spread); n_uint math_root(n_uint squ); n_byte math_turn_towards(n_vect2 * p, n_byte fac, n_byte turn); #undef DEBUG_RANDOM #undef VERBOSE_DEBUG_RANDOM #ifdef DEBUG_RANDOM #include <stdio.h> #define math_random(num) math_random_debug(num, __FILE__, __LINE__) #define math_random3(num) math_random_debug(num, __FILE__, __LINE__) #define mrdc(string) math_random_debug_count(string) n_byte2 math_random_debug(n_byte2 * local, n_string file_string, n_int line_number); void math_random_debug_count(n_string place); #else #define mrdc(string) /* math_random_debug_count(string) */ n_byte2 math_random(n_byte2 * local); void math_random3(n_byte2 * local); #endif n_byte math_join(n_int sx, n_int sy, n_int dx, n_int dy, n_join * draw); n_int math_spread_byte(n_byte val); n_int math_sine(n_int direction, n_int divisor); n_byte math_join_vect2(n_int sx, n_int sy, n_vect2 * vect, n_join * draw); n_byte math_line_vect(n_vect2 * point1, n_vect2 * point2, n_join * draw); n_byte math_line(n_int x1, n_int y1, n_int x2, n_int y2, n_join * draw); n_int math_seg14(n_int character); n_byte math_do_intersect(n_vect2 * p1, n_vect2 * q1, n_vect2 * p2, n_vect2 * q2); void io_number_to_string(n_string value, n_uint number); void io_string_number(n_string output_string, n_string input_string, n_uint number); void io_three_strings(n_string output_string, n_string first_string, n_string second_string, n_string third_string, n_byte new_line); void io_entry_execution(n_int argc, n_string * argv); void io_command_line_execution_set(void); n_int io_command_line_execution(void); void io_lower(n_string value, n_int length); void io_whitespace(n_file * input); void io_whitespace_json(n_file * input); void io_audit_file(const simulated_file_entry * format, n_byte section_to_audit); void io_search_file_format(const simulated_file_entry * format, n_string compare); void io_string_write(n_string dest, n_string insert, n_int * pos); n_int io_read_bin(n_file * fil, n_byte * local_byte); n_int io_file_write(n_file * fil, n_byte byte); void io_file_reused(n_file * fil); n_int io_write(n_file * fil, n_constant_string ch, n_byte new_line); n_int io_writenumber(n_file * fil, n_int loc_val, n_uint numer, n_uint denom); n_int io_length(n_string value, n_int max); n_int io_find(n_string check, n_int from, n_int max, n_string value_find, n_int value_find_length); n_int io_read_buff(n_file * fil, n_byte * data, const simulated_file_entry * commands); n_int io_write_buff(n_file * fil, void * data, const simulated_file_entry * commands, n_byte command_num, n_file_specific * func); n_int io_write_csv(n_file * fil, n_byte * data, const simulated_file_entry * commands, n_byte command_num, n_byte initial) ; void memory_copy(n_byte * from, n_byte * to, n_uint number); void * memory_new(n_uint bytes); void memory_free(void ** ptr); void * memory_new_range(n_uint memory_min, n_uint *memory_allocated); n_file * io_file_new(void); void io_file_free(n_file ** file); void io_file_debug(n_file * file); n_int io_number(n_string number_string, n_int * actual_value, n_int * decimal_divisor); void memory_erase(n_byte * buf_offscr, n_uint nestop); n_int io_disk_read(n_file * local_file, n_string file_name); n_int io_disk_read_no_error(n_file * local_file, n_string file_name); n_int io_disk_write(n_file * local_file, n_constant_string file_name); n_int io_disk_check(n_constant_string file_name); n_string * io_tab_delimit_to_n_string_ptr(n_file * tab_file, n_int * size_value, n_int * row_value); void io_three_string_combination(n_string output, n_string first, n_string second, n_string third, n_int count); void io_time_to_string(n_string value); n_string io_string_copy(n_string string); n_int io_read_byte4(n_file * fil, n_uint * actual_value, n_byte * final_char); n_int io_writenum(n_file * fil, n_int loc_val, n_byte ekind, n_byte new_line); n_int io_command(n_file * fil, const simulated_file_entry * commands); n_int io_read_data(n_file * fil, n_byte2 command, n_byte * data_read); void io_output_contents(n_file * file); n_uint io_file_hash(n_file * file); n_file * io_file_ready(n_int entry, n_file * file); void io_file_cleanup(n_int * entry, n_file ** file); void io_file_writeon(n_int * entry, n_file ** file, n_byte blocked_write); void io_file_writeoff(n_int * entry, n_file * file); void io_file_string(n_int entry, n_file * file, n_constant_string string); n_uint io_find_size_data(simulated_file_entry * commands); #define ASCII_QUOTE(num) ((num) == '"') #define ASCII_TEXT(num) ((ASCII_UPPERCASE(num) || ASCII_LOWERCASE(num)) || ((num) == '_')) #define ASCII_SEMICOLON(num) ((num) == ';') #define ASCII_COLON(num) ((num) == ':') #define ASCII_COMMA(num) ((num) == ',') #define ASCII_EQUAL(num) ((num) == '=') #define ASCII_BRACKET(num) (((num) == '(')||((num) == ')')) #define ASCII_BRACES(num) (((num) == '{')||((num) == '}')) #define ASCII_LOGICAL(num) ((((num) == '&')||((num) == '|'))||(((num) == '^')||((num) == '!'))) #define ASCII_ARITHMETIC(num) ((((num) == '+')||((num) == '-'))||(((num) == '*')||((num) == '/'))) #define ASCII_DIRECTIONAL(num) (((num)=='<')||((num)=='>')) #define CODE_VALUE_REQUIRED(num) (((num) == APESCRIPT_OPERATOR || (num) == APESCRIPT_NUMBER) || ((num) == APESCRIPT_TEXT)) #define SIZEOF_NUMBER_WRITE (sizeof(n_int)) void io_int_to_bytes(n_int value, n_byte * bytes); n_int io_bytes_to_int(n_byte * bytes); #ifndef ABS #define ABS(a) (((a) < 0) ? -(a) : (a)) #endif typedef short n_audio; #define AUDIO_FFT_MAX_BITS (15) #define AUDIO_FFT_MAX_BUFFER (1<<AUDIO_FFT_MAX_BITS) void audio_fft(n_byte inverse, n_uint power_sample); void audio_new_fft(n_uint power_sample, n_int InverseTransform, n_double *RealIn, n_double *ImagIn, n_double *RealOut, n_double *ImagOut ); void audio_clear_buffers(n_uint length); void audio_clear_output(n_audio * audio, n_uint length); void audio_equal_output(n_audio * audio, n_uint length); void audio_multiply_output(n_audio * audio, n_uint length); void audio_set_frequency(n_uint entry, n_uint value); void audio_low_frequency(n_audio * buffer, n_int number_freq, n_int debug); void audio_buffer_clear(n_audio * buffer, n_int size); void audio_buffer_double_clear(n_double * buffer, n_int size); void audio_buffer_copy_to_audio(n_double * buffer_double, n_audio * buffer_audio, n_int size); void audio_buffer_copy_to_double(n_audio * buffer_audio, n_double * buffer_double, n_int size); void audio_buffer_copy_to_double_double(n_double * buffer_double1, n_double * buffer_double2, n_int size); void audio_buffer_copy_to_double_double(n_double * buffer_double_to, n_double * buffer_double_from, n_int size); void graph_init(n_int four_byte_factory); void graph_erase(n_byte * buffer, n_vect2 * img, n_rgba32 * color); /* draws a line */ void graph_line(n_byte * buffer, n_vect2 * img, n_vect2 * previous, n_vect2 * current, n_rgba32 * color, n_byte thickness); void graph_curve(n_byte * buffer, n_vect2 * img, n_vect2 * pt0, n_vect2 * pt1, n_vect2 * pt2, n_rgba32 * color, n_byte radius_percent, n_uint start_thickness, n_uint end_thickness); void graph_fill_polygon(n_vect2 * points, n_int no_of_points, n_rgba32 * color, n_byte transparency, n_byte * buffer, n_vect2 * img); typedef n_string (n_console_input)(n_string value, n_int length); typedef void (n_console_output)(n_constant_string value); typedef n_int (n_console)(void * ptr, n_string response, n_console_output output_function); typedef struct { n_console * function; n_string command; n_string addition; n_string help_information; } simulated_console_command; void audio_aiff_header(void * fptr, n_uint total_samples); n_int audio_aiff_is_header(void * fptr, n_uint *samples); void audio_aiff_body(void * fptr, n_audio *samples, n_uint number_samples); n_int io_quit(void * ptr, n_string response, n_console_output output_function); n_int io_help(void * ptr, n_string response, n_console_output output_function); n_string io_console_entry_clean(n_string string, n_int length); n_string io_console_entry(n_string string, n_int length); void io_console_out(n_constant_string value); n_int io_console(void * ptr, simulated_console_command * commands, n_console_input input_function, n_console_output output_function); void io_help_line(simulated_console_command * specific, n_console_output output_function); void io_console_quit(void); #endif /* _TOOLKIT_H_ */ <|start_filename|>universe/transfer.c<|end_filename|> /**************************************************************** transfer.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #include "../entity/entity.h" #include "universe_internal.h" #include "universe.h" /* does not appear to be used here */ void transfer_debug_csv(n_file * fil, n_byte initial) { simulated_group * group = sim_group(); io_write_csv(fil, (n_byte *)(&(group->beings[0])), simulated_file_format, FIL_BEI, initial); } /* provide an output file buffer to be written */ static void transfer_land(n_file * tranfer_out, simulated_group * group, simulated_file_entry * format) { n_byte2 loc_signature[2] = {(n_byte2)SIMULATED_APE_SIGNATURE, (n_byte2)VERSION_NUMBER}; #ifdef USE_FIL_VER io_write_buff(tranfer_out, loc_signature, format, FIL_VER, 0L); #endif #ifdef USE_FIL_LAN io_write_buff(tranfer_out, land_ptr(), format, FIL_LAN, 0L); #endif #ifdef USE_FIL_WEA io_write_buff(tranfer_out, value->weather, format, FIL_WEA, 0L); #endif } static void transfer_being(n_file * tranfer_out, simulated_group * group, n_int being, simulated_file_entry * format) { #ifdef USE_FIL_SOE n_int loop = (SOCIAL_SIZE * being); n_int loop_end = loop + SOCIAL_SIZE; #endif #ifdef USE_FIL_EPI n_int loop_episodic = (EPISODIC_SIZE * being); n_int loop_episodic_end = loop + EPISODIC_SIZE; #endif #ifdef USE_FIL_BEI io_write_buff(tranfer_out, &(group->beings[being]), format, FIL_BEI, 0L); #endif #ifdef USE_FIL_SOE while (loop < loop_end) { io_write_buff(tranfer_out, being_social(&(value->beings[being])), format, FIL_SOE, &brain_three_byte_command); loop++; } #endif #ifdef USE_FIL_EPI while (loop_episodic < loop_episodic_end) { io_write_buff(tranfer_out, being_episodic(&(value->beings[being])), format, FIL_EPI, 0L); loop_episodic++; } #endif } static n_object * transfer_land_obj(void) { n_object * simulated_iland = object_number(0L, "date", land_date()); n_byte2 * genetics_values = land_genetics(); n_array * land_genetics = array_number(genetics_values[0]); array_add(land_genetics, array_number(genetics_values[1])); object_array(simulated_iland, "genetics", land_genetics); object_number(simulated_iland, "time", land_time()); return simulated_iland; } static n_object * transfer_being_spacetime_obj(n_spacetime * value) { n_object * simulated_ispacetime = object_number(0L, "date", value->date); n_array * simulated_ilocation = array_number(value->location[0]); array_add(simulated_ilocation, array_number(value->location[1])); object_array(simulated_ispacetime, "location", simulated_ilocation); object_number(simulated_ispacetime, "time", value->time); return simulated_ispacetime; } static n_object * transfer_being_constant_obj(simulated_being_constant * constant) { n_int genetic_count = 1; n_object * simulated_being_contant = object_number(0L, "date_of_birth", constant->date_of_birth); n_array * generation = array_number(constant->generation_min); n_array * genetics = array_number(constant->genetics[0]); while (genetic_count < CHROMOSOMES) { array_add(genetics, array_number(constant->genetics[genetic_count++])); } object_array(simulated_being_contant, "genetics", genetics); array_add(generation, array_number(constant->generation_max)); object_array(simulated_being_contant, "generation_range", generation); return simulated_being_contant; } static n_object * transfer_being_delta_obj(simulated_being_delta * delta) { n_object * simulated_being_delta = object_number(0L, "direction_facing", delta->direction_facing); n_array * location = array_number(delta->location[0]); n_array * seed = array_number(delta->seed[0]); n_array * goal = array_number(delta->goal[0]); n_array * social_coord = array_number(delta->social_coord_x); array_add(location, array_number(delta->location[1])); array_add(seed, array_number(delta->seed[1])); array_add(goal, array_number(delta->goal[1])); array_add(goal, array_number(delta->goal[2])); array_add(goal, array_number(delta->goal[3])); array_add(social_coord, array_number(delta->social_coord_y)); array_add(social_coord, array_number(delta->social_coord_nx)); array_add(social_coord, array_number(delta->social_coord_ny)); object_array(simulated_being_delta, "location", location); object_number(simulated_being_delta, "velocity", delta->velocity); object_number(simulated_being_delta, "stored_energy", delta->stored_energy); object_array(simulated_being_delta, "seed", seed); object_number(simulated_being_delta, "macro_state", delta->macro_state); object_number(simulated_being_delta, "parasites", delta->parasites); object_number(simulated_being_delta, "honor", delta->honor); object_number(simulated_being_delta, "crowding", delta->crowding); object_number(simulated_being_delta, "height", delta->height); object_number(simulated_being_delta, "mass", delta->mass); object_number(simulated_being_delta, "posture", delta->posture); object_array(simulated_being_delta, "goal", goal); object_array(simulated_being_delta, "social_coord", social_coord); return simulated_being_delta; } static n_object * transfer_being_obj(simulated_being * being) { n_object * simulated_being = 0L; n_string_block simple_name; being_name_simple(being, simple_name); simulated_being = object_string(0L, "name", simple_name); object_object(simulated_being, "delta", transfer_being_delta_obj(&(being->delta))); object_object(simulated_being, "constant", transfer_being_constant_obj(&(being->constant))); return simulated_being; } static n_object * transfer_sim_obj(void) { n_object * simulated_isim_identifier = object_number(0L, "signature", SIMULATED_APE_SIGNATURE); object_number(simulated_isim_identifier, "version number", VERSION_NUMBER); object_string(simulated_isim_identifier, "copyright", FULL_VERSION_COPYRIGHT); object_string(simulated_isim_identifier, "date", FULL_DATE); return simulated_isim_identifier; } n_file * tranfer_out_json(void) { n_file *output_file = 0L; simulated_group * group = sim_group(); n_object * simulation_object = object_object(0L, "information", transfer_sim_obj()); object_object(simulation_object, "land", transfer_land_obj()); if (group->num > 0) { n_uint count = 1; simulated_being *local_beings = group->beings; n_object *being_object = transfer_being_obj(&(local_beings[0])); n_array *beings = array_object(being_object); while (count < group->num) { being_object = transfer_being_obj(&(local_beings[count++])); array_add(beings, array_object(being_object)); } object_array(simulation_object, "beings", beings); } output_file = obj_json(simulation_object); obj_free(&simulation_object); return output_file; } n_file * tranfer_out(void) { simulated_group * group = sim_group(); n_file *returnFile = io_file_new(); n_int loop = 0; n_string fluff[5] = {SHORT_VERSION_NAME, FULL_DATE, COPYRIGHT_DATE, COPYRIGHT_NAME, COPYRIGHT_FOLLOW }; if(returnFile == 0L) { return 0L; } if(returnFile->data == 0L) { memory_free((void**)&returnFile); return 0L; } io_write_buff(returnFile, fluff, 0L, FILE_COPYRIGHT, 0L); transfer_land(returnFile, group, (simulated_file_entry *)simulated_file_format); while (loop < (n_int)(group->num)) { transfer_being(returnFile, group, loop, (simulated_file_entry *)simulated_file_format); loop++; } /* TODO: Brain block */ return returnFile; } n_int tranfer_in(n_file * input_file) { n_int ret_val; n_byte *temp_store = 0L; n_uint ape_count = 0; n_uint social_count = 0; n_uint episodic_count = 0; simulated_group * group = sim_group(); n_uint size_buffer = io_find_size_data((simulated_file_entry *)simulated_file_format); temp_store = (n_byte *)memory_new(size_buffer); if (temp_store == 0L) { return SHOW_ERROR("No temporary storage memory available"); } io_whitespace(input_file); input_file->location = 0; ret_val = io_read_buff(input_file, temp_store, simulated_file_format); if(ret_val != FIL_VER) /* signature must be first */ return SHOW_ERROR("Signature not first in file"); { n_byte2 *signature = (n_byte2 *)temp_store; if(signature[0] != SIMULATED_APE_SIGNATURE) /* not a Simulated Ape file */ return SHOW_ERROR("Not a Simulated Ape File"); if(signature[1] > VERSION_NUMBER) /* file version greater than this version */ return SHOW_ERROR("File newer than Simulation"); } do { n_byte *temp = 0L; ret_val = io_read_buff(input_file, temp_store, simulated_file_format); if (ret_val == -1) SHOW_ERROR("Failure in file load"); if (ret_val < FILE_EOF) { n_uint loop_end = 0; switch (ret_val) { case FIL_LAN: temp = (n_byte*)land_ptr(); loop_end = 11; /* Needs to be fixed */ break; case FIL_BEI: temp = (n_byte*) &(group->beings[ape_count]); loop_end = sizeof(simulated_being); break; case FIL_SOE: { simulated_isocial * local_social = being_social(&(group->beings[ape_count])); temp = (n_byte*)(&local_social[social_count]); loop_end = sizeof(simulated_isocial); } break; case FIL_EPI: { simulated_iepisodic * local_episodic = being_episodic(&(group->beings[ape_count])); temp = (n_byte*)(&local_episodic[episodic_count]); loop_end = sizeof(simulated_iepisodic); } break; default: { return SHOW_ERROR("Unknown file kind"); /*unknown kind*/ } break; } if(temp != 0L) { memory_copy(temp_store, temp, loop_end); } if (ret_val == FIL_BEI) { ape_count ++; if (ape_count == group->max) { group->num = ape_count; return SHOW_ERROR("Too many apes for memory"); } } if (ret_val == FIL_SOE) { social_count ++; if (social_count == (group->max * SOCIAL_SIZE)) { group->num = ape_count; return SHOW_ERROR("Too many social graph events for memory"); } } if (ret_val == FIL_EPI) { episodic_count ++; if (episodic_count == (group->max * EPISODIC_SIZE)) { group->num = ape_count; return SHOW_ERROR("Too many episodic events for memory"); } } } } while (ret_val < FILE_EOF); if (ret_val == FILE_EOF) { group->num = ape_count; return 0; } return SHOW_ERROR("Process file failed"); } <|start_filename|>test/test_apescript.c<|end_filename|> /**************************************************************** test_apescript.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #ifndef _WIN32 #include "../toolkit/toolkit.h" #include "../script/script.h" #else #include "..\toolkit\toolkit.h" #include "..\script\script.h" #endif #include <unistd.h> #include <stdio.h> #include <unistd.h> #include <time.h> /* This is intended to be overwritten by third-party usage where applicable. */ enum SECONDARY_APESCRIPT { VARIABLE_RANDOM = (VARIABLE_IF + 1), VARIABLE_ESCAPE_PER_SECOND, VARIABLE_GET_ONE, VARIABLE_GET_TWO, VARIABLE_GET_THREE, VARIABLE_GET_FOUR, VARIABLE_GET_FIVE, VARIABLE_GET_SIX, VARIABLE_GET_SEVEN, VARIABLE_GET_EIGHT, VARIABLE_EXTERNAL_ONE, VARIABLE_EXTERNAL_TWO, VARIABLE_EXTERNAL_THREE, VARIABLE_EXTERNAL_FOUR, VARIABLE_EXTERNAL_FIVE, VARIABLE_EXTERNAL_SIX, VARIABLE_PERSIST, VARIABLE_ONE, VARIABLE_TWO, VARIABLE_THREE, VARIABLE_FOUR, VARIABLE_FIVE, VARIABLE_SIX, VARIABLE_SEVEN, VARIABLE_RANDOM_SEED, VARIABLE_EXIT, VARIABLE_RUN_EXTERNAL_FUNCTION, VARIABLE_ESCAPE, VARIABLE_MAIN /* This is a special case, it is the location where the main code starts */ }; #define VARIABLE_READWRITE VARIABLE_EXTERNAL_SIX #define VARIABLE_FIRST_REAL_ONE VARIABLE_ONE static variable_string variable_codes[VARIABLE_MAX]= { /* 0 */ /* special "variables" */ "function", "run", /* 2 */ "while", "if", /* output only */ "random", "escape_per_second", "variable_get_one", "variable_get_two", "variable_get_three", "variable_get_four", "variable_get_five", "variable_get_six", "variable_get_seven", "variable_get_eight", "external_function_one", "external_function_two", "external_function_three", "external_function_four", "external_function_five", "external_function_six", /* input and output */ "persist", "variable_one", "variable_two", "variable_three", "variable_four", "variable_five", "variable_six", "variable_seven", "random_seed", "exit", "run_external_function", "escape", /* main call */ "main" }; #define FUNCTION_ONE_TRIGGER_NUMBER (65001) #define FUNCTION_TWO_TRIGGER_NUMBER (65002) #define FUNCTION_THREE_TRIGGER_NUMBER (65003) #define FUNCTION_FOUR_TRIGGER_NUMBER (65004) #define FUNCTION_FIVE_TRIGGER_NUMBER (65005) #define FUNCTION_SIX_TRIGGER_NUMBER (65006) #define FRACTION_OF_SECOND (6) static n_byte2 random_seed[2]; static n_byte random_populated = 0; static n_int persist_value = 0; static n_uint random_noise = 0x6d73e3a3; static void commands_random_seed(n_int seed_value) { random_populated = 1; if (seed_value < 0) { n_uint unsignedvalue = time(NULL); switch (random_noise % 2) { case 0: random_noise ^= (unsignedvalue ^ 0x47c23e19); break; case 1: random_noise ^= (unsignedvalue ^ 0x9ef1de93); break; case 2: random_noise ^= (unsignedvalue ^ 0x2e97c735); break; } random_seed[0] ^= (random_noise>>16) & 0xFFFF; random_seed[1] ^= random_noise & 0xFFFF; } else { n_uint seed = ABS(seed_value); seed = (seed * 2999)&0xFFFFFFFF; random_seed[0] = (seed>>16) & 0xFFFF; random_seed[1] = seed & 0xFFFF; } } static n_byte2 commands_handle_random() { if (random_populated == 0) { commands_random_seed(-1); } return math_random(random_seed); } /* notification here is optional and it can be done asynchronously */ static void commands_notify_done(n_int * notification) { notification[0] = 0; } static void commands_process_run(n_int value, n_int * notification) { /* do not create any additional noise if the values aren't found */ switch (value) { case FUNCTION_ONE_TRIGGER_NUMBER: case FUNCTION_TWO_TRIGGER_NUMBER: case FUNCTION_THREE_TRIGGER_NUMBER: case FUNCTION_FOUR_TRIGGER_NUMBER: case FUNCTION_FIVE_TRIGGER_NUMBER: case FUNCTION_SIX_TRIGGER_NUMBER: /* best not to add a new line for the debug format */ commands_notify_done(notification); break; } } n_int commands_input(void *vindividual, n_byte kind, n_int value) { n_individual_interpret *individual = (n_individual_interpret *)vindividual; n_int *local_vr = individual->variable_references; if (kind > VARIABLE_READWRITE) { if (kind == VARIABLE_PERSIST) { persist_value = value; } else { local_vr[kind - VARIABLE_FIRST_REAL_ONE] = value; } if (kind == VARIABLE_RUN_EXTERNAL_FUNCTION) { commands_process_run(value, &local_vr[kind - VARIABLE_FIRST_REAL_ONE]); } if (kind == VARIABLE_RANDOM_SEED) { commands_random_seed(value); } if (kind == VARIABLE_ESCAPE) { individual->leave = value; } return 0; } return -1; /* where this fails is more important than this failure */ } n_int commands_output(void * vcode, void * vindividual, n_byte * kind, n_int * number) { n_interpret *code = (n_interpret *)vcode; n_individual_interpret *individual = (n_individual_interpret *)vindividual; n_byte first_value = kind[0]; n_byte second_value = kind[1]; if(first_value == 'n') { *number = code->number_buffer[second_value]; return 0; } if((first_value == 't') && (VARIABLE_SPECIAL(second_value, code)==0)) { n_int *local_vr = individual->variable_references; if(second_value>VARIABLE_READWRITE) { if (second_value == VARIABLE_PERSIST) { *number = persist_value; } else { *number = local_vr[second_value - VARIABLE_FIRST_REAL_ONE]; } return 0; } else { switch(second_value) { case VARIABLE_RANDOM: *number = commands_handle_random(); return 0; /* this is a special constant */ case VARIABLE_ESCAPE_PER_SECOND: *number = FRACTION_OF_SECOND; return 0; case VARIABLE_GET_ONE: *number = 1; /* this could be any value */ return 0; case VARIABLE_GET_TWO: *number = 2; /* this could be any value */ return 0; case VARIABLE_GET_THREE: *number = 3; /* this could be any value */ return 0; case VARIABLE_GET_FOUR: *number = 4; /* this could be any value */ return 0; case VARIABLE_GET_FIVE: *number = 5; /* this could be any value */ return 0; case VARIABLE_GET_SIX: *number = 6; /* this could be any value */ return 0; case VARIABLE_GET_SEVEN: *number = 7; /* this could be any value */ return 0; case VARIABLE_GET_EIGHT: *number = 8; /* this could be any value */ return 0; /* there are a number of ways of doing this in terms of unique execution points */ case VARIABLE_EXTERNAL_ONE: *number = FUNCTION_ONE_TRIGGER_NUMBER; return 0; case VARIABLE_EXTERNAL_TWO: *number = FUNCTION_TWO_TRIGGER_NUMBER; return 0; case VARIABLE_EXTERNAL_THREE: *number = FUNCTION_THREE_TRIGGER_NUMBER; return 0; case VARIABLE_EXTERNAL_FOUR: *number = FUNCTION_FOUR_TRIGGER_NUMBER; return 0; case VARIABLE_EXTERNAL_FIVE: *number = FUNCTION_FIVE_TRIGGER_NUMBER; return 0; case VARIABLE_EXTERNAL_SIX: *number = FUNCTION_SIX_TRIGGER_NUMBER; return 0; } } } return -1; /* where this fails is more important than this failure */ } static n_interpret *interpret = 0L; n_int draw_error(n_constant_string error_text, n_constant_string location, n_int line_number) { printf("ERROR: %s @%s, %ld\n",error_text, location, line_number); return -1; } static n_int test_interpret(n_byte * buff, n_uint len) { n_file local; local . size = len; local . location = 0; local . data = buff; interpret = parse_convert(&local, VARIABLE_MAIN, (variable_string *)variable_codes); if(interpret == 0L) { return -1; } else { SC_DEBUG_ON(0L); /* turn on debugging after script loading */ } interpret->sc_input = &commands_input; interpret->sc_output = &commands_output; interpret->input_greater = VARIABLE_READWRITE; return 0; } static n_int test_init(n_string interpret_string) { n_file * source_file = io_file_new(); if (io_disk_check(interpret_string) == 0) { return -1; } if (io_disk_read(source_file, interpret_string) == FILE_ERROR) { io_file_free(&source_file); return -1; } if (test_interpret(source_file->data,source_file->location) == -1) { io_file_free(&source_file); return -1; } io_file_free(&source_file); return 0; } static void test_close() { interpret_cleanup(&interpret); } int main(int argc, char *argv[]) { n_int return_value = 0; n_individual_interpret individual; printf(" --- test apescript --- start -----------------------------------------\n"); interpret_individual(&individual); if (argc != 2) { printf("ERROR: Single script file string expected\n"); return 0; } if (test_init(argv[1]) == -1) { printf("ERROR: Load Script %s failed\n",argv[1]); return 0; } do { return_value = interpret_cycle(interpret, &individual, VARIABLE_EXIT - VARIABLE_FIRST_REAL_ONE, 0L,0L,0L,0L); if (individual.leave != 0) { #ifdef COMMAND_LINE_DEBUG printf("..."); #endif } } while (return_value == 1); if (return_value == -1) { printf("ERROR: Script %s Ended with Error\n",argv[1]); } test_close(); printf(" --- test apescript --- end -----------------------------------------\n"); return 0; } <|start_filename|>test/example6.json<|end_filename|> {"general_variables":"test","general_variables2":{"general_variables":[1,2,4,5,9],"general_variables2":-12345,"general_variables3":{"general_variables":"test","general_variables2":[{"animal":"hat","right":0},{"animal":"cat","right":1},{"animal":"horse","right":1},{"animal":"rat","right":1}],"general_variables3":"test"}},"general_variables3":"test"} <|start_filename|>macsim/ASSimulationView.h<|end_filename|> /**************************************************************** ASSimulationView.h ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #import <Cocoa/Cocoa.h> #import "ASMacView.h" @interface ASSimulationView : ASMacView - (void) awakeFromNib; - (void) loadUrlString:(NSString*) urlString; - (void) menuCheckMark:(id)sender check:(int)value; - (IBAction) menuFileNew:(id) sender; - (IBAction) menuFileNewAgents:(id) sender; - (IBAction) menuFileOpen:(id) sender; - (IBAction) menuFileOpenScript:(id) sender; - (IBAction) menuFileSaveAs:(id) sender; - (void) debugOutput; -(IBAction) menuControlNoTerritory:(id) sender; -(IBAction) menuControlNoWeather:(id) sender; -(IBAction) menuControlNoBrain:(id) sender; -(IBAction) menuControlNoBrainCode:(id) sender; -(IBAction) menuControlDaylightTide:(id)sender; -(IBAction) menuControlFlood:(id) sender; -(IBAction) menuControlHealthyCarrier:(id) sender; -(IBAction) loadManual:(id) sender; -(IBAction) loadSimulationPage:(id) sender; -(IBAction) menuControlPause:(id) sender; -(IBAction) menuControlFollow:(id) sender; -(IBAction) menuControlSocialWeb:(id) sender; -(IBAction) menuControlPrevious:(id) sender; -(IBAction) menuControlNext:(id) sender; -(IBAction) menuControlClearErrors:(id) sender; @end <|start_filename|>toolkit/vect.c<|end_filename|> /**************************************************************** vect.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /*! \file vect.c * \brief This covers vector math in Simulated Ape. */ #include "toolkit.h" /** \brief new_sd stands for new sine dump and hold the sine and cosine values for the simulation */ static const n_int new_sd[256] = { 0, 659, 1318, 1977, 2634, 3290, 3944, 4595, 5244, 5889, 6531, 7169, 7802, 8431, 9055, 9673, 10286, 10892, 11492, 12085, 12671, 13249, 13819, 14380, 14933, 15477, 16012, 16537, 17052, 17557, 18051, 18534, 19007, 19467, 19916, 20353, 20778, 21190, 21590, 21976, 22349, 22709, 23055, 23387, 23706, 24009, 24299, 24573, 24833, 25078, 25308, 25523, 25722, 25906, 26074, 26226, 26363, 26484, 26589, 26677, 26750, 26807, 26847, 26871, 26880, 26871, 26847, 26807, 26750, 26677, 26589, 26484, 26363, 26226, 26074, 25906, 25722, 25523, 25308, 25078, 24833, 24573, 24299, 24009, 23706, 23387, 23055, 22709, 22349, 21976, 21590, 21190, 20778, 20353, 19916, 19467, 19007, 18534, 18051, 17557, 17052, 16537, 16012, 15477, 14933, 14380, 13819, 13249, 12671, 12085, 11492, 10892, 10286, 9673, 9055, 8431, 7802, 7169, 6531, 5889, 5244, 4595, 3944, 3290, 2634, 1977, 1318, 659, 0, -659, -1318, -1977, -2634, -3290, -3944, -4595, -5244, -5889, -6531, -7169, -7802, -8431, -9055, -9673, -10286, -10892, -11492, -12085, -12671, -13249, -13819, -14380, -14933, -15477, -16012, -16537, -17052, -17557, -18051, -18534, -19007, -19467, -19916, -20353, -20778, -21190, -21590, -21976, -22349, -22709, -23055, -23387, -23706, -24009, -24299, -24573, -24833, -25078, -25308, -25523, -25722, -25906, -26074, -26226, -26363, -26484, -26589, -26677, -26750, -26807, -26847, -26871, -26880, -26871, -26847, -26807, -26750, -26677, -26589, -26484, -26363, -26226, -26074, -25906, -25722, -25523, -25308, -25078, -24833, -24573, -24299, -24009, -23706, -23387, -23055, -22709, -22349, -21976, -21590, -21190, -20778, -20353, -19916, -19467, -19007, -18534, -18051, -17557, -17052, -16537, -16012, -15477, -14933, -14380, -13819, -13249, -12671, -12085, -11492, -10892, -10286, -9673, -9055, -8431, -7802, -7169, -6531, -5889, -5244, -4595, -3944, -3290, -2634, -1977, -1318, -659 }; void area2_add(n_area2 * area, n_vect2 * vect, n_byte first) { if (first) { area->bottom_right.x = vect->x; area->bottom_right.y = vect->y; area->top_left.x = vect->x; area->top_left.y = vect->y; return; } if (vect->x < area->top_left.x) { area->top_left.x = vect->x; } if (vect->y < area->top_left.y) { area->top_left.y = vect->y; } if (vect->x > area->bottom_right.x) { area->bottom_right.x = vect->x; } if (vect->y > area->bottom_right.y) { area->bottom_right.y = vect->y; } } /** * Converts an array of n_byte2 to a 2d vector (n_vect2) * @param converter the vector to hold the information. * @param input the n_byte2 that is converted to the n_vect2. */ void vect2_byte2(n_vect2 * converter, n_byte2 * input) { NA_ASSERT(converter, "converter NULL"); NA_ASSERT(input, "input NULL"); if (converter == 0L) return; if (input == 0L) return; converter->x = input[0]; converter->y = input[1]; } /** * Adds two 2d vectors into a resultant vector. * @param equals the vector that holds the result. * @param initial the first vector to be added. * @param second the second vector to be added. */ void vect2_add(n_vect2 * equals, n_vect2 * initial, n_vect2 * second) { NA_ASSERT(equals, "equals NULL"); NA_ASSERT(initial, "initial NULL"); NA_ASSERT(second, "second NULL"); if (equals == 0L) return; if (initial == 0L) return; if (second == 0L) return; equals->x = initial->x + second->x; equals->y = initial->y + second->y; } void vect2_center(n_vect2 * center, n_vect2 * initial, n_vect2 * second) { vect2_add(center, initial, second); center->x = center->x / 2; center->y = center->y / 2; } void vect2_scalar_multiply(n_vect2 * value, n_int multiplier) { value->x = value->x * multiplier; value->y = value->y * multiplier; } void vect2_scalar_divide(n_vect2 * value, n_int divisor) { value->x = value->x / divisor; value->y = value->y / divisor; } void vect2_scalar_bitshiftdown(n_vect2 * value, n_int bitshiftdown) { value->x = value->x >> bitshiftdown; value->y = value->y >> bitshiftdown; } /** * Subtracts one 2d vector from another 2d vector into a resultant vector. * @param equals the vector that holds the result. * @param initial the first vector. * @param second the second vector to be subtracted. */ void vect2_subtract(n_vect2 * equals, n_vect2 * initial, n_vect2 * second) { NA_ASSERT(equals, "equals NULL"); NA_ASSERT(initial, "initial NULL"); NA_ASSERT(second, "second NULL"); if (equals == 0L) return; if (initial == 0L) return; if (second == 0L) return; equals->x = initial->x - second->x; equals->y = initial->y - second->y; } void vect2_divide(n_vect2 * equals, n_vect2 * initial, n_vect2 * second, n_int divisor) { vect2_subtract(equals, second, initial); if (equals == 0L || (divisor == 0)) { return; } equals->x = equals->x / divisor; equals->y = equals->y / divisor; } /** * Multiplies one 2d vector with another 2d vector times a multiplier divided by a divisor. * @param equals the vector that holds the result. * @param initial the first vector. * @param second the second vector to be multiplied. * @param multiplier the scalar multiplier. * @param divisor the the scalar divisor. */ void vect2_multiplier(n_vect2 * equals, n_vect2 * initial, n_vect2 * second, n_int multiplier, n_int divisor) { NA_ASSERT(equals, "equals NULL"); NA_ASSERT(initial, "initial NULL"); NA_ASSERT(second, "second NULL"); NA_ASSERT(divisor, "divisor ZERO"); if (equals == 0L) return; if (initial == 0L) return; if (second == 0L) return; if (divisor == 0L) return; equals->x = (multiplier * initial->x * second->x) / divisor; equals->y = (multiplier * initial->y * second->y) / divisor; } /** * Adds one 2d vector with another 2d vector times a multiplier divided by a divisor. * @param initial the first vector that takes the summation of the second vector. * @param second the second vector to be multiplied. * @param multiplier the scalar multiplier. * @param divisor the the scalar divisor. */ void vect2_d(n_vect2 * initial, n_vect2 * second, n_int multiplier, n_int divisor) { NA_ASSERT(initial, "initial NULL"); NA_ASSERT(second, "second NULL"); NA_ASSERT(divisor, "divisor ZERO"); if (initial == 0L) return; if (second == 0L) return; if (divisor == 0L) return; initial->x += ( (multiplier * second->x) / divisor); initial->y += ( (multiplier * second->y) / divisor); } /** This produces the dot product of two vectors with the scalar multiplier and divisor noted. @param initial The first vector @param second The second vector @param multiplier The numerator multiplier @param divisor The divisor multiplier @return The resultant scalar */ n_int vect2_dot(n_vect2 * initial, n_vect2 * second, n_int multiplier, n_int divisor) { NA_ASSERT(initial, "initial NULL"); NA_ASSERT(second, "second NULL"); NA_ASSERT(divisor, "divisor ZERO"); if (initial == 0L) return 0; if (second == 0L) return 0; return (multiplier * ((initial->x * second->x) + (initial->y * second->y))) / divisor; } n_int vect2_distance_under(n_vect2 * first, n_vect2 * second, n_int distance) { n_vect2 difference; n_int distance_squ; vect2_subtract(&difference, first, second); distance_squ = (difference.x * difference.x) + (difference.y * difference.y); return (distance * distance) > distance_squ; } /** This produces a sine value @param direction 256 units per rotation @param divisor The divisor for the output value @return The sine value */ n_int math_sine(n_int direction, n_int divisor) { NA_ASSERT(divisor, "divisor ZERO"); return new_sd[(direction)&255] / (divisor); } void vect2_rotate90(n_vect2 * rotation) { n_int temp = rotation->y; rotation->y = 0 - rotation->x; rotation->x = temp; } /** This produces a direction vector @param initial The vector output @param direction 256 units per rotation @param divisor The divisor for the output value */ void vect2_direction(n_vect2 * initial, n_int direction, n_int divisor) { NA_ASSERT(initial, "initial NULL"); NA_ASSERT(divisor, "divisor ZERO"); initial->x = ((new_sd[((direction)+64)&255]) / (divisor)); initial->y = ((new_sd[(direction)&255]) / (divisor)); } void vect2_delta(n_vect2 * initial, n_vect2 * delta) { NA_ASSERT(initial, "initial NULL"); NA_ASSERT(delta, "delta NULL"); if (initial == 0L) return; if (delta == 0L) return; initial->x += delta->x; initial->y += delta->y; } void vect2_offset(n_vect2 * initial, n_int dx, n_int dy) { NA_ASSERT(initial, "initial NULL"); if (initial == 0L) return; initial->x += dx; initial->y += dy; } void vect2_back_byte2(n_vect2 * converter, n_byte2 * output) { NA_ASSERT(converter, "converter NULL"); NA_ASSERT(output, "output NULL"); if (converter == 0L) return; if (output == 0L) return; if (converter->x > 65535) converter->x = 65535; if (converter->y > 65535) converter->y = 65535; if (converter->x < 0) converter->x = 0; if (converter->y < 0) converter->y = 0; output[0] = (n_byte2) converter->x; output[1] = (n_byte2) converter->y; } void vect2_copy(n_vect2 * to, n_vect2 * from) { to->x = from->x; to->y = from->y; } void vect2_populate(n_vect2 * value, n_int x, n_int y) { value->x = x; value->y = y; } void vect2_rotation(n_vect2 * location, n_vect2 * rotation) { n_vect2 temp; temp.x = ((location->x * rotation->x) + (location->y * rotation->y)) / SINE_MAXIMUM; temp.y = ((location->x * rotation->y) - (location->y * rotation->x)) / SINE_MAXIMUM; location->x = temp.x; location->y = temp.y; } void vect2_rotation_bitshift(n_vect2 * location, n_vect2 * rotation) { n_vect2 temp; temp.x = ((location->x * rotation->x) + (location->y * rotation->y)) >> 15; temp.y = ((location->x * rotation->y) - (location->y * rotation->x)) >> 15; location->x = temp.x; location->y = temp.y; } n_int vect2_nonzero(n_vect2 * nonzero) { return ((nonzero->x != 0) || (nonzero->y != 0)); } n_vect2 * vect2_min_max_init(void) { n_vect2 * min_max = memory_new(2 * sizeof(n_vect2)); if (min_max == 0L) { return 0L; } vect2_populate(&min_max[0], BIG_INTEGER, BIG_INTEGER); vect2_populate(&min_max[1], BIG_NEGATIVE_INTEGER, BIG_NEGATIVE_INTEGER); return min_max; } void vect2_min_max(n_vect2 * points, n_int number, n_vect2 * maxmin) { n_int loop = 0; while(loop < number) { n_int px = points[loop].x; n_int py = points[loop].y; if (px < maxmin[0].x) { maxmin[0].x = px; } if (py < maxmin[0].y) { maxmin[0].y = py; } if (px > maxmin[1].x) { maxmin[1].x = px; } if (py > maxmin[1].y) { maxmin[1].y = py; } loop++; } } void vect3_double(n_vect3 * converter, n_double * input) { NA_ASSERT(converter, "converter NULL"); NA_ASSERT(input, "input NULL"); if (converter == 0L) return; if (input == 0L) return; converter->x = input[0]; converter->y = input[1]; converter->z = input[1]; } void vect3_add(n_vect3 * equals, n_vect3 * initial, n_vect3 * second) { NA_ASSERT(equals, "equals NULL"); NA_ASSERT(initial, "initial NULL"); NA_ASSERT(second, "second NULL"); if (equals == 0L) return; if (initial == 0L) return; if (second == 0L) return; equals->x = initial->x + second->x; equals->y = initial->y + second->y; equals->z = initial->z + second->z; } void vect3_center(n_vect3 * center, n_vect3 * initial, n_vect3 * second) { vect3_add(center, initial, second); center->x = center->x / 2; center->y = center->y / 2; center->z = center->z / 2; } void vect3_subtract(n_vect3 * equals, n_vect3 * initial, n_vect3 * second) { NA_ASSERT(equals, "equals NULL"); NA_ASSERT(initial, "initial NULL"); NA_ASSERT(second, "second NULL"); if (equals == 0L) return; if (initial == 0L) return; if (second == 0L) return; equals->x = initial->x - second->x; equals->y = initial->y - second->y; equals->z = initial->z - second->z; } void vect3_divide(n_vect3 * equals, n_vect3 * initial, n_vect3 * second, n_double divisor) { vect3_subtract(equals, second, initial); if (equals == 0L || (divisor == 0)) { return; } equals->x = equals->x / divisor; equals->y = equals->y / divisor; equals->z = equals->z / divisor; } void vect3_multiplier(n_vect3 * equals, n_vect3 * initial, n_vect3 * second, n_double multiplier, n_double divisor) { NA_ASSERT(equals, "equals NULL"); NA_ASSERT(initial, "initial NULL"); NA_ASSERT(second, "second NULL"); NA_ASSERT(divisor != 0, "divisor ZERO"); if (equals == 0L) return; if (initial == 0L) return; if (second == 0L) return; if (divisor == 0L) return; equals->x = (multiplier * initial->x * second->x) / divisor; equals->y = (multiplier * initial->y * second->y) / divisor; equals->z = (multiplier * initial->z * second->z) / divisor; } void vect3_d(n_vect3 * initial, n_vect3 * second, n_double multiplier, n_double divisor) { NA_ASSERT(initial, "initial NULL"); NA_ASSERT(second, "second NULL"); NA_ASSERT(divisor != 0, "divisor ZERO"); if (initial == 0L) return; if (second == 0L) return; if (divisor == 0L) return; initial->x += ( (multiplier * second->x) / divisor); initial->y += ( (multiplier * second->y) / divisor); initial->z += ( (multiplier * second->z) / divisor); } n_double vect3_dot(n_vect3 * initial, n_vect3 * second, n_double multiplier, n_double divisor) { NA_ASSERT(initial, "initial NULL"); NA_ASSERT(second, "second NULL"); NA_ASSERT(divisor != 0, "divisor ZERO"); if (initial == 0L) return 0; if (second == 0L) return 0; return (multiplier * ((initial->x * second->x) + (initial->y * second->y) + (initial->z * second->z))) / divisor; } void vect3_delta(n_vect3 * initial, n_vect3 * delta) { NA_ASSERT(initial, "initial NULL"); NA_ASSERT(delta, "delta NULL"); if (initial == 0L) return; if (delta == 0L) return; initial->x += delta->x; initial->y += delta->y; initial->z += delta->z; } void vect3_offset(n_vect3 * initial, n_double dx, n_double dy, n_double dz) { NA_ASSERT(initial, "initial NULL"); if (initial == 0L) return; initial->x += dx; initial->y += dy; initial->z += dz; } void vect3_back_double(n_vect3 * converter, n_double * output) { NA_ASSERT(converter, "converter NULL"); NA_ASSERT(output, "output NULL"); if (converter == 0L) return; if (output == 0L) return; output[0] = converter->x; output[1] = converter->y; output[2] = converter->z; } void vect3_copy(n_vect3 * to, n_vect3 * from) { to->x = from->x; to->y = from->y; to->z = from->z; } void vect3_populate(n_vect3 * value, n_double x, n_double y, n_double z) { value->x = x; value->y = y; value->z = z; } n_int vect3_nonzero(n_vect3 * nonzero) { return ((nonzero->x != 0) || (nonzero->y != 0) || (nonzero->z != 0)); } <|start_filename|>entity/food.c<|end_filename|> /**************************************************************** food.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /*! \file food.c * \brief Functions related to eating */ #include "entity.h" #include "entity_internal.h" /** Various energy use and addition through eating characteristics */ /** Energy from vegetables */ #define GENE_ENERGY_FROM_VEGETABLES(gene) GENE_VAL_REG(gene, 3, 13, 15, 3) /** Energy from fruits */ #define GENE_ENERGY_FROM_FRUITS(gene) GENE_VAL_REG(gene, 14, 7, 6, 4) /** Energy from shellfish */ #define GENE_ENERGY_FROM_SHELLFISH(gene) GENE_VAL_REG(gene, 10, 12, 12, 2) /** Energy from seaweed */ #define GENE_ENERGY_FROM_SEAWEED(gene) GENE_VAL_REG(gene, 0, 9, 11, 12) /** Energy from bird eggs */ #define GENE_ENERGY_FROM_BIRD_EGGS(gene) GENE_VAL_REG(gene, 7, 1, 9, 5) /** Energy from lizard eggs */ #define GENE_ENERGY_FROM_LIZARD_EGGS(gene) GENE_VAL_REG(gene, 15, 3, 12, 8) /** * @brief How much energy is absorbed from a given type of food * @param food_type The type of food * @param local pointer to the ape * @return Energy absorbed */ n_int food_absorption(simulated_being * local, n_int max_energy, n_byte food_type) { n_genetics * genetics = being_genetics(local); n_int vegetable = GENE_ENERGY_FROM_VEGETABLES(genetics); n_int fruit = GENE_ENERGY_FROM_FRUITS(genetics); n_int shellfish = GENE_ENERGY_FROM_SHELLFISH(genetics); n_int seawood = GENE_ENERGY_FROM_SEAWEED(genetics); n_int bird_eggs = GENE_ENERGY_FROM_BIRD_EGGS(genetics); n_int lizard_eggs = GENE_ENERGY_FROM_LIZARD_EGGS(genetics); n_int return_value = 0; /** note that the absorbition for different foods is normalised */ n_int absorb_denom = 1 + vegetable + fruit + seawood + bird_eggs + lizard_eggs; /** ingest pathogens from certain foods */ being_ingest_pathogen(local, food_type); switch (food_type) { case FOOD_VEGETABLE: #ifdef DEBUG_LACK_OF_MOVEMENT { n_string_block information_string; sprintf(information_string, "vegetable %ld absorbtion %ld food", vegetable, absorb_denom); being_register_movement(local, information_string); } #endif return_value = (vegetable << 4) / absorb_denom; break; case FOOD_FRUIT: #ifdef DEBUG_LACK_OF_MOVEMENT being_register_movement(local, "fruit food"); #endif return_value = (fruit << 4) / absorb_denom; break; case FOOD_SHELLFISH: #ifdef DEBUG_LACK_OF_MOVEMENT being_register_movement(local, "shellfish food"); #endif return_value = (shellfish << 4) / absorb_denom; break; case FOOD_SEAWEED: #ifdef DEBUG_LACK_OF_MOVEMENT being_register_movement(local, "seaweed food"); #endif return_value = (seawood << 4) / absorb_denom; break; case FOOD_BIRD_EGGS: #ifdef DEBUG_LACK_OF_MOVEMENT being_register_movement(local, "bird egg food"); #endif return_value = (seawood << 4) / absorb_denom; break; case FOOD_LIZARD_EGGS: #ifdef DEBUG_LACK_OF_MOVEMENT being_register_movement(local, "lizard egg food"); #endif return_value = (seawood << 4) / absorb_denom; break; default: #ifdef DEBUG_LACK_OF_MOVEMENT being_register_movement(local, "no food"); #endif return 0; } return_value = (max_energy * (1 + return_value) >> 3); if (return_value > 320) { return_value = 320; /**< can only eat so much in one go */ } return return_value; } /** * @brief Returns the amount of food of the given type at the given location * @param loc_x x coordinate * @param loc_y y coordinate * @param kind The type of food * @return The amount of food of the given type at this location */ static n_int food_location(n_int loc_x, n_int loc_y, n_int kind) { return land_operator_interpolated(loc_x, loc_y, (n_byte*)&operators[kind - VARIABLE_BIOLOGY_AREA]); } /** * @brief Returns the values for grass, trees and bushes at the given location * @param loc_x X ape coordinate on the map * @param loc_y Y ape coordinate on the lap * @param grass Returned value for grass * @param trees Returned value for trees * @param bush Returned value for bushes */ void food_values(n_int loc_x, n_int loc_y, n_int *grass, n_int *trees, n_int *bush) { /* TODO include bird and lizard eggs */ /** grass at this location */ *grass = food_location(loc_x, loc_y, VARIABLE_BIOLOGY_GRASS)+OFFSET_GRASS; /** trees at this location */ *trees = food_location(loc_x, loc_y, VARIABLE_BIOLOGY_TREE); /** bushes at this location */ *bush = food_location(loc_x, loc_y, VARIABLE_BIOLOGY_BUSH)+OFFSET_BUSH; *grass += LAND_DITHER(*grass, *trees, *bush); } /** * @brief Returns the dominant food type on land and its associated maximum energy value * @param loc_x X ape coordinate * @param loc_y Y ape coordinate * @param energy Returned maximum energy value for the food type * @return The type of food */ static n_byte food_eat_land( n_int loc_x, n_int loc_y, n_int * energy) { n_byte food_type = FOOD_VEGETABLE; n_int grass, trees, bush; /* TODO Handle this logic centrally - including the int values in the function not outside */ food_values(loc_x,loc_y,&grass, &trees, &bush); /** which is the dominant form of vegetation in this area? */ if ((grass > bush) && (grass > trees)) { *energy = ENERGY_GRASS; } else { if (bush > trees) { *energy = ENERGY_BUSH; } else { *energy = ENERGY_FRUIT; food_type = FOOD_FRUIT; } } return food_type; } /** * @brief Returns the dominant food type in the intertidal zone and its associated maximum energy value * @param loc_x X ape coordinate * @param loc_y Y ape coordinate * @param energy Returned maximum energy value for the food type * @return The type of food */ static n_byte food_intertidal( n_int loc_x, n_int loc_y, n_int * energy) { n_byte food_type = FOOD_VEGETABLE; n_int seaweed, rockpool, beach; /** seaweed at this location */ seaweed = food_location(loc_x, loc_y, VARIABLE_BIOLOGY_SEAWEED); /** rockpools at this location */ rockpool = food_location(loc_x, loc_y, VARIABLE_BIOLOGY_ROCKPOOL); /** beach at this location */ beach = food_location(loc_x, loc_y, VARIABLE_BIOLOGY_BEACH); beach += LAND_DITHER(seaweed, rockpool, beach); /** which is the dominant form of food in this area? */ if ((seaweed > rockpool) && (seaweed > beach)) { *energy = ENERGY_SEAWEED; food_type = FOOD_SEAWEED; } else { if (rockpool > beach) { *energy = ENERGY_SHELLFISH; food_type = FOOD_SHELLFISH; } } return food_type; } /** * @brief Eat food at the given location and return the energy increase * @param loc_x X ape coordinate * @param loc_y Y ape coordinate * @param az Z ape coordinate * @param local_being Pointer to the ape * @return Energy obtained from the food */ n_int food_eat( n_int loc_x, n_int loc_y, n_int az, n_byte * food_type, simulated_being * local_being) { n_int max_energy = BEING_DEAD; *food_type = FOOD_VEGETABLE; if (az > TIDE_MAX) { /** above the high water mark */ *food_type = food_eat_land(loc_x, loc_y, &max_energy); } else { /** in the intertidal zone */ *food_type = food_intertidal(loc_x, loc_y, &max_energy); } return food_absorption(local_being, max_energy, *food_type); } <|start_filename|>entity/being.c<|end_filename|> /**************************************************************** being.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /*! \file being.c * \brief Historically this represented the Simulated Ape but moreso now it represents the Simulated Ape's interface to something external. being.c also now connects to the social, brain, body and metabolim simulations through to external simulations. */ #include "entity.h" #include "entity_internal.h" #include <stdio.h> #include <stdlib.h> /*#pragma mark - macros*/ /** checks the being's line of sight to a point NB: As the direction of scanning can't be determined, the breaking sight point can't be detected through tracking the being_ground results. */ /** returning 0 - not in line of sight, 1 - in line of sight */ typedef struct { n_int start_z; n_int offset_x; n_int offset_y; n_int visibility_delta; n_int visibility_total; } being_draw; /*#pragma mark - can_move*/ static simulated_being_can_move * being_can_move_local = 0L; n_byte being_can_move(n_vect2 * location, n_vect2 * delta) { if (being_can_move_local) { return being_can_move_local(location, delta); } return 1; } void being_can_move_override(simulated_being_can_move * new_can_move) { being_can_move_local = new_can_move; } /*#pragma mark - wrap*/ static simulated_being_wrap * being_wrap_local = 0L; void being_wrap(n_vect2 * location) { if (being_wrap_local) { being_wrap_local(location); } else { n_int px = location->x; n_int py = location->y; px = (px + APESPACE_BOUNDS + 1) & APESPACE_BOUNDS; py = (py + APESPACE_BOUNDS + 1) & APESPACE_BOUNDS; location->x = px; location->y = py; } } void being_wrap_override(simulated_being_wrap * new_move) { being_wrap_local = new_move; } /*#pragma mark - initial_location*/ static simulated_being_initial_location * being_local_initial_location_local = 0L; void being_initial_location(n_vect2 * location, n_byte2 * seed) { if (being_local_initial_location_local) { being_local_initial_location_local(location, seed); } else { n_int loop = 0; do { n_vect2 location_vector; location->x = math_random(seed) & APESPACE_BOUNDS; location->y = math_random(seed) & APESPACE_BOUNDS; being_wrap(&location_vector); loop ++; } while ((loop < 20) && (WATER_TEST( land_location(APESPACE_TO_MAPSPACE(location->x), APESPACE_TO_MAPSPACE(location->y)), land_tide_level() ))); } } void being_initial_location_override(simulated_being_initial_location * new_initial_location) { being_local_initial_location_local = new_initial_location; } /** This checks to see if a Simulated Ape can see a particular point @param local The simulated_being pointer @param location The location of the point to be seen. @return 1 can see, 0 can not see */ static n_byte being_los(simulated_being * local, n_vect2 * location) { n_int local_facing = ((being_facing(local))>>5); n_vect2 temp_location; temp_location.x = location->x; temp_location.y = location->y; /* There is probably a logical simplification of this as I can't think of it here is the brute force method. The Simulated Ape Simulation universe wraps around in all directions you need to calculate the line of site off the map too. */ /* 6 5 7 4 0 3 1 2 */ if (being_los_projection(local,&temp_location) == 1) return 1; if ((local_facing == 6) || (local_facing == 7) || (local_facing == 0) || (local_facing == 1) || (local_facing == 2)) { temp_location.x = location->x + MAP_APE_RESOLUTION_SIZE; temp_location.y = location->y; if (being_los_projection(local, &temp_location) == 1) return 1; } if ((local_facing == 7) || (local_facing == 0) || (local_facing == 1) || (local_facing == 2) || (local_facing == 3)) { temp_location.x = location->x + MAP_APE_RESOLUTION_SIZE; temp_location.y = location->y + MAP_APE_RESOLUTION_SIZE; if (being_los_projection(local, &temp_location) == 1) return 1; } if ((local_facing == 0) || (local_facing == 1) || (local_facing == 2) || (local_facing == 3) || (local_facing == 4)) { temp_location.x = location->x; temp_location.y = location->y+ MAP_APE_RESOLUTION_SIZE; if (being_los_projection(local, &temp_location) == 1) return 1; } if ((local_facing == 1) || (local_facing == 2) || (local_facing == 3) || (local_facing == 4) || (local_facing == 5)) { temp_location.x = location->x - MAP_APE_RESOLUTION_SIZE; temp_location.y = location->y + MAP_APE_RESOLUTION_SIZE; if (being_los_projection(local, &temp_location) == 1) return 1; } if ((local_facing == 2) || (local_facing == 3) || (local_facing == 4) || (local_facing == 5) || (local_facing == 6)) { temp_location.x = location->x - MAP_APE_RESOLUTION_SIZE; temp_location.y = location->y; if (being_los_projection(local, &temp_location) == 1) return 1; } if ((local_facing == 3) || (local_facing == 4) || (local_facing == 5) || (local_facing == 6) || (local_facing == 7)) { temp_location.x = location->x - MAP_APE_RESOLUTION_SIZE; temp_location.y = location->y- MAP_APE_RESOLUTION_SIZE; if (being_los_projection(local, &temp_location) == 1) return 1; } if ((local_facing == 4) || (local_facing == 5) || (local_facing == 6) || (local_facing == 7) || (local_facing == 0)) { temp_location.x = location->x; temp_location.y = location->y - MAP_APE_RESOLUTION_SIZE; if (being_los_projection(local, &temp_location) == 1) return 1; } if ((local_facing == 5) || (local_facing == 6) || (local_facing == 7) || (local_facing == 0) || (local_facing == 1)) { temp_location.x = location->x + MAP_APE_RESOLUTION_SIZE; temp_location.y = location->y - MAP_APE_RESOLUTION_SIZE; if (being_los_projection(local, &temp_location) == 1) return 1; } return 0; } /*#pragma mark - random*/ static void being_random3(simulated_being * value) { math_random3(value->delta.seed); } n_byte2 being_random(simulated_being * value) { return math_random(value->delta.seed); } static void being_set_random(simulated_being * value, n_byte2 * seed) { value->delta.seed[0] = seed[0]; value->delta.seed[1] = seed[1]; } static void being_set_random1(simulated_being * value, n_byte2 seed1) { value->delta.seed[1] = seed1; } static n_byte2 * being_get_random(simulated_being * value) { return value->delta.seed; } static void being_immune_init(simulated_being * local) { #ifdef IMMUNE_ON n_byte i; n_byte2 * local_random = being_get_random(local); simulated_immune_system * immune = &(local->immune_system); for (i = 0; i < IMMUNE_ANTIGENS; i += 2) { immune->antigens[i]=0; immune->antigens[i+1]=0; math_random3(local_random); immune->shape_antigen[i] = (n_byte)(local_random[0]&255); immune->shape_antigen[i+1] = (n_byte)(local_random[1]&255); } for (i = 0; i < IMMUNE_POPULATION; i += 2) { immune->antibodies[i]=0; immune->antibodies[i+1]=0; math_random3(local_random); immune->shape_antibody[i] = (n_byte)(local_random[0]&255); immune->shape_antibody[i+1] = (n_byte)(local_random[1]&255); } #endif } void being_immune_seed(simulated_being * mother, simulated_being * child) { #ifdef IMMUNE_ON n_byte i; simulated_immune_system * immune_mother = &(mother->immune_system); simulated_immune_system * immune_child = &(child->immune_system); /** child acquires mother's antibodies */ for (i=0; i<IMMUNE_POPULATION; i++) { immune_child->shape_antibody[i]=immune_mother->shape_antibody[i]; immune_child->antibodies[i]=immune_mother->antibodies[i]; } #endif } static void being_acquire_pathogen(simulated_being * local, n_byte transmission_type) { #ifdef IMMUNE_ON n_byte i; simulated_immune_system * immune = &(local->immune_system); n_byte2 * local_random = being_get_random(local); math_random3(local_random); if (local_random[0] < PATHOGEN_ENVIRONMENT_PROB) { i = local_random[1]%IMMUNE_ANTIGENS; if (immune->antigens[i]==0) { math_random3(local_random); immune->antigens[i]=(n_byte)(local_random[0]&7); immune->shape_antigen[i] = (n_byte)RANDOM_PATHOGEN(local_random[1], transmission_type); } } #endif } void being_ingest_pathogen(simulated_being * local, n_byte food_type) { n_byte transmission_type=food_type+PATHOGEN_TRANSMISSION_FOOD_VEGETABLE; being_acquire_pathogen(local,transmission_type); } void being_immune_transmit(simulated_being * meeter_being, simulated_being * met_being, n_byte transmission_type) { #ifdef IMMUNE_ON n_byte i,j; n_byte2 * local_random = being_get_random(meeter_being); simulated_immune_system * immune0 = &(meeter_being->immune_system); simulated_immune_system * immune1 = &(met_being->immune_system); /** pathogen obtained from environment */ being_acquire_pathogen(meeter_being, transmission_type); /** pathogen transmitted between beings */ math_random3(local_random); if (local_random[0] < PATHOGEN_TRANSMISSION_PROB) { math_random3(local_random); i = local_random[0]%IMMUNE_ANTIGENS; if ((immune0->antigens[i]>0) && (PATHOGEN_TRANSMISSION(immune0->shape_antigen[i])==transmission_type)) { /** does the other being already carry this pathogen ? */ for (j = 0; j < IMMUNE_ANTIGENS; j++) { if (immune0->shape_antigen[i]==immune1->shape_antigen[j]) { if (immune1->antigens[j]<255) immune1->antigens[j]++; break; } } if (j == IMMUNE_ANTIGENS) { j = local_random[1]%IMMUNE_ANTIGENS; if (immune1->antigens[j]<=MIN_ANTIGENS) { /** spread pathogen */ immune1->shape_antigen[j]=immune0->shape_antigen[i]; } } } } #endif } void being_immune_response(simulated_being * local) { #ifdef IMMUNE_ON n_int min_antibodies; n_int max_bits_matched; n_byte2 total_antigens,max_severity; n_byte i,j,k,match,best_match,bits_matched,bit; n_byte2 * local_random = being_get_random(local); simulated_immune_system * immune = &(local->immune_system); /** antibodies die at some fixed rate */ math_random3(local_random); if (local_random[0]<ANTIBODY_DEPLETION_PROB) { i = local_random[1]%IMMUNE_POPULATION; if (immune->antibodies[i]>0) { immune->antibodies[i]--; } } /** pick an antigen */ math_random3(local_random); i = local_random[0]%IMMUNE_ANTIGENS; if (immune->antigens[i] != 0) { /** mutate with some probability */ if (local_random[1]<PATHOGEN_MUTATION_PROB) { math_random3(local_random); if ((immune->shape_antigen[i] & (1<<(local_random[0]&7))) != 0) { immune->shape_antigen[i] ^= (local_random[0]&7); } else { immune->shape_antigen[i] |= (local_random[0]&7); } } /** try to find a matching antibody */ max_bits_matched=0; best_match=0; for (j = 0; j < IMMUNE_POPULATION; j++) { match = (immune->shape_antibody[j] & immune->shape_antigen[i]) | ((~immune->shape_antibody[j]) & (~immune->shape_antigen[i])); if (match!=0) { /** how good is the fit ? */ bits_matched=0; for (bit=0; bit<8; bit++) { if ((match & (1<<bit)) != 0) { bits_matched++; } } /** record best fit */ if (bits_matched>max_bits_matched) { max_bits_matched=bits_matched; best_match = j; } } } /** select the antibody with the smallest population */ min_antibodies=immune->antibodies[0]; j=0; for (k=1; k<IMMUNE_POPULATION; k++) { if (immune->antibodies[k]<min_antibodies) { min_antibodies = immune->antibodies[k]; j = k; } } /** match antigen and antibody */ if (max_bits_matched>IMMUNE_FIT) { /** Antibodies multiply A better fit results in more antibodies */ if (immune->antibodies[best_match]<255-max_bits_matched) { immune->antibodies[best_match]+=(n_byte)max_bits_matched; /** apply a minimum threshold so that generated antibodies don't overwrite known good fits */ if (immune->antibodies[best_match]<MIN_ANTIBODIES) { immune->antibodies[best_match]=MIN_ANTIBODIES; } } /** antigens are depleted according to the immune system strength */ if (immune->antigens[i]>being_honor_immune(local)) { immune->antigens[i]-=being_honor_immune(local); } else { immune->antigens[i]=0; } /** clone antibody with mutation */ if (j!=best_match) { immune->antibodies[j]=1; match = immune->shape_antibody[best_match]; math_random3(local_random); if ((match & (1<<(local_random[0]&7))) != 0) { match ^= (local_random[0]&7); } else { match |= (local_random[0]&7); } immune->shape_antibody[j] = match; } } else { /** If pathogens are not challenged they multiply */ if (immune->antigens[i]<255) { immune->antigens[i]++; } /** produce differently shaped antibodies */ math_random3(local_random); if (local_random[0]<ANTIBODY_GENERATION_PROB(local)) { math_random3(local_random); immune->shape_antibody[j]=(n_byte)(local_random[0]&255); immune->antibodies[j]=(n_byte)(local_random[1]&7); } } } /** Energy level is reduced based upon pathogens. Note that not all pathogens have the same energy cost. */ total_antigens=0; max_severity=0; for (i=0; i<IMMUNE_ANTIGENS; i++) { /* total quantity of pathogen */ total_antigens+=immune->antigens[i]; /* record the maximum pathogen severity */ if (immune->shape_antigen[i]>max_severity) { max_severity=immune->shape_antigen[i]; } } math_random3(local_random); if ((local_random[0] < (total_antigens>>2)) && (being_energy_less_than(local, BEING_DEAD + 1) == 0)) { being_energy_delta(local, 0-PATHOGEN_SEVERITY(max_severity)); } #endif } static n_uint being_genetic_count_zeros(n_genetics count) { n_uint loop = 0; n_uint addition = 0; while (loop < sizeof(n_genetics)*8) { if (((count>>loop) & 1) == 0) { addition++; } loop++; } return addition; } n_uint being_genetic_comparison(n_genetics * primary, n_genetics * secondary, n_int parse_requirements) { n_int loop = 0; n_uint addition = 0; if (FIND_SEX(secondary[CHROMOSOME_Y]) != SEX_FEMALE) { if (parse_requirements == 1) return 0; } else { if (parse_requirements == 0) return 0; } while (loop < CHROMOSOMES) { n_genetics comparison = primary[loop] ^ secondary[loop]; addition += being_genetic_count_zeros(comparison); loop++; } return addition; } static simulated_being_line_of_sight * being_line_of_sight_local = 0L; void being_line_of_sight_override(simulated_being_line_of_sight * new_line_of_sight) { being_line_of_sight_local = new_line_of_sight; } n_byte being_line_of_sight(simulated_being * local, n_vect2 * location) { if (being_line_of_sight_local) { return being_line_of_sight_local(local, location); } else { return being_los(local, location); } } static simulated_being_brain_cycle * being_brain_cycle_local = 0L; void being_brain_cycle_override(simulated_being_brain_cycle * new_brain_cycle) { being_brain_cycle_local = new_brain_cycle; } void being_brain_cycle(n_byte * local, n_byte2 * constants) { if (being_brain_cycle_local) { being_brain_cycle_local(local, constants); } else { brain_cycle(local, constants); } } /*#pragma mark - braincode*/ #ifdef BRAINCODE_ON n_byte * being_braincode_external(simulated_being * value) { simulated_isocial * social_value = being_social(value); return social_value[ATTENTION_EXTERNAL].braincode; } void being_clear_attention(simulated_being * value) { memory_erase((n_byte*)(value->braindata.attention), ATTENTION_SIZE); } void being_set_attention(simulated_being * value, n_int index, n_int attention) { value->braindata.attention[index] = (n_byte)attention; } n_byte being_attention(simulated_being * value, n_int index) { return value->braindata.attention[index]; } n_byte * being_braincode_internal(simulated_being * value) { simulated_isocial * social_value = being_social(value); n_int attention_location = being_attention(value, ATTENTION_ACTOR); return social_value[attention_location].braincode; } #else void being_clear_attention(simulated_being * value) { } void being_set_attention(simulated_being * value, n_int index, n_int attention) { } n_byte being_attention(simulated_being * value, n_int index) { return 0; } #endif /* ape names */ #define NAMES_SURNAMES 256 #define NAMES_FIRST 256 const n_string english_last_names[256] = { "Abbott","Adams","Allen","Arnold","Ashton","Atkins","Austin","Bailey","Baird","Baker","Ball","Banks","Barker", "Barlow","Barnes","Barton","Bates","Baxter","Begum","Bell","Benson","Berry","Bird","Bishop","Black","Blair", "Blake","Bloggs","Bolton","Bond","Booth","Bowden","Bowen","Boyd","Brennan","Briggs","Brown","Browne","Bryant", "Bull","Burke","Burns","Burton","Butler","Byrne","Carr","Carroll","Carter","Clark","Clarke","Coates","Cole", "Coles","Cook","Cooke","Cooper","Cox","Cross","Cullen","Curtis","Dale","Davey","Davis","Dawson","Day","Dean", "Dennis","Dixon","Doyle","Duffy","Duncan","Dunn","Ellis","Evans","Farrell","Field","Finch","Fisher","Flynn", "Ford","Foster","Fowler","Fox","Fraser","French","Frost","Fuller","Garner","George","Gibson","Giles","Gill", "Glover","Gordon","Gough","Graham","Grant","Gray","Green","Haines","Hall","Hardy","Harper","Harris","Hart", "Harvey","Hayes","Haynes","Heath","Hewitt","Higgins","Hill","Hilton","Hobbs","Holden","Holmes","Holt","Hooper", "Hope","Howard","Howe","Hudson","Hughes","Hunt","Hunter","Jacobs","James","Jarvis","Jones","Jordan","Kemp", "Kent","Kerr","King","Kirk","Knight","Lane","Lawson","Leach","Lee","Leigh","Lewis","Little","Lloyd","Long", "Lord","Love","Lowe","Lucas","Lynch","Mann","Marsh","Mason","May","Mellor","Miles","Miller","Mills","Moore", "Moran","Morgan","Morris","Morton","Moss","Murphy","Murray","Nash","Naylor","Nelson","Newman","Newton","Norman", "Owens","Page","Palmer","Park","Parker","Parry","Patel","Payne","Pearce","Perry","Peters","Poole","Porter", "Potter","Powell","Power","Price","Quinn","Randall","Read","Reed","Rees","Reid","Reilly","Rhodes","Rice","Riley", "Robson","Rogers","Rose","Ross","Rossi","Rowe","Ryan","Savage","Scott","Shah","Sharma","Sharp","Shaw","Silva", "Simmons","Singh","Slater","Smart","Smith","Steele","Stewart","Stevens","Stone","Stuart","Sutton","Swift","Tait", "Taylor","Thomas","Thorne","Todd","Tucker","Turner","Walker","Wall","Wallace","Walsh","Walton","Ward","Warren", "Watson","Watts","Weaver","Webb","Welch","Wells","West","Whelan","White","Willis","Wilson","Wood","Woods", "Wright","Wyatt","Yates","Young" }; const n_string english_female_first_names[256] = { "Ada","Agatha","Agnes","Aileen","Aimee","Alanna","Alda","Alice","Alina","Alison","Alma","Amanda","Amber","Andrea","Angela", "Anita","Anthea","April","Ariana","Arleen","Astrid","Audrey","Beata","Becky","Beryl","Bess","Bianca","Blair","Blythe", "Bonnie","Brenda","Briana","Brooke","Carla","Carly","Carmen","Cheryl","Chloe","Coral","Daphne","Davida","Dawn","Denise", "Donna","Dora","Doris","Echo","Eda","Edana","Edith","Edlyn","Edna","Edwina","Effie","Eileen","Elaine","Elena","Elga", "Elise","Eliza","Ella","Ellen","Eloise","Elsie","Elvira","Emily","Emma","Erika","Erin","Estra","Ethel","Eudora","Eunice", "Faith","Fannie","Fawn","Faye","Fedora","Fern","Fiona","Flora","Gale","Gaye","Geneva","Gilda","Gladys","Gloria","Grace", "Gwynne","Harley","Hattie","Hazel","Hetty","Hilda","Holly","Honey","Hope","Ingrid","Irene","Iris","Ivory","Ivy","Jade", "Jane","Janet","Janice","Jeanne","Jemima","Jewel","Joan","Joanna","Joy","June","Kacey","Kara","Kate","Kay","Keely","Kelsey", "Kendra","Kerri","Kyla","Lacey","Lane","Lara","Larina","Leanne","Leslie","Linda","Livia","Lizzie","Lois","Lorena","Lulu", "Luna","Lynn","Mabel","Madge","Maggie","Maia","Maisie","Mandy","Marcia","Margot","Marnia","Mary","Maude","Maura","Mavis", "Maxine","Megan","Melody","Mercy","Meris","Merle","Miriam","Misty","Moira","Molly","Mona","Monica","Mora","Morgan","Muriel", "Myra","Myrtle","Nancy","Naomi","Nell","Nerita","Nina","Noelle","Nola","Norma","Nydia","Odette","Olga","Opal","Oprah","Orva", "Page","Pamela","Pansy","Patty","Pearl","Phoebe","Polly","Quenna","Questa","Rachel","Ramona","Regina","Rhea","Rhoda","Rita", "Robin","Rosa","Rowena","Ruby","Ruth","Sacha","Sadie","Salena","Sally","Salome","Sandra","Sarah","Serena","Shana","Sharon", "Sheila","Sibley","Silver","Sirena","Talia","Tamara","Tammy","Tanya","Tara","Tasha","Tatum","Tess","Thalia","Thea","Thelma", "Thora","Tilda","Tina","Tracy","Trina","Trista","Tyne","Udele","Ula","Ulrica","Ulva","Una","Unity","Ursa","Ursula","Valda", "Vania","Veleda","Vera","Verda","Violet","Vita","Wanda","Wilda","Willa","Willow","Wynne","Zea","Zelda","Zera","Zoe" }; const n_string english_male_first_names[256] = { "Aaron","Abbott","Abel","Adam","Albern","Albert","Alfie","Alfred","Alvin","Amery","Amos","Andrew","Angus","Ansel","Arlen", "Arnold","Arvel","Austin","Axel","Baird","Barry","Basil","Bert","Blair","Blake","Boris","Brent","Brian","Brice","Brock", "Bruce","Bruno","Bryant","Buck","Bud","Burton","Byron","Calvin","Carl","Carter","Carver","Cary","Casey","Casper","Cecil", "Cedric","Claude","Clive","Clyde","Colin","Conan","Connor","Conrad","Conroy","Conway","Corwin","Craig","Crosby","Culver", "Curt","Curtis","Cyril","Damon","Daniel","Darcy","David","Dean","Declan","Dennis","Derek","Dermot","Derwin","Dexter", "Dillon","Dion","Dirk","Donald","Dorian","Drew","Dudley","Duncan","Dwayne","Dwight","Dylan","Earl","Edgar","Edwin","Efrain", "Egbert","Elbert","Elmer","Elroy","Elton","Elvis","Emmett","Emrick","Ernest","Errol","Esmond","Eugene","Evan","Ezra","Fabian", "Farley","Felix","Fenton","Ferris","Finbar","Floyd","Foster","Fox","Frank","Gale","Galvin","Garret","Garth","Gavin","George", "Gideon","Giles","Gilroy","Glenn","Godwin","Graham","Grant","Guy","Hadden","Hadley","Hadwin","Hale","Hall","Hamlin","Hardy", "Harley","Hector","Henry","Herman","Homer","Howard","Hubert","Hunter","Ian","Isaac","Isaiah","Ivan","Ives","Jack","Jacob", "Jarvis","Jason","Jasper","Jed","Jerome","Jesse","John","Joshua","Justin","Keaton","Keith","Kelsey","Kelvin","Kent","Kerry", "Kevin","Kirby","Kirk","Kit","Kody","Konrad","Kurt","Kyle","Lamont","Landon","Lane","Lars","Lee","Leroy","Leslie","Lester", "Lionel","Lloyd","Logan","Lowell","Lyndon","Marcus","Marlon","Martin","Marvin","Medwin","Melvin","Merlin","Miles","Morgan", "Morris","Morton","Murray","Neal","Nigel","Noel","Norman","Olaf","Olin","Oliver","Oscar","Oswald","Otis","Owen","Paul", "Perry","Peter","Philip","Pierce","Quincy","Quinn","Ralph","Rex","Riley","Rodney","Roger","Roland","Rolf","Ronald","Rory", "Ross","Roy","Rufus","Rupert","Ryan","Samson","Samuel","Scott","Sean","Seth","Shawn","Sidney","Simon","Sloane","Stacy", "Thomas","Toby","Todd","Tony","Trent","Trevor","Troy","Tyler","Unwin","Vance","Victor","Walter","Warren","Wayne","Wilbur", "Willis","Wyatt","Wylie" }; #define FAMILY_NAME_AND_MOD (NAMES_SURNAMES - 1) #define FIRST_NAME_AND_MOD (NAMES_FIRST - 1) #define UNPACK_FAMILY_FIRST_NAME(packed_family_name) (packed_family_name & 255) #define UNPACK_FAMILY_SECOND_NAME(packed_family_name) ((packed_family_name >> 8) & 255) #define GET_NAME_FAMILY(f0,f1) ((n_byte2)((f0&255)|((f1&255)<<8))) void being_unpack_family(n_byte2 name, n_byte * values) /* brain.c */ { values[0] = UNPACK_FAMILY_FIRST_NAME(name); values[1] = UNPACK_FAMILY_SECOND_NAME(name); } n_byte being_first_name(simulated_being * value) { if (value == 0L) { return 0; } { return value->constant.name[0] & FIRST_NAME_AND_MOD; } } static void being_set_first_name(simulated_being * value, n_byte2 name) { value->constant.name[0] = name & FIRST_NAME_AND_MOD; } void being_set_family_name(simulated_being * value, n_byte first, n_byte last) { value->constant.name[1] = (n_byte2)(first | (last << 8)); } n_byte2 being_gender_name(simulated_being * value) { if (value == 0L) { return 0; } return (n_byte2)((being_first_name(value) | (FIND_SEX(GET_I(value))<<8))); } n_byte2 being_family_name(simulated_being * value) { if (value == 0L) { return 0; } return (GET_NAME_FAMILY(being_family_first_name(value),being_family_second_name(value))); } n_int being_name_comparison(simulated_being * value, n_byte2 gender_name, n_byte2 family_name) { return ((being_gender_name(value) == gender_name) && (being_family_name(value) == family_name)); } n_byte being_family_first_name(simulated_being * value) { if (value == 0L) { return 0; } { return UNPACK_FAMILY_FIRST_NAME(value->constant.name[1]); } } n_byte being_family_second_name(simulated_being * value) { if (value == 0L) { return 0; } { return UNPACK_FAMILY_SECOND_NAME(value->constant.name[1]); } } static void being_name(n_byte female, n_int first, n_byte family0, n_byte family1, n_string name) { n_int position = 0; if (first != -1) { if (female) { io_string_write(name, english_female_first_names[ first ], &position); } else { io_string_write(name, english_male_first_names[ first ], &position); } io_string_write(name, " ", &position); io_string_write(name, english_last_names[ family0 ], &position); io_string_write(name, "-", &position); io_string_write(name, english_last_names[ family1 ], &position); } else { io_string_write(name, "Unknown", &position); } } void being_name_simple(simulated_being * value, n_string str) { being_name((FIND_SEX(GET_I(value)) == SEX_FEMALE), being_first_name(value), being_family_first_name(value), being_family_second_name(value), str); } void being_name_byte2(n_byte2 first, n_byte2 family, n_string name) { being_name((n_byte)((first>>8)==SEX_FEMALE), (n_int)(first&255), (n_byte)UNPACK_FAMILY_FIRST_NAME(family), (n_byte)UNPACK_FAMILY_SECOND_NAME(family), name); } void being_state_description(n_byte2 state, n_string result) { /* if you change this you need to change the corresponding definitions in entity.h */ const n_string state_description[] = { "Sleeping", "Awake", "Hungry", "Swimming", "Eating", "Moving", "Speaking", "Shouting", "Grooming", "Suckling", "Showing Force", "Attacking" }; n_int string_length=0; n_int n=2; if (state == BEING_STATE_ASLEEP) { io_string_write(result, state_description[0], &string_length); return; } while (n < BEING_STATES) { if (state & (1<<(n-1))) { if (string_length > 0) { io_string_write(result, ", ", &string_length); } io_string_write(result, state_description[n], &string_length); } n++; } } /** This moves the specified Simulated Ape outside the core simulation movement interface - think mouse movement or keyboard movement. @param local The pointer to the simulated_being being moved. @param rel_vel The movement variable used - historically the velocity hence the variable name. @param kind The kind of movement used - 0 = turning around pivoting on the z-axis (ie a standing turn), 1 = move forwards or backwards based on the direction facing, 2 = cursor like movements along the X and Y axis useful when operating the arrow keys (but not much else). */ void being_move(simulated_being * local, n_int rel_vel, n_byte kind) { n_vect2 location_vector; n_byte2 loc[2]; being_space(local, &location_vector); if (kind == 1) { n_vect2 facing_vector; being_facing_vector(local, &facing_vector, 1); vect2_d(&location_vector, &facing_vector, rel_vel, 512); } else { if (rel_vel < 2) location_vector.y -= (rel_vel * 200)-100; else location_vector.x += 500-(rel_vel * 200); } being_wrap(&location_vector); loc[0] = (n_byte2)location_vector.x; loc[1] = (n_byte2)location_vector.y; being_set_location(local, loc); } n_byte being_crowding(simulated_being * value) { return value->delta.crowding; } void being_crowding_cycle(simulated_being * value, n_int beings_in_vacinity) { /** if the being is not overcrowded and its social drive is not saturated */ if (beings_in_vacinity < (value->delta.crowding + SOCIAL_TOLLERANCE)) { /** increase the social drive */ being_inc_drive(value, DRIVE_SOCIAL); } else { /** decrease the social drive */ being_dec_drive(value, DRIVE_SOCIAL); } /** Adjust crowding (typical expected number of neighbours). */ if (beings_in_vacinity < value->delta.crowding) { if (value->delta.crowding > MIN_CROWDING) { value->delta.crowding--; } } if (beings_in_vacinity > value->delta.crowding) { if (value->delta.crowding < MAX_CROWDING) { value->delta.crowding++; } } } /*#pragma mark - state*/ void being_set_state(simulated_being * value, being_state_type state) { value->delta.macro_state = state; } void being_add_state(simulated_being * value, being_state_type state) { value->delta.macro_state |= state; } n_byte2 being_state(simulated_being * value) { return value->delta.macro_state; } /*#pragma mark - brainstates*/ #ifdef BRAIN_ON void being_set_brainstates(simulated_being * value, n_int asleep, n_byte2 val1, n_byte2 val2, n_byte2 val3) { n_int three_offset = (asleep ? 0 : 3); value->braindata.brain_state[three_offset + 0] = val1; value->braindata.brain_state[three_offset + 1] = val2; value->braindata.brain_state[three_offset + 2] = val3; } #endif n_int being_brainstates(simulated_being * value, n_int asleep, n_byte2 * states) { n_int three_offset = (asleep ? 0 : 3); states[0] = value->braindata.brain_state[three_offset + 0]; states[1] = value->braindata.brain_state[three_offset + 1]; states[2] = value->braindata.brain_state[three_offset + 2]; return ((states[0] != 0) || (states[1] != 1024) || (states[2] != 0)); } /*#pragma mark - erase*/ void being_erase(simulated_being * value) { memory_erase((n_byte*)value, sizeof(simulated_being)); } /*#pragma mark - honor*/ void being_honor_delta(simulated_being * value, n_int delta) { n_int honor_value = value->delta.honor; if (delta > 0) { if ((honor_value + delta) > 255) { value->delta.honor = 255; return; } } else { if ((honor_value + delta) < 0) { value->delta.honor = 0; return; } } value->delta.honor += (n_byte)delta; } n_byte being_honor(simulated_being * value) { return value->delta.honor; } void being_honor_inc_dec(simulated_being * inc, simulated_being * dec) { if (inc->delta.honor < 255) inc->delta.honor++; if (dec->delta.honor > 0) dec->delta.honor--; } void being_honor_swap(simulated_being * victor, simulated_being * vanquished) { if (victor->delta.honor < vanquished->delta.honor) { /** swap social status */ n_byte temp_hon = victor->delta.honor; victor->delta.honor = vanquished->delta.honor; vanquished->delta.honor = temp_hon; } } n_int being_honor_compare(simulated_being * first, simulated_being * second) { if (first->delta.honor > second->delta.honor) { return 1; } if (first->delta.honor < second->delta.honor) { return -1; } return 0; } n_byte being_honor_immune(simulated_being * value) { n_int local_honor = being_honor(value); if (local_honor < 250) /* ALPHA_RANK */ { return (n_byte)(1 + (local_honor>>6)); } return 2; /* IMMUNE_STRENGTH_ALPHA */ } /*#pragma mark - posture*/ n_byte being_posture(simulated_being * value) { return value->delta.posture; } void being_set_posture(simulated_being * value, n_byte post) { value->delta.posture = post; } n_int being_posture_under(simulated_being * value, enum posture_type post) { return (value->delta.posture < post); } /*#pragma mark - brain*/ #ifdef BRAIN_ON n_byte * being_brain(simulated_being * value) { return value->braindata.brain; } #endif /*#pragma mark - misc*/ simulated_iepisodic * being_episodic(simulated_being * value) { return value->events.episodic; } simulated_isocial * being_social(simulated_being * value) { return value->events.social; } n_int being_location_x(simulated_being * value) { return (n_int)value->delta.location[0]; } n_int being_location_y(simulated_being * value) { return (n_int)value->delta.location[1]; } void being_high_res(simulated_being * value, n_vect2 * vector) { vector->x = APESPACE_TO_HR_MAPSPACE(being_location_x(value)); vector->y = APESPACE_TO_HR_MAPSPACE(being_location_y(value)); } void being_space(simulated_being * value, n_vect2 * vector) { vector->x = value->delta.location[0]; vector->y = value->delta.location[1]; } n_byte2 * being_location(simulated_being * value) { return value->delta.location; } void being_set_location(simulated_being * value, n_byte2 * from) { value->delta.location[0] = from[0]; value->delta.location[1] = from[1]; } #ifdef DEBUG_LACK_OF_MOVEMENT n_int being_total_movement(simulated_being * value) { return (n_int) value->delta.total_movement; } void being_add_total_movement(simulated_being * value) { value->delta.total_movement += value->delta.velocity; } void being_zero_total_movement(simulated_being * value) { value->delta.total_movement = 0; } void being_register_movement(simulated_being * value, n_string comment_string) { if ((IS_NIGHT(land_time()) == 0) && (being_total_movement(value) == 0)) { n_string_block name_string, time_string; io_time_to_string(time_string); being_name_simple(value, name_string); printf("%s %s %s\n", time_string, name_string, comment_string); } } #endif n_byte being_speed(simulated_being * value) { return value->delta.velocity; } void being_set_speed(simulated_being * value, n_byte sp) { value->delta.velocity = sp; } void being_delta(simulated_being * primary, simulated_being * secondary, n_vect2 * delta) { delta->x = primary->delta.location[0] - secondary->delta.location[0]; delta->y = primary->delta.location[1] - secondary->delta.location[1]; } /*#pragma mark - parasites*/ void being_add_parasites(simulated_being * value) { /* maximum number of parasites in the range 0-255 */ if (value->delta.parasites < ((GENE_HAIR(being_genetics(value))*255)>>4)) { value->delta.parasites++; } } void being_remove_parasites(simulated_being * value, n_int number_of_parasites) { if (value->delta.parasites > number_of_parasites) { value->delta.parasites -= (n_byte)number_of_parasites; } else { value->delta.parasites = 0; } } n_int being_parasites(simulated_being * value) { return value->delta.parasites; } void being_set_parasites(simulated_being * value, n_byte parasites) { value->delta.parasites = parasites; } /*#pragma mark - misc part 2*/ n_int being_dob(simulated_being * value) { return value->constant.date_of_birth; } void being_facing_towards(simulated_being * value, n_vect2 * vector) { value->delta.direction_facing = math_turn_towards(vector, value->delta.direction_facing, 0); } void being_wander(simulated_being * value, n_int wander) { value->delta.direction_facing = (n_byte)((value->delta.direction_facing + 256 + wander) & 255); } void being_facing_init(simulated_being * value) { value->delta.direction_facing = (n_byte)(being_random(value) & 255); } void being_facing_vector(simulated_being * value, n_vect2 * vect, n_int divisor) { vect2_direction(vect, value->delta.direction_facing, divisor * 32); } n_byte being_facing(simulated_being * value) { return value->delta.direction_facing; } n_genetics * being_genetics(simulated_being * value) { return value->constant.genetics; } n_int being_pregnant(simulated_being * value) { return value->changes.date_of_conception; } n_int being_female(simulated_being * value) { return (FIND_SEX(GET_I(value)) == SEX_FEMALE); } n_int being_speaking(simulated_being * value) { return (value->delta.awake && (being_state(value) & BEING_STATE_SPEAKING)); } n_genetics * being_fetal_genetics(simulated_being * value) { return value->changes.fetal_genetics; } /* TODO: Remove this kind of access eventually */ n_int being_energy(simulated_being * value) { return value->delta.stored_energy; } n_int being_energy_less_than(simulated_being * value, n_int less_than) { return being_energy(value) < less_than; } void being_dead(simulated_being * value) { value->delta.stored_energy = BEING_DEAD; } void being_living(simulated_being * value) { value->delta.stored_energy = BEING_FULL; } void being_energy_delta(simulated_being * value, n_int delta) { n_int total = value->delta.stored_energy + delta; if (total < BEING_DEAD) { total = BEING_DEAD; } value->delta.stored_energy = (n_byte2) total; } n_byte being_drive(simulated_being * value, enum drives_definition drive) { return value->changes.drives[drive]; } void being_inc_drive(simulated_being * value, enum drives_definition drive) { if (value->changes.drives[drive] < DRIVES_MAX) { value->changes.drives[drive]++; } } void being_dec_drive(simulated_being * value, enum drives_definition drive) { if (value->changes.drives[drive] > 0) { value->changes.drives[drive]--; } } void being_reset_drive(simulated_being * value, enum drives_definition drive) { value->changes.drives[drive] = 0; } n_int being_height(simulated_being * value) { return value->delta.height; } void being_set_height(simulated_being * value, n_int height) { value->delta.height = (n_byte2)height; } n_int being_mass(simulated_being * value) { return value->delta.mass; } void being_turn_away_from_water(simulated_being * value) { n_int it_water_turn = 0; n_vect2 location_vector; being_space(value, &location_vector); while (it_water_turn < 7) { /* find higher land first */ n_int iturn = 8 - it_water_turn; n_int loc_f = being_facing(value); n_int iturn_plus = loc_f + iturn; n_int iturn_minus = loc_f + (256-iturn); n_byte turn_plus = (n_byte)((iturn_plus) & 255); n_byte turn_minus = (n_byte)((iturn_minus) & 255); n_vect2 temp_vector; n_int z_plus; n_int z_minus; vect2_direction(&temp_vector, turn_plus, 128); vect2_add(&temp_vector, &temp_vector, &location_vector); land_convert_to_map(&temp_vector); z_plus = land_location_vect(&temp_vector); vect2_direction(&temp_vector, turn_minus, 128); vect2_add(&temp_vector, &temp_vector, &location_vector); land_convert_to_map(&temp_vector); z_minus = land_location_vect(&temp_vector); if (z_minus > z_plus) { being_wander(value, -iturn); } else if (z_minus < z_plus) { being_wander(value, iturn); } it_water_turn++; } } enum inventory_type being_carried(simulated_being * value, enum BODY_INVENTORY_TYPES location) { return (value)->changes.inventory[location] & 0xfffff8; } void being_drop(simulated_being * value, enum BODY_INVENTORY_TYPES location) { (value)->changes.inventory[location] &= 7; being_set_attention(value, ATTENTION_BODY, location); } void being_take(simulated_being * value, enum BODY_INVENTORY_TYPES location, enum inventory_type object) { (value)->changes.inventory[location] |= object; being_set_attention(value, ATTENTION_BODY, location); } /** * @brief Check if a being is on ground or in water * @param px x coordinate of the being location * @param py y coordinate of the being location * @param params being_draw pointer * @return 1 if on ground, 0 otherwise */ static n_byte being_ground(n_int px, n_int py, n_int dx, n_int dy, void * params) { n_int abs_sum = ABS(dx) + ABS(dy); being_draw * being_pixel = (being_draw *) params; n_int d_vis = being_pixel->visibility_delta; n_int local_z = ((px*(being_pixel->offset_x)) + (py*(being_pixel->offset_y))) >> 9; if (abs_sum) { weather_values seven_values = weather_seven_values(APESPACE_TO_MAPSPACE(px), APESPACE_TO_MAPSPACE(py)); n_int span10 = ((abs_sum - 1) ? 1448 : 1024); switch (seven_values) { case WEATHER_SEVEN_SUNNY_DAY: case WEATHER_SEVEN_CLOUDY_DAY: being_pixel->visibility_total += (span10 * (d_vis + 16)) >> 11; break; case WEATHER_SEVEN_RAINY_DAY: case WEATHER_SEVEN_DAWN_DUSK: being_pixel->visibility_total += (span10 * ((2 * d_vis) + 25)) >> 11; break; case WEATHER_SEVEN_CLEAR_NIGHT: being_pixel->visibility_total += (span10 * ((5 * d_vis) + 65)) >> 11; case WEATHER_SEVEN_CLOUDY_NIGHT: being_pixel->visibility_total += (span10 * ((8 * d_vis) + 93)) >> 11; case WEATHER_SEVEN_RAINY_NIGHT: being_pixel->visibility_total += (span10 * ((12 * d_vis) + 145)) >> 11; break; case WEATHER_SEVEN_ERROR: default: return 1; } if (being_pixel->visibility_total > VISIBILITY_MAXIMUM) return 1; local_z += being_pixel->start_z; if (local_z < WALK_ON_WATER(land_location(px, py), land_tide_level())) { return 1; } } return 0; } n_byte being_basic_line_of_sight(simulated_being * local, n_vect2 * extern_end, n_vect2 * start, n_vect2 * delta, n_vect2 * end) { n_vect2 vector_facing; vect2_copy(end, extern_end); /* TODO: Check for being awake - need a land and being based awake check */ being_space(local, start); vect2_subtract(delta, end, start); { n_int distance_squared = vect2_dot(delta, delta, 1, 1); if (distance_squared > (VISIBILITY_SPAN * VISIBILITY_SPAN)) { return 0; } } /** check trivial case first - self aware */ if ((delta->x == 0) && (delta->y == 0)) { return 1; } being_facing_vector(local, &vector_facing, 16); /* if it is behind, it can't be in the line of sight */ if (vect2_dot(&vector_facing, delta, 1, 64) < 0) { return 0; } return 2; } n_byte being_los_projection(simulated_being * local, n_vect2 * extern_end) { n_vect2 start, delta, end; n_byte return_value = being_basic_line_of_sight(local, extern_end, &start, &delta, &end); if (return_value != 2) { return return_value; } /** move everything from being co-ordinates to map co-ordinates */ land_convert_to_map(&start); land_convert_to_map(&delta); land_convert_to_map(&end); /* check trivial case first - self aware (after co-ord translation) */ if ((delta.x == 0) && (delta.y == 0)) { return 1; } { const n_int simulated_iape_height = 3; n_int start_z = (n_int)WALK_ON_WATER(land_location_vect(&start),land_tide_level()) + simulated_iape_height; n_int delta_z = (n_int)WALK_ON_WATER(land_location_vect(&end),land_tide_level()) - start_z + simulated_iape_height; n_int common_divisor = vect2_dot(&delta, &delta, 1, 1); being_draw translate; if(common_divisor == 0) { common_divisor = 1; } { n_vect2 offset = {0}; vect2_d(&offset, &delta, 512 * delta_z, common_divisor); start_z -= vect2_dot(&start, &offset, 1, 512); translate.start_z = start_z; translate.offset_x = offset.x; translate.offset_y = offset.y; translate.visibility_total = 100 * GENE_VISION_INITIAL(being_genetics(local)); translate.visibility_delta = GENE_VISION_DELTA(being_genetics(local)); } { n_join being_point; being_point.information = (void *) &translate; being_point.pixel_draw = &being_ground; if(math_join_vect2(start.x, start.y, &delta, &being_point)) { return 0; } } } return 1; } #ifdef BRAINCODE_ON static void being_init_braincode_create(simulated_being * local, n_byte internal) { n_byte2 * local_random = being_get_random(local); n_int ch = 0; /** initially seed the brain with instructions which are random but genetically biased */ while (ch < BRAINCODE_SIZE) { math_random3(local_random); if (internal != 0) { #ifdef RANDOM_INITIAL_BRAINCODE being_braincode_internal(local)[ch] = math_random(local_random) & 255; #else being_random3(local); being_braincode_internal(local)[ch] = (math_random(local_random) & 192) | get_braincode_instruction(local); #endif being_braincode_internal(local)[ch+1] = math_random(local_random) & 255; being_braincode_internal(local)[ch+2] = math_random(local_random) & 255; } else { #ifdef RANDOM_INITIAL_BRAINCODE being_braincode_external(local)[ch] = math_random(local_random) & 255; #else being_random3(local); being_braincode_external(local)[ch] = (math_random(local_random) & 192) | get_braincode_instruction(local); #endif being_braincode_external(local)[ch+1] = math_random(local_random) & 255; being_braincode_external(local)[ch+2] = math_random(local_random) & 255; } ch += 3; } } /** initialise inner or outer braincode */ void being_init_braincode(simulated_being * local, simulated_being * other, n_byte friend_foe, n_byte internal) { n_uint i,most_similar_index,diff,min,actor_index; simulated_isocial * graph; if (other==0L) { being_init_braincode_create(local, internal); } else { /** initialise based upon a similar being */ graph = being_social(local); if (graph == 0L) { return; } most_similar_index=0; min=99999; actor_index = being_attention(local,ATTENTION_ACTOR); /** Find the entry in the social graph with the most similar friend or foe value. The FOF value is used because when two beings meet for the first time this value is calculated based upon a variety of genetic and learned dispositions. Notice also that the search includes index zero, which is the self. */ for (i=0; i<SOCIAL_SIZE; i++) { if ((i!=actor_index) && (!SOCIAL_GRAPH_ENTRY_EMPTY(graph,i))) { n_int signed_diff = (n_int)graph[i].friend_foe - (n_int)friend_foe; if (signed_diff < 0) { diff = (n_uint)(0-signed_diff); } else { diff = (n_uint)signed_diff; } if (diff < min) { min = diff; most_similar_index = i; } } } /** Copy braincode for the most similar individual */ memory_copy(graph[most_similar_index].braincode, graph[actor_index].braincode, BRAINCODE_SIZE); } } #endif /** Assign a unique name to the given being, based upon the given family names */ static n_int being_set_unique_name(simulated_being * beings, n_int number, simulated_being * local_being, n_byte2 mother_family_name, n_byte2 father_family_name) { n_int i; n_int samples=0,found=0; n_byte2 possible_family_name; n_byte2 possible_first_name; /** random number initialization */ being_random3(local_being); being_random3(local_being); /** if no mother and father are specified then randomly create names */ if ((mother_family_name==0) && (father_family_name==0)) { n_byte2 * random_factor = being_get_random(local_being); mother_family_name = GET_NAME_FAMILY((random_factor[0] & FAMILY_NAME_AND_MOD), (random_factor[1] & FAMILY_NAME_AND_MOD)); math_random3(random_factor); father_family_name = GET_NAME_FAMILY((random_factor[0] & FAMILY_NAME_AND_MOD), (random_factor[1] & FAMILY_NAME_AND_MOD)); } /** conventional family name */ possible_family_name = GET_NAME_FAMILY(UNPACK_FAMILY_FIRST_NAME(mother_family_name), UNPACK_FAMILY_FIRST_NAME(father_family_name)); while ((found == 0) && (samples < 2048)) { n_byte2 * random_factor = being_get_random(local_being); being_random3(local_being); /** choose a first_name at random */ possible_first_name = (n_byte2)((random_factor[0] & 255) | (FIND_SEX(GET_I(local_being))<<8)); /** avoid the same two family names */ if (UNPACK_FAMILY_FIRST_NAME(mother_family_name) == UNPACK_FAMILY_SECOND_NAME(father_family_name)) { being_random3(local_being); random_factor = being_get_random(local_being); possible_family_name = GET_NAME_FAMILY((random_factor[0] & FAMILY_NAME_AND_MOD), (random_factor[1] & FAMILY_NAME_AND_MOD)); } if (samples == 1024) { being_random3(local_being); random_factor = being_get_random(local_being); possible_family_name = GET_NAME_FAMILY((random_factor[0] & FAMILY_NAME_AND_MOD), (random_factor[1] & FAMILY_NAME_AND_MOD)); } /** avoid the same two family names */ if (UNPACK_FAMILY_SECOND_NAME(mother_family_name) == UNPACK_FAMILY_FIRST_NAME(father_family_name)) { being_random3(local_being); random_factor = being_get_random(local_being); possible_family_name = GET_NAME_FAMILY((random_factor[0] & FAMILY_NAME_AND_MOD), (random_factor[1] & FAMILY_NAME_AND_MOD)); } being_set_first_name(local_being, possible_first_name); being_set_family_name(local_being, UNPACK_FAMILY_FIRST_NAME(possible_family_name), UNPACK_FAMILY_SECOND_NAME(possible_family_name)); /** does the name already exist in the population */ found = 1; for (i = 0; i < number; i++) { simulated_being * other_being = &beings[i]; if (being_name_comparison(local_being, being_gender_name(other_being), being_family_name(other_being))) { found = 0; break; } } samples++; } return found; } static void being_random_genetics(n_genetics * value, n_byte2 * random, n_int male) { n_int loop = 0; math_random3(random); while (loop < CHROMOSOMES) { n_uint loop2 = 0; value[loop] = 0; while (loop2 < (sizeof(n_genetics)*8)) { if (math_random(random)&1) { value[loop] |= 1 << loop2; } loop2++; } loop++; } value[CHROMOSOME_Y] = (n_genetics)(value[CHROMOSOME_Y] & 0xfffffffe); value[CHROMOSOME_Y] |= (male ? 2 : 3); } n_uint being_init_group(simulated_being * beings, n_byte2 * local_random, n_uint count_to, n_uint max) { n_uint num = 0; math_random3(local_random); while (num < count_to) { math_random3(local_random); if((num + 1) < max) { if (being_init(beings, (n_int)num, &beings[num], 0L, local_random) != 0) { being_erase(&beings[num]); break; } else { num++; } } } return num; } /** * Initialise the ape's variables and clear its brain \ * @param mother Pointer to the mother * @param random_factor Random seed * @return 0 */ n_int being_init(simulated_being * beings, n_int number, simulated_being * local, simulated_being * mother, n_byte2* random_factor) { n_int loop = 0; #ifdef EPISODIC_ON simulated_isocial * local_social_graph = being_social(local); simulated_iepisodic * local_episodic = being_episodic(local); if (local_social_graph == 0L) { return SHOW_ERROR("Social memory not available"); } if (local_episodic == 0L) { return SHOW_ERROR("Episodic memory not available"); } #endif being_erase(local); #ifdef BRAIN_ON { n_byte * brain_memory = being_brain(local); if (brain_memory != 0L) { memory_erase(brain_memory, DOUBLE_BRAIN); } else { return SHOW_ERROR("Brain memory not available"); } } #endif being_set_goal_none(local); /** Set learned preferences to 0.5 (no preference in either direction. This may seem like tabla rasa, but there are genetic biases */ while(loop < PREFERENCES) { local->changes.learned_preference[loop++]=127; } being_immune_init(local); being_clear_attention(local); /** clear the generation numbers for mother and father */ if (mother) { local->constant.generation_max = mother->changes.child_generation_max + 1; local->constant.generation_min = mother->changes.child_generation_min + 1; } else { local->constant.generation_max = 0; local->constant.generation_min = 0; } local->changes.child_generation_max = 0; local->changes.child_generation_min = 0; /** initially seed the brain with instructions which are genetically biased */ if (random_factor) { being_set_random(local, random_factor); being_random3(local); being_random3(local); } else if (mother) { (void)being_random(mother); being_set_random(local, being_get_random(mother)); being_random3(local); being_set_random1(local, being_get_random(mother)[0]); being_random3(local); being_set_random1(local, (n_byte2)land_time()); being_random3(local); } else { NA_ASSERT(random_factor, "Random factor not set"); NA_ASSERT(mother, "Mother not set"); return SHOW_ERROR("No correct being interface provided"); } #ifdef BRAINCODE_ON being_random3(local); #ifdef EPISODIC_ON /** has no social connections initially */ memory_erase((n_byte*)local_social_graph,sizeof(simulated_isocial)*SOCIAL_SIZE); loop = 0; while (loop <EPISODIC_SIZE) { local_episodic[loop++].affect=EPISODIC_AFFECT_ZERO; } local_social_graph[0].relationship=RELATIONSHIP_SELF; loop = 0; while (loop < SOCIAL_SIZE) { /** default type of entity */ local_social_graph[loop].entity_type = ENTITY_BEING; /** friend_or_foe can be positive or negative, with SOCIAL_RESPECT_NORMAL as the zero point */ local_social_graph[loop].friend_foe = SOCIAL_RESPECT_NORMAL; loop++; } #endif /* TODO: Apply fitness function around the braincode generation */ being_init_braincode(local, 0L, 0, BRAINCODE_INTERNAL); being_init_braincode(local, 0L, 0, BRAINCODE_EXTERNAL); /** randomly initialize registers */ loop = 0; while (loop < BRAINCODE_PSPACE_REGISTERS) { being_random3(local); local->braindata.braincode_register[loop++] = (n_byte)being_random(local)&255; } /** initialize brainprobes */ loop = 0; while (loop < BRAINCODE_PROBES) { being_random3(local); if (being_random(local)&1) { local->braindata.brainprobe[loop].type = INPUT_SENSOR; } else { local->braindata.brainprobe[loop].type = OUTPUT_ACTUATOR; } local->braindata.brainprobe[loop].frequency = (n_byte)1 + (being_random(local)%BRAINCODE_MAX_FREQUENCY); being_random3(local); local->braindata.brainprobe[loop].address = (n_byte)being_random(local)&255; local->braindata.brainprobe[loop].position = (n_byte)being_random(local)&255; being_random3(local); local->braindata.brainprobe[loop].offset = (n_byte)being_random(local)&255; loop++; } #endif being_facing_init(local); if (random_factor) { n_byte2 location[2]; n_vect2 location_vector; being_random3(local); being_initial_location(&location_vector, being_get_random(local)); location[0] = (n_byte2)location_vector.x; location[1] = (n_byte2)location_vector.y; being_set_location(local, location); { n_genetics mother_genetics[CHROMOSOMES]; n_genetics father_genetics[CHROMOSOMES]; n_byte2 gene_random[2]; being_random3(local); gene_random[0] = being_random(local); being_random3(local); being_random3(local); gene_random[1] = being_random(local); being_random_genetics(mother_genetics, gene_random, 0); being_random3(local); gene_random[0] = being_random(local); being_random3(local); being_random3(local); being_random3(local); gene_random[1] = being_random(local); being_random_genetics(father_genetics, gene_random, 1); being_random3(local); body_genetics(beings, number, being_genetics(local), mother_genetics, father_genetics, gene_random); being_set_unique_name(beings, number, local, 0L, 0L); } local->delta.social_coord_x = local->delta.social_coord_nx = (math_random(local->delta.seed) & 32767)+16384; local->delta.social_coord_y = local->delta.social_coord_ny = (math_random(local->delta.seed) & 32767)+16384; local->constant.date_of_birth = 0; } else { being_set_location(local, being_location(mother)); /** this is the same as equals */ being_wander(local, being_facing(mother) - being_facing(local)); (void) being_random(local); local->delta.social_coord_x = local->delta.social_coord_nx = mother->delta.social_coord_x; local->delta.social_coord_y = local->delta.social_coord_ny = mother->delta.social_coord_y; genetics_set(being_genetics(local), being_fetal_genetics(mother)); /** ascribed social status */ local->delta.honor = (n_byte)being_honor(mother); being_set_unique_name(beings, number, local, being_family_name(mother), mother->changes.father_name[1]); local->constant.date_of_birth = land_date(); } being_living(local); if (random_factor) { being_set_height(local, BIRTH_HEIGHT); GET_M(local) = BIRTH_MASS; } else { /** produce an initial distribution of heights and masses*/ being_random3(local); being_set_height(local, BIRTH_HEIGHT + (local->delta.seed[0]%(BEING_MAX_HEIGHT-BIRTH_HEIGHT))); GET_M(local) = BIRTH_MASS + (local->delta.seed[1]%(BEING_MAX_MASS_G-BIRTH_MASS)); } local->delta.crowding = MIN_CROWDING; #ifdef BRAIN_ON if (being_brain(local)) { /** These magic numbers were found in March 2001 - feel free to change them! */ being_set_brainstates(local, 0, 171, 0, 146); being_set_brainstates(local, 1, 86, 501, 73); } #endif return 0; } n_int being_move_energy(simulated_being * local_being, n_int * conductance) { n_int local_s = being_speed(local_being); n_int delta_e = 0; n_vect2 location_vector; n_vect2 facing_vector; n_genetics *genetics = being_genetics(local_being); being_space(local_being, &location_vector); being_facing_vector(local_being, &facing_vector, 1); if (local_s > 0) { n_byte2 location[2]; vect2_d(&location_vector, &facing_vector, local_s, 512); /* vector to n_byte2 may do incorrect wrap around MUST be improved */ being_wrap(&location_vector); location[0] = (n_byte2)location_vector.x; location[1] = (n_byte2)location_vector.y; being_set_location(local_being, location); #ifdef DEBUG_LACK_OF_MOVEMENT being_add_total_movement(local_being); #endif } { n_int delta_z; n_int delta_energy; n_int local_z; n_vect2 slope_vector; land_vect2(&slope_vector, &local_z, &location_vector); delta_z = vect2_dot(&slope_vector, &facing_vector, 1, 96); delta_energy = ((512 - delta_z) * local_s)/80; if (WATER_TEST(local_z, land_tide_level())) { n_int insulation = 0; /** the more body fat, the less energy is lost whilst swimming */ n_int fat_mass = GET_BODY_FAT(local_being); delta_energy = ((delta_energy * delta_energy) >> 9); if (fat_mass > BEING_MAX_MASS_FAT_G) { fat_mass = BEING_MAX_MASS_FAT_G; } insulation = fat_mass * 5 / BEING_MAX_MASS_FAT_G; delta_e += (delta_energy + 10 - insulation) >> 3; *conductance = 4; } else { if (delta_z > 0) { /** going uphill */ delta_energy += GENE_HILL_CLIMB(genetics); } delta_energy = ((delta_energy * delta_energy) >> 9); /* the more massive the more energy consumed when moving */ delta_e += (delta_energy + 4 + (GET_M(local_being)*5/BEING_MAX_MASS_G)) >> 2; } } return delta_e; } <|start_filename|>toolkit/graph.c<|end_filename|> /**************************************************************** graph.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /*! \file graph.c * \brief This covers the primary graphics of Simulated Ape. */ #include "toolkit.h" typedef void (graph_func_set_color)(n_byte * buffer, n_rgba32 * color, n_int number); typedef void (graph_func_set_color_transparency)(n_byte * buffer, n_rgba32 * color, n_int number, n_byte transparency); typedef n_int (graph_func_bytes_per_unit)(void); void graph_four_set_color_transparency(n_byte * buffer, n_rgba32 * color, n_int number, n_byte transparency) { n_int n4 = number * 4; buffer[n4] = ((color->rgba.b*(255-transparency)) + (buffer[n4]*transparency))/256; buffer[n4+1] = ((color->rgba.g*(255-transparency)) + (buffer[n4+1]*transparency))/256; buffer[n4+2] = ((color->rgba.r*(255-transparency)) + (buffer[n4+2]*transparency))/256; buffer[n4+3] = 0; } void graph_four_set_color(n_byte * buffer, n_rgba32 * color, n_int number) { n_byte4 *convert = (n_byte4 *)buffer; convert[number] = color->thirtytwo; } n_int graph_four_bytes_per_unit(void) { return 4; } void graph_one_set_color_transparency(n_byte * buffer, n_rgba32 * color, n_int number, n_byte transparency) { buffer[number] = ((color->rgba.b*(255-transparency)) + (buffer[number]*transparency))/256; } void graph_one_set_color(n_byte * buffer, n_rgba32 * color, n_int number) { buffer[number] = color->rgba.b; } n_int graph_one_bytes_per_unit(void) { return 1; } static graph_func_set_color * graph_local_set_color = &graph_one_set_color; static graph_func_bytes_per_unit * graph_local_bytes_per_unit = &graph_one_bytes_per_unit; static graph_func_set_color_transparency * graph_local_set_color_transparency = &graph_one_set_color_transparency; void graph_init(n_int four_byte_factory) { if (four_byte_factory) { graph_local_set_color = &graph_four_set_color; graph_local_bytes_per_unit = &graph_four_bytes_per_unit; graph_local_set_color_transparency = &graph_four_set_color_transparency; } } void graph_erase(n_byte * buffer, n_vect2 * img, n_rgba32 * color) { n_int i = 0; while (i < img->x) { graph_local_set_color(buffer, color, i++); } i = 1; while (i < img->y) { n_int bytes_per_unit = graph_local_bytes_per_unit(); memory_copy(buffer, &buffer[ i++ * img->x * bytes_per_unit], (n_uint)(img->x * bytes_per_unit)); } } /* draws a line */ void graph_line(n_byte * buffer, n_vect2 * img, n_vect2 * previous, n_vect2 * current, n_rgba32 * color, n_byte thickness) { n_int i,max; n_vect2 delta; n_vect2 absdelta; vect2_subtract(&delta, current, previous); vect2_copy(&absdelta, &delta); if (absdelta.x < 0) absdelta.x = -delta.x; if (absdelta.y < 0) absdelta.y = -delta.y; max = absdelta.x; if (absdelta.y > max) max = absdelta.y; for (i=0; i<max; i++) { n_int xx = previous->x + (i*(current->x - previous->x)/max); if ((xx > -1) && (xx < img->x)) { n_int yy = previous->y + (i*(current->y-previous->y)/max); if ((yy > -1) && (yy < img->y)) { n_int n = (yy*img->x + xx); graph_local_set_color(buffer, color, n); if (thickness > 2) { if (yy > 0) { n_int n = (yy-1)*img->x + xx; graph_local_set_color(buffer, color, n); } if (xx > 0) { n_int n = (yy*img->x + xx - 1); graph_local_set_color(buffer, color, n); } if ((yy+1) < img->y) { n_int n = ((yy+1)*img->x + xx ); graph_local_set_color(buffer, color, n); } if ((xx+1) < img->x) { n_int n = (yy*img->x + xx + 1); graph_local_set_color(buffer, color, n); } } } } } } /** * @brief Draws a curve using three points * @param buffer Image buffer (three bytes per pixel) * @param img Vector size of the image * @param pt0 the start point * @param pt1 the middle point * @param pt2 the end point * @param color color * @param radius_percent Radius of the curve as a percentage * @param start_thickness Thickness of the curve at the start point * @param end_thickness Thickness of the curve at the end point */ void graph_curve(n_byte * buffer, n_vect2 * img, n_vect2 * pt0, n_vect2 * pt1, n_vect2 * pt2, n_rgba32 * color, n_byte radius_percent, n_uint start_thickness, n_uint end_thickness) { n_int pts[8]; n_vect2 current; n_vect2 previous = {0, 0}; n_uint i; const n_uint divisions = 20; n_double c[5],d[5],f; /** turn three points into four using the curve radius */ pts[0] = pt0->x; pts[1] = pt0->y; pts[2] = pt1->x + ((pt0->x - pt1->x)*radius_percent/100); pts[3] = pt1->y + ((pt0->y - pt1->y)*radius_percent/100); pts[4] = pt1->x + ((pt2->x - pt1->x)*radius_percent/100); pts[5] = pt1->y + ((pt2->y - pt1->y)*radius_percent/100); pts[6] = pt2->x; pts[7] = pt2->y; c[0] = (-pts[0*2] + 3 * pts[1*2] - 3 * pts[2*2] + pts[3*2]) / 6.0; c[1] = (3 * pts[0*2] - 6 * pts[1*2] + 3 * pts[2*2]) / 6.0; c[2] = (-3 * pts[0*2] + 3 * pts[2*2]) / 6.0; c[3] = (pts[0*2] + 4 * pts[1*2] + pts[2*2]) / 6.0; d[0] = (-pts[(0*2)+1] + 3 * pts[(1*2)+1] - 3 * pts[(2*2)+1] + pts[(3*2)+1]) / 6.0; d[1] = (3 * pts[(0*2)+1] - 6 * pts[(1*2)+1] + 3 * pts[(2*2)+1]) / 6.0; d[2] = (-3 * pts[(0*2)+1] + 3 * pts[(2*2)+1]) / 6.0; d[3] = (pts[(0*2)+1] + 4 * pts[(1*2)+1] + pts[(2*2)+1]) / 6.0; for (i = 0; i < divisions; i++) { f = (n_double)i / (n_double)divisions; current.x = (n_int)((c[2] + f * (c[1] + f * c[0])) * f + c[3]); current.y = (n_int)((d[2] + f * (d[1] + f * d[0])) * f + d[3]); if (i > 0) { graph_line(buffer, img, &previous, &current, color, (n_byte)(start_thickness + ((end_thickness - start_thickness) * i / divisions))); } vect2_copy(&previous, &current); } } #define MAX_POLYGON_CORNERS 1000 /** * @brief Draw a filled polygon * @param points Array containing 2D points * @param no_of_points The number of 2D points * @param color color of polygon * @param transparency Degree of transparency * @param buffer Image buffer (3 bytes per pixel) * @param img image vector size */ void graph_fill_polygon(n_vect2 * points, n_int no_of_points, n_rgba32 * color, n_byte transparency, n_byte * buffer, n_vect2 * img) { n_int nodes, nodeX[MAX_POLYGON_CORNERS], i, j, swap, n, x, y; n_int min_x = 99999, min_y = 99999; n_int max_x = -99999, max_y = -99999; for (i = 0; i < no_of_points; i++) { x = points[i].x; y = points[i].y; if ((x==9999) || (y==9999)) continue; if (x < min_x) min_x = x; if (y < min_y) min_y = y; if (x > max_x) max_x = x; if (y > max_y) max_y = y; } if (min_x < 0) min_x = 0; if (min_y < 0) min_y = 0; if (max_x >= img->x) max_x = img->x - 1; if (max_y >= img->y) max_y = img->y - 1; for (y = min_y; y <= max_y; y++) { /** Build a list of nodes */ nodes = 0; j = no_of_points-1; for (i = 0; i < no_of_points; i++) { if (((points[i].y < y) && (points[j].y >= y)) || ((points[j].y < y) && (points[i].y >= y))) { nodeX[nodes++] = points[i].x + (y - points[i].y) * (points[j].x - points[i].x) / (points[j].y - points[i].y); } j = i; if (nodes == MAX_POLYGON_CORNERS) break; } /** Sort the nodes, via a simple “Bubble” sort */ i = 0; while (i < nodes-1) { if (nodeX[i] > nodeX[i+1]) { swap = nodeX[i]; nodeX[i] = nodeX[i+1]; nodeX[i+1] = swap; if (i) i--; } else { i++; } } /** Fill the pixels between node pairs */ for (i = 0; i < nodes; i += 2) { if (nodeX[i] >= max_x) break; if (nodeX[i+1] > min_x) { /** range check */ if (nodeX[i] <= min_x) nodeX[i] = min_x+1; if (nodeX[i+1] >= max_x) nodeX[i+1] = max_x-1; for (x = nodeX[i]; x < nodeX[i+1]; x++) { n = ((y*img->x)+x); if (transparency == 0) { graph_local_set_color(buffer, color, n); } else { graph_local_set_color_transparency(buffer, color, n, transparency); } } } } } } <|start_filename|>gui/shared.c<|end_filename|> /**************************************************************** shared.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /* This is intended to dramatically simplify the interface between the various platform versions of Simulated Ape */ #include <stdio.h> #include "gui.h" #ifndef _WIN32 #include "../toolkit/shared.h" #else #include "..\toolkit\shared.h" #endif static n_int simulation_started = 0; static n_int mouse_x, mouse_y; static n_byte mouse_option, mouse_identification; static n_byte mouse_down; static n_byte mouse_drag; static n_int mouse_drag_x , mouse_drag_y; static n_byte key_identification; static n_byte2 key_value; static n_byte key_down; #define Y_DELTA 36 #define X_DELTA 20 static n_int toggle_pause = 0; static n_int control_toggle_pause(n_byte actual_toggle) { if (io_command_line_execution()) { command_stop(0L,"",io_console_out); } if (actual_toggle) { toggle_pause ^= 1; } else { toggle_pause = 1; } return toggle_pause; } /* do mouse down interaction over a window, at a point, with keys possibly pressed */ extern n_byte check_about; extern n_uint tilt_z; #ifdef MULTITOUCH_CONTROLS touch_control_state tc_state = TCS_SHOW_NOTHING; touch_control_state tc_temp_state = TCS_SHOW_NOTHING; n_int tc_countdown = 0; #endif static n_int control_mouse_was_down = 0; static void control_mouse(n_byte wwind, n_int px, n_int py, n_byte option) { if (wwind == NUM_CONTROL) { if (!mouse_down && control_mouse_was_down) { sim_control_regular(px, py, draw_control_font_scaling()); } control_mouse_was_down = mouse_down; } if (wwind == NUM_VIEW) { if (option) { sim_view_options(px, py); } else { if (sim_view_regular(px, py)) { if (mouse_drag == 0) { mouse_drag_x = px; mouse_drag_y = py; mouse_drag = 1; } } } } if (wwind == NUM_TERRAIN) { n_int upper_x, upper_y; check_about = 0; #ifdef MULTITOUCH_CONTROLS if ((tc_state & 1) == 0) { tc_temp_state = tc_state + 1; tc_countdown = 60; } #endif draw_terrain_coord(&upper_x, &upper_y); if (option != 0) { if ((px > (upper_x/4)) && (px < ((upper_x * 3)/4))) { if (py < (upper_y/4)) { tilt_z = ((tilt_z + 1) & 255); } else if (py < ((upper_y * 3)/4)) { tilt_z = ((tilt_z + 255) & 255); } } } else { n_int sx = px - ((upper_x)>>1); #ifdef MULTITOUCH_CONTROLS if (px < TC_FRACTION_X) { if (tc_state == TCS_LEFT_STATE_CONTROLS) { tc_temp_state = TCS_SHOW_CONTROLS; tc_countdown = 60; } else { tc_temp_state = TCS_RIGHT_STATE_CONTROLS; tc_countdown = 60; } return; } if (px > (upper_x - TC_FRACTION_X)) { if (tc_state == TCS_RIGHT_STATE_CONTROLS) { tc_temp_state = TCS_SHOW_CONTROLS; tc_countdown = 60; } else { tc_temp_state = TCS_LEFT_STATE_CONTROLS; tc_countdown = 60; } return; } #endif sim_terrain(sx); } } } /* do key down in which window */ static void control_key(n_byte wwind, n_byte2 num) { if ((num > 27) && (num < 32)) /* 28, 29, 30, 31 */ { if (wwind != NUM_VIEW) { if ((num - 28) < 2) sim_rotate(0-(1 - ((num - 28) << 1))); else sim_move((160-((num - 28) << 6)), 1); } else { sim_move((31-num), 0); } } if ((num > 2075) && (num < 2078)) { sim_rotate(0 - ( -1 + ((2077-num) << 1))); } if ((num > 2077) && (num < 2080)) { sim_change_selected(num == 2078); } } #ifdef SCRIPT_DEBUG static n_int script_entry = 1; static n_int shared_script_debug_ready(void) { if (script_entry == 0) { return 0; } if (scdebug_file_ready() != 0L) { script_entry = 0; return 1; } return 0; } void shared_script_debug_handle(n_constant_string cStringFileName) { if (cStringFileName) { n_file * outputfile = scdebug_file_ready(); io_disk_write(outputfile, cStringFileName); } scdebug_file_cleanup(); script_entry = 1; } #else void shared_script_debug_handle(n_string cStringFileName) { } #endif static void * control_init(KIND_OF_USE kind, n_uint randomise) { void * sim_return = 0L; shared_menu(NA_MENU_CLEAR_ERRORS); draw_undraw_clear(); sim_return = sim_init(kind, randomise, OFFSCREENSIZE, VIEWWINDOW(0)); sim_set_output(1); if (sim_return) { return draw_offscreen(sim_return); } return 0; } void shared_dimensions(n_int* dimensions) { dimensions[0] = 2; dimensions[1] = 512; dimensions[2] = 512; dimensions[3] = 1; } shared_cycle_state shared_cycle(n_uint ticks, n_int localIdentification) { shared_cycle_state return_value = SHARED_CYCLE_OK; if (simulation_started == 0) { return return_value; } ticks = ticks & 67108863; /* 71 58 27 88 */ ticks *= 60; #ifndef _WIN32 sim_thread_console(); #endif if (mouse_identification == localIdentification) { if (localIdentification == NUM_CONTROL) { control_mouse(mouse_identification, mouse_x, mouse_y, mouse_option); } else if (mouse_down == 1) { if (localIdentification == NUM_VIEW) { #if (MAP_BITS == 8) control_mouse(mouse_identification, mouse_x/2, mouse_y/2, mouse_option); #else control_mouse(mouse_identification, mouse_x, mouse_y, mouse_option); #endif } else { control_mouse(mouse_identification, mouse_x, mouse_y, mouse_option); } } } #ifdef MULTITOUCH_CONTROLS if ((mouse_down == 0) && (mouse_identification == fIdentification)) { if (tc_temp_state != tc_state) { tc_state = tc_temp_state; } } #endif if((key_down == 1) && (key_identification == localIdentification)) { if ((key_identification == NUM_VIEW) || (key_identification == NUM_TERRAIN)) { control_key(key_identification, key_value); } } if (localIdentification == WINDOW_PROCESSING) { sim_realtime(ticks); #ifdef MULTITOUCH_CONTROLS if (tc_countdown) { tc_countdown--; if (tc_countdown == 0) { if ((tc_state & 1) == 1) { tc_temp_state = tc_state - 1; } } } #endif if ((io_command_line_execution() != 1) && (!toggle_pause)) { sim_cycle(); sim_update_output(); } #ifndef _WIN32 if (sim_new_run_condition()) { return_value = SHARED_CYCLE_NEW_APES; } #endif #ifdef SCRIPT_DEBUG if (shared_script_debug_ready()) { return_value = SHARED_CYCLE_DEBUG_OUTPUT; } #endif #ifndef _WIN32 if (sim_thread_console_quit()) { return_value = SHARED_CYCLE_QUIT; } #endif } return return_value; } n_int shared_init(n_int view, n_uint random) { key_down = 0; mouse_down = 0; mouse_drag = 0; if (view == WINDOW_PROCESSING) { if (control_init(KIND_START_UP, random) == 0L) { return SHOW_ERROR("Initialization failed lack of memory"); } } simulation_started = 1; return view; } void shared_close(void) { sim_close(); } void shared_keyReceived(n_int value, n_int fIdentification) { key_down = 1; key_value = value; key_identification = fIdentification; } void shared_keyUp(void) { key_down = 0; } void shared_mouseOption(n_byte option) { mouse_option = option; } void shared_mouseReceived(n_double valX, n_double valY, n_int fIdentification) { mouse_down = 1; mouse_identification = fIdentification; if (fIdentification == NUM_VIEW) { n_vect2 * being_location = draw_selected_location(); mouse_x = (n_int)(valX + 256 + being_location->x) & 511; mouse_y = (n_int)(valY + 256 + being_location->y) & 511; } else { mouse_x = (n_int)valX; mouse_y = (n_int)valY; } } void shared_mouseUp(void) { mouse_down = 0; mouse_drag = 0; } void shared_about(void) { draw_about(); } static void shared_clearErrors(void) { (void)draw_error(0L, 0L, 0); } static n_int shared_new_type(KIND_OF_USE type, n_uint seed) { static n_int NewBlock = 0; if (NewBlock) { return 0; } NewBlock = 1; (void)control_init(type, seed); NewBlock = 0; return 0; } n_int shared_new(n_uint seed) { return shared_new_type(KIND_NEW_SIMULATION, seed); } n_int shared_new_agents(n_uint seed) { return shared_new_type(KIND_NEW_APES, seed); } n_byte shared_openFileName(n_constant_string cStringFileName, n_int isScript) { (void)control_toggle_pause(0); if (isScript) { return (command_script(0L, cStringFileName, 0L) == 0); } return (command_open(0L, cStringFileName, 0L) == 0); } void shared_saveFileName(n_constant_string cStringFileName) { (void)control_toggle_pause(0); (void)command_save(0L, cStringFileName, 0L); } void shared_delta(n_double delta_x, n_double delta_y, n_int wwind) { } void shared_zoom(n_double num, n_int wwind) { } void shared_rotate(n_double num, n_int wwind) { if (wwind == NUM_TERRAIN) { n_int integer_rotation_256 = (n_int)((num * 256) / 360); sim_rotate(integer_rotation_256); } } n_uint shared_max_fps(void) { return 60; } n_int shared_menu(n_int menuVal) { switch (menuVal) { case NA_MENU_PAUSE: return control_toggle_pause(1); case NA_MENU_WEATHER: return draw_toggle_weather(); case NA_MENU_BRAIN: return draw_toggle_brain(); case NA_MENU_BRAINCODE: return draw_toggle_braincode(); case NA_MENU_TERRITORY: return draw_toggle_territory(); case NA_MENU_TIDEDAYLIGHT: return draw_toggle_tide_daylight(); case NA_MENU_PREVIOUS_APE: (void)control_key(0, 2079); return 0; case NA_MENU_NEXT_APE: (void)control_key(0, 2078); return 0; case NA_MENU_CLEAR_ERRORS: (void)draw_error(0L, 0L, 0); return 0; case NA_MENU_FLOOD: sim_flood(); return 0; case NA_MENU_HEALTHY_CARRIER: sim_healthy_carrier(); return 0; case NA_MENU_FOLLOW: return draw_toggle_follow(); case NA_MENU_SOCIAL_WEB: return draw_toggle_social_web(); } return -1; } n_byte * shared_legacy_draw(n_byte fIdentification, n_int dim_x, n_int dim_y) { if (fIdentification == NUM_TERRAIN) { draw_window(dim_x, dim_y); } draw_cycle(0, DRAW_WINDOW_VIEW | DRAW_WINDOW_CONTROL | DRAW_WINDOW_TERRAIN); return draw_pointer(fIdentification); } void shared_color_8_bit_to_48_bit(n_byte2 * fit) { land_color_time(fit, 1); } static n_byte4 colorLookUp[256][256]; static n_uint old_hash = 0; static void shared_color_update(void) { n_int loop = 0; n_int loopColors = 0; n_byte fit[256*3]; n_int cloud = 1; n_uint new_hash; land_color_time_8bit(fit, draw_toggle_tide_daylight_value()); new_hash = math_hash(fit, 256 * 3); if (new_hash != old_hash) { old_hash = new_hash; while(loopColors < 256) { n_byte *juxtapose = (n_byte*)&colorLookUp[0][loopColors]; n_byte red = fit[loop++]; n_byte green = fit[loop++]; n_byte blue = fit[loop++]; n_byte alpha = 0; #ifdef METAL_RENDER #ifdef APESIM_IOS juxtapose[0] = alpha; juxtapose[1] = red; juxtapose[2] = green; juxtapose[3] = blue; #else juxtapose[0] = blue; juxtapose[1] = green; juxtapose[2] = red; juxtapose[3] = alpha; #endif #else juxtapose[0] = alpha; juxtapose[1] = red; juxtapose[2] = green; juxtapose[3] = blue; #endif loopColors++; } while (cloud < 256) { n_int negCloud = 256 - cloud; loopColors = 0; while (loopColors < 256) { n_byte *juxtapose = (n_byte*)&colorLookUp[cloud][loopColors]; n_byte *juxtapose0 = (n_byte*)&colorLookUp[0][loopColors]; juxtapose[0] = (n_byte)(cloud + ((negCloud*juxtapose0[0])>>8)); juxtapose[1] = (n_byte)(cloud + ((negCloud*juxtapose0[1])>>8)); juxtapose[2] = (n_byte)(cloud + ((negCloud*juxtapose0[2])>>8)); juxtapose[3] = (n_byte)(cloud + ((negCloud*juxtapose0[3])>>8)); loopColors++; } cloud++; } } } static void shared_bitcopy_view(n_byte * outputBuffer, n_int dim_x, n_int dim_y, n_int offset_x, n_int offset_y, n_int multi_x) { n_byte * index = draw_pointer(NUM_VIEW); n_byte * local_weather = draw_weather_grayscale(); n_vect2 * being_location = draw_selected_location(); n_byte4 * outputBuffer4 = (n_byte4 *)outputBuffer; n_int loop = 0; n_int ly = 0; if (index == 0L) { return; } while (ly < dim_y) { n_int lx = 0; #ifdef APESIM_IOS n_int point_y = ((dim_y - ly - 1) + (dim_y + 256 + being_location->y)) % dim_y; #else n_int point_y = (ly + (dim_y + 256 + being_location->y)) % dim_y; #endif n_int offset = point_y * dim_x; n_byte * indexLocalX = &index[offset]; n_byte * weatherLocalX = &local_weather[offset]; loop = (ly+offset_y) * multi_x; while (lx < dim_x) { n_int point_x = ((lx + (dim_x + 256 + being_location->x)) % dim_x) + offset_x; n_byte cloud = weatherLocalX[point_x]; n_byte value = indexLocalX[point_x]; outputBuffer4[loop++] = colorLookUp[cloud][value]; lx++; } ly++; } } static void shared_bitcopy_view_ios(n_byte * outputBuffer, n_int dimension, n_int offset_x, n_int offset_y, n_int multi_x) { n_byte * index = draw_pointer(NUM_VIEW); n_byte * local_weather = draw_weather_grayscale(); n_vect2 * being_location = draw_selected_location(); n_byte4 * outputBuffer4 = (n_byte4 *)outputBuffer; n_int map_dim_x = MAP_DIMENSION; n_int map_dim_y = MAP_DIMENSION; n_int point_start = (MAP_DIMENSION - dimension) / 2; n_int loop = 0; n_int screen_y = 0; if (dimension > MAP_DIMENSION) { point_start = 0; dimension = MAP_DIMENSION; } if (index == 0L) { return; } while (screen_y < dimension) { n_int ly = point_start + screen_y; n_int screen_x = 0; #ifdef APESIM_IOS n_int point_y = ((map_dim_y - ly - 1) + (map_dim_y + 256 + being_location->y)) % map_dim_y; #else n_int point_y = (ly + (map_dim_y + 256 + being_location->y)) % map_dim_y; #endif n_int offset = point_y * map_dim_x; n_byte * indexLocalX = &index[offset]; n_byte * weatherLocalX = &local_weather[offset]; loop = (ly+offset_y) * multi_x; while (screen_x < dimension) { n_int lx = point_start + screen_x; n_int point_x = ((lx + (map_dim_x + 256 + being_location->x)) % map_dim_x) + offset_x; n_byte cloud = weatherLocalX[point_x]; n_byte value = indexLocalX[point_x]; outputBuffer4[loop++] = colorLookUp[cloud][value]; screen_x++; } screen_y++; } } static void shared_bitcopy(n_byte * outputBuffer, n_int dim_x, n_int dim_y, n_int offset_x, n_int offset_y, n_int multi_x, n_int fIdentification) { n_byte * index = draw_pointer(fIdentification); n_byte4 * outputBuffer4 = (n_byte4 *)outputBuffer; n_int loop = 0; n_int ly = 0; if (index == 0L) { return; } while (ly < dim_y) { n_int lx = 0; #ifdef APESIM_IOS n_byte * indexLocalX = &index[(dim_y-ly-1)*dim_x]; #else n_byte * indexLocalX = &index[ly*dim_x]; #endif loop = ((ly+offset_y) * multi_x) + offset_x; while (lx < dim_x) { n_byte value = indexLocalX[ lx++ ]; outputBuffer4[ loop++ ] = colorLookUp[ 0 ][ value ]; } ly++; } } void shared_draw(n_byte * outputBuffer, n_int fIdentification, n_int dim_x, n_int dim_y, n_byte size_changed) { if (simulation_started == 0) { SHOW_ERROR("draw - simulation not started"); return; } { #ifdef _WIN32 { n_byte* index = draw_pointer(fIdentification); memory_copy(index, outputBuffer, dim_x * dim_y); } #else draw_window(dim_x, dim_y); draw_cycle(size_changed, (n_byte)(1 << fIdentification)); shared_color_update(); #ifdef ALPHA_WEATHER_DRAW if (fIdentification == NUM_VIEW) { shared_bitcopy_view(outputBuffer, dim_x, dim_y, 0, 0, dim_x); } else #endif { shared_bitcopy(outputBuffer, dim_x, dim_y, 0, 0, dim_x, fIdentification); } #endif } } #ifdef APESIM_IOS #undef IOS_PROCESSOR_SAVER #ifdef IOS_PROCESSOR_SAVER static n_int ios_time_cycle = 0; #endif shared_cycle_state shared_cycle_ios(n_uint ticks) { shared_cycle_state return_value = SHARED_CYCLE_OK; if (simulation_started == 0) { return return_value; } ticks = ticks & 67108863; /* 71 58 27 88 */ ticks *= 60; #ifndef _WIN32 sim_thread_console(); #endif sim_realtime(ticks); #ifdef IOS_PROCESSOR_SAVER ios_time_cycle++; if ((ios_time_cycle &3) == 1) #endif { if ((io_command_line_execution() != 1) && (!toggle_pause)) { sim_cycle(); sim_update_output(); } } if (sim_new_run_condition()) { return_value = SHARED_CYCLE_NEW_APES; } #ifdef SCRIPT_DEBUG if (shared_script_debug_ready()) { return_value = SHARED_CYCLE_DEBUG_OUTPUT; } #endif #ifndef _WIN32 if (sim_thread_console_quit()) { return_value = SHARED_CYCLE_QUIT; } #endif return return_value; } static n_int rotation_vertical = -1; void shared_draw_ios(n_byte4 * outputBuffer, n_int dim_x, n_int dim_y) { n_int new_rotation_vertical = (dim_x < dim_y); if (simulation_started == 0) { SHOW_ERROR("draw - simulation not started"); return; } #ifdef IOS_PROCESSOR_SAVER if (((ios_time_cycle &3) != 3) && (rotation_vertical == new_rotation_vertical)) { return; } #endif if (rotation_vertical != new_rotation_vertical) { memory_erase((n_byte*)outputBuffer, dim_x * dim_y * 4); } rotation_vertical = new_rotation_vertical; if (dim_x < dim_y) { /* portrait */ draw_window(dim_x, dim_y - dim_x); draw_cycle(0, DRAW_WINDOW_TERRAIN | DRAW_WINDOW_VIEW); shared_color_update(); shared_bitcopy((n_byte*)outputBuffer, dim_x, dim_y - dim_x, 0, 0, dim_x, NUM_TERRAIN); shared_bitcopy_view_ios((n_byte*)outputBuffer, dim_x, 0, dim_y - dim_x, dim_x); } else { /* landscape */ n_int point_start = (MAP_DIMENSION - dim_y) / 2; if (point_start < 0) { point_start = 0; } draw_window(dim_x - dim_y, dim_y); draw_cycle(0, DRAW_WINDOW_CONTROL | DRAW_WINDOW_VIEW); shared_color_update(); shared_bitcopy((n_byte*)outputBuffer, dim_x - dim_y, dim_y, dim_y, 0, dim_x, NUM_CONTROL); shared_bitcopy_view_ios((n_byte*)outputBuffer, dim_y, 0, 0 - point_start, dim_x); } } #endif <|start_filename|>gui/draw.c<|end_filename|> /**************************************************************** draw.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #ifndef _WIN32 #include "../toolkit/toolkit.h" #include "../toolkit/shared.h" #include "../script/script.h" #include "../sim/sim.h" #else #include "..\toolkit\toolkit.h" #include "..\toolkit\shared.h" #include "..\script\script.h" #include "..\sim\sim.h" #endif #include "gui.h" #include <stdio.h> /* the weather/time of day icons hard coded */ static const n_byte icns[896] = { /* sunny day */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x0A, 0x80, 0x00, 0x01, 0x0A, 0x84, 0x00, 0x04, 0x8A, 0x89, 0x00, 0x02, 0x4A, 0x92, 0x00, 0x09, 0x2A, 0xA4, 0x80, 0x04, 0x9F, 0xC9, 0x00, 0x02, 0x70, 0x72, 0x00, 0x01, 0x60, 0x34, 0x00, 0x00, 0xC0, 0x18, 0x00, 0x1F, 0x80, 0x0F, 0xC0, 0x00, 0x80, 0x08, 0x00, 0x3F, 0x80, 0x0F, 0xE0, 0x00, 0x80, 0x08, 0x00, 0x1F, 0x80, 0x0F, 0xC0, 0x00, 0xC0, 0x18, 0x00, 0x01, 0x60, 0x34, 0x00, 0x02, 0x70, 0x72, 0x00, 0x04, 0x9F, 0xC9, 0x00, 0x09, 0x2A, 0xA4, 0x80, 0x02, 0x4A, 0x92, 0x00, 0x04, 0x8A, 0x89, 0x00, 0x01, 0x0A, 0x84, 0x00, 0x00, 0x0A, 0x80, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* cloudy day */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x0A, 0x80, 0x00, 0x01, 0x0A, 0x84, 0x00, 0x04, 0x8A, 0x89, 0x00, 0x02, 0x4A, 0x92, 0x00, 0x09, 0x2A, 0xA4, 0x80, 0x04, 0x9F, 0xC9, 0x00, 0x02, 0x70, 0x72, 0x00, 0x01, 0x60, 0x34, 0x00, 0x00, 0xC0, 0x18, 0x00, 0x1F, 0x80, 0x0F, 0xC0, 0x00, 0xB8, 0x08, 0x00, 0x01, 0xC7, 0x1C, 0x00, 0x0E, 0x00, 0xE3, 0x00, 0x10, 0x00, 0x00, 0x80, 0x20, 0x00, 0x00, 0x40, 0x20, 0x00, 0x00, 0x40, 0x20, 0x00, 0x00, 0x40, 0x10, 0x00, 0x00, 0x80, 0x10, 0x00, 0x00, 0x80, 0x10, 0x00, 0x00, 0x80, 0x08, 0x00, 0x00, 0x40, 0x08, 0x00, 0x00, 0x40, 0x08, 0x01, 0xC0, 0x40, 0x07, 0x8E, 0x38, 0x80, 0x00, 0x70, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* rainy day */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x38, 0xE3, 0x80, 0x01, 0xC0, 0x1C, 0x60, 0x02, 0x00, 0x00, 0x10, 0x04, 0x00, 0x00, 0x08, 0x04, 0x00, 0x00, 0x08, 0x04, 0x00, 0x00, 0x08, 0x02, 0x00, 0x00, 0x10, 0x02, 0x00, 0x00, 0x10, 0x02, 0x00, 0x00, 0x10, 0x01, 0x00, 0x00, 0x08, 0x01, 0x00, 0x00, 0x08, 0x01, 0x00, 0x38, 0x08, 0x00, 0xF1, 0xD7, 0x10, 0x00, 0xAE, 0xAA, 0xE0, 0x01, 0x55, 0x55, 0x40, 0x02, 0xAA, 0xAA, 0x80, 0x05, 0x55, 0x55, 0x00, 0x0A, 0xAA, 0xAA, 0x00, 0x05, 0x55, 0x54, 0x00, 0x0A, 0xAA, 0xA8, 0x00, 0x05, 0x55, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* clear night */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF1, 0xFF, 0xFF, 0xFF, 0xE6, 0xFF, 0xFF, 0xFF, 0xE7, 0xFF, 0xFF, 0xFF, 0xE6, 0xFF, 0xFF, 0xFF, 0xF1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xEF, 0xFF, 0xFF, 0xFF, 0xFF, 0xDF, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF7, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, /* cloudy night */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFD, 0x7F, 0xFF, 0xF1, 0xEA, 0xAE, 0xBF, 0xE7, 0x55, 0x55, 0x5F, 0xE6, 0xAA, 0xAA, 0xAF, 0xE7, 0x55, 0x55, 0x57, 0xF2, 0xAA, 0xAA, 0xAF, 0xFF, 0x55, 0x55, 0x5F, 0xFF, 0xAA, 0xAA, 0xAF, 0xFF, 0x55, 0x55, 0x5F, 0xFB, 0xAA, 0xAA, 0xAF, 0xF5, 0xD5, 0x55, 0x57, 0xEA, 0xAA, 0xAA, 0xAF, 0xD5, 0xFD, 0xF7, 0xDF, 0xEB, 0xEF, 0xBE, 0xFF, 0xFF, 0x55, 0x57, 0x57, 0xFA, 0xAA, 0xAA, 0xAF, 0xF5, 0x55, 0x55, 0x57, 0xEA, 0xAA, 0xAA, 0xEB, 0xF5, 0x55, 0x55, 0x57, 0xFA, 0xAA, 0xAA, 0xAF, 0xF5, 0x55, 0x55, 0xDF, 0xFA, 0xAA, 0xAA, 0xFF, 0xFD, 0x55, 0x55, 0x7F, 0xFA, 0xAA, 0xAA, 0xFF, 0xFD, 0x55, 0xD5, 0x7F, 0xFF, 0xAF, 0xFA, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, /* rainy night */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xBF, 0xFF, 0xFF, 0xFF, 0xFF, 0xBF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF8, 0xFF, 0xFF, 0xFF, 0xE2, 0x3E, 0x7F, 0xFE, 0x00, 0x00, 0x1F, 0xFC, 0x88, 0x88, 0x8F, 0xDC, 0x00, 0x00, 0x0F, 0xFE, 0x22, 0x22, 0x2F, 0xFE, 0x00, 0x00, 0x1F, 0xFE, 0x88, 0x88, 0x9F, 0xFE, 0x00, 0x00, 0x1F, 0xFB, 0x22, 0x22, 0x2F, 0xFF, 0x00, 0x00, 0x0F, 0xFF, 0x88, 0xB8, 0x8F, 0xFF, 0xF1, 0xD7, 0x1F, 0xFF, 0xAE, 0xAA, 0xFF, 0xFF, 0x55, 0x55, 0x7F, 0xFE, 0xAA, 0xAA, 0xFF, 0xFD, 0x55, 0x55, 0xFF, 0xFA, 0xAA, 0xAB, 0xFF, 0xFD, 0x55, 0x57, 0xFF, 0xFA, 0xAA, 0xBF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, /* sunrise/sunset */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xD5, 0xFB, 0xFF, 0xFF, 0xAA, 0xBF, 0xFF, 0x77, 0x55, 0x55, 0xF5, 0xAB, 0xA0, 0xAA, 0xAA, 0x55, 0x40, 0x01, 0x55, 0xAA, 0x80, 0x00, 0x2A, 0x54, 0x00, 0x00, 0x55, 0xA0, 0x00, 0x00, 0x2A, 0x40, 0x00, 0x00, 0x55, 0xA0, 0x00, 0x00, 0x2A, 0x00, 0x00, 0x00, 0x05, 0x00, 0x02, 0x00, 0x0A, 0x00, 0x0A, 0x80, 0x05, 0x01, 0x0A, 0x84, 0x02, 0x04, 0x8A, 0x89, 0x05, 0x02, 0x4A, 0x92, 0x02, 0x09, 0x2A, 0xA4, 0x80, 0x04, 0x9F, 0xC9, 0x00, 0x02, 0x70, 0x72, 0x00, 0x01, 0x60, 0x34, 0x00, 0x00, 0xC0, 0x18, 0x00, 0x1F, 0x80, 0x0F, 0xC0, 0x00, 0x80, 0x08, 0x00, 0xFF, 0xFF, 0xFF, 0xFF }; #define MAX_NUMBER_ERRORS 35 static n_byte character_location; static n_byte number_errors; static n_string_block error_array[MAX_NUMBER_ERRORS + 1]; static n_byte weather_grayscale[MAP_AREA]; static n_int control_font_scaling; #ifdef BRAIN_ON static n_uint tilt_y = 0; #endif n_byte check_about = 0; n_uint tilt_z = 118; static n_int toggle_weather = 1; static n_int toggle_brain = 1; static n_int toggle_braincode = 0; static n_int toggle_territory = 0; static n_int toggle_tidedaylight = 0; static n_int toggle_follow = 1; static n_int toggle_social_web = 0; static n_int changing_size = 0; static n_vect2 selected_location; static n_byte * local_offscreen = 0L; void draw_point(n_int x, n_int y) { n_byte * draw = VIEWWINDOW(local_offscreen); draw[x + (y * 512)] = 255; } n_vect2 * draw_selected_location(void) { return &selected_location; } n_int draw_toggle_follow(void) { toggle_follow ^= 1; return toggle_follow; } n_int draw_toggle_social_web(void) { toggle_social_web ^= 1; return toggle_social_web; } n_int draw_toggle_weather(void) { toggle_weather ^= 1; return toggle_weather; } n_int draw_toggle_brain(void) { toggle_brain ^= 1; return toggle_brain; } n_int draw_toggle_braincode(void) { toggle_braincode ^= 1; return toggle_braincode; } n_int draw_toggle_territory(void) { toggle_territory ^= 1; return toggle_territory; } n_int draw_toggle_tide_daylight(void) { toggle_tidedaylight ^= 1; return toggle_tidedaylight; } n_int draw_toggle_tide_daylight_value(void) { return toggle_tidedaylight; } /* this needs to be grouped eventually, it is here as a test */ #define UNDRAW_MAX (100000+ (HI_RES_MAP_DIMENSION * HI_RES_MAP_DIMENSION / 16)) static n_byte * undraw_location[UNDRAW_MAX]; static n_byte undraw_color[UNDRAW_MAX]; static n_int undraw_count = 0; void draw_undraw_clear(void) { undraw_count = 0; } static void draw_undraw() { if (undraw_count == 0) return; undraw_count--; do { *undraw_location[undraw_count] = undraw_color[undraw_count]; undraw_count--; } while(undraw_count > -1); undraw_count = 0; } n_byte * draw_offscreen(n_byte * value) { local_offscreen = value; return local_offscreen; } static n_byte pixel_color8_hires(n_int px, n_int py, n_int dx, n_int dy, void * information) { n_color8 *local_col = information; n_byte *location = &local_col->screen[ (px<<1) | (py<<(HI_RES_MAP_BITS+1)) | 1 ]; undraw_location[undraw_count] = location; undraw_color[undraw_count] = location[0]; undraw_count++; if (undraw_count > UNDRAW_MAX) { (void)SHOW_ERROR("Erase count outside limit"); } location[0] = local_col->color; return 0; } static n_byte pixel_color8(n_int px, n_int py, n_int dx, n_int dy, void * information) { n_color8 *local_col = information; local_col->screen[ px | (py<<MAP_BITS) ] = local_col->color; return 0; } static n_int window_dim_x = 512; static n_int window_dim_y = 511; static n_byte pixel_map(n_int px, n_int py, n_int dx, n_int dy, void * information) { n_color8 local_color; local_color.color = COLOR_WHITE; local_color.screen = information; return pixel_color8(px, py, dx, dy, &local_color); } static n_byte pixel_map_hires(n_int px, n_int py, n_int dx, n_int dy, void * information) { n_color8 local_color; local_color.color = COLOR_WHITE; local_color.screen = information; return pixel_color8_hires(px, py, dx, dy, &local_color); } static n_byte pixel_map_checker(n_int px, n_int py, n_int dx, n_int dy, void * information) { if ((px + py) & 1) { return pixel_map(px, py, dx, dy, information); } return 0; } static n_byte pixel_white(n_int px, n_int py, n_int dx, n_int dy, void * information) { n_byte *byte_info = information; byte_info[ px + (py * window_dim_x) ] = COLOR_WHITE; return 0; } static n_int smart_character_toggle; static n_int bold_character_toggle; static n_byte pixel_control(n_int px, n_int py, n_int dx, n_int dy, void * information) { n_byte *byte_info = information; byte_info[ px + (py * window_dim_x) ] = smart_character_toggle ? COLOR_BLUE : COLOR_WHITE; if (bold_character_toggle) { byte_info[ px + 1 + ((py+1) * window_dim_x) ] = smart_character_toggle ? COLOR_BLUE : COLOR_WHITE; } return 0; } static n_byte pixel_white_checker(n_int px, n_int py, n_int dx, n_int dy, void * information) { if ((px + py) & 1) { n_byte *byte_info = information; byte_info[ px + (py * window_dim_x) ] = COLOR_WHITE; } return 0; } static n_byte pixel_black(n_int px, n_int py, n_int dx, n_int dy, void * information) { n_byte *byte_info = information; byte_info[ px + (py * window_dim_x) ] = COLOR_BLACK; return 0; } n_byte * draw_pointer(n_int which_one) { if (local_offscreen) { switch(which_one) { case NUM_TERRAIN: return TERRAINWINDOW(local_offscreen); break; case NUM_VIEW: return VIEWWINDOW(local_offscreen); break; case NUM_CONTROL: return CONTROLWINDOW(local_offscreen); break; } } return 0L; } #ifdef MULTITOUCH_CONTROLS extern touch_control_state tc_state; void draw_tc_controls(n_join * local_mono) { const n_int half_y = window_dim_y / 2; n_vect2 point1, point2, point3; if (tc_state == TCS_SHOW_CONTROLS) { vect2_populate(&point1, 5, half_y + TC_OFFSET_Y); vect2_populate(&point2, 5, half_y - TC_OFFSET_Y); vect2_populate(&point3, TC_FRACTION_X - 5, half_y); math_line_vect(&point1, &point2, local_mono); math_line_vect(&point2, &point3, local_mono); math_line_vect(&point3, &point1, local_mono); vect2_populate(&point1, window_dim_x - 5, half_y + TC_OFFSET_Y); vect2_populate(&point2, window_dim_x - 5, half_y - TC_OFFSET_Y); vect2_populate(&point3, window_dim_x - TC_FRACTION_X + 5, half_y); math_line_vect(&point1, &point2, local_mono); math_line_vect(&point2, &point3, local_mono); math_line_vect(&point3, &point1, local_mono); } if (tc_state == TCS_LEFT_STATE_CONTROLS) { vect2_populate(&point1, TC_FRACTION_X - 5, half_y + TC_OFFSET_Y); vect2_populate(&point2, TC_FRACTION_X - 5, half_y - TC_OFFSET_Y); vect2_populate(&point3, 5, half_y); math_line_vect(&point1, &point2, local_mono); math_line_vect(&point2, &point3, local_mono); math_line_vect(&point3, &point1, local_mono); } if (tc_state == TCS_RIGHT_STATE_CONTROLS) { vect2_populate(&point1, window_dim_x - TC_FRACTION_X + 5, half_y + TC_OFFSET_Y); vect2_populate(&point2, window_dim_x - TC_FRACTION_X + 5, half_y - TC_OFFSET_Y); vect2_populate(&point3, window_dim_x - 5, half_y); math_line_vect(&point1, &point2, local_mono); math_line_vect(&point2, &point3, local_mono); math_line_vect(&point3, &point1, local_mono); } } #endif void draw_about(void) { check_about = 1; } /* shows the about information */ static void draw_about_information(n_byte terrain) { n_join local_draw; n_byte *buffer = draw_pointer(terrain ? NUM_TERRAIN : NUM_CONTROL); n_int line_y_offset = 100; n_int linx_x_offset = CHARACTER_WIDTH * 3; n_int tab_offset = CHARACTER_WIDTH * 5; if (buffer == 0L) { check_about = 0; return; } local_draw.information = buffer; local_draw.pixel_draw = &pixel_black; draw_string(SHORT_VERSION_NAME, linx_x_offset, line_y_offset, &local_draw); line_y_offset += CHARACTER_HEIGHT; line_y_offset += CHARACTER_HEIGHT; draw_string(FULL_DATE, linx_x_offset, line_y_offset, &local_draw); line_y_offset += CHARACTER_HEIGHT; line_y_offset += CHARACTER_HEIGHT; draw_string(FULL_VERSION_COPYRIGHT, linx_x_offset + tab_offset, line_y_offset, &local_draw); line_y_offset += CHARACTER_HEIGHT; draw_string(COPYRIGHT_FOLLOW, linx_x_offset + tab_offset, line_y_offset, &local_draw); line_y_offset += CHARACTER_HEIGHT; line_y_offset += CHARACTER_HEIGHT; draw_string("This software is a continuing work of ", linx_x_offset, line_y_offset, &local_draw); line_y_offset += CHARACTER_HEIGHT; draw_string("<NAME> begun on 13 June 1996.", linx_x_offset, line_y_offset, &local_draw); line_y_offset += CHARACTER_HEIGHT; line_y_offset += CHARACTER_HEIGHT; draw_string("No apes or cats were harmed in the ", linx_x_offset, line_y_offset, &local_draw); line_y_offset += CHARACTER_HEIGHT; draw_string("writing of this software.", linx_x_offset, line_y_offset, &local_draw); line_y_offset = 100-1; linx_x_offset = (CHARACTER_WIDTH * 3)-1; local_draw.pixel_draw = &pixel_white; draw_string(SHORT_VERSION_NAME, linx_x_offset, line_y_offset, &local_draw); line_y_offset += CHARACTER_HEIGHT; line_y_offset += CHARACTER_HEIGHT; draw_string(FULL_DATE, linx_x_offset, line_y_offset, &local_draw); line_y_offset += CHARACTER_HEIGHT; line_y_offset += CHARACTER_HEIGHT; draw_string(FULL_VERSION_COPYRIGHT, linx_x_offset + tab_offset, line_y_offset, &local_draw); line_y_offset += CHARACTER_HEIGHT; draw_string(COPYRIGHT_FOLLOW, linx_x_offset + tab_offset, line_y_offset, &local_draw); line_y_offset += CHARACTER_HEIGHT; line_y_offset += CHARACTER_HEIGHT; draw_string("This software is a continuing work of ", linx_x_offset, line_y_offset, &local_draw); line_y_offset += CHARACTER_HEIGHT; draw_string("<NAME> begun on 13 June 1996.", linx_x_offset, line_y_offset, &local_draw); line_y_offset += CHARACTER_HEIGHT; line_y_offset += CHARACTER_HEIGHT; draw_string("No apes or cats were harmed in the ", linx_x_offset, line_y_offset, &local_draw); line_y_offset += CHARACTER_HEIGHT; draw_string("writing of this software.", linx_x_offset, line_y_offset, &local_draw); } /* draws a string starting at point (off_x,off_y) */ #define ledfir(x, y, dx, dy, c, scale) if(((val >> c)&1)) (*local_draw)((scale*(x + off_x + offset))/10,(scale*((y + off_y)))/10, (scale * dx)/ 10, (scale * dy) /10, local_info) static void draw_character(n_pixel * local_draw, n_int offset, void * local_info, n_int off_x, n_int off_y, n_int val, n_int scale) { ledfir(3, 8, 0, 0, 15, scale);//P ledfir(3, 2, 0, 0, 14, scale);//O ledfir(0, 0, 5, 0, 13, scale);//N ledfir(6, 0, 0, 4, 12, scale);//M ledfir(6, 4, 0, 3, 11, scale);//L ledfir(0, 8, 5, 0, 10, scale);//K ledfir(0, 4, 0, 4, 9, scale);//J ledfir(0, 0, 0, 3, 8, scale);//I ledfir(3, 4, 3, 0, 7, scale);//H ledfir(0, 4, 3, 0, 6, scale);//G ledfir(3, 4, 0, 4, 5, scale);//F ledfir(3, 5, 3, 3, 4, scale);//E ledfir(3, 5, -3, 3, 3, scale);//D ledfir(3, 3, 3, -3, 2, scale);//C ledfir(0, 0, 3, 3, 1, scale); //B ledfir(3, 0, 0, 4, 0, scale); //A } /** This is used to produce letter LED style letters through the generic draw function specified. @param str The string to be drawn. @param off_x The starting x location for the string to be drawn. @param off_y The starting y location for the string to be drawn. @param draw The generic draw function used to draw the character. */ static void draw_string_line(n_constant_string str, n_int off_x, n_int off_y, n_join * draw) { n_pixel * local_draw = draw->pixel_draw; void * local_info = draw->information; n_int char_loop = 0; while (str[char_loop] > 31) { n_int val = math_seg14(str[char_loop] - 32); n_int offset = char_loop << 3; /* draw the character as a 14-segment LCD/LED output */ draw_character(local_draw, offset, local_info, off_x, off_y, val, 10); char_loop ++; } } static void draw_smart_string_line(n_constant_string str, n_int off_x, n_int off_y, n_join * draw) { n_pixel * local_draw = draw->pixel_draw; void * local_info = draw->information; n_int char_loop = 0; n_int char_location = 0; while (str[char_loop] > 31) { n_byte character = (n_byte)str[char_loop]; n_int val = math_seg14(character - 32); n_int offset = char_location << 3; /* draw the character as a 14-segment LCD/LED output */ if (character == '<') { bold_character_toggle = 1; char_location++; } else if (character == '>') { bold_character_toggle = 0; } else if (character == '*') { smart_character_toggle ^= 1; if (smart_character_toggle == 0) { character_location++; } } else { if (smart_character_toggle) { sim_control_set(off_x + offset, off_y, character_location, character, control_font_scaling); } draw_character(local_draw, offset, local_info, off_x, off_y, val, control_font_scaling); char_location++; } char_loop ++; } } static n_byte draw_character_line(n_int px, n_int py, n_int dx, n_int dy, void * data) { return math_join(px, py, dx, dy, data); } void draw_string(n_constant_string str, n_int off_x, n_int off_y, n_join * draw) { n_join local_pixel; local_pixel.pixel_draw = &draw_character_line; local_pixel.information = draw; draw_string_line(str, off_x, off_y, &local_pixel); } static void draw_smart_string(n_constant_string str, n_int off_x, n_int off_y, n_join * draw) { n_join local_pixel; local_pixel.pixel_draw = &draw_character_line; local_pixel.information = draw; draw_smart_string_line(str, off_x, off_y, &local_pixel); } /* this is the ocelot landscape algorithm */ #define POS_HIRES(num) ((num+(HI_RES_MAP_DIMENSION*2))&(HI_RES_MAP_DIMENSION-1)) #define CONVERT_X(x, cx) (n_uint)((POS_HIRES((x)+cx)) ) #define CONVERT_Y(y, cy) (n_uint)((POS_HIRES((y)+cy)) << HI_RES_MAP_BITS) #define CONVERT_XY(x,y) (CONVERT_X(x) | CONVERT_Y(y)) typedef struct { n_int const_lowdiv2; n_int lowest_s; n_int lowest_c; n_vect2 co; n_vect2 dimensions; n_vect2 value_vector; n_byte *offscreen; } draw_terrain_scan_struct; static void draw_terrain_scan(void * void_dtss, void * xlocation, void * unused) { draw_terrain_scan_struct * dtss = (draw_terrain_scan_struct *)void_dtss; n_byte * buf_offscr = (n_byte *) dtss->offscreen; n_int scrx = ((n_int *)xlocation)[0]; /* take the very bottom pixel */ n_int dim_x = dtss->dimensions.x; n_int dim_y1 = dtss->dimensions.y - 1; n_int pixy = (scrx + (dim_x >> 1)) + (dim_y1 * dim_x ); n_int actual = dim_y1; /* start with a map point which is below/off the screen */ n_int scry = dtss->const_lowdiv2; /* rotated and add offset (which will be &ed off) */ n_int big_x = dtss->lowest_s + (scrx * dtss->value_vector.y); /* rotated and sub offset (subtracted further down) */ n_int big_y = dtss->lowest_c - (scrx * dtss->value_vector.x); n_byte2 * combined = (n_byte2 *)land_topography_highdef(); n_int co_x = dtss->co.x; n_int co_y = dtss->co.y; n_int valc2 = dtss->value_vector.y << 1; n_int vals2 = dtss->value_vector.x << 1; while(actual > -1) { const n_uint check_change = CONVERT_X((big_x >> 8), co_x) | CONVERT_Y((big_y >> 8), co_y); const n_byte2 value = combined[check_change]; const n_int z00 = value & 255; const n_byte col00 = value >> 8; n_int aval = (scry - z00); if (aval < -1) aval = -1; scry--; /* next map point from screen value */ big_x -= vals2; big_y -= valc2; while (actual > aval) { buf_offscr[pixy] = col00; pixy -= dim_x; actual--; } } memory_free(&xlocation); memory_free(&void_dtss); } static void draw_terrain(simulated_group * group, n_vect2 * dimensions) { n_byte * buf_offscr = draw_pointer(NUM_TERRAIN); if (buf_offscr == 0L) { return; } if (group->select == 0L) { memory_erase(buf_offscr, (n_uint)(dimensions->x * dimensions->y)); return; } { const n_int lowest_y = ((dimensions->y + 256) * dimensions->y)/256; simulated_being * loc_being = group->select; draw_terrain_scan_struct dtss; n_byte2 * local_combined = (n_byte2 *)land_topography_highdef(); /* start at the left-most row */ n_int scrx = (0 - (dimensions->x >> 1)); /* find the central map point */ n_int flatval; n_vect2 value_vector; vect2_direction(&value_vector, being_facing(loc_being) + 128, 105); vect2_copy(&(dtss.value_vector), &value_vector); dtss.lowest_s = ((value_vector.x * (((lowest_y)) - dimensions->y))); dtss.lowest_c = ((value_vector.y * (((lowest_y)) - dimensions->y))); being_high_res(loc_being, &dtss.co); flatval = local_combined[CONVERT_X((HI_RES_MAP_DIMENSION/2), dtss.co.x) | CONVERT_Y((HI_RES_MAP_DIMENSION/2), dtss.co.y)] & 255; if (flatval < WATER_MAP) /* if the central map point is underwater,*/ { flatval = WATER_MAP; /* put it on water level */ } dtss.const_lowdiv2 = (((lowest_y)) >> 1) + flatval; vect2_copy(&(dtss.dimensions), dimensions); dtss.offscreen = buf_offscr; /* repeat until the right-most row is reached */ while (scrx < (dimensions->x - (dimensions->x >> 1))) { n_int * screen_x_location = memory_new(sizeof(n_int)); draw_terrain_scan_struct * local_dtss = (draw_terrain_scan_struct *)memory_new(sizeof(draw_terrain_scan_struct)); memory_copy((n_byte *)&dtss, (n_byte *)local_dtss, sizeof(draw_terrain_scan_struct)); screen_x_location[0] = scrx; draw_terrain_scan(local_dtss, screen_x_location, 0L); scrx++; /* next column */ } } } #define mndivmin 15 #define mndivhr 180 #define mndivmonth 7 #define mndivyear 91 #define YELLOW_CHECKER_LINE(px, py, dx, dy) math_join(px, py, dx, dy, &local_kind_yellow_checker) #define YELLOW_LINE(px, py, dx, dy) math_join(px, py, dx, dy, &local_kind_yellow) #define BLACK_LINE(px, py, dx, dy) math_join(px, py, dx, dy, &local_kind_black) #define YELLOW_VECT_LINE(px, py, vector) math_join_vect2(px, py, vector, &local_kind_yellow) #define FACING_OFFSIDE (window_dim_x-101) #define SP_EN_OFFSIDE (window_dim_x-187) #define GENETICS_X (window_dim_x-178) #define GENETICS_Y (8) #define GENDER_X (window_dim_x-110) #define GENDER_Y (10) static void draw_meters(simulated_group * group) { n_pixel * local_draw_yellow = &pixel_white; n_pixel * local_draw_yellow_checker = &pixel_white_checker; n_pixel * local_draw_black = &pixel_black; n_byte * local_info = draw_pointer(NUM_TERRAIN); n_join local_kind_yellow; n_join local_kind_yellow_checker; n_join local_kind_black; const n_byte * local_icon; n_int ha1 = 6; n_int ha2 = 0; n_int hr = 0; if (local_info == 0L) { return; } local_kind_yellow.pixel_draw = local_draw_yellow; local_kind_yellow.information = local_info; local_kind_yellow_checker.pixel_draw = local_draw_yellow_checker; local_kind_yellow_checker.information = local_info; local_kind_black.pixel_draw = local_draw_black; local_kind_black.information = local_info; while (hr < 41) { if ((hr != 40) && (hr != 0)) { BLACK_LINE(6, 5+hr, 38, 0); } hr ++; } YELLOW_CHECKER_LINE(5, 5, 40, 0); YELLOW_CHECKER_LINE(5, 5, 0, 40); YELLOW_CHECKER_LINE(45, 5, 0, 40); YELLOW_CHECKER_LINE(5, 45, 40, 0); hr = 0; while (hr < 12) { n_vect2 hour_clock; vect2_direction(&hour_clock, ((hr << 8) / 12), 320); YELLOW_LINE((25 + (hour_clock.x / 5)), (25 + (hour_clock.y / 5)), (hour_clock.x / 17), (hour_clock.y / 17)); hr++; } if (group->select) { simulated_being * loc_being = group->select; hr = 0; while (hr < 41) { if ((hr != 40) && (hr != 0)) { BLACK_LINE(51 + 5 + FACING_OFFSIDE, 5+hr, 38, 0); BLACK_LINE(51 + 55 + SP_EN_OFFSIDE, 5+hr, 6, 0); BLACK_LINE(51 + 55 + 18 + SP_EN_OFFSIDE, 5+hr, 6, 0); } hr ++; } YELLOW_CHECKER_LINE(50 + 5 + FACING_OFFSIDE, 5, 0, 40); YELLOW_CHECKER_LINE(50 + 45+ FACING_OFFSIDE, 5, 0, 40); YELLOW_CHECKER_LINE(50 + 5 + FACING_OFFSIDE, 45, 40, 0); YELLOW_CHECKER_LINE(50 + 5 + FACING_OFFSIDE, 5, 40, 0); YELLOW_CHECKER_LINE(58 + 55 + SP_EN_OFFSIDE, 5, 0, 40); YELLOW_CHECKER_LINE(50 + 55 + SP_EN_OFFSIDE, 5, 0, 40); YELLOW_CHECKER_LINE(58 + 55 + 18 + SP_EN_OFFSIDE, 5, 0, 40); YELLOW_CHECKER_LINE(50 + 55 + 18 + SP_EN_OFFSIDE, 5, 0, 40); YELLOW_CHECKER_LINE(50 + 55 + SP_EN_OFFSIDE, 5, 9, 0); YELLOW_CHECKER_LINE(50 + 55 + SP_EN_OFFSIDE, 45, 9, 0); YELLOW_CHECKER_LINE(50 + 55 + 18 + SP_EN_OFFSIDE, 5, 9, 0); YELLOW_CHECKER_LINE(50 + 55 + 18 + SP_EN_OFFSIDE, 45, 9, 0); hr = 0; while (hr < 8) { n_vect2 facing_clock; vect2_direction(&facing_clock, (hr << 5), 320); YELLOW_LINE((25 + 50 + (facing_clock.x / 5))+ FACING_OFFSIDE, (25 + (facing_clock.y / 5)), (facing_clock.x / 17), (facing_clock.y / 17)); hr++; } YELLOW_LINE(50 + 55 + 18+ SP_EN_OFFSIDE-1, 25, 1, 0); YELLOW_LINE(58 + 55 + 18+ SP_EN_OFFSIDE, 25, 1, 0); YELLOW_LINE(50 + 55 + 18+ SP_EN_OFFSIDE-2, 15, 2, 0); YELLOW_LINE(58 + 55 + 18+ SP_EN_OFFSIDE, 15, 2, 0); YELLOW_LINE(50 + 55 + 18+ SP_EN_OFFSIDE-2, 35, 2, 0); YELLOW_LINE(58 + 55 + 18+ SP_EN_OFFSIDE, 35, 2, 0); { n_genetics *genetics = being_genetics(loc_being); /* draw genetics */ while (ha2 < CHROMOSOMES) { n_uint ha3 = 0; n_genetics genetic_block = genetics[ha2]; ha1 = 0; while (ha3 < (sizeof(n_genetics)*4)) { n_int four = ( genetic_block >> (ha3 * 2) ) & 3 ; if ( four != 0 ) { YELLOW_LINE((ha1)+GENETICS_X, GENETICS_Y + (ha2 * 10), 0, 7); } ha1++; if ( four == 3 ) { YELLOW_LINE((ha1)+GENETICS_X, GENETICS_Y + (ha2 * 10), 0, 7); } ha1 += 3; ha3++; } ha2++; } } /* draw sex */ YELLOW_LINE(GENDER_X+5, GENDER_Y+10, 5, 11); YELLOW_LINE(GENDER_X+10,GENDER_Y+21, 5, -11); YELLOW_LINE(GENDER_X+15,GENDER_Y+10, -10, 0); if (being_female(loc_being)) { YELLOW_LINE(GENDER_X+10, GENDER_Y+20, 0, 6); YELLOW_LINE(GENDER_X+8, GENDER_Y+23, 4, 0); } else { YELLOW_LINE(GENDER_X+15, GENDER_Y+10, 4, -4); YELLOW_LINE(GENDER_X+19, GENDER_Y+6, -2, 0); YELLOW_LINE(GENDER_X+19, GENDER_Y+6, 0, 2); } /* draw direction facing */ { n_vect2 direction_facing; vect2_direction(&direction_facing, being_facing(loc_being), 63 * 32); YELLOW_VECT_LINE(75+ FACING_OFFSIDE, 25, &direction_facing); } { n_int local_speed = being_speed(loc_being); n_int local_energy = being_energy(loc_being); n_int local_x = being_location_x(loc_being); n_int local_y = being_location_y(loc_being); if (local_speed != 0) { YELLOW_LINE(106 + SP_EN_OFFSIDE, (45-local_speed), 6, 0); } if (local_energy > 127) { YELLOW_LINE(106 + 18 + SP_EN_OFFSIDE, (45-(local_energy >> 7)), 6, 0); } local_icon = &icns[weather_seven_values(local_x, local_y) << 7]; } } else { /* still give weather even with no Simulated Apes */ local_icon = &icns[weather_seven_values(0, 0) << 7]; } { n_int date_multiplier = (land_date() << 6); n_int time_multiplier = (land_time() << 6); n_vect2 year_hand; n_vect2 month_hand; n_vect2 hour_hand; n_vect2 minute_hand; vect2_direction(&year_hand, (date_multiplier/ mndivyear), 5440); vect2_direction(&month_hand, (date_multiplier / mndivmonth), 5440); vect2_direction(&hour_hand, (time_multiplier/ mndivhr), 2688); vect2_direction(&minute_hand, (time_multiplier / mndivmin), 2016); vect2_rotate90(&year_hand); vect2_rotate90(&month_hand); vect2_rotate90(&hour_hand); vect2_rotate90(&minute_hand); YELLOW_VECT_LINE(17, 25, &year_hand); YELLOW_VECT_LINE(33, 25, &month_hand); YELLOW_VECT_LINE(25, 25, &hour_hand); YELLOW_VECT_LINE(25, 25, &minute_hand); } ha1 = 0; while (ha1 < 32) { n_uint icon_stripe = (n_uint)((local_icon[(ha1<<2)|3] << 0) | (local_icon[(ha1<<2)|2] << 8) | (local_icon[(ha1<<2)|1] << 16) | (local_icon[(ha1<<2)|0] << 24)); n_int startRun = -1; n_int stopRun = -1; ha2 = 0; while ( ha2 < 32 ) { if ((icon_stripe >> (31-ha2)) & 1) { if (startRun < 0) { startRun = ha2; } stopRun = ha2; } if ((stopRun < ha2) && (startRun > -1)) { YELLOW_LINE(60 + startRun, 8 + ha1, stopRun - startRun, 0); startRun = -1; } ha2++; } if ((stopRun < ha2) && (startRun > -1)) { YELLOW_LINE(60 + startRun, 8 + ha1, stopRun - startRun, 0); startRun = -1; } ha1++; } } static void draw_feelers(simulated_being * bei, n_color8 * local_info, n_vect2 * location, n_int start_point, n_pixel *local_draw, n_byte hires) { n_int local_facing = ((((being_facing(bei))>>2) + 4) & 63) >> 3; /* D C G F H E B A */ n_color8 *local_col = local_info; local_col->color = COLOR_WHITE; if(local_facing == 0 || local_facing == 7) { if (hires) { (*local_draw)(POSITIVE_LAND_COORD_HIRES(location->x + start_point ), POSITIVE_LAND_COORD_HIRES(location->y - 2 ), 0, 0, local_info); /* F */ } else { (*local_draw)(POSITIVE_LAND_COORD(location->x + start_point ), POSITIVE_LAND_COORD(location->y - 2 ), 0, 0, local_info); /* F */ } } if(local_facing == 1 || local_facing == 0) { if (hires) { (*local_draw)(POSITIVE_LAND_COORD_HIRES(location->x + start_point ), POSITIVE_LAND_COORD_HIRES(location->y + 2 ), 0, 0, local_info); /* E */ } else { (*local_draw)(POSITIVE_LAND_COORD(location->x + start_point ), POSITIVE_LAND_COORD(location->y + 2 ), 0, 0, local_info); /* E */ } } if(local_facing == 2 || local_facing == 1) { if (hires) { (*local_draw)(POSITIVE_LAND_COORD_HIRES(location->x + 2 ), POSITIVE_LAND_COORD_HIRES(location->y + start_point ), 0, 0, local_info); /* A */ } else { (*local_draw)(POSITIVE_LAND_COORD(location->x + 2 ), POSITIVE_LAND_COORD(location->y + start_point ), 0, 0, local_info); /* A */ } } if(local_facing == 3 || local_facing == 2) { if (hires) { (*local_draw)(POSITIVE_LAND_COORD_HIRES(location->x - 2 ), POSITIVE_LAND_COORD_HIRES(location->y + start_point ), 0, 0, local_info); /* B */ } else { (*local_draw)(POSITIVE_LAND_COORD(location->x - 2 ), POSITIVE_LAND_COORD(location->y + start_point ), 0, 0, local_info); /* B */ } } if(local_facing == 4 || local_facing == 3) { if (hires) { (*local_draw)(POSITIVE_LAND_COORD_HIRES(location->x - start_point ), POSITIVE_LAND_COORD_HIRES(location->y + 2 ), 0, 0, local_info); /* H */ } else { (*local_draw)(POSITIVE_LAND_COORD(location->x - start_point ), POSITIVE_LAND_COORD(location->y + 2 ), 0, 0, local_info); /* H */ } } if(local_facing == 5 || local_facing == 4) { if (hires) { (*local_draw)(POSITIVE_LAND_COORD_HIRES(location->x - start_point ), POSITIVE_LAND_COORD_HIRES(location->y - 2 ), 0, 0, local_info); /* G */ } else { (*local_draw)(POSITIVE_LAND_COORD(location->x - start_point ), POSITIVE_LAND_COORD(location->y - 2 ), 0, 0, local_info); /* G */ } } if(local_facing == 6 || local_facing == 5) { if (hires) { (*local_draw)(POSITIVE_LAND_COORD_HIRES(location->x - 2 ), POSITIVE_LAND_COORD_HIRES(location->y - start_point ), 0, 0, local_info); /* D */ } else { (*local_draw)(POSITIVE_LAND_COORD(location->x - 2 ), POSITIVE_LAND_COORD(location->y - start_point ), 0, 0, local_info); /* D */ } } if(local_facing == 7 || local_facing == 6) { if (hires) { (*local_draw)(POSITIVE_LAND_COORD_HIRES(location->x + 2 ), POSITIVE_LAND_COORD_HIRES(location->y - start_point ), 0, 0, local_info); /* C */ } else { (*local_draw)(POSITIVE_LAND_COORD(location->x + 2 ), POSITIVE_LAND_COORD(location->y - start_point ), 0, 0, local_info); /* C */ } } } #define ACTIVE_PIXEL(px,py) sketch_psetc(POSITIVE_LAND_COORD(px),POSITIVE_LAND_COORD(py),COLOR_RED) #define ERASER_PIXEL(px,py) sketch_psetc(POSITIVE_LAND_COORD(px),POSITIVE_LAND_COORD(py), \ (n_byte)local_val) /* * kind = 0, draw normal ape * kind = 1, draw selected ape * kind = 2, erase normal ape * kind = 3, erase selected ape */ static void draw_apeloc(simulated_group * group, simulated_being *bei, n_join * draw) { simulated_timing * timing = sim_timing(); n_pixel *local_draw = draw->pixel_draw; void *local_info = draw->information; n_int start = -1, stop = 2; n_int time_coef = timing->real_time >> 4; n_int start_point = ((time_coef &3 )) + 3; n_vect2 location; n_vect2 delta; being_space(bei, &location); land_convert_to_map(&location); delta.y = start; while (delta.y < stop) { delta.x = start; while (delta.x < stop) { n_vect2 screen; vect2_add(&screen, &location, &delta); (*local_draw)(POSITIVE_LAND_COORD(screen.x), POSITIVE_LAND_COORD(screen.y), 0, 0, local_info); delta.x++; } delta.y++; } if (bei == group->select) { n_int ty = -1; if (toggle_follow) { selected_location.x = location.x; selected_location.y = location.y; } while (ty < 2) { (*local_draw)(POSITIVE_LAND_COORD(location.x + ty), POSITIVE_LAND_COORD(location.y - 2 ), 0, 0, local_info); (*local_draw)(POSITIVE_LAND_COORD(location.x + ty), POSITIVE_LAND_COORD(location.y + 2 ), 0, 0, local_info); (*local_draw)(POSITIVE_LAND_COORD(location.x - 2 ), POSITIVE_LAND_COORD(location.y + ty), 0, 0, local_info); (*local_draw)(POSITIVE_LAND_COORD(location.x + 2 ), POSITIVE_LAND_COORD(location.y + ty), 0, 0, local_info); ty++; } start_point++; } if (being_speaking(bei)) { draw_feelers(bei, local_info, &location, start_point, local_draw, 0); } } /* * kind = 0, draw normal ape * kind = 1, draw selected ape * kind = 2, erase normal ape * kind = 3, erase selected ape */ static void draw_apeloc_hires(simulated_group * group, simulated_being *bei, n_join * draw) { simulated_timing * timing = sim_timing(); n_pixel *local_draw = draw->pixel_draw; void *local_info = draw->information; n_int start = -1, stop = 2; n_int time_coef = timing->real_time >> 4; n_int start_point = ((time_coef &3 )) + 3; n_vect2 location; n_vect2 delta; being_high_res(bei, &location); delta.y = start; while (delta.y < stop) { delta.x = start; while (delta.x < stop) { n_vect2 screen_point; vect2_add(&screen_point, &location, &delta); (*local_draw)(POSITIVE_LAND_COORD_HIRES(screen_point.x), POSITIVE_LAND_COORD_HIRES(screen_point.y), 0, 0, local_info); delta.x++; } delta.y++; } if (bei == group->select) { n_int ty = -1; while (ty < 2) { (*local_draw)(POSITIVE_LAND_COORD_HIRES(location.x + ty), POSITIVE_LAND_COORD_HIRES(location.y - 2 ), 0, 0, local_info); (*local_draw)(POSITIVE_LAND_COORD_HIRES(location.x + ty), POSITIVE_LAND_COORD_HIRES(location.y + 2 ), 0, 0, local_info); (*local_draw)(POSITIVE_LAND_COORD_HIRES(location.x - 2 ), POSITIVE_LAND_COORD_HIRES(location.y + ty), 0, 0, local_info); (*local_draw)(POSITIVE_LAND_COORD_HIRES(location.x + 2 ), POSITIVE_LAND_COORD_HIRES(location.y + ty), 0, 0, local_info); ty++; } start_point++; } if (being_speaking(bei)) { draw_feelers(bei, local_info, &location, start_point, local_draw, 1); } } static void draw_region_hires(n_color8 * color) { n_join local_draw; n_int step = (HI_RES_MAP_DIMENSION / 16); n_int ly = step - 1; local_draw.information = color->screen; if (local_draw.information == 0L) return; local_draw.pixel_draw = &pixel_map_hires; while (ly < HI_RES_MAP_DIMENSION) { math_line(0, ly, HI_RES_MAP_DIMENSION, ly, &local_draw); math_line(ly, 0, ly, HI_RES_MAP_DIMENSION, &local_draw); ly += step; } } static void draw_region(simulated_being * local) { n_join local_draw; n_byte * draw = draw_pointer(NUM_VIEW); n_int ly = 31; if (draw == 0L) return; local_draw.information = draw; local_draw.pixel_draw = &pixel_map_checker; while (ly < MAP_DIMENSION) { math_line(0, ly, MAP_DIMENSION, ly, &local_draw); math_line(ly, 0, ly, MAP_DIMENSION, &local_draw); ly += 32; } #ifdef TERRITORY_ON local_draw.pixel_draw = &pixel_map; ly = 0; while (ly < TERRITORY_DIMENSION) { n_int lx = 0; while (lx < TERRITORY_DIMENSION) { n_string_block string_draw; n_int value = local->events.territory[lx + (ly * TERRITORY_DIMENSION)].familiarity; if (value) { io_number_to_string(string_draw, (n_uint)value); draw_string(string_draw, (lx*32)+2 , (ly*32)+5, &local_draw); } lx++; } ly++; } #endif } #ifdef ALPHA_WEATHER_DRAW n_byte * draw_weather_grayscale(void) { return weather_grayscale; } static void draw_weather(n_int toggle) { if (toggle) { n_c_int *local_pressure = land_weather(0); n_int loop = 0; while(loop < MAP_AREA) { n_int value = local_pressure[ loop ]>>7; if (value < 0) value = 0; if (value > 255) value = 255; weather_grayscale[ loop ] = (n_byte)value; loop++; } } else { memory_erase(weather_grayscale, MAP_AREA); } } #else n_byte * draw_weather_grayscale(void) { return 0L; } static void draw_weather(n_int toggle) { n_int map_dimensions = land_map_dimension(); n_color8 local_col; n_pixel * local_draw = &pixel_color8; void * local_info = &local_col; n_int py = 0; if (toggle == 0) { return; } local_col.color = COLOR_WHITE; local_col.screen = draw_pointer(NUM_VIEW); if (local_col.screen == 0L) { return; } while(py < (map_dimensions)) { n_int px = 0; n_int scr_y = py; while(px < (map_dimensions)) { n_int scr_x = px; n_int tmp = weather_pressure(WEATHER_TO_MAPSPACE(px), WEATHER_TO_MAPSPACE(py)); /* from weather dimension to map dimension */ if (((scr_x & 1) == 1) && ((scr_y & 1) == 1)) { if(tmp > WEATHER_CLOUD) { (*local_draw)(scr_x, scr_y, 0, 0, local_info); } } if (((scr_x & 1) == 0) && ((scr_y & 1) == 0)) { if(tmp > WEATHER_RAIN) { (*local_draw)(scr_x, scr_y , 0, 0, local_info); } } px++; } py++; } } #endif static void draw_count_number(n_uint count, n_string value) { n_uint lp = 0, division = 1000000; while (lp < 6) { if ((count + 1) > division) { if (division != 0) { value[lp] = (n_char)('0' + ((count / division) % 10)); } else { value[lp] = (n_char)('0'); } } division /= 10; lp++; } value[6] = ('0' + ((count / 1) % 10)); } static void draw_metrics(n_uint bcps, n_uint fps, n_join * local_mono) { n_int offset_y = 8; if (bcps) { n_string_block bcps_string = {' ', ' ', ' ', ' ', ' ', ' ', 'X', ' ', 'B', '/', 'S', ' ', ' ', ' ', ' ', ' ', ' ', 0 }; draw_count_number(bcps, bcps_string); draw_string(bcps_string, (window_dim_x/2)-60, offset_y, local_mono); offset_y += CHARACTER_HEIGHT; } if (fps) { n_string_block fps_string = {' ', ' ', ' ', ' ', ' ', ' ', 'X', ' ', 'F', '/', 'S', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 0 }; draw_count_number(fps, fps_string); draw_string(fps_string, (window_dim_x/2)-60, offset_y, local_mono); } } /* draws the rotating brain, this is always draw and never erase */ #ifdef BRAIN_ON #ifndef SIMULATED_APE_CLIENT static void draw_brain(simulated_group * group, n_vect2 * dimensions) { n_byte draw_big = 1; if ((group->select == 0L) || (number_errors != 0) || changing_size) { return; } { n_byte * local = being_brain(group->select); n_join local_mono; n_int turn_y = (n_int)tilt_z; n_int turn_z = (n_int)tilt_y; n_pixel * local_draw_brain = &pixel_white; void * local_info_brain = draw_pointer(NUM_TERRAIN); n_int lpx = 0; n_int loop = 0; n_int center_x = dimensions->x >> 1; n_int center_y = dimensions->y >> 1; n_int act_x2a, term_1a, term_2a; n_byte * brainptr = local; n_byte * obrainptr = &local[ 32 * 32 * 32 ]; n_int a11, a12, a13, a21, a23, a31, a32, a33; n_vect2 vect_y, vect_z; vect2_direction(&vect_y, turn_y, 105); vect2_direction(&vect_z, turn_z, 23); //NEW_SD_MULTIPLE/1152); a32 = vect_y.x; a12 = vect_y.y; a21 = vect_z.x; a23 = vect_z.y; a11 = -((a32 * a23) >> 8); a13 = ((a32 * a21) >> 8); a31 = ((a12 * a23) >> 8); a33 = -((a12 * a21) >> 8); local_mono.pixel_draw = &pixel_white; local_mono.information = draw_pointer(NUM_TERRAIN); if (local == 0L) { return; } a12 = (a12 * 1152) >> 8; a32 = (a32 * 1152) >> 8; act_x2a = -((a21 + a23) << 4); term_1a = -((a11 + a12 + a13) << 4); term_2a = -((a31 + a32 + a33) << 4); while (lpx < 32) { n_int lpy = 0; n_int term_1 = term_1a; n_int term_2 = term_2a; while (lpy < 32) { n_int act_x1 = term_1 ; n_int act_x2 = act_x2a; n_int act_y1 = term_2 ; n_int lpz = 0; while (lpz < 32) { if ((brainptr[loop] ^ obrainptr[loop]) >> 5) { /* TODO Fix this re-scaling bug */ n_int scr_z = 256 + (act_x1 >> 11); n_int s_x = ((act_x2 * scr_z) >> 17) + center_x; n_int s_y = ((act_y1 * scr_z) >> 17) + center_y - 100; //120 (*local_draw_brain)(s_x, s_y, 0, 0, local_info_brain); if ((act_x1 > 0) && draw_big) { (*local_draw_brain)(s_x - 1, s_y, 0, 0, local_info_brain); (*local_draw_brain)(s_x + 1, s_y, 0, 0, local_info_brain); (*local_draw_brain)(s_x, s_y - 1, 0, 0, local_info_brain); (*local_draw_brain)(s_x, s_y + 1, 0, 0, local_info_brain); } } act_x1 += a13; act_x2 += a23; act_y1 += a33; loop++; lpz++; } term_1 += a12; term_2 += a32; lpy++; } term_1a += a11; term_2a += a31; act_x2a += a21; lpx++; } tilt_y = ( tilt_y + 2 ) & 255; } } #endif #endif n_int draw_error(n_constant_string error_text, n_constant_string location, n_int line_number) { n_int loop = 0; n_int error_char_copy; n_string_block simulation_date_time = {0}; n_string_block simulation_date_time_error = {0}; n_int position = 0; if (error_text) { #ifdef SIMULATED_APE_ASSERT printf("ERROR: %s\n", error_text); #endif #ifdef EXPLICIT_DEBUG printf("ERROR: %s (%s, %ld)\n", error_text, location, line_number); #endif io_time_to_string(simulation_date_time); io_string_write(simulation_date_time_error, simulation_date_time, &position); io_string_write(simulation_date_time_error, " ", &position); if(number_errors == MAX_NUMBER_ERRORS) { io_string_write(simulation_date_time_error, " ** Maximum errors reached **" , &position); } else { io_string_write(simulation_date_time_error, (n_string)error_text, &position); } } else { number_errors = 0; return 0; } if (io_command_line_execution()) { io_console_out(simulation_date_time_error); return -1; } do { error_char_copy = error_array[number_errors][loop] = simulation_date_time_error[loop]; loop++; } while((loop < STRING_BLOCK_SIZE) && (error_char_copy != 0)); error_array[number_errors][loop] = 0; if(number_errors != MAX_NUMBER_ERRORS) { number_errors++; } return -1; } #ifndef SIMULATED_APE_CLIENT static void draw_remains(simulated_group * group, n_byte * screen) { simulated_remains * remains = group->remains; n_int loop = 0; while(loop < remains->count) { simulated_idead_body * body = &(remains->bodies[loop]); n_int lx = MAP_DIMENSION - 2; n_vect2 location; vect2_byte2(&location, body->location); land_convert_to_map(&location); while (lx < (MAP_DIMENSION + 3)) { screen[((location.x + lx)&(MAP_DIMENSION-1)) + (((location.y)&(MAP_DIMENSION-1)) * MAP_DIMENSION)] = COLOR_WHITE; screen[((location.x)&(MAP_DIMENSION-1)) + (((location.y + lx)&(MAP_DIMENSION-1)) * MAP_DIMENSION)] = COLOR_WHITE; lx++; } loop++; } } #endif static void draw_tides(n_byte * map, n_byte * screen, n_byte tide) { n_byte tide_compress[45]; n_int lp = 0; n_byte tide_point = tide - 106; n_int ar = 106; n_int dr = 128; n_int fl = tide_point; n_int fp = 0; if (toggle_tidedaylight) { return; } while (lp < 45) { tide_compress[lp] = (n_byte)(((ar * (fl - lp)) + (dr * (lp - fp))) / (fl-fp)); if (lp == tide_point) { ar = 128; dr = 150; fl = 150 - 106; fp = tide_point; } lp++; } lp = 0; while (lp < MAP_AREA) { n_byte val = map[lp]; if ((val > 105) && (val < 151)) { screen[lp] = tide_compress[val - 106]; } lp++; } } static void draw_tides_hi_res(n_byte * data, n_byte4 * block, n_byte tide) { n_byte tide_compress[45]; n_int lp = 0; n_byte tide_point = tide - 106; n_int ar = 106; n_int dr = 128; n_int fl = tide_point; n_int fp = 0; if (toggle_tidedaylight) { return; } while (lp < 45) { tide_compress[lp] = (n_byte)(((ar * (fl - lp)) + (dr * (lp - fp))) / (fl - fp)); if (lp == tide_point) { ar = 128; dr = 150; fl = 150 - 106; fp = tide_point; } lp++; } lp = 0; while (lp < HI_RES_MAP_AREA) { n_byte4 block_group = block[lp >> 5]; if (block_group != 0) { n_int local_loop = lp << 1; n_int local_loop_end = local_loop+64; n_int lp = 0; while (local_loop < local_loop_end) { if ((block_group >> lp) & 1) { data[local_loop|1] = tide_compress[data[local_loop] - 106]; } local_loop += 2; lp++; } } lp += 32; } } static void draw_ape(simulated_group * group, simulated_being * being, n_byte color, n_color8 * col8) { n_vect2 location_vect; n_join local_8bit; col8->color = color; being_space(being, &location_vect); if (col8->screen == land_topography_highdef()) { local_8bit.pixel_draw = &pixel_color8_hires; } else { local_8bit.pixel_draw = &pixel_color8; } local_8bit.information = col8; if (col8->screen == land_topography_highdef()) { draw_apeloc_hires(group, being, &local_8bit); } else { draw_apeloc(group, being, &local_8bit); } } static void draw_apes_loop(simulated_group * group, simulated_being * bei, void * data) { n_join local_8bit; n_color8 local_col; n_vect2 location_vect; /* makes this use thread safe */ memory_copy(data, (n_byte*)&local_col, sizeof(n_color8)); being_space(bei, &location_vect); if (being_line_of_sight(group->select, &location_vect) == 1) { local_col.color = COLOR_RED; } else { local_col.color = COLOR_RED_DARK; } if (local_col.screen == land_topography_highdef()) { local_8bit.pixel_draw = &pixel_color8_hires; } else { local_8bit.pixel_draw = &pixel_color8; } local_8bit.information = &local_col; if (local_col.screen == land_topography_highdef()) { draw_apeloc_hires(group, bei, &local_8bit); } else { draw_apeloc(group, bei, &local_8bit); } } static void draw_apes(simulated_group * group, n_byte lores) { n_color8 local_col; if (lores) /* set up drawing environ */ { local_col.screen = draw_pointer(NUM_VIEW); memory_copy(land_topography(), local_col.screen, MAP_AREA); } else { draw_undraw(); local_col.screen = land_topography_highdef(); } if (lores) { draw_tides(land_topography(), local_col.screen, land_tide_level()); if (toggle_territory) { draw_region(group->select); } #ifndef SIMULATED_APE_CLIENT draw_remains(group, local_col.screen); #endif } else { static n_byte local_tide; if (local_tide != land_tide_level()) { local_tide = land_tide_level(); draw_tides_hi_res(land_topography_highdef(), land_highres_tide(), local_tide); } if (toggle_territory) { draw_region_hires(&local_col); } } if (group->select) { loop_no_thread(group, 0L, draw_apes_loop, &local_col); } } static void draw_social_web(simulated_group * group, n_byte lores) { n_int loop = 0; n_int friends_count = command_relationship_count(0); n_int enemies_count = command_relationship_count(1); n_int attract_count = command_relationship_count(2); n_color8 local_col; if (lores) /* set up drawing environ */ { local_col.screen = draw_pointer(NUM_VIEW); } else { local_col.screen = land_topography_highdef(); } loop = 0; while (loop < attract_count) { simulated_being * attract = command_relationship_being(group, 2, loop); if (attract) { draw_ape(group, attract, COLOR_BLUE, &local_col); } loop++; } loop = 0; while (loop < friends_count) { simulated_being * friend = command_relationship_being(group, 0, loop); if (friend) { draw_ape(group, friend, COLOR_WHITE, &local_col); } loop++; } loop = 0; while (loop < enemies_count) { simulated_being * enemy = command_relationship_being(group, 1, loop); if (enemy) { draw_ape(group, enemy, COLOR_BLACK, &local_col); } loop++; } } static void draw_errors(void) { n_join local_mono; local_mono.pixel_draw = &pixel_white; local_mono.information = draw_pointer(NUM_TERRAIN); if(number_errors != 0) { n_int loop = 0; while(loop< (number_errors+1)) { draw_string(error_array[loop], 40, (loop * CHARACTER_HEIGHT) + 62, &local_mono); loop++; } } } n_int draw_control_font_scaling(void) { return control_font_scaling; } #ifdef DEBUG_CONTROL_STRING static n_uint debug_hash_old = 0; #endif static void draw_control(simulated_group * group, n_int window_dim_x, n_int window_dim_y) { n_string string_stats; n_join local_mono; n_int location_ptr = 0; n_int max_characters = (342 - 16) / 8; n_int control_font_scaling_x = (window_dim_x * 10) / 342; n_int control_font_scaling_y = (window_dim_y * 10) / 512; control_font_scaling = (control_font_scaling_x + control_font_scaling_y) / 2; max_characters = (window_dim_x - 16) * 10 / (control_font_scaling * 8); if (group == 0L) { return; } if (sim_get_writing_output()) { return; } sim_control_erase(window_dim_x, window_dim_y, control_font_scaling); character_location = 1; smart_character_toggle = 0; bold_character_toggle = 0; local_mono.pixel_draw = &pixel_control; local_mono.information = draw_pointer(NUM_CONTROL); memory_erase(local_mono.information, (n_uint)(window_dim_x * window_dim_y)); string_stats = sim_output_string(); #ifdef DEBUG_CONTROL_STRING { n_uint new_hash = math_hash(string_stats, io_length(string_stats, STRING_BLOCK_SIZE)); if (new_hash != debug_hash_old) { printf("%s\n\n",string_stats); debug_hash_old = new_hash; } } #endif { n_char character = 'Y'; n_int line_count = 0; do{ n_string_block string_line = {0}; n_string_block string_second_line = {0}; n_int location_line_ptr = 0; do{ character = string_stats[location_ptr++]; if (character != '\n') { string_line[location_line_ptr++] = character; } }while ((character != '\n') && (location_line_ptr < STRING_BLOCK_SIZE)); if (location_line_ptr > max_characters) { n_int is_space = 0; n_int second_line_location = max_characters; do{ n_char character = string_line[location_line_ptr]; if (is_space) { string_second_line[second_line_location] = ' '; } else { string_second_line[second_line_location] = character; string_line[location_line_ptr] = 0; location_line_ptr--; } second_line_location--; if (character == ' ' && location_line_ptr < (max_characters-2)) { is_space = 1; } }while(second_line_location > -1); } draw_smart_string(string_line, CHARACTER_WIDTH, CHARACTER_WIDTH + (line_count * CHARACTER_HEIGHT), &local_mono); if (string_second_line[0]) { line_count++; draw_smart_string(string_second_line, CHARACTER_WIDTH, CHARACTER_WIDTH + (line_count * CHARACTER_HEIGHT), &local_mono); } line_count++; }while (string_stats[location_ptr] != 0); } } #ifdef BRAINCODE_ON static void draw_line_braincode(n_string pointer, n_int line) { n_join local_mono; if (changing_size) { return; } local_mono.pixel_draw = &pixel_white; local_mono.information = draw_pointer(NUM_TERRAIN); draw_string(pointer, 4 + (window_dim_x/2) - 256, (line * CHARACTER_HEIGHT) + 68, &local_mono); } #endif void draw_terrain_coord(n_int * co_x, n_int * co_y) { *co_x = window_dim_x; *co_y = window_dim_y; } void draw_window(n_int dim_x, n_int dim_y) { window_dim_x = dim_x; window_dim_y = dim_y; } #ifdef SKELETON_RENDER static void draw_skeleton(simulated_group * group) { n_genetics * genetics = 0L; if (group->select) { genetics = group->select->constant.genetics; } if (genetics != 0L) { n_int dim_x = window_dim_x; n_int dim_y = window_dim_y; /** set this to a non-zero value to show key points on the skeleton which may be useful for debugging */ /* doesn't work with Ofast optimization */ n_vect2 dim; n_vect2 tp; n_vect2 bp; n_byte show_skeleton_keypoints = 0; dim.x = dim_x; dim.y = dim_y; tp.x = dim_x * 10/100; tp.y = dim_y * 10/100; bp.x = dim_x * 40/100; bp.y = dim_y * 90/100; vascular_draw(genetics, draw_pointer(NUM_TERRAIN), &dim, &tp, &bp, 1, 0, /* don't erase here */ 30, 0, 20, 20, 0, show_skeleton_keypoints); } } #endif void draw_cycle(n_byte size_changed, n_byte kind) { simulated_group * group = sim_group(); if (sim_new()) { if (CHECK_DRAW_WINDOW(kind, DRAW_WINDOW_TERRAIN)) { draw_about_information(1); } #ifdef APESIM_IOS if (CHECK_DRAW_WINDOW(kind, DRAW_WINDOW_CONTROL)) { draw_about_information(0); } #endif return; } changing_size = size_changed; if (CHECK_DRAW_WINDOW(kind, DRAW_WINDOW_CONTROL)) { draw_control(group, window_dim_x, window_dim_y); } if (CHECK_DRAW_WINDOW(kind, DRAW_WINDOW_VIEW)) { draw_apes(group, 1); /* lo res */ } if (CHECK_DRAW_WINDOW(kind, DRAW_WINDOW_TERRAIN)) { draw_apes(group, 0); /* hi res */ } if (toggle_social_web) { if (CHECK_DRAW_WINDOW(kind, DRAW_WINDOW_VIEW)) { draw_social_web(group, 1); } if (CHECK_DRAW_WINDOW(kind, DRAW_WINDOW_TERRAIN)) { draw_social_web(group, 0); } } if (CHECK_DRAW_WINDOW(kind, DRAW_WINDOW_TERRAIN)) { simulated_timing * timing = sim_timing(); n_vect2 local_vect; n_join local_mono; local_mono.pixel_draw = &pixel_white; local_mono.information = draw_pointer(NUM_TERRAIN); local_vect.x = window_dim_x; local_vect.y = window_dim_y; draw_terrain(group, &local_vect); #ifdef BRAIN_ON if (toggle_brain) { draw_brain(group, &local_vect); } #endif #ifdef BRAINCODE_ON if (toggle_braincode) { command_populate_braincode(group, draw_line_braincode); } #endif draw_meters(group); draw_errors(); /* 12 */ #ifndef SIMULATED_APE_CLIENT draw_metrics(0, timing->delta_frames, &local_mono); #endif #ifdef SKELETON_RENDER if (group->select != 0L) { draw_skeleton(group); } #endif } if (CHECK_DRAW_WINDOW(kind, DRAW_WINDOW_VIEW)) { #ifdef WEATHER_ON draw_weather(toggle_weather); /* 10 */ #endif } if (CHECK_DRAW_WINDOW(kind, DRAW_WINDOW_TERRAIN)) { if (check_about) { draw_about_information(1); } } #ifdef MULTITOUCH_CONTROLS draw_tc_controls(&local_mono); #endif } <|start_filename|>test/test_compress.c<|end_filename|> /**************************************************************** test_compress.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of Tom Barbalet, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /* this doesn't currently work, it is included here for unit testing in the future */ #include <stdio.h> #include <time.h> #include "../noble/noble.h" n_int draw_error(n_constant_string error_text, n_constant_string location, n_int line_number) { if (error_text) { printf("ERROR: %s @ %s %ld\n", (n_constant_string)error_text, location, line_number); } return -1; } static void check_compress(void) { const n_int step = 7; n_int loop = 0; n_byte decomp_string[8*7] = {0}; n_byte sample_string[7*3] = "1 to 99 This is a"; /*012012012012012012012*/ /* 1 2 3 4 5 6 */ printf("%s\n", sample_string); compress_buffer_run(&sample_string, decomp_string, step, 1, 3); compress_buffer_run(decomp_string, &sample_string, step, 0, 3); printf("%s\n", sample_string); } int main(int argc, const char * argv[]) { printf(" --- test compress --- start ------------------------------------------------\n"); check_compress(); printf(" --- test compress --- end ------------------------------------------------\n"); return 0; } <|start_filename|>toolkit/memory.c<|end_filename|> /**************************************************************** memory.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /*! \file memory.c * \brief Covers the low level input and output relating to memory. */ #include "toolkit.h" #include <string.h> #include <stdlib.h> #include <stdio.h> /** * This is a historical legacy function as all platforms now use memcpy. Although in the future this may change. * @param from pointer to copy from. * @param to pointer to copy to. * @param number the number of bytes to copy. */ void memory_copy(n_byte * from, n_byte * to, n_uint number) { memcpy(to, from, number); } /** * This is a historical legacy function as all platforms now use malloc. Although in the future this may change. * @param bytes number of bytes to allocate. * @return a void* pointer of the allocated bytes. */ void * memory_new(n_uint bytes) { void * tmp = 0L; if (bytes) { tmp = (void *) malloc(bytes); } return (tmp); } /** * This is a historical legacy function as all platforms now use free. Although in the future this may change. * @param ptr the void * pointer to be freed. Should really be a void ** to catch the 0L-ing. */ void memory_free(void ** ptr) { if (*ptr != 0L) { free(*ptr); *ptr = 0L; } } /** * This is allocates a range of memory depending on availability. * @param memory_min the minimum possible allocated memory before returning 0L. * @param memory_allocated the starting value for memory size and returning the actual size. * @return a void* pointer of the allocated bytes. */ void * memory_new_range(n_uint memory_min, n_uint *memory_allocated) { void * memory_buffer = 0L; do { memory_buffer = (void *) malloc(*memory_allocated); if (memory_buffer == 0L) { *memory_allocated = ((*memory_allocated) * 3) >> 2; } } while((memory_buffer == 0L) && ((*memory_allocated) > memory_min)); return memory_buffer; } void memory_erase(n_byte * buf_offscr, n_uint nestop) { memset(buf_offscr, 0, nestop); } <|start_filename|>entity/entity.h<|end_filename|> /**************************************************************** entity.h ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #ifndef SIMULATEDAPE_ENTITY_H #define SIMULATEDAPE_ENTITY_H #include "../toolkit/toolkit.h" #include "../script/script.h" #include "../sim/sim.h" #include "../universe/universe.h" #define LAND_ON #define WEATHER_ON #define RANDOM_INITIAL_BRAINCODE #undef SHORT_NAMES #undef FIXED_RANDOM_SIM #undef LARGE_SIM enum being_energy { BEING_DEAD = 0, BEING_HUNGRY = (10 * 128), BEING_FULL = (BEING_HUNGRY * 3) }; #define SOCIAL_RESPECT_NORMAL 127 enum BRAINPROBE_TYPE { INPUT_SENSOR = 0, OUTPUT_ACTUATOR, NUMBER_BRAINPROBE_TYPES }; #define GENEALOGY_ON enum GENEALOGY_FORMAT { GENEALOGY_NONE = 0, GENEALOGY_GENXML, GENEALOGY_GEDCOM, GENEALOGY_FORMATS }; /* if you change this you need to change the corresponding definitions in being_state_description */ typedef enum { BEING_STATE_ASLEEP = 0, BEING_STATE_AWAKE = 1, BEING_STATE_HUNGRY = 2, BEING_STATE_SWIMMING = 4, BEING_STATE_EATING = 8, BEING_STATE_MOVING = 16, BEING_STATE_SPEAKING = 32, BEING_STATE_SHOUTING = 64, BEING_STATE_GROOMING = 128, BEING_STATE_SUCKLING = 256, BEING_STATE_SHOWFORCE = 512, BEING_STATE_ATTACK = 1024, BEING_STATE_NO_FOOD = 2048, BEING_STATES = 13 } being_state_type; typedef enum { EVENT_EAT = 1, EVENT_MATE, EVENT_HIT, EVENT_HIT_BY, EVENT_SWIM, EVENT_GROOM, EVENT_GROOMED, EVENT_CHAT, EVENT_SHOUT, EVENT_BIRTH, EVENT_CARRIED, EVENT_CARRIED_BY, EVENT_SUCKLED, EVENT_SUCKLED_BY, EVENT_SEEK_MATE, EVENT_WHACKED, EVENT_WHACKED_BY, EVENT_HURLED, EVENT_HURLED_BY, EVENT_HUGGED, EVENT_HUGGED_BY, EVENT_PRODDED, EVENT_PRODDED_BY, EVENT_DRAG, EVENT_BRANDISH, EVENT_DROP, EVENT_PICKUP, EVENT_GIVEN, EVENT_GIVEN_BY, EVENT_CHEW, EVENT_BASH_OBJECTS, EVENT_FISH, EVENT_SMILED, EVENT_SMILED_BY, EVENT_GLOWERED, EVENT_GLOWERED_BY, EVENT_PATTED, EVENT_PATTED_BY, EVENT_POINT, EVENT_POINTED, EVENT_TICKLED, EVENT_TICKLED_BY, EVENTS } being_episodic_event_type; /* affect (how many cycles it takes to forget particular episodic memory events) */ #define COMPOSITE_AFFECT(enjoyment,interest,surprise, \ anger,disgust,dissmell, \ distress,fear,shame) \ ((enjoyment)+(interest)-(anger)-(disgust)-(dissmell)-(distress)-(fear)-(shame)) typedef enum { AFFECT_MATE = COMPOSITE_AFFECT(1000,0,0, 0,0,0, 0,0,0), AFFECT_BIRTH = COMPOSITE_AFFECT(1500,0,1000, 0,100,100, 200,200,50), AFFECT_CARRYING = COMPOSITE_AFFECT(300,300,0, 0,0,0, 0,0,0), AFFECT_CARRIED = COMPOSITE_AFFECT(300,300,0, 0,0,0, 0,0,0), AFFECT_SUCKLING = COMPOSITE_AFFECT(500,0,0, 0,0,0, 0,0,0), AFFECT_CHAT = COMPOSITE_AFFECT(0,100,0, 0,0,0, 0,0,0), AFFECT_GROOM = COMPOSITE_AFFECT(50,50,0, 0,0,0, 0,0,0), AFFECT_SEEK_MATE = COMPOSITE_AFFECT(0,600,0, 0,0,0, 0,0,0), AFFECT_SQUABBLE_VICTOR = COMPOSITE_AFFECT(1100,0,100, 0,0,0, 100,0,0), AFFECT_SQUABBLE_VANQUISHED = COMPOSITE_AFFECT(0,0,100, 200,0,0, 600,100,100), AFFECT_WHACKED = COMPOSITE_AFFECT(0,0,100, 20,0,0, 20,20,40), AFFECT_HURL = COMPOSITE_AFFECT(0,0,0, 100,0,0, 0,0,0), AFFECT_HUGGED = COMPOSITE_AFFECT(100,0,0, 0,0,0, 0,0,0), AFFECT_PRODDED = COMPOSITE_AFFECT(0,0,0, 0,0,0, 5,0,5), AFFECT_RECEIVE = COMPOSITE_AFFECT(25,25,0, 0,0,0, 0,0,0), AFFECT_FISH = COMPOSITE_AFFECT(100,100,0, 0,0,0, 0,0,0), AFFECT_SMILED = COMPOSITE_AFFECT(10,0,0, 0,0,0, 0,0,0), AFFECT_GLOWER = COMPOSITE_AFFECT(0,0,10, 0,0,0, 0,10,0), EPISODIC_AFFECT_ZERO = (16384) } AFFECT_TYPE; enum inventory_type { INVENTORY_CHILD = 1, INVENTORY_WOUND = 2, INVENTORY_GROOMED = 4, INVENTORY_BRANCH = 8, INVENTORY_ROCK = 16, INVENTORY_SHELL = 32, INVENTORY_TWIG = 64, INVENTORY_NUT = 128, INVENTORY_NUT_CRACKED = 256, INVENTORY_GRASS = 512, INVENTORY_SCRAPER = 1024, INVENTORY_SPEAR = 2048, INVENTORY_FISH = 4096, INVENTORY_BIRD_EGGS = 8192, INVENTORY_LIZARD_EGGS = 16384 }; /* energy values for different foods */ /* TODO: add EGGS and potentially INSECTS to food groups */ enum FOOD_KINDS { FOOD_VEGETABLE = 0, FOOD_FRUIT, FOOD_SHELLFISH, FOOD_SEAWEED, FOOD_BIRD_EGGS, FOOD_LIZARD_EGGS, FOOD_TYPES }; /* maximum energy obtainable from different types of food */ enum energy_types { ENERGY_GRASS = 50, ENERGY_BUSH = 100, ENERGY_FRUIT = 100, ENERGY_SEAWEED = 30, ENERGY_SHELLFISH = 300, ENERGY_NUT = 200, ENERGY_FISH = 600, ENERGY_BIRD_EGGS = 800, ENERGY_LIZARD_EGGS = 1000 }; /* gestation period in days */ #define GESTATION_DAYS 1 /* energy gained by the child when suckling from the mother per time step */ #define SUCKLING_ENERGY 2 /* maximum separation between mother and child when suckling */ #define SUCKLING_MAX_SEPARATION METRES_TO_APESPACE(2) /* number of days after birth that weaning takes place */ #define WEANING_DAYS 14 /* time during which the mother is able to carry a child on her back */ #define CARRYING_DAYS 3 /* after a new ape is born how soon can the mother conceive */ #define CONCEPTION_INHIBITION_DAYS 5 #define APESPACE_TO_HR_MAPSPACE(num) ((num)>>3) /* nature in the range 0-15 from the genetics nurture in the range 0-255 from learned preferences. Resulting value is in the range 0-15 */ #define NATURE_NURTURE(nature,nurture) (((nature) + ((nurture)>>4))>>1) /* A social drive threshold value above which beings interact */ #define SOCIAL_THRESHOLD(bei) ((NATURE_NURTURE(GENE_SOCIAL(being_genetics(bei)),bei->changes.learned_preference[PREFERENCE_SOCIAL]))>>1) /* Defines initial braincode instruction type probability*/ #define GENE_BRAINCODE_SENSORS(gene) GENE_VAL_REG(gene, 11, 14, 4, 7) #define GENE_BRAINCODE_ACTUATORS(gene) GENE_VAL_REG(gene, 15, 10, 10, 0) #define GENE_BRAINCODE_CONDITIONALS(gene) GENE_VAL_REG(gene, 4, 9, 0, 2) #define GENE_BRAINCODE_OPERATORS(gene) GENE_VAL_REG(gene, 12, 1, 6, 12) #define GENE_BRAINCODE_DATA(gene) GENE_VAL_REG(gene, 8, 15, 7, 12) /* Rates at which the affect associated with episodic memories fade over time. This makes dysphoria-like memory effects possible, and also regulate how long events remain in episodic memory */ #define GENE_NEGATIVE_AFFECT_FADE(gene) GENE_VAL_REG(gene, 9, 15, 13, 2) #define GENE_POSITIVE_AFFECT_FADE(gene) GENE_VAL_REG(gene, 11, 4, 3, 12) /* preference for social activity, similar to flocking */ #define GENE_SOCIAL(gene) GENE_VAL_REG(gene, 22, 2, 13, 9) /* worst case 1500 + 180 per step */ #define VISIBILITY_MAXIMUM (2000) #define VISIBILITY_SPAN VISIBILITY_MAXIMUM /*(VISIBILITY_MAXIMUM / ((15+16) >> 1))*/ #define WALK_ON_WATER(pz,w) (((pz)<w) ? w : (pz)) /** Swim - better or worse at swimming both speed and energy use */ #define GENE_SWIM(gene) GENE_VAL_REG(gene, 9, 11, 13, 7) /** Speed on land - faster v. slower */ #define GENE_SPEED(gene) GENE_VAL_REG(gene, 14, 5, 12, 10) /** Control on random wander - more or less random wander */ #define GENE_STAGGER(gene) GENE_VAL_REG(gene, 12, 14, 3, 11) /** Hill climbing - improved energy use for climbing */ #define GENE_HILL_CLIMB(gene) GENE_VAL_REG(gene, 4, 6, 5, 2) /* different types of goal */ typedef enum { GOAL_NONE = 0, GOAL_LOCATION = 1, GOAL_MATE = 2, GOAL_UNKNOWN = 3 /* add a new goal here when needed */ } goal_types; typedef struct { simulated_being * local; simulated_isocial * local_social; n_uint opposite_sex_distance; n_uint same_sex_distance; simulated_being * opposite_sex; simulated_being * same_sex; } being_nearest; void being_living(simulated_being * value); void being_inc_drive(simulated_being * value, enum drives_definition drive); void being_dec_drive(simulated_being * value, enum drives_definition drive); n_int being_energy_less_than(simulated_being * value, n_int less_than); void being_turn_away_from_water(simulated_being * value); void being_facing_init(simulated_being * value); n_byte being_honor_immune(simulated_being * value); void being_set_brainstates(simulated_being * value, n_int asleep, n_byte2 val1, n_byte2 val2, n_byte2 val3); void being_delta(simulated_being * primary, simulated_being * secondary, n_vect2 * delta); void being_facing_towards(simulated_being * value, n_vect2 * vector); n_int being_pregnant(simulated_being * value); n_int being_female(simulated_being * value); n_int being_speaking(simulated_being * value); n_genetics * being_fetal_genetics(simulated_being * value); n_int social_set_relationship(simulated_group * group, simulated_being * meeter_being, n_byte relationship,simulated_being * met_being); n_int social_get_relationship(simulated_being * meeter_being, n_byte relationship); n_int social_network(simulated_group * group, simulated_being * meeter_being, simulated_being * met_being, n_uint distance); n_byte social_groom(simulated_group * group, simulated_being * meeter_being, simulated_being * met_being, n_uint distance, n_int awake, n_byte2 familiarity); n_byte2 social_squabble(simulated_being * meeter_being, simulated_being * met_being, n_uint distance, n_int is_female, simulated_group * group); n_int social_mate(simulated_being * meeter_being, simulated_being * met_being, n_int being_index, n_uint distance, simulated_group * group); n_int social_chat(simulated_being * meeter_being, simulated_being * met_being, n_int being_index, simulated_group * group); void episodic_food(simulated_being * local, n_int energy, n_byte food_type); void being_immune_seed(simulated_being * mother, simulated_being * child); void body_genetics(simulated_being * beings, n_int number, n_genetics * genetics, n_genetics * mother_genetics, n_genetics * father_genetics, n_byte2 * local); n_int food_eat( n_int loc_x, n_int loc_y, n_int az, n_byte * food_type, simulated_being * local_being); void genetics_set(n_genetics * genetics_a, n_genetics * n_genetics); void episodic_self( simulated_being * local, being_episodic_event_type event, AFFECT_TYPE affect, n_byte2 arg); void episodic_close( simulated_being * local, simulated_being * other, being_episodic_event_type event, AFFECT_TYPE affect, n_byte2 arg); n_byte being_los_projection(simulated_being * local, n_vect2 * extern_end); #ifdef BRAIN_ON n_byte * being_brain(simulated_being * value); #endif simulated_iepisodic * being_episodic(simulated_being * value); simulated_isocial * being_social(simulated_being * value); n_int being_brainstates(simulated_being * value, n_int awake, n_byte2 * states); n_byte being_honor(simulated_being * value); void being_honor_delta(simulated_being * value, n_int delta); n_byte being_first_name(simulated_being * value); void being_set_family_name(simulated_being * value, n_byte first, n_byte last); n_byte being_family_first_name(simulated_being * value); n_byte being_family_second_name(simulated_being * value); n_byte2 being_gender_name(simulated_being * value); n_byte2 being_family_name(simulated_being * value); void being_name_simple(simulated_being * value, n_string str); n_byte being_posture(simulated_being * value); void being_set_posture(simulated_being * value, n_byte post); n_int being_location_x(simulated_being * value); n_int being_location_y(simulated_being * value); n_byte2 * being_location(simulated_being * value); void being_set_location(simulated_being * value, n_byte2 * from); #ifdef DEBUG_LACK_OF_MOVEMENT n_int being_total_movement(simulated_being * value); void being_add_total_movement(simulated_being * value); void being_zero_total_movement(simulated_being * value); void being_register_movement(simulated_being * value, n_string comment_string); #endif n_int being_dob(simulated_being * value); n_byte being_speed(simulated_being * value); void being_set_speed(simulated_being * value, n_byte sp); void being_facing_vector(simulated_being * value, n_vect2 * vect, n_int divisor); n_byte being_facing(simulated_being * value); void being_wander(simulated_being * value, n_int wander); n_genetics * being_genetics(simulated_being * value); n_int being_energy(simulated_being * value); void being_dead(simulated_being * value); void being_energy_delta(simulated_being * value, n_int delta); n_int being_parasites(simulated_being * value); void being_set_parasites(simulated_being * value, n_byte parasites); void being_add_parasites(simulated_being * value); void being_remove_parasites(simulated_being * value, n_int number_of_parasites); n_byte being_drive(simulated_being * value, enum drives_definition drive); n_int being_height(simulated_being * value); void being_set_height(simulated_being * value, n_int height); n_int being_mass(simulated_being * value); typedef struct { n_int max_shout_volume; simulated_being * local; } being_listen_struct; void being_listen(simulated_group * group, simulated_being * local, void * data); void being_listen_loop_no_sim(simulated_being * other, void * data); #ifdef BRAINCODE_ON n_byte * being_braincode_external(simulated_being * value); n_byte * being_braincode_internal(simulated_being * value); #endif void being_remove_external_set(n_int value); n_int being_remove_internal(void); void being_remove_internal_clear(void); void metabolism_vascular_description(n_int index, n_string description); n_string metabolism_description(n_int index); n_int metabolism_vascular_radius(simulated_being * local_being, n_int vessel_index); void being_name_byte2(n_byte2 first, n_byte2 family, n_string name); n_int being_init(simulated_being * beings, n_int number, simulated_being * local, simulated_being * mother, n_byte2* random_factor); n_uint being_init_group(simulated_being * beings, n_byte2 * local_random, n_uint count_to, n_uint max); void being_erase(simulated_being * value); n_uint being_affect(simulated_being * local, n_byte is_positive); void episodic_cycle(simulated_group * group, simulated_being * local, void * data); void episodic_cycle_no_sim(simulated_being * local_being, void * data); void being_cycle_awake(simulated_group * group, simulated_being * local); void being_cycle_universal(simulated_being * local); typedef struct { n_int beings_in_vacinity; simulated_being * being; } drives_sociability_data; void drives_sociability_loop_no_sim(simulated_being * other, void * data); void drives_cycle(simulated_group * group, simulated_being * local_being, void * data); void drives_fatigue(simulated_being * local); void drives_hunger(simulated_being * local); void being_state_description(n_byte2 state, n_string result); void being_set_state(simulated_being * value, being_state_type state); void being_add_state(simulated_being * value, being_state_type state); n_byte2 being_state(simulated_being * value); n_byte2 being_random(simulated_being * value); void being_set_goal_mate(simulated_being * local, n_byte2 first_name, n_byte2 family_name); void being_set_goal_none(simulated_being * local); void being_set_goal_location(simulated_being * local, n_byte2 lx, n_byte2 ly); n_int being_check_goal(simulated_being * local, goal_types goal); void being_goal_cycle(simulated_being * local); void being_set_select_name(simulated_group * group, n_string name); n_string being_get_select_name(simulated_group * group); n_int being_name_comparison(simulated_being * value, n_byte2 gender_name, n_byte2 family_name); void social_graph_link_name( simulated_group * group, simulated_being * local_being, n_int social_graph_index, n_byte met, n_string name); n_int episodic_first_person_memories_percent( simulated_being * local, n_byte intention); void being_immune_transmit(simulated_being * meeter_being, simulated_being * met_being, n_byte transmission_type); void body_genome(n_byte maternal, n_genetics * genome, n_byte * genome_str); void being_relationship_description(n_int index, n_string description); n_string being_body_inventory_description(n_int index); void brain_dialogue( simulated_group * group, n_byte awake, simulated_being * meeter_being, simulated_being * met_being, n_byte * bc0, n_byte * bc1, n_int being_index); simulated_being * being_from_name(simulated_group * group, n_string name); void being_remove(simulated_group * group); void brain_three_byte_command(n_string string, n_byte * response); void brain_sentence(n_string string, n_byte * response); n_int episode_description(simulated_being * local_being, n_int index, n_string description); void episodic_logging(n_console_output * output_function, n_int social); n_uint social_respect_mean(simulated_being *local_being); void social_goals(simulated_being * local); void being_genetic_wandering(simulated_being * local, being_nearest * nearest); void being_territory_index(simulated_being * local); void being_calculate_speed(simulated_being * local, n_int tmp_speed, n_byte2 loc_state); simulated_being * being_find_name(simulated_group * group, n_byte2 first_gender, n_byte2 family); void being_move(simulated_being * local, n_int vel, n_byte kind); n_byte being_awake(simulated_being * local); n_byte being_crowding(simulated_being * value); void being_crowding_cycle(simulated_being * value, n_int beings_in_vacinity); void speak_out(n_string filename, n_string paragraph); void social_conception(simulated_being * female, simulated_being * male, simulated_group * group); void social_initial_loop(simulated_group * group, simulated_being * local_being, void * data); void social_secondary_loop_no_sim(simulated_being * local_being, void * data); void being_tidy_loop_no_sim(simulated_being * local_being, void * data); void being_recalibrate_honor_loop_no_sim(simulated_being * value, void * data); void being_remove_loop1(simulated_group * group, simulated_being * local_being, void * data); typedef struct { simulated_being * being_count; simulated_being * reference; n_int selected_died; n_uint count; } being_remove_loop2_struct; void being_remove_loop2(simulated_group * group, simulated_being * local, void * data); being_remove_loop2_struct * being_remove_initial(simulated_group * group); void being_remains_init(simulated_remains * remains); n_int being_index(simulated_group * group, simulated_being * local); void being_high_res(simulated_being * value, n_vect2 * vector); void being_space(simulated_being * value, n_vect2 * vector); void being_clear_attention(simulated_being * value); void being_set_attention(simulated_being * value, n_int index, n_int attention); n_byte being_attention(simulated_being * value, n_int index); n_byte being_basic_line_of_sight(simulated_being * local, n_vect2 * extern_end, n_vect2 * start, n_vect2 * delta, n_vect2 * end); typedef n_byte (simulated_being_can_move)(n_vect2 * location, n_vect2 * delta); void being_can_move_override(simulated_being_can_move * new_can_move); n_byte being_can_move(n_vect2 * location, n_vect2 * delta); typedef void (simulated_being_wrap)(n_vect2 * location); void being_wrap_override(simulated_being_wrap * new_move); void being_wrap(n_vect2 * location); typedef void (simulated_being_initial_location)(n_vect2 * location, n_byte2 * seed); void being_initial_location_override(simulated_being_initial_location * new_initial_location); void being_initial_location(n_vect2 * location, n_byte2 * seed); typedef n_byte (simulated_being_line_of_sight)(simulated_being * local, n_vect2 * location); void being_line_of_sight_override(simulated_being_line_of_sight * new_line_of_sight); n_byte being_line_of_sight(simulated_being * local, n_vect2 * location); typedef void (simulated_being_brain_cycle)(n_byte * local, n_byte2 * constants); void being_brain_cycle_override(simulated_being_brain_cycle * new_brain_cycle); void being_brain_cycle(n_byte * local, n_byte2 * constants); void being_immune_response(simulated_being * local); void being_reset_drive(simulated_being * value, enum drives_definition drive); n_uint being_genetic_comparison(n_genetics * primary, n_genetics * secondary, n_int parse_requirements); n_int being_move_energy(simulated_being * local_being, n_int * conductance); #endif /* SIMULATEDAPE_ENTITY_H */ <|start_filename|>test/test_io.c<|end_filename|> /**************************************************************** test_io.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of Tom Barbalet, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /* this doesn't currently work, it is included here for unit testing in the future */ #include "../toolkit/toolkit.h" #include <stdio.h> #include <time.h> typedef struct { n_byte2 location[2]; n_byte direction_facing; n_byte velocity; n_byte2 stored_energy; n_byte2 date_of_birth[2]; n_byte2 seed[2]; n_byte2 macro_state; n_byte2 brain_state[6]; n_byte2 height; n_byte2 mass; n_byte2 script_overrides; } test_being; #define FIL_BEI (0x30) n_int draw_error(n_constant_string error_text, n_constant_string location, n_int line_number) { if (error_text) { printf("ERROR: %s @ %s %ld\n", (n_constant_string)error_text, location, line_number); } return -1; } static const simulated_file_entry test_file_format[]= { {"being{", FIL_BEI, 0, 0, "Being Definition"}, {"locat=", FIL_BEI | FILE_TYPE_BYTE2, 2, 0, "Location in x and y coordinates"}, /*n_byte2 x;n_byte2 y;*/ {"facin=", FIL_BEI | FILE_TYPE_BYTE, 1, 4, "Direction facing"}, /*n_byte facing;*/ {"speed=", FIL_BEI | FILE_TYPE_BYTE, 1, 5, "Speed traveling"}, /*n_byte speed;*/ {"energ=", FIL_BEI | FILE_TYPE_BYTE2, 1, 6, "Energy within"}, /*n_byte2 energy;*/ {"datob=", FIL_BEI | FILE_TYPE_BYTE2, 2, 8, "Date of birth in days and millenia"}, /*n_byte2 date_of_birth[2];*/ {"rando=", FIL_BEI | FILE_TYPE_BYTE2, 2, 12,"Random within"}, /*n_byte2 seed[2];*/ {"state=", FIL_BEI | FILE_TYPE_BYTE2, 1, 16,"State description"}, /*n_byte2 state;*/ {"brast=", FIL_BEI | FILE_TYPE_BYTE2, 6, 18,"Brain state values"}, /*n_byte2 brain_state[6];*/ {"heigt=", FIL_BEI | FILE_TYPE_BYTE2, 1, 30, "Height"}, /*n_byte2 height;*/ {"masss=", FIL_BEI | FILE_TYPE_BYTE2, 1, 32, "Mass"}, /*n_byte2 mass;*/ {"overr=", FIL_BEI | FILE_TYPE_BYTE2, 1, 34, "ApeScript overrides"}, {{0, 0, 0, 0, 0, 0, 0},0, 0, 0, 0L} }; static void test_pad_with_noise(n_uint random, test_being * value) { n_byte2 randomizer[2]; const n_uint sizeof_buffer = sizeof(test_being); n_byte * byte_pack = (n_byte *)value; n_uint loop = 0; randomizer[0] = random & 0x0000ffff; randomizer[1] = (random >> 16) & 0x0000ffff; while(loop < sizeof_buffer) { byte_pack[loop] = math_random(randomizer) & 255; loop++; } } static void test_file_write(n_string file_name, n_uint random, n_byte4 * hash) { test_being check_being; n_file * output_file = io_file_new(); test_pad_with_noise(random, &check_being); io_write_buff(output_file, &check_being, test_file_format, FIL_BEI, 0L); io_disk_write(output_file, file_name); io_file_free(&output_file); if (hash) { *hash = math_hash((n_byte*)&check_being, sizeof(test_being)); } } static n_int test_file_read(n_string file_name, n_byte4 * hash) { test_being check_being; n_file * input_file = io_file_new(); io_disk_read(input_file, file_name); io_whitespace(input_file); input_file->location = 0; if (io_read_buff(input_file, (n_byte *)&check_being, test_file_format) != FIL_BEI) { io_file_free(&input_file); return SHOW_ERROR("Wrong filetype found"); } io_file_free(&input_file); if (hash) { *hash = math_hash((n_byte*)&check_being, sizeof(test_being)); } return 0; } static void check_io(void) { n_byte4 hash_write = 0; n_byte4 hash_read = 0; n_int actual_value = 1; n_int decimal_divisor = 1; n_int error_number = io_number("-9223372036854775808", &actual_value, &decimal_divisor); printf("characters %ld number %ld, decimal %ld\n",error_number, actual_value, decimal_divisor); error_number = io_number("9223372036854775807", &actual_value, &decimal_divisor); printf("characters %ld number %ld, decimal %ld\n",error_number, actual_value, decimal_divisor); error_number = io_number("-9223372036854775809", &actual_value, &decimal_divisor); printf("characters %ld number %ld, decimal %ld\n",error_number, actual_value, decimal_divisor); error_number = io_number("9223372036854775808", &actual_value, &decimal_divisor); printf("characters %ld number %ld, decimal %ld\n",error_number, actual_value, decimal_divisor); error_number = io_number("-92233.72036854775808", &actual_value, &decimal_divisor); printf("characters %ld number %ld, decimal %ld\n",error_number, actual_value, decimal_divisor); error_number = io_number("92.23372036854775807", &actual_value, &decimal_divisor); printf("characters %ld number %ld, decimal %ld\n",error_number, actual_value, decimal_divisor); test_file_write("compare_file.txt", 0xf7283da, &hash_write); (void)test_file_read("compare_file.txt", &hash_read); if (hash_write != hash_read) { SHOW_ERROR("Read/write not equal"); } } int main(int argc, const char * argv[]) { printf(" --- test io --- start ------------------------------------------------\n"); check_io(); printf(" --- test io --- end ------------------------------------------------\n"); return 0; } <|start_filename|>entity/speak.c<|end_filename|> /**************************************************************** speak.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #define _CRT_SECURE_NO_WARNINGS /** working on the real solution */ #include <stdio.h> #include <stdlib.h> #include "entity.h" #include "entity_internal.h" /** the sound lengths vary from: (8k) 0.185 sec to (16k) 0.371 sec to (32k) 0.743 sec these can contain sounds or pauses */ static n_audio output[AUDIO_FFT_MAX_BUFFER]; static n_uint speak_length(n_byte character) { switch (character) { case 'a': case 'e': case 'i': case 'o': return 1; case 'p': case 'b': case 'j': case 't': return 0; default: return 2; } } static n_uint speak_length_total(n_string paragraph) { n_int loop = 0; n_int character; n_int length = 0; do { character = paragraph[loop++]; if (character != '\n' && character != 0) { length += 1 << speak_length((n_byte)character); } } while (character != '\n' && character != 0); return (n_uint)length; } static const n_int set_frequencies[24] = { 175,178,180,183, 185,188,191,193, 196,199,202,205, 208,211,214,217, 220,223,227,229, 233,237,240,244 }; static const n_int vowel_reorder[8] = { 4, 7, 0, 2, 1, 6, 3, 5 }; static const n_int consonant_reorder[16] = { 6, 13, 3, 7, 0, 14, 1, 12, 9, 11, 2, 15, 4, 10, 5, 8 }; static const n_int low_freq[13]= { 60000, 45000, 30000, 55000, 30000, 40000, 35000, 60000, 40000, 20000, 65000, 40000, 30000 }; static void speak_freq(n_int * high, n_int * low, n_byte value) { const n_string character_building = "aeiovfstpbjm"; n_int loop = 0; do { if (value != character_building[loop]) { loop++; } } while ((loop<12) && (value != character_building[loop])); if (loop < 12) { low[1] = low_freq[loop ]; low[0] = 1; low[3] = low_freq[loop+1]; low[2] = 2; if (loop < 4) /**< vowel */ { high[0] = set_frequencies[vowel_reorder[loop]]; high[1] = 600000; high[2] = set_frequencies[vowel_reorder[loop+1]]; high[3] = 300000; high[4] = set_frequencies[vowel_reorder[loop+2]+2]; high[5] = 200000; high[6] = set_frequencies[vowel_reorder[loop+4]+3]; high[7] = 50000; } else /**< consonant */ { high[0] = set_frequencies[consonant_reorder[loop-4]]; high[1] = 600000; high[2] = set_frequencies[consonant_reorder[loop-2]+3]; high[3] = 400000; high[4] = set_frequencies[consonant_reorder[loop+1]+8]; high[5] = 100000; high[6] = set_frequencies[consonant_reorder[loop+3]+8]; high[7] = 50000; } } else { low[0] = 0; low[1] = 0; low[2] = 0; low[3] = 0; high[0] = 0; high[1] = 0; high[2] = 0; high[3] = 0; high[4] = 0; high[5] = 0; high[6] = 0; high[7] = 0; } } void speak_out(n_string filename, n_string paragraph) { FILE *out_file = 0L; n_uint total_length = AUDIO_FFT_MAX_BUFFER * speak_length_total(paragraph) >> 2; n_int loop = 0; n_byte found_character; if (total_length < 1) { (void)SHOW_ERROR("Speaking length is less than one"); return; } out_file = fopen(filename,"w"); if (out_file == 0L) { (void)SHOW_ERROR("Failed create speak file!"); return; } audio_aiff_header(out_file, total_length); do { n_uint power_sample = (speak_length(found_character = (n_byte)paragraph[loop++]) + AUDIO_FFT_MAX_BITS - 2); n_uint length = 1 << power_sample; n_int division = AUDIO_FFT_MAX_BUFFER / length; audio_clear_buffers(length); if (found_character != '\n' && found_character != 0) { if (found_character !=' ' && found_character != '.') { n_int local_high[8], local_low[4]; speak_freq(local_high, local_low,found_character); audio_set_frequency((n_uint)(local_high[0]/division), (n_uint)(local_high[1]/division)); audio_set_frequency((n_uint)(local_high[2]/division), (n_uint)(local_high[3]/division)); audio_set_frequency((n_uint)(local_high[4]/division), (n_uint)(local_high[5]/division)); audio_set_frequency((n_uint)(local_high[6]/division), (n_uint)(local_high[7]/division)); audio_fft(1, power_sample); audio_equal_output(output, length); audio_clear_buffers(length); audio_set_frequency((n_uint)(local_low[0]), (n_uint)(local_low[1]/division)); audio_set_frequency((n_uint)(local_low[2]), (n_uint)(local_low[3]/division)); audio_fft(1, power_sample); audio_multiply_output(output, length); } else { audio_clear_output(output, length); } audio_aiff_body(out_file, output, length); } } while (found_character != '\n' && found_character != 0); if (fclose(out_file) != 0) { (void)SHOW_ERROR("Failed to close speak file"); } return; } <|start_filename|>test/example3c.json<|end_filename|> {"general_variables":[{"agent":"yellow","here":"right now"},{"agent":"blue","here":"later","square":[1,2,3,4,5,6,7]}],"general_variables2":["a","a","a","a","b","a"],"end":"yo"} <|start_filename|>toolkit/math.c<|end_filename|> /**************************************************************** math.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /*! \file math.c * \brief This covers vector math, the hash/random mathematics, (Newton) square root, the Bresenham's line algorithm, the bilinear interpolation and other abstract math that is used in Simulated Ape. */ #include "toolkit.h" /** This is used to produce a series of steps between two points useful for drawing a line or a line of sight test. @param sx The starting x location. @param sy The starting y location. @param dx The distance to be traveled in the x direction. @param dy The distance to be traveled in the y direction. @param draw The generic draw function used to traverse the line points. @return This is 0 if the line draw is completed successfully and 1 if it exits through the generic draw function's request. */ n_byte math_join(n_int sx, n_int sy, n_int dx, n_int dy, n_join * draw) { n_int px = sx; n_int py = sy; n_pixel * local_draw; void * local_info; NA_ASSERT(draw, "draw NULL"); if (draw == 0L) return 1; if (draw->pixel_draw == 0L) return 1; local_draw = draw->pixel_draw; local_info = draw->information; NA_ASSERT(local_draw, "local_draw NULL"); NA_ASSERT(local_info, "local_info NULL"); if ((*local_draw)(px, py, 0, 0, local_info)) { return 1; } if ((dx == 0) && (dy == 0)) { return 0; } { n_int dxabs = dx; n_int dyabs = dy; n_int sdx = (dxabs != 0); n_int sdy = (dyabs != 0); if (dxabs < 0) { dxabs = 0 - dxabs; sdx = -1; } if (dyabs < 0) { dyabs = 0 - dyabs; sdy = -1; } if (dxabs >= dyabs) { n_int y2 = dxabs >> 1; n_int i = 0; while (i++ < dxabs) { y2 += dyabs; if (y2 >= dxabs) { y2 -= dxabs; py += sdy; } px += sdx; if ((*local_draw)(px, py, sdx, sdy, local_info)) return 1; } } else { n_int x2 = dyabs >> 1; n_int i = 0; while (i++ < dyabs) { x2 += dxabs; if (x2 >= dyabs) { x2 -= dyabs; px += sdx; } py += sdy; if ((*local_draw)(px, py, sdx, sdy, local_info)) return 1; } } } return 0; } n_byte math_join_vect2(n_int sx, n_int sy, n_vect2 * vect, n_join * draw) { return math_join(sx, sy, vect->x, vect->y, draw); } n_byte math_line_vect(n_vect2 * point1, n_vect2 * point2, n_join * draw) { n_vect2 delta; vect2_subtract(&delta, point2, point1); return math_join(point1->x, point1->y, delta.x, delta.y, draw); } n_byte math_line(n_int x1, n_int y1, n_int x2, n_int y2, n_join * draw) { n_int dx = x2 - x1; n_int dy = y2 - y1; return math_join(x1, y1, dx, dy, draw); } n_byte4 math_hash_fnv1(n_constant_string key) { n_byte4 hash = 2166136261; while(*key) hash = (16777619 * hash) ^ (n_byte4)(*key++); return hash; } /** Creates a near-unique integer value from a block of data. This is similar to CRC or other hash methods. @param values The data in byte chunks. @param length The length of the data in bytes. @return The hash value produced. */ n_uint math_hash(n_byte * values, n_uint length) { n_uint loop = 0; n_byte2 round[5]= {0xfa78, 0xfad7, 0x53e7, 0xa728, 0x2c81}; NA_ASSERT(values, "values NULL"); if (sizeof(n_uint) == 8) { n_uint big_round[4]; while( loop < length) { round[0]^=round[4]; round[1]^=values[loop++]; math_random3(round); math_random3(&round[1]); math_random3(&round[2]); math_random3(&round[3]); } big_round[0] = round[0]; big_round[1] = round[1]; big_round[2] = round[2]; big_round[3] = round[3]; return big_round[0] | (big_round[1]<<16) | (big_round[2] << 32) | (big_round[3]<<48); } while(loop<length) { round[1]^=values[loop++]; math_random3(round); } return (n_uint)(round[0] | (round[1]<<16)); } #define NUMBER_TURN_TOWARDS_POINTS 8 /** Calculates the direction location needs to turn to turn towards a vector. @param p The x vector direction. @param fac The current direction facing. @param turn The number of facing angle units that could be turned (it may not be the number of angle units turned). @return The new direction facing value. */ n_byte math_turn_towards(n_vect2 * p, n_byte fac, n_byte turn) { n_int track[NUMBER_TURN_TOWARDS_POINTS] = { 64, 64, 32, 16, 8, 4, 2, 1 }; n_vect2 vector_facing; n_int best_p; n_int best_f = fac; n_int loop = turn; NA_ASSERT(p, "p NULL"); vect2_direction(&vector_facing, best_f, 32); best_p = vect2_dot(p, &vector_facing, 1, 1); while (loop < NUMBER_TURN_TOWARDS_POINTS) { n_int loc_track = track[loop]; n_int loc_f = (best_f + loc_track) & 255; n_int project1; vect2_direction(&vector_facing, loc_f, 32); project1 = vect2_dot(p, &vector_facing, 1, 1); if (project1 > best_p) { best_f = loc_f; best_p = project1; } else { n_int loc_f2 = (best_f + 256 - loc_track) & 255; n_int project2; vect2_direction(&vector_facing, loc_f, 32); project2 = vect2_dot(p, &vector_facing, 1, 1); if (project2 > best_p) { best_f = loc_f2; best_p = project2; } } loop++; } return (n_byte)best_f; } n_int math_spread_byte(n_byte val) { n_int result = (n_int)(val >> 1); if ((val & 1) == 1) { result = 0 - result; } return result; } #ifdef DEBUG_RANDOM n_uint debug_random_count = 0; void math_random_debug_count(n_string string) { printf("debug random count (%s) %ld\n", string, debug_random_count); } #endif /** Generates a random number from two change-able two-byte random number values passed into the function in the form of a pointer. @param local The pointer leading to both the two-byte numbers used to seed (and change in the process). @return The two-byte random number produced. */ #ifdef DEBUG_RANDOM n_byte2 math_random_debug(n_byte2 * local, n_string file_string, n_int line_number) #else n_byte2 math_random(n_byte2 * local) #endif { n_byte2 tmp0; n_byte2 tmp1; tmp0 = local[0]; tmp1 = local[1]; local[0] = tmp1; switch (tmp0 & 7) { case 0: local[1] = (unsigned short)(tmp1 ^ (tmp0 >> 1) ^ 0xd028); break; case 4: local[1] = (unsigned short)(tmp1 ^ (tmp0 >> 2) ^ 0xae08); break; case 8: local[1] = (unsigned short)(tmp1 ^ (tmp0 >> 3) ^ 0x6320); break; default: local[1] = (unsigned short)(tmp1 ^ (tmp0 >> 1)); break; } #ifdef DEBUG_RANDOM #ifdef VERBOSE_DEBUG_RANDOM if ((debug_random_count & 15) == 0) { printf("\n(%ld %s %ld) %d ", debug_random_count++, file_string, line_number, tmp1); } else { printf(" %d ", tmp1); } #endif debug_random_count++; #endif return (tmp1); } #ifndef DEBUG_RANDOM void math_random3(n_byte2 * local) { NA_ASSERT(local, "local NULL"); (void)math_random(local); (void)math_random(local); (void)math_random(local); } #endif /* math_newton_root may need to be obsoleted */ n_uint math_root(n_uint input) { n_uint op = input; n_uint res = 0; n_uint one = 1uL << ((sizeof(n_uint) * 8) - 2); /* "one" starts at the highest power of four <= than the argument. */ while (one > op) { one >>= 2; } while (one != 0) { if (op >= res + one) { op = op - (res + one); res = res + 2 * one; } res >>= 1; one >>= 2; } return res; } /* from ASCII 32 - 127, corresponding to the seg14 results */ /* n_byte segment = seg14[ conv[ character_value ]]; */ static const n_byte conv[ 96 ] = { 0, 40, 41, 0, 0, 0, 0, 42, 43, 44, 38, 39, 45, 11, 46, 47, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 48, 49, 0, 50, 0, 51, 0, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 52, 53, 54, 0, 55, 56, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 57, 58, 59, 0, 0 }; /* one bit per segment */ static const n_byte2 seg14[ 60 ] = { 0x0000, 0x3F00, 0x1800, 0x36C0, 0x3CC0, 0x19C0, 0x2DC0, 0x2FC0, 0x3800, 0x3FC0, 0x3DC0, 0x00C0, 0x3BC0, 0x3CA1, 0x2700, 0x3C21, 0x27C0, 0x23C0, 0x2F80, 0x1BC0, 0x2421, 0x1E00, 0x0354, 0x0700, 0x1B06, 0x1B12, 0x3F00, 0x33C0, 0x3F10, 0x33D0, 0x2DC0, 0x2021, 0x1F00, 0x030C, 0x1B18, 0x001E, 0x11E0, 0x240C, 0x00FF, 0x00E1, 0x8001, 0x0101, 0x0001, 0x0014, 0x000A, 0x0008, 0x8000, 0x000C, 0xC000, 0x4008, 0x04C0, 0xA004, 0x2700, 0x0012, 0x3402, 0x0400, 0x0002, 0x244A, 0x0021, 0x2494 }; n_int math_seg14(n_int character) { return seg14[conv[character]]; } static n_int math_max(n_int a, n_int b) { return (a<b)?b:a; } static n_int math_min(n_int a, n_int b) { return !(b<a)?a:b; } /*Given three colinear points p, q, r, the function checks if point q lies on line segment 'pr' */ static n_byte math_on_segment(n_vect2 * p, n_vect2 * q, n_vect2 * r) { if ((q->x <= math_max(p->x, r->x)) && (q->x >= math_min(p->x, r->x)) && (q->y <= math_max(p->y, r->y)) && (q->y >= math_min(p->y, r->y))) return 1; return 0; } /* To find orientation of ordered triplet (p, q, r). The function returns following values 0 --> p, q and r are colinear 1 --> Clockwise 2 --> Counterclockwise */ static n_int math_orientation(n_vect2 * p, n_vect2 * q, n_vect2 * r) { n_int val = ((q->y - p->y) * (r->x - q->x)) - ((q->x - p->x) * (r->y - q->y)); if (val == 0) return 0; /* colinear */ return (val > 0)? 1: 2; /* clock or counterclock wise */ } /* The main function that returns true if line segment 'p1q1' and 'p2q2' intersect. */ n_byte math_do_intersect(n_vect2 * p1, n_vect2 * q1, n_vect2 * p2, n_vect2 * q2) { /* Find the four orientations needed for general and special cases */ n_int o1 = math_orientation(p1, q1, p2); n_int o2 = math_orientation(p1, q1, q2); n_int o3 = math_orientation(p2, q2, p1); n_int o4 = math_orientation(p2, q2, q1); /* General case */ if (o1 != o2 && o3 != o4) return 1; /* Special Cases */ /* p1, q1 and p2 are colinear and p2 lies on segment p1q1 */ if (o1 == 0 && math_on_segment(p1, p2, q1)) return 1; /* p1, q1 and p2 are colinear and q2 lies on segment p1q1 */ if (o2 == 0 && math_on_segment(p1, q2, q1)) return 1; /* p2, q2 and p1 are colinear and p1 lies on segment p2q2 */ if (o3 == 0 && math_on_segment(p2, p1, q2)) return 1; /* p2, q2 and q1 are colinear and q1 lies on segment p2q2 */ if (o4 == 0 && math_on_segment(p2, q1, q2)) return 1; return 0; /* Doesn't fall in any of the above cases */ } <|start_filename|>universe/sim.c<|end_filename|> /**************************************************************** sim.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #define CONSOLE_REQUIRED #define CONSOLE_ONLY #include "../toolkit/toolkit.h" #include "../toolkit/shared.h" #include "../script/script.h" #include "../sim/sim.h" #include "../universe/universe.h" #include "../entity/entity.h" #include <stdio.h> #include "universe_internal.h" #ifndef _WIN32 #include <pthread.h> #endif static variable_string apescript_variable_codes[VARIABLE_MAX]= { /* special "variables" */ "function", "run", "while", "if", /* output only */ "vector_x", "vector_y", "random", "water_level", "biology_area", "biology_height", "biology_water", "biology_moving_sun", "biology_total_sun", "biology_salt", "biology_bush", "biology_grass", "biology_tree", "biology_seaweed", "biology_rockpool", "biology_beach", "biology_insect", "biology_mouse", "biology_parrot", "biology_lizard", "biology_eagle", "biology_output", "hungry", "energy", "location_z", "test_z", "is_visible", "time", "date", "current_being", "number_beings", "location_x", "location_y", "state", "id_number", "date_of_birth", "is_error", "weather", "brain_value", /* special input/output */ /* actual variables start here */ "vector_angle", "facing", "speed", "energy_delta", "honor", "parasites", "height", "first_name", "family_name_one", "family_name_two", "goal_type", "goal_x", "goal_y", "drive_hunger", "drive_social", "drive_fatigue", "drive_sex", "brain_x", "brain_y", "brain_z", "select_being", "test_x", "test_y", "biology_operator", "posture", "preference_mate_height_male", "preference_mate_height_female", "preference_mate_pigment_male", "preference_mate_pigment_female", "preference_mate_hair_male", "preference_mate_hair_female", "preference_mate_frame_male", "preference_mate_frame_female", "preference_groom_male", "preference_groom_female", "preference_anecdote_event", "preference_anecdote_affect", "preference_chat", "attention_actor_index", "attention_episode_index", "attention_body_index", "shout_content", "shout_heard", "shout_counter", "shout_volume", "shout_family_first", "shout_family_last", "social_graph_location_x", "social_graph_location_y", "social_graph_time", "social_graph_date", "social_graph_attraction", "social_graph_fof", "social_graph_familiarity", "social_graph_first_name", "social_graph_family_first", "social_graph_family_last", "memory_location_x", "memory_location_y", "memory_time", "memory_date", "memory_first_name_zero", "memory_family_first_zero", "memory_family_last_zero", "memory_first_name_one", "memory_family_first_one", "memory_family_last_one", "memory_event", "memory_affect", "being" }; n_byte * offbuffer = 0L; /* Twice the minimum number of apes the Simulation will allow to run */ #define MIN_BEINGS 4 static simulated_group group; static simulated_timing timing; static n_interpret *interpret = 0L; static n_int sim_new_progress = 0; static n_int sim_new_run = 0; static n_uint initial_memory_allocated; static n_int sim_desire_output = 0; static n_int sim_writing_output = 0; static n_string_block sim_console_output; void sim_set_output(n_int value) { sim_desire_output = value; } n_int sim_get_writing_output(void) { return sim_writing_output; } n_string sim_output_string(void) { return sim_console_output; } n_int sim_new(void) { return sim_new_progress; } #ifndef _WIN32 static n_int sim_quit_value = 0; static pthread_t threads[2] = {0}; static n_byte threads_running[2] = {0}; n_int sim_thread_console_quit(void) { return sim_quit_value; } n_int sim_new_run_condition(void) { return sim_new_run; } static void sim_console_clean_up(void) { if ((io_command_line_execution() == 0) || sim_quit_value) { return; } sim_quit_value = 1; command_quit(0L,0L,0L); while (command_executing()) {} } static void *sim_thread_posix(void *threadid) { n_byte *local = (n_byte *)threadid; if (io_console(&group, (simulated_console_command *) control_commands, io_console_entry_clean, io_console_out) != 0) { sim_console_clean_up(); } local[0] = 0; pthread_exit(0L); } void sim_thread_console(void) { if (io_command_line_execution() == 0) { return; } if ((threads_running[0] == 0)||(threads_running[1] == 0)) { n_int loop = 0; while (loop < 2) { if (threads_running[loop] == 0) { threads_running[loop] = 1; pthread_create(&threads[loop], 0L, sim_thread_posix, &threads_running[loop]); return; } loop++; } } } #endif void sim_realtime(n_uint time) { timing.real_time = time; } static simulated_being * sim_being_local(void) { simulated_group * group = sim_group(); if (group == 0L) { return 0L; } return group->select; } void sim_move(n_int rel_vel, n_byte kind) { simulated_being * local; if ((local = sim_being_local())) { being_move(local, rel_vel, kind); } } void sim_view_options(n_int px, n_int py) { simulated_being * local; if ((local = sim_being_local())) { n_byte2 location[2]; location[0] = APESPACE_CONFINED(MAPSPACE_TO_APESPACE(px)); location[1] = APESPACE_CONFINED(MAPSPACE_TO_APESPACE(py)); being_set_location(local, location); } } #define MAX_POSSIBLE_CONTROL_CHARACTER_X ((2048 - CHARACTER_WIDTH)/CHARACTER_WIDTH) #define MAX_POSSIBLE_CONTROL_CHARACTER_Y ((2048 - CHARACTER_WIDTH)/CHARACTER_HEIGHT) static n_byte sim_control_string[255 * 40]; static n_int sim_control_string_offset[255]; static n_byte sim_control[MAX_POSSIBLE_CONTROL_CHARACTER_X * MAX_POSSIBLE_CONTROL_CHARACTER_Y]; static n_int sim_control_max_x; static n_byte sim_control_previous_character; static n_byte sim_control_character_location; simulated_timing * sim_timing(void) { return &timing; } simulated_group * sim_group(void) { return &group; } void sim_control_set(n_int px, n_int py, n_byte value, n_byte character, n_int scale) { n_int gen_x = (px * 10) / scale; n_int gen_y = (py * 10) / scale; n_int character_x = (gen_x - CHARACTER_WIDTH) / CHARACTER_WIDTH; if ((character_x > -1) && (character_x < MAX_POSSIBLE_CONTROL_CHARACTER_X)) { n_int character_y = (gen_y - CHARACTER_WIDTH) / CHARACTER_HEIGHT; if ((character_y > -1) && (character_y < MAX_POSSIBLE_CONTROL_CHARACTER_Y)) { sim_control[(character_y * sim_control_max_x) + character_x] = value; if (value != sim_control_previous_character) { if (sim_control_previous_character) { sim_control_string[sim_control_character_location] = 0; sim_control_character_location++; } sim_control_string_offset[sim_control_previous_character] = sim_control_character_location; sim_control_previous_character = value; } sim_control_string[sim_control_character_location] = character; sim_control_character_location++; } } } void sim_control_erase(n_int size_x, n_int size_y, n_int scale) { /*n_int gen_x = (size_x * 10) / scale;*/ n_int gen_y = (size_y * 10) / scale; n_int max_y = (gen_y - CHARACTER_WIDTH) / CHARACTER_HEIGHT; sim_control_max_x = (gen_y - CHARACTER_WIDTH) / CHARACTER_WIDTH; sim_control_previous_character = 0; sim_control_character_location = 0; memory_erase(sim_control, (n_uint)(sim_control_max_x * max_y)); memory_erase(sim_control_string, 255 * 40); } static simulated_being * sim_select_name(n_string name) { n_uint name_hash = math_hash((n_byte *)name, (n_uint)io_length(name, STRING_BLOCK_SIZE)); n_uint loop = 0; simulated_group * group = sim_group(); simulated_being * local_beings = group->beings; while (loop < group->num) { n_uint being_hash; simulated_being * local_being = &local_beings[loop]; n_string_block local_name; being_name_simple(local_being, local_name); being_hash = math_hash((n_byte *)local_name, (n_uint)io_length(local_name, STRING_BLOCK_SIZE)); if (name_hash == being_hash) { return local_being; } loop++; } return 0L; } void sim_control_regular(n_int px, n_int py, n_int scale) { n_int gen_x = (px * 10) / scale; n_int gen_y = (py * 10) / scale; n_int character_x = (gen_x - CHARACTER_WIDTH) / CHARACTER_WIDTH; if ((character_x > -1) && (character_x < MAX_POSSIBLE_CONTROL_CHARACTER_X)) { n_int character_y = (gen_y - CHARACTER_WIDTH) / CHARACTER_HEIGHT; if ((character_y > -1) && (character_y < MAX_POSSIBLE_CONTROL_CHARACTER_Y)) { n_byte value = sim_control[character_x + (character_y*sim_control_max_x)]; if (value) { n_int offset = sim_control_string_offset[value - 1]; n_string contral_name = (n_string)&sim_control_string[offset]; simulated_being * select_being = sim_select_name(contral_name); if (select_being) { sim_set_select(select_being); } } } } } n_int sim_view_regular(n_int px, n_int py) { simulated_being * local; if ((local = sim_being_local())) { simulated_group * group = sim_group(); simulated_being * desired_ape = local; n_uint high_squ = 31; n_uint loop = 0; while (loop < group->num) { simulated_being * current_ape = &(group->beings[loop]); n_int screen_x = APESPACE_TO_MAPSPACE(being_location_x(current_ape)) - px; n_int screen_y = APESPACE_TO_MAPSPACE(being_location_y(current_ape)) - py; n_uint current_squ = (n_uint)((screen_x * screen_x) + (screen_y * screen_y)); if (high_squ > current_squ) { high_squ = current_squ; desired_ape = current_ape; } loop++; } if (local != desired_ape) { sim_set_select(desired_ape); return 0; } return 1; } return 0; } void sim_terrain(n_int sx) { simulated_being * local; if (sx > 0) { if ((local = sim_being_local())) { being_wander(local, 1); } } if (sx <= 0) { if ((local = sim_being_local())) { being_wander(local, -1); } } } void sim_rotate(n_int integer_rotation_256) { simulated_being * local; if ((local = sim_being_local())) { being_wander(local, integer_rotation_256); } } void sim_change_selected(n_byte forwards) { simulated_group * group = sim_group(); if (group) { command_change_selected(group, forwards); } } static n_int sim_input(void *vcode, n_byte kind, n_int value) { n_individual_interpret * code = (n_individual_interpret *)vcode; n_int *local_vr = code->variable_references; simulated_being *local_being = 0L; n_int temp_select = local_vr[ VARIABLE_SELECT_BEING - VARIABLE_VECT_ANGLE ]; if( temp_select < 0 ) { return APESCRIPT_ERROR(code, AE_SELECTED_ENTITY_OUT_OF_RANGE); } { n_uint local_select = (n_uint)temp_select; simulated_group * group = sim_group(); if( local_select >= group->num) { return APESCRIPT_ERROR(code, AE_SELECTED_ENTITY_OUT_OF_RANGE); } local_being = &(group->beings[local_select]); } switch(kind) { case VARIABLE_BRAIN_VALUE: { #ifdef BRAIN_ON n_int current_x = local_vr[VARIABLE_BRAIN_X - VARIABLE_VECT_ANGLE]; n_int current_y = local_vr[VARIABLE_BRAIN_Y - VARIABLE_VECT_ANGLE]; n_int current_z = local_vr[VARIABLE_BRAIN_Z - VARIABLE_VECT_ANGLE]; if((value < 0) || (value > 255)) { return APESCRIPT_ERROR(code, AE_VALUE_OUT_OF_RANGE); } if( (current_x < 0) || (current_y < 0) || (current_z < 0) || (current_x > 31) || (current_y > 31) || (current_z > 31)) { return APESCRIPT_ERROR(code, AE_COORDINATES_OUT_OF_RANGE); } { simulated_being * local_being = (simulated_being *)((n_individual_interpret *)code)->interpret_data; n_byte *local_brain = being_brain(local_being); if (local_brain != 0L) { TRACK_BRAIN(local_brain, current_x, current_y, current_z) = (n_byte) value; } } /* add brain value */ #endif return 0; } case VARIABLE_HONOR: local_being->delta.honor = (n_byte) value; break; case VARIABLE_PARASITES: being_set_parasites(local_being, (n_byte) value); break; case VARIABLE_HEIGHT: being_set_height(local_being, value); break; #if 0 /* TODO: This should not be done */ case VARIABLE_FAMILY_NAME_ONE: being_set_family_name(local_being, UNPACK_FAMILY_FIRST_NAME((n_byte2) value), UNPACK_FAMILY_SECOND_NAME(being_family_name(local_being))); break; case VARIABLE_FAMILY_NAME_TWO: being_set_family_name(local_being, UNPACK_FAMILY_FIRST_NAME(being_family_name(local_being)), UNPACK_FAMILY_SECOND_NAME((n_byte2) value)); break; #endif case VARIABLE_GOAL_TYPE: local_being->delta.goal[0] = (n_byte) (value % 3); break; case VARIABLE_GOAL_X: local_being->delta.goal[1] = (n_byte2) value; break; case VARIABLE_GOAL_Y: local_being->delta.goal[2] = (n_byte2) value; break; case VARIABLE_POSTURE: being_set_posture(local_being, (n_byte) value); break; case VARIABLE_DRIVE_HUNGER: local_being->changes.drives[DRIVE_HUNGER] = (n_byte) value; break; case VARIABLE_DRIVE_SOCIAL: local_being->changes.drives[DRIVE_SOCIAL] = (n_byte) value; break; case VARIABLE_DRIVE_FATIGUE: local_being->changes.drives[DRIVE_FATIGUE] = (n_byte) value; break; case VARIABLE_DRIVE_SEX: local_being->changes.drives[DRIVE_SEX] = (n_byte) value; break; case VARIABLE_PREFERENCE_MATE_HEIGHT_MALE: local_being->changes.learned_preference[PREFERENCE_MATE_HEIGHT_MALE] = (n_byte) value; break; case VARIABLE_PREFERENCE_MATE_HEIGHT_FEMALE: local_being->changes.learned_preference[PREFERENCE_MATE_HEIGHT_FEMALE] = (n_byte) value; break; case VARIABLE_PREFERENCE_MATE_PIGMENTATION_MALE: local_being->changes.learned_preference[PREFERENCE_MATE_PIGMENTATION_MALE] = (n_byte) value; break; case VARIABLE_PREFERENCE_MATE_PIGMENTATION_FEMALE: local_being->changes.learned_preference[PREFERENCE_MATE_PIGMENTATION_FEMALE] = (n_byte) value; break; case VARIABLE_PREFERENCE_MATE_HAIR_MALE: local_being->changes.learned_preference[PREFERENCE_MATE_HAIR_MALE] = (n_byte) value; break; case VARIABLE_PREFERENCE_MATE_HAIR_FEMALE: local_being->changes.learned_preference[PREFERENCE_MATE_HAIR_FEMALE] = (n_byte) value; break; case VARIABLE_PREFERENCE_MATE_FRAME_MALE: local_being->changes.learned_preference[PREFERENCE_MATE_FRAME_MALE] = (n_byte) value; break; case VARIABLE_PREFERENCE_MATE_FRAME_FEMALE: local_being->changes.learned_preference[PREFERENCE_MATE_FRAME_FEMALE] = (n_byte) value; break; case VARIABLE_PREFERENCE_GROOM_MALE: local_being->changes.learned_preference[PREFERENCE_GROOM_MALE] = (n_byte) value; break; case VARIABLE_PREFERENCE_GROOM_FEMALE: local_being->changes.learned_preference[PREFERENCE_GROOM_FEMALE] = (n_byte) value; break; case VARIABLE_PREFERENCE_ANECDOTE_EVENT_MUTATION: local_being->changes.learned_preference[PREFERENCE_ANECDOTE_EVENT_MUTATION] = (n_byte) value; break; case VARIABLE_PREFERENCE_ANECDOTE_AFFECT_MUTATION: local_being->changes.learned_preference[PREFERENCE_ANECDOTE_AFFECT_MUTATION] = (n_byte) value; break; case VARIABLE_PREFERENCE_CHAT: local_being->changes.learned_preference[PREFERENCE_CHAT] = (n_byte) value; break; case VARIABLE_ATTENTION_ACTOR_INDEX: being_set_attention(local_being,ATTENTION_ACTOR, value % SOCIAL_SIZE); break; case VARIABLE_ATTENTION_EPISODE_INDEX: being_set_attention(local_being,ATTENTION_EPISODE, value % EPISODIC_SIZE); break; case VARIABLE_ATTENTION_BODY_INDEX: being_set_attention(local_being,ATTENTION_BODY, value % INVENTORY_SIZE); break; } if (kind>VARIABLE_BRAIN_VALUE) { local_vr[kind-VARIABLE_VECT_ANGLE] = value; return 0; } return -1; /* where this fails is more important than this failure */ } static n_int sim_output(void * vcode, void * vindividual, n_byte * kind, n_int * number) { simulated_group * group = sim_group(); n_interpret * code = (n_interpret *) vcode; n_individual_interpret * individual = (n_individual_interpret *) vindividual; n_byte first_value = kind[0]; n_byte second_value = kind[1]; if(first_value == APESCRIPT_NUMBER) { *number = code->number_buffer[second_value]; return 0; } if((first_value == APESCRIPT_TEXT) && (VARIABLE_SPECIAL(second_value, code) == 0)) { n_int *local_vr = individual->variable_references; if( (second_value >= VARIABLE_BIOLOGY_AREA) && (second_value <= VARIABLE_BIOLOGY_EAGLE)) { *number = second_value - VARIABLE_BIOLOGY_AREA; return 0; } if(second_value>VARIABLE_BRAIN_VALUE) { *number = local_vr[ second_value - VARIABLE_VECT_ANGLE ]; return 0; } { simulated_being * local_current = (simulated_being *)individual->interpret_data; n_int local_number = 0; n_vect2 local_vector; vect2_direction(&local_vector, local_vr[0], 32); switch(second_value) { case VARIABLE_VECT_X: local_number = local_vector.x; break; case VARIABLE_VECT_Y: local_number = local_vector.y; break; case VARIABLE_RANDOM: local_number = being_random(local_current); break; case VARIABLE_WATER_LEVEL: local_number = land_tide_level(); break; case VARIABLE_HUNGRY: local_number = BEING_HUNGRY; break; case VARIABLE_ENERGY: { simulated_being * local_being = (simulated_being *)individual->interpret_data; local_number = being_energy(local_being); } break; case VARIABLE_LOCATION_Z: case VARIABLE_TEST_Z: case VARIABLE_IS_VISIBLE: case VARIABLE_BIOLOGY_OUTPUT: { n_int quick_x; n_int quick_y; if(second_value == VARIABLE_LOCATION_Z) { quick_x = being_location_x(local_current); quick_y = being_location_y(local_current); } else { quick_x = local_vr[VARIABLE_TEST_X-VARIABLE_VECT_ANGLE]; quick_y = local_vr[VARIABLE_TEST_Y-VARIABLE_VECT_ANGLE]; if( (quick_x < 0) || (quick_y < 0) || (quick_x > APESPACE_BOUNDS ) || (quick_y > APESPACE_BOUNDS) ) { return APESCRIPT_ERROR(individual, AE_COORDINATES_OUT_OF_RANGE); } } if ( second_value == VARIABLE_IS_VISIBLE ) { /* range already checked */ simulated_being * local_being = (simulated_being *)individual->interpret_data; n_vect2 location; location.x = (n_byte2)quick_x; location.y = (n_byte2)quick_y; local_number = being_line_of_sight(local_being, &location); } else { if(second_value == VARIABLE_BIOLOGY_OUTPUT) { n_int int_qu_op = local_vr[VARIABLE_BIOLOGY_OPERATOR-VARIABLE_VECT_ANGLE]; if((int_qu_op < 0 ) || (int_qu_op > (VARIABLE_BIOLOGY_EAGLE - VARIABLE_BIOLOGY_AREA))) { return APESCRIPT_ERROR(individual, AE_VALUE_OUT_OF_RANGE); } local_number = land_operator_interpolated( (n_byte)quick_x, (n_byte)quick_y, (n_byte*)&operators[int_qu_op-VARIABLE_BIOLOGY_AREA]); } else { local_number = land_location(quick_x, quick_y); } } } break; case VARIABLE_TIME: local_number = land_time(); break; case VARIABLE_DATE: local_number = land_date(); break; case VARIABLE_CURRENT_BEING: local_number = being_index(group, (simulated_being *)individual->interpret_data); break; case VARIABLE_NUMBER_BEINGS: local_number = (n_int)group->num; break; case VARIABLE_IS_ERROR: local_number = -1; break; case VARIABLE_WEATHER: { n_int quick_x; n_int quick_y; quick_x = local_vr[VARIABLE_TEST_X-VARIABLE_VECT_ANGLE]; quick_y = local_vr[VARIABLE_TEST_Y-VARIABLE_VECT_ANGLE]; if( (quick_x < 0) || (quick_y < 0) || (quick_x > APESPACE_BOUNDS ) || (quick_y > APESPACE_BOUNDS) ) { return APESCRIPT_ERROR(individual, AE_COORDINATES_OUT_OF_RANGE); } local_number = weather_seven_values(quick_x, quick_y); } break; case VARIABLE_BRAIN_VALUE: { #ifdef BRAIN_ON n_int current_x = local_vr[VARIABLE_BRAIN_X - VARIABLE_VECT_ANGLE]; n_int current_y = local_vr[VARIABLE_BRAIN_Y - VARIABLE_VECT_ANGLE]; n_int current_z = local_vr[VARIABLE_BRAIN_Z - VARIABLE_VECT_ANGLE]; if( (current_x < 0) || (current_y < 0) || (current_z < 0) || (current_x > 31) || (current_y > 31) || (current_z > 31)) { return APESCRIPT_ERROR(individual, AE_COORDINATES_OUT_OF_RANGE); } { simulated_being * local_being = (simulated_being *)individual->interpret_data; n_byte *local_brain = being_brain(local_being); if (local_brain != 0L) { local_number = TRACK_BRAIN(local_brain, current_x, current_y, current_z); } } #endif } break; default: { n_int temp_select = local_vr[ VARIABLE_SELECT_BEING - VARIABLE_VECT_ANGLE ]; simulated_being *local_being = 0L; simulated_isocial *local_social_graph = 0L; simulated_isocial social_graph; n_vect2 location_vect; #ifdef EPISODIC_ON simulated_iepisodic *local_episodic = 0L; simulated_iepisodic episodic; #endif if( temp_select < 0 ) { return APESCRIPT_ERROR(individual, AE_SELECTED_ENTITY_OUT_OF_RANGE); } { n_uint local_select = (n_uint)temp_select; if( local_select >= group->num) { return APESCRIPT_ERROR(individual, AE_SELECTED_ENTITY_OUT_OF_RANGE); } local_being = &(group->beings[local_select]); if (local_being != 0L) { local_social_graph = being_social(local_being); if (local_social_graph!=0L) { social_graph = local_social_graph[being_attention(local_being,ATTENTION_ACTOR)]; } #ifdef EPISODIC_ON local_episodic = being_episodic(local_being); if (local_episodic != 0L) { episodic = local_episodic[being_attention(local_being,ATTENTION_EPISODE)]; } #endif } } /* TODO: if the being knows the other being it may be possible to guess some of these */ /* if the current being can't see the other being, it can't get this information */ being_space(local_being, &location_vect); if (being_line_of_sight(local_current, &location_vect) == 0) { local_number = -1; } else if ((local_being != 0L) && (local_social_graph != 0L)) { switch(second_value) { case VARIABLE_HONOR: local_number = being_honor(local_being); break; case VARIABLE_PARASITES: local_number = being_parasites(local_being); break; case VARIABLE_HEIGHT: local_number = being_height(local_being); break; case VARIABLE_FIRST_NAME: local_number = being_gender_name(local_being); break; #if 0 /* TODO: This should not be done */ case VARIABLE_FAMILY_NAME_ONE: local_number = UNPACK_FAMILY_FIRST_NAME(being_family_name(local_being)); break; case VARIABLE_FAMILY_NAME_TWO: local_number = UNPACK_FAMILY_SECOND_NAME(being_family_name(local_being)); break; #endif case VARIABLE_GOAL_TYPE: local_number = local_being->delta.goal[0]; break; case VARIABLE_GOAL_X: local_number = local_being->delta.goal[1]; break; case VARIABLE_GOAL_Y: local_number = local_being->delta.goal[2]; break; case VARIABLE_POSTURE: local_number = being_posture(local_being); break; case VARIABLE_DRIVE_HUNGER: local_number = local_being->changes.drives[DRIVE_HUNGER]; break; case VARIABLE_DRIVE_SOCIAL: local_number = local_being->changes.drives[DRIVE_SOCIAL]; break; case VARIABLE_DRIVE_FATIGUE: local_number = local_being->changes.drives[DRIVE_FATIGUE]; break; case VARIABLE_DRIVE_SEX: local_number = local_being->changes.drives[DRIVE_SEX]; break; case VARIABLE_LOCATION_X: local_number = being_location_x(local_being); break; case VARIABLE_LOCATION_Y: local_number = being_location_y(local_being); break; case VARIABLE_ID_NUMBER: local_number = GET_I(local_being); break; case VARIABLE_DATE_OF_BIRTH: local_number = being_dob(local_being); break; case VARIABLE_STATE: local_number = being_state(local_being); break; case VARIABLE_PREFERENCE_MATE_HEIGHT_MALE: local_number = local_being->changes.learned_preference[PREFERENCE_MATE_HEIGHT_MALE]; break; case VARIABLE_PREFERENCE_MATE_HEIGHT_FEMALE: local_number = local_being->changes.learned_preference[PREFERENCE_MATE_HEIGHT_FEMALE]; break; case VARIABLE_PREFERENCE_MATE_PIGMENTATION_MALE: local_number = local_being->changes.learned_preference[PREFERENCE_MATE_PIGMENTATION_MALE]; break; case VARIABLE_PREFERENCE_MATE_PIGMENTATION_FEMALE: local_number = local_being->changes.learned_preference[PREFERENCE_MATE_PIGMENTATION_FEMALE]; break; case VARIABLE_PREFERENCE_MATE_HAIR_MALE: local_number = local_being->changes.learned_preference[PREFERENCE_MATE_HAIR_MALE]; break; case VARIABLE_PREFERENCE_MATE_HAIR_FEMALE: local_number = local_being->changes.learned_preference[PREFERENCE_MATE_HAIR_FEMALE]; break; case VARIABLE_PREFERENCE_MATE_FRAME_MALE: local_number = local_being->changes.learned_preference[PREFERENCE_MATE_FRAME_MALE]; break; case VARIABLE_PREFERENCE_MATE_FRAME_FEMALE: local_number = local_being->changes.learned_preference[PREFERENCE_MATE_FRAME_FEMALE]; break; case VARIABLE_PREFERENCE_GROOM_MALE: local_number = local_being->changes.learned_preference[PREFERENCE_GROOM_MALE]; break; case VARIABLE_PREFERENCE_GROOM_FEMALE: local_number = local_being->changes.learned_preference[PREFERENCE_GROOM_FEMALE]; break; case VARIABLE_PREFERENCE_ANECDOTE_EVENT_MUTATION: local_number = local_being->changes.learned_preference[PREFERENCE_ANECDOTE_EVENT_MUTATION]; break; case VARIABLE_PREFERENCE_ANECDOTE_AFFECT_MUTATION: local_number = local_being->changes.learned_preference[PREFERENCE_ANECDOTE_AFFECT_MUTATION]; break; case VARIABLE_PREFERENCE_CHAT: local_number = local_being->changes.learned_preference[PREFERENCE_CHAT]; break; case VARIABLE_ATTENTION_ACTOR_INDEX: local_number = being_attention(local_being,ATTENTION_ACTOR); break; case VARIABLE_ATTENTION_EPISODE_INDEX: local_number = being_attention(local_being,ATTENTION_EPISODE); break; case VARIABLE_ATTENTION_BODY_INDEX: local_number = being_attention(local_being,ATTENTION_BODY); break; case VARIABLE_SHOUT_CONTENT: local_number = local_being->changes.shout[SHOUT_CONTENT]; break; case VARIABLE_SHOUT_HEARD: local_number = local_being->changes.shout[SHOUT_HEARD]; break; case VARIABLE_SHOUT_CTR: local_number = local_being->changes.shout[SHOUT_CTR]; break; case VARIABLE_SHOUT_VOLUME: local_number = local_being->changes.shout[SHOUT_VOLUME]; break; case VARIABLE_SHOUT_FAMILY0: local_number = local_being->changes.shout[SHOUT_FAMILY0]; break; case VARIABLE_SHOUT_FAMILY1: local_number = local_being->changes.shout[SHOUT_FAMILY1]; break; case VARIABLE_SOCIAL_GRAPH_LOCATION_X: local_number = social_graph.space_time.location[0]; break; case VARIABLE_SOCIAL_GRAPH_LOCATION_Y: local_number = social_graph.space_time.location[1]; break; case VARIABLE_SOCIAL_GRAPH_TIME: local_number = social_graph.space_time.time; break; case VARIABLE_SOCIAL_GRAPH_DATE: local_number = social_graph.space_time.date; break; case VARIABLE_SOCIAL_GRAPH_ATTRACTION: local_number = social_graph.attraction; break; case VARIABLE_SOCIAL_GRAPH_FOF: local_number = (n_int)social_graph.friend_foe - (n_int)social_respect_mean(local_being); break; case VARIABLE_SOCIAL_GRAPH_FAMILIARITY: local_number = social_graph.familiarity; break; case VARIABLE_MEMORY_FIRST_NAME: local_number = social_graph.first_name[BEING_MET]; break; #if 0 /* TODO: This should not be done */ case VARIABLE_MEMORY_FAMILY_NAME_ONE: local_number = UNPACK_FAMILY_FIRST_NAME(social_graph.family_name[BEING_MET]); break; case VARIABLE_MEMORY_FAMILY_NAME_TWO: local_number = UNPACK_FAMILY_SECOND_NAME(social_graph.family_name[BEING_MET]); break; #endif #ifdef EPISODIC_ON case VARIABLE_MEMORY_LOCATION_X: local_number = episodic.space_time.location[0]; break; case VARIABLE_MEMORY_LOCATION_Y: local_number = episodic.space_time.location[1]; break; case VARIABLE_MEMORY_TIME: local_number = episodic.space_time.time; break; case VARIABLE_MEMORY_DATE: local_number = episodic.space_time.date; break; case VARIABLE_MEMORY_FIRST_NAME0: local_number = episodic.first_name[0]; break; case VARIABLE_MEMORY_FIRST_NAME1: local_number = episodic.first_name[BEING_MET]; break; #if 0 /* TODO: This should not be done */ case VARIABLE_MEMORY_FAMILY_NAME_ONE0: local_number = UNPACK_FAMILY_FIRST_NAME(episodic.family_name[0]); break; case VARIABLE_MEMORY_FAMILY_NAME_TWO0: local_number = UNPACK_FAMILY_SECOND_NAME(episodic.family_name[0]); break; case VARIABLE_MEMORY_FAMILY_NAME_ONE1: local_number = UNPACK_FAMILY_FIRST_NAME(episodic.family_name[BEING_MET]); break; case VARIABLE_MEMORY_FAMILY_NAME_TWO1: local_number = UNPACK_FAMILY_SECOND_NAME(episodic.family_name[BEING_MET]); break; #endif case VARIABLE_MEMORY_EVENT: local_number = episodic.event; break; case VARIABLE_MEMORY_AFFECT: local_number = episodic.affect - EPISODIC_AFFECT_ZERO; break; #endif } } } break; } /* put variable cross here */ *number = local_number; return 0; } } return -1; /* where this fails is more important than this failure */ } n_int sim_interpret(n_file * input_file) { input_file->size = input_file->location; input_file->location = 0; interpret = parse_convert(input_file, VARIABLE_BEING, (variable_string *)apescript_variable_codes); if(interpret == 0L) { return -1; } else { SC_DEBUG_ON(group.select); /* turn on debugging after script loading */ } interpret->sc_input = &sim_input; interpret->sc_output = &sim_output; interpret->input_greater = VARIABLE_WEATHER; interpret->special_less = VARIABLE_VECT_X; return 0; } #ifdef BRAIN_ON static void sim_brain_loop(simulated_group * group, simulated_being * local_being, void * data) { n_byte2 local_brain_state[3]; if(being_brainstates(local_being, (local_being->delta.awake == 0), local_brain_state)) { n_byte *local_brain = being_brain(local_being); if (local_brain != 0L) { being_brain_cycle(local_brain, local_brain_state); } } } #endif #ifdef BRAINCODE_ON static void sim_brain_dialogue_loop(simulated_group * group, simulated_being * local_being, void * data) { n_byte awake = 1; n_byte *local_internal = being_braincode_internal(local_being); n_byte *local_external = being_braincode_external(local_being); if(local_being->delta.awake == 0) { awake=0; } /* This should be independent of the brainstate/cognitive simulation code */ brain_dialogue(group, awake, local_being, local_being, local_internal, local_external, being_random(local_being)%SOCIAL_SIZE); brain_dialogue(group, awake, local_being, local_being, local_external, local_internal, being_random(local_being)%SOCIAL_SIZE); } #endif static void sim_being_awake_loop_no_sim(simulated_being * local_being, void * data) { n_byte awake_condition = being_awake(local_being); local_being->delta.awake = awake_condition; #ifdef DEBUG_LACK_OF_MOVEMENT being_register_movement(local_being, "awake condition"); #endif } static void sim_being_universal_loop_no_sim(simulated_being * local_being, void * data) { being_cycle_universal(local_being); } static void sim_being_cycle(simulated_group * group, simulated_being * local_being, void * data) { if (local_being->delta.awake == 0) return; being_cycle_awake(group, local_being); } static void sim_start_conditions(void * vindividual, void * structure, void * data) { n_individual_interpret * individual = (n_individual_interpret *)vindividual; n_int * variables = individual->variable_references; simulated_being * local_being = (simulated_being*)data; variables[VARIABLE_FACING - VARIABLE_VECT_ANGLE] = being_facing(local_being); variables[VARIABLE_SPEED - VARIABLE_VECT_ANGLE] = being_speed(local_being); variables[VARIABLE_ENERGY_DELTA - VARIABLE_VECT_ANGLE] = 0; variables[VARIABLE_SELECT_BEING - VARIABLE_VECT_ANGLE] = being_index(sim_group(), local_being); variables[VARIABLE_HEIGHT - VARIABLE_VECT_ANGLE] = being_height(local_being); variables[VARIABLE_GOAL_TYPE - VARIABLE_VECT_ANGLE] = local_being->delta.goal[0]; variables[VARIABLE_GOAL_X - VARIABLE_VECT_ANGLE] = local_being->delta.goal[1]; variables[VARIABLE_GOAL_Y - VARIABLE_VECT_ANGLE] = local_being->delta.goal[2]; variables[VARIABLE_DRIVE_HUNGER - VARIABLE_VECT_ANGLE] = local_being->changes.drives[DRIVE_HUNGER]; variables[VARIABLE_DRIVE_SOCIAL - VARIABLE_VECT_ANGLE] = local_being->changes.drives[DRIVE_SOCIAL]; variables[VARIABLE_DRIVE_FATIGUE - VARIABLE_VECT_ANGLE] = local_being->changes.drives[DRIVE_FATIGUE]; variables[VARIABLE_DRIVE_SEX - VARIABLE_VECT_ANGLE] = local_being->changes.drives[DRIVE_SEX]; variables[VARIABLE_FAMILY_NAME_ONE - VARIABLE_VECT_ANGLE] = being_family_first_name(local_being); variables[VARIABLE_FAMILY_NAME_TWO - VARIABLE_VECT_ANGLE] = being_family_second_name(local_being); variables[VARIABLE_HONOR - VARIABLE_VECT_ANGLE] = being_honor(local_being); variables[VARIABLE_PARASITES - VARIABLE_VECT_ANGLE] = being_parasites(local_being); } static void sim_end_conditions(void * vindividual, void * structure, void * data) { n_individual_interpret * individual = (n_individual_interpret *)vindividual; n_int * variables = individual->variable_references; simulated_being * local_being = (simulated_being*)data; n_int local_facing = variables[VARIABLE_FACING - VARIABLE_VECT_ANGLE]; n_int local_speed = variables[VARIABLE_SPEED - VARIABLE_VECT_ANGLE]; n_int local_energy_delta = variables[VARIABLE_ENERGY_DELTA - VARIABLE_VECT_ANGLE]; n_int local_height = variables[VARIABLE_HEIGHT - VARIABLE_VECT_ANGLE]; n_int local_goal_type = variables[VARIABLE_GOAL_TYPE - VARIABLE_VECT_ANGLE]; n_int local_goal_x = variables[VARIABLE_GOAL_X - VARIABLE_VECT_ANGLE]; n_int local_goal_y = variables[VARIABLE_GOAL_Y - VARIABLE_VECT_ANGLE]; n_int local_drive_hunger = variables[VARIABLE_DRIVE_HUNGER - VARIABLE_VECT_ANGLE]; n_int local_drive_social = variables[VARIABLE_DRIVE_SOCIAL - VARIABLE_VECT_ANGLE]; n_int local_drive_fatigue = variables[VARIABLE_DRIVE_FATIGUE - VARIABLE_VECT_ANGLE]; n_int local_drive_sex = variables[VARIABLE_DRIVE_SEX - VARIABLE_VECT_ANGLE]; n_int local_family_name1 = variables[VARIABLE_FAMILY_NAME_ONE - VARIABLE_VECT_ANGLE]; n_int local_family_name2 = variables[VARIABLE_FAMILY_NAME_TWO - VARIABLE_VECT_ANGLE]; n_int local_honor = variables[VARIABLE_HONOR - VARIABLE_VECT_ANGLE]; n_int local_parasites = variables[VARIABLE_PARASITES - VARIABLE_VECT_ANGLE]; if(local_facing< 0) { local_facing = 255 - ( (0 - local_facing) & 255 ); } else { local_facing = local_facing & 255; } if (local_speed > 39) local_speed = 39; if (local_speed < 0) local_speed = 0; being_wander(local_being, local_facing - being_facing(local_being)); being_set_speed(local_being, (n_byte) local_speed); being_energy_delta(local_being, local_energy_delta); being_set_height(local_being, local_height); if (local_goal_type!=GOAL_NONE) { local_being->delta.goal[0] = (n_byte2)local_goal_type; local_being->delta.goal[1] = (n_byte2)local_goal_x; local_being->delta.goal[2] = (n_byte2)local_goal_y; local_being->delta.goal[3] = GOAL_TIMEOUT; local_being->braindata.script_overrides |= OVERRIDE_GOAL; } if (local_drive_hunger>-1) { local_being->changes.drives[DRIVE_HUNGER] = (n_byte)local_drive_hunger; } if (local_drive_social>-1) { local_being->changes.drives[DRIVE_SOCIAL] = (n_byte)local_drive_social; } if (local_drive_fatigue>-1) { local_being->changes.drives[DRIVE_FATIGUE] = (n_byte)local_drive_fatigue; } if (local_drive_sex>-1) { local_being->changes.drives[DRIVE_SEX] = (n_byte)local_drive_sex; } being_set_family_name(local_being,(n_byte)local_family_name1,(n_byte)local_family_name2); local_being->delta.honor = (n_byte)local_honor; being_set_parasites(local_being, (n_byte)local_parasites); } static void sim_being_interpret(simulated_group * group, simulated_being * local_being, void * data) { n_individual_interpret individual; interpret_individual(&individual); if (local_being->delta.awake == 0) return; if (interpret == 0L) return; if(interpret_cycle(interpret, &individual, -1, group->beings, local_being, &sim_start_conditions, &sim_end_conditions) == -1) { interpret_cleanup(&interpret); } } static void sim_time(simulated_group * group) { simulated_timing *timing = sim_timing(); timing->count_cycles += group->num; timing->count_frames ++; if ((timing->real_time - timing->last_time) > 60) { timing->last_time = timing->real_time; timing->delta_cycles = timing->count_cycles; timing->delta_frames = timing->count_frames; timing->count_cycles = 0; timing->count_frames = 0; } } #if 1 #define PROCESSING_HEAVY_WEIGHT (4) #define PROCESSING_MIDDLE_WEIGHT (8) #define PROCESSING_WELTER_WEIGHT (16) #define PROCESSING_LIGHT_WEIGHT (32) #define PROCESSING_FEATHER_WEIGHT (64) #else #define PROCESSING_HEAVY_WEIGHT (3) #define PROCESSING_MIDDLE_WEIGHT (7) #define PROCESSING_WELTER_WEIGHT (17) #define PROCESSING_LIGHT_WEIGHT (31) #define PROCESSING_FEATHER_WEIGHT (67) #endif static void sim_being_remove_final(simulated_group * group, being_remove_loop2_struct ** brls) { group->num = (*brls)->count; if ((*brls)->selected_died) { if ((*brls)->count) { sim_set_select(group->beings); } else { sim_set_select(0L); } } if ((*brls)->count == 0) { if (sim_new_run == 0) { (void)SHOW_ERROR("No Apes remain start new run"); sim_new_run = 1; } } being_remove_internal_clear(); memory_free((void **)brls); } void sim_update_output(void) { if (sim_desire_output == 0) { return; } if (group.select == 0L) { return; } #ifndef _WIN32 sim_writing_output = 1; memory_erase((n_byte *)sim_console_output, STRING_BLOCK_SIZE); watch_control(&group, being_get_select_name(&group), group.select, sim_console_output); sim_writing_output = 0; #endif } static KIND_OF_USE local_execution = KIND_PRE_STARTUP; void sim_cycle(void) { if (local_execution == KIND_PRE_STARTUP) { return; } if (local_execution != KIND_NOTHING_TO_RUN) { if (local_execution != KIND_MEMORY_SETUP) { if (local_execution != KIND_NEW_APES) { land_clear(local_execution, AGE_OF_MATURITY); #ifdef LAND_ON land_init(); land_init_high_def(1); land_tide(); #endif } if (local_execution != KIND_LOAD_FILE) { n_byte2 local_random[2]; n_byte2 *genetics = land_genetics(); local_random[0] = genetics[0]; local_random[1] = genetics[1]; math_random3(local_random); #ifdef WEATHER_ON weather_init(); #endif /* Sets the number of Simulated Apes initially created, and creates them */ group.num = being_init_group(group.beings, local_random, group.max >> 1, group.max); } } sim_set_select(group.beings); sim_new_progress = 0; local_execution = KIND_NOTHING_TO_RUN; } n_int max_honor = 0; land_cycle(); #ifdef WEATHER_ON weather_cycle(); #endif loop_being_no_sim(group.beings, group.num, sim_being_awake_loop_no_sim, 0L); loop_being_no_sim(group.beings, group.num, sim_being_universal_loop_no_sim, 0L); if (interpret) { loop_being(&group, sim_being_interpret, PROCESSING_WELTER_WEIGHT); } else { /** Listen for any shouts */ loop_being(&group, being_listen, PROCESSING_FEATHER_WEIGHT); #ifdef EPISODIC_ON loop_being_no_sim(group.beings, group.num, episodic_cycle_no_sim, 0L); #endif loop_being(&group, sim_being_cycle, PROCESSING_MIDDLE_WEIGHT); loop_being(&group, drives_cycle, PROCESSING_LIGHT_WEIGHT); } if (land_time() & 1) { #ifdef BRAIN_ON loop_being(&group, sim_brain_loop, PROCESSING_WELTER_WEIGHT); #endif } #ifdef BRAINCODE_ON else { loop_being(&group, sim_brain_dialogue_loop, PROCESSING_MIDDLE_WEIGHT); } #endif loop_being_no_sim(group.beings, group.num, being_tidy_loop_no_sim, &max_honor); loop_being(&group, social_initial_loop, PROCESSING_LIGHT_WEIGHT); if (max_honor) { loop_being_no_sim(group.beings, group.num, being_recalibrate_honor_loop_no_sim, 0L); } loop_being_no_sim(group.beings, group.num, social_secondary_loop_no_sim, 0L); { n_string_block selected_name = {0}; n_int selected_lives = 1; being_remove_loop2_struct * brls = being_remove_initial(&group); if (group.select) { being_name_simple(group.select, selected_name); } if (group.ext_death != 0L) { loop_no_thread(&group, 0L, being_remove_loop1, 0L); } loop_no_thread(&group, 0L, being_remove_loop2, brls); selected_lives = brls->selected_died == 0; sim_being_remove_final(&group, &brls); if (selected_lives) { simulated_being * new_select = sim_select_name(selected_name); if (new_select) { sim_set_select(new_select); } } } sim_time(&group); } #define MINIMAL_ALLOCATION ((512*512)+(TERRAIN_WINDOW_AREA)+(CONTROL_WINDOW_AREA)+(sizeof(simulated_being) * MIN_BEINGS)+sizeof(simulated_remains)+1) #define MAXIMUM_ALLOCATION (MINIMAL_ALLOCATION + (sizeof(simulated_being) * 400)) n_uint sim_memory_allocated(n_int max) { if (max) { return MAXIMUM_ALLOCATION; }else{ return initial_memory_allocated; } } static void sim_memory_remains(simulated_group * group, n_byte * buffer, n_uint * location) { group->remains = (simulated_remains *) & buffer[ *location ]; *location += sizeof(simulated_remains); } static n_int being_memory(simulated_group * group, n_byte * buffer, n_uint * location, n_uint memory_available) { n_uint lpx = 0; n_uint number_apes = 0; if ((memory_available < 1) || (buffer == 0L)) { return SHOW_ERROR("Memory not available"); } number_apes = (memory_available / sizeof(simulated_being)) - 1; if (number_apes < 1) { return SHOW_ERROR("Not enough memory for an ape"); } #ifdef LARGE_SIM group->max = LARGE_SIM; #else group->max = (memory_available / sizeof(simulated_being)) - 1; #endif group->beings = (simulated_being *) & buffer[ * location ]; * location += sizeof(simulated_being) * group->max ; while (lpx < group->max) { simulated_being * local_being = &(group->beings[ lpx ]); memory_erase((n_byte *)local_being, sizeof(simulated_being)); lpx ++; } return 0; } static n_int sim_memory(n_uint offscreen_size) { n_uint current_location = 0; n_uint memory_allocated = MAXIMUM_ALLOCATION; offbuffer = memory_new_range(offscreen_size + MINIMAL_ALLOCATION, &memory_allocated); if (offbuffer == 0L) { return SHOW_ERROR("Memory not available"); } memory_erase(offbuffer, memory_allocated); initial_memory_allocated = memory_allocated; current_location = offscreen_size; sim_memory_remains(&group, offbuffer, &current_location); memory_allocated = memory_allocated - current_location; return being_memory(&group, offbuffer, &current_location, memory_allocated); } static void debug_birth_event(simulated_being * born, simulated_being * mother, void * sim) { n_string_block name, mother_name, father_name; being_name_simple(born, name); being_name_simple(mother, mother_name); being_name_byte2(mother->changes.father_name[0], mother->changes.father_name[1], father_name); printf("*** Born: %s (Mother: %s Father: %s)\n", name, mother_name, father_name); } static void debug_death_event(simulated_being * deceased, void * sim) { n_string_block name; being_name_simple(deceased, name); printf("*** Dead: %s\n", name); } void * sim_init(KIND_OF_USE kind, n_uint randomise, n_uint offscreen_size, n_uint landbuffer_size) { n_byte2 local_random[2]; sim_writing_output = 1; sim_new_progress = 1; if (kind == KIND_NEW_SIMULATION) { if(interpret) { interpret_cleanup(&interpret); interpret = 0L; } } timing.real_time = randomise; timing.last_time = randomise; #ifdef FIXED_RANDOM_SIM randomise = FIXED_RANDOM_SIM; #endif timing.delta_cycles = 0; timing.count_cycles = 0; timing.delta_frames = 0; timing.count_frames = 0; #if 0 group.ext_birth = &debug_birth_event; group.ext_death = &debug_death_event; #else group.ext_birth = 0L; group.ext_death = 0L; #endif if ((kind == KIND_START_UP) || (kind == KIND_MEMORY_SETUP)) { if (sim_memory(offscreen_size) != 0) { return 0L; } } local_random[0] = (n_byte2)(randomise >> 16) & 0xffff; local_random[1] = (n_byte2)(randomise & 0xffff); math_random3(local_random); if ((kind != KIND_LOAD_FILE) && (kind != KIND_MEMORY_SETUP)) { land_seed_genetics(local_random); } being_remains_init(group.remains); /* Eventually this should be captured through the file handling and moved into the code below */ local_execution = kind; return ((void *) offbuffer); } void sim_close(void) { command_quit(0L, 0L, 0L); io_console_quit(); #ifndef _WIN32 sim_console_clean_up(); #endif interpret_cleanup(&interpret); memory_free((void **) &offbuffer); /*death_record_file_cleanup();*/ } void sim_set_select(simulated_being * select) { group.select = select; sim_update_output(); } static void sim_flood_loop(simulated_group * group, simulated_being * local, void * data) { n_vect2 location; being_space(local, &location); land_convert_to_map(&location); if (land_location_vect(&location) < 160) { being_dead(local); } } void sim_flood(void) { loop_no_thread(&group, 0L, sim_flood_loop, 0L); } void sim_healthy_carrier(void) { n_uint loop = (group.num >> 2); while (loop < group.num) { simulated_being * local = &group.beings[loop]; being_dead(local); loop++; } } <|start_filename|>win/platform.h<|end_filename|> /**************************************************************** platform.h ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #ifndef _NOBLEAPE_PLATFORM_H_ #define _NOBLEAPE_PLATFORM_H_ #define FILE_NEW_HANDLE 40101 #define FILE_OPEN_HANDLE 40102 #define FILE_OPEN_SCRIPT_HANDLE 40103 #define SCRIPT_ADDITION 1 #define FILE_CLOSE_HANDLE (40103 + SCRIPT_ADDITION) #define FILE_SAVE_AS_HANDLE (40104 + SCRIPT_ADDITION) #define FILE_EXIT_HANDLE (40105 + SCRIPT_ADDITION) #define EDIT_UNDO_HANDLE 40256 #define EDIT_CUT_HANDLE 40257 #define EDIT_COPY_HANDLE 40258 #define EDIT_PASTE_HANDLE 40259 #define EDIT_CLEAR_HANDLE 40260 #define CONTROL_PAUSE_HANDLE 40017 #define CONTROL_PREV_HANDLE 40019 #define CONTROL_NEXT_HANDLE 40020 #define CONTROL_CLEAR_ERRORS 40021 #define CONTROL_WEATHER_HANDLE 40022 #define CONTROL_BRAIN_HANDLE 40023 #define CONTROL_BRAINCODE_HANDLE 40024 #define CONTROL_TERRITORY_HANDLE 40025 #define CONTROL_DAYLIGHT_TIDES_HANDLE 40026 #define CONTROL_WEATHER_HANDLE 40022 #define CONTROL_WEATHER_HANDLE 40022 #define HELP_ABOUT_HANDLE 40254 #define NOBLE_APE_FILE_OPEN "All Files (*.*)\0*.*\0" #define NOBLE_APE_FILE_SAVE "All Files (*.*)\0*.*\0" #endif <|start_filename|>entity/brain.c<|end_filename|> /**************************************************************** brain.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #include "entity.h" #include "entity_internal.h" #include <stdio.h> /* typical minimum spacing between MVB instructions */ #define BRAINCODE_MIN_MVB_SPACING 2 #define BRAINCODE_CONSTANT0_BIT (64) #define BRAINCODE_CONSTANT1_BIT (128) #define BRAINCODE_DATA_START BRAINCODE_DAT0 #define BRAINCODE_DATA_NUMBER (1 + BRAINCODE_DAT1 - BRAINCODE_DATA_START) #define BRAINCODE_OPERATORS_START BRAINCODE_ADD #define BRAINCODE_OPERATORS_NUMBER (1 + BRAINCODE_LTP - BRAINCODE_OPERATORS_START) #define BRAINCODE_CONDITIONALS_START BRAINCODE_JMZ #define BRAINCODE_CONDITIONALS_NUMBER (1 + BRAINCODE_SLT - BRAINCODE_CONDITIONALS_START) #define BRAINCODE_SENSORS_START BRAINCODE_SEN #define BRAINCODE_SENSORS_NUMBER (1 + BRAINCODE_SEN3 - BRAINCODE_SENSORS_START) #define BRAINCODE_ACTUATORS_START BRAINCODE_ACT #define BRAINCODE_ACTUATORS_NUMBER (1 + BRAINCODE_ANE - BRAINCODE_ACTUATORS_START) #define BRAINCODE_INSTRUCTION(braincode,i) ((braincode[i] & (BRAINCODE_CONSTANT0_BIT-1)) % BRAINCODE_INSTRUCTIONS) #define BRAINCODE_CONSTANT0(braincode,i) (braincode[i] & BRAINCODE_CONSTANT0_BIT) #define BRAINCODE_CONSTANT1(braincode,i) (braincode[i] & BRAINCODE_CONSTANT1_BIT) #define BRAINCODE_VALUE(braincode,i,n) (braincode[(i+1+n) & (BRAINCODE_SIZE - 1)]) /* Brain definitions */ #define B_SIZE (32768) #define B_WR (B_SIZE - 1) #define F_X (1) #define F_Y (32) #define F_Z (1024) #define B_Z (B_SIZE - F_Z) #define B_Y (B_SIZE - F_Y) #define B_X (B_SIZE - F_X) /* * The basic brain formula is; * b(t+1) = a*l + b(t)*m + (b(t)-b(t-1))*n; * * The waking mind works differently to the sleeping mind. This is quantified * with two distinct but similar equations. There are two versions for the awake * and asleep states, in this function it is simplified to; * b(t+1) = a*l_a + b(t)*l_b - b(t-1)*l_c; * * where, l_a = l, l_b = m+n, l_c = n */ #define B_FN(ave, bra, obra) ((ave+bra-obra)>>10) /** positive and negative, lower and upper halves */ #define B_P_LH (br[loc+F_Z]+br[loc+F_Y]+br[loc+F_X]) #define B_P_UH (br[loc-F_X]+br[loc-F_Y]+br[loc-F_Z]) #define B_N_LH (br[(loc+F_X)&B_WR]+br[(loc+F_Y)&B_WR]+br[(loc+F_Z)&B_WR]) #define B_N_UH (br[(loc+B_Z)&B_WR]+br[(loc+B_Y)&B_WR]+br[(loc+B_X)&B_WR]) /** * @brief Updates the brain * @param local Pointer to the brain array * @param constants Array containing brain constants */ void brain_cycle(n_byte * local, n_byte2 * constants) { n_byte br[B_SIZE]; n_byte *bract = local, *obr = &local[B_SIZE]; n_int l_a = constants[0]; n_int l_c = constants[2]; n_int l_b = constants[1] + l_c; n_int loc = 0; n_int average; n_int obr_tmp; n_int br_tmp; n_int count = F_Z; memory_copy(bract, br, B_SIZE); do { average = (B_P_LH + B_N_UH); br_tmp = br[loc]; obr_tmp = obr[loc]; average *= l_a; obr_tmp *= l_c; br_tmp *= l_b; br_tmp -= obr_tmp; average += br_tmp; br[loc++] = (n_byte)(average>>10); count--; } while(count); count = B_Z - F_Z; do { average = br[loc-F_Z]; average += br[loc-F_Y]; average += br[loc-F_X]; br_tmp = br[loc]; average += br[loc+F_X]; average += br[loc+F_Y]; average += br[loc+F_Z]; obr_tmp = obr[loc]; average *= l_a; obr_tmp *= l_c; br_tmp *= l_b; br_tmp -= obr_tmp; average += br_tmp; br[loc++] = (n_byte)(average>>10); count--; } while (count); count = F_Z; do { average = B_P_UH; br_tmp = br[loc]; average += B_N_LH; obr_tmp = obr[loc]; average *= l_a; obr_tmp *= l_c; br_tmp *= l_b; br_tmp -= obr_tmp; average += br_tmp; br[loc++] = (n_byte)(average>>10); count--; } while (count); memory_copy(bract, obr, B_SIZE); memory_copy(br, bract, B_SIZE); } /** "XXX_#NNN_#NNN"*/ /** "0123456789012"*/ enum BC_FORMAT { BC_FORMAT_A = 0, BC_FORMAT_C, BC_FORMAT_E, BC_FORMAT_F, BC_FORMAT_G, BC_FORMAT_H }; const n_string braincode_mnemonic[BRAINCODE_INSTRUCTIONS] = { /** data */ "DAT0", "DAT1", /** operators */ "ADD ", "SUB ", "MUL ", "DIV ", "MOD ", "MVB ", "MOV ", "JMP ", "CTR ", "SWP ", "INV ", "STP ", "LTP ", /** conditionals */ "JMZ ", "JMN ", "DJN ", "AND ", "OR ", "SEQ ", "SNE ", "SLT ", /** sensors */ "SEN ", "SEN2", "SEN3", /** actuators */ "ACT ", "ACT2", "ACT3", "ANE " }; /** * @brief Returns the type of formatting of a three byte instruction * @param instruction The instruction type * @param command Whether the subsequent two bytes are constants or variables * @param value0 The first argument * @param value1 The second argument * @return The format type used to display a three byte instruction */ static enum BC_FORMAT brain_format(n_byte instruction, n_byte command, n_byte value0, n_byte value1) { n_byte is_constant0 = ((command & BRAINCODE_CONSTANT0_BIT) != 0); n_byte is_constant1 = ((command & BRAINCODE_CONSTANT1_BIT) != 0); switch(instruction) { case BRAINCODE_AND: case BRAINCODE_OR: case BRAINCODE_MOV: case BRAINCODE_ADD: case BRAINCODE_SUB: case BRAINCODE_MUL: case BRAINCODE_MOD: if ((!is_constant0) && (!is_constant1)) { return BC_FORMAT_A; } return BC_FORMAT_C; break; case BRAINCODE_JMZ: case BRAINCODE_JMN: case BRAINCODE_DJN: return BC_FORMAT_E; break; case BRAINCODE_SEQ: case BRAINCODE_SNE: case BRAINCODE_SLT: if ((!is_constant0) && (!is_constant1)) { return BC_FORMAT_A; } return BC_FORMAT_F; break; case BRAINCODE_DAT0: case BRAINCODE_DAT1: case BRAINCODE_JMP: return BC_FORMAT_C; break; case BRAINCODE_INV: if (is_constant0) { return BC_FORMAT_G; } return BC_FORMAT_H; break; case BRAINCODE_STP: case BRAINCODE_LTP: if ((is_constant0) && (!is_constant1)) { return BC_FORMAT_F; } if ((is_constant0) && (is_constant1)) { return BC_FORMAT_C; } if ((!is_constant0) && (is_constant1)) { return BC_FORMAT_E; } break; } return BC_FORMAT_A; } /** "aeio" "fmsv"; */ const n_string braincode_spoken_dictionary[BRAINCODE_INSTRUCTIONS] = { /** data */ "a", /**< "DAT0", */ "o", /**< "DAT1", */ /** operators */ "mam", /**< "ADD ",*/ "vos", /**< "SUB ",*/ "sie", /**< "MUL ",*/ "fes", /**< "DIV ",*/ "feo", /**< "MOD ",*/ "mas", /**< "MVB ",*/ "vam", /**< "MOV ",*/ "amo", /**< "JMP ",*/ "sam", /**< "CTR ",*/ "mao", /**< "SWP ",*/ "ova", /**< "INV ",*/ "eef", /**< "STP ",*/ "fee", /**< "LTP ",*/ /** conditionals */ "om", /**< "JMZ ",*/ "ov", /**< "JMN ",*/ "fi", /**< "DJN ",*/ "im", /**< "AND ",*/ "se", /**< "OR ",*/ "es", /**< "SEQ ",*/ "os", /**< "SNE ",*/ "is", /**< "SLT ",*/ /** sensors */ "favos", /**< "SEN ",*/ "vamos", /**< "SEN2",*/ "famov", /**< "SEN3",*/ /** actuators */ "iema", /**< "ACT ",*/ "iova", /**< "ACT2",*/ "iafi", /**< "ACT3",*/ "ovma", /**< "ANE "*/ }; static n_byte brain_vc(n_byte value, n_byte vowel) { if (vowel) { switch (value) { case 3: return 'a'; case 1: return 'e'; case 2: return 'i'; default: return 'o'; } } switch (value) { case 0: return 'v'; case 1: return 'f'; case 2: return 's'; case 3: return 't'; case 4: return 'p'; case 5: return 'b'; case 6: return 'j'; default: return 'm'; } } static void brain_longword(n_string output, n_byte value) { output[0] = (n_char)brain_vc((value >> 0) & 7,0); output[1] = (n_char)brain_vc((value >> 3) & 3,1); output[2] = (n_char)brain_vc((value >> 5) & 7,0); output[4] = 0; } static void brain_four_character_byte(n_string value, n_byte star, n_byte dashes, n_byte number) { if (star) { value[0] = '*'; } else { value[0] = ' '; } if (dashes) { value[1] = '-'; value[2] = '-'; value[3] = '-'; } else { value[1] = '0' + (number/100) % 10; value[2] = '0' + (number/10) % 10; value[3] = '0' + (number/1) % 10; if (value[1] == '0') { value[1] = ' '; if (value[2] == '0') { value[2] = ' '; } } } } static void brain_space_nstruction_space(n_string value, n_byte instruction) { n_string instruction_string = braincode_mnemonic[instruction]; value[0] = ' '; value[1] = instruction_string[0]; value[2] = instruction_string[1]; value[3] = instruction_string[2]; value[4] = instruction_string[3]; value[5] = ' '; } /** * @brief prints a three byte instruction in the appropriate format * @param string The returned string * @param response Array containing the three byte instruction */ void brain_three_byte_command(n_string string, n_byte * response) { n_byte command = response[0]; n_byte value0 = response[1]; n_byte value1 = response[2]; n_byte instruction = (command & (BRAINCODE_CONSTANT0_BIT-1)) % BRAINCODE_INSTRUCTIONS; enum BC_FORMAT format = brain_format(instruction, command, value0, value1); brain_space_nstruction_space(string, instruction); switch(format) { case BC_FORMAT_A: brain_four_character_byte(&string[6], 0, 0, value0); brain_four_character_byte(&string[10], 0, 0, value1); break; case BC_FORMAT_C: brain_four_character_byte(&string[6], 1, 0, value0); brain_four_character_byte(&string[10], 1, 0, value1); break; case BC_FORMAT_E: brain_four_character_byte(&string[6], 0, 0, value0); brain_four_character_byte(&string[10], 1, 0, value1); break; case BC_FORMAT_F: brain_four_character_byte(&string[6], 1, 0, value0); brain_four_character_byte(&string[10], 0, 0, value1); break; case BC_FORMAT_G: brain_four_character_byte(&string[6], 0, 0, value0); brain_four_character_byte(&string[10], 0, 1, 0); break; default: brain_four_character_byte(&string[6], 0, 1, 0); brain_four_character_byte(&string[10], 0, 0, value1); break; } string[14] = 0; } /** * @brief A simple sort of sentence construction from three byte instructions * @param string The returned sentence * @param response Array containing three byte instruction */ void brain_sentence(n_string string, n_byte * response) { n_byte command = response[0]; n_byte value0 = response[1]; n_byte value1 = response[2]; n_byte instruction = (command & (BRAINCODE_CONSTANT0_BIT-1)) % BRAINCODE_INSTRUCTIONS; enum BC_FORMAT format = brain_format(instruction, command, value0, value1); n_string_block first_word, second_word; n_int position = 0; brain_longword(first_word, value0); brain_longword(second_word, value1); switch(format) { case BC_FORMAT_A: case BC_FORMAT_C: case BC_FORMAT_E: case BC_FORMAT_F: io_string_write(string, braincode_spoken_dictionary[instruction], &position); io_string_write(string, " ", &position); io_string_write(string, first_word, &position); io_string_write(string, second_word, &position); break; case BC_FORMAT_G: io_string_write(string, braincode_spoken_dictionary[instruction], &position); io_string_write(string, " ", &position); io_string_write(string, first_word, &position); break; default: io_string_write(string, braincode_spoken_dictionary[instruction], &position); io_string_write(string, " ", &position); io_string_write(string, second_word, &position); break; } } #ifdef BRAINCODE_ON /** * @brief returns a random braincode instruction of the given type * @param instruction_type Number indicating the type of instruction * @return braincode instruction */ static n_byte get_braincode_instruction_type(n_byte instruction_type) { n_byte2 local_random[2]; math_random3(local_random); switch(instruction_type) { case 0: /**< GENE_BRAINCODE_SENSORS(genetics);*/ return BRAINCODE_DATA_START+(local_random[0]%(BRAINCODE_DATA_NUMBER)); case 1: /**< GENE_BRAINCODE_ACTUATORS(genetics); */ return BRAINCODE_SENSORS_START+(local_random[0]%(BRAINCODE_SENSORS_NUMBER)); case 2: /**< GENE_BRAINCODE_CONDITIONALS(genetics); */ return BRAINCODE_ACTUATORS_START+(local_random[0]%(BRAINCODE_ACTUATORS_NUMBER)); case 3: /**< GENE_BRAINCODE_OPERATORS(genetics); */ return BRAINCODE_OPERATORS_START+(local_random[0]%(BRAINCODE_OPERATORS_NUMBER)); case 4: /**< GENE_BRAINCODE_DATA(genetics); */ return BRAINCODE_CONDITIONALS_START+(local_random[0]%(BRAINCODE_CONDITIONALS_NUMBER)); } return BRAINCODE_DATA_START; } /* return the number of instruction_types in the braincode */ /** * @brief returns a random braincode instruction * @param local_being Pointer to the being * @return braincode instruction */ n_byte get_braincode_instruction(simulated_being * local_being) { n_byte2 prob[5], total, index; n_genetics * genetics = being_genetics(local_being); n_byte i; const n_byte2 min=2; prob[0] = (n_byte2)(min + GENE_BRAINCODE_SENSORS(genetics)); prob[1] = (n_byte2)(min + GENE_BRAINCODE_ACTUATORS(genetics)); prob[2] = (n_byte2)(min + GENE_BRAINCODE_CONDITIONALS(genetics)); prob[3] = (n_byte2)(min + GENE_BRAINCODE_OPERATORS(genetics)); prob[4] = (n_byte2)(min + GENE_BRAINCODE_DATA(genetics)); total = prob[0] + prob[1] + prob[2] + prob[3] + prob[4]; if (total == 0) { index = 0; } else { index = being_random(local_being); } total = 0; for (i=0; i<5; i++,total+=prob[i]) { if (index>=total) { return get_braincode_instruction_type(i); } } return get_braincode_instruction_type(4); } static n_int get_actor_index(simulated_isocial * social_graph, n_int value) { n_int i; for (i=0; i<SOCIAL_SIZE; i++) { if (SOCIAL_GRAPH_ENTRY_EMPTY(social_graph,i)) break; } if (i == 0) return 0; return value % i; } /** * @brief returns the social graph index for a being with the same (or similar) name to the given episodic memory event * @param social_graph Pointer to the social graph * @param episodic_event Pointer to the episodic memory * @param episode_index Index of the episode which is the current focus of attention * @return Social graph index */ static n_int get_actor_index_from_episode( simulated_isocial * social_graph, simulated_iepisodic * episodic_event, n_int episode_index) { n_int i,actor_index=-1; for (i=1; i<SOCIAL_SIZE_BEINGS; i++) { if (!SOCIAL_GRAPH_ENTRY_EMPTY(social_graph,i)) { if (social_graph[i].family_name == episodic_event[episode_index].family_name) { actor_index = i; if (social_graph[i].first_name == episodic_event[episode_index].first_name) { actor_index = i; break; } } } } return actor_index; } typedef n_int (n_similar)(simulated_iepisodic * episodic, n_int * carry_through); /** * @brief Returns the index of the most similar episodic memory * @param episode_index Current episodic memory index * @param episodic Pointer to the episodic memory * @param memory_visited Array which keeps track of which episodic memories have already been visited * @param carry_through The property to be compared against * @param function The similarity function to be used to do the comparrisson * @return Episodic memory index of the most similar event */ static n_int attention_similar(n_int episode_index, simulated_iepisodic * episodic, n_int * memory_visited, n_int * carry_through, n_similar function) { n_int i; n_int visited_max = memory_visited[episode_index] - (EPISODIC_SIZE>>1); n_int min=-1; n_int next_episode_index = -1; if (visited_max<0) visited_max=0; for (i = 0; i < EPISODIC_SIZE; i++) { if (episodic[i].event == 0) continue; if (i != episode_index) { /** was this episode recently visited? */ if (memory_visited[i] <= visited_max) { /** difference between episodes */ n_int diff = function(&episodic[i], carry_through); if (diff < 0) diff = -diff; if ((min == -1) || (diff < min)) { /** record most similar */ min = diff; next_episode_index = i; } } } } if (next_episode_index>-1) { /** mark this episode as having been visited */ memory_visited[next_episode_index] = memory_visited[episode_index]+1; } return next_episode_index; } /** * @brief returns the temporal proximity of an episodic event to the given reference time * @param episodic Pointer to the episodic memory event * @param carry_through Time to be compared against * @return Absolute temporal proximity */ static n_int similar_time(simulated_iepisodic * episodic, n_int * carry_through) { n_int dt = episodic->space_time.time - carry_through[0]; if (dt < 0) { dt = - dt; } return dt; } /** * @brief Returns the temporal proximity of an episodic memory event to the given time * @param episode_index Index of the current focus of attention within the episodic memory * @param episodic Pointer to the episodic memory * @param memory_visited Time to be compared against * @return Absolute temporal proximity */ static n_int attention_similar_time(n_int episode_index, simulated_iepisodic * episodic, n_int * memory_visited) { n_int time = episodic[episode_index].space_time.time; return attention_similar(episode_index, episodic, memory_visited, &time, similar_time); } /** * @brief Returns the affective similarity of the given affect value to an episodic memory event * @param episodic Pointer to the episodic memory event * @param carry_through Affect value to be compared against * @return Absolute difference in affect value */ static n_int similar_affect(simulated_iepisodic * episodic, n_int * carry_through) { n_int da = episodic->affect - carry_through[0]; if (da < 0) { da = - da; } return da; } /** * @brief Returns the affective similarity of the given affect value to an episodic memory event * @param episode_index Index of the current focus of attention within the episodic memory * @param episodic Pointer to the episodic memory * @param memory_visited Affect value to be compared against * @return Absolute difference in affect value */ static n_int attention_similar_affect(n_int episode_index, simulated_iepisodic * episodic, n_int * memory_visited) { n_int affect = episodic[episode_index].affect; return attention_similar(episode_index, episodic, memory_visited, &affect, similar_affect); } /** * @brief Returns the similarity between a given episodic memory event and the given family name * @param episodic Pointer to the episodic memory event * @param carry_through Family name to be compared against * @return Similarity value in the range 0-3 */ static n_int similar_name(simulated_iepisodic * episodic, n_int * carry_through) { n_int similarity = 3; n_byte values[2]; being_unpack_family(episodic->family_name[BEING_MET], values); if (values[0] == carry_through[0]) similarity--; if (values[1] == carry_through[1]) similarity--; if (episodic->first_name[BEING_MET] == carry_through[2]) similarity--; return similarity; } /** * @brief Returns the similarity between a given episodic memory event and the given being name * @param episode_index Index of the current focus of attention within the episodic memory * @param episodic Pointer to the episodic memory * @param memory_visited Affect value to be compared against * @return Similarity value */ static n_int attention_similar_name(n_int episode_index, simulated_iepisodic * episodic, simulated_being * meeter, n_int * memory_visited) { n_int name[3]; n_byte values[2]; being_unpack_family(episodic->family_name[BEING_MET], values); name[0] = values[0]; name[1] = values[1]; name[2] = episodic[episode_index].first_name[BEING_MET]; return attention_similar(episode_index, episodic, memory_visited, name, similar_name); } /** * @brief Returns the similarity of a given date to the date of the given episodic memory event * @param episodic Pointer to the episodic memory event * @param carry_through Date to be compared against * @return Absolute difference in date value */ static n_int similar_date(simulated_iepisodic * episodic, n_int * carry_through) { n_int dd = episodic->space_time.date - carry_through[0]; if (dd < 0) { dd = - dd; } return dd; } /** * @brief Returns the similarity of a given date to the date of the given episodic memory event * @param episode_index Index of the current focus of attention within the episodic memory * @param episodic Pointer to the episodic memory * @param memory_visited Date to be compared against * @return Similarity value */ static n_int attention_similar_date(n_int episode_index, simulated_iepisodic * episodic, n_int * memory_visited) { n_int time = episodic[episode_index].space_time.date; return attention_similar(episode_index, episodic, memory_visited, &time, similar_date); } /** * @brief Returns the similarity between the given episodic memory event place and a given reference location * @param episodic Pointer to the episodic memory event * @param carry_through 2D coordinate of the place to be compared against * @return Similarity value (2D distance squared) */ static n_int similar_place(simulated_iepisodic * episodic, n_int * carry_through) { n_int dx = episodic->space_time.location[0] - carry_through[0]; n_int dy = episodic->space_time.location[1] - carry_through[1]; /** TODO should be calculated in the future with wrap around comparison */ n_int da = (dx * dx) + (dy * dy); return da; } /** * @brief Returns the similarity between the given episodic memory event place and a given reference location * @param episode_index Index of the episodic memory which is the current focus of attention * @param episodic Pointer to the episodic memory * @param memory_visited 2D coordinate of the place to be compared against * @return Similarity value (2D distance squared) */ static n_int attention_similar_place(n_int episode_index, simulated_iepisodic * episodic, n_int * memory_visited) { n_int location[2]; location[0] = episodic[episode_index].space_time.location[0]; location[1] = episodic[episode_index].space_time.location[1]; return attention_similar(episode_index, episodic, memory_visited, location, similar_place); } n_byte * math_general_allocation(n_byte * bc0, n_byte * bc1, n_int i) { if (BRAINCODE_ADDRESS(i) < BRAINCODE_SIZE) { /** address within this being */ return &bc0[BRAINCODE_ADDRESS(i)]; } /** Address within the other being */ return &bc1[BRAINCODE_ADDRESS(i) - BRAINCODE_SIZE]; } void math_general_execution(n_int instruction, n_int is_constant0, n_int is_constant1, n_byte * addr0, n_byte * addr1, n_int value0, n_int * i, n_int is_const0, n_int is_const1, n_byte * pspace, n_byte *bc0, n_byte *bc1, n_int braincode_min_loop) { /** Logical and */ switch( instruction ) { case BRAINCODE_AND: if (is_constant0) { addr0[0] &= addr1[0]; } else { if ((addr0[0]>127) && (addr1[0]>127)) *i += BRAINCODE_BYTES_PER_INSTRUCTION; } break; /** Logical or */ case BRAINCODE_OR: if (is_constant0) { addr0[0] |= addr1[0]; } else { if ((addr0[0]>127) || (addr1[0]>127)) *i += BRAINCODE_BYTES_PER_INSTRUCTION; } break; /** Move a byte, with no particular alignment */ case BRAINCODE_MOV: if ((!is_constant0) && (!is_constant1)) { addr1[0] = addr0[0]; } else { addr1[0] = (n_byte)value0; } break; /** Move a block of instructions */ case BRAINCODE_MVB: { n_int ptr0, ptr1, n, instructions_to_copy, dat = 0; if (!is_constant0) { ptr0 = BRAINCODE_ADDRESS(*i + ((n_int)addr0[0]*BRAINCODE_BYTES_PER_INSTRUCTION)); } else { ptr0 = BRAINCODE_ADDRESS(*i + ((n_int)value0*BRAINCODE_BYTES_PER_INSTRUCTION)); } ptr1 = BRAINCODE_ADDRESS(*i + ((n_int)is_const0 * BRAINCODE_BYTES_PER_INSTRUCTION)); instructions_to_copy = 1 + (pspace[1]%BRAINCODE_BLOCK_COPY); while (dat < instructions_to_copy) { if (ptr0 < BRAINCODE_SIZE) { addr0 = &bc0[ptr0]; } else { addr0 = &bc1[ptr0 - BRAINCODE_SIZE]; } if (ptr1 < BRAINCODE_SIZE) { addr1 = &bc0[ptr1]; } else { addr1 = &bc1[ptr1 - BRAINCODE_SIZE]; } for (n = 0; n < BRAINCODE_BYTES_PER_INSTRUCTION; n++) { addr1[n] = addr0[n]; } dat++; ptr0 = BRAINCODE_ADDRESS(ptr0 + BRAINCODE_BYTES_PER_INSTRUCTION); ptr1 = BRAINCODE_ADDRESS(ptr1 + BRAINCODE_BYTES_PER_INSTRUCTION); } } break; /** Add */ case BRAINCODE_ADD: if ((!is_constant0) && (!is_constant1)) { addr1[0] += addr0[0]; } else { addr1[0] += value0; } break; /** Subtract */ case BRAINCODE_SUB: if ((!is_constant0) && (!is_constant1)) { addr1[0] -= addr0[0]; } else { addr1[0] -= value0; } break; /** Multiply */ case BRAINCODE_MUL: if ((!is_constant0) && (!is_constant1)) { addr1[0] *= addr0[0]; } else { addr1[0] *= value0; } break; /** Divide */ case BRAINCODE_DIV: if ((!is_constant0) && (!is_constant1)) { addr1[0] >>= (addr0[0]%4); } else { addr1[0] >>= (value0%4); } break; /** Modulus */ case BRAINCODE_MOD: if ((!is_constant0) && (!is_constant1)) { if (addr0[0] != 0) { addr1[0] %= addr0[0]; } } else { if (value0 != 0) { addr1[0] %= value0; } } break; /** Count up or down */ case BRAINCODE_CTR: if (addr0[0] > 127) { if (addr1[0] < 255) { addr1[0]++; } else { addr1[0]=0; } } else { if (addr1[0] > 0) { addr1[0]--; } else { addr1[0]=255; } } break; /** Goto */ case BRAINCODE_JMP: { n_int v0 = is_const0; n_int v1 = is_const1; n_int i2 = (*i + (((v0*256) + v1)*BRAINCODE_BYTES_PER_INSTRUCTION)) % BRAINCODE_SIZE; if (i2 <= *i) { if ((*i-i2) < braincode_min_loop) { i2 = *i - braincode_min_loop; if (i2 < 0) i2 += BRAINCODE_SIZE; } } *i = i2-BRAINCODE_BYTES_PER_INSTRUCTION; break; } /** Goto if zero */ case BRAINCODE_JMZ: { n_int v0 = is_const0; if (v0 == 0) { n_int i2 = (*i + ((n_int) is_const1 *BRAINCODE_BYTES_PER_INSTRUCTION)) % BRAINCODE_SIZE; if (i2 <= *i) { if ((*i-i2) < braincode_min_loop) { i2 = *i - braincode_min_loop; if (i2 < 0) i2 += BRAINCODE_SIZE; } } *i = i2-BRAINCODE_BYTES_PER_INSTRUCTION; } break; } /** Goto if not zero */ case BRAINCODE_JMN: { n_int v0 = is_const0; if (v0 != 0) { n_int i2 = (*i + ((n_int) is_const1 *BRAINCODE_BYTES_PER_INSTRUCTION)) % BRAINCODE_SIZE; if (i2 <= *i) { if ((*i-i2) < braincode_min_loop) { i2 = *i - braincode_min_loop; if (i2 < 0) i2 += BRAINCODE_SIZE; } } *i = i2-BRAINCODE_BYTES_PER_INSTRUCTION; } break; } /** Goto and decrement if not zero */ case BRAINCODE_DJN: if (addr0[0]-1 != 0) { n_int i2 = (*i + ((n_int) is_const1 *BRAINCODE_BYTES_PER_INSTRUCTION)) % BRAINCODE_SIZE; addr0[0]--; if (i2 <= *i) { if ((*i-i2) < braincode_min_loop) { i2 = *i - braincode_min_loop; if (i2 < 0) i2 += BRAINCODE_SIZE; } } *i = i2-BRAINCODE_BYTES_PER_INSTRUCTION; } break; /** If two values are equal then skip the next n instructions */ case BRAINCODE_SEQ: if ((!is_constant0) && (!is_constant1)) { if (addr1[0] == addr0[0]) { *i = (*i + (BRAINCODE_BYTES_PER_INSTRUCTION * (1 + (n_int)pspace[0]))) % BRAINCODE_SIZE; } } else { if (addr1[0] == value0) { *i = (*i + (BRAINCODE_BYTES_PER_INSTRUCTION * (1 + (n_int)pspace[0]))) % BRAINCODE_SIZE; } } break; /** If two values are not equal then skip the next n instructions */ case BRAINCODE_SNE: if ((!is_constant0) && (!is_constant1)) { if (addr1[0] != addr0[0]) { *i = (*i + (BRAINCODE_BYTES_PER_INSTRUCTION * (1 + (n_int)pspace[0]))) % BRAINCODE_SIZE; } } else { if (addr1[0] != value0) { *i = (*i + (BRAINCODE_BYTES_PER_INSTRUCTION * (1 + (n_int)pspace[0]))) % BRAINCODE_SIZE; } } break; /** Skip the next n instructions if less than */ case BRAINCODE_SLT: if ((!is_constant0) && (!is_constant1)) { if (addr1[0] < addr0[0]) { *i = (*i + (BRAINCODE_BYTES_PER_INSTRUCTION * (1 + (n_int)pspace[0]))) % BRAINCODE_SIZE; } } else { if (addr1[0] < value0) { *i = (*i + (BRAINCODE_BYTES_PER_INSTRUCTION * (1 + (n_int)pspace[0]))) % BRAINCODE_SIZE; } } break; /** No operation (data only) */ case BRAINCODE_DAT0: case BRAINCODE_DAT1: break; /** swap */ case BRAINCODE_SWP: { n_byte tmp = addr0[0]; addr0[0] = addr1[0]; addr1[0] = tmp; break; } /** invert */ case BRAINCODE_INV: if (is_constant0) { addr0[0] = 255 - addr0[0]; } else { addr1[0] = 255 - addr1[0]; } break; /** Save to Pspace */ case BRAINCODE_STP: { n_byte v0 = (n_byte)is_const0; n_byte v1 = (n_byte)is_const1; pspace[v0 % BRAINCODE_PSPACE_REGISTERS] = v1; break; } /** Load from Pspace */ case BRAINCODE_LTP: { n_byte v0 = (n_byte)is_const0; addr1[0] = pspace[v0 % BRAINCODE_PSPACE_REGISTERS]; break; } } } /** * @brief Returns a sensor value * @param group Pointer to the simulated_group object * @param meeter_being Pointer to the being doing the meeting * @param met_being Pointer to the being which was met * @param meeter_social_graph Pointer to the meeter being's social graph * @param actor_index Social graph index of the being which is the current focus of attention * @param switcher The type of sensor * @return Sensor value */ static n_byte brain_first_sense(simulated_group * group, simulated_being * meeter_being, simulated_being * met_being, simulated_isocial * meeter_social_graph, n_int actor_index, n_byte switcher) { switch (switcher % 32) { case 0: return being_honor(meeter_being); case 1: return being_honor(met_being); case 2: return (n_byte)being_parasites(meeter_being); case 3: return (n_byte)being_parasites(met_being); case 4: return being_crowding(meeter_being); case 5: return being_family_first_name(meeter_being); case 6: return being_family_second_name(meeter_being); case 7: return being_family_first_name(met_being); case 8: return being_family_second_name(met_being); case 9: return being_facing(meeter_being); case 10: return being_facing(met_being); case 11: return being_speed(meeter_being); case 12: return meeter_social_graph[actor_index].familiarity&255; case 13: return meeter_social_graph[actor_index].friend_foe; case 14: return meeter_social_graph[actor_index].attraction; /** Location */ /* case 15: return (n_byte)(APESPACE_TO _MAPSPACE(being_location_x(meeter_being)) * 255 / land_map_dimension()); case 16: return (n_byte)(APESPACE_TO _MAPSPACE(being_location_y(meeter_being)) * 255 / land_map_dimension()); */ /** Being state (lower)*/ case 17: return (n_byte)(being_state(meeter_being)&255); /** Being state (upper)*/ case 18: return (n_byte)((being_state(meeter_being)>>8)&255); /** Drives */ case 19: return (n_byte)being_drive(meeter_being, DRIVE_HUNGER); case 20: return (n_byte)being_drive(meeter_being, DRIVE_SOCIAL); case 21: return (n_byte)being_drive(meeter_being, DRIVE_FATIGUE); case 22: return (n_byte)being_drive(meeter_being, DRIVE_SEX); /** Sexisms */ case 23: if (FIND_SEX(GET_I(meeter_being)) == FIND_SEX(GET_I(met_being))) { return 0; } else { return 255; } break; case 24: if (FIND_SEX(GET_I(met_being)) == SEX_FEMALE) { return 255; } else { return 0; } break; case 25: if (FIND_SEX(GET_I(met_being)) != SEX_FEMALE) { return 255; } else { return 0; } /** Overall grooming */ case 26: { n_int v=0; n_int n; for (n=0; n<INVENTORY_SIZE; n++) { if (met_being->changes.inventory[n] & INVENTORY_GROOMED) v++; } return (n_byte) (v<<4); } case 27: { n_int v=0; n_int n; for (n=0; n<INVENTORY_SIZE; n++) { if (meeter_being->changes.inventory[n] & INVENTORY_GROOMED) v++; } return (n_byte) (v<<4); } /** Wounds */ case 28: { n_int v=0; n_int n; for (n=0; n<INVENTORY_SIZE; n++) { if (met_being->changes.inventory[n] & INVENTORY_WOUND) v++; } return (n_byte) (v<<4); } case 29: { n_int v=0; n_int n; for (n=0; n<INVENTORY_SIZE; n++) { if (meeter_being->changes.inventory[n] & INVENTORY_WOUND) v++; } return (n_byte) (v<<4); } /** Posture */ case 30: return being_posture(meeter_being); } /** case 31: */ return being_posture(met_being); } static n_byte territory_familiarity(simulated_being * local_being, n_byte2 index) { n_byte result=0; #ifdef TERRITORY_ON n_uint familiarity = (n_uint)(local_being->events.territory[index].familiarity); n_uint i,max_familiarity = 1; /** find the maximum familiarity */ for (i=0; i<TERRITORY_AREA; i++) { if (local_being->events.territory[i].familiarity > max_familiarity) { max_familiarity = (n_uint)local_being->events.territory[i].familiarity; } } if (max_familiarity == 0) { return 0; } result = (n_byte)(familiarity*255/max_familiarity); #endif return result; } static void being_second_sense(simulated_group * group, n_byte addr00, n_byte * local_addr10, simulated_being * meeter_being, simulated_being * met_being, n_int actor_index, n_byte is_const1, n_int episode_index, simulated_iepisodic * episodic) { n_int new_episode_index=-1; n_int switcher = addr00%25; n_vect2 location; simulated_isocial * meeter_social_graph = being_social(meeter_being); n_int territory_index = (n_int)(being_attention(meeter_being,ATTENTION_TERRITORY)); n_int memory_visited[EPISODIC_SIZE]; n_int i; n_int relationship_index = (n_int)(being_attention(meeter_being,ATTENTION_RELATIONSHIP)); being_space(meeter_being, &location); land_convert_to_map(&location); /** clear episodes visited. This array helps to avoid repeatedly visiting the same memories */ for (i = 0; i < EPISODIC_SIZE; i++) { memory_visited[i] = 0; } switch (switcher) { /** Shift attention to a different actor */ case 0: actor_index = get_actor_index(meeter_social_graph, is_const1 % SOCIAL_SIZE); /** store the current focus of attention */ being_set_attention(meeter_being,ATTENTION_ACTOR, actor_index); break; /** Shift attention to a different episode */ case 1: new_episode_index = is_const1 % EPISODIC_SIZE; break; /** Shift attention to a different territory */ case 2: territory_index = is_const1; being_set_attention(meeter_being, ATTENTION_TERRITORY, territory_index); break; /** Shift attention to a body region */ case 3: being_set_attention(meeter_being,ATTENTION_BODY, is_const1 % INVENTORY_SIZE); break; case 4: /** Shift attention to a similar location */ new_episode_index = attention_similar_place(episode_index, episodic, memory_visited); break; case 5: /** Shift attention to a similar time */ new_episode_index = attention_similar_time(episode_index, episodic, memory_visited); break; case 6: /** Shift attention to a similar date */ new_episode_index = attention_similar_date(episode_index, episodic, memory_visited); break; case 7: /** Shift attention to a similar name */ new_episode_index = attention_similar_name(episode_index, episodic, meeter_being, memory_visited); break; case 8: /** Shift attention to a similar affect */ new_episode_index = attention_similar_affect(episode_index, episodic, memory_visited); break; case 9: *local_addr10 = episodic[episode_index].event; break; case 10: *local_addr10 = episodic[episode_index].food; break; case 11: *local_addr10 = episodic[episode_index].affect&255; break; case 12: *local_addr10 = episodic[episode_index].arg&255; break; case 13: *local_addr10 = (n_byte)(episodic[episode_index].space_time.location[0] * 255 / land_map_dimension()); break; case 14: *local_addr10 = (n_byte)(episodic[episode_index].space_time.location[1] * 255 / land_map_dimension()); break; case 15: { /** atmosphere pressure */ n_int pressure = weather_pressure(POSITIVE_LAND_COORD(location.x), POSITIVE_LAND_COORD(location.y)); if (pressure > 100000) pressure = 100000; if (pressure < 0) pressure = 0; *local_addr10 = (n_byte)(pressure>>9); break; } case 16: { /** wind magnitude */ n_vect2 wind; weather_wind_vector(&location, &wind); if (wind.x<0) wind.x=-wind.x; if (wind.y<0) wind.y=-wind.y; *local_addr10 = (n_byte)((wind.x+wind.y)>>7); break; } case 17: *local_addr10 = (n_byte)(land_time()>>3); break; case 18: /** attention to body */ *local_addr10 = being_attention(meeter_being,ATTENTION_BODY)*30; break; case 19: #ifdef TERRITORY_ON /** territory name */ *local_addr10 = meeter_being->events.territory[territory_index].name; #endif break; case 20: /** territory familiarity */ *local_addr10 = territory_familiarity(meeter_being,(n_byte2)territory_index); break; case 21: /** territory familiarity */ *local_addr10 = territory_familiarity(met_being,(n_byte2)territory_index); break; case 22: { /** carrying object */ n_byte2 carrying = being_carried(meeter_being,BODY_RIGHT_HAND); n_byte2 obj_type=0; if (carrying==0) carrying = being_carried(meeter_being,BODY_LEFT_HAND); if (carrying!=0) { /* TODO Is this willed into existence? */ switch(addr00%12) { case 0: obj_type = INVENTORY_BRANCH; break; case 1: obj_type = INVENTORY_TWIG; break; case 2: obj_type = INVENTORY_ROCK; break; case 3: obj_type = INVENTORY_SHELL; break; case 4: obj_type = INVENTORY_GRASS; break; case 5: obj_type = INVENTORY_NUT; break; case 6: obj_type = INVENTORY_NUT_CRACKED; break; case 7: obj_type = INVENTORY_SCRAPER; break; case 8: obj_type = INVENTORY_SPEAR; break; case 9: obj_type = INVENTORY_FISH; break; case 10: obj_type = INVENTORY_BIRD_EGGS; break; case 11: obj_type = INVENTORY_LIZARD_EGGS; break; } if (carrying & obj_type) { *local_addr10 = 255; } else { *local_addr10 = 0; } } break; } case 23: { /** shift attention to a given social graph entry based on relationship */ n_int idx = social_get_relationship(meeter_being, (n_byte)relationship_index); if (idx > -1) { actor_index = idx; /** store the current focus of attention */ being_set_attention(meeter_being,ATTENTION_ACTOR, actor_index); } break; } case 24: { /** shift attention to a different relationship type */ relationship_index = 1+(*local_addr10 % (OTHER_MOTHER-1)); /** store the current relationship attention */ being_set_attention(meeter_being,ATTENTION_RELATIONSHIP, relationship_index); break; } } /** If attention has shifted to a new episode */ if (new_episode_index > -1) { n_int possible_actor_index; episode_index = new_episode_index; being_set_attention(meeter_being,ATTENTION_EPISODE, episode_index); /** Shift attention to the being in this episode */ possible_actor_index = get_actor_index_from_episode(meeter_social_graph,episodic,episode_index); if (possible_actor_index>-1) { actor_index = possible_actor_index; /** store the change in attention */ being_set_attention(meeter_being,ATTENTION_ACTOR, actor_index); } /** set territory attention to the location where the episode occurred */ being_set_attention(meeter_being,ATTENTION_TERRITORY, (APESPACE_TO_TERRITORY(episodic[episode_index].space_time.location[1])*16)+ APESPACE_TO_TERRITORY(episodic[episode_index].space_time.location[0])); } } /** * @brief Returns a sensor value * @param group Pointer to the simulated_group object * @param meeter_being Pointer to the being doing the meeting * @param met_being Pointer to the being which was met * @param internal Non-zero if this is an internal dialogue * @param switcher The type of sensor * @param additional_write No operation value * @return Sensor value */ static n_byte brain_third_sense(simulated_group * group, simulated_being * meeter_being, simulated_being * met_being, n_byte internal, n_byte switcher, n_byte * additional_write) { n_byte half_switcher = switcher >> 1; simulated_being * important_being = ((switcher & 1) ? met_being : meeter_being); n_genetics * genetics = being_genetics(important_being); switch (half_switcher % 10) { /** Facial characteristics. Here we shift the 0-15 gene values into a 0-255 range */ case 0: return (n_byte)(GENE_EYE_SHAPE(genetics) << 4); case 1: return (n_byte)(GENE_EYE_COLOR(genetics) << 4); case 2: return (n_byte)(GENE_EYE_SEPARATION(genetics) << 4); case 3: return (n_byte)(GENE_NOSE_SHAPE(genetics) << 4); case 4: return (n_byte)(GENE_EAR_SHAPE(genetics) << 4); case 5: return (n_byte)(GENE_EYEBROW_SHAPE(genetics) << 4); case 6: return (n_byte)(GENE_MOUTH_SHAPE(genetics) << 4); case 7:/* healthyness */ { n_byte return_value = 0; #ifdef IMMUNE_ON n_int n; simulated_immune_system * immune = &(important_being->immune_system); return_value = immune->antigens[0]; for (n=1; n<IMMUNE_ANTIGENS; n++) { if (immune->antigens[n]>return_value) { return_value = immune->antigens[n]; } } #endif return return_value; } /** the 8 case is covered in the default: */ case 9: /** listen for shouts */ if ((internal!=0) && (!(being_state(meeter_being)&BEING_STATE_SHOUTING)) && (!(being_state(meeter_being)&BEING_STATE_SPEAKING)) && (meeter_being->changes.shout[SHOUT_HEARD]>0)) { return meeter_being->changes.shout[SHOUT_HEARD]; } break; break; /** listen for name shouts */ default: if (switcher == 16) /** positive affect */ { n_uint positive = being_affect(meeter_being,1)>>7; if (positive>255) positive=255; return (n_byte)positive; } { /* (switcher == 17) negative affect */ n_uint negative=being_affect(meeter_being,0)>>1; if (negative>255) negative=255; return (n_byte)negative; } } return additional_write[0]; /** no op case. Not sure if the compiler will recognize that though */ } static void brain_first_action(simulated_group * group, n_byte awake, n_byte * local_addr00, n_byte * local_addr10, simulated_being * meeter_being, simulated_being * met_being, n_int episode_index, simulated_iepisodic * episodic, n_byte pspace0, n_int actor_index, simulated_isocial * meeter_social_graph, n_byte is_const1) { switch(*local_addr00 % 6) { /** individual or social action */ case 0: if ((awake != 0) && (*local_addr00 > 127)) { if (meeter_being == met_being) { social_action(meeter_being, 0L, *local_addr10); } else { social_action(meeter_being, met_being, *local_addr10); } *local_addr00 = 0; } break; /** Set location goal */ case 1: if (!(meeter_being->braindata.script_overrides&OVERRIDE_GOAL)) { being_set_goal_location(meeter_being, episodic[episode_index].space_time.location[0], episodic[episode_index].space_time.location[1]); } break; /** alter friend or foe value */ case 2: { n_byte fof0 = pspace0; n_byte fof1 = *local_addr10; if (fof0 > (n_byte)(fof1 + 85)) { if (meeter_social_graph[actor_index].friend_foe < 170) { meeter_social_graph[actor_index].friend_foe++; } } if (fof1>(n_byte)(fof0+85)) { if (meeter_social_graph[actor_index].friend_foe > 85) { meeter_social_graph[actor_index].friend_foe--; } } break; } /** alter attraction */ case 3: { n_byte att0 = *local_addr10; n_byte att1 = pspace0; if (att0>(n_byte)(att1+85)) { if (meeter_social_graph[actor_index].attraction < 255) { meeter_social_graph[actor_index].attraction++; } } if (att1>(n_byte)(att0+85)) { if (meeter_social_graph[actor_index].attraction > 16) { meeter_social_graph[actor_index].attraction--; } } break; } /** alter familiarity */ case 4: /** The values 10 and 20 meetings were just found experimentally */ if ((*local_addr10>100) && (*local_addr10<150)) { if (meeter_social_graph[actor_index].familiarity < 65535) { meeter_social_graph[actor_index].familiarity++; *local_addr10 = 0; } } if ((*local_addr10>150) && (*local_addr10<200)) { if (meeter_social_graph[actor_index].familiarity > 10) { meeter_social_graph[actor_index].familiarity--; *local_addr10 = 0; } } break; /** brainprobe frequency */ case 5: { n_int n = pspace0 % BRAINCODE_PROBES; n_byte f = 1 + (is_const1 % BRAINCODE_MAX_FREQUENCY); meeter_being->braindata.brainprobe[n].frequency = f; break; } } } #define IS_CONST0 (is_constant0 ? value0 : addr0[0]) #define IS_CONST1 (is_constant1 ? value1 : addr1[0]) /** * @brief Two beings meet and chat, or a being engages in an internal dialogue * @param group Pointer to the simulated_group object * @param awake Whether the being is awake * @param meeter_being Pointer to the being doing the meeting * @param met_being Pointer to the being which was met * @param bc0 Braincode of the meeter * @param bc1 Braincode of the met * @param being_index Social graph index of the being which is the current focus of attention */ void brain_dialogue( simulated_group* group, n_byte awake, simulated_being * meeter_being, simulated_being * met_being, n_byte * bc0, n_byte * bc1, n_int being_index) { #ifdef EPISODIC_ON n_byte internal = (meeter_being == met_being); const n_int braincode_min_loop = 8*BRAINCODE_BYTES_PER_INSTRUCTION; n_int i = 0, itt = 0; n_int actor_index; n_int episode_index = (n_int)(being_attention(meeter_being,ATTENTION_EPISODE)); n_int anecdote_episode_index=-1; n_int intention_episode_index=-1; simulated_isocial * meeter_social_graph = being_social(meeter_being); simulated_iepisodic * episodic = being_episodic(meeter_being); n_int max_itterations; n_byte * pspace = (n_byte*)meeter_being->braindata.braincode_register; /* what is the current actor index within episodic memory? */ if (being_index>-1) { actor_index = being_index; } else { being_index = being_attention(meeter_being,ATTENTION_ACTOR); actor_index = being_index; } if (meeter_being == met_being) { /** fixed number of itterations for internal dialogue */ max_itterations = BRAINCODE_MAX_ADDRESS/BRAINCODE_BYTES_PER_INSTRUCTION; } else { /** variable number of itterations for chat */ max_itterations = 8 + meeter_being->changes.learned_preference[PREFERENCE_CHAT]; } i = 0; while (itt<max_itterations) { n_byte instruction = BRAINCODE_INSTRUCTION(bc0, i); n_byte is_constant0 = BRAINCODE_CONSTANT0(bc0, i); n_byte is_constant1 = BRAINCODE_CONSTANT1(bc0, i); n_byte value0 = BRAINCODE_VALUE(bc0, i, 0); n_byte value1 = BRAINCODE_VALUE(bc0, i, 1); n_byte *addr0 = math_general_allocation(bc0, bc1, i+value0); n_byte *addr1 = math_general_allocation(bc0, bc1, i+value1); switch(instruction) { /** General sensor */ case BRAINCODE_SEN: { addr1[0] = brain_first_sense(group, meeter_being, met_being, meeter_social_graph, actor_index, addr0[0]); break; } case BRAINCODE_SEN2: { being_second_sense(group, addr0[0], &addr1[0], meeter_being, met_being, actor_index, IS_CONST1, episode_index, episodic); break; } case BRAINCODE_SEN3: addr1[0] = brain_third_sense(group, meeter_being, met_being, internal, addr0[0], addr1); break; /** Action */ case BRAINCODE_ACT: { brain_first_action(group, awake, &addr0[0], &addr1[0], meeter_being, met_being, episode_index, episodic, pspace[0], actor_index, meeter_social_graph, IS_CONST1); break; } case BRAINCODE_ACT2: { switch(addr0[0]%6) { case 0: /* brainprobe type */ { n_int n = pspace[0] % BRAINCODE_PROBES; n_byte typ = IS_CONST1 & 1; meeter_being->braindata.brainprobe[n].type = typ; break; } case 1: /** brainprobe address */ { n_int n = pspace[0] % BRAINCODE_PROBES; n_byte adr = IS_CONST1; meeter_being->braindata.brainprobe[n].address = adr; break; } case 2: /** shout out */ { n_byte msg = addr1[0]; if (is_constant1) { msg = value1; } if ((internal!=0) && (awake!=0) && (!(being_state(meeter_being)&BEING_STATE_SHOUTING)) && (!(being_state(meeter_being)&BEING_STATE_SPEAKING)) && (meeter_being->changes.shout[SHOUT_CONTENT]==0) && (meeter_being->changes.shout[SHOUT_HEARD]==0) && (meeter_being->changes.shout[SHOUT_CTR]==0) && (msg>0)) { meeter_being->changes.shout[SHOUT_CTR] = SHOUT_REFRACTORY; being_add_state(meeter_being, BEING_STATE_SHOUTING); /** volume of message */ meeter_being->changes.shout[SHOUT_VOLUME] = pspace[0]; /** type of message */ meeter_being->changes.shout[SHOUT_CONTENT] = msg; } break; } case 3: /** intention */ { if (intention_episode_index != episode_index) { n_byte v0 = pspace[0]; n_byte v1 = IS_CONST1; if (episodic_intention(meeter_being, episode_index, (n_byte2)(v0*10), v1)!=0) { intention_episode_index = episode_index; } } break; } case 4: /** brainprobe offset */ { n_int n = pspace[0] % BRAINCODE_PROBES; n_byte offset = IS_CONST1; meeter_being->braindata.brainprobe[n].offset = offset; break; } case 5: /** posture */ if (awake != 0) { being_set_posture(meeter_being, addr1[0]); } break; } break; } case BRAINCODE_ACT3: switch(addr0[0]%2) { /** brainprobe position */ case 0: { n_int n = pspace[0] % BRAINCODE_PROBES; n_byte p = IS_CONST1; meeter_being->braindata.brainprobe[n].position = p; break; } /** alter learned preferences */ case 1: { n_int n; n_byte prf = addr1[0]; n = pspace[0]%PREFERENCES; if ((prf > 55) && (prf < 155)) { if (meeter_being->changes.learned_preference[n] < 255) { meeter_being->changes.learned_preference[n]++; addr1[0] = 0; } } if (prf >= 155) { if (meeter_being->changes.learned_preference[n] > 0) { meeter_being->changes.learned_preference[n]--; addr1[0] = 0; } } break; } break; } /** spread anecdote */ case BRAINCODE_ANE: if (internal == 0) { /** not internal dialogue */ /** avoid repeated anecdotes in the same conversation */ if (anecdote_episode_index != episode_index) { if (episodic_anecdote(meeter_being, met_being) != 0) { anecdote_episode_index = episode_index; } } } break; default: math_general_execution(instruction, is_constant0, is_constant1, addr0, addr1, value0, &i, IS_CONST0, IS_CONST1, pspace, bc0, bc1, braincode_min_loop); break; } i += BRAINCODE_BYTES_PER_INSTRUCTION; itt++; if (i >= BRAINCODE_SIZE) { i -= BRAINCODE_SIZE; } } #endif } #endif <|start_filename|>sim/land.c<|end_filename|> /**************************************************************** land.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #include "../toolkit/toolkit.h" #include "sim.h" /* Resources Wood Meat - Fish Meat - Animals Gold Silver Tin Lead Copper Stone Limestone Landscape Changes Path Road Hut Smelter/Blacksmith Boat Building Boat Posessions ? */ static n_land m_land; n_byte * land_topography_highdef(void) { return m_land.topography_highdef; } n_land * land_ptr(void) { return &m_land; } n_byte4 land_date(void) { return m_land.date; } n_byte4 land_time(void) { return m_land.time; } n_byte land_tide_level(void) { return m_land.tide_level; } n_byte4 * land_highres_tide(void) { return (n_byte4 *)m_land.highres_tide; } void land_cycle(void) { m_land.time++; if (m_land.time == TIME_DAY_MINUTES) { m_land.time = 0; m_land.date++; } land_tide(); } /* all this hardcoding will need to be de-hardcoded in the future */ void math_bilinear_8_times(n_byte * side512, n_byte * data, n_byte double_spread) { n_int loop_y = 0; NA_ASSERT(side512, "side512 NULL"); NA_ASSERT(data, "data NULL"); if (side512 == 0L) return; if (data == 0L) return; while (loop_y < HI_RES_MAP_DIMENSION) { n_int loop_x = 0; while (loop_x < HI_RES_MAP_DIMENSION) { /* find the micro x (on the map used for bilinear interpolation) */ n_int mic_x = ( loop_x & 7); /* find the micro y (on the map used for bilinear interpolation) */ n_int mic_y = ( loop_y & 7); n_int mac_x = (loop_x >> 3); n_int mac_y = (loop_y >> 3); n_uint px0 = (n_uint)(mac_x); n_uint py0 = (n_uint)(mac_y * MAP_DIMENSION); n_uint px1 = (mac_x + 1) & (MAP_DIMENSION-1); n_uint py1 = ((mac_y + 1) & (MAP_DIMENSION-1)) * MAP_DIMENSION; n_int z00 = side512[px0|py0]; n_int z01 = side512[px1|py0]; n_int z10 = side512[px0|py1] - z00; n_int z11 = side512[px1|py1] - z01 - z10; n_uint point = (n_uint)(loop_x + (loop_y * HI_RES_MAP_DIMENSION)); n_byte value; z01 = (z01 - z00) << 3; z10 = z10 << 3; value = (n_byte)((z00 + (((z01 * mic_x) + (z10 * mic_y) + (z11 * mic_x * mic_y) ) >> 6))); if (double_spread) { data[(point<<1)|1] = data[point<<1] = value; } else { data[point] = value; } loop_x++; } loop_y++; } } #define OPERATOR_AREA(fg, dfg, fdg) ((((dfg) * (dfg)) + ((fdg) * (fdg))) >> 6) #define OPERATOR_HEIGHT(fg, dfg, fdg) (((WATER_MAP + fg) * (WATER_MAP + fg)) >> 8 ) #define OPERATOR_WATER(fg, dfg, fdg) (((WATER_MAP - fg) * (WATER_MAP - fg)) >> 8 ) #define OPERATOR_SUN(fg, dfg, fdg, ct, st) (((((ct) * (fg)) + ((st) * (dfg))) >> 4) + WATER_MAP) #define OPERATOR_SALT(fg, dfg, fdg, fs) (((fs*fs)+(dfg*fdg))>>4) #define WATER_MAP2 (WATER_MAP * 2) static n_int land_operator(n_int locx, n_int locy, n_byte *specific_kind) { n_int temp = 0, temp_add; n_int number_sum = 0; n_int fg; n_int dfg; n_int fdg; NA_ASSERT(specific_kind, "specific_kind NULL"); fg = land_location(locx, locy); dfg = land_location(locx + 1, locy); fdg = land_location(locx, locy + 1); dfg = (dfg - fg) * 8; fdg = (fdg - fg) * 8; fg = fg - WATER_MAP; if(specific_kind[0] != '.') { number_sum ++; temp_add = OPERATOR_AREA(fg, dfg, fdg); /* A */ if(specific_kind[0] == '+') temp += temp_add; else temp += WATER_MAP2 - temp_add; } if(specific_kind[1] != '.') { number_sum ++; temp_add = OPERATOR_HEIGHT(fg, dfg, fdg); /* H */ if(specific_kind[1] == '+') temp += temp_add; else temp += WATER_MAP2 - temp_add; } if(specific_kind[2] != '.') { number_sum ++; temp_add = OPERATOR_WATER(fg, dfg, fdg); /* W */ if(specific_kind[2] == '+') temp += temp_add; else temp += WATER_MAP2 - temp_add; } if(specific_kind[3] != '.') { if(IS_NIGHT(m_land.time) == 0) { /* 180 is minutes in the day / 8 */ n_int hr = ((((m_land.time << 6) / 180) + 32) & 255); n_int weather = weather_seven_values(MAPSPACE_TO_APESPACE(locx), MAPSPACE_TO_APESPACE(locy)); n_int weather_divide = (105 + ((weather % 3) * 30)); n_vect2 time_weather; vect2_direction(&time_weather, hr, weather_divide * 32); vect2_offset(&time_weather, 840/ weather_divide, 840/ weather_divide); number_sum ++; temp_add = OPERATOR_SUN(fg, dfg, fdg, time_weather.x, time_weather.y); /* O */ if(specific_kind[3] == '+') temp += temp_add; else temp += WATER_MAP2 - temp_add; } } if(specific_kind[4] != '.') { number_sum ++; temp_add = OPERATOR_SUN(fg, dfg, fdg, 11, 11); /* U */ if(specific_kind[4] == '+') temp += temp_add; else temp += WATER_MAP2 - temp_add; } if(specific_kind[5] != '.') { n_int fs = -(fg - TIDE_AMPLITUDE_LUNAR - TIDE_AMPLITUDE_SOLAR); if ((fs < 0) || (fs > (TIDE_AMPLITUDE_LUNAR + TIDE_AMPLITUDE_SOLAR)*2)) { if(specific_kind[5] == '+') temp=0; } else { number_sum ++; if(specific_kind[5] == '+') temp += OPERATOR_SALT(fg, dfg, fdg, fs); /* S */ } } NA_ASSERT(number_sum, "number_sum is ZERO"); if(number_sum != 0) { temp = temp / number_sum; } return (temp); } n_int land_operator_interpolated(n_int locx, n_int locy, n_byte * kind) { n_int map_dimension = land_map_dimension(); n_int map_x = APESPACE_TO_MAPSPACE(locx); n_int map_y = APESPACE_TO_MAPSPACE(locy); n_int interpolated; NA_ASSERT(kind, "kind NULL"); /* Not bilinear interpolation but linear interpolation. Probably should replace with bilinear (ie each value has x and y dependency) */ interpolated = (land_operator((map_x+1)&(map_dimension-1), map_y, kind)*(locx-(map_x << APE_TO_MAP_BIT_RATIO))) >> APE_TO_MAP_BIT_RATIO; interpolated += (land_operator((map_x-1)&(map_dimension-1), map_y, kind)*(((map_x+1)<<APE_TO_MAP_BIT_RATIO)-locx)) >> APE_TO_MAP_BIT_RATIO; interpolated += (land_operator(map_x, (map_y+1)&(map_dimension-1), kind)*(locy-(map_y<<APE_TO_MAP_BIT_RATIO))) >> APE_TO_MAP_BIT_RATIO; interpolated += (land_operator(map_x, (map_y-1)&(map_dimension-1), kind)*(((map_y+1)<<APE_TO_MAP_BIT_RATIO)-locy)) >> APE_TO_MAP_BIT_RATIO; return interpolated >> 1; } n_int land_location_vect(n_vect2 * value) { return land_location(value->x, value->y); } weather_values weather_seven_values(n_int px, n_int py) { n_byte ret_val; n_int val; n_int map_x = POSITIVE_LAND_COORD(APESPACE_TO_MAPSPACE(px)); n_int map_y = POSITIVE_LAND_COORD(APESPACE_TO_MAPSPACE(py)); if(IS_DAWNDUSK(m_land.time)) { return WEATHER_SEVEN_DAWN_DUSK; } if(IS_NIGHT(m_land.time)) { ret_val = WEATHER_SEVEN_CLEAR_NIGHT; } else { ret_val = WEATHER_SEVEN_SUNNY_DAY; } val = weather_pressure(map_x, map_y); if ( val == -1) { return WEATHER_SEVEN_ERROR; /* Error has already been shown */ } if(val > WEATHER_RAIN) { return ret_val+2; } if(val > WEATHER_CLOUD) { return ret_val+1; } return ret_val; } n_int land_map_dimension(void) { return MAP_DIMENSION; } n_int land_map_bits(void) { return MAP_BITS; } n_byte2 * land_genetics(void) { return (n_byte2 *)m_land.tiles[0].genetics; } n_byte * land_topography(void) { return (n_byte *)m_land.tiles[0].topography; } n_c_int * land_weather(n_int tile) { return (n_c_int *)m_land.tiles[tile].atmosphere; } void weather_cycle(void) { tile_cycle(&m_land); /* tile_cycle(&m_land); tile_cycle(&m_land); */ tile_wind(&m_land); } void weather_init(void) { tile_weather_init(&m_land); } n_int weather_pressure(n_int px, n_int py) { return tiles_atmosphere(&m_land, 0, 0, px, py); } /* * The weather is maintained in a 18-bit band from bits_neg */ void weather_wind_vector(n_vect2 * pos, n_vect2 * wind) { n_int local_pressure; NA_ASSERT(pos, "pos NULL"); NA_ASSERT(wind, "wind NULL"); if (pos == 0L) return; if (wind == 0L) return; local_pressure = weather_pressure(pos->x, pos->y); wind->x = local_pressure - weather_pressure(pos->x - WEATHER_TO_MAPSPACE(1), pos->y); wind->y = local_pressure - weather_pressure(pos->x, pos->y - WEATHER_TO_MAPSPACE(1)); } n_byte * land_location_tile(n_int tile) { return tiles_topography_map(&m_land, tile, 0); } n_int land_location(n_int px, n_int py) { return tiles_topography(&m_land, 0, 0, px, py); } void land_tide(void) { n_int current_time = m_land.time + (m_land.date * TIME_DAY_MINUTES); n_int lunar_mins = current_time % LUNAR_ORBIT_MINS; n_int lunar_angle_256 = (((m_land.time * 255) / 720)+((lunar_mins * 255) / LUNAR_ORBIT_MINS)); n_int solar_mins = current_time % (TIME_DAY_MINUTES * TIME_YEAR_DAYS); n_int solar_angle_256 = (solar_mins * 255) / (TIME_DAY_MINUTES * TIME_YEAR_DAYS); n_int lunar = math_sine(lunar_angle_256, NEW_SD_MULTIPLE / TIDE_AMPLITUDE_LUNAR); n_int solar = math_sine(solar_angle_256, NEW_SD_MULTIPLE / TIDE_AMPLITUDE_SOLAR); NA_ASSERT((((WATER_MAP + lunar + solar) > -1) && ((WATER_MAP + lunar + solar) < 256)), "(WATER_MAP + lunar + solar) outside byte boundaries"); m_land.tide_level = (n_byte)(WATER_MAP + lunar + solar); } void land_clear(KIND_OF_USE kind, n_byte4 start) { tile_land_erase(&m_land); if (kind != KIND_LOAD_FILE) { m_land.time = 5 * TIME_HOUR_MINUTES; m_land.date = start; } } void land_seed_genetics(n_byte2 * local_random) { tile_land_random(&m_land, local_random); } void land_init(void) { tile_land_init(&m_land); } void land_init_high_def(n_byte double_spread) { n_uint lp = 0; n_byte4 value_setting = 0; math_bilinear_8_times((n_byte *)m_land.tiles[0].topography[0], m_land.topography_highdef, double_spread); memory_erase((n_byte *)m_land.highres_tide, sizeof(n_byte4) * HI_RES_MAP_AREA/32); while (lp < HI_RES_MAP_AREA) { n_byte val = m_land.topography_highdef[lp<<1]; if ((val > 105) && (val < 151)) { value_setting |= 1 << (lp & 31); } if ((lp & 31) == 31) { m_land.highres_tide[ lp >> 5 ] = value_setting; value_setting = 0; } lp++; } } void land_vect2(n_vect2 * output, n_int * actual_z, n_vect2 * location) { n_int loc_x; n_int loc_y; n_int z; NA_ASSERT(output, "output NULL"); NA_ASSERT(actual_z, "actual_z NULL"); NA_ASSERT(location, "location NULL"); if (output == 0L) return; if (location == 0L) return; loc_x = location->x; loc_y = location->y; z = land_location(APESPACE_TO_MAPSPACE(loc_x), APESPACE_TO_MAPSPACE(loc_y)); if (actual_z != 0L) { *actual_z = z; } output->x = (z - land_location((APESPACE_TO_MAPSPACE(loc_x) + 1), APESPACE_TO_MAPSPACE(loc_y))); output->y = (z - land_location(APESPACE_TO_MAPSPACE(loc_x), (APESPACE_TO_MAPSPACE(loc_y) + 1))); } n_int spacetime_after(n_spacetime * initial, n_spacetime * second) { if (initial->date < second->date) { return 0; } if (initial->date > second->date) { return 1; } if (initial->time > second->time) { return 1; } return 0; } n_int spacetime_before_now(n_spacetime * initial) { if (initial->date > m_land.date) { return 0; } if (initial->date < m_land.date) { return 1; } if (initial->time < m_land.time) { return 1; } return 0; } void spacetime_copy(n_spacetime * to, n_spacetime * from) { to->location[0] = from->location[0]; to->location[1] = from->location[1]; to->date = from->date; to->time = from->time; } void spacetime_set(n_spacetime * set, n_byte2 * location) { set->location[0] = location[0]; set->location[1] = location[1]; set->time = m_land.time; set->date = m_land.date; } void land_convert_to_map(n_vect2 * value) { value->x = APESPACE_TO_MAPSPACE(value->x); value->y = APESPACE_TO_MAPSPACE(value->y); } static n_byte2 color_group[256*3]; static n_byte land_color_initialized = 0; #define SUBSTA(c) ((c<<8)|c) void land_color_init(void) { static n_byte points[] = { 0, 0, 0, 0, 106, 43, 70, 120, 125, 107, 201, 202, 128, 255, 255, 239, 150, 88, 169, 79, 190, 8, 15, 7, 208, 208, 216, 206, 255, 255, 255, 255 }; /* performs a linear interpolation of n 8-bit points to 256 16-bit blend values */ n_int lp = 0, lp2 = 0; n_int dr = 0, dg = 0, db = 0; n_int ar = 0, ag = 0, ab = 0, cntr = 0; n_int fp = 0, fl = 0, del_c = 0; while (lp < 256) { if (lp == points[cntr]) { ar = SUBSTA(points[(cntr) | 1]); ag = SUBSTA(points[(cntr) | 2]); ab = SUBSTA(points[(cntr) | 3]); fp = lp; cntr += 4; if (lp != 255) { fl = points[cntr]; del_c = (fl - fp); dr = SUBSTA(points[(cntr) | 1]); dg = SUBSTA(points[(cntr) | 2]); db = SUBSTA(points[(cntr) | 3]); } } if (del_c == 0) { return; } if (lp != 255) { n_int del_a = (fl - lp), del_b = (lp - fp); color_group[lp2++] = (n_byte2)(((ar * del_a) + (dr * del_b)) / del_c); color_group[lp2++] = (n_byte2)(((ag * del_a) + (dg * del_b)) / del_c); color_group[lp2++] = (n_byte2)(((ab * del_a) + (db * del_b)) / del_c); } else { color_group[lp2++] = (n_byte2)(ar); color_group[lp2++] = (n_byte2)(ag); color_group[lp2++] = (n_byte2)(ab); } lp ++; } color_group[(COLOR_WHITE*3) ] = 0xffff; color_group[(COLOR_WHITE*3) + 1] = 0xffff; color_group[(COLOR_WHITE*3) + 2] = 0xffff; color_group[(COLOR_BLUE*3) ] = 0x5500; color_group[(COLOR_BLUE*3) + 1] = 0x5500; color_group[(COLOR_BLUE*3) + 2] = 0xeeff; color_group[(COLOR_RED_DARK*3) ] = (0xeeff * 2) >> 2; /* return to * 3 following debugging */ color_group[(COLOR_RED_DARK*3) + 1] = 0x0000; color_group[(COLOR_RED_DARK*3) + 2] = 0x0000; color_group[(COLOR_RED*3) ] = 0xeeff; color_group[(COLOR_RED*3) + 1] = 0x0000; color_group[(COLOR_RED*3) + 2] = 0x0000; } void land_color_time(n_byte2 * color_fit, n_int toggle_tidedaylight) { n_int day_rotation = ((land_time() * 255)/TIME_DAY_MINUTES); n_int darken = math_sine(day_rotation + 64 + 128, NEW_SD_MULTIPLE / 400); n_int loop = 0; n_int sign = 1; if (land_color_initialized == 0) { land_color_init(); land_color_initialized = 1; } if (!toggle_tidedaylight) { if (darken < 1) { sign = -1; } darken = (darken * darken) / 402; darken = (sign * darken) + 624; while(loop < (NON_INTERPOLATED * 3)) { n_int cg_val = color_group[loop]; n_int response = (cg_val * darken) >> 10; color_fit[loop] = (n_byte2)response; loop++; } } while(loop < (256 * 3)) { color_fit[loop] = color_group[loop]; loop++; } } void land_color_time_8bit(n_byte * color_fit, n_int toggle_tidedaylight) { n_int day_rotation = ((land_time() * 255)/TIME_DAY_MINUTES); n_int darken = math_sine(day_rotation + 64 + 128, NEW_SD_MULTIPLE / 400); n_int loop = 0; n_int sign = 1; if (land_color_initialized == 0) { land_color_init(); land_color_initialized = 1; } if (!toggle_tidedaylight) { if (darken < 1) { sign = -1; } darken = (darken * darken) / 402; darken = (sign * darken) + 624; while(loop < (NON_INTERPOLATED * 3)) { n_int cg_val = color_group[loop]; n_int response = (cg_val * darken) >> 10; color_fit[loop] = (n_byte)(response >> 8); loop++; } } while(loop < (256 * 3)) { color_fit[loop] = (n_byte)(color_group[loop] >> 8); loop++; } } void io_time_to_string(n_string value) { n_int minutes = land_time(); n_int days = land_date(); n_int military_time = (minutes % 60); n_int hours = (minutes/60); military_time += hours * 100; value[0] = '0' + (military_time / 1000) % 10; value[1] = '0' + (military_time / 100) % 10; value[2] = '0' + (military_time / 10) % 10; value[3] = '0' + (military_time / 1) % 10; value[4] = ':'; io_number_to_string(&value[5], (n_uint)days); } <|start_filename|>test/test_object.c<|end_filename|> /**************************************************************** test_object.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #include "../toolkit/toolkit.h" #include <stdio.h> n_int draw_error(n_constant_string error_text, n_constant_string location, n_int line_number) { if (error_text) { printf("ERROR: %s @ %s %ld\n", (n_constant_string)error_text, location, line_number); } return -1; } static n_object * check_element(n_int value) { n_string_block string_value = "0 The good ship"; string_value[0] += value; { n_object * element_obj = object_string(0L, "name", string_value); object_number(element_obj, "number", value); object_number(element_obj, "constant", 4321); return element_obj; } } static void check_object(void) { n_object * new_object = object_number(0L, "index", 1); n_object * sub_object = object_number(0L, "index", 2); n_array * new_array = array_number(-1); array_add(new_array, array_number(-1)); array_add(new_array, array_number(-1)); array_add(new_array, array_string("hello")); array_add(new_array, array_number(2)); array_add(new_array, array_string("is")); array_add(new_array, array_number(4)); array_add(new_array, array_string("it me")); array_add(new_array, array_number(50)); object_number(sub_object, "top", 3); object_array(sub_object, "array", new_array); array_add(new_array, array_number(10)); array_add(new_array, array_number(20)); array_add(new_array, array_number(30)); io_file_debug(obj_json(sub_object)); object_number(new_object, "top", 2); object_string(new_object, "name", "Benson"); object_string(new_object, "another", "corner"); io_file_debug(obj_json(new_object)); object_string(new_object, "name", "Kevin"); io_file_debug(obj_json(sub_object)); io_file_debug(obj_json(new_object)); { n_uint count = 1; n_object *being_object = check_element(0); n_array *beings = array_object(being_object); while (count < 9) { being_object = check_element(count++); array_add(beings, array_object(being_object)); } object_array(new_object, "beings", beings); } io_file_debug(obj_json(new_object)); object_object(new_object, "example", sub_object); io_file_debug(obj_json(new_object)); object_number(sub_object, "top", 4); io_file_debug(obj_json(new_object)); io_file_debug(obj_json(sub_object)); obj_free(&new_object); } int main(int argc, const char * argv[]) { printf(" --- test object --- start --------------------------------------------\n"); check_object(); printf(" --- test object --- end --------------------------------------------\n"); return 0; } <|start_filename|>universe/loop.c<|end_filename|> /**************************************************************** loop.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #include "../entity/entity.h" #include "universe.h" #include <stdio.h> void loop_no_thread(simulated_group * group, simulated_being * being_not, loop_fn bf_func, void * data) { n_uint loop = 0; while (loop < group->num) { simulated_being * output = &(group->beings[loop]); if (output != being_not) { bf_func(group, output, data); } loop++; } } void loop_being_no_sim(simulated_being * beings, n_uint number_beings, loop_no_sim_fn bf_func, void * data) { n_uint loop = 0; while (loop < number_beings) { simulated_being * output = &(beings[loop]); bf_func(output, data); loop++; } } static void loop_add_generic(execute_function * function, void * general_data, void * read_data, void * write_data, n_int count, n_int size) { if (size) { n_byte *location = (n_byte *)read_data; n_int loop = 0; while (loop < count) { if (function(general_data, (void *)&location[loop * size], 0L) == -1) { break; } loop++; } } else { function(general_data,read_data,write_data); } } void loop_being(simulated_group * group, loop_fn bf_func, n_int beings_per_thread) { n_uint loop = 0; n_uint count = (n_uint)beings_per_thread; n_uint beings_per_thread_uint = (n_uint)beings_per_thread; while (loop < group->num) { simulated_being * output = &(group->beings[loop]); if ((beings_per_thread_uint + loop) >= group->num) { count = group->num - loop; } loop_add_generic((execute_function*)bf_func, (void*)group, (void*)output, 0L, (n_int)count, sizeof(simulated_being)); if (count != beings_per_thread_uint) { break; } else { loop += count; } } } typedef struct { n_string name; simulated_being * being_from_name; } being_from_name_loop_struct; static void being_from_name_loop(simulated_group * group, simulated_being * local, void * data) { being_from_name_loop_struct * bfns = (being_from_name_loop_struct *)data; n_string_block str; if (bfns->being_from_name) { return; } being_name_simple(local, str); io_lower(str, io_length(str,STRING_BLOCK_SIZE)); if (io_find(str,0,io_length(str,STRING_BLOCK_SIZE),bfns->name,io_length(bfns->name,STRING_BLOCK_SIZE))>-1) { bfns->being_from_name = local; } } /** * @brief return the being array index with the given name * @param group Pointer to the simulated_group object * @param name Name of the being * @return Array index of the being within the simulation object */ simulated_being * being_from_name(simulated_group * group, n_string name) { being_from_name_loop_struct bfns; bfns.being_from_name = 0L; io_lower(name, io_length(name,STRING_BLOCK_SIZE)); bfns.name = name; loop_no_thread(group, 0L, being_from_name_loop, &bfns); return bfns.being_from_name; } void being_set_select_name(simulated_group * group, n_string name) { simulated_being * response = being_from_name(group, name); if (response == 0L) { (void)SHOW_ERROR("Ape not found"); return; } group->select = response; } n_string being_get_select_name(simulated_group * group) { static n_string_block name; n_int position = 0; if (group->select == 0L) { io_string_write(name,"*** ALL APES DEAD ***", &position); } else { being_name_simple(group->select, name); } return (n_string)name; } typedef struct { n_int parse_requirements; n_int older; n_uint comparison_best; n_int actual_age; n_genetics * genetics; simulated_being * return_value; } being_find_closest_struct; static void being_find_closest_loop(simulated_group * group, simulated_being * local, void * data) { being_find_closest_struct * bfcs = (being_find_closest_struct *)data; n_byte success = 0; n_int local_dob = being_dob(local); if (bfcs->older == 0) success = 1; if ((bfcs->older == 1) && ((local_dob - AGE_OF_MATURITY) > bfcs->actual_age)) { success = 1; } if ((bfcs->older == -1) && ((bfcs->actual_age - AGE_OF_MATURITY) > local_dob)) { success = 1; } if (success) { n_uint comparison = being_genetic_comparison(bfcs->genetics, being_genetics(local), bfcs->parse_requirements); if (comparison > bfcs->comparison_best) { bfcs->comparison_best = comparison; bfcs->return_value = local; } } } static simulated_being * being_find_closest(simulated_group * group, simulated_being * actual, n_int parse_requirements, n_int older) { being_find_closest_struct bfcs; bfcs.parse_requirements = parse_requirements; bfcs.older = older; /** comparison must be better than average */ bfcs.comparison_best = 3 * sizeof(n_genetics) * CHROMOSOMES; bfcs.return_value = 0L; bfcs.genetics = being_genetics(actual); bfcs.actual_age = being_dob(actual); loop_no_thread(group, actual, being_find_closest_loop, &bfcs); return bfcs.return_value; } typedef struct { n_uint comparison_best; n_int max_age; n_genetics * genetics; simulated_being * return_value; } being_find_child_struct; static void being_find_child_loop(simulated_group * group, simulated_being * local, void * data) { being_find_child_struct * bfcs = (being_find_child_struct *) data; n_uint comparison = being_genetic_comparison(bfcs->genetics, being_genetics(local), -1); if ((comparison > bfcs->comparison_best) && ((land_date() - being_dob(local)) < bfcs->max_age)) { bfcs->comparison_best = comparison; bfcs->return_value = local; } } static simulated_being * being_find_child(simulated_group * group, n_genetics * genetics, n_int max_age) { being_find_child_struct bfcs; bfcs.comparison_best = 0; bfcs.max_age = max_age; bfcs.genetics = genetics; bfcs.return_value = 0L; loop_no_thread(group, 0L, being_find_child_loop, &bfcs); return bfcs.return_value; } typedef struct { n_byte2 first_gender; n_byte2 family; simulated_being * local; } being_find_name_struct; static void being_find_name_loop(simulated_group * group, simulated_being * local, void * data) { being_find_name_struct * bfns = (being_find_name_struct *)data; if (bfns->local == 0L) { if (being_name_comparison(local, bfns->first_gender, bfns->family)) { bfns->local = local; } } } simulated_being * being_find_name(simulated_group * group, n_byte2 first_gender, n_byte2 family) { being_find_name_struct bfns; bfns.first_gender = first_gender; bfns.family = family; bfns.local = 0L; loop_no_thread(group, 0L, being_find_name_loop, &bfns); return bfns.local; } /** returns the total positive and negative affect within memory */ n_uint being_affect(simulated_being * local, n_byte is_positive) { n_uint affect = 0; #ifdef EPISODIC_ON n_uint i; simulated_iepisodic * local_episodic = being_episodic(local); if (!local_episodic) return affect; for (i=0; i<EPISODIC_SIZE; i++) { if (is_positive!=0) { if (local_episodic[i].affect>EPISODIC_AFFECT_ZERO) { affect += (n_uint)(local_episodic[i].affect) - EPISODIC_AFFECT_ZERO; } } else { if (local_episodic[i].affect<EPISODIC_AFFECT_ZERO) { affect += EPISODIC_AFFECT_ZERO - (n_uint)(local_episodic[i].affect); } } } #endif return affect; } const n_string body_inventory_description[INVENTORY_SIZE] = { "Head","Teeth","Back","Front","Left hand","Right hand","Left foot","Right foot" }; n_string being_body_inventory_description(n_int index) { return body_inventory_description[index % INVENTORY_SIZE]; } const n_string relationship_description[RELATIONSHIPS] = { "Associate","Self","Mother","Father","Daughter", "Son","Granddaughter","Grandson","Sister","Brother", "Maternal Grandmother","Maternal Grandfather","Paternal Grandmother","Paternal Grandson", "Mother", "Father","Daughter","Son","Granddaughter","Grandson", "Sister","Brother","Maternal Grandmother","Maternal Grandfather","Paternal Grandmother", "Paternal Grandson" }; void being_relationship_description(n_int index, n_string description) { n_int position = 0; if (index >= RELATIONSHIPS) { n_string_block index_string; io_number_to_string(index_string, (n_uint)index); io_three_strings(description, "ERROR: relationship out of range ", index_string, "", 1); return; } io_string_write(description, relationship_description[index], &position); } static void being_inventory_string(n_string string, n_int * location, n_int item) { switch (item) { case INVENTORY_BRANCH: io_string_write(string,"branch",location); break; case INVENTORY_ROCK: io_string_write(string,"rock",location); break; case INVENTORY_SHELL: io_string_write(string,"shell",location); break; case INVENTORY_TWIG: io_string_write(string,"twig",location); break; case INVENTORY_NUT_CRACKED: io_string_write(string,"cracked nut",location); break; case INVENTORY_GRASS: io_string_write(string,"piece of grass",location); break; case INVENTORY_SCRAPER: io_string_write(string,"scraper",location); break; case INVENTORY_SPEAR: io_string_write(string,"spear",location); break; case INVENTORY_FISH: io_string_write(string,"fish",location); break; case INVENTORY_BIRD_EGGS: io_string_write(string,"bird eggs",location); break; case INVENTORY_LIZARD_EGGS: io_string_write(string,"lizard eggs",location); break; case INVENTORY_CHILD: case INVENTORY_WOUND: case INVENTORY_GROOMED: default: io_string_write(string,"thing being carried",location); break; } } static void being_social_event_string(n_string string, n_int * location, n_int event_type, n_string name_str) { switch (event_type) { case EVENT_MATE: io_string_write(string,"Mated with ",location); break; case EVENT_SEEK_MATE: io_string_write(string,"Searched for ",location); break; /*case EVENT_GROOM: io_string_write(string,"Groomed ",location); break; */ case EVENT_GROOMED: io_string_write(string,"Groomed by ",location); break; case EVENT_CHAT: io_string_write(string,"Chatted with ",location); break; case EVENT_BIRTH: io_string_write(string,"Gave birth to ",location); break; case EVENT_HURLED: io_string_write(string,"Hurled a rock at ",location); break; case EVENT_HURLED_BY: io_string_write(string,"Hit by a rock hurled by ",location); break; case EVENT_HIT: io_string_write(string,"Hit ",location); break; case EVENT_HIT_BY: io_string_write(string,"Hit by ",location); break; case EVENT_CARRIED: io_string_write(string,"Carried ",location); break; case EVENT_CARRIED_BY: io_string_write(string,"Carried by ",location); break; case EVENT_SUCKLED: io_string_write(string,"Suckled ",location); break; case EVENT_SUCKLED_BY: io_string_write(string,"Suckled by ",location); break; case EVENT_WHACKED: io_string_write(string,"Whacked ",location); break; case EVENT_WHACKED_BY: io_string_write(string,"Whacked by ",location); break; case EVENT_HUGGED: io_string_write(string,"Hugged ",location); break; case EVENT_HUGGED_BY: io_string_write(string,"Hugged by ",location); break; case EVENT_PRODDED: io_string_write(string,"Prodded ",location); break; case EVENT_PRODDED_BY: io_string_write(string,"Prodded by ",location); break; case EVENT_GIVEN: io_string_write(string,"Given ",location); break; case EVENT_GIVEN_BY: io_string_write(string,"Given by ",location); break; case EVENT_POINT: io_string_write(string,"Pointed to ",location); break; case EVENT_POINTED: io_string_write(string,"Pointed to by ",location); break; case EVENT_SMILED: io_string_write(string,"Smiled at ",location); break; case EVENT_SMILED_BY: io_string_write(string,"Smiled at by ",location); break; case EVENT_TICKLED: io_string_write(string,"Tickled ",location); break; case EVENT_TICKLED_BY: io_string_write(string,"Tickled by ",location); break; case EVENT_GLOWERED: io_string_write(string,"Glowered at ",location); break; case EVENT_GLOWERED_BY: io_string_write(string,"Glowered at by ",location); break; case EVENT_PATTED: io_string_write(string,"Patted ",location); break; case EVENT_PATTED_BY: io_string_write(string,"Patted by ",location); break; default: { n_string_block number_str; io_number_to_string(number_str, (n_uint)event_type); io_string_write(string,"Erroneous action (",location); io_string_write(string,number_str,location); io_string_write(string,") with ",location); break; } } io_string_write(string,"*",location); io_string_write(string,name_str,location); io_string_write(string,"*",location); } void being_remains_init(simulated_remains * remains) { remains->count = 0; remains->location = 0; } static void being_remains(simulated_group * group, simulated_being * dead) { simulated_remains * remains = group->remains; n_byte2 location = remains->location; remains->bodies[location].location[0] = dead->delta.location[0]; remains->bodies[location].location[1] = dead->delta.location[1]; remains->location = (remains->location + 1) % NUMBER_OF_BODIES; if (remains->count <= NUMBER_OF_BODIES) { remains->count++; } } n_int episode_description(simulated_being * local_being, n_int index, n_string description) { n_string_block str = {0}; n_int string_index = 0; n_int social = 0; #ifdef EPISODIC_ON n_string_block str2, name_str; simulated_iepisodic * local_episodic; n_uint days_elapsed,time_elapsed; local_episodic = being_episodic(local_being); if(local_episodic == 0L) { return SHOW_ERROR("No episodic description"); } if ((local_episodic[index].event>0) && being_name_comparison(local_being, local_episodic[index].first_name[0], local_episodic[index].family_name[0])) { being_name_byte2(local_episodic[index].first_name[BEING_MET], local_episodic[index].family_name[BEING_MET], name_str); if (local_episodic[index].event & (EVENT_INTENTION)) { io_string_write(str,"Intends ",&string_index); } switch(local_episodic[index].event & (EVENT_INTENTION - 1)) { case EVENT_EAT: { io_string_write(str,"Was eating ",&string_index); switch(local_episodic[index].food) { case FOOD_VEGETABLE: { io_string_write(str,"vegetation",&string_index); break; } case FOOD_FRUIT: { io_string_write(str,"fruit",&string_index); break; } case FOOD_SHELLFISH: { io_string_write(str,"shellfish",&string_index); break; } case FOOD_SEAWEED: { io_string_write(str,"seaweed",&string_index); break; } case FOOD_BIRD_EGGS: { io_string_write(str,"bird eggs",&string_index); break; } case FOOD_LIZARD_EGGS: { io_string_write(str,"lizard eggs",&string_index); break; } } break; } case EVENT_SWIM: { io_string_write(str,"Went swimming",&string_index); break; } case EVENT_GROOM: // this appears to be a duplicate { io_string_write(str,"Groomed *",&string_index); io_string_write(str,name_str,&string_index); io_string_write(str,"*'s ",&string_index); io_string_write(str, being_body_inventory_description(local_episodic[index].arg), &string_index); social = 1; break; } case EVENT_SHOUT: { io_string_write(str,"Shouted ",&string_index); break; } case EVENT_FISH: { io_string_write(str,"Caught a fish ",&string_index); break; } case EVENT_CHEW: { io_string_write(str,"Chewing ",&string_index); if (local_episodic[index].arg & INVENTORY_GRASS) { io_string_write(str,"grass ",&string_index); } else { if (local_episodic[index].arg & INVENTORY_TWIG) { io_string_write(str,"twig ",&string_index); } else { if (local_episodic[index].arg & INVENTORY_FISH) { io_string_write(str,"fish ",&string_index); } else { if (local_episodic[index].arg & INVENTORY_NUT_CRACKED) { io_string_write(str,"a cracked nut ",&string_index); } else { { if (local_episodic[index].arg & INVENTORY_BIRD_EGGS) { io_string_write(str,"birds eggs ",&string_index); } else { if (local_episodic[index].arg & INVENTORY_LIZARD_EGGS) { io_string_write(str,"lizard eggs ",&string_index); } } } } } } } if (local_episodic[index].arg & 1) { io_string_write(str,"held in right hand ",&string_index); } else { io_string_write(str,"held in left hand ",&string_index); } break; } case EVENT_DRAG: io_string_write(str,"Dragged a ",&string_index); being_inventory_string(str, &string_index, local_episodic[index].arg); break; case EVENT_BRANDISH: io_string_write(str,"Waved a ",&string_index); being_inventory_string(str, &string_index, local_episodic[index].arg); break; case EVENT_DROP: io_string_write(str,"Dropped a ",&string_index); being_inventory_string(str, &string_index, local_episodic[index].arg); break; case EVENT_PICKUP: io_string_write(str,"Picked up a ",&string_index); being_inventory_string(str, &string_index, local_episodic[index].arg); break; default: being_social_event_string(str, &string_index, local_episodic[index].event & (EVENT_INTENTION - 1), name_str); social = 1; break; } if (string_index == 0) { return SHOW_ERROR("No string in episodic description"); } days_elapsed = land_date() - local_episodic[index].space_time.date; if (days_elapsed == 0) { time_elapsed = land_time() - local_episodic[index].space_time.time; if (time_elapsed < 60) { if (time_elapsed == 0) { io_string_write(str," now",&string_index); } else if (time_elapsed == 1) { io_string_write(str," a minute ago",&string_index); } else if (time_elapsed<5) { io_string_write(str," a few minutes ago",&string_index); } else { n_string_block time_elapsed_string; io_number_to_string(time_elapsed_string, time_elapsed); io_three_strings(str2, " ", time_elapsed_string, " minutes ago", 0); io_string_write(str,str2, &string_index); } } else { if (time_elapsed<120) { io_string_write(str," an hour ago",&string_index); } else { n_string_block time_elapsed_string; io_number_to_string(time_elapsed_string, time_elapsed/60); io_three_strings(str2, " ", time_elapsed_string, " hours ago", 0); io_string_write(str,str2, &string_index); } } } else { if (days_elapsed == 1) { io_string_write(str, " yesterday",&string_index); } else { n_string_block days_elapsed_string; io_number_to_string(days_elapsed_string, days_elapsed); io_three_strings(str2, " ", days_elapsed_string, " days ago", 0); io_string_write(str,str2, &string_index); } } } #endif str[string_index] = 0; string_index = 0; io_string_write(description, str, &string_index); return social; } /** This checks to see if the Simulated Ape is awake @param local The simulation pointer @return 2 is fully awake, 1 is slightly awake to eat, 0 is asleep */ n_byte being_awake(simulated_being * local) { if (being_energy_less_than(local, BEING_DEAD + 1)) { return FULLY_ASLEEP; } /** if it is not night, the being is fully awake */ if (IS_NIGHT(land_time()) == 0) { return FULLY_AWAKE; } /** if it night the being is... */ /** ... fully awake to swim */ { n_vect2 location; being_space(local, &location); land_convert_to_map(&location); if(WATER_TEST(land_location_vect(&location),land_tide_level())) { return FULLY_AWAKE; } } /** ... slightly awake to eat */ if (being_energy_less_than(local, BEING_HUNGRY + 1)) { #ifdef DEBUG_LACK_OF_MOVEMENT being_register_movement(local, "set slightly awake due to energy"); #endif return SLIGHTLY_AWAKE; } /** ... slightly awake to slow down */ if(being_speed(local) > 0) { #ifdef DEBUG_LACK_OF_MOVEMENT being_register_movement(local, "set slightly awake due to speed"); #endif return SLIGHTLY_AWAKE; } /** ... asleep */ return FULLY_ASLEEP; } /* Rough sketch on brain compression method Hypthesis: From a zeroed brain, After n OUTPUT_ACTUATOR firings into the brain, and, After m brain_cycle occurrences with the states recorded, There should be a near identical brain to a standard run brain. n and m are independent but an acceptable level needs to be recorded. Data set: Type (either output actuator or brain cycle) For output actuator, record position in brain (n_byte2) and set value (n_byte) For brain cycle, record awake or asleep. Position in brain is on the 32k boundry, the delimiting could be: Position in brain - if 32k-1 then actuator set. If 64k-1, then brain cycle Set value is set value if actuator set, 0 is asleep, 1 is awake if brain cycle */ #ifdef BRAINCODE_ON #ifdef BRAIN_ON static void being_brain_probe(simulated_being * local) { n_byte * local_brain = being_brain(local); n_int i = 0; n_int count[NUMBER_BRAINPROBE_TYPES] = {0}; if (local_brain == 0L) return; while (i < BRAINCODE_PROBES) { count[local->braindata.brainprobe[i++].type]++; } /** check to ensure that there are a minimum number of sensors and actuators */ if (count[INPUT_SENSOR] < (BRAINCODE_PROBES>>2)) { local->braindata.brainprobe[0].type = INPUT_SENSOR; } else if (count[OUTPUT_ACTUATOR] < (BRAINCODE_PROBES>>2)) { local->braindata.brainprobe[0].type = OUTPUT_ACTUATOR; } /** update each probe */ i = 0; while (i < BRAINCODE_PROBES) { local->braindata.brainprobe[i].state++; if (local->braindata.brainprobe[i].state >= local->braindata.brainprobe[i].frequency) { n_byte * local_braincode = being_braincode_internal(local); /** position within the brain */ n_int position_in_brain = ((local->braindata.brainprobe[i].position * (SINGLE_BRAIN>>8))) & (SINGLE_BRAIN-1); n_int position_in_braincode = local->braindata.brainprobe[i].address % BRAINCODE_SIZE; local->braindata.brainprobe[i].state = 0; if (local->braindata.brainprobe[i].type == INPUT_SENSOR) { /** address within braincode */ n_int set_value = (local_brain[position_in_brain] + local->braindata.brainprobe[i].offset)&255; /** read from brain */ local_braincode[position_in_braincode] = (n_byte)set_value; } else { /** address within braincode */ n_int set_value = (local_braincode[position_in_braincode] + local->braindata.brainprobe[i].offset)&255; /** write to brain */ local_brain[position_in_brain] = (n_byte)set_value; } } i++; } } #endif #endif /** stuff still goes on during sleep */ void being_cycle_universal(simulated_being * local) { being_immune_response(local); #ifdef BRAINCODE_ON #ifdef BRAIN_ON /** may need to add external probe linking too */ being_brain_probe(local); #endif #endif if ((local->delta.awake == 0) && local) { being_set_state(local, BEING_STATE_ASLEEP); being_reset_drive(local, DRIVE_FATIGUE); } } /* For a new child this populates the social graph with family relationships */ static void being_create_family_links(simulated_being * mother, simulated_being * child, simulated_group * group) { n_int i,j,index; simulated_being * parent[6]= {0L}; simulated_being * sibling; n_byte parent_relation[6]; n_byte child_relation[6]; n_byte sibling_relation; simulated_isocial * parent_social_graph; if (mother==0L) return; /** First tow entries in the array are parents. Subsequent entries are grandparents */ parent[0] = mother; parent[1] = being_find_name(group, mother->changes.father_name[0], mother->changes.father_name[1]); parent_relation[0] = RELATIONSHIP_DAUGHTER; parent_relation[1] = RELATIONSHIP_DAUGHTER; parent_relation[2] = RELATIONSHIP_GRANDDAUGHTER; parent_relation[3] = RELATIONSHIP_GRANDDAUGHTER; parent_relation[4] = RELATIONSHIP_GRANDDAUGHTER; parent_relation[5] = RELATIONSHIP_GRANDDAUGHTER; child_relation[0] = RELATIONSHIP_MOTHER; child_relation[1] = RELATIONSHIP_MOTHER; child_relation[2] = RELATIONSHIP_MATERNAL_GRANDMOTHER; child_relation[3] = RELATIONSHIP_MATERNAL_GRANDMOTHER; child_relation[4] = RELATIONSHIP_PATERNAL_GRANDMOTHER; child_relation[5] = RELATIONSHIP_PATERNAL_GRANDMOTHER; /** grandparents */ for (j = 0; j < 2; j++) /** maternal or paternal */ { if (parent[j]) { /** social graph for mother or father */ parent_social_graph = being_social(parent[j]); if (parent_social_graph) { for (i = 0; i < 2; i++) /** grandmother or grandfather */ { parent[2+(j*2)+i] = 0L; /** graph index for parent's mother or father */ index = social_get_relationship(parent[j], (n_byte)(RELATIONSHIP_MOTHER+i)); if ((index > -1) && (parent_social_graph != 0L)) { /** store the grandparent reference if still living */ parent[2+(j*2)+i] = being_find_name(group, parent_social_graph[index].first_name[BEING_MET], parent_social_graph[index].family_name[BEING_MET]); } } } } } /** brothers and sisters */ sibling_relation = RELATIONSHIP_BROTHER; if (FIND_SEX(GET_I(child)) == SEX_FEMALE) { sibling_relation = RELATIONSHIP_SISTER; } for (j = 0; j < 2; j++) { /** social graph for mother or father */ if (parent[j]) { parent_social_graph = being_social(parent[j]); if (parent_social_graph) { for (i=1; i<SOCIAL_SIZE_BEINGS; i++) { if ((parent_social_graph[i].relationship==RELATIONSHIP_SON) || (parent_social_graph[i].relationship==RELATIONSHIP_DAUGHTER)) { sibling = being_find_name(group, parent_social_graph[i].first_name[BEING_MET], parent_social_graph[i].family_name[BEING_MET]); if (sibling!=0L) { if (parent_social_graph[i].relationship==RELATIONSHIP_SON) { social_set_relationship(group, child, RELATIONSHIP_BROTHER, sibling); } else { social_set_relationship(group, child, RELATIONSHIP_SISTER, sibling); } social_set_relationship(group, sibling, sibling_relation, child); } } } } } } /** set relationships */ for (i = 0; i < 6; i++) { if (parent[i]==0L) continue; /** create the parent/child social graph relation */ if (FIND_SEX(GET_I(child)) == SEX_FEMALE) { social_set_relationship(group, parent[i], parent_relation[i], child); } else { social_set_relationship(group, parent[i], parent_relation[i]+1, child); } if (i%2==0) { social_set_relationship(group, child, child_relation[i], parent[i]); } else { social_set_relationship(group, child, child_relation[i]+1, parent[i]); } } } void being_set_goal_mate(simulated_being * local, n_byte2 first_name, n_byte2 family_name) { local->delta.goal[0] = GOAL_MATE; local->delta.goal[1] = first_name; local->delta.goal[2] = family_name; local->delta.goal[3] = GOAL_TIMEOUT; } void being_set_goal_none(simulated_being * local) { local->delta.goal[0] = GOAL_NONE; } void being_set_goal_location(simulated_being * local, n_byte2 lx, n_byte2 ly) { local->delta.goal[0] = GOAL_LOCATION; local->delta.goal[1] = lx; local->delta.goal[2] = ly; local->delta.goal[3] = GOAL_TIMEOUT; } n_int being_check_goal(simulated_being * local, goal_types goal) { return (local->delta.goal[0] == goal); } void being_goal_cycle(simulated_being * local) { /** decrement the goal counter */ if (local->delta.goal[3] > 0) { local->delta.goal[3]--; } else { /** timed out */ being_set_goal_none(local); } } static void being_follow_loop1(simulated_group * group, simulated_being * other, void * data) { being_nearest * nearest = (being_nearest *)data; n_vect2 difference_vector; /** is this the same as the name of the being to which we are paying attention? */ if ((FIND_SEX(GET_I(other))!=FIND_SEX(GET_I(nearest->local))) && being_name_comparison(other, nearest->local->delta.goal[1], nearest->local->delta.goal[2])) { n_vect2 other_location; being_delta(nearest->local, other, &difference_vector); being_space(other, &other_location); if (being_line_of_sight(nearest->local, &other_location)) /* incorrect use of los */ { n_uint compare_distance = (n_uint)vect2_dot(&difference_vector, &difference_vector, 1, 1); if (compare_distance < nearest->opposite_sex_distance) { nearest->opposite_sex = other; nearest->opposite_sex_distance = compare_distance; } } } } static void being_follow_loop2(simulated_group * group, simulated_being * other, void * data) { being_nearest * nearest = (being_nearest *)data; n_vect2 difference_vector; /** is this the same as the name of the being to which we are paying attention? */ if (being_name_comparison(other, nearest->local_social->first_name[BEING_MET], nearest->local_social->family_name[BEING_MET])) { /** Is this being within sight? */ n_vect2 other_location; being_delta(nearest->local, other, &difference_vector); being_space(other, &other_location); if (being_line_of_sight(nearest->local, &other_location)) { n_uint compare_distance = (n_uint)vect2_dot(&difference_vector, &difference_vector, 1, 1); if (FIND_SEX(GET_I(other))!=FIND_SEX(GET_I(nearest->local))) { if (compare_distance < nearest->opposite_sex_distance) { nearest->opposite_sex = other; nearest->opposite_sex_distance = compare_distance; } } else { if (compare_distance < nearest->same_sex_distance) { nearest->same_sex = other; nearest->same_sex_distance = compare_distance; } } } } } /** * Follow a being to which we are paying attention * @param group Pointer to the simulated_group * @param local The current being * @param nearest The nearest being structure */ static void being_follow(simulated_group * group, simulated_being * local, being_nearest * nearest) { /* There is a bug here where same_sex and opposite_sex appears to never be set */ simulated_isocial * local_social_graph; n_int social_graph_index; nearest->local = local; nearest->opposite_sex_distance = 0xffffffff; nearest->same_sex_distance = 0xffffffff; nearest->opposite_sex = 0L; nearest->same_sex = 0L; /** is a mate in view? */ if (being_check_goal(local, GOAL_MATE)) { loop_no_thread(group, local, being_follow_loop1, nearest); if (nearest->opposite_sex != 0L) { return; } } local_social_graph = being_social(local); if (local_social_graph == 0L) return; /** which entry in the social graph are we paying attention to? */ social_graph_index = being_attention(local, ATTENTION_ACTOR); nearest->local_social = &local_social_graph[social_graph_index]; /** Does this entry correspond to another being? */ if ((social_graph_index>0) && (local_social_graph[social_graph_index].entity_type == ENTITY_BEING) && (!SOCIAL_GRAPH_ENTRY_EMPTY(local_social_graph, social_graph_index))) { loop_no_thread(group, local, being_follow_loop2, nearest); } } void being_listen_loop_no_sim(simulated_being * other, void * data) { being_listen_struct * bls = (being_listen_struct *)data; n_vect2 difference_vector; n_uint compare_distance; being_delta(bls->local, other, &difference_vector); compare_distance = (n_uint)vect2_dot(&difference_vector, &difference_vector, 1, 1); /** listen for the nearest shout out */ if ((being_state(other)&BEING_STATE_SHOUTING) && (compare_distance < SHOUT_RANGE) && (other->changes.shout[SHOUT_VOLUME] > bls->max_shout_volume)) { bls->max_shout_volume = other->changes.shout[SHOUT_VOLUME]; bls->local->changes.shout[SHOUT_HEARD] = other->changes.shout[SHOUT_CONTENT]; bls->local->changes.shout[SHOUT_FAMILY0] = being_family_first_name(other); bls->local->changes.shout[SHOUT_FAMILY1] = being_family_second_name(other); } } /** * Listen for shouts * @param group Pointer to the simulated_group * @param local_being Array index of the current being * @param data Unused here */ void being_listen(simulated_group * group, simulated_being * local_being, void * data) { being_listen_struct bls; if (local_being->delta.awake == 0) return; bls.max_shout_volume = 127; bls.local = local_being; /** clear shout values */ if (local_being->changes.shout[SHOUT_CTR] > 0) { local_being->changes.shout[SHOUT_CTR]--; } loop_being_no_sim(group->beings, group->num, being_listen_loop_no_sim, &bls); } static void being_closest_loop(simulated_group * group, simulated_being * test_being, void * data) { being_nearest * nearest = (being_nearest *)data; n_vect2 difference_vector; n_uint compare_distance; n_vect2 location_test; being_delta(nearest->local, test_being, &difference_vector); compare_distance = (n_uint)vect2_dot(&difference_vector, &difference_vector, 1, 1); if (FIND_SEX(GET_I(test_being)) != FIND_SEX(GET_I(nearest->local))) { if (compare_distance < nearest->opposite_sex_distance) { being_space(test_being, &location_test); /* 'function' : conversion from 'n_int' to 'n_byte2', possible loss of data x 2 */ if (being_line_of_sight(nearest->local, &location_test)) { nearest->opposite_sex_distance = compare_distance; nearest->opposite_sex = test_being; } } } else { if ( compare_distance < nearest->same_sex_distance ) { being_space(test_being, &location_test); if (being_line_of_sight(nearest->local, &location_test)) { nearest->same_sex_distance = compare_distance; nearest->same_sex = test_being; } } } } /** * Returns the closest beings * @param group Pointer to the simulated_group * @param local Array index of the current being */ static void being_closest(simulated_group * group, simulated_being * local, being_nearest * nearest) { nearest->local = local; nearest->opposite_sex_distance = 0xffffffff; nearest->same_sex_distance = 0xffffffff; nearest->opposite_sex = 0L; nearest->same_sex = 0L; loop_no_thread(group, local, being_closest_loop, nearest); } /** * One being interacts with another * @param group Pointer to the simulated_group * @param local Array index of the being * @param other_being Array index of the other being * @param other_being_distance Distance to the other being * @param awake Whether the being is awake * @param state The state of the being * @param speed The speed of the being * @param opposite_sex Non zero if the other being is the opposite sex */ static void being_interact(simulated_group * group, simulated_being * local, simulated_being * other_being, n_uint other_being_distance, n_int * awake, n_byte2 * state, n_int * speed, n_byte opposite_sex) { if (other_being != 0L) { n_int today_days = land_date(); n_int birth_days = being_dob(local); n_int local_is_female = FIND_SEX(GET_I(local)); n_vect2 delta_vector; /** social networking */ n_byte2 familiarity = 0; n_int being_index = social_network(group, local, other_being, other_being_distance); being_delta(local, other_being, &delta_vector); if (being_index > -1) { simulated_isocial * local_social_graph = being_social(local); if (local_social_graph) { familiarity = local_social_graph[being_index].familiarity; } } being_facing_towards(local, &delta_vector); if ((birth_days+AGE_OF_MATURITY) < today_days) { if (social_groom(group, local, other_being, other_being_distance, *awake, familiarity)) { *state |= BEING_STATE_GROOMING; /* both beings stop */ *speed = 0; being_set_speed(other_being, 0); } else { /* squabbling between adults */ if ((other_being_distance < SQUABBLE_RANGE) && ((being_dob(other_being)+AGE_OF_MATURITY) < today_days)) { n_byte2 squabble_val; being_set_speed(local, (n_byte)*speed); #ifdef DEBUG_LACK_OF_MOVEMENT if (*speed == 0) { being_register_movement(local, "speed is zero"); } #endif squabble_val = social_squabble(local, other_being, other_being_distance, local_is_female, group); if (squabble_val != 0) { *state |= squabble_val; *speed = being_speed(local); } } } } if ((other_being_distance < SOCIAL_RANGE) && (being_index>-1)) { /* attraction and mating */ if (opposite_sex != 0) { *state |= social_mate(local, other_being, being_index, other_being_distance, group); } /* chat */ *state |= social_chat(local, other_being, being_index, group); } } } typedef struct { n_int counter; n_int return_value; simulated_being * being; } being_index_loop_struct; static void being_index_loop(simulated_group * group, simulated_being * local_being, void * data) { being_index_loop_struct * bils = (being_index_loop_struct *) data; if (bils->return_value != -1) { return; } if (local_being == bils->being) { bils->return_value = bils->counter; } else { bils->counter++; } } n_int being_index(simulated_group * group, simulated_being * local) { being_index_loop_struct value; value.return_value = -1; value.being = local; value.counter = 0; loop_no_thread(group, 0L, being_index_loop, &value); return value.return_value; } void being_territory_index(simulated_being * local) { n_uint territory_index = APESPACE_TO_TERRITORY(being_location_y(local))*TERRITORY_DIMENSION + APESPACE_TO_TERRITORY(being_location_x(local)); if (local->events.territory[territory_index].familiarity<65534) { local->events.territory[territory_index].familiarity++; } else { /** rescale familiarity values */ for (territory_index=0; territory_index<TERRITORY_AREA; territory_index++) { local->events.territory[territory_index].familiarity>>=2; } } } static n_int being_temporary_speed(simulated_being* local, n_int * test_land, n_int *az) { n_vect2 location_vector; n_vect2 facing_vector; n_vect2 slope_vector; n_vect2 looking_vector; being_space(local, &location_vector); being_facing_vector(local, &facing_vector, 4); land_vect2(&slope_vector, az, &location_vector); vect2_add(&looking_vector, &location_vector, &facing_vector); land_convert_to_map(&looking_vector); *test_land = (WATER_TEST(land_location_vect(&looking_vector),land_tide_level())!= 0); { n_int delta_z = vect2_dot(&slope_vector,&facing_vector,1,24); n_int tmp_speed = ((delta_z + 280) >> 4); #ifdef DEBUG_LACK_OF_MOVEMENT if (tmp_speed == 0) { being_register_movement(local, "temp speed zero in setting temp speed"); } #endif return tmp_speed; } } static n_int being_conception_child_mass(simulated_group * group, simulated_being * local, n_byte2 loc_state) { n_int birth_days = being_dob(local); n_int today_days = land_date(); n_int child_mass = 0; n_int carrying_child = 0; n_genetics * genetics = being_genetics(local); /** a certain time after giving birth females become receptive again */ if ((being_pregnant(local) != 0) && ((being_pregnant(local) + GESTATION_DAYS + CONCEPTION_INHIBITION_DAYS) < today_days)) { /** zero value indicates ready to conceive */ local->changes.date_of_conception = 0; } if ((loc_state & (BEING_STATE_AWAKE | BEING_STATE_SWIMMING)) == BEING_STATE_AWAKE) { n_int conception_days = being_pregnant(local) ; if (conception_days > 0) { n_int gestation_days = conception_days + GESTATION_DAYS; if (today_days > gestation_days) { /** A mother could have multiple children, so only find the youngest */ simulated_being * being_child = being_find_child(group, genetics, CARRYING_DAYS); /** Birth */ if (being_child == 0L) { if((group->num + 1) < group->max) { being_child = &(group->beings[group->num]); if (being_init(group->beings, (n_int)group->num, being_child, local, 0L) == 0) { #ifdef EPISODIC_ON episodic_close(local, being_child, EVENT_BIRTH, AFFECT_BIRTH, 0); #endif being_create_family_links(local, being_child, group); if (group->ext_birth != 0) { group->ext_birth(being_child, local, group); } group->num++; } } } else { /** mother carries the child */ n_int carrying_days = conception_days + GESTATION_DAYS + CARRYING_DAYS; if (today_days < carrying_days) { if (!((local->changes.inventory[BODY_FRONT] & INVENTORY_CHILD) || (local->changes.inventory[BODY_BACK] & INVENTORY_CHILD))) { local->changes.inventory[BODY_BACK] |= INVENTORY_CHILD; being_set_attention(local,ATTENTION_BODY, BODY_BACK); } carrying_child = 1; being_set_location(being_child, being_location(local)); child_mass = GET_M(being_child); #ifdef EPISODIC_ON episodic_close(local, being_child, EVENT_CARRIED, AFFECT_CARRYING, 0); episodic_close(being_child, local, EVENT_CARRIED_BY, AFFECT_CARRIED, 0); #endif } } } else { /** Compute the mass of the unborn child. This will be added to the mass of the mother */ child_mass = (today_days - conception_days) * BIRTH_MASS / GESTATION_DAYS; } } /** child follows the mother */ if ((birth_days + WEANING_DAYS) > today_days) { simulated_being * mother = being_find_closest(group, local, 1, 1); if (mother != 0L) { /** orient towards the mother */ n_vect2 mother_vector; being_delta(mother, local, &mother_vector); being_facing_towards(local, &mother_vector); /** suckling */ if ((loc_state & BEING_STATE_HUNGRY) != 0) { n_int distance = vect2_dot(&mother_vector, &mother_vector, 1, 1); if (distance < SUCKLING_MAX_SEPARATION) { /** child moves from back to front */ if (mother->changes.inventory[BODY_BACK] & INVENTORY_CHILD) { mother->changes.inventory[BODY_BACK] -= INVENTORY_CHILD; } mother->changes.inventory[BODY_FRONT] |= INVENTORY_CHILD; being_set_attention(mother,ATTENTION_BODY, BODY_FRONT); /** sucking causes loss of grooming */ if (mother->changes.inventory[BODY_FRONT] & INVENTORY_GROOMED) { mother->changes.inventory[BODY_FRONT] -= INVENTORY_GROOMED; } /** hungry mothers stop producing milk */ if (being_energy_less_than(mother, BEING_HUNGRY) == 0) { /** mother loses energy */ being_energy_delta(mother, 0 - SUCKLING_ENERGY); /** child gains energy */ being_energy_delta(local, SUCKLING_ENERGY); /** set child state to suckling */ loc_state |= BEING_STATE_SUCKLING; /** child acquires immunity from mother */ being_immune_seed(mother, local); #ifdef EPISODIC_ON episodic_close(mother, local, EVENT_SUCKLED, AFFECT_SUCKLING, 0); episodic_close(local, mother, EVENT_SUCKLED_BY, AFFECT_SUCKLING, 0); #endif } } } } } } /** no longer carrying the child */ if ((carrying_child==0) && (FIND_SEX(GET_I(local)) == SEX_FEMALE)) { if (local->changes.inventory[BODY_FRONT] & INVENTORY_CHILD) { local->changes.inventory[BODY_FRONT] -= INVENTORY_CHILD; } if (local->changes.inventory[BODY_BACK] & INVENTORY_CHILD) { local->changes.inventory[BODY_BACK] -= INVENTORY_CHILD; } } return child_mass; } static n_byte2 being_state_find(simulated_being * local, n_int az, n_int loc_s) { n_byte2 loc_state = BEING_STATE_ASLEEP; n_int awake = local->delta.awake; #ifdef LAND_ON /* TODO why not test_land here? */ if (WATER_TEST(az,land_tide_level()) != 0) { loc_state |= BEING_STATE_SWIMMING; } #endif if (awake != FULLY_ASLEEP) { loc_state |= BEING_STATE_AWAKE; } if (loc_s != 0) { loc_state |= BEING_STATE_MOVING; } { n_int hungry = being_energy_less_than(local, BEING_HUNGRY); if ((loc_state & (BEING_STATE_AWAKE | BEING_STATE_SWIMMING | BEING_STATE_MOVING)) == BEING_STATE_AWAKE) { hungry = being_energy_less_than(local, BEING_FULL); #ifdef DEBUG_LACK_OF_MOVEMENT being_register_movement(local, "is eating path"); #endif } if (hungry != 0) { #ifdef DEBUG_LACK_OF_MOVEMENT being_register_movement(local, "is hungry"); #endif loc_state |= BEING_STATE_HUNGRY; } } return loc_state; } static void being_not_swimming(simulated_group * group, simulated_being * local, n_int * tmp_speed, being_nearest * nearest, n_int * loc_s, n_byte2 * loc_state) { n_genetics * genetics = being_genetics(local); /** adjust speed using genetics */ *tmp_speed = (*tmp_speed * (GENE_SPEED(genetics)+8)) >> 3; /** is the being to which we are paying attention within view? */ being_follow(group, local, nearest); if (nearest->opposite_sex == 0L) { /** Find the closest beings */ being_closest(group, local, nearest); } /* TODO: SOCIAL_THRESHOLD should not be a macro, it should be a function returning n_int */ if (being_drive(local, DRIVE_SOCIAL) > SOCIAL_THRESHOLD(local)) { n_int awake = local->delta.awake; being_interact(group, local, nearest->same_sex, nearest->same_sex_distance, &awake, loc_state, loc_s, 0); being_interact(group, local, nearest->opposite_sex, nearest->opposite_sex_distance, &awake, loc_state, loc_s, 1); } } static void being_swimming(simulated_group * group, simulated_being * local, n_int * tmp_speed) { n_uint loop; n_genetics * genetics = being_genetics(local); being_turn_away_from_water(local); /** horizontally oriented posture */ being_set_posture(local, 0); /** When swimming drop everything except what's on your head or back. Note that the groomed flag is also cleared */ for (loop=0; loop<INVENTORY_SIZE; loop++) { if (!((loop==BODY_HEAD) || (loop==BODY_BACK))) { local->changes.inventory[loop] = 0; } } /** swimming proficiency */ *tmp_speed = (*tmp_speed * (GENE_SWIM(genetics)+8)) >> 4; /* TODO: affect_type should probably be used rather than energy? */ #ifdef EPISODIC_ON episodic_self(local, EVENT_SWIM, AFFECT_GROOM, (n_byte2)being_energy(local)); #endif /** bathing removes parasites */ being_remove_parasites(local, 1); } static void being_mass_calculation(simulated_group * group, simulated_being * local, n_byte2 loc_state) { n_int loc_h = being_height(local); n_int child_mass = being_conception_child_mass(group, local, loc_state); /** amount of body fat in kg */ n_int fat_mass = GET_BODY_FAT(local); if (fat_mass > BEING_MAX_MASS_FAT_G) { fat_mass = BEING_MAX_MASS_FAT_G; } GET_M(local) = (n_byte2)((BEING_MAX_MASS_G * loc_h / BEING_MAX_HEIGHT) + fat_mass + child_mass); } void being_genetic_wandering(simulated_being * local, being_nearest * nearest) { n_genetics * genetics = being_genetics(local); if (being_check_goal(local, GOAL_NONE) && (nearest->opposite_sex == 0L) && (nearest->same_sex == 0L) && (being_random(local) < 1000 + 3600*GENE_STAGGER(genetics))) { n_int wander = math_spread_byte(being_random(local) & 7); being_wander(local, wander); } } void being_calculate_speed(simulated_being * local, n_int tmp_speed, n_byte2 loc_state) { n_int loc_s = being_speed(local); if (tmp_speed > 39) tmp_speed = 39; if (tmp_speed < 0) tmp_speed = 0; if ((local->delta.awake != FULLY_AWAKE) || ((loc_state & (BEING_STATE_HUNGRY | BEING_STATE_NO_FOOD)) == BEING_STATE_HUNGRY)) { if ((loc_state & BEING_STATE_SWIMMING) != 0) { tmp_speed = (being_energy(local) >> 7); } else { if ((loc_state & BEING_STATE_NO_FOOD) != BEING_STATE_NO_FOOD) { tmp_speed = 0; #ifdef DEBUG_LACK_OF_MOVEMENT being_register_movement(local, "not fully awake and hungry not swimming"); #endif } } } if (tmp_speed > loc_s) loc_s++; if (tmp_speed < loc_s) loc_s--; if (tmp_speed < loc_s) loc_s--; if (tmp_speed < loc_s) loc_s--; being_set_speed(local, (n_byte)loc_s); } void being_cycle_awake(simulated_group * group, simulated_being * local) { n_int loc_s = being_speed(local); n_int loc_h = being_height(local); n_int birth_days = being_dob(local); n_int today_days = land_date(); /** tmp_speed is the optimum speed based on the gradient */ /** delta_energy is the energy required for movement */ n_int az; being_nearest nearest; n_int test_land = 1; n_int tmp_speed = being_temporary_speed(local, &test_land, &az); n_byte2 loc_state = being_state_find(local, az, loc_s); nearest.opposite_sex = 0L; nearest.same_sex = 0L; /** If it sees water in the distance then turn */ if (((loc_state & BEING_STATE_SWIMMING) != 0) || test_land) { being_swimming(group, local, &tmp_speed); } else { being_not_swimming(group, local, &tmp_speed, &nearest, &loc_s, &loc_state); } #ifdef DEBUG_LACK_OF_MOVEMENT if (tmp_speed == 0) { being_register_movement(local, "temp speed zero"); } #endif if ((loc_state & (BEING_STATE_SWIMMING | BEING_STATE_GROOMING | BEING_STATE_ATTACK | BEING_STATE_SHOWFORCE)) == 0) { if ((loc_state & BEING_STATE_HUNGRY) == BEING_STATE_HUNGRY) { if (loc_s == 0) { /** eating when stopped */ n_byte food_type; n_int energy = food_eat(being_location_x(local), being_location_y(local), az, &food_type, local); #ifdef DEBUG_LACK_OF_MOVEMENT { n_string_block energy_string; sprintf(energy_string, "energy delta is %ld tmp_speed is %ld", energy, tmp_speed); being_register_movement(local, energy_string); } #endif if (energy != 0) { #ifdef EPISODIC_ON /** remember eating */ episodic_food(local, energy, food_type); #endif being_energy_delta(local, energy); being_reset_drive(local, DRIVE_HUNGER); loc_state |= BEING_STATE_EATING; /** grow */ if (loc_h < BEING_MAX_HEIGHT) { if ((birth_days+AGE_OF_MATURITY) > today_days) { loc_h += ENERGY_TO_GROWTH(local,energy); } } } else { loc_state |= BEING_STATE_NO_FOOD; #ifdef DEBUG_LACK_OF_MOVEMENT { being_register_movement(local, "no food state set"); } #endif } } } else { /** orient towards a goal */ social_goals(local); if (loc_s == 0) { loc_s = 10; } } } being_set_height(local, loc_h); being_set_state(local, loc_state); being_calculate_speed(local, tmp_speed, loc_state); being_genetic_wandering(local, &nearest); #ifdef TERRITORY_ON being_territory_index(local); #endif being_mass_calculation(group, local, loc_state); } void being_tidy_loop_no_sim(simulated_being * local_being, void * data) { n_genetics *genetics = being_genetics(local_being); n_int local_honor = being_honor(local_being); n_int delta_e = 0; n_int conductance = 5; n_int *max_honor = data; if (local_honor >= 254) { max_honor[0] = 1; } if (local_being->delta.awake != FULLY_ASLEEP) { delta_e = being_move_energy(local_being, &conductance); } else { being_set_speed(local_being, 0); #ifdef DEBUG_LACK_OF_MOVEMENT being_register_movement(local_being, "not fully awake"); #endif delta_e += (7) >> 2; } if (delta_e > 0) { /** hairy creatures are better insulated */ delta_e -= ((GENE_HAIR(genetics)*delta_e)>>conductance); if (delta_e < 1) delta_e = 1; } being_energy_delta(local_being, 0 - delta_e); if (land_time() == 0) { n_int age_in_years = AGE_IN_YEARS(local_being); /** this simulates natural death or at least some trauma the ape may or may not be able to recover from */ if (age_in_years > 29) { if(being_random(local_being) < (age_in_years - 29)) { being_energy_delta(local_being, 0 - BEING_HUNGRY); } } } } void being_recalibrate_honor_loop_no_sim(simulated_being * value, void * data) { value->delta.honor = (n_byte)(((n_int)(value->delta.honor)*220)/255); } static n_int being_remove_internal_value = 0; static n_int being_remove_external_value = 0; n_int being_remove_internal(void) { return being_remove_internal_value; } void being_remove_external_set(n_int value) { being_remove_external_value = value; } void being_remove_loop1(simulated_group * group, simulated_being * local_being, void * data) { if (being_energy_less_than(local_being, BEING_DEAD + 1)) { group->ext_death(local_being, group); } } void being_remove_loop2(simulated_group * group, simulated_being * local, void * data) { being_remove_loop2_struct * brls = (being_remove_loop2_struct *)data; if (being_energy_less_than(local, BEING_DEAD + 1) == 0) { if ( local != brls->being_count ) { memory_copy((n_byte *)local, (n_byte *)brls->being_count, sizeof(simulated_being)); } brls->being_count++; brls->count++; } else { being_remains(group, local); if (local == brls->reference) { brls->selected_died = 1; } } } being_remove_loop2_struct * being_remove_initial(simulated_group * group) { being_remove_loop2_struct * brls = (being_remove_loop2_struct *)memory_new(sizeof(being_remove_loop2_struct)); brls->reference = group->select; brls->being_count = group->beings; brls->selected_died = 0; brls->count = 0; if (being_remove_external_value) { do {} while(being_remove_external_value); } being_remove_internal_value = 1; return brls; } void being_remove_internal_clear(void) { being_remove_internal_value = 0; } <|start_filename|>script/interpret.c<|end_filename|> /**************************************************************** interpret.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /*! \file interpret.c * \brief This handles the interpretation end of ApeScript (i.e. after parsing). Unlike the parsing code that should be run only once in general use, the interpretation code is run multiple times in a simulation cycle. Thus slightly more care must be taken in optimizing the interpret code. */ #include "../toolkit/toolkit.h" #include "script.h" /** * Makes sure all the data associated with the interpreter is freed etc. * @param individual pointer to the interpreter structure that is being executed. * @param eval pointer execution points being executed. * @param location the location in the execution points. * @return minus one on failure, zero on success. */ static n_int interpret_braces(n_individual_interpret * individual, n_byte * eval, n_int location) { n_int local_b_count; NA_ASSERT(individual, "individual NULL"); local_b_count = individual->braces_count; if(location == -1) { if(local_b_count == 0) { return APESCRIPT_ERROR(individual, AE_TOO_MANY_CLOSE_BRACES); } individual->braces_count--; } else { n_uint loop = 0; n_byte *local_evaluate; if(local_b_count == BRACES_MAX) { return APESCRIPT_ERROR(individual, AE_MAXIMUM_BRACES_REACHED); } local_evaluate = individual->braces[ local_b_count ].evaluate; while(loop < SIZE_OF_EVALUATE) { n_byte eval_val = 0; if(eval != 0L) { eval_val = eval[loop]; } local_evaluate[ loop++ ] = eval_val; } individual->braces[ local_b_count ].braces_start = location; individual->braces_count++; } return 0; } /** * Makes sure all the data associated with the interpreter is freed etc. * @param code pointer to the interpreter structure that is being executed. * @param evaluate pointer execution points being executed. * @param number the pointer to the result of the execution block. * @param end_char the end character expected. * @return minus one on failure, otherwise the number of execution points to advance. */ static n_int interpret_apply(n_interpret * code, n_individual_interpret * individual, n_byte * evaluate, n_int * number, n_byte end_char) { n_int val_a, val_b, val_c; NA_ASSERT(code, "code NULL"); NA_ASSERT(evaluate, "evaluate NULL"); NA_ASSERT(number, "number NULL"); if (code == 0L) return SHOW_ERROR("No code provided"); if (evaluate == 0L) return SHOW_ERROR("Nothing to evaluate"); if (number == 0L) return SHOW_ERROR("No numbers provided"); if(code->sc_output(code, individual, evaluate,&val_a) == -1) { return APESCRIPT_ERROR(individual, AE_FIRST_VALUE_FAILED); } if(evaluate[2] == end_char) { *number = val_a; return 3; } if(evaluate[2] != APESCRIPT_OPERATOR) { return APESCRIPT_ERROR(individual, AE_UNKNOWN_SYNTAX_MISSING_EQUALS); } if(code->sc_output(code, individual, &evaluate[4],&val_b) == -1) { return APESCRIPT_ERROR(individual, AE_SECOND_VALUE_FAILED); } val_c = val_a - val_b; switch(evaluate[3]) { case SYNTAX_MINUS: *number = val_c; break; case SYNTAX_ADDITION: *number = (val_a + val_b); break; case SYNTAX_MULTIPLY: *number = (val_a * val_b); break; case SYNTAX_AND: *number = (val_a & val_b); break; case SYNTAX_XOR: *number = (val_a ^ val_b); break; case SYNTAX_OR: *number = (val_a | val_b); break; case SYNTAX_GREATER_THAN: *number = ((0 - val_c)<0); break; case SYNTAX_LESS_THAN: *number = (val_c < 0); break; case SYNTAX_EQUAL_TO: *number = (val_c == 0); break; case SYNTAX_NOT_EQUAL_TO: *number = (val_c != 0); break; case SYNTAX_CONDITIONAL_AND: *number = (val_a && val_b); break; case SYNTAX_CONDITIONAL_OR: *number = (val_a || val_b); break; case SYNTAX_DIVISION: if (val_b == 0) *number = 0; else *number = (val_a / val_b); break; case SYNTAX_MODULUS: if (val_b == 0) *number = 0; else *number = (val_a % val_b); break; case SYNTAX_GREATER_EQUAL: *number = ((0 - val_c) <= 0); break; case SYNTAX_LESS_EQUAL: *number = (val_c <= 0); break; case SYNTAX_BITSHIFT_RIGHT: val_b = 0 - val_b; case SYNTAX_BITSHIFT_LEFT: if (val_b == 0) { *number = val_a; } else { if (val_b < 0) { *number = val_a << val_b; } else { val_b = 0 - val_b; *number = val_a >> val_b; } } break; default: return APESCRIPT_ERROR(individual, AE_UNKNOWN_SYNTAX_NO_COMMAND); break; } if(evaluate[6] == end_char) { return 7; } return APESCRIPT_ERROR(individual, AE_WRONG_END); } /** * Makes sure all the data associated with the interpreter is freed etc. * @param code pointer to the interpreter structure that is being executed. * @param value pointer execution points being executed. * @param location the location in the execution points. * @return minus one on failure, otherwise the number of execution points to advance. */ static n_int interpret_syntax(n_interpret * code, n_individual_interpret * individual, n_byte * value, n_int location) { n_byte first_value; n_byte second_value; n_int output_number = 0; NA_ASSERT(code, "code NULL"); NA_ASSERT(value, "value NULL"); if (code == 0L) return SHOW_ERROR("No code provided"); if (value == 0L) return SHOW_ERROR("No values provided"); first_value = value[0]; second_value = value[1]; if(first_value == APESCRIPT_CLOSE_BRACE) /* what do you do with the tailing brace? */ { n_brace *local_brace; n_int brace_value = (individual->braces_count) - 1; if(brace_value < 0 ) { return APESCRIPT_ERROR(individual, AE_TOO_MANY_CLOSE_BRACES); } local_brace = &(individual->braces[brace_value]); if(local_brace->evaluate[0] == 0) /* exit if */ { if(interpret_braces(individual, 0L, -1) == -1) { return -1; /* Enough error information provided by this point */ } SC_DEBUG_STRING(individual->interpret_data, "}"); SC_DEBUG_DOWN(individual->interpret_data); SC_DEBUG_NEWLINE(individual->interpret_data); return 1; } return 0; /* exit while and run function */ } if(first_value != APESCRIPT_TEXT) { return APESCRIPT_ERROR(individual, AE_LINE_START_INCORRECT); } if((second_value > VARIABLE_IF) && (second_value <= code->input_greater)) { return APESCRIPT_ERROR(individual, AE_OUTPUT_SET_AS_INPUT_VARIABLE); } if(VARIABLE_SPECIAL(second_value,code)) /* if/while/function/run( something ){} */ { n_int return_value; n_int error_value = -1; if(value[2] != APESCRIPT_OPEN_BRACKET) { return APESCRIPT_ERROR(individual, AE_IF_WHILE_NOT_FOLLOWED_BY_BRACKET); } return_value = interpret_apply(code, individual, &value[3], &output_number, APESCRIPT_CLOSE_BRACKET); if(return_value == -1) { return -1; /* Enough information presented by this point */ } if(second_value == VARIABLE_FUNCTION || second_value == VARIABLE_RUN) { if(value[3] != APESCRIPT_TEXT) { return APESCRIPT_ERROR(individual, AE_FUNCTION_ISNT_VARIABLE); } if(return_value != 3) { return APESCRIPT_ERROR(individual, AE_NON_FUNCTION_APPLIED); } } else { SC_DEBUG_STRING(individual->interpret_data, scdebug_variable(second_value)); SC_DEBUG_STRING(individual->interpret_data, " ( ) {"); if(output_number == 0) { SC_DEBUG_STRING(individual->interpret_data, " }"); } else { SC_DEBUG_UP(individual->interpret_data); } SC_DEBUG_NEWLINE(individual->interpret_data); } if(second_value == VARIABLE_FUNCTION) { if(output_number != 0) { return APESCRIPT_ERROR(individual, AE_FUNCTION_DEFINED_PRIOR); } } if(second_value == VARIABLE_RUN) { if((output_number < 1) || (output_number > 0xFFFF)) { return APESCRIPT_ERROR(individual, AE_FUNCTION_OUT_OF_RANGE); } if(value[3 + return_value] != APESCRIPT_SEMICOLON) { return APESCRIPT_ERROR(individual, AE_WITHOUT_SEMICOLON); } { n_byte function_location[SIZE_OF_EVALUATE] = {APESCRIPT_FUNCTION,0}; n_byte *location_write =(n_byte *)&function_location[1]; n_int continuation = return_value + 4 + location; io_int_to_bytes(output_number, location_write); location_write = (n_byte *)&function_location[1 + SIZEOF_NUMBER_WRITE]; io_int_to_bytes(continuation,location_write); NA_ASSERT((n_byte *)function_location, "eval function_location"); if(interpret_braces(individual, (n_byte *)function_location, 0) == -1) { return -1; /* Enough information presented by this point */ } } SC_DEBUG_STRING(individual->interpret_data,"run( "); SC_DEBUG_STRING(individual->interpret_data,scdebug_variable(value[4])); SC_DEBUG_STRING(individual->interpret_data," ){"); SC_DEBUG_UP(individual->interpret_data); SC_DEBUG_NEWLINE(individual->interpret_data); return 0; /* want to trigger while check */ } /* if the future code will contain if()run(); then the if should be checked here */ if(value[3 + return_value] != APESCRIPT_OPEN_BRACE) { return APESCRIPT_ERROR(individual, AE_WITHOUT_OPEN_BRACE); } if(second_value == VARIABLE_FUNCTION) { if(code->sc_input(individual, value[4], (4 + return_value + location) ) == -1) { return APESCRIPT_ERROR(individual, AE_FUNCTION_SETTING_FAILED); } if(value[4] == code->main_entry) { if(interpret_braces(individual, 0L, 0) == -1) { return APESCRIPT_ERROR(individual, AE_ERROR_STARTING_MAIN); } individual->main_status = MAIN_RUN; SC_DEBUG_STRING(individual->interpret_data, "function( "); SC_DEBUG_STRING(individual->interpret_data, scdebug_variable(value[4])); SC_DEBUG_STRING(individual->interpret_data, " ){"); SC_DEBUG_UP(individual->interpret_data); SC_DEBUG_NEWLINE(individual->interpret_data); return 3 + 4; /* tF(tf){*/ } if(individual->main_status != MAIN_NOT_RUN) { return APESCRIPT_ERROR(individual, AE_CODE_AFTER_MAIN); } } /* if the result is zero find the end of the correctly nested } */ if(output_number == 0) { n_int loop = return_value + 4; n_int braces_open = 1; n_int remaining_bytes = (n_int)code->binary_code->location; do { n_byte actual_value = value[loop++]; /* get actual point, avoid text variable numerical reference to { } */ if(CODE_VALUE_REQUIRED(actual_value)) loop++; if(actual_value == APESCRIPT_OPEN_BRACE) { braces_open ++; } if(actual_value == APESCRIPT_CLOSE_BRACE) { braces_open --; } if((loop + location) > remaining_bytes) { return APESCRIPT_ERROR(individual, AE_NO_CLOSE_BRACE_TO_END_OF_FILE); } } while(braces_open != 0); return loop; } /* evaulate accordingly */ if(second_value == VARIABLE_IF) { error_value = interpret_braces(individual, 0L, 0); } if(second_value == VARIABLE_WHILE) { NA_ASSERT(&value[3], "eval value[3]"); error_value = interpret_braces(individual, &value[3], location + return_value + 4); } if(error_value == -1) { return -1; /* Enough information presented by this point */ } return return_value + 4; } if(individual->main_status == MAIN_NOT_RUN) { return APESCRIPT_ERROR(individual, AE_CODE_OUTSIDE_FUNCTION); } if(VARIABLE_INPUT(second_value, code)) /* x = y + z; */ { n_int return_value; if((value[2] != APESCRIPT_OPERATOR) || (value[3] != SYNTAX_EQUALS)) { return APESCRIPT_ERROR(individual, AE_INPUT_VARIABLE_WITHOUT_EQUALS); } return_value = interpret_apply(code, individual, &value[4], &output_number, APESCRIPT_SEMICOLON); if(return_value == -1) { return -1; /* Enough information presented by this point */ } if(code->sc_input(individual, second_value,output_number) == -1) { return APESCRIPT_ERROR(individual, AE_ASSIGN_VALUE_FAILED); } SC_DEBUG_STRING(individual->interpret_data, scdebug_variable(second_value)); SC_DEBUG_STRING(individual->interpret_data, " = "); SC_DEBUG_NUMBER(individual->interpret_data, output_number); SC_DEBUG_STRING(individual->interpret_data, " ;"); SC_DEBUG_NEWLINE(individual->interpret_data); return return_value + 4; } return APESCRIPT_ERROR(individual, AE_UNKNOWN_SYNTAX_FROM_INTERPRET); } /** * The start of the interpreter cycle. * @param interp pointer to the interpreter structure that is being executed. */ static void interpret_start(n_interpret * interp, n_individual_interpret * individual) { n_byte *local_data = interp->binary_code->data; n_int *local_number = interp->number_buffer; n_int *local_variable = individual->variable_references; n_int end_loop = io_bytes_to_int(local_data); n_byte *start_numbers = &local_data[end_loop]; n_int local_number_num = io_bytes_to_int(start_numbers); n_int loop = 0; individual->main_status = MAIN_NOT_RUN; individual->braces_count = 0; while(loop++ < BRACES_MAX) { (void)interpret_braces(individual, 0L, 0); /* No errors in this initialisation */ } individual->braces_count = 0; loop = 1; local_number[0] = 0; while(loop < local_number_num) { local_number[loop] = (n_int)io_bytes_to_int(&start_numbers[loop*(n_int)SIZEOF_NUMBER_WRITE]); loop++; } loop = 0; while(loop < (VARIABLE_MAX)) { local_variable[loop++] = 0; } } /** * Makes sure all the data associated with the interpreter is freed etc. * @param interp pointer to the interpreter structure that is being executed. * @return zero on success, minus one on failure. */ static n_int interpret_code(n_interpret * interp, n_individual_interpret * individual) { n_byte *local_data = interp->binary_code->data; n_int loop = SIZEOF_NUMBER_WRITE; n_int cycle_count = 0; n_int end_loop = io_bytes_to_int(local_data); if (individual->interpret_location != 0) { loop = individual->interpret_location; individual->interpret_location = 0; } /* this is the interpret loop */ do { n_int result = interpret_syntax(interp, individual, &local_data[loop], loop); if(result == -1) { return -1; /* Enough information presented by this point */ } if(result != 0) { loop += result; } else /* This is the while check conditional */ { n_brace * local_brace; n_int brace_number = (individual->braces_count - 1); n_byte first_evaluate; if(brace_number < 0) { return APESCRIPT_ERROR(individual, AE_TOO_MANY_CLOSE_BRACES); } local_brace = &(individual->braces[brace_number]); first_evaluate = local_brace->evaluate[0]; if(first_evaluate == APESCRIPT_RUN || first_evaluate == APESCRIPT_FUNCTION) /* check the function run */ { if(first_evaluate == APESCRIPT_FUNCTION) { local_brace->evaluate[0] = APESCRIPT_RUN; loop = io_bytes_to_int(&(local_brace->evaluate[1])); } else /* end of the run function , put back to where 'run' is called */ { loop = io_bytes_to_int(&(local_brace->evaluate[1 + SIZEOF_NUMBER_WRITE])); if(interpret_braces(individual, 0L, -1) == -1) /* remove the run function from braces */ { return -1; /* Enough information presented by this point */ } SC_DEBUG_STRING(individual->interpret_data, "}"); SC_DEBUG_DOWN(individual->interpret_data); SC_DEBUG_NEWLINE(individual->interpret_data); } } else { n_int return_value = 0; if(interpret_apply(interp, individual, local_brace->evaluate, &return_value, APESCRIPT_CLOSE_BRACKET) == -1) { return -1; /* Enough information presented by this point */ } if(return_value == 0) { if(interpret_braces(individual, 0L, -1) == -1) { return -1; /* Enough information presented by this point */ } SC_DEBUG_STRING(individual->interpret_data,"}"); SC_DEBUG_DOWN(individual->interpret_data); SC_DEBUG_NEWLINE(individual->interpret_data); loop++; } else { loop = local_brace->braces_start; } } } cycle_count++; } while((loop < end_loop) && (cycle_count < CYCLE_COUNT_RESET) && (individual->leave == 0)); if ((individual->leave != 0) || (cycle_count == CYCLE_COUNT_RESET)) { individual->interpret_location = loop; } else { if(individual->main_status == MAIN_NOT_RUN) { return APESCRIPT_ERROR(individual, AE_NO_MAIN_CODE); } SC_DEBUG_OFF(individual->interpret_data); /* turn off debugging after first cycle */ } return 0; } void interpret_individual(n_individual_interpret * individual) { individual->interpret_location = 0; individual->leave = 0; individual->localized_leave = 0; } /** Makes sure all the data associated with the interpreter is freed etc. @param to_clean The pointer to the n_interpret struct that is being expunged. */ void interpret_cleanup(n_interpret ** to_clean) { #ifdef SCRIPT_DEBUG scdebug_file_cleanup(); #endif if (*to_clean == 0L) { return; } if ((*to_clean)->binary_code != 0L) { io_file_free(&((*to_clean)->binary_code)); } memory_free((void**)to_clean); } /** * This processes a single cycle of the ApeScript interpreter. * @param code the ApeScript code to be executed. * @param exit_offset if greater than minus one, the value entry to indicate exiting interpreter. * @param structure the structure to be passed into the start and end functions. * @param start the function to be run at the start of the ApeScript cycle. * @param end the function to be run at the end of the ApeScript cycle. * @return -1 in error case, 0 in leave and don't cycle back, 1 in leave and continue to cycle back. */ n_int interpret_cycle(n_interpret * code, n_individual_interpret * individual, n_int exit_offset, void * structure, void * data, script_external * start, script_external * end) { if (code == 0L) { return 0; } individual->interpret_data = data; if (individual->localized_leave) { individual->localized_leave--; } /* the localized_leave = 1 case is where the interpreter was left initially */ if (individual->localized_leave) { return 1; } if (individual->interpret_location == 0) { interpret_start(code, individual); if (start != 0L) { (*start)(individual, structure, data); } } if (interpret_code(code, individual) == -1) { return -1; } if (individual->interpret_location == 0) { if ((code != 0L) && (end != 0L)) { (*end)(individual, structure, data); } } individual->localized_leave = individual->leave; if (exit_offset > -1) { n_int * variables = individual->variable_references; if (variables[exit_offset] == 0) { return 1; } } return 0; } n_int apescript_error(n_individual_interpret * individual, AE_ENUM value, n_constant_string location, n_int line_number) { n_int loop = 0; AE_ENUM local_enum; n_constant_string local_error; do { local_enum = apescript_errors[loop].enum_value; local_error = apescript_errors[loop].error_string; if (value == local_enum) { if (individual->interpret_data) { SC_DEBUG_STRING(individual->interpret_data, " [ ERROR : "); SC_DEBUG_STRING(individual->interpret_data, local_error ); SC_DEBUG_STRING(individual->interpret_data," ]"); SC_DEBUG_NEWLINE(individual->interpret_data); SC_DEBUG_OFF(individual->interpret_data); } return SHOW_ERROR_FILE_LINE(local_error, location, line_number); } loop++; } while((local_enum != AE_NO_ERROR) && (local_error != 0L)); return apescript_error(individual, AE_UNKNOWN_ERROR, location, line_number); } <|start_filename|>test/test_sim_time.c<|end_filename|> /**************************************************************** test_sim_time.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #include <stdio.h> #include <time.h> #include "../toolkit/toolkit.h" #include "../script/script.h" #include "../sim/sim.h" #include "../entity/entity.h" #include "../universe/universe.h" n_int draw_error(n_constant_string error_text, n_constant_string location, n_int line_number) { printf("ERROR: %s @ %s %ld\n",(const n_string) error_text, location, line_number); return -1; } int main (int c, char **v) { n_uint count = 0; clock_t startTime = clock(); clock_t deltaTime = (CLOCKS_PER_SEC * 60 * 50) + startTime; n_uint xorchoff = 0; if (c == 2) { n_int string_length = io_length((n_byte*)v[1], STRING_BLOCK_SIZE); if (string_length > 0) { xorchoff = math_hash((n_byte*)v[1], (n_uint)string_length); } } printf(" --- test sim time --- start -----------------------------------------------\n"); printf("start rand %lu\n", startTime ^ xorchoff); sim_init(KIND_START_UP, startTime ^ xorchoff, MAP_AREA, 0); do { sim_cycle(); count++; } while (deltaTime > clock()); sim_close(); printf("count %lu\n", count); printf(" --- test sim time --- end -----------------------------------------------\n"); return 0; } <|start_filename|>entity/social.c<|end_filename|> /**************************************************************** social.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /*! \file social.c * \brief This handles social interactions and management of the social graph */ #include "entity.h" #include "entity_internal.h" /** Status preference */ #define GENE_STATUS_PREFERENCE(gene) GENE_VAL_REG(gene, 15, 12, 10, 1) /** Pigmentation preference */ #define GENE_PIGMENTATION_PREFERENCE(gene) GENE_VAL_REG(gene, 5, 3, 11, 4) /** mating preference for height */ #define GENE_HEIGHT_PREFERENCE(gene) GENE_VAL_REG(gene, 9, 8, 14, 10) /** mating preference for frame */ #define GENE_FRAME_PREFERENCE(gene) GENE_VAL_REG(gene, 9, 0, 8, 2) /** mating preference for hair length */ #define GENE_HAIR_PREFERENCE(gene) GENE_VAL_REG(gene, 10, 7, 14, 15) /** Groom */ #define GENE_GROOM(gene) GENE_VAL_REG(gene, 14, 2, 5, 10) /** Aggression */ #define GENE_AGGRESSION(gene) GENE_VAL_REG(gene, 11, 3, 5, 0) /** Mate bond */ #define GENE_MATE_BOND(gene) GENE_VAL_REG(gene, 10, 2, 4, 0) /** Degree of aversion to incest */ #define GENE_INCEST_AVERSION(gene) GENE_VAL_REG(gene, 10, 8, 4, 9) /** Latent energy use */ #define GENE_LATENT_ENERGY_USE(gene) GENE_VAL_REG(gene, 14, 3, 6, 10) #ifdef FEATURE_SET static void simulated_feature_copy(simulated_feature * to, simulated_feature * from) { to->type = from->type; to->value = from->value; to->frequency = from->frequency; } static void simulated_feature_set(simulated_feature * to, n_byte feature_type, n_byte2 feature_value) { to->type = (n_byte)feature_type; to->value = (n_byte2)feature_value; to->frequency = (n_byte2)1; } /** * @brief Returns the array index of a given feature type within a set * @param s A set of features * @param feature_type the feature type * @return array index of a given feature type within a set */ static n_int simulated_featureset_feature_index(simulated_featureset * s, n_byte feature_type) { n_int i=0; while (i < s->feature_number) { if (s->features[i].type >= feature_type) { break; } i++; } if (i == s->feature_number) { return -1; } return i; } /** * @brief Normalises the feature frequencies within a set * @param s a set of features */ static void simulated_featureset_normalise_feature_frequencies(simulated_featureset *s) { n_uint i, tot=0; n_uint max = MAX_FEATURE_FREQUENCY>>1; /** get the total frequency count */ for (i = 0; i < s->feature_number; i++) { tot += (n_uint)s->features[i].frequency; } if (tot == 0) tot = 1; for (i = 0; i < s->feature_number; i++) { s->features[i].frequency = (n_byte2)((n_uint)s->features[i].frequency * max / tot); } } /** * @brief Adds a feature to the given set * @param s Pointer to the feature set * @param feature_type the type of feature * @param feature_value value of the feature * @return 0 on success, -1 otherwise */ static n_int simulated_featureset_update(simulated_featureset * s, n_byte feature_type, n_int feature_value) { /** get the index of the feature within the array */ n_int feature_index = simulated_featureset_feature_index(s, feature_type); n_byte2 min; n_int i,j; if (s->features[feature_index].type == (n_byte)feature_type) { /** alter the value associated with an existing feature type */ s->features[feature_index].value = (n_byte2)feature_value; s->features[feature_index].frequency++; /** normalise the feature frequencies to prevent them from going out of bounds */ if (s->features[feature_index].frequency > MAX_FEATURE_FREQUENCY) { simulated_featureset_normalise_feature_frequencies(s); } return 0; } else { if (s->feature_number < MAX_FEATURESET_SIZE) { /** add a new feature type to the array */ if (s->feature_number > 1) { for (i = (n_int)s->feature_number-1; i >= (n_int)feature_index; i--) { simulated_feature_copy(&(s->features[i+1]), &(s->features[i])); } } i = feature_index; s->feature_number++; simulated_feature_set(&(s->features[i]), (n_byte)feature_type, (n_byte2)feature_value); return 0; } else { /** pick the least frequent feature and replace it */ min = s->features[0].frequency; feature_index = 0; for (i = 1; i < (n_int)s->feature_number; i++) { if (s->features[i].frequency < min) { min = s->features[i].frequency; feature_index = i; } } /** re-sort */ j = 0; for (i = 0; i < (n_int)s->feature_number; i++) { if (s->features[i].type >= (n_byte)feature_type) { j = i; break; } } for (i = (n_int)feature_index; i > j; i--) { simulated_feature_copy(&(s->features[i]), &(s->features[i-1])); } simulated_feature_set(&(s->features[j]), (n_byte)feature_type, (n_byte2)feature_value); for (i = 0; i < (n_int)s->feature_number; i++) { for (j = i+1; j < (n_int)s->feature_number; j++) { if (s->features[j].type < s->features[i].type) { feature_type = s->features[i].type; s->features[i].type = s->features[j].type; s->features[j].type = (n_byte)feature_type; } } } } } return -1; } static n_int featureset_match_threshold(n_byte feature_type) { if (feature_type == FEATURESET_TERRITORY) return 1; return 2; } /** * @brief Normalises the number of observations for each stereotype * @param local_being Pointer to the being */ static void social_normalise_stereotype_observations( simulated_being * local_being) { simulated_isocial * graph; n_uint i, tot=0; simulated_featureset * s; n_uint max = MAX_FEATURESET_OBSERVATIONS>>1; /** Get the social graph */ graph = being_social(local_being); if (graph==0) return; for (i = SOCIAL_SIZE_BEINGS; i < SOCIAL_SIZE; i++) { if (!SOCIAL_GRAPH_ENTRY_EMPTY(graph,i)) { s = &graph[i].classification; tot += (n_uint)s->observations; } } if (tot == 0) return; for (i = SOCIAL_SIZE_BEINGS; i < SOCIAL_SIZE; i++) { if (!SOCIAL_GRAPH_ENTRY_EMPTY(graph,i)) { s = &graph[i].classification; s->observations = (n_byte2)((n_uint)s->observations * max / tot); } } } /** * @brief Returns the social graph array index of the closest matching * stereotype to the met being * @param meeter_being Pointer to the being doing the meeting * @param social_graph_index Social graph index of the being which was met * @return Social graph array index of the closest stereotype * or -1 of there are no stereotypes */ static n_int social_get_stereotype( simulated_being * meeter_being, n_int social_graph_index) { n_int i,j,diff,dv,index,hits,min=0,result=-1; n_byte normalise_features; simulated_isocial * meeter_social_graph; simulated_featureset * s1, * s2; /** Get the social graph for the being doing the meeting */ meeter_social_graph = being_social(meeter_being); if (meeter_social_graph==0) return -1; /** get the observed feature set for the met being */ s2 = &meeter_social_graph[social_graph_index].classification; /** the upper range of social graph entries between SOCIAL_SIZE_BEINGS and SOCIAL_SIZE contains abstract beings or stereotypes */ for (i = SOCIAL_SIZE_BEINGS; i < SOCIAL_SIZE; i++) { if (!SOCIAL_GRAPH_ENTRY_EMPTY(meeter_social_graph,i)) { /** get the feature set for the stereotype */ s1 = &meeter_social_graph[i].classification; normalise_features = 0; diff = 0; hits = 0; /** for every feature within the stereotype */ for (j = 0; j < s1->feature_number; j++) { /** does this feature exist for the met being? */ index = simulated_featureset_feature_index(s2, s1->features[j].type); if (index > -1) { hits++; /** difference between the feature values */ dv = (n_int)s1->features[j].value - (n_int)s2->features[index].value; if (dv < 0) dv = -dv; /** update the total difference between the stereotype and the met being */ diff += dv; /** does the stereotype feature match the met being feature? if so then increment the observation frequency */ if (dv < featureset_match_threshold(s1->features[j].type)) { /** increment the frequency of stereotype features */ s1->features[j].frequency++; if (s1->features[j].frequency > MAX_FEATURE_FREQUENCY) { normalise_features = 1; } } } } /** if all stereotype features were matched and the match was better than the best found */ if (hits == s1->feature_number) { if ((result == -1) || (diff < min)) { min = diff; result = i; } /** increment the number of times when this stereotype was fully matched */ s1->observations++; if (s1->observations > MAX_FEATURESET_OBSERVATIONS) { social_normalise_stereotype_observations(meeter_being); } } /** normalise the stereotype feature frequencies if necessary */ if (normalise_features == 1) { simulated_featureset_normalise_feature_frequencies(s1); } } } return result; } /** * @brief When one being meets another remember the observable features * @param meeter_being the being foing the meeting * @param met_being the being which was met * @param social_graph_index index within the meeters social graph of the met being */ static void social_meet_update_features( simulated_being * meeter_being, simulated_being * met_being, n_int social_graph_index) { simulated_isocial * meeter_social_graph; #ifdef TERRITORY_ON n_int idx; #endif /** Get the social graph for the being doing the meeting */ meeter_social_graph = being_social(meeter_being); if (meeter_social_graph==0) return; /** Note: perhaps not all features should be observed at once. This should maybe be under attentional control. Also observations should perhaps include learned biases from existing stereotypes */ simulated_featureset_update(&meeter_social_graph[social_graph_index].classification, FEATURESET_PIGMENTATION, GENE_PIGMENTATION(being_genetics(met_being))); simulated_featureset_update(&meeter_social_graph[social_graph_index].classification, FEATURESET_HAIR, GENE_HAIR(being_genetics(met_being))); simulated_featureset_update(&meeter_social_graph[social_graph_index].classification, FEATURESET_HEIGHT, being_height(met_being)); simulated_featureset_update(&meeter_social_graph[social_graph_index].classification, FEATURESET_FAT, GET_BODY_FAT(met_being)); simulated_featureset_update(&meeter_social_graph[social_graph_index].classification, FEATURESET_EYE_SHAPE, GENE_EYE_SHAPE(being_genetics(met_being))); simulated_featureset_update(&meeter_social_graph[social_graph_index].classification, FEATURESET_EYE_COLOR, GENE_EYE_COLOR(being_genetics(met_being))); simulated_featureset_update(&meeter_social_graph[social_graph_index].classification, FEATURESET_EYE_SEPARATION, GENE_EYE_SEPARATION(being_genetics(met_being))); simulated_featureset_update(&meeter_social_graph[social_graph_index].classification, FEATURESET_NOSE_SHAPE, GENE_NOSE_SHAPE(being_genetics(met_being))); simulated_featureset_update(&meeter_social_graph[social_graph_index].classification, FEATURESET_EAR_SHAPE, GENE_EAR_SHAPE(being_genetics(met_being))); simulated_featureset_update(&meeter_social_graph[social_graph_index].classification, FEATURESET_EYEBROW_SHAPE, GENE_EYEBROW_SHAPE(being_genetics(met_being))); simulated_featureset_update(&meeter_social_graph[social_graph_index].classification, FEATURESET_MOUTH_SHAPE, GENE_MOUTH_SHAPE(being_genetics(met_being))); #ifdef TERRITORY_ON idx = APESPACE_TO_TERRITORY(being_location_y(meeter_being))*TERRITORY_DIMENSION + APESPACE_TO_TERRITORY(being_location_x(meeter_being)); simulated_featureset_update(&meeter_social_graph[social_graph_index].classification, FEATURESET_TERRITORY, meeter_being->events.territory[idx].name); #endif } #endif /** * @brief Returns a string for the name of the ape in the given social graph array index. * @param group Pointer to the simulated_group * @param local_being Pinter to the ape * @param social_graph_index Array index within the social graph * @param met BEING_MEETER=return name for the meeter, BEING_MET=return name for the met * @param name Returned ape name */ void social_graph_link_name( simulated_group * group, simulated_being * local_being, n_int social_graph_index, n_byte met, n_string name) { simulated_isocial * local_social_graph; /** Get the social graph for the being */ local_social_graph = being_social(local_being); if (local_social_graph==0) return; switch(local_social_graph[social_graph_index].entity_type) { case ENTITY_BEING: { being_name_byte2(local_social_graph[social_graph_index].first_name[met], local_social_graph[social_graph_index].family_name[met], name); break; } case ENTITY_BEING_GROUP: (void)SHOW_ERROR("Unimplemented being group entity type"); break; case ENTITY_OBJECT: (void)SHOW_ERROR("Unimplemented object entity type"); break; case ENTITY_TERRITORY: (void)SHOW_ERROR("Unimplemented territory entity type"); break; default: (void)SHOW_ERROR("Unimplemented entity type"); break; } } /** * @brief Align learned preferences with another ape, depending upon * whether it is part of the ingroup or outgroup. * @param group Pointer to the simulated_group * @param meeter_being Pointer to the ape doing the meeting * @param met_being Pointer to the ape being met * @param social_graph_index Array index within the meeter social graph for the met ape */ static void social_group_align_preferences( simulated_group * group, simulated_being * meeter_being, simulated_being * met_being, n_int social_graph_index) { n_int i, incr = -1; simulated_isocial * social_graph; /** don't align with yourself */ if ((meeter_being==met_being) || (social_graph_index < 1)) return; /** get the social graph */ social_graph = being_social(meeter_being); if (social_graph == 0L) return; /** the entry in the social graph for the other being shouldn't be empty */ if (SOCIAL_GRAPH_ENTRY_EMPTY(social_graph,social_graph_index)) return; /** if you are friendly then make your preferences more similar, otherwise make them more disimilar */ if (social_graph[social_graph_index].friend_foe >= (n_byte)social_respect_mean(meeter_being)) { incr = 1; } /** align preferences */ for (i = 0; i < PREFERENCES; i++) { n_int resultant = meeter_being->changes.learned_preference[i]; if (resultant < met_being->changes.learned_preference[i]) { if ((incr > 0) || ((incr < 0) && (resultant > 0))) { resultant += incr; } } else if (resultant > met_being->changes.learned_preference[i]) { if ((incr > 0) || ((incr < 0) && (meeter_being->changes.learned_preference[i]<255))) { resultant -= incr; } } meeter_being->changes.learned_preference[i] = (n_byte)resultant; } } /** * @brief What is the pigmentation attractiveness of met ape to the meeter being ? * @param being_meeter Pointer to the ape doing the meeting * @param being_met Pointer to the ape being met * @return Attractiveness value */ static n_int social_attraction_pigmentation( simulated_being * being_meeter, simulated_being * being_met) { n_int ppref, pdiff; n_byte fem = (FIND_SEX(GET_I(being_meeter)) == SEX_FEMALE); /** Either no preference for pigmentation, or only favour attractive mates */ ppref = NATURE_NURTURE( GENE_PIGMENTATION_PREFERENCE(being_genetics(being_meeter)), being_meeter->changes.learned_preference[PREFERENCE_MATE_PIGMENTATION_MALE+fem]); pdiff = GENE_PIGMENTATION(being_genetics(being_met)) - ppref; if ((pdiff >= -2) && (pdiff <= 2)) { pdiff = ABS(pdiff); return (3 - pdiff); } return 0; } /** * What is the hair attractiveness of the met ape to the meeter being ? * @param meeter_being Pointer to the ape doing the meeting * @param met_being Pointer to the ape being met * @return Attractiveness value */ static n_int social_attraction_hair( simulated_being * meeter_being, simulated_being * met_being) { n_int ppref, pdiff; n_byte fem = (FIND_SEX(GET_I(meeter_being)) == SEX_FEMALE); /** either no preference for hair length, or only favour attractive mates */ ppref = NATURE_NURTURE( GENE_HAIR_PREFERENCE(being_genetics(meeter_being)), meeter_being->changes.learned_preference[PREFERENCE_MATE_HAIR_MALE+fem]); pdiff = GENE_HAIR(being_genetics(met_being)) - ppref; if ((pdiff >= -2) && (pdiff <= 2)) { pdiff = ABS(pdiff); return (3 - pdiff); } return 0; } /** * What is the height attractiveness of the met ape to the meeter being ? * @param meeter_being Pointer to the ape doing the meeting * @param met_being Pointer to the ape being met * @return Attractiveness value */ static n_int social_attraction_height( simulated_being * meeter_being, simulated_being * met_being) { n_int ppref; n_byte fem = (FIND_SEX(GET_I(meeter_being)) == SEX_FEMALE); /** Either don't care about height or favour mates who are taller or shorter */ ppref = NATURE_NURTURE( GENE_HEIGHT_PREFERENCE(being_genetics(meeter_being)), meeter_being->changes.learned_preference[PREFERENCE_MATE_HEIGHT_MALE+fem]); /** prefer taller or shorter, < 8 don't care about height 12-15 prefer taller 8-11 prefer shorter*/ if (ppref >= 8) { if ((ppref>=12) && (being_height(met_being) > being_height(meeter_being))) { /** prefer taller */ return 1; } else { if ((ppref<12) && (being_height(met_being) < being_height(meeter_being))) { /** prefer shorter */ return 1; } } } return 0; } /** * @brief What is the frame attractiveness of the met ape to the meeter being ? * @param meeter_being Pointer to the ape doing the meeting * @param met_being Pointer to the ape being met * @return Attractiveness value */ static n_int social_attraction_frame( simulated_being * meeter_being, simulated_being * met_being) { n_int ppref; n_byte fem = (FIND_SEX(GET_I(meeter_being)) == SEX_FEMALE); /** Either don't care about frame or favour mates who are fatter or thinner */ ppref = NATURE_NURTURE( GENE_FRAME_PREFERENCE(being_genetics(meeter_being)), meeter_being->changes.learned_preference[PREFERENCE_MATE_FRAME_MALE+fem]); if ((ppref>6) && (ppref<=11) && (GET_BODY_FAT(met_being) > GET_BODY_FAT(meeter_being))) { /** prefer fatter */ return 1; } else { if ((ppref>11) && (GET_BODY_FAT(met_being) < GET_BODY_FAT(meeter_being))) { /** prefer thinner */ return 1; } } return 0; } /** * @brief What is the pheromone attractiveness of the met ape to the meeter being ? * Pheromone attraction is inversely proportional to genetic similarity. * @param meeter_being Pointer to the ape doing the meeting * @param met_being Pointer to the ape being met * @return Attractiveness value */ static n_int social_attraction_pheromone( simulated_being * meeter_being, simulated_being * met_being) { n_int ch, i, different = 0; n_genetics * meeter_genetics = being_genetics(meeter_being); n_genetics * met_genetics = being_genetics(met_being); for (ch = 0; ch < CHROMOSOMES; ch++) { for (i = 0; i < 32; i++) { if (((meeter_genetics[ch] >> i) & 1) != ((met_genetics[ch] >> i) & 1)) { different++; } } } if (different < MINIMUM_GENETIC_VARIATION) { return 0-GENE_INCEST_AVERSION(meeter_genetics); } else { return 1; } } /** * @brief If two beings have previously met return the social graph index * @param meeter_being Pointer to the ape doing the meeting * @param met_being Pointer to the ape being met * @return Array index within the social graph of the meeter, -1 if not found */ n_int get_simulated_isocial( simulated_being * meeter_being, simulated_being * met_being) { n_byte2 i; simulated_isocial * graph = being_social(meeter_being); if (!graph) return -1; for (i=1; i<SOCIAL_SIZE_BEINGS; i++) { if (!SOCIAL_GRAPH_ENTRY_EMPTY(graph,i)) { if (graph[i].entity_type==ENTITY_BEING) { if (being_name_comparison(met_being, graph[i].first_name[BEING_MET], graph[i].family_name[BEING_MET])) { return i; } } } } return -1; } /** * @brief Returns the social graph index for the least familiar ape * @param meeter_being Pointer to the ape doing the meeting * @param met_being Pointer to the ape being met * @return Array index for the least familiar ape within the social graph of the meeter, -1 if not met */ static n_int get_stranger_link( simulated_being * meeter_being, simulated_being * met_being) { n_byte2 i=1; n_int stranger_index=-1; n_byte2 stranger=65535, familiarity=0; n_int time_since_met; simulated_isocial * graph = being_social(meeter_being); if (!graph) return 0; for (i=1; i<SOCIAL_SIZE_BEINGS; i++) { if (!SOCIAL_GRAPH_ENTRY_EMPTY(graph,i)) { /** not a family relationship */ if (!IS_FAMILY_MEMBER(graph,i)) { /** minimum familiarity */ familiarity = graph[i].familiarity; if (familiarity < stranger) { /** Forget old stuff in order to avoid too much inflexibility */ time_since_met = land_date() - graph[i].space_time.date; if ((time_since_met >= SOCIAL_FORGET_DAYS) || (graph[i].space_time.date==0)) { stranger = familiarity; stranger_index = i; } } } } else { /** If this entry is empty */ stranger_index = i; break; } } return stranger_index; } /** * @brief When two beings meet this updates the social graph * @param meeter_being Pointer to the being doing the meeting * @param met_being Pointer to the being who was met * @param location_type type of meeting * @return Array index within the social graph of the meeter, -1 if not met */ static n_int social_meet( simulated_being * meeter_being, simulated_being * met_being, n_byte location_type) { n_int friend_or_foe, index = -1, stereotype_index = -1; n_byte2 familiarity = 0; simulated_isocial * graph = being_social(meeter_being); n_byte2 met = 0; if (!graph) return -1; /** transmit any pathogens between the meeting beings */ being_immune_transmit(meeter_being, met_being, PATHOGEN_TRANSMISSION_AIR); /** get the social graph index which will be used to represent this relation */ index = get_simulated_isocial(meeter_being, met_being); if (index > 0) { familiarity = graph[index].familiarity; met=1; } else { /** get the index of an existing social graph entry which can be overwritten */ index = get_stranger_link(meeter_being, met_being); } if ((met == 1) || ((met == 0) && (index > 0))) { #ifdef FEATURE_SET /** record the observable features of the being which was met */ social_meet_update_features( meeter_being, met_being, index); /** get the social graph index of the corresponding stereotype */ stereotype_index = social_get_stereotype( meeter_being, index); #endif /** set the focus of attention to this being */ being_set_attention(meeter_being,ATTENTION_ACTOR, index); /** if we havn't met previously */ if (met == 0) { if (stereotype_index > -1) { /** get the predisposition towards this stereotype */ friend_or_foe = graph[stereotype_index].friend_foe; } else { /** the prejudice function */ friend_or_foe = SOCIAL_RESPECT_NORMAL - social_attraction_pheromone(meeter_being,met_being) + social_attraction_pigmentation(meeter_being,met_being) + social_attraction_height(meeter_being,met_being) + social_attraction_frame(meeter_being,met_being) + social_attraction_hair(meeter_being,met_being) #ifdef EPISODIC_ON + episodic_met_being_celebrity(meeter_being, met_being) #endif ; /** TODO create new stereotype based upon the met being features */ } /** Met another being */ graph[index].entity_type = ENTITY_BEING; /** who did the meeting */ graph[index].first_name[BEING_MEETER] = being_gender_name(meeter_being); graph[index].family_name[BEING_MEETER] = being_family_name(meeter_being); /** who was met */ graph[index].first_name[BEING_MET] = being_gender_name(met_being); graph[index].family_name[BEING_MET] = being_family_name(met_being); /** initially no attraction */ graph[index].attraction = 0; /** limit fof within range */ if (friend_or_foe < 0) friend_or_foe = 0; if (friend_or_foe > 255) friend_or_foe = 255; graph[index].friend_foe = (n_byte)friend_or_foe; #ifdef BRAINCODE_ON /** initialise the braincode associated with this individual */ being_init_braincode(meeter_being, met_being, graph[index].friend_foe, BRAINCODE_EXTERNAL); #endif } if (location_type == LOCATION_KNOWN) { /** this being was seen somewhere in my vicinity */ graph[index].space_time.location[0] = (n_byte2)being_location_x(meeter_being); graph[index].space_time.location[1] = (n_byte2)being_location_y(meeter_being); } else { /** location unknown */ graph[index].space_time.location[0] = 0; graph[index].space_time.location[1] = 0; } /** record the state of the met beting */ graph[index].belief = being_state(met_being); /** date of the meeting */ graph[index].space_time.date = land_date(); graph[index].space_time.time = land_time(); /** getting more familiar */ if (familiarity < 65535) { graph[index].familiarity = familiarity + 1; } /** friendliness can be increased simply through familiarity */ if (graph[index].friend_foe < 255) { graph[index].friend_foe++; } } return index; } /** * @brief Returns the social graph index of the given relationship type. * This can be used for example to search for the father of an * ape within the social graph. * @param meeter_being Pointer to the ape * @param relationship The type of relationship to search for * @return Array index of the social graph for the given type of relationship, -1 if not found */ n_int social_get_relationship( simulated_being * meeter_being, n_byte relationship) { n_int index; simulated_isocial * meeter_social_graph; /** get the social graph */ meeter_social_graph = being_social(meeter_being); if (meeter_social_graph == 0L) { return -1; } /** Search the social graph */ for (index = 1; index < SOCIAL_SIZE_BEINGS; index++) { /** Is this the desired relationship type? */ if (meeter_social_graph[index].relationship == relationship) { return index; } } return -1; } /** * @brief Set the relationship type between two apes * @param meeter_being Pointer to the ape doing the meeting * @param relationship The type of relationship * @param met_being Pointer to the ape being met * @param group Pointer to the simulated_group * @return Array index of the meeter social graph, -1 if not met */ n_int social_set_relationship(simulated_group * group, simulated_being * meeter_being, n_byte relationship, simulated_being * met_being) { n_int index; simulated_isocial * meeter_social_graph; /** no relationship specified */ if (relationship == 0) return -1; /** create the social graph entry if necessary and return its array index */ index = social_meet(meeter_being, met_being, LOCATION_UNKNOWN); if (index > -1) { /** get the social graph */ meeter_social_graph = being_social(meeter_being); if (meeter_social_graph == 0L) { return -1; } /** set the relationship type */ meeter_social_graph[index].relationship = relationship; } return index; } /** * @brief When two apes meet within a given maximum range * this updates the social graph of both. * @param meeter_being Pointer to the ape doing the meeting * @param met_being Pointer to the ape being met * @param distance Distance between the apes * @param group Pointer to the simulated_group * @return Array index of the meeter social graph, -1 if not met */ n_int social_network(simulated_group * group, simulated_being * meeter_being, simulated_being * met_being, n_uint distance) { n_int being_index = -1; if (distance < SOCIAL_RANGE) { being_index = social_meet(meeter_being, met_being, LOCATION_KNOWN); } return being_index; } static void social_parasite_cycle(simulated_being * meeter_being, simulated_being * met_being, n_int distance) { /** acquire parasites from the environment with some low probability, and existing parasites multiply */ n_int paraprob = being_random(meeter_being); if (paraprob < (PARASITE_ENVIRONMENT + (PARASITE_BREED * being_parasites(meeter_being)))) { being_add_parasites(meeter_being); } /** parasites sap energy */ being_energy_delta(meeter_being, 0 - (PARASITE_ENERGY_COST * being_parasites(meeter_being))); if (distance < PARASITE_HOP_MAX_DISTANCE) { /** parasite transmission - e.g. flea hop */ if (being_parasites(met_being) < being_parasites(meeter_being)) { being_add_parasites(met_being); being_remove_parasites(meeter_being, 1); } } } /** * @brief Grooming behavior * @param meeter_being Pointer to the ape doing the meeting * @param met_being Pointer to the ape being met * @param distance Distance between the apes * @param awake Whether the met being is awake * @param familiarity Familiarity with the met ape * @param group Pointer to the simulated_group * @return 1 if grooming, 0 otherwise */ n_byte social_groom( simulated_group * group, simulated_being * meeter_being, simulated_being * met_being, n_uint distance, n_int awake, n_byte2 familiarity) { n_int meeter_index, met_index; n_byte grooming = 0, groom_decisions, groomloc; n_int gpref; social_parasite_cycle(meeter_being, met_being, distance); /** social grooming removes parasites and alters social status relationships */ if ((awake != FULLY_ASLEEP) && (distance < GROOMING_MAX_SEPARATION) && (being_speed(meeter_being) < MAX_SPEED_WHILST_GROOMING)) { n_int groomprob = being_random(meeter_being) & 16383; if (familiarity > 16) familiarity=16; { /** is the groomee female? */ n_byte fem = (FIND_SEX(GET_I(met_being)) == SEX_FEMALE); /** grooming preference */ gpref = NATURE_NURTURE( GENE_GROOM(being_genetics(meeter_being)), meeter_being->changes.learned_preference[PREFERENCE_GROOM_MALE+fem]); } /** individuals which are familiar tend to groom more often */ if (groomprob < GROOMING_PROB + (gpref*(1+familiarity)*GROOMING_PROB_HONOR*(1+being_honor(met_being)))) { /** transmit pathogens via touch */ being_immune_transmit(meeter_being, met_being, PATHOGEN_TRANSMISSION_TOUCH); being_immune_transmit(met_being, meeter_being, PATHOGEN_TRANSMISSION_TOUCH); /** pick a body location to groom */ groomloc = being_attention(meeter_being,ATTENTION_BODY); groom_decisions = 0; while ((met_being->changes.inventory[groomloc] & INVENTORY_GROOMED) && (groom_decisions<4)) { met_being->changes.inventory[groomloc] |= INVENTORY_GROOMED; groomloc = (n_byte)(being_random(meeter_being) % INVENTORY_SIZE); groom_decisions++; } /** groomed wounds disappear */ if (met_being->changes.inventory[groomloc] & INVENTORY_WOUND) { met_being->changes.inventory[groomloc] = INVENTORY_GROOMED; } /** grooming location becomes the new focus of attention */ being_set_attention(meeter_being, ATTENTION_BODY, groomloc); episodic_interaction(meeter_being, met_being, EVENT_GROOM, AFFECT_GROOM, groomloc); episodic_interaction(met_being, meeter_being, EVENT_GROOMED, AFFECT_GROOM, groomloc); /** the two beings meet and become more friendly */ meeter_index = social_meet(meeter_being, met_being, LOCATION_KNOWN); if (meeter_index > -1) { met_index = social_meet(met_being, meeter_being, LOCATION_KNOWN); if (met_index > -1) { simulated_isocial * graph = being_social(meeter_being); if (!graph) return 0; if ((graph[meeter_index].friend_foe)<255) { graph[meeter_index].friend_foe++; } if ((graph[met_index].friend_foe)<255) { graph[met_index].friend_foe++; } } } /** Alter social status relations. The groomer gains status, since they are providing a service */ being_honor_inc_dec(meeter_being, met_being); /** Decrement parasites */ being_remove_parasites(met_being, PARASITES_REMOVED); grooming = 1; } } return grooming; } /** * @brief Squabbling and fighting * @param meeter_being Pointer to the ape doing the meeting * @param met_being Pointer to the ape being met * @param distance Distance between the apes * @param is_female Whether the met being is female * @param group Pointer to the simulated_group * @return The new being state: showforce/attack */ n_byte2 social_squabble( simulated_being * meeter_being, simulated_being * met_being, n_uint distance, n_int is_female, simulated_group * group) { n_uint agro; n_byte2 ret_val = 0; simulated_being * victor, * vanquished; n_int victor_index, vanquished_index; n_byte2 punchloc; n_vect2 delta; /** distance between beings */ being_delta(met_being, meeter_being, &delta); /** battle with rival families */ if ((being_family_first_name(meeter_being) != being_family_first_name(met_being)) && (being_family_second_name(meeter_being) != being_family_second_name(met_being))) { being_facing_towards(meeter_being, &delta); /** high ranking apes will more aggressively defend their honor */ agro = GENE_AGGRESSION(being_genetics(meeter_being)); /** females are less agressive (less testosterone) */ if (is_female) agro >>= 3; if (being_random(meeter_being) < (agro* 4096 + agro* being_honor(meeter_being)*10)) { /** who is the strongest ? */ victor = meeter_being; vanquished = met_being; if (((being_random(meeter_being)&7)*being_energy(meeter_being)) < ((being_random(meeter_being)&7)*being_energy(met_being))) { victor = met_being; vanquished = meeter_being; } vanquished_index = social_meet(victor, vanquished, LOCATION_KNOWN); if (vanquished_index > -1) { victor_index = social_meet(vanquished, victor, LOCATION_KNOWN); if (victor_index > -1) { simulated_isocial * victor_social_graph = being_social(victor); simulated_isocial * vanquished_social_graph = being_social(vanquished); if ((!victor_social_graph) || (!vanquished_social_graph)) return 0; /** victor disrespects the vanquished */ if (victor_social_graph[vanquished_index].friend_foe > SQUABBLE_DISRESPECT) { victor_social_graph[vanquished_index].friend_foe-=SQUABBLE_DISRESPECT; } /** vanquished disrespects the victor */ if (vanquished_social_graph[victor_index].friend_foe > SQUABBLE_DISRESPECT) { vanquished_social_graph[victor_index].friend_foe-=SQUABBLE_DISRESPECT; } } } /** victor increases in honor */ if (being_honor(victor) < 255-SQUABBLE_HONOR_ADJUST) { being_honor_delta(victor, SQUABBLE_HONOR_ADJUST); } /** vanquished decreases in honor */ if (being_honor(vanquished) > SQUABBLE_HONOR_ADJUST) { being_honor_delta(vanquished, 0-SQUABBLE_HONOR_ADJUST); } punchloc = being_random(victor) % INVENTORY_SIZE; if (distance > SQUABBLE_SHOW_FORCE_DISTANCE) { /** show of force */ vanquished->changes.inventory[punchloc] = 0; being_energy_delta(victor, 0 - SQUABBLE_ENERGY_SHOWFORCE); being_energy_delta(vanquished, 0 -SQUABBLE_ENERGY_SHOWFORCE); ret_val |= BEING_STATE_SHOWFORCE; } else { /** attack */ vanquished->changes.inventory[punchloc] = INVENTORY_WOUND; being_energy_delta(victor, 0 - SQUABBLE_ENERGY_ATTACK); being_energy_delta(vanquished, 0 -SQUABBLE_ENERGY_ATTACK); being_honor_swap(victor, vanquished); ret_val |= BEING_STATE_ATTACK; } /** remember the fight */ episodic_interaction(victor, vanquished, EVENT_HIT, AFFECT_SQUABBLE_VICTOR, punchloc); episodic_interaction(vanquished, victor, EVENT_HIT_BY, AFFECT_SQUABBLE_VANQUISHED, punchloc); /** vanquished turns away */ if (meeter_being == vanquished) { n_vect2 negative_delta, zero = {0}; vect2_subtract(&negative_delta, &zero, &delta); being_facing_towards(vanquished, &negative_delta); } else { being_facing_towards(vanquished, &delta); } /** vanquished flees */ being_set_speed(vanquished, SQUABBLE_FLEE_SPEED); } return ret_val; } return 0; } /** * @brief Returns the average friend or foe value * @param local_being Pointer to the ape * @return The average friend or foe value for all social graph entries */ n_uint social_respect_mean( simulated_being *local_being) { n_uint simulated_isocials=0,average=0; simulated_isocial * local_social_graph; n_int i; local_social_graph = being_social(local_being); if (!local_social_graph) return 0; /** note that this includes the self */ for (i=0; i<SOCIAL_SIZE; i++) { if (!SOCIAL_GRAPH_ENTRY_EMPTY(local_social_graph,i)) { simulated_isocials++; average += (n_uint)(local_social_graph[i].friend_foe); } } if (simulated_isocials>0) { return average/simulated_isocials; } return SOCIAL_RESPECT_NORMAL; } /** * @brief Update for a conception event. This stores the date, * details of the father and resets drives and goals. * @param female Pointer to the mother * @param male Pointer to the father * @param group Pointer to the simulated_group */ /*static*/ void social_conception( simulated_being * female, simulated_being * male, simulated_group * group) { if ((male == 0L) || (female == 0L)) { return; } body_genetics(group->beings, group->num, being_fetal_genetics(female), being_genetics(female), being_genetics(male), female->delta.seed); /** store the date of conception */ female->changes.date_of_conception = land_date(); female->changes.father_name[0] = male->constant.name[0]; female->changes.father_name[1] = male->constant.name[1]; if (male->constant.generation_min < female->constant.generation_min) { female->changes.child_generation_min = male->constant.generation_min; } else { female->changes.child_generation_min = female->constant.generation_min; } if (male->constant.generation_max > female->constant.generation_max) { female->changes.child_generation_max = male->constant.generation_max; } else { female->changes.child_generation_max = female->constant.generation_max; } /** reset sex drive and goal */ being_reset_drive(female, DRIVE_SEX); being_reset_drive(male, DRIVE_SEX); being_set_goal_none(female); being_set_goal_none(male); /** remember the event */ episodic_interaction(female, male, EVENT_MATE, (GENE_MATE_BOND(being_genetics(female))*AFFECT_MATE), 0); episodic_interaction(male, female, EVENT_MATE, (GENE_MATE_BOND(being_genetics(male))*AFFECT_MATE), 0); } /** * @brief Mating behavior * @param meeter_being Pointer to the ape doing the meeting * @param met_being Pointer to the ape whi is being met * @param being_index Array index for the met individual within the social graph of the meeter * @param distance The Distance between the two apes * @param group Pointer to simulated_group * @return The being state: reproducing or not */ n_int social_mate( simulated_being * meeter_being, simulated_being * met_being, n_int being_index, n_uint distance, simulated_group * group) { n_int loc_state = 0; n_int attraction = 0; n_int attract; /* n_byte2 matingprob;*/ simulated_isocial * meeter_social_graph = being_social(meeter_being); if (!meeter_social_graph) return -1; /*if ((being_drive(meeter_being, DRIVE_SEX) > THRESHOLD_SEEK_MATE) && (being_drive(met_being, DRIVE_SEX) > THRESHOLD_SEEK_MATE))*/ { /** mating is probabilistic, with a bias towards higher status individuals */ /* matingprob = being_random(meeter_being); if (matingprob < (32000 + (n_byte2)(met_being->honor)* GENE_STATUS_PREFERENCE(being_genetics(meeter_being))*MATING_PROB)) */ { /** attractiveness based upon various criteria */ attraction = 1 + social_attraction_pheromone(meeter_being,met_being) + social_attraction_pigmentation(meeter_being,met_being) + social_attraction_height(meeter_being,met_being) + social_attraction_frame(meeter_being,met_being) + social_attraction_hair(meeter_being,met_being) #ifdef EPISODIC_ON + episodic_met_being_celebrity(meeter_being, met_being) #endif ; /** some minimum level of attraction required for pair bonding */ /*if (meeter_social_graph[being_index].attraction > PAIR_BOND_THRESHOLD) { attraction++; */ if (distance < MATING_RANGE) { /** transmit pathogens */ being_immune_transmit(meeter_being, met_being, PATHOGEN_TRANSMISSION_SEX); being_immune_transmit(met_being, meeter_being, PATHOGEN_TRANSMISSION_SEX); /** check opposite sexes */ if ((FIND_SEX(GET_I(meeter_being)) == SEX_FEMALE) && (FIND_SEX(GET_I(met_being)) != SEX_FEMALE)) { if (being_pregnant(meeter_being) == 0) { social_conception(meeter_being, met_being, group); } } } /* } else { attraction--; }*/ } attract = meeter_social_graph[being_index].attraction; if (attraction > 0) { if (attraction < PAIR_BOND_THRESHOLD*4) { if (attract < 255-attraction) attract+=attraction; } } else { if (attract > -attraction) { attract += attraction; } else { attract=0; } } meeter_social_graph[being_index].attraction=(n_byte)attract; /**< '=' : conversion from 'n_int' to 'n_byte', possible loss of data */ } return loc_state; } /** * @brief When two beings meet agree on the name for the current territory * @param meeter_being Pointer to the being doing the meeting * @param met_being Pointer to the being whi is being met * @param being_index Array index for the met individual within the social graph of the meeter * @param meeter_graph Pointer to the social graph of the meeter * @param respect_mean Average friend of foe value within the social graph */ static void social_chat_territory( simulated_being * meeter_being, simulated_being * met_being, n_int being_index, simulated_isocial * meeter_graph, n_uint respect_mean) { #ifdef TERRITORY_ON n_int idx=0,idx2,i=0,x,y; idx = APESPACE_TO_TERRITORY(being_location_y(meeter_being))*TERRITORY_DIMENSION + APESPACE_TO_TERRITORY(being_location_x(meeter_being)); if (meeter_being->events.territory[idx].name==0) { i=0; for (y=-1; y<=1; y++) { for (x=-1; x<=1; x++) { if (!((x==0)&&(y==0))) { idx2 = idx + (y*TERRITORY_DIMENSION+x); if (idx2<0) idx2+=TERRITORY_AREA; if (idx2>=TERRITORY_AREA) idx2-=TERRITORY_AREA; i = meeter_being->events.territory[idx2].name; if (i>0) { y = 2; break; } } } } /** give the current place a name at random */ if (i == 0) { i = 1 + (n_byte)(being_random(meeter_being) & 255); } meeter_being->events.territory[idx].name = (n_byte)i; } /** take advice from more honorable friends */ if (meeter_graph[being_index].friend_foe >= respect_mean) { if (being_honor_compare(met_being, meeter_being) == 1) { if (met_being->events.territory[idx].name > 0) { meeter_being->events.territory[idx].name = met_being->events.territory[idx].name; } } else { if ((being_honor_compare(met_being, meeter_being) == -1) && (meeter_being->events.territory[idx].name > 0)) { met_being->events.territory[idx].name = meeter_being->events.territory[idx].name; } } } #endif } /** * @brief Dialogue between beings * @param meeter_being Pointer to the being doing the meeting * @param met_being Pointer to the being which is being met * @param being_index Array index for the met individual within the social graph of the meeter * @param group Pointer to the simulated_group * @return A non-zero value if speaking */ n_int social_chat( simulated_being * meeter_being, simulated_being * met_being, n_int being_index, simulated_group * group) { n_int idx,i=0; n_byte relationship_index; n_byte2 name, family; n_int replace; n_int speaking = 0; simulated_isocial * meeter_graph = being_social(meeter_being); simulated_isocial * met_graph = being_social(met_being); n_uint respect_mean = social_respect_mean(meeter_being); if (!meeter_graph) { return 0; } if (!met_graph) { return 0; } /** agree upon terrirory */ social_chat_territory(meeter_being, met_being,being_index,meeter_graph,respect_mean); /** do I respect their views ? */ if ((meeter_graph[being_index].friend_foe) >= respect_mean) { episodic_interaction(meeter_being, met_being, EVENT_CHAT, AFFECT_CHAT, 0); /** pick one of the individuals from their graph */ idx=-1; if (being_check_goal(meeter_being, GOAL_MATE)) { /** ask about an individual we're searching for */ for (i=1; i<SOCIAL_SIZE_BEINGS; i++) { if (!SOCIAL_GRAPH_ENTRY_EMPTY(met_graph,i)) { if ((met_graph[i].first_name[BEING_MET]==meeter_being->delta.goal[1]) && (met_graph[i].family_name[BEING_MET]==meeter_being->delta.goal[2])) { idx=i; break; } } } } if (idx == -1) { /** what type of family relationship is currently being attended to */ relationship_index = being_attention(meeter_being,ATTENTION_RELATIONSHIP); if (relationship_index>0) { idx = social_get_relationship(meeter_being, relationship_index); } else { /** choose randomly */ idx = 1+(being_random(meeter_being)%(SOCIAL_SIZE_BEINGS-1)); } } if (idx > -1) { /** have I already met this individual? */ name = met_graph[idx].first_name[BEING_MET]; family = met_graph[idx].family_name[BEING_MET]; if (!((name==0) && (family==0))) { for (i=1; i<SOCIAL_SIZE_BEINGS; i++) { if (!SOCIAL_GRAPH_ENTRY_EMPTY(meeter_graph,i)) { if ((meeter_graph[i].first_name[BEING_MET]==name) && (meeter_graph[i].family_name[BEING_MET]==family)) { break; } } } if (i<SOCIAL_SIZE_BEINGS) { /** was already met */ if (being_honor_compare(met_being, meeter_being) == 1) { meeter_graph[i].friend_foe++; } if (being_honor_compare(met_being, meeter_being) == -1) { meeter_graph[i].friend_foe--; } if (meeter_graph[i].familiarity < 65535) meeter_graph[i].familiarity++; /** update this being's belief */ if (spacetime_after(&met_graph[idx].space_time, &meeter_graph[i].space_time)) { /** belief about location */ spacetime_copy(&meeter_graph[i].space_time, &met_graph[idx].space_time); /** belief about state */ meeter_graph[i].belief = met_graph[idx].belief; } speaking |= BEING_STATE_SPEAKING; } else { /** if we have never met then add to my graph as someone I've "heard of". This is like a prior expectation or second hand information. The least familiar relationship is replaced */ replace = get_stranger_link(meeter_being, met_being); if (replace > -1) { memory_copy((n_byte *)&met_graph[idx], (n_byte *)&meeter_graph[replace], sizeof(simulated_isocial)); meeter_graph[replace].attraction = 0; speaking |= BEING_STATE_SPEAKING; /** if this is a family member of the previously unknown being then make sure that the family member type is set to OTHER - i.e. not my family someone else's */ if (IS_FAMILY_MEMBER(met_graph,idx)) { meeter_graph[replace].relationship = meeter_graph[replace].relationship+(OTHER_MOTHER-RELATIONSHIP_MOTHER); } #ifdef BRAINCODE_ON /** initialise the braincode */ being_init_braincode(meeter_being, met_being, met_graph[idx].friend_foe, BRAINCODE_EXTERNAL); #endif } } } } } being_reset_drive(met_being, DRIVE_SOCIAL); being_reset_drive(meeter_being, DRIVE_SOCIAL); #ifdef BRAINCODE_ON brain_dialogue( group,1,meeter_being,met_being, being_braincode_external(meeter_being), being_braincode_external(met_being), being_index); #endif #ifdef EPISODIC_ON social_group_align_preferences( group,meeter_being,met_being,being_index); #endif if (speaking != 0) { being_add_state(meeter_being, BEING_STATE_SPEAKING); being_add_state(met_being, BEING_STATE_SPEAKING); } return speaking; } /** * @brief Goal oriented behavior * @param local Pointer to the ape */ void social_goals(simulated_being * local) { if (being_check_goal(local, GOAL_LOCATION)) { /** move towards a location */ n_int delta_x=0, delta_y=0, distsqr; n_vect2 delta_vector,location_vector; if ((being_state(local) & BEING_STATE_SWIMMING) == 0) { vect2_byte2(&delta_vector, (n_byte2 *)&(local->delta.goal[1])); being_space(local, &location_vector); vect2_subtract(&delta_vector, &location_vector, &delta_vector); being_facing_towards(local, &delta_vector); } distsqr = delta_x*delta_x + delta_y*delta_y; if ((distsqr < GOAL_RADIUS) || ((being_state(local) & BEING_STATE_SWIMMING) != 0)) { /** destination reached - goal cancelled */ being_set_goal_none(local); /** clear any script override */ local->braindata.script_overrides -= OVERRIDE_GOAL; } } being_goal_cycle(local); } void social_initial_loop(simulated_group * group, simulated_being * local_being, void * data) { n_uint respect_mean = social_respect_mean(local_being); n_uint social_loop = 0; n_vect2 location, sum_delta = {0,0}; n_int familiar_being_count = 0; vect2_byte2(&location,(n_byte2 *)&(local_being->delta.social_coord_x)); while ( social_loop < SOCIAL_SIZE_BEINGS ) { simulated_isocial * specific_individual = &(being_social(local_being)[social_loop]); simulated_being * specific_being; if (!specific_individual) return; if (!SOCIAL_GRAPH_ENTRY_EMPTY(being_social(local_being),social_loop)) { specific_being = being_find_name(group, specific_individual->first_name[BEING_MET], specific_individual->family_name[BEING_MET]); if (specific_being != 0L) { n_vect2 weighted_delta; n_vect2 familiar_location; n_int local_friend_or_foe = specific_individual->friend_foe; n_int distance_squared; local_friend_or_foe -= respect_mean; familiar_being_count++; vect2_byte2(&familiar_location,(n_byte2 *)&(specific_being->delta.social_coord_x)); vect2_subtract(&weighted_delta, &familiar_location, &location); distance_squared = vect2_dot(&weighted_delta, &weighted_delta, 1, 512); if (distance_squared<0) distance_squared=0; /**< Bug fix for division by zero on the following line */ vect2_d(&sum_delta,&weighted_delta, local_friend_or_foe * 2048, (distance_squared + 1)); } } social_loop++; } if (familiar_being_count != 0) { vect2_d(&location,&sum_delta,1,(familiar_being_count*20)); } vect2_back_byte2(&location,(n_byte2 *)&(local_being->delta.social_coord_nx)); } void social_secondary_loop_no_sim(simulated_being * local_being, void * data) { local_being->delta.social_coord_x = local_being->delta.social_coord_nx; local_being->delta.social_coord_y = local_being->delta.social_coord_ny; } <|start_filename|>universe/universe.h<|end_filename|> /**************************************************************** universe.h ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #ifndef SIMULATEDAPE_UNIVERSE_H #define SIMULATEDAPE_UNIVERSE_H #define EPISODIC_ON #define TERRITORY_ON /* entity */ #define BRAINCODE_ON /* entity */ #define IMMUNE_ON /* entity */ #ifdef APESIM_IOS #undef BRAIN_ON #else #define BRAIN_ON #endif #define FEATURE_SET #undef DEBUG_LACK_OF_MOVEMENT #define SINGLE_BRAIN (32768) #define DOUBLE_BRAIN (SINGLE_BRAIN*2) #define CHARACTER_WIDTH (8) #define CHARACTER_HEIGHT (14) /* This table represents the operator calculation that is used to create the density graphs. The first section of the table shows if a component is added "+", subtracted "-", not used "." or boolean true "X". This is translated to numbers in the second part of the table. This is condensed into the operator number and at the far right what these operator sums represent. */ static const n_byte operators[17][7] = { /*AHWOUS*/ "+.....", /* Area */ ".+....", /* Height */ "..+...", /* Water */ "...+..", /* Moving Sun */ "....+.", /* Total Sun */ ".....+", /* Salt */ /*AHWOUS*/ ".-+.+-", /* Bush */ "..+.+-", /* Grass */ "-++.+-", /* Tree */ "-++.-+", /* Seaweed */ "+.-.-+", /* Rockpool */ "+-+-++", /* Beach */ /*AHWOUS*/ "..+-.-", /* Insect */ "..--.-", /* Mouse */ "..+++-", /* Parrot */ "-+.-.-", /* Lizard */ "..+-+-" /* Eagle */ /*AHWOUS*/ }; #define AGE_IN_DAYS(bei) (land_date() - being_dob(bei)) #define AGE_IN_YEARS(bei) (AGE_IN_DAYS(bei)/TIME_YEAR_DAYS) /* in days, a little young, yes */ #define AGE_OF_MATURITY (30) /*4*/ enum SECONDARY_APESCRIPT { VARIABLE_VECT_X = (VARIABLE_IF + 1), VARIABLE_VECT_Y, VARIABLE_RANDOM, VARIABLE_WATER_LEVEL, VARIABLE_BIOLOGY_AREA, VARIABLE_BIOLOGY_HEIGHT, VARIABLE_BIOLOGY_WATER, VARIABLE_BIOLOGY_MOVING_SUN, VARIABLE_BIOLOGY_TOTAL_SUN, VARIABLE_BIOLOGY_SALT, VARIABLE_BIOLOGY_BUSH, VARIABLE_BIOLOGY_GRASS, VARIABLE_BIOLOGY_TREE, VARIABLE_BIOLOGY_SEAWEED, VARIABLE_BIOLOGY_ROCKPOOL, VARIABLE_BIOLOGY_BEACH, VARIABLE_BIOLOGY_INSECT, VARIABLE_BIOLOGY_MOUSE, VARIABLE_BIOLOGY_PARROT, VARIABLE_BIOLOGY_LIZARD, VARIABLE_BIOLOGY_EAGLE, VARIABLE_BIOLOGY_OUTPUT, VARIABLE_HUNGRY, VARIABLE_ENERGY, VARIABLE_LOCATION_Z, VARIABLE_TEST_Z, VARIABLE_IS_VISIBLE, VARIABLE_TIME, VARIABLE_DATE, VARIABLE_CURRENT_BEING, VARIABLE_NUMBER_BEINGS, VARIABLE_LOCATION_X, VARIABLE_LOCATION_Y, VARIABLE_STATE, VARIABLE_ID_NUMBER, VARIABLE_DATE_OF_BIRTH, VARIABLE_IS_ERROR, VARIABLE_WEATHER, /* Everything after this value can be both set and get */ VARIABLE_BRAIN_VALUE, /* This is a special case, all the remainder are stored as variables */ VARIABLE_VECT_ANGLE, VARIABLE_FACING, VARIABLE_SPEED, VARIABLE_ENERGY_DELTA, VARIABLE_HONOR, VARIABLE_PARASITES, VARIABLE_HEIGHT, VARIABLE_FIRST_NAME, VARIABLE_FAMILY_NAME_ONE, VARIABLE_FAMILY_NAME_TWO, VARIABLE_GOAL_TYPE, VARIABLE_GOAL_X, VARIABLE_GOAL_Y, VARIABLE_DRIVE_HUNGER, VARIABLE_DRIVE_SOCIAL, VARIABLE_DRIVE_FATIGUE, VARIABLE_DRIVE_SEX, VARIABLE_BRAIN_X, VARIABLE_BRAIN_Y, VARIABLE_BRAIN_Z, VARIABLE_SELECT_BEING, VARIABLE_TEST_X, VARIABLE_TEST_Y, VARIABLE_BIOLOGY_OPERATOR, VARIABLE_POSTURE, VARIABLE_PREFERENCE_MATE_HEIGHT_MALE, VARIABLE_PREFERENCE_MATE_HEIGHT_FEMALE, VARIABLE_PREFERENCE_MATE_PIGMENTATION_MALE, VARIABLE_PREFERENCE_MATE_PIGMENTATION_FEMALE, VARIABLE_PREFERENCE_MATE_HAIR_MALE, VARIABLE_PREFERENCE_MATE_HAIR_FEMALE, VARIABLE_PREFERENCE_MATE_FRAME_MALE, VARIABLE_PREFERENCE_MATE_FRAME_FEMALE, VARIABLE_PREFERENCE_GROOM_MALE, VARIABLE_PREFERENCE_GROOM_FEMALE, VARIABLE_PREFERENCE_ANECDOTE_EVENT_MUTATION, VARIABLE_PREFERENCE_ANECDOTE_AFFECT_MUTATION, VARIABLE_PREFERENCE_CHAT, VARIABLE_ATTENTION_ACTOR_INDEX, VARIABLE_ATTENTION_EPISODE_INDEX, VARIABLE_ATTENTION_BODY_INDEX, VARIABLE_SHOUT_CONTENT, VARIABLE_SHOUT_HEARD, VARIABLE_SHOUT_CTR, VARIABLE_SHOUT_VOLUME, VARIABLE_SHOUT_FAMILY0, VARIABLE_SHOUT_FAMILY1, VARIABLE_SOCIAL_GRAPH_LOCATION_X, VARIABLE_SOCIAL_GRAPH_LOCATION_Y, VARIABLE_SOCIAL_GRAPH_TIME, VARIABLE_SOCIAL_GRAPH_DATE, VARIABLE_SOCIAL_GRAPH_ATTRACTION, VARIABLE_SOCIAL_GRAPH_FOF, VARIABLE_SOCIAL_GRAPH_FAMILIARITY, VARIABLE_MEMORY_FIRST_NAME, VARIABLE_MEMORY_FAMILY_NAME_ONE, VARIABLE_MEMORY_FAMILY_NAME_TWO, VARIABLE_MEMORY_LOCATION_X, VARIABLE_MEMORY_LOCATION_Y, VARIABLE_MEMORY_TIME, VARIABLE_MEMORY_DATE, VARIABLE_MEMORY_FIRST_NAME0, VARIABLE_MEMORY_FAMILY_NAME_ONE0, VARIABLE_MEMORY_FAMILY_NAME_TWO0, VARIABLE_MEMORY_FIRST_NAME1, VARIABLE_MEMORY_FAMILY_NAME_ONE1, VARIABLE_MEMORY_FAMILY_NAME_TWO1, VARIABLE_MEMORY_EVENT, VARIABLE_MEMORY_AFFECT, VARIABLE_BEING /* This is a special case, it is the location where the main code starts */ }; enum BODY_INVENTORY_TYPES { BODY_HEAD = 0, BODY_TEETH, BODY_BACK, BODY_FRONT, BODY_LEFT_HAND, BODY_RIGHT_HAND, BODY_LEFT_FOOT, BODY_RIGHT_FOOT, INVENTORY_SIZE }; enum { RELATIONSHIP_SELF = 1, RELATIONSHIP_MOTHER, RELATIONSHIP_FATHER, RELATIONSHIP_DAUGHTER, RELATIONSHIP_SON, RELATIONSHIP_GRANDDAUGHTER, RELATIONSHIP_GRANDSON, RELATIONSHIP_SISTER, RELATIONSHIP_BROTHER, RELATIONSHIP_MATERNAL_GRANDMOTHER, RELATIONSHIP_MATERNAL_GRANDFATHER, RELATIONSHIP_PATERNAL_GRANDMOTHER, RELATIONSHIP_PATERNAL_GRANDFATHER, OTHER_MOTHER, OTHER_FATHER, OTHER_DAUGHTER, OTHER_SON, OTHER_GRANDDAUGHTER, OTHER_GRANDSON, OTHER_SISTER, OTHER_BROTHER, OTHER_MATERNAL_GRANDMOTHER, OTHER_MATERNAL_GRANDFATHER, OTHER_PATERNAL_GRANDMOTHER, OTHER_PATERNAL_GRANDFATHER, RELATIONSHIPS }; enum PREFERENCES_MATE { PREFERENCE_MATE_HEIGHT_MALE = 0, PREFERENCE_MATE_HEIGHT_FEMALE, PREFERENCE_MATE_PIGMENTATION_MALE, PREFERENCE_MATE_PIGMENTATION_FEMALE, PREFERENCE_MATE_HAIR_MALE, PREFERENCE_MATE_HAIR_FEMALE, PREFERENCE_MATE_FRAME_MALE, PREFERENCE_MATE_FRAME_FEMALE, PREFERENCE_GROOM_MALE, PREFERENCE_GROOM_FEMALE, PREFERENCE_ANECDOTE_EVENT_MUTATION, PREFERENCE_ANECDOTE_AFFECT_MUTATION, PREFERENCE_CHAT, PREFERENCE_SOCIAL, PREFERENCES }; enum attention_type { ATTENTION_EXTERNAL = 0, ATTENTION_ACTOR, ATTENTION_EPISODE, ATTENTION_BODY, ATTENTION_RELATIONSHIP, ATTENTION_TERRITORY, ATTENTION_SIZE }; enum { INTERVAL_MINS = 0, INTERVAL_HOURS, INTERVAL_DAYS, INTERVAL_MONTHS, INTERVAL_YEARS, INTERVALS }; static const n_int interval_steps[] = { 1, TIME_HOUR_MINUTES, TIME_DAY_MINUTES, TIME_MONTH_MINUTES, TIME_YEAR_MINUTES}; static const n_constant_string interval_description[] = { " mins"," hours"," days"," months"," years" }; #define FISHING_PROB (1<<8) /* converts a distance in metres to a squared range value */ #define METRES_TO_APESPACE(m) (m*m*80000) /* shouting */ #define SHOUT_RANGE METRES_TO_APESPACE(50) #define SHOUT_REFRACTORY 10 enum shout_elements { SHOUT_CONTENT = 0, SHOUT_HEARD, SHOUT_CTR, SHOUT_VOLUME, SHOUT_FAMILY0, SHOUT_FAMILY1, SHOUT_BYTES }; /* threshold for the sex drive, beyond which the being seeks a preferred mate */ #define THRESHOLD_SEEK_MATE 100 /* During gestation sex drive will be decreased by this amount per cycle */ #define GESTATION_SEX_DRIVE_DECREMENT 16 /* Speed beyond which fatigue drive begins to increase */ #define FATIGUE_SPEED_THRESHOLD 8 /* determines how often anecdotes will be mutated */ #define ANECDOTE_EVENT_MUTATION_RATE 5000 #define ANECDOTE_AFFECT_MUTATION_RATE 5000 /* used in the social graph */ enum being_interaction_social { BEING_MEETER = 0, /* the first person, I/me */ BEING_MET /* the second person, You */ }; /* number of days after which social graph entries may be forgotten */ #define SOCIAL_FORGET_DAYS 10 /* Distance within which social communication can take place. Note that this is a squared value */ #define SOCIAL_RANGE METRES_TO_APESPACE(10) /* range for squabbling */ #define SQUABBLE_RANGE METRES_TO_APESPACE(5) /* Distance within which mating can take place */ #define MATING_RANGE METRES_TO_APESPACE(5) /* Tollerance within which social drive continues to increase */ #define SOCIAL_TOLLERANCE 1 /* Minimum expected neighbours within the social range */ #define MIN_CROWDING 1 /* Maximum expected neighbours within the social range. Beyond this behavioral sink occurs. */ #define MAX_CROWDING 3 /* maximum mass of the being in 10g increments */ #define BEING_MAX_MASS_G 7000 /* maximum body fat in 10g increments */ #define BEING_MAX_MASS_FAT_G (BEING_MAX_MASS_G>>2) #ifndef MIN #define MIN(a,b) (((a) < (b)) ? (a) : (b)) #endif /* calculate the mass of fat in 10g increments */ #define FAT_MASS(frame,energy) (MIN( ((BEING_MAX_MASS_FAT_G*energy*frame)>>(4+12)),BEING_MAX_MASS_FAT_G)) /* returns the amount of body fat in 10g increments */ #define GET_BODY_FAT(bei) (FAT_MASS(GENE_FRAME(being_genetics(bei)),being_energy(bei))) /* maximum height of the being (in millimetres) */ #define BEING_MAX_HEIGHT_MM 2000 /* maximum height of the being (in arbitrary units) */ #define BEING_MAX_HEIGHT 65535 /* returns height in real units (mm) */ #define GET_BEING_HEIGHT(bei) (being_height(bei)*BEING_MAX_HEIGHT_MM/BEING_MAX_HEIGHT) /* the amount of growth for a given energy intake Note that if AGE_OF_MATURITY is changed then this may also need to be changed to have a similar adult growth */ #define ENERGY_TO_GROWTH(b,e) ((e>>3)*3) /* physical characteristics at birth */ #define BIRTH_HEIGHT 2000 #define BIRTH_MASS 100 /* is the given index within a social graph empty? */ #define SOCIAL_GRAPH_ENTRY_EMPTY(graph,index) ((graph[index].first_name[BEING_MET]==0) && (graph[index].family_name[BEING_MET]==0) && (graph[index].relationship<=RELATIONSHIP_SELF)) /* is there a known location for the given social graph entry? */ #define SOCIAL_GRAPH_ENTRY_LOCATION_EXISTS(graph,index) (graph[index].location[0] + graph[index].location[1] > 0) /* is the given social graph entry a family member? */ #define IS_FAMILY_MEMBER(graph,index) ((graph[index].relationship > RELATIONSHIP_SELF) && (graph[index].relationship < OTHER_MOTHER)) #define EVENT_INTENTION (128) /* this possible could be genetic */ #define THROW_ACCURACY (1<<15) #define WHACK_ACCURACY (1<<15) #define PAIR_BOND_THRESHOLD 2 /* minimum level of attraction for mating */ #ifdef FEATURE_SET #define MAX_FEATURESET_SIZE 16 /* max size of a set of features associated with a social graph entry */ /* The maximum hit counter value for each feature within a set */ #define MAX_FEATURE_FREQUENCY 2048 /* the maximum number of matches of a stereotype */ #define MAX_FEATURESET_OBSERVATIONS 2048 #endif #define SOCIAL_SIZE 12 /* maximum size of the social network */ #define SOCIAL_SIZE_BEINGS (SOCIAL_SIZE>>1) /* max number of specific beings within the social graph */ #define EPISODIC_SIZE 12 /* maximum number of episodic memories */ /* ApeScript overrides */ #define OVERRIDE_GOAL 1 /* number of time steps after which a goal is abandoned */ #define GOAL_TIMEOUT (60*24) /* how close do we need to get to a goal to say that it has been reached? */ #define GOAL_RADIUS 40000 #define DRIVES_MAX 255 /* maximum value of each drive */ enum drives_definition { DRIVE_HUNGER = 0, DRIVE_SOCIAL, DRIVE_FATIGUE, DRIVE_SEX, DRIVES /* number of biological drives */ }; /** used with social_meet function to specify whether the location should be included within the social graph entry */ enum being_meet_location_type { LOCATION_KNOWN = 0, LOCATION_UNKNOWN }; /* Types of entities which it's possible to have a disposition towards */ enum { ENTITY_BEING=0, ENTITY_BEING_GROUP, ENTITY_OBJECT, ENTITY_TERRITORY }; typedef struct { n_byte2 value; n_byte2 frequency; n_byte type; } simulated_feature; #ifdef FEATURE_SET typedef struct { n_byte2 feature_number; simulated_feature features[MAX_FEATURESET_SIZE]; n_byte2 observations; } simulated_featureset; #endif /*! @struct @discussion This describes a disposition towards other beings or things (an edge in the social graph) @field entity_type The type of entity encountered @field location Location where the entity was last seen @field time The time when the social graph entry was last updated @field date The date when the social graph entry was last updated @field first_name The first name of the entity @field family_name The family names of the entity @field attraction Attraction/desirability value used for mating @field friend_foe Whether friendly or hostile towards this entity @field belief Current belief about the state of this entity @field familiarity How many times has this entity been encountered @field relationship The type of relationship with the entity @field classification set of features which belong to this entity @field braincode the language machinery associated with this entity */ typedef struct { n_spacetime space_time; n_byte2 first_name[2]; n_byte2 family_name[2]; n_byte attraction; n_byte friend_foe; n_byte2 belief; n_byte2 familiarity; n_byte relationship; n_byte entity_type; #ifdef FEATURE_SET simulated_featureset classification; #endif #ifdef BRAINCODE_ON n_byte braincode[BRAINCODE_SIZE]; #endif } simulated_isocial; /*! @struct @discussion Describes an episodic memory event @field event Type of event @field affect Affect value associated with the event @field location Location of the event @field time Time when the event occurred @field date0 First component of the date when the event occurred @field date1 Second component of the date when the event occurred @field first_name First name of a being associated with the event @field food Food item associated with the event @field family_name Family name of a being associated with the event @field arg Additional argument */ typedef struct { n_spacetime space_time; n_byte2 first_name[2]; n_byte2 family_name[2]; n_byte event; n_byte food; n_byte2 affect; n_byte2 arg; } simulated_iepisodic; /*! @struct @field name A number representing the place name @field familiarity Number of times that this place has been visited @discussion This is the equivalent of a place cell, containing parameters for a particular place on the map */ typedef struct { n_byte name; n_byte2 familiarity; } simulated_iplace; #ifdef BRAINCODE_ON /*! @struct @field type type of probe (0=read, 1=write) @field position position of the probe within the brain @field address address within the braincode @field frequency frequency of the pulse in time steps (minutes) @field offset resting value @field frequency current state of the probe @discussion A probe which can be attached to the brain to inject or detect signals. */ typedef struct { n_byte type; n_byte position; n_byte address; n_byte frequency; n_byte offset; n_byte state; } simulated_ibrain_probe; #endif typedef n_byte4 n_genetics; #define CHROMOSOMES 4 #define CHROMOSOME_Y 0 #define IMMUNE_ANTIGENS 8 #define IMMUNE_POPULATION 16 enum { WATCH_NONE = 0, WATCH_ALL = 1, WATCH_SOCIAL_GRAPH, WATCH_EPISODIC, WATCH_BRAINCODE, WATCH_BRAINPROBES, WATCH_APPEARANCE, WATCH_SPEECH, WATCH_STATES }; /* ------- ------- ------- SIMULATED APE GENETICS MATRIX (BETA) ------- ------- ------- */ #define GET_NUCLEOTIDE(gene,num) ((gene[((num)>>3) & 3]>>((num&7)*2))&3) /* returns a value for the gene in the range 0-15 */ #define GENE_VAL(gene, num0, num1) ((GET_NUCLEOTIDE(gene,num0) << 2) | GET_NUCLEOTIDE(gene,num1)) /* Genes which regulate the transcription network */ #define GENE_REGULATOR(gene,a,b) (1+GENE_VAL(gene,(15+(a)),(15+(b)))) #define GENE_VAL_REG(gene,a,b,c,d) GENE_VAL(gene,GENE_REGULATOR(gene,a,b),GENE_REGULATOR(gene,c,d)) /* this may become redundant since body frame will be determined by other genes */ #define GENE_FRAME(gene) GENE_VAL_REG(gene, 10, 11, 1, 6) /* hair length */ #define GENE_HAIR(gene) GENE_VAL_REG(gene, 12, 5, 12, 11) /* Nose shape */ #define GENE_NOSE_SHAPE(gene) GENE_VAL_REG(gene, 4, 5, 6, 8) /* Mouth shape */ #define GENE_MOUTH_SHAPE(gene) GENE_VAL_REG(gene, 9, 5, 8, 15) /* Pigmentation */ #define GENE_PIGMENTATION(gene) GENE_VAL_REG(gene, 8, 9, 8, 3) /* Ear shape */ #define GENE_EAR_SHAPE(gene) GENE_VAL_REG(gene, 12, 4, 14, 1) /* Eyebrow shape */ #define GENE_EYEBROW_SHAPE(gene) GENE_VAL_REG(gene, 9, 10, 8, 4) /* Eye shape */ #define GENE_EYE_SHAPE(gene) GENE_VAL_REG(gene, 9, 12, 1, 5) /* Eye color */ #define GENE_EYE_COLOR(gene) GENE_VAL_REG(gene, 9, 7, 3, 7) /* Eye separation */ #define GENE_EYE_SEPARATION(gene) GENE_VAL_REG(gene, 3, 2, 0, 14) /* Rate of growth */ /*#define GENE_RATE_OF_GROWTH(gene) GENE_VAL_REG(gene, 11, 5, 13, 11) not used */ /* Returns a value for a gene corresponding to a body segment The number of body segments defined by the constant BONES is assumed to be < 18 */ #define GENE_HOX(gene,bodyseg) GENE_VAL_REG(gene, 2+(bodyseg), 4+(bodyseg), 18-(bodyseg), 21-(bodyseg)) /* Vision */ #define GENE_VISION_INITIAL(gene) GENE_VAL_REG(gene, 2, 12, 3, 9) #define GENE_VISION_DELTA(gene) GENE_VAL_REG(gene, 11, 7, 2, 9) /* Ear shape */ #define GENE_EAR_SHAPE(gene) GENE_VAL_REG(gene, 12, 4, 14, 1) /* Eyebrow shape */ #define GENE_EYEBROW_SHAPE(gene) GENE_VAL_REG(gene, 9, 10, 8, 4) #ifdef IMMUNE_ON /*! @struct @field antigens The number of antigens for each shape @field shape_antigen The shape of the antigen @field antbodies The number of antibodies for each shape @field shape_antibody The shape of the antibody @field strength immune system strength @discussion Immune system parameters */ typedef struct { n_byte antigens[IMMUNE_ANTIGENS]; n_byte shape_antigen[IMMUNE_ANTIGENS]; n_byte antibodies[IMMUNE_POPULATION]; n_byte shape_antibody[IMMUNE_POPULATION]; } simulated_immune_system; #endif typedef struct { n_byte2 location[2]; } simulated_idead_body; #define NUMBER_OF_BODIES (10) typedef struct { simulated_idead_body bodies[NUMBER_OF_BODIES]; n_byte2 count; n_byte2 location; } simulated_remains; typedef struct { n_byte4 date_of_birth; n_byte2 generation_min; n_byte2 generation_max; n_byte2 name[2]; n_genetics genetics[CHROMOSOMES]; /* constant */ } simulated_being_constant; #define IMMUNE_FIT 5 #define MIN_ANTIBODIES 16 #define MIN_ANTIGENS 8 #define IMMUNE_ANTIGENS 8 #define IMMUNE_POPULATION 16 #define PATHOGEN_TRANSMISSION_PROB 1000 #define PATHOGEN_ENVIRONMENT_PROB 100 #define PATHOGEN_MUTATION_PROB 100 #define ANTIBODY_DEPLETION_PROB 100 #define ANTIBODY_GENERATION_PROB(bei) (being_energy(bei)) enum PATHOGEN_TRANSMISSION_METHOD { PATHOGEN_TRANSMISSION_AIR = 0, PATHOGEN_TRANSMISSION_SOIL, PATHOGEN_TRANSMISSION_SEX, PATHOGEN_TRANSMISSION_TOUCH, PATHOGEN_TRANSMISSION_FOOD_VEGETABLE, PATHOGEN_TRANSMISSION_FOOD_FRUIT, PATHOGEN_TRANSMISSION_FOOD_SHELLFISH, PATHOGEN_TRANSMISSION_FOOD_SEAWEED, PATHOGEN_TRANSMISSION_TOTAL }; #define RANDOM_PATHOGEN(seed,pathogen_type) (((seed%(255/PATHOGEN_TRANSMISSION_TOTAL))*PATHOGEN_TRANSMISSION_TOTAL)+pathogen_type) #define PATHOGEN_SEVERITY(pathogen) (((pathogen)*(pathogen))>>11) #define PATHOGEN_TRANSMISSION(pathogen) ((pathogen)&7) enum { METABOLISM_STATE=0, METABOLISM_PROTEIN, METABOLISM_STARCH, METABOLISM_FAT, METABOLISM_SUGAR, METABOLISM_WATER, METABOLISM_BILE, METABOLISM_GLUCOSE, METABOLISM_MUSCLE, METABOLISM_AMINO_ACIDS, METABOLISM_GLUCOGEN, METABOLISM_ADRENALIN, METABOLISM_GLYCOGEN, METABOLISM_AMMONIA, METABOLISM_UREA, METABOLISM_LACTATE, METABOLISM_OXYGEN, METABOLISM_CO2, METABOLISM_FATTY_ACIDS, METABOLISM_TRIGLYCERIDE, METABOLISM_ADIPOSE, METABOLISM_INSULIN, METABOLISM_ADP, METABOLISM_ATP, METABOLISM_ENERGY, METABOLISM_HEAT, METABOLISM_PYRUVATE, METABOLISM_WASTE, METABOLISM_LEPTIN, METABOLISM_GHRELIN, METABOLISM_PROLACTIN, METABOLISM_MILK, METABOLISM_HEART_RATE, METABOLISM_BREATHING_RATE, METABOLISM_THERMOREGULATOR, METABOLISM_LUNG_CAPACITY, METABOLISM_SIZE }; enum { ORGAN_STOMACH=1, ORGAN_MUSCLES, ORGAN_LIVER, ORGAN_KIDNEYS, ORGAN_LUNGS, ORGAN_PANCREAS_A, ORGAN_PANCREAS_B, ORGAN_TISSUE, ORGANS }; typedef enum { FULLY_ASLEEP = 0, SLIGHTLY_AWAKE = 1, FULLY_AWAKE = 2 } sleep_state; typedef struct { n_byte2 location[2]; n_byte direction_facing; n_byte velocity; n_byte2 stored_energy; n_byte2 seed[2]; n_byte2 macro_state; n_byte parasites; n_byte honor; n_byte crowding; n_byte2 height; n_byte2 mass; n_byte posture; n_byte2 goal[4]; #ifdef DEBUG_LACK_OF_MOVEMENT n_int total_movement; #endif n_byte2 social_coord_x; n_byte2 social_coord_y; n_byte2 social_coord_nx; /* why is this needed? */ n_byte2 social_coord_ny; /* why is this needed? */ sleep_state awake; } simulated_being_delta; typedef struct { simulated_isocial social[SOCIAL_SIZE]; simulated_iepisodic episodic[EPISODIC_SIZE]; #ifdef TERRITORY_ON simulated_iplace territory[TERRITORY_DIMENSION*TERRITORY_DIMENSION]; #endif } simulated_being_events; typedef struct { n_byte drives[DRIVES]; n_byte shout[SHOUT_BYTES]; n_byte2 inventory[INVENTORY_SIZE]; n_byte learned_preference[PREFERENCES]; n_byte4 date_of_conception; n_genetics fetal_genetics[CHROMOSOMES]; /* constant */ n_byte2 father_name[2]; n_byte2 mother_name[2]; n_byte2 child_generation_min; n_byte2 child_generation_max; }simulated_being_volatile; typedef struct { #ifdef BRAINCODE_ON n_byte braincode_register[BRAINCODE_PSPACE_REGISTERS]; simulated_ibrain_probe brainprobe[BRAINCODE_PROBES]; #endif #ifdef BRAIN_ON n_byte brain[DOUBLE_BRAIN]; #endif n_byte2 brain_state[6]; n_byte2 script_overrides; n_byte attention[ATTENTION_SIZE]; } simulated_being_brain; typedef struct { simulated_being_delta delta; simulated_being_constant constant; simulated_being_events events; simulated_being_brain braindata; simulated_being_volatile changes; #ifdef IMMUNE_ON simulated_immune_system immune_system; #endif } simulated_being; typedef void (being_birth_event)(simulated_being * born, simulated_being * mother, void * sim); typedef void (being_death_event)(simulated_being * deceased, void * sim); typedef struct { simulated_remains * remains; simulated_being * beings; simulated_being * select; /* used by gui */ being_birth_event * ext_birth; being_death_event * ext_death; n_uint num; n_uint max; } simulated_group; typedef struct { n_uint real_time; n_uint last_time; n_uint delta_cycles; n_uint count_cycles; n_uint delta_frames; n_uint count_frames; } simulated_timing; /* macros defined to ease in the vectorised code */ #define GET_M(bei) ((bei)->delta.mass) #define GET_I(bei) (being_genetics(bei)[CHROMOSOME_Y]) #define FIND_SEX(array) (array&3) #define SEX_FEMALE 3 #define BRAIN_OFFSET(num) (num) typedef void (loop_fn)(simulated_group * group, simulated_being * actual, void * data); typedef void (loop_no_sim_fn)(simulated_being * actual, void * data); void loop_no_thread(simulated_group * group, simulated_being * being_not, loop_fn bf_func, void * data); void loop_being_no_sim(simulated_being * beings, n_uint number_beings, loop_no_sim_fn bf_func, void * data); void loop_being(simulated_group * group, loop_fn bf_func, n_int beings_per_thread); n_int being_location_x(simulated_being * value); n_int being_location_y(simulated_being * value); n_int being_energy(simulated_being * value); n_genetics * being_genetics(simulated_being * value); n_int being_dob(simulated_being * value); typedef void (console_generic)(void *ptr, n_string ape_name, simulated_being * local_being, n_string result); typedef void (line_braincode)(n_string pointer, n_int line); #ifdef BRAINCODE_ON void command_populate_braincode(simulated_group * group, line_braincode function); #endif n_file * death_record_file_ready(void); void death_record_file_cleanup(void); void console_capture_death(simulated_being * deceased, void * sim); void * sim_init(KIND_OF_USE kind, n_uint randomise, n_uint offscreen_size, n_uint landbuffer_size); void sim_cycle(void); void sim_update_output(void); /* This is the new way. Please continue forwards. */ n_file * tranfer_out(void); n_file * tranfer_out_json(void); n_int tranfer_in(n_file * input_file); n_int sim_interpret(n_file * input_file); void sim_close(void); simulated_timing * sim_timing(void); simulated_group * sim_group(void); n_uint sim_memory_allocated(n_int max); void sim_flood(void); void sim_healthy_carrier(void); void sim_realtime(n_uint time); void sim_set_select(simulated_being * select); n_int sim_new_run_condition(void); void sim_view_options(n_int px, n_int py); void sim_rotate(n_int integer_rotation_256); void sim_move(n_int rel_vel, n_byte kind); void sim_change_selected(n_byte forwards); n_int sim_view_regular(n_int px, n_int py); void sim_control_set(n_int px, n_int py, n_byte value, n_byte character, n_int scale); void sim_control_erase(n_int size_x, n_int size_y, n_int scale); void sim_control_regular(n_int px, n_int py, n_int scale); void sim_terrain(n_int sx); void sim_set_output(n_int value); n_int sim_get_writing_output(void); n_string sim_output_string(void); n_int sim_new(void); void transfer_debug_csv(n_file * fil, n_byte initial); n_int get_time_interval(n_string str, n_int * number, n_int * interval); void watch_ape(void * ptr, n_console_output output_function); void watch_control(void *ptr, n_string beingname, simulated_being * local_being, n_string result); n_int command_speak(void * ptr, n_string response, n_console_output output_function); n_int command_alphabet(void * ptr, n_string response, n_console_output output_function); void command_change_selected(simulated_group * group, n_byte forwards); n_int command_stop(void * ptr, n_string response, n_console_output output_function); n_int command_idea(void * ptr, n_string response, n_console_output output_function); n_int command_being(void * ptr, n_string response, n_console_output output_function); n_int command_braincode(void * ptr, n_string response, n_console_output output_function); n_int command_speech(void * ptr, n_string response, n_console_output output_function); n_int command_relationship_count(n_int friend_type); simulated_being * command_relationship_being(simulated_group * group, n_int friend_type, n_int location); n_int command_social_graph(void * ptr, n_string response, n_console_output output_function); n_int command_genome(void * ptr, n_string response, n_console_output output_function); n_int command_appearance(void * ptr, n_string response, n_console_output output_function); n_int command_stats(void * ptr, n_string response, n_console_output output_function); n_int command_episodic(void * ptr, n_string response, n_console_output output_function); n_int command_probes(void * ptr, n_string response, n_console_output output_function); n_int command_watch(void * ptr, n_string response, n_console_output output_function); n_int command_logging(void * ptr, n_string response, n_console_output output_function); n_int command_list(void * ptr, n_string response, n_console_output output_function); n_int command_memory(void * ptr, n_string response, n_console_output output_function); n_int command_next(void * ptr, n_string response, n_console_output output_function); n_int command_previous(void * ptr, n_string response, n_console_output output_function); n_int command_simulation(void * ptr, n_string response, n_console_output output_function); n_int command_step(void * ptr, n_string response, n_console_output output_function); n_int command_run(void * ptr, n_string response, n_console_output output_function); n_int command_interval(void * ptr, n_string response, n_console_output output_function); n_int command_reset(void * ptr, n_string response, n_console_output output_function); n_int command_top(void * ptr, n_string response, n_console_output output_function); n_int command_epic(void * ptr, n_string response, n_console_output output_function); n_int command_file(void * ptr, n_string response, n_console_output output_function); n_int command_event(void * ptr, n_string response, n_console_output output_function); n_int command_epic(void * ptr, n_string response, n_console_output output_function); n_int command_debug(void * ptr, n_string response, n_console_output output_function); n_int console_death(void * ptr, n_string response, n_console_output output_function); n_int command_save(void * ptr, n_string response, n_console_output output_function); n_int command_open(void * ptr, n_string response, n_console_output output_function); n_int command_script(void * ptr, n_string response, n_console_output output_function); n_int command_quit(void * ptr, n_string response, n_console_output output_function); #ifndef _WIN32 n_int sim_thread_console_quit(void); void sim_thread_console(void); #endif #ifdef CONSOLE_REQUIRED const static simulated_console_command control_commands[] = { {&io_help, "help", "[(command)]", "Displays a list of all the commands"}, #ifdef COMMAND_LINE_EXPLICIT {&command_reset, "reset", "", "Reset the simulation"}, {&command_reset, "clear" "", ""}, {&command_open, "open", "[file]", "Load a simulation file"}, {&command_open, "load", "", ""}, #endif {&command_script, "script", "[file]", "Load an ApeScript simulation file"}, {&command_save, "save", "[file]", "Save a simulation file"}, {&command_quit, "quit", "", "Quits the console"}, {&command_quit, "exit", "", ""}, {&command_quit, "close", "", ""}, {&command_stop, "stop", "", "Stop the simulation during step or run"}, {&command_speak, "speak", "[file]", "Create an AIFF file of Ape speech"}, {&command_alphabet, "alpha", "[file]", "Create an AIFF file of Ape alphabet"}, {&command_file, "file", "[(component)]", "Information on the file format"}, {&command_run, "run", "(time format)|forever","Simulate for a given number of days or forever"}, {&command_step, "step", "", "Run for a single logging interval"}, {&command_top, "top", "", "List the top apes"}, {&command_epic, "epic", "", "List the most talked about apes"}, {&command_interval, "interval", "(days)", "Set the simulation logging interval in days"}, {&command_event, "event", "on|social|off", "Episodic events (all) on, social on or all off"}, {&command_logging, "logging", "on|off", "Turn logging of images and data on or off"}, {&command_logging, "log", "", ""}, {&command_simulation, "simulation", "", ""}, {&command_simulation, "sim", "", "Show simulation parameters"}, {&command_watch, "watch", "(ape name)|all|off|*", "Watch (specific *) for the current ape"}, {&command_watch, "monitor", "", ""}, {&command_idea, "idea", "", "Track shared braincode between apes"}, {&command_being, "ape", "", "Name of the currently watched ape"}, {&command_being, "pwd", "", ""}, {&command_social_graph, "friends", "", ""}, {&command_social_graph, "social", "", ""}, {&command_social_graph, "socialgraph", "", ""}, {&command_social_graph, "graph", "(ape name)", "* Show social graph for a named ape"}, {&command_braincode, "braincode", "(ape name)", "* Show braincode for a named ape"}, {&command_speech, "speech", "(ape name)", "* Show speech for a named ape"}, {&command_episodic, "episodic", "(ape name)", "* Show episodic memory for a named ape"}, {&command_probes, "probes", "(ape name)", "* Show brain probes for a named ape"}, {&command_stats, "stats", "(ape name)", "* Show parameters for a named ape"}, {&command_stats, "status", "", ""}, {&command_appearance, "appearance", "(ape name)", "* Show appearance values for a named ape"}, {&command_appearance, "physical", "", ""}, {&command_genome, "genome", "(ape name)", "Show genome for a named ape"}, {&command_genome, "genetics", "", ""}, {&command_list, "list", "", "List all ape names"}, {&command_list, "ls", "", ""}, {&command_list, "dir", "", ""}, {&command_next, "next", "", "Next ape"}, {&command_previous, "previous", "", "Previous ape"}, {&command_previous, "prev", "", ""}, {&command_debug, "debug", "", "Run debug check"}, {&command_memory, "memory", "", "Memory information for the simulation"}, {0L, 0L}, }; #endif #endif /* SIMULATEDAPE_UNIVERSE_H */ <|start_filename|>longterm.c<|end_filename|> /**************************************************************** longterm.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #define _CRT_SECURE_NO_WARNINGS #define CONSOLE_ONLY /* Please maintain this define until after ALIFE XIII July 22nd */ #define CONSOLE_REQUIRED #undef AUDIT_FILE #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #ifdef _WIN32 #define SIMPLE_LONGTERM_CLE #endif #ifndef SIMPLE_LONGTERM_CLE #include <pthread.h> #include <unistd.h> #include <signal.h> #include <sys/time.h> #endif #include "toolkit/toolkit.h" #include "sim/sim.h" #include "script/script.h" #include "universe/universe.h" #ifdef AUDIT_FILE #include "universe/universe_internal.h" #endif n_string_block simulation_filename; #ifdef AUDIT_FILE static void audit_print_offset(n_byte * start, n_byte * point, char * text) { printf("%s %ld\n", text, (unsigned long)(point - start)); } static void audit_compart_offset() { simulated_being local; n_byte * start = (n_byte *)&local; audit_print_offset(start,(n_byte *)&(local.macro_state),"macro_state"); audit_print_offset(start,(n_byte *)&(local.crowding),"crowding"); audit_print_offset(start,(n_byte *)&(local.parasites),"parasites"); audit_print_offset(start,(n_byte *)&(local.honor),"honor"); audit_print_offset(start,(n_byte *)&(local.date_of_conception[0]),"date_of_conception[0]"); audit_print_offset(start,(n_byte *)&(local.fetal_genetics[0]),"fetal_genetics[0]"); audit_print_offset(start,(n_byte *)&(local.genetics[0]),"genetics[0]"); audit_print_offset(start,(n_byte *)&(local.father_name[0]),"father_name[0]"); audit_print_offset(start,(n_byte *)&(local.social_x),"social_x"); audit_print_offset(start,(n_byte *)&(local.drives[0]),"drives[0]"); audit_print_offset(start,(n_byte *)&(local.goal[0]),"goal[0]"); audit_print_offset(start,(n_byte *)&(local.learned_preference[0]),"learned_preference[0]"); audit_print_offset(start,(n_byte *)&(local.generation_min),"generation_min"); audit_print_offset(start,(n_byte *)&(local.territory[0]),"territory[0]"); audit_print_offset(start,(n_byte *)&(local.immune_system),"immune_system[0]"); audit_print_offset(start,(n_byte *)&(local.vessel[0]),"vessel[0]"); audit_print_offset(start,(n_byte *)&(local.metabolism[0]),"metabolism[0]"); audit_print_offset(start,(n_byte *)&(local.braincode_register[0]),"braincode_register[0]"); audit_print_offset(start,(n_byte *)&(local.brainprobe[0]),"brainprobe[0]"); audit_print_offset(start,(n_byte *)&(local.vessel[0]),"vessel[0]"); audit_print_offset(start,(n_byte *)&(local.vessel[1]),"vessel[1]"); audit_print_offset(start,(n_byte *)&(local.vessel[2]),"vessel[2]"); audit_print_offset(start,(n_byte *)&(local.vessel[3]),"vessel[3]"); audit_print_offset(start,(n_byte *)&(local.vessel[4]),"vessel[4]"); audit_print_offset(start,(n_byte *)&(local.vessel[5]),"vessel[5]"); audit_print_offset(start,(n_byte *)&(local.vessel[6]),"vessel[6]"); audit_print_offset(start,(n_byte *)&(local.vessel[7]),"vessel[7]"); audit_print_offset(start,(n_byte *)&(local.vessel[8]),"vessel[8]"); audit_print_offset(start,(n_byte *)&(local.vessel[9]),"vessel[9]"); audit_print_offset(start,(n_byte *)&(local.vessel[10]),"vessel[10]"); audit_print_offset(start,(n_byte *)&(local.vessel[11]),"vessel[11]"); audit_print_offset(start,(n_byte *)&(local.vessel[12]),"vessel[12]"); audit_print_offset(start,(n_byte *)&(local.vessel[13]),"vessel[13]"); audit_print_offset(start,(n_byte *)&(local.vessel[14]),"vessel[14]"); audit_print_offset(start,(n_byte *)&(local.vessel[15]),"vessel[15]"); audit_print_offset(start,(n_byte *)&(local.vessel[16]),"vessel[16]"); audit_print_offset(start,(n_byte *)&(local.vessel[17]),"vessel[17]"); audit_print_offset(start,(n_byte *)&(local.vessel[18]),"vessel[18]"); audit_print_offset(start,(n_byte *)&(local.vessel[19]),"vessel[19]"); audit_print_offset(start,(n_byte *)&(local.vessel[20]),"vessel[20]"); audit_print_offset(start,(n_byte *)&(local.vessel[21]),"vessel[21]"); audit_print_offset(start,(n_byte *)&(local.vessel[22]),"vessel[22]"); audit_print_offset(start,(n_byte *)&(local.vessel[23]),"vessel[23]"); audit_print_offset(start,(n_byte *)&(local.vessel[24]),"vessel[24]"); audit_print_offset(start,(n_byte *)&(local.vessel[25]),"vessel[25]"); audit_print_offset(start,(n_byte *)&(local.vessel[26]),"vessel[26]"); audit_print_offset(start,(n_byte *)&(local.vessel[27]),"vessel[27]"); audit_print_offset(start,(n_byte *)&(local.brain),"brain"); } static void audit(void) { printf("sizeof(n_byte) %d\n",(int)sizeof(n_byte)); printf("sizeof(n_byte2) %d\n",(int)sizeof(n_byte2)); printf("sizeof(n_uint) %d\n",(int)sizeof(n_uint)); printf("sizeof(n_byte *)) %d \n", (int)sizeof(n_byte *)); /* io_audit_file(simulated_file_format, FIL_VER); io_audit_file(simulated_file_format, FIL_LAN); */ io_audit_file(simulated_file_format, FIL_BEI); /* io_audit_file(simulated_file_format, FIL_SOE); io_audit_file(simulated_file_format, FIL_EPI); */ audit_compart_offset(); } #endif n_int draw_error(n_constant_string error_text, n_constant_string location, n_int line_number) { printf("ERROR: %s @ %s %ld\n",(const n_string) error_text, location, line_number); return -1; } /* moved to console.c with minor modifications */ /* load simulation data */ static n_int cle_load(void * ptr, n_string response, n_console_output output_function) { if (io_disk_check(response)!=0) { command_open(ptr, response, output_function); sprintf(simulation_filename,"%s",response); printf("Simulation file %s loaded\n",response); } return 0; } int command_line_run(void) { simulated_group * group = sim_group(); printf("\n *** %sConsole, %s ***\n", SHORT_VERSION_NAME, FULL_DATE); printf(" For a list of commands type 'help'\n\n"); sprintf(simulation_filename,"%s","realtime.txt"); #ifdef AUDIT_FILE audit(); #endif io_command_line_execution_set(); srand((unsigned int) time(NULL) ); sim_init(KIND_START_UP, rand(), MAP_AREA, 0); cle_load(group, (n_string)simulation_filename, io_console_out); #ifndef SIMPLE_LONGTERM_CLE do { sim_thread_console(); } while (sim_thread_console_quit() == 0); #else { n_int return_value = 0; do { return_value = io_console(group, (simulated_console_command *)control_commands, io_console_entry, io_console_out); } while (return_value == 0); } #endif sim_close(); return(1); } #ifndef SIMPLE_LONGTERM_CLE static int make_periodic(unsigned int period, sigset_t * alarm_sig) { int ret; struct itimerval value; /* Block SIGALRM in this thread */ sigemptyset(alarm_sig); sigaddset(alarm_sig, SIGALRM); pthread_sigmask(SIG_BLOCK, alarm_sig, NULL); /* Set the timer to go off after the first period and then repetitively */ value.it_value.tv_sec = period / 1000000; value.it_value.tv_usec = period % 1000000; value.it_interval.tv_sec = period / 1000000; value.it_interval.tv_usec = period % 1000000; ret = setitimer(ITIMER_REAL, &value, NULL); if (ret != 0) perror("Failed to set timer"); return ret; } static void wait_period(sigset_t * alarm_sig) { int sig; /* Wait for the next SIGALRM */ sigwait(alarm_sig, &sig); } #define TIMING_CONST_MS 100 static n_uint count = 0; static void *periodic_thread(void *arg) { sigset_t alarm_sig; simulated_group * group; make_periodic(1000 * TIMING_CONST_MS, &alarm_sig); while (1) { group = sim_group(); sim_cycle(); count++; if ((count & 2047) == 0) { printf("count is %ld\n", count); } if (group->num == 0) { printf("new run at %ld\n", count); sim_init(1,rand(),MAP_AREA,0); } wait_period(&alarm_sig); } return NULL; } #endif #if 0 int cycle_run(void) { pthread_t t_1; sigset_t alarm_sig; printf("\n *** %sConsole, %s ***\n", SHORT_VERSION_NAME, FULL_DATE); /* Block SIGALRM (not really necessary with uClibc) */ sigemptyset(&alarm_sig); sigaddset(&alarm_sig, SIGALRM); sigprocmask(SIG_BLOCK, &alarm_sig, NULL); srand((unsigned int) time(NULL)); sim_init(2,rand(),MAP_AREA,0); pthread_create(&t_1, NULL, periodic_thread, NULL); while (1) { sleep(100); } return 0; } #endif int main(int argc, n_string argv[]) { return command_line_run(); } <|start_filename|>sim/territory.c<|end_filename|> /**************************************************************** territory.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of Tom Barbalet, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #include "../toolkit/toolkit.h" #include "sim.h" typedef enum { NAME_UNKNOWN, NAME_ATOLL, NAME_BASIN, NAME_BAY, NAME_BEACH, NAME_CLIFF, NAME_FLATLAND, NAME_HEADLAND, NAME_HILL, NAME_LAGOON, NAME_LAKE, NAME_MOUNTAIN, NAME_PENINSULA, NAME_POND, NAME_RIDGE, NAME_RIVER, NAME_SPRING, NAME_STREAM, NAME_SUMMIT, NAME_TRENCH, NAME_VALLEY, NAME_TOTAL }territory_name; static n_string territory_description(territory_name value) { n_string territory_names[NAME_TOTAL]={ " ", "Atoll", "Basin", "Bay", "Beach", "Cliff", "Flatland", "Headland", "Hill", "Lagoon", "Lake", "Mountain", "Peninsula", "Pond", "Ridge", "River", "Spring", "Stream", "Summit", "Trench", "Valley" }; return territory_names[value]; } static void territory_description_init(n_byte * land, territory_name * set_names) { n_int tx = 0; while (tx < TERRITORY_DIMENSION) { n_int ty = 0; while (ty < TERRITORY_DIMENSION) { n_byte2 count[16]; n_int dx = 0; n_int dy = 0; n_byte highest_value = 0; n_byte loweest_value = 255; n_int center_average = 0; n_byte top_right; n_byte bottom_right; n_byte top_left; n_byte bottom_left; n_int mx = 0; while (mx < (MAP_DIMENSION/TERRITORY_DIMENSION)) { n_int my = 0; n_int normalx = mx + (tx * (MAP_DIMENSION/TERRITORY_DIMENSION)); while (my < (MAP_DIMENSION/TERRITORY_DIMENSION)) { n_int normaly = my + (ty * (MAP_DIMENSION/TERRITORY_DIMENSION)); n_byte value = land[normalx + (normaly*MAP_DIMENSION)]; count[value>>4]++; if (value > highest_value) { highest_value = value; } if (value < loweest_value) { loweest_value = value; } if (mx == 0) { dx -= (n_int)value; if (my == 0) { top_left = value; } if (my == ((MAP_DIMENSION/TERRITORY_DIMENSION)-1)) { bottom_left = value; } } if (my == 0) { dy -= (n_int)value; } if (mx == ((MAP_DIMENSION/TERRITORY_DIMENSION)-1)) { dx += (n_int)value; if (my == 0) { top_right = value; } if (my == ((MAP_DIMENSION/TERRITORY_DIMENSION)-1)) { bottom_right = value; } } if (my == ((MAP_DIMENSION/TERRITORY_DIMENSION)-1)) { dy += (n_int)value; } if (((mx/2) == (my/2))&& ((mx/2) == ((MAP_DIMENSION/TERRITORY_DIMENSION)/2))) { center_average += (n_int)value; } my++; } mx++; } /* naming logic goes here */ { territory_name return_name = NAME_UNKNOWN; *(set_names++) = return_name; } ty++; } tx++; } } <|start_filename|>test/example5.json<|end_filename|> {"general_variables":"test","general_variables2":{"general_variables":[1,2,4,5,9],"general_variables2":-12345,"general_variables3":{"general_variables":"test","general_variables2":["hat","cat","horse","rat"],"general_variables3":"test"}},"general_variables3":"test"} <|start_filename|>mac/ASMacView.h<|end_filename|> /**************************************************************** ASMacView.h ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of Tom Barbalet, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #import <Cocoa/Cocoa.h> //@import MetalKit; #ifdef MUSHROOM #import "ASShared.h" #else #ifndef SIMULATED_PLANET #ifdef WARFARE #import "ASShared.h" #else #import "Simulated_Ape-Swift.h" #endif #else #import "ASShared.h" #ifndef SIMULATED_PLANET #import "../apple/ASDefaults.h" #define USE_SIMULATED_DEFAULTS #endif #endif #endif #import "ASMacCG.h" @interface ASMacView :ASMacCG //MTKView { CGContextRef drawRef; CVDisplayLinkRef displayLink; #ifdef USE_SIMULATED_DEFAULTS ASDefaults *defaults; #endif } @property (nonatomic, strong) ASShared* shared; - (void) startView; - (void) sharedReady; - (BOOL) acceptsFirstResponder; - (BOOL) becomeFirstResponder; - (BOOL) resignFirstResponder; - (void) awakeFromNib; - (void) startEverything:(BOOL)headyLifting; - (void) quitProcedure; - (IBAction) menuQuit:(id) sender; - (IBAction) aboutDialog:(id) sender; - (void) keyUp:(NSEvent *)theEvent; - (void) keyDown:(NSEvent *)theEvent; - (void) mouseDown:(NSEvent *)theEvent; - (void) rightMouseDown:(NSEvent *)theEvent; - (void) otherMouseDown:(NSEvent *)theEvent; - (void) mouseUp:(NSEvent *)theEvent; - (void) rightMouseUp:(NSEvent *)theEvent; - (void) otherMouseUp:(NSEvent *)theEvent; - (void) mouseDragged:(NSEvent *)theEvent; - (void) scrollWheel:(NSEvent *)theEvent; - (void) rightMouseDragged:(NSEvent *)theEvent; - (void) otherMouseDragged:(NSEvent *)theEvent; @end <|start_filename|>test/random_check.c<|end_filename|> /**************************************************************** random_check.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of Tom Barbalet, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /* This provides a checking utility for the first 65536, 256 and 16 values */ #include <stdio.h> typedef unsigned short n_byte2; n_byte2 math_random(n_byte2 * local) { n_byte2 tmp0; n_byte2 tmp1; tmp0 = local[0]; tmp1 = local[1]; local[0] = tmp1; switch (tmp0 & 7) { case 0: local[1] = (unsigned short)(tmp1 ^ (tmp0 >> 1) ^ 0xd028); break; case 4: local[1] = (unsigned short)(tmp1 ^ (tmp0 >> 2) ^ 0xae08); break; case 8: local[1] = (unsigned short)(tmp1 ^ (tmp0 >> 3) ^ 0x6320); break; default: local[1] = (unsigned short)(tmp1 ^ (tmp0 >> 1)); break; } return (tmp1); } void from_seed(unsigned short * local) { unsigned long summation = 0; unsigned long odd = 0; unsigned long lower256 = 0; unsigned long upper256 = 0; int loop = 0; while (loop < (256*256)) { unsigned short value = math_random(local); summation += value; if (value&1) odd++; lower256 += (value & 255); upper256 += (value >> 8); loop++; } printf("average %lu odd %lu first %lu second %lu\n", summation/(256*256), odd, lower256/(256*256), upper256/(256*256)); } void from_seed256(unsigned short * local) { unsigned long summation = 0; unsigned long odd = 0; unsigned long lower256 = 0; unsigned long upper256 = 0; int loop = 0; while (loop < 256) { unsigned short value = math_random(local); summation += value; if (value&1) odd++; lower256 += (value & 255); upper256 += (value >> 8); loop++; } printf("256 average %lu odd %lu first %lu second %lu\n", summation/(256), odd, lower256/(256), upper256/(256)); } void from_seed16(unsigned short * local) { unsigned long summation = 0; unsigned long odd = 0; unsigned long lower256 = 0; unsigned long upper256 = 0; int loop = 0; while (loop < 16) { unsigned short value = math_random(local); summation += value; if (value&1) odd++; lower256 += (value & 255); upper256 += (value >> 8); loop++; } printf("16 average %lu odd %lu first %lu second %lu\n", summation/(16), odd, lower256/(16), upper256/(16)); } int main(void) { unsigned short seed[2]; printf(" --- test math --- start ----------------------------------------------\n"); seed[0] = 0x625f; seed[1] = 0xe980; from_seed(seed); seed[0] = 0; seed[1] = 0; from_seed(seed); seed[0] = 0; seed[1] = 0xffff; from_seed(seed); seed[0] = 0; seed[1] = 0xffff; from_seed(seed); seed[0] = 0x8000; seed[1] = 0x8000; from_seed(seed); seed[0] = 0x7fff; seed[1] = 0x7fff; from_seed(seed); seed[0] = 0x625f; seed[1] = 0xe980; from_seed256(seed); seed[0] = 0; seed[1] = 0; from_seed256(seed); seed[0] = 0; seed[1] = 0xffff; from_seed256(seed); seed[0] = 0; seed[1] = 0xffff; from_seed256(seed); seed[0] = 0x8000; seed[1] = 0x8000; from_seed256(seed); seed[0] = 0x7fff; seed[1] = 0x7fff; from_seed256(seed); seed[0] = 0x625f; seed[1] = 0xe980; from_seed16(seed); seed[0] = 0; seed[1] = 0; from_seed16(seed); seed[0] = 0; seed[1] = 0xffff; from_seed16(seed); seed[0] = 0; seed[1] = 0xffff; from_seed16(seed); seed[0] = 0x8000; seed[1] = 0x8000; from_seed16(seed); seed[0] = 0x7fff; seed[1] = 0x7fff; from_seed16(seed); printf(" --- test math --- end ----------------------------------------------\n"); return 1; } <|start_filename|>gui/gui.h<|end_filename|> /**************************************************************** gui.h ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #ifndef SIMULATEDAPE_GUI_H #define SIMULATEDAPE_GUI_H #ifndef _WIN32 #include "../toolkit/toolkit.h" #include "../script/script.h" #include "../sim/sim.h" #ifdef SIMULATED_APE_CLIENT #include "client.h" #else #include "../universe/universe.h" #include "../entity/entity.h" #endif #else #ifdef SIMULATED_APE_CLIENT #include "client.h" #else #include "..\universe\universe.h" #include "..\entity\entity.h" #endif #endif #undef MULTITOUCH_CONTROLS #define TERRAINWINDOW(alpha) (alpha) #define CONTROLWINDOW(alpha) (alpha + TERRAIN_WINDOW_AREA) #define VIEWWINDOW(alpha) (alpha + TERRAIN_WINDOW_AREA + CONTROL_WINDOW_AREA) #define IS_WINDOW_KIND(x,y) (((x)>>(y))&1) #define spot_color(alpha,spx,spy,col) alpha[((spx)|((spy)<<8))]=(col) /* Graphics Metrics */ /* Icon Offset */ #define ICONOFFSET 27 #ifdef MULTITOUCH_CONTROLS typedef enum { TCS_SHOW_NOTHING = 0, TCS_SHOW_CONTROLS, TCS_LEFT_STATE, TCS_LEFT_STATE_CONTROLS, TCS_RIGHT_STATE, TCS_RIGHT_STATE_CONTROLS } touch_control_state; #define TC_OFFSET_Y (40) #define TC_FRACTION_X (40) #endif n_byte * draw_weather_grayscale(void); void vascular_draw(n_genetics * genetics, n_byte * buffer, n_vect2* img, n_vect2 *tp, n_vect2 * bp, n_byte thickness, n_byte clear, n_int shoulder_angle, n_int elbow_angle, n_int wrist_angle, n_int hip_angle, n_int knee_angle, n_byte show_skeleton_keypoints); n_vect2 * draw_selected_location(void); void draw_point(n_int x, n_int y); n_int draw_toggle_follow(void); n_int draw_toggle_social_web(void); n_int draw_toggle_weather(void); n_int draw_toggle_brain(void); n_int draw_toggle_braincode(void); n_int draw_toggle_territory(void); n_int draw_toggle_tide_daylight(void); n_int draw_toggle_tide_daylight_value(void); void draw_terrain_coord(n_int * co_x, n_int * co_y); void draw_undraw_clear(void); n_byte * draw_pointer(n_int which_one); n_byte * draw_color_fit(void); void draw_about(void); void draw_string(n_constant_string str, n_int off_x, n_int off_y, n_join * draw); void draw_window(n_int dim_x, n_int dim_y); void draw_cycle(n_byte size_changed, n_byte kind); n_byte * draw_offscreen(n_byte * value); n_int draw_control_font_scaling(void); #endif /* SIMULATEDAPE_GUI_H */ <|start_filename|>universe/command.c<|end_filename|> /**************************************************************** command.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #define _CRT_SECURE_NO_WARNINGS #define REMOVE_BOLDING_TEXT #include "../entity/entity.h" #include "universe_internal.h" #include <stdio.h> static n_int simulation_running = 1; static n_int simulation_executing = 0; const n_string RUN_STEP_CONST = "RSC"; /** The type of watch */ static n_int watch_type = WATCH_NONE; /** keeps a running count of the total string length */ static n_int watch_string_length = 0; /** enable or disable logging to file */ static n_int nolog = 0; /** number of steps to periodically log simulation indicators */ static n_int indicator_index = 1; /** How many steps at which to periodically save the simulation */ static n_uint save_interval_steps = 60; static n_int command_file_interaction = 0; static n_string_block command_file_name; static void command_offset(n_byte * start, n_byte * point, n_string text) { printf("%s %ld\n", text, (n_int)(point - start)); } #define FILE_CHECK(value) command_offset((n_byte*)&here, (n_byte*)value, #value) static void command_audit(void) { { simulated_being here; FILE_CHECK(&here.delta.location[0]); FILE_CHECK(&here.delta.direction_facing); FILE_CHECK(&here.delta.velocity); FILE_CHECK(&here.delta.stored_energy); FILE_CHECK(&here.constant.date_of_birth); FILE_CHECK(&here.delta.seed[0]); FILE_CHECK(&here.delta.macro_state); FILE_CHECK(&here.braindata.brain_state[0]); FILE_CHECK(&here.delta.height); FILE_CHECK(&here.delta.mass); FILE_CHECK(&here.braindata.script_overrides); FILE_CHECK(&here.changes.shout[0]); FILE_CHECK(&here.delta.crowding); FILE_CHECK(&here.delta.posture); FILE_CHECK(&here.changes.inventory[0]); FILE_CHECK(&here.delta.parasites); FILE_CHECK(&here.delta.honor); FILE_CHECK(&here.changes.date_of_conception); /* constant */ FILE_CHECK(&here.braindata.attention[0]); FILE_CHECK(&here.constant.genetics[0]); /* constant */ FILE_CHECK(&here.changes.fetal_genetics[0]); /* constant */ FILE_CHECK(&here.changes.father_name[0]); /* why is this needed? */ FILE_CHECK(&here.delta.social_coord_x); FILE_CHECK(&here.delta.social_coord_y); FILE_CHECK(&here.delta.social_coord_nx); /* why is this needed? */ FILE_CHECK(&here.delta.social_coord_ny); /* why is this needed? */ FILE_CHECK(&here.changes.drives[0]); FILE_CHECK(&here.delta.goal[0]); FILE_CHECK(&here.changes.learned_preference[0]); FILE_CHECK(&here.constant.generation_min); FILE_CHECK(&here.constant.generation_max); FILE_CHECK(&here.changes.child_generation_min); FILE_CHECK(&here.changes.child_generation_max); #ifdef TERRITORY_ON FILE_CHECK(&here.events.territory[0]); #endif #ifdef IMMUNE_ON FILE_CHECK(&here.immune_system); #endif #ifdef BRAINCODE_ON FILE_CHECK(&here.braindata.braincode_register[0]); FILE_CHECK(&here.braindata.brainprobe[0]); #endif #ifdef BRAIN_ON FILE_CHECK(&here.braindata.brain[0]); #endif FILE_CHECK(&here.events.social[0]); FILE_CHECK(&here.events.episodic[0]); } { simulated_isocial here; FILE_CHECK(&here.space_time.location[0]); FILE_CHECK(&here.space_time.time); FILE_CHECK(&here.space_time.date); FILE_CHECK(&here.first_name[0]); FILE_CHECK(&here.family_name[0]); FILE_CHECK(&here.attraction); FILE_CHECK(&here.friend_foe); FILE_CHECK(&here.belief); FILE_CHECK(&here.familiarity); FILE_CHECK(&here.relationship); FILE_CHECK(&here.entity_type); #ifdef FEATURE_SET FILE_CHECK(&here.classification); #endif #ifdef BRAINCODE_ON FILE_CHECK(&here.braincode[0]); #endif } { simulated_iepisodic here; FILE_CHECK(&here.space_time.location[0]); FILE_CHECK(&here.space_time.time); FILE_CHECK(&here.space_time.date); FILE_CHECK(&here.first_name[0]); FILE_CHECK(&here.family_name[0]); FILE_CHECK(&here.event); FILE_CHECK(&here.food); FILE_CHECK(&here.affect); FILE_CHECK(&here.arg); } } n_int command_executing(void) { return simulation_executing; } /** * * @param ptr pointer to simulated_group object * @param response command parameters * @param output_function the output function */ n_int command_being(void * ptr, n_string response, n_console_output output_function) { simulated_group * group = (simulated_group *) ptr; output_function(being_get_select_name(group)); return 0; } static n_byte2 command_friends_first[SOCIAL_SIZE_BEINGS]; static n_byte2 command_friends_family[SOCIAL_SIZE_BEINGS]; static n_int command_friends_count; static n_byte2 command_enemies_first[SOCIAL_SIZE_BEINGS]; static n_byte2 command_enemies_family[SOCIAL_SIZE_BEINGS]; static n_int command_enemies_count; static n_byte2 command_attract_first[SOCIAL_SIZE_BEINGS]; static n_byte2 command_attract_family[SOCIAL_SIZE_BEINGS]; static n_int command_attract_count; n_int command_relationship_count(n_int friend_type) { switch(friend_type) { case 0: /**< friends */ return command_friends_count; case 1: /**< enemies */ return command_enemies_count; case 2: /**< attraction */ return command_attract_count; } return 0; } simulated_being * command_relationship_being(simulated_group * group, n_int friend_type, n_int location) { n_byte2 first_name_look_up; n_byte2 family_name_look_up; n_uint loop = 0; switch(friend_type) { case 0: /**< friends */ first_name_look_up = command_friends_first[location]; family_name_look_up = command_friends_family[location]; break; case 1: /**< enemies */ first_name_look_up = command_enemies_first[location]; family_name_look_up = command_enemies_family[location]; break; case 2: /**< attraction */ first_name_look_up = command_friends_first[location]; family_name_look_up = command_friends_family[location]; break; default: return 0L; } while (loop < group->num) { simulated_being * local = &group->beings[loop]; if ((being_gender_name(local) == first_name_look_up) && (being_family_name(local) == family_name_look_up)) { return local; } loop++; } return 0L; } static void command_show_friends_being(void * ptr, simulated_being * local_being, n_int friend_type, n_string result, n_string eight_characters) { simulated_group * group = (simulated_group *) ptr; n_int i,found; simulated_isocial * local_social_graph; n_int first = 1; if (local_being == 0) return; /** Get the social graph for the being */ local_social_graph = being_social(local_being); if (local_social_graph == 0L) return; switch(friend_type) { case 0: /**< friends */ command_friends_count = 0; break; case 1: /**< enemies */ command_enemies_count = 0; break; case 2: /**< attraction */ command_attract_count = 0; break; } /** For each entry in the social graph */ for (i = 1; i < SOCIAL_SIZE_BEINGS; i++) { /** Skip empty entries */ if (SOCIAL_GRAPH_ENTRY_EMPTY(local_social_graph, i)) continue; found = 0; switch(friend_type) { case 0: /**< friends */ { if (local_social_graph[i].friend_foe >= social_respect_mean(local_being)) { if (local_social_graph[i].entity_type == ENTITY_BEING) { command_friends_first[command_friends_count] = local_social_graph[i].first_name[BEING_MET]; command_friends_family[command_friends_count] = local_social_graph[i].family_name[BEING_MET]; command_friends_count++; } found = 1; } break; } case 1: /**< enemies */ { if (local_social_graph[i].friend_foe < social_respect_mean(local_being)) { if (local_social_graph[i].entity_type == ENTITY_BEING) { command_enemies_first[command_enemies_count] = local_social_graph[i].first_name[BEING_MET]; command_enemies_family[command_enemies_count] = local_social_graph[i].family_name[BEING_MET]; command_enemies_count++; } found = 1; } break; } case 2: /**< attraction */ { if (local_social_graph[i].attraction > 0) { if (local_social_graph[i].entity_type == ENTITY_BEING) { command_attract_first[command_attract_count] = local_social_graph[i].first_name[BEING_MET]; command_attract_family[command_attract_count] = local_social_graph[i].family_name[BEING_MET]; command_attract_count++; } found = 1; } break; } } if (found==1) { n_int relationship_index; n_string_block relationship_str1; n_string_block relationship_str2; n_string_block met_being_name; n_string_block result_str; /** Print the name and familiarity */ social_graph_link_name(group, local_being, i, BEING_MET, met_being_name); /** type of relationship */ relationship_index = local_social_graph[i].relationship; if (relationship_index > RELATIONSHIP_SELF) { being_relationship_description(relationship_index, relationship_str1); if (IS_FAMILY_MEMBER(local_social_graph,i)) { io_three_strings(relationship_str2, " (", relationship_str1, ")", 0); } else { n_string_block meeter_being_name; n_string_block string_of_strings; io_three_strings(meeter_being_name, " ", "", "", 0); social_graph_link_name(group, local_being, i, BEING_MEETER, meeter_being_name); io_three_strings(string_of_strings, relationship_str1, " of *", meeter_being_name, 0); #ifdef REMOVE_BOLDING_TEXT io_three_strings(relationship_str2, " ", string_of_strings, "*", 0); #else io_three_strings(relationship_str2, " <", string_of_strings, "*>", 0); #endif } } else { io_three_strings(relationship_str2, " ", "", "", 0); } if (i != being_attention(local_being,ATTENTION_ACTOR)) { /** Not the current focus of attention */ if (first) { sprintf(result_str,"%s %05d *%s*%s\n",eight_characters,(int)local_social_graph[i].familiarity,met_being_name,relationship_str2); first = 0; } else { sprintf(result_str," %05d *%s*%s\n",(int)local_social_graph[i].familiarity,met_being_name,relationship_str2); } } else { if (first) { /** The current focus of attention */ #ifdef REMOVE_BOLDING_TEXT sprintf(result_str,"%s %05d *%s*%s\n", eight_characters,(int)local_social_graph[i].familiarity,met_being_name,relationship_str2); #else sprintf(result_str,"%s %05d <*%s*>%s\n", eight_characters,(int)local_social_graph[i].familiarity,met_being_name,relationship_str2); #endif first = 0; } else { #ifdef REMOVE_BOLDING_TEXT sprintf(result_str," %05d *%s*%s\n",(int)local_social_graph[i].familiarity,met_being_name,relationship_str2); #else sprintf(result_str," %05d <*%s*>%s\n",(int)local_social_graph[i].familiarity,met_being_name,relationship_str2); #endif } } /** Write to the final result string */ io_string_write(result, result_str, &watch_string_length); } } } /** * Show the friends of the given being * @param ptr pointer to simulated_group object * @param beingname name of the being * @param friend_type 0=friends, 1=enemies, 2=mates * @param result returned text */ static void command_show_friends(void * ptr, n_string beingname, n_int friend_type, n_string result) { simulated_group * group = (simulated_group *) ptr; simulated_being * local_being; n_string local_being_name = io_string_copy(beingname); /** Get the being object from its name */ local_being = being_from_name(group, local_being_name); memory_free((void**)&local_being_name); if (local_being == 0) return; command_show_friends_being(ptr, local_being, friend_type, result, " "); } /** * gets the number of mins/hours/days/months/years * @param str text to be processed * @param number the number of the time units * @param interval the time units * @return number of mins/hours/days/months/years */ n_int get_time_interval(n_string str, n_int * number, n_int * interval) { n_int i,index=0,ctr=0,result=0,divisor=0; char c; n_string_block buf; n_int retval = -1; n_int length = io_length(str,256); for (i = 0; i < length; i++) { if (str[i] != ' ') { buf[ctr++] = str[i]; } if ((str[i] == ' ') || (i==(length-1))) { buf[ctr]=0; switch(index) { case 0: { io_number((n_string)buf, &result, &divisor); *number = result; retval = 0; break; } case 1: { if (ctr==1) { char lower_c; lower_c = c = buf[0]; IO_LOWER_CHAR(lower_c); if (c=='m') *interval = INTERVAL_MINS; if (lower_c=='h') *interval = INTERVAL_HOURS; if (lower_c=='d') *interval = INTERVAL_DAYS; if (c=='M') *interval = INTERVAL_MONTHS; if (lower_c=='y') *interval = INTERVAL_YEARS; } else { IO_LOWER_CHAR(buf[0]); if (io_find((n_string)buf,0,ctr,"min",3)>-1) *interval = INTERVAL_MINS; if ((io_find((n_string)buf,0,ctr,"hour",4)>-1) || (io_find((n_string)buf,0,ctr,"hr",2)>-1)) { *interval = INTERVAL_HOURS; } if (io_find((n_string)buf,0,ctr,"day",3)>-1) *interval = INTERVAL_DAYS; if (io_find((n_string)buf,0,ctr,"mon",3)>-1) *interval = INTERVAL_MONTHS; } break; } } index++; ctr=0; } } return retval; } static void command_simulation_loop(simulated_group * group, simulated_being * local_being, void * data) { n_int *int_data = data; if (FIND_SEX(GET_I(local_being)) == SEX_FEMALE) { int_data[0]++; } if ((land_date() - being_dob(local_being)) < AGE_OF_MATURITY) { int_data[1]++; } } /** * Show details of the overall simulation * @param ptr pointer to simulated_group object * @param response parameters of the command * @param output_function function to be used to display the result * @return 0 */ n_int command_simulation(void * ptr, n_string response, n_console_output output_function) { simulated_group * group = (simulated_group *) ptr; simulated_timing * timing = sim_timing(); n_string_block beingstr, time; n_int int_data[2]; n_byte2 *local_land_genetics = land_genetics(); n_string_block land_dimension, land_genetics0, land_genetics1, genetics, population; n_string_block adults, juveniles, tide_level; loop_no_thread(group, 0L, command_simulation_loop, int_data); io_number_to_string(land_dimension, (n_uint)land_map_dimension()); io_number_to_string(land_genetics0, local_land_genetics[0]); io_number_to_string(land_genetics1, local_land_genetics[1]); io_number_to_string(population, group->num); io_number_to_string(adults, (n_uint)((n_int)(group->num) - int_data[1])); io_number_to_string(juveniles, (n_uint)int_data[1]); io_number_to_string(tide_level, land_tide_level()); io_three_strings(beingstr, "Map dimension: ", land_dimension, "", 1); io_three_strings(genetics, land_genetics0, " ", land_genetics1, 0); io_three_strings(beingstr, beingstr, "Land seed: ", genetics, 1); io_three_strings(beingstr, beingstr, "Population: ", population, 1); io_three_strings(beingstr, beingstr, "Adults: ", adults, 0); io_three_strings(beingstr, beingstr, " Juveniles: ", juveniles, 1); if (group->num > 0) { n_string_block males, females, males_percent, females_percent; io_number_to_string(males, (group->num - int_data[0])); io_number_to_string(females, int_data[0]); io_number_to_string(males_percent, ((group->num - int_data[0])*100)/group->num); io_number_to_string(females_percent, (int_data[0] * 100)/group->num); io_three_strings(beingstr, beingstr, "Females: ", females, 0); io_three_strings(beingstr, beingstr, " (", females_percent, 0); io_three_strings(beingstr, beingstr, "%) Males: ", males, 0); io_three_strings(beingstr, beingstr, " (", males_percent, 0); io_three_strings(beingstr, beingstr, "%)", "", 1); } io_three_strings(beingstr, beingstr, "Tide level: ", tide_level, 1); io_time_to_string(time); if (timing->delta_cycles) { n_string_block delta_cycles; io_number_to_string(delta_cycles, timing->delta_cycles); io_three_strings(beingstr, beingstr, "Brain Cycles Per Second: ", delta_cycles, 1); } if (simulation_executing) { io_three_strings(beingstr, beingstr, time, " Simulation running", 0); } else { io_three_strings(beingstr, beingstr, time, " Simulation not running", 0); } output_function(beingstr); return 0; } /** * Shows the names of all beings * @param ptr pointer to simulated_group * @param response parameters of the command * @param output_function function used to display the result * @return 0 */ n_int command_list(void * ptr, n_string response, n_console_output output_function) { simulated_group * group = (simulated_group *) ptr; simulated_being * local_being; n_string_block line_text; n_int location = 0; n_uint loop = 0; if (group->num == 0) { output_function("No apes present. Trying (re)running the Simulation"); return 0; } /** show names in index order */ while (loop < group->num) { n_string_block name; n_int length; /** get the being */ local_being = &group->beings[loop]; /** get the name of the being */ being_name_simple(local_being, name); io_string_write(line_text, name, &location); length = io_length(name, STRING_BLOCK_SIZE); while (length < 24) { io_string_write(line_text, " ", &location); length++; } if ((loop % 3) == 2) { output_function(line_text); location = 0; } loop++; } if (location != 0) { output_function(line_text); } return 0; } void command_change_selected(simulated_group * group, n_byte forwards) { simulated_being * local_select = group->select; simulated_being * first = group->beings; simulated_being * last = &(group->beings[group->num - 1]); if (forwards) { if (group->select != last) { local_select++; } else { local_select = first; } } else { if (group->select != first) { local_select--; } else { local_select = last; } } sim_set_select(local_select); } static n_int command_check_ape_present(void * ptr, n_console_output output_function) { simulated_group * group = (simulated_group *) ptr; if (group->select) { return 1; } if (group->num) { output_function("No apes selected."); } else { output_function("No apes selected. Trying (re)running the Simulation"); } return 0; } n_int command_next(void * ptr, n_string response, n_console_output output_function) { if (command_check_ape_present(ptr, output_function)) { command_change_selected((simulated_group *) ptr, 1); } return 0; } n_int command_previous(void * ptr, n_string response, n_console_output output_function) { if (command_check_ape_present(ptr, output_function)) { command_change_selected((simulated_group *) ptr, 0); } return 0; } #ifdef BRAINCODE_ON void command_populate_braincode(simulated_group * group, line_braincode function) { if (group->select) { simulated_being * local_being = group->select; n_byte * internal_bc = being_braincode_internal(local_being); n_byte * external_bc = being_braincode_external(local_being); n_int loop = 0; n_string_block initial_information; n_int position = 0; io_string_write(initial_information, "EXT INT", &position); (*function)(initial_information, -1); while(loop < 22) { n_string_block command_information; n_string_block first_internal; n_string_block first_external; position = 0; brain_three_byte_command((n_string)first_internal, &internal_bc[loop*BRAINCODE_BYTES_PER_INSTRUCTION]); brain_three_byte_command((n_string)first_external, &external_bc[loop*BRAINCODE_BYTES_PER_INSTRUCTION]); if (loop == 21) { io_string_write(command_information, first_external, &position); io_string_write(command_information, " ", &position); io_string_write(command_information, first_internal, &position); } else { n_string_block second_internal; n_string_block second_external; brain_three_byte_command((n_string)second_internal, &internal_bc[(loop+22)*BRAINCODE_BYTES_PER_INSTRUCTION]); brain_three_byte_command((n_string)second_external, &external_bc[(loop+22)*BRAINCODE_BYTES_PER_INSTRUCTION]); io_string_write(command_information, first_external, &position); io_string_write(command_information, " ", &position); io_string_write(command_information, second_external, &position); io_string_write(command_information, " ", &position); io_string_write(command_information, first_internal, &position); io_string_write(command_information, " ", &position); io_string_write(command_information, second_internal, &position); } (*function)(command_information, loop); loop++; } } } #endif /** * Show the appearance parameters for a being * @param ptr pointer to simulated_group object * @param beingname name of the being * @param local_being being to be shown * @param result resulting text containing appearance */ static void watch_appearance(void *ptr, n_string beingname, simulated_being * local_being, n_string result) { n_string_block str; n_genetics * genetics = being_genetics(local_being); sprintf(str,"Height: %.3f m\n", (int)GET_BEING_HEIGHT(local_being)/1000.0f); io_string_write(result, str, &watch_string_length); sprintf(str,"Mass: %.2f Kg\n", (float)GET_M(local_being)/100.0f); io_string_write(result, str, &watch_string_length); sprintf(str,"Body fat: %.2f Kg\n", (float)GET_BODY_FAT(local_being)/100.0f); io_string_write(result, str, &watch_string_length); sprintf(str,"Hair length: %.1f mm\n", (float)(GENE_HAIR(genetics)*100.0f/160.0f)); io_string_write(result, str, &watch_string_length); sprintf(str,"Pigmentation: %02d\n", (int)(GENE_PIGMENTATION(genetics))); io_string_write(result, str, &watch_string_length); sprintf(str,"Body frame: %02d\n", (int)(GENE_FRAME(genetics))); io_string_write(result, str, &watch_string_length); sprintf(str,"Eye separation: %.1f mm\n", 80.0f + ((float)(GENE_EYE_SEPARATION(genetics)))); io_string_write(result, str, &watch_string_length); sprintf(str,"Eye color: %02d Eye shape: %02d\n", (int)(GENE_EYE_COLOR(genetics)), (int)(GENE_EYE_SHAPE(genetics))); io_string_write(result, str, &watch_string_length); sprintf(str,"Nose shape: %02d Ear shape: %02d\n", (int)(GENE_NOSE_SHAPE(genetics)), (int)(GENE_EAR_SHAPE(genetics))); io_string_write(result, str, &watch_string_length); sprintf(str,"Eyebrow shape: %02d Mouth shape: %02d\n", (int)(GENE_EYEBROW_SHAPE(genetics)), (int)(GENE_MOUTH_SHAPE(genetics))); io_string_write(result, str, &watch_string_length); } #ifdef BRAINCODE_ON static n_string static_result; static void watch_line_braincode(n_string string, n_int line) { io_string_write(static_result, string, &watch_string_length); io_string_write(static_result, "\n", &watch_string_length); } #endif /** * Shows braincode for the given being * @param ptr pointer to simulated_group object * @param beingname Name of the being * @param local_being being to be viewed * @param result returned text */ static void watch_braincode(void *ptr, n_string beingname, simulated_being * local_being, n_string result) { #ifdef BRAINCODE_ON n_int i; io_string_write(result, "\nRegisters:\n", &watch_string_length); for (i=0; i<BRAINCODE_PSPACE_REGISTERS; i++) { result[watch_string_length++]=(n_char)(65+(local_being->braindata.braincode_register[i]%60)); } result[watch_string_length++]='\n'; result[watch_string_length++]='\n'; static_result = result; command_populate_braincode(ptr,watch_line_braincode); static_result = 0L; result[watch_string_length++]='\n'; #endif } static void watch_speech(void *ptr, n_string beingname, simulated_being * local, n_string result) { #ifdef BRAINCODE_ON n_int loop; n_byte * external_bc = being_braincode_external(local); for (loop = 0; loop < BRAINCODE_SIZE/BRAINCODE_BYTES_PER_INSTRUCTION; loop++) { n_string_block sentence; brain_sentence((n_string)sentence, &external_bc[loop*3]); io_string_write(result, sentence, &watch_string_length); if ((loop &3) == 3) { result[watch_string_length++]='.'; } if (loop < BRAINCODE_SIZE/BRAINCODE_BYTES_PER_INSTRUCTION-1) { result[watch_string_length++]=' '; } } result[watch_string_length++]='.'; result[watch_string_length++]='\n'; #endif } /** * Shows the social graph for the given being * @param ptr pointer to simulated_group object * @param beingname Name of the being * @param local_being being to be viewed * @param result returned text */ static void watch_social_graph(void *ptr, n_string beingname, simulated_being * local_being, n_string result) { io_string_write(result, "\nFriends:\n", &watch_string_length); command_show_friends(ptr, beingname, 0, result); io_string_write(result, "\nEnemies:\n", &watch_string_length); command_show_friends(ptr, beingname, 1, result); } /** * Shows the episodic memory for the given being * @param ptr pointer to simulated_group object * @param beingname Name of the being * @param local_being being to be viewed * @param result returned text */ static void watch_episodic(void *ptr, n_string beingname, simulated_being * local_being, n_string result) { n_uint i; for (i = 0; i < EPISODIC_SIZE; i++) { n_string_block str = {0}; n_string_block description = {0}; n_int position = 0; (void)episode_description(local_being, i, str); if (io_length(str, STRING_BLOCK_SIZE) > 0) { #ifdef REMOVE_BOLDING_TEXT io_string_write(description, " ", &position); io_string_write(description, str, &position); io_string_write(description, "\n", &position); #else if (being_attention(local_being, ATTENTION_EPISODE) != i) { io_string_write(description, " ", &position); io_string_write(description, str, &position); io_string_write(description, "\n", &position); } else { io_string_write(description, " <", &position); io_string_write(description, str, &position); io_string_write(description, ">\n", &position); } #endif io_string_write(result, description, &watch_string_length); } } } /** * Shows the genome for the given being * @param ptr pointer to simulated_group object * @param beingname Name of the being * @param local_being being to be viewed * @param result returned text */ static void watch_genome(void *ptr, n_string beingname, simulated_being * local_being, n_string result) { n_int i,j; n_byte genome[CHROMOSOMES*8+1]; for (i = 0; i < 2; i++) { body_genome((n_byte)i, being_genetics(local_being), genome); for (j = 0; j < CHROMOSOMES*8; j++) { if ((j>0) && (j%8==0)) { io_string_write(result, "\t", &watch_string_length); } result[watch_string_length++] = genome[j]; } io_string_write((n_string)result, "\n", &watch_string_length); } } /** * Shows brainprobes for the given being * @param ptr pointer to simulated_group object * @param beingname Name of the being * @param local_being being to be viewed * @param result returned text */ static void watch_brainprobes(void *ptr, n_string beingname, simulated_being * local_being, n_string result) { #ifdef BRAINCODE_ON n_int i; n_string_block str2; n_string_block type_str; io_string_write(result, "\n Type Posn Freq Offset Addr State\n ", &watch_string_length); for (i = 0; i < 36; i++) { io_string_write(result, "-", &watch_string_length); } io_string_write(result, "\n", &watch_string_length); io_three_strings(type_str, "Input ", "", "", 0); for (i = 0; i < BRAINCODE_PROBES; i++) { if (local_being->braindata.brainprobe[i].type == INPUT_SENSOR) { sprintf((n_string)str2," %s %03d %02d %03d %03d %d\n", type_str, local_being->braindata.brainprobe[i].position, local_being->braindata.brainprobe[i].frequency, local_being->braindata.brainprobe[i].offset, local_being->braindata.brainprobe[i].address, local_being->braindata.brainprobe[i].state); io_string_write(result, (n_string)str2, &watch_string_length); } } io_three_strings(type_str, "Output ", "", "", 0); for (i = 0; i < BRAINCODE_PROBES; i++) { if (local_being->braindata.brainprobe[i].type == OUTPUT_ACTUATOR) { sprintf((n_string)str2," %s %03d %02d %03d %03d %d\n", type_str, local_being->braindata.brainprobe[i].position, local_being->braindata.brainprobe[i].frequency, local_being->braindata.brainprobe[i].offset, local_being->braindata.brainprobe[i].address, local_being->braindata.brainprobe[i].state); io_string_write(result, (n_string)str2, &watch_string_length); } } #endif } /** * Shows the main parameters for the given being * @param ptr pointer to simulated_group object * @param beingname Name of the being * @param local_being being to be viewed * @param result returned text */ static void watch_stats(void *ptr, n_string beingname, simulated_being * local_being, n_string result) { n_string_block str; n_string_block relationship_str; n_string_block status; if (local_being == 0L) { (void)SHOW_ERROR("No being for stats"); return; } being_state_description(being_state(local_being), status); being_relationship_description(being_attention(local_being,ATTENTION_RELATIONSHIP),relationship_str); sprintf(str, "%s: %s\nGeneration %lu:%lu Sex: %c Energy %ld\nLocation: (%ld . %ld) Facing: %d\nHonor: %d Height: %ld Age(days): %ld\n", beingname, status, (n_uint)local_being->constant.generation_min, (n_uint)local_being->constant.generation_max, ((FIND_SEX(GET_I(local_being)) == SEX_FEMALE) ? 'F' : 'M'), being_energy(local_being), being_location_x(local_being), being_location_y(local_being), being_facing(local_being), being_honor(local_being), GET_BEING_HEIGHT(local_being), land_date() - being_dob(local_being) ); io_string_write(result, str, &watch_string_length); if (being_pregnant(local_being)) { sprintf(str, "Pregnant(days): %ld\n",land_date() - being_pregnant(local_being)); io_string_write(result, str, &watch_string_length); } sprintf(str, "Drives Hunger: %d Social: %d\n Fatigue: %d Sex: %d\n", (int)being_drive(local_being, DRIVE_HUNGER), (int)being_drive(local_being, DRIVE_SOCIAL), (int)being_drive(local_being, DRIVE_FATIGUE), (int)being_drive(local_being, DRIVE_SEX)); io_string_write(result, str, &watch_string_length); sprintf(str, "Aware Body: %s Link: %s\n", being_body_inventory_description(being_attention(local_being,ATTENTION_BODY)), relationship_str); io_string_write(result, str, &watch_string_length); command_show_friends_being(ptr, local_being, 0, result, "Friends:"); command_show_friends_being(ptr, local_being, 2, result, "Attract:"); command_show_friends_being(ptr, local_being, 1, result, "Enemies:"); io_string_write(result, "Narrative\n", &watch_string_length); watch_episodic(ptr, beingname, local_being, result); } void watch_control(void *ptr, n_string beingname, simulated_being * local_being, n_string result) { watch_string_length = 0; watch_stats(ptr, beingname, local_being, result); } /** * This should duplicate all console for watch functions * @param ptr pointer to simulated_group object * @param response command parameters * @param output_function function used to show the output * @param title title * @param watch_function watch function * @return 0 */ static n_int command_duplicate(void * ptr, n_string response, n_console_output output_function, n_string title, console_generic watch_function) { simulated_group * group = (simulated_group *) ptr; simulated_being * local_being = 0L; n_string_block beingstr; watch_string_length=0; if ((response == 0) && (group->select)) { response = being_get_select_name(group); if (title != 0L) { io_string_write((n_string)beingstr, "\n", &watch_string_length); io_string_write((n_string)beingstr, title, &watch_string_length); io_string_write((n_string)beingstr, " for ", &watch_string_length); io_string_write((n_string)beingstr, response, &watch_string_length); io_string_write((n_string)beingstr, "\n", &watch_string_length); } } if (response != 0L) { local_being = being_from_name(group, response); if (local_being == 0L) { (void)SHOW_ERROR("Being not found"); return 0; } being_set_select_name(group, response); watch_function(ptr, being_get_select_name(group), local_being, (n_string)beingstr); beingstr[watch_string_length] = 0; output_function(beingstr); return 0; } (void)SHOW_ERROR("No being was specified"); return 0; } /** * * @param ptr pointer to simulated_group object * @param response response string * @param output_function output function * @return 0 */ n_int command_genome(void * ptr, n_string response, n_console_output output_function) { return command_duplicate(ptr, response, output_function, "Genome", watch_genome); } /** * * @param ptr pointer to simulated_group object * @param response response string * @param output_function output function * @return 0 */ n_int command_stats(void * ptr, n_string response, n_console_output output_function) { return command_duplicate(ptr, response, output_function, 0L, watch_stats); } /** * * @param ptr pointer to simulated_group object * @param response response string * @param output_function output function * @return 0 */ n_int command_probes(void * ptr, n_string response, n_console_output output_function) { return command_duplicate(ptr, response, output_function, "Brain probes", watch_brainprobes); } /** * Show the episodic memory * @param ptr pointer to simulated_group object * @param response response string * @param output_function output function * @return 0 */ n_int command_episodic(void * ptr, n_string response, n_console_output output_function) { return command_duplicate(ptr, response, output_function, "Episodic memory", watch_episodic); } /** * Show the social graph * @param ptr pointer to simulated_group object * @param response response string * @param output_function output function * @return 0 */ n_int command_social_graph(void * ptr, n_string response, n_console_output output_function) { return command_duplicate(ptr, response, output_function, "Social graph", watch_social_graph); } /** * Show the braincode * @param ptr pointer to simulated_group object * @param response response string * @param output_function output function * @return 0 */ n_int command_braincode(void * ptr, n_string response, n_console_output output_function) { return command_duplicate(ptr, response, output_function, "Braincode", watch_braincode); } n_int command_speech(void * ptr, n_string response, n_console_output output_function) { return command_duplicate(ptr, response, output_function, "Speech", watch_speech); } /** * Show appearance values * @param ptr pointer to simulated_group object * @param response response string * @param output_function output function * @return 0 */ n_int command_appearance(void * ptr, n_string response, n_console_output output_function) { return command_duplicate(ptr, response, output_function, "Appearance", watch_appearance); } static void histogram_being_state_loop(simulated_group * group, simulated_being * local_being, void * data) { n_uint * histogram = data; n_uint n = 2; if (being_state(local_being) == BEING_STATE_ASLEEP) { histogram[0]++; } else { while (n < BEING_STATES) { if (being_state(local_being) & (1<<(n-1))) { histogram[n]++; } n++; } } } /** * Update a histogram of being states * @param group pointer to simulated_group object * @param histogram histogram array to be updated * @param normalize whether to normalize the histogram */ static void histogram_being_state(simulated_group * group, n_uint * histogram, n_byte normalize) { n_uint i; for (i = 0; i < BEING_STATES; i++) histogram[i] = 0; loop_no_thread(group, 0L, histogram_being_state_loop, histogram); if (normalize) { n_uint tot=0; for (i = 0; i < BEING_STATES; i++) tot += histogram[i]; if (tot > 0) { for (i = 0; i < BEING_STATES; i++) histogram[i] = histogram[i]*1000/tot; } } } /** * Watch a particular being * @param ptr pointer to simulated_group object * @param output_function output function to be used */ static void watch_being(void * ptr, n_console_output output_function) { simulated_group * group = (simulated_group *) ptr; simulated_being * local_being; n_string_block beingstr; n_uint i; n_int j; n_byte2 state; if (being_remove_internal()) { do {} while(being_remove_internal()); } being_remove_external_set(1); if (watch_type == WATCH_STATES) { n_uint histogram[16]; n_string_block str; watch_string_length=0; io_time_to_string(str); io_string_write(beingstr,str,&watch_string_length); histogram_being_state(group, (n_uint*)histogram, 1); for (i = 0; i < BEING_STATES; i++) { if (i == 1) continue; /**< skip the awake state */ if (i==0) { state = 0; } else { state = (n_byte2)(1 << (i-1)); } being_state_description(state, (n_string)str); io_string_write(beingstr,(n_string)str,&watch_string_length); io_string_write(beingstr,":",&watch_string_length); for (j = 0; j < 12 - io_length((n_string)str,STRING_BLOCK_SIZE); j++) { io_string_write(beingstr," ",&watch_string_length); } if (histogram[i] > 0) { sprintf((n_string)str,"%.1f\n",histogram[i]/10.0f); io_string_write(beingstr,str,&watch_string_length); } else { io_string_write(beingstr,"----\n",&watch_string_length); } } output_function(beingstr); return; } if (group->select) { local_being = group->select; watch_string_length = 0; switch(watch_type) { case WATCH_ALL: { watch_stats(ptr, being_get_select_name(group), local_being, beingstr); break; } case WATCH_SOCIAL_GRAPH: { watch_social_graph(ptr, being_get_select_name(group), local_being, beingstr); break; } case WATCH_EPISODIC: { watch_episodic(ptr, being_get_select_name(group), local_being, beingstr); break; } case WATCH_BRAINCODE: { watch_braincode(ptr, being_get_select_name(group), local_being, beingstr); break; } case WATCH_BRAINPROBES: { watch_brainprobes(ptr, being_get_select_name(group), local_being, beingstr); break; } case WATCH_APPEARANCE: { watch_appearance(ptr, being_get_select_name(group), local_being, beingstr); break; } case WATCH_SPEECH: { watch_speech(ptr, being_get_select_name(group), local_being, beingstr); break; } } if (watch_type != WATCH_NONE) { output_function(beingstr); } } being_remove_external_set(0); } static n_int command_on_off(n_string response) { n_int length; if (response == 0) return -1; length = io_length(response,STRING_BLOCK_SIZE); if ((io_find(response,0,length,"off",3)>-1) || (io_find(response,0,length,"0",1)>-1) || (io_find(response,0,length,"false",5)>-1) || (io_find(response,0,length,"no",2)>-1)) { return 0; } if ((io_find(response,0,length,"on",2)>-1) || (io_find(response,0,length,"1",1)>-1) || (io_find(response,0,length,"true",4)>-1) || (io_find(response,0,length,"yes",3)>-1)) { return 1; } return -1; } n_int command_event(void * ptr, n_string response, n_console_output output_function) { #ifdef EPISODIC_ON n_int return_response = command_on_off(response); if ((return_response == -1) && response) { if (io_find(response, 0, io_length(response,STRING_BLOCK_SIZE),"social",6)>-1) { episodic_logging(output_function, 1); output_function("Event output for social turned on"); } return 0; } if (return_response == 0) { episodic_logging(0L, 0); output_function("Event output turned off"); } else { episodic_logging(output_function, 0); output_function("Event output turned on"); } #else output_function("Episodic not supported in this build"); #endif return 0; } n_int command_memory(void * ptr, n_string response, n_console_output output_function) { simulated_group * group = (simulated_group *) ptr; n_string_block str2; sprintf(str2, "maximum memory %ld\nallocated memory %ld\nmaximum apes %ld", sim_memory_allocated(1), sim_memory_allocated(0), group->max); output_function(str2); return 0; } /** * Enable or disable logging * @param ptr pointer to simulated_group object * @param response command parameters - off/on/0/1/yes/no * @param output_function function to be used to display output * @return 0 */ n_int command_logging(void * ptr, n_string response, n_console_output output_function) { n_int return_response = command_on_off(response); if (return_response == -1) { return 0; } if (return_response == 0) { nolog = 1; indicator_index = 0; watch_type = WATCH_NONE; output_function("Logging turned off"); } else { nolog = 0; indicator_index = 1; output_function("Logging turned on"); } return 0; } #ifdef BRAINCODE_ON /** * Compare two braincode arrays * @param braincode0 Braincode array for the first being * @param braincode1 Braincode byte array for the second being * @param block_size The number of instructions to compare within a block * @returns Location of the first match within the first braincode array */ static n_int command_compare_brain(n_byte * braincode0, n_byte * braincode1, n_int block_size) { n_int block_size_bytes = block_size*BRAINCODE_BYTES_PER_INSTRUCTION; n_int loop = 0; while (loop < (BRAINCODE_SIZE - block_size_bytes)) { n_int loop2 = 0; while (loop2 < (BRAINCODE_SIZE - block_size_bytes)) { n_int block_step = 0; while (block_step < block_size) { if (braincode0[loop + block_step*BRAINCODE_BYTES_PER_INSTRUCTION] == braincode1[loop2 + block_step*BRAINCODE_BYTES_PER_INSTRUCTION]) { block_step++; if (block_step == block_size) { return loop; } } else { break; } } loop2 += BRAINCODE_BYTES_PER_INSTRUCTION; } loop += BRAINCODE_BYTES_PER_INSTRUCTION; } return -1; } #endif /** * Shows repeated sections of braincode * @param ptr pointer to simulated_group * @param response response string * @param output_function output function * @returns 0 */ n_int command_idea(void * ptr, n_string response, n_console_output output_function) { #ifdef BRAINCODE_ON #ifndef CONSOLE_IDEA_MIN_BLOCK_SIZE #define CONSOLE_IDEA_MIN_BLOCK_SIZE 3 #define CONSOLE_IDEA_MAX_BLOCK_SIZE 8 #endif const n_int min_block_size = 3; const n_int max_block_size = 8; n_uint i, total_matches=0, total_tests=0; n_uint histogram[5 + 1]; simulated_group * group = (simulated_group *) ptr; /* clear the histogram */ for (i = 0; i <= (n_uint)(max_block_size - min_block_size); i++) { histogram[i]=0; } if (group->select) { n_uint loop = 0; while (loop < group->num) { simulated_being * local_being = &(group->beings[loop]); n_byte * bc_external = being_braincode_external(local_being); if (bc_external) { n_uint loop2 = loop + 1; while (loop2 < group->num) { simulated_being * local_being2 = &(group->beings[loop2]); n_byte * bc_external2 = being_braincode_external(local_being2); if (bc_external2) { n_int location = 0; n_int block_size = min_block_size; while (block_size <= max_block_size) { location = command_compare_brain(bc_external, bc_external2, block_size); if (location != -1) { histogram[block_size-min_block_size]++; total_matches++; } total_tests++; block_size++; } } loop2++; } } loop++; } } if (total_tests > 0) { n_string_block output; sprintf(output, "Matches %03u.%04u percent\n", (n_c_int)(total_matches*100/total_tests), (n_c_int)(total_matches*1000000/total_tests)%10000); output_function(output); output_function("Block Percent Instances"); output_function("-------------------------"); for (i = 0; i <= (n_uint)(max_block_size - min_block_size); i++) { sprintf(output, "%02u %03u.%04u %04u", (n_c_int)(i+min_block_size), (n_c_int)(histogram[i]*100/total_tests), (n_c_int)((histogram[i]*1000000/total_tests)%10000), (n_c_int)histogram[i]); output_function(output); } } #endif return 0; } /** * Watch a particular being * @param ptr pointer to simulated_group object * @param response command parameters * @param output_function function to be used to display output * @return 0 */ n_int command_watch(void * ptr, n_string response, n_console_output output_function) { simulated_group * group = (simulated_group *) ptr; n_int length; n_string_block output; n_int position = 0; if (command_check_ape_present(ptr, output_function) == 0) { return 0; } if (response == 0L) { return 0; } else { length = io_length(response,STRING_BLOCK_SIZE); } if ((length<5) && (io_find(response,0,length,"off",3)>-1)) { output_function("Stopped watching"); watch_type=WATCH_NONE; return 0; } if ((length<10) && (io_find(response,0,length,"state",5)>-1)) { watch_type = WATCH_STATES; output_function("Watching being states"); return 0; } if (being_from_name(group, response) != 0) { being_set_select_name(group, response); io_string_write(output, "Watching ", &position); io_string_write(output, being_get_select_name(group), &position); output_function(output); position = 0; watch_type = WATCH_ALL; } else { if (group->select) { if (io_find(response,0,length,"braincode",9)>-1) { watch_type = WATCH_BRAINCODE; io_string_write(output, "Watching braincode for ", &position); io_string_write(output, being_get_select_name(group), &position); output_function(output); return 0; } if ((io_find(response,0,length,"brainprobe",10)>-1) || (io_find(response,0,length,"brain probe",11)>-1) || (io_find(response,0,length,"probes",6)>-1)) { watch_type = WATCH_BRAINPROBES; io_string_write(output, "Watching brain probes for ", &position); io_string_write(output, being_get_select_name(group), &position); output_function(output); return 0; } if ((io_find(response,0,length,"graph",5)>-1) || (io_find(response,0,length,"friend",6)>-1)) { watch_type = WATCH_SOCIAL_GRAPH; io_string_write(output, "Watching social graph for ", &position); io_string_write(output, being_get_select_name(group), &position); output_function(output); return 0; } if ((io_find(response,0,length,"episodic",8)>-1) || (io_find(response,0,length,"episodic memory",15)>-1) || (io_find(response,0,length,"memory",6)>-1)) { watch_type = WATCH_EPISODIC; io_string_write(output, "Watching episodic memory for ", &position); io_string_write(output, being_get_select_name(group), &position); output_function(output); return 0; } if (io_find(response,0,length,"speech",6)>-1) { watch_type = WATCH_SPEECH; io_string_write(output, "Watching speech for ", &position); io_string_write(output, being_get_select_name(group), &position); output_function(output); return 0; } if ((length<5) && (io_find(response,0,length,"all",3)>-1)) { watch_type = WATCH_ALL; io_string_write(output, "Watching ", &position); io_string_write(output, being_get_select_name(group), &position); output_function(output); return 0; } if (io_find(response,0,length,"appear",6)>-1) { watch_type = WATCH_APPEARANCE; io_string_write(output, "Watching appearance for ", &position); io_string_write(output, being_get_select_name(group), &position); output_function(output); return 0; } } output_function("Being not found\n"); } return 0; } /** * Set the time interval for simulation * @param ptr pointer to simulated_group object * @param response command parameters * @param output_function function used to display the output * @return 0 */ n_int command_interval(void * ptr, n_string response, n_console_output output_function) { n_int number=1,interval=INTERVAL_DAYS,interval_set=0; if (response != 0) { if (io_length(response, STRING_BLOCK_SIZE) > 0) { if (get_time_interval(response, &number, &interval) > -1) { if (number > 0) { n_string_block output, number_string; save_interval_steps = number * interval_steps[interval]; io_number_to_string(number_string, number); io_three_strings(output, "Logging interval set to ", number_string, (n_string)interval_description[interval], 0); output_function(output); interval_set=1; } } } } if (interval_set == 0) { if (save_interval_steps < 60) { n_string_block output, number_string; io_number_to_string(number_string, save_interval_steps); io_three_strings(output, "Current time interval is ",number_string, " min(s)",0); output_function(output); } else { if (save_interval_steps < 60*24) { n_string_block output, number_string; io_number_to_string(number_string, save_interval_steps/60); io_three_strings(output, "Current time interval is ",number_string, " hour(s)",0); output_function(output); } else { n_string_block output, number_string; io_number_to_string(number_string, save_interval_steps/(60*24)); io_three_strings(output, "Current time interval is ",number_string, " day(s)",0); output_function(output); } } } return 0; } n_int command_stop(void * ptr, n_string response, n_console_output output_function) { simulation_running = 0; if (output_function) { output_function("Simulation stopped"); } return 0; } /** * * @param ptr pointer to simulated_group * @param response response string * @param output_function output function */ n_int command_file(void * ptr, n_string response, n_console_output output_function) { io_search_file_format(simulated_file_format, response); return 0; } /** * Run the simulation for a single time interval * @param ptr pointer to simulated_group object * @param response command parameters * @param output_function function used to display the output * @return 0 */ n_int command_step(void * ptr, n_string response, n_console_output output_function) { simulated_group * group = (simulated_group *) ptr; n_uint loop = 0; if (response != RUN_STEP_CONST) { if (simulation_executing == 1) { output_function("Simulation already running"); return 0; } if (command_file_interaction) { output_function("File interaction in use: step"); return 0; } simulation_executing = 1; } simulation_running = 1; while ((loop < save_interval_steps) && simulation_running) { sim_cycle(); if (group->num == 0) { simulation_running = 0; } loop++; } if (response != RUN_STEP_CONST) { watch_being(group, output_function); } if (response != RUN_STEP_CONST) { simulation_executing = 0; } return 0; } /** * Run the simulation * @param ptr pointer to simulated_group object * @param response command parameters * @param output_function function used to display the output * @return 0 */ n_int command_run(void * ptr, n_string response, n_console_output output_function) { n_uint run = 0; n_int number = 0, interval = INTERVAL_DAYS; n_int forever = 0; if (simulation_executing == 1) { output_function("Simulation already running"); return 0; } if (command_file_interaction) { output_function("File interaction in use: run"); return 0; } simulation_executing = 1; simulation_running = 1; if (response != 0L) { n_int length = io_length(response,STRING_BLOCK_SIZE); if (length > 0) { if ((io_find(response,0,length,"forever",7)>-1)) { forever = 1; number = 1; } else if (get_time_interval(response, &number, &interval) <= -1) { number = -1; } if (number > 0) { n_uint i = 0; n_string_block output; n_uint end_point = (number * interval_steps[interval]); n_uint temp_save_interval_steps = save_interval_steps; n_uint count = 0; save_interval_steps = 1; if (forever) { io_three_strings(output, "Running forever (type \"stop\" to end)", "", "", 0); } else { n_string_block number_string; io_number_to_string(number_string, number); io_three_strings(output, "Running for ", number_string, (n_string)interval_description[interval], 0); } output_function(output); while ((i < end_point) && simulation_running) { command_step(ptr, RUN_STEP_CONST, output_function); if (temp_save_interval_steps) { if ((count % temp_save_interval_steps) == 0) { watch_being(ptr, output_function); } } count++; if (!forever) i++; } if (temp_save_interval_steps) { if ((count % temp_save_interval_steps) != 1) { watch_being(ptr, output_function); } } save_interval_steps = temp_save_interval_steps; run = 1; } } } simulation_executing = 0; if (run == 0) { (void)SHOW_ERROR("Time not specified, examples: run 2 days, run 6 hours"); } return 0; } /** * Reset the simulation * @param ptr pointer to simulated_group object * @param response command parameters * @param output_function function used to display the output * @return 0 */ n_int command_reset(void * ptr, n_string response, n_console_output output_function) { n_byte2 seed[2]; n_byte2 * local_land_genetics = land_genetics(); seed[0] = local_land_genetics[0]; seed[1] = local_land_genetics[1]; math_random3(seed); if (sim_init(KIND_NEW_SIMULATION, (n_uint)((seed[0]<<16)|seed[1]), MAP_AREA, 0)) { output_function("Simulation reset"); return 0; } output_function("Simulation has not enough memory"); return 1; } /** * Returns a mode value used by epic and top commands * @param response command parameter: female/male/juvenile * @return 0 */ static n_byte command_get_response_mode(n_string response) { n_int length; if (response == 0L) return 0; length = io_length(response,STRING_BLOCK_SIZE); if (response != 0) { /** females */ if (io_find(response,0,length,"fem",3)>-1) { return 1; } /** males */ if (io_find(response,0,length,"male",4)>-1) { return 2; } /** juveniles */ if ((io_find(response,0,length,"juv",3)>-1) || (io_find(response,0,length,"chil",4)>-1)) { return 3; } } return 0; } n_int command_speak(void * ptr, n_string response, n_console_output output_function) { n_string_block paragraph = {0}; simulated_group * group = (simulated_group *) ptr; simulated_being * local = group->select; watch_speech(ptr, 0L, local, paragraph); watch_string_length = 0; speak_out(response, paragraph); return 0; } n_int command_alphabet(void * ptr, n_string response, n_console_output output_function) { speak_out(response, " aeio a e i o vfstpbjm abefijmopstv a b e f i j m o p s t v. . \n"); return 0; } n_int command_save(void * ptr, n_string response, n_console_output output_function) { n_file * file_opened; n_string_block output_string; if (response == 0L) return 0; if (command_file_interaction) { if (output_function) { output_function("File interaction in use: save"); } return 0; } command_stop(ptr, "", output_function); file_opened = tranfer_out_json(); if (file_opened == 0L) { return SHOW_ERROR("Failed to generate output contents"); } command_file_interaction = 1; io_disk_write(file_opened, response); io_file_free(&file_opened); if (output_function) { n_int position = 0; io_string_write(command_file_name, response, &position); position = 0; io_string_write(output_string, "Simulation file ", &position); io_string_write(output_string, response, &position); io_string_write(output_string, " saved\n", &position); output_function(output_string); } command_file_interaction = 0; return 0; } /* load simulation-data/script */ static n_int command_base_open(void * ptr, n_string response, n_console_output output_function, n_byte script) { if (response == 0L) return 0; if (command_file_interaction) { if (output_function) { output_function("File interaction in use: open"); } return 0; } command_stop(ptr,"",output_function); command_file_interaction = 1; if (io_disk_check(response)!=0) { n_file * file_opened = io_file_new(); n_string_block output_string; if(io_disk_read(file_opened, response) != FILE_OKAY) { io_file_free(&file_opened); command_file_interaction = 0; return SHOW_ERROR("Failed to open file"); } if (script) { if (sim_interpret(file_opened) != 0) { io_file_free(&file_opened); command_file_interaction = 0; return SHOW_ERROR("Failed to interpret file"); } } else { if (tranfer_in(file_opened) != 0) { io_file_free(&file_opened); command_file_interaction = 0; return SHOW_ERROR("Failed to read in file"); } if (sim_init(KIND_LOAD_FILE, 0, MAP_AREA, 0) == 0L) { return SHOW_ERROR("Not enough memory to load file"); } io_file_free(&file_opened); } command_file_interaction = 0; if (output_function) { n_int position = 0; io_string_write(command_file_name, response, &position); position = 0; io_string_write(output_string, "Simulation file ", &position); io_string_write(output_string, response, &position); io_string_write(output_string, " open\n", &position); output_function(output_string); } } return 0; } /* load simulation data */ n_int command_open(void * ptr, n_string response, n_console_output output_function) { return command_base_open(ptr, response, output_function, 0); } /* load apescript file */ n_int command_script(void * ptr, n_string response, n_console_output output_function) { return command_base_open(ptr, response, output_function, 1); } /** * Displays beings in descending order of honor value * @param ptr pointer to simulated_group object * @param response command parameters * @param output_function function used to display the output * @return 0 */ n_int command_top(void * ptr, n_string response, n_console_output output_function) { simulated_group * group = (simulated_group *) ptr; n_uint i,j; n_int k; n_uint max=10; n_byte * eliminated; n_uint current_date,local_dob,age_in_years,age_in_months,age_in_days; n_string_block str; simulated_being * b; n_byte mode = command_get_response_mode(response); output_function("Honor Name Sex\tAge"); output_function("-----------------------------------------------------------------"); eliminated = (n_byte *)memory_new(group->num*sizeof(n_byte)); for (i = 0; i < group->num; i++) eliminated[i] = 0; if (group->num < max) max = group->num; for (i = 0; i < max; i++) { n_int winner = -1; n_int max_honor = 0; n_byte passed; n_string_block output_value; for (j = 0; j < group->num; j++) { if (eliminated[j] == 0) { n_int honor; b = &group->beings[j]; honor = being_honor(b); if (honor >= max_honor) { passed=0; switch(mode) { case 0: { passed=1; break; } case 1: { if (FIND_SEX(GET_I(b)) == SEX_FEMALE) passed=1; break; } case 2: { if (FIND_SEX(GET_I(b)) != SEX_FEMALE) passed=1; break; } case 3: { if (AGE_IN_DAYS(b)<AGE_OF_MATURITY) passed=1; break; } } if (passed!=0) { winner = (n_int)j; max_honor = honor; } } } } if (winner==-1) break; eliminated[winner] = 1; b = &group->beings[winner]; sprintf(output_value, "%03d ", (int)(being_honor(b))); being_name_simple(b, str); io_three_strings(output_value, output_value, str, "", 0); for (k=0; k<25-io_length(str,STRING_BLOCK_SIZE); k++) { io_three_strings(output_value, output_value, " ", "", 0); } if (FIND_SEX(GET_I(b)) == SEX_FEMALE) { io_three_strings(output_value, output_value, "Female\t", "", 0); } else { io_three_strings(output_value, output_value, "Male\t", "", 0); } current_date = land_date(); local_dob = (n_uint)being_dob(b); age_in_years = (n_uint)AGE_IN_YEARS(b); age_in_months = ((current_date - local_dob) - (age_in_years * TIME_YEAR_DAYS)) / (TIME_YEAR_DAYS/12); age_in_days = (current_date - local_dob) - ((TIME_YEAR_DAYS/12) * age_in_months) - (age_in_years * TIME_YEAR_DAYS); if (age_in_years>0) { n_string_block number; io_number_to_string(number, age_in_years); io_three_strings(output_value, output_value, number, " yrs ", 0 ); } if (age_in_months>0) { n_string_block number; io_number_to_string(number, age_in_months); io_three_strings(output_value, output_value, number, " mnths ", 0 ); } { n_string_block number; io_number_to_string(number, age_in_days); io_three_strings(output_value, output_value, number, " days", 0 ); } output_function(output_value); } memory_free((void**)&eliminated); return 0; } n_int command_debug(void * ptr, n_string response, n_console_output output_function) { command_audit(); return 0; } /** * Lists the most talked about beings, based upon episodic memories * @param ptr pointer to simulated_group object * @param response command parameters * @param output_function function used to display the output * @return 0 */ n_int command_epic(void * ptr, n_string response, n_console_output output_function) { simulated_group * group = (simulated_group *) ptr; n_uint i, j, k, e; simulated_being * local_being; simulated_iepisodic * local_episodic; const n_uint max = 1024; n_byte2 * first_name = (n_byte2*)memory_new(max*sizeof(n_byte2)); n_byte2 * family_name = (n_byte2*)memory_new(max*sizeof(n_byte2)); n_byte2 * hits = (n_byte2*)memory_new(max*sizeof(n_byte2)); n_byte2 temp; n_string_block name; n_byte passed,mode = command_get_response_mode(response); /** clear the list of beings and their hit scores */ for (i = 0; i < max; i++) { first_name[i] = 0; family_name[i] = 0; hits[i] = 0; } for (i = 0; i < group->num; i++) { /** get the being */ local_being = &group->beings[i]; /** get the episodic memories for the being */ local_episodic = being_episodic(local_being); /** skip is no memories were retrieved */ if (local_episodic == 0L) continue; /** for all memories */ for (e = 0; e < EPISODIC_SIZE; e++) { /** non-empty slot */ if (local_episodic[e].event > 0) { /** j = 0 is the being having the memory j = 1 is the being who is the subject of the memory */ for (j = BEING_MEETER; j <= BEING_MET; j++) { /** name should be non-zero */ if (local_episodic[e].first_name[j] + local_episodic[e].family_name[j] > 0) { passed=0; switch(mode) { case 0: { passed=1; break; } case 1: { if ((local_episodic[e].first_name[j]>>8) == SEX_FEMALE) passed=1; break; } case 2: { if ((local_episodic[e].first_name[j]>>8) != SEX_FEMALE) passed=1; break; } case 3: { simulated_being * b=0L; n_string_block name; being_name_byte2(local_episodic[e].first_name[j], local_episodic[e].family_name[j], name); b = being_from_name(group, name); if (b!=0L) { if (AGE_IN_DAYS(b)<AGE_OF_MATURITY) passed=1; } break; } } if (passed != 0) { /** Avoid memories about yourself, since we're interested in gossip about other beings */ if (being_name_comparison(local_being, local_episodic[e].first_name[j], local_episodic[e].family_name[j])) { if (((j == BEING_MET) && (local_episodic[e].event != EVENT_SEEK_MATE) && (local_episodic[e].event != EVENT_EAT)) || (j == BEING_MEETER)) { /** add this being to the list, or increment its hit score */ for (k = 0; k < max; k++) { if (hits[k] == 0) /**< last entry in the list */ { first_name[k] = local_episodic[e].first_name[j]; family_name[k] = local_episodic[e].family_name[j]; break; } if (first_name[k] == local_episodic[e].first_name[j]) { if (family_name[k] == local_episodic[e].family_name[j]) { /** being found in the list */ break; } } } /** increment the hit score for the being */ if (k < max) hits[k]++; } } } } } } } } /** top 10 most epic beings */ for (i = 0; i < 10; i++) { /** search the rest of the list */ for (j = i+1; j < max; j++) { if (hits[j] == 0) break; /**< end of the list */ /** if this being has more hits then swap list entries, so that the most popular beings are at the top of the list */ if (hits[j] > hits[i]) { /** swap */ temp = first_name[j]; first_name[j] = first_name[i]; first_name[i] = temp; temp = family_name[j]; family_name[j] = family_name[i]; family_name[i] = temp; temp = hits[j]; hits[j] = hits[i]; hits[i] = temp; } } if (hits[i] > 0) { n_string_block output_value; /** get the name of the being */ being_name_byte2(first_name[i], family_name[i], name); sprintf(output_value, "%06d %s", (int)hits[i], name); output_function(output_value); } } /** free list memory */ memory_free((void**)&first_name); memory_free((void**)&family_name); memory_free((void**)&hits); return 0; } n_int command_quit(void * ptr, n_string response, n_console_output output_function) { simulation_executing = 0; (void)command_stop(ptr, response, output_function); return io_quit(ptr, response, output_function); } <|start_filename|>sim/tile.c<|end_filename|> /**************************************************************** tile.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #include "../toolkit/toolkit.h" #include "sim.h" #define tile_wind_aim (-96 + (math_random(land->genetics) % 194)) #define tile_wind_dissipation (math_random(land->genetics) & 3) #define bits_neg ((-131072 * 254) / 256) #define bits_pos (( 131071 * 254) / 256) /* +---------+ | C | |A 0 B| A | | B C +---------+---------+---------+---------+ | | | | | | 1 | 2 | 3 | 4 | | | | | | +---------+---------+---------+---------+ D | | E F |D 5 E| | F | +---------+ */ static void tile_coordinate_rotate(n_tile_coordinates * coordinates, n_int rotate90, n_int tile) { n_int pos_x = (coordinates->x + MAP_DIMENSION) & (MAP_DIMENSION-1); n_int pos_y = (coordinates->y + MAP_DIMENSION) & (MAP_DIMENSION-1); n_uint pos_facing = coordinates->facing; if (rotate90 == 0) { coordinates->x = pos_x; coordinates->y = pos_y; } if (rotate90 == 1) { coordinates->facing = (pos_facing + 64) & 255; coordinates->x = pos_y; coordinates->y = MAP_DIMENSION - 1 - pos_x; } if (rotate90 == 2) { coordinates->facing = (pos_facing + 128) & 255; coordinates->x = MAP_DIMENSION - 1 - pos_x; coordinates->y = MAP_DIMENSION - 1 - pos_y; } if (rotate90 == 3) { coordinates->facing = (pos_facing + 64 + 128) & 255; coordinates->x = MAP_DIMENSION - 1 - pos_y; coordinates->y = pos_x; } coordinates->tile = tile; } void tile_resolve_coordinates(n_tile_coordinates * coordinates) { n_int pos_x = (coordinates->x >= MAP_DIMENSION) - (coordinates->x < 0); n_int pos_y = (coordinates->y >= MAP_DIMENSION) - (coordinates->y < 0); if ((pos_x == 0) && (pos_y == 0)) { return; } if (pos_y == 0) { if ((coordinates->tile > 0) && (coordinates->tile < 5)) { n_int new_x = (coordinates->x + MAP_DIMENSION) & (MAP_DIMENSION - 1); n_int new_tile = coordinates->tile; if (pos_x < 0) { if (new_tile == 1) /* moving leftwards */ { new_tile = 4; } else { new_tile--; } } else { if (new_tile == 4) /* moving rightwards */ { new_tile = 1; } else { new_tile++; } } coordinates->tile = new_tile; coordinates->x = new_x; } else { if (coordinates->tile == 0) { if (pos_x < 0) { /* A */ tile_coordinate_rotate(coordinates, 3, 1); } else { /* B */ tile_coordinate_rotate(coordinates, 1, 3); } } else /* coordinates->tile == 5 */ { if (pos_x < 0) { /* D */ tile_coordinate_rotate(coordinates, 3, 1); } else { /* E */ tile_coordinate_rotate(coordinates, 1, 3); } } /* +---------+ | C | |A 0 B| A | | B C +---------+---------+---------+---------+ | | | | | | 1 | 2 | 3 | 4 | | | | | | +---------+---------+---------+---------+ D | | E F |D 5 E| | F | +---------+ */ } } else if (pos_x == 0) { if ((coordinates->tile == 0) || (coordinates->tile == 2) || (coordinates->tile == 5)) { n_int new_y = (coordinates->y + MAP_DIMENSION) & (MAP_DIMENSION - 1); n_int new_tile = -1; if (pos_y < 0) { if (coordinates->tile == 0) tile_coordinate_rotate(coordinates, 2, 4); if (coordinates->tile == 2) new_tile = 0; if (coordinates->tile == 5) new_tile = 2; } else { if (coordinates->tile == 0) new_tile = 2; if (coordinates->tile == 2) new_tile = 5; if (coordinates->tile == 5) /* F */ tile_coordinate_rotate(coordinates, 2, 4); } if (new_tile != -1) { coordinates->tile = new_tile; coordinates->y = new_y; } } else { /* +---------+ | C | |A 0 B| A | | B C +---------+---------+---------+---------+ | | | | | | 1 | 2 | 3 | 4 | | | | | | +---------+---------+---------+---------+ D | | E F |D 5 E| | F | +---------+ */ if (pos_y < 0) { if (coordinates->tile == 1) { /* A */ tile_coordinate_rotate(coordinates, 1, 0); } if (coordinates->tile == 3) { /* B */ tile_coordinate_rotate(coordinates, 3, 0); } if (coordinates->tile == 4) { /* C */ tile_coordinate_rotate(coordinates, 2, 0); } } else { if (coordinates->tile == 1) { /* D */ tile_coordinate_rotate(coordinates, 3, 5); } if (coordinates->tile == 3) { /* E */ tile_coordinate_rotate(coordinates, 1, 5); } if (coordinates->tile == 4) { /* F */ tile_coordinate_rotate(coordinates, 2, 5); } } } } else { if (coordinates->x > (MAP_DIMENSION-1)) { coordinates->x = (MAP_DIMENSION-1); }else if (coordinates->x < 0) { coordinates->x = 0; } if (coordinates->y > (MAP_DIMENSION-1)) { coordinates->y = (MAP_DIMENSION-1); }else if (coordinates->y < 0) { coordinates->y = 0; } } } static void tile_wrap(n_land * land, n_int tile) { n_c_int * section = land->tiles[tile].atmosphere[1]; n_int placement = 0; while (placement < (MAP_AREA)) { n_c_int value = section[placement]; section[placement++] = (value * 253) / 256; } } static void title_wind_calculation(n_land * land) { if ((math_random(land->genetics) & 31) == 0) { land->wind_aim_x = tile_wind_aim; math_random3(land->genetics); land->wind_aim_y = tile_wind_aim; land->wind_dissipation = tile_wind_dissipation; } if (land->wind_aim_x > land->wind_value_x) { land->wind_value_x++; } if (land->wind_aim_x < land->wind_value_x) { land->wind_value_x--; } if (land->wind_aim_y > land->wind_value_y) { land->wind_value_y++; } if (land->wind_aim_y < land->wind_value_y) { land->wind_value_y--; } } static void tile_pressure_range(n_tile * tile, n_byte2 value) { if (value > tile->delta_pressure_highest) { tile->delta_pressure_highest = value; } if (value < tile->delta_pressure_lowest) { tile->delta_pressure_lowest = value; } } static void tile_atmosphere_range(n_land * land, n_int tile, n_c_int value) { n_tile * tilePtr = &land->tiles[tile]; if (value > tilePtr->atmosphere_highest) { tilePtr->atmosphere_highest = value; } if (value < tilePtr->atmosphere_lowest) { tilePtr->atmosphere_lowest = value; } } static n_uint tiles_non_planet(n_int lx, n_int ly) { n_int converted_x = (lx + MAP_DIMENSION) & (MAP_DIMENSION - 1); n_int converted_y = (ly + MAP_DIMENSION) & (MAP_DIMENSION - 1); return (n_uint)(converted_x | (converted_y * MAP_DIMENSION)); } n_c_int tiles_atmosphere(n_land * land, n_int tile, n_int buffer, n_int lx, n_int ly) { #ifdef SIMULATED_PLANET n_tile_coordinates coord; coord.facing = 0; coord.tile = tile; coord.x = lx; coord.y = ly; tile_resolve_coordinates(&coord); return land->tiles[coord.tile].atmosphere[buffer][tiles_non_planet(coord.x, coord.y)]; #else return land->tiles[tile].atmosphere[buffer][tiles_non_planet(lx, ly)]; #endif } static void tiles_set_atmosphere(n_land * land, n_int tile, n_int buffer, n_int lx, n_int ly, n_c_int value) { #ifdef SIMULATED_PLANET n_tile_coordinates coord; coord.facing = 0; coord.tile = tile; coord.x = lx; coord.y = ly; tile_resolve_coordinates(&coord); land->tiles[coord.tile].atmosphere[buffer][tiles_non_planet(coord.x, coord.y)] = value; #else land->tiles[tile].atmosphere[buffer][tiles_non_planet(lx, ly)] = value; #endif } static void tiles_swap_atmosphere(n_land * land, n_int tile) { memory_copy((n_byte *)land->tiles[tile].atmosphere[1], (n_byte *)land->tiles[tile].atmosphere[0], (sizeof(n_c_int) * MAP_AREA)); } static n_byte2 tiles_pressure(n_land * land, n_int tile, n_int lx, n_int ly) { #ifdef SIMULATED_PLANET n_tile_coordinates coord; coord.facing = 0; coord.tile = tile; coord.x = lx; coord.y = ly; tile_resolve_coordinates(&coord); return land->tiles[coord.tile].delta_pressure[tiles_non_planet(coord.x, coord.y)]; #else return land->tiles[tile].delta_pressure[tiles_non_planet(lx, ly)]; #endif } static void tiles_set_pressure(n_land * land, n_int tile, n_int lx, n_int ly, n_byte2 value) { #ifdef SIMULATED_PLANET n_tile_coordinates coord; coord.facing = 0; coord.tile = tile; coord.x = lx; coord.y = ly; tile_resolve_coordinates(&coord); land->tiles[coord.tile].delta_pressure[tiles_non_planet(coord.x, coord.y)] = value; #else land->tiles[tile].delta_pressure[tiles_non_planet(lx, ly)] = value; #endif } n_byte * tiles_topography_map(n_land * land, n_int tile, n_int buffer) { return (n_byte *) land->tiles[tile].topography[buffer]; } n_byte tiles_topography(n_land * land, n_int tile, n_int buffer, n_int lx, n_int ly) { #ifdef SIMULATED_PLANET n_tile_coordinates coord; coord.facing = 0; coord.tile = tile; coord.x = lx; coord.y = ly; tile_resolve_coordinates(&coord); return land->tiles[coord.tile].topography[buffer][tiles_non_planet(coord.x, coord.y)]; #else return land->tiles[tile].topography[buffer][tiles_non_planet(lx, ly)]; #endif } static void tiles_set_topography(n_land * land, n_int tile, n_int buffer, n_int lx, n_int ly, n_byte value) { #ifdef SIMULATED_PLANET n_tile_coordinates coord; coord.facing = 0; coord.tile = tile; coord.x = lx; coord.y = ly; tile_resolve_coordinates(&coord); land->tiles[coord.tile].topography[buffer][tiles_non_planet(coord.x, coord.y)] = value; #else land->tiles[tile].topography[buffer][tiles_non_planet(lx, ly)] = value; #endif } static void tiles_swap_topography(n_land * land, n_int tile) { memory_copy((n_byte *)&land->tiles[tile].topography[0], (n_byte *)&land->tiles[tile].topography[1], MAP_AREA); } static void title_pack_atmosphere(n_land * land, n_int tile) { n_int loop = 0; while (loop < MAP_AREA) { land->tiles[tile].atmosphere[0][loop] = 0; loop++; } } static void title_pack_topography(n_land * land, n_int tile) { n_int loop = 0; while (loop < MAP_AREA) { land->tiles[tile].topography[0][loop] = 128; loop++; } } static void tile_atmosphere_topography(n_land * land, n_int tile) { n_int loop = 0; while ( loop < MAP_AREA ) { land->tiles[tile].atmosphere[0][ loop ] = (n_c_int)(land->tiles[tile].topography[0][ loop ] * 4); loop++; } } void tile_cycle(n_land * land) { const n_c_int dissipation = (n_c_int)(land->wind_dissipation + 1020); n_int tile = 0; while (tile < MAP_TITLES) { n_int new_delta = 0; n_int ly = 0; land->tiles[tile].atmosphere_lowest = bits_pos; land->tiles[tile].atmosphere_highest = bits_neg; while ( ly < MAP_DIMENSION ) { n_int lx = 0; while ( lx < MAP_DIMENSION ) { n_c_int value = (dissipation * tiles_atmosphere(land, tile, 0, lx, ly)) >> 10; n_int local_atm = (2 * tiles_atmosphere(land, tile, 0, lx, ly-1)) + (2 * tiles_atmosphere(land, tile, 0, lx-1, ly)) - (2 * tiles_atmosphere(land, tile, 0, lx+1, ly)) - (2 * tiles_atmosphere(land, tile, 0, lx, ly+1)); value += (n_c_int) ((local_atm - land->tiles[tile].local_delta) >> MAP_BITS) + tiles_pressure(land, 0, lx, ly); tiles_set_atmosphere(land, tile, 1, lx, ly, value); new_delta += value; tile_atmosphere_range(land, tile, value); lx++; } ly++; } land->tiles[tile].local_delta = new_delta >> MAP_BITS; tile++; } tile = 0; while (tile < MAP_TITLES) { tiles_swap_atmosphere(land, tile); tile++; } } static void tile_wind_pp(n_land * land) { n_int tile = 0; /* Add dynamic wind */ const n_int p01 = land->wind_value_x, p10 = land->wind_value_y; while (tile < MAP_TITLES) { n_int ly = 0; while ( ly < MAP_DIMENSION ) { n_int lx = 0; while ( lx < MAP_DIMENSION ) { n_int delta_pressure = tiles_pressure(land, tile, lx, ly); n_int tp01 = (p01 * delta_pressure) / land->tiles[tile].delta_pressure_highest; n_int tp10 = (p10 * delta_pressure) / land->tiles[tile].delta_pressure_highest; n_int tp00 = 256 - tp01 - tp10; n_int local_atm = (tp00 * tiles_atmosphere(land, tile, 0,lx, ly)) + (tp10 * tiles_atmosphere(land, tile, 0,lx, ly+1)) + (tp01 * tiles_atmosphere(land, tile, 0,lx+1, ly)); tiles_set_atmosphere(land, tile, 1, lx, ly, (n_c_int)local_atm >> 8); lx++; } ly++; } tile++; } } static void tile_wind_np(n_land * land) { n_int tile = 0; /* Add dynamic wind */ const n_int p01 = land->wind_value_x, p10 = 0 - land->wind_value_y; while (tile < MAP_TITLES) { n_int ly = 0; while ( ly < MAP_DIMENSION ) { n_int lx = 0; while ( lx < MAP_DIMENSION ) { n_int delta_pressure = tiles_pressure(land, tile, lx, ly); n_int tp01 = (p01 * delta_pressure) / land->tiles[tile].delta_pressure_highest; n_int tp10 = (p10 * delta_pressure) / land->tiles[tile].delta_pressure_highest; n_int tp00 = 256 - tp01 - tp10; n_int local_atm = (tp00 * tiles_atmosphere(land, tile, 0,lx, ly)) + (tp10 * tiles_atmosphere(land, tile, 0,lx, ly-1)) + (tp01 * tiles_atmosphere(land, tile, 0,lx+1, ly)); tiles_set_atmosphere(land, tile, 1, lx, ly, (n_c_int)local_atm >> 8); lx++; } ly++; } tile++; } } static void tile_wind_pn(n_land * land) { n_int tile = 0; /* Add dynamic wind */ const n_int p01 = 0-land->wind_value_x, p10 = land->wind_value_y; while (tile < MAP_TITLES) { n_int ly = 0; while ( ly < MAP_DIMENSION ) { n_int lx = 0; while ( lx < MAP_DIMENSION ) { n_int delta_pressure = tiles_pressure(land, tile, lx, ly); n_int tp01 = (p01 * delta_pressure) / land->tiles[tile].delta_pressure_highest; n_int tp10 = (p10 * delta_pressure) / land->tiles[tile].delta_pressure_highest; n_int tp00 = 256 - tp01 - tp10; n_int local_atm = (tp00 * tiles_atmosphere(land, tile, 0,lx, ly)) + (tp10 * tiles_atmosphere(land, tile, 0,lx, ly+1)) + (tp01 * tiles_atmosphere(land, tile, 0,lx-1, ly)); tiles_set_atmosphere(land, tile, 1, lx, ly, (n_c_int)local_atm >> 8); lx++; } ly++; } tile++; } } static void tile_wind_nn(n_land * land) { n_int tile = 0; /* Add dynamic wind */ const n_int p01 = 0 - land->wind_value_x, p10 = 0 - land->wind_value_y; while (tile < MAP_TITLES) { n_int ly = 0; while ( ly < MAP_DIMENSION ) { n_int lx = 0; while ( lx < MAP_DIMENSION ) { n_int delta_pressure = tiles_pressure(land, tile, lx, ly); n_int tp01 = (p01 * delta_pressure) / land->tiles[tile].delta_pressure_highest; n_int tp10 = (p10 * delta_pressure) / land->tiles[tile].delta_pressure_highest; n_int tp00 = 256 - tp01 - tp10; n_int local_atm = (tp00 * tiles_atmosphere(land, tile, 0,lx, ly)) + (tp10 * tiles_atmosphere(land, tile, 0,lx, ly-1)) + (tp01 * tiles_atmosphere(land, tile, 0,lx-1, ly)); tiles_set_atmosphere(land, tile, 1, lx, ly, (n_c_int)local_atm >> 8); lx++; } ly++; } tile++; } } void tile_wind(n_land * land) { n_int tile = 0, p01, p10; title_wind_calculation(land); p01 = land->wind_value_x; p10 = land->wind_value_y; if (p01 > -1) { if (p10 > -1) { tile_wind_pp(land); } else { tile_wind_np(land); } }else { if (p10 > -1) { tile_wind_pn(land); } else { tile_wind_nn(land); } } while (tile < MAP_TITLES) { if ((land->tiles[tile].atmosphere_lowest < bits_neg) || (land->tiles[tile].atmosphere_highest > bits_pos)) { tile_wrap(land, tile); } tile++; } tile = 0; while (tile < MAP_TITLES) { tiles_swap_atmosphere(land, tile); tile++; } } void tile_weather_init(n_land * land) { n_int tile = 0; land->wind_value_x = tile_wind_aim; land->wind_aim_y = tile_wind_aim; math_random3(land->genetics); land->wind_value_y = tile_wind_aim; land->wind_aim_x = tile_wind_aim; land->wind_dissipation = tile_wind_dissipation; while (tile < MAP_TITLES) { n_tile * tilePtr = &land->tiles[tile]; math_random3(tilePtr->genetics); tilePtr->local_delta = 0; tilePtr->delta_pressure_lowest = 0xffff; tilePtr->delta_pressure_highest = 1; memory_erase((n_byte *)tilePtr->atmosphere, sizeof(n_c_int) * MAP_AREA); memory_erase((n_byte *)tilePtr->delta_pressure, sizeof(n_byte2) * MAP_AREA); tile_atmosphere_topography(land, tile); tile++; } tile = 0; while (tile < MAP_TITLES) { n_int ly = 0; while ( ly < MAP_DIMENSION ) { n_int lx = 0; while ( lx < MAP_DIMENSION ) { n_byte2 value = (n_byte2)( tiles_atmosphere(land, tile, 0, lx + 1, ly) - tiles_atmosphere(land, tile, 0, lx - 1, ly) + tiles_atmosphere(land, tile, 0, lx, ly + 1) - tiles_atmosphere(land, tile, 0, lx, ly - 1) + 512); tiles_set_pressure(land, tile, lx, ly, value); tile_pressure_range(&land->tiles[tile], value); lx++; } ly++; } tile++; } tile = 0; #ifndef FAST_START_UNREALISTIC_INITIAL_WEATHER while (tile < MAP_TITLES) #else while (tile < (MAP_TITLES/2)) #endif { title_pack_atmosphere(land, tile); tile++; } } void tile_land_erase(n_land * land) { n_byte2 save_genetics[MAP_TITLES][2]; n_int tile = 0; while (tile < MAP_TITLES) { save_genetics[tile][0] = land->tiles[tile].genetics[0]; save_genetics[tile][1] = land->tiles[tile].genetics[1]; tile++; } memory_erase((n_byte *)land, sizeof(n_land)); tile = 0; while (tile < MAP_TITLES) { land->tiles[tile].genetics[0] = save_genetics[tile][0]; land->tiles[tile].genetics[1] = save_genetics[tile][1]; title_pack_topography(land, tile); tile++; } } static void tile_round(n_land * land, n_int tile) { n_int local_tile_dimension = 1 << MAP_BITS; n_int span_minor = 0; /** Perform four nearest neighbor blur runs */ while (span_minor < 6) { n_int py = 0; while (py < local_tile_dimension) { n_int px = 0; while (px < local_tile_dimension) { n_int sum = 0; n_int ty = -1; while (ty < 2) { n_int tx = -1; while (tx < 2) { sum += tiles_topography(land, tile, (span_minor&1), px + tx, py + ty); tx++; } ty++; } tiles_set_topography(land, tile, (span_minor&1)^1, px, py, (n_byte)(sum / 9)); px ++; } py ++; } span_minor ++; } } static void tile_patch(n_land * land, n_int tile, n_int refine) { /** size of the local tiles */ /** number of 256 x 256 tiles in each dimension */ const n_int local_tiles = 1 << (MAP_BITS-8); const n_int span_minor = (64 >> ((refine&7)^7)); const n_int span_major = (1 << ((refine&7)^7)); n_int tile_y = 0; /** begin the tile traversal in the y dimension */ while (tile_y < local_tiles) { /** begin the tile traversal in the x dimension */ n_int tile_x = 0; while (tile_x < local_tiles) { /** scan through the span_minor values */ n_int py = 0; while (py < span_minor) { n_int px = 0; while (px < span_minor) { /** each of the smaller tiles are based on 256 * 256 tiles */ n_int val1 = ((px << 2) + (py << 10)); n_int ty = 0; n_int tseed = math_random(land->tiles[tile].genetics); while (ty < 4) { n_int tx = 0; while (tx < 4) { n_int val2 = (tseed >> (tx | (ty << 2))); n_int val3 = ((((val2 & 1) << 1)-1) * 20); n_int my = 0; val2 = (tx | (ty << 8)); while (my < span_major) { n_int mx = 0; while (mx < span_major) { n_int point = ((mx | (my << 8)) + (span_major * (val1 + val2))); n_int pointx = (point & 255); n_int pointy = (point >> 8); /** perform rotation on 2,3,6,7,10,11 etc */ if (refine&2) { n_int pointx_tmp = pointx + pointy; pointy = pointx - pointy; pointx = pointx_tmp; } { /** include the wrap around for the 45 degree rotation cases in particular */ n_int local_map_point = tiles_topography(land, tile, 0, pointx + (tile_x<<8), pointy + (tile_y<<8)) + val3; if (local_map_point < 0) local_map_point = 0; if (local_map_point > 255) local_map_point = 255; tiles_set_topography(land, tile, 0, pointx + (tile_x<<8), pointy + (tile_y<<8), (n_byte)local_map_point); } mx++; } my++; } tx++; } ty++; } px++; } py++; } tile_x++; } tile_y++; } } static n_int tile_memory_location(n_int px, n_int py) { #define POSITIVE_TILE_COORD(num) ((num+(3*MAP_DIMENSION))&(MAP_DIMENSION-1)) return POSITIVE_TILE_COORD(px) + (POSITIVE_TILE_COORD(py) << MAP_BITS); } void tile_land_init(n_land * land) { n_int refine = 0; while (refine < 7) { n_int tile = 0; while (tile < MAP_TITLES) { tile_patch(land, tile, refine); tile++; } tile = 0; while (tile < MAP_TITLES) { tile_round(land, tile); tile++; } tile = 0; while (tile < MAP_TITLES) { tiles_swap_topography(land, tile); tile++; } refine++; } } void tile_land_random(n_land * land, n_byte2 * random) { n_int tile = 0; while (tile < MAP_TITLES) { land->tiles[tile].genetics[0] = (n_byte2)(((math_random(random) & 255) << 8) | (math_random(random) & 255)); land->tiles[tile].genetics[1] = (n_byte2)(((math_random(random) & 255) << 8) | (math_random(random) & 255)); math_random3(random); tile++; } land->genetics[0] = (n_byte2)(((math_random(random) & 255) << 8) | (math_random(random) & 255)); land->genetics[1] = (n_byte2)(((math_random(random) & 255) << 8) | (math_random(random) & 255)); } <|start_filename|>test/example4b.json<|end_filename|> {"general_variables":"test","general_variables2":{"general_variables3":{"general_variables2":-12345}},"general_variables3":"test"} <|start_filename|>universe/universe_internal.h<|end_filename|> /**************************************************************** universe_internal.h ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #ifndef SIMULATEDAPE_UNIVERSE_INTERNAL_H #define SIMULATEDAPE_UNIVERSE_INTERNAL_H #define USE_FIL_VER #define USE_FIL_LAN #define USE_FIL_BEI #undef USE_FIL_SOE #undef USE_FIL_EPI #undef USE_FIL_WEA #undef USE_FIL_BRA /* Land - References */ #undef REDUCE_FILE /* Time definitions */ #define GENERATIONS_BYTES (sizeof(n_byte)*4) #define DRIVES_BYTES (DRIVES) #define GOALS_BYTES (sizeof(n_byte2)*3) #define SOCIAL_BYTES ((SOCIAL_SIZE*sizeof(simulated_isocial))+(2*4)) #ifdef EPISODIC_ON #define EPISODIC_BYTES (EPISODIC_SIZE*sizeof(simulated_iepisodic)) #else #define EPISODIC_BYTES 0 #endif #ifdef BRAINCODE_ON #define BRAINCODE_BYTES (BRAINCODE_SIZE) #define BRAINCODE_PROBE_BYTES (BRAINCODE_PROBES*sizeof(simulated_ibrain_probe)) #else #define BRAINCODE_BYTES 0 #define BRAINCODE_PROBE_BYTES 0 #endif #ifdef TERRITORY_ON #define TERRITORY_BYTES (TERRITORY_AREA*sizeof(simulated_iplace)) #else #define TERRITORY_BYTES 0 #endif #define PARA_BYTES 2 #define PARA_ENTRIES 2 #ifdef IMMUNE_ON #define IMMUNE_BYTES (sizeof(simulated_immune_system)) #else #define IMMUNE_BYTES 0 #endif #define GENETICS_BYTES (sizeof(n_genetics)*CHROMOSOMES) #define GENETICS_ENTRIES 1 #define PARENT_BYTES (9+(GENETICS_BYTES*2)) #define INVENTORY_BYTES (INVENTORY_SIZE*sizeof(n_byte2)) /* offsets within the file */ #define INITIAL_BLOCK_BYTES (40+INVENTORY_BYTES) #define OFFSET_PARASITES (INITIAL_BLOCK_BYTES+SHOUT_BYTES) #define OFFSET_PARENTING (OFFSET_PARASITES+PARA_BYTES) #define OFFSET_GENETICS (OFFSET_PARENTING+14+GENETICS_BYTES+(CHROMOSOMES*4)) #define OFFSET_SOCIAL (OFFSET_GENETICS+GENETICS_BYTES) #define OFFSET_EPISODIC (OFFSET_SOCIAL+SOCIAL_BYTES) #define OFFSET_TERRITORY (OFFSET_EPISODIC+EPISODIC_BYTES+DRIVES_BYTES+GOALS_BYTES+PREFERENCES+GENERATIONS_BYTES) #define OFFSET_IMMUNE ((OFFSET_GENETICS+GENETICS_BYTES+DRIVES_BYTES+6+PREFERENCES+GENERATIONS_BYTES+8)+TERRITORY_BYTES) #define OFFSET_VASCULAR (OFFSET_IMMUNE+IMMUNE_BYTES) #define OFFSET_METABOLISM (OFFSET_VASCULAR) #define OFFSET_BRAINCODE (OFFSET_METABOLISM) enum file_section_type { FIL_VER = (0x10), FIL_LAN = (0x20), FIL_BEI = (0x30), FIL_SOE = (0x40), FIL_EPI = (0x50), FIL_WEA = (0x60), FIL_BRA = (0x70), FIL_END = (0x80) }; static const simulated_file_entry simulated_file_format[]= { #ifdef USE_FIL_VER {"simul{", FIL_VER, 0, 0, "Simulation Version Definition"}, {"signa=", FIL_VER | FILE_TYPE_BYTE2, 1, 0, "Simulation signature"}, {"verio=", FIL_VER | FILE_TYPE_BYTE2, 1, 2, "Simulation version number"}, #endif #ifdef USE_FIL_LAN {"landd{", FIL_LAN, 0, 0, "land definition"}, {"dated=", FIL_LAN | FILE_TYPE_BYTE4, 1, 0, "Date in days and millenia"}, {"timed=", FIL_LAN | FILE_TYPE_BYTE2, 1, 4, "Time in minutes"}, {"landg=", FIL_LAN | FILE_TYPE_BYTE2, 2, 6, "Seed that created the land"}, #endif /* the line above is a substantial limit to the simulation space. The weather will limit the map area to; ((sizeof(n_int)/2) * (MAP_AREA)/(256*256)) <= 255 */ #ifdef USE_FIL_WEA {"weath{", FIL_WEA, 0, 0}, {"press=", FIL_WEA | FILE_TYPE_BYTE, sizeof(n_c_int), 0}, #endif #ifndef REDUCE_FILE /* FILE_TYPE_PACKED has a different form - no offset and the number is the size of the PACKED_DATA_BLOCK units */ /* {"atmos=", FIL_WEA | DONTFILE_TYPE_PACKED, ((sizeof(n_c_int) * MAP_AREA) / (PACKED_DATA_BLOCK*2)), 1},*/ #endif #ifdef USE_FIL_BEI {"being{", FIL_BEI, 0, 0, "Being Definition"}, {"locat=", FIL_BEI | FILE_TYPE_BYTE2, 2, 0, "Location in x and y coordinates"}, /*n_byte2 x;n_byte2 y;*/ {"facin=", FIL_BEI | FILE_TYPE_BYTE, 1, 4, "Direction facing"}, /*n_byte facing;*/ {"speed=", FIL_BEI | FILE_TYPE_BYTE, 1, 5, "Speed traveling"}, /*n_byte speed;*/ {"energ=", FIL_BEI | FILE_TYPE_BYTE2, 1, 6, "Energy within"}, /*n_byte2 energy;*/ {"datob=", FIL_BEI | FILE_TYPE_BYTE4, 1, 8, "Date of birth in days and millenia"}, /*n_byte2 date_of_birth[2];*/ {"rando=", FIL_BEI | FILE_TYPE_BYTE2, 2, 12,"Random within"}, /*n_byte2 seed[2];*/ {"state=", FIL_BEI | FILE_TYPE_BYTE2, 1, 16,"State description"}, /*n_byte2 state;*/ {"brast=", FIL_BEI | FILE_TYPE_BYTE2, 6, 18,"Brain state values"}, /*n_byte2 brain_state[6];*/ {"heigt=", FIL_BEI | FILE_TYPE_BYTE2, 1, 30, "Height"}, /*n_byte2 height;*/ {"masss=", FIL_BEI | FILE_TYPE_BYTE2, 1, 32, "Mass"}, /*n_byte2 mass;*/ {"overr=", FIL_BEI | FILE_TYPE_BYTE2, 1, 34, "ApeScript overrides"}, /*n_byte2 script_overrides;*/ {"shout=", FIL_BEI | FILE_TYPE_BYTE, SHOUT_BYTES, 36, "Shouting values"}, /*n_byte shout[SHOUT_BYTES];*/ {"crowd=", FIL_BEI | FILE_TYPE_BYTE, 1, 42, "Crowding"}, /*n_byte crowding;*/ {"postu=", FIL_BEI | FILE_TYPE_BYTE, 1, 43, "Posture"}, /*n_byte posture;*/ {"inven=", FIL_BEI | FILE_TYPE_BYTE2, INVENTORY_SIZE, 44, "Inventory"}, /*n_byte2 inventory[INVENTORY_SIZE];*/ {"paras=", FIL_BEI | FILE_TYPE_BYTE, 1, 60, "Number of parasites"}, /*n_byte parasites;*/ {"honor=", FIL_BEI | FILE_TYPE_BYTE, 1, 61, "Honor"}, /*n_byte honor;*/ {"conce=", FIL_BEI | FILE_TYPE_BYTE4, 1, 62, "Date of conception in days and millenia"}, /*n_byte2 date_of_conception[2];*/ {"atten=", FIL_BEI | FILE_TYPE_BYTE, ATTENTION_SIZE, 66, "Attention group"}, /*n_byte attention[ATTENTION_SIZE];*/ {"genet=", FIL_BEI | FILE_TYPE_BYTE2, CHROMOSOMES * 2, 72, "Genetics"}, /*n_genetics genetics[CHROMOSOMES];*/ {"fetag=", FIL_BEI | FILE_TYPE_BYTE2, CHROMOSOMES * 2, 88, "Father genetics"}, /*n_genetics fetal_genetics[CHROMOSOMES];*/ {"fathn=", FIL_BEI | FILE_TYPE_BYTE , 2, 104, "Father family names"}, /*n_byte father_name[2];*/ {"sosim=", FIL_BEI | FILE_TYPE_BYTE2, 4, 108, "Social simulation values"}, /* n_byte2 social simulation values x, y, nx, ny */ {"drive=", FIL_BEI | FILE_TYPE_BYTE, DRIVES, 116, "Drives"}, /*n_byte drives[DRIVES];*/ {"goals=", FIL_BEI | FILE_TYPE_BYTE2, 4, 120, "Goals"}, {"prefe=", FIL_BEI | FILE_TYPE_BYTE, PREFERENCES, 128, "Preferences"}, {"genex=", FIL_BEI | FILE_TYPE_BYTE2, 1, 142, "Generation Max"}, {"genen=", FIL_BEI | FILE_TYPE_BYTE2, 1, 144, "Generation Min"}, {"chigx=", FIL_BEI | FILE_TYPE_BYTE2, 1, 146, "Child Generation Max"}, {"chign=", FIL_BEI | FILE_TYPE_BYTE2, 1, 148, "Child Generation Min"}, #ifdef TERRITORY_ON {"terit=", FIL_BEI | FILE_TYPE_BYTE2, TERRITORY_BYTES/2, 150, "Territory information"}, #endif #ifdef IMMUNE_ON {"immun=", FIL_BEI | FILE_TYPE_BYTE, IMMUNE_BYTES, 406, "Immune system information"}, #endif #ifdef BRAINCODE_ON {"brreg=", FIL_BEI | FILE_TYPE_BYTE, BRAINCODE_PSPACE_REGISTERS, 451, "Brain code register"}, {"brpro=", FIL_BEI | FILE_TYPE_BYTE, (sizeof(simulated_ibrain_probe)*BRAINCODE_PROBES), 454, "Brain code probe"}, #endif #endif #ifdef USE_FIL_SOE {"sgcia{", FIL_SOE, 0, 0, "Social graph definition"}, {"sgloc=", FIL_SOE | FILE_TYPE_BYTE2, 2, 0, "Location in x and y coordinates"}, /* n_byte2 location[2];*/ {"sgtim=", FIL_SOE | FILE_TYPE_BYTE2, 1, 4, "Time in minutes"}, /* n_byte2 time;*/ {"sgdat=", FIL_SOE | FILE_TYPE_BYTE4, 1, 6, "Date in days and millenia"}, /* n_byte2 date[2];*/ {"sgfin=", FIL_SOE | FILE_TYPE_BYTE2, 1, 10, "First name"},/* n_byte2 first_name;*/ {"sgfan=", FIL_SOE | FILE_TYPE_BYTE2, 1, 14, "Family name"},/* n_byte2 family_name;*/ {"sgatt=", FIL_SOE | FILE_TYPE_BYTE, 1, 18, "Attraction"},/* n_byte attraction;*/ {"sgfof=", FIL_SOE | FILE_TYPE_BYTE, 1, 19, "Friend or foe"},/* n_byte friend_foe;*/ {"sgbel=", FIL_SOE | FILE_TYPE_BYTE2, 1, 20, "Belief"},/* n_byte2 belief;*/ {"sgfam=", FIL_SOE | FILE_TYPE_BYTE2, 1, 22, "Familiarity"},/* n_byte2 familiarity;*/ {"sgrel=", FIL_SOE | FILE_TYPE_BYTE, 1, 24, "Relationship"},/* n_byte relationship;*/ {"sgtyp=", FIL_SOE | FILE_TYPE_BYTE, 1, 25, "Entity type"},/* n_byte relationship;*/ #ifdef BRAINCODE_ON {"sgbrc=", FIL_SOE | FILE_TYPE_BYTE_EXT, BRAINCODE_SIZE, 26, "Local braincode"}, /*n_byte braincode[BRAINCODE_SIZE];*/ #endif #endif #ifdef USE_FIL_EPI {"episo{", FIL_EPI, 0, 0, "Episodic memory definition"}, {"eploc=", FIL_EPI | FILE_TYPE_BYTE2, 2, 0, "Location in x and y coordinates"}, /* n_byte2 location[2];*/ {"eptim=", FIL_EPI | FILE_TYPE_BYTE2, 1, 4, "Time in minutes"}, /* n_byte2 time;*/ {"epdat=", FIL_EPI | FILE_TYPE_BYTE4, 1, 6, "Date in days and millenia"}, /* n_byte2 date[2];*/ {"epfin=", FIL_EPI | FILE_TYPE_BYTE2, 2, 10, "First name"},/* n_byte2 first_name;*/ {"epfan=", FIL_EPI | FILE_TYPE_BYTE2, 2, 14, "Family name"},/* n_byte2 family_name;*/ {"epeve=", FIL_EPI | FILE_TYPE_BYTE, 1, 18, "Event"},/* n_byte event;*/ {"epfoo=", FIL_EPI | FILE_TYPE_BYTE, 1, 19, "Food"},/* n_byte food;*/ {"epafe=", FIL_EPI | FILE_TYPE_BYTE2, 1, 20, "Affect"},/* n_byte2 affect;*/ {"eparg=", FIL_EPI | FILE_TYPE_BYTE2, 1, 22, "Arg"},/* n_byte2 arg;*/ #endif #ifndef REDUCE_FILE /* FILE_TYPE_PACKED has a different form - no offset and the number is the size of the PACKED_DATA_BLOCK units */ /* {"brdat=", FIL_BRA | DONTFILE_TYPE_PACKED, DOUBLE_BRAIN/PACKED_DATA_BLOCK, 1 },*/ #endif {{0, 0, 0, 0, 0, 0, 0},0, 0, 0, 0L} }; #define TRACK_BRAIN(loc,lx,ly,lz) ((loc)[(lx)|((ly)<<5)|((lz)<<10)]) /* functions */ n_int command_executing(void); #endif /* SIMULATEDAPE_UNIVERSE_INTERNAL_H */ <|start_filename|>test/test_sim.c<|end_filename|> /**************************************************************** test_sim.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of Tom Barbalet, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #include <stdio.h> #include <time.h> #include "../toolkit/toolkit.h" #include "../script/script.h" #include "../sim/sim.h" #include "../entity/entity.h" #include "../universe/universe.h" n_int draw_error(n_constant_string error_text, n_constant_string location, n_int line_number) { printf("ERROR: %s @ %s %ld\n",(const n_string) error_text, location, line_number); return -1; } n_uint test_distance_moved(simulated_group * group, n_int show_stopped) { n_int loop = 0; n_uint total_moved = 0; while (loop < group->num) { simulated_being * being = &group->beings[loop]; n_byte speed = being_speed(being); if(IS_NIGHT(land_time()) == 0) { if ((speed == 0) && show_stopped) { n_string_block name_string; n_string_block time_string; io_time_to_string(time_string); being_name_simple(being, name_string); printf("%s %s stopped\n", time_string, name_string); } } total_moved += speed; loop++; } return total_moved; } void test_total_moved(simulated_group * group) { #ifdef DEBUG_LACK_OF_MOVEMENT n_int loop = 0; while (loop < group->num) { simulated_being * being = &group->beings[loop]; n_int total_moved = being_total_movement(being); if(total_moved == 0) { n_string_block name_string; n_file *description = obj_json(file_being(being)); being_name_simple(being, name_string); printf("%s stopped\n", name_string); io_file_debug(description); } loop++; } #endif } n_int test_hash(void) { simulated_group * group = sim_group(); simulated_being * first_being = &(group->beings[0]); simulated_being_constant * first_being_constant = &(first_being->constant); simulated_being_delta * first_being_delta = &(first_being->delta); simulated_being_events * first_being_events = &(first_being->events); simulated_being_brain * first_being_brain = &(first_being->braindata); simulated_immune_system * first_being_immune = &(first_being->immune_system); simulated_being_volatile * first_being_volatile = &(first_being->changes); n_byte2 random = being_random(first_being); /* n_uint being_hash1 = math_hash((n_byte *)first_being, sizeof(simulated_being)); n_uint being_constant_hash1 = math_hash((n_byte *)first_being_constant, sizeof(simulated_being_constant)); n_uint being_delta_hash1 = math_hash((n_byte *)first_being_delta, sizeof(simulated_being_delta)); n_uint being_events_hash1 = math_hash((n_byte *)first_being_events, sizeof(simulated_being_events)); n_uint being_brain_hash1 = math_hash((n_byte *)first_being_brain, sizeof(simulated_being_brain)); n_uint being_immune_hash1 = math_hash((n_byte*)first_being_immune, sizeof(simulated_immune_system)); n_uint being_volatile_hash1 = math_hash((n_byte*)first_being_volatile, sizeof(simulated_being_volatile)); printf("hash %lx\n", being_hash1); printf("constant %lx\n", being_constant_hash1); printf("delta %lx\n", being_delta_hash1); printf("events %lx\n", being_events_hash1); printf("brain %lx\n", being_brain_hash1); printf("immune %lx\n", being_immune_hash1); printf("volatile %lx\n", being_volatile_hash1); */ printf("random %d\n", random); if (random != 20979) { return 1; } return 0; } n_int test_sim_run(void) { n_int counter = 0; simulated_group * group = sim_group(); n_uint distance_moved = 0; while (counter < (512*4)) { n_uint distance_delta; sim_cycle(); distance_delta = test_distance_moved(group, 0); distance_moved += distance_delta; if ((counter & 511) == 0) { printf("%ld distance moved %ld running total %ld\n", counter, distance_delta, distance_moved); if (counter == 0) { if ((distance_delta != 0) || (distance_moved != 0)) { return 1; } } if (counter == 512) { if ((distance_delta != 4394) || (distance_moved != 2619196)) { return 1; } } if (counter == 1024) { if ((distance_delta != 196) || (distance_moved != 4298690)) { return 1; } } if (counter == 1536) { if ((distance_delta != 1299) || (distance_moved != 4442560)) { return 1; } } } counter ++; } printf("total distance moved %ld\n", distance_moved); if (distance_moved != 5873831) { return 1; } { n_int number_beings = group->num; n_int outer_loop = 0; n_int line_of_sight_count = 0; while (outer_loop < (number_beings-1)) { n_int inner_loop = 1 + outer_loop; while (inner_loop < number_beings) { n_vect2 location_vect; being_space(&group->beings[inner_loop], &location_vect); line_of_sight_count += being_line_of_sight(&group->beings[outer_loop], &location_vect); inner_loop++; } outer_loop++; } printf("line-of-sight count %ld for %ld\n", line_of_sight_count, number_beings); if ((line_of_sight_count != 128) || (number_beings != 315)) { return 1; } } test_total_moved(group); return 0; } int main(int argc, const char * argv[]) { printf(" --- test sim --- start -----------------------------------------------\n"); sim_init(KIND_START_UP, 0x12738291, MAP_AREA, 0); if (test_sim_run() != 0) { return 1; } if (test_hash() != 0) { return 1; } sim_close(); sim_init(KIND_START_UP, 0x12738291, MAP_AREA, 0); if (test_sim_run() != 0) { return 1; } if (test_hash() != 0) { return 1; } sim_init(KIND_NEW_SIMULATION, 0x12738291, MAP_AREA, 0); if (test_sim_run() != 0) { return 1; } if (test_hash() != 0) { return 1; } sim_close(); printf(" --- test sim --- end -----------------------------------------------\n"); return 0; } <|start_filename|>sim/sim.h<|end_filename|> /**************************************************************** sim.h ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /*! \file sim.h * \brief This is the interface between the ApeSDK toolkit and what consumes the ApeSDK toolkit. */ #ifndef _SIM_H_ #define _SIM_H_ /* Variable Definitions */ #undef SKELETON_RENDER #ifndef _WIN32 #define ALPHA_WEATHER_DRAW #undef METAL_RENDER #else #undef ALPHA_WEATHER_DRAW #endif #define FAST_START_UNREALISTIC_INITIAL_WEATHER #ifdef AUTOMATED #define FIXED_RANDOM_SIM 0x5261f726 #endif /*! @define */ #define SHORT_VERSION_NAME "Simulated Ape 0.699 " #define FULL_DATE __DATE__ /*! @define */ #define VERSION_NUMBER 699 #define COPYRIGHT_DATE "Copyright 1996 - 2020 " #define FULL_VERSION_COPYRIGHT "Copyright <NAME>, 1996-2020." /*! @define */ #define SIMULATED_APE_SIGNATURE (('N'<< 8) | 'A') #define SIMULATED_WAR_SIGNATURE (('N'<< 8) | 'W') #define COPYRIGHT_NAME "<NAME>. " #define COPYRIGHT_FOLLOW "All rights reserved." /*! @struct @field signature The program signature defined as SIMULATED_APE_SIGNATURE through the Simulated Ape file handling etc. @field version The version of the implementation that is the version number defined as VERSION_NUMBER (thus changes between versions). @discussion This is a means of tracking the programs and file versions that are used primarily through the file interface but also through other implementations over the Simulated Ape development. This includes Simulated Warfare currently, but potentially could include other software that accepts the Simulated Ape text based file format. */ typedef struct { n_byte2 signature; n_byte2 version; } n_version; typedef enum { ET_SIMULATED_APE, ET_SIMULATED_APE_GHOST, ET_FIERCE_FELINE, ET_FIERCE_BIRD_OF_PREY, }entity_type; #define WINDOW_PROCESSING NUM_TERRAIN #define DRAW_WINDOW_VIEW (1) #define DRAW_WINDOW_TERRAIN (2) #define DRAW_WINDOW_CONTROL (4) #define CHECK_DRAW_WINDOW(num, kind) (num & kind) /* maximum bytes in a braincode program */ #define BRAINCODE_SIZE 128 /* number of probes which can be applied to the brain */ #define BRAINCODE_PROBES (BRAINCODE_SIZE>>3) #define BRAINCODE_PSPACE_REGISTERS 3 /* maximum frequency of a brain probe */ #define BRAINCODE_MAX_FREQUENCY 16 /* number of bytes per instruction */ #define BRAINCODE_BYTES_PER_INSTRUCTION 3 /* number of instructions which a MVB copies */ #define BRAINCODE_BLOCK_COPY 16 #define BRAINCODE_MAX_ADDRESS (BRAINCODE_SIZE*2) #define BRAINCODE_ADDRESS(i) ((i) % BRAINCODE_MAX_ADDRESS) enum braincode_locations { BRAINCODE_EXTERNAL = 0, BRAINCODE_INTERNAL }; /* instruction codes */ enum BRAINCODE_COMMANDS { /* data */ BRAINCODE_DAT0 = 0, BRAINCODE_DAT1, /* operators */ BRAINCODE_ADD, BRAINCODE_SUB, BRAINCODE_MUL, BRAINCODE_DIV, BRAINCODE_MOD, BRAINCODE_MVB, BRAINCODE_MOV, BRAINCODE_JMP, BRAINCODE_CTR, BRAINCODE_SWP, BRAINCODE_INV, BRAINCODE_STP, BRAINCODE_LTP, /* conditionals */ BRAINCODE_JMZ, BRAINCODE_JMN, BRAINCODE_DJN, BRAINCODE_AND, BRAINCODE_OR, BRAINCODE_SEQ, BRAINCODE_SNE, BRAINCODE_SLT, /* sensors */ BRAINCODE_SEN, BRAINCODE_SEN2, BRAINCODE_SEN3, /* actuators */ BRAINCODE_ACT, BRAINCODE_ACT2, BRAINCODE_ACT3, BRAINCODE_ANE, BRAINCODE_INSTRUCTIONS }; typedef enum { WEATHER_SEVEN_ERROR = -1, WEATHER_SEVEN_SUNNY_DAY = 0, WEATHER_SEVEN_CLOUDY_DAY = 1, WEATHER_SEVEN_RAINY_DAY = 2, WEATHER_SEVEN_CLEAR_NIGHT = 3, WEATHER_SEVEN_CLOUDY_NIGHT = 4, WEATHER_SEVEN_RAINY_NIGHT = 5, WEATHER_SEVEN_DAWN_DUSK = 6 } weather_values; typedef enum { KIND_PRE_STARTUP = -2, KIND_NOTHING_TO_RUN = -1, KIND_LOAD_FILE = 0, KIND_NEW_SIMULATION, KIND_NEW_APES, KIND_START_UP, KIND_MEMORY_SETUP, } KIND_OF_USE; extern n_int draw_error(n_constant_string error_text, n_constant_string location, n_int line_number); void compress_buffer(n_byte * input, n_byte * output, n_int n, n_int compressed); void compress_buffer_run(n_byte * input, n_byte * output, n_int n, n_int compressed, n_int number); void compress_brain_compressed(n_byte * brain); void compress_brain_expand(n_byte * brain); enum color_type { COLOR_BLACK = (0), COLOR_WHITE = (252), COLOR_BLUE = (253), COLOR_RED_DARK = (254), COLOR_RED = (255) }; #define NON_INTERPOLATED COLOR_WHITE #ifdef SIMULATED_PLANET #define MAP_BITS (8) #define MAP_TITLES (6) #else #define MAP_BITS (9) #define MAP_TITLES (1) #endif /* 750 1624 874 828 1472 644 750 1334 584 640 1136 496 */ #define MAP_DIMENSION (1<<(MAP_BITS)) #define MAP_AREA (1<<(2*MAP_BITS)) #define APE_TO_MAP_BIT_RATIO (6) #define MAP_TO_TERRITORY_RATIO (5) #define APESPACE_TO_MAPSPACE(num) ((num)>>APE_TO_MAP_BIT_RATIO) #define MAPSPACE_TO_APESPACE(num) ((num)<<APE_TO_MAP_BIT_RATIO) #define MAPSPACE_TO_TERRITORY(num) ((num)>>MAP_TO_TERRITORY_RATIO) #define TERRITORY_DIMENSION MAPSPACE_TO_TERRITORY(MAP_DIMENSION) #define TERRITORY_AREA (TERRITORY_DIMENSION*TERRITORY_DIMENSION) /* dimension of the territory map */ #define APESPACE_TO_TERRITORY(num) (APESPACE_TO_MAPSPACE(num)>>MAP_TO_TERRITORY_RATIO) #define HI_RES_MAP_BITS (MAP_BITS+3) #define HI_RES_MAP_DIMENSION (1<<(HI_RES_MAP_BITS)) #define HI_RES_MAP_AREA (1<<(2*HI_RES_MAP_BITS)) #define MAP_APE_RESOLUTION_SIZE (MAPSPACE_TO_APESPACE(MAP_DIMENSION)) #define APESPACE_BOUNDS ((MAP_APE_RESOLUTION_SIZE)-1) #define APESPACE_CONFINED(num) (n_byte2)((num)>APESPACE_BOUNDS ? APESPACE_BOUNDS : ((num)<0 ? 0 : (num))) #define LAND_TILE_EDGE (256) #define POSITIVE_LAND_COORD(num) ((num+(3*MAP_DIMENSION))&(MAP_DIMENSION-1)) #define POSITIVE_LAND_COORD_HIRES(num) ((num+(3*HI_RES_MAP_DIMENSION))&(HI_RES_MAP_DIMENSION-1)) #define NUMBER_LAND_TILES (MAP_DIMENSION/LAND_TILE_EDGE) #define WEATHER_TO_MAPSPACE(num) ((num)) #define MAPSPACE_TO_WEATHER(num) ((num)) #define LAND_DITHER(x,y,z) (((x+y+z)&15)-(((x&y)|z)&7)-((x|(y&z))&7)) #define OFFSCREENSIZE (MAP_AREA + TERRAIN_WINDOW_AREA + CONTROL_WINDOW_AREA) #define WEATHER_CLOUD (32768>>4) #define WEATHER_RAIN (WEATHER_CLOUD * 3) #define TIME_HOUR_MINUTES (60) #define TIME_DAY_MINUTES (TIME_HOUR_MINUTES * 24) #define TIME_MONTH_MINUTES (TIME_DAY_MINUTES * 28) #define TIME_YEAR_MINUTES (TIME_MONTH_MINUTES * 13) #define TIME_YEAR_DAYS (7 * 52) /*364 also = 13 * 28 */ #define TIME_CENTURY_DAYS (TIME_YEAR_DAYS * 100) #define LUNAR_ORBIT_MINS 39312 #define WATER_TEST(pz,w) ((pz)<(w)) #define WATER_MAP 128 #define TIDE_AMPLITUDE_LUNAR 8 #define TIDE_AMPLITUDE_SOLAR 2 #define TIDE_MAX (WATER_MAP + TIDE_AMPLITUDE_LUNAR + TIDE_AMPLITUDE_SOLAR) /* Night/Day definitions */ #define IS_NIGHT(num) ((((num)>>5) < (11))||(((num)>>5) > (36))) #define IS_DAWNDUSK(num) ((((num)>>5) == (11))||(((num)>>5) == (36))) #define NIGHT_END_POINT (256) #define DAWN_END_POINT (384) #define DAY_END_POINT (1152) #define DUSK_END_POINT (1184) #define MAX_MODIFIED_TIME (238) #define NIGHT_TIME_DIVISION(time) ((time)>>4) #define DAWN_DUSK_TIME_DIVISION(time) ((time)>>3) #define DAY_TIME_DIVISION(time) ((time)>>2) /* Night 1184 - 1439 Night 0 - 351 Dawn 352 - 383 Day 384 - 1151 Dusk 1152 - 1183 */ void weather_init(void); void weather_wind_vector(n_vect2 * pos, n_vect2 * wind); n_int weather_pressure(n_int px, n_int py); void weather_cycle(void); void weather_wind(void); weather_values weather_seven_values(n_int px, n_int py); void land_seed_genetics(n_byte2 * local_random); void land_init(void); void land_init_high_def(n_byte double_spread); void land_clear(KIND_OF_USE kind, n_byte4 start); void land_cycle(void); void land_vect2(n_vect2 * output, n_int * actual_z, n_vect2 * location); n_int land_operator_interpolated(n_int locx, n_int locy, n_byte * kind); n_int land_map_dimension(void); n_int land_map_bits(void); void land_tide(void); n_int land_location(n_int px, n_int py); n_byte * land_location_tile(n_int tile); n_int land_location_vect(n_vect2 * value); typedef struct { n_byte2 genetics[2]; /* save-able */ n_byte topography[2][MAP_AREA]; /* generated */ n_c_int atmosphere[2][ MAP_AREA]; /* save-able and generate-able */ n_byte2 delta_pressure[ MAP_AREA]; /* generated */ n_byte2 delta_pressure_highest; n_byte2 delta_pressure_lowest; n_c_int atmosphere_highest; n_c_int atmosphere_lowest; n_int local_delta; } n_tile; typedef struct { #ifdef SIMULATED_PLANET n_tile tiles[6]; #else n_tile tiles[1]; #endif n_byte2 genetics[2]; /* save-able */ n_int wind_value_x; /* 6 to 96 */ n_int wind_value_y; /* 6 to 96 */ n_int wind_aim_x; /* 6 to 96 */ n_int wind_aim_y; /* 6 to 96 */ n_int wind_dissipation; n_byte4 date; /* save-able */ n_byte2 time; /* save-able */ n_byte tide_level; /* generated */ n_byte topography_highdef[HI_RES_MAP_AREA * 2]; /* generated */ n_byte4 highres_tide[HI_RES_MAP_AREA/32]; /* generated */ } n_land; typedef struct { n_int x, y; n_int tile; n_uint facing; } n_tile_coordinates; void tile_wind(n_land * land); void tile_cycle(n_land * land); void tile_weather_init(n_land * land); void tile_land_init(n_land * land); void tile_land_erase(n_land * land); void tile_land_random(n_land * land, n_byte2 * random); void tile_creation(n_byte * map, n_byte2 * random); n_byte tiles_topography(n_land * land, n_int tile, n_int buffer, n_int lx, n_int ly); n_byte * tiles_topography_map(n_land * land, n_int tile, n_int buffer); n_c_int tiles_atmosphere(n_land * land, n_int tile, n_int buffer, n_int lx, n_int ly); void tile_resolve_coordinates(n_tile_coordinates * coordinates); void land_color_init(void); void land_color_time(n_byte2 * color_fit, n_int toggle_tidedaylight); void land_color_time_8bit(n_byte * color_fit, n_int toggle_tidedaylight); n_land * land_ptr(void); n_byte4 land_date(void); n_byte4 land_time(void); n_byte2 * land_genetics(void); n_byte land_tide_level(void); n_byte * land_topography(void); n_byte * land_topography_highdef(void); n_byte4 * land_highres_tide(void); n_c_int * land_weather(n_int tile); #define BASH_COLOR_DEFAULT "\033[0m" #define BASH_COLOR_LIGHT_GREEN "\033[92m" #define BASH_COLOR_LIGHT_YELLOW "\033[93m" #define BASH_COLOR_LIGHT_RED "\033[91m" #define BASH_COLOR_LIGHT_GREY "\033[37m" #define BASH_COLOR_DARK_GREY "\033[90m" n_int spacetime_after(n_spacetime * initial, n_spacetime * second); void spacetime_copy(n_spacetime * to, n_spacetime * from); n_int spacetime_before_now(n_spacetime * initial); void spacetime_set(n_spacetime * set, n_byte2 * location); void land_convert_to_map(n_vect2 * value); #endif /* _SIM_H_ */ <|start_filename|>mac/ASShared.h<|end_filename|> /**************************************************************** ASShared.h ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #import <Cocoa/Cocoa.h> #include "shared.h" @interface ASShared : NSObject - (id) initWithFrame:(NSRect)frameRect; - (id) init; - (BOOL) start; - (void) about; - (void) draw:(unsigned char *)buffer width:(NSInteger)width height:(NSInteger)height; - (void) keyReceived:(NSUInteger)key; - (void) mouseReceivedWithXLocation:(n_double)xLocation yLocation:(n_double)yLocation; - (void) mouseOption:(BOOL)mouseOption; - (void) keyUp; - (void) mouseUp; - (void) rotation:(double)rotationAmount; - (void) delta_x:(double)delta_x delta_y:(double)delta_y; - (void) zoom:(double)zoomAmount; - (NSTimeInterval) timeInterval; - (void) scriptDebugHandle:(NSString *)fileName; - (void) close; - (void) identificationBasedOnName:(NSString *)windowName; - (void) newSimulation; - (void) newAgents; - (void) cycle; - (BOOL) cycleDebugOutput; - (BOOL) cycleQuit; - (BOOL) cycleNewApes; - (BOOL) menuPause; - (void) menuPreviousApe; - (void) menuNextApe; - (void) menuClearErrors; - (BOOL) menuNoTerritory; - (BOOL) menuNoWeather; - (BOOL) menuNoBrain; - (BOOL) menuNoBrainCode; - (BOOL) menuDaylightTide; - (void) menuFlood; - (void) menuHealthyCarrier; - (void) savedFileName:(NSString*)name; - (BOOL) openFileName:(NSString*)name isScript:(BOOL)scriptFile; @property (nonatomic, assign, readonly) NSInteger identification; @end <|start_filename|>entity/body.c<|end_filename|> /**************************************************************** body.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #include "entity.h" #include "entity_internal.h" /** * @brief One being gives something to another * @param local The being doing the giving * @param other The being receiving * @param carrying objects being carried */ static void body_action_give(simulated_being * local, simulated_being * other, n_byte2 carrying) { n_byte hand = BODY_RIGHT_HAND; if (carrying == 0) { hand = BODY_LEFT_HAND; carrying = being_carried(local,hand); } if ((carrying != 0) && ((being_carried(other,BODY_LEFT_HAND)==0) || (being_carried(other,BODY_RIGHT_HAND)==0))) { being_set_attention(local,ATTENTION_BODY, BODY_RIGHT_HAND); being_set_attention(other,ATTENTION_BODY, BODY_RIGHT_HAND); episodic_interaction(local, other, EVENT_GIVEN, EPISODIC_AFFECT_ZERO, carrying); episodic_interaction(other, local, EVENT_GIVEN_BY, AFFECT_RECEIVE, carrying); being_drop(local,hand); if (being_carried(other,BODY_RIGHT_HAND)==0) { being_take(other,BODY_RIGHT_HAND,carrying); } else { being_take(other,BODY_LEFT_HAND,carrying); } } } /** * @brief One being bashes another * @param local The being doing the bashing * @param other The being being bashed * @param carrying Objects being carried */ static void body_action_bash(simulated_being * local, simulated_being * other, n_byte2 carrying) { n_byte hand = BODY_RIGHT_HAND; n_int index, hit = 0; simulated_isocial * graph; if (carrying == 0) { hand = BODY_LEFT_HAND; carrying = being_carried(local,hand); } if (carrying!=0) { if ((carrying & INVENTORY_BRANCH) || (carrying & INVENTORY_ROCK)) { being_set_attention(local,ATTENTION_BODY, BODY_RIGHT_HAND); being_set_attention(other,ATTENTION_BODY, BODY_BACK); index = get_simulated_isocial(other, local); if (index>-1) { graph = being_social(other); if (!graph) return; if (graph[index].friend_foe>1) graph[index].friend_foe-=2; } if ((carrying & INVENTORY_ROCK) && (being_random(other)>THROW_ACCURACY)) { hit=1; being_energy_delta(other, 0 - SQUABBLE_ENERGY_ROCK_HURL); } if ((carrying & INVENTORY_BRANCH) && (being_random(other)>WHACK_ACCURACY)) { hit=1; being_energy_delta(other, 0 - SQUABBLE_ENERGY_BRANCH_WHACK); } } if (carrying & INVENTORY_BRANCH) { if (hit != 0) { episodic_interaction(local, other, EVENT_WHACKED, EPISODIC_AFFECT_ZERO, 0); episodic_interaction(other, local, EVENT_WHACKED_BY, AFFECT_WHACKED, 0); } } if (carrying & INVENTORY_ROCK) { episodic_interaction(local, other, EVENT_HURLED, EPISODIC_AFFECT_ZERO, 0); if (hit != 0) { episodic_interaction(other, local, EVENT_HURLED_BY, AFFECT_HURL, 0); } } } } /** * @brief Remember interaction between two beings * @param local Pointer to the first being * @param other Pointer to the second being * @param local_attention Focus of attention for the first being * @param other_attention Focus of attention for the second being * @param kind The type of event */ static void body_action_interactive(simulated_being * local, simulated_being * other, n_byte local_attention, n_byte other_attention, n_byte kind) { being_set_attention(local, ATTENTION_BODY, local_attention); being_set_attention(other, ATTENTION_BODY, other_attention); episodic_interaction(local, other, kind, EPISODIC_AFFECT_ZERO, 0); episodic_interaction(other, local, kind+1, EPISODIC_AFFECT_ZERO, 0); } /*** This block should also be the same function ***/ static void body_action_interactive_change(simulated_being * local, simulated_being * other, n_byte local_attention, n_byte other_attention, n_byte kind, n_byte positive, AFFECT_TYPE affect) { n_int index; being_set_attention(local, ATTENTION_BODY, local_attention); being_set_attention(other, ATTENTION_BODY, other_attention); index = get_simulated_isocial(other, local); if (index>-1) { simulated_isocial * graph = being_social(other); if (!graph) return; if (positive) { if (graph[index].friend_foe<255) graph[index].friend_foe++; } else { if (graph[index].friend_foe>0) graph[index].friend_foe--; } } episodic_interaction(local, other, kind, EPISODIC_AFFECT_ZERO, 0); episodic_interaction(other, local, kind+1, affect, 0); } /** * @brief Carry an object in a hand * @param local Pointer to the being * @param carrying Objects which are carried * @param hand left or right hand * @param kind The kind of object */ static void body_action_hand_object(simulated_being * local, n_byte2 carrying, n_byte hand, n_byte kind) { if (carrying == 0) { hand = BODY_LEFT_HAND; carrying = being_carried(local,hand); } #ifdef EPISODIC_ON if (carrying!=0) { if (carrying & INVENTORY_BRANCH) { episodic_self(local, kind, EPISODIC_AFFECT_ZERO, INVENTORY_BRANCH); } else { if (carrying & INVENTORY_TWIG) { episodic_self(local, kind, EPISODIC_AFFECT_ZERO, INVENTORY_TWIG); } else { if (carrying & INVENTORY_SPEAR) { episodic_self(local, kind, EPISODIC_AFFECT_ZERO, INVENTORY_SPEAR); } } } } #endif } /** * @brief Performs a jabbing action * @param local Pointer to the being * @param carrying Objects which are carried * @param hand Left or right hand */ static void body_action_jab(simulated_being * local, n_byte2 carrying, n_byte hand) { enum inventory_type carrying2 = being_carried(local,BODY_LEFT_HAND); if ((carrying & INVENTORY_SPEAR) || (carrying2 & INVENTORY_SPEAR)) { n_int az; n_vect2 location_vector,facing_vector,slope_vector; being_space(local, &location_vector); being_facing_vector(local, &facing_vector, 4); land_vect2(&slope_vector, &az, &location_vector); if ((az > WATER_MAP) && (az < TIDE_MAX)) { /* some probability of spearing a fish */ if (being_random(local)<FISHING_PROB) { /* carry fish */ if (carrying & INVENTORY_SPEAR) { being_take(local,BODY_LEFT_HAND, INVENTORY_FISH); } else { being_take(local,hand, INVENTORY_FISH); } #ifdef EPISODIC_ON episodic_self(local, EVENT_FISH, AFFECT_FISH, 0); #endif } } } } /** * @brief Bashes one object on another. Both objects must be carried. * @param local Pointer to the being * @param carrying Things which are carried * @param hand left or right hand */ static void body_action_bash_objects(simulated_being * local, n_byte2 carrying, n_byte hand) { enum inventory_type carrying2 = being_carried(local,BODY_LEFT_HAND); if ((carrying & INVENTORY_ROCK) && (carrying2 & INVENTORY_ROCK)) { /** bash two rocks to make a scraper */ being_drop(local,hand); being_take(local,hand,INVENTORY_SCRAPER); } if (((carrying & INVENTORY_ROCK) && (carrying2 & INVENTORY_NUT)) || ((carrying & INVENTORY_NUT) && (carrying2 & INVENTORY_ROCK))) { /** bash nut with a rock */ if (carrying & INVENTORY_NUT) { being_drop(local,hand); being_take(local,hand,INVENTORY_NUT_CRACKED); } else { being_drop(local,BODY_LEFT_HAND); being_take(local,BODY_LEFT_HAND,INVENTORY_NUT_CRACKED); } } if (((carrying & INVENTORY_BRANCH) && (carrying2 & INVENTORY_SCRAPER)) || ((carrying & INVENTORY_SCRAPER) && (carrying2 & INVENTORY_BRANCH))) { /** use a scraper to make a spear */ if (carrying & INVENTORY_BRANCH) { being_drop(local,hand); being_take(local,hand,INVENTORY_SPEAR); } else { being_drop(local,BODY_LEFT_HAND); being_take(local,BODY_LEFT_HAND,INVENTORY_SPEAR); } } if (((carrying & INVENTORY_BRANCH) && (carrying2 & INVENTORY_NUT)) || ((carrying & INVENTORY_NUT) && (carrying2 & INVENTORY_BRANCH))) { /** whack nut with a branch */ if (carrying & INVENTORY_NUT) { being_drop(local,hand); being_take(local,hand,INVENTORY_NUT_CRACKED); } else { being_drop(local,BODY_LEFT_HAND); being_take(local,BODY_LEFT_HAND,INVENTORY_NUT_CRACKED); } } } /** * @brief A being chews on something * @param local Pointer to the being * @param carrying Things which are carried * @param hand left or right hand */ static void body_action_chew(simulated_being * local, n_byte2 carrying, n_byte hand) { if (!((carrying & INVENTORY_GRASS) || (carrying & INVENTORY_TWIG) || (carrying & INVENTORY_FISH) || (carrying & INVENTORY_BIRD_EGGS) || (carrying & INVENTORY_LIZARD_EGGS) || (carrying & INVENTORY_NUT_CRACKED))) { hand = BODY_LEFT_HAND; carrying = being_carried(local,hand); } if ((carrying & INVENTORY_GRASS) || (carrying & INVENTORY_TWIG) || (carrying & INVENTORY_FISH) || (carrying & INVENTORY_BIRD_EGGS) || (carrying & INVENTORY_LIZARD_EGGS) || (carrying & INVENTORY_NUT_CRACKED)) { if (hand == BODY_RIGHT_HAND) { carrying |= 1; } #ifdef EPISODIC_ON episodic_self(local,EVENT_CHEW, EPISODIC_AFFECT_ZERO, carrying); #endif } if (carrying & INVENTORY_GRASS) { /** consume grass */ being_energy_delta(local, food_absorption(local, ENERGY_GRASS, FOOD_VEGETABLE)); being_drop(local,hand); } else { if (carrying & INVENTORY_FISH) { /** consume fish */ being_energy_delta(local, food_absorption(local, ENERGY_FISH, FOOD_SHELLFISH)); being_drop(local,hand); } else { if (carrying & INVENTORY_NUT_CRACKED) { /** consume nut */ being_energy_delta(local, food_absorption(local, ENERGY_NUT, FOOD_VEGETABLE)); being_drop(local,hand); } else { if (carrying & INVENTORY_BIRD_EGGS) { /** consume nut */ being_energy_delta(local, food_absorption(local, ENERGY_BIRD_EGGS, FOOD_BIRD_EGGS)); being_drop(local,hand); } else { if (carrying & INVENTORY_LIZARD_EGGS) { /** consume nut */ being_energy_delta(local, food_absorption(local, ENERGY_LIZARD_EGGS, FOOD_LIZARD_EGGS)); being_drop(local,hand); } } } } } } /** * @brief If anything is being carried in a hand this swaps it between hands * @param local Pointer to the being * @param carrying Things which are carried * @param hand left or right hand */ static void body_action_swap_hands(simulated_being * local, n_byte2 carrying, n_byte hand) { if ((carrying != 0) && (being_carried(local,BODY_LEFT_HAND)==0)) { being_drop(local,hand); being_take(local,BODY_LEFT_HAND,carrying); } else { if ((carrying == 0) && (being_carried(local,BODY_LEFT_HAND)!=0)) { carrying = being_carried(local,BODY_LEFT_HAND); being_drop(local,BODY_LEFT_HAND); being_take(local,hand,carrying); } } } /** * @brief A being drops something * @param local Pointer to the being * @param carrying Things which are carried * @param hand left or right hand */ static void body_action_drop(simulated_being * local, n_byte2 carrying, n_byte hand) { if (carrying == 0) { hand = BODY_LEFT_HAND; carrying = being_carried(local,hand); } if (carrying != 0) { being_drop(local,hand); #ifdef EPISODIC_ON episodic_self(local, EVENT_DROP, EPISODIC_AFFECT_ZERO, carrying); #endif } } /** * @brief A being picks something up * @param local Pointer to the being * @param carrying Things being carried by the being * @param hand left or right hand */ static void body_action_pickup(simulated_being * local, n_byte2 carrying, n_byte hand) { if ((carrying != 0) && (!being_posture_under(local,POSTURE_CROUCHING))) { hand = BODY_LEFT_HAND; carrying = being_carried(local,hand); } if (carrying == 0) { n_int az; n_vect2 location_vector,facing_vector,slope_vector; being_space(local, &location_vector); being_facing_vector(local, &facing_vector, 4); land_vect2(&slope_vector,&az,&location_vector); if (az > WATER_MAP) { if (az > TIDE_MAX) { /* TODO handle this logic centrally */ n_int grass, trees, bush; food_values(being_location_x(local), being_location_y(local), &grass, &trees, &bush); if ((grass>bush) && (grass>trees)) { being_take(local,hand, INVENTORY_GRASS); #ifdef EPISODIC_ON episodic_self(local, EVENT_PICKUP,EPISODIC_AFFECT_ZERO, INVENTORY_GRASS); #endif } if ((trees>grass) && (trees>bush)) { if (being_posture_under(local, POSTURE_UPRIGHT)) { being_take(local,hand, INVENTORY_BRANCH); #ifdef EPISODIC_ON episodic_self(local, EVENT_PICKUP,EPISODIC_AFFECT_ZERO, INVENTORY_BRANCH); #endif } else { being_take(local,hand, INVENTORY_NUT); #ifdef EPISODIC_ON episodic_self(local, EVENT_PICKUP,EPISODIC_AFFECT_ZERO, INVENTORY_NUT); #endif } } if ((bush>grass) && (bush>trees)) { being_take(local,hand, INVENTORY_TWIG); #ifdef EPISODIC_ON episodic_self(local, EVENT_PICKUP,EPISODIC_AFFECT_ZERO, INVENTORY_TWIG); #endif } } else { being_take(local,hand, INVENTORY_ROCK); #ifdef EPISODIC_ON episodic_self(local, EVENT_PICKUP,EPISODIC_AFFECT_ZERO, INVENTORY_ROCK); #endif } } } } /** * @brief Performs a given action * @param local Pointer to the being performing the action * @param other Pointer to another being involved in the action * @param action The type of action */ void social_action( simulated_being * local, simulated_being * other, n_byte action) { n_byte2 carrying; n_byte hand = BODY_RIGHT_HAND; if (local->delta.awake == FULLY_ASLEEP) { return; } carrying = being_carried(local,hand); if (other == 0L) { /** individual action */ switch(action % INDIVIDUAL_ACTIONS) { case ACTION_JAB: body_action_jab(local, carrying, hand); break; case ACTION_BASH_OBJECTS: body_action_bash_objects(local, carrying, hand); break; case ACTION_CHEW: body_action_chew(local, carrying, hand); break; case ACTION_BRANDISH: body_action_hand_object(local, carrying, hand, EVENT_BRANDISH); break; case ACTION_DRAG: body_action_hand_object(local, carrying, hand, EVENT_DRAG); break; case ACTION_SWAP_HANDS: body_action_swap_hands(local, carrying, hand); break; case ACTION_DROP: body_action_drop(local, carrying, hand); break; case ACTION_PICKUP: body_action_pickup(local, carrying, hand); break; } } else { /** social action */ switch(action % SOCIAL_ACTIONS) { case ACTION_PROD: body_action_interactive_change(local, other, BODY_RIGHT_HAND, BODY_FRONT, EVENT_PRODDED, 0, AFFECT_PRODDED); break; case ACTION_HUG: body_action_interactive_change(local, other, BODY_FRONT, BODY_FRONT, EVENT_HUGGED, 1, AFFECT_HUGGED); break; case ACTION_SMILE: body_action_interactive_change(local, other, BODY_TEETH, BODY_TEETH, EVENT_SMILED, 1, AFFECT_SMILED); break; case ACTION_GLOWER: body_action_interactive_change(local, other, BODY_HEAD, BODY_HEAD, EVENT_GLOWERED, 0, AFFECT_GLOWER); break; case ACTION_TICKLE: body_action_interactive(local, other, BODY_RIGHT_HAND, BODY_FRONT, EVENT_TICKLED); break; case ACTION_POINT: body_action_interactive(local, other, BODY_RIGHT_HAND, BODY_RIGHT_HAND, EVENT_POINT); break; case ACTION_PAT: body_action_interactive(local, other, BODY_RIGHT_HAND, BODY_BACK, EVENT_PATTED); break; case ACTION_BASH: body_action_bash(local, other, carrying); break; case ACTION_GIVE: body_action_give(local, other, carrying); break; } } } /** * @brief Compares two genetics and returns 1 if they are the same * @param genetics_a First genetics * @param genetics_b Second genetics * @return 1 if the two genetics are the same, 0 otherwise */ n_int genetics_compare(n_genetics * genetics_a, n_genetics * genetics_b) { n_int loop = 0; while (loop < CHROMOSOMES) { if (genetics_a[loop] != genetics_b[loop]) { return 0; } loop++; } return 1; } /** * @brief Sets genetics A to be the same as genetics B * @param genetics_a The destination genetics * @param genetics_b The source genetics */ void genetics_set(n_genetics * genetics_a, n_genetics * genetics_b) { n_int loop = 0; while (loop < CHROMOSOMES) { genetics_a[loop] = genetics_b[loop]; loop++; } } /** * @brief Creates a blank genome * @param genetics_a The genetics to be cleared */ void genetics_zero(n_genetics * genetics_a) { n_int loop = 0; while (loop < CHROMOSOMES) { genetics_a[loop] = 0; loop++; } } /** * @brief Returns 1 if the given genetics are unique within the population * @param local Pointer to the simulation object * @param genetics The new genetics to be compared * @return 1 if the given genetics are unique in the population */ static n_int genetics_unique(simulated_being * local, n_int number, n_genetics * genetics) { n_int loop = 0; if (number == 0) { return 1; } while (loop < number) { simulated_being * local_being = &(local[loop]); if (genetics_compare(being_genetics(local_being), genetics)) { return 0; } loop++; } return 1; } /** * @brief Returns the 2 bit gene value from the given point within a diploid chromosome. This includes mutations * @param chromosome The chromosome as a 32 bit value. Lower 16 bits are from father, upper 16 bits from mother * @param point The index within the chromosome * @param mutation_prob The probability of mutation * @param local Random number generator seed * @return 2 bit gene value */ static n_int genetics_child_gene(n_genetics chromosome, n_int point, n_byte2 mutation_prob, n_byte2 * local) { n_byte2 mutation_type; n_int child_gene = 0; math_random3(local); if (math_random(local) < mutation_prob) { mutation_type = (math_random(local) & 7); switch(mutation_type) { /** mutation on the maternal chromosome */ case MUTATION_MATERNAL: child_gene = DIPLOID( (math_random(local) & 3), ((CHROMOSOME_FROM_FATHER(chromosome) >> point ) & 3)); break; /** mutation on the paternal chromosome */ case MUTATION_PATERNAL: child_gene = DIPLOID( ((CHROMOSOME_FROM_MOTHER(chromosome) >> point ) & 3), (math_random(local) & 3)); break; /** duplicate of the maternal gene on both sides */ case MUTATION_MATERNAL_DUPLICATE: child_gene = DIPLOID( ((CHROMOSOME_FROM_MOTHER(chromosome) >> point ) & 3), ((CHROMOSOME_FROM_MOTHER(chromosome) >> point ) & 3)); break; /** duplicate of the paternal gene on both sides */ case MUTATION_PATERNAL_DUPLICATE: child_gene = DIPLOID( ((CHROMOSOME_FROM_FATHER(chromosome) >> point ) & 3), ((CHROMOSOME_FROM_FATHER(chromosome) >> point ) & 3)); break; default: math_random3(local); child_gene = DIPLOID( (math_random(local) & 3), (math_random(local) & 3)); } } else { /** normal gene. What grandparent genes get into the current generation is randomly chosen */ if ((math_random(local) & 1)!=0) { child_gene = DIPLOID( ((CHROMOSOME_FROM_MOTHER(chromosome) >> point ) & 3), ((CHROMOSOME_FROM_FATHER(chromosome) >> point ) & 3)); } else { child_gene = DIPLOID( ((CHROMOSOME_FROM_FATHER(chromosome) >> point ) & 3), ((CHROMOSOME_FROM_MOTHER(chromosome) >> point ) & 3)); } } return child_gene; } /** * @brief Performs crossover and mutation * @param mother Chromosome of the mother (first 16 bits from maternal grandfather, second 16 bits from maternal grandmother) * @param father Chromosome of the father (first 16 bits from paternal grandfather, second 16 bits from paternal grandmother) * @param local Random number generator seed * @return Child chromosome */ static n_genetics genetics_crossover(n_genetics mother, n_genetics father, n_byte2 * local) { n_int loop = 0; n_genetics result = 0; n_int point, point2; n_int deletion_point = 16; n_byte2 prob; n_genetics parent; /** randomly select a crossover point */ n_int crossover_point = (math_random(local) >> 13) << 1; /** gene insertion/deletion */ if (math_random(local) < MUTATION_DELETION_PROB) { deletion_point = (math_random(local) >> 13) << 1; } point = point2 = crossover_point - 8; /** for every 2 bit gene in the 16 bit chromosome */ while(loop< 16) { if (loop == deletion_point) point2 -= 2; /** equal genetic contribution from mother and father */ if (point2 < 0) { point2 += 16; } else { if (point2 > 15) point2 -= 16; } if (loop < 8) { parent=father; /** higher mutation probability in males */ prob = MUTATION_CROSSOVER_PROB*50; } else { parent=mother; prob = MUTATION_CROSSOVER_PROB; } result |= ( genetics_child_gene(parent, point2, prob, local) << point ); loop += 2; point += 2; point2 += 2; } return result; } /** * @brief Mutates a single chromosome, without crossover * @param chromosome The chromosome to be mutated * @param local Random number generator seed * @return The mutated chromosome */ static n_genetics genetics_mutate(n_genetics chromosome, n_byte2 * local) { n_genetics result = 0; n_int point = 0; n_int loop = 0; n_int deletion_point = 16; /** gene insertion/deletion */ if (math_random(local) < MUTATION_DELETION_PROB) { deletion_point = (math_random(local) >> 13) << 1; } /** for every 2 bit gene in the 16 bit chromosome */ point = 0; while(loop< 16) { if (loop == deletion_point) { point -= 2; if (point < 0) { point += 16; } } if (point > 15) point -= 16; result |= ( genetics_child_gene(chromosome, point, MUTATION_CROSSOVER_PROB, local) << point ); loop += 2; point += 2; } return result; } /** * @brief Transposes segments of the genome between chromosomes or within the same chromosome. This is the main cause of variation between siblings. * @param genetics Pointer to the genetics * @param local Random number generator seed */ static void genetics_transpose(n_genetics * genetics, n_byte2 * local) { math_random3(local); if (math_random(local) < MUTATION_TRANSPOSE_PROB) { /** number of bits to transpose */ /** chromosome numbers */ /** locations within the chromosomes */ n_byte2 local_random0 = math_random(local); n_byte2 local_random1 = math_random(local); n_byte source_offset = (local_random0>>8)&31; n_byte dest_offset = local_random1&31; /** whether to invert the sequence */ n_byte inversion = (local_random0>>13) & 1; n_byte source_ch = (local_random1>>5) % CHROMOSOMES; n_byte dest_ch = (local_random1>>7) % CHROMOSOMES; n_int ctr1 = source_offset; n_byte p = 0; math_random3(local); while (p < (math_random(local)&15)) { n_int ctr2; ctr1 = (ctr1 & 31); if (inversion==0) { ctr2=(n_int)(dest_offset+p); } else { /** inverted sequence */ ctr2=(n_int)dest_offset-p+32; } ctr2 = (ctr2 & 31); /** clear destination bit */ if ((genetics[dest_ch] & (1<<ctr2)) != 0) { genetics[dest_ch] ^= (1 << ctr2); } /** set destination bit */ if ((genetics[source_ch] & (1<<ctr1)) != 0) { genetics[dest_ch] |= (1 << ctr2); } p++; ctr1++; } } } void body_genetics(simulated_being * beings, n_int number, n_genetics * genetics, n_genetics * mother_genetics, n_genetics * father_genetics, n_byte2 * local) { n_int ch; n_byte sex = 2; math_random3(local); sex |= (math_random(local)&1); do { math_random3(local); /** crossover and mutation */ for (ch = 0; ch < CHROMOSOMES; ch++) { if (ch != CHROMOSOME_Y) { genetics[ch] = genetics_crossover(mother_genetics[ch], father_genetics[ch], local); } } /** Y chromosome does not undergo crossover and passes from father to son */ if (sex != SEX_FEMALE) { genetics[CHROMOSOME_Y] = genetics_mutate(father_genetics[CHROMOSOME_Y], local); } else { genetics[CHROMOSOME_Y] = genetics_mutate(mother_genetics[CHROMOSOME_Y], local); } /** transpose genes between chromosomes */ genetics_transpose(genetics, local); /** align the sex genetics */ genetics[CHROMOSOME_Y] &= ~1; genetics[CHROMOSOME_Y] |= sex; } while (genetics_unique(beings, number, genetics) == 0); } /** * @brief Returns a string of letters representing the genome * @param maternal Show either the maternal or paternal side of each chromosome * @param genome The genome to be shown * @param genome_str The returned string */ void body_genome(n_byte maternal, n_genetics * genome, n_byte * genome_str) { n_byte string_point = 0; n_int ch, value; n_byte nucleotide[] = { 'A', 'T', 'C', 'G' }; /** for every chromosome */ for (ch = 0; ch < CHROMOSOMES; ch++) { /** for each 2 bit gene in the chromosome. Each chromosome is 16 bits long with the full 32 bit value containing the chromosome pair */ n_byte gene_point = 0; while (gene_point < 16) { if (maternal!=0) { /** the maternal part of the diplod */ value = ( CHROMOSOME_FROM_MOTHER(genome[ch]) >> gene_point ) & 3; } else { /** the paternal part of the diploid */ value = ( CHROMOSOME_FROM_FATHER(genome[ch]) >> gene_point ) & 3; } genome_str[string_point++] = nucleotide[value]; gene_point += 2; } } genome_str[string_point] = 0; } <|start_filename|>test/test_gui.c<|end_filename|> /**************************************************************** test_gui.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of Tom Barbalet, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #include <stdio.h> #include <time.h> #include "../toolkit/toolkit.h" #include "../toolkit/shared.h" #include "../script/script.h" #include "../sim/sim.h" #include "../entity/entity.h" #include "../universe/universe.h" #include "../gui/gui.h" void test_gui_run(void) { n_int counter = 0; n_int tickCounter = 0x12738291; n_byte drawBuffer[512 * 512 * 4]; shared_init(0,tickCounter); tickCounter += 2601; shared_init(1,tickCounter); tickCounter += 2601; shared_init(2,tickCounter); tickCounter += 2601; while (counter < (512*4)) { (void) shared_cycle(tickCounter, 0); tickCounter += 2601; (void) shared_cycle(tickCounter, 1); tickCounter += 2601; (void) shared_cycle(tickCounter, 2); tickCounter += 2601; shared_draw(drawBuffer, 0, 512, 512, 0); tickCounter += 2601; shared_draw(drawBuffer, 0, 512, 512, 1); tickCounter += 2601; shared_draw(drawBuffer, 0, 512, 512, 2); tickCounter += 2601; counter ++; } shared_close(); } int main(int argc, const char * argv[]) { printf(" --- test gui --- start -----------------------------------------------\n"); test_gui_run(); printf(" --- test gui --- end -----------------------------------------------\n"); return 0; } <|start_filename|>toolkit/console.c<|end_filename|> /**************************************************************** console.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /*! \file n_console.c * \brief Covers the low level input and output relating to console. */ #include <string.h> #include <stdlib.h> #include <stdio.h> #include "toolkit.h" simulated_console_command * local_commands = 0L; static n_int command_line_execution; static n_int command_line_external_exit = 0; void io_command_line_execution_set(void) { command_line_execution = 1; } n_int io_command_line_execution(void) { return command_line_execution; } void io_entry_execution(n_int argc, n_string * argv) { if (argv) { if ((argc == 2) && (argv[1][0] == 'c')) { io_command_line_execution_set(); } } } void io_help_line(simulated_console_command * specific, n_console_output output_function) { n_string_block string_line = {0}; io_three_string_combination(string_line, specific->command, specific->addition, specific->help_information, 28); output_function(string_line); } n_int io_help(void * ptr, n_string response, n_console_output output_function) { n_int loop = 0; n_int response_len = 0; n_int found = 0; if (response != 0L) { response_len = io_length(response, 1024); } if (response_len == 0) { output_function("Commands:"); } do { if (local_commands[loop].function != 0L) { if ((local_commands[loop].help_information) && (local_commands[loop].help_information[0] != 0)) { if (response_len == 0) { io_help_line(&local_commands[loop], output_function); } else { n_int command_len = io_length(local_commands[loop].command, 1024); n_int count = io_find(response, 0, response_len, local_commands[loop].command, command_len); if (count == command_len) { io_help_line(&local_commands[loop], output_function); found = 1; } } } loop++; } } while (local_commands[loop].function != 0L); if ((response_len != 0) && (found == 0)) { (void)SHOW_ERROR("Command not found, type help for more information"); } return 0; } n_int io_quit(void * ptr, n_string response, n_console_output output_function) { return 1; } n_string io_console_entry_clean(n_string string, n_int length) { return fgets(string, (int)length, stdin); } n_string io_console_entry(n_string string, n_int length) { printf(">"); return io_console_entry_clean(string, length); } void io_console_out(n_constant_string value) { printf("%s\n", value); fflush(stdout); } void io_console_quit(void) { command_line_external_exit = 1; } n_int io_console(void * ptr, simulated_console_command * commands, n_console_input input_function, n_console_output output_function) { n_string_block buffer; local_commands = commands; if ((input_function)(buffer, STRING_BLOCK_SIZE) != 0L) { n_int loop = 0; n_int buffer_len = io_length(buffer, STRING_BLOCK_SIZE); if ((commands[0].command == 0L) && (commands[0].function == 0L)) { return SHOW_ERROR("No commands provided"); } /* captures linux, mac and windows line ending issue */ if (IS_RETURN(buffer[buffer_len-1])) { buffer[buffer_len-1] = 0; buffer_len--; } if (IS_RETURN(buffer[buffer_len-1])) { buffer[buffer_len-1] = 0; buffer_len--; } if (buffer_len != 0) { do { n_int command_len = io_length(commands[loop].command, 1024); n_int count = io_find((n_string)buffer, 0, buffer_len, commands[loop].command, command_len); if (count != -1) { n_int return_value; n_console * function = commands[loop].function; if (IS_SPACE(buffer[count])) { return_value = (*function)(ptr,(n_string)&buffer[count+1], output_function); if (command_line_external_exit) { return 1; } return return_value; } else if (buffer[count] == 0) { return_value = (*function)(ptr,0L, output_function); if (command_line_external_exit) { return 1; } return return_value; } } loop++; } while ((commands[loop].command != 0L) && (commands[loop].function != 0L)); (void)SHOW_ERROR("Command not found, type help for more information"); return 0; } else { return 0; } } return SHOW_ERROR("Console failure"); } <|start_filename|>test/test_object_string.c<|end_filename|> /**************************************************************** test_object_string.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #include "../toolkit/toolkit.h" #include <stdio.h> n_int draw_error(n_constant_string error_text, n_constant_string location, n_int line_number) { if (error_text) { printf("ERROR: %s @ %s %ld\n", (n_constant_string)error_text, location, line_number); } return -1; } void tof_gather(n_string file_in) { n_file local_file; n_file *output_file; n_int file_error = io_disk_read(&local_file, file_in); n_string file_out = io_string_copy(file_in); io_whitespace_json(&local_file); printf("%s --- \n", file_in); file_out[0]='2'; if (file_error != -1) { n_object * returned_object = object_file_to_tree(&local_file); if (returned_object) { output_file = obj_json(returned_object); if (output_file) { file_error = io_disk_write(output_file, file_out); io_file_free(&output_file); } obj_free(&returned_object); } } } void tof_gather_string(n_string file_in) { n_int length = io_length(file_in, STRING_BLOCK_SIZE); n_file local_file; local_file.data = (n_byte *)io_string_copy(file_in); local_file.location = 0; local_file.size = length; io_whitespace_json(&local_file); { n_object * returned_object = object_file_to_tree(&local_file); if (returned_object) { obj_free(&returned_object); } } memory_free((void**)&local_file.data); } #ifndef OBJECT_TEST int main(int argc, const char * argv[]) { #if 0 n_string example = "{\"general_variables\":\"test\",\"general_variables2\":{\"general_variables\":[1,2,4,5,9],\"general_variables2\":-12345,\"general_variables3\":{\"general_variables\":\"test\",\"general_variables2\":[\"hat\",\"cat\",\"horse\",\"rat\"],\"general_variables3\":\"test\"}},\"general_variables3\":\"test\"}"; n_string example = "{\"general_variables\":\"general_test\"}";/* good */ n_string example = "{\"general_variables\":[\"0\",\"1\",\"2\",\"3\"]}"; /* good*/ n_string example = "{\"general_variables\":[1,2,3,4]}"; /* good */ n_string example = "{\"general_variables\":[{\"agent\":\"yellow\"},{\"agent\":\"blue\"}]}"; /* good */ n_string example = "{\"general_variables2\":{\"general_variables\":[1,2,4,5,9],\"general_variables2\":-12345,\"general_variables3\":{\"general_variables\":\"test\",\"general_variables2\":[\"hat\",\"cat\",\"horse\",\"rat\"],\"general_variables3\":\"test\"}}}"; /*bad */ n_string example = "{\"general_variables2\":{\"general_variables\":[1,2,4,5,9],\"general_variables3\":{\"general_variables\":\"test\",\"general_variables2\":[\"hat\",\"cat\",\"horse\",\"rat\"]}}}";/* bad */ n_string example = "{\"general_variables2\":{\"general_variables\":[1,2,4,5,9],\"general_variables3\":{\"general_variables2\":[\"hat\",\"cat\",\"horse\",\"rat\"]}}}"; /* bad */ n_string example = "{\"general_variables2\":{\"general_variables3\":{\"general_variables2\":[\"hat\",\"cat\",\"horse\",\"rat\"]}}}"; /* good */ n_string example = "{\"general_variables2\":{\"general_variables\":[1,2,4,5,9],\"general_variables3\":{\"general_variables2\":[\"hat\",\"cat\",\"horse\",\"rat\"]}}}"; /* bad */ n_string example = "{\"general_variables\":[1,2,4,5,9],\"general_variables3\":{\"general_variables2\":[\"hat\",\"cat\",\"horse\",\"rat\"]}}"; /* bad */ n_string example = "{\"general_variables\":[1,2,4,5,9],\"general_variables3\":{\"general_variables2\":0}}"; /* bad */ n_string example = "{\"general_variables\":[1,2,4,5,9],\"general_variables3\":\"general_variables2\"}"; /* bad */ n_string example = "{\"general_variables\":2,\"general_variables3\":\"general_variables2\"}"; /* bad */ n_string example = "{\"general_variables\":2,\"general_variables3\":2}"; /* good */ #else n_string example = "{\"general_variables\":\"test\",\"general_variables2\":{\"general_variables\":[1,2,4,5,9],\"general_variables2\":-12345,\"general_variables3\":{\"general_variables\":\"test\",\"general_variables2\":[\"hat\",\"cat\",\"horse\",\"rat\"],\"general_variables3\":\"test\"}},\"general_variables3\":\"test\"}"; #endif tof_gather_string(example); return 0; } #endif <|start_filename|>test/battle.json<|end_filename|> {"general_variables":{"random0":58668,"random1":8717,"attack_melee_dsq":5,"declare_group_facing_dsq":8000,"declare_max_start_dsq":65535,"declare_one_to_one_dsq":65535,"declare_close_enough_dsq":5},"unit_types":[{"defence":4,"melee_attack":6,"melee_damage":3,"melee_armpie":1,"missile_attack":3,"missile_damage":4,"missile_armpie":1,"missile_rate":100,"missile_range":40,"speed_maximum":3,"stature":4,"leadership":2,"wounds_per_combatant":3,"type_id":0},{"defence":2,"melee_attack":3,"melee_damage":1,"melee_armpie":1,"missile_attack":0,"missile_damage":0,"missile_armpie":0,"missile_rate":0,"missile_range":0,"speed_maximum":4,"stature":1,"leadership":2,"wounds_per_combatant":2,"type_id":1},{"defence":4,"melee_attack":6,"melee_damage":2,"melee_armpie":2,"missile_attack":0,"missile_damage":0,"missile_armpie":0,"missile_rate":0,"missile_range":0,"speed_maximum":6,"stature":2,"leadership":4,"wounds_per_combatant":3,"type_id":2},{"defence":2,"melee_attack":7,"melee_damage":1,"melee_armpie":3,"missile_attack":0,"missile_damage":0,"missile_armpie":0,"missile_rate":0,"missile_range":0,"speed_maximum":7,"stature":2,"leadership":3,"wounds_per_combatant":1,"type_id":3}],"units":[{"type_id":0,"width":28,"average":[100,200],"angle":120,"number_combatants":480,"alignment":0,"missile_number":20},{"type_id":0,"width":28,"average":[100,400],"angle":128,"number_combatants":480,"alignment":0,"missile_number":20},{"type_id":0,"width":28,"average":[100,600],"angle":136,"number_combatants":480,"alignment":0,"missile_number":20},{"type_id":2,"width":10,"average":[250,400],"angle":128,"number_combatants":100,"alignment":0,"missile_number":0},{"type_id":2,"width":10,"average":[265,200],"angle":128,"number_combatants":100,"alignment":0,"missile_number":0},{"type_id":0,"width":50,"average":[500,200],"angle":0,"number_combatants":600,"alignment":1,"missile_number":20},{"type_id":2,"width":35,"average":[500,600],"angle":0,"number_combatants":100,"alignment":1,"missile_number":0},{"type_id":0,"width":40,"average":[700,600],"angle":0,"number_combatants":600,"alignment":1,"missile_number":20},{"type_id":3,"width":40,"average":[600,600],"angle":0,"number_combatants":200,"alignment":1,"missile_number":0}]} <|start_filename|>entity/episodic.c<|end_filename|> /**************************************************************** episodic.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of Tom Barbalet, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /*! \file episodic.c * \brief This handles episodic memory */ #include "entity.h" #include "entity_internal.h" /*! /file episodic.c * /brief Functions relating to updates of episodic memories and intentions. */ #ifdef EPISODIC_ON static n_console_output * local_logging; static n_int local_social; void episodic_logging(n_console_output * output_function, n_int social) { local_logging = output_function; local_social = social; } /** * @brief If the given episodic memory is an intention, as defined by the event type, * then update the learned preferences based upon the intention type. * For example, if the ape intends to chat then the chatting preference * may be increased which makes chatting more likely. * @param local pointer to the particular ape * @param episode_index array index of the episodic memory representing the intention */ static void episodic_intention_update(simulated_being * local, n_int episode_index) { simulated_iepisodic * local_episodic = being_episodic(local); n_byte event; n_int learned_preference_index=-1; if (local_episodic == 0L) { return; } event = local_episodic[episode_index].event - EVENT_INTENTION; switch(event) { case EVENT_CHAT: { learned_preference_index = PREFERENCE_CHAT; break; } case EVENT_GROOM: { if ((local_episodic[episode_index].arg&2)!=0) { learned_preference_index = PREFERENCE_GROOM_MALE; } else { learned_preference_index = PREFERENCE_GROOM_FEMALE; } break; } } /** alter preferences */ if (learned_preference_index>-1) { if ((local_episodic[episode_index].arg&1)!=0) { if (local->changes.learned_preference[learned_preference_index]<255) { local->changes.learned_preference[learned_preference_index]++; } } else { if (local->changes.learned_preference[learned_preference_index]>0) { local->changes.learned_preference[learned_preference_index]--; } } } } /** * @brief Update the episodic memories for a given ape. * This is based upon a fading memory model in which older memories * are replaced by newer ones. Each memory has an associated affect * value indicating its emotional impact, and this fades over time. * * The rate of fading is genetically regulated, with different rates * for memories with positive and negative affect. * This facilitates optimistic/pessimistic and forgetful/memorable * type personalities. * * The fading memory model may not be strictly realistic, and might * be replaced by something else in future. * @param local_being pointer to the ape */ void episodic_cycle_no_sim(simulated_being * local_being, void * data) { if (local_being->delta.awake == 0) return; { n_int i; simulated_iepisodic * local_episodic = being_episodic(local_being); n_genetics * genetics = being_genetics(local_being); if (!local_episodic) return; for (i=0; i<EPISODIC_SIZE; i++) { if (local_episodic[i].event == 0) continue; /** remove intentions which are outdated */ if (local_episodic[i].event >= EVENT_INTENTION) { /** is this my intention, or someone else's? */ if (being_name_comparison(local_being, local_episodic[i].first_name[BEING_MEETER], local_episodic[i].family_name[BEING_MEETER])) { if (spacetime_before_now(&local_episodic[i].space_time)) { local_episodic[i].event = 0; continue; } } episodic_intention_update(local_being, i); } /** fade towards EPISODIC_AFFECT_ZERO */ if (local_episodic[i].affect < EPISODIC_AFFECT_ZERO) { /** negative memories fade */ if (EPISODIC_AFFECT_ZERO - local_episodic[i].affect > 16) { local_episodic[i].affect+=(1+GENE_NEGATIVE_AFFECT_FADE(genetics)); } else { local_episodic[i].affect++; } } else { if (local_episodic[i].affect > EPISODIC_AFFECT_ZERO) { /** positive memories fade */ if (local_episodic[i].affect - EPISODIC_AFFECT_ZERO > 16) { local_episodic[i].affect-=(1+GENE_POSITIVE_AFFECT_FADE(genetics)); } else { local_episodic[i].affect--; } } } } } } /** * @brief Returns a celebrity factor based upon how many apes within * the episodic memory of the given ape have a similar name to the * met ape, and their friend or foe values. * This means that initial beliefs about other apes are partly * a form of stereotyping * @param meeter_being pointer to the ape * @param met_being pointer to another ape * @return celebrity value of the met ape */ n_int episodic_met_being_celebrity( simulated_being * meeter_being, simulated_being * met_being) { n_int i,j,celebrity=0,ctr,aff; simulated_iepisodic * meeter_episodic = being_episodic(meeter_being); n_byte2 first_name = being_gender_name(met_being); n_byte2 family_name = being_family_name(met_being); if (!meeter_episodic) return 0; /** check all episodic memories of the meeter */ for (i=0; i<EPISODIC_SIZE; i++) { aff = (n_int)(meeter_episodic[i].affect) - EPISODIC_AFFECT_ZERO; if (aff>1) aff=1; if (aff<-1) aff=-1; /** check both the meeter and the met ape for each memory */ for (j=BEING_MEETER; j<=BEING_MET; j++) { ctr=0; /** same first name */ if (meeter_episodic[i].first_name[j]==first_name) { celebrity+=aff; ctr++; } /** same family name */ if (meeter_episodic[i].family_name[j]==family_name) { celebrity+=aff; ctr++; } /** if both first name and family name match then increase the celebrity value further */ if (ctr==2) { celebrity+=aff*2; } } } /** limit within range */ if (celebrity>16) celebrity=16; if (celebrity<-16) celebrity=-16; return celebrity; } /** * @brief This returns the percentage of episodic memories or intentions which are first person. * Some memories originate from the self and others are acquired from others via chatting. * @param local pointer to the ape * @param intention 0=episodic memories, 1=intentions * @return percentage in the range 0-100 */ n_int episodic_first_person_memories_percent( simulated_being * local, n_byte intention) { n_int i,hits=0,memories=0; simulated_iepisodic * local_episodic = being_episodic(local); if (local_episodic == 0L) { return 0; } /** examine all memories */ for (i=0; i<EPISODIC_SIZE; i++) { if (local_episodic[i].event>0) { if (intention!=0) { /** ratio of intentions to other memories */ if (local_episodic[i].event >= EVENT_INTENTION) { hits++; } } else { /** ratio of first person memories to other memories */ if (being_name_comparison(local, local_episodic[i].first_name[BEING_MEETER], local_episodic[i].family_name[BEING_MEETER])) { hits++; } } memories++; } } if (memories>0) { return hits*100/memories; } else { if (intention!=0) { return 0; } return 100; } } /** * @brief Returns the index of the the episodic memory which can be overwritten with a new one. * @param event The type of event * @param affect The affect value associated with the event * @param name1 Name of the first ape in the memory (meeter) * @param family1 Family name of the first ape in the memory (meeter) * @param name2 Name of the second ape in the memory (met) * @param family2 Family name of the second ape in the memory (met) * @param local Pointer to the ape * @return array index of the episodic memory which can be replaced. */ static n_int simulated_iepisodic_replace_index( being_episodic_event_type event, n_int affect, n_byte2 name1, n_byte2 family1, n_byte2 name2, n_byte2 family2, simulated_being * local) { /** absolute affect value */ n_int abs_aff = affect; n_int i; n_int replace=-1; n_int min; n_byte event_exists=0; simulated_iepisodic * local_episodic = being_episodic(local); if (!local_episodic) return -1; /** replace only events with an affect lower then the current */ abs_aff = ABS(abs_aff); min = abs_aff; for (i=0; i<EPISODIC_SIZE; i++) { /** is this the same type of event */ if (local_episodic[i].event == event) { /** is this the same being? */ if ((local_episodic[i].first_name[BEING_MEETER]==name1) && (local_episodic[i].family_name[BEING_MEETER]==family1)) { /** get absolute affect value */ n_int aff1 = ABS((n_int)(local_episodic[i].affect)-EPISODIC_AFFECT_ZERO); /** does this have the least affect (most forgettable) */ event_exists = 1; if (aff1 <= min) { min = aff1; replace = i; } } } } if (event_exists==0) { /** Use any empty memory slots */ for (i=0; i<EPISODIC_SIZE; i++) { if (local_episodic[i].event == 0) { return i; } } /** no event of this type was found, so search for any event with the lowest affect */ min = abs_aff; for (i=0; i<EPISODIC_SIZE; i++) { /** get absolute affect value */ n_int aff1 = ABS((n_int)(local_episodic[i].affect)-EPISODIC_AFFECT_ZERO); /** does this have the least affect (most forgettable) */ if (aff1 < min) { min = aff1; replace = i; } } } return replace; } /** * @brief Stores an episodic memory * @param local Pointer to the being * @param event The type of event * @param affect Affect value associated with the event * @param name1 First name of a being participating in the event * @param family1 Family names of a being participating in the event * @param name2 First name of a second being participating in the event * @param family2 Family names of a second being participating in the event * @param arg Any additional argument * @param food Type of food */ static void episodic_store_full( simulated_being * local, being_episodic_event_type event, n_int affect, n_byte2 name1, n_byte2 family1, n_byte2 name2, n_byte2 family2, n_byte2 arg, n_byte food) { simulated_iepisodic * local_episodic = being_episodic(local); n_int replace; n_byte old_event; n_byte4 old_time; n_byte4 new_time; if (local_episodic == 0L) { return; } if (local->delta.awake == FULLY_ASLEEP) return; replace = simulated_iepisodic_replace_index(event,affect,name1,family1,name2,family2,local); if (replace == -1) return; old_event = local_episodic[replace].event; old_time = local_episodic[replace].space_time.time; /** insert the current event into the episodic memory */ local_episodic[replace].event = event; local_episodic[replace].affect = (n_byte2)(affect+EPISODIC_AFFECT_ZERO); spacetime_set(&local_episodic[replace].space_time, being_location(local)); new_time = local_episodic[replace].space_time.time; local_episodic[replace].first_name[BEING_MEETER]=name1; local_episodic[replace].family_name[BEING_MEETER]=family1; local_episodic[replace].first_name[BEING_MET]=name2; local_episodic[replace].family_name[BEING_MET]=family2; local_episodic[replace].food=food; local_episodic[replace].arg=arg; if ((event == 0) || (event>=EVENTS)) { (void)SHOW_ERROR("Event outside scope"); } if (local_logging) { if ((old_event != event) /*|| ((old_time+10) < (new_time))*/) /**< TODO this may need to be changed */ { n_string_block description = {0}; n_string_block str = {0}; n_string_block time = {0}; n_string_block combination = {0}; n_int social_event; social_event = episode_description(local, replace, description); if ((local_social == 1) && (social_event == 0)) { return; } being_name_simple(local, str); io_time_to_string(time); io_three_string_combination(combination, time, str, description, 35); (*local_logging)(combination); } } } /** * @brief Remember eating * @param local Pointer to the being * @param energy Energy obtained from food * @param food_type The type of food */ void episodic_food(simulated_being * local, n_int energy, n_byte food_type) { episodic_store_full(local, EVENT_EAT, energy, being_gender_name(local), being_family_name(local), 0, 0, 0, food_type); } /** * @brief Updates the episodic memory with details about an event * @param local Pointer to the ape * @param event The type of event * @param affect The affect value associated with the event * @param name1 Name of the first ape in the memory (meeter) * @param family1 Family name of the first ape in the memory (meeter) * @param name2 Name of the second ape in the memory (met) * @param family2 Family name of the second ape in the memory (met) * @param arg Any additional arguments */ void episodic_store_memory( simulated_being * local, being_episodic_event_type event, AFFECT_TYPE affect, n_byte2 name1, n_byte2 family1, n_byte2 name2, n_byte2 family2, n_byte2 arg) { episodic_store_full(local, event,affect,name1,family1,name2,family2, arg, 0); } /** * @brief Store an episodic memory about the self * @param local Pointer to the being * @param event The type of event * @param affect An affect value associated with the event * @param arg Any additional argument */ void episodic_self( simulated_being * local, being_episodic_event_type event, AFFECT_TYPE affect, n_byte2 arg) { episodic_store_memory(local, event, affect, being_gender_name(local), being_family_name(local), 0, 0, arg); } /** * @brief Remember an event which occurred between being in close proximity * @param local Pointer to the first being * @param other Pointer to the second being * @param event The type of event * @param affect Affect value associated with the event * @param arg Any additional argument */ void episodic_close( simulated_being * local, simulated_being * other, being_episodic_event_type event, AFFECT_TYPE affect, n_byte2 arg) { episodic_store_memory( local, event, affect, being_gender_name(other), being_family_name(other), 0, 0, arg); } /** * @brief Remember a particular interaction between two beings * @param local Pointer to the being * @param other Pointer to the being being interacted with * @param event The type of event * @param affect The affect associated with the interaction * @param arg Any additional argument */ void episodic_interaction( simulated_being * local, simulated_being * other, being_episodic_event_type event, AFFECT_TYPE affect, n_byte2 arg) { episodic_store_memory( local, event, affect, being_gender_name(local),being_family_name(local), being_gender_name(other),being_family_name(other), arg); } /** * @brief Generate an intention. * Note that intentions are stored together with episodic memories, * with the event type making the difference between a memory about * the past and an intention about the future. * @param local Pointer to the ape * @param episode_index Episodic memory array index to use. * @param mins_ahead The number of minutes into the future for which the intention will last. * @param args Any additional arguments * @return Returns 1 if the update was successful, or 0 otherwise. */ n_byte episodic_intention( simulated_being * local, n_int episode_index, n_byte2 mins_ahead, n_byte args) { n_byte4 date; n_byte4 time; n_int replace; n_byte event; simulated_iepisodic * local_episodic = being_episodic(local); if (local_episodic == 0L) { return 0; } event = local_episodic[episode_index].event; if (event==0) return 0; time = land_time(); date = local_episodic[episode_index].space_time.date; if (time >= TIME_DAY_MINUTES) { /** increment date by one day */ time %= TIME_DAY_MINUTES; date++; } if (event >= EVENT_INTENTION) { /** extend the time of an existing intention */ local_episodic[episode_index].space_time.time = time; local_episodic[episode_index].space_time.date = date; local_episodic[episode_index].arg = args; /** if this was someone else's intention it now becomes yours */ local_episodic[episode_index].first_name[BEING_MEETER] = being_gender_name(local); local_episodic[episode_index].family_name[BEING_MEETER] = being_family_name(local); return 1; } /** only certain types of events become intentions */ if (!((event==EVENT_GROOM) || (event==EVENT_CHAT))) { return 0; } /** find a memory index to replace */ replace = simulated_iepisodic_replace_index( EVENT_INTENTION + event, (n_int)(local_episodic[episode_index].affect)-EPISODIC_AFFECT_ZERO, being_gender_name(local), being_family_name(local), local_episodic[episode_index].first_name[BEING_MET], local_episodic[episode_index].family_name[BEING_MET], local); if (replace == -1) { return 0; } if (replace == episode_index) { return 0; } memory_copy((n_byte*)&local_episodic[episode_index], (n_byte*)&local_episodic[replace], sizeof(simulated_iepisodic)); local_episodic[replace].event = EVENT_INTENTION + event; local_episodic[replace].space_time.time = time; local_episodic[replace].space_time.date = date; local_episodic[replace].first_name[BEING_MEETER] = being_gender_name(local); local_episodic[replace].family_name[BEING_MEETER] = being_family_name(local); local_episodic[replace].arg = args; return 1; } /** * @brief Copy an episodic memory (an anecdote) from one ape to another during chat. * @param local Pointer to the ape conveying the anecdote * @param other Pointer to the ape to which the anecdote will be copied * @return Returns 1 if the copy was successful, 0 otherwise */ n_byte episodic_anecdote( simulated_being * local, simulated_being * other) { simulated_iepisodic * local_episodic = being_episodic(local); simulated_iepisodic * other_episodic = being_episodic(other); n_int affect; n_byte event; n_int replace,mult=1; if (local_episodic == 0L || other_episodic == 0L || local == other) { return 0; } affect = (n_int)(local_episodic[being_attention(local,ATTENTION_EPISODE)].affect)-EPISODIC_AFFECT_ZERO; event = local_episodic[being_attention(local,ATTENTION_EPISODE)].event; /** both protagonists must be awake */ if ((event==0) || (local->delta.awake == FULLY_ASLEEP) || (other->delta.awake == FULLY_ASLEEP)) { return 0; } if (local->delta.awake != FULLY_AWAKE) { /** more likely to make errors while drowsy */ mult=2; } /** mutate with some probability */ if (being_random(local) < (ANECDOTE_EVENT_MUTATION_RATE+ (local->changes.learned_preference[PREFERENCE_ANECDOTE_EVENT_MUTATION])*100)*mult) { event = (n_byte)(being_random(local) % EVENTS); } if (being_random(local) < (ANECDOTE_AFFECT_MUTATION_RATE+ (local->changes.learned_preference[PREFERENCE_ANECDOTE_AFFECT_MUTATION])*100)*mult) { /** affect gets exaggerated or downplayed */ affect = (affect * (64 + (n_int)(being_random(local) & 127))) / 128; /** keep affect within range */ if (affect<-32000) affect=-32000; if (affect>32000) affect=32000; } /** find an index within the other episodic memory in which to insert */ replace = simulated_iepisodic_replace_index( event,affect, local_episodic[being_attention(local,ATTENTION_EPISODE)].first_name[BEING_MEETER], local_episodic[being_attention(local,ATTENTION_EPISODE)].family_name[BEING_MEETER], local_episodic[being_attention(local,ATTENTION_EPISODE)].first_name[BEING_MET], local_episodic[being_attention(local,ATTENTION_EPISODE)].family_name[BEING_MET], local); if (replace==-1) return 0; other_episodic[replace] = local_episodic[being_attention(local,ATTENTION_EPISODE)]; other_episodic[replace].event = event; other_episodic[replace].affect = (n_byte2)(affect+EPISODIC_AFFECT_ZERO); /** other ape pays attention to the incoming anecdote */ being_set_attention(local, ATTENTION_EPISODE, replace); return 1; } #else /** * An empty function */ void episodic_interaction( simulated_being * local, simulated_being * other, being_episodic_event_type event, AFFECT_TYPE affect, n_byte2 arg) { } /** * An empty function */ void episodic_store_memory( simulated_being * local, being_episodic_event_type event, AFFECT_TYPE affect, n_byte2 name1, n_byte2 family1, n_byte2 name2, n_byte2 family2, n_byte2 arg) { } #endif <|start_filename|>toolkit/object.c<|end_filename|> /**************************************************************** object.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /*! \file object.c * \brief Provides a primitive object type to allow for dynamic * object creation and also reading and writing in a * JSON format. */ #include "toolkit.h" #include <stdio.h> static void object_write_object(n_file * file, n_object *start); static void object_write_array(n_file * file, n_array *start); #undef OBJECT_DEBUG #undef OBJECT_RETAIN1 #define OBJECT_RETAIN2 // diff name #define OBJECT_RETAIN3 // warfare to run but with leak #ifdef OBJECT_RETAIN1 #define STRING_COPY1(value) io_string_copy(value) #else #define STRING_COPY1(value) (value) #endif #ifdef OBJECT_RETAIN2 #define STRING_COPY2(value) io_string_copy(value) #else #define STRING_COPY2(value) (value) #endif #ifdef OBJECT_RETAIN3 #define STRING_COPY3(value) io_string_copy(value) #else #define STRING_COPY3(value) (value) #endif #ifdef OBJECT_DEBUG #define OBJ_DBG( test, string ) if (test == 0L) printf("%s\n", string) #else #define OBJ_DBG( test, string ) /* test string */ #endif static n_object * object_file_base(n_file * file); static n_object_type object_type(n_array * array) { return array->type; } static void object_erase(n_object * object) { memory_erase((n_byte*)object, sizeof(n_object)); } static n_object * object_new(void) { n_object * return_object = (n_object *)memory_new(sizeof(n_object)); if (return_object) { object_erase(return_object); } return return_object; } void obj_free(n_object ** object); static void obj_free_array(n_int is_array, void ** payload, n_object_type type) { n_array *array = 0L; if (is_array) { array = (n_array *)(*payload); } else { n_object * array_object = (n_object *)(*payload); array = (n_array *)&(array_object->primitive); } if (type == OBJECT_NUMBER) { } if (type == OBJECT_STRING) { memory_free((void**)&array->data); } if (type == OBJECT_ARRAY) { n_array *local_array = obj_get_array(array->data); obj_free_array(1, (void**)&local_array, local_array->type); } if (type == OBJECT_OBJECT) { n_object *object = obj_get_object(array->data); obj_free(&object); } if (array->next) { if (is_array) { n_array * next_array = (n_array *)array->next; obj_free_array(1, (void **)&next_array, next_array->type); } else { obj_free((n_object **)&array->next); } } memory_free(payload); } void obj_free(n_object ** object) { n_array *string_primitive = &((*object)->primitive); memory_free((void**)&(*object)->name); obj_free_array(0, (void **) object, string_primitive->type); } void object_top_object(n_file * file, n_object * top_level) { io_write(file, "{", 0); object_write_object(file, top_level); io_write(file, "}", 0); } static void object_top_array(n_file * file, n_array * top_level) { io_write(file, "[", 0); object_write_array(file, top_level); io_write(file, "]", 0); } static void * object_write_primitive(n_file * file, n_array * primitive) { switch (object_type(primitive)) { case OBJECT_NUMBER: { n_int * int_data = (n_int *)&primitive->data; io_writenumber(file, int_data[0],1,0); } break; case OBJECT_STRING: io_write(file, "\"", 0); io_write(file, primitive->data, 0); io_write(file, "\"", 0); break; case OBJECT_OBJECT: object_top_object(file, (n_object *)primitive->data); break; case OBJECT_ARRAY: object_top_array(file, (n_array *)primitive->data); break; default: (void)SHOW_ERROR("Object kind not found"); return 0L; } if (primitive->next) { io_write(file, ",", 0); } return primitive->next; } n_array * obj_get_array(n_string array) { return (n_array *)array; } n_object * obj_get_object(n_string object) { return (n_object *)object; } n_int obj_get_number(n_string object) { n_int * data = (n_int *)&object; return data[0]; } static void object_write_object(n_file * file, n_object *start) { n_object * current = start; do{ io_write(file, "\"", 0); io_write(file, current->name, 0); io_write(file, "\":", 0); current = (n_object *)object_write_primitive(file, &current->primitive); }while (current); } static void object_write_array(n_file * file, n_array *start) { n_array * current = start; do{ current = (n_array *)object_write_primitive(file, current); }while (current); } n_file * obj_json(n_object * object) { n_file * output_file = io_file_new(); object_top_object(output_file, object); return output_file; } static n_object * object_end_or_find(n_object * object, n_string name) { n_object * previous_object = 0L; n_int string_length = io_length(name, STRING_BLOCK_SIZE); if (string_length > 0) { n_uint hash = math_hash((n_byte *)name, (n_uint) string_length); if (object == 0L) { return 0L; } do { if (hash == object->name_hash) { return previous_object; } previous_object = object; object = object->primitive.next; }while (object); } return previous_object; } static n_object * obj_get(n_object * object, n_string name) { n_object * set_object; n_int string_length = io_length(name, STRING_BLOCK_SIZE); if (string_length > 0) { n_uint hash = math_hash((n_byte *)name, (n_uint)string_length); if (object == 0L) { object = object_new(); } if (object_type(&object->primitive) == OBJECT_EMPTY) { set_object = object; } else { n_object * previous_object = object_end_or_find(object, name); if (previous_object == 0L) { set_object = object; } else { set_object = previous_object->primitive.next; if (set_object == 0L) { set_object = object_new(); } previous_object->primitive.next = set_object; } } set_object->name = STRING_COPY1(name); set_object->name_hash = hash; return set_object; } return 0L; } n_array * array_add(n_array * array, n_array * element) { if (array) { n_array * next = array; do{ if (next->next) { next = next->next; } }while (next->next); next->next = element; } return element; } static void * ar_pass_through(void * ptr) { if (ptr == 0L) { ptr = memory_new(sizeof(n_array)); if (ptr) { memory_erase((n_byte *)ptr, sizeof(n_array)); } } return ptr; } static void * ar_number(void * ptr, n_int set_number) { n_array * cleaned = (n_array *)ar_pass_through(ptr); if (cleaned) { n_int * number; cleaned->type = OBJECT_NUMBER; number = (n_int *)&cleaned->data; number[0] = set_number; } return (void *)cleaned; } static void * ar_string(void * ptr, n_string set_string) { n_array * cleaned = (n_array *)ar_pass_through(ptr); if (cleaned) { cleaned->type = OBJECT_STRING; cleaned->data = STRING_COPY2(set_string); } return (void *)cleaned; } static void * ar_object(void * ptr, n_object * set_object) { n_array * cleaned = (n_array *)ar_pass_through(ptr); if (cleaned) { cleaned->type = OBJECT_OBJECT; cleaned->data = (n_string)set_object; } return (void *)cleaned; } static void * ar_array(void * ptr, n_array * set_array) { n_array * cleaned = (n_array *)ar_pass_through(ptr); if (cleaned) { cleaned->type = OBJECT_ARRAY; cleaned->data = (n_string)set_array; } return (void *)cleaned; } n_array * array_number(n_int set_number) { return ar_number(0L, set_number); } n_array * array_string(n_string set_string) { return ar_string(0L, set_string); } n_array * array_object(n_object * set_object) { return ar_object(0L, set_object); } n_array * array_array(n_array * set_array) { return ar_array(0L, set_array); } static n_object * obj_number(n_object * obj, n_string name, n_int number) { return ar_number(obj_get(obj, name), number); } static n_object * obj_string(n_object * obj, n_string name, n_string string) { return ar_string(obj_get(obj, name), string); } static n_object * obj_object(n_object * obj, n_string name, n_object * object) { return ar_object(obj_get(obj, name), object); } static n_object * obj_array(n_object * obj, n_string name, n_array * array) { return ar_array(obj_get(obj, name), array); } n_object * object_number(n_object * obj, n_string name, n_int number) { return obj_number(obj, io_string_copy(name), number); } n_object * object_string(n_object * obj, n_string name, n_string string) { return obj_string(obj, io_string_copy(name), string); } n_object * object_object(n_object * obj, n_string name, n_object * object) { return obj_object(obj, io_string_copy(name), object); } n_object * object_array(n_object * obj, n_string name, n_array * array) { return obj_array(obj, io_string_copy(name), array); } static n_int tracking_array_open; static n_int tracking_object_open; static n_int tracking_string_quote; #define CHECK_FILE_SIZE(error_string) if (file->location >= file->size) \ { \ (void)SHOW_ERROR(error_string); \ return 0L; \ } static n_string object_file_read_string(n_file * file) { n_string return_string = 0L; n_string_block block_string = {0}; n_int location = 0; if (file->data[file->location] != '"') // TODO: Replace with smart char handling { (void)SHOW_ERROR("json not string as expected"); return return_string; } tracking_string_quote = 1; file->location ++; do{ CHECK_FILE_SIZE("end of json file reach unexpectedly"); if(file->data[file->location] != '"') { block_string[location] = (n_char)file->data[file->location]; location++; file->location++; } }while (file->data[file->location] != '"'); if (location == 0) { (void)SHOW_ERROR("blank string in json file"); return 0L; } tracking_string_quote = 0; file->location++; CHECK_FILE_SIZE("end of json file reach unexpectedly"); return_string = STRING_COPY3(block_string); return return_string; } static n_int object_file_read_number(n_file * file, n_int * with_error) { n_int return_number = 0; n_string_block block_string = {0}; n_int location = 0; n_byte read_char = file->data[file->location]; n_int char_okay = (ASCII_NUMBER(read_char) || (read_char == '-')); *with_error = 1; if (!char_okay) { (void)SHOW_ERROR("first character not number or minus"); return 0; } CHECK_FILE_SIZE("end of json file reach unexpectedly for number"); block_string[location] = (n_char)read_char; file->location++; location++; do{ read_char = file->data[file->location]; char_okay = ASCII_NUMBER(read_char); CHECK_FILE_SIZE("end of json file reach unexpectedly for number"); if(char_okay) { block_string[location] = (n_char)read_char; location++; file->location++; } }while (char_okay); { n_int actual_value = 1; n_int decimal_divisor = 1; n_int error_number = io_number((n_string)block_string, &actual_value, &decimal_divisor); if (error_number == -1) { return 0; } if (decimal_divisor != 0) { (void)SHOW_ERROR("decimal number in json file"); return 0; } return_number = actual_value; } *with_error = 0; return return_number; } static n_object_stream_type object_stream_char(n_byte value) { if (value == '{') { return OBJ_TYPE_OBJECT_OPEN; } if (value == '}') { return OBJ_TYPE_OBJECT_CLOSE; } if (value == '[') { return OBJ_TYPE_ARRAY_OPEN; } if (value == ']') { return OBJ_TYPE_ARRAY_CLOSE; } if (ASCII_NUMBER(value) || (value == '-')) { return OBJ_TYPE_NUMBER; } if (ASCII_COMMA(value)) { return OBJ_TYPE_COMMA; } if (ASCII_COLON(value)) { return OBJ_TYPE_COLON; } if (ASCII_QUOTE(value)) { return OBJ_TYPE_STRING_NOTATION; } return OBJ_TYPE_EMPTY; } static n_array * object_file_array(n_file * file) { n_array * base_array = 0L; n_object_stream_type stream_type; n_object_stream_type stream_type_in_this_array = OBJ_TYPE_EMPTY; if (file->data[file->location] != '[') // TODO: Replace with smart char handling { (void)SHOW_ERROR("json not array as expected"); return base_array; } tracking_array_open ++; file->location ++; do{ CHECK_FILE_SIZE("end of json file reach unexpectedly"); stream_type = object_stream_char(file->data[file->location]); if (stream_type_in_this_array == OBJ_TYPE_EMPTY) { stream_type_in_this_array = stream_type; } else if (stream_type_in_this_array != stream_type) { (void)SHOW_ERROR("array contains mutliple types"); return 0L; } if (stream_type == OBJ_TYPE_ARRAY_OPEN) { n_array * array_value = object_file_array(file); if (array_value) { stream_type = object_stream_char(file->data[file->location]); if ((stream_type == OBJ_TYPE_ARRAY_CLOSE) || (stream_type == OBJ_TYPE_COMMA)) { if (base_array == 0L) { base_array = array_array(array_value); } else { array_add(base_array, array_array(array_value)); } } } stream_type = object_stream_char(file->data[file->location]); } if (stream_type == OBJ_TYPE_OBJECT_OPEN) { n_object * object_value = object_file_base(file); OBJ_DBG(object_value, "object value is nil?"); if (object_value) { file->location++; CHECK_FILE_SIZE("end of json file reach unexpectedly"); stream_type = object_stream_char(file->data[file->location]); if ((stream_type == OBJ_TYPE_ARRAY_CLOSE) || (stream_type == OBJ_TYPE_COMMA)) { if (base_array == 0L) { base_array = array_object(object_value); } else { array_add(base_array, array_object(object_value)); } } } OBJ_DBG(base_array, "base array still nil?"); CHECK_FILE_SIZE("end of json file reach unexpectedly"); stream_type = object_stream_char(file->data[file->location]); } if (stream_type == OBJ_TYPE_STRING_NOTATION) { n_string string_value = object_file_read_string(file); if (string_value) { stream_type = object_stream_char(file->data[file->location]); if ((stream_type == OBJ_TYPE_ARRAY_CLOSE) || (stream_type == OBJ_TYPE_COMMA)) { if (base_array == 0L) { base_array = array_string(string_value); } else { array_add(base_array, array_string(string_value)); } } } stream_type = object_stream_char(file->data[file->location]); } if (stream_type == OBJ_TYPE_NUMBER) { n_int with_error; n_int number_value = object_file_read_number(file, &with_error); if (with_error == 0) { stream_type = object_stream_char(file->data[file->location]); if ((stream_type == OBJ_TYPE_ARRAY_CLOSE) || (stream_type == OBJ_TYPE_COMMA)) { if (base_array == 0L) { base_array = array_number(number_value); } else { array_add(base_array, array_number(number_value)); } } } stream_type = object_stream_char(file->data[file->location]); } if (stream_type == OBJ_TYPE_ARRAY_CLOSE) { tracking_array_open --; } file->location ++; OBJ_DBG(base_array, "base array nil check?"); }while (stream_type == OBJ_TYPE_COMMA); OBJ_DBG(base_array, "base array really nil?"); return base_array; } static n_object * object_file_base(n_file * file) { n_object * base_object = 0L; n_object_stream_type stream_type; CHECK_FILE_SIZE("file read outside end of file"); stream_type = object_stream_char(file->data[file->location]); if (stream_type == OBJ_TYPE_OBJECT_OPEN) { tracking_object_open++; do{ file->location++; CHECK_FILE_SIZE("file read outside end of file"); stream_type = object_stream_char(file->data[file->location]); if (stream_type == OBJ_TYPE_STRING_NOTATION) { n_string string_key = object_file_read_string(file); if (string_key) { stream_type = object_stream_char(file->data[file->location]); if (stream_type == OBJ_TYPE_COLON) { file->location++; CHECK_FILE_SIZE("file read outside end of file"); stream_type = object_stream_char(file->data[file->location]); if (stream_type == OBJ_TYPE_OBJECT_OPEN) { n_object * insert_object = object_file_base(file); if (insert_object) { if (base_object) { obj_object(base_object, string_key, insert_object); } else { base_object = obj_object(base_object, string_key, insert_object); } file->location++; CHECK_FILE_SIZE("file read outside end of file"); stream_type = object_stream_char(file->data[file->location]); } } if (stream_type == OBJ_TYPE_NUMBER) { n_int number_error; n_int number_value = object_file_read_number(file, &number_error); if (number_error == 0) { stream_type = object_stream_char(file->data[file->location]); if ((stream_type == OBJ_TYPE_OBJECT_CLOSE) || (stream_type == OBJ_TYPE_COMMA)) { if (base_object) { obj_number(base_object, string_key, number_value); } else { base_object = obj_number(base_object, string_key, number_value); } } } } if (stream_type == OBJ_TYPE_STRING_NOTATION) { n_string string_value = object_file_read_string(file); if (string_value) { stream_type = object_stream_char(file->data[file->location]); if ((stream_type == OBJ_TYPE_OBJECT_CLOSE) || (stream_type == OBJ_TYPE_COMMA)) { if (base_object) { obj_string(base_object, string_key, string_value); } else { base_object = obj_string(base_object, string_key, string_value); } } } } if (stream_type == OBJ_TYPE_ARRAY_OPEN) { n_array * array_value = object_file_array(file); // TODO: rename object_file_read_array if (array_value) { stream_type = object_stream_char(file->data[file->location]); if ((stream_type == OBJ_TYPE_OBJECT_CLOSE) || (stream_type == OBJ_TYPE_COMMA)) { if (base_object) { obj_array(base_object, string_key, array_value); } else { base_object = obj_array(base_object, string_key, array_value); } } CHECK_FILE_SIZE("file read outside end of file"); stream_type = object_stream_char(file->data[file->location]); } OBJ_DBG(array_value, "array value nil?"); } } } } if (stream_type == OBJ_TYPE_OBJECT_CLOSE) { tracking_object_open--; } } while (stream_type == OBJ_TYPE_COMMA); } return base_object; } n_object * object_file_to_tree(n_file * file) { n_object * base_object = 0L; n_int something_wrong = 0; tracking_array_open = 0; tracking_object_open = 0; tracking_string_quote = 0; io_whitespace_json(file); file->location = 0; base_object = object_file_base(file); if (tracking_array_open != 0) { (void)SHOW_ERROR("Array json does not match up"); something_wrong = 1; } if (tracking_object_open != 0) { (void)SHOW_ERROR("Object json does not match up"); something_wrong = 1; } if (tracking_string_quote != 0) { (void)SHOW_ERROR("String quote json does not match up"); something_wrong = 1; } if (something_wrong) { obj_free(&base_object); return 0L; } return base_object; } n_string obj_contains(n_object* base, n_string name, n_object_type type) { n_object * return_object = base; n_int string_length = io_length(name, STRING_BLOCK_SIZE); if (string_length > 0) { n_uint hash = math_hash((n_byte *)name, (n_uint)string_length); if (return_object == 0L) { return 0L; } do { if ((hash == return_object->name_hash) && (type == object_type(&return_object->primitive))) { return return_object->primitive.data; } return_object = return_object->primitive.next; }while (return_object); } return 0L; } n_int obj_contains_number(n_object* base, n_string name, n_int *number) { n_object * return_object = base; n_int string_length = io_length(name, STRING_BLOCK_SIZE); if (string_length > 0) { n_uint hash = math_hash((n_byte *)name, (n_uint)string_length); if (return_object == 0L) { return 0; } do { if ((hash == return_object->name_hash) && (OBJECT_NUMBER == object_type(&return_object->primitive))) { n_int * data = (n_int *)&return_object->primitive.data; number[0] = data[0]; return 1; } return_object = return_object->primitive.next; }while (return_object); } return 0; } n_array * obj_array_next(n_array * array, n_array * element) { if (element == 0L) { return array; } return (n_array *)element->next; } n_int obj_array_count(n_array * array_obj) { n_array * arr_second_follow = 0L; n_int count = 0; if (array_obj) { while ((arr_second_follow = obj_array_next(array_obj, arr_second_follow))) { count++; } } return count; } n_int obj_contains_array_nbyte2(n_object* base, n_string name, n_byte2 * array_numbers, n_int size) { n_string array_string; if ((array_string = obj_contains(base, name, OBJECT_ARRAY))) { n_array * array_obj = obj_get_array(array_string); n_array * arr_follow = 0L; n_int count = 0; n_int estimated_size = obj_array_count(array_obj); if (estimated_size != size) { return -1; } while ((arr_follow = obj_array_next(array_obj, arr_follow))) { n_int follow_number = obj_get_number(arr_follow->data); array_numbers[count++] = follow_number; if (count == size) { return 1; } } } return 0; } n_int obj_contains_array_numbers(n_object* base, n_string name, n_int * array_numbers, n_int size) { n_string array_string; if ((array_string = obj_contains(base, name, OBJECT_ARRAY))) { n_array * array_obj = obj_get_array(array_string); n_array * arr_follow = 0L; n_int count = 0; n_int estimated_size = obj_array_count(array_obj); if (estimated_size != size) { return -1; } while ((arr_follow = obj_array_next(array_obj, arr_follow))) { n_int follow_number = obj_get_number(arr_follow->data); array_numbers[count++] = follow_number; if (count == size) { return 1; } } } return 0; } <|start_filename|>test/example4.json<|end_filename|> {"general_variables":"test","general_variables2":{"general_variables":"test","general_variables2":-12345,"general_variables3":{"general_variables":"test","general_variables2":-12345,"general_variables3":"test"}},"general_variables3":"test"} <|start_filename|>toolkit/file.c<|end_filename|> /**************************************************************** file.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /*! \file n_file.c * \brief Covers the low level input and output relating to files. */ #include "toolkit.h" #include <string.h> #include <stdlib.h> #include <stdio.h> #define CHAR_TAB (9) /* this is v2 of the file parsing, v3 is soon to be implemented through the scripting interface */ #define CHAR_EOF 0 #define IS_TAB(val) ((val) == CHAR_TAB) #define IS_WHITE_HORIZON(val) (IS_TAB(val) || IS_SPACE(val)) #define IS_WHITE_SPACE(val) (IS_WHITE_HORIZON((val))||IS_RETURN((val))) #define FILE_END_INCLUSION 0x0101 #define FILE_TYPE(num) ((num)&0x07) #define FILE_CONTINUATION 0x80 /** * Allocates a new file. * @return a 4k worth of data file pointer. */ n_file * io_file_new(void) { n_file * output = memory_new(sizeof(n_file)); if (output == 0L) { return 0L; } output->size = 4096; output->data = memory_new(4096); if (output->data == 0L) { memory_free((void **)&output); return 0L; } output->location = 0; return output; } /** * Frees the file pointer * @param file the pointer to be freed. */ void io_file_free(n_file ** file) { if (file != 0L) { if ((*file)->data) { memory_free((void **)&((*file)->data)); } } memory_free((void **)file); } void io_int_to_bytes(n_int value, n_byte * bytes) { memory_copy((n_byte *)&value, bytes, sizeof(n_int)); } n_int io_bytes_to_int(n_byte * bytes) { /*n_uint unsigned_value;*/ n_int return_value; memory_copy(bytes, (n_byte *)&return_value, sizeof(n_int)); return return_value; } n_uint io_file_hash(n_file * local_file) { n_uint hash = math_hash((n_byte *)&local_file->location, sizeof(n_uint)); hash ^= math_hash((n_byte *)&local_file->size, sizeof(n_uint)); hash ^= math_hash(local_file->data, local_file->size); return hash; } /** * Reads a file from disk. * @param local_file the pointer to the n_file data that will have the file stored in it. * @param file_name the name of the file to be read. * @return FILE_ERROR if there is a problem and FILE_OKAY if it is successful. */ static n_int io_disk_read_error(n_file * local_file, n_string file_name, n_byte error_show) { n_uint file_size; #ifndef _WIN32 FILE * in_file = fopen(file_name,"rb"); #else FILE * in_file = 0L; fopen_s(&in_file,file_name,"rb"); #endif if (in_file == 0L) { if (error_show) { return SHOW_ERROR("File does not exist"); } return -1; } fseek(in_file, 0L, SEEK_END); file_size = ftell(in_file); fseek(in_file, 0L, SEEK_SET); memory_free((void**)&local_file->data); local_file->data = memory_new(file_size * 2); if (local_file->data == 0L) { if (error_show) { return SHOW_ERROR("File data could not be allocated"); } return -1; } memory_erase(local_file->data, file_size * 2); fread(local_file->data, 1, file_size, in_file); local_file->size = file_size * 2; local_file->location = file_size; fclose(in_file); return FILE_OKAY; } /** * Reads a file from disk. * @param local_file the pointer to the n_file data that will have the file stored in it. * @param file_name the name of the file to be read. * @return FILE_ERROR if there is a problem and FILE_OKAY if it is successful. */ n_int io_disk_read(n_file * local_file, n_string file_name) { return io_disk_read_error(local_file, file_name, 1); } n_int io_disk_read_no_error(n_file * local_file, n_string file_name) { return io_disk_read_error(local_file, file_name, 0); } /** * Writes a file to disk. * @param local_file the pointer to the n_file data that is written to disk. * @param file_name the name of the file to be written. * @return FILE_ERROR if there is a problem and FILE_OKAY if it is successful. */ n_int io_disk_write(n_file * local_file, n_constant_string file_name) { n_uint written_length; FILE * out_file = 0L; #ifndef _WIN32 out_file = fopen(file_name,"wb"); #else fopen_s(&out_file,file_name,"wb"); #endif if (out_file == 0L) { return SHOW_ERROR("Error opening file to write"); } if (local_file->data == 0L) { return SHOW_ERROR("No data in file to be written"); } written_length = fwrite(local_file->data,1,local_file->location, out_file); if (fclose(out_file) != 0) { return SHOW_ERROR("File could not be closed"); } if (written_length != local_file->location) { return SHOW_ERROR("File did not complete write"); } return FILE_OKAY; } /** * Appends a file to disk. * @param file_name the name of the file to be appended. * @return FILE_ERROR if there is a problem and FILE_OKAY if it is successful. */ n_int io_disk_check(n_constant_string file_name) { #ifndef _WIN32 FILE * local_check_file = fopen(file_name,"rb"); #else FILE * local_check_file = 0L; fopen_s(&local_check_file,file_name,"rb"); #endif if (local_check_file == 0L) return 0; if (fclose(local_check_file) != 0) { return 0; } return 1; } /** * Reads binary data from the file pointer. * @param fil the pointer to the n_file data that is read from. * @param local_byte the single byte. * @return FILE_ERROR if there is a problem and FILE_OKAY if it is successful. */ n_int io_read_bin(n_file * fil, n_byte * local_byte) { n_uint file_location = fil -> location; if (file_location >= (fil -> size)) { return -1; } *local_byte = fil -> data[file_location]; fil->location = (file_location + 1); return 0; } /** * Reads a character - white-space and comments have already been removed * @param fil the pointer to the n_file data that is read from. * @return CHAR_EOF if there is a problem and the byte value if it is successful. */ static n_byte io_read(n_file * fil) { n_byte val = 0; if (io_read_bin(fil, &val) == -1) { return(CHAR_EOF); } return (val); } /** * Converts a tab delimited file to a series of string pointers * @param tab_file the pointer to the n_file data that is read from. * @param size_value the pointer to the total number. * @param row_value the pointer to the number of columns per row. * @return string pointers. */ n_string * io_tab_delimit_to_n_string_ptr(n_file * tab_file, n_int * size_value, n_int * row_value) { n_int string_point_location = 1; n_int first_value = 0; n_uint loop = 0; n_string *string_point; n_int local_row_value = 0; n_byte resultant_value; if (tab_file->location != 0) { while (loop < tab_file->location) { resultant_value = tab_file->data[loop]; if (IS_TAB(resultant_value) || IS_RETURN(resultant_value)) { tab_file->data[loop] = 0; first_value = 1; if ((local_row_value == 0) && IS_RETURN(resultant_value)) { local_row_value = string_point_location; } } else { if (first_value) { string_point_location++; first_value = 0; } } loop ++; } } if (size_value != 0L) { *size_value = string_point_location; } if (row_value != 0L) { *row_value = local_row_value; } if (tab_file->location == 0) { return 0L; } if ((string_point = (n_string *)memory_new(string_point_location*sizeof(n_string *))) == 0L) { return 0L; } string_point_location = 0; first_value = 0; loop = 0; string_point[string_point_location++] = (n_string)&(tab_file->data[0]); while (loop < tab_file->location) { resultant_value = tab_file->data[loop]; if ((first_value) && (resultant_value != 0)) { string_point[string_point_location++] = (n_string)&(tab_file->data[loop]); first_value = 0; } if (resultant_value == 0) { first_value = 1; } loop ++; } return string_point; } /** * Appends a file to disk. * @param local_file the pointer to the n_file data that is written to disk. * @param file_name the name of the file to be appended. * @return FILE_ERROR if there is a problem and FILE_OKAY if it is successful. */ static n_int io_disk_append(n_file * local_file, n_string file_name) { n_uint written_length; #ifndef _WIN32 FILE * out_file = fopen(file_name,"a"); #else FILE * out_file = 0L; fopen_s(&out_file,file_name,"a"); #endif written_length = fwrite(local_file->data,1,local_file->location, out_file); if (fclose(out_file) != 0) { return SHOW_ERROR("File could not be closed"); } if (written_length != local_file->location) { return SHOW_ERROR("File did not complete write"); } return FILE_OKAY; } /** * Adds XML open to the named string. * @param file the pointer to the n_file data that is written. * @param name the string that is wrapped. * @return FILE_ERROR if there is a problem and FILE_OKAY if it is successful. */ static n_int io_file_xml_open(n_file * file, n_string name) { if (io_write(file,"<", 0) == -1) return -1; if (io_write(file,name, 0) == -1) return -1; if (io_write(file,">", 1) == -1) return -1; return 0; } /** * Adds XML close to the named string. * @param file the pointer to the n_file data that is written. * @param name the string that is wrapped. * @return FILE_ERROR if there is a problem and FILE_OKAY if it is successful. */ static n_int io_file_xml_close(n_file * file, n_string name) { if (io_write(file,"</", 0) == -1) return -1; if (io_write(file,name, 0) == -1) return -1; if (io_write(file,">", 1) == -1) return -1; return 0; } /** * Wraps a string with XML open and close * @param file the pointer to the n_file data that is written. * @param name the string that is the wrapper. * @param string the string that is wrapped. * @return FILE_ERROR if there is a problem and FILE_OKAY if it is successful. */ static n_int io_file_xml_string(n_file * file, n_string name, n_string string) { if (io_file_xml_open(file,name) == -1) return -1; if (io_write(file,string, 0) == -1) return -1; if (io_file_xml_close(file,name) == -1) return -1; return 0; } /** * Wraps an integer with XML open and close * @param file the pointer to the n_file data that is written. * @param name the string that is the wrapper. * @param number the integer that is wrapped. * @return FILE_ERROR if there is a problem and FILE_OKAY if it is successful. */ static n_int io_file_xml_int(n_file * file, n_string name, n_int number) { if (io_file_xml_open(file,name) == -1) return -1; if (io_writenumber(file, number, 1, 0) == -1) return -1; if (io_file_xml_close(file,name) == -1) return -1; return 0; } /** * Read a four byte value from n_file * @param fil the pointer to the n_file data that is read from. * @param actual_value the actual value read. * @param final_char the final character (after the last number). * @return number of characters read in condition of success and -1 in condition of failure. */ n_int io_read_byte4(n_file * fil, n_uint * actual_value, n_byte * final_char) { n_uint temp = 0; n_int ten_power_place = 0; while (1) { n_byte value = io_read(fil); n_uint mod_ten; if (!ASCII_NUMBER(value)) { *actual_value = temp; *final_char = value; return ten_power_place; } mod_ten = value - '0'; if ((temp == 429496729) && (mod_ten > 5)) { return -1; } if (temp > 429496729) { return -1; } temp = (temp * 10) + mod_ten; ten_power_place++; } } #define ASCII_WHITESPACE(num) ((((num)>8)&&((num)<14))||((num)==32)) /** * Removes the whitespace from the initial file - CRs, LFs, tabs and spaces. * @param input the file pointer that will have the white space removed. */ void io_whitespace(n_file * input) { n_uint loop = 0, out_loop = 0; n_uint end_loop = input->size; n_byte *local_data = input->data; while(loop < end_loop) { n_byte temp = local_data[loop++]; if((temp == '/') && (loop != end_loop)) { n_byte check_twice[2]= {'/', 0}; check_twice[1] = local_data[loop++]; if(check_twice[1] != '*') { local_data[out_loop++] = '/'; if(ASCII_WHITESPACE(check_twice[1]) == 0) { local_data[out_loop++] = check_twice[1]; } } else { check_twice[0] = 0; check_twice[1] = 0; do { check_twice[0] = check_twice[1]; check_twice[1] = local_data[loop++]; } while((loop != end_loop) && !((check_twice[0]=='*')&&(check_twice[1]=='/'))); } } else if(ASCII_WHITESPACE(temp) == 0) { local_data[out_loop++] = temp; } } loop = out_loop; while (loop < end_loop) { local_data[loop++] = 0; } input->size = out_loop; } void io_whitespace_json(n_file * input) { n_uint loop = 0, out_loop = 0; n_uint end_loop = input->size; n_byte *local_data = input->data; n_int inside_string = 0; while(loop < end_loop) { n_byte temp = local_data[loop++]; if (temp == '"') { inside_string ^= 1; local_data[out_loop++] = temp; } else if ((ASCII_WHITESPACE(temp) == 0) || inside_string) { local_data[out_loop++] = temp; } } loop = out_loop; while (loop < end_loop) { local_data[loop++] = 0; } input->size = out_loop; input->location = 0; } /** This is a dynamic write to file function which will increase the file size and allocated a larger data buffer if the original end of the file is reached. It is very useful for a number of dynamic file applications through the simulation. @param fil The file data to be written to. @param byte The byte/character to be written. @return Whether the parsing was successful or -1 on failure. */ n_int io_file_write(n_file * fil, n_byte byte) { n_uint local_size = fil->size; if((fil->location + 1) == local_size) { /* This logic had to be changed for large file handling.*/ n_uint temp_size; n_byte *temp_data; if (local_size <= (256*1024)) { temp_size = local_size * 4; } else { if (local_size <= (512*1024*1024)) { temp_size = local_size * 2; } else { temp_size = (local_size * 3) >> 1; } } temp_data = memory_new(temp_size); if (temp_data == 0L) { return(SHOW_ERROR("Attempted file overwrite")); } memory_copy(fil->data, temp_data, local_size); memory_free((void **)&(fil->data)); fil->data = temp_data; fil->size = temp_size; } fil->data[fil->location++] = byte; return (FILE_OKAY); } /* Memory saving */ void io_file_reused(n_file * fil) { memory_erase(fil->data, fil->size); fil->location = 0; } /* writes a string, adding a new line if required in the OS correct format */ #define FILE_MACRO_WRITE(ch) if(io_file_write(fil,(ch)) == -1) return -1 n_int io_write(n_file * fil, n_constant_string ch, n_byte new_line) { if (ch[0] != 0) { n_uint lp = 0; while (ch[lp] != 0) { FILE_MACRO_WRITE(ch[lp++]); } } if (new_line&1) { #ifdef _WIN32 FILE_MACRO_WRITE(13); #endif FILE_MACRO_WRITE(10); } if (new_line&2) { FILE_MACRO_WRITE(9); } return (FILE_OKAY); } /* writes a 16-bit or 8-bit number with an end terminator(,/;) and new line if required */ /* n_int error */ n_int io_writenumber(n_file * fil, n_int loc_val, n_uint numer, n_uint denom) { n_byte number_buffer[14] = {0}; n_byte negative; n_byte decimal = 0; n_uint positive_number; n_int location = 12; if(loc_val < 0) { negative = 1; positive_number = (n_uint)(0 - loc_val); } else { negative = 0; positive_number = (n_uint)(loc_val); } if(denom != 0) { n_uint roll_over = positive_number; positive_number = positive_number * numer * 100; if(positive_number < roll_over) return -1; positive_number = positive_number / denom; decimal = 1; } do { number_buffer[location --] = (n_byte)((positive_number % 10) + '0'); positive_number = positive_number / 10; if(decimal && location == 10) { number_buffer[location --] = '.'; if(positive_number == 0) number_buffer[location --] = '0'; } } while((positive_number>0) || (decimal && (location > 9))); if(negative) number_buffer[location] = '-'; else location++; return io_write(fil, (n_string)&number_buffer[location], 0); } n_int io_writenum(n_file * fil, n_int loc_val, n_byte ekind, n_byte new_line) { n_int return_val = io_writenumber(fil, loc_val,1,0); n_byte ekind_buffer[2] = {0}; if(return_val!=FILE_OKAY) return return_val; ekind_buffer[0] = ekind; return io_write(fil, (n_string)ekind_buffer, new_line); } /* find the variable command */ n_int io_command(n_file * fil, const simulated_file_entry * commands) { n_byte found_text[7] = {0}; n_byte * commands_bytes = (n_byte *) commands[0].characters; n_byte2 lp = 0; found_text[0] = io_read(fil); if (found_text[0] == 0) { return (FILE_EOF); } found_text[1] = io_read(fil); if (found_text[0] == '}' && found_text[1] == ';') { return (FILE_END_INCLUSION); } found_text[2] = io_read(fil); found_text[3] = io_read(fil); found_text[4] = io_read(fil); found_text[5] = io_read(fil); while (POPULATED(commands_bytes)) { commands_bytes = (n_byte *) commands[lp].characters; if (((commands_bytes[0] == found_text[0]) && (commands_bytes[1] == found_text[1])) && ((commands_bytes[2] == found_text[2]) && (commands_bytes[3] == found_text[3])) && ((commands_bytes[4] == found_text[4]) && (commands_bytes[5] == found_text[5]))) { return (lp); } lp ++; } /*io_output_contents(fil);*/ printf("String length : %ld\n", io_length((n_string)fil->data, 0xffff)); printf("Actual size : %lu\n", fil->size); printf("String location : %lu\n", fil->location); printf("Failed text %s\n", found_text); printf("Failed text %d\n", found_text[0]); printf("Failed text %d\n", found_text[1]); printf("Failed text %d\n", found_text[2]); printf("Failed text %d\n", found_text[3]); printf("Failed text %d\n", found_text[4]); printf("Failed text %d\n", found_text[5]); NA_ASSERT(0, "Failed here"); return SHOW_ERROR((n_constant_string)found_text); } /* find the largest size data unit to handle the file copying to data structures */ n_uint io_find_size_data(simulated_file_entry * commands) { n_uint max_entry = 0; n_int lp = 1; n_byte last_incl = FILE_INCL(commands[0].incl_kind); n_byte *last_characters; do { n_byte data_incl = FILE_INCL(commands[lp].incl_kind); last_characters = commands[lp].characters; if (last_incl != data_incl) { n_uint local_kind = FILE_KIND(commands[lp-1].incl_kind); n_uint data_size; n_uint running_entry = commands[lp-1].start_location; switch(local_kind) { case FILE_TYPE_BYTE4: data_size = 4; break; case FILE_TYPE_BYTE2: data_size = 2; break; default: data_size = 1; break; } running_entry += data_size * commands[lp-1].number_entries; if (running_entry > max_entry) { max_entry = running_entry; } last_incl = data_incl; } lp++; } while (POPULATED(last_characters)); return max_entry; } #define FILE_MACRO_CONCLUSION(ch) (((comman_req==1) && (ch) == ',') || \ ((comman_req==0) && (ch) == ';')) /* after the variable command, read the kind of data in specified through the commands array */ /* n_int error */ n_int io_read_data(n_file * fil, n_byte2 command, n_byte * data_read) { n_int comman_req = ((command & FILE_CONTINUATION) == FILE_CONTINUATION); n_byte type_from_command = (n_byte)FILE_TYPE(command); if (type_from_command == FILE_TYPE_PACKED) { n_uint loop = 0; n_byte buffer[5]= {0}; n_uint output_val; n_byte num_char; if (data_read == 0L) { return (FILE_OKAY); } while (loop < PACKED_DATA_BLOCK) { buffer[0] = io_read(fil); buffer[1] = io_read(fil); buffer[2] = io_read(fil); output_val = (buffer[0]-65); output_val += (buffer[1]-65) * 41; output_val += (buffer[2]-65) * 41 * 41; data_read[loop++] = (output_val >> 0) & 255; data_read[loop++] = (output_val >> 8) & 255; } num_char = io_read(fil); if (FILE_MACRO_CONCLUSION(num_char)) return (FILE_OKAY); return SHOW_ERROR("Packed ends incorrectly"); } if ((type_from_command == FILE_TYPE_BYTE) || (type_from_command == FILE_TYPE_BYTE_EXT) || (type_from_command == FILE_TYPE_BYTE2) || (type_from_command == FILE_TYPE_BYTE4)) { n_uint number = 0; n_byte num_char; n_int response_code = io_read_byte4(fil, &number, &num_char); if (response_code == 0) { return SHOW_ERROR("Expected number not found"); } if (response_code < 0) { return SHOW_ERROR("Expected number too big"); } if ((type_from_command == FILE_TYPE_BYTE) || (type_from_command == FILE_TYPE_BYTE_EXT)) { if (number > 0x000000ff) return SHOW_ERROR("Expected byte too big"); data_read[0] = (n_byte) number; } if (type_from_command == FILE_TYPE_BYTE2) { n_byte2 * data_read2 = (n_byte2 *)data_read; if (number > 0x0000ffff) return SHOW_ERROR("Expected two byte too big"); data_read2[0] = (n_byte2) number; } if (type_from_command == FILE_TYPE_BYTE4) { n_byte4 * data_read4 = (n_byte4 *)data_read; data_read4[0] = (n_byte4) number; } if (FILE_MACRO_CONCLUSION(num_char)) return (FILE_OKAY); return SHOW_ERROR("Number ends incorrectly"); } return SHOW_ERROR("Type not found"); } void io_output_contents(n_file * file) { n_uint loop = 0; printf("--------------------FILE--------------------\n"); printf("Location %ld\n", file->location); printf("Size %ld\n", file->size); printf("* * * * * * \n"); while (loop < file->location) { printf("%c", file->data[loop++]); } printf("--------------------------------------------n"); } /** @discussion This function takes a file and parses the file date with the commands shown into the output data. This function is extremely powerful because it allows all different kinds of format-rich text data to be converted into binary information based on the command information passed in to this function too. @param fil The file data to be parsed. @param data The resultant output data. @param commands The commands used to parse the output data. @return Whether the parsing was successful or -1 on failure. */ n_int io_read_buff(n_file * fil, n_byte * data, const simulated_file_entry * commands) { n_int inclusion_number = 0xffff; n_int result_number = 0; do { result_number = io_command(fil, commands); if(result_number == -1) return SHOW_ERROR("Unknown command"); if (result_number > 0x00ff) { if (result_number != FILE_END_INCLUSION) return (result_number); } else { n_byte com_inclusion = FILE_INCL(commands[result_number].incl_kind); n_byte com_kind = FILE_KIND(commands[result_number].incl_kind); n_uint com_number_of = commands[result_number].number_entries; n_uint com_location = commands[result_number].start_location; n_uint loop = 0; n_byte *local_data = &data[com_location]; if (inclusion_number == 0xffff) { if (commands[result_number].characters[5] != '{') return SHOW_ERROR("{ expected in the file"); inclusion_number = com_inclusion; } if (inclusion_number != com_inclusion) return SHOW_ERROR("Wrong start in file"); while (loop < com_number_of) { n_byte local_kind = com_kind; if ((loop + 1) != com_number_of) { local_kind |= FILE_CONTINUATION; } if (io_read_data(fil, local_kind, local_data) != FILE_OKAY) { return (FILE_ERROR); } if (com_kind == FILE_TYPE_PACKED) { local_data = &local_data[ PACKED_DATA_BLOCK ]; } else { if (com_kind == FILE_TYPE_BYTE_EXT) { local_data = &local_data[ 1 ]; } else { local_data = &local_data[ com_kind ]; } } loop++; } } } while (result_number != FILE_END_INCLUSION); return (inclusion_number); } #define IO_CHECK_ERROR(cnd) \ { \ n_int out_cnd = cnd; \ if ( (out_cnd) != FILE_OKAY) \ return out_cnd; \ } /** This function takes a block of data and various format-rules (through the commands) and applies these rules to produce an output datafile. In many regards this can be thought of as the inverse of io_read_buff. @param fil The file data that is produced. @param data The resultant output data. @param commands The commands used to parse data to the output file. @param command_num Output the command number block of commands. @param func Allows a file specific function to be injected to add additional format requirments. @return Whether the parsing was successful. */ n_int io_write_buff(n_file * fil, void * data, const simulated_file_entry * commands, n_byte command_num, n_file_specific * func) { if (command_num == FILE_COPYRIGHT) { n_string *fluff = (n_string *) data; IO_CHECK_ERROR(io_write(fil, "/*", 3)); IO_CHECK_ERROR(io_write(fil, fluff[0], 0)); IO_CHECK_ERROR(io_write(fil, fluff[1], 3)); IO_CHECK_ERROR(io_write(fil, fluff[2], 0)); IO_CHECK_ERROR(io_write(fil, fluff[3], 0)); IO_CHECK_ERROR(io_write(fil, fluff[4], 1)); IO_CHECK_ERROR(io_write(fil, "*/", 1)); IO_CHECK_ERROR(io_write(fil, "", 1)); return (FILE_OKAY); } { const n_byte *commands_bytes; n_byte writeout_commands[7]= {0}; n_uint offset = 0; n_int release = FILE_ERROR; do { commands_bytes = commands[offset].characters; if ((commands_bytes[0] == 0) && (commands_bytes[1] == 0) && (commands_bytes[2] == 0) && (commands_bytes[3] == 0) && (commands_bytes[4] == 0) && (commands_bytes[5] == 0)) { return SHOW_ERROR("File command not found"); } if (FILE_INCL(commands[offset].incl_kind) == command_num) release = FILE_OKAY; else offset++; } while (release == FILE_ERROR); writeout_commands[0] = commands_bytes[0]; writeout_commands[1] = commands_bytes[1]; writeout_commands[2] = commands_bytes[2]; writeout_commands[3] = commands_bytes[3]; writeout_commands[4] = commands_bytes[4]; writeout_commands[5] = commands_bytes[5]; IO_CHECK_ERROR(io_write(fil, (n_string)writeout_commands, 3)); release = FILE_ERROR; offset++; do { commands_bytes = commands[offset].characters; if ((commands_bytes[0] == 0) && (commands_bytes[1] == 0) && (commands_bytes[2] == 0) && (commands_bytes[3] == 0) && (commands_bytes[4] == 0) && (commands_bytes[5] == 0)) release = FILE_OKAY; if (FILE_INCL(commands[offset].incl_kind) != command_num) release = FILE_OKAY; if (release == FILE_ERROR) { n_uint loop = 0; n_byte data_type = FILE_KIND(commands[offset].incl_kind); n_uint end_loop = commands[offset].number_entries; n_uint data_offset = commands[offset].start_location; n_int right_ending = (FILE_INCL(commands[offset+1].incl_kind) != command_num); right_ending |= ((commands[offset+1].characters[0] == 0) && (commands[offset+1].characters[1] == 0) && (commands[offset+1].characters[2] == 0) && (commands[offset+1].characters[3] == 0) && (commands[offset+1].characters[4] == 0) && (commands[offset+1].characters[5] == 0)); right_ending = 3 - (right_ending * 2); #if 0 if (data_type == FILE_TYPE_PACKED) { if (unpack_data != 0L) { n_byte buffer[6]= {0}; n_uint output_val; n_byte *local_unpack_data = unpack_data; writeout_commands[0] = commands_bytes[0]; writeout_commands[1] = commands_bytes[1]; writeout_commands[2] = commands_bytes[2]; writeout_commands[3] = commands_bytes[3]; writeout_commands[4] = commands_bytes[4]; writeout_commands[5] = commands_bytes[5]; IO_CHECK_ERROR(io_write(fil, (n_string)writeout_commands, (n_byte)right_ending)); while (loop < end_loop) { n_uint data_loop = 0; while (data_loop < PACKED_DATA_BLOCK) { output_val = local_unpack_data[data_loop++]; output_val |= local_unpack_data[data_loop++] << 8; buffer[0] = (output_val % 41) + 65; output_val /= 41; buffer[1] = (output_val % 41) + 65; output_val /= 41; buffer[2] = (output_val % 41) + 65; if ((data_loop % 80 ) == 0) { IO_CHECK_ERROR(io_write(fil, (n_string) buffer, (n_byte)right_ending)); } else { IO_CHECK_ERROR(io_write(fil, (n_string) buffer, 0)); } } local_unpack_data = &local_unpack_data[PACKED_DATA_BLOCK]; loop++; if (loop == end_loop) { IO_CHECK_ERROR(io_write(fil, ";", (n_byte)right_ending)); } else { IO_CHECK_ERROR(io_write(fil, ",", (n_byte)right_ending)); } } } } else #endif { n_byte *byte_data = (n_byte *)data; if (data_type == FILE_TYPE_BYTE_EXT) { n_string_block block_code= {0}; if (func != 0) (*func)((n_string)block_code, byte_data); IO_CHECK_ERROR(io_write(fil, "", 1)); IO_CHECK_ERROR(io_write(fil, "", 2)); IO_CHECK_ERROR(io_write(fil, "/* ", 0)); IO_CHECK_ERROR(io_writenumber(fil, loop, 1, 0)); IO_CHECK_ERROR(io_write(fil, "", 2)); IO_CHECK_ERROR(io_write(fil, block_code, 0)); IO_CHECK_ERROR(io_write(fil, " */", 2)); } writeout_commands[0] = commands_bytes[0]; writeout_commands[1] = commands_bytes[1]; writeout_commands[2] = commands_bytes[2]; writeout_commands[3] = commands_bytes[3]; writeout_commands[4] = commands_bytes[4]; writeout_commands[5] = commands_bytes[5]; IO_CHECK_ERROR(io_write(fil, (n_string)writeout_commands, 0)); while (loop < end_loop) { n_byte4 num_write = 0; switch (data_type) { case FILE_TYPE_BYTE_EXT: if((loop != 0) && ((loop % 3) == 0) && (loop != 126)) { n_string_block block_code = {0}; if (func != 0L) (*func)(block_code, &byte_data[data_offset + loop]); IO_CHECK_ERROR(io_write(fil, "", 1)); IO_CHECK_ERROR(io_write(fil, "", 2)); IO_CHECK_ERROR(io_write(fil, "/* ", 0)); IO_CHECK_ERROR(io_writenumber(fil, loop, 1, 0)); IO_CHECK_ERROR(io_write(fil, "", 2)); IO_CHECK_ERROR(io_write(fil, (n_string)block_code, 0)); IO_CHECK_ERROR(io_write(fil, " */", 2)); } case FILE_TYPE_BYTE: num_write = byte_data[data_offset + loop]; break; case FILE_TYPE_BYTE2: { num_write = ((n_byte2 *) &byte_data[data_offset + (loop * 2)])[0]; } break; case FILE_TYPE_BYTE4: num_write = ((n_byte4 *) &byte_data[data_offset + (loop * 4)])[0]; break; } loop++; if (loop == end_loop) { IO_CHECK_ERROR(io_writenum(fil, num_write, ';', (n_byte)right_ending)); } else { IO_CHECK_ERROR(io_writenum(fil, num_write, ',', 0)); } } } offset++; } } while (release == FILE_ERROR); IO_CHECK_ERROR(io_write(fil, "};", 1)); IO_CHECK_ERROR(io_write(fil, "", 1)); } return (FILE_OKAY); } /* write the output data with the commands array and the required copyright "fluff" */ /* n_int error */ n_int io_write_csv(n_file * fil, n_byte * data, const simulated_file_entry * commands, n_byte command_num, n_byte initial) { if (command_num == FILE_COPYRIGHT) { return (FILE_OKAY); } { const n_byte * commands_bytes; n_uint offset = 0; n_int release = FILE_ERROR; n_byte first_entry = 1; n_byte writeout_commands[6]= {0}; do { commands_bytes = commands[offset].characters; if ((commands_bytes[0] == 0) && (commands_bytes[1] == 0) && (commands_bytes[2] == 0) && (commands_bytes[3] == 0) && (commands_bytes[4] == 0) && (commands_bytes[5] == 0)) return SHOW_ERROR("File command not found"); if (FILE_INCL(commands[offset].incl_kind) == command_num) release = FILE_OKAY; else offset++; } while (release == FILE_ERROR); release = FILE_ERROR; offset++; do { commands_bytes = commands[offset].characters; if ((commands_bytes[0] == 0) && (commands_bytes[1] == 0) && (commands_bytes[2] == 0) && (commands_bytes[3] == 0) && (commands_bytes[4] == 0) && (commands_bytes[5] == 0)) release = FILE_OKAY; if (FILE_INCL(commands[offset].incl_kind) != command_num) release = FILE_OKAY; if (release == FILE_ERROR) { n_uint loop = 0; n_byte data_type = FILE_KIND(commands[offset].incl_kind); n_uint end_loop = commands[offset].number_entries; n_uint data_offset = commands[offset].start_location; if (data_type != FILE_TYPE_PACKED) { while (loop < end_loop) { n_byte2 num_write = 0; if (first_entry == 0) { IO_CHECK_ERROR(io_write(fil, ",", 0)); } else { first_entry = 0; } if (initial == 1) { writeout_commands[0] = commands_bytes[0]; writeout_commands[1] = commands_bytes[1]; writeout_commands[2] = commands_bytes[2]; writeout_commands[3] = commands_bytes[3]; writeout_commands[4] = commands_bytes[4]; writeout_commands[5] = commands_bytes[5]; IO_CHECK_ERROR(io_write(fil, (n_string)writeout_commands, 0)); IO_CHECK_ERROR(io_writenumber(fil, loop, 1, 0)); } else { switch (data_type) { case FILE_TYPE_BYTE: case FILE_TYPE_BYTE_EXT: num_write = data[data_offset + loop]; break; case FILE_TYPE_BYTE2: num_write = ((n_byte2 *) & data[data_offset + (loop * 2)])[0]; break; } IO_CHECK_ERROR(io_writenumber(fil, num_write, 1, 0)); } loop++; } } offset++; } } while (release == FILE_ERROR); IO_CHECK_ERROR(io_write(fil, "", 1)); } return (FILE_OKAY); } void io_search_file_format(const simulated_file_entry * format, n_string compare) { n_int loop = 0; n_byte print_file_format_exit = 0; n_byte print_file_place_show_all = 0; simulated_file_entry * place; if (compare == 0L) { print_file_place_show_all = 2; } else { n_byte leave_condition = 0; do { place = (simulated_file_entry *)&format[loop++]; if ((place->characters[0] != 0) && (place->characters[1] != 0) && (place->characters[2] != 0) && (place->characters[3] != 0) && (place->characters[4] != 0) && (place->characters[5] != 0)) { if ((place->characters[0] == compare[0]) && (place->characters[1] == compare[1]) && (place->characters[2] == compare[2]) && (place->characters[3] == compare[3]) && (place->characters[4] == compare[4]) && (0 == compare[5])) { leave_condition = 1; } } else { print_file_format_exit = 1; } } while((print_file_format_exit == 0) && (leave_condition == 0)); if (print_file_format_exit == 1) { (void)SHOW_ERROR("String not found"); return; } if(place->characters[5] =='{') { print_file_place_show_all = 1; } loop--; } do { place = (simulated_file_entry *)&format[loop++]; if ((place->characters[0] != 0) && (place->characters[1] != 0) && (place->characters[2] != 0) && (place->characters[3] != 0) && (place->characters[4] != 0) && (place->characters[5] != 0)) { if (place->characters[5] == '{') { printf(" %c%c%c%c%c %s\n", place->characters[0],place->characters[1],place->characters[2], place->characters[3],place->characters[4], place->what_is_it); } else { printf(" %c%c%c%c%c %s\n", place->characters[0],place->characters[1],place->characters[2], place->characters[3],place->characters[4], place->what_is_it); } if (print_file_place_show_all == 0) { return; } if ((format[loop].characters[5]=='{') && (print_file_place_show_all == 1)) { return; } } else { print_file_format_exit = 1; } } while(print_file_format_exit == 0); } void io_audit_file(const simulated_file_entry * format, n_byte section_to_audit) { n_uint loop = 0; n_uint being_counter = 0; n_byte *local_characters; do { n_byte local_incl_kind = format[loop].incl_kind; n_uint local_number = format[loop].number_entries; n_uint local_location = format[loop].start_location; n_string_block printout_characters = {0}; local_characters = (n_byte*)format[loop].characters; if ((local_incl_kind & 0xF0) == section_to_audit) { n_uint local_type = local_incl_kind & 0x0F; if (local_type == FILE_TYPE_BYTE_EXT) { local_type = FILE_TYPE_BYTE; } if ((local_type == FILE_TYPE_BYTE) || (local_type == FILE_TYPE_BYTE2) || (local_type == FILE_TYPE_BYTE4)) { printout_characters[0] = (n_char)local_characters[0]; printout_characters[1] = (n_char)local_characters[1]; printout_characters[2] = (n_char)local_characters[2]; printout_characters[3] = (n_char)local_characters[3]; printout_characters[4] = (n_char)local_characters[4]; printout_characters[5] = (n_char)local_characters[5]; printf("%s \t %lu * %lu = %lu bytes \t reported/actual/diff offset %d / %d / %d\n", printout_characters, local_number, local_type, (local_number * local_type), (int)local_location, (int)being_counter, ((int)local_location - (int)being_counter)); being_counter += (local_number * local_type); } } loop++; } while((local_characters[0] != 0) && (local_characters[1] != 0) && (local_characters[2] != 0) && (local_characters[3] != 0)); } n_file * io_file_ready(n_int entry, n_file * file) { if (entry == 1) { return 0L; } return file; } void io_file_cleanup(n_int * entry, n_file ** file) { /* This setting to zero may be duplicated in at least one place but provides additional protection - it may not be needed following a case-by-case review */ *entry = 0; if (*file) { io_file_free(file); } } void io_file_writeon(n_int * entry, n_file ** file, n_byte blocked_write) { if (*entry == 0) return; #ifndef COMMAND_LINE_DEBUG if (*file == 0L) /* io_file_reused */ { *file = io_file_new(); } if(*file == 0L) { (void)SHOW_ERROR("Could not set up special use file"); return; } if (blocked_write) { *entry = 1; } else { *entry = 2; } #endif } void io_file_writeoff(n_int * entry, n_file * file) { if (*entry == 0) return; #ifndef COMMAND_LINE_DEBUG if(file != 0L) { *entry = 0; } #endif } void io_file_string(n_int entry, n_file * file, n_constant_string string) { if (entry == 0) return; if((string != 0L) #ifndef COMMAND_LINE_DEBUG && (file != 0L) #endif ) { #ifndef COMMAND_LINE_DEBUG io_write(file, string, 0); #else printf("%s",string); #endif } } void io_file_debug(n_file * file) { n_uint loop = 0; while (loop < file->location) { printf("%c", file->data[loop]); loop++; } printf("\n\n"); } <|start_filename|>toolkit/io.c<|end_filename|> /**************************************************************** io.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /*! \file io.c * \brief Covers the low level input and output relating to memory and files. In addition to memory and file handling, io has typically been a place holder for new functionality. */ #include "toolkit.h" #include <string.h> #include <stdlib.h> #include <stdio.h> /** * Moves the string to lower case for the length shown. * @param value the string with the case to be lowered. * @param length the number of bytes to be lowered. */ void io_lower(n_string value, n_int length) { n_int loop = 0; while (loop < length) { IO_LOWER_CHAR(value[loop]); loop++; } } /** * Read a number from a string. * @param number_string the string to be read from. * @param actual_value the actual value read. * @param decimal_divisor the value required to provide a decimal version. * @return number of characters read in condition of success and -1 in condition of failure. */ n_int io_number(n_string number_string, n_int * actual_value, n_int * decimal_divisor) { n_uint temp = 0; n_int divisor = 0; n_int ten_power_place = 0; n_int string_point = 0; n_byte negative = 0; if (number_string == 0L) return -1; if (number_string[0] == 0) return -1; if (number_string[0] == '-') { negative = 1; string_point++; } while (1) { n_char value = number_string[string_point++]; n_uint mod_ten; if (value == 0) { n_int translate; if (negative == 1) { translate = 0 - temp; } else { translate = temp; } *actual_value = translate; if (divisor > 0) { divisor--; } *decimal_divisor = divisor; return ten_power_place; } if (value == '.') { if (divisor != 0) { return SHOW_ERROR("double decimal point in number"); } divisor = 1; } else { if (!ASCII_NUMBER(value)) { return SHOW_ERROR("number contains non-numeric value"); } mod_ten = value - '0'; if (temp == 922337203685477580) { if (negative == 1) { if (mod_ten > 8) { return SHOW_ERROR("number too small"); } } else { if (mod_ten > 7) { return SHOW_ERROR("number too large"); } } } if (temp > 922337203685477580) { return SHOW_ERROR("number numerically too large"); } if (divisor != 0) { divisor++; } temp = (temp * 10) + mod_ten; ten_power_place++; } } } /* This is too slow, consider: n_uint io_length(n_string s) { n_string start = s; while(*s)s++; return s - start; } */ /* this is used for finding the actual length of fixed length strings, max length is enforced */ n_int io_length(n_string value, n_int max) { n_int return_length = -1; if (value == 0L) { return 0; } if (max < 1) { return -1; } do { return_length++; } while ((value[return_length] != 0) && (return_length < max)); return return_length; } /* These are too slow too. Consider: return <0 if s<t, 0 if s==t, >0 if s>t n_int io_find(n_string s, n_string t) { for ( ; *s == *t; s++, t++) if (*s == '\0') return 0; return *s - *t; } */ n_int io_find(n_string check, n_int from, n_int max, n_string value_find, n_int value_find_length) { n_int loop = from; n_int check_length = 0; while (loop < max) { if (check[loop] == value_find[check_length]) { check_length++; if (check_length == value_find_length) { return loop + 1; } } else { check_length = 0; } loop ++; } return -1; } void io_string_write(n_string dest, n_string insert, n_int * pos) { n_int loop = 0; n_char character = 127; do { character = insert [loop++]; if (character) { dest[*pos] = character; *(pos) += 1; } } while (character); dest[*pos] = 0; } void io_three_string_combination(n_string output, n_string first, n_string second, n_string third, n_int count) { n_int command_length = io_length(first, STRING_BLOCK_SIZE); n_int addition_length = io_length(second, STRING_BLOCK_SIZE); n_int total = count - (command_length + addition_length + 1); n_int loop2 = 0; n_int position = 0; io_string_write(output, " ", &position); io_string_write(output, first, &position); io_string_write(output, " ", &position); io_string_write(output, second, &position); while (loop2 < total) { io_string_write(output, " ", &position); loop2++; } io_string_write(output, third, &position); } void io_number_to_string(n_string value, n_uint number) { n_uint temp_number = number; n_uint digits_in_number = 0; n_uint multiplier = 1; n_uint number_location = 0; do{ temp_number = temp_number / 10; digits_in_number++; if (temp_number != 0) { multiplier = multiplier * 10; } }while (temp_number != 0); do{ value[number_location++] = '0' + (number/multiplier) % 10; multiplier = multiplier /10; digits_in_number --; }while (multiplier != 0); value[number_location++] = 0; } void io_string_number(n_string output_string, n_string input_string,n_uint number) { n_int input_length = io_length(input_string, STRING_BLOCK_SIZE); if (input_length > 0) { memory_copy((n_byte *)input_string, (n_byte *)output_string, (n_uint)input_length); io_number_to_string(&output_string[input_length], number); return ; } io_number_to_string(output_string, number); } void io_three_strings(n_string output_string, n_string first_string, n_string second_string, n_string third_string, n_byte new_line) { n_int first_length = io_length(first_string, STRING_BLOCK_SIZE); n_int second_length = io_length(second_string, STRING_BLOCK_SIZE); n_int third_length = io_length(third_string, STRING_BLOCK_SIZE); n_int carried_length = 0; if (first_length > 0) { if (first_string != output_string) { memory_copy((n_byte *)first_string, (n_byte *)output_string, (n_uint)first_length); } carried_length += first_length; } if (second_length > 0) { memory_copy((n_byte *)second_string, (n_byte *)&output_string[carried_length], (n_uint)second_length); carried_length += second_length; } if (third_length > 0) { memory_copy((n_byte *)third_string, (n_byte *)&output_string[carried_length], (n_uint)third_length); carried_length += third_length; } if (new_line) { #ifdef _WIN32 output_string[carried_length++] = 13; #endif output_string[carried_length++] = 10; } output_string[carried_length] = 0; } n_string io_string_copy(n_string string) { n_string return_string = 0L; n_uint string_length = (n_uint)(io_length(string, STRING_BLOCK_SIZE) + 1); if (string_length > 0) { return_string = (n_string)memory_new(string_length); memory_copy((n_byte *)string, (n_byte *)return_string, string_length-1); return_string[string_length-1] = 0; } return return_string; } #ifdef SIMULATED_APE_ASSERT void io_assert(n_string message, n_string file_loc, n_int line) { printf("Assert: %s, %s, %ld\n", message, file_loc, line); } #endif <|start_filename|>script/script.h<|end_filename|> /**************************************************************** script.h ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /*! \file script.h * \brief This is the interface between ApeScript and the ApeSDK. */ #ifndef _SCRIPT_H_ #define _SCRIPT_H_ /* Variable Definitions */ #define SCRIPT_DEBUG /* Add all the runtime debug */ #undef ROUGH_CODE_OUT /* printf outputs the interpret stream in character number format */ typedef enum { AE_NO_ERROR = -1, AE_UNKNOWN_ERROR, AE_NUMBER_EXPECTED, AE_NUMBER_OUT_OF_RANGE, AE_MAXIMUM_NUMBERS_REACHED, AE_MAXIMUM_SCRIPT_SIZE_REACHED, AE_MAXIMUM_VARIABLES_REACHED, AE_UNKNOWN_SYNTAX_PARSER_BUFFER, AE_UNKNOWN_SYNTAX_PARSER_CONVERT, AE_SELECTED_ENTITY_OUT_OF_RANGE, AE_COORDINATES_OUT_OF_RANGE, AE_VALUE_OUT_OF_RANGE, AE_TOO_MANY_CLOSE_BRACES, AE_MAXIMUM_BRACES_REACHED, AE_FIRST_VALUE_FAILED, AE_SECOND_VALUE_FAILED, AE_UNKNOWN_SYNTAX_MISSING_EQUALS, AE_UNKNOWN_SYNTAX_NO_COMMAND, AE_WRONG_END, AE_LINE_START_INCORRECT, AE_OUTPUT_SET_AS_INPUT_VARIABLE, AE_IF_WHILE_NOT_FOLLOWED_BY_BRACKET, AE_FUNCTION_ISNT_VARIABLE, AE_NON_FUNCTION_APPLIED, AE_FUNCTION_DEFINED_PRIOR, AE_FUNCTION_OUT_OF_RANGE, AE_WITHOUT_SEMICOLON, AE_WITHOUT_OPEN_BRACE, AE_FUNCTION_SETTING_FAILED, AE_ERROR_STARTING_MAIN, AE_CODE_AFTER_MAIN, AE_NO_CLOSE_BRACE_TO_END_OF_FILE, AE_CODE_OUTSIDE_FUNCTION, AE_INPUT_VARIABLE_WITHOUT_EQUALS, AE_ASSIGN_VALUE_FAILED, AE_UNKNOWN_SYNTAX_FROM_INTERPRET, AE_NO_MAIN_CODE, AE_NUMBER_ERRORS } AE_ENUM; typedef struct { AE_ENUM enum_value; n_constant_string error_string; n_constant_string help_string; } n_ae_error; /** \brief apescript_errors track the errors in ApeScript and additional text for user-manual level documentation */ static const n_ae_error apescript_errors[]= { {AE_UNKNOWN_ERROR, "Unknown error", "Please contact tom at apesim dot io"}, {AE_NUMBER_EXPECTED, "Number expected", "A non-numeric character is included in a number string."}, {AE_NUMBER_OUT_OF_RANGE, "Number out of range", "Number does not fit in the range"}, {AE_MAXIMUM_NUMBERS_REACHED, "Maximum numbers reached", "Please contact tom at apesim dot io"}, {AE_MAXIMUM_SCRIPT_SIZE_REACHED, "Maximum script size reached", "Please contact tom at apesim dot io"}, {AE_MAXIMUM_VARIABLES_REACHED, "Maximum variables reached", "Please contact tom at apesim dot io"}, {AE_UNKNOWN_SYNTAX_PARSER_BUFFER, "Unknown syntax (parser buffer)", "Syntax is incorrect"}, {AE_UNKNOWN_SYNTAX_PARSER_CONVERT, "Unknown syntax (parser convert)", "Syntax is incorrect"}, {AE_SELECTED_ENTITY_OUT_OF_RANGE, "Selected entity out of range", "Selected entity is outside the bounds of the number of entities."}, {AE_COORDINATES_OUT_OF_RANGE, "Coordinates out of range", "Coordinates outside the prescribed range."}, {AE_VALUE_OUT_OF_RANGE, "Value out of range", "Value outside the presecribed range."}, {AE_TOO_MANY_CLOSE_BRACES, "Too many }", "You have closed too many braces. Go back to the code and see if there is an erroneous additional } in the code."}, {AE_MAXIMUM_BRACES_REACHED, "Maximum braces reached", "Please contact tom at apesim dot io"}, {AE_FIRST_VALUE_FAILED, "First value failed", "Something is wrong with the first value of an equality, if or while operation. It could be the first and only value in this function."}, {AE_SECOND_VALUE_FAILED, "Second value failed", "Something is wrong with the second number/variable value of an equality, if or while operation."}, {AE_UNKNOWN_SYNTAX_MISSING_EQUALS, "Unknown syntax (missing =)", "Syntax is incorrect"}, {AE_UNKNOWN_SYNTAX_NO_COMMAND, "Unknown syntax (no command)", "Syntax is incorrect"}, {AE_WRONG_END, "Wrong end", "A bracket or colon was expected but not found."}, {AE_LINE_START_INCORRECT, "Line start incorrect", "A line of code begins incorrectly. It could start with a number or an operator when if/while or a variable was expected."}, {AE_OUTPUT_SET_AS_INPUT_VARIABLE, "Output set as input variable", "An output only variable is attempting to be set."}, {AE_IF_WHILE_NOT_FOLLOWED_BY_BRACKET, "if/while not followed by {", "All if/while statements require a bracket following the if/while (allowing for any amount of whitespace too)."}, {AE_FUNCTION_ISNT_VARIABLE, "Function isn't variable", "Function must not be a special term."}, {AE_NON_FUNCTION_APPLIED, "Non-function applied", "Expecting a function."}, {AE_FUNCTION_DEFINED_PRIOR, "Function defined prior", "Single function definition only."}, {AE_FUNCTION_OUT_OF_RANGE, "Function out of range", "Function defined outside the range of the code presented."}, {AE_WITHOUT_SEMICOLON, "Without ;", "Semi-colon required."}, {AE_WITHOUT_OPEN_BRACE, "Without {", "All if/while statements expect what is executed through the bracket enclosed statement being correct to be followed by inclusive braces { }. There is no single line if or while statements without { } in ApeScript."}, {AE_FUNCTION_SETTING_FAILED, "Function setting failed", "Function could not be set."}, {AE_ERROR_STARTING_MAIN, "Error starting main", "Main could not be started."}, {AE_CODE_AFTER_MAIN, "Code after main", "All the code in ApeScript must exist before the end of main."}, {AE_NO_CLOSE_BRACE_TO_END_OF_FILE, "No } to end of file", "Based on the final main function it is expected that the last meaningful character will be }."}, {AE_CODE_OUTSIDE_FUNCTION, "Code outside function", "All code in ApeScript needs to exist within functions."}, {AE_INPUT_VARIABLE_WITHOUT_EQUALS, "Input variable without equals", "All variables set require an equals following the variable."}, {AE_ASSIGN_VALUE_FAILED, "Assign value failed", "Something is wrong with the variable set by an equality."}, {AE_UNKNOWN_SYNTAX_FROM_INTERPRET, "Unknown syntax (from interpret)", "Syntax is incorrect"}, {AE_NO_MAIN_CODE, "No main code", "ApeScript requires a main function."}, {AE_NO_ERROR, 0L, 0L} }; /* "---1---2---3---4---5---6---7--" */ /* length of the errors */ #define APESCRIPT_ERROR(individual, value) (apescript_error(individual, value, __FILE__, __LINE__)) #define SHOW_ERROR_FILE_LINE(val, file, line) (draw_error(val, file, line)) #define SHOW_ERROR(val) (draw_error(val, __FILE__, __LINE__)) #define IO_LOWER_CHAR(value) if(ASCII_UPPERCASE(value)) (value) += 'a' - 'A' enum PRIMARY_APESCRIPT { VARIABLE_FUNCTION = 0, VARIABLE_RUN, VARIABLE_WHILE, VARIABLE_IF }; enum SYNTAX_APESCRIPT { SYNTAX_MINUS = 0, SYNTAX_ADDITION, SYNTAX_MULTIPLY, SYNTAX_AND, SYNTAX_XOR, SYNTAX_OR, SYNTAX_GREATER_THAN, SYNTAX_LESS_THAN, SYNTAX_EQUAL_TO, SYNTAX_NOT_EQUAL_TO, SYNTAX_CONDITIONAL_AND, SYNTAX_CONDITIONAL_OR, SYNTAX_DIVISION, SYNTAX_MODULUS, SYNTAX_BITSHIFT_RIGHT, SYNTAX_BITSHIFT_LEFT, SYNTAX_LESS_EQUAL, SYNTAX_GREATER_EQUAL, SYNTAX_EQUALS }; enum SYNTAX_ADDITIONAL_BRAINCODE { SYNTAX_MOVE = SYNTAX_EQUALS + 1, SYNTAX_JUMP_TO, SYNTAX_JUMP_EQUAL_ZERO, SYNTAX_DATA }; enum APESCRIPT_INTERPRET_TYPES { APESCRIPT_OPEN_BRACKET = ('('), APESCRIPT_CLOSE_BRACKET = (')'), APESCRIPT_OPEN_BRACE = ('{'), APESCRIPT_CLOSE_BRACE = ('}'), APESCRIPT_OPERATOR = ('='), APESCRIPT_NUMBER = ('n'), APESCRIPT_TEXT = ('t'), APESCRIPT_SEMICOLON = (';'), APESCRIPT_FAILURE = ('F'), APESCRIPT_FUNCTION = ('f'), APESCRIPT_RUN = ('r'), APESCRIPT_STRING = ('"') }; #define ASCII_QUOTE(num) ((num) == '"') #define ASCII_TEXT(num) ((ASCII_UPPERCASE(num) || ASCII_LOWERCASE(num)) || ((num) == '_')) #define ASCII_SEMICOLON(num) ((num) == ';') #define ASCII_COLON(num) ((num) == ':') #define ASCII_COMMA(num) ((num) == ',') #define ASCII_EQUAL(num) ((num) == '=') #define ASCII_BRACKET(num) (((num) == '(')||((num) == ')')) #define ASCII_BRACES(num) (((num) == '{')||((num) == '}')) #define ASCII_LOGICAL(num) ((((num) == '&')||((num) == '|'))||(((num) == '^')||((num) == '!'))) #define ASCII_ARITHMETIC(num) ((((num) == '+')||((num) == '-'))||(((num) == '*')||((num) == '/'))) #define ASCII_DIRECTIONAL(num) (((num)=='<')||((num)=='>')) #define CODE_VALUE_REQUIRED(num) (((num) == APESCRIPT_OPERATOR || (num) == APESCRIPT_NUMBER) || ((num) == APESCRIPT_TEXT)) #define SIZEOF_NUMBER_WRITE (sizeof(n_int)) void io_int_to_bytes(n_int value, n_byte * bytes); n_int io_bytes_to_int(n_byte * bytes); #define VARIABLE_INPUT(num,code) ((num)>((code)->input_greater)) #define VARIABLE_SPECIAL(num,code) ((num)<((code)->special_less)) #define NUMBER_MAX 256 #define VARIABLE_MAX 256 #define BRACES_MAX 16 #define SIZE_OF_EVALUATE (SIZEOF_NUMBER_WRITE+SIZEOF_NUMBER_WRITE+1) /* (tA=XtB) */ #define CYCLE_COUNT_RESET 4096 #define MAIN_NOT_RUN 0 #define MAIN_RUN 1 /*! @typedef @field code The pointer to the n_interpret struct. @field kind The variable in question - this could be thought of as an index to a variable array. @field value The value to set the variable in question. @return Any error that is reported. @discussion The two primay interfaces in ApeScript relate to the getting and setting of information. This function covers the setting of information. */ typedef n_int (script_input )(void * individual, n_byte kind, n_int value); /*! @typedef @field code The pointer to the n_interpret struct. @field kind The pointer has two values either a variable or a number. @field value The resultant value. @return Any error that is reported. @discussion The two primay interfaces in ApeScript relate to the getting and setting of information. This function covers the getting of information. */ typedef n_int (script_output)(void * code, void * individual, n_byte * kind, n_int * number); typedef void (script_external)(void * individual, void * structure, void * data); #define VARIABLE_WIDTH 32 typedef n_byte variable_string[VARIABLE_WIDTH]; /*! @struct @field evaluate The length of the evaluated string. @field braces_start The location where the braces start. @discussion This structure is used for the evaluation of if/then or while checks in ApeScript and it shows where the braces code should return to in the case of a while loop. */ typedef struct { n_byte evaluate[SIZE_OF_EVALUATE]; n_int braces_start; } n_brace; typedef struct { n_file *binary_code; n_int number_buffer[NUMBER_MAX]; /* per entry */ variable_string *variable_strings; n_int main_entry; n_int input_greater; n_int special_less; script_input *sc_input; script_output *sc_output; } n_interpret; typedef struct { n_int interpret_location; /* per entry */ n_int leave; /* per entry */ n_int localized_leave; /* per entry */ void * interpret_data; /* per entry */ n_int variable_references[VARIABLE_MAX]; /* per entry */ n_int braces_count; /* per entry */ n_brace braces[BRACES_MAX]; /* per entry */ n_byte main_status; /* per entry */ } n_individual_interpret; /* used for stripping ApeScript errors for documentation */ n_int apescript_error(n_individual_interpret * individual, AE_ENUM value, n_constant_string location, n_int line_number); n_interpret * parse_convert(n_file * input, n_int main_entry, variable_string * variables); void interpret_individual(n_individual_interpret * individual); void interpret_cleanup(n_interpret ** to_clean); n_int interpret_cycle(n_interpret * code, n_individual_interpret * individual, n_int exit_offset, void * structure, void * data, script_external * start, script_external * end); #ifdef SCRIPT_DEBUG n_file * scdebug_file_ready(void); void scdebug_file_cleanup(void); void scdebug_string(void * ptr, n_constant_string string); void scdebug_int(void * ptr, n_int number); void scdebug_newline(void * ptr); void scdebug_tabstep(void * ptr, n_int steps); n_string scdebug_variable(n_int variable); void scdebug_writeon(void * ptr); void scdebug_writeoff(void * ptr); #define SC_DEBUG_STRING(ptr, string) scdebug_string(ptr, string) #define SC_DEBUG_NUMBER(ptr, number) scdebug_int(ptr, number) #define SC_DEBUG_NEWLINE(ptr) scdebug_newline(ptr) #define SC_DEBUG_UP(ptr) scdebug_tabstep(ptr,1) #define SC_DEBUG_DOWN(ptr) scdebug_tabstep(ptr,-1) #define SC_DEBUG_ON(ptr) scdebug_writeon(ptr) #define SC_DEBUG_OFF(ptr) scdebug_writeoff(ptr) #else #define SC_DEBUG_STRING(string) /* string */ #define SC_DEBUG_NUMBER(number) /* number */ #define SC_DEBUG_NEWLINE /* */ #define SC_DEBUG_UP /* */ #define SC_DEBUG_DOWN /* */ #define SC_DEBUG_ON(ptr) /* ptr */ #define SC_DEBUG_OFF /* */ #endif #endif /* _SCRIPT_H_ */ <|start_filename|>entity/skeleton.c<|end_filename|> /**************************************************************** skeleton.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #include <math.h> #include "../toolkit/toolkit.h" #include "entity.h" #define MAX_SKELETON_DIAGRAM_POINTS 200000 #undef VASCULAR_DRAWING_READY enum { SKELETON_NECK = 0, SKELETON_LUMBAR, SKELETON_PELVIS, SKELETON_LEFT_HIP, SKELETON_RIGHT_HIP, SKELETON_LEFT_KNEE, SKELETON_RIGHT_KNEE, SKELETON_LEFT_ANKLE, SKELETON_RIGHT_ANKLE, SKELETON_LEFT_SHOULDER, SKELETON_RIGHT_SHOULDER, SKELETON_LEFT_SHOULDER_SOCKET, SKELETON_RIGHT_SHOULDER_SOCKET, SKELETON_LEFT_ELBOW, SKELETON_RIGHT_ELBOW, SKELETON_LEFT_WRIST, SKELETON_RIGHT_WRIST, SKELETON_LEFT_COLLAR, SKELETON_RIGHT_COLLAR, SKELETON_POINTS }; enum BODY_BONES { BONE_ARM_UPPER = 0, BONE_ARM_LOWER1, BONE_ARM_LOWER2, BONE_CLAVICAL, BONE_LEG_UPPER, BONE_LEG_LOWER1, BONE_LEG_LOWER2, BONE_PELVIS, BONE_HAND, BONE_FINGER, BONE_VERTIBRA, BONE_SCAPULA, BONE_RIBS, BONES }; #define SKELETON_LUMBAR_VERTIBRA 4 #define SKELETON_LUMBAR_VERTIBRA2 8 #define SKELETON_VERTIBRA_RIBS 10 const n_int bone_points[] = { 54, /* arm upper */ 44, /* arm lower1 */ 41, /* arm lower2 */ 33, /* clavical */ 58, /* leg upper */ 30, /* leg lower1 */ 37, /* leg lower2 */ 88, /* pelvis */ 24, /* hand */ 33, /* finger */ 36, /* vertibra */ 48, /* scapula */ 82 /* ribs */ }; const n_vect2 bone_arm_upper[] = { {42,0}, {53,475}, /* axis */ {49,0}, {16,8}, {9,21}, {2,37}, {5,50}, {10,64}, {14,77}, {14,95}, {12,143}, {12,193}, {10,241}, {12,259}, {18,286}, {21,314}, {21,343}, {20,372}, {17,408}, {13,424}, {5,438}, {1,444}, {3,458}, {14,470}, {18,472}, {28,473}, {42,477}, {52,476}, {63,469}, {75,477}, {92,477}, {90,458}, {99,455}, {107,450}, {111,440}, {107,429}, {100,425}, {88,418}, {77,407}, {69,393}, {65,382}, {62,347}, {60,313}, {56,270}, {51,218}, {52,174}, {52,127}, {54,88}, {57,71}, {64,68}, {69,54}, {75,47}, {81,36}, {84,27}, {77,10}, {67,1} }; const n_vect2 bone_arm_lower1[] = { {34,4}, {59,346}, /* axis */ {48,0}, {35,0}, {21,1}, {14,9}, {15,15}, {22,23}, {24,31}, {24,42}, {20,67}, {15,102}, {9,132}, {4,157}, {2,177}, {3,197}, {7,225}, {11,258}, {16,290}, {18,308}, {19,327}, {20,337}, {19,347}, {23,351}, {36,349}, {50,347}, {60,342}, {70,340}, {72,336}, {72,331}, {67,327}, {51,314}, {46,305}, {40,285}, {33,259}, {31,233}, {28,208}, {28,183}, {30,166}, {37,131}, {48,77}, {52,60}, {45,45}, {43,31}, {45,13}, {44,4} }; const n_vect2 bone_arm_lower2[] = { {34,4}, {59,346}, /* axis */ {65,0}, {53,0}, {48,11}, {45,25}, {40,40}, {35,102}, {35,127}, {35,151}, {39,178}, {43,209}, {48,237}, {54,266}, {58,299}, {60,317}, {55,329}, {53,339}, {54,343}, {69,344}, {80,346}, {88,349}, {91,343}, {89,335}, {84,324}, {78,314}, {75,293}, {74,271}, {70,239}, {64,207}, {60,174}, {57,132}, {58,112}, {62,77}, {65,58}, {72,48}, {74,35}, {85,27}, {95,23}, {98,16}, {96,8}, {86,5}, {77,2} }; const n_vect2 bone_clavical[] = { {23,201}, {31,13}, /* axis */ {26,4}, {20,12}, {19,22}, {24,30}, {30,39}, {29,53}, {24,77}, {15,100}, {10,114}, {6,130}, {4,146}, {5,159}, {9,176}, {14,189}, {15,200}, {18,206}, {23,207}, {28,206}, {31,199}, {31,192}, {27,182}, {25,173}, {22,156}, {22,143}, {24,126}, {28,110}, {39,88}, {45,68}, {49,52}, {50,40}, {48,27}, {43,12}, {38,7} }; const n_vect2 bone_leg_upper[] = { {119,33}, {80,416}, /* axis */ {47,3}, {36,7}, {30,15}, {27,22}, {23,43}, {19,73}, {18,90}, {20,112}, {22,140}, {23,178}, {24,223}, {29,286}, {32,330}, {30,360}, {26,378}, {24,386}, {28,398}, {36,410}, {49,419}, {65,425}, {78,422}, {84,417}, {91,410}, {102,405}, {114,408}, {126,408}, {133,401}, {134,389}, {135,373}, {125,362}, {114,354}, {99,347}, {89,330}, {78,305}, {71,274}, {64,221}, {64,174}, {67,126}, {73,93}, {76,77}, {87,67}, {99,63}, {111,59}, {116,61}, {121,63}, {126,58}, {127,51}, {122,38}, {117,22}, {109,14}, {99,13}, {91,19}, {86,24}, {78,26}, {70,25}, {64,17}, {66,7}, {60,3} }; const n_vect2 bone_leg_lower1[] = { {94,5}, {46,287}, /* axis */ {23,26}, {14,33}, {12,45}, {14,55}, {16,68}, {17,101}, {18,132}, {18,166}, {17,195}, {18,223}, {20,241}, {17,251}, {11,260}, {5,269}, {5,275}, {14,280}, {25,284}, {33,283}, {37,275}, {36,261}, {32,240}, {28,210}, {27,171}, {30,154}, {31,134}, {30,94}, {31,69}, {36,48}, {36,36}, {32,27} }; const n_vect2 bone_leg_lower2[] = { {94,5}, {46,287}, /* axis */ {66,1}, {44,1}, {28,1}, {24,8}, {25,24}, {34,37}, {41,49}, {49,66}, {54,85}, {58,106}, {59,130}, {59,165}, {57,196}, {51,227}, {45,245}, {40,254}, {36,266}, {39,280}, {47,287}, {59,287}, {77,281}, {87,277}, {90,272}, {90,265}, {84,250}, {83,230}, {83,188}, {83,149}, {85,109}, {88,74}, {92,47}, {100,38}, {110,29}, {116,18}, {114,6}, {98,5}, {80,1} }; const n_vect2 bone_pelvis[] = { {214,27}, {203,382}, /* axis */ {213,24}, {183,21}, {166,22}, {156,18}, {139,12}, {118,6}, {100,6}, {79,8}, {68,11}, {60,19}, {46,34}, {35,49}, {25,65}, {17,81}, {9,96}, {6,108}, {6,122}, {15,136}, {27,150}, {44,165}, {59,181}, {71,197}, {75,221}, {78,240}, {77,255}, {84,254}, {97,259}, {104,271}, {107,284}, {106,295}, {105,303}, {112,315}, {116,330}, {118,347}, {112,358}, {105,365}, {101,367}, {102,376}, {111,384}, {127,393}, {141,393}, {158,390}, {177,387}, {189,381}, {201,369}, {213,359}, {215,336}, {216,349}, {218,358}, {225,370}, {240,380}, {254,385}, {272,387}, {294,387}, {307,387}, {316,375}, {317,367}, {310,357}, {300,337}, {300,320}, {308,308}, {316,304}, {321,294}, {320,283}, {322,275}, {321,266}, {330,259}, {342,254}, {349,245}, {348,217}, {354,192}, {364,176}, {381,162}, {402,144}, {423,131}, {432,121}, {433,104}, {427,84}, {411,60}, {392,37}, {377,22}, {360,11}, {336,7}, {311,11}, {277,18}, {258,25}, {244,26}, {222,24}, {101,272}, /* left leg */ {321,265} /* right leg */ }; const n_vect2 bone_hand[] = { {20,6}, {14,100}, /* axis */ {19,4}, {12,6}, {9,12}, {9,23}, {10,40}, {9,59}, {8,75}, {6,86}, {3,91}, {8,98}, {9,102}, {15,102}, {20,101}, {24,96}, {27,90}, {27,84}, {24,76}, {23,64}, {24,40}, {24,24}, {26,18}, {29,10}, {28,4}, {23,3} }; const n_vect2 bone_finger[] = { {14,1}, {15,114}, /* axis */ {13,1}, {6,3}, {4,6}, {3,10}, {6,14}, {6,26}, {6,40}, {8,52}, {9,56}, {8,60}, {6,66}, {6,72}, {8,82}, {7,92}, {9,98}, {10,104}, {11,112}, {14,114}, {16,113}, {18,107}, {19,100}, {19,92}, {20,86}, {20,78}, {20,68}, {23,60}, {25,52}, {26,44}, {24,34}, {23,18}, {23,7}, {21,3}, {16,2} }; const n_vect2 bone_vertibra[] = { {53,1}, {53,47}, /* axis */ {53,2}, {41,2}, {30,4}, {22,7}, {22,16}, {22,24}, {20,32}, {14,32}, {4,34}, {1,36}, {1,42}, {5,46}, {14,48}, {18,48}, {18,54}, {24,53}, {33,50}, {43,48}, {53,49}, {62,50}, {72,53}, {81,56}, {87,56}, {88,50}, {95,50}, {98,48}, {100,42}, {98,38}, {91,37}, {84,35}, {84,33}, {84,24}, {86,14}, {84,10}, {74,6}, {62,0} }; const n_vect2 bone_scapula[] = { {35, 0}, {134,214}, /* axis */ {37,3}, {22,7}, {11,15}, {6,21}, {4,28}, {4,40}, {9,58}, {19,80}, {38,113}, {60,142}, {81,178}, {101,204}, {114,219}, {128,226}, {138,230}, {153,221}, {165,211}, {171,194}, {173,170}, {175,143}, {177,116}, {176,97}, {168,81}, {177,69}, {187,60}, {188,41}, {184,23}, {175,13}, {162,11}, {151,12}, {146,22}, {136,34}, {128,46}, {118,59}, {113,56}, {109,43}, {100,34}, {93,34}, {84,36}, {83,46}, {75,51}, {67,52}, {58,42}, {58,34}, {48,27}, {51,19}, {52,12}, {45,6} }; const n_vect2 bone_ribs[] = { {227,11}, {212,350}, /* axis */ {226,10}, {199,7}, {177,15}, {152,25}, {139,37}, {122,52}, {112,62}, {104,75}, {91,93}, {85,108}, {76,127}, {69,149}, {62,169}, {61,183}, {53,208}, {53,218}, {44,230}, {39,244}, {40,255}, {36,262}, {30,278}, {28,295}, {28,299}, {22,317}, {22,336}, {23,348}, {16,365}, {15,389}, {14,411}, {10,437}, {13,449}, {18,446}, {18,434}, {33,425}, {56,407}, {83,392}, {116,382}, {141,373}, {159,362}, {173,351}, {184,351}, {213,348}, {235,355}, {242,356}, {244,352}, {264,363}, {283,377}, {304,386}, {333,396}, {355,409}, {375,423}, {395,443}, {409,458}, {416,450}, {419,440}, {415,429}, {417,404}, {411,383}, {408,366}, {411,348}, {411,327}, {409,315}, {407,296}, {402,278}, {395,267}, {393,243}, {385,232}, {384,213}, {379,200}, {371,194}, {367,172}, {359,155}, {357,134}, {344,114}, {334,90}, {322,80}, {318,67}, {301,47}, {289,30}, {275,22}, {247,15}, {227,12}, {35,3}, {416,3}, /* shoulder sockets */ {35,-20}, {416,-20}, /* shoulders */ }; /** * @brief Returns an array of 2D points used for drawing diagrams * @param source_points Array of 2D points which is the template * @param no_of_source_points Number of 2D points in the template * @param extra_points The number of points to be returned via the extra parameters * @param x The starting x coordinate * @param y The starting y coordinate * @param mirror Flip in the vertical axis * @param scale Horizontal scaling factor x1000 * @param angle Rotation angle of the result */ static void outline_points(const n_vect2 * source_points, n_int no_of_source_points, n_int extra_points, n_int x, n_int y, n_byte mirror, n_vect2 * scale, n_int angle, n_vect2 *axis, n_vect2 *extra_1, n_vect2 *extra_2, n_vect2 *extra_3, n_vect2 *extra_4, n_points * collection) { n_vect2 ds, location, vector; n_int i, axis_length,point_length; n_double axis_angle, point_angle; n_double ang = angle*TWO_PI/7200; vect2_populate(&location, x, y); vect2_subtract(&ds, (n_vect2 *)&source_points[1], (n_vect2 *)source_points); vect2_multiplier(&ds, &ds, scale, 1, 1000); /** length of the object */ axis_length = (n_int)math_root(vect2_dot(&ds, &ds, 1, 1)); if (axis_length < 1) axis_length=1; /** invert around the vertical axis if needed */ if (mirror != 0) { ds.x = -ds.x; } /** find the orientation angle of the axis */ axis_angle = (float)acos(ds.x/(float)axis_length); if (ds.y < 0) { axis_angle = TWO_PI-axis_angle; } vect2_populate(&vector, (n_int)(axis_length*sin(ang+(TWO_PI/4)-axis_angle)), (n_int)(axis_length*cos(ang+(TWO_PI/4)-axis_angle))); /** calculate the position of the end point of the axis */ vect2_add(axis, &location, &vector); /** draw lines between each point */ for (i = 2; i < no_of_source_points + 2 + extra_points; i++) { n_vect2 point; vect2_subtract(&ds, (n_vect2 *)&source_points[i], (n_vect2 *)source_points); vect2_multiplier(&ds, &ds, scale, 1, 1000); point_length = (n_int)math_root(vect2_dot(&ds, &ds, 1, 1)); if (point_length < 1) { point_length = 1; } /** invert the line around the vertical axis if necessary */ if (mirror != 0) { ds.x = -ds.x; } /** angle of the line */ point_angle = (float)acos(ds.x/(float)point_length); if (ds.y < 0) { point_angle = (TWO_PI)-point_angle; } /** position of the end of the line */ vect2_populate(&vector, (n_int)(point_length*sin(ang+point_angle-axis_angle)), (n_int)(point_length*cos(ang+point_angle-axis_angle))); vect2_add(&point, &location, &vector); /** store the calculated point positions in an array */ if (collection->no_of_points < collection->max_points) { if (i < no_of_source_points + 2) { vect2_copy(&collection->points[collection->no_of_points], &point); collection->no_of_points++; } } /* TODO else { (void)SHOW_ERROR("Maximum number of skeleton points reached"); } */ /** This is a crude way of keeping track of the last few points so that they can be returned by the function */ vect2_copy(extra_1, extra_2); vect2_copy(extra_2, extra_3); vect2_copy(extra_3, extra_4); vect2_copy(extra_4, &point); } if (collection->no_of_points > -1 && collection->no_of_points < collection->max_points) { collection->points[collection->no_of_points].x = 9999; collection->points[collection->no_of_points].y = 9999; collection->no_of_points++; } else { SHOW_ERROR("Outside point range for drawing"); } } /** * @brief Returns vertical and horizontal scaling factors based upon the * genetics for a particular body segment * @param keypoint The index within the BONES enumeration * @param scale The returned scale for the bone x1000 */ static void body_skeleton_gene(n_genetics * genetics, n_byte keypoint, n_vect2* scale) { /** the maximum variation in body segment proportions, typically in the range 0-500 */ const n_int MAX_SEGMENT_VARIANCE = 200; /** these are 4 bit gene values in the range 0-15 */ n_byte gene_val1 = (n_byte)GENE_HOX(genetics,keypoint); n_byte gene_val2 = (n_byte)GENE_HOX(genetics,20-keypoint); /** convert the gene values into scaling values */ scale->x = 1000 - MAX_SEGMENT_VARIANCE + (((n_int)gene_val1)*MAX_SEGMENT_VARIANCE*2/15); scale->y = 1000 - MAX_SEGMENT_VARIANCE + (((n_int)gene_val2)*MAX_SEGMENT_VARIANCE*2/15); } /** * @brief returns a set of points corresponding to key locations on the skeleton * @param keypoints Array which returns the x,y coordinates of each key point on the skeleton * @param collection The returned 2D points of the skeleton diagram * @param shoulder_angle Angle of the shoulders in degrees * @param elbow_angle Angle of the elbows in degrees * @param wrist_angle Angle of the wrists in degrees * @param hip_angle Angle of the hips in degrees * @param knee_angle Angle of the knees in degrees * @return Number of 2D points within the skeleton diagram */ static n_int graph_skeleton_points(n_genetics * genetics, n_vect2 * keypoints, n_points * collection, n_int shoulder_angle, n_int elbow_angle, n_int wrist_angle, n_int hip_angle, n_int knee_angle) { n_int angle=0; n_vect2 scale = {1000, 1000}; n_vect2 extra[4]; n_vect2 vertibra = {0,0}; n_vect2 knuckle = {0,0}; n_int i, vertical; collection->no_of_points = 0; NA_ASSERT(keypoints, "keypoints NULL"); /** position of the bottom of the neck */ keypoints[SKELETON_NECK].x = 0; keypoints[SKELETON_NECK].y = 0; /** position of the bottom of the ribs */ body_skeleton_gene(genetics, BONE_RIBS, &scale); outline_points(bone_ribs, bone_points[BONE_RIBS],4, keypoints[SKELETON_NECK].x, keypoints[SKELETON_NECK].y, 0, &scale, angle, &keypoints[SKELETON_LUMBAR], &keypoints[SKELETON_LEFT_SHOULDER_SOCKET], &keypoints[SKELETON_RIGHT_SHOULDER_SOCKET], &keypoints[SKELETON_LEFT_SHOULDER], &keypoints[SKELETON_RIGHT_SHOULDER], collection); /** left scapula */ body_skeleton_gene(genetics, BONE_SCAPULA, &scale); outline_points(bone_scapula, bone_points[BONE_SCAPULA],0, keypoints[SKELETON_LEFT_SHOULDER].x, keypoints[SKELETON_LEFT_SHOULDER].y, 0, &scale, angle-600, &extra[0], &extra[0], &extra[1], &extra[2], &extra[3], collection); /** right scapula */ outline_points(bone_scapula, bone_points[BONE_SCAPULA],0, keypoints[SKELETON_RIGHT_SHOULDER].x, keypoints[SKELETON_RIGHT_SHOULDER].y, 1, &scale, angle+500, &extra[0], &extra[0], &extra[1], &extra[2], &extra[3], collection); /** ribs */ body_skeleton_gene(genetics, BONE_RIBS, &scale); outline_points(bone_ribs, bone_points[BONE_RIBS],4, keypoints[SKELETON_NECK].x, keypoints[SKELETON_NECK].y, 0, &scale, angle, &keypoints[SKELETON_LUMBAR], &keypoints[SKELETON_LEFT_SHOULDER_SOCKET], &keypoints[SKELETON_RIGHT_SHOULDER_SOCKET], &keypoints[SKELETON_LEFT_SHOULDER], &keypoints[SKELETON_RIGHT_SHOULDER], collection); /** position of the top of the pelvis */ keypoints[SKELETON_PELVIS].x = keypoints[SKELETON_LUMBAR].x; keypoints[SKELETON_PELVIS].y = keypoints[SKELETON_LUMBAR].y + ((keypoints[SKELETON_LUMBAR].y-keypoints[SKELETON_NECK].y)*40/100); /** position of hips */ body_skeleton_gene(genetics, BONE_PELVIS, &scale); outline_points(bone_pelvis, bone_points[BONE_PELVIS],2, keypoints[SKELETON_PELVIS].x, keypoints[SKELETON_PELVIS].y, 0, &scale, angle, &extra[0], &extra[0], &extra[1], &keypoints[SKELETON_LEFT_HIP], &keypoints[SKELETON_RIGHT_HIP], collection); /** left upper leg */ body_skeleton_gene(genetics, BONE_LEG_UPPER, &scale); outline_points(bone_leg_upper, bone_points[BONE_LEG_UPPER],0, keypoints[SKELETON_LEFT_HIP].x, keypoints[SKELETON_LEFT_HIP].y, 0, &scale, angle+(hip_angle*10), &keypoints[SKELETON_LEFT_KNEE], &extra[0], &extra[1], &extra[2], &extra[3], collection); /** left lower leg 1 */ body_skeleton_gene(genetics, BONE_LEG_LOWER1, &scale); outline_points(bone_leg_lower1, bone_points[BONE_LEG_LOWER1],0, keypoints[SKELETON_LEFT_KNEE].x, keypoints[SKELETON_LEFT_KNEE].y, 0, &scale, angle+(knee_angle*10), &keypoints[SKELETON_LEFT_ANKLE], &extra[0], &extra[1], &extra[2], &extra[3], collection); /** left lower leg 2 */ body_skeleton_gene(genetics, BONE_LEG_LOWER1, &scale); outline_points(bone_leg_lower2, bone_points[BONE_LEG_LOWER2],0, keypoints[SKELETON_LEFT_KNEE].x, keypoints[SKELETON_LEFT_KNEE].y, 0, &scale, angle+(knee_angle*10), &keypoints[SKELETON_LEFT_ANKLE], &extra[0], &extra[1], &extra[2], &extra[3], collection); /** right upper leg */ body_skeleton_gene(genetics, BONE_LEG_UPPER, &scale); outline_points(bone_leg_upper, bone_points[BONE_LEG_UPPER],0, keypoints[SKELETON_RIGHT_HIP].x, keypoints[SKELETON_RIGHT_HIP].y, 1, &scale, angle-(hip_angle*10), &keypoints[SKELETON_RIGHT_KNEE], &extra[0], &extra[1], &extra[2], &extra[3], collection); /** right lower leg 1 */ body_skeleton_gene(genetics, BONE_LEG_LOWER1, &scale); outline_points(bone_leg_lower1, bone_points[BONE_LEG_LOWER1],0, keypoints[SKELETON_RIGHT_KNEE].x, keypoints[SKELETON_RIGHT_KNEE].y, 1, &scale, angle-(knee_angle*10), &keypoints[SKELETON_RIGHT_ANKLE], &extra[0], &extra[1], &extra[2], &extra[3], collection); /** right lower leg 2 */ body_skeleton_gene(genetics, BONE_LEG_LOWER1, &scale); outline_points(bone_leg_lower2, bone_points[BONE_LEG_LOWER2],0, keypoints[SKELETON_RIGHT_KNEE].x, keypoints[SKELETON_RIGHT_KNEE].y, 1, &scale, angle-(knee_angle*10), &keypoints[SKELETON_RIGHT_ANKLE], &extra[0], &extra[1], &extra[2], &extra[3], collection); /** left upper arm */ body_skeleton_gene(genetics, BONE_ARM_UPPER, &scale); outline_points(bone_arm_upper, bone_points[BONE_ARM_UPPER],0, keypoints[SKELETON_LEFT_SHOULDER_SOCKET].x, keypoints[SKELETON_LEFT_SHOULDER_SOCKET].y, 0, &scale, angle+(shoulder_angle*10), &keypoints[SKELETON_LEFT_ELBOW], &extra[0], &extra[1], &extra[2], &extra[3], collection); /** left lower arm 1 */ body_skeleton_gene(genetics, BONE_ARM_LOWER1, &scale); outline_points(bone_arm_lower1, bone_points[BONE_ARM_LOWER1],0, keypoints[SKELETON_LEFT_ELBOW].x, keypoints[SKELETON_LEFT_ELBOW].y, 0, &scale, angle+(elbow_angle*10), &keypoints[SKELETON_LEFT_WRIST], &extra[0], &extra[1], &extra[2], &extra[3], collection); /** left lower arm 2 */ body_skeleton_gene(genetics, BONE_ARM_LOWER1, &scale); outline_points(bone_arm_lower2, bone_points[BONE_ARM_LOWER2],0, keypoints[SKELETON_LEFT_ELBOW].x, keypoints[SKELETON_LEFT_ELBOW].y, 0, &scale, angle+(elbow_angle*10), &keypoints[SKELETON_LEFT_WRIST], &extra[0], &extra[1], &extra[2], &extra[3], collection); /** right upper arm */ body_skeleton_gene(genetics, BONE_ARM_UPPER, &scale); outline_points(bone_arm_upper, bone_points[BONE_ARM_UPPER],0, keypoints[SKELETON_RIGHT_SHOULDER_SOCKET].x, keypoints[SKELETON_RIGHT_SHOULDER_SOCKET].y, 1, &scale, angle-(shoulder_angle*10), &keypoints[SKELETON_RIGHT_ELBOW], &extra[0], &extra[1], &extra[2], &extra[3], collection); /** right lower arm 1 */ body_skeleton_gene(genetics, BONE_ARM_LOWER1, &scale); outline_points(bone_arm_lower1, bone_points[BONE_ARM_LOWER1],0, keypoints[SKELETON_RIGHT_ELBOW].x, keypoints[SKELETON_RIGHT_ELBOW].y, 1, &scale, angle-(elbow_angle*10), &keypoints[SKELETON_RIGHT_WRIST], &extra[0], &extra[1], &extra[2], &extra[3], collection); /** left lower arm 2 */ body_skeleton_gene(genetics, BONE_ARM_LOWER1, &scale); outline_points(bone_arm_lower2, bone_points[BONE_ARM_LOWER2],0, keypoints[SKELETON_RIGHT_ELBOW].x, keypoints[SKELETON_RIGHT_ELBOW].y, 1, &scale, angle-(elbow_angle*10), &keypoints[SKELETON_RIGHT_WRIST], &extra[0], &extra[1], &extra[2], &extra[3], collection); /** left clavical */ body_skeleton_gene(genetics, BONE_CLAVICAL, &scale); outline_points(bone_clavical, bone_points[BONE_CLAVICAL],0, keypoints[SKELETON_LEFT_SHOULDER].x, keypoints[SKELETON_LEFT_SHOULDER].y, 0, &scale, angle-1800, &keypoints[SKELETON_LEFT_COLLAR], &extra[0], &extra[1], &extra[2], &extra[3], collection); /** right clavical */ outline_points(bone_clavical, bone_points[BONE_CLAVICAL],0, keypoints[SKELETON_RIGHT_SHOULDER].x, keypoints[SKELETON_RIGHT_SHOULDER].y, 1, &scale, angle+1700, &keypoints[SKELETON_RIGHT_COLLAR], &extra[0], &extra[1], &extra[2], &extra[3], collection); vertical = keypoints[SKELETON_NECK].y; for (i = 0; i < SKELETON_VERTIBRA_RIBS; i++) { n_vect2 rib_scale; body_skeleton_gene(genetics, BONE_RIBS, &scale); rib_scale.x = (scale.x*5/10)+((scale.x*5/10)*i/SKELETON_VERTIBRA_RIBS); rib_scale.y = (scale.y*5/10)+((scale.y*5/10)*i/SKELETON_VERTIBRA_RIBS); outline_points(bone_vertibra, bone_points[BONE_VERTIBRA],0, keypoints[SKELETON_NECK].x+((keypoints[SKELETON_LUMBAR].x-keypoints[SKELETON_NECK].x)*i/SKELETON_VERTIBRA_RIBS), vertical, 0, &rib_scale, angle, &vertibra, &extra[0], &extra[1], &extra[2], &extra[3], collection); vertical = vertibra.y; } vertical = keypoints[SKELETON_LUMBAR].y; for (i = 0; i < SKELETON_LUMBAR_VERTIBRA; i++) { outline_points(bone_vertibra, bone_points[BONE_VERTIBRA],0, keypoints[SKELETON_LUMBAR].x, vertical, 0, &scale, angle, &vertibra, &extra[0], &extra[1], &extra[2], &extra[3], collection); vertical = vertibra.y; } for (i = 0; i < SKELETON_LUMBAR_VERTIBRA2; i++) { n_vect2 vertibra_scale; vertibra_scale.x = scale.x*(SKELETON_LUMBAR_VERTIBRA2-i)/SKELETON_LUMBAR_VERTIBRA2; vertibra_scale.y = ((scale.y*2/3)*(SKELETON_LUMBAR_VERTIBRA2-i)/SKELETON_LUMBAR_VERTIBRA2); outline_points(bone_vertibra, bone_points[BONE_VERTIBRA],0, keypoints[SKELETON_LUMBAR].x, vertical, 0, &vertibra_scale, angle, &vertibra, &extra[0], &extra[1], &extra[2], &extra[3], collection); vertical = vertibra.y; } for (i = 0; i < 4; i++) { /** left hand */ body_skeleton_gene(genetics, BONE_HAND, &scale); outline_points(bone_hand, bone_points[BONE_HAND],0, keypoints[SKELETON_LEFT_WRIST].x-(i*15), keypoints[SKELETON_LEFT_WRIST].y, 0, &scale, angle+200-(i*400/4)+(wrist_angle*10), &knuckle, &extra[0], &extra[1], &extra[2], &extra[3], collection); /** left finger */ body_skeleton_gene(genetics, BONE_FINGER, &scale); outline_points(bone_finger, bone_points[BONE_FINGER],0, knuckle.x, knuckle.y, 0, &scale, angle+400-(i*800/4)+(wrist_angle*10), &extra[0], &extra[0], &extra[1], &extra[2], &extra[3], collection); /** right hand */ body_skeleton_gene(genetics, BONE_HAND, &scale); outline_points(bone_hand, bone_points[BONE_HAND],0, keypoints[SKELETON_RIGHT_WRIST].x+((3-i)*15), keypoints[SKELETON_RIGHT_WRIST].y, 1, &scale, angle+200-(i*400/4)-(wrist_angle*10), &knuckle, &extra[0], &extra[1], &extra[2], &extra[3], collection); /** right finger */ body_skeleton_gene(genetics, BONE_FINGER, &scale); outline_points(bone_finger, bone_points[BONE_FINGER],0, knuckle.x, knuckle.y, 1, &scale, angle+400-(i*800/4)-(wrist_angle*10), &extra[0], &extra[0], &extra[1], &extra[2], &extra[3], collection); } /** left thumb */ body_skeleton_gene(genetics, BONE_FINGER, &scale); outline_points(bone_finger, bone_points[BONE_FINGER],0, keypoints[SKELETON_LEFT_WRIST].x-50, keypoints[SKELETON_LEFT_WRIST].y, 0, &scale, angle-800+(wrist_angle*10), &extra[0], &extra[0], &extra[1], &extra[2], &extra[3], collection); /** right thumb */ outline_points(bone_finger, bone_points[BONE_FINGER],0, keypoints[SKELETON_RIGHT_WRIST].x+50, keypoints[SKELETON_RIGHT_WRIST].y, 1, &scale, angle+800-(wrist_angle*10), &extra[0], &extra[0], &extra[1], &extra[2], &extra[3], collection); return collection->no_of_points; } /** * @brief Draws a the skeleton * @param buffer Image buffer (3 bytes per pixel) * @param img Image dimensions * @param tp Top coordinate of the bounding box * @param bp Bottom coordinate of the bounding box * @param thickness Thickness of the outline in pixels * @param shoulder_angle Angle of the shoulders in degrees * @param elbow_angle Angle of the elbows in degrees * @param wrist_angle Angle of the wrists in degrees * @param hip_angle Angle of the hips in degrees * @param knee_angle Angle of the knees in degrees * @param show_keypoints If non-zero show key points on the skeleton */ static void skeleton_draw(n_genetics * genetics, n_byte * buffer, n_vect2 * img, n_vect2 *tp, n_vect2 * bp, n_byte thickness, n_vect2 * keypoints, n_int shoulder_angle, n_int elbow_angle, n_int wrist_angle, n_int hip_angle, n_int knee_angle, n_byte show_keypoints) { n_vect2 skeleton_points[MAX_SKELETON_DIAGRAM_POINTS]; n_vect2 min = {99999,99999}; n_vect2 max = {-99999,-99999}; n_vect2 current; n_vect2 previous = {0, 0}; n_int i,no_of_points,first_point=0,ctr=0; n_rgba32 bone_shade = {220, 220, 220, 0}; n_rgba32 color = {150, 150, 150, 0}; n_points collection; collection.max_points = MAX_SKELETON_DIAGRAM_POINTS; collection.points = skeleton_points; collection.no_of_points = 0; /** get points on the skeleton */ no_of_points = graph_skeleton_points(genetics, keypoints, &collection, shoulder_angle, elbow_angle, wrist_angle, hip_angle, knee_angle); /** get the bounding box for the points */ for (i = 0; i < no_of_points; i++) { vect2_copy(&current, &skeleton_points[i]); if ((current.x==9999) || (current.y==9999)) continue; if (current.x < min.x) min.x = current.x; if (current.y < min.y) min.y = current.y; if (current.x > max.x) max.x = current.x; if (current.y > max.y) max.y = current.y; } if ((max.x - min.x) && (max.y - min.y)) { /** rescale the skeleton keypoints into the bounding box */ for (i = 0; i < SKELETON_POINTS; i++) { if (keypoints[i].x != 9999) { keypoints[i].x = tp->x + ((keypoints[i].x - min.x)*(bp->x - tp->x)/(max.x - min.x)); keypoints[i].y = tp->y + ((keypoints[i].y - min.y)*(bp->y - tp->y)/(max.y - min.y)); } } } if ((max.x - min.x) && (max.y - min.y)) { /** rescale the drawing points into the bounding box */ for (i = 0; i < no_of_points; i++) { if (skeleton_points[i].x != 9999) { skeleton_points[i].x = tp->x + ((skeleton_points[i].x - min.x)*(bp->x - tp->x)/(max.x - min.x)); skeleton_points[i].y = tp->y + ((skeleton_points[i].y - min.y)*(bp->y - tp->y)/(max.y - min.y)); } } } /** do the drawing */ for (i = 0; i < no_of_points; i++) { vect2_copy(&current, &skeleton_points[i]); if (i > 0) { if ((current.x!=9999) && (previous.x!=9999)) { if (first_point == -1) { first_point = i; } graph_line(buffer, img, &previous, &current, &color, thickness); } else { if ((first_point > -1) && (i - first_point > 2)) { graph_fill_polygon(&skeleton_points[first_point], i - first_point, &bone_shade, 127, buffer, img); ctr++; } first_point = -1; } } vect2_copy(&previous, &current); } /** optionally show the keypoints on the skeleton */ if (show_keypoints != 0) { for (i = 0; i < SKELETON_POINTS; i++) { if (keypoints[i].x != 9999) { n_vect2 negative_x, positive_x, negative_y, positive_y; n_rgba32 green = {0, 255, 0, 0}; vect2_copy(&negative_x, &keypoints[i]); vect2_copy(&positive_x, &keypoints[i]); vect2_copy(&negative_y, &keypoints[i]); vect2_copy(&positive_y, &keypoints[i]); negative_x.x -= 10; negative_y.y -= 10; positive_x.x += 10; positive_y.y += 10; graph_line(buffer, img, &negative_x, &positive_x, &green, 1); graph_line(buffer, img, &negative_y, &positive_y, &green, 1); } } } } #ifdef VASCULAR_DRAWING_READY /** * @brief body_point_relative_to_skeleton * @param keypoints Key points on the skeleton * @param start_keypoint_index Index of the start skeleton keypoint * @param end_keypoint_index Index of the end skeleton keypoint * @param distance_along_axis_percent Distance of the point along the axis between the start and end skeleton keypoints * @param distance_from_axis_percent Distance perpendicular to the axis as a percentage of the axis length * @param x Returned x coordinate * @param y Returned y coordinate */ void point_relative_to_skeleton(n_int * keypoints, n_int start_keypoint_index, n_int end_keypoint_index, n_int distance_along_axis_percent, n_int distance_from_axis_percent, n_vect2 * pt) { /** length of the axis */ n_int dx = keypoints[end_keypoint_index*2] - keypoints[start_keypoint_index*2]; n_int dy = keypoints[end_keypoint_index*2+1] - keypoints[start_keypoint_index*2+1]; /** point position on the axis */ n_int axis_x = keypoints[start_keypoint_index*2] + (dx * distance_along_axis_percent / 100); n_int axis_y = keypoints[start_keypoint_index*2+1] + (dy * distance_along_axis_percent / 100); /** point position */ pt->x = axis_x + (dy * distance_from_axis_percent / 100); pt->y = axis_y + (dx * distance_from_axis_percent / 100); } #endif const n_int no_of_vascular_diagram_points = 40; const n_int vascular_diagram_fields = 10; const n_int vascular_diagram_points[] = { -1, SKELETON_NECK, SKELETON_LUMBAR, 0, 0, SKELETON_NECK, SKELETON_LUMBAR, 90, 0, 2, /**< 0 */ /** left arm */ 0, SKELETON_NECK, SKELETON_LUMBAR, 0, 0, SKELETON_NECK, SKELETON_LEFT_SHOULDER, 100, 0, 12, /**< 1 */ 1, SKELETON_LEFT_SHOULDER, SKELETON_LEFT_ELBOW, 0, 0, SKELETON_LEFT_SHOULDER, SKELETON_LEFT_ELBOW, 100, 0, 12, /**< 2 */ 2, SKELETON_LEFT_ELBOW, SKELETON_LEFT_WRIST, 0, 0, SKELETON_LEFT_ELBOW, SKELETON_LEFT_WRIST, 100, 3, 19, /**< 3 */ 2, SKELETON_LEFT_ELBOW, SKELETON_LEFT_WRIST, 0, 0, SKELETON_LEFT_ELBOW, SKELETON_LEFT_WRIST, 100, -3, 20, /**< 4 */ /** right arm */ 0, SKELETON_NECK, SKELETON_LUMBAR, 0, 0, SKELETON_NECK, SKELETON_RIGHT_SHOULDER, 10, 0, 8, /**< 5 */ 5, SKELETON_NECK, SKELETON_RIGHT_SHOULDER, 10, 0, SKELETON_NECK, SKELETON_RIGHT_SHOULDER, 100, 0, 9, /**< 6 */ 6, SKELETON_RIGHT_SHOULDER, SKELETON_RIGHT_ELBOW, 0, 0, SKELETON_RIGHT_SHOULDER, SKELETON_RIGHT_ELBOW, 100, 0, 9, /**< 7 */ 7, SKELETON_RIGHT_ELBOW, SKELETON_RIGHT_WRIST, 0, 0, SKELETON_RIGHT_ELBOW, SKELETON_RIGHT_WRIST, 100, -3, 14, /**< 8 */ 7, SKELETON_RIGHT_ELBOW, SKELETON_RIGHT_WRIST, 0, 0, SKELETON_RIGHT_ELBOW, SKELETON_RIGHT_WRIST, 100, 3, 13, /**< 9 */ /** abdomen */ 0, SKELETON_NECK, SKELETON_LUMBAR, 90, 0, SKELETON_NECK, SKELETON_LUMBAR, 95, 20, 21, /**< 10 */ 10, SKELETON_NECK, SKELETON_LUMBAR, 90, 0, SKELETON_LUMBAR, SKELETON_PELVIS, 50, 0, 3, /**< 11 */ 11, SKELETON_LUMBAR, SKELETON_PELVIS, 50, 0, SKELETON_LUMBAR, SKELETON_PELVIS, 60, 40, 22, /**< 12 */ 11, SKELETON_LUMBAR, SKELETON_PELVIS, 50, 0, SKELETON_LUMBAR, SKELETON_PELVIS, 60, -40, 22, /**< 13 */ 11, SKELETON_LUMBAR, SKELETON_PELVIS, 50, 0, SKELETON_LUMBAR, SKELETON_PELVIS, 80, 40, 23, /**< 14 */ 11, SKELETON_LUMBAR, SKELETON_PELVIS, 50, 0, SKELETON_LUMBAR, SKELETON_PELVIS, 90, 0, 4, /**< 15 */ 15, SKELETON_LUMBAR, SKELETON_PELVIS, 90, 0, SKELETON_LUMBAR, SKELETON_PELVIS, 100, 30, 24, /**< 16 */ 15, SKELETON_LUMBAR, SKELETON_PELVIS, 90, 0, SKELETON_LUMBAR, SKELETON_PELVIS, 150, 0, 4, /**< 17 */ /** left leg */ 17, SKELETON_LUMBAR, SKELETON_PELVIS, 150, 0, SKELETON_PELVIS, SKELETON_LEFT_HIP, 100, 0, 5, /**< 18 */ 18, SKELETON_LEFT_HIP, SKELETON_LEFT_KNEE, 0, 0, SKELETON_LEFT_HIP, SKELETON_LEFT_KNEE, 20, 12, 5, /**< 19 */ 19, SKELETON_LEFT_HIP, SKELETON_LEFT_KNEE, 20, 12, SKELETON_LEFT_HIP, SKELETON_LEFT_KNEE, 90, 12, 25, /**< 20 */ 19, SKELETON_LEFT_HIP, SKELETON_LEFT_KNEE, 20, 12, SKELETON_LEFT_HIP, SKELETON_LEFT_KNEE, 100, 5, 6, /**< 21 */ 21, SKELETON_LEFT_HIP, SKELETON_LEFT_KNEE, 100, 5, SKELETON_LEFT_KNEE, SKELETON_LEFT_ANKLE, 40, 5, 7, /**< 22 */ 21, SKELETON_LEFT_HIP, SKELETON_LEFT_KNEE, 100, 5, SKELETON_LEFT_KNEE, SKELETON_LEFT_ANKLE, 60, 15, 26, /**< 23 */ 22, SKELETON_LEFT_KNEE, SKELETON_LEFT_ANKLE, 40, 5, SKELETON_LEFT_KNEE, SKELETON_LEFT_ANKLE, 95, 0, 27, /**< 24 */ 22, SKELETON_LEFT_KNEE, SKELETON_LEFT_ANKLE, 40, 5, SKELETON_LEFT_KNEE, SKELETON_LEFT_ANKLE, 95, 10, 28, /**< 25 */ /** right leg */ 17, SKELETON_LUMBAR, SKELETON_PELVIS, 150, 0, SKELETON_PELVIS, SKELETON_RIGHT_HIP, 100, 0, 5, /**< 26 */ 26, SKELETON_RIGHT_HIP, SKELETON_RIGHT_KNEE, 0, 0, SKELETON_RIGHT_HIP, SKELETON_RIGHT_KNEE, 20, -12, 5, /**< 27 */ 27, SKELETON_RIGHT_HIP, SKELETON_RIGHT_KNEE, 20, -12, SKELETON_RIGHT_HIP, SKELETON_RIGHT_KNEE, 90, -12, 25, /**< 28 */ 27, SKELETON_RIGHT_HIP, SKELETON_RIGHT_KNEE, 20, -12, SKELETON_RIGHT_HIP, SKELETON_RIGHT_KNEE, 100, -5, 6, /**< 29 */ 29, SKELETON_RIGHT_HIP, SKELETON_RIGHT_KNEE, 100, -5, SKELETON_RIGHT_KNEE, SKELETON_RIGHT_ANKLE, 40, -5, 7, /**< 30 */ 29, SKELETON_RIGHT_HIP, SKELETON_RIGHT_KNEE, 100, -5, SKELETON_RIGHT_KNEE, SKELETON_RIGHT_ANKLE, 60, -15, 26, /**< 31 */ 30, SKELETON_RIGHT_KNEE, SKELETON_RIGHT_ANKLE, 40, -5, SKELETON_RIGHT_KNEE, SKELETON_RIGHT_ANKLE, 95, 0, 27, /**< 32 */ 30, SKELETON_RIGHT_KNEE, SKELETON_RIGHT_ANKLE, 40, -5, SKELETON_RIGHT_KNEE, SKELETON_RIGHT_ANKLE, 95, -10, 28, /**< 33 */ /** right neck */ 5, SKELETON_NECK, SKELETON_RIGHT_SHOULDER, 10, 0, SKELETON_NECK, SKELETON_RIGHT_SHOULDER, -15, 80, 10, /**< 34 */ 34, SKELETON_NECK, SKELETON_RIGHT_SHOULDER, -15, 80, SKELETON_NECK, SKELETON_RIGHT_SHOULDER, -25, 150, 15, /**< 35 */ 34, SKELETON_NECK, SKELETON_RIGHT_SHOULDER, -15, 80, SKELETON_NECK, SKELETON_RIGHT_SHOULDER, -45, 150, 16, /**< 36 */ /** left neck */ -1, SKELETON_NECK, SKELETON_LEFT_SHOULDER, 20, 0, SKELETON_NECK, SKELETON_LEFT_SHOULDER, 15, -80, 11, /**< 37 */ 37, SKELETON_NECK, SKELETON_LEFT_SHOULDER, 16, -80, SKELETON_NECK, SKELETON_LEFT_SHOULDER, 10, -130, 17, /**< 38 */ 37, SKELETON_NECK, SKELETON_LEFT_SHOULDER, 16, -80, SKELETON_NECK, SKELETON_LEFT_SHOULDER, 30, -130, 18, /**< 39 */ }; /** * @brief Draws a representation of the vascular system * @param buffer Image buffer (3 bytes per pixel) * @param img Image dimesions * @param tp Top coordinate of the bounding box * @param bp Bottom coordinate of the bounding box * @param thickness Thickness of the outline in pixels * @param clear Non zero if the image should be cleared before drawing * @param shoulder_angle Angle of the shoulders in degrees * @param elbow_angle Angle of the elbows in degrees * @param wrist_angle Angle of the wrists in degrees * @param hip_angle Angle of the hips in degrees * @param knee_angle Angle of the knees in degrees * @param show_skeleton_keypoints If non-zero show key points on the skeleton */ void vascular_draw(n_genetics * genetics, n_byte * buffer, n_vect2* img, n_vect2 *tp, n_vect2 * bp, n_byte thickness, n_byte clear, n_int shoulder_angle, n_int elbow_angle, n_int wrist_angle, n_int hip_angle, n_int knee_angle, n_byte show_skeleton_keypoints) { n_vect2 keypoints[SKELETON_POINTS]; #ifdef VASCULAR_DRAWING_READY n_int i,vascular_model_index,previous_index; n_uint start_thickness=4, end_thickness=4; n_vect2 pt[3]; n_rgba32 blood = {255, 0, 0, 0}; #endif /** clear the image if necessary */ if (clear != 0) { n_rgba32 white = {255, 255, 255, 0}; graph_erase(buffer, img, &white); } /** draw the skeleton */ skeleton_draw(genetics, buffer, img, tp, bp, thickness, keypoints, shoulder_angle, elbow_angle, wrist_angle, hip_angle, knee_angle, show_skeleton_keypoints); #ifdef VASCULAR_DRAWING_READY for (i = 0; i < no_of_vascular_diagram_points; i++) { /** index of the previous segment */ previous_index = vascular_diagram_points[i*vascular_diagram_fields]; pt[0].x = -1; if (previous_index > -1) { /** end point of the vessel */ point_relative_to_skeleton((n_int *)keypoints, vascular_diagram_points[previous_index*vascular_diagram_fields+5], vascular_diagram_points[previous_index*vascular_diagram_fields+6], vascular_diagram_points[previous_index*vascular_diagram_fields+7], vascular_diagram_points[previous_index*vascular_diagram_fields+8], &pt[0]); } /** beginning point of the vessel */ point_relative_to_skeleton((n_int *)keypoints, vascular_diagram_points[i*vascular_diagram_fields+1], vascular_diagram_points[i*vascular_diagram_fields+2], vascular_diagram_points[i*vascular_diagram_fields+3], vascular_diagram_points[i*vascular_diagram_fields+4], &pt[1]); /** end point of the vessel */ point_relative_to_skeleton((n_int *)keypoints, vascular_diagram_points[i*vascular_diagram_fields+5], vascular_diagram_points[i*vascular_diagram_fields+6], vascular_diagram_points[i*vascular_diagram_fields+7], vascular_diagram_points[i*vascular_diagram_fields+8], &pt[2]); /** compartment index within the vascular simulation */ vascular_model_index = vascular_diagram_points[i*vascular_diagram_fields+9]; if (pt[0].x != -1) { /* draw a curve */ graph_curve(buffer, img, &pt[0], &pt[1], &pt[2], &blood, 10, start_thickness, end_thickness); } else { /* draw a line */ graph_line(buffer, img, &pt[1], &pt[2], &blood, end_thickness); } } #endif } <|start_filename|>entity/drives.c<|end_filename|> /**************************************************************** drives.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /*! \file drives.c * \brief Functions related to biological drives */ #include "entity.h" #include "entity_internal.h" /** Mate seeking */ #define GENE_MATE_SEEK(gene) GENE_VAL_REG(gene, 8, 9, 14, 2) /** * @brief Update the hunger drive * @param local Pointer to the ape */ void drives_hunger(simulated_being * local) { /** if the being is hungry and its hunger drive is not already saturated */ if (being_energy_less_than(local, BEING_HUNGRY)) { /** increase hunger drive */ being_inc_drive(local, DRIVE_HUNGER); /** decrease sex drive (hunger subsumes sex) */ being_dec_drive(local, DRIVE_SEX); } else { /** otherwise decrease hunger drive */ being_dec_drive(local, DRIVE_HUNGER); } } void drives_sociability_loop_no_sim(simulated_being * other, void * data) { drives_sociability_data * dsd = (drives_sociability_data *)data; n_int distance_squared; n_vect2 difference_vector; /* this needs to be checked against simulation near sight and sound values */ const n_int apespace_span = 2; /*(10) >> APE_TO_MAP_BIT_RATIO; too low */ being_delta(dsd->being, other, &difference_vector); /* los should not be used here, it's too expensive */ distance_squared = vect2_dot(&difference_vector, &difference_vector, 1, 1); if (distance_squared < (apespace_span * apespace_span)) { dsd->beings_in_vacinity++; } } /** * @brief Social drive governs how likely the being is to interact with others. * This affects behaviors such as grooming, chatting and mating * @param local Pointer to the ape * @param group Pointer to the simulated_group */ static void drives_sociability( simulated_being * local, simulated_group * group) { drives_sociability_data dsd; dsd.beings_in_vacinity = 0; dsd.being = local; loop_being_no_sim(group->beings, group->num, drives_sociability_loop_no_sim, &dsd); being_crowding_cycle(local, dsd.beings_in_vacinity); } /** * @brief Updates the sex drive * @param local Pointer to the ape * @param awake whether the ape is awake */ static void drives_sex( simulated_being * local, n_int awake) { n_int i,max; simulated_isocial * local_social_graph = being_social(local); n_int age_in_days = AGE_IN_DAYS(local); #ifdef EPISODIC_ON simulated_iepisodic * local_episodic = being_episodic(local); #endif /** is the being mature */ if (age_in_days > AGE_OF_MATURITY) { /** is the being awake and its sex drive not saturated */ if (awake) { /** increase the sex drive */ being_inc_drive(local, DRIVE_SEX); /** if sex drive is above a mate seeking threshold and the being has no current goal */ if ((being_drive(local, DRIVE_SEX) > THRESHOLD_SEEK_MATE) && being_check_goal(local, GOAL_NONE)) { /** either search for a preferred mate, or mate randomly */ if (GENE_MATE_SEEK(being_genetics(local))&1) { /** look for a mate */ #ifdef EPISODIC_ON if (!local_episodic) return; /** does the being remember mating in the recent past */ for(i=0; i<EPISODIC_SIZE; i++) { if (local_episodic[i].event == EVENT_MATE) { /** not someone else's mate */ if (being_name_comparison(local, local_episodic[i].first_name[BEING_MEETER], local_episodic[i].family_name[BEING_MEETER])) { /** set a goal to seek the remembered mate */ being_set_goal_mate(local, local_episodic[i].first_name[BEING_MET], local_episodic[i].family_name[BEING_MET]); /** remember seeking a mate */ episodic_store_memory( local, EVENT_SEEK_MATE, AFFECT_SEEK_MATE, being_gender_name(local), being_family_name(local), local->delta.goal[1], local->delta.goal[2],0); break; } } } #endif /** if the being is not seeking a remembered mate then examine the social graph for attractive prospects */ if (being_check_goal(local, GOAL_MATE) == 0) { max = 0; if (!local_social_graph) return; for(i=1; i<SOCIAL_SIZE_BEINGS; i++) { if (!SOCIAL_GRAPH_ENTRY_EMPTY(local_social_graph,i)) { if ((local_social_graph[i].attraction) > max) { /** who are we most attracted to? */ max=local_social_graph[i].attraction; being_set_goal_mate(local, local_social_graph[i].first_name[BEING_MET], local_social_graph[i].family_name[BEING_MET]); } } } /** if an attractive mate was found then remember this event */ if (being_check_goal(local, GOAL_MATE)) { episodic_store_memory( local, EVENT_SEEK_MATE, AFFECT_SEEK_MATE, being_gender_name(local), being_family_name(local), local->delta.goal[1], local->delta.goal[2],0); } } } } /** during gestation reduce the sex drive */ if (being_pregnant(local) != 0) { if (being_drive(local, DRIVE_SEX) >= GESTATION_SEX_DRIVE_DECREMENT) { being_dec_drive(local, DRIVE_SEX); } } } else { /** while sleeping reduce sex drive */ being_dec_drive(local, DRIVE_SEX); } /** if sex drive falls below the mate seeking threshold and the being is seeking a mate, then stop seeking a mate */ if ((being_drive(local, DRIVE_SEX) < THRESHOLD_SEEK_MATE) && being_check_goal(local, GOAL_MATE)) { being_set_goal_none(local); } } } /** * @brief Updates the fatigue drive. This doesn't do much, but is * accessible to the braincode. * @param local Pointer to the ape */ void drives_fatigue( simulated_being * local) { /** if the being is moving fast enough then increase the fatigue drive */ if (being_speed(local) > FATIGUE_SPEED_THRESHOLD) { being_inc_drive(local, DRIVE_FATIGUE); /** Add extra fatigue when swimming */ if (being_state(local) & BEING_STATE_SWIMMING) { being_inc_drive(local, DRIVE_FATIGUE); } /** As fatigue increases, sex drive decreases */ being_dec_drive(local, DRIVE_SEX); } else { /** When resting fatigue drive decreases */ being_dec_drive(local, DRIVE_FATIGUE); } } void drives_cycle(simulated_group * group, simulated_being * local_being, void * data) { drives_hunger(local_being); drives_sociability(local_being, group); drives_sex(local_being, local_being->delta.awake); drives_fatigue(local_being); } <|start_filename|>toolkit/shared.h<|end_filename|> /**************************************************************** shared.h ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #ifndef SIMULATEDAPE_SHARED_H #define SIMULATEDAPE_SHARED_H #include "toolkit.h" typedef enum { SHARED_CYCLE_OK = 0, SHARED_CYCLE_QUIT, SHARED_CYCLE_DEBUG_OUTPUT, SHARED_CYCLE_NEW_APES } shared_cycle_state; enum window_information { TERRAIN_WINDOW_WIDTH = (4096), TERRAIN_WINDOW_HEIGHT = (3072), TERRAIN_WINDOW_AREA = (TERRAIN_WINDOW_WIDTH * TERRAIN_WINDOW_HEIGHT), CONTROL_WINDOW_WIDTH = (2048), CONTROL_WINDOW_HEIGHT = (2048), CONTROL_WINDOW_AREA = (CONTROL_WINDOW_WIDTH * CONTROL_WINDOW_HEIGHT) }; #define NUM_VIEW (0) #define NUM_TERRAIN (1) #define NUM_CONTROL (2) enum { NA_MENU_PAUSE = 0, NA_MENU_WEATHER, NA_MENU_BRAIN, NA_MENU_BRAINCODE, NA_MENU_TIDEDAYLIGHT, NA_MENU_TERRITORY, NA_MENU_PREVIOUS_APE, NA_MENU_NEXT_APE, NA_MENU_CLEAR_ERRORS, NA_MENU_FLOOD, NA_MENU_HEALTHY_CARRIER, NA_MENU_FOLLOW, NA_MENU_SOCIAL_WEB }; void shared_color_8_bit_to_48_bit(n_byte2 * fit); void shared_dimensions(n_int * dimensions); n_int shared_init(n_int view, n_uint random); void shared_close(void); n_int shared_menu(n_int menuValue); n_uint shared_max_fps(void); void shared_rotate(n_double num, n_int wwind); void shared_delta(n_double delta_x, n_double delta_y, n_int wwind); void shared_zoom(n_double num, n_int wwind); void shared_keyReceived(n_int value, n_int localIdentification); void shared_keyUp(void); void shared_mouseOption(n_byte option); void shared_mouseReceived(n_double valX, n_double valY, n_int localIdentification); void shared_mouseUp(void); void shared_about(void); void shared_draw(n_byte * outputBuffer, n_int fIdentification, n_int dim_x, n_int dim_y, n_byte size_changed); void shared_draw_ios(n_byte4 * outputBuffer, n_int dim_x, n_int dim_y); shared_cycle_state shared_cycle(n_uint ticks, n_int localIdentification); shared_cycle_state shared_cycle_ios(n_uint ticks); n_byte * shared_legacy_draw(n_byte fIdentification, n_int dim_x, n_int dim_y); n_int shared_new(n_uint seed); n_int shared_new_agents(n_uint seed); n_byte shared_openFileName(n_constant_string cStringFileName, n_int isScript); void shared_saveFileName(n_constant_string cStringFileName); void shared_script_debug_handle(n_constant_string cStringFileName); #ifndef _WIN32 n_int sim_thread_console_quit(void); #endif #endif /* SIMULATEDAPE_SHARED_H */ <|start_filename|>entity/entity_internal.h<|end_filename|> /**************************************************************** entity_internal.h ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #ifndef SIMULATEDAPE_ENTITY_INTERNAL_H #define SIMULATEDAPE_ENTITY_INTERNAL_H #define CONSUME_E(being, max_energy, food) /* offsets applied to land operator values */ #define OFFSET_GRASS 40 #define OFFSET_BUSH 14 #define IMMUNE_FIT 5 #define MIN_ANTIBODIES 16 #define MIN_ANTIGENS 8 #define PATHOGEN_TRANSMISSION_PROB 1000 #define PATHOGEN_ENVIRONMENT_PROB 100 #define PATHOGEN_MUTATION_PROB 100 #define ANTIBODY_DEPLETION_PROB 100 #define ANTIBODY_GENERATION_PROB(bei) (being_energy(bei)) enum featureset_members { FEATURESET_PIGMENTATION, FEATURESET_HAIR, FEATURESET_HEIGHT, FEATURESET_FAT, FEATURESET_EYE_SHAPE, FEATURESET_EYE_COLOR, FEATURESET_EYE_SEPARATION, FEATURESET_NOSE_SHAPE, FEATURESET_EAR_SHAPE, FEATURESET_EYEBROW_SHAPE, FEATURESET_MOUTH_SHAPE, FEATURESET_TERRITORY, FEATURESET_FEATURE_SET, FEATURESET_SIZE }; /* honor multiplier used to calculate the probability of a female mating */ #define MATING_PROB 12 /* Note that the number here are reduced from realistic values into a smaller 30 day maturity range */ /* maximum distance over which a parasite can hob from one being to another */ #define PARASITE_HOP_MAX_DISTANCE METRES_TO_APESPACE(2) /* how much energy does a parasite cost the ape per time step */ #define PARASITE_ENERGY_COST 1 /* probability of acquiring a parasite from the environment */ #define PARASITE_ENVIRONMENT 5000 /* multiplying factor used to increase the probability if already carrying parasites */ #define PARASITE_BREED 10 /* maximum separation between grooming apes */ #define GROOMING_MAX_SEPARATION METRES_TO_APESPACE(2) /* apes must be moving slowly to be able to groom */ #define MAX_SPEED_WHILST_GROOMING 30 /* the probability of social grooming */ #define GROOMING_PROB 10000 /* multiplier used to increase the probability of grooming a higher status individual */ #define GROOMING_PROB_HONOR 10 /* number of parasites removed at each grooming session */ #define PARASITES_REMOVED 2 /* speed of running away */ #define SQUABBLE_FLEE_SPEED 20 /* amount of energy consumed during a show of force */ #define SQUABBLE_ENERGY_SHOWFORCE 200 /* amount of energy consumed during an attack */ #define SQUABBLE_ENERGY_ATTACK 500 /* amount of energy lost if hit by a rock */ #define SQUABBLE_ENERGY_ROCK_HURL 100 /* amount of energy lost if hit by a branch */ #define SQUABBLE_ENERGY_BRANCH_WHACK 50 /* friend or foe adjustment made within the social graph after a squabble */ #define SQUABBLE_DISRESPECT 20 /* honor value adjustment after a squabble */ #define SQUABBLE_HONOR_ADJUST 10 /* distance beyond which a squabble only results in a show of force */ #define SQUABBLE_SHOW_FORCE_DISTANCE 10 /* the minimum amount of genetic variation (bases) below which individuals are considered to be related */ #define MINIMUM_GENETIC_VARIATION 32 /* Affect values are composed from primitives */ enum mutation_type { MUTATION_MATERNAL = 0, MUTATION_PATERNAL, MUTATION_MATERNAL_DUPLICATE, MUTATION_PATERNAL_DUPLICATE }; #define DIPLOID(parent1,parent2) ((parent1)|((parent2)<<16)) #define CHROMOSOME_FROM_MOTHER(ch) (((ch)>>16)&65535) #define CHROMOSOME_FROM_FATHER(ch) ((ch)&65535) /* probability of mutation */ #define MUTATION_CROSSOVER_PROB 500 #define MUTATION_DELETION_PROB 200 #define MUTATION_TRANSPOSE_PROB 200 enum posture_type { POSTURE_CROUCHING = 100, POSTURE_UPRIGHT = 200 }; enum individual_action_type { ACTION_PICKUP = 0, ACTION_DRAG, ACTION_DROP, ACTION_SWAP_HANDS, ACTION_BRANDISH, ACTION_CHEW, ACTION_BASH_OBJECTS, ACTION_JAB, INDIVIDUAL_ACTIONS }; enum social_action_type { ACTION_GIVE = 0, ACTION_BASH, ACTION_HUG, ACTION_PROD, ACTION_POINT, ACTION_TICKLE, ACTION_SMILE, ACTION_GLOWER, ACTION_PAT, SOCIAL_ACTIONS }; n_int food_absorption(simulated_being * local, n_int max_energy, n_byte food_type); void food_values(n_int loc_x, n_int loc_y, n_int *grass, n_int *trees, n_int *bush); n_int genetics_compare(n_genetics * genetics_a, n_genetics * genetics_b); void genetics_zero(n_genetics * genetics_a); void social_action(simulated_being * meeter_being, simulated_being * met_being, n_byte action); n_int get_simulated_isocial(simulated_being * meeter_being, simulated_being * met_being); n_int episodic_met_being_celebrity( simulated_being * meeter_being, simulated_being * met_being); void episodic_store_memory( simulated_being * local, being_episodic_event_type event, AFFECT_TYPE affect, n_byte2 name1, n_byte2 family1, n_byte2 name2, n_byte2 family2, n_byte2 arg); void episodic_interaction( simulated_being * local, simulated_being * other, being_episodic_event_type event, AFFECT_TYPE affect, n_byte2 arg); n_byte episodic_intention( simulated_being * local, n_int episode_index, n_byte2 mins_ahead, n_byte args); n_byte episodic_anecdote( simulated_being * local, simulated_being * other); void being_init_braincode(simulated_being * local, simulated_being * other, n_byte friend_foe, n_byte internal); n_byte get_braincode_instruction(simulated_being * local_being); void being_ingest_pathogen(simulated_being * local, n_byte food_type); n_int being_posture_under(simulated_being * value, enum posture_type post); void being_honor_inc_dec(simulated_being * inc, simulated_being * dec); void being_honor_swap(simulated_being * victor, simulated_being * vanquished); n_int being_honor_compare(simulated_being * first, simulated_being * second); void being_unpack_family(n_byte2 name, n_byte * values); void being_remove_parasites(simulated_being * value, n_int number_of_parasites); enum inventory_type being_carried(simulated_being * value, enum BODY_INVENTORY_TYPES location); void being_drop(simulated_being * value, enum BODY_INVENTORY_TYPES location); void being_take(simulated_being * value, enum BODY_INVENTORY_TYPES location, enum inventory_type object); void being_remains(simulated_group * group, simulated_being * dead); void brain_cycle(n_byte * local, n_byte2 * constants); #endif /* SIMULATEDAPE_ENTITY_INTERNAL_H */ <|start_filename|>script/parse.c<|end_filename|> /**************************************************************** parse.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /*! \file parse.c * \brief This parses ApeScript and produces the ApeScript byte-code. */ #include "../toolkit/toolkit.h" #include "script.h" #if defined(ROUGH_CODE_OUT) || defined(COMMAND_LINE_DEBUG) #include <stdio.h> #endif #define SYNTAX_NUM 19 #define SYNTAX_WIDTH 4 static const n_byte syntax_codes[SYNTAX_NUM][SYNTAX_WIDTH]= { "-", "+", "*", "&", "^", "|", ">", "<", "==", "!=", "&&", "||", "/", "%", ">>", "<<", "<=", ">=", "=" }; static n_int variable_num; static n_int number_num; static n_int quote_up; #ifdef SCRIPT_DEBUG static n_int tab_step = 0; static variable_string * local_var_codes; n_file * file_debug = 0L; static n_int single_entry = 1; static void * writable_selection; n_file * scdebug_file_ready(void) { return io_file_ready(single_entry, file_debug); } void scdebug_file_cleanup(void) { io_file_cleanup(&single_entry, &file_debug); } void scdebug_writeon(void * ptr) { writable_selection = ptr; io_file_writeon(&single_entry, &file_debug, 1); } void scdebug_writeoff(void * ptr) { if (ptr != writable_selection) return; io_file_writeoff(&single_entry, file_debug); } void scdebug_string(void * ptr,n_constant_string string) { if (ptr != writable_selection) return; io_file_string(single_entry, file_debug, string); } n_string scdebug_variable(n_int variable) { n_string return_value = 0L; if((variable < VARIABLE_MAX) #ifndef COMMAND_LINE_DEBUG && (file_debug != 0L) #endif ) { return_value = (n_string) local_var_codes[variable]; } return return_value; } void scdebug_int(void * ptr, n_int number) { if (single_entry == 0) return; if (ptr != writable_selection) return; #ifndef COMMAND_LINE_DEBUG if(file_debug != 0L) { io_writenumber(file_debug, number, 1, 0); } #else printf("%d",(int)number); #endif } void scdebug_newline(void * ptr) { if (single_entry == 0) return; if (ptr != writable_selection) return; #ifndef COMMAND_LINE_DEBUG if(file_debug != 0L) #endif { n_int loop = 0; #ifndef COMMAND_LINE_DEBUG io_write(file_debug, "", 1); #else printf("\n"); #endif if(tab_step > 0) { while(loop<tab_step) { #ifndef COMMAND_LINE_DEBUG io_write(file_debug," ",0); #else printf(" "); #endif loop++; } } } } void scdebug_tabstep(void * ptr, n_int steps) { if (ptr != writable_selection) return; #ifndef COMMAND_LINE_DEBUG if(file_debug != 0L) #endif { tab_step += steps; } } #endif static n_int parse_number_add(n_interpret * interpret, n_int out_value) { n_int loop = 0; /* is this number already stored? */ while(loop < number_num) { if(interpret->number_buffer[loop] == out_value) return loop; loop++; } /* if not, add it to the number store */ interpret->number_buffer[loop] = out_value; if(number_num < NUMBER_MAX) { number_num++; } else { return APESCRIPT_ERROR(0L, AE_MAXIMUM_NUMBERS_REACHED); } return loop; } /* outputs the number of bytes to advance in the interpret stream */ static n_int parse_number(n_interpret * interpret, const n_byte * number) { n_int out_value = 0; n_int point_counter = 0; /* read out the number from the interpret stream */ do { n_byte temp = number[point_counter++]; if((!ASCII_NUMBER(temp)) && (temp != 0)) { return APESCRIPT_ERROR(0L, AE_NUMBER_EXPECTED); /* this error should never occur */ } out_value = (out_value * 10) + (temp - '0'); } while((number[point_counter]!=0) && (out_value>-1)); if((out_value < 0) || (out_value > 0x7fffffff)) { return APESCRIPT_ERROR(0L, AE_NUMBER_OUT_OF_RANGE); } return parse_number_add(interpret, out_value); } static n_int parse_quoted_string(n_interpret * interpret, n_constant_string string) { return parse_number_add(interpret, (n_int)math_hash_fnv1(string)); } static n_byte parse_character(n_byte temp) { if(ASCII_QUOTE(temp)) { quote_up ^= 1; return APESCRIPT_STRING; } if (quote_up) { return APESCRIPT_STRING; } if(ASCII_BRACES(temp) || ASCII_BRACKET(temp)) { return temp; } if((ASCII_EQUAL(temp) || ASCII_LOGICAL(temp))||(ASCII_ARITHMETIC(temp) || ASCII_DIRECTIONAL(temp))) { return APESCRIPT_OPERATOR; } if(ASCII_NUMBER(temp)) { return APESCRIPT_NUMBER; } if(ASCII_TEXT(temp)) { return APESCRIPT_TEXT; } if(ASCII_SEMICOLON(temp)) { return APESCRIPT_SEMICOLON; } return APESCRIPT_FAILURE; } static n_int parse_write_code(n_interpret * final_prog, n_byte value, n_byte code) { #ifdef ROUGH_CODE_OUT printf("%c ",value); #endif if (io_file_write(final_prog->binary_code, value) == -1) { return APESCRIPT_ERROR(0L, AE_MAXIMUM_SCRIPT_SIZE_REACHED); } if (CODE_VALUE_REQUIRED(value)) { if(io_file_write(final_prog->binary_code, code) == -1) { return APESCRIPT_ERROR(0L, AE_MAXIMUM_SCRIPT_SIZE_REACHED); } #ifdef ROUGH_CODE_OUT printf("%d ",code); #endif } #ifdef ROUGH_CODE_OUT if (value == APESCRIPT_SEMICOLON || value == APESCRIPT_OPEN_BRACE || value == APESCRIPT_CLOSE_BRACE) { printf("\n"); } #endif return 0; } static n_int parse_string(const n_byte * test, const n_byte * compare, n_int number) { n_int loop = 0; while(loop<number) { if(test[loop] != compare[loop]) return -1; loop++; } return 1; } static n_int parse_buffer(n_interpret * final_prog, n_byte previous, const n_byte * buffer) { variable_string *variable_codes = final_prog->variable_strings; n_int result = -1; n_int loop = 0; switch(previous) { case (APESCRIPT_NUMBER): result = parse_number(final_prog, buffer); /* this loads the number into the number buffer */ if(result == -1) { return -1; } if(parse_write_code(final_prog, previous, (n_byte)result) == -1) /* this writes the number allocation code */ { return -1; } break; case (APESCRIPT_STRING): result = parse_quoted_string(final_prog, (n_constant_string)buffer); /* this loads the number into the number buffer */ if(result == -1) { return -1; } if(parse_write_code(final_prog, APESCRIPT_NUMBER, (n_byte)result) == -1) /* this writes the number allocation code */ { return -1; } break; case (APESCRIPT_TEXT): while((loop < variable_num) && (result == -1)) { if(parse_string(variable_codes[loop], buffer, VARIABLE_WIDTH) == 1) { result = loop; } loop++; } if(result == -1) { if(variable_num < VARIABLE_MAX) { n_int loop2 = 0; while(loop2 < (VARIABLE_WIDTH)) { variable_codes[variable_num][loop2] = buffer[loop2]; loop2++; } variable_num++; } else { return APESCRIPT_ERROR(0L, AE_MAXIMUM_VARIABLES_REACHED); } result = loop; } if(parse_write_code(final_prog, previous, (n_byte)result) == -1) { return -1; } break; case (APESCRIPT_OPERATOR): while((loop < SYNTAX_NUM) && (result == -1)) { if(parse_string(syntax_codes[loop],buffer,SYNTAX_WIDTH) == 1) { result = loop; } loop++; } if(result == -1) /* no error reported up until now */ { return APESCRIPT_ERROR(0L, AE_UNKNOWN_SYNTAX_PARSER_BUFFER); } if(parse_write_code(final_prog, previous, (n_byte)result) == -1) { return -1; } break; default: { n_byte value; while((value = buffer[loop++]) != 0) { if(parse_write_code(final_prog, value, 0) == -1) { return -1; } } } break; } return 0; } /** Turns an input file into an interpret-able pointer. @param input The file pointer containing the ApeScript text data. @param main_entry The variable defined as main. In the case of this implementation of ApeScript, being. @param variables The pointer to the variable string used for debugging to output the actual variable names. @return The interpreter pointer created from the file pointer. */ n_interpret * parse_convert(n_file * input, n_int main_entry, variable_string * variables) { n_interpret * final_prog = 0L; n_byte * local_data; n_uint end_loop; n_uint loop = 0; n_int * local_number; n_byte buffer[ VARIABLE_WIDTH ]; n_int buffer_size = 0; n_byte previous = 0; /* remove the white space from the input file */ io_whitespace(input); /* perform the initial allocations */ if((final_prog = memory_new(sizeof(n_interpret))) == 0L) { return 0L; } if((final_prog->binary_code = io_file_new())== 0L) { memory_free((void **)&final_prog); return 0L; } if(final_prog->binary_code->data == 0L) { interpret_cleanup(&final_prog); return 0L; } /* allow for the space for the size to be written after everything else has been written/calculated */ final_prog->binary_code->location = SIZEOF_NUMBER_WRITE; final_prog->variable_strings = variables; final_prog->special_less = (VARIABLE_IF + 1); final_prog->main_entry = main_entry; local_number = final_prog->number_buffer; variable_num = main_entry + 1; number_num = 1; quote_up = 0; /* clear everything initially */ while(loop < NUMBER_MAX) { local_number[ loop++ ] = 0; } loop = 0; memory_erase(buffer, VARIABLE_WIDTH); local_data = input->data; end_loop = input->size; /* work through each character in the input file */ while(loop < end_loop) { n_byte temp = local_data[ loop++ ]; /* each character has a particular type */ n_byte convert = parse_character(temp); /* if it is a failure type i.e. not to be used, then fail */ if (convert == APESCRIPT_FAILURE) { interpret_cleanup(&final_prog); (void)APESCRIPT_ERROR(0L, AE_UNKNOWN_SYNTAX_PARSER_CONVERT); return 0L; } /* if there is a change in type, then parse the previous buffer */ if ((previous != convert) && (previous != 0)) { if(parse_buffer(final_prog, previous, buffer) == -1) { interpret_cleanup(&final_prog); return 0L; } /* clear the buffer for new characters coming in */ buffer_size = 0; memory_erase(buffer, VARIABLE_WIDTH); } /* add the character to the buffer */ buffer[buffer_size++] = temp; /* if the buffer gets to big, it's a problem */ if (buffer_size == (VARIABLE_WIDTH - 1)) { interpret_cleanup(&final_prog); (void)APESCRIPT_ERROR(0L, AE_MAXIMUM_SCRIPT_SIZE_REACHED); return 0L; } /* track the previous type */ previous = convert; } /* handle the last type case at the end of the input file */ if (parse_buffer(final_prog, previous, buffer) == -1) { interpret_cleanup(&final_prog); return 0L; } { n_byte local_numbers[SIZEOF_NUMBER_WRITE]; n_uint loop_sizeof_number; /* this is the one special case for direct writing as the original stamp size was allowed */ io_int_to_bytes(final_prog->binary_code->location,final_prog->binary_code->data); /* write the basic size header */ end_loop = number_num; loop = 1; io_int_to_bytes(number_num,local_numbers); /* write the number of numbers */ loop_sizeof_number = 0; while (loop_sizeof_number < SIZEOF_NUMBER_WRITE) { if(io_file_write(final_prog->binary_code, local_numbers[loop_sizeof_number]) == -1) { interpret_cleanup(&final_prog); return 0L; } loop_sizeof_number++; } while (loop<end_loop) { io_int_to_bytes((final_prog->number_buffer[loop]),local_numbers); /* write the numbers */ loop_sizeof_number = 0; while (loop_sizeof_number < SIZEOF_NUMBER_WRITE) { if(io_file_write(final_prog->binary_code, local_numbers[loop_sizeof_number]) == -1) { interpret_cleanup(&final_prog); return 0L; } loop_sizeof_number++; } loop++; } } #ifdef SCRIPT_DEBUG local_var_codes = variables; #endif return final_prog; } <|start_filename|>toolkit/audio.c<|end_filename|> /**************************************************************** audio.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /*! \file audio.c * \brief Handles audio output for the ApeSDK Toolkit */ #include "toolkit.h" #include <math.h> #include <stdio.h> static n_double frequency[AUDIO_FFT_MAX_BUFFER]; static n_double timedomain[AUDIO_FFT_MAX_BUFFER]; static n_double frequencyi[AUDIO_FFT_MAX_BUFFER]; static n_double timedomaini[AUDIO_FFT_MAX_BUFFER]; /* static void bsort(n_double * A, n_int *B, n_int size) { for(n_int i=0; i<size; i++) { for(n_int j=0; j<size-1; j++) { if( A[j] < A[j+1] ) { n_double temp = A[j]; n_int tempi = B[j]; A[j] = A[j+1]; B[j] = B[j+1]; A[j+1] = temp; B[j+1] = tempi; } } } } */ void audio_buffer_clear(n_audio * buffer, n_int size) { n_int loop = 0; while (loop < size) { buffer[loop++] = 0; } } void audio_buffer_double_clear(n_double * buffer, n_int size) { n_int loop = 0; while (loop < size) { buffer[loop++] = 0E+00; } } void audio_buffer_copy_to_audio(n_double * buffer_double, n_audio * buffer_audio, n_int size) { n_int loop = 0; while (loop < size) { buffer_audio[loop] = (n_audio)buffer_double[loop]; loop++; } } void audio_buffer_copy_to_double(n_audio * buffer_audio, n_double * buffer_double, n_int size) { n_int loop = 0; while (loop < size) { buffer_double[loop] = (n_double)buffer_audio[loop] ; loop++; } } void audio_buffer_copy_to_double_double(n_double * buffer_double_to, n_double * buffer_double_from, n_int size) { n_int loop = 0; while (loop < size) { buffer_double_to[loop] = buffer_double_from[loop]; loop++; } } /** * Creates a bit reversed value of a particular index value. * @param index value to be bit reversed. * @param power_sample the size in bits of the value to be reversed. * @return reversed bit value. */ static n_uint audio_reverse_bits (n_uint index, n_uint power_sample) { n_uint i = 0; n_uint rev = 0; while(i < power_sample) { rev = (rev << 1) | (index & 1); index >>= 1; i++; } return rev; } /* * Complex Fast Fourier Transform */ void audio_new_fft( n_uint NumBits, n_int InverseTransform, n_double *RealIn, n_double *ImagIn, n_double *RealOut, n_double *ImagOut ) { n_uint NumSamples = 1 << NumBits; n_uint i, j; n_uint k, n; n_uint BlockSize, BlockEnd; n_double angle_numerator = TWO_PI; n_double tr, ti; /* temp real, temp imaginary */ if ( InverseTransform ) { angle_numerator = -angle_numerator; } /* ** Do simultaneous data copy and bit-reversal ordering into outputs... */ for ( i=0; i < NumSamples; i++ ) { j = audio_reverse_bits ( i, NumBits ); RealOut[j] = RealIn[i]; ImagOut[j] = ImagIn[i]; } /* ** Do the FFT itself... */ BlockEnd = 1; for ( BlockSize = 2; BlockSize <= NumSamples; BlockSize <<= 1 ) { n_double delta_angle = angle_numerator / (double)BlockSize; n_double sm2 = sin ( -2 * delta_angle ); n_double sm1 = sin ( -delta_angle ); n_double cm2 = cos ( -2 * delta_angle ); n_double cm1 = cos ( -delta_angle ); n_double w = 2 * cm1; n_double ar0, ar1, ar2, ai0, ai1, ai2; for ( i=0; i < NumSamples; i += BlockSize ) { ar2 = cm2; ar1 = cm1; ai2 = sm2; ai1 = sm1; for ( j=i, n=0; n < BlockEnd; j++, n++ ) { ar0 = w*ar1 - ar2; ar2 = ar1; ar1 = ar0; ai0 = w*ai1 - ai2; ai2 = ai1; ai1 = ai0; k = j + BlockEnd; tr = ar0*RealOut[k] - ai0*ImagOut[k]; ti = ar0*ImagOut[k] + ai0*RealOut[k]; RealOut[k] = RealOut[j] - tr; ImagOut[k] = ImagOut[j] - ti; RealOut[j] += tr; ImagOut[j] += ti; } } BlockEnd = BlockSize; } /* ** Need to normalize if inverse transform... */ if ( InverseTransform ) { float denom = (float)NumSamples; for ( i=0; i < NumSamples; i++ ) { RealOut[i] /= denom; ImagOut[i] /= denom; } } } /** * Perform a fast fourier transform. * @param inverse if this is an inverse FFT. * @param power_sample the number of bits of the FFT cell size. */ void audio_fft(n_byte inverse, n_uint power_sample) { n_uint NumSamples = 1 << power_sample; /* Number of bits needed to store indices */ n_uint i; n_uint BlockSize, BlockEnd; n_double *d_in, *d_ini, *d_out, *d_outi; n_double angle_numerator = TWO_PI; if ( inverse ) { angle_numerator = -angle_numerator; d_in = frequency; d_ini = frequencyi; d_out = timedomain; d_outi = timedomaini; } else { d_in = timedomain; d_ini = timedomaini; d_out = frequency; d_outi = frequencyi; } /* ** Do simultaneous data copy and bit-reversal ordering into outputs... */ i=0; while(i < NumSamples) { n_uint j = audio_reverse_bits (i, power_sample); d_outi[j] = d_in[i]; d_out[j] = d_ini[i]; i++; } /* ** Do the FFT itself... */ BlockEnd = 1; BlockSize = 2; while (BlockSize <= NumSamples) { n_double delta_angle = angle_numerator / (n_double)BlockSize; n_double sm2 = sin ((n_double) -2.0f * delta_angle ); n_double sm1 = sin ((n_double) -delta_angle ); n_double cm2 = cos ((n_double) -2.0f * delta_angle ); n_double cm1 = cos ((n_double) -delta_angle ); n_double w = 2 * cm1; i=0; while( i < NumSamples ) { n_uint j=i; n_uint n=0; n_double ar2 = cm2; n_double ar1 = cm1; n_double ai2 = sm2; n_double ai1 = sm1; while(n < BlockEnd) { n_double ar0 = w*ar1 - ar2; n_double ai0 = w*ai1 - ai2; ar2 = ar1; ar1 = ar0; ai2 = ai1; ai1 = ai0; { n_uint k = j + BlockEnd; n_double tr = ar0*d_outi[k] - ai0*d_out[k]; n_double ti = ar0*d_out[k] + ai0*d_outi[k]; d_outi[k] = d_outi[j] - tr; d_out[k] = d_out[j] - ti; d_outi[j] += tr; d_out[j] += ti; } j++; n++; } i += BlockSize; } BlockEnd = BlockSize; BlockSize <<= 1; } /* ** Need to normalize if inverse transform... */ if ( inverse ) { n_double denom = (n_double) NumSamples; i = 0; while (i < NumSamples) { d_outi[i] /= denom; d_out[i] /= denom; i++; } } } /** * Clears all the buffers associated with the FFT. * @param length the length of the buffer to be cleared. */ void audio_clear_buffers(n_uint length) { n_uint loop = 0; while (loop < length) { frequency[loop] = 0; timedomain[loop] = 0; frequencyi[loop] = 0; timedomaini[loop] = 0; loop++; } } /** * Clears an audio output buffer * @param audio the audio buffer to be cleared. * @param length the length of the buffer to be cleared. */ void audio_clear_output(n_audio * audio, n_uint length) { n_uint loop = 0; while (loop < length) { audio[loop] = 0; loop++; } } /** * Sets an audio ouput buffer to the FFT time-domain buffer. * @param audio the audio buffer to be set. * @param length the length of the buffer to be set. */ void audio_equal_output(n_audio * audio, n_uint length) { n_uint loop = 0; while (loop < length) { audio[loop] = (n_audio)timedomain[loop]; loop++; } } /** * Sets an audio ouput buffer to the FFT time-domain buffer. * @param audio the audio buffer to be set. * @param length the length of the buffer to be set. */ static void audio_equal_input(n_audio * audio, n_uint length) { n_uint loop = 0; while (loop < length) { timedomain[loop] = (n_double)audio[loop]; loop++; } } /** * Multiplies an audio ouput buffer to the FFT time-domain buffer. * @param audio the audio buffer to be multiplied. * @param length the length of the buffer to be multiplied. */ void audio_multiply_output(n_audio * audio, n_uint length) { n_uint loop = 0; while (loop < length) { audio[loop] *= timedomain[loop]; loop++; } } /** * Sets frequency values in the frequency FFT buffer. * @param entry the frequency entry point. * @param value the specific value to set in the frequency entry. */ void audio_set_frequency(n_uint entry, n_uint value) { frequency[entry] = value/1E+00; frequencyi[entry] = 0E+00; } void audio_low_frequency(n_audio * buffer, n_int number_freq, n_int debug) { audio_equal_input(buffer, AUDIO_FFT_MAX_BUFFER); audio_fft(0, 15); audio_fft(1, 15); audio_equal_output(buffer, AUDIO_FFT_MAX_BUFFER); } static void audio_aiff_uint(n_byte * buffer, n_uint value) { buffer[0] = (value & 0xff000000) >> 24; buffer[1] = (value & 0x00ff0000) >> 16; buffer[2] = (value & 0x0000ff00) >> 8; buffer[3] = (value & 0x000000ff) >> 0; } static n_uint audio_aiff_byte(n_byte * buffer) { n_uint value = buffer[3]; value |= (n_uint)(buffer[2] << 8); value |= (n_uint)(buffer[1] << 16); value |= (n_uint)(buffer[0] << 24); return value; } void audio_aiff_body(void * fptr, n_audio *samples, n_uint number_samples) { fwrite(samples,number_samples,sizeof(n_audio),(FILE*)fptr); } static void audio_header(n_byte * header) { header[0] = 'F'; header[1] = 'O'; header[2] = 'R'; header[3] = 'M'; header[8] = 'A'; header[9] = 'I'; header[10] = 'F'; header[11] = 'F'; header[12] = 'C'; header[13] = 'O'; header[14] = 'M'; header[15] = 'M'; header[19] = 18; header[21] = 1; header[27] = 16; header[28] = 0x40; header[29] = 0x0e; header[30] = 0xac; header[31] = 0x44; header[38] = 'S'; header[39] = 'S'; header[40] = 'N'; header[41] = 'D'; } static n_uint audio_total_size(n_uint total_samples) { return (sizeof(n_audio) * total_samples) + 46; } static n_uint audio_sound_size(n_uint total_samples) { return (sizeof(n_audio) * total_samples) + 8; } void audio_aiff_header(void * fptr, n_uint total_samples) { n_byte header[54] = {0}; audio_header(header); audio_aiff_uint(&header[4], audio_total_size(total_samples)); audio_aiff_uint(&header[22], total_samples); audio_aiff_uint(&header[42], audio_sound_size(total_samples)); fwrite(header, 54, 1, (FILE*)fptr); } static n_int audio_aiff_comparison(n_byte * compare1, n_byte * compare2, n_int start, n_int end) { n_int loop_section = start; while (loop_section < end) { if (compare1[loop_section] != compare2[loop_section]) { printf("failed at point %ld\n", loop_section); return loop_section; } loop_section++; } return -1; } n_int audio_aiff_is_header(void * fptr, n_uint *samples) { n_byte read_header[54] = {0}; n_byte compare_header[54] = {0}; audio_header(compare_header); fread(read_header, 54, 1, (FILE*)fptr); if (audio_aiff_comparison(read_header, compare_header, 0, 4) != -1) { return 0; } if (audio_aiff_comparison(read_header, compare_header, 8, 22) != -1) { return 0; } if (audio_aiff_comparison(read_header, compare_header, 26, 42) != -1) { return 0; } if (audio_aiff_comparison(read_header, compare_header, 46, 54) != -1) { return 0; } *samples = audio_aiff_byte(&read_header[22]); return 1; } <|start_filename|>test/test_math.c<|end_filename|> /**************************************************************** test_math.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of Tom Barbalet, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ /* this doesn't currently work, it is included here for unit testing in the future */ #include "../toolkit/toolkit.h" #include <stdio.h> n_int draw_error(n_constant_string error_text, n_constant_string location, n_int line_number) { printf("ERROR: %s @ %s %ld\n",(const n_string) error_text, location, line_number); return -1; } n_int check_root(n_uint value, n_uint squared) { n_uint result = math_root(squared); if (result != value) { printf("squared %ld expects value %ld, instead %ld\n", squared, value, result); return -1; } return 0; } void check_intersection(void) { n_vect2 p1, p2, q1, q2; p1.x = 1; p1.y = 1; q1.x = 10; q1.y = 1; p2.x = 1; p2.y = 2; q2.x = 10; q2.y = 2; if (math_do_intersect(&p1, &q1, &p2, &q2) != 0) { printf("first intersection should be 0\n"); return; } p1.x = 10; p1.y = 0; q1.x = 0; q1.y = 10; p2.x = 0; p2.y = 0; q2.x = 10; q2.y = 10; if (math_do_intersect(&p1, &q1, &p2, &q2) != 1) { printf("second intersection should be 1\n"); return; } p1.x = -5; p1.y = -5; q1.x = 0; q1.y = 0; p2.x = 1; p2.y = 1; q2.x = 10; q2.y = 10; if (math_do_intersect(&p1, &q1, &p2, &q2) != 0) { printf("third intersection should be 0\n"); return; } printf("Intersections passed fine!\n"); } void check_math(void) { n_int loop = 0; n_int sum = 0; n_vect2 sum_vect = {0}; (void)check_root(1234, 1522756); (void)check_root(4, 17); (void)check_root(4, 16); (void)check_root(3, 15); (void)check_root(3, 14); check_intersection(); while (loop < 256) { n_vect2 each_vect; sum += math_sine(loop, 1); vect2_direction(&each_vect, loop, 1); vect2_d(&sum_vect, &each_vect, 1, 1); loop++; } if (sum != 0) { printf("scalar sum expecting 0 instead %ld\n", sum); } if (sum_vect.x != 0 || sum_vect.y != 0) { printf("vect sum expecting 0, 0 instead %ld, %ld\n", sum_vect.x, sum_vect.y); } } int main(int argc, const char * argv[]) { printf(" --- test math --- start ----------------------------------------------\n"); check_math(); printf(" --- test math --- end ----------------------------------------------\n"); return 0; } <|start_filename|>gui/message.c<|end_filename|> /**************************************************************** message.c ============================================================= Copyright 1996-2020 <NAME>. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This software is a continuing work of <NAME>, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #include "gui.h" typedef struct { n_string message; n_int * spaces; n_string_block * direct_rendering; n_int x; n_int y; n_int width; n_int height; n_int time_to_expire; } n_message; #define MAXIMUM_NUMBER_MESSAGE 10 static n_int number_messages = 0; n_message messages[MAXIMUM_NUMBER_MESSAGE]; static n_int * message_find_spaces(n_string string, n_int * count) { n_int local_count = 0; n_int loop = 0; n_int *return_value = 0L; if (*count) { return_value = memory_new((n_uint)(*count) * sizeof(n_int)); } if (string == 0L) { return 0L; } if (string[0] == 0) { return 0L; } do { if (string[loop] == ' ') { if (*count) { return_value[local_count] = loop; } local_count++; } } while(string[loop]); return return_value; } static void message_remove(n_int remove) { n_message *value = &messages[remove]; if (value) { if (value->message) { memory_free((void**)&(value->message)); } if (value->spaces) { memory_free((void**)&(value->spaces)); } } if (remove != (number_messages-1)) { n_message *copy_from = &messages[number_messages-1]; value->message = copy_from->message; value->spaces = copy_from->spaces; value->direct_rendering = copy_from->direct_rendering; value->x = copy_from->x; value->y = copy_from->y; value->width = copy_from->width; value->height = copy_from->height; value->time_to_expire = copy_from->time_to_expire; } number_messages--; } static void message_add(n_string message, n_int time_to_expire) { n_int * spaces; n_string copied_message; n_int space_count = 0; if (number_messages == (MAXIMUM_NUMBER_MESSAGE-1)) { /* if the message stack is full remove the oldest message */ n_int loop = 0; n_int oldest_loop = 0; n_int oldest_time_to_expire = 100000; while (loop < number_messages) { if (oldest_time_to_expire > messages[loop].time_to_expire) { oldest_loop = loop; oldest_time_to_expire = messages[loop].time_to_expire; } loop++; } message_remove(oldest_loop); } if (message == 0L) { return; } if (time_to_expire == 0) { return; } (void)message_find_spaces(message, &space_count); if (space_count == 0) { return; } spaces = message_find_spaces(message, &space_count); if (spaces == 0L) { return; } copied_message = io_string_copy(message); if (copied_message == 0L) { memory_free((void**)&(spaces)); return; } messages[number_messages].time_to_expire = time_to_expire; messages[number_messages].message = copied_message; messages[number_messages].spaces = spaces; number_messages++; }
barbalet/nobleape
<|start_filename|>.babelrc.js<|end_filename|> module.exports = { presets: [ [ '@babel/preset-env', { targets: 'defaults', modules: process.env.ESM === 'true' ? false : 'commonjs', }, ], '@babel/preset-react', '@babel/preset-typescript', ], plugins: ['babel-plugin-typescript-to-proptypes'], }; <|start_filename|>jest.config.js<|end_filename|> module.exports = { testEnvironment: 'jsdom', setupFilesAfterEnv: ['./test/jest-setup.ts'], testPathIgnorePatterns: ['/node_modules/', '/examples/', '/lib/'], timers: 'fake', resetModules: true, resetMocks: true, };
Yoctol/react-d3-cloud
<|start_filename|>Makefile<|end_filename|> PRGM = i3lock-fancy PREFIX ?= /usr SHRDIR ?= $(PREFIX)/share BINDIR ?= $(PREFIX)/bin install: @install -Dm755 i3lock-fancy -t $(DESTDIR)$(BINDIR) @install -Dm644 icons/* -t $(DESTDIR)$(SHRDIR)/$(PRGM)/icons @install -Dm644 doc/i3lock-fancy.1 -t $(DESTDIR)$(SHRDIR)/man/man1 @install -Dm644 LICENSE -t $(DESTDIR)$(SHRDIR)/licenses/$(PRGM) uninstall: @unlink $(DESTDIR)$(BINDIR)/$(PRGM) # Remove binary @rm -Rf $(DESTDIR)$(SHRDIR)/$(PRGM) # Remove icons @unlink $(DESTDIR)$(SHRDIR)/man/man1/i3lock-fancy.1 # Remove man @rm -Rf $(DESTDIR)$(SHRDIR)/licenses/$(PRGM) # Remove license
Nicofolxarus/i3lock-fancy
<|start_filename|>updater/src/main/java/com/simplepeng/updater/UpdaterFileProvider.java<|end_filename|> package com.simplepeng.updater; import android.support.v4.content.FileProvider; public class UpdaterFileProvider extends FileProvider { } <|start_filename|>updater/src/main/java/com/simplepeng/updater/ProgressListener.java<|end_filename|> package com.simplepeng.updater; public interface ProgressListener { void onProgressChange(long totalBytes, long curBytes, int progress); } <|start_filename|>updater/src/main/java/com/simplepeng/updater/Updater.java<|end_filename|> package com.simplepeng.updater; import android.Manifest; import android.app.Activity; import android.app.DownloadManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.support.v4.content.ContextCompat; import android.text.TextUtils; import android.widget.Toast; import com.yanzhenjie.permission.Action; import com.yanzhenjie.permission.AndPermission; import com.yanzhenjie.permission.Permission; import java.io.File; import java.util.ArrayList; import java.util.List; public class Updater { private String apkFileName; private String apkFilePath; private String apkDirName; private String title; private String downloadUrl; private Activity context; private DownloadManager downloadManager; private long mTaskId; private boolean hideNotification = false; // private ProgressListener mProgressListener; private boolean allowedOverRoaming = false; private DownloadReceiver downloadReceiver; private DownloadObserver downloadObserver; private boolean claerCache = false; private String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}; private static final int RC_SDCARD = 123; private DownloadFailedReceiver downloadFailedReceiver = new DownloadFailedReceiver(); private Updater(Activity context) { this.context = context; } private void checkPermissions() { AndPermission.with(context) .runtime() .permission(Permission.Group.STORAGE) .onGranted(new Action<List<String>>() { @Override public void onAction(List<String> data) { download(); } }) .onDenied(new Action<List<String>>() { @Override public void onAction(List<String> data) { Toast.makeText(context, "取消了授权", Toast.LENGTH_SHORT).show(); } }) .start(); } private void download() { if (context == null) { throw new NullPointerException("context must not be null"); } if (TextUtils.isEmpty(downloadUrl)) { throw new NullPointerException("downloadUrl must not be null"); } if (downloadManager == null) { downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); } DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl)); request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager .Request.NETWORK_WIFI); request.setAllowedOverRoaming(allowedOverRoaming); request.setTitle(TextUtils.isEmpty(title) ? apkFileName : title); request.setNotificationVisibility(hideNotification ? DownloadManager.Request.VISIBILITY_HIDDEN : DownloadManager.Request.VISIBILITY_VISIBLE); if (TextUtils.isEmpty(apkFileName)) { apkFileName = Utils.getFileNameForUrl(downloadUrl); } if (!apkFileName.endsWith(".apk")) { apkFileName += ".apk"; } //设置下载路径 if (TextUtils.isEmpty(apkFilePath) && TextUtils.isEmpty(apkDirName)) { request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, apkFileName); } else if (!TextUtils.isEmpty(apkDirName)) { request.setDestinationInExternalPublicDir(apkDirName, apkFileName); } else { String apkAbsPath = apkFilePath + File.separator + apkFileName; request.setDestinationUri(Uri.fromFile(new File(apkAbsPath))); } //将下载请求加入下载队列 //加入下载队列后会给该任务返回一个long型的id, //通过该id可以取消任务,重启任务等等 mTaskId = downloadManager.enqueue(request); if (downloadFailedReceiver != null) { context.registerReceiver(downloadFailedReceiver, new IntentFilter(Updater.DownloadFailedReceiver.tag)); } } /** * 注册下载完成的监听 */ public void registerDownloadReceiver() { if (downloadReceiver == null) { downloadReceiver = new DownloadReceiver(); } context.registerReceiver(downloadReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); } /** * 解绑下载完成的监听 */ public void unRegisterDownloadReceiver() { if (downloadReceiver != null) { context.unregisterReceiver(downloadReceiver); } } private ArrayList<ProgressListener> listeners; /** * 添加下载进度回调 */ public void addProgressListener(ProgressListener progressListener) { if (listeners == null) { listeners = new ArrayList<>(); } if (!listeners.contains(progressListener)) { listeners.add(progressListener); } if (downloadObserver == null && handler != null && downloadManager != null) { downloadObserver = new DownloadObserver(handler, downloadManager, mTaskId); context.getContentResolver().registerContentObserver(Uri.parse("content://downloads/"), true, downloadObserver); } } /** * 移除下载进度回调 */ public void removeProgressListener(ProgressListener progressListener) { if (!listeners.contains(progressListener)) { throw new NullPointerException("this progressListener not attch Updater"); } if (listeners != null && !listeners.isEmpty()) { listeners.remove(progressListener); if (listeners.isEmpty() && downloadObserver != null) context.getContentResolver().unregisterContentObserver(downloadObserver); } } public static void showToast(Context context, String msg) { Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); } private Handler handler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { Bundle data = msg.getData(); long cutBytes = data.getLong(DownloadObserver.CURBYTES); long totalBytes = data.getLong(DownloadObserver.TOTALBYTES); int progress = data.getInt(DownloadObserver.PROGRESS); if (listeners != null && !listeners.isEmpty()) { for (ProgressListener listener : listeners) { listener.onProgressChange(totalBytes, cutBytes, progress); } } return false; } }); public static class Builder { private Updater mUpdater; public Builder(Activity context) { synchronized (Updater.class) { if (mUpdater == null) { synchronized (Updater.class) { mUpdater = new Updater(context); } } } } /** * 设置下载下来的apk文件名 * * @param apkName apk文件的名字 * @return */ public Builder setApkFileName(String apkName) { mUpdater.apkFileName = apkName; return this; } /** * 设置apk下载的路径 * * @param apkPath 自定义的全路径 * @return */ public Builder setApkPath(String apkPath) { mUpdater.apkFilePath = apkPath; return this; } /** * 设置下载apk的文件目录 * * @param dirName sd卡的文件夹名字 * @return */ public Builder setApkDir(String dirName) { mUpdater.apkDirName = dirName; return this; } /** * 设置下载的链接地址 * * @param downloadUrl apk的下载链接 * @return */ public Builder setDownloadUrl(String downloadUrl) { mUpdater.downloadUrl = downloadUrl; return this; } /** * 通知栏显示的标题 * * @param title 标题 * @return */ public Builder setNotificationTitle(String title) { mUpdater.title = title; return this; } /** * 隐藏通知栏 * * @return */ public Builder hideNotification() { mUpdater.hideNotification = true; return this; } /** * 是否为debug模式,会输出很多log信息(手动斜眼) * * @return */ public Builder debug() { LogUtils.isDebug = true; return this; } /** * 允许漫游网络可下载 * * @return */ public Builder allowedOverRoaming() { mUpdater.allowedOverRoaming = true; return this; } public Builder clearCache() { mUpdater.claerCache = true; return this; } /** * 开始下载 * * @return */ public Updater start() { mUpdater.checkPermissions(); return mUpdater; } } public class DownloadFailedReceiver extends BroadcastReceiver { public static final String tag = "DownloadFailedReceiver"; @Override public void onReceive(Context context, Intent intent) { LogUtils.debug("开始重新下载"); download(); } } } <|start_filename|>updater/src/main/java/com/simplepeng/updater/DownloadObserver.java<|end_filename|> package com.simplepeng.updater; import android.app.DownloadManager; import android.database.ContentObserver; import android.database.Cursor; import android.os.Bundle; import android.os.Handler; import android.os.Message; public class DownloadObserver extends ContentObserver { private DownloadManager mDownloadManager; private long mTaskId; private Handler mHandler; private Bundle bundle = new Bundle(); private Message message; private DownloadManager.Query query; private Cursor cursor; public static final String CURBYTES = "curBytes"; public static final String TOTALBYTES = "totalBytes"; public static final String PROGRESS = "progress"; /** * Creates a content observer. * * @param handler The handler to run {@link #onChange} on, or null if none. */ public DownloadObserver(Handler handler, DownloadManager downloadManager, long taskId) { super(handler); this.mHandler = handler; this.mDownloadManager = downloadManager; this.mTaskId = taskId; query = new DownloadManager.Query().setFilterById(mTaskId); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); try { cursor = mDownloadManager.query(query); if (cursor == null) { return; } cursor.moveToFirst(); long curBytes = cursor .getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)); long totalBytes = cursor .getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)); int mProgress = (int) ((curBytes * 100) / totalBytes); if (totalBytes != 0) { LogUtils.debug("curBytes==" + curBytes); LogUtils.debug("totalBytes==" + totalBytes); LogUtils.debug("mProgress------->" + mProgress); message = mHandler.obtainMessage(); bundle.putLong(CURBYTES, curBytes); bundle.putLong(TOTALBYTES, totalBytes); bundle.putInt(PROGRESS, mProgress); message.setData(bundle); mHandler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); } } } } <|start_filename|>updater/src/main/java/com/simplepeng/updater/LogUtils.java<|end_filename|> package com.simplepeng.updater; import android.util.Log; public class LogUtils { private static final String TAG = "Updater"; public static boolean isDebug = false; public static void debug(String msg) { if (isDebug) { Log.d(TAG, msg); } } } <|start_filename|>updater/src/main/java/com/simplepeng/updater/Utils.java<|end_filename|> package com.simplepeng.updater; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.support.v4.content.FileProvider; import android.text.TextUtils; import java.io.File; public class Utils { public static final String getFileNameForUrl(String url) { if (TextUtils.isEmpty(url)) { throw new NullPointerException("url is null"); } return url.substring(url.lastIndexOf("/") + 1); } public static void installApk(Context context, Uri uri) { File file = new File(uri.getPath()); if (!file.exists()) { LogUtils.debug("apk file not exists"); return; } Intent intent = new Intent(); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) { String packageName = context.getPackageName(); LogUtils.debug("packageName==" + packageName); Uri providerUri = FileProvider .getUriForFile(context, packageName + ".fileProvider", file); // Uri providerUri = FileProvider // .getUriForFile(context, "com.simplepeng.updaterlibrary.fileprovider", file); LogUtils.debug("providerUri==" + providerUri); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setDataAndType(providerUri, "application/vnd.android.package-archive"); } else { intent.setDataAndType(uri, "application/vnd.android.package-archive"); } intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(Intent.ACTION_VIEW); context.startActivity(intent); } } <|start_filename|>demo/src/main/java/com/github/demo/MainActivity.java<|end_filename|> package com.github.demo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import com.simplepeng.updater.Updater; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditText editText = findViewById(R.id.editText); String apkUrl = "https://raw.githubusercontent.com/simplepeng/Updater/master/apk/demo-release-unsigned.apk"; editText.setText(apkUrl); findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String url = editText.getText().toString().trim(); updateApk(url); } }); } private void updateApk(String url) { new Updater.Builder(this) .setDownloadUrl(url) .setApkFileName("Updater") .setNotificationTitle("正在下载最新apk") .debug() .start(); } } <|start_filename|>updater/src/main/java/com/simplepeng/updater/DownloadReceiver.java<|end_filename|> package com.simplepeng.updater; import android.app.DownloadManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v4.content.FileProvider; import android.text.TextUtils; import java.io.File; public class DownloadReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); if (bundle == null) return; long downId = bundle.getLong(DownloadManager.EXTRA_DOWNLOAD_ID, 0); //下载完成或点击通知栏 if (TextUtils.equals(intent.getAction(), (DownloadManager.ACTION_DOWNLOAD_COMPLETE)) || TextUtils.equals(intent.getAction(), (DownloadManager.ACTION_NOTIFICATION_CLICKED))) { queryFileUri(context, downId); } } private void queryFileUri(Context context, long downloadApkId) { DownloadManager dManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(downloadApkId); if (dManager == null)return; Cursor c = dManager.query(query); if (c != null && c.moveToFirst()) { int status = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS)); switch (status) { case DownloadManager.STATUS_PENDING: LogUtils.debug("STATUS_PENDING"); break; case DownloadManager.STATUS_PAUSED: LogUtils.debug("STATUS_PAUSED"); break; case DownloadManager.STATUS_RUNNING: LogUtils.debug("STATUS_RUNNING"); break; case DownloadManager.STATUS_SUCCESSFUL: LogUtils.debug("STATUS_SUCCESSFUL"); String downloadFileUrl = c .getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)); Utils.installApk(context, Uri.parse(downloadFileUrl)); // context.unregisterReceiver(); break; case DownloadManager.STATUS_FAILED: LogUtils.debug("STATUS_FAILED"); Updater.showToast(context, "下载失败,开始重新下载..."); context.sendBroadcast(new Intent(Updater.DownloadFailedReceiver.tag)); break; } c.close(); } } }
simplepeng/Updater
<|start_filename|>FaceTracker/src/seeta/FaceTracker.cpp<|end_filename|> // // Created by kier on 2019-09-16. // #pragma once #include <seeta/FaceDetector.h> #include <vector> #include <algorithm> #include <queue> #include <seeta/CTrackingFaceInfo.h> #include <seeta/FaceTracker.h> #include <iostream> namespace seeta { namespace v2 { struct TrackedFace { SeetaRect pos = {0, 0, 0, 0}; int PID = 0; float conf = 0; int frame_no = 0; }; class FaceTracker::Implement { public: Implement(); ~Implement(); void bind(const std::shared_ptr<seeta::FaceDetector> pFD); void refresh(); const std::vector<TrackedFace> &Detect(const SeetaImageData &image, int frame_no = -1) const; SeetaTrackingFaceInfoArray DetectV2(const SeetaImageData &image, int frame_no = -1) const; seeta::FaceDetector &FD() { return *pFD; } const seeta::FaceDetector &FD() const { return *pFD; } private: std::shared_ptr<seeta::FaceDetector> pFD; mutable std::vector<TrackedFace> pre_tracked_faces; mutable int max_PID = 0; float min_score = 0.3f; float max_score = 0.5f; mutable int frame_no = 0; mutable std::vector<SeetaTrackingFaceInfo> tracked_faces; }; } using namespace v2; } namespace seeta { namespace v2 { FaceTracker::Implement::Implement() { } FaceTracker::Implement::~Implement() { } void FaceTracker::Implement::bind(const std::shared_ptr<seeta::FaceDetector> pFD) { this->pFD = pFD; this->refresh(); } void FaceTracker::Implement::refresh() { this->max_PID = 0; this->frame_no = 0; } struct ScoredTrackedFace { ScoredTrackedFace(const TrackedFace &tracked_face) : face(tracked_face) {} TrackedFace face; float iou_score = 0; }; static float IoU(const SeetaRect &w1, const SeetaRect &w2) { int xOverlap = std::max(0, std::min(w1.x + w1.width - 1, w2.x + w2.width - 1) - std::max(w1.x, w2.x) + 1); int yOverlap = std::max(0, std::min(w1.y + w1.height - 1, w2.y + w2.height - 1) - std::max(w1.y, w2.y) + 1); int intersection = xOverlap * yOverlap; int unio = w1.width * w1.height + w2.width * w2.height - intersection; return float(intersection) / unio; } const std::vector<TrackedFace> &FaceTracker::Implement::Detect(const SeetaImageData &image, int frame_no) const { if (!this->pFD) { pre_tracked_faces.clear(); return pre_tracked_faces; } if (frame_no < 0) { frame_no = this->frame_no; ++this->frame_no; } int num = 0; auto face_array = this->pFD->detect(image); std::vector<SeetaRect> faces; num = int(face_array.size); for (int i = 0; i < num; ++i) { faces.push_back(face_array.data[i].pos); } // prepare scored trakced faces std::deque<ScoredTrackedFace> scored_tracked_faces(pre_tracked_faces.begin(), pre_tracked_faces.end()); std::vector<TrackedFace> now_trakced_faces; for (int i = 0; i < num; ++i) { auto &face = faces[i]; for (auto &scored_tracked_face : scored_tracked_faces) { scored_tracked_face.iou_score = IoU(scored_tracked_face.face.pos, face); std::cout << scored_tracked_face.iou_score << std::endl; } if (scored_tracked_faces.size() > 1) { std::partial_sort(scored_tracked_faces.begin(), scored_tracked_faces.begin() + 1, scored_tracked_faces.end(), [](const ScoredTrackedFace &a, const ScoredTrackedFace &b) { return a.iou_score > b.iou_score; }); } if (!scored_tracked_faces.empty() && scored_tracked_faces.front().iou_score > this->min_score) { ScoredTrackedFace matched_face = scored_tracked_faces.front(); scored_tracked_faces.pop_front(); TrackedFace &tracked_face = matched_face.face; if (matched_face.iou_score < max_score) { tracked_face.pos.x = (tracked_face.pos.x + face.x) / 2; tracked_face.pos.y = (tracked_face.pos.y + face.y) / 2; tracked_face.pos.width = (tracked_face.pos.width + face.width) / 2; tracked_face.pos.height = (tracked_face.pos.height + face.height) / 2; } else { tracked_face.pos = face; } tracked_face.conf = face_array.data[i].score; tracked_face.frame_no = frame_no; now_trakced_faces.push_back(tracked_face); } else { TrackedFace tracked_face; tracked_face.pos = face; tracked_face.PID = max_PID; tracked_face.conf = face_array.data[i].score; tracked_face.frame_no = frame_no; max_PID++; now_trakced_faces.push_back(tracked_face); } } pre_tracked_faces = now_trakced_faces; return pre_tracked_faces; } SeetaTrackingFaceInfoArray FaceTracker::Implement::DetectV2(const SeetaImageData &image, int frame_no) const { auto &faces = Detect(image, frame_no); tracked_faces.clear(); for (auto &face : faces) { SeetaTrackingFaceInfo info; info.PID = face.PID; info.score = face.conf; info.frame_no = face.frame_no; info.pos = face.pos; tracked_faces.push_back(info); } SeetaTrackingFaceInfoArray result = {nullptr, 0}; result.data = tracked_faces.data(); result.size = tracked_faces.size(); return result; } } FaceTracker::FaceTracker(const SeetaModelSetting &setting) { m_impl = new Implement; m_impl->bind(std::make_shared<seeta::FaceDetector>(setting)); m_impl->FD().set(seeta::FaceDetector::Property(PROPERTY_VIDEO_STABLE), 0); } FaceTracker::FaceTracker(const SeetaModelSetting &setting, int core_width, int core_height) { m_impl = new Implement; m_impl->bind(std::make_shared<seeta::FaceDetector>(setting, core_width, core_height)); m_impl->FD().set(seeta::FaceDetector::Property(PROPERTY_VIDEO_STABLE), 0); } FaceTracker::~FaceTracker() { delete m_impl; } SeetaTrackingFaceInfoArray FaceTracker::track(const SeetaImageData &image, int frame_no) const { return m_impl->DetectV2(image, frame_no); } void FaceTracker::set(FaceTracker::Property property, double value) { if (property == PROPERTY_VIDEO_STABLE) return; m_impl->FD().set(seeta::FaceDetector::Property(property), value); } double FaceTracker::get(FaceTracker::Property property) const { return m_impl->FD().get(seeta::FaceDetector::Property(property)); } }
frkhit/SeetaFace2
<|start_filename|>nrfx_saadc_continuous_sampling/main.c<|end_filename|> /** * Copyright (c) 2014 - 2017, Nordic Semiconductor ASA * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form, except as embedded into a Nordic * Semiconductor ASA integrated circuit in a product or a software update for * such product, 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. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * 4. This software, with or without modification, must only be used with a * Nordic Semiconductor ASA integrated circuit. * * 5. Any software provided in binary form under this license must not be reverse * engineered, decompiled, modified and/or disassembled. * * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA 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. * */ /** * Perhipheral: nRF52 SAADC * Compatibility: nRF52832/nRF52833/nRF52840, nRF5 SDK 17.0.0 * Softdevice used: No softdevice * * This example uses the internal timer feature of the SAADC to trigger sampling at a fixed sample rate, * as set by the SAADC_SAMPLE_FREQUENCY define. * * Please note that this feature only supports a limited range of sampling frequencies, and for sampling at frequencies * below 8kHz it is necessary to use a dedicated timer as shown in some of the other examples. * * The example samples on a single input pin, AIN0, which maps to physical pin P0.02 on the nRF52832/nRF52840 ICs. */ #include <stdbool.h> #include <stdint.h> #include <nrfx_saadc.h> #include "nrf_delay.h" #include "nrf_drv_clock.h" #include "nrf_log.h" #include "nrf_log_ctrl.h" #include "nrf_log_default_backends.h" #define SAADC_BUF_SIZE 1024 #define SAADC_BUF_COUNT 2 #define SAADC_SAMPLE_FREQUENCY 8000 static nrf_saadc_value_t samples[SAADC_BUF_COUNT][SAADC_BUF_SIZE]; static nrfx_saadc_channel_t channel_config = NRFX_SAADC_DEFAULT_CHANNEL_SE(NRF_SAADC_INPUT_AIN0, 0); // Simple function to provide an index to the next input buffer // Will simply alernate between 0 and 1 when SAADC_BUF_COUNT is 2 static uint32_t next_free_buf_index(void) { static uint32_t buffer_index = -1; buffer_index = (buffer_index + 1) % SAADC_BUF_COUNT; return buffer_index; } static void event_handler(nrfx_saadc_evt_t const * p_event) { ret_code_t err_code; switch (p_event->type) { case NRFX_SAADC_EVT_DONE: NRF_LOG_INFO("DONE. Sample[0] = %i", p_event->data.done.p_buffer[0]); // Add code here to process the input // If the processing is time consuming execution should be deferred to the main context break; case NRFX_SAADC_EVT_BUF_REQ: // Set up the next available buffer err_code = nrfx_saadc_buffer_set(&samples[next_free_buf_index()][0], SAADC_BUF_SIZE); APP_ERROR_CHECK(err_code); break; } } static void adc_start(uint32_t cc_value) { ret_code_t err_code; nrfx_saadc_adv_config_t saadc_adv_config = NRFX_SAADC_DEFAULT_ADV_CONFIG; saadc_adv_config.internal_timer_cc = cc_value; saadc_adv_config.start_on_end = true; err_code = nrfx_saadc_advanced_mode_set((1<<0), NRF_SAADC_RESOLUTION_10BIT, &saadc_adv_config, event_handler); APP_ERROR_CHECK(err_code); // Configure two buffers to ensure double buffering of samples, to avoid data loss when the sampling frequency is high err_code = nrfx_saadc_buffer_set(&samples[next_free_buf_index()][0], SAADC_BUF_SIZE); APP_ERROR_CHECK(err_code); err_code = nrfx_saadc_buffer_set(&samples[next_free_buf_index()][0], SAADC_BUF_SIZE); APP_ERROR_CHECK(err_code); err_code = nrfx_saadc_mode_trigger(); APP_ERROR_CHECK(err_code); } int main(void) { ret_code_t err_code; // Configure Logging. LOGGING is used to show the SAADC sampled result. Default is UART, but RTT can be configured in sdk_config.h err_code = NRF_LOG_INIT(NULL); APP_ERROR_CHECK(err_code); NRF_LOG_DEFAULT_BACKENDS_INIT(); NRF_LOG_INFO("nrfx_saadc_api2 simple SAADC Continuous Sampling Example."); err_code = nrfx_saadc_init(NRFX_SAADC_CONFIG_IRQ_PRIORITY); APP_ERROR_CHECK(err_code); err_code = nrfx_saadc_channels_config(&channel_config, 1); APP_ERROR_CHECK(err_code); uint32_t adc_cc_value = 16000000 / SAADC_SAMPLE_FREQUENCY; if(adc_cc_value < 80 || adc_cc_value > 2047) { NRF_LOG_ERROR("SAMPLERATE frequency outside legal range. Consider using a timer to trigger the ADC instead."); APP_ERROR_CHECK(false); } adc_start(adc_cc_value); while (1) { while(NRF_LOG_PROCESS() != NRF_SUCCESS); __WFE(); } } <|start_filename|>saadc_low_power/main.c<|end_filename|> /** * Copyright (c) 2014 - 2017, Nordic Semiconductor ASA * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form, except as embedded into a Nordic * Semiconductor ASA integrated circuit in a product or a software update for * such product, 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. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * 4. This software, with or without modification, must only be used with a * Nordic Semiconductor ASA integrated circuit. * * 5. Any software provided in binary form under this license must not be reverse * engineered, decompiled, modified and/or disassembled. * * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA 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. * */ /** * Perhipheral: nRF52 SAADC * Compatibility: nRF52832 rev 1/nRF52840 Eng A, nRF5 SDK 13.0.0 * Softdevice used: No softdevice * * This example enables the RTC timer to periodically trigger SAADC sampling. RTC is chosen here instead of * TIMER because it is low power. The example samples on a single input pin, the AIN0, which maps to physical pin P0.02 on the nRF52832 IC. * This SAADC example shows the following features: * - Low Power -> Enabled with initializing SAADC when sampling and uninitializing when sampling is complete. * Low power can only be obtained when UART_PRINTING_ENABLED is not defined and * SAADC_SAMPLES_IN_BUFFER is 1 * - Oversampling -> This reduces SAADC noise level, especially for higher SAADC resolutions, see * https://devzone.nordicsemi.com/question/83938/nrf52832-saadc-sampling/?comment=84340#comment-84340 * Configured with the SAADC_OVERSAMPLE constant. * - BURST mode -> Burst mode can be combined with oversampling, which makes the SAADC sample all oversamples as fast * as it can with one SAMPLE task trigger. Set the SAADC_BURST_MODE constant to enable BURST mode. * - Offset Calibration -> SAADC needs to be occasionally calibrated. The desired calibration interval depends on the * expected temperature change rate, see the nRF52832 PS for more information. The * calibration interval can be adjusted with configuring the SAADC_CALIBRATION_INTERVAL * constant. * The SAADC sample result is printed on UART. To see the UART output, a UART terminal (e.g. Realterm) can be configured on * your PC with the UART configuration set in the uart_config function, which is also described in the saadc example documentation -> * http://infocenter.nordicsemi.com/topic/com.nordic.infocenter.sdk5.v11.0.0/nrf_dev_saadc_example.html?cp=5_0_0_4_5_24 * * Indicators on the nRF52-DK board: * LED1: SAADC Sampling triggered * LED2: SAADC sampling buffer full and event received * LED3: SAADC Offset calibration complete */ #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include "nrf.h" #include "nrf_drv_saadc.h" #include "boards.h" #include "app_error.h" #include "app_util_platform.h" #include "nrf_pwr_mgmt.h" #include "nrf_drv_power.h" #include "nrf_drv_clock.h" #include "nrf_drv_rtc.h" #include "nrf_log.h" #include "nrf_log_ctrl.h" #include "nrf_log_default_backends.h" #define RTC_FREQUENCY 32 //Determines the RTC frequency and prescaler #define RTC_CC_VALUE 8 //Determines the RTC interrupt frequency and thereby the SAADC sampling frequency #define SAADC_SAMPLE_INTERVAL_MS 250 //Interval in milliseconds at which RTC times out and triggers SAADC sample task ( #define SAADC_CALIBRATION_INTERVAL 5 //Determines how often the SAADC should be calibrated relative to NRF_DRV_SAADC_EVT_DONE event. E.g. value 5 will make the SAADC calibrate every fifth time the NRF_DRV_SAADC_EVT_DONE is received. #define SAADC_SAMPLES_IN_BUFFER 1 //Number of SAADC samples in RAM before returning a SAADC event. For low power SAADC set this constant to 1. Otherwise the EasyDMA will be enabled for an extended time which consumes high current. #define SAADC_OVERSAMPLE NRF_SAADC_OVERSAMPLE_DISABLED //Oversampling setting for the SAADC. Setting oversample to 4x This will make the SAADC output a single averaged value when the SAMPLE task is triggered 4 times. Enable BURST mode to make the SAADC sample 4 times when triggering SAMPLE task once. #define SAADC_BURST_MODE 0 //Set to 1 to enable BURST mode, otherwise set to 0. const nrf_drv_rtc_t rtc = NRF_DRV_RTC_INSTANCE(2); /**< Declaring an instance of nrf_drv_rtc for RTC2. */ static uint32_t rtc_ticks = RTC_US_TO_TICKS(SAADC_SAMPLE_INTERVAL_MS*1000, RTC_FREQUENCY); static nrf_saadc_value_t m_buffer_pool[2][SAADC_SAMPLES_IN_BUFFER]; static uint32_t m_adc_evt_counter = 0; static bool m_saadc_calibrate = false; static void rtc_handler(nrf_drv_rtc_int_type_t int_type) { uint32_t err_code; if (int_type == NRF_DRV_RTC_INT_COMPARE0) { nrf_drv_saadc_sample(); //Trigger the SAADC SAMPLE task LEDS_INVERT(BSP_LED_0_MASK); //Toggle LED1 to indicate SAADC sampling start err_code = nrf_drv_rtc_cc_set(&rtc, 0, rtc_ticks, true); //Set RTC compare value. This needs to be done every time as the nrf_drv_rtc clears the compare register on every compare match APP_ERROR_CHECK(err_code); nrf_drv_rtc_counter_clear(&rtc); //Clear the RTC counter to start count from zero } } static void lfclk_config(void) { ret_code_t err_code = nrf_drv_clock_init(); //Initialize the clock source specified in the nrf_drv_config.h file, i.e. the CLOCK_CONFIG_LF_SRC constant APP_ERROR_CHECK(err_code); nrf_drv_clock_lfclk_request(NULL); } static void rtc_config(void) { uint32_t err_code; //Initialize RTC instance nrf_drv_rtc_config_t rtc_config; rtc_config.prescaler = RTC_FREQ_TO_PRESCALER(RTC_FREQUENCY); err_code = nrf_drv_rtc_init(&rtc, &rtc_config, rtc_handler); //Initialize the RTC with callback function rtc_handler. The rtc_handler must be implemented in this applicaiton. Passing NULL here for RTC configuration means that configuration will be taken from the sdk_config.h file. APP_ERROR_CHECK(err_code); err_code = nrf_drv_rtc_cc_set(&rtc, 0, rtc_ticks, true); //Set RTC compare value to trigger interrupt. Configure the interrupt frequency by adjust RTC_CC_VALUE and RTC_FREQUENCY constant in top of main.c APP_ERROR_CHECK(err_code); //Power on RTC instance nrf_drv_rtc_enable(&rtc); //Enable RTC } void saadc_callback(nrf_drv_saadc_evt_t const * p_event) { ret_code_t err_code; if (p_event->type == NRF_DRV_SAADC_EVT_DONE) //Capture offset calibration complete event { LEDS_INVERT(BSP_LED_1_MASK); //Toggle LED2 to indicate SAADC buffer full if((m_adc_evt_counter % SAADC_CALIBRATION_INTERVAL) == 0) //Evaluate if offset calibration should be performed. Configure the SAADC_CALIBRATION_INTERVAL constant to change the calibration frequency { m_saadc_calibrate = true; // Set flag to trigger calibration in main context when SAADC is stopped } NRF_LOG_INFO("ADC event number: %d\r\n",(int)m_adc_evt_counter); //Print the event number on UART for (int i = 0; i < p_event->data.done.size; i++) { NRF_LOG_INFO("%d\r\n", p_event->data.done.p_buffer[i]); //Print the SAADC result on UART } if(m_saadc_calibrate == false) { err_code = nrf_drv_saadc_buffer_convert(p_event->data.done.p_buffer, SAADC_SAMPLES_IN_BUFFER); //Set buffer so the SAADC can write to it again. APP_ERROR_CHECK(err_code); } m_adc_evt_counter++; } else if (p_event->type == NRF_DRV_SAADC_EVT_CALIBRATEDONE) { LEDS_INVERT(BSP_LED_2_MASK); //Toggle LED3 to indicate SAADC calibration complete err_code = nrf_drv_saadc_buffer_convert(m_buffer_pool[0], SAADC_SAMPLES_IN_BUFFER); //Set buffer so the SAADC can write to it again. APP_ERROR_CHECK(err_code); err_code = nrf_drv_saadc_buffer_convert(m_buffer_pool[1], SAADC_SAMPLES_IN_BUFFER); //Need to setup both buffers, as they were both removed with the call to nrf_drv_saadc_abort before calibration. APP_ERROR_CHECK(err_code); NRF_LOG_INFO("SAADC calibration complete ! \r\n"); //Print on UART } } void saadc_init(void) { ret_code_t err_code; nrf_drv_saadc_config_t saadc_config; nrf_saadc_channel_config_t channel_config; //Configure SAADC saadc_config.low_power_mode = true; //Enable low power mode. saadc_config.resolution = NRF_SAADC_RESOLUTION_12BIT; //Set SAADC resolution to 12-bit. This will make the SAADC output values from 0 (when input voltage is 0V) to 2^12=4096 (when input voltage is 3.6V for channel gain setting of 1/6). saadc_config.oversample = SAADC_OVERSAMPLE; //Set oversample to 4x. This will make the SAADC output a single averaged value when the SAMPLE task is triggered 4 times. saadc_config.interrupt_priority = APP_IRQ_PRIORITY_LOW; //Set SAADC interrupt to low priority. //Initialize SAADC err_code = nrf_drv_saadc_init(&saadc_config, saadc_callback); //Initialize the SAADC with configuration and callback function. The application must then implement the saadc_callback function, which will be called when SAADC interrupt is triggered APP_ERROR_CHECK(err_code); //Configure SAADC channel channel_config.reference = NRF_SAADC_REFERENCE_INTERNAL; //Set internal reference of fixed 0.6 volts channel_config.gain = NRF_SAADC_GAIN1_6; //Set input gain to 1/6. The maximum SAADC input voltage is then 0.6V/(1/6)=3.6V. The single ended input range is then 0V-3.6V channel_config.acq_time = NRF_SAADC_ACQTIME_10US; //Set acquisition time. Set low acquisition time to enable maximum sampling frequency of 200kHz. Set high acquisition time to allow maximum source resistance up to 800 kohm, see the SAADC electrical specification in the PS. channel_config.mode = NRF_SAADC_MODE_SINGLE_ENDED; //Set SAADC as single ended. This means it will only have the positive pin as input, and the negative pin is shorted to ground (0V) internally. if(SAADC_BURST_MODE) { channel_config.burst = NRF_SAADC_BURST_ENABLED; //Configure burst mode for channel 0. Burst is useful together with oversampling. When triggering the SAMPLE task in burst mode, the SAADC will sample "Oversample" number of times as fast as it can and then output a single averaged value to the RAM buffer. If burst mode is not enabled, the SAMPLE task needs to be triggered "Oversample" number of times to output a single averaged value to the RAM buffer. } channel_config.pin_p = NRF_SAADC_INPUT_AIN0; //Select the input pin for the channel. AIN0 pin maps to physical pin P0.02. channel_config.pin_n = NRF_SAADC_INPUT_DISABLED; //Since the SAADC is single ended, the negative pin is disabled. The negative pin is shorted to ground internally. channel_config.resistor_p = NRF_SAADC_RESISTOR_DISABLED; //Disable pullup resistor on the input pin channel_config.resistor_n = NRF_SAADC_RESISTOR_DISABLED; //Disable pulldown resistor on the input pin //Initialize SAADC channel err_code = nrf_drv_saadc_channel_init(0, &channel_config); //Initialize SAADC channel 0 with the channel configuration APP_ERROR_CHECK(err_code); err_code = nrf_drv_saadc_buffer_convert(m_buffer_pool[0],SAADC_SAMPLES_IN_BUFFER); //Set SAADC buffer 1. The SAADC will start to write to this buffer APP_ERROR_CHECK(err_code); err_code = nrf_drv_saadc_buffer_convert(m_buffer_pool[1],SAADC_SAMPLES_IN_BUFFER); //Set SAADC buffer 2. The SAADC will write to this buffer when buffer 1 is full. This will give the applicaiton time to process data in buffer 1. APP_ERROR_CHECK(err_code); } /** * @brief Function for main application entry. */ int main(void) { LEDS_CONFIGURE(LEDS_MASK); //Configure all leds LEDS_OFF(LEDS_MASK); //Turn off all leds NRF_POWER->DCDCEN = 1; //Enabling the DCDC converter for lower current consumption uint32_t err_code = NRF_LOG_INIT(NULL); APP_ERROR_CHECK(err_code); //Configure Logging. LOGGING is used to show the SAADC sampled result. Default is UART, but RTT can be configured in sdk_config.h NRF_LOG_DEFAULT_BACKENDS_INIT(); NRF_LOG_INFO("SAADC Low Power Example."); lfclk_config(); //Configure low frequency 32kHz clock rtc_config(); //Configure RTC. The RTC will generate periodic interrupts. Requires 32kHz clock to operate. saadc_init(); //Initialize and start SAADC while (1) { if(m_saadc_calibrate == true) { nrf_drv_saadc_abort(); // Abort all ongoing conversions. Calibration cannot be run if SAADC is busy NRF_LOG_INFO("SAADC calibration starting..."); //Print on UART while(nrf_drv_saadc_calibrate_offset() != NRF_SUCCESS); //Trigger calibration task m_saadc_calibrate = false; } while(NRF_LOG_PROCESS() != NRF_SUCCESS); nrf_pwr_mgmt_run(); } } /** @} */ <|start_filename|>nrfx_saadc_simple_low_power_app_timer/main.c<|end_filename|> /** * Copyright (c) 2014 - 2017, Nordic Semiconductor ASA * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form, except as embedded into a Nordic * Semiconductor ASA integrated circuit in a product or a software update for * such product, 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. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * 4. This software, with or without modification, must only be used with a * Nordic Semiconductor ASA integrated circuit. * * 5. Any software provided in binary form under this license must not be reverse * engineered, decompiled, modified and/or disassembled. * * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA 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. * */ /** * Perhipheral: nRF52 SAADC * Compatibility: nRF52832 rev 1/nRF52840 Eng A, nRF5 SDK 13.0.0 * Softdevice used: No softdevice * * This example enables the RTC timer to periodically trigger SAADC sampling. RTC is chosen here instead of * TIMER because it is low power. The example samples on a single input pin, the AIN0, which maps to physical pin P0.02 on the nRF52832 IC. * This SAADC example shows the following features: * - Low Power -> Enabled with initializing SAADC when sampling and uninitializing when sampling is complete. * Low power can only be obtained when UART_PRINTING_ENABLED is not defined and * SAADC_SAMPLES_IN_BUFFER is 1 * - Oversampling -> This reduces SAADC noise level, especially for higher SAADC resolutions, see * https://devzone.nordicsemi.com/question/83938/nrf52832-saadc-sampling/?comment=84340#comment-84340 * Configured with the SAADC_OVERSAMPLE constant. * - BURST mode -> Burst mode can be combined with oversampling, which makes the SAADC sample all oversamples as fast * as it can with one SAMPLE task trigger. Set the SAADC_BURST_MODE constant to enable BURST mode. * - Offset Calibration -> SAADC needs to be occasionally calibrated. The desired calibration interval depends on the * expected temperature change rate, see the nRF52832 PS for more information. The * calibration interval can be adjusted with configuring the SAADC_CALIBRATION_INTERVAL * constant. * The SAADC sample result is printed on UART. To see the UART output, a UART terminal (e.g. Realterm) can be configured on * your PC with the UART configuration set in the uart_config function, which is also described in the saadc example documentation -> * http://infocenter.nordicsemi.com/topic/com.nordic.infocenter.sdk5.v11.0.0/nrf_dev_saadc_example.html?cp=5_0_0_4_5_24 * * Indicators on the nRF52-DK board: * LED1: SAADC Sampling triggered * LED2: SAADC sampling buffer full and event received * LED3: SAADC Offset calibration complete */ #include <stdbool.h> #include <stdint.h> #include <nrfx_saadc.h> #include "nrf_delay.h" #include "app_timer.h" #include "nrf_drv_clock.h" #include "nrf_log.h" #include "nrf_log_ctrl.h" #include "nrf_log_default_backends.h" #define SAADC_CHANNEL_COUNT 1 #define SAADC_SAMPLE_INTERVAL_MS 250 static volatile bool is_ready = true; static nrf_saadc_value_t samples[SAADC_CHANNEL_COUNT]; static nrfx_saadc_channel_t channels[SAADC_CHANNEL_COUNT] = {NRFX_SAADC_DEFAULT_CHANNEL_SE(NRF_SAADC_INPUT_AIN0, 0)}; APP_TIMER_DEF(m_sample_timer_id); /**< Handler for repeated timer used to blink LED 1. */ static void event_handler(nrfx_saadc_evt_t const * p_event) { if (p_event->type == NRFX_SAADC_EVT_DONE) { for(int i = 0; i < p_event->data.done.size; i++) { NRF_LOG_INFO("CH%d: %d", i, p_event->data.done.p_buffer[i]); } is_ready = true; } } /**@brief Timeout handler for the repeated timer. */ static void sample_timer_handler(void * p_context) { if(is_ready) { ret_code_t err_code; err_code = nrfx_saadc_simple_mode_set((1<<0), NRF_SAADC_RESOLUTION_12BIT, NRF_SAADC_OVERSAMPLE_DISABLED, event_handler); APP_ERROR_CHECK(err_code); err_code = nrfx_saadc_buffer_set(samples, SAADC_CHANNEL_COUNT); APP_ERROR_CHECK(err_code); err_code = nrfx_saadc_mode_trigger(); APP_ERROR_CHECK(err_code); is_ready = false; } } static void lfclk_config(void) { ret_code_t err_code = nrf_drv_clock_init(); //Initialize the clock source specified in the nrf_drv_config.h file, i.e. the CLOCK_CONFIG_LF_SRC constant APP_ERROR_CHECK(err_code); nrf_drv_clock_lfclk_request(NULL); } /**@brief Create timers. */ static void timers_init() { lfclk_config(); //Configure low frequency 32kHz clock app_timer_init(); ret_code_t err_code; // Create timers err_code = app_timer_create(&m_sample_timer_id, APP_TIMER_MODE_REPEATED, sample_timer_handler); APP_ERROR_CHECK(err_code); err_code = app_timer_start(m_sample_timer_id, APP_TIMER_TICKS(SAADC_SAMPLE_INTERVAL_MS), NULL); APP_ERROR_CHECK(err_code); } int main(void) { NRF_POWER->DCDCEN = 1; ret_code_t err_code; err_code = NRF_LOG_INIT(NULL); APP_ERROR_CHECK(err_code); //Configure Logging. LOGGING is used to show the SAADC sampled result. Default is UART, but RTT can be configured in sdk_config.h NRF_LOG_DEFAULT_BACKENDS_INIT(); NRF_LOG_INFO("nrfx_saadc_api2 simple SAADC Low Power Example."); err_code = nrfx_saadc_init(NRFX_SAADC_CONFIG_IRQ_PRIORITY); APP_ERROR_CHECK(err_code); err_code = nrfx_saadc_channels_config(channels, SAADC_CHANNEL_COUNT); APP_ERROR_CHECK(err_code); timers_init(); while (1) { while(NRF_LOG_PROCESS() != NRF_SUCCESS); __WFE(); } } /** @} */ <|start_filename|>nrfx_saadc_multi_channel_ppi/main.c<|end_filename|> /** * Copyright (c) 2014 - 2017, Nordic Semiconductor ASA * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form, except as embedded into a Nordic * Semiconductor ASA integrated circuit in a product or a software update for * such product, 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. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * 4. This software, with or without modification, must only be used with a * Nordic Semiconductor ASA integrated circuit. * * 5. Any software provided in binary form under this license must not be reverse * engineered, decompiled, modified and/or disassembled. * * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA 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. * */ #include <stdbool.h> #include <stdint.h> #include <nrfx_saadc.h> #include "nrfx_timer.h" #include "nrfx_ppi.h" #include "nrf_delay.h" #include "nrf_log.h" #include "nrf_log_ctrl.h" #include "nrf_log_default_backends.h" #define ADC_CHANNELS_IN_USE 6 // Note: If changed, the logging during the NRFX_SAADC_EVT_DONE must be updated. #define SAADC_BUF_SIZE ADC_CHANNELS_IN_USE #define SAADC_BUF_COUNT 2 #define SAADC_SAMPLE_FREQUENCY 8000 static nrf_saadc_value_t samples[SAADC_BUF_COUNT][SAADC_BUF_SIZE]; static const nrfx_timer_t m_sample_timer = NRFX_TIMER_INSTANCE(1); static nrf_ppi_channel_t m_timer_saadc_ppi_channel; static nrf_ppi_channel_t m_saadc_internal_ppi_channel; static const uint32_t saadc_sampling_rate = 1000; // milliseconds (ms) static const nrf_saadc_input_t ANALOG_INPUT_MAP[NRF_SAADC_CHANNEL_COUNT] = { NRF_SAADC_INPUT_AIN0, NRF_SAADC_INPUT_AIN1, NRF_SAADC_INPUT_AIN2, NRF_SAADC_INPUT_AIN3, NRF_SAADC_INPUT_AIN4, NRF_SAADC_INPUT_AIN5, NRF_SAADC_INPUT_AIN6, NRF_SAADC_INPUT_AIN7}; // Simple function to provide an index to the next input buffer // Will simply alernate between 0 and 1 when SAADC_BUF_COUNT is 2 static uint32_t next_free_buf_index(void) { static uint32_t buffer_index = -1; buffer_index = (buffer_index + 1) % SAADC_BUF_COUNT; return buffer_index; } static void timer_handler(nrf_timer_event_t event_type, void * p_context) { } static void event_handler(nrfx_saadc_evt_t const * p_event) { ret_code_t err_code; switch (p_event->type) { case NRFX_SAADC_EVT_DONE: NRF_LOG_INFO("ADC Values: %6d %6d %6d %6d %6d %6d", p_event->data.done.p_buffer[0], p_event->data.done.p_buffer[1], p_event->data.done.p_buffer[2], p_event->data.done.p_buffer[3], p_event->data.done.p_buffer[4], p_event->data.done.p_buffer[5]); break; case NRFX_SAADC_EVT_BUF_REQ: // Set up the next available buffer err_code = nrfx_saadc_buffer_set(&samples[next_free_buf_index()][0], SAADC_BUF_SIZE); APP_ERROR_CHECK(err_code); break; default: NRF_LOG_INFO("SAADC evt %d", p_event->type); break; } } static void timer_init(void) { nrfx_err_t err_code; nrfx_timer_config_t timer_config = NRFX_TIMER_DEFAULT_CONFIG; timer_config.frequency = NRF_TIMER_FREQ_31250Hz; err_code = nrfx_timer_init(&m_sample_timer, &timer_config, timer_handler); APP_ERROR_CHECK(err_code); nrfx_timer_extended_compare(&m_sample_timer, NRF_TIMER_CC_CHANNEL0, nrfx_timer_ms_to_ticks(&m_sample_timer, saadc_sampling_rate), NRF_TIMER_SHORT_COMPARE0_CLEAR_MASK, false); nrfx_timer_resume(&m_sample_timer); } static void ppi_init(void) { // Trigger task sample from timer nrfx_err_t err_code = nrfx_ppi_channel_alloc(&m_timer_saadc_ppi_channel); APP_ERROR_CHECK(err_code); err_code = nrfx_ppi_channel_assign(m_timer_saadc_ppi_channel, nrfx_timer_event_address_get(&m_sample_timer, NRF_TIMER_EVENT_COMPARE0), nrf_saadc_task_address_get(NRF_SAADC_TASK_SAMPLE)); APP_ERROR_CHECK(err_code); err_code = nrfx_ppi_channel_enable(m_timer_saadc_ppi_channel); APP_ERROR_CHECK(err_code); } static void adc_configure(void) { ret_code_t err_code; nrfx_saadc_adv_config_t saadc_adv_config = NRFX_SAADC_DEFAULT_ADV_CONFIG; saadc_adv_config.internal_timer_cc = 0; saadc_adv_config.start_on_end = true; err_code = nrfx_saadc_init(NRFX_SAADC_CONFIG_IRQ_PRIORITY); APP_ERROR_CHECK(err_code); static nrfx_saadc_channel_t channel_configs[ADC_CHANNELS_IN_USE]; uint8_t channel_mask = 0; for(int i = 0; i < ADC_CHANNELS_IN_USE; i++) { nrf_saadc_input_t pin = ANALOG_INPUT_MAP[i]; // Apply default config to each channel nrfx_saadc_channel_t config = NRFX_SAADC_DEFAULT_CHANNEL_SE(pin, i); // Replace some parameters in default config config.channel_config.reference = NRF_SAADC_REFERENCE_VDD4; config.channel_config.gain = NRF_SAADC_GAIN1_4; // Copy to list of channel configs memcpy(&channel_configs[i], &config, sizeof(config)); // Update channel mask channel_mask |= 1 << i; } err_code = nrfx_saadc_channels_config(channel_configs, ADC_CHANNELS_IN_USE); APP_ERROR_CHECK(err_code); err_code = nrfx_saadc_advanced_mode_set(channel_mask, NRF_SAADC_RESOLUTION_14BIT, &saadc_adv_config, event_handler); APP_ERROR_CHECK(err_code); // Configure two buffers to ensure double buffering of samples, to avoid data loss when the sampling frequency is high err_code = nrfx_saadc_buffer_set(&samples[next_free_buf_index()][0], SAADC_BUF_SIZE); APP_ERROR_CHECK(err_code); err_code = nrfx_saadc_buffer_set(&samples[next_free_buf_index()][0], SAADC_BUF_SIZE); APP_ERROR_CHECK(err_code); err_code = nrfx_saadc_mode_trigger(); APP_ERROR_CHECK(err_code); } int main(void) { ret_code_t err_code; // Configure Logging. LOGGING is used to show the SAADC sampled result. err_code = NRF_LOG_INIT(NULL); APP_ERROR_CHECK(err_code); NRF_LOG_DEFAULT_BACKENDS_INIT(); NRF_LOG_INFO("nrfx_saadc_api2 simple SAADC Continuous Sampling Example using timer and PPI."); adc_configure(); ppi_init(); timer_init(); while (1) { while(NRF_LOG_PROCESS() != NRF_SUCCESS); __WFE(); } }
NordicSemiconductor/nRF52-ADC-examples-
<|start_filename|>src/Scheduler.cpp<|end_filename|> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "Scheduler.hpp" #ifdef _WIN32 #include <assert.h> #include <strsafe.h> #else #include <assert.h> #include <pthread.h> #include <sched.h> #endif namespace BackgroundTaskScheduler { //------------------------------------------------------------------------------------------------- Scheduler::Scheduler() { m_QueuedEvents.emplace_back(); // throw( bad_alloc ) m_QueuedEventsPseudoEnd = m_QueuedEvents.begin(); } //------------------------------------------------------------------------------------------------- void Scheduler::QueueTask(Task task) { bool bCancelTask = false; { std::lock_guard<std::mutex> lock(m_Lock); if (m_CurrentMode.NumThreads == 0 || m_bShutdown) { bCancelTask = true; } else { m_Tasks.push_back(QueuedTask{ task, m_QueuedEventsPseudoEnd }); // throw( bad_alloc ) } } if (bCancelTask) { if (task.m_Cancel) { task.m_Cancel(task.m_pContext); } } else { m_CV.notify_one(); } } inline auto PriorityToPlatformPriority(Priority p) { switch (p) { default: #ifdef _WIN32 case Priority::Normal: return THREAD_PRIORITY_NORMAL; case Priority::Idle: return THREAD_PRIORITY_IDLE; #else case Priority::Normal: return SCHED_OTHER; case Priority::Idle: return SCHED_IDLE; #endif } } inline void SetPlatformThreadPriority(std::thread::native_handle_type t, int p) { #ifdef _WIN32 SetThreadPriority(t, p); #else pthread_setschedprio(t, p); #endif } //------------------------------------------------------------------------------------------------- void Scheduler::SetSchedulingModeImpl(SchedulingMode mode, std::unique_lock<std::mutex>& lock) { assert(lock.owns_lock()); std::vector<std::thread> ThreadsToWaitOn; SchedulingMode previousMode = m_EffectiveMode; m_EffectiveMode = mode; size_t NewNumThreads = mode.NumThreads; size_t PreviousNumThreads = m_Threads.size(); // Adjust number of threads if (NewNumThreads > PreviousNumThreads) { m_Threads.resize(NewNumThreads); // throw( bad_alloc ) for (auto i = PreviousNumThreads; i < NewNumThreads; ++i) { m_Threads[i] = std::thread([this, i]() { TaskThread((int)i); }); // throw (...) } } else if (NewNumThreads < PreviousNumThreads) { ThreadsToWaitOn.reserve(PreviousNumThreads - NewNumThreads); // throw( bad_alloc ) for (size_t i = NewNumThreads; i < PreviousNumThreads; ++i) { if (m_Threads[i].joinable()) { if (m_Threads[i].get_id() == std::this_thread::get_id()) { m_ExitingThreads.push_back(std::move(m_Threads[i])); // throw( bad_alloc ) } else { ThreadsToWaitOn.emplace_back(std::move(m_Threads[i])); } } } m_Threads.resize(NewNumThreads); } // Set priorities auto NewPriority = PriorityToPlatformPriority(mode.ThreadPriority); auto OldPriority = PriorityToPlatformPriority(previousMode.ThreadPriority); for (size_t i = 0; i < NewNumThreads; ++i) { auto ThisThreadOldPriority = (i < PreviousNumThreads) ? OldPriority : PriorityToPlatformPriority(Priority::Normal); if (NewPriority != ThisThreadOldPriority) { SetPlatformThreadPriority(m_Threads[i].native_handle(), NewPriority); } } // If we're increasing priority but lowering thread count, increase priority of threads we're going to wait on. if (NewPriority > OldPriority) { for (auto& thread : ThreadsToWaitOn) { SetPlatformThreadPriority(thread.native_handle(), NewPriority); } } // Wait for threads lock.unlock(); if (!ThreadsToWaitOn.empty()) { m_CV.notify_all(); for (auto& thread : ThreadsToWaitOn) { thread.join(); } } } //------------------------------------------------------------------------------------------------- void Scheduler::SetSchedulingMode(SchedulingMode mode) { std::unique_lock<std::mutex> lock(m_Lock); if (m_bShutdown) { // If we're shut down, ignore requests to spin back up. return; } if (mode == m_CurrentMode) { return; } if (m_CurrentMode == m_EffectiveMode && (mode > m_EffectiveMode || IsSchedulerIdle(lock))) { // Increasing number or priority of threads OR there's nothing currently executing - do it immediately m_CurrentMode = mode; SetSchedulingModeImpl(mode, lock); // Releases lock } else { // Decreasing number or priority of threads, or there's already a pending mode // change, so just queue the mode change if (m_CurrentMode.NumThreads == 0) { // There's a task queued which will drop the mode down to no threads // Since we'll refuse to queue tasks when in this mode, this task should // be the last one - replace it with our new task m_Tasks.pop_back(); } QueueSetSchedulingModeTask(mode, lock); lock.unlock(); m_CV.notify_one(); } } //------------------------------------------------------------------------------------------------- void Scheduler::SignalEventOnCompletionOfCurrentTasks(XPlatHelpers::Event hEvent, SchedulingMode modeAfterSignal) { { std::unique_lock<std::mutex> lock(m_Lock); // Tasks won't execute - just set the event if (m_EffectiveMode.NumThreads == 0 || IsSchedulerIdle(lock)) { XPlatHelpers::SetEvent(hEvent); m_CurrentMode = modeAfterSignal; SetSchedulingModeImpl(modeAfterSignal, lock); return; } // Update the entry that existing tasks will signal QueuedEventSignal& signal = m_QueuedEvents.back(); signal.m_RefCount = (long)(m_Tasks.size() + m_TasksInProgress); signal.m_Event = XPlatHelpers::unique_event(hEvent, XPlatHelpers::unique_event::copy_tag{}); // Add a new entry that new tasks will reference m_QueuedEvents.emplace_back(); ++m_QueuedEventsPseudoEnd; // If we want to end up in a different mode, then queue a task to put us there if (modeAfterSignal != m_CurrentMode) { QueueSetSchedulingModeTask(modeAfterSignal, lock); } } m_CV.notify_one(); } //------------------------------------------------------------------------------------------------- void Scheduler::TaskThread(int ThreadID) noexcept { { #if _WIN32 wchar_t ThreadName[64]; if (SUCCEEDED(StringCchPrintfW(ThreadName, _countof(ThreadName), L"D3D Background Thread %d", ThreadID))) { SetThreadDescription(GetCurrentThread(), ThreadName); } #endif } std::unique_lock<std::mutex> lock(m_Lock); while (true) { QueuedTask task = {}; while (true) { if (ThreadID >= (int)m_EffectiveMode.NumThreads) { // This thread is done return; } if (!m_Tasks.empty()) { // Pop the front task and exit the loop, this thread will now do work task = m_Tasks.front(); m_Tasks.pop_front(); ++m_TasksInProgress; break; } // Not supposed to exit yet, and nothing to do - wait for a notification m_CV.wait(lock); } // Do the work lock.unlock(); task.m_Callback(task.m_pContext); lock.lock(); RetireTask(task, lock); --m_TasksInProgress; } } //------------------------------------------------------------------------------------------------- void Scheduler::SetSchedulingModeTask(SchedulingMode mode) noexcept { std::unique_lock<std::mutex> lock(m_Lock); SetSchedulingModeImpl(mode, lock); // Releases lock } struct SetSchedulingModeTaskContext { Scheduler* pThis; SchedulingMode mode; }; //------------------------------------------------------------------------------------------------- void __stdcall Scheduler::SetSchedulingModeTaskStatic(void* pContext) { std::unique_ptr<SetSchedulingModeTaskContext> spContext(static_cast<SetSchedulingModeTaskContext*>(pContext)); spContext->pThis->SetSchedulingModeTask(spContext->mode); } //------------------------------------------------------------------------------------------------- void Scheduler::QueueSetSchedulingModeTask(SchedulingMode mode, std::unique_lock<std::mutex> const& lock) { assert(lock.owns_lock()); UNREFERENCED_PARAMETER(lock); m_CurrentMode = mode; std::unique_ptr<SetSchedulingModeTaskContext> spContext(new SetSchedulingModeTaskContext{ this, mode }); // throw m_Tasks.push_back(QueuedTask{ Task{ SetSchedulingModeTaskStatic, mode.NumThreads == 0 ? SetSchedulingModeTaskStatic : nullptr, spContext.get() }, m_QueuedEventsPseudoEnd }); // throw spContext.release(); } //------------------------------------------------------------------------------------------------- void Scheduler::CancelExistingTasks() noexcept { decltype(m_Tasks) TasksToCancel; { std::lock_guard<std::mutex> lock(m_Lock); std::swap(TasksToCancel, m_Tasks); } for (auto& task : TasksToCancel) { if (task.m_Cancel) { task.m_Cancel(task.m_pContext); } } std::unique_lock<std::mutex> lock(m_Lock); for (auto& task : TasksToCancel) { RetireTask(task, lock); } } //------------------------------------------------------------------------------------------------- void Scheduler::Shutdown() noexcept { { std::lock_guard<std::mutex> lock(m_Lock); m_bShutdown = true; } CancelExistingTasks(); std::unique_lock<std::mutex> lock(m_Lock); m_CurrentMode = { 0, Priority::Idle }; SetSchedulingModeImpl(m_CurrentMode, lock); // Releases lock assert(m_Threads.empty()); // The SetSchedulingMode call either waited for all threads to exit, or a thread processed // a task to wait for all other threads to exit, and then it will exit itself. // In the latter case, it would've added itself to this list. We need to make sure it's // actually exited before allowing this object to be destroyed, so wait for that now. // // It's safe to read this without a lock, because we know the only threads still running // won't modify this - they're already past the point where that's possible. for (auto& t : m_ExitingThreads) { t.join(); } } //------------------------------------------------------------------------------------------------- void Scheduler::RetireTask(QueuedTask const& task, std::unique_lock<std::mutex> const& lock) noexcept { assert(lock.owns_lock()); UNREFERENCED_PARAMETER(lock); for (auto iter = task.m_QueuedEventsAtTimeOfTaskSubmission; iter->m_Event;) { int refcount = --iter->m_RefCount; if (refcount == 0) { iter->m_Event.set(); iter = m_QueuedEvents.erase(iter); continue; } ++iter; } assert(m_QueuedEvents.size() > 0); } } <|start_filename|>src/device.cpp<|end_filename|> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "device.hpp" #include "task.hpp" #include "queue.hpp" #include <wil/resource.h> #include <directx/d3d12compatibility.h> extern CL_API_ENTRY cl_int CL_API_CALL clGetDeviceIDs(cl_platform_id platform, cl_device_type device_type, cl_uint num_entries, cl_device_id * devices, cl_uint * num_devices) CL_API_SUFFIX__VERSION_1_0 { if (!platform) { return CL_INVALID_PLATFORM; } if (num_entries && !devices) { return CL_INVALID_VALUE; } try { auto pPlatform = Platform::CastFrom(platform); cl_uint NumDevices = 0; if ((device_type & CL_DEVICE_TYPE_GPU) || device_type == CL_DEVICE_TYPE_DEFAULT) { NumDevices += pPlatform->GetNumDevices(); } if (num_devices) { *num_devices = NumDevices; } for (cl_uint i = 0; i < num_entries && i < NumDevices; ++i) { devices[i] = pPlatform->GetDevice(i); } } catch (std::bad_alloc&) { return CL_OUT_OF_HOST_MEMORY; } catch (std::exception&) { return CL_OUT_OF_RESOURCES; } catch (_com_error&) { return CL_OUT_OF_RESOURCES; } return CL_SUCCESS; } extern CL_API_ENTRY cl_int CL_API_CALL clGetDeviceInfo(cl_device_id device, cl_device_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0 { if (!device) { return CL_INVALID_DEVICE; } auto RetValue = [&](auto&& param) { return CopyOutParameter(param, param_value_size, param_value, param_value_size_ret); }; auto pDevice = Device::CastFrom(device); auto ImageRetValue = [&](auto&& GPUValue, auto&& MCDMValue) { return RetValue(pDevice->IsMCDM() ? MCDMValue : GPUValue); }; auto ImageRetValueOrZero = [&](auto GPUValue) { return RetValue(pDevice->IsMCDM() ? (decltype(GPUValue))0 : GPUValue); }; try { switch (param_name) { case CL_DEVICE_TYPE: return RetValue((cl_device_type)CL_DEVICE_TYPE_GPU); case CL_DEVICE_VENDOR_ID: return RetValue(pDevice->GetHardwareIds().vendorID); case CL_DEVICE_MAX_COMPUTE_UNITS: return RetValue((cl_uint)1); case CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS: return RetValue((cl_uint)3); case CL_DEVICE_MAX_WORK_ITEM_SIZES: { constexpr size_t WorkItemSizes[3] = { D3D12_CS_THREAD_GROUP_MAX_X, D3D12_CS_THREAD_GROUP_MAX_Y, D3D12_CS_THREAD_GROUP_MAX_Z }; return RetValue(WorkItemSizes); } case CL_DEVICE_MAX_WORK_GROUP_SIZE: return RetValue((size_t)D3D12_CS_THREAD_GROUP_MAX_THREADS_PER_GROUP); case CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR: // Fallthrough case CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR: return RetValue((cl_uint)16); case CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF: // Fallthrough case CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF: // Fallthrough case CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT: // Fallthrough case CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT: return RetValue((cl_uint)8); case CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT: // Fallthrough case CL_DEVICE_NATIVE_VECTOR_WIDTH_INT: // Fallthrough case CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT: // Fallthrough case CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT: return RetValue((cl_uint)4); case CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG: // Fallthrough case CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG: // Fallthrough case CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE: // Fallthrough case CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE: return RetValue((cl_uint)2); case CL_DEVICE_MAX_CLOCK_FREQUENCY: return RetValue((cl_uint)12); case CL_DEVICE_ADDRESS_BITS: return RetValue(64u); case CL_DEVICE_MAX_MEM_ALLOC_SIZE: return RetValue(min((size_t)pDevice->GetGlobalMemSize() / 4, (size_t)1024 * 1024 * 1024)); case CL_DEVICE_IMAGE_SUPPORT: return ImageRetValue((cl_bool)CL_TRUE, (cl_bool)CL_FALSE); case CL_DEVICE_MAX_READ_IMAGE_ARGS: /*SRVs*/ return ImageRetValueOrZero((cl_uint)128); case CL_DEVICE_MAX_WRITE_IMAGE_ARGS: /*UAVs*/return ImageRetValueOrZero((cl_uint)64); case CL_DEVICE_MAX_READ_WRITE_IMAGE_ARGS: /*Typed UAVs*/ return ImageRetValueOrZero((cl_uint)(pDevice->SupportsTypedUAVLoad() ? 64 : 0)); case CL_DEVICE_IL_VERSION: return RetValue("SPIR-V_1.0"); case CL_DEVICE_ILS_WITH_VERSION: return RetValue(nullptr); case CL_DEVICE_IMAGE2D_MAX_WIDTH: return ImageRetValueOrZero((size_t)D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); case CL_DEVICE_IMAGE2D_MAX_HEIGHT: return ImageRetValueOrZero((size_t)D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION); case CL_DEVICE_IMAGE3D_MAX_WIDTH: return ImageRetValueOrZero((size_t)D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); case CL_DEVICE_IMAGE3D_MAX_HEIGHT: return ImageRetValueOrZero((size_t)D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); case CL_DEVICE_IMAGE3D_MAX_DEPTH: return ImageRetValueOrZero((size_t)D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION); case CL_DEVICE_IMAGE_MAX_BUFFER_SIZE: return ImageRetValueOrZero((size_t)(2 << D3D12_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP)); case CL_DEVICE_IMAGE_MAX_ARRAY_SIZE: return ImageRetValueOrZero((size_t)D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION); case CL_DEVICE_MAX_SAMPLERS: return ImageRetValueOrZero((cl_uint)D3D12_COMMONSHADER_SAMPLER_SLOT_COUNT); case CL_DEVICE_IMAGE_PITCH_ALIGNMENT: return ImageRetValueOrZero((cl_uint)0); case CL_DEVICE_IMAGE_BASE_ADDRESS_ALIGNMENT: return RetValue((cl_uint)0); case CL_DEVICE_MAX_PARAMETER_SIZE: return RetValue((size_t)1024); case CL_DEVICE_MEM_BASE_ADDR_ALIGN: return RetValue((cl_uint)D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT * 8); case CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE: return RetValue((cl_int)(64 * 16)); // sizeof(long16) case CL_DEVICE_SINGLE_FP_CONFIG: // Fallthrough { constexpr cl_device_fp_config fp_config = CL_FP_FMA | CL_FP_ROUND_TO_NEAREST | CL_FP_INF_NAN; return RetValue(fp_config); } case CL_DEVICE_DOUBLE_FP_CONFIG: return RetValue((cl_device_fp_config)0); case CL_DEVICE_GLOBAL_MEM_CACHE_TYPE: return RetValue((cl_device_mem_cache_type)CL_NONE); case CL_DEVICE_GLOBAL_MEM_CACHE_SIZE: return RetValue((cl_ulong)0); case CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE: return RetValue((cl_uint)0); case CL_DEVICE_GLOBAL_MEM_SIZE: return RetValue(pDevice->GetGlobalMemSize()); case CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE: return RetValue((cl_ulong)(D3D12_REQ_CONSTANT_BUFFER_ELEMENT_COUNT * 16)); case CL_DEVICE_MAX_CONSTANT_ARGS: return RetValue((cl_uint)15); case CL_DEVICE_MAX_GLOBAL_VARIABLE_SIZE: return RetValue((size_t)0); case CL_DEVICE_GLOBAL_VARIABLE_PREFERRED_TOTAL_SIZE: return RetValue((size_t)0); case CL_DEVICE_LOCAL_MEM_TYPE: return RetValue((cl_device_local_mem_type)CL_LOCAL); case CL_DEVICE_LOCAL_MEM_SIZE: return RetValue((cl_ulong)(D3D12_CS_TGSM_REGISTER_COUNT * sizeof(UINT))); case CL_DEVICE_ERROR_CORRECTION_SUPPORT: return RetValue((cl_bool)CL_FALSE); case CL_DEVICE_PROFILING_TIMER_RESOLUTION: return RetValue((size_t)80); case CL_DEVICE_ENDIAN_LITTLE: return RetValue((cl_bool)CL_TRUE); case CL_DEVICE_AVAILABLE: return RetValue(pDevice->IsAvailable()); case CL_DEVICE_COMPILER_AVAILABLE: return RetValue((cl_bool)CL_TRUE); case CL_DEVICE_LINKER_AVAILABLE: return RetValue((cl_bool)CL_TRUE); case CL_DEVICE_EXECUTION_CAPABILITIES: return RetValue((cl_device_exec_capabilities)CL_EXEC_KERNEL); case CL_DEVICE_QUEUE_ON_HOST_PROPERTIES: return RetValue( (cl_command_queue_properties)(CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE | CL_QUEUE_PROFILING_ENABLE)); case CL_DEVICE_QUEUE_ON_DEVICE_PROPERTIES: return RetValue((cl_command_queue_properties)0); case CL_DEVICE_QUEUE_ON_DEVICE_PREFERRED_SIZE: return RetValue((cl_uint)0); case CL_DEVICE_QUEUE_ON_DEVICE_MAX_SIZE: return RetValue((cl_uint)0); case CL_DEVICE_MAX_ON_DEVICE_QUEUES: return RetValue((cl_uint)0); case CL_DEVICE_MAX_ON_DEVICE_EVENTS: return RetValue((cl_uint)0); case CL_DEVICE_BUILT_IN_KERNELS: return RetValue(""); case CL_DEVICE_BUILT_IN_KERNELS_WITH_VERSION: return RetValue(nullptr); case CL_DEVICE_PLATFORM: return RetValue(static_cast<cl_platform_id>(&pDevice->m_Parent.get())); case CL_DEVICE_NAME: return RetValue(pDevice->GetDeviceName().c_str()); case CL_DEVICE_VENDOR: return RetValue(pDevice->m_Parent->Vendor); case CL_DRIVER_VERSION: return RetValue("1.1.0"); case CL_DEVICE_PROFILE: return RetValue(pDevice->m_Parent->Profile); case CL_DEVICE_VERSION: return RetValue(pDevice->m_Parent->Version); case CL_DEVICE_OPENCL_C_VERSION: return RetValue("OpenCL C 1.2 "); case CL_DEVICE_OPENCL_C_ALL_VERSIONS: { constexpr cl_name_version versions[] = { { CL_MAKE_VERSION(1, 0, 0), "OpenCL C" }, { CL_MAKE_VERSION(1, 1, 0), "OpenCL C" }, { CL_MAKE_VERSION(1, 2, 0), "OpenCL C" }, #ifdef CLON12_SUPPORT_3_0 { CL_MAKE_VERSION(3, 0, 0), "OpenCL C" }, #endif }; return RetValue(versions); } case CL_DEVICE_EXTENSIONS: return RetValue("cl_khr_global_int32_base_atomics " "cl_khr_global_int32_extended_atomics " "cl_khr_local_int32_base_atomics " "cl_khr_local_int32_extended_atomics " "cl_khr_byte_addressable_store " "cl_khr_il_program " ); case CL_DEVICE_PRINTF_BUFFER_SIZE: return RetValue((size_t)1024 * 1024); case CL_DEVICE_PREFERRED_INTEROP_USER_SYNC: return RetValue((cl_bool)CL_TRUE); case CL_DEVICE_PARENT_DEVICE: return RetValue((cl_device_id)nullptr); case CL_DEVICE_PARTITION_MAX_SUB_DEVICES: return RetValue((cl_uint)0); case CL_DEVICE_PARTITION_PROPERTIES: return RetValue((cl_uint)0); case CL_DEVICE_PARTITION_AFFINITY_DOMAIN: return RetValue((cl_device_affinity_domain)0); case CL_DEVICE_PARTITION_TYPE: return CL_INVALID_VALUE; case CL_DEVICE_REFERENCE_COUNT: return RetValue((cl_uint)1); case CL_DEVICE_SVM_CAPABILITIES: return RetValue((cl_device_svm_capabilities)0); case CL_DEVICE_PREFERRED_PLATFORM_ATOMIC_ALIGNMENT: return RetValue((cl_uint)0); case CL_DEVICE_PREFERRED_GLOBAL_ATOMIC_ALIGNMENT: return RetValue((cl_uint)0); case CL_DEVICE_PREFERRED_LOCAL_ATOMIC_ALIGNMENT: return RetValue((cl_uint)0); case CL_DEVICE_MAX_NUM_SUB_GROUPS: return RetValue((cl_uint)1); case CL_DEVICE_SUB_GROUP_INDEPENDENT_FORWARD_PROGRESS: return RetValue((cl_bool)CL_FALSE); case CL_DEVICE_HOST_UNIFIED_MEMORY: return RetValue((cl_bool)pDevice->IsUMA()); case CL_DEVICE_MAX_PIPE_ARGS: return RetValue((cl_uint)0); case CL_DEVICE_PIPE_MAX_ACTIVE_RESERVATIONS: return RetValue((cl_uint)0); case CL_DEVICE_PIPE_MAX_PACKET_SIZE: return RetValue((cl_uint)0); case CL_DEVICE_ATOMIC_MEMORY_CAPABILITIES: return RetValue((cl_device_atomic_capabilities)( CL_DEVICE_ATOMIC_ORDER_RELAXED | CL_DEVICE_ATOMIC_ORDER_ACQ_REL | CL_DEVICE_ATOMIC_ORDER_SEQ_CST | CL_DEVICE_ATOMIC_SCOPE_WORK_ITEM | CL_DEVICE_ATOMIC_SCOPE_WORK_GROUP | CL_DEVICE_ATOMIC_SCOPE_DEVICE)); case CL_DEVICE_ATOMIC_FENCE_CAPABILITIES: return RetValue((cl_device_atomic_capabilities)( CL_DEVICE_ATOMIC_ORDER_RELAXED | CL_DEVICE_ATOMIC_ORDER_ACQ_REL | CL_DEVICE_ATOMIC_ORDER_SEQ_CST | CL_DEVICE_ATOMIC_SCOPE_WORK_ITEM | CL_DEVICE_ATOMIC_SCOPE_WORK_GROUP | CL_DEVICE_ATOMIC_SCOPE_DEVICE)); case CL_DEVICE_NON_UNIFORM_WORK_GROUP_SUPPORT: return RetValue((cl_bool)CL_FALSE); case CL_DEVICE_WORK_GROUP_COLLECTIVE_FUNCTIONS_SUPPORT: return RetValue((cl_bool)CL_FALSE); case CL_DEVICE_GENERIC_ADDRESS_SPACE_SUPPORT: return RetValue((cl_bool)CL_FALSE); case CL_DEVICE_DEVICE_ENQUEUE_CAPABILITIES: return RetValue((cl_device_device_enqueue_capabilities)0); case CL_DEVICE_PIPE_SUPPORT: return RetValue((cl_bool)CL_FALSE); case CL_DEVICE_PREFERRED_WORK_GROUP_SIZE_MULTIPLE: return RetValue((size_t)64); case CL_DEVICE_LATEST_CONFORMANCE_VERSION_PASSED: return RetValue(""); } return CL_INVALID_VALUE; } catch (std::bad_alloc&) { return CL_OUT_OF_HOST_MEMORY; } } Device::Device(Platform& parent, IDXCoreAdapter* pAdapter) : CLChildBase(parent) , m_spAdapter(pAdapter) { pAdapter->GetProperty(DXCoreAdapterProperty::HardwareID, sizeof(m_HWIDs), &m_HWIDs); } Device::~Device() = default; void Device::InitD3D() { std::lock_guard Lock(m_InitLock); ++m_ContextCount; if (m_ImmCtx) { return; } g_Platform->DeviceInit(); THROW_IF_FAILED(D3D12CreateDevice(m_spAdapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&m_spDevice))); //THROW_IF_FAILED(D3D12CreateDevice(m_spAdapter.Get(), D3D_FEATURE_LEVEL_1_0_CORE, IID_PPV_ARGS(&m_spDevice))); CacheCaps(Lock); m_Callbacks.m_pfnPostSubmit = []() {}; ImmCtx::CreationArgs Args = {}; Args.CreatesAndDestroysAreMultithreaded = true; Args.RenamingIsMultithreaded = true; Args.UseResidencyManagement = true; Args.UseThreadpoolForPSOCreates = true; Args.CreatorID = __uuidof(OpenCLOn12CreatorID); m_ImmCtx.emplace(0, m_D3D12Options, m_spDevice.Get(), nullptr, m_Callbacks, 0, Args); BackgroundTaskScheduler::SchedulingMode mode{ 1u, BackgroundTaskScheduler::Priority::Normal }; m_CompletionScheduler.SetSchedulingMode(mode); auto commandQueue = m_ImmCtx->GetCommandQueue(D3D12TranslationLayer::COMMAND_LIST_TYPE::GRAPHICS); (void)commandQueue->GetTimestampFrequency(&m_TimestampFrequency); UINT64 CPUTimestamp = 0, GPUTimestamp = 0; (void)commandQueue->GetClockCalibration(&GPUTimestamp, &CPUTimestamp); LARGE_INTEGER QPCFrequency = {}; QueryPerformanceFrequency(&QPCFrequency); m_GPUToQPCTimestampOffset = (INT64)Task::TimestampToNanoseconds(CPUTimestamp, QPCFrequency.QuadPart) - (INT64)Task::TimestampToNanoseconds(GPUTimestamp, m_TimestampFrequency); m_RecordingSubmission.reset(new Submission); m_ShaderCache.emplace(GetDevice()); } void Device::ReleaseD3D() { std::lock_guard Lock(m_InitLock); if (--m_ContextCount != 0) return; g_Platform->DeviceUninit(); m_ImmCtx.reset(); BackgroundTaskScheduler::SchedulingMode mode{ 0u, BackgroundTaskScheduler::Priority::Normal }; m_CompletionScheduler.SetSchedulingMode(mode); m_RecordingSubmission.reset(); m_spDevice.Reset(); m_ShaderCache.reset(); } cl_bool Device::IsAvailable() const noexcept { bool driverUpdateInProgress = true; return SUCCEEDED(m_spAdapter->QueryState(DXCoreAdapterState::IsDriverUpdateInProgress, 0, nullptr, sizeof(driverUpdateInProgress), &driverUpdateInProgress)) && !driverUpdateInProgress; } cl_ulong Device::GetGlobalMemSize() { // Just report one segment's worth of memory, depending on whether we're UMA or not. if (IsUMA()) { uint64_t sharedMemory = 0; m_spAdapter->GetProperty(DXCoreAdapterProperty::SharedSystemMemory, sizeof(sharedMemory), &sharedMemory); return sharedMemory; } else { uint64_t localMemory = 0; m_spAdapter->GetProperty(DXCoreAdapterProperty::DedicatedAdapterMemory, sizeof(localMemory), &localMemory); return localMemory; } } DXCoreHardwareID const& Device::GetHardwareIds() const noexcept { return m_HWIDs; } bool Device::IsMCDM() const noexcept { return !m_spAdapter->IsAttributeSupported(DXCORE_ADAPTER_ATTRIBUTE_D3D12_GRAPHICS); } bool Device::IsUMA() { { std::lock_guard Lock(m_InitLock); CacheCaps(Lock); } return m_Architecture.UMA; } bool Device::SupportsInt16() { { std::lock_guard Lock(m_InitLock); CacheCaps(Lock); } return m_D3D12Options4.Native16BitShaderOpsSupported; } bool Device::SupportsTypedUAVLoad() { { std::lock_guard Lock(m_InitLock); CacheCaps(Lock); } return m_D3D12Options.TypedUAVLoadAdditionalFormats; } ShaderCache& Device::GetShaderCache() { return *m_ShaderCache; } std::string Device::GetDeviceName() const { std::string name; size_t nameSize = 0; if (SUCCEEDED(m_spAdapter->GetPropertySize(DXCoreAdapterProperty::DriverDescription, &nameSize))) { name.resize(nameSize); m_spAdapter->GetProperty(DXCoreAdapterProperty::DriverDescription, nameSize, name.data()); } return name; } void Device::SubmitTask(Task* task, TaskPoolLock const& lock) { assert(task->m_CommandType != CL_COMMAND_USER); // User commands are treated as 'submitted' when they're created task->Submit(); if (task->m_TasksToWaitOn.empty()) { ReadyTask(task, lock); } else { for (auto& dependency : task->m_TasksToWaitOn) { if (dependency->GetState() == Task::State::Queued) { // It's impossible to have a task with a dependency on a task later on in the same queue. assert(dependency->m_CommandQueue != task->m_CommandQueue); // Ensure that any dependencies are also submitted. Notes: // - For recursive flushes, don't flush the overall device, we'll do it when we're done with all queues // - This might recurse back to the same queue... this is safe, because this task has already been removed // from its own queue and had its state updated, so recursive flushes will pick up where we left off, // and unwinding back will see that the flush has already been finished. dependency->m_CommandQueue->Flush(lock, /* flushDevice */ false); } } } } void Device::ReadyTask(Task* task, TaskPoolLock const& lock) { assert(task->m_TasksToWaitOn.empty()); task->MigrateResources(); if (!task->m_TasksToWaitOn.empty()) { // Need to wait for resources to migrate. // Once the migration is done, this task will be readied for real return; } m_RecordingSubmission->push_back(task); task->Ready(lock); } void Device::Flush(TaskPoolLock const&) { if (m_RecordingSubmission->empty()) { return; } struct ExecutionHandler { Device& m_Device; std::unique_ptr<Submission> m_Tasks; }; std::unique_ptr<ExecutionHandler> spHandler(new ExecutionHandler{ *this, std::move(m_RecordingSubmission) }); m_CompletionScheduler.QueueTask({ [](void* pContext) { std::unique_ptr<ExecutionHandler> spHandler(static_cast<ExecutionHandler*>(pContext)); spHandler->m_Device.ExecuteTasks(*spHandler->m_Tasks); }, [](void* pContext) { std::unique_ptr<ExecutionHandler> spHandler(static_cast<ExecutionHandler*>(pContext)); }, spHandler.get() }); spHandler.release(); m_RecordingSubmission.reset(new Submission); } std::unique_ptr<D3D12TranslationLayer::PipelineState> Device::CreatePSO(D3D12TranslationLayer::COMPUTE_PIPELINE_STATE_DESC const& Desc) { std::lock_guard PSOCreateLock(m_PSOCreateLock); return std::make_unique<D3D12TranslationLayer::PipelineState>(&ImmCtx(), Desc); } void Device::ExecuteTasks(Submission& tasks) { { for (cl_uint i = 0; i < tasks.size(); ++i) { try { auto& task = tasks[i]; task->Record(); auto Lock = g_Platform->GetTaskPoolLock(); task->Started(Lock); } catch (...) { auto Lock = g_Platform->GetTaskPoolLock(); if ((cl_int)tasks[i]->GetState() > 0) { tasks[i]->Complete(CL_OUT_OF_RESOURCES, Lock); } for (size_t j = i + 1; j < tasks.size(); ++j) { auto& task = tasks[j]; task->Complete(CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST, Lock); } tasks.erase(tasks.begin() + i, tasks.end()); } } ImmCtx().Flush(D3D12TranslationLayer::COMMAND_LIST_TYPE_GRAPHICS_MASK); } ImmCtx().WaitForCompletion(D3D12TranslationLayer::COMMAND_LIST_TYPE::GRAPHICS); { auto Lock = g_Platform->GetTaskPoolLock(); for (auto& task : tasks) { task->Complete(CL_SUCCESS, Lock); } // Enqueue another execution task if there's new items ready to go g_Platform->FlushAllDevices(Lock); } } void Device::CacheCaps(std::lock_guard<std::mutex> const&) { if (m_CapsValid) return; bool bTempDevice = false; if (!m_spDevice) { THROW_IF_FAILED(D3D12CreateDevice(m_spAdapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&m_spDevice))); bTempDevice = true; } GetDevice()->CheckFeatureSupport(D3D12_FEATURE_ARCHITECTURE, &m_Architecture, sizeof(m_Architecture)); GetDevice()->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &m_D3D12Options, sizeof(m_D3D12Options)); GetDevice()->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS4, &m_D3D12Options4, sizeof(m_D3D12Options4)); if (bTempDevice) { m_spDevice.Reset(); } m_CapsValid = true; } extern CL_API_ENTRY cl_int CL_API_CALL clRetainDevice(cl_device_id device) CL_API_SUFFIX__VERSION_1_2 { if (!device) return CL_INVALID_DEVICE; return CL_SUCCESS; } extern CL_API_ENTRY cl_int CL_API_CALL clReleaseDevice(cl_device_id device) CL_API_SUFFIX__VERSION_1_2 { if (!device) return CL_INVALID_DEVICE; return CL_SUCCESS; } extern CL_API_ENTRY cl_int CL_API_CALL clGetDeviceAndHostTimer(cl_device_id device_, cl_ulong* device_timestamp, cl_ulong* host_timestamp) CL_API_SUFFIX__VERSION_2_1 { if (!device_) { return CL_INVALID_DEVICE; } if (!device_timestamp || !host_timestamp) { return CL_INVALID_VALUE; } Device& device = *static_cast<Device*>(device_); try { // Should I just return 0 here if they haven't created a context on this device? device.InitD3D(); auto cleanup = wil::scope_exit([&]() { device.ReleaseD3D(); }); auto pQueue = device.ImmCtx().GetCommandQueue(D3D12TranslationLayer::COMMAND_LIST_TYPE::GRAPHICS); D3D12TranslationLayer::ThrowFailure(pQueue->GetClockCalibration(device_timestamp, host_timestamp)); return CL_SUCCESS; } catch (_com_error&) { return CL_OUT_OF_RESOURCES; } catch (std::bad_alloc&) { return CL_OUT_OF_HOST_MEMORY; } } extern CL_API_ENTRY cl_int CL_API_CALL clGetHostTimer(cl_device_id device, cl_ulong * host_timestamp) CL_API_SUFFIX__VERSION_2_1 { if (!device) { return CL_INVALID_DEVICE; } if (!host_timestamp) { return CL_INVALID_VALUE; } LARGE_INTEGER QPC; QueryPerformanceCounter(&QPC); *host_timestamp = QPC.QuadPart; return CL_SUCCESS; } <|start_filename|>include/program.hpp<|end_filename|> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include "context.hpp" #include "compiler.hpp" #include <variant> #undef GetBinaryType using unique_spirv = std::unique_ptr<ProgramBinary>; using unique_dxil = std::unique_ptr<CompiledDxil>; class Kernel; class Program : public CLChildBase<Program, Context, cl_program> { public: const std::string m_Source; const std::vector<std::byte> m_IL; Context& GetContext() const { return m_Parent.get(); } Program(Context& Parent, std::string Source); Program(Context& Parent, std::vector<std::byte> IL); Program(Context& Parent, std::vector<Device::ref_ptr_int> Devices); using Callback = void(CL_CALLBACK*)(cl_program, void*); cl_int Build(std::vector<Device::ref_ptr_int> Devices, const char* options, Callback pfn_notify, void* user_data); cl_int Compile(std::vector<Device::ref_ptr_int> Devices, const char* options, cl_uint num_input_headers, const cl_program *input_headers, const char**header_include_names, Callback pfn_notify, void* user_data); cl_int Link(const char* options, cl_uint num_input_programs, const cl_program* input_programs, Callback pfn_notify, void* user_data); void StoreBinary(Device* Device, unique_spirv OwnedBinary, cl_program_binary_type Type); const ProgramBinary* GetSpirV(Device* device) const; friend cl_int CL_API_CALL clGetProgramInfo(cl_program, cl_program_info, size_t, void*, size_t*); friend cl_int CL_API_CALL clGetProgramBuildInfo(cl_program, cl_device_id, cl_program_build_info, size_t, void*, size_t*); friend cl_kernel CL_API_CALL clCreateKernel(cl_program, const char*, cl_int*); friend cl_int CL_API_CALL clCreateKernelsInProgram(cl_program, cl_uint, cl_kernel*, cl_uint*); void KernelCreated(); void KernelFreed(); struct SpecializationKey { union { struct { uint16_t LocalSize[3]; uint16_t LowerInt64 : 1; uint16_t LowerInt16 : 1; uint16_t SupportGlobalOffsets : 1; uint16_t SupportLocalOffsets : 1; uint16_t Padding : 12; } Bits; uint64_t Value; } ConfigData; uint32_t NumArgs; union PackedArgData { uint32_t LocalArgSize; struct { unsigned NormalizedCoords : 1; unsigned AddressingMode : 3; unsigned LinearFiltering : 1; unsigned Padding : 27; } SamplerArgData; } Args[1]; static std::unique_ptr<SpecializationKey> Allocate(CompiledDxil::Configuration const& conf); private: SpecializationKey(CompiledDxil::Configuration const& conf); }; struct SpecializationKeyHash { size_t operator()(std::unique_ptr<SpecializationKey> const&) const; }; struct SpecializationKeyEqual { bool operator()(std::unique_ptr<SpecializationKey> const& a, std::unique_ptr<SpecializationKey> const& b) const; }; struct SpecializationValue { unique_dxil m_Dxil; std::unique_ptr<D3D12TranslationLayer::Shader> m_Shader; std::unique_ptr<D3D12TranslationLayer::PipelineState> m_PSO; SpecializationValue(decltype(m_Dxil) d, decltype(m_Shader) s, decltype(m_PSO) p) : m_Dxil(std::move(d)), m_Shader(std::move(s)), m_PSO(std::move(p)) { } }; SpecializationValue *FindExistingSpecialization(Device* device, std::string const& kernelName, std::unique_ptr<SpecializationKey> const& key) const; template <typename... TArgs> SpecializationValue *StoreSpecialization(Device* device, std::string const& kernelName, std::unique_ptr<SpecializationKey>& key, TArgs&&... args) { std::lock_guard programLock(m_Lock); auto& buildData = m_BuildData[device]; std::lock_guard specializationCacheLock(buildData->m_SpecializationCacheLock); auto kernelsIter = buildData->m_Kernels.find(kernelName); assert(kernelsIter != buildData->m_Kernels.end()); auto ret = kernelsIter->second.m_SpecializationCache.try_emplace(std::move(key), std::forward<TArgs>(args)...); return &ret.first->second; } private: mutable std::recursive_mutex m_Lock; uint32_t m_NumLiveKernels = 0; struct KernelData { KernelData(unique_dxil d) : m_GenericDxil(std::move(d)) {} unique_dxil m_GenericDxil; std::unordered_map<std::unique_ptr<SpecializationKey>, SpecializationValue, SpecializationKeyHash, SpecializationKeyEqual> m_SpecializationCache; }; struct PerDeviceData { Device* m_Device; cl_build_status m_BuildStatus = CL_BUILD_IN_PROGRESS; std::string m_BuildLog; unique_spirv m_OwnedBinary; cl_program_binary_type m_BinaryType = CL_PROGRAM_BINARY_TYPE_NONE; std::string m_LastBuildOptions; std::map<std::string, KernelData> m_Kernels; uint32_t m_NumPendingLinks = 0; void CreateKernels(Program& program); std::mutex m_SpecializationCacheLock; }; std::unordered_map<Device*, std::shared_ptr<PerDeviceData>> m_BuildData; friend struct Loggers; std::vector<Device::ref_ptr_int> m_AssociatedDevices; struct CommonOptions { std::shared_ptr<PerDeviceData> BuildData; std::vector<std::string> Args; bool CreateLibrary; bool EnableLinkOptions; // Does nothing, validation only Callback pfn_notify; void* CallbackUserData; }; struct CompileArgs { std::map<std::string, Program::ref_ptr_int> Headers; CommonOptions Common; }; struct LinkArgs { CommonOptions Common; std::vector<Program::ref_ptr_int> LinkPrograms; }; struct BuildArgs { CommonOptions Common; std::vector<Device::ref_ptr_int> BinaryBuildDevices; }; void AddBuiltinOptions(std::vector<Device::ref_ptr_int> const& devices, CommonOptions& optionsStruct); cl_int ParseOptions(const char* optionsStr, CommonOptions& optionsStruct, bool SupportCompilerOptions, bool SupportLinkerOptions); cl_int BuildImpl(BuildArgs const& Args); cl_int CompileImpl(CompileArgs const& Args); cl_int LinkImpl(LinkArgs const& Args); }; <|start_filename|>src/compilers/compiler_common.cpp<|end_filename|> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "compiler.hpp" #include "platform.hpp" #include <dxc/dxcapi.h> void Logger::Log(const char *msg) const { std::lock_guard lock(m_lock); m_buildLog += msg; } static ProgramBinary::Kernel const& FindKernelInfo(std::vector<ProgramBinary::Kernel> const& kernels, const char *name) { auto iter = std::find_if(kernels.begin(), kernels.end(), [name](ProgramBinary::Kernel const& k) { return strcmp(k.name, name) == 0; }); assert(iter != kernels.end()); // We can't get DXIL if there's no data for a kernel with this name return *iter; } CompiledDxil::CompiledDxil(ProgramBinary const& parent, const char *name) : m_Parent(parent) , m_Metadata(FindKernelInfo(parent.GetKernelInfo(), name)) { } CompiledDxil::Metadata const& CompiledDxil::GetMetadata() const { return m_Metadata; } static void SignBlob(void* pBlob, size_t size) { auto& DXIL = g_Platform->GetDXIL(); auto pfnCreateInstance = DXIL.proc_address<decltype(&DxcCreateInstance)>("DxcCreateInstance"); ComPtr<IDxcValidator> spValidator; if (SUCCEEDED(pfnCreateInstance(CLSID_DxcValidator, IID_PPV_ARGS(&spValidator)))) { struct Blob : IDxcBlob { void* pBlob; UINT Size; Blob(void* p, UINT s) : pBlob(p), Size(s) { } STDMETHOD(QueryInterface)(REFIID, void** ppv) { *ppv = this; return S_OK; } STDMETHOD_(ULONG, AddRef)() { return 1; } STDMETHOD_(ULONG, Release)() { return 0; } STDMETHOD_(void*, GetBufferPointer)() override { return pBlob; } STDMETHOD_(SIZE_T, GetBufferSize)() override { return Size; } } Blob = { pBlob, (UINT)size }; ComPtr<IDxcOperationResult> spResult; (void)spValidator->Validate(&Blob, DxcValidatorFlags_InPlaceEdit, &spResult); HRESULT hr = S_OK; if (spResult) { (void)spResult->GetStatus(&hr); } if (FAILED(hr)) { ComPtr<IDxcBlobEncoding> spError; spResult->GetErrorBuffer(&spError); BOOL known = FALSE; UINT32 cp = 0; spError->GetEncoding(&known, &cp); if (cp == CP_UTF8 || cp == CP_ACP) printf("%s", (char*)spError->GetBufferPointer()); else printf("%S", (wchar_t*)spError->GetBufferPointer()); DebugBreak(); } } } void CompiledDxil::Sign() { SignBlob(GetBinary(), GetBinarySize()); } std::vector<ProgramBinary::Kernel> const& ProgramBinary::GetKernelInfo() const { return m_KernelInfo; } <|start_filename|>src/kernel_tasks.cpp<|end_filename|> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "kernel.hpp" #include "task.hpp" #include "queue.hpp" #include "resources.hpp" #include "sampler.hpp" #include "program.hpp" #include "compiler.hpp" #include <wil/resource.h> #include <sstream> #include <numeric> extern void SignBlob(void* pBlob, size_t size); constexpr uint32_t PrintfBufferSize = 1024 * 1024; constexpr uint32_t PrintfBufferInitialData[PrintfBufferSize / sizeof(uint32_t)] = { sizeof(uint32_t) * 2, PrintfBufferSize }; auto Program::SpecializationKey::Allocate(CompiledDxil::Configuration const& conf) -> std::unique_ptr<SpecializationKey> { uint32_t NumAllocatedArgs = conf.args.size() ? (uint32_t)conf.args.size() - 1 : 0; std::unique_ptr<SpecializationKey> bits(reinterpret_cast<SpecializationKey*>(operator new( sizeof(SpecializationKey) + sizeof(PackedArgData) * NumAllocatedArgs))); new (bits.get()) SpecializationKey(conf); return bits; } Program::SpecializationKey::SpecializationKey(CompiledDxil::Configuration const& conf) { ConfigData.Bits.LocalSize[0] = conf.local_size[0]; ConfigData.Bits.LocalSize[1] = conf.local_size[1]; ConfigData.Bits.LocalSize[2] = conf.local_size[2]; ConfigData.Bits.SupportGlobalOffsets = conf.support_global_work_id_offsets; ConfigData.Bits.SupportLocalOffsets = conf.support_work_group_id_offsets; ConfigData.Bits.LowerInt64 = conf.lower_int64; ConfigData.Bits.LowerInt16 = conf.lower_int64; ConfigData.Bits.Padding = 0; NumArgs = (uint32_t)conf.args.size(); for (uint32_t i = 0; i < NumArgs; ++i) { memset(&Args[i], 0, sizeof(Args[i])); if (auto localConfig = std::get_if<CompiledDxil::Configuration::Arg::Local>(&conf.args[i].config); localConfig) { Args[i].LocalArgSize = localConfig->size; } else if (auto samplerConfig = std::get_if<CompiledDxil::Configuration::Arg::Sampler>(&conf.args[i].config); samplerConfig) { Args[i].SamplerArgData.AddressingMode = samplerConfig->addressingMode; Args[i].SamplerArgData.LinearFiltering = samplerConfig->linearFiltering; Args[i].SamplerArgData.NormalizedCoords = samplerConfig->normalizedCoords; Args[i].SamplerArgData.Padding = 0; } else { Args[i].LocalArgSize = 0; } } } size_t Program::SpecializationKeyHash::operator()(std::unique_ptr<Program::SpecializationKey> const& ptr) const { size_t val = std::hash<uint64_t>()(ptr->ConfigData.Value); for (uint32_t i = 0; i < ptr->NumArgs; ++i) { D3D12TranslationLayer::hash_combine(val, ptr->Args[i].LocalArgSize); } return val; } bool Program::SpecializationKeyEqual::operator()(std::unique_ptr<Program::SpecializationKey> const& a, std::unique_ptr<Program::SpecializationKey> const& b) const { assert(a->NumArgs == b->NumArgs); uint32_t NumAllocatedArgs = a->NumArgs ? a->NumArgs - 1 : 0; size_t size = sizeof(Program::SpecializationKey) + sizeof(Program::SpecializationKey::PackedArgData) * NumAllocatedArgs; return memcmp(a.get(), b.get(), size) == 0; } Program::SpecializationValue* Program::FindExistingSpecialization(Device* device, std::string const& kernelName, std::unique_ptr<Program::SpecializationKey> const& key) const { std::lock_guard programLock(m_Lock); auto buildDataIter = m_BuildData.find(device); assert(buildDataIter != m_BuildData.end()); auto& buildData = buildDataIter->second; auto kernelsIter = buildData->m_Kernels.find(kernelName); assert(kernelsIter != buildData->m_Kernels.end()); auto& kernel = kernelsIter->second; std::lock_guard specializationCacheLock(buildData->m_SpecializationCacheLock); auto iter = kernel.m_SpecializationCache.find(key); if (iter != kernel.m_SpecializationCache.end()) return &iter->second; return nullptr; } class ExecuteKernel : public Task { public: Kernel::ref_ptr_int m_Kernel; const std::array<uint32_t, 3> m_DispatchDims; std::vector<D3D12TranslationLayer::UAV*> m_UAVs; std::vector<D3D12TranslationLayer::SRV*> m_SRVs; std::vector<D3D12TranslationLayer::Sampler*> m_Samplers; std::vector<D3D12TranslationLayer::Resource*> m_CBs; std::vector<cl_uint> m_CBOffsets; Resource::UnderlyingResourcePtr m_KernelArgsCb; Resource::ref_ptr m_PrintfUAV; std::vector<Resource::ref_ptr_int> m_KernelArgUAVs; std::vector<Resource::ref_ptr_int> m_KernelArgSRVs; std::vector<Sampler::ref_ptr_int> m_KernelArgSamplers; std::mutex m_SpecializeLock; std::condition_variable m_SpecializeEvent; Program::SpecializationValue *m_Specialized = nullptr; bool m_SpecializeError = false; void MigrateResources() final { for (auto& res : m_KernelArgUAVs) { if (res.Get()) res->EnqueueMigrateResource(&m_CommandQueue->GetDevice(), this, 0); } for (auto& res : m_KernelArgSRVs) { if (res.Get()) res->EnqueueMigrateResource(&m_CommandQueue->GetDevice(), this, 0); } } void RecordImpl() final; void OnComplete() final; ExecuteKernel(Kernel& kernel, cl_command_queue queue, std::array<uint32_t, 3> const& dims, std::array<uint32_t, 3> const& offset, std::array<uint16_t, 3> const& localSize, cl_uint workDims) : Task(kernel.m_Parent->GetContext(), CL_COMMAND_NDRANGE_KERNEL, queue) , m_Kernel(&kernel) , m_DispatchDims(dims) , m_UAVs(kernel.m_UAVs.size(), nullptr) , m_SRVs(kernel.m_SRVs.size(), nullptr) , m_Samplers(kernel.m_Samplers.size(), nullptr) , m_KernelArgUAVs(kernel.m_UAVs.begin(), kernel.m_UAVs.end()) , m_KernelArgSRVs(kernel.m_SRVs.begin(), kernel.m_SRVs.end()) , m_KernelArgSamplers(kernel.m_Samplers.begin(), kernel.m_Samplers.end()) { cl_uint KernelArgCBIndex = kernel.m_Dxil.GetMetadata().kernel_inputs_cbv_id; cl_uint WorkPropertiesCBIndex = kernel.m_Dxil.GetMetadata().work_properties_cbv_id; unsigned num_cbs = max(KernelArgCBIndex + 1, WorkPropertiesCBIndex + 1); m_CBs.resize(num_cbs); m_CBOffsets.resize(num_cbs); WorkProperties work_properties = {}; work_properties.global_offset_x = offset[0]; work_properties.global_offset_y = offset[1]; work_properties.global_offset_z = offset[2]; work_properties.work_dim = workDims; work_properties.group_count_total_x = dims[0]; work_properties.group_count_total_y = dims[1]; work_properties.group_count_total_z = dims[2]; cl_uint numXIterations = ((dims[0] - 1) / D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION) + 1; cl_uint numYIterations = ((dims[1] - 1) / D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION) + 1; cl_uint numZIterations = ((dims[2] - 1) / D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION) + 1; cl_uint numIterations = numXIterations * numYIterations * numZIterations; size_t KernelInputsCbSize = kernel.m_Dxil.GetMetadata().kernel_inputs_buf_size; size_t WorkPropertiesOffset = D3D12TranslationLayer::Align<size_t>(KernelInputsCbSize, D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT); m_CBOffsets[WorkPropertiesCBIndex] = (UINT)WorkPropertiesOffset / 16; auto pCompiler = g_Platform->GetCompiler(); size_t WorkPropertiesSize = pCompiler->GetWorkPropertiesChunkSize() * numIterations; KernelInputsCbSize = WorkPropertiesOffset + WorkPropertiesSize; kernel.m_KernelArgsCbData.resize(KernelInputsCbSize); std::byte* workPropertiesData = kernel.m_KernelArgsCbData.data() + WorkPropertiesOffset; for (cl_uint x = 0; x < numXIterations; ++x) { for (cl_uint y = 0; y < numYIterations; ++y) { for (cl_uint z = 0; z < numZIterations; ++z) { work_properties.group_id_offset_x = x * D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION; work_properties.group_id_offset_y = y * D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION; work_properties.group_id_offset_z = z * D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION; workPropertiesData = pCompiler->CopyWorkProperties(workPropertiesData, work_properties); } } } auto& Device = m_CommandQueue->GetDevice(); D3D12TranslationLayer::ResourceCreationArgs Args = {}; Args.m_appDesc.m_Subresources = 1; Args.m_appDesc.m_SubresourcesPerPlane = 1; Args.m_appDesc.m_NonOpaquePlaneCount = 1; Args.m_appDesc.m_MipLevels = 1; Args.m_appDesc.m_ArraySize = 1; Args.m_appDesc.m_Depth = 1; Args.m_appDesc.m_Width = (UINT)kernel.m_KernelArgsCbData.size(); Args.m_appDesc.m_Height = 1; Args.m_appDesc.m_Format = DXGI_FORMAT_UNKNOWN; Args.m_appDesc.m_Samples = 1; Args.m_appDesc.m_Quality = 0; Args.m_appDesc.m_resourceDimension = D3D12_RESOURCE_DIMENSION_BUFFER; Args.m_appDesc.m_usage = D3D12TranslationLayer::RESOURCE_USAGE_DYNAMIC; Args.m_appDesc.m_bindFlags = D3D12TranslationLayer::RESOURCE_BIND_CONSTANT_BUFFER; Args.m_appDesc.m_cpuAcess = D3D12TranslationLayer::RESOURCE_CPU_ACCESS_WRITE; Args.m_desc12 = CD3DX12_RESOURCE_DESC::Buffer(Args.m_appDesc.m_Width); Args.m_heapDesc = CD3DX12_HEAP_DESC(Args.m_appDesc.m_Width, D3D12_HEAP_TYPE_UPLOAD); Args.m_heapType = D3D12TranslationLayer::AllocatorHeapType::Upload; assert(Args.m_appDesc.m_Width % D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT == 0); m_KernelArgsCb = D3D12TranslationLayer::Resource::CreateResource( &Device.ImmCtx(), Args, D3D12TranslationLayer::ResourceAllocationContext::FreeThread); m_CBs[KernelArgCBIndex] = m_KernelArgsCb.get(); m_CBs[WorkPropertiesCBIndex] = m_KernelArgsCb.get(); if (kernel.m_Dxil.GetMetadata().printf_uav_id >= 0) { m_PrintfUAV.Attach(static_cast<Resource*>(clCreateBuffer(&m_Parent.get(), CL_MEM_ALLOC_HOST_PTR | CL_MEM_COPY_HOST_PTR, PrintfBufferSize, (void*)PrintfBufferInitialData, nullptr))); m_PrintfUAV->EnqueueMigrateResource(&Device, this, 0); m_UAVs[kernel.m_Dxil.GetMetadata().printf_uav_id] = &m_PrintfUAV->GetUAV(&Device); } CompiledDxil::Configuration config = {}; config.lower_int64 = true; config.lower_int16 = !m_Device->SupportsInt16(); config.support_global_work_id_offsets = std::any_of(std::begin(offset), std::end(offset), [](cl_uint v) { return v != 0; }); config.support_work_group_id_offsets = numIterations != 1; std::copy(std::begin(localSize), std::end(localSize), config.local_size); config.args = kernel.m_ArgMetadataToCompiler; auto SpecKey = Program::SpecializationKey::Allocate(config); m_Specialized = kernel.m_Parent->FindExistingSpecialization(m_Device.Get(), kernel.m_Name, SpecKey); if (!m_Specialized) { g_Platform->QueueProgramOp([this, &Device, config = std::move(config), SpecKey = std::move(SpecKey), kernel = this->m_Kernel, refThis = Task::ref_int(*this)]() mutable { try { auto pCompiler = g_Platform->GetCompiler(); auto spirv = kernel->m_Parent->GetSpirV(&m_CommandQueue->GetDevice()); auto name = kernel->m_Dxil.GetMetadata().program_kernel_info.name; auto specialized = pCompiler->GetKernel(name, *spirv, &config, nullptr); if (specialized) specialized->Sign(); auto CS = std::make_unique<D3D12TranslationLayer::Shader>(&Device.ImmCtx(), specialized->GetBinary(), specialized->GetBinarySize(), kernel->m_ShaderDecls); D3D12TranslationLayer::COMPUTE_PIPELINE_STATE_DESC Desc = { CS.get() }; auto PSO = Device.CreatePSO(Desc); auto cacheEntry = kernel->m_Parent->StoreSpecialization(m_Device.Get(), kernel->m_Name, SpecKey, std::move(specialized), std::move(CS), std::move(PSO)); { std::lock_guard lock(m_SpecializeLock); m_Specialized = cacheEntry; } m_SpecializeEvent.notify_all(); } catch (...) { { std::lock_guard lock(m_SpecializeLock); m_SpecializeError = true; } m_SpecializeEvent.notify_all(); } }); } } }; extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueNDRangeKernel(cl_command_queue command_queue, cl_kernel kernel_, cl_uint work_dim, const size_t* global_work_offset, const size_t* global_work_size, const size_t* local_work_size, cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event) CL_API_SUFFIX__VERSION_1_0 { if (!command_queue) { return CL_INVALID_COMMAND_QUEUE; } if (!kernel_) { return CL_INVALID_KERNEL; } CommandQueue& queue = *static_cast<CommandQueue*>(command_queue); Context& context = queue.GetContext(); auto ReportError = context.GetErrorReporter(); Kernel& kernel = *static_cast<Kernel*>(kernel_); if (&kernel.m_Parent->GetContext() != &context) { return ReportError("Kernel was not created on the same context as the command queue.", CL_INVALID_CONTEXT); } if ((event_wait_list == nullptr) != (num_events_in_wait_list == 0)) { return ReportError("If event_wait_list is null, then num_events_in_wait_list mut be zero, and vice versa.", CL_INVALID_EVENT_WAIT_LIST); } if (work_dim == 0 || work_dim > 3) { return ReportError("work_dim must be between 1 and 3.", CL_INVALID_WORK_DIMENSION); } if (!global_work_size) { return ReportError("global_work_size must be specified.", CL_INVALID_GLOBAL_WORK_SIZE); } std::array<uint32_t, 3> GlobalWorkItemOffsets = {}; if (global_work_offset != nullptr) { for (cl_uint i = 0; i < work_dim; ++i) { if (global_work_offset[i] + global_work_size[i] > std::numeric_limits<uint32_t>::max()) { return ReportError("global_work_offset + global_work_size would exceed maximum value.", CL_INVALID_GLOBAL_OFFSET); } GlobalWorkItemOffsets[i] = (uint32_t)global_work_offset[i]; } } std::array<uint32_t, 3> DispatchDimensions = { 1, 1, 1 }; std::array<uint16_t, 3> LocalSizes = { 1, 1, 1 }; auto RequiredDims = kernel.GetRequiredLocalDims(); auto DimsHint = kernel.GetLocalDimsHint(); const std::array<uint16_t, 3> AutoDims[3] = { { 64, 1, 1 }, { 8, 8, 1 }, { 4, 4, 4 } }; const std::array<uint16_t, 3> MaxDims = { D3D12_CS_THREAD_GROUP_MAX_X, D3D12_CS_THREAD_GROUP_MAX_Y, D3D12_CS_THREAD_GROUP_MAX_Z }; for (cl_uint i = 0; i < work_dim; ++i) { uint16_t& LocalSize = LocalSizes[i]; if (local_work_size && local_work_size[i] > std::numeric_limits<uint16_t>::max()) { return ReportError("local_work_size is too large.", CL_INVALID_WORK_GROUP_SIZE); } LocalSize = local_work_size ? (uint16_t)local_work_size[i] : (DimsHint ? DimsHint[i] : AutoDims[work_dim - 1][i]); if (RequiredDims) { if (RequiredDims[i] != LocalSize) { return ReportError("local_work_size does not match required size declared by kernel.", CL_INVALID_WORK_GROUP_SIZE); } if (global_work_size[i] % LocalSize != 0) { return ReportError("local_work_size must evenly divide the global_work_size.", CL_INVALID_WORK_GROUP_SIZE); } if (LocalSize > MaxDims[i]) { return ReportError("local_work_size exceeds max in one dimension.", CL_INVALID_WORK_ITEM_SIZE); } } else { while (global_work_size[i] % LocalSize != 0 || LocalSize > MaxDims[i]) { // TODO: Better backoff algorithm LocalSize /= 2; } } } if (RequiredDims) { if ((uint64_t)LocalSizes[0] * (uint64_t)LocalSizes[1] * (uint64_t)LocalSizes[2] > D3D12_CS_THREAD_GROUP_MAX_THREADS_PER_GROUP) { return ReportError("local_work_size exceeds max work items per group.", CL_INVALID_WORK_GROUP_SIZE); } } else { cl_uint dimension = work_dim - 1; while ((uint64_t)LocalSizes[0] * (uint64_t)LocalSizes[1] * (uint64_t)LocalSizes[2] > D3D12_CS_THREAD_GROUP_MAX_THREADS_PER_GROUP) { // Find a dimension to shorten // TODO: Better backoff algorithm if (LocalSizes[dimension] > 1) { LocalSizes[dimension] /= 2; } dimension = (dimension == 0) ? work_dim - 1 : dimension - 1; } } for (cl_uint i = 0; i < work_dim; ++i) { DispatchDimensions[i] = (uint32_t)(global_work_size[i] / LocalSizes[i]); if (!RequiredDims) { // Try to expand local size to avoid having to loop Dispatches while (DispatchDimensions[i] > D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION) { auto OldLocalSize = LocalSizes[i]; LocalSizes[i] *= 2; if ((uint64_t)LocalSizes[0] * (uint64_t)LocalSizes[1] * (uint64_t)LocalSizes[2] > D3D12_CS_THREAD_GROUP_MAX_THREADS_PER_GROUP || LocalSizes[i] > MaxDims[i] || global_work_size[i] % LocalSizes[i] != 0) { LocalSizes[i] = OldLocalSize; break; } DispatchDimensions[i] /= 2; } } } try { std::unique_ptr<Task> task(new ExecuteKernel(kernel, command_queue, DispatchDimensions, GlobalWorkItemOffsets, LocalSizes, work_dim)); auto Lock = g_Platform->GetTaskPoolLock(); task->AddDependencies(event_wait_list, num_events_in_wait_list, Lock); queue.QueueTask(task.get(), Lock); // No more exceptions if (event) *event = task.release(); else task.release()->Release(); } catch (std::bad_alloc&) { return ReportError(nullptr, CL_OUT_OF_HOST_MEMORY); } catch (std::exception & e) { return ReportError(e.what(), CL_OUT_OF_RESOURCES); } catch (_com_error&) { return ReportError(nullptr, CL_OUT_OF_RESOURCES); } catch (Task::DependencyException&) { return ReportError("Context mismatch between command_queue and event_wait_list", CL_INVALID_CONTEXT); } return CL_SUCCESS; } extern CL_API_ENTRY CL_API_PREFIX__VERSION_1_2_DEPRECATED cl_int CL_API_CALL clEnqueueTask(cl_command_queue command_queue, cl_kernel kernel, cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event) CL_API_SUFFIX__VERSION_1_2_DEPRECATED { size_t global_work_size = 1, local_work_size = 1; return clEnqueueNDRangeKernel( command_queue, kernel, 1, nullptr, &global_work_size, &local_work_size, num_events_in_wait_list, event_wait_list, event); } constexpr UINT c_aUAVAppendOffsets[D3D11_1_UAV_SLOT_COUNT] = { (UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1, (UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1, (UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1, (UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1, (UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1, (UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1, (UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1, (UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1,(UINT)-1, }; constexpr UINT c_NumConstants[D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT] = { D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT, D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT, D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT, D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT, D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT, D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT, D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT, D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT, D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT, D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT, D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT, D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT, D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT, D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT }; void ExecuteKernel::RecordImpl() { std::unique_lock lock(m_SpecializeLock); while (!m_Specialized && !m_SpecializeError) { m_SpecializeEvent.wait(lock); } if (m_SpecializeError) { auto Lock = g_Platform->GetTaskPoolLock(); Complete(CL_BUILD_PROGRAM_FAILURE, Lock); throw std::exception("Failed to specialize"); } auto& Device = m_CommandQueue->GetDevice(); std::transform(m_KernelArgUAVs.begin(), m_KernelArgUAVs.end(), m_UAVs.begin(), [&Device](Resource::ref_ptr_int& resource) { return resource.Get() ? &resource->GetUAV(&Device) : nullptr; }); std::transform(m_KernelArgSRVs.begin(), m_KernelArgSRVs.end(), m_SRVs.begin(), [&Device](Resource::ref_ptr_int& resource) { return resource.Get() ? &resource->GetSRV(&Device) : nullptr; }); std::transform(m_KernelArgSamplers.begin(), m_KernelArgSamplers.end(), m_Samplers.begin(), [&Device](Sampler::ref_ptr_int& sampler) { return sampler.Get() ? &sampler->GetUnderlying(&Device) : nullptr; }); if (m_PrintfUAV.Get()) { m_UAVs[m_Kernel->m_Dxil.GetMetadata().printf_uav_id] = &m_PrintfUAV->GetUAV(&Device); } auto& ImmCtx = Device.ImmCtx(); ImmCtx.CsSetUnorderedAccessViews(0, (UINT)m_UAVs.size(), m_UAVs.data(), c_aUAVAppendOffsets); ImmCtx.SetShaderResources<D3D12TranslationLayer::e_CS>(0, (UINT)m_SRVs.size(), m_SRVs.data()); ImmCtx.SetSamplers<D3D12TranslationLayer::e_CS>(0, (UINT)m_Samplers.size(), m_Samplers.data()); ImmCtx.SetPipelineState(m_Specialized->m_PSO.get()); // Fill out offsets that'll be read by the kernel for local arg pointers, based on the offsets // returned by the compiler for this specialization for (UINT i = 0; i < m_Specialized->m_Dxil->GetMetadata().args.size(); ++i) { if (m_Specialized->m_Dxil->GetMetadata().program_kernel_info.args[i].address_qualifier != ProgramBinary::Kernel::Arg::AddressSpace::Local) continue; UINT *offsetLocation = reinterpret_cast<UINT*>(&m_Kernel->m_KernelArgsCbData[m_Specialized->m_Dxil->GetMetadata().args[i].offset]); *offsetLocation = std::get<CompiledDxil::Metadata::Arg::Local>(m_Specialized->m_Dxil->GetMetadata().args[i].properties).sharedmem_offset; } D3D11_SUBRESOURCE_DATA Data = { m_Kernel->m_KernelArgsCbData.data() }; Device.ImmCtx().UpdateSubresources( m_KernelArgsCb.get(), m_KernelArgsCb->GetFullSubresourceSubset(), &Data, nullptr, D3D12TranslationLayer::ImmediateContext::UpdateSubresourcesFlags::ScenarioInitialData); cl_uint numXIterations = ((m_DispatchDims[0] - 1) / D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION) + 1; cl_uint numYIterations = ((m_DispatchDims[1] - 1) / D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION) + 1; cl_uint numZIterations = ((m_DispatchDims[2] - 1) / D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION) + 1; auto pCompiler = g_Platform->GetCompiler(); cl_uint WorkPropertiesChunkSize = (cl_uint)pCompiler->GetWorkPropertiesChunkSize(); for (cl_uint x = 0; x < numXIterations; ++x) { for (cl_uint y = 0; y < numYIterations; ++y) { for (cl_uint z = 0; z < numZIterations; ++z) { UINT DimsX = (x == numXIterations - 1) ? (m_DispatchDims[0] - D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION * (numXIterations - 1)) : D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION; UINT DimsY = (y == numYIterations - 1) ? (m_DispatchDims[1] - D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION * (numYIterations - 1)) : D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION; UINT DimsZ = (z == numZIterations - 1) ? (m_DispatchDims[2] - D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION * (numZIterations - 1)) : D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION; ImmCtx.SetConstantBuffers<D3D12TranslationLayer::e_CS>(0, (UINT)m_CBs.size(), m_CBs.data(), m_CBOffsets.data(), c_NumConstants); ImmCtx.Dispatch(DimsX, DimsY, DimsZ); m_CBOffsets[m_Kernel->m_Dxil.GetMetadata().work_properties_cbv_id] += WorkPropertiesChunkSize / 16; } } } ImmCtx.ClearState(); } void ExecuteKernel::OnComplete() { auto Cleanup = wil::scope_exit([this]() { m_Kernel.Release(); }); if (m_PrintfUAV.Get()) { auto& Device = m_CommandQueue->GetDevice(); auto& ImmCtx = Device.ImmCtx(); auto TranslationResource = m_PrintfUAV->GetUnderlyingResource(&Device); D3D12TranslationLayer::MappedSubresource MapRet = {}; ImmCtx.Map(TranslationResource, 0, D3D12TranslationLayer::MAP_TYPE_READ, false, nullptr, &MapRet); auto Unmap = wil::scope_exit([&]() { ImmCtx.Unmap(TranslationResource, 0, D3D12TranslationLayer::MAP_TYPE_READ, nullptr); }); // The buffer has a two-uint header. constexpr uint32_t InitialBufferOffset = sizeof(uint32_t) * 2; // The first uint is the offset where the next chunk of data would be written. Alternatively, // it's the size of the buffer that's *been* written, including the size of the header. uint32_t NumBytesWritten = *reinterpret_cast<uint32_t*>(MapRet.pData); uint32_t CurOffset = InitialBufferOffset; std::byte* ByteStream = reinterpret_cast<std::byte*>(MapRet.pData); while (CurOffset < NumBytesWritten && CurOffset < PrintfBufferSize) { uint32_t FormatStringId = *reinterpret_cast<uint32_t*>(ByteStream + CurOffset); assert(FormatStringId <= m_Kernel->m_Dxil.GetMetadata().printfs.size()); if (FormatStringId == 0) break; auto& PrintfData = m_Kernel->m_Dxil.GetMetadata().printfs[FormatStringId - 1]; CurOffset += sizeof(FormatStringId); auto StructBeginOffset = CurOffset; uint32_t OffsetInStruct = 0; uint32_t ArgIdx = 0; uint32_t TotalArgSize = std::accumulate(PrintfData.arg_sizes, PrintfData.arg_sizes + PrintfData.num_args, 0u); TotalArgSize = D3D12TranslationLayer::Align<uint32_t>(TotalArgSize, 4); if (CurOffset + TotalArgSize > PrintfBufferSize) break; std::ostringstream stream; const char* SectionStart = PrintfData.str; while (const char* SectionEnd = strchr(SectionStart, '%')) { if (SectionEnd[1] == '%') { stream << std::string_view(SectionStart, SectionEnd - SectionStart + 2); SectionStart = SectionEnd + 2; continue; } stream << std::string_view(SectionStart, SectionEnd - SectionStart); // Parse the printf declaration to find what type we should load char FinalFormatString[16] = "%", *OutputFormatString = FinalFormatString + 1; const char* FormatStr = SectionEnd + 1; for (; *FormatStr; ++FormatStr) { switch (*FormatStr) { case '+': case '-': case ' ': case '#': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': // Flag, field width, or precision *(OutputFormatString++) = *FormatStr; continue; } break; } uint32_t VectorSize = 1; if (*FormatStr == 'v') { ++FormatStr; switch (*FormatStr) { case '2': VectorSize = 2; break; case '3': VectorSize = 3; break; case '4': VectorSize = 4; break; case '8': VectorSize = 8; break; case '1': ++FormatStr; if (*FormatStr == '6') { VectorSize = 16; break; } // fallthrough default: printf("Invalid format string, unexpected vector size.\n"); return; } ++FormatStr; } uint32_t DataSize = 4; bool ExplicitDataSize = false; switch (*FormatStr) { case 'h': ExplicitDataSize = true; ++FormatStr; if (*FormatStr == 'h') { DataSize = 1; *(OutputFormatString++) = 'h'; *(OutputFormatString++) = 'h'; ++FormatStr; } else if (*FormatStr == 'l') { if (VectorSize == 1) { printf("Invalid format string, hl precision only valid with vectors.\n"); return; } DataSize = 4; ++FormatStr; } else { *(OutputFormatString++) = 'h'; DataSize = 2; } break; case 'l': ExplicitDataSize = true; *(OutputFormatString++) = 'l'; ++FormatStr; DataSize = 8; break; } if (!ExplicitDataSize && VectorSize > 1) { printf("Invalid format string, vectors require explicit data size.\n"); return; } *(OutputFormatString++) = *FormatStr; if (!ExplicitDataSize) { switch (*FormatStr) { case 's': case 'p': // Pointers are 64bit DataSize = 8; break; } } // Get the base pointer to the arg, now that we know how big it is uint32_t ArgSize = DataSize * (VectorSize == 3 ? 4 : VectorSize); assert(ArgSize == PrintfData.arg_sizes[ArgIdx]); uint32_t ArgOffset = D3D12TranslationLayer::Align<uint32_t>(OffsetInStruct, 4) + StructBeginOffset; std::byte* ArgPtr = ByteStream + ArgOffset; OffsetInStruct += ArgSize; std::string StringBuffer; StringBuffer.resize(32); for (uint32_t i = 0; i < VectorSize; ++i) { switch (*FormatStr) { default: printf("Invalid format string, unknown conversion specifier.\n"); return; case 's': { if (DataSize != 8 || VectorSize != 1) { printf("Invalid format string, precision or vector applied to string.\n"); return; } uint64_t StringId = *reinterpret_cast<uint64_t*>(ArgPtr); const char *Str = &PrintfData.str[StringId]; // Use sprintf to deal with precision potentially shortening how much is printed StringBuffer.resize(snprintf(nullptr, 0, FinalFormatString, Str) + 1); sprintf_s(StringBuffer.data(), StringBuffer.size(), FinalFormatString, Str); break; } case 'f': case 'F': case 'e': case 'E': case 'g': case 'G': case 'a': case 'A': { if (DataSize != 4) { printf("Invalid format string, floats other than 4 bytes are not supported.\n"); return; } float val = *reinterpret_cast<float*>(ArgPtr); sprintf_s(StringBuffer.data(), StringBuffer.size(), FinalFormatString, val); break; } break; case 'c': DataSize = 1; // fallthrough case 'd': case 'i': switch (DataSize) { case 1: sprintf_s(StringBuffer.data(), StringBuffer.size(), FinalFormatString, *reinterpret_cast<int8_t*>(ArgPtr)); break; case 2: sprintf_s(StringBuffer.data(), StringBuffer.size(), FinalFormatString, *reinterpret_cast<int16_t*>(ArgPtr)); break; case 4: sprintf_s(StringBuffer.data(), StringBuffer.size(), FinalFormatString, *reinterpret_cast<int32_t*>(ArgPtr)); break; case 8: sprintf_s(StringBuffer.data(), StringBuffer.size(), FinalFormatString, *reinterpret_cast<int64_t*>(ArgPtr)); break; } break; case 'o': case 'u': case 'x': case 'X': case 'p': switch (DataSize) { case 1: sprintf_s(StringBuffer.data(), StringBuffer.size(), FinalFormatString, *reinterpret_cast<uint8_t*>(ArgPtr)); break; case 2: sprintf_s(StringBuffer.data(), StringBuffer.size(), FinalFormatString, *reinterpret_cast<uint16_t*>(ArgPtr)); break; case 4: sprintf_s(StringBuffer.data(), StringBuffer.size(), FinalFormatString, *reinterpret_cast<uint32_t*>(ArgPtr)); break; case 8: sprintf_s(StringBuffer.data(), StringBuffer.size(), FinalFormatString, *reinterpret_cast<uint64_t*>(ArgPtr)); break; } break; } ArgPtr += DataSize; stream << StringBuffer.c_str(); if (i < VectorSize - 1) stream << ","; } SectionStart = FormatStr + 1; ArgIdx++; } stream << SectionStart; printf("%s", stream.str().c_str()); fflush(stdout); CurOffset += TotalArgSize; } } } <|start_filename|>src/resources.cpp<|end_filename|> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "resources.hpp" #include "formats.hpp" #include "task.hpp" constexpr cl_mem_flags ValidMemFlags = CL_MEM_READ_WRITE | CL_MEM_WRITE_ONLY | CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR | CL_MEM_ALLOC_HOST_PTR | CL_MEM_COPY_HOST_PTR | CL_MEM_HOST_WRITE_ONLY | CL_MEM_HOST_READ_ONLY | CL_MEM_HOST_NO_ACCESS; constexpr cl_mem_flags DeviceReadWriteFlagsMask = CL_MEM_READ_WRITE | CL_MEM_WRITE_ONLY | CL_MEM_READ_ONLY; constexpr cl_mem_flags HostReadWriteFlagsMask = CL_MEM_HOST_WRITE_ONLY | CL_MEM_HOST_READ_ONLY | CL_MEM_HOST_NO_ACCESS; constexpr cl_mem_flags HostPtrFlagsMask = CL_MEM_USE_HOST_PTR | CL_MEM_ALLOC_HOST_PTR | CL_MEM_COPY_HOST_PTR; void ModifyResourceArgsForMemFlags(D3D12TranslationLayer::ResourceCreationArgs& Args, cl_mem_flags flags) { if ((flags & DeviceReadWriteFlagsMask) == 0) flags |= CL_MEM_READ_WRITE; if (flags & CL_MEM_ALLOC_HOST_PTR) { Args.m_heapDesc.Properties = CD3DX12_HEAP_PROPERTIES(D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE, D3D12_MEMORY_POOL_L0); switch (flags & HostReadWriteFlagsMask) { default: Args.m_appDesc.m_cpuAcess = D3D12TranslationLayer::RESOURCE_CPU_ACCESS_READ | D3D12TranslationLayer::RESOURCE_CPU_ACCESS_WRITE; break; case CL_MEM_HOST_NO_ACCESS: Args.m_appDesc.m_cpuAcess = D3D12TranslationLayer::RESOURCE_CPU_ACCESS_NONE; break; case CL_MEM_HOST_READ_ONLY: Args.m_appDesc.m_cpuAcess = D3D12TranslationLayer::RESOURCE_CPU_ACCESS_READ; break; case CL_MEM_HOST_WRITE_ONLY: Args.m_appDesc.m_cpuAcess = D3D12TranslationLayer::RESOURCE_CPU_ACCESS_WRITE; break; } } } template <typename TErrFunc> bool ValidateMemFlagsBase(cl_mem_flags flags, TErrFunc&& ReportError) { if (flags & ~ValidMemFlags) { ReportError("Unknown flags specified.", CL_INVALID_VALUE); return false; } if (!IsZeroOrPow2(flags & DeviceReadWriteFlagsMask)) { ReportError("Only one of CL_MEM_READ_WRITE, CL_MEM_WRITE_ONLY, and CL_MEM_READ_ONLY can be specified.", CL_INVALID_VALUE); return false; } if (!IsZeroOrPow2(flags & HostReadWriteFlagsMask)) { ReportError("Only one of CL_MEM_HOST_WRITE_ONLY, CL_MEM_HOST_READ_ONLY, and CL_MEM_HOST_NO_ACCESS can be specified.", CL_INVALID_VALUE); return false; } if ((flags & CL_MEM_USE_HOST_PTR) && (flags & (CL_MEM_ALLOC_HOST_PTR | CL_MEM_COPY_HOST_PTR))) { ReportError("CL_MEM_USE_HOST_PTR cannot be used with either CL_MEM_ALLOC_HOST_PTR or CL_MEM_COPY_HOST_PTR.", CL_INVALID_VALUE); return false; } return true; } template <typename TErrFunc> bool ValidateMemFlags(cl_mem_flags flags, bool bHaveHostPtr, TErrFunc&& ReportError) { const bool bNeedHostPtr = (flags & (CL_MEM_USE_HOST_PTR | CL_MEM_COPY_HOST_PTR)); if (bNeedHostPtr && !bHaveHostPtr) { ReportError("When CL_MEM_USE_HOST_PTR or CL_MEM_COPY_HOST_PTR are specified, host_ptr must not be null.", CL_INVALID_HOST_PTR); return false; } else if (bHaveHostPtr && !bNeedHostPtr) { ReportError("When CL_MEM_USE_HOST_PTR or CL_MEM_COPY_HOST_PTR are not specified, host_ptr must be null.", CL_INVALID_HOST_PTR); return false; } return ValidateMemFlagsBase(flags, ReportError); } template <typename TErrFunc> bool ValidateMemFlagsForBufferReference(cl_mem_flags& flags, Resource& buffer, TErrFunc&& ReportError) { if (flags & HostPtrFlagsMask) { ReportError("Cannot set CL_MEM_USE_HOST_PTR, CL_MEM_ALLOC_HOST_PTR, or CL_MEM_COPY_HOST_PTR for sub-buffers or 1D image buffers.", CL_INVALID_VALUE); return false; } flags |= buffer.m_Flags & HostPtrFlagsMask; if ((flags & DeviceReadWriteFlagsMask) == 0) { flags |= buffer.m_Flags & DeviceReadWriteFlagsMask; } else if (((buffer.m_Flags & CL_MEM_WRITE_ONLY) && (flags & (CL_MEM_READ_ONLY | CL_MEM_READ_WRITE))) || ((buffer.m_Flags & CL_MEM_READ_ONLY) && (flags & (CL_MEM_WRITE_ONLY | CL_MEM_READ_WRITE)))) { ReportError("Attempting to add device read or write capabilities via sub-buffer or 1D image buffer.", CL_INVALID_VALUE); return false; } if ((flags & HostReadWriteFlagsMask) == 0) { flags |= buffer.m_Flags & HostReadWriteFlagsMask; } else if (((buffer.m_Flags & CL_MEM_HOST_WRITE_ONLY) && (flags & CL_MEM_HOST_READ_ONLY)) || ((buffer.m_Flags & CL_MEM_HOST_READ_ONLY) && (flags & CL_MEM_HOST_WRITE_ONLY)) || ((buffer.m_Flags & CL_MEM_HOST_NO_ACCESS) && (flags & (CL_MEM_HOST_READ_ONLY | CL_MEM_HOST_WRITE_ONLY)))) { ReportError("Attempting to add host read or write capabilities via sub-buffer or 1D image buffer.", CL_INVALID_VALUE); return false; } return true; } /* Memory Object APIs */ extern CL_API_ENTRY cl_mem CL_API_CALL clCreateBufferWithProperties(cl_context context_, const cl_mem_properties* properties, cl_mem_flags flags, size_t size, void * host_ptr, cl_int * errcode_ret) CL_API_SUFFIX__VERSION_3_0 { if (!context_) { if (errcode_ret) *errcode_ret = CL_INVALID_CONTEXT; return nullptr; } Context& context = *static_cast<Context*>(context_); auto ReportError = context.GetErrorReporter(errcode_ret); if (properties && properties[0] != 0) { return ReportError("Invalid properties specified", CL_INVALID_PROPERTY); } if (size == 0 || size > UINT_MAX) { return ReportError("Invalid buffer size.", CL_INVALID_BUFFER_SIZE); } if (!ValidateMemFlags(flags, host_ptr != nullptr, ReportError)) { return nullptr; } D3D12TranslationLayer::ResourceCreationArgs Args = {}; Args.m_appDesc.m_Subresources = 1; Args.m_appDesc.m_SubresourcesPerPlane = 1; Args.m_appDesc.m_NonOpaquePlaneCount = 1; Args.m_appDesc.m_MipLevels = 1; Args.m_appDesc.m_ArraySize = 1; Args.m_appDesc.m_Depth = 1; Args.m_appDesc.m_Width = (UINT)size; Args.m_appDesc.m_Height = 1; Args.m_appDesc.m_Format = DXGI_FORMAT_UNKNOWN; Args.m_appDesc.m_Samples = 1; Args.m_appDesc.m_Quality = 0; Args.m_appDesc.m_resourceDimension = D3D12_RESOURCE_DIMENSION_BUFFER; Args.m_appDesc.m_usage = D3D12TranslationLayer::RESOURCE_USAGE_DEFAULT; Args.m_appDesc.m_bindFlags = D3D12TranslationLayer::RESOURCE_BIND_UNORDERED_ACCESS | D3D12TranslationLayer::RESOURCE_BIND_SHADER_RESOURCE | D3D12TranslationLayer::RESOURCE_BIND_CONSTANT_BUFFER; Args.m_desc12 = CD3DX12_RESOURCE_DESC::Buffer(D3D12TranslationLayer::Align<size_t>(size, 4), D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); Args.m_heapDesc = CD3DX12_HEAP_DESC(0, D3D12_HEAP_TYPE_DEFAULT); ModifyResourceArgsForMemFlags(Args, flags); try { if (errcode_ret) *errcode_ret = CL_SUCCESS; return Resource::CreateBuffer(context, Args, host_ptr, flags); } catch (std::bad_alloc&) { return ReportError(nullptr, CL_OUT_OF_HOST_MEMORY); } catch (_com_error& e) { if (e.Error() == E_INVALIDARG) return ReportError("Invalid buffer description.", CL_INVALID_VALUE); return ReportError(nullptr, CL_OUT_OF_RESOURCES); } catch (std::exception& e) { return ReportError(e.what(), CL_OUT_OF_RESOURCES); } } extern CL_API_ENTRY cl_mem CL_API_CALL clCreateBuffer(cl_context context, cl_mem_flags flags, size_t size, void * host_ptr, cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0 { return clCreateBufferWithProperties(context, nullptr, flags, size, host_ptr, errcode_ret); } extern CL_API_ENTRY cl_mem CL_API_CALL clCreateSubBuffer(cl_mem buffer_, cl_mem_flags flags, cl_buffer_create_type buffer_create_type, const void * buffer_create_info, cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_1 { if (!buffer_) { if (errcode_ret) *errcode_ret = CL_INVALID_CONTEXT; return nullptr; } Resource& buffer = *static_cast<Resource*>(buffer_); Context& context = buffer.m_Parent.get(); auto ReportError = context.GetErrorReporter(errcode_ret); if (!ValidateMemFlagsForBufferReference(flags, buffer, ReportError)) { return nullptr; } if (buffer_create_type != CL_BUFFER_CREATE_TYPE_REGION) { return ReportError("Invalid buffer create type.", CL_INVALID_VALUE); } auto& region = *reinterpret_cast<const cl_buffer_region*>(buffer_create_info); if (region.size == 0) return ReportError("Invalid buffer region size.", CL_INVALID_BUFFER_SIZE); if ((region.origin % D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT) != 0) return ReportError("Invalid buffer region origin alignment.", CL_MISALIGNED_SUB_BUFFER_OFFSET); if (region.origin + region.size > buffer.m_Desc.image_width) return ReportError("Origin + size for sub-buffer is out of bounds", CL_INVALID_VALUE); try { if (errcode_ret) *errcode_ret = CL_SUCCESS; return Resource::CreateSubBuffer(buffer, region, flags); } catch (std::bad_alloc&) { return ReportError(nullptr, CL_OUT_OF_HOST_MEMORY); } catch (std::exception& e) { return ReportError(e.what(), CL_OUT_OF_RESOURCES); } } extern CL_API_ENTRY cl_mem CL_API_CALL clCreateImageWithProperties(cl_context context_, const cl_mem_properties* properties, cl_mem_flags flags, const cl_image_format * image_format, const cl_image_desc * image_desc, void * host_ptr, cl_int * errcode_ret) CL_API_SUFFIX__VERSION_3_0 { if (!context_) { if (errcode_ret) *errcode_ret = CL_INVALID_CONTEXT; return nullptr; } Context& context = *static_cast<Context*>(context_); auto ReportError = context.GetErrorReporter(errcode_ret); if (properties && properties[0] != 0) { return ReportError("Invalid properties", CL_INVALID_PROPERTY); } if (!ValidateMemFlags(flags, host_ptr != nullptr, ReportError)) { return nullptr; } if (!image_format) { return ReportError("Null image format.", CL_INVALID_IMAGE_FORMAT_DESCRIPTOR); } if (!image_desc) { return ReportError("Null image desc.", CL_INVALID_IMAGE_DESCRIPTOR); } auto image_desc_copy = *image_desc; D3D12TranslationLayer::ResourceCreationArgs Args = {}; switch (image_desc->image_type) { case CL_MEM_OBJECT_BUFFER: return ReportError("image_type of CL_MEM_OBJECT_BUFFER is invalid for clCreateImage.", CL_INVALID_IMAGE_DESCRIPTOR); case CL_MEM_OBJECT_IMAGE1D_ARRAY: if (image_desc->image_array_size > D3D12_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) return ReportError("Array size exceeds maximum Texture1D array dimensionality.", CL_INVALID_IMAGE_DESCRIPTOR); // fallthrough case CL_MEM_OBJECT_IMAGE1D: Args.m_appDesc.m_resourceDimension = D3D12_RESOURCE_DIMENSION_TEXTURE1D; if (image_desc->image_width > D3D12_REQ_TEXTURE1D_U_DIMENSION) return ReportError("Width exceeds maximum Texture1D width.", CL_INVALID_IMAGE_DESCRIPTOR); image_desc_copy.image_height = 0; image_desc_copy.image_depth = 0; break; case CL_MEM_OBJECT_IMAGE1D_BUFFER: if (image_desc->image_width > (2 << D3D12_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP)) return ReportError("Width exceeds maximum 1D image buffer width.", CL_INVALID_IMAGE_DESCRIPTOR); break; case CL_MEM_OBJECT_IMAGE2D_ARRAY: if (image_desc->image_array_size > D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) return ReportError("Array size exceeds maximum Texture2D array dimensionality.", CL_INVALID_IMAGE_DESCRIPTOR); // fallthrough case CL_MEM_OBJECT_IMAGE2D: Args.m_appDesc.m_resourceDimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; if (image_desc->image_width > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION) return ReportError("Width exceeds maximum Texture2D width.", CL_INVALID_IMAGE_DESCRIPTOR); if (image_desc->image_height > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION) return ReportError("Height exceeds maximum Texture2D height.", CL_INVALID_IMAGE_DESCRIPTOR); image_desc_copy.image_depth = 0; break; case CL_MEM_OBJECT_IMAGE3D: Args.m_appDesc.m_resourceDimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; if (image_desc->image_width > D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) return ReportError("Width exceeds maximum Texture3D width.", CL_INVALID_IMAGE_DESCRIPTOR); if (image_desc->image_height > D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) return ReportError("Height exceeds maximum Texture3D height.", CL_INVALID_IMAGE_DESCRIPTOR); if (image_desc->image_depth > D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) return ReportError("Depth exceeds maximum Texture3D depth.", CL_INVALID_IMAGE_DESCRIPTOR); break; default: return ReportError("Invalid image_type.", CL_INVALID_IMAGE_DESCRIPTOR); } Args.m_appDesc.m_NonOpaquePlaneCount = 1; Args.m_appDesc.m_MipLevels = 1; Args.m_appDesc.m_Depth = max((UINT)image_desc->image_depth, 1u); Args.m_appDesc.m_Width = max((UINT)image_desc->image_width, 1u); Args.m_appDesc.m_Height = max((UINT)image_desc->image_height, 1u); Args.m_appDesc.m_Format = GetDXGIFormatForCLImageFormat(*image_format); Args.m_appDesc.m_Samples = 1; Args.m_appDesc.m_Quality = 0; Args.m_appDesc.m_ArraySize = (UINT16)image_desc->image_array_size; if (image_desc->image_type != CL_MEM_OBJECT_IMAGE1D_ARRAY && image_desc->image_type != CL_MEM_OBJECT_IMAGE2D_ARRAY) { if (image_desc->image_array_size > 1) ReportError("image_array_size shouldn't be specified for non-array image types.", CL_SUCCESS); Args.m_appDesc.m_ArraySize = 1; image_desc_copy.image_array_size = 0; } else if (image_desc->image_array_size == 0) { return ReportError("image_array_size must be > 0 for array types.", CL_INVALID_IMAGE_DESCRIPTOR); } auto ElementByteSize = CD3D11FormatHelper::GetByteAlignment(Args.m_appDesc.m_Format); if (image_desc->image_row_pitch == 0) { image_desc_copy.image_row_pitch = ElementByteSize * image_desc->image_width; } else if (host_ptr == nullptr) { return ReportError("image_row_pitch must be 0 if host_ptr is null.", CL_INVALID_IMAGE_DESCRIPTOR); } else if (image_desc->image_row_pitch < ElementByteSize * image_desc->image_width || image_desc->image_row_pitch % ElementByteSize != 0) { return ReportError("image_row_pitch must be >= image_width * size of element in bytes, and must be a multiple of the element size in bytes.", CL_INVALID_IMAGE_DESCRIPTOR); } switch (image_desc->image_type) { case CL_MEM_OBJECT_IMAGE1D_ARRAY: case CL_MEM_OBJECT_IMAGE2D_ARRAY: case CL_MEM_OBJECT_IMAGE3D: if (image_desc->image_slice_pitch == 0) { image_desc_copy.image_slice_pitch = image_desc_copy.image_row_pitch * max<size_t>(image_desc->image_height, 1); } else if (host_ptr == nullptr) { return ReportError("image_slice_pitch must be 0 if host_ptr is null.", CL_INVALID_IMAGE_DESCRIPTOR); } else if (image_desc->image_slice_pitch < image_desc_copy.image_row_pitch * max<size_t>(image_desc->image_height, 1) || image_desc->image_slice_pitch % image_desc_copy.image_row_pitch != 0) { return ReportError("image_slice_pitch must be >= image_row_pitch * height (or just image_row_pitch for buffers), and must be a multiple of the image_row_pitch.", CL_INVALID_IMAGE_DESCRIPTOR); } break; default: image_desc_copy.image_slice_pitch = 0; } image_desc = &image_desc_copy; Args.m_appDesc.m_Subresources = Args.m_appDesc.m_ArraySize; Args.m_appDesc.m_SubresourcesPerPlane = Args.m_appDesc.m_ArraySize; if (image_desc->num_mip_levels != 0 || image_desc->num_samples != 0) { return ReportError("num_mip_levels and num_samples must be 0.", CL_INVALID_IMAGE_DESCRIPTOR); } image_desc_copy.num_mip_levels = 0; image_desc_copy.num_samples = 0; if (Args.m_appDesc.m_Format == DXGI_FORMAT_UNKNOWN) { return ReportError("Invalid image format.", CL_IMAGE_FORMAT_NOT_SUPPORTED); } if (image_desc->image_type == CL_MEM_OBJECT_IMAGE1D_BUFFER) { if (image_desc->buffer == nullptr) { return ReportError("When image_type is CL_MEM_OBJECT_IMAGE1D_BUFFER, buffer must be valid.", CL_INVALID_IMAGE_DESCRIPTOR); } Resource& buffer = *static_cast<Resource*>(image_desc->buffer); if (buffer.m_Desc.image_type != CL_MEM_OBJECT_BUFFER) { return ReportError("When image_type is CL_MEM_OBJECT_IMAGE1D_BUFFER, buffer must specify a buffer.", CL_INVALID_IMAGE_DESCRIPTOR); } if (!ValidateMemFlagsForBufferReference(flags, buffer, ReportError)) { return nullptr; } size_t size = CD3D11FormatHelper::GetByteAlignment(GetDXGIFormatForCLImageFormat(*image_format)) * image_desc->image_width; if (size > buffer.m_Desc.image_width) { return ReportError("1D image buffer size is too large.", CL_INVALID_IMAGE_DESCRIPTOR); } } else { if (image_desc->buffer != nullptr) { return ReportError("Only specify buffer when image_type is CL_MEM_OBJECT_IMAGE1D_BUFFER.", CL_INVALID_IMAGE_DESCRIPTOR); } } try { if (errcode_ret) *errcode_ret = CL_SUCCESS; if (image_desc->image_type == CL_MEM_OBJECT_IMAGE1D_BUFFER) { return Resource::CreateImage1DBuffer(*static_cast<Resource*>(image_desc->buffer), *image_format, *image_desc, flags); } else { Args.m_appDesc.m_usage = D3D12TranslationLayer::RESOURCE_USAGE_DEFAULT; Args.m_appDesc.m_bindFlags = D3D12TranslationLayer::RESOURCE_BIND_UNORDERED_ACCESS | D3D12TranslationLayer::RESOURCE_BIND_SHADER_RESOURCE; Args.m_heapDesc = CD3DX12_HEAP_DESC(0, D3D12_HEAP_TYPE_DEFAULT); ModifyResourceArgsForMemFlags(Args, flags); Args.m_desc12.Dimension = Args.m_appDesc.m_resourceDimension; Args.m_desc12.Width = Args.m_appDesc.m_Width; Args.m_desc12.Height = Args.m_appDesc.m_Height; Args.m_desc12.DepthOrArraySize = Args.m_desc12.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? (UINT16)Args.m_appDesc.m_Depth : Args.m_appDesc.m_ArraySize; Args.m_desc12.Format = Args.m_appDesc.m_Format; Args.m_desc12.MipLevels = Args.m_appDesc.m_MipLevels; Args.m_desc12.SampleDesc = { Args.m_appDesc.m_Samples, Args.m_appDesc.m_Quality }; Args.m_desc12.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; Args.m_desc12.Flags = D3D12_RESOURCE_FLAG_NONE; if ((flags & DeviceReadWriteFlagsMask) == 0 || (flags & (CL_MEM_READ_WRITE | CL_MEM_WRITE_ONLY))) Args.m_desc12.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; return Resource::CreateImage(context, Args, host_ptr, *image_format, *image_desc, flags); } } catch (std::bad_alloc &) { return ReportError(nullptr, CL_OUT_OF_HOST_MEMORY); } catch (_com_error &e) { if (e.Error() == E_INVALIDARG) return ReportError("Invalid buffer description.", CL_INVALID_VALUE); return ReportError(nullptr, CL_OUT_OF_RESOURCES); } catch (std::exception &e) { return ReportError(e.what(), CL_OUT_OF_RESOURCES); } } extern CL_API_ENTRY cl_mem CL_API_CALL clCreateImage(cl_context context, cl_mem_flags flags, const cl_image_format * image_format, const cl_image_desc * image_desc, void * host_ptr, cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2 { return clCreateImageWithProperties(context, nullptr, flags, image_format, image_desc, host_ptr, errcode_ret); } extern CL_API_ENTRY CL_API_PREFIX__VERSION_1_1_DEPRECATED cl_mem CL_API_CALL clCreateImage2D(cl_context context, cl_mem_flags flags, const cl_image_format * image_format, size_t image_width, size_t image_height, size_t image_row_pitch, void * host_ptr, cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_1_DEPRECATED { cl_image_desc desc = {}; desc.image_type = CL_MEM_OBJECT_IMAGE2D; desc.image_width = image_width; desc.image_height = image_height; desc.image_row_pitch = image_row_pitch; return clCreateImage(context, flags, image_format, &desc, host_ptr, errcode_ret); } extern CL_API_ENTRY CL_API_PREFIX__VERSION_1_1_DEPRECATED cl_mem CL_API_CALL clCreateImage3D(cl_context context, cl_mem_flags flags, const cl_image_format * image_format, size_t image_width, size_t image_height, size_t image_depth, size_t image_row_pitch, size_t image_slice_pitch, void * host_ptr, cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_1_DEPRECATED { cl_image_desc desc = {}; desc.image_type = CL_MEM_OBJECT_IMAGE3D; desc.image_width = image_width; desc.image_height = image_height; desc.image_depth = image_depth; desc.image_row_pitch = image_row_pitch; desc.image_slice_pitch = image_slice_pitch; return clCreateImage(context, flags, image_format, &desc, host_ptr, errcode_ret); } extern CL_API_ENTRY cl_int CL_API_CALL clRetainMemObject(cl_mem memobj) CL_API_SUFFIX__VERSION_1_0 { if (!memobj) { return CL_INVALID_MEM_OBJECT; } static_cast<Resource*>(memobj)->Retain(); return CL_SUCCESS; } extern CL_API_ENTRY cl_int CL_API_CALL clReleaseMemObject(cl_mem memobj) CL_API_SUFFIX__VERSION_1_0 { if (!memobj) { return CL_INVALID_MEM_OBJECT; } static_cast<Resource*>(memobj)->Release(); return CL_SUCCESS; } extern CL_API_ENTRY cl_int CL_API_CALL clGetSupportedImageFormats(cl_context context_, cl_mem_flags flags, cl_mem_object_type image_type, cl_uint num_entries, cl_image_format * image_formats, cl_uint * num_image_formats) CL_API_SUFFIX__VERSION_1_0 { if (!context_) { return CL_INVALID_CONTEXT; } Context& context = *static_cast<Context*>(context_); auto ReportError = context.GetErrorReporter(); { cl_int validation_error; if (!ValidateMemFlagsBase(flags, context.GetErrorReporter(&validation_error))) { return validation_error; } } switch (image_type) { case CL_MEM_OBJECT_IMAGE1D: case CL_MEM_OBJECT_IMAGE1D_ARRAY: case CL_MEM_OBJECT_IMAGE1D_BUFFER: case CL_MEM_OBJECT_IMAGE2D: case CL_MEM_OBJECT_IMAGE2D_ARRAY: case CL_MEM_OBJECT_IMAGE3D: break; default: return ReportError("Invalid image_type.", CL_INVALID_VALUE); } if (num_entries == 0 && image_formats != nullptr) { return ReportError("num_entries must be nonzero when image_formats is not null.", CL_INVALID_VALUE); } cl_uint NumFormats = 0; for (UINT i = 0; i < DXGI_FORMAT_B8G8R8X8_UNORM; ++i) { bool IsSupported = [&]() { for (cl_uint device = 0; device < context.GetDeviceCount(); ++device) { D3D12_FEATURE_DATA_FORMAT_SUPPORT Support = { (DXGI_FORMAT)i }; if (FAILED(context.GetDevice(device).GetDevice()->CheckFeatureSupport( D3D12_FEATURE_FORMAT_SUPPORT, &Support, sizeof(Support)))) { return false; } if ((flags & (CL_MEM_WRITE_ONLY | CL_MEM_READ_WRITE)) && (Support.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE) == D3D12_FORMAT_SUPPORT2_NONE) { return false; } if ((flags & (CL_MEM_READ_ONLY | CL_MEM_READ_WRITE)) && (Support.Support1 & D3D12_FORMAT_SUPPORT1_SHADER_LOAD) == D3D12_FORMAT_SUPPORT1_NONE) { return false; } if ((flags & CL_MEM_KERNEL_READ_AND_WRITE) && (Support.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD) == D3D12_FORMAT_SUPPORT2_NONE) { return false; } D3D12_FORMAT_SUPPORT1 bit = D3D12_FORMAT_SUPPORT1_NONE; switch (image_type) { case CL_MEM_OBJECT_IMAGE1D_BUFFER: bit = D3D12_FORMAT_SUPPORT1_BUFFER; break; case CL_MEM_OBJECT_IMAGE1D: case CL_MEM_OBJECT_IMAGE1D_ARRAY: bit = D3D12_FORMAT_SUPPORT1_TEXTURE1D; break; case CL_MEM_OBJECT_IMAGE2D: case CL_MEM_OBJECT_IMAGE2D_ARRAY: bit = D3D12_FORMAT_SUPPORT1_TEXTURE2D; break; case CL_MEM_OBJECT_IMAGE3D: bit = D3D12_FORMAT_SUPPORT1_TEXTURE3D; break; } if ((Support.Support1 & bit) == D3D12_FORMAT_SUPPORT1_NONE) { return false; } } return true; }(); if (!IsSupported) continue; cl_image_format format = GetCLImageFormatForDXGIFormat((DXGI_FORMAT)i); if (format.image_channel_data_type != 0) { if (NumFormats < num_entries && image_formats) { image_formats[NumFormats] = format; } ++NumFormats; } } if (num_image_formats) { *num_image_formats = NumFormats; } return CL_SUCCESS; } extern CL_API_ENTRY cl_int CL_API_CALL clGetMemObjectInfo(cl_mem memobj, cl_mem_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0 { if (!memobj) { return CL_INVALID_MEM_OBJECT; } Resource& resource = *static_cast<Resource*>(memobj); auto RetValue = [&](auto&& param) { return CopyOutParameter(param, param_value_size, param_value, param_value_size_ret); }; switch (param_name) { case CL_MEM_TYPE: return RetValue(resource.m_Desc.image_type); case CL_MEM_FLAGS: return RetValue(resource.m_Flags); case CL_MEM_SIZE: { if (resource.m_Desc.image_type == CL_MEM_OBJECT_BUFFER) return RetValue(resource.m_Desc.image_width); auto Underlying = resource.GetActiveUnderlyingResource(); if (!Underlying) Underlying = resource.GetUnderlyingResource(&resource.m_Parent->GetDevice(0)); return RetValue((size_t)Underlying->GetResourceSize()); // TODO: GetResourceAllocationInfo instead? } case CL_MEM_HOST_PTR: return RetValue(resource.m_pHostPointer); case CL_MEM_MAP_COUNT: return RetValue(resource.GetMapCount()); case CL_MEM_REFERENCE_COUNT: return RetValue(resource.GetRefCount()); case CL_MEM_CONTEXT: return RetValue(&resource.m_Parent.get()); case CL_MEM_ASSOCIATED_MEMOBJECT: return RetValue(resource.m_ParentBuffer.Get()); case CL_MEM_OFFSET: return RetValue(resource.m_Offset); case CL_MEM_USES_SVM_POINTER: return RetValue((bool)CL_FALSE); case CL_MEM_PROPERTIES: return RetValue(nullptr); } return resource.m_Parent->GetErrorReporter()("Unknown param_name", CL_INVALID_VALUE); } extern CL_API_ENTRY cl_int CL_API_CALL clGetImageInfo(cl_mem image, cl_image_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0 { if (!image) { return CL_INVALID_MEM_OBJECT; } Resource& resource = *static_cast<Resource*>(image); if (resource.m_Desc.image_type == CL_MEM_OBJECT_BUFFER) { return resource.m_Parent->GetErrorReporter()("clGetImageInfo cannot be called on a buffer.", CL_INVALID_MEM_OBJECT); } auto RetValue = [&](auto&& param) { return CopyOutParameter(param, param_value_size, param_value, param_value_size_ret); }; switch (param_name) { case CL_IMAGE_FORMAT: return RetValue(resource.m_Format); case CL_IMAGE_ELEMENT_SIZE: return RetValue((size_t)CD3D11FormatHelper::GetByteAlignment(GetDXGIFormatForCLImageFormat(resource.m_Format))); case CL_IMAGE_ROW_PITCH: return RetValue(resource.m_Desc.image_row_pitch); case CL_IMAGE_SLICE_PITCH: return RetValue(resource.m_Desc.image_slice_pitch); case CL_IMAGE_WIDTH: return RetValue(resource.m_Desc.image_width); case CL_IMAGE_HEIGHT: return RetValue(resource.m_Desc.image_height); case CL_IMAGE_DEPTH: return RetValue(resource.m_Desc.image_depth); case CL_IMAGE_ARRAY_SIZE: return RetValue(resource.m_Desc.image_array_size); case CL_IMAGE_BUFFER: return RetValue(resource.m_Desc.buffer); case CL_IMAGE_NUM_MIP_LEVELS: return RetValue(resource.m_Desc.num_mip_levels); case CL_IMAGE_NUM_SAMPLES: return RetValue(resource.m_Desc.num_samples); } return resource.m_Parent->GetErrorReporter()("Unknown param_name", CL_INVALID_VALUE); } auto Resource::GetUnderlyingResource(Device* device) -> UnderlyingResource* { std::lock_guard Lock(m_MultiDeviceLock); auto& Entry = m_UnderlyingMap[device]; if (Entry.get()) return Entry.get(); if (m_ParentBuffer.Get()) { Entry.reset(m_ParentBuffer->GetUnderlyingResource(device)); } else { Entry = UnderlyingResource::CreateResource(&device->ImmCtx(), m_CreationArgs, D3D12TranslationLayer::ResourceAllocationContext::FreeThread); } if (m_CreationArgs.m_desc12.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) { m_UAVs.try_emplace(device, &device->ImmCtx(), m_UAVDesc, *Entry.get()); } if (m_Desc.image_type != CL_MEM_OBJECT_BUFFER && Entry->GetEffectiveUsage() == D3D12TranslationLayer::RESOURCE_USAGE_DEFAULT) { m_SRVs.try_emplace(device, &device->ImmCtx(), m_SRVDesc, *Entry.get()); } return Entry.get(); } void Resource::SetActiveDevice(Device* device) { std::lock_guard Lock(m_MultiDeviceLock); m_ActiveUnderlying = GetUnderlyingResource(device); m_CurrentActiveDevice = device; } D3D12TranslationLayer::SRV& Resource::GetSRV(Device* device) { auto iter = m_SRVs.find(device); assert(iter != m_SRVs.end()); return iter->second; } D3D12TranslationLayer::UAV& Resource::GetUAV(Device* device) { auto iter = m_UAVs.find(device); assert(iter != m_UAVs.end()); return iter->second; } Resource* Resource::CreateBuffer(Context& Parent, D3D12TranslationLayer::ResourceCreationArgs& Args, void* pHostPointer, cl_mem_flags flags) { return new Resource(Parent, Args, pHostPointer, Args.m_appDesc.m_Width, flags); } Resource* Resource::CreateSubBuffer(Resource& ParentBuffer, const cl_buffer_region& region, cl_mem_flags flags) { cl_image_format image_format = {}; return new Resource(ParentBuffer, region.origin, region.size, image_format, CL_MEM_OBJECT_BUFFER, flags); } Resource* Resource::CreateImage(Context& Parent, D3D12TranslationLayer::ResourceCreationArgs& Args, void* pHostPointer, const cl_image_format& image_format, const cl_image_desc& image_desc, cl_mem_flags flags) { return new Resource(Parent, Args, pHostPointer, image_format, image_desc, flags); } Resource* Resource::CreateImage1DBuffer(Resource& ParentBuffer, const cl_image_format& image_format, const cl_image_desc& image_desc, cl_mem_flags flags) { return new Resource(ParentBuffer, 0, image_desc.image_width, image_format, image_desc.image_type, flags); } Resource::Resource(Context& Parent, D3D12TranslationLayer::ResourceCreationArgs const& CreationArgs, void* pHostPointer, size_t size, cl_mem_flags flags) : CLChildBase(Parent) , m_Flags(flags) , m_pHostPointer(pHostPointer) , m_Desc(GetBufferDesc(size, CL_MEM_OBJECT_BUFFER)) , m_CreationArgs(CreationArgs) { if (pHostPointer) { m_InitialData.reset(new byte[size]); memcpy(m_InitialData.get(), pHostPointer, size); } auto& UAVDescWrapper = m_UAVDesc; auto& UAVDesc = UAVDescWrapper.m_Desc12; UAVDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; UAVDesc.Format = DXGI_FORMAT_R32_TYPELESS; UAVDesc.Buffer.CounterOffsetInBytes = 0; UAVDesc.Buffer.StructureByteStride = 0; UAVDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; UAVDesc.Buffer.FirstElement = m_Offset / 4; UAVDesc.Buffer.NumElements = (UINT)((size - 1) / 4) + 1; UAVDescWrapper.m_D3D11UAVFlags = D3D11_BUFFER_UAV_FLAG_RAW; } Resource::Resource(Resource& ParentBuffer, size_t offset, size_t size, const cl_image_format& image_format, cl_mem_object_type type, cl_mem_flags flags) : CLChildBase(ParentBuffer.m_Parent.get()) , m_pHostPointer(ParentBuffer.m_pHostPointer && type == CL_MEM_OBJECT_BUFFER ? reinterpret_cast<char*>(ParentBuffer.m_pHostPointer) + offset : nullptr) , m_Flags(flags) , m_ParentBuffer(&ParentBuffer) , m_Format(image_format) , m_Offset(offset) , m_Desc(GetBufferDesc(size, type)) , m_CreationArgs(ParentBuffer.m_CreationArgs) { if (type == CL_MEM_OBJECT_IMAGE1D_BUFFER) { DXGI_FORMAT DXGIFormat = GetDXGIFormatForCLImageFormat(image_format); assert(m_Offset == 0); { auto& UAVDescWrapper = m_UAVDesc; auto &UAVDesc = UAVDescWrapper.m_Desc12; UAVDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; UAVDesc.Format = DXGIFormat; UAVDesc.Buffer.CounterOffsetInBytes = 0; UAVDesc.Buffer.StructureByteStride = 0; UAVDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE; UAVDesc.Buffer.FirstElement = 0; // m_Offset / FormatByteSize; UAVDesc.Buffer.NumElements = (UINT)size; UAVDescWrapper.m_D3D11UAVFlags = 0; } { auto& SRVDesc = m_SRVDesc; SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; SRVDesc.Format = DXGIFormat; SRVDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; SRVDesc.Buffer.StructureByteStride = 0; SRVDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; SRVDesc.Buffer.FirstElement = 0; // m_Offset / FormatByteSize; SRVDesc.Buffer.NumElements = (UINT)size; } } else { auto& UAVDescWrapper = m_UAVDesc; auto& UAVDesc = UAVDescWrapper.m_Desc12; UAVDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; UAVDesc.Format = DXGI_FORMAT_R32_TYPELESS; UAVDesc.Buffer.CounterOffsetInBytes = 0; UAVDesc.Buffer.StructureByteStride = 0; UAVDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; UAVDesc.Buffer.FirstElement = m_Offset / 4; UAVDesc.Buffer.NumElements = (UINT)((size - 1) / 4) + 1; UAVDescWrapper.m_D3D11UAVFlags = D3D11_BUFFER_UAV_FLAG_RAW; } } Resource::Resource(Context& Parent, D3D12TranslationLayer::ResourceCreationArgs const& Args, void* pHostPointer, const cl_image_format& image_format, const cl_image_desc& image_desc, cl_mem_flags flags) : CLChildBase(Parent) , m_pHostPointer(pHostPointer) , m_Format(image_format) , m_Desc(image_desc) , m_Flags(flags) , m_CreationArgs(Args) { if (pHostPointer) { size_t size = GetFormatSizeBytes(image_format) * image_desc.image_width + image_desc.image_row_pitch * (m_CreationArgs.m_desc12.Height - 1) + image_desc.image_slice_pitch * (m_CreationArgs.m_desc12.DepthOrArraySize - 1); m_InitialData.reset(new byte[size]); memcpy(m_InitialData.get(), pHostPointer, size); } DXGI_FORMAT DXGIFormat = GetDXGIFormatForCLImageFormat(image_format); { auto& UAVDescWrapper = m_UAVDesc; auto &UAVDesc = UAVDescWrapper.m_Desc12; UAVDesc.Format = DXGIFormat; switch (image_desc.image_type) { case CL_MEM_OBJECT_IMAGE1D: UAVDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; UAVDesc.Texture1D.MipSlice = 0; break; case CL_MEM_OBJECT_IMAGE1D_ARRAY: UAVDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY; UAVDesc.Texture1DArray.FirstArraySlice = 0; UAVDesc.Texture1DArray.ArraySize = (UINT)image_desc.image_array_size; UAVDesc.Texture1DArray.MipSlice = 0; break; case CL_MEM_OBJECT_IMAGE2D: UAVDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; UAVDesc.Texture2D.MipSlice = 0; UAVDesc.Texture2D.PlaneSlice = 0; break; case CL_MEM_OBJECT_IMAGE2D_ARRAY: UAVDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; UAVDesc.Texture2DArray.FirstArraySlice = 0; UAVDesc.Texture2DArray.ArraySize = (UINT)image_desc.image_array_size; UAVDesc.Texture2DArray.MipSlice = 0; UAVDesc.Texture2DArray.PlaneSlice = 0; break; case CL_MEM_OBJECT_IMAGE3D: UAVDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; UAVDesc.Texture3D.FirstWSlice = 0; UAVDesc.Texture3D.WSize = (UINT)image_desc.image_depth; UAVDesc.Texture3D.MipSlice = 0; break; default: assert(false); } } { auto& SRVDesc = m_SRVDesc; SRVDesc.Format = DXGIFormat; SRVDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; switch (image_desc.image_type) { case CL_MEM_OBJECT_IMAGE1D: SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D; SRVDesc.Texture1D.MipLevels = 1; SRVDesc.Texture1D.MostDetailedMip = 0; SRVDesc.Texture1D.ResourceMinLODClamp = 0; break; case CL_MEM_OBJECT_IMAGE1D_ARRAY: SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1DARRAY; SRVDesc.Texture1DArray.FirstArraySlice = 0; SRVDesc.Texture1DArray.ArraySize = (UINT)image_desc.image_array_size; SRVDesc.Texture1DArray.MipLevels = 1; SRVDesc.Texture1DArray.MostDetailedMip = 0; SRVDesc.Texture1DArray.ResourceMinLODClamp = 0; break; case CL_MEM_OBJECT_IMAGE2D: SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; SRVDesc.Texture2D.MipLevels = 1; SRVDesc.Texture2D.MostDetailedMip = 0; SRVDesc.Texture2D.PlaneSlice = 0; SRVDesc.Texture2D.ResourceMinLODClamp = 0; break; case CL_MEM_OBJECT_IMAGE2D_ARRAY: SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; SRVDesc.Texture2DArray.FirstArraySlice = 0; SRVDesc.Texture2DArray.ArraySize = (UINT)image_desc.image_array_size; SRVDesc.Texture2DArray.MipLevels = 1; SRVDesc.Texture2DArray.MostDetailedMip = 0; SRVDesc.Texture2DArray.PlaneSlice = 0; SRVDesc.Texture2DArray.ResourceMinLODClamp = 0; break; case CL_MEM_OBJECT_IMAGE3D: SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; SRVDesc.Texture3D.MipLevels = 1; SRVDesc.Texture3D.MostDetailedMip = 0; SRVDesc.Texture3D.ResourceMinLODClamp = 0; break; default: assert(false); } } } Resource::~Resource() { for (auto&& [ptr, vec] : m_OutstandingMaps) { for (auto& map : vec) { map->Unmap(true); } } for (auto iter = m_DestructorCallbacks.rbegin(); iter != m_DestructorCallbacks.rend(); ++iter) { auto& callback = *iter; callback.m_pfn(this, callback.m_userData); } } void Resource::AddMapTask(MapTask *task) { std::lock_guard MapLock(m_MapLock); m_OutstandingMaps[task->GetPointer()].emplace_back(task); ++m_MapCount; } MapTask* Resource::GetMapTask(void* ptr) { std::lock_guard MapLock(m_MapLock); auto iter = m_OutstandingMaps.find(ptr); if (iter == m_OutstandingMaps.end()) return nullptr; auto& vec = iter->second; assert(!vec.empty()); return vec.front().Get(); } void Resource::RemoveMapTask(MapTask *task) { std::lock_guard MapLock(m_MapLock); auto iter = m_OutstandingMaps.find(task->GetPointer()); if (iter == m_OutstandingMaps.end()) return; auto& vec = iter->second; auto vecIter = std::find_if(vec.begin(), vec.end(), [task](::ref_ptr_int<MapTask> const& ptr) { return ptr.Get() == task; }); if (vecIter == vec.end()) return; --m_MapCount; vec.erase(vecIter); if (!vec.empty()) return; m_OutstandingMaps.erase(iter); } void Resource::AddDestructionCallback(DestructorCallback::Fn pfn, void* pUserData) { std::lock_guard DestructorLock(m_DestructorLock); m_DestructorCallbacks.push_back({ pfn, pUserData }); } cl_image_desc Resource::GetBufferDesc(size_t size, cl_mem_object_type type) { cl_image_desc desc = {}; desc.image_width = size; desc.image_type = type; return desc; } extern CL_API_ENTRY cl_int CL_API_CALL clSetMemObjectDestructorCallback(cl_mem memobj, void (CL_CALLBACK * pfn_notify)(cl_mem memobj, void * user_data), void * user_data) CL_API_SUFFIX__VERSION_1_1 { if (!memobj) { return CL_INVALID_MEM_OBJECT; } if (!pfn_notify) { return CL_INVALID_VALUE; } static_cast<Resource*>(memobj)->AddDestructionCallback(pfn_notify, user_data); return CL_SUCCESS; } <|start_filename|>src/compilers/v1/compiler_v1.cpp<|end_filename|> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #define NOMINMAX #include "clc_compiler.h" #include "compiler.hpp" #include "cache.hpp" #include "platform.hpp" class CompilerV1 : public Compiler { private: XPlatHelpers::unique_module m_Compiler; std::mutex m_InitializationLock; std::unique_ptr<clc_context, void(*)(clc_context*)> m_Context{nullptr, nullptr}; public: CompilerV1(XPlatHelpers::unique_module compiler); static CompilerV1 *Instance(); // Compiler functions decltype(&clc_context_new) CreateContext = nullptr; decltype(&clc_context_serialize) SerializeContext = nullptr; decltype(&clc_context_deserialize) DeserializeContext = nullptr; decltype(&clc_context_free_serialized) FreeSerializedContext = nullptr; decltype(&clc_free_context) FreeContext = nullptr; decltype(&clc_compile) CompileImpl = nullptr; decltype(&clc_link) LinkImpl = nullptr; decltype(&clc_free_object) FreeSpirv = nullptr; decltype(&clc_to_dxil) GetKernelImpl = nullptr; decltype(&clc_free_dxil_object) FreeDxil = nullptr; decltype(&clc_compiler_get_version) GetCompilerVersion = nullptr; clc_context *GetContext() const { return m_Context.get(); } // Inherited via Compiler virtual ~CompilerV1() = default; virtual bool Initialize(ShaderCache &cache) final; virtual std::unique_ptr<ProgramBinary> Compile(CompileArgs const& args, Logger const& logger) const final; virtual std::unique_ptr<ProgramBinary> Link(LinkerArgs const& args, Logger const& logger) const final; virtual std::unique_ptr<ProgramBinary> Load(const void *data, size_t size) const final; virtual std::unique_ptr<CompiledDxil> GetKernel(const char *name, ProgramBinary const& obj, CompiledDxil::Configuration const *, Logger const *logger) const final; virtual std::byte * CopyWorkProperties(std::byte *WorkPropertiesBuffer, WorkProperties const& props) const final; virtual size_t GetWorkPropertiesChunkSize() const final; virtual uint64_t GetVersionForCache() const final; }; class ProgramBinaryV1 : public ProgramBinary { public: using unique_ptr = std::unique_ptr<clc_object, void(*)(clc_object*)>; private: unique_ptr m_Object; public: ProgramBinaryV1(unique_ptr obj); clc_object *GetRaw() const { return m_Object.get(); } // Inherited via ProgramBinary virtual ~ProgramBinaryV1() = default; virtual bool Parse(Logger const *logger) final; virtual size_t GetBinarySize() const final; virtual const void *GetBinary() const final; }; class CompiledDxilV1 : public CompiledDxil { public: using unique_ptr = std::unique_ptr<clc_dxil_object, void(*)(clc_dxil_object*)>; private: unique_ptr m_Object; public: CompiledDxilV1(ProgramBinaryV1 const& parent, unique_ptr obj); clc_dxil_object *GetRaw() const { return m_Object.get(); } // Inherited via CompiledDxil virtual ~CompiledDxilV1() = default; virtual size_t GetBinarySize() const final; virtual const void *GetBinary() const final; virtual void *GetBinary() final; }; static clc_logger ConvertLogger(Logger const& logger) { auto log = [](void *ctx, const char *msg) { static_cast<Logger*>(ctx)->Log(msg); }; clc_logger ret; ret.error = log; ret.warning = log; ret.priv = (void*)&logger; return ret; } #if 0 #endif CompilerV1::CompilerV1(XPlatHelpers::unique_module compiler) : m_Compiler(std::move(compiler)) { #define GET_FUNC(Member, api) Member = m_Compiler.proc_address<decltype(&api)>(#api) GET_FUNC(CreateContext, clc_context_new); GET_FUNC(SerializeContext, clc_context_serialize); GET_FUNC(DeserializeContext, clc_context_deserialize); GET_FUNC(FreeSerializedContext, clc_context_free_serialized); GET_FUNC(FreeContext, clc_free_context); GET_FUNC(CompileImpl, clc_compile); GET_FUNC(LinkImpl, clc_link); GET_FUNC(FreeSpirv, clc_free_object); GET_FUNC(GetKernelImpl, clc_to_dxil); GET_FUNC(FreeDxil, clc_free_dxil_object); GET_FUNC(GetCompilerVersion, clc_compiler_get_version); #undef GET_FUNC // Older versions of the v1 compiler interface didn't have support for "context" serialization // and didn't have version info exported. These aren't strictly required to work. if (!CreateContext || !FreeContext || !CompileImpl || !LinkImpl || !FreeSpirv || !GetKernelImpl || !FreeDxil) throw std::runtime_error("Failed to load required compiler entrypoints"); m_Context = decltype(m_Context)(nullptr, FreeContext); } CompilerV1 *CompilerV1::Instance() { return static_cast<CompilerV1*>(g_Platform->GetCompiler()); } bool CompilerV1::Initialize(ShaderCache &cache) { if (m_Context) return true; std::lock_guard lock(m_InitializationLock); if (m_Context) return true; // {1B9DC5F4-545A-4356-98D3-B4C0062E6253} static const GUID ClcContextKey = { <KEY> { 0x98, 0xd3, 0xb4, 0xc0, 0x6, 0x2e, 0x62, 0x53 } }; if (DeserializeContext) { if (auto CachedContext = cache.Find(&ClcContextKey, sizeof(ClcContextKey)); CachedContext.first) { m_Context.reset(DeserializeContext(CachedContext.first.get(), CachedContext.second)); return true; } } clc_context_options options = {}; options.optimize = cache.HasCache() && SerializeContext && FreeSerializedContext; m_Context.reset(CreateContext(nullptr, &options)); if (m_Context && options.optimize) { void* serialized = nullptr; size_t serializedSize = 0; SerializeContext(m_Context.get(), &serialized, &serializedSize); if (serialized) { try { cache.Store(&ClcContextKey, sizeof(ClcContextKey), serialized, serializedSize); } catch (...) {} FreeSerializedContext(serialized); } } return m_Context != nullptr; } std::unique_ptr<ProgramBinary> CompilerV1::Compile(CompileArgs const& args, Logger const& logger) const { ProgramBinaryV1::unique_ptr obj(nullptr, FreeSpirv); clc_compile_args args_impl; args_impl.args = args.cmdline_args.data(); args_impl.num_args = (unsigned)args.cmdline_args.size(); args_impl.source = { "source.cl", args.program_source }; static_assert(sizeof(clc_named_value) == sizeof(CompileArgs::Header)); static_assert(offsetof(clc_named_value, name) == offsetof(CompileArgs::Header, name)); static_assert(offsetof(clc_named_value, value) == offsetof(CompileArgs::Header, contents)); args_impl.headers = (clc_named_value*)args.headers.data(); args_impl.num_headers = (unsigned)args.headers.size(); auto logger_impl = ConvertLogger(logger); obj.reset(CompileImpl(GetContext(), &args_impl, &logger_impl)); return obj ? std::make_unique<ProgramBinaryV1>(std::move(obj)) : nullptr; } std::unique_ptr<ProgramBinary> CompilerV1::Link(LinkerArgs const& args, Logger const& logger) const { ProgramBinaryV1::unique_ptr linked(nullptr, FreeSpirv); std::vector<clc_object *> raw_objs; raw_objs.reserve(args.objs.size()); for (auto& obj : args.objs) raw_objs.push_back(static_cast<ProgramBinaryV1 const*>(obj)->GetRaw()); clc_linker_args args_impl; args_impl.create_library = args.create_library; args_impl.num_in_objs = (unsigned)raw_objs.size(); args_impl.in_objs = raw_objs.data(); auto logger_impl = ConvertLogger(logger); linked.reset(LinkImpl(GetContext(), &args_impl, &logger_impl)); if (!linked) return nullptr; auto ret = std::make_unique<ProgramBinaryV1>(std::move(linked)); if (!ret) return nullptr; if (!ret->Parse(&logger)) return nullptr; return ret; } std::unique_ptr<ProgramBinary> CompilerV1::Load(const void *data, size_t size) const { auto deleter = [](clc_object *obj) { if (obj->spvbin.data) delete[] obj->spvbin.data; delete obj; }; ProgramBinaryV1::unique_ptr obj(new clc_object{}, deleter); obj->spvbin.size = size; obj->spvbin.data = new uint32_t[size / 4]; memcpy(obj->spvbin.data, data, size); return std::make_unique<ProgramBinaryV1>(std::move(obj)); } std::unique_ptr<CompiledDxil> CompilerV1::GetKernel(const char *name, ProgramBinary const& obj, CompiledDxil::Configuration const *conf, Logger const *logger) const { CompiledDxilV1::unique_ptr dxil(nullptr, FreeDxil); clc_runtime_kernel_conf conf_impl; std::vector<clc_runtime_arg_info> conf_args; if (conf) { std::copy(conf->local_size, std::end(conf->local_size), conf_impl.local_size); conf_impl.lower_bit_size = (conf->lower_int16 ? 16 : 0) | (conf->lower_int64 ? 64 : 0); conf_impl.support_global_work_id_offsets = conf->support_global_work_id_offsets; conf_impl.support_work_group_id_offsets = conf->support_work_group_id_offsets; conf_args.resize(conf->args.size()); for (auto& arg : conf->args) { clc_runtime_arg_info arg_impl; if (auto local = std::get_if<CompiledDxil::Configuration::Arg::Local>(&arg.config); local) { arg_impl.localptr.size = local->size; } else if (auto sampler = std::get_if<CompiledDxil::Configuration::Arg::Sampler>(&arg.config); sampler) { arg_impl.sampler.addressing_mode = sampler->addressingMode; arg_impl.sampler.linear_filtering = sampler->linearFiltering; arg_impl.sampler.normalized_coords = sampler->normalizedCoords; } conf_args.push_back(arg_impl); } conf_impl.args = conf_args.data(); } clc_logger logger_impl; if (logger) logger_impl = ConvertLogger(*logger); dxil.reset(GetKernelImpl(GetContext(), static_cast<ProgramBinaryV1 const&>(obj).GetRaw(), name, conf ? &conf_impl : nullptr, logger ? &logger_impl : nullptr)); return dxil ? std::make_unique<CompiledDxilV1>(static_cast<ProgramBinaryV1 const&>(obj), std::move(dxil)) : nullptr; } std::byte *CompilerV1::CopyWorkProperties(std::byte *WorkPropertiesBuffer, WorkProperties const& props) const { static_assert(sizeof(props) == sizeof(clc_work_properties_data)); static_assert(offsetof(WorkProperties, global_offset_z) == offsetof(clc_work_properties_data, global_offset_z)); static_assert(offsetof(WorkProperties, work_dim) == offsetof(clc_work_properties_data, work_dim)); static_assert(offsetof(WorkProperties, group_count_total_z) == offsetof(clc_work_properties_data, group_count_total_z)); static_assert(offsetof(WorkProperties, group_id_offset_z) == offsetof(clc_work_properties_data, group_id_offset_z)); memcpy(WorkPropertiesBuffer, &props, sizeof(props)); return WorkPropertiesBuffer + GetWorkPropertiesChunkSize(); } size_t CompilerV1::GetWorkPropertiesChunkSize() const { return std::max<size_t>(sizeof(clc_work_properties_data), D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT); } uint64_t CompilerV1::GetVersionForCache() const { if (GetCompilerVersion) { return GetCompilerVersion(); } #if _WIN32 else { WCHAR FileName[MAX_PATH]; DWORD FileNameLength = GetModuleFileNameW(m_Compiler.get(), FileName, ARRAYSIZE(FileName)); if (FileNameLength != 0 && FileNameLength != ARRAYSIZE(FileName)) { HANDLE hFile = CreateFileW(FileName, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile != INVALID_HANDLE_VALUE) { FILETIME Time = {}; GetFileTime(hFile, nullptr, nullptr, &Time); CloseHandle(hFile); return reinterpret_cast<UINT64&>(Time); } } } #endif return 0; } ProgramBinaryV1::ProgramBinaryV1(unique_ptr obj) : m_Object(std::move(obj)) { } bool ProgramBinaryV1::Parse(Logger const *) { if (m_KernelInfo.size()) return true; if (m_Object->num_kernels) { m_KernelInfo.reserve(m_Object->num_kernels); for (unsigned i = 0; i < m_Object->num_kernels; ++i) { Kernel info; info.name = m_Object->kernels[i].name; info.vec_hint_size = m_Object->kernels[i].vec_hint_size; static_assert(CLC_VEC_HINT_TYPE_CHAR == (int)Kernel::VecHintType::Char); static_assert(CLC_VEC_HINT_TYPE_SHORT == (int)Kernel::VecHintType::Short); static_assert(CLC_VEC_HINT_TYPE_INT == (int)Kernel::VecHintType::Int); static_assert(CLC_VEC_HINT_TYPE_LONG == (int)Kernel::VecHintType::Long); static_assert(CLC_VEC_HINT_TYPE_HALF == (int)Kernel::VecHintType::Half); static_assert(CLC_VEC_HINT_TYPE_FLOAT == (int)Kernel::VecHintType::Float); static_assert(CLC_VEC_HINT_TYPE_DOUBLE == (int)Kernel::VecHintType::Double); info.vec_hint_type = (Kernel::VecHintType)m_Object->kernels[i].vec_hint_type; info.args.reserve(m_Object->kernels[i].num_args); for (unsigned j = 0; j < m_Object->kernels[i].num_args; ++j) { Kernel::Arg arg; static_assert(CLC_KERNEL_ARG_ADDRESS_PRIVATE == (int)Kernel::Arg::AddressSpace::Private); static_assert(CLC_KERNEL_ARG_ADDRESS_CONSTANT == (int)Kernel::Arg::AddressSpace::Constant); static_assert(CLC_KERNEL_ARG_ADDRESS_LOCAL == (int)Kernel::Arg::AddressSpace::Local); static_assert(CLC_KERNEL_ARG_ADDRESS_GLOBAL == (int)Kernel::Arg::AddressSpace::Global); arg.address_qualifier = (Kernel::Arg::AddressSpace)m_Object->kernels[i].args[j].address_qualifier; arg.is_const = (m_Object->kernels[i].args[j].type_qualifier & CLC_KERNEL_ARG_TYPE_CONST) != 0; arg.is_restrict = (m_Object->kernels[i].args[j].type_qualifier & CLC_KERNEL_ARG_TYPE_RESTRICT) != 0; arg.is_volatile = (m_Object->kernels[i].args[j].type_qualifier & CLC_KERNEL_ARG_TYPE_VOLATILE) != 0; arg.readable = (m_Object->kernels[i].args[j].access_qualifier & CLC_KERNEL_ARG_ACCESS_READ) != 0; arg.writable = (m_Object->kernels[i].args[j].access_qualifier & CLC_KERNEL_ARG_ACCESS_WRITE) != 0; arg.name = m_Object->kernels[i].args[j].name; arg.type_name = m_Object->kernels[i].args[j].type_name; info.args.push_back(arg); } m_KernelInfo.push_back(std::move(info)); } return true; } return false; } size_t ProgramBinaryV1::GetBinarySize() const { return m_Object->spvbin.size; } const void *ProgramBinaryV1::GetBinary() const { return m_Object->spvbin.data; } CompiledDxilV1::CompiledDxilV1(ProgramBinaryV1 const& parent, unique_ptr obj) : CompiledDxil(parent, obj->kernel->name) , m_Object(std::move(obj)) { m_Metadata.kernel_inputs_cbv_id = m_Object->metadata.kernel_inputs_cbv_id; m_Metadata.kernel_inputs_buf_size = m_Object->metadata.kernel_inputs_buf_size; m_Metadata.work_properties_cbv_id = m_Object->metadata.work_properties_cbv_id; m_Metadata.printf_uav_id = m_Object->metadata.printf.uav_id; m_Metadata.num_uavs = m_Object->metadata.num_uavs; m_Metadata.num_srvs = m_Object->metadata.num_srvs; m_Metadata.num_samplers = m_Object->metadata.num_samplers; m_Metadata.local_mem_size = m_Object->metadata.local_mem_size; m_Metadata.priv_mem_size = m_Object->metadata.priv_mem_size; std::copy(m_Object->metadata.local_size, std::end(m_Object->metadata.local_size), m_Metadata.local_size); std::copy(m_Object->metadata.local_size_hint, std::end(m_Object->metadata.local_size_hint), m_Metadata.local_size_hint); m_Metadata.args.reserve(m_Object->kernel->num_args); for (unsigned i = 0; i < m_Object->kernel->num_args; ++i) { CompiledDxil::Metadata::Arg arg; auto& argMeta = m_Object->metadata.args[i]; auto& argInfo = m_Object->kernel->args[i]; arg.offset = argMeta.offset; arg.size = argMeta.size; if (argInfo.address_qualifier == CLC_KERNEL_ARG_ADDRESS_GLOBAL || argInfo.address_qualifier == CLC_KERNEL_ARG_ADDRESS_CONSTANT) { if (argInfo.access_qualifier) { CompiledDxil::Metadata::Arg::Image imageMeta; imageMeta.num_buffer_ids = argMeta.image.num_buf_ids; std::copy(argMeta.image.buf_ids, std::end(argMeta.image.buf_ids), imageMeta.buffer_ids); arg.properties = imageMeta; } else { arg.properties = CompiledDxil::Metadata::Arg::Memory{ argMeta.globconstptr.buf_id }; } } else if (argInfo.address_qualifier == CLC_KERNEL_ARG_ADDRESS_LOCAL) { arg.properties = CompiledDxil::Metadata::Arg::Local{ argMeta.localptr.sharedmem_offset }; } else if (strcmp(argInfo.type_name, "sampler_t") == 0) { arg.properties = CompiledDxil::Metadata::Arg::Sampler{ argMeta.sampler.sampler_id }; } m_Metadata.args.push_back(arg); } m_Metadata.consts.reserve(m_Object->metadata.num_consts); for (unsigned i = 0; i < m_Object->metadata.num_consts; ++i) { CompiledDxil::Metadata::Consts consts; consts.data = m_Object->metadata.consts[i].data; consts.size = m_Object->metadata.consts[i].size; consts.uav_id = m_Object->metadata.consts[i].uav_id; m_Metadata.consts.push_back(consts); } m_Metadata.constSamplers.reserve(m_Object->metadata.num_const_samplers); for (unsigned i = 0; i < m_Object->metadata.num_const_samplers; ++i) { CompiledDxil::Metadata::ConstSampler sampler; sampler.addressing_mode = m_Object->metadata.const_samplers[i].addressing_mode; sampler.filter_mode = m_Object->metadata.const_samplers[i].filter_mode; sampler.normalized_coords = m_Object->metadata.const_samplers[i].normalized_coords; sampler.sampler_id = m_Object->metadata.const_samplers[i].sampler_id; m_Metadata.constSamplers.push_back(sampler); } m_Metadata.printfs.reserve(m_Object->metadata.printf.info_count); for (unsigned i = 0; i < m_Object->metadata.printf.info_count; ++i) { CompiledDxil::Metadata::Printf printf; printf.arg_sizes = m_Object->metadata.printf.infos[i].arg_sizes; printf.num_args = m_Object->metadata.printf.infos[i].num_args; printf.str = m_Object->metadata.printf.infos[i].str; m_Metadata.printfs.push_back(printf); } } size_t CompiledDxilV1::GetBinarySize() const { return m_Object->binary.size; } const void *CompiledDxilV1::GetBinary() const { return m_Object->binary.data; } void *CompiledDxilV1::GetBinary() { return m_Object->binary.data; } std::unique_ptr<Compiler> Compiler::GetV1() { XPlatHelpers::unique_module compiler; compiler.load("CLGLOn12Compiler.dll"); if (!compiler) LoadFromNextToSelf(compiler, "CLGLOn12Compiler.dll"); if (!compiler) return nullptr; return std::make_unique<CompilerV1>(std::move(compiler)); } <|start_filename|>include/resources.hpp<|end_filename|> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include "context.hpp" class MapTask; class Task; class Resource : public CLChildBase<Resource, Context, cl_mem> { public: using UnderlyingResource = D3D12TranslationLayer::Resource; using UnderlyingResourcePtr = D3D12TranslationLayer::unique_comptr<UnderlyingResource>; struct DestructorCallback { using Fn = void(CL_CALLBACK *)(cl_mem, void*); Fn m_pfn; void* m_userData; }; const cl_mem_flags m_Flags; void* const m_pHostPointer; const ref_ptr_int m_ParentBuffer; const size_t m_Offset = 0; const cl_image_format m_Format = {}; const cl_image_desc m_Desc; D3D12TranslationLayer::ResourceCreationArgs m_CreationArgs; static Resource* CreateBuffer(Context& Parent, D3D12TranslationLayer::ResourceCreationArgs& Args, void* pHostPointer, cl_mem_flags flags); static Resource* CreateSubBuffer(Resource& ParentBuffer, const cl_buffer_region& region, cl_mem_flags flags); static Resource* CreateImage(Context& Parent, D3D12TranslationLayer::ResourceCreationArgs& Args, void* pHostPointer, const cl_image_format& image_format, const cl_image_desc& image_desc, cl_mem_flags flags); static Resource* CreateImage1DBuffer(Resource& ParentBuffer, const cl_image_format& image_format, const cl_image_desc& image_desc, cl_mem_flags flags); UnderlyingResource* GetUnderlyingResource(Device*); void SetActiveDevice(Device*); UnderlyingResource* GetActiveUnderlyingResource() const { return m_ActiveUnderlying; } cl_uint GetMapCount() const { std::lock_guard MapLock(m_MapLock); return m_MapCount; } void EnqueueMigrateResource(Device* newDevice, Task* triggeringTask, cl_mem_migration_flags flags); D3D12TranslationLayer::SRV& GetSRV(Device*); D3D12TranslationLayer::UAV& GetUAV(Device*); ~Resource(); void AddMapTask(MapTask*); MapTask* GetMapTask(void* MapPtr); void RemoveMapTask(MapTask*); void AddDestructionCallback(DestructorCallback::Fn pfn, void* pUserData); protected: std::recursive_mutex m_MultiDeviceLock; Device *m_CurrentActiveDevice = nullptr; UnderlyingResource *m_ActiveUnderlying = nullptr; std::unordered_map<Device*, UnderlyingResourcePtr> m_UnderlyingMap; std::unordered_map<Device*, D3D12TranslationLayer::SRV> m_SRVs; std::unordered_map<Device*, D3D12TranslationLayer::UAV> m_UAVs; std::unique_ptr<byte[]> m_InitialData; D3D12TranslationLayer::D3D12_UNORDERED_ACCESS_VIEW_DESC_WRAPPER m_UAVDesc; D3D12_SHADER_RESOURCE_VIEW_DESC m_SRVDesc; mutable std::mutex m_MapLock; std::unordered_map<void*, std::vector<::ref_ptr_int<MapTask>>> m_OutstandingMaps; cl_uint m_MapCount = 0; mutable std::mutex m_DestructorLock; std::vector<DestructorCallback> m_DestructorCallbacks; Resource(Context& Parent, decltype(m_CreationArgs) const& CreationArgs, void* pHostPointer, size_t size, cl_mem_flags flags); Resource(Resource& ParentBuffer, size_t offset, size_t size, const cl_image_format& image_format, cl_mem_object_type type, cl_mem_flags flags); Resource(Context& Parent, decltype(m_CreationArgs) const& CreationArgs, void* pHostPointer, const cl_image_format& image_format, const cl_image_desc& image_desc, cl_mem_flags flags); static cl_image_desc GetBufferDesc(size_t size, cl_mem_object_type type); void UploadInitialData(Task* triggeringTask); friend class UploadInitialData; }; <|start_filename|>test/openclon12test.cpp<|end_filename|> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "gtest/gtest.h" #define CL_TARGET_OPENCL_VERSION 220 #include <CL/cl.h> #define CL_HPP_ENABLE_EXCEPTIONS #define CL_HPP_TARGET_OPENCL_VERSION 220 #define CL_HPP_MINIMUM_OPENCL_VERSION 220 #define CL_HPP_CL_1_2_DEFAULT_BUILD #include "cl2.hpp" #include <memory> #include <utility> #include <algorithm> #include <numeric> #include <d3d12.h> std::pair<cl::Context, cl::Device> GetWARPContext() { std::vector<cl::Platform> platforms; cl::Platform::get(&platforms); if (platforms.size() != 1) { ADD_FAILURE() << "Unexpected platforms"; } std::vector<cl::Device> devices; platforms[0].getDevices(CL_DEVICE_TYPE_GPU, &devices); if (devices.size() < 2) { ADD_FAILURE() << "Unexpected device count"; } cl::Device device; for (auto& d : devices) { auto vendor_id = d.getInfo<CL_DEVICE_VENDOR_ID>(); if (vendor_id == 0x1414) // Microsoft { device = d; break; } } if (!device()) { ADD_FAILURE() << "Couldn't find WARP"; } cl_context_properties context_props[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platforms[0](), 0 }; cl::Context context(device, context_props, [](const char* msg, const void*, size_t, void*) { ADD_FAILURE() << msg; }); return { context, device }; } TEST(OpenCLOn12, Basic) { (void)GetWARPContext(); } TEST(OpenCLOn12, SimpleKernel) { auto&& [context, device] = GetWARPContext(); cl::CommandQueue queue(context, device); const char* kernel_source = "__kernel void main_test(__global uint *output)\n\ {\n\ output[get_global_id(0)] = get_global_id(0);\n\ }\n"; const size_t width = 4; cl::Buffer buffer(context, (cl_mem_flags)(CL_MEM_ALLOC_HOST_PTR | CL_MEM_READ_WRITE), width * sizeof(uint32_t)); cl::Program program(context, kernel_source, true /*build*/); cl::Kernel kernel(program, "main_test"); kernel.setArg(0, buffer); queue.enqueueNDRangeKernel(kernel, 1, width); uint32_t result[width] = {}; std::fill_n(result, width, 0xdeaddead); queue.enqueueReadBuffer(buffer, true, 0, sizeof(result), result); for (uint32_t i = 0; i < width; ++i) { EXPECT_EQ(result[i], i); } } TEST(OpenCLOn12, SimpleImages) { auto&& [context, device] = GetWARPContext(); cl::CommandQueue queue(context, device); const char* kernel_source = "__kernel void main_test(read_only image2d_t input, write_only image2d_t output, float foo)\n\ {\n\ int2 coord = (int2)(get_global_id(0), get_global_id(1));\n\ write_imagef(output, coord, read_imagef(input, coord) + foo);\n\ }\n"; const size_t width = 16; const size_t height = 16; cl::NDRange offset(0, 0); cl::NDRange localSize(4, 4); cl::NDRange globalSize(width, height); float InputData[width * height * 4]; std::iota(InputData, std::end(InputData), 1.0f); cl::Image2D input(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, cl::ImageFormat(CL_RGBA, CL_FLOAT), width, height, sizeof(float) * width * 4, InputData); cl::Image2D output(context, CL_MEM_WRITE_ONLY | CL_MEM_HOST_READ_ONLY, cl::ImageFormat(CL_RGBA, CL_FLOAT), width, height); cl::Program program(context, kernel_source, true /*build*/); cl::Kernel kernel(program, "main_test"); kernel.setArg(0, input); kernel.setArg(1, output); queue.enqueueNDRangeKernel(kernel, offset, globalSize, localSize); float OutputData[width * height * 4]; cl::array<cl::size_type, 3> origin{}, region{ width, height, 1 }; queue.enqueueReadImage(output, true, origin, region, sizeof(float) * width * 4, sizeof(float) * width * height * 4, OutputData); for (int i = 0; i < std::extent_v<decltype(InputData)>; ++i) { EXPECT_EQ(InputData[i], OutputData[i]); } } TEST(OpenCLOn12, LargeDispatch) { auto&& [context, device] = GetWARPContext(); cl::CommandQueue queue(context, device); const char* kernel_source = R"(struct OutputStruct { unsigned global_id; unsigned local_id; unsigned work_group_id; }; __kernel void main_test(__global struct OutputStruct *output) { uint global_id = get_global_id(0); output[global_id].global_id = global_id; output[global_id].local_id = get_local_id(0); output[global_id].work_group_id = get_group_id(0); })"; struct OutputStruct { uint32_t global, local, work_group; }; const size_t widthInStructs = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION * D3D12_CS_THREAD_GROUP_MAX_X * 2; const size_t widthInBytes = widthInStructs * sizeof(OutputStruct); static_assert(widthInBytes < UINT32_MAX); cl::NDRange offset(0); cl::NDRange globalSize(widthInStructs); cl::Buffer output(context, CL_MEM_WRITE_ONLY, widthInBytes, nullptr); cl::Program program(context, kernel_source, true /*build*/); cl::Kernel kernel(program, "main_test"); kernel.setArg(0, output); queue.enqueueNDRangeKernel(kernel, offset, globalSize); std::vector<OutputStruct> OutputData(widthInStructs); queue.enqueueReadBuffer(output, true, 0, widthInBytes, OutputData.data()); for (uint32_t i = 0; i < widthInStructs; ++i) { EXPECT_EQ(OutputData[i].global, i); EXPECT_EQ(OutputData[i].local, i % D3D12_CS_THREAD_GROUP_MAX_X); EXPECT_EQ(OutputData[i].work_group, i / D3D12_CS_THREAD_GROUP_MAX_X); } } TEST(OpenCLOn12, Printf) { auto&& [context, device] = GetWARPContext(); cl::CommandQueue queue(context, device); const char* kernel_source = R"( constant uchar arr[6] = {'c', 'l', 'o', 'n', '1', '2'}; kernel void test_printf() { printf("hello %d %f %s %s %c\n", 15, 1.5, "test", "this string", arr[3]); printf("goodbye %d %f %s %c %s\n", 30, -1.5, "cruel", arr[2], "world"); printf("hello cl\n", 10, "oh now"); printf("hello cl %s\n", "again"); })"; cl::Program program(context, kernel_source, true /*build*/); cl::Kernel kernel(program, "test_printf"); queue.enqueueNDRangeKernel(kernel, cl::NullRange, cl::NDRange(1)); queue.finish(); } TEST(OpenCLOn12, RecursiveFlush) { auto&& [context, device] = GetWARPContext(); cl::CommandQueue queue1(context, device); cl::CommandQueue queue2(context, device); cl::UserEvent userEvent(context); cl::Event queue1Task1; cl::vector<cl::Event> waitList({ userEvent }); queue1.enqueueBarrierWithWaitList(&waitList, &queue1Task1); waitList = {{ queue1Task1 }}; cl::Event queue2Task1; queue2.enqueueBarrierWithWaitList(&waitList, &queue2Task1); waitList = {{ queue2Task1 }}; cl::Event queue1Task2; queue1.enqueueBarrierWithWaitList(&waitList, &queue1Task2); EXPECT_EQ(queue1Task1.getInfo<CL_EVENT_COMMAND_EXECUTION_STATUS>(), CL_QUEUED); EXPECT_EQ(queue2Task1.getInfo<CL_EVENT_COMMAND_EXECUTION_STATUS>(), CL_QUEUED); EXPECT_EQ(queue1Task2.getInfo<CL_EVENT_COMMAND_EXECUTION_STATUS>(), CL_QUEUED); queue1.flush(); EXPECT_EQ(queue1Task1.getInfo<CL_EVENT_COMMAND_EXECUTION_STATUS>(), CL_SUBMITTED); EXPECT_EQ(queue2Task1.getInfo<CL_EVENT_COMMAND_EXECUTION_STATUS>(), CL_SUBMITTED); EXPECT_EQ(queue1Task2.getInfo<CL_EVENT_COMMAND_EXECUTION_STATUS>(), CL_SUBMITTED); userEvent.setStatus(CL_SUCCESS); queue1.finish(); EXPECT_EQ(queue1Task1.getInfo<CL_EVENT_COMMAND_EXECUTION_STATUS>(), CL_COMPLETE); EXPECT_EQ(queue2Task1.getInfo<CL_EVENT_COMMAND_EXECUTION_STATUS>(), CL_COMPLETE); EXPECT_EQ(queue1Task2.getInfo<CL_EVENT_COMMAND_EXECUTION_STATUS>(), CL_COMPLETE); } TEST(OpenCLOn12, SPIRV) { // This is the pre-assembled SPIR-V from the compiler DLL's "spec_constant" test: // https://gitlab.freedesktop.org/mesa/mesa/-/blob/f8517d9f43cc191fc7465db2850c2b813b94f023/src/microsoft/clc/clc_compiler_test.cpp#L2226. // The original source was the "built_ins_global_id_rmw" test, with the hardcoded 1 manually modified in the asm to make it a spec constant: // https://gitlab.freedesktop.org/mesa/mesa/-/blob/f8517d9f43cc191fc7465db2850c2b813b94f023/src/microsoft/clc/clc_compiler_test.cpp#L394 /* __kernel void main_test(__global uint *output) { uint id = get_global_id(0); output[id] = output[id] * (id + {spec constant, id 1, default value 1}); } */ static const unsigned char spirv[] = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x07, 0x00, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x04, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x06, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x05, 0x00, 0x01, 0x00, 0x00, 0x00, 0x4f, 0x70, 0x65, 0x6e, 0x43, 0x4c, 0x2e, 0x73, 0x74, 0x64, 0x00, 0x00, 0x0e, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x07, 0x00, 0x06, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x5f, 0x74, 0x65, 0x73, 0x74, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x07, 0x00, 0x0b, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6b, 0x65, 0x72, 0x6e, 0x65, 0x6c, 0x5f, 0x61, 0x72, 0x67, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x6d, 0x61, 0x69, 0x6e, 0x5f, 0x74, 0x65, 0x73, 0x74, 0x2e, 0x75, 0x69, 0x6e, 0x74, 0x2a, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x70, 0x8e, 0x01, 0x00, 0x05, 0x00, 0x0b, 0x00, 0x03, 0x00, 0x00, 0x00, 0x5f, 0x5f, 0x73, 0x70, 0x69, 0x72, 0x76, 0x5f, 0x42, 0x75, 0x69, 0x6c, 0x74, 0x49, 0x6e, 0x47, 0x6c, 0x6f, 0x62, 0x61, 0x6c, 0x49, 0x6e, 0x76, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x05, 0x00, 0x00, 0x00, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x65, 0x6e, 0x74, 0x72, 0x79, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x2e, 0x61, 0x64, 0x64, 0x72, 0x00, 0x05, 0x00, 0x03, 0x00, 0x08, 0x00, 0x00, 0x00, 0x69, 0x64, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x09, 0x00, 0x00, 0x00, 0x63, 0x61, 0x6c, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x63, 0x6f, 0x6e, 0x76, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x69, 0x64, 0x78, 0x70, 0x72, 0x6f, 0x6d, 0x00, 0x05, 0x00, 0x05, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x61, 0x72, 0x72, 0x61, 0x79, 0x69, 0x64, 0x78, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x61, 0x64, 0x64, 0x00, 0x05, 0x00, 0x03, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x6d, 0x75, 0x6c, 0x00, 0x05, 0x00, 0x05, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x69, 0x64, 0x78, 0x70, 0x72, 0x6f, 0x6d, 0x31, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x10, 0x00, 0x00, 0x00, 0x61, 0x72, 0x72, 0x61, 0x79, 0x69, 0x64, 0x78, 0x32, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x03, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x47, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x11, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x15, 0x00, 0x04, 0x00, 0x12, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x15, 0x00, 0x04, 0x00, 0x13, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x32, 0x00, 0x04, 0x00, 0x13, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, 0x14, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x15, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x13, 0x00, 0x02, 0x00, 0x16, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x17, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x21, 0x00, 0x04, 0x00, 0x18, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x19, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x1a, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x15, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x36, 0x00, 0x05, 0x00, 0x16, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x37, 0x00, 0x03, 0x00, 0x17, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0x06, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x19, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x1a, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x06, 0x00, 0x14, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, 0x12, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x71, 0x00, 0x04, 0x00, 0x13, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x05, 0x00, 0x08, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x06, 0x00, 0x17, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x06, 0x00, 0x13, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x71, 0x00, 0x04, 0x00, 0x12, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x00, 0x00, 0x46, 0x00, 0x05, 0x00, 0x17, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x06, 0x00, 0x13, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x06, 0x00, 0x13, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x80, 0x00, 0x05, 0x00, 0x13, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x84, 0x00, 0x05, 0x00, 0x13, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x06, 0x00, 0x17, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x06, 0x00, 0x13, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x71, 0x00, 0x04, 0x00, 0x12, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x46, 0x00, 0x05, 0x00, 0x17, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x05, 0x00, 0x10, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00, }; auto&& [context, device] = GetWARPContext(); cl::CommandQueue queue(context, device); std::vector<char> IL(spirv, std::end(spirv)); cl::Program prog(context, IL, true /*build*/); cl::Kernel kernel(prog, "main_test"); uint32_t data[] = { 0x00000001, 0x10000001, 0x00020002, 0x04010203 }; cl::Buffer inout(context, data, std::end(data), false, true); kernel.setArg(0, inout); cl::NDRange offset(0); cl::NDRange global(_countof(data)); queue.enqueueNDRangeKernel(kernel, offset, global); queue.enqueueMapBuffer(inout, CL_TRUE, CL_MAP_READ, 0, sizeof(data)); EXPECT_EQ(data[0], 0x00000001u); EXPECT_EQ(data[1], 0x20000002u); EXPECT_EQ(data[2], 0x00060006u); EXPECT_EQ(data[3], 0x1004080cu); } int main(int argc, char** argv) { ID3D12Debug* pDebug = nullptr; if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&pDebug)))) { pDebug->EnableDebugLayer(); pDebug->Release(); } testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|start_filename|>include/Scheduler.hpp<|end_filename|> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include <vector> #include <deque> #include <thread> #include <mutex> #include <condition_variable> #include <algorithm> #include <list> #include <atomic> #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #ifndef NOMINMAX #define NOMINMAX #endif #include <windows.h> #include <XPlatHelpers.h> namespace BackgroundTaskScheduler { enum class Priority { Idle, Normal }; struct SchedulingMode { uint32_t NumThreads; Priority ThreadPriority; bool operator==(SchedulingMode const& b) { return NumThreads == b.NumThreads && ThreadPriority == b.ThreadPriority; } bool operator!=(SchedulingMode const& b) { return !(*this == b); } bool operator>(SchedulingMode const& b) { return NumThreads > b.NumThreads || (int)ThreadPriority > (int)b.ThreadPriority; } }; struct Task { using FnType = void(APIENTRY*)(void* pContext); FnType m_Callback; FnType m_Cancel; void* m_pContext; }; class Scheduler { protected: struct QueuedEventSignal { std::atomic<long> m_RefCount; XPlatHelpers::unique_event m_Event; }; std::list<QueuedEventSignal> m_QueuedEvents; std::list<QueuedEventSignal>::iterator m_QueuedEventsPseudoEnd; struct QueuedTask : Task { std::list<QueuedEventSignal>::iterator m_QueuedEventsAtTimeOfTaskSubmission; QueuedTask() = default; QueuedTask(Task const& t, decltype(m_QueuedEventsAtTimeOfTaskSubmission) iter) : Task(t), m_QueuedEventsAtTimeOfTaskSubmission(iter) { } QueuedTask(QueuedTask const&) = default; QueuedTask(QueuedTask&&) = default; QueuedTask& operator=(QueuedTask const&) = default; QueuedTask& operator=(QueuedTask&&) = default; }; // These are the tasks that are waiting for a thread to consume them. std::deque<QueuedTask> m_Tasks; // This is a counter of how many tasks are currently being processed by // worker threads. Adding this to the size of m_Tasks enables determining // the total number of currently not-completed tasks. uint32_t m_TasksInProgress = 0; std::vector<std::thread> m_Threads; std::vector<std::thread> m_ExitingThreads; mutable std::mutex m_Lock; std::condition_variable m_CV; SchedulingMode m_CurrentMode = { 0, Priority::Idle }; SchedulingMode m_EffectiveMode = { 0, Priority::Idle }; bool m_bShutdown = false; // These methods require the lock to be held. // Const-ref methods just require it, non-const-ref methods may release it. bool IsSchedulerIdle(std::unique_lock<std::mutex> const&) const noexcept { return m_Tasks.empty() && m_TasksInProgress == 0; } void SetSchedulingModeImpl(SchedulingMode mode, std::unique_lock<std::mutex>& lock); // Releases lock void QueueSetSchedulingModeTask(SchedulingMode mode, std::unique_lock<std::mutex> const&); void RetireTask(QueuedTask const& task, std::unique_lock<std::mutex> const&) noexcept; // These methods will take the lock. void SetSchedulingModeTask(SchedulingMode mode) noexcept; static void __stdcall SetSchedulingModeTaskStatic(void* pContext); void TaskThread(int ThreadID) noexcept; public: Scheduler(); ~Scheduler() { Shutdown(); } void SetSchedulingMode(SchedulingMode mode); void QueueTask(Task task); void SignalEventOnCompletionOfCurrentTasks(XPlatHelpers::Event hEvent, SchedulingMode modeAfterSignal); void CancelExistingTasks() noexcept; void Shutdown() noexcept; SchedulingMode GetCurrentMode() const { std::lock_guard<std::mutex> lock(m_Lock); return m_CurrentMode; } SchedulingMode GetEffectiveMode() const { std::lock_guard<std::mutex> lock(m_Lock); return m_EffectiveMode; } }; } <|start_filename|>src/platform.cpp<|end_filename|> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "platform.hpp" #include "cache.hpp" #include "compiler.hpp" CL_API_ENTRY cl_int CL_API_CALL clGetPlatformInfo(cl_platform_id platform, cl_platform_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0 { if (param_value_size == 0 && param_value != NULL) { return CL_INVALID_VALUE; } if (param_name == CL_PLATFORM_HOST_TIMER_RESOLUTION) { if (param_value_size && param_value_size < sizeof(cl_ulong)) { return CL_INVALID_VALUE; } if (param_value_size) { LARGE_INTEGER TicksPerSecond; QueryPerformanceFrequency(&TicksPerSecond); *reinterpret_cast<cl_ulong*>(param_value) = 1000000000 / TicksPerSecond.QuadPart; } if (param_value_size_ret) { *param_value_size_ret = sizeof(cl_ulong); } return CL_SUCCESS; } else if (param_name == CL_PLATFORM_NUMERIC_VERSION) { return CopyOutParameter( #ifdef CLON12_SUPPORT_3_0 CL_MAKE_VERSION(3, 0, 0), #else CL_MAKE_VERSION(1, 2, 0), #endif param_value_size, param_value, param_value_size_ret); } else if (param_name == CL_PLATFORM_EXTENSIONS_WITH_VERSION) { constexpr cl_name_version extensions[] = { { CL_MAKE_VERSION(1, 0, 0), "cl_khr_icd" }, { CL_MAKE_VERSION(1, 0, 0), "cl_khr_extended_versioning" }, { CL_MAKE_VERSION(1, 0, 0), "cl_khr_global_int32_base_atomics" }, { CL_MAKE_VERSION(1, 0, 0), "cl_khr_global_int32_extended_atomics" }, { CL_MAKE_VERSION(1, 0, 0), "cl_khr_local_int32_base_atomics" }, { CL_MAKE_VERSION(1, 0, 0), "cl_khr_local_int32_extended_atomics" }, { CL_MAKE_VERSION(1, 0, 0), "cl_khr_byte_addressable_store" }, { CL_MAKE_VERSION(1, 0, 0), "cl_khr_il_program" }, }; return CopyOutParameter(extensions, param_value_size, param_value, param_value_size_ret); } auto pPlatform = Platform::CastFrom(platform); auto pString = [pPlatform, param_name]() -> const char* { switch (param_name) { case CL_PLATFORM_PROFILE: return pPlatform->Profile; case CL_PLATFORM_VERSION: return pPlatform->Version; case CL_PLATFORM_NAME: return pPlatform->Name; case CL_PLATFORM_VENDOR: return pPlatform->Vendor; case CL_PLATFORM_EXTENSIONS: return pPlatform->Extensions; case CL_PLATFORM_ICD_SUFFIX_KHR: return pPlatform->ICDSuffix; } return nullptr; }(); if (!pString) { return CL_INVALID_VALUE; } auto stringlen = strlen(pString) + 1; if (param_value_size && param_value_size < stringlen) { return CL_INVALID_VALUE; } if (param_value_size) { memcpy(param_value, pString, stringlen); } if (param_value_size_ret) { *param_value_size_ret = stringlen; } return CL_SUCCESS; } extern CL_API_ENTRY cl_int CL_API_CALL clUnloadPlatformCompiler(cl_platform_id platform) CL_API_SUFFIX__VERSION_1_2 { if (!platform) { return CL_INVALID_PLATFORM; } static_cast<Platform*>(platform)->UnloadCompiler(); return CL_SUCCESS; } #include "device.hpp" Platform::Platform(cl_icd_dispatch* dispatch) { this->dispatch = dispatch; ComPtr<IDXCoreAdapterFactory> spFactory; THROW_IF_FAILED(DXCoreCreateAdapterFactory(IID_PPV_ARGS(&spFactory))); THROW_IF_FAILED(spFactory->CreateAdapterList(1, &DXCORE_ADAPTER_ATTRIBUTE_D3D12_CORE_COMPUTE, IID_PPV_ARGS(&m_spAdapters))); m_Devices.resize(m_spAdapters->GetAdapterCount()); for (cl_uint i = 0; i < m_Devices.size(); ++i) { ComPtr<IDXCoreAdapter> spAdapter; THROW_IF_FAILED(m_spAdapters->GetAdapter(i, IID_PPV_ARGS(&spAdapter))); m_Devices[i] = std::make_unique<Device>(*this, spAdapter.Get()); } char *forceWarpStr = nullptr; bool forceWarp = _dupenv_s(&forceWarpStr, nullptr, "CLON12_FORCE_WARP") == 0 && forceWarpStr && strcmp(forceWarpStr, "1") == 0; free(forceWarpStr); char *forceHardwareStr = nullptr; bool forceHardware = !forceWarp && _dupenv_s(&forceHardwareStr, nullptr, "CLON12_FORCE_HARDWARE") == 0 && forceHardwareStr && strcmp(forceHardwareStr, "1") == 0; free(forceHardwareStr); if (forceWarp) { (void)std::remove_if(m_Devices.begin(), m_Devices.end(), [](std::unique_ptr<Device> const& a) { auto&& hwids = a->GetHardwareIds(); return hwids.deviceID != 0x8c && hwids.vendorID != 0x1414; }); } if (forceWarp || forceHardware) { m_Devices.resize(1); } } Platform::~Platform() = default; cl_uint Platform::GetNumDevices() const noexcept { return (cl_uint)m_Devices.size(); } cl_device_id Platform::GetDevice(cl_uint i) const noexcept { return m_Devices[i].get(); } TaskPoolLock Platform::GetTaskPoolLock() { TaskPoolLock lock; lock.m_Lock = std::unique_lock<std::recursive_mutex>{ m_TaskLock }; return lock; } void Platform::FlushAllDevices(TaskPoolLock const& Lock) { for (auto& device : m_Devices) { if (device->GetDevice()) { device->Flush(Lock); } } } void Platform::DeviceInit() { std::lock_guard Lock(m_ModuleLock); if (m_ActiveDeviceCount++ > 0) { return; } BackgroundTaskScheduler::SchedulingMode mode{ 1u, BackgroundTaskScheduler::Priority::Normal }; m_CallbackScheduler.SetSchedulingMode(mode); mode.NumThreads = std::thread::hardware_concurrency(); m_CompileAndLinkScheduler.SetSchedulingMode(mode); } void Platform::DeviceUninit() { std::lock_guard Lock(m_ModuleLock); if (--m_ActiveDeviceCount > 0) { return; } BackgroundTaskScheduler::SchedulingMode mode{ 0u, BackgroundTaskScheduler::Priority::Normal }; m_CallbackScheduler.SetSchedulingMode(mode); m_CompileAndLinkScheduler.SetSchedulingMode(mode); } #ifdef _WIN32 extern "C" extern IMAGE_DOS_HEADER __ImageBase; #endif void LoadFromNextToSelf(XPlatHelpers::unique_module& mod, const char* name) { #ifdef _WIN32 char selfPath[MAX_PATH] = ""; if (auto pathSize = GetModuleFileNameA((HINSTANCE)&__ImageBase, selfPath, sizeof(selfPath)); pathSize == 0 || pathSize == sizeof(selfPath)) { return; } auto lastSlash = strrchr(selfPath, '\\'); if (!lastSlash) { return; } *(lastSlash + 1) = '\0'; if (strcat_s(selfPath, name) != 0) { return; } mod.load(selfPath); #endif } Compiler *Platform::GetCompiler() { std::lock_guard lock(m_ModuleLock); if (!m_Compiler) { m_Compiler = Compiler::GetV2(); } if (!m_Compiler) { m_Compiler = Compiler::GetV1(); } return m_Compiler.get(); } XPlatHelpers::unique_module const& Platform::GetDXIL() { std::lock_guard lock(m_ModuleLock); if (!m_DXIL) { m_DXIL.load("DXIL.dll"); } if (!m_DXIL) { LoadFromNextToSelf(m_DXIL, "DXIL.dll"); } return m_DXIL; } void Platform::UnloadCompiler() { // If we want to actually support unloading the compiler, // we'll need to track all live programs/kernels, because // they need to call back into the compiler to be able to // free their program memory. } bool Platform::AnyD3DDevicesExist() const noexcept { return std::any_of(m_Devices.begin(), m_Devices.end(), [](auto& dev) { return dev->GetDevice(); }); } void Platform::CloseCaches() { for (auto& device : m_Devices) { if (device->GetDevice()) { device->GetShaderCache().Close(); } } } <|start_filename|>include/kernel.hpp<|end_filename|> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include "program.hpp" #include "resources.hpp" #include <cstddef> class Sampler; class Kernel : public CLChildBase<Kernel, Program, cl_kernel> { private: CompiledDxil const& m_Dxil; std::string const m_Name; D3D12TranslationLayer::SShaderDecls m_ShaderDecls; std::vector<std::byte> m_KernelArgsCbData; std::vector<CompiledDxil::Configuration::Arg> m_ArgMetadataToCompiler; // These are weak references for the API kernel object, however // these will be converted into strong references by an *execution* // of that kernel. Releasing an object *while a kernel is enqueued* // must be safe (according to the CTS), while the API kernel must not // hold any references. std::vector<Resource*> m_UAVs; std::vector<Resource*> m_SRVs; std::vector<Sampler*> m_Samplers; std::vector<::ref_ptr<Sampler>> m_ConstSamplers; std::vector<::ref_ptr<Resource>> m_InlineConsts; friend class ExecuteKernel; friend extern CL_API_ENTRY cl_int CL_API_CALL clGetKernelInfo(cl_kernel, cl_kernel_info, size_t, void*, size_t*); friend extern CL_API_ENTRY cl_int CL_API_CALL clGetKernelArgInfo(cl_kernel, cl_uint, cl_kernel_arg_info, size_t, void*, size_t*); friend extern CL_API_ENTRY cl_int CL_API_CALL clGetKernelWorkGroupInfo(cl_kernel, cl_device_id, cl_kernel_work_group_info, size_t, void*, size_t*); public: Kernel(Program& Parent, std::string const& name, CompiledDxil const& Dxil); Kernel(Kernel const&); ~Kernel(); cl_int SetArg(cl_uint arg_index, size_t arg_size, const void* arg_value); uint16_t const* GetRequiredLocalDims() const; uint16_t const* GetLocalDimsHint() const; }; <|start_filename|>src/compilers/v2/compiler_v2.cpp<|end_filename|> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #define NOMINMAX #include "clc_compiler.h" #include "compiler.hpp" #include "cache.hpp" #include "platform.hpp" template <typename T> struct unique_object : public T { using DeleterT = void(*)(T*); DeleterT m_Deleter = nullptr; unique_object() = default; unique_object(DeleterT) : T(), m_Deleter(d) {} unique_object(T const& t, DeleterT d = nullptr) : T(t), m_Deleter(d) {} unique_object(T &&t, DeleterT d) : T(std::move(t)), m_Deleter(d) {} unique_object(unique_object &&o) : T(std::move(o)), m_Deleter(o.m_Deleter) { o.m_Deleter = nullptr; } ~unique_object() { if (m_Deleter) m_Deleter(this); } }; class CompilerV2 : public Compiler { private: XPlatHelpers::unique_module m_Compiler; std::mutex m_InitializationLock; std::unique_ptr<clc_libclc, void(*)(clc_libclc*)> m_Libclc{nullptr, nullptr}; public: CompilerV2(XPlatHelpers::unique_module compiler); static CompilerV2 *Instance(); // Compiler functions decltype(&clc_libclc_new) LoadLibclc = nullptr; decltype(&clc_libclc_serialize) SerializeLibclc = nullptr; decltype(&clc_libclc_deserialize) DeserializeLibclc = nullptr; decltype(&clc_libclc_free_serialized) FreeSerializedLibclc = nullptr; decltype(&clc_free_libclc) FreeLibclc = nullptr; decltype(&clc_compile_c_to_spirv) CompileImpl = nullptr; decltype(&clc_link_spirv) LinkImpl = nullptr; decltype(&clc_free_spirv) FreeSpirv = nullptr; decltype(&clc_parse_spirv) ParseSpirv = nullptr; decltype(&clc_free_parsed_spirv) FreeParsedSpirv = nullptr; decltype(&clc_spirv_to_dxil) GetKernelImpl = nullptr; decltype(&clc_free_dxil_object) FreeDxil = nullptr; decltype(&clc_compiler_get_version) GetCompilerVersion = nullptr; clc_libclc *GetLibclc() const { return m_Libclc.get(); } // Inherited via Compiler virtual ~CompilerV2() = default; virtual bool Initialize(ShaderCache &cache) final; virtual std::unique_ptr<ProgramBinary> Compile(CompileArgs const& args, Logger const& logger) const final; virtual std::unique_ptr<ProgramBinary> Link(LinkerArgs const& args, Logger const& logger) const final; virtual std::unique_ptr<ProgramBinary> Load(const void *data, size_t size) const final; virtual std::unique_ptr<CompiledDxil> GetKernel(const char *name, ProgramBinary const& obj, CompiledDxil::Configuration const *, Logger const *logger) const final; virtual std::byte * CopyWorkProperties(std::byte *WorkPropertiesBuffer, WorkProperties const& props) const final; virtual size_t GetWorkPropertiesChunkSize() const final; virtual uint64_t GetVersionForCache() const final; }; class ProgramBinaryV2 : public ProgramBinary { public: using unique_obj = unique_object<clc_binary>; private: unique_obj m_Object; unique_object<clc_parsed_spirv> m_Parsed; public: ProgramBinaryV2(unique_obj obj); clc_binary const& GetRaw() const { return m_Object; } clc_parsed_spirv const& GetParsedInfo() const { return m_Parsed; } // Inherited via ProgramBinary virtual ~ProgramBinaryV2() = default; virtual bool Parse(Logger const *logger) final; virtual size_t GetBinarySize() const final; virtual const void *GetBinary() const final; }; class CompiledDxilV2 : public CompiledDxil { public: using unique_obj = unique_object<clc_dxil_object>; private: unique_obj m_Object; public: CompiledDxilV2(ProgramBinaryV2 const& parent, unique_obj obj); clc_dxil_object const& GetRaw() { return m_Object; } // Inherited via CompiledDxil virtual ~CompiledDxilV2() = default; virtual size_t GetBinarySize() const final; virtual const void *GetBinary() const final; virtual void *GetBinary() final; }; static clc_logger ConvertLogger(Logger const& logger) { auto log = [](void *ctx, const char *msg) { static_cast<Logger*>(ctx)->Log(msg); }; clc_logger ret; ret.error = log; ret.warning = log; ret.priv = (void*)&logger; return ret; } #if 0 #endif CompilerV2::CompilerV2(XPlatHelpers::unique_module compiler) : m_Compiler(std::move(compiler)) { #define GET_FUNC(Member, api) Member = m_Compiler.proc_address<decltype(&api)>(#api) GET_FUNC(LoadLibclc, clc_libclc_new); GET_FUNC(SerializeLibclc, clc_libclc_serialize); GET_FUNC(DeserializeLibclc, clc_libclc_deserialize); GET_FUNC(FreeSerializedLibclc, clc_libclc_free_serialized); GET_FUNC(FreeLibclc, clc_free_libclc); GET_FUNC(CompileImpl, clc_compile_c_to_spirv); GET_FUNC(LinkImpl, clc_link_spirv); GET_FUNC(FreeSpirv, clc_free_spirv); GET_FUNC(ParseSpirv, clc_parse_spirv); GET_FUNC(FreeParsedSpirv, clc_free_parsed_spirv); GET_FUNC(GetKernelImpl, clc_spirv_to_dxil); GET_FUNC(FreeDxil, clc_free_dxil_object); GET_FUNC(GetCompilerVersion, clc_compiler_get_version); #undef GET_FUNC if (!LoadLibclc || !SerializeLibclc || !DeserializeLibclc || !FreeSerializedLibclc || !FreeLibclc || !CompileImpl || !LinkImpl || !FreeSpirv || !ParseSpirv || !FreeParsedSpirv || !GetKernelImpl || !FreeDxil || !GetCompilerVersion) throw std::runtime_error("Failed to load required compiler entrypoints"); m_Libclc = decltype(m_Libclc)(nullptr, FreeLibclc); } CompilerV2 *CompilerV2::Instance() { return static_cast<CompilerV2*>(g_Platform->GetCompiler()); } bool CompilerV2::Initialize(ShaderCache &cache) { if (m_Libclc) return true; std::lock_guard lock(m_InitializationLock); if (m_Libclc) return true; // {1B9DC5F4-545A-4356-98D3-B4C0062E6253} static const GUID LibclcKey = { <KEY>, 0x545a, 0x4356, { 0x98, 0xd3, 0xb4, 0xc0, 0x6, 0x2e, 0x62, 0x53 } }; if (DeserializeLibclc) { if (auto CachedContext = cache.Find(&LibclcKey, sizeof(LibclcKey)); CachedContext.first) { m_Libclc.reset(DeserializeLibclc(CachedContext.first.get(), CachedContext.second)); return true; } } clc_libclc_options options = {}; options.optimize = cache.HasCache() && SerializeLibclc && FreeSerializedLibclc; m_Libclc.reset(LoadLibclc(nullptr, &options)); if (m_Libclc && options.optimize) { void* serialized = nullptr; size_t serializedSize = 0; SerializeLibclc(m_Libclc.get(), &serialized, &serializedSize); if (serialized) { try { cache.Store(&LibclcKey, sizeof(LibclcKey), serialized, serializedSize); } catch (...) {} FreeSerializedLibclc(serialized); } } return m_Libclc != nullptr; } std::unique_ptr<ProgramBinary> CompilerV2::Compile(CompileArgs const& args, Logger const& logger) const { ProgramBinaryV2::unique_obj obj({}, FreeSpirv); clc_compile_args args_impl; args_impl.args = args.cmdline_args.data(); args_impl.num_args = (unsigned)args.cmdline_args.size(); args_impl.source = { "source.cl", args.program_source }; static_assert(sizeof(clc_named_value) == sizeof(CompileArgs::Header)); static_assert(offsetof(clc_named_value, name) == offsetof(CompileArgs::Header, name)); static_assert(offsetof(clc_named_value, value) == offsetof(CompileArgs::Header, contents)); args_impl.headers = (clc_named_value*)args.headers.data(); args_impl.num_headers = (unsigned)args.headers.size(); auto logger_impl = ConvertLogger(logger); if (!CompileImpl(&args_impl, &logger_impl, &obj)) return nullptr; return std::make_unique<ProgramBinaryV2>(std::move(obj)); } std::unique_ptr<ProgramBinary> CompilerV2::Link(LinkerArgs const& args, Logger const& logger) const { ProgramBinaryV2::unique_obj linked({}, FreeSpirv); std::vector<clc_binary const*> raw_objs; raw_objs.reserve(args.objs.size()); for (auto& obj : args.objs) raw_objs.push_back(&static_cast<ProgramBinaryV2 const*>(obj)->GetRaw()); clc_linker_args args_impl; args_impl.create_library = args.create_library; args_impl.num_in_objs = (unsigned)raw_objs.size(); args_impl.in_objs = raw_objs.data(); auto logger_impl = ConvertLogger(logger); if (!LinkImpl(&args_impl, &logger_impl, &linked)) return nullptr; auto ret = std::make_unique<ProgramBinaryV2>(std::move(linked)); if (!ret) return nullptr; if (!ret->Parse(&logger)) return nullptr; return ret; } std::unique_ptr<ProgramBinary> CompilerV2::Load(const void *data, size_t size) const { auto deleter = [](clc_binary *obj) { if (obj->data) operator delete(obj->data); }; ProgramBinaryV2::unique_obj obj({}, deleter); obj.size = size; obj.data = operator new(size); memcpy(obj.data, data, size); return std::make_unique<ProgramBinaryV2>(std::move(obj)); } std::unique_ptr<CompiledDxil> CompilerV2::GetKernel(const char *name, ProgramBinary const& obj, CompiledDxil::Configuration const *conf, Logger const *logger) const { CompiledDxilV2::unique_obj dxil({}, FreeDxil); clc_runtime_kernel_conf conf_impl; std::vector<clc_runtime_arg_info> conf_args; if (conf) { std::copy(conf->local_size, std::end(conf->local_size), conf_impl.local_size); conf_impl.lower_bit_size = (conf->lower_int16 ? 16 : 0) | (conf->lower_int64 ? 64 : 0); conf_impl.support_global_work_id_offsets = conf->support_global_work_id_offsets; conf_impl.support_work_group_id_offsets = conf->support_work_group_id_offsets; conf_args.resize(conf->args.size()); for (auto& arg : conf->args) { clc_runtime_arg_info arg_impl; if (auto local = std::get_if<CompiledDxil::Configuration::Arg::Local>(&arg.config); local) { arg_impl.localptr.size = local->size; } else if (auto sampler = std::get_if<CompiledDxil::Configuration::Arg::Sampler>(&arg.config); sampler) { arg_impl.sampler.addressing_mode = sampler->addressingMode; arg_impl.sampler.linear_filtering = sampler->linearFiltering; arg_impl.sampler.normalized_coords = sampler->normalizedCoords; } conf_args.push_back(arg_impl); } conf_impl.args = conf_args.data(); } clc_logger logger_impl; if (logger) logger_impl = ConvertLogger(*logger); ProgramBinaryV2 const& objv2 = static_cast<ProgramBinaryV2 const&>(obj); if (!GetKernelImpl(GetLibclc(), &objv2.GetRaw(), &objv2.GetParsedInfo(), name, conf ? &conf_impl : nullptr, nullptr, logger ? &logger_impl : nullptr, &dxil)) return nullptr; return std::make_unique<CompiledDxilV2>(static_cast<ProgramBinaryV2 const&>(obj), std::move(dxil)); } std::byte *CompilerV2::CopyWorkProperties(std::byte *WorkPropertiesBuffer, WorkProperties const& props) const { static_assert(sizeof(props) == sizeof(clc_work_properties_data)); static_assert(offsetof(WorkProperties, global_offset_z) == offsetof(clc_work_properties_data, global_offset_z)); static_assert(offsetof(WorkProperties, work_dim) == offsetof(clc_work_properties_data, work_dim)); static_assert(offsetof(WorkProperties, group_count_total_z) == offsetof(clc_work_properties_data, group_count_total_z)); static_assert(offsetof(WorkProperties, group_id_offset_z) == offsetof(clc_work_properties_data, group_id_offset_z)); memcpy(WorkPropertiesBuffer, &props, sizeof(props)); return WorkPropertiesBuffer + GetWorkPropertiesChunkSize(); } size_t CompilerV2::GetWorkPropertiesChunkSize() const { return std::max<size_t>(sizeof(clc_work_properties_data), D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT); } uint64_t CompilerV2::GetVersionForCache() const { return GetCompilerVersion(); } ProgramBinaryV2::ProgramBinaryV2(unique_obj obj) : m_Object(std::move(obj)) , m_Parsed({}, CompilerV2::Instance()->FreeParsedSpirv) { } bool ProgramBinaryV2::Parse(Logger const *logger) { if (m_Parsed.num_kernels || m_Parsed.num_spec_constants) return true; clc_logger logger_impl; if (logger) logger_impl = ConvertLogger(*logger); if (!CompilerV2::Instance()->ParseSpirv(&m_Object, logger ? &logger_impl : nullptr, &m_Parsed)) return false; if (m_Parsed.num_kernels) { m_KernelInfo.reserve(m_Parsed.num_kernels); for (unsigned i = 0; i < m_Parsed.num_kernels; ++i) { Kernel info; info.name = m_Parsed.kernels[i].name; info.vec_hint_size = m_Parsed.kernels[i].vec_hint_size; static_assert(CLC_VEC_HINT_TYPE_CHAR == (int)Kernel::VecHintType::Char); static_assert(CLC_VEC_HINT_TYPE_SHORT == (int)Kernel::VecHintType::Short); static_assert(CLC_VEC_HINT_TYPE_INT == (int)Kernel::VecHintType::Int); static_assert(CLC_VEC_HINT_TYPE_LONG == (int)Kernel::VecHintType::Long); static_assert(CLC_VEC_HINT_TYPE_HALF == (int)Kernel::VecHintType::Half); static_assert(CLC_VEC_HINT_TYPE_FLOAT == (int)Kernel::VecHintType::Float); static_assert(CLC_VEC_HINT_TYPE_DOUBLE == (int)Kernel::VecHintType::Double); info.vec_hint_type = (Kernel::VecHintType)m_Parsed.kernels[i].vec_hint_type; info.args.reserve(m_Parsed.kernels[i].num_args); for (unsigned j = 0; j < m_Parsed.kernels[i].num_args; ++j) { Kernel::Arg arg; static_assert(CLC_KERNEL_ARG_ADDRESS_PRIVATE == (int)Kernel::Arg::AddressSpace::Private); static_assert(CLC_KERNEL_ARG_ADDRESS_CONSTANT == (int)Kernel::Arg::AddressSpace::Constant); static_assert(CLC_KERNEL_ARG_ADDRESS_LOCAL == (int)Kernel::Arg::AddressSpace::Local); static_assert(CLC_KERNEL_ARG_ADDRESS_GLOBAL == (int)Kernel::Arg::AddressSpace::Global); arg.address_qualifier = (Kernel::Arg::AddressSpace)m_Parsed.kernels[i].args[j].address_qualifier; arg.is_const = (m_Parsed.kernels[i].args[j].type_qualifier & CLC_KERNEL_ARG_TYPE_CONST) != 0; arg.is_restrict = (m_Parsed.kernels[i].args[j].type_qualifier & CLC_KERNEL_ARG_TYPE_RESTRICT) != 0; arg.is_volatile = (m_Parsed.kernels[i].args[j].type_qualifier & CLC_KERNEL_ARG_TYPE_VOLATILE) != 0; arg.readable = (m_Parsed.kernels[i].args[j].access_qualifier & CLC_KERNEL_ARG_ACCESS_READ) != 0; arg.writable = (m_Parsed.kernels[i].args[j].access_qualifier & CLC_KERNEL_ARG_ACCESS_WRITE) != 0; arg.name = m_Parsed.kernels[i].args[j].name; arg.type_name = m_Parsed.kernels[i].args[j].type_name; info.args.push_back(arg); } m_KernelInfo.push_back(std::move(info)); } } return true; } size_t ProgramBinaryV2::GetBinarySize() const { return m_Object.size; } const void *ProgramBinaryV2::GetBinary() const { return m_Object.data; } CompiledDxilV2::CompiledDxilV2(ProgramBinaryV2 const& parent, unique_obj obj) : CompiledDxil(parent, obj.kernel->name) , m_Object(std::move(obj)) { m_Metadata.kernel_inputs_cbv_id = m_Object.metadata.kernel_inputs_cbv_id; m_Metadata.kernel_inputs_buf_size = m_Object.metadata.kernel_inputs_buf_size; m_Metadata.work_properties_cbv_id = m_Object.metadata.work_properties_cbv_id; m_Metadata.printf_uav_id = m_Object.metadata.printf.uav_id; m_Metadata.num_uavs = m_Object.metadata.num_uavs; m_Metadata.num_srvs = m_Object.metadata.num_srvs; m_Metadata.num_samplers = m_Object.metadata.num_samplers; m_Metadata.local_mem_size = m_Object.metadata.local_mem_size; m_Metadata.priv_mem_size = m_Object.metadata.priv_mem_size; std::copy(m_Object.metadata.local_size, std::end(m_Object.metadata.local_size), m_Metadata.local_size); std::copy(m_Object.metadata.local_size_hint, std::end(m_Object.metadata.local_size_hint), m_Metadata.local_size_hint); m_Metadata.args.reserve(m_Object.kernel->num_args); for (unsigned i = 0; i < m_Object.kernel->num_args; ++i) { CompiledDxil::Metadata::Arg arg; auto& argMeta = m_Object.metadata.args[i]; auto& argInfo = m_Object.kernel->args[i]; arg.offset = argMeta.offset; arg.size = argMeta.size; if (argInfo.address_qualifier == CLC_KERNEL_ARG_ADDRESS_GLOBAL || argInfo.address_qualifier == CLC_KERNEL_ARG_ADDRESS_CONSTANT) { if (argInfo.access_qualifier) { CompiledDxil::Metadata::Arg::Image imageMeta; imageMeta.num_buffer_ids = argMeta.image.num_buf_ids; std::copy(argMeta.image.buf_ids, std::end(argMeta.image.buf_ids), imageMeta.buffer_ids); arg.properties = imageMeta; } else { arg.properties = CompiledDxil::Metadata::Arg::Memory{ argMeta.globconstptr.buf_id }; } } else if (argInfo.address_qualifier == CLC_KERNEL_ARG_ADDRESS_LOCAL) { arg.properties = CompiledDxil::Metadata::Arg::Local{ argMeta.localptr.sharedmem_offset }; } else if (strcmp(argInfo.type_name, "sampler_t") == 0) { arg.properties = CompiledDxil::Metadata::Arg::Sampler{ argMeta.sampler.sampler_id }; } m_Metadata.args.push_back(arg); } m_Metadata.consts.reserve(m_Object.metadata.num_consts); for (unsigned i = 0; i < m_Object.metadata.num_consts; ++i) { CompiledDxil::Metadata::Consts consts; consts.data = m_Object.metadata.consts[i].data; consts.size = m_Object.metadata.consts[i].size; consts.uav_id = m_Object.metadata.consts[i].uav_id; m_Metadata.consts.push_back(consts); } m_Metadata.constSamplers.reserve(m_Object.metadata.num_const_samplers); for (unsigned i = 0; i < m_Object.metadata.num_const_samplers; ++i) { CompiledDxil::Metadata::ConstSampler sampler; sampler.addressing_mode = m_Object.metadata.const_samplers[i].addressing_mode; sampler.filter_mode = m_Object.metadata.const_samplers[i].filter_mode; sampler.normalized_coords = m_Object.metadata.const_samplers[i].normalized_coords; sampler.sampler_id = m_Object.metadata.const_samplers[i].sampler_id; m_Metadata.constSamplers.push_back(sampler); } m_Metadata.printfs.reserve(m_Object.metadata.printf.info_count); for (unsigned i = 0; i < m_Object.metadata.printf.info_count; ++i) { CompiledDxil::Metadata::Printf printf; printf.arg_sizes = m_Object.metadata.printf.infos[i].arg_sizes; printf.num_args = m_Object.metadata.printf.infos[i].num_args; printf.str = m_Object.metadata.printf.infos[i].str; m_Metadata.printfs.push_back(printf); } } size_t CompiledDxilV2::GetBinarySize() const { return m_Object.binary.size; } const void *CompiledDxilV2::GetBinary() const { return m_Object.binary.data; } void *CompiledDxilV2::GetBinary() { return m_Object.binary.data; } std::unique_ptr<Compiler> Compiler::GetV2() { XPlatHelpers::unique_module compiler; compiler.load("CLOn12Compiler.dll"); if (!compiler) LoadFromNextToSelf(compiler, "CLOn12Compiler.dll"); if (!compiler) return nullptr; return std::make_unique<CompilerV2>(std::move(compiler)); } <|start_filename|>include/compiler.hpp<|end_filename|> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include <vector> #include <memory> #include <mutex> #include <variant> #include <cstddef> class Logger { protected: std::recursive_mutex &m_lock; std::string &m_buildLog; public: Logger(std::recursive_mutex &lock, std::string& build_log) : m_lock(lock), m_buildLog(build_log) { } void Log(const char *msg) const; }; // An abstraction over a program binary class ProgramBinary { public: struct Kernel { struct Arg { enum class AddressSpace { Private, Constant, Local, Global }; const char *name; const char *type_name; bool readable, writable; bool is_const, is_restrict, is_volatile; AddressSpace address_qualifier; }; enum class VecHintType { Char, Short, Int, Long, Half, Float, Double }; const char *name; std::vector<Arg> args; unsigned vec_hint_size; VecHintType vec_hint_type; }; virtual ~ProgramBinary() = default; virtual bool Parse(Logger const *logger) = 0; virtual size_t GetBinarySize() const = 0; virtual const void* GetBinary() const = 0; const std::vector<Kernel> &GetKernelInfo() const; protected: std::vector<Kernel> m_KernelInfo; }; // An abstraction over DXIL + metadata class CompiledDxil { public: struct Metadata { struct Arg { unsigned offset, size; struct Image { unsigned buffer_ids[3]; unsigned num_buffer_ids; }; struct Sampler { unsigned sampler_id; }; struct Memory { unsigned buffer_id; }; struct Local { unsigned sharedmem_offset; }; std::variant<std::monostate, Image, Sampler, Memory, Local> properties; }; struct Consts { void *data; size_t size; unsigned uav_id; }; struct ConstSampler { unsigned sampler_id; unsigned addressing_mode; unsigned filter_mode; bool normalized_coords; }; struct Printf { unsigned num_args; unsigned *arg_sizes; char *str; }; ProgramBinary::Kernel const& program_kernel_info; std::vector<Arg> args; std::vector<Consts> consts; std::vector<ConstSampler> constSamplers; std::vector<Printf> printfs; unsigned kernel_inputs_cbv_id; unsigned kernel_inputs_buf_size; unsigned work_properties_cbv_id; int printf_uav_id; size_t num_uavs; size_t num_srvs; size_t num_samplers; size_t local_mem_size; size_t priv_mem_size; uint16_t local_size[3]; uint16_t local_size_hint[3]; Metadata(ProgramBinary::Kernel const& parent) : program_kernel_info(parent) { } }; struct Configuration { struct Arg { struct Local { unsigned size; }; struct Sampler { bool normalizedCoords, linearFiltering; unsigned addressingMode; }; std::variant<std::monostate, Local, Sampler> config; }; uint16_t local_size[3]; std::vector<Arg> args; bool lower_int64; bool lower_int16; bool support_global_work_id_offsets; bool support_work_group_id_offsets; }; virtual ~CompiledDxil() = default; virtual size_t GetBinarySize() const = 0; virtual const void* GetBinary() const = 0; virtual void *GetBinary() = 0; CompiledDxil(ProgramBinary const& parent, const char *name); void Sign(); Metadata const& GetMetadata() const; protected: Metadata m_Metadata; ProgramBinary const& m_Parent; }; struct WorkProperties { /* Returned from get_global_offset(), and added into get_global_id() */ unsigned global_offset_x; unsigned global_offset_y; unsigned global_offset_z; /* Returned from get_work_dim() */ unsigned work_dim; /* The number of work groups being launched (i.e. the parameters to Dispatch). * If the requested global size doesn't fit in a single Dispatch, these values should * indicate the total number of groups that *should* have been launched. */ unsigned group_count_total_x; unsigned group_count_total_y; unsigned group_count_total_z; unsigned padding; /* If the requested global size doesn't fit in a single Dispatch, subsequent dispatches * should fill out these offsets to indicate how many groups have already been launched */ unsigned group_id_offset_x; unsigned group_id_offset_y; unsigned group_id_offset_z; }; class ShaderCache; class Compiler { public: struct CompileArgs { struct Header { const char *name; const char *contents; }; std::vector<Header> headers; const char *program_source; std::vector<const char*> cmdline_args; }; struct LinkerArgs { std::vector<ProgramBinary const*> objs; bool create_library; }; static std::unique_ptr<Compiler> GetV1(); static std::unique_ptr<Compiler> GetV2(); virtual ~Compiler() = default; // Ensure libclc is loaded and ready to go virtual bool Initialize(ShaderCache &cache) = 0; // Compile OpenCL C into SPIR-V virtual std::unique_ptr<ProgramBinary> Compile(CompileArgs const& args, Logger const& logger) const = 0; // Link multiple SPIR-V binaries into one, and remove linkage info virtual std::unique_ptr<ProgramBinary> Link(LinkerArgs const& args, Logger const& logger) const = 0; // Load a SPIR-V binary from a memory blob virtual std::unique_ptr<ProgramBinary> Load(const void *data, size_t size) const = 0; // Convert a kernel from SPIR-V into DXIL with configuration properties virtual std::unique_ptr<CompiledDxil> GetKernel(const char *name, ProgramBinary const& obj, CompiledDxil::Configuration const*, Logger const* logger) const = 0; // Copy the work properties into a constant buffer virtual std::byte* CopyWorkProperties(std::byte* WorkPropertiesBuffer, WorkProperties const& props) const = 0; virtual size_t GetWorkPropertiesChunkSize() const = 0; // Return a version that can be used for initializing a shader cache virtual uint64_t GetVersionForCache() const = 0; }; <|start_filename|>src/stubs.cpp<|end_filename|> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "context.hpp" #include "queue.hpp" #include "program.hpp" #include "kernel.hpp" #pragma warning(disable: 4100) extern CL_API_ENTRY cl_int CL_API_CALL clCreateSubDevices(cl_device_id in_device, const cl_device_partition_property * properties, cl_uint num_devices, cl_device_id * out_devices, cl_uint * num_devices_ret) CL_API_SUFFIX__VERSION_1_2 { if (!in_device) { return CL_INVALID_DEVICE; } if (properties && properties[0] != 0) { // We don't support any of the partition modes, so the spec says we should return this return CL_INVALID_VALUE; } return CL_INVALID_DEVICE_PARTITION_COUNT; } extern CL_API_ENTRY cl_int CL_API_CALL clSetDefaultDeviceCommandQueue(cl_context context_, cl_device_id device_, cl_command_queue command_queue) CL_API_SUFFIX__VERSION_2_1 { if (!context_) { return CL_INVALID_CONTEXT; } Context& context = *static_cast<Context*>(context_); auto ReportError = context.GetErrorReporter(); if (!device_) { return ReportError("Device must not be null", CL_INVALID_DEVICE); } Device& device = *static_cast<Device*>(device_); if (!context.ValidDeviceForContext(device)) { return ReportError("Device not valid for this context", CL_INVALID_DEVICE); } if (!command_queue) { return ReportError("Queue must not be null", CL_INVALID_COMMAND_QUEUE); } // We don't support creating on-device queues so it's impossible to call this correctly return ReportError("Queue is not an on-device queue", CL_INVALID_COMMAND_QUEUE); } extern CL_API_ENTRY cl_mem CL_API_CALL clCreatePipe(cl_context context, cl_mem_flags flags, cl_uint pipe_packet_size, cl_uint pipe_max_packets, const cl_pipe_properties * properties, cl_int * errcode_ret) CL_API_SUFFIX__VERSION_2_0 { if (!context) { if (errcode_ret) *errcode_ret = CL_INVALID_CONTEXT; return nullptr; } return static_cast<Context*>(context)->GetErrorReporter(errcode_ret)("Platform does not support pipes", CL_INVALID_OPERATION); } extern CL_API_ENTRY cl_int CL_API_CALL clGetPipeInfo(cl_mem pipe, cl_pipe_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_2_0 { return CL_INVALID_MEM_OBJECT; } extern CL_API_ENTRY void * CL_API_CALL clSVMAlloc(cl_context context, cl_svm_mem_flags flags, size_t size, cl_uint alignment) CL_API_SUFFIX__VERSION_2_0 { if (context) { static_cast<Context*>(context)->GetErrorReporter()("Platform does not support SVM", CL_INVALID_OPERATION); } return nullptr; } extern CL_API_ENTRY void CL_API_CALL clSVMFree(cl_context context, void * svm_pointer) CL_API_SUFFIX__VERSION_2_0 { if (context) { static_cast<Context*>(context)->GetErrorReporter()("Platform does not support SVM", CL_INVALID_OPERATION); } } extern CL_API_ENTRY cl_program CL_API_CALL clCreateProgramWithBuiltInKernels(cl_context context_, cl_uint num_devices, const cl_device_id * device_list, const char * kernel_names, cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2 { if (!context_) { if (errcode_ret) *errcode_ret = CL_INVALID_CONTEXT; return nullptr; } Context& context = *static_cast<Context*>(context_); auto ReportError = context.GetErrorReporter(errcode_ret); if (!device_list || !num_devices) { return ReportError("Device list must not be null", CL_INVALID_VALUE); } if (!kernel_names) { return ReportError("Kernel names must not be null", CL_INVALID_VALUE); } for (cl_uint i = 0; i < num_devices; ++i) { if (!device_list[i]) { return ReportError("Device list must not contain null entries", CL_INVALID_DEVICE); } if (!context.ValidDeviceForContext(*static_cast<Device*>(device_list[i]))) { return ReportError("Device list contains device that's invalid for context", CL_INVALID_DEVICE); } } return ReportError("No builtin kernels are supported by this platform", CL_INVALID_VALUE); } extern CL_API_ENTRY CL_API_PREFIX__VERSION_2_2_DEPRECATED cl_int CL_API_CALL clSetProgramReleaseCallback(cl_program program, void (CL_CALLBACK * pfn_notify)(cl_program program, void * user_data), void * user_data) CL_API_SUFFIX__VERSION_2_2_DEPRECATED { if (!program) { return CL_INVALID_PROGRAM; } Context& context = static_cast<Program*>(program)->m_Parent.get(); return context.GetErrorReporter()("This platform does not support global program destructors", CL_INVALID_OPERATION); } extern CL_API_ENTRY cl_int CL_API_CALL clSetProgramSpecializationConstant(cl_program program, cl_uint spec_id, size_t spec_size, const void* spec_value) CL_API_SUFFIX__VERSION_2_2 { if (!program) { return CL_INVALID_PROGRAM; } Context& context = static_cast<Program*>(program)->m_Parent.get(); return context.GetErrorReporter()("This platform does not yet support SPIR-V programs", CL_INVALID_OPERATION); } extern CL_API_ENTRY cl_int CL_API_CALL clSetKernelArgSVMPointer(cl_kernel kernel, cl_uint arg_index, const void * arg_value) CL_API_SUFFIX__VERSION_2_0 { if (!kernel) { return CL_INVALID_KERNEL; } return static_cast<Kernel*>(kernel)->m_Parent->m_Parent->GetErrorReporter()("Platform does not support SVM", CL_INVALID_OPERATION); } extern CL_API_ENTRY cl_int CL_API_CALL clSetKernelExecInfo(cl_kernel kernel, cl_kernel_exec_info param_name, size_t param_value_size, const void * param_value) CL_API_SUFFIX__VERSION_2_0 { if (!kernel) { return CL_INVALID_KERNEL; } return static_cast<Kernel*>(kernel)->m_Parent->m_Parent->GetErrorReporter()("Platform does not support SVM", CL_INVALID_OPERATION); } extern CL_API_ENTRY cl_int CL_API_CALL clGetKernelSubGroupInfo(cl_kernel kernel, cl_device_id device, cl_kernel_sub_group_info param_name, size_t input_value_size, const void* input_value, size_t param_value_size, void* param_value, size_t* param_value_size_ret) CL_API_SUFFIX__VERSION_2_1 { if (!kernel) { return CL_INVALID_KERNEL; } return static_cast<Kernel*>(kernel)->m_Parent->m_Parent->GetErrorReporter()("Platform does not support subgroups", CL_INVALID_OPERATION); } extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueNativeKernel(cl_command_queue command_queue, void (CL_CALLBACK * user_func)(void *), void * args, size_t cb_args, cl_uint num_mem_objects, const cl_mem * mem_list, const void ** args_mem_loc, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event) CL_API_SUFFIX__VERSION_1_0 { if (!command_queue) { return CL_INVALID_COMMAND_QUEUE; } return static_cast<CommandQueue*>(command_queue)->GetContext().GetErrorReporter()("Platform does not support native kernels", CL_INVALID_OPERATION); } extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueSVMFree(cl_command_queue command_queue, cl_uint num_svm_pointers, void * svm_pointers[], void (CL_CALLBACK * pfn_free_func)(cl_command_queue queue, cl_uint num_svm_pointers, void * svm_pointers[], void * user_data), void * user_data, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event) CL_API_SUFFIX__VERSION_2_0 { if (!command_queue) { return CL_INVALID_COMMAND_QUEUE; } return static_cast<CommandQueue*>(command_queue)->GetContext().GetErrorReporter()("Platform does not support SVM", CL_INVALID_OPERATION); } extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueSVMMemcpy(cl_command_queue command_queue, cl_bool blocking_copy, void * dst_ptr, const void * src_ptr, size_t size, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event) CL_API_SUFFIX__VERSION_2_0 { if (!command_queue) { return CL_INVALID_COMMAND_QUEUE; } return static_cast<CommandQueue*>(command_queue)->GetContext().GetErrorReporter()("Platform does not support SVM", CL_INVALID_OPERATION); } extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueSVMMemFill(cl_command_queue command_queue, void * svm_ptr, const void * pattern, size_t pattern_size, size_t size, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event) CL_API_SUFFIX__VERSION_2_0 { if (!command_queue) { return CL_INVALID_COMMAND_QUEUE; } return static_cast<CommandQueue*>(command_queue)->GetContext().GetErrorReporter()("Platform does not support SVM", CL_INVALID_OPERATION); } extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueSVMMap(cl_command_queue command_queue, cl_bool blocking_map, cl_map_flags flags, void * svm_ptr, size_t size, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event) CL_API_SUFFIX__VERSION_2_0 { if (!command_queue) { return CL_INVALID_COMMAND_QUEUE; } return static_cast<CommandQueue*>(command_queue)->GetContext().GetErrorReporter()("Platform does not support SVM", CL_INVALID_OPERATION); } extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueSVMUnmap(cl_command_queue command_queue, void * svm_ptr, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event) CL_API_SUFFIX__VERSION_2_0 { if (!command_queue) { return CL_INVALID_COMMAND_QUEUE; } return static_cast<CommandQueue*>(command_queue)->GetContext().GetErrorReporter()("Platform does not support SVM", CL_INVALID_OPERATION); } extern CL_API_ENTRY cl_int CL_API_CALL clEnqueueSVMMigrateMem(cl_command_queue command_queue, cl_uint num_svm_pointers, const void ** svm_pointers, const size_t * sizes, cl_mem_migration_flags flags, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event) CL_API_SUFFIX__VERSION_2_1 { if (!command_queue) { return CL_INVALID_COMMAND_QUEUE; } return static_cast<CommandQueue*>(command_queue)->GetContext().GetErrorReporter()("Platform does not support SVM", CL_INVALID_OPERATION); } /* Extension function access * * Returns the extension function address for the given function name, * or NULL if a valid function can not be found. The client must * check to make sure the address is not NULL, before using or * calling the returned function address. */ extern CL_API_ENTRY void * CL_API_CALL clGetExtensionFunctionAddressForPlatform(cl_platform_id platform, const char * func_name) CL_API_SUFFIX__VERSION_1_2 { return nullptr; } /* Deprecated OpenCL 1.1 APIs */ extern CL_API_ENTRY CL_API_PREFIX__VERSION_1_1_DEPRECATED cl_int CL_API_CALL clUnloadCompiler(void) CL_API_SUFFIX__VERSION_1_1_DEPRECATED { return CL_SUCCESS; } <|start_filename|>include/queue.hpp<|end_filename|> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include "device.hpp" #include "context.hpp" #include "task.hpp" class CommandQueue : public CLChildBase<CommandQueue, Device, cl_command_queue> { public: CommandQueue(Device& device, Context& context, const cl_queue_properties* properties, bool synthesizedProperties); friend cl_int CL_API_CALL clGetCommandQueueInfo(cl_command_queue, cl_command_queue_info, size_t, void*, size_t*); Context& GetContext() const { return m_Context.get(); } Device& GetDevice() const { return m_Parent.get(); } void Flush(TaskPoolLock const&, bool flushDevice); void QueueTask(Task*, TaskPoolLock const&); void NotifyTaskCompletion(Task*, TaskPoolLock const&); void AddAllTasksAsDependencies(Task*, TaskPoolLock const&); const bool m_bOutOfOrder; const bool m_bProfile; const bool m_bPropertiesSynthesized; std::vector<cl_queue_properties> const m_Properties; protected: Context::ref_int m_Context; std::deque<Task::ref_ptr> m_QueuedTasks; std::vector<Task::ref_ptr_int> m_OutstandingTasks; Task* m_LastQueuedTask = nullptr; Task* m_LastQueuedBarrier = nullptr; }; <|start_filename|>src/cache.cpp<|end_filename|> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include "platform.hpp" #include "cache.hpp" #include "compiler.hpp" #include <numeric> #pragma warning(disable: 4100) ShaderCache::ShaderCache(ID3D12Device* d) { #ifdef __ID3D12ShaderCacheSession_INTERFACE_DEFINED__ ComPtr<ID3D12Device9> device9; if (FAILED(d->QueryInterface(device9.ReleaseAndGetAddressOf()))) return; D3D12_SHADER_CACHE_SESSION_DESC Desc = {}; // {17CB474E-4C55-4DBC-BC2E-D5132115BDA3} Desc.Identifier = { 0x17cb474e, 0x4c55, 0x4dbc, { 0xbc, 0x2e, 0xd5, 0x13, 0x21, 0x15, 0xbd, 0xa3 } }; Desc.Mode = D3D12_SHADER_CACHE_MODE_DISK; auto pCompiler = g_Platform->GetCompiler(); Desc.Version = pCompiler->GetVersionForCache(); (void)device9->CreateShaderCacheSession(&Desc, IID_PPV_ARGS(&m_pSession)); #endif } void ShaderCache::Store(const void* key, size_t keySize, const void* value, size_t valueSize) noexcept { #ifdef __ID3D12ShaderCacheSession_INTERFACE_DEFINED__ if (m_pSession) { (void)m_pSession->StoreValue(key, (UINT)keySize, value, (UINT)valueSize); } #endif } void ShaderCache::Store(const void* const* keys, const size_t* keySizes, unsigned keyParts, const void* value, size_t valueSize) { #ifdef __ID3D12ShaderCacheSession_INTERFACE_DEFINED__ if (m_pSession) { size_t combinedSize = std::accumulate(keySizes, keySizes + keyParts, (size_t)0); std::unique_ptr<byte[]> combinedKey(new byte[combinedSize]); unsigned i = 0; for (byte* ptr = combinedKey.get(); ptr != combinedKey.get() + combinedSize; ptr += keySizes[i++]) { memcpy(ptr, keys[i], keySizes[i]); } Store(combinedKey.get(), combinedSize, value, valueSize); } #endif } ShaderCache::FoundValue ShaderCache::Find(const void* key, size_t keySize) { #ifdef __ID3D12ShaderCacheSession_INTERFACE_DEFINED__ if (m_pSession) { UINT valueSize = 0; if (SUCCEEDED(m_pSession->FindValue(key, (UINT)keySize, nullptr, &valueSize))) { ShaderCache::FoundValue value(new byte[valueSize], valueSize); if (SUCCEEDED(m_pSession->FindValue(key, (UINT)keySize, value.first.get(), &valueSize))) { return value; } } } #endif return {}; } ShaderCache::FoundValue ShaderCache::Find(const void* const* keys, const size_t* keySizes, unsigned keyParts) { #ifdef __ID3D12ShaderCacheSession_INTERFACE_DEFINED__ if (m_pSession) { size_t combinedSize = std::accumulate(keySizes, keySizes + keyParts, (size_t)0); std::unique_ptr<byte[]> combinedKey(new byte[combinedSize]); unsigned i = 0; for (byte* ptr = combinedKey.get(); ptr != combinedKey.get() + combinedSize; ptr += keySizes[i++]) { memcpy(ptr, keys[i], keySizes[i]); } return Find(combinedKey.get(), combinedSize); } #endif return {}; } void ShaderCache::Close() { #ifdef __ID3D12ShaderCacheSession_INTERFACE_DEFINED__ m_pSession.Reset(); #endif } <|start_filename|>src/compilers/v1/clc_compiler.h<|end_filename|> /* * Copyright © Microsoft Corporation * * 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 (including the next * paragraph) 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. */ #ifndef CLC_COMPILER_H #define CLC_COMPILER_H #ifdef __cplusplus extern "C" { #endif #include <stddef.h> #include <stdint.h> struct clc_named_value { const char *name; const char *value; }; struct clc_compile_args { const struct clc_named_value *headers; unsigned num_headers; struct clc_named_value source; const char * const *args; unsigned num_args; }; struct clc_linker_args { const struct clc_object * const *in_objs; unsigned num_in_objs; unsigned create_library; }; typedef void (*clc_msg_callback)(void *priv, const char *msg); struct clc_logger { void *priv; clc_msg_callback error; clc_msg_callback warning; }; struct spirv_binary { uint32_t *data; size_t size; }; enum clc_kernel_arg_type_qualifier { CLC_KERNEL_ARG_TYPE_CONST = 1 << 0, CLC_KERNEL_ARG_TYPE_RESTRICT = 1 << 1, CLC_KERNEL_ARG_TYPE_VOLATILE = 1 << 2, }; enum clc_kernel_arg_access_qualifier { CLC_KERNEL_ARG_ACCESS_READ = 1 << 0, CLC_KERNEL_ARG_ACCESS_WRITE = 1 << 1, }; enum clc_kernel_arg_address_qualifier { CLC_KERNEL_ARG_ADDRESS_PRIVATE, CLC_KERNEL_ARG_ADDRESS_CONSTANT, CLC_KERNEL_ARG_ADDRESS_LOCAL, CLC_KERNEL_ARG_ADDRESS_GLOBAL, }; struct clc_kernel_arg { const char *name; const char *type_name; unsigned type_qualifier; unsigned access_qualifier; enum clc_kernel_arg_address_qualifier address_qualifier; }; enum clc_vec_hint_type { CLC_VEC_HINT_TYPE_CHAR = 0, CLC_VEC_HINT_TYPE_SHORT = 1, CLC_VEC_HINT_TYPE_INT = 2, CLC_VEC_HINT_TYPE_LONG = 3, CLC_VEC_HINT_TYPE_HALF = 4, CLC_VEC_HINT_TYPE_FLOAT = 5, CLC_VEC_HINT_TYPE_DOUBLE = 6 }; struct clc_kernel_info { const char *name; size_t num_args; const struct clc_kernel_arg *args; unsigned vec_hint_size; enum clc_vec_hint_type vec_hint_type; }; struct clc_object { struct spirv_binary spvbin; const struct clc_kernel_info *kernels; unsigned num_kernels; }; #define CLC_MAX_CONSTS 32 #define CLC_MAX_BINDINGS_PER_ARG 3 #define CLC_MAX_SAMPLERS 16 struct clc_printf_info { unsigned num_args; unsigned *arg_sizes; char *str; }; struct clc_dxil_metadata { struct { unsigned offset; unsigned size; union { struct { unsigned buf_ids[CLC_MAX_BINDINGS_PER_ARG]; unsigned num_buf_ids; } image; struct { unsigned sampler_id; } sampler; struct { unsigned buf_id; } globconstptr; struct { unsigned sharedmem_offset; } localptr; }; } *args; unsigned kernel_inputs_cbv_id; unsigned kernel_inputs_buf_size; unsigned work_properties_cbv_id; size_t num_uavs; size_t num_srvs; size_t num_samplers; struct { void *data; size_t size; unsigned uav_id; } consts[CLC_MAX_CONSTS]; size_t num_consts; struct { unsigned sampler_id; unsigned addressing_mode; unsigned normalized_coords; unsigned filter_mode; } const_samplers[CLC_MAX_SAMPLERS]; size_t num_const_samplers; size_t local_mem_size; size_t priv_mem_size; uint16_t local_size[3]; uint16_t local_size_hint[3]; struct { unsigned info_count; struct clc_printf_info *infos; int uav_id; } printf; }; struct clc_dxil_object { const struct clc_kernel_info *kernel; struct clc_dxil_metadata metadata; struct { void *data; size_t size; } binary; }; struct clc_context { const void *libclc_nir; }; struct clc_context_options { unsigned optimize; }; struct clc_context *clc_context_new(const struct clc_logger *logger, const struct clc_context_options *options); void clc_free_context(struct clc_context *ctx); void clc_context_serialize(struct clc_context *ctx, void **serialized, size_t *size); void clc_context_free_serialized(void *serialized); struct clc_context *clc_context_deserialize(void *serialized, size_t size); struct clc_object * clc_compile(struct clc_context *ctx, const struct clc_compile_args *args, const struct clc_logger *logger); struct clc_object * clc_link(struct clc_context *ctx, const struct clc_linker_args *args, const struct clc_logger *logger); void clc_free_object(struct clc_object *obj); struct clc_runtime_arg_info { union { struct { unsigned size; } localptr; struct { unsigned normalized_coords; unsigned addressing_mode; /* See SPIR-V spec for value meanings */ unsigned linear_filtering; } sampler; }; }; struct clc_runtime_kernel_conf { uint16_t local_size[3]; struct clc_runtime_arg_info *args; unsigned lower_bit_size; unsigned support_global_work_id_offsets; unsigned support_work_group_id_offsets; }; struct clc_dxil_object * clc_to_dxil(struct clc_context *ctx, const struct clc_object *obj, const char *entrypoint, const struct clc_runtime_kernel_conf *conf, const struct clc_logger *logger); void clc_free_dxil_object(struct clc_dxil_object *dxil); /* This struct describes the layout of data expected in the CB bound at global_work_offset_cbv_id */ struct clc_work_properties_data { /* Returned from get_global_offset(), and added into get_global_id() */ unsigned global_offset_x; unsigned global_offset_y; unsigned global_offset_z; /* Returned from get_work_dim() */ unsigned work_dim; /* The number of work groups being launched (i.e. the parameters to Dispatch). * If the requested global size doesn't fit in a single Dispatch, these values should * indicate the total number of groups that *should* have been launched. */ unsigned group_count_total_x; unsigned group_count_total_y; unsigned group_count_total_z; unsigned padding; /* If the requested global size doesn't fit in a single Dispatch, subsequent dispatches * should fill out these offsets to indicate how many groups have already been launched */ unsigned group_id_offset_x; unsigned group_id_offset_y; unsigned group_id_offset_z; }; uint64_t clc_compiler_get_version(); #ifdef __cplusplus } #endif #endif <|start_filename|>src/kernel.cpp<|end_filename|> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "kernel.hpp" #include "sampler.hpp" #include "compiler.hpp" extern CL_API_ENTRY cl_kernel CL_API_CALL clCreateKernel(cl_program program_, const char* kernel_name, cl_int* errcode_ret) CL_API_SUFFIX__VERSION_1_0 { if (!program_) { if (errcode_ret) *errcode_ret = CL_INVALID_PROGRAM; return nullptr; } Program& program = *static_cast<Program*>(program_); auto ReportError = program.GetContext().GetErrorReporter(errcode_ret); const CompiledDxil* kernel = nullptr; { std::lock_guard Lock(program.m_Lock); cl_uint DeviceCountWithProgram = 0, DeviceCountWithKernel = 0; for (auto& Device : program.m_AssociatedDevices) { auto& BuildData = program.m_BuildData[Device.Get()]; if (!BuildData || BuildData->m_BuildStatus != CL_BUILD_SUCCESS || BuildData->m_BinaryType != CL_PROGRAM_BINARY_TYPE_EXECUTABLE) { continue; } ++DeviceCountWithProgram; auto iter = BuildData->m_Kernels.find(kernel_name); if (iter == BuildData->m_Kernels.end()) { continue; } ++DeviceCountWithKernel; if (kernel) { auto& first_info = kernel->GetMetadata().program_kernel_info; auto& second_info = iter->second.m_GenericDxil->GetMetadata().program_kernel_info; if (first_info.args.size() != second_info.args.size()) { return ReportError("Kernel argument count differs between devices.", CL_INVALID_KERNEL_DEFINITION); } for (unsigned i = 0; i < first_info.args.size(); ++i) { auto& a = first_info.args[i]; auto& b = second_info.args[i]; if (strcmp(a.type_name, b.type_name) != 0 || strcmp(a.name, b.name) != 0 || a.address_qualifier != b.address_qualifier || a.readable != b.readable || a.writable != b.writable || a.is_const != b.is_const || a.is_restrict != b.is_restrict || a.is_volatile != b.is_volatile) { return ReportError("Kernel argument differs between devices.", CL_INVALID_KERNEL_DEFINITION); } } } kernel = iter->second.m_GenericDxil.get(); if (!kernel) { return ReportError("Kernel failed to compile.", CL_OUT_OF_RESOURCES); } } if (!DeviceCountWithProgram) { return ReportError("No executable available for program.", CL_INVALID_PROGRAM_EXECUTABLE); } if (!DeviceCountWithKernel) { return ReportError("No kernel with that name found.", CL_INVALID_KERNEL_NAME); } } try { if (errcode_ret) *errcode_ret = CL_SUCCESS; return new Kernel(program, kernel_name, *kernel); } catch (std::bad_alloc&) { return ReportError(nullptr, CL_OUT_OF_HOST_MEMORY); } catch (std::exception & e) { return ReportError(e.what(), CL_OUT_OF_RESOURCES); } catch (_com_error&) { return ReportError(nullptr, CL_OUT_OF_RESOURCES); } } extern CL_API_ENTRY cl_int CL_API_CALL clCreateKernelsInProgram(cl_program program_, cl_uint num_kernels, cl_kernel* kernels, cl_uint* num_kernels_ret) CL_API_SUFFIX__VERSION_1_0 { if (!program_) { return CL_INVALID_PROGRAM; } Program& program = *static_cast<Program*>(program_); auto ReportError = program.GetContext().GetErrorReporter(); try { std::map<std::string, Kernel::ref_ptr> temp; { std::lock_guard Lock(program.m_Lock); for (auto& Device : program.m_AssociatedDevices) { auto& BuildData = program.m_BuildData[Device.Get()]; if (!BuildData || BuildData->m_BuildStatus != CL_BUILD_SUCCESS || BuildData->m_BinaryType != CL_PROGRAM_BINARY_TYPE_EXECUTABLE) { continue; } for (auto& pair : BuildData->m_Kernels) { temp.emplace(pair.first, nullptr); } } if (temp.empty()) { return ReportError("No executable available for program.", CL_INVALID_PROGRAM_EXECUTABLE); } if (num_kernels && num_kernels < temp.size()) { return ReportError("num_kernels is too small.", CL_INVALID_VALUE); } } if (num_kernels_ret) { *num_kernels_ret = (cl_uint)temp.size(); } if (num_kernels) { for (auto& pair : temp) { cl_int error = CL_SUCCESS; pair.second.Attach(static_cast<Kernel*>(clCreateKernel(program_, pair.first.c_str(), &error))); if (error != CL_SUCCESS) { return error; } } for (auto& pair : temp) { *kernels = pair.second.Detach(); ++kernels; } } } catch (std::bad_alloc&) { return ReportError(nullptr, CL_OUT_OF_HOST_MEMORY); } catch (std::exception & e) { return ReportError(e.what(), CL_OUT_OF_RESOURCES); } catch (_com_error&) { return ReportError(nullptr, CL_OUT_OF_RESOURCES); } return CL_SUCCESS; } extern CL_API_ENTRY cl_int CL_API_CALL clRetainKernel(cl_kernel kernel) CL_API_SUFFIX__VERSION_1_0 { if (!kernel) { return CL_INVALID_KERNEL; } static_cast<Kernel*>(kernel)->Retain(); return CL_SUCCESS; } extern CL_API_ENTRY cl_int CL_API_CALL clReleaseKernel(cl_kernel kernel) CL_API_SUFFIX__VERSION_1_0 { if (!kernel) { return CL_INVALID_KERNEL; } static_cast<Kernel*>(kernel)->Release(); return CL_SUCCESS; } extern CL_API_ENTRY cl_int CL_API_CALL clSetKernelArg(cl_kernel kernel, cl_uint arg_index, size_t arg_size, const void* arg_value) CL_API_SUFFIX__VERSION_1_0 { if (!kernel) { return CL_INVALID_KERNEL; } return static_cast<Kernel*>(kernel)->SetArg(arg_index, arg_size, arg_value); } static cl_mem_object_type MemObjectTypeFromName(const char* name) { if (strcmp(name, "image1d_buffer_t") == 0) return CL_MEM_OBJECT_IMAGE1D_BUFFER; if (strcmp(name, "image1d_t") == 0) return CL_MEM_OBJECT_IMAGE1D; if (strcmp(name, "image1d_array_t") == 0) return CL_MEM_OBJECT_IMAGE1D_ARRAY; if (strcmp(name, "image2d_t") == 0) return CL_MEM_OBJECT_IMAGE2D; if (strcmp(name, "image2d_array_t") == 0) return CL_MEM_OBJECT_IMAGE2D_ARRAY; if (strcmp(name, "image3d_t") == 0) return CL_MEM_OBJECT_IMAGE3D; return 0; } static D3D12TranslationLayer::RESOURCE_DIMENSION ResourceDimensionFromMemObjectType(cl_mem_object_type type) { switch (type) { case CL_MEM_OBJECT_IMAGE1D: return D3D12TranslationLayer::RESOURCE_DIMENSION::TEXTURE1D; case CL_MEM_OBJECT_IMAGE1D_ARRAY: return D3D12TranslationLayer::RESOURCE_DIMENSION::TEXTURE1DARRAY; case CL_MEM_OBJECT_IMAGE1D_BUFFER: return D3D12TranslationLayer::RESOURCE_DIMENSION::BUFFER; case CL_MEM_OBJECT_IMAGE2D: return D3D12TranslationLayer::RESOURCE_DIMENSION::TEXTURE2D; case CL_MEM_OBJECT_IMAGE2D_ARRAY: return D3D12TranslationLayer::RESOURCE_DIMENSION::TEXTURE2DARRAY; case CL_MEM_OBJECT_IMAGE3D: return D3D12TranslationLayer::RESOURCE_DIMENSION::TEXTURE3D; } return D3D12TranslationLayer::RESOURCE_DIMENSION::UNKNOWN; } static D3D12TranslationLayer::SShaderDecls DeclsFromMetadata(CompiledDxil::Metadata const& metadata) { D3D12TranslationLayer::SShaderDecls decls = {}; cl_uint KernelArgCBIndex = metadata.kernel_inputs_cbv_id; cl_uint WorkPropertiesCBIndex = metadata.work_properties_cbv_id; decls.m_NumCBs = max(KernelArgCBIndex + 1, WorkPropertiesCBIndex + 1); decls.m_NumSamplers = (UINT)metadata.num_samplers; decls.m_ResourceDecls.resize(metadata.num_srvs); decls.m_UAVDecls.resize(metadata.num_uavs); for (cl_uint i = 0; i < metadata.args.size(); ++i) { auto& arg_info = metadata.program_kernel_info.args[i]; auto& arg_meta = metadata.args[i]; if (arg_info.address_qualifier == ProgramBinary::Kernel::Arg::AddressSpace::Global || arg_info.address_qualifier == ProgramBinary::Kernel::Arg::AddressSpace::Constant) { cl_mem_object_type imageType = MemObjectTypeFromName(arg_info.type_name); if (imageType != 0) { auto dim = ResourceDimensionFromMemObjectType(imageType); bool uav = arg_info.writable; auto& declVector = uav ? decls.m_UAVDecls : decls.m_ResourceDecls; auto& image_meta = std::get<CompiledDxil::Metadata::Arg::Image>(arg_meta.properties); for (cl_uint j = 0; j < image_meta.num_buffer_ids; ++j) declVector[image_meta.buffer_ids[j]] = dim; } else { auto& mem_meta = std::get<CompiledDxil::Metadata::Arg::Memory>(arg_meta.properties); decls.m_UAVDecls[mem_meta.buffer_id] = D3D12TranslationLayer::RESOURCE_DIMENSION::BUFFER; } } } return decls; } static cl_addressing_mode CLAddressingModeFromSpirv(unsigned addressing_mode) { return addressing_mode + CL_ADDRESS_NONE; } static unsigned SpirvAddressingModeFromCL(cl_addressing_mode mode) { return mode - CL_ADDRESS_NONE; } static cl_filter_mode CLFilterModeFromSpirv(unsigned filter_mode) { return filter_mode + CL_FILTER_NEAREST; } Kernel::Kernel(Program& Parent, std::string const& name, CompiledDxil const& Dxil) : CLChildBase(Parent) , m_Dxil(Dxil) , m_Name(name) , m_ShaderDecls(DeclsFromMetadata(Dxil.GetMetadata())) { m_UAVs.resize(m_ShaderDecls.m_UAVDecls.size()); m_SRVs.resize(m_ShaderDecls.m_ResourceDecls.size()); m_Samplers.resize(m_ShaderDecls.m_NumSamplers); m_ArgMetadataToCompiler.resize(Dxil.GetMetadata().args.size()); for (cl_uint i = 0; i < Dxil.GetMetadata().args.size(); ++i) { auto& meta = Dxil.GetMetadata().args[i]; auto& config = m_ArgMetadataToCompiler[i].config; if (std::holds_alternative<CompiledDxil::Metadata::Arg::Local>(meta.properties)) config = CompiledDxil::Configuration::Arg::Local{ 0 }; else if (std::holds_alternative<CompiledDxil::Metadata::Arg::Sampler>(meta.properties)) config = CompiledDxil::Configuration::Arg::Sampler{}; } size_t KernelInputsCbSize = Dxil.GetMetadata().kernel_inputs_buf_size; m_KernelArgsCbData.resize(KernelInputsCbSize); m_ConstSamplers.reserve(Dxil.GetMetadata().constSamplers.size()); for (auto& samplerMeta : Dxil.GetMetadata().constSamplers) { Sampler::Desc desc = { samplerMeta.normalized_coords, CLAddressingModeFromSpirv(samplerMeta.addressing_mode), CLFilterModeFromSpirv(samplerMeta.filter_mode) }; m_ConstSamplers.emplace_back(new Sampler(m_Parent->GetContext(), desc, nullptr)); m_Samplers[samplerMeta.sampler_id] = m_ConstSamplers.back().Get(); } for (auto& constMeta : Dxil.GetMetadata().consts) { auto resource = static_cast<Resource*>(clCreateBuffer(&Parent.GetContext(), CL_MEM_COPY_HOST_PTR | CL_MEM_READ_ONLY | CL_MEM_HOST_NO_ACCESS, constMeta.size, constMeta.data, nullptr)); m_InlineConsts.emplace_back(resource, adopt_ref{}); m_UAVs[constMeta.uav_id] = resource; } m_Parent->KernelCreated(); } Kernel::Kernel(Kernel const& other) : CLChildBase(other.m_Parent.get()) , m_Dxil(other.m_Dxil) , m_Name(other.m_Name) , m_ShaderDecls(other.m_ShaderDecls) , m_UAVs(other.m_UAVs) , m_SRVs(other.m_SRVs) , m_Samplers(other.m_Samplers) , m_ArgMetadataToCompiler(other.m_ArgMetadataToCompiler) , m_KernelArgsCbData(other.m_KernelArgsCbData) , m_ConstSamplers(other.m_ConstSamplers) , m_InlineConsts(other.m_InlineConsts) { m_Parent->KernelCreated(); } Kernel::~Kernel() { m_Parent->KernelFreed(); } cl_int Kernel::SetArg(cl_uint arg_index, size_t arg_size, const void* arg_value) { auto ReportError = m_Parent->GetContext().GetErrorReporter(); if (arg_index > m_Dxil.GetMetadata().args.size()) { return ReportError("Argument index out of bounds", CL_INVALID_ARG_INDEX); } auto& arg_meta = m_Dxil.GetMetadata().args[arg_index]; auto& arg_info = m_Dxil.GetMetadata().program_kernel_info.args[arg_index]; switch (arg_info.address_qualifier) { case ProgramBinary::Kernel::Arg::AddressSpace::Global: case ProgramBinary::Kernel::Arg::AddressSpace::Constant: { if (arg_size != sizeof(cl_mem)) { return ReportError("Invalid argument size, must be sizeof(cl_mem) for global and constant arguments", CL_INVALID_ARG_SIZE); } cl_mem_object_type imageType = MemObjectTypeFromName(arg_info.type_name); cl_mem mem = arg_value ? *reinterpret_cast<cl_mem const*>(arg_value) : nullptr; Resource* resource = static_cast<Resource*>(mem); if (imageType != 0) { auto& imageMeta = std::get<CompiledDxil::Metadata::Arg::Image>(arg_meta.properties); bool validImageType = true; if (resource) { validImageType = resource->m_Desc.image_type == imageType; } if (!validImageType) { return ReportError("Invalid image type.", CL_INVALID_ARG_VALUE); } if (arg_info.writable) { if (resource && (resource->m_Flags & CL_MEM_READ_ONLY)) { return ReportError("Invalid mem object flags, binding read-only image to writable image argument.", CL_INVALID_ARG_VALUE); } if (arg_info.readable && resource && (resource->m_Flags & CL_MEM_WRITE_ONLY)) { return ReportError("Invalid mem object flags, binding write-only image to read-write image argument.", CL_INVALID_ARG_VALUE); } for (cl_uint i = 0; i < imageMeta.num_buffer_ids; ++i) { m_UAVs[imageMeta.buffer_ids[i]] = resource; } } else { if (resource && (resource->m_Flags & CL_MEM_WRITE_ONLY)) { return ReportError("Invalid mem object flags, binding write-only image to read-only image argument.", CL_INVALID_ARG_VALUE); } for (cl_uint i = 0; i < imageMeta.num_buffer_ids; ++i) { m_SRVs[imageMeta.buffer_ids[i]] = resource; } } // Store image format in the kernel args cl_image_format* ImageFormatInKernelArgs = reinterpret_cast<cl_image_format*>( m_KernelArgsCbData.data() + arg_meta.offset); *ImageFormatInKernelArgs = {}; if (resource) { *ImageFormatInKernelArgs = resource->m_Format; // The SPIR-V expects the values coming from the intrinsics to be 0-indexed, and implicitly // adds the necessary values to put it back into the CL constant range ImageFormatInKernelArgs->image_channel_data_type -= CL_SNORM_INT8; ImageFormatInKernelArgs->image_channel_order -= CL_R; } } else { if (resource && resource->m_Desc.image_type != CL_MEM_OBJECT_BUFFER) { return ReportError("Invalid mem object type, must be buffer.", CL_INVALID_ARG_VALUE); } auto& memMeta = std::get<CompiledDxil::Metadata::Arg::Memory>(arg_meta.properties); uint64_t *buffer_val = reinterpret_cast<uint64_t*>(m_KernelArgsCbData.data() + arg_meta.offset); m_UAVs[memMeta.buffer_id] = resource; if (resource) { *buffer_val = (uint64_t)memMeta.buffer_id << 32ull; } else { *buffer_val = ~0ull; } } break; } case ProgramBinary::Kernel::Arg::AddressSpace::Private: if (strcmp(arg_info.type_name, "sampler_t") == 0) { if (arg_size != sizeof(cl_sampler)) { return ReportError("Invalid argument size, must be sizeof(cl_mem) for global arguments", CL_INVALID_ARG_SIZE); } cl_sampler samp = arg_value ? *reinterpret_cast<cl_sampler const*>(arg_value) : nullptr; Sampler* sampler = static_cast<Sampler*>(samp); auto& samplerMeta = std::get<CompiledDxil::Metadata::Arg::Sampler>(arg_meta.properties); auto& samplerConfig = std::get<CompiledDxil::Configuration::Arg::Sampler>(m_ArgMetadataToCompiler[arg_index].config); m_Samplers[samplerMeta.sampler_id] = sampler; samplerConfig.normalizedCoords = sampler ? sampler->m_Desc.NormalizedCoords : 1u; samplerConfig.addressingMode = sampler ? SpirvAddressingModeFromCL(sampler->m_Desc.AddressingMode) : 0u; samplerConfig.linearFiltering = sampler ? (sampler->m_Desc.FilterMode == CL_FILTER_LINEAR) : 0u; } else { if (arg_size != arg_meta.size) { return ReportError("Invalid argument size", CL_INVALID_ARG_SIZE); } memcpy(m_KernelArgsCbData.data() + arg_meta.offset, arg_value, arg_size); } break; case ProgramBinary::Kernel::Arg::AddressSpace::Local: if (arg_size == 0) { return ReportError("Argument size must be nonzero for local arguments", CL_INVALID_ARG_SIZE); } if (arg_value != nullptr) { return ReportError("Argument value must be null for local arguments", CL_INVALID_ARG_VALUE); } auto& localConfig = std::get<CompiledDxil::Configuration::Arg::Local>(m_ArgMetadataToCompiler[arg_index].config); localConfig.size = (cl_uint)arg_size; break; } return CL_SUCCESS; } uint16_t const* Kernel::GetRequiredLocalDims() const { if (m_Dxil.GetMetadata().local_size[0] != 0) return m_Dxil.GetMetadata().local_size; return nullptr; } uint16_t const* Kernel::GetLocalDimsHint() const { if (m_Dxil.GetMetadata().local_size_hint[0] != 0) return m_Dxil.GetMetadata().local_size_hint; return nullptr; } extern CL_API_ENTRY cl_int CL_API_CALL clGetKernelInfo(cl_kernel kernel_, cl_kernel_info param_name, size_t param_value_size, void* param_value, size_t* param_value_size_ret) CL_API_SUFFIX__VERSION_1_0 { if (!kernel_) { return CL_INVALID_KERNEL; } auto RetValue = [&](auto&& param) { return CopyOutParameter(param, param_value_size, param_value, param_value_size_ret); }; auto& kernel = *static_cast<Kernel*>(kernel_); switch (param_name) { case CL_KERNEL_FUNCTION_NAME: return RetValue(kernel.m_Dxil.GetMetadata().program_kernel_info.name); case CL_KERNEL_NUM_ARGS: return RetValue((cl_uint)kernel.m_Dxil.GetMetadata().args.size()); case CL_KERNEL_REFERENCE_COUNT: return RetValue(kernel.GetRefCount()); case CL_KERNEL_CONTEXT: return RetValue((cl_context)&kernel.m_Parent->m_Parent.get()); case CL_KERNEL_PROGRAM: return RetValue((cl_program)&kernel.m_Parent.get()); case CL_KERNEL_ATTRIBUTES: return RetValue(""); } return kernel.m_Parent->GetContext().GetErrorReporter()("Unknown param_name", CL_INVALID_VALUE); } extern CL_API_ENTRY cl_int CL_API_CALL clGetKernelArgInfo(cl_kernel kernel_, cl_uint arg_indx, cl_kernel_arg_info param_name, size_t param_value_size, void* param_value, size_t* param_value_size_ret) CL_API_SUFFIX__VERSION_1_2 { if (!kernel_) { return CL_INVALID_KERNEL; } auto RetValue = [&](auto&& param) { return CopyOutParameter(param, param_value_size, param_value, param_value_size_ret); }; auto& kernel = *static_cast<Kernel*>(kernel_); if (arg_indx > kernel.m_Dxil.GetMetadata().args.size()) { return CL_INVALID_ARG_INDEX; } auto& arg_info = kernel.m_Dxil.GetMetadata().program_kernel_info.args[arg_indx]; switch (param_name) { case CL_KERNEL_ARG_ADDRESS_QUALIFIER: switch (arg_info.address_qualifier) { default: case ProgramBinary::Kernel::Arg::AddressSpace::Private: return RetValue(CL_KERNEL_ARG_ADDRESS_PRIVATE); case ProgramBinary::Kernel::Arg::AddressSpace::Constant: return RetValue(CL_KERNEL_ARG_ADDRESS_CONSTANT); case ProgramBinary::Kernel::Arg::AddressSpace::Local: return RetValue(CL_KERNEL_ARG_ADDRESS_LOCAL); case ProgramBinary::Kernel::Arg::AddressSpace::Global: return RetValue(CL_KERNEL_ARG_ADDRESS_GLOBAL); } break; case CL_KERNEL_ARG_ACCESS_QUALIFIER: if (arg_info.writable && arg_info.readable) return RetValue(CL_KERNEL_ARG_ACCESS_READ_WRITE); else if (arg_info.writable) return RetValue(CL_KERNEL_ARG_ACCESS_WRITE_ONLY); else if (arg_info.readable) return RetValue(CL_KERNEL_ARG_ACCESS_READ_ONLY); else return RetValue(CL_KERNEL_ARG_ACCESS_NONE); case CL_KERNEL_ARG_TYPE_NAME: return RetValue(arg_info.type_name); case CL_KERNEL_ARG_TYPE_QUALIFIER: { cl_kernel_arg_type_qualifier qualifier = CL_KERNEL_ARG_TYPE_NONE; if (arg_info.is_const || arg_info.address_qualifier == ProgramBinary::Kernel::Arg::AddressSpace::Constant) qualifier |= CL_KERNEL_ARG_TYPE_CONST; if (arg_info.is_restrict) qualifier |= CL_KERNEL_ARG_TYPE_RESTRICT; if (arg_info.is_volatile) qualifier |= CL_KERNEL_ARG_TYPE_VOLATILE; return RetValue(qualifier); } case CL_KERNEL_ARG_NAME: if (arg_info.name) return RetValue(arg_info.name); return CL_KERNEL_ARG_INFO_NOT_AVAILABLE; } return kernel.m_Parent->GetContext().GetErrorReporter()("Unknown param_name", CL_INVALID_VALUE); } extern CL_API_ENTRY cl_int CL_API_CALL clGetKernelWorkGroupInfo(cl_kernel kernel_, cl_device_id device, cl_kernel_work_group_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0 { if (!kernel_) { return CL_INVALID_KERNEL; } UNREFERENCED_PARAMETER(device); auto RetValue = [&](auto&& param) { return CopyOutParameter(param, param_value_size, param_value, param_value_size_ret); }; auto& kernel = *static_cast<Kernel*>(kernel_); switch (param_name) { case CL_KERNEL_WORK_GROUP_SIZE: return RetValue((size_t)D3D12_CS_THREAD_GROUP_MAX_THREADS_PER_GROUP); case CL_KERNEL_COMPILE_WORK_GROUP_SIZE: { size_t size[3] = {}; auto ReqDims = kernel.GetRequiredLocalDims(); if (ReqDims) std::copy(ReqDims, ReqDims + 3, size); return RetValue(size); } case CL_KERNEL_LOCAL_MEM_SIZE: { size_t size = kernel.m_Dxil.GetMetadata().local_mem_size; for (cl_uint i = 0; i < kernel.m_Dxil.GetMetadata().args.size(); ++i) { if (kernel.m_Dxil.GetMetadata().program_kernel_info.args[i].address_qualifier == ProgramBinary::Kernel::Arg::AddressSpace::Local) { size -= 4; size += std::get<CompiledDxil::Configuration::Arg::Local>(kernel.m_ArgMetadataToCompiler[i].config).size; } } return RetValue(size); } case CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE: return RetValue((size_t)64); case CL_KERNEL_PRIVATE_MEM_SIZE: return RetValue(kernel.m_Dxil.GetMetadata().priv_mem_size); } return CL_INVALID_VALUE; } extern CL_API_ENTRY cl_kernel CL_API_CALL clCloneKernel(cl_kernel source_kernel, cl_int* errcode_ret) CL_API_SUFFIX__VERSION_2_1 { if (!source_kernel) { if (errcode_ret) *errcode_ret = CL_INVALID_KERNEL; return nullptr; } Kernel &kernel = *static_cast<Kernel*>(source_kernel); auto ReportError = kernel.m_Parent->m_Parent->GetErrorReporter(errcode_ret); try { if (errcode_ret) *errcode_ret = CL_SUCCESS; return new Kernel(kernel); } catch (std::bad_alloc&) { return ReportError(nullptr, CL_OUT_OF_HOST_MEMORY); } catch (_com_error&) { return ReportError(nullptr, CL_OUT_OF_RESOURCES); } } <|start_filename|>include/cache.hpp<|end_filename|> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include "d3d12.h" #include <memory> #include <utility> #include <wrl/client.h> class ShaderCache { public: ShaderCache(ID3D12Device*); bool HasCache() const { #ifdef __ID3D12ShaderCacheSession_INTERFACE_DEFINED__ return m_pSession; #else return false; #endif } void Store(const void* key, size_t keySize, const void* value, size_t valueSize) noexcept; void Store(const void* const* keys, const size_t* keySizes, unsigned keyParts, const void* value, size_t valueSize); using FoundValue = std::pair<std::unique_ptr<byte[]>, size_t>; FoundValue Find(const void* key, size_t keySize); FoundValue Find(const void* const* keys, const size_t* keySizes, unsigned keyParts); void Close(); #ifdef __ID3D12ShaderCacheSession_INTERFACE_DEFINED__ private: Microsoft::WRL::ComPtr<ID3D12ShaderCacheSession> m_pSession; #endif }; <|start_filename|>src/sampler.cpp<|end_filename|> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "sampler.hpp" static D3D12_SAMPLER_DESC TranslateSamplerDesc(Sampler::Desc const& desc) { D3D12_SAMPLER_DESC ret = {}; ret.AddressU = ret.AddressV = ret.AddressW = [](cl_addressing_mode mode) { switch (mode) { default: case CL_ADDRESS_CLAMP: return D3D12_TEXTURE_ADDRESS_MODE_BORDER; case CL_ADDRESS_REPEAT: return D3D12_TEXTURE_ADDRESS_MODE_WRAP; case CL_ADDRESS_MIRRORED_REPEAT: return D3D12_TEXTURE_ADDRESS_MODE_MIRROR; case CL_ADDRESS_CLAMP_TO_EDGE: return D3D12_TEXTURE_ADDRESS_MODE_CLAMP; } }(desc.AddressingMode); ret.Filter = [](cl_filter_mode mode) { switch (mode) { default: case CL_FILTER_NEAREST: return D3D12_FILTER_MIN_MAG_MIP_POINT; case CL_FILTER_LINEAR: return D3D12_FILTER_MIN_MAG_MIP_LINEAR; } }(desc.FilterMode); ret.MaxLOD = std::numeric_limits<float>::max(); return ret; } Sampler::Sampler(Context& Parent, Desc const& desc, const cl_sampler_properties *properties) : CLChildBase(Parent) , m_Desc(desc) , m_Properties(PropertiesToVector(properties)) { } D3D12TranslationLayer::Sampler& Sampler::GetUnderlying(Device* device) { std::lock_guard Lock(m_Lock); auto iter = m_UnderlyingSamplers.find(device); if (iter != m_UnderlyingSamplers.end()) return iter->second; auto ret = m_UnderlyingSamplers.try_emplace(device, &device->ImmCtx(), TranslateSamplerDesc(m_Desc)); return ret.first->second; } template <typename TReporter> bool ValidateSamplerProperties(cl_sampler_properties const* properties, TReporter&& ReportError) { constexpr cl_sampler_properties KnownProperties[] = { CL_SAMPLER_NORMALIZED_COORDS, CL_SAMPLER_ADDRESSING_MODE, CL_SAMPLER_FILTER_MODE }; bool SeenProperties[std::extent_v<decltype(KnownProperties)>] = {}; for (auto CurProp = properties; properties && *CurProp; CurProp += 2) { auto KnownPropIter = std::find(KnownProperties, std::end(KnownProperties), *CurProp); if (KnownPropIter == std::end(KnownProperties)) { return !ReportError("Unknown property.", CL_INVALID_PROPERTY); } auto PropIndex = std::distance(KnownProperties, KnownPropIter); if (SeenProperties[PropIndex]) { return !ReportError("Property specified twice.", CL_INVALID_PROPERTY); } SeenProperties[PropIndex] = true; } return true; } static cl_sampler clCreateSamplerWithPropertiesImpl(cl_context context_, const cl_sampler_properties * sampler_properties, Sampler::Desc & desc, cl_int * errcode_ret) { if (!context_) { if (errcode_ret) *errcode_ret = CL_INVALID_CONTEXT; return nullptr; } Context& context = *static_cast<Context*>(context_); auto ReportError = context.GetErrorReporter(errcode_ret); if (desc.NormalizedCoords > 1) desc.NormalizedCoords = 1; switch (desc.AddressingMode) { case CL_ADDRESS_NONE: case CL_ADDRESS_CLAMP_TO_EDGE: case CL_ADDRESS_CLAMP: case CL_ADDRESS_REPEAT: case CL_ADDRESS_MIRRORED_REPEAT: break; default: return ReportError("Invalid sampler addressing mode.", CL_INVALID_VALUE); } switch (desc.FilterMode) { case CL_FILTER_LINEAR: case CL_FILTER_NEAREST: break; default: return ReportError("Invalid sampler filter mode.", CL_INVALID_VALUE); } try { if (errcode_ret) *errcode_ret = CL_SUCCESS; return new Sampler(context, desc, sampler_properties); } catch (std::bad_alloc&) { return ReportError(nullptr, CL_OUT_OF_HOST_MEMORY); } catch (std::exception& e) { return ReportError(e.what(), CL_OUT_OF_RESOURCES); } catch (_com_error &) { return ReportError(nullptr, CL_OUT_OF_RESOURCES); } } CL_API_ENTRY cl_sampler CL_API_CALL clCreateSamplerWithProperties(cl_context context_, const cl_sampler_properties * sampler_properties, cl_int * errcode_ret) CL_API_SUFFIX__VERSION_2_0 { if (!context_) { if (errcode_ret) *errcode_ret = CL_INVALID_CONTEXT; return nullptr; } Context& context = *static_cast<Context*>(context_); auto ReportError = context.GetErrorReporter(errcode_ret); if (!ValidateSamplerProperties(sampler_properties, ReportError)) { return nullptr; } Sampler::Desc desc = { false, CL_ADDRESS_CLAMP, CL_FILTER_NEAREST }; if (auto FoundVal = FindProperty<cl_sampler_properties>(sampler_properties, CL_SAMPLER_NORMALIZED_COORDS); FoundVal) desc.NormalizedCoords = (cl_bool)*FoundVal; if (auto FoundVal = FindProperty<cl_sampler_properties>(sampler_properties, CL_SAMPLER_ADDRESSING_MODE); FoundVal) desc.AddressingMode = (cl_addressing_mode)*FoundVal; if (auto FoundVal = FindProperty<cl_sampler_properties>(sampler_properties, CL_SAMPLER_FILTER_MODE); FoundVal) desc.FilterMode = (cl_filter_mode)*FoundVal; return clCreateSamplerWithPropertiesImpl(context_, sampler_properties, desc, errcode_ret); } CL_API_ENTRY CL_API_PREFIX__VERSION_1_2_DEPRECATED cl_sampler CL_API_CALL clCreateSampler(cl_context context, cl_bool normalized_coords, cl_addressing_mode addressing_mode, cl_filter_mode filter_mode, cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2_DEPRECATED { Sampler::Desc desc = { normalized_coords, addressing_mode, filter_mode }; return clCreateSamplerWithPropertiesImpl(context, nullptr, desc, errcode_ret); } CL_API_ENTRY cl_int CL_API_CALL clRetainSampler(cl_sampler sampler) CL_API_SUFFIX__VERSION_1_0 { if (!sampler) return CL_INVALID_SAMPLER; static_cast<Sampler*>(sampler)->Retain(); return CL_SUCCESS; } CL_API_ENTRY cl_int CL_API_CALL clReleaseSampler(cl_sampler sampler) CL_API_SUFFIX__VERSION_1_0 { if (!sampler) return CL_INVALID_SAMPLER; static_cast<Sampler*>(sampler)->Release(); return CL_SUCCESS; } CL_API_ENTRY cl_int CL_API_CALL clGetSamplerInfo(cl_sampler sampler_, cl_sampler_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0 { if (!sampler_) { return CL_INVALID_SAMPLER; } Sampler& sampler = *static_cast<Sampler*>(sampler_); auto& desc = sampler.m_Desc; auto RetValue = [&](auto&& param) { return CopyOutParameter(param, param_value_size, param_value, param_value_size_ret); }; switch (param_name) { case CL_SAMPLER_REFERENCE_COUNT: return RetValue(sampler.GetRefCount()); case CL_SAMPLER_CONTEXT: return RetValue((cl_context)&sampler.m_Parent.get()); case CL_SAMPLER_NORMALIZED_COORDS: return RetValue(desc.NormalizedCoords); case CL_SAMPLER_ADDRESSING_MODE: return RetValue(desc.AddressingMode); case CL_SAMPLER_FILTER_MODE: return RetValue(desc.FilterMode); case CL_SAMPLER_PROPERTIES: return CopyOutParameterImpl(sampler.m_Properties.data(), sampler.m_Properties.size() * sizeof(sampler.m_Properties[0]), param_value_size, param_value, param_value_size_ret); } return sampler.m_Parent->GetErrorReporter()("Unknown param_name", CL_INVALID_VALUE); } <|start_filename|>include/platform.hpp<|end_filename|> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #define NOMINMAX #define CL_USE_DEPRECATED_OPENCL_1_0_APIS #define CL_USE_DEPRECATED_OPENCL_1_1_APIS #define CL_USE_DEPRECATED_OPENCL_1_2_APIS #define CL_USE_DEPRECATED_OPENCL_2_0_APIS #define CL_USE_DEPRECATED_OPENCL_2_1_APIS #define CL_USE_DEPRECATED_OPENCL_2_2_APIS #define CL_TARGET_OPENCL_VERSION 300 #include <D3D12TranslationLayerDependencyIncludes.h> #include <D3D12TranslationLayerIncludes.h> #include <CL/OpenCL.h> #include <CL/cl.h> #include <CL/cl_ext.h> #include <CL/cl_d3d10.h> #include <CL/cl_d3d11.h> #include <CL/cl_dx9_media_sharing.h> #include <CL/cl_icd.h> #include <type_traits> #include <memory> #include <vector> #include <atomic> #include <map> #include <algorithm> #ifndef assert #include <assert.h> #endif using std::min; using std::max; #include <wrl.h> using Microsoft::WRL::ComPtr; #define WIL_ENABLE_EXCEPTIONS #include <wil/result_macros.h> #include "XPlatHelpers.h" #include <Scheduler.hpp> #include <TraceLoggingProvider.h> TRACELOGGING_DECLARE_PROVIDER(g_hOpenCLOn12Provider); template <typename T> struct LifetimeLogger { LifetimeLogger() { TraceLoggingWrite(g_hOpenCLOn12Provider, "ObjectCreate", TraceLoggingString(typeid(T).name())); } ~LifetimeLogger() { TraceLoggingWrite(g_hOpenCLOn12Provider, "ObjectDestroy", TraceLoggingString(typeid(T).name())); } }; #define DEFINE_DISPATCHABLE_HANDLE(name) \ struct _##name { cl_icd_dispatch* dispatch; } DEFINE_DISPATCHABLE_HANDLE(cl_platform_id); DEFINE_DISPATCHABLE_HANDLE(cl_device_id); DEFINE_DISPATCHABLE_HANDLE(cl_context); DEFINE_DISPATCHABLE_HANDLE(cl_command_queue); DEFINE_DISPATCHABLE_HANDLE(cl_mem); DEFINE_DISPATCHABLE_HANDLE(cl_program); DEFINE_DISPATCHABLE_HANDLE(cl_kernel); DEFINE_DISPATCHABLE_HANDLE(cl_event); DEFINE_DISPATCHABLE_HANDLE(cl_sampler); template <typename TClass, typename TCLPtr> class CLBase : public std::remove_pointer_t<TCLPtr> { public: static TClass* CastFrom(TCLPtr handle) { return static_cast<TClass*>(handle); } }; struct adopt_ref {}; class Compiler; struct TaskPoolLock { std::unique_lock<std::recursive_mutex> m_Lock; }; class Device; class Platform : public CLBase<Platform, cl_platform_id> { public: static constexpr const char* Profile = "FULL_PROFILE"; #ifdef CLON12_SUPPORT_3_0 static constexpr const char* Version = "OpenCL 3.0 D3D12 Implementation"; #else static constexpr const char* Version = "OpenCL 1.2 D3D12 Implementation"; #endif static constexpr const char* Name = "OpenCLOn12"; static constexpr const char* Vendor = "Microsoft"; static constexpr const char* Extensions = "cl_khr_icd " "cl_khr_extended_versioning " "cl_khr_global_int32_base_atomics " "cl_khr_global_int32_extended_atomics " "cl_khr_local_int32_base_atomics " "cl_khr_local_int32_extended_atomics " "cl_khr_byte_addressable_store " "cl_khr_il_program "; static constexpr const char* ICDSuffix = "oclon12"; Platform(cl_icd_dispatch* dispatch); ~Platform(); cl_uint GetNumDevices() const noexcept; cl_device_id GetDevice(cl_uint i) const noexcept; Compiler *GetCompiler(); XPlatHelpers::unique_module const& GetDXIL(); void UnloadCompiler(); TaskPoolLock GetTaskPoolLock(); void FlushAllDevices(TaskPoolLock const& Lock); bool AnyD3DDevicesExist() const noexcept; void CloseCaches(); class ref_int { Platform& m_obj; public: Platform& get() const { return m_obj; } ref_int(Platform& obj, adopt_ref const& = {}) noexcept : m_obj(obj) { } ref_int(ref_int const& o) noexcept : m_obj(o.get()) { m_obj; } Platform* operator->() const { return &m_obj; } }; template <typename Fn> void QueueCallback(Fn&& fn) { struct Context { Fn m_fn; }; std::unique_ptr<Context> context(new Context{ std::forward<Fn>(fn) }); m_CallbackScheduler.QueueTask({ [](void* pContext) { std::unique_ptr<Context> context(static_cast<Context*>(pContext)); context->m_fn(); }, [](void* pContext) { delete static_cast<Context*>(pContext); }, context.get() }); context.release(); } template <typename Fn> void QueueProgramOp(Fn&& fn) { struct Context { Fn m_fn; }; std::unique_ptr<Context> context(new Context{ std::forward<Fn>(fn) }); m_CompileAndLinkScheduler.QueueTask({ [](void* pContext) { std::unique_ptr<Context> context(static_cast<Context*>(pContext)); context->m_fn(); }, [](void* pContext) { delete static_cast<Context*>(pContext); }, context.get() }); context.release(); } void DeviceInit(); void DeviceUninit(); protected: ComPtr<IDXCoreAdapterList> m_spAdapters; std::vector<std::unique_ptr<Device>> m_Devices; std::recursive_mutex m_ModuleLock; std::unique_ptr<Compiler> m_Compiler; XPlatHelpers::unique_module m_DXIL; unsigned m_ActiveDeviceCount = 0; std::recursive_mutex m_TaskLock; BackgroundTaskScheduler::Scheduler m_CallbackScheduler; BackgroundTaskScheduler::Scheduler m_CompileAndLinkScheduler; }; extern Platform* g_Platform; template <typename TClass> class ref_ptr { TClass* m_pPtr = nullptr; void Retain() noexcept { if (m_pPtr) { m_pPtr->Retain(); } } public: void Release() noexcept { if (m_pPtr) { m_pPtr->Release(); m_pPtr = nullptr; } } TClass* Detach() noexcept { auto pPtr = m_pPtr; m_pPtr = nullptr; return pPtr; } TClass* Get() const noexcept { return m_pPtr; } void Attach(TClass* p) noexcept { Release(); m_pPtr = p; } ref_ptr(TClass* p) noexcept : m_pPtr(p) { Retain(); } ref_ptr(TClass* p, adopt_ref const&) noexcept : m_pPtr(p) { } ref_ptr() noexcept = default; ref_ptr(ref_ptr const& o) noexcept : m_pPtr(o.Get()) { Retain(); } ref_ptr& operator=(ref_ptr const& o) noexcept { Release(); m_pPtr = o.m_pPtr; Retain(); return *this; } ref_ptr(ref_ptr&& o) noexcept : m_pPtr(o.Detach()) { } ref_ptr& operator=(ref_ptr &&o) noexcept { Release(); m_pPtr = o.Detach(); return *this; } ~ref_ptr() noexcept { Release(); } TClass* operator->() const { return m_pPtr; } }; template <typename TClass> class ref_ptr_int { TClass* m_pPtr = nullptr; void Retain() noexcept { if (m_pPtr) { m_pPtr->AddInternalRef(); } } public: void Release() noexcept { if (m_pPtr) { m_pPtr->ReleaseInternalRef(); m_pPtr = nullptr; } } TClass* Detach() noexcept { auto pPtr = m_pPtr; m_pPtr = nullptr; return pPtr; } TClass* Get() const noexcept { return m_pPtr; } void Attach(TClass* p) noexcept { Release(); m_pPtr = p; } ref_ptr_int(TClass* p) noexcept : m_pPtr(p) { Retain(); } ref_ptr_int(TClass* p, adopt_ref const&) noexcept : m_pPtr(p) { } ref_ptr_int() noexcept = default; ref_ptr_int(ref_ptr_int const& o) noexcept : m_pPtr(o.Get()) { Retain(); } ref_ptr_int& operator=(ref_ptr_int const& o) noexcept { Release(); m_pPtr = o.m_pPtr; Retain(); return *this; } ref_ptr_int(ref_ptr_int&& o) noexcept : m_pPtr(o.Detach()) { } ref_ptr_int& operator=(ref_ptr_int &&o) noexcept { Release(); m_pPtr = o.Detach(); return *this; } ~ref_ptr_int() noexcept { Release(); } TClass* operator->() const { return m_pPtr; } bool operator<(ref_ptr_int const& o) const { return m_pPtr < o.m_pPtr; } bool operator>(ref_ptr_int const& o) const { return m_pPtr > o.m_pPtr; } bool operator==(ref_ptr_int const& o) const { return m_pPtr == o.m_pPtr; } bool operator!=(ref_ptr_int const& o) const { return m_pPtr != o.m_pPtr; } }; template <typename TClass> class ref { TClass& m_obj; public: TClass& get() const noexcept { return m_obj; } ref(TClass& obj) noexcept : m_obj(obj) { m_obj.Retain(); } ref(TClass& obj, adopt_ref const&) noexcept : m_obj(obj) { } ref(ref const& o) noexcept : m_obj(o.get()) { m_obj.Retain(); } ~ref() noexcept { m_obj.Release(); } TClass* operator->() const { return &m_obj; } }; template <typename TClass> class ref_int { TClass& m_obj; public: TClass& get() const { return m_obj; } ref_int(TClass& obj) noexcept : m_obj(obj) { m_obj.AddInternalRef(); } ref_int(TClass& obj, adopt_ref const&) noexcept : m_obj(obj) { } ref_int(ref_int const& o) noexcept : m_obj(o.get()) { m_obj.AddInternalRef(); } ~ref_int() noexcept { m_obj.ReleaseInternalRef(); } TClass* operator->() const { return &m_obj; } }; template <typename TClass, typename TParent, typename TCLPtr> class CLChildBase : public CLBase<TClass, TCLPtr> { public: typename TParent::ref_int m_Parent; std::atomic<uint64_t> m_RefCount = 1; LifetimeLogger<TClass> m_Logger; CLChildBase(TParent& parent) : m_Parent(parent) { this->dispatch = m_Parent->dispatch; } void Retain() { ++m_RefCount; } void Release() { if (--m_RefCount == 0) delete static_cast<TClass*>(this); } void AddInternalRef() { m_RefCount += (1ull << 32); } void ReleaseInternalRef() { if ((m_RefCount -= (1ull << 32)) == 0) delete static_cast<TClass*>(this); } uint32_t GetRefCount() { return static_cast<uint32_t>(m_RefCount.load()); } using ref_ptr = ::ref_ptr<TClass>; using ref_ptr_int = ::ref_ptr_int<TClass>; using ref = ::ref<TClass>; using ref_int = ::ref_int<TClass>; }; // Helpers for property arrays as inputs template <typename TProperties> std::vector<TProperties> PropertiesToVector(const TProperties* Props) { std::vector<TProperties> Ret; if (Props == nullptr) return Ret; auto EndProp = Props; for (; *EndProp != 0; EndProp += 2); Ret.assign(Props, EndProp + 1); return Ret; } template <typename TProperties> TProperties const* FindProperty(const TProperties* Props, TProperties value) { if (Props == nullptr) return nullptr; for (auto CurProp = Props; *CurProp != 0; CurProp += 2) { if (*CurProp == value) return &CurProp[1]; } return nullptr; } // Helpers for property getters inline cl_int CopyOutParameterImpl(const void* pValue, size_t ValueSize, size_t InputValueSize, void* pOutValue, size_t* pOutValueSize) { if (InputValueSize && InputValueSize < ValueSize) { return CL_INVALID_VALUE; } if (InputValueSize) { memcpy(pOutValue, pValue, ValueSize); } if (pOutValueSize) { *pOutValueSize = ValueSize; } return CL_SUCCESS; } template <typename T> inline cl_int CopyOutParameter(T value, size_t param_value_size, void* param_value, size_t* param_value_size_ret) { return CopyOutParameterImpl(&value, sizeof(T), param_value_size, param_value, param_value_size_ret); } template <typename T, size_t size> inline cl_int CopyOutParameter(const T(&value)[size], size_t param_value_size, void* param_value, size_t* param_value_size_ret) { return CopyOutParameterImpl(&value, sizeof(value), param_value_size, param_value, param_value_size_ret); } inline cl_int CopyOutParameter(const char* value, size_t param_value_size, void* param_value, size_t* param_value_size_ret) { return CopyOutParameterImpl(value, strlen(value) + 1, param_value_size, param_value, param_value_size_ret); } inline cl_int CopyOutParameter(nullptr_t, size_t param_value_size, void* param_value, size_t *param_value_size_ret) { return CopyOutParameterImpl(nullptr, 0, param_value_size, param_value, param_value_size_ret); } inline bool IsZeroOrPow2(cl_bitfield bits) { return !bits || !(bits & (bits - 1)); } inline bool IsPow2(cl_bitfield bits) { return bits && !(bits & (bits - 1)); } void LoadFromNextToSelf(XPlatHelpers::unique_module& mod, const char* name); <|start_filename|>include/context.hpp<|end_filename|> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include "platform.hpp" #include "device.hpp" class Context : public CLChildBase<Context, Platform, cl_context> { public: using PfnCallbackType = void (CL_CALLBACK *)(const char * errinfo, const void * private_info, size_t cb, void * user_data); struct DestructorCallback { using Fn = void(CL_CALLBACK *)(cl_context, void*); Fn m_pfn; void* m_userData; }; private: std::vector<Device::ref_ptr_int> m_AssociatedDevices; const PfnCallbackType m_ErrorCallback; void* const m_CallbackContext; std::vector<cl_context_properties> const m_Properties; mutable std::mutex m_DestructorLock; std::vector<DestructorCallback> m_DestructorCallbacks; static void CL_CALLBACK DummyCallback(const char*, const void*, size_t, void*) {} friend cl_int CL_API_CALL clGetContextInfo(cl_context, cl_context_info, size_t, void*, size_t*); public: Context(Platform& Platform, std::vector<Device::ref_ptr_int> Devices, const cl_context_properties* Properties, PfnCallbackType pfnErrorCb, void* CallbackContext); ~Context(); void ReportError(const char* Error); auto GetErrorReporter(cl_int* errcode_ret) { if (errcode_ret) *errcode_ret = CL_SUCCESS; return [=](const char* ErrorMsg, cl_int ErrorCode) { if (ErrorMsg) ReportError(ErrorMsg); if (errcode_ret) *errcode_ret = ErrorCode; return nullptr; }; } auto GetErrorReporter() { return [this](const char* ErrorMsg, cl_int ErrorCode) { if (ErrorMsg) ReportError(ErrorMsg); return ErrorCode; }; } cl_uint GetDeviceCount() const noexcept; Device& GetDevice(cl_uint index) const noexcept; bool ValidDeviceForContext(Device& device) const noexcept; std::vector<Device::ref_ptr_int> GetDevices() const noexcept { return m_AssociatedDevices; } void AddDestructionCallback(DestructorCallback::Fn pfn, void* pUserData); };
microsoft/OpenCLOn12
<|start_filename|>test/WebSites/InlineConstraintsWebSite/Views/Home/Index.cshtml<|end_filename|> @{ Layout = "/Views/Shared/_Layout.cshtml"; ViewBag.Title = "Inline Constraints Home Page"; } <div> <h1>ASP.NET vNext</h1> </div>
augustoproiete-forks/aspnet--Mvc
<|start_filename|>Makefile<|end_filename|> .PHONY: all book summary clean OUTPUT:=_output MDBOOK_BIN:=${OUTPUT}/mdbook SUMMARY_MD:=${OUTPUT}/src/SUMMARY.md all: book book: ${MDBOOK_BIN} ${SUMMARY_MD} cp *.md ${OUTPUT}/src ${MDBOOK_BIN} build ${OUTPUT} ${SUMMARY_MD}: mkdir -p ${OUTPUT}/src ./generate-summary.pl > $@ ${MDBOOK_BIN}: ${OUTPUT}/mdbook.tgz tar xf $< -C ${OUTPUT} touch $@ ${OUTPUT}/mdbook.tgz: mkdir -p ${OUTPUT} curl -L https://github.com/rust-lang-nursery/mdBook/releases/download/0.0.21/mdBook-0.0.21-x86_64-unknown-linux-gnu.tar.gz -o $@ clean: rm -rf ${OUTPUT}
yidingcn/novel
<|start_filename|>Pods/Crashlytics/iOS/Crashlytics.framework/Headers/Crashlytics.h<|end_filename|> // // Crashlytics.h // Crashlytics // // Copyright (c) 2015 Crashlytics, Inc. All rights reserved. // #import <Foundation/Foundation.h> #import "CLSAttributes.h" #import "CLSLogging.h" #import "CLSReport.h" #import "CLSStackFrame.h" #import "Answers.h" NS_ASSUME_NONNULL_BEGIN @protocol CrashlyticsDelegate; /** * Crashlytics. Handles configuration and initialization of Crashlytics. * * Note: The Crashlytics class cannot be subclassed. If this is causing you pain for * testing, we suggest using either a wrapper class or a protocol extension. */ @interface Crashlytics : NSObject @property (nonatomic, readonly, copy) NSString *APIKey; @property (nonatomic, readonly, copy) NSString *version; @property (nonatomic, assign) BOOL debugMode; /** * * The delegate can be used to influence decisions on reporting and behavior, as well as reacting * to previous crashes. * * Make certain that the delegate is setup before starting Crashlytics with startWithAPIKey:... or * via +[Fabric with:...]. Failure to do will result in missing any delegate callbacks that occur * synchronously during start. * **/ @property (nonatomic, assign, nullable) id <CrashlyticsDelegate> delegate; /** * The recommended way to install Crashlytics into your application is to place a call to +startWithAPIKey: * in your -application:didFinishLaunchingWithOptions: or -applicationDidFinishLaunching: * method. * * Note: Starting with 3.0, the submission process has been significantly improved. The delay parameter * is no longer required to throttle submissions on launch, performance will be great without it. * * @param apiKey The Crashlytics API Key for this app * * @return The singleton Crashlytics instance */ + (Crashlytics *)startWithAPIKey:(NSString *)apiKey; + (Crashlytics *)startWithAPIKey:(NSString *)apiKey afterDelay:(NSTimeInterval)delay CLS_DEPRECATED("Crashlytics no longer needs or uses the delay parameter. Please use +startWithAPIKey: instead."); /** * If you need the functionality provided by the CrashlyticsDelegate protocol, you can use * these convenience methods to activate the framework and set the delegate in one call. * * @param apiKey The Crashlytics API Key for this app * @param delegate A delegate object which conforms to CrashlyticsDelegate. * * @return The singleton Crashlytics instance */ + (Crashlytics *)startWithAPIKey:(NSString *)apiKey delegate:(nullable id<CrashlyticsDelegate>)delegate; + (Crashlytics *)startWithAPIKey:(NSString *)apiKey delegate:(nullable id<CrashlyticsDelegate>)delegate afterDelay:(NSTimeInterval)delay CLS_DEPRECATED("Crashlytics no longer needs or uses the delay parameter. Please use +startWithAPIKey:delegate: instead."); /** * Access the singleton Crashlytics instance. * * @return The singleton Crashlytics instance */ + (Crashlytics *)sharedInstance; /** * The easiest way to cause a crash - great for testing! */ - (void)crash; /** * The easiest way to cause a crash with an exception - great for testing. */ - (void)throwException; /** * Specify a user identifier which will be visible in the Crashlytics UI. * * Many of our customers have requested the ability to tie crashes to specific end-users of their * application in order to facilitate responses to support requests or permit the ability to reach * out for more information. We allow you to specify up to three separate values for display within * the Crashlytics UI - but please be mindful of your end-user's privacy. * * We recommend specifying a user identifier - an arbitrary string that ties an end-user to a record * in your system. This could be a database id, hash, or other value that is meaningless to a * third-party observer but can be indexed and queried by you. * * Optionally, you may also specify the end-user's name or username, as well as email address if you * do not have a system that works well with obscured identifiers. * * Pursuant to our EULA, this data is transferred securely throughout our system and we will not * disseminate end-user data unless required to by law. That said, if you choose to provide end-user * contact information, we strongly recommend that you disclose this in your application's privacy * policy. Data privacy is of our utmost concern. * * @param identifier An arbitrary user identifier string which ties an end-user to a record in your system. */ - (void)setUserIdentifier:(nullable NSString *)identifier; /** * Specify a user name which will be visible in the Crashlytics UI. * Please be mindful of your end-user's privacy and see if setUserIdentifier: can fulfil your needs. * @see setUserIdentifier: * * @param name An end user's name. */ - (void)setUserName:(nullable NSString *)name; /** * Specify a user email which will be visible in the Crashlytics UI. * Please be mindful of your end-user's privacy and see if setUserIdentifier: can fulfil your needs. * * @see setUserIdentifier: * * @param email An end user's email address. */ - (void)setUserEmail:(nullable NSString *)email; + (void)setUserIdentifier:(nullable NSString *)identifier CLS_DEPRECATED("Please access this method via +sharedInstance"); + (void)setUserName:(nullable NSString *)name CLS_DEPRECATED("Please access this method via +sharedInstance"); + (void)setUserEmail:(nullable NSString *)email CLS_DEPRECATED("Please access this method via +sharedInstance"); /** * Set a value for a for a key to be associated with your crash data which will be visible in the Crashlytics UI. * When setting an object value, the object is converted to a string. This is typically done by calling * -[NSObject description]. * * @param value The object to be associated with the key * @param key The key with which to associate the value */ - (void)setObjectValue:(nullable id)value forKey:(NSString *)key; /** * Set an int value for a key to be associated with your crash data which will be visible in the Crashlytics UI. * * @param value The integer value to be set * @param key The key with which to associate the value */ - (void)setIntValue:(int)value forKey:(NSString *)key; /** * Set an BOOL value for a key to be associated with your crash data which will be visible in the Crashlytics UI. * * @param value The BOOL value to be set * @param key The key with which to associate the value */ - (void)setBoolValue:(BOOL)value forKey:(NSString *)key; /** * Set an float value for a key to be associated with your crash data which will be visible in the Crashlytics UI. * * @param value The float value to be set * @param key The key with which to associate the value */ - (void)setFloatValue:(float)value forKey:(NSString *)key; + (void)setObjectValue:(nullable id)value forKey:(NSString *)key CLS_DEPRECATED("Please access this method via +sharedInstance"); + (void)setIntValue:(int)value forKey:(NSString *)key CLS_DEPRECATED("Please access this method via +sharedInstance"); + (void)setBoolValue:(BOOL)value forKey:(NSString *)key CLS_DEPRECATED("Please access this method via +sharedInstance"); + (void)setFloatValue:(float)value forKey:(NSString *)key CLS_DEPRECATED("Please access this method via +sharedInstance"); /** * This method can be used to record a single exception structure in a report. This is particularly useful * when your code interacts with non-native languages like Lua, C#, or Javascript. This call can be * expensive and should only be used shortly before process termination. This API is not intended be to used * to log NSException objects. All safely-reportable NSExceptions are automatically captured by * Crashlytics. * * @param name The name of the custom exception * @param reason The reason this exception occured * @param frameArray An array of CLSStackFrame objects */ - (void)recordCustomExceptionName:(NSString *)name reason:(nullable NSString *)reason frameArray:(CLS_GENERIC_NSARRAY(CLSStackFrame *) *)frameArray; /** * * This allows you to record a non-fatal event, described by an NSError object. These events will be grouped and * displayed similarly to crashes. Keep in mind that this method can be expensive. Also, the total number of * NSErrors that can be recorded during your app's life-cycle is limited by a fixed-size circular buffer. If the * buffer is overrun, the oldest data is dropped. Errors are relayed to Crashlytics on a subsequent launch * of your application. * * You can also use the -recordError:withAdditionalUserInfo: to include additional context not represented * by the NSError instance itself. * **/ - (void)recordError:(NSError *)error; - (void)recordError:(NSError *)error withAdditionalUserInfo:(nullable CLS_GENERIC_NSDICTIONARY(NSString *, id) *)userInfo; - (void)logEvent:(NSString *)eventName CLS_DEPRECATED("Please refer to Answers +logCustomEventWithName:"); - (void)logEvent:(NSString *)eventName attributes:(nullable NSDictionary *) attributes CLS_DEPRECATED("Please refer to Answers +logCustomEventWithName:"); + (void)logEvent:(NSString *)eventName CLS_DEPRECATED("Please refer to Answers +logCustomEventWithName:"); + (void)logEvent:(NSString *)eventName attributes:(nullable NSDictionary *) attributes CLS_DEPRECATED("Please refer to Answers +logCustomEventWithName:"); @end /** * * The CrashlyticsDelegate protocol provides a mechanism for your application to take * action on events that occur in the Crashlytics crash reporting system. You can make * use of these calls by assigning an object to the Crashlytics' delegate property directly, * or through the convenience +startWithAPIKey:delegate: method. * */ @protocol CrashlyticsDelegate <NSObject> @optional - (void)crashlyticsDidDetectCrashDuringPreviousExecution:(Crashlytics *)crashlytics CLS_DEPRECATED("Please refer to -crashlyticsDidDetectReportForLastExecution:"); - (void)crashlytics:(Crashlytics *)crashlytics didDetectCrashDuringPreviousExecution:(id <CLSCrashReport>)crash CLS_DEPRECATED("Please refer to -crashlyticsDidDetectReportForLastExecution:"); /** * * Called when a Crashlytics instance has determined that the last execution of the * application ended in a crash. This is called synchronously on Crashlytics * initialization. Your delegate must invoke the completionHandler, but does not need to do so * synchronously, or even on the main thread. Invoking completionHandler with NO will cause the * detected report to be deleted and not submitted to Crashlytics. This is useful for * implementing permission prompts, or other more-complex forms of logic around submitting crashes. * * @warning Failure to invoke the completionHandler will prevent submissions from being reported. Watch out. * * @warning Just implementing this delegate method will disable all forms of synchronous report submission. This can * impact the reliability of reporting crashes very early in application launch. * * @param report The CLSReport object representing the last detected crash * @param completionHandler The completion handler to call when your logic has completed. * */ - (void)crashlyticsDidDetectReportForLastExecution:(CLSReport *)report completionHandler:(void (^)(BOOL submit))completionHandler; /** * If your app is running on an OS that supports it (OS X 10.9+, iOS 7.0+), Crashlytics will submit * most reports using out-of-process background networking operations. This results in a significant * improvement in reliability of reporting, as well as power and performance wins for your users. * If you don't want this functionality, you can disable by returning NO from this method. * * @warning Background submission is not supported for extensions on iOS or OS X. * * @param crashlytics The Crashlytics singleton instance * * @return Return NO if you don't want out-of-process background network operations. * */ - (BOOL)crashlyticsCanUseBackgroundSessions:(Crashlytics *)crashlytics; @end /** * `CrashlyticsKit` can be used as a parameter to `[Fabric with:@[CrashlyticsKit]];` in Objective-C. In Swift, use Crashlytics.sharedInstance() */ #define CrashlyticsKit [Crashlytics sharedInstance] NS_ASSUME_NONNULL_END <|start_filename|>CurrencyConverter-Bridging-Header.h<|end_filename|> // // CurrencyConverter-Bridging-Header.h // CurrencyConverter // // Created by <NAME> on 29/09/16. // Copyright © 2016 CelerStudio. All rights reserved. // #ifndef CurrencyConverter_Bridging_Header_h #define CurrencyConverter_Bridging_Header_h #endif /* CurrencyConverter_Bridging_Header_h */ <|start_filename|>Pods/Google-Mobile-Ads-SDK/Frameworks/GoogleMobileAds.framework/Versions/A/Headers/Mediation/GADMAdNetworkConnectorProtocol.h<|end_filename|> // // GADMAdNetworkConnectorProtocol.h // Google Mobile Ads SDK // // Copyright 2011 Google. All rights reserved. // #import <GoogleMobileAds/GoogleMobileAds.h> #import <UIKit/UIKit.h> #import "GADMediationAdRequest.h" @protocol GADMAdNetworkAdapter; /// Ad network adapters interact with the mediation SDK using an object that implements the /// GADMAdNetworkConnector protocol. The connector object can be used to obtain necessary /// information for ad requests, and to call back to the mediation SDK on ad request returns and /// user interactions. @protocol GADMAdNetworkConnector<GADMediationAdRequest> /// When you need to show a landing page or any other modal view, such as when a user clicks or when /// your Ads SDK needs to show an interstitial, use this method to obtain a UIViewController that /// you can use to show your modal view. Call the -presentViewController:animated:completion: method /// of the returned UIViewController . - (UIViewController *)viewControllerForPresentingModalView; #pragma mark - Adapter Callbacks /// Tells the connector that the adapter failed to receive an ad. - (void)adapter:(id<GADMAdNetworkAdapter>)adapter didFailAd:(NSError *)error; /// Tells the connector that the adapter received a banner ad. - (void)adapter:(id<GADMAdNetworkAdapter>)adapter didReceiveAdView:(UIView *)view; /// Tells the connector that the adapter received an interstitial. - (void)adapterDidReceiveInterstitial:(id<GADMAdNetworkAdapter>)adapter; /// Tells the connector that the adapter has received a mediated native ad. |mediatedNativeAd| is /// used by the Google Mobile Ads SDK for constructing a native ad object. - (void)adapter:(id<GADMAdNetworkAdapter>)adapter didReceiveMediatedNativeAd:(id<GADMediatedNativeAd>)mediatedNativeAd; #pragma mark Ad events // Adapter should call as many of these as possible, during the lifecycle of the loaded banner or // interstitial ad. /// Tells the connector that the adapter recorded a user click. - (void)adapterDidGetAdClick:(id<GADMAdNetworkAdapter>)adapter; /// Tells the connector that the adapter will leave the application because of a user action. - (void)adapterWillLeaveApplication:(id<GADMAdNetworkAdapter>)adapter; // Adapter should call as many of these as possible, during the lifecycle of the loaded banner ad. /// Tells the connector that the adapter will present a full screen modal. - (void)adapterWillPresentFullScreenModal:(id<GADMAdNetworkAdapter>)adapter; /// Tells the connector that the adapter will dismiss a full screen modal. - (void)adapterWillDismissFullScreenModal:(id<GADMAdNetworkAdapter>)adapter; /// Tells the connector that the adapter dismissed a full screen modal. - (void)adapterDidDismissFullScreenModal:(id<GADMAdNetworkAdapter>)adapter; // Adapter should call these methods during the lifecycle of the loaded interstitial ad. /// Tells the connector that the adapter will present an interstitial. - (void)adapterWillPresentInterstitial:(id<GADMAdNetworkAdapter>)adapter; /// Tells the connector that the adapter will dismiss an interstitial. - (void)adapterWillDismissInterstitial:(id<GADMAdNetworkAdapter>)adapter; /// Tells the connector that the adapter did dismiss an interstitial. - (void)adapterDidDismissInterstitial:(id<GADMAdNetworkAdapter>)adapter; #pragma mark Deprecated - (void)adapter:(id<GADMAdNetworkAdapter>)adapter didReceiveInterstitial:(NSObject *)interstitial GAD_DEPRECATED_MSG_ATTRIBUTE("Use adapterDidReceiveInterstitial:."); - (void)adapter:(id<GADMAdNetworkAdapter>)adapter clickDidOccurInBanner:(UIView *)view GAD_DEPRECATED_MSG_ATTRIBUTE("Use adapterDidGetAdClick:."); - (void)adapter:(id<GADMAdNetworkAdapter>)adapter didFailInterstitial:(NSError *)error GAD_DEPRECATED_MSG_ATTRIBUTE("Use adapter:didFailAd:"); @end
pqhuy1987/Currentconvert
<|start_filename|>src/main.cpp<|end_filename|> /****************************************************************************** * * * Copyright (C) 2018 Fondazione Istituto Italiano di Tecnologia (IIT) * * All Rights Reserved. * * * ******************************************************************************/ /** * @file main.cpp * @authors: <NAME> <<EMAIL>> */ #include <cstdlib> #include <memory> #include <mutex> #include <cmath> #include <vector> #include <set> #include <map> #include <algorithm> #include <string> #include <sstream> #include <fstream> #include <yarp/os/all.h> #include <yarp/sig/all.h> #include <yarp/math/Math.h> #include <yarp/math/Rand.h> #include <iCub/ctrl/clustering.h> #include <vtkSmartPointer.h> #include <vtkCommand.h> #include <vtkProperty.h> #include <vtkPolyDataMapper.h> #include <vtkPointData.h> #include <vtkSuperquadric.h> #include <vtkUnsignedCharArray.h> #include <vtkTransform.h> #include <vtkSampleFunction.h> #include <vtkContourFilter.h> #include <vtkActor.h> #include <vtkOrientationMarkerWidget.h> #include <vtkAxesActor.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> #include <vtkVertexGlyphFilter.h> #include <vtkCamera.h> #include <vtkInteractorStyleSwitch.h> #include "nlp.h" using namespace std; using namespace yarp::os; using namespace yarp::sig; using namespace yarp::math; using namespace iCub::ctrl; mutex mtx; /****************************************************************/ class UpdateCommand : public vtkCommand { const bool *closing; public: /****************************************************************/ vtkTypeMacro(UpdateCommand, vtkCommand); /****************************************************************/ static UpdateCommand *New() { return new UpdateCommand; } /****************************************************************/ UpdateCommand() : closing(nullptr) { } /****************************************************************/ void set_closing(const bool &closing) { this->closing=&closing; } /****************************************************************/ void Execute(vtkObject *caller, unsigned long vtkNotUsed(eventId), void *vtkNotUsed(callData)) { lock_guard<mutex> lck(mtx); vtkRenderWindowInteractor* iren=static_cast<vtkRenderWindowInteractor*>(caller); if (closing!=nullptr) { if (*closing) { iren->GetRenderWindow()->Finalize(); iren->TerminateApp(); return; } } iren->GetRenderWindow()->SetWindowName("Find Superquadric"); iren->Render(); } }; /****************************************************************/ class Object { protected: vtkSmartPointer<vtkPolyDataMapper> vtk_mapper; vtkSmartPointer<vtkActor> vtk_actor; public: /****************************************************************/ vtkSmartPointer<vtkActor> &get_actor() { return vtk_actor; } }; /****************************************************************/ class Points : public Object { protected: vtkSmartPointer<vtkPoints> vtk_points; vtkSmartPointer<vtkUnsignedCharArray> vtk_colors; vtkSmartPointer<vtkPolyData> vtk_polydata; vtkSmartPointer<vtkVertexGlyphFilter> vtk_glyphFilter; public: /****************************************************************/ Points(const vector<Vector> &points, const int point_size) { vtk_points=vtkSmartPointer<vtkPoints>::New(); for (size_t i=0; i<points.size(); i++) vtk_points->InsertNextPoint(points[i][0],points[i][1],points[i][2]); vtk_polydata=vtkSmartPointer<vtkPolyData>::New(); vtk_polydata->SetPoints(vtk_points); vtk_glyphFilter=vtkSmartPointer<vtkVertexGlyphFilter>::New(); vtk_glyphFilter->SetInputData(vtk_polydata); vtk_glyphFilter->Update(); vtk_mapper=vtkSmartPointer<vtkPolyDataMapper>::New(); vtk_mapper->SetInputConnection(vtk_glyphFilter->GetOutputPort()); vtk_actor=vtkSmartPointer<vtkActor>::New(); vtk_actor->SetMapper(vtk_mapper); vtk_actor->GetProperty()->SetPointSize(point_size); } /****************************************************************/ void set_points(const vector<Vector> &points) { vtk_points=vtkSmartPointer<vtkPoints>::New(); for (size_t i=0; i<points.size(); i++) vtk_points->InsertNextPoint(points[i][0],points[i][1],points[i][2]); vtk_polydata->SetPoints(vtk_points); } /****************************************************************/ bool set_colors(const vector<vector<unsigned char>> &colors) { if (colors.size()==vtk_points->GetNumberOfPoints()) { vtk_colors=vtkSmartPointer<vtkUnsignedCharArray>::New(); vtk_colors->SetNumberOfComponents(3); for (size_t i=0; i<colors.size(); i++) vtk_colors->InsertNextTypedTuple(colors[i].data()); vtk_polydata->GetPointData()->SetScalars(vtk_colors); return true; } else return false; } /****************************************************************/ vtkSmartPointer<vtkPolyData> &get_polydata() { return vtk_polydata; } }; /****************************************************************/ class Superquadric : public Object { protected: vtkSmartPointer<vtkSuperquadric> vtk_superquadric; vtkSmartPointer<vtkSampleFunction> vtk_sample; vtkSmartPointer<vtkContourFilter> vtk_contours; vtkSmartPointer<vtkTransform> vtk_transform; public: /****************************************************************/ Superquadric(const Vector &r, const vector<double> &color, const double opacity) { double bx=r[4]; double by=r[6]; double bz=r[5]; vtk_superquadric=vtkSmartPointer<vtkSuperquadric>::New(); vtk_superquadric->ToroidalOff(); vtk_superquadric->SetSize(1.0); vtk_superquadric->SetCenter(zeros(3).data()); vtk_superquadric->SetScale(bx,by,bz); vtk_superquadric->SetPhiRoundness(r[7]); vtk_superquadric->SetThetaRoundness(r[8]); vtk_sample=vtkSmartPointer<vtkSampleFunction>::New(); vtk_sample->SetSampleDimensions(50,50,50); vtk_sample->SetImplicitFunction(vtk_superquadric); vtk_sample->SetModelBounds(-bx,bx,-by,by,-bz,bz); // The isosurface is defined at 0.0 as specified in // https://github.com/Kitware/VTK/blob/master/Common/DataModel/vtkSuperquadric.cxx vtk_contours=vtkSmartPointer<vtkContourFilter>::New(); vtk_contours->SetInputConnection(vtk_sample->GetOutputPort()); vtk_contours->GenerateValues(1,0.0,0.0); vtk_mapper=vtkSmartPointer<vtkPolyDataMapper>::New(); vtk_mapper->SetInputConnection(vtk_contours->GetOutputPort()); vtk_mapper->ScalarVisibilityOff(); vtk_actor=vtkSmartPointer<vtkActor>::New(); vtk_actor->SetMapper(vtk_mapper); vtk_actor->GetProperty()->SetColor(color[0],color[1],color[2]); vtk_actor->GetProperty()->SetOpacity(opacity); vtk_transform=vtkSmartPointer<vtkTransform>::New(); vtk_transform->Translate(r.subVector(0,2).data()); vtk_transform->RotateZ(r[3]); vtk_transform->RotateX(-90.0); vtk_actor->SetUserTransform(vtk_transform); } /****************************************************************/ void set_parameters(const Vector &r) { // Note: roundness parameter for axes x and y is shared in SQ model, // but VTK shares axes x and z (ThetaRoundness). // To get a good display, directions of axes y and z need to be swapped // => parameters for y and z are inverted and a rotation of -90 degrees around x is added double bx=r[4]; double by=r[6]; double bz=r[5]; vtk_superquadric->SetScale(bx,by,bz); vtk_superquadric->SetPhiRoundness(r[7]); // roundness along model z axis (vtk y axis) vtk_superquadric->SetThetaRoundness(r[8]); // common roundness along model x and y axes (vtk x and z axes) vtk_sample->SetModelBounds(-bx,bx,-by,by,-bz,bz); vtk_transform->Identity(); vtk_transform->Translate(r.subVector(0,2).data()); vtk_transform->RotateZ(r[3]); // rotate around vertical vtk_transform->RotateX(-90.0); // rotate to invert y and z } }; /****************************************************************/ class Finder : public RFModule { Bottle outliersRemovalOptions; unsigned int uniform_sample; double random_sample; bool from_file; bool test_derivative; bool viewer_enabled; double inside_penalty; bool closing; class PointsProcessor : public PortReader { Finder *finder; bool read(ConnectionReader &connection) override { PointCloud<DataXYZRGBA> points; if (!points.read(connection)) return false; Bottle reply; finder->process(points,reply); if (ConnectionWriter *writer=connection.getWriter()) reply.write(*writer); return true; } public: PointsProcessor(Finder *finder_) : finder(finder_) { } } pointsProcessor; RpcServer rpcPoints,rpcService; vector<Vector> all_points,in_points,out_points,dwn_points; vector<vector<unsigned char>> all_colors; unique_ptr<Points> vtk_all_points,vtk_out_points,vtk_dwn_points; unique_ptr<Superquadric> vtk_superquadric; vtkSmartPointer<vtkRenderer> vtk_renderer; vtkSmartPointer<vtkRenderWindow> vtk_renderWindow; vtkSmartPointer<vtkRenderWindowInteractor> vtk_renderWindowInteractor; vtkSmartPointer<vtkAxesActor> vtk_axes; vtkSmartPointer<vtkOrientationMarkerWidget> vtk_widget; vtkSmartPointer<vtkCamera> vtk_camera; vtkSmartPointer<vtkInteractorStyleSwitch> vtk_style; vtkSmartPointer<UpdateCommand> vtk_updateCallback; /****************************************************************/ void removeOutliers() { double t0=Time::now(); if (outliersRemovalOptions.size()>=2) { double radius=outliersRemovalOptions.get(0).asFloat64(); int minpts=outliersRemovalOptions.get(1).asInt32(); Property options; options.put("epsilon",radius); options.put("minpts",minpts); DBSCAN dbscan; map<size_t,set<size_t>> clusters=dbscan.cluster(all_points,options); size_t largest_class; size_t largest_size=0; for (auto it=begin(clusters); it!=end(clusters); it++) { if (it->second.size()>largest_size) { largest_size=it->second.size(); largest_class=it->first; } } auto &c=clusters[largest_class]; for (size_t i=0; i<all_points.size(); i++) { if (c.find(i)==end(c)) out_points.push_back(all_points[i]); else in_points.push_back(all_points[i]); } } else in_points=all_points; double t1=Time::now(); yInfo()<<out_points.size()<<"outliers removed out of" <<all_points.size()<<"points in"<<t1-t0<<"[s]"; } /****************************************************************/ void sampleInliers() { double t0=Time::now(); if (random_sample>=1.0) { unsigned int cnt=0; for (auto &p:in_points) { if ((cnt++%uniform_sample)==0) dwn_points.push_back(p); } } else { set<unsigned int> idx; while (idx.size()<(size_t)(random_sample*in_points.size())) { unsigned int i=(unsigned int)(Rand::scalar(0.0,1.0)*in_points.size()); if (idx.find(i)==idx.end()) { dwn_points.push_back(in_points[i]); idx.insert(i); } } } double t1=Time::now(); yInfo()<<dwn_points.size()<<"samples out of" <<in_points.size()<<"inliers in"<<t1-t0<<"[s]"; } /****************************************************************/ Vector findSuperquadric() const { Ipopt::SmartPtr<Ipopt::IpoptApplication> app=new Ipopt::IpoptApplication; app->Options()->SetNumericValue("tol",1e-6); app->Options()->SetNumericValue("constr_viol_tol",1e-3); app->Options()->SetIntegerValue("acceptable_iter",0); app->Options()->SetStringValue("mu_strategy","adaptive"); app->Options()->SetIntegerValue("max_iter",1000); app->Options()->SetStringValue("hessian_approximation","limited-memory"); app->Options()->SetStringValue("derivative_test",test_derivative?"first-order":"none"); app->Options()->SetIntegerValue("print_level",test_derivative?5:0); app->Initialize(); double t0=Time::now(); Ipopt::SmartPtr<SuperQuadricNLP> nlp=new SuperQuadricNLP(dwn_points,inside_penalty); Ipopt::ApplicationReturnStatus status=app->OptimizeTNLP(GetRawPtr(nlp)); double t1=Time::now(); Vector r=nlp->get_result(); yInfo()<<"center = ("<<r.subVector(0,2).toString(3,3)<<")"; yInfo()<<"angle ="<<r[3]<<"[deg]"; yInfo()<<"size = ("<<r.subVector(4,6).toString(3,3)<<")"; yInfo()<<"shape = ("<<r.subVector(7,8).toString(3,3)<<")"; yInfo()<<"found in ="<<t1-t0<<"[s]"; return r; } /****************************************************************/ bool configure(ResourceFinder &rf) override { Rand::init(); from_file=rf.check("file"); if (from_file) { string file=rf.find("file").asString(); ifstream fin(file.c_str()); if (!fin.is_open()) { yError()<<"Unable to open file \""<<file<<"\""; return false; } Vector p(3); vector<unsigned int> c_(3); vector<unsigned char> c(3); string line; while (getline(fin,line)) { istringstream iss(line); if (!(iss>>p[0]>>p[1]>>p[2])) break; all_points.push_back(p); fill(c_.begin(),c_.end(),120); iss>>c_[0]>>c_[1]>>c_[2]; c[0]=(unsigned char)c_[0]; c[1]=(unsigned char)c_[1]; c[2]=(unsigned char)c_[2]; all_colors.push_back(c); } } else { rpcPoints.open("/find-superquadric/points:rpc"); rpcPoints.setReader(pointsProcessor); rpcService.open("/find-superquadric/service:rpc"); attach(rpcService); } if (rf.check("remove-outliers")) if (const Bottle *ptr=rf.find("remove-outliers").asList()) outliersRemovalOptions=*ptr; uniform_sample=(unsigned int)rf.check("uniform-sample",Value(1)).asInt32(); random_sample=rf.check("random-sample",Value(1.0)).asFloat64(); inside_penalty=rf.check("inside-penalty",Value(1.0)).asFloat64(); test_derivative=rf.check("test-derivative"); viewer_enabled=!rf.check("disable-viewer"); vector<double> color={0.0,0.3,0.6}; if (rf.check("color")) { if (const Bottle *ptr=rf.find("color").asList()) { size_t len=std::min(color.size(),ptr->size()); for (size_t i=0; i<len; i++) color[i]=ptr->get(i).asFloat64(); } } double opacity=rf.check("opacity",Value(0.25)).asFloat64(); vector<double> backgroundColor={0.7,0.7,0.7}; if (rf.check("background-color")) { if (const Bottle *ptr=rf.find("background-color").asList()) { size_t len=std::min(backgroundColor.size(),ptr->size()); for (size_t i=0; i<len; i++) backgroundColor[i]=ptr->get(i).asFloat64(); } } removeOutliers(); sampleInliers(); vtk_all_points=unique_ptr<Points>(new Points(all_points,2)); vtk_out_points=unique_ptr<Points>(new Points(out_points,4)); vtk_dwn_points=unique_ptr<Points>(new Points(dwn_points,1)); vtk_all_points->set_colors(all_colors); vtk_out_points->get_actor()->GetProperty()->SetColor(1.0,0.0,0.0); vtk_dwn_points->get_actor()->GetProperty()->SetColor(1.0,1.0,0.0); Vector r(9,0.0); if (dwn_points.size()>0) r=findSuperquadric(); vtk_superquadric=unique_ptr<Superquadric>(new Superquadric(r,color,opacity)); vtk_renderer=vtkSmartPointer<vtkRenderer>::New(); vtk_renderWindow=vtkSmartPointer<vtkRenderWindow>::New(); vtk_renderWindow->SetSize(600,600); vtk_renderWindow->AddRenderer(vtk_renderer); vtk_renderWindowInteractor=vtkSmartPointer<vtkRenderWindowInteractor>::New(); vtk_renderWindowInteractor->SetRenderWindow(vtk_renderWindow); vtk_renderer->AddActor(vtk_all_points->get_actor()); vtk_renderer->AddActor(vtk_out_points->get_actor()); if (dwn_points.size()!=in_points.size()) vtk_renderer->AddActor(vtk_dwn_points->get_actor()); vtk_renderer->AddActor(vtk_superquadric->get_actor()); vtk_renderer->SetBackground(backgroundColor.data()); vtk_axes=vtkSmartPointer<vtkAxesActor>::New(); vtk_widget=vtkSmartPointer<vtkOrientationMarkerWidget>::New(); vtk_widget->SetOutlineColor(0.9300,0.5700,0.1300); vtk_widget->SetOrientationMarker(vtk_axes); vtk_widget->SetInteractor(vtk_renderWindowInteractor); vtk_widget->SetViewport(0.0,0.0,0.2,0.2); vtk_widget->SetEnabled(1); vtk_widget->InteractiveOn(); vector<double> bounds(6),centroid(3); vtk_all_points->get_polydata()->GetBounds(bounds.data()); for (size_t i=0; i<centroid.size(); i++) centroid[i]=0.5*(bounds[i<<1]+bounds[(i<<1)+1]); vtk_camera=vtkSmartPointer<vtkCamera>::New(); vtk_camera->SetPosition(centroid[0]+1.0,centroid[1],centroid[2]+0.5); vtk_camera->SetFocalPoint(centroid.data()); vtk_camera->SetViewUp(0.0,0.0,1.0); vtk_renderer->SetActiveCamera(vtk_camera); vtk_style=vtkSmartPointer<vtkInteractorStyleSwitch>::New(); vtk_style->SetCurrentStyleToTrackballCamera(); vtk_renderWindowInteractor->SetInteractorStyle(vtk_style); if (viewer_enabled) { vtk_renderWindowInteractor->Initialize(); vtk_renderWindowInteractor->CreateRepeatingTimer(10); vtk_updateCallback=vtkSmartPointer<UpdateCommand>::New(); vtk_updateCallback->set_closing(closing); vtk_renderWindowInteractor->AddObserver(vtkCommand::TimerEvent,vtk_updateCallback); vtk_renderWindowInteractor->Start(); } return true; } /****************************************************************/ double getPeriod() override { return 1.0; } /****************************************************************/ bool updateModule() override { return (!from_file && !viewer_enabled); } /****************************************************************/ void process(const PointCloud<DataXYZRGBA> &points, Bottle &reply) { reply.clear(); if (points.size()>0) { lock_guard<mutex> lck(mtx); all_points.clear(); all_colors.clear(); in_points.clear(); out_points.clear(); dwn_points.clear(); Vector p(3); vector<unsigned char> c(3); for (int i=0; i<points.size(); i++) { p[0]=points(i).x; p[1]=points(i).y; p[2]=points(i).z; c[0]=points(i).r; c[1]=points(i).g; c[2]=points(i).b; all_points.push_back(p); all_colors.push_back(c); } removeOutliers(); sampleInliers(); Vector r=findSuperquadric(); vtk_all_points->set_points(all_points); vtk_all_points->set_colors(all_colors); vtk_out_points->set_points(out_points); vtk_dwn_points->set_points(dwn_points); vtk_superquadric->set_parameters(r); reply.read(r); } } /****************************************************************/ bool respond(const Bottle &command, Bottle &reply) override { lock_guard<mutex> lck(mtx); bool ok=false; if (command.check("remove-outliers")) { if (const Bottle *ptr=command.find("remove-outliers").asList()) outliersRemovalOptions=*ptr; ok=true; } if (command.check("uniform-sample")) { uniform_sample=(unsigned int)command.find("uniform-sample").asInt32(); ok=true; } if (command.check("random-sample")) { random_sample=command.find("random-sample").asFloat64(); ok=true; } if (command.check("inside-penalty")) { inside_penalty=command.find("inside-penalty").asFloat64(); ok=true; } reply.addVocab32(ok?"ack":"nack"); return true; } /****************************************************************/ bool interruptModule() override { closing=true; return true; } /****************************************************************/ bool close() override { if (rpcPoints.asPort().isOpen()) rpcPoints.close(); if (rpcService.asPort().isOpen()) rpcService.close(); return true; } public: /****************************************************************/ Finder() : closing(false), pointsProcessor(this) { } }; /****************************************************************/ int main(int argc, char *argv[]) { Network yarp; ResourceFinder rf; rf.configure(argc,argv); if (!rf.check("file")) { if (!yarp.checkNetwork()) { yError()<<"Unable to find Yarp server!"; return EXIT_FAILURE; } } Finder finder; return finder.runModule(rf); } <|start_filename|>src/nlp.cpp<|end_filename|> /****************************************************************************** * * * Copyright (C) 2018 Fondazione Istituto Italiano di Tecnologia (IIT) * * All Rights Reserved. * * * ******************************************************************************/ /** * @file nlp.cpp * @authors: <NAME> <<EMAIL>> */ #include <cmath> #include <limits> #include <yarp/math/Math.h> #include "nlp.h" using namespace std; using namespace yarp::sig; using namespace yarp::math; /****************************************************************/ bool SuperQuadricNLP::get_nlp_info(Ipopt::Index &n, Ipopt::Index &m, Ipopt::Index &nnz_jac_g, Ipopt::Index &nnz_h_lag, IndexStyleEnum &index_style) { n=9; m=1; nnz_jac_g=2; nnz_h_lag=0; index_style=TNLP::C_STYLE; return true; } /****************************************************************/ bool SuperQuadricNLP::get_bounds_info(Ipopt::Index n, Ipopt::Number *x_l, Ipopt::Number *x_u, Ipopt::Index m, Ipopt::Number *g_l, Ipopt::Number *g_u) { Vector margin(3); margin[0]=0.25*(bounds(0,1)-bounds(0,0)); margin[1]=0.25*(bounds(1,1)-bounds(1,0)); margin[2]=0.25*(bounds(2,1)-bounds(2,0)); // center x_l[0]=bounds(0,0)+margin[0]; x_u[0]=bounds(0,1)-margin[0]; x_l[1]=bounds(1,0)+margin[1]; x_u[1]=bounds(1,1)-margin[1]; x_l[2]=bounds(2,0)+margin[2]; x_u[2]=bounds(2,1)-margin[2]; // angle around z-axis x_l[3]=0.0; x_u[3]=2.0*M_PI; // size x_l[4]=0.001; x_u[4]=numeric_limits<double>::infinity(); x_l[5]=0.001; x_u[5]=numeric_limits<double>::infinity(); x_l[6]=0.001; x_u[6]=numeric_limits<double>::infinity(); // shape x_l[7]=0.1; x_u[7]=1.0; x_l[8]=0.1; x_u[8]=1.0; // limit on z-min g_l[0]=bounds(2,0); g_u[0]=numeric_limits<double>::infinity(); return true; } /****************************************************************/ bool SuperQuadricNLP::get_starting_point(Ipopt::Index n, bool init_x, Ipopt::Number *x, bool init_z, Ipopt::Number *z_L, Ipopt::Number *z_U, Ipopt::Index m, bool init_lambda, Ipopt::Number *lambda) { x[0]=centroid[0]; x[1]=centroid[1]; x[2]=centroid[2]; x[3]=0.0; x[4]=0.5*(bounds(0,1)-bounds(0,0)); x[5]=0.5*(bounds(1,1)-bounds(1,0)); x[6]=0.5*(bounds(2,1)-bounds(2,0)); x[7]=1.0; x[8]=1.0; return true; } /****************************************************************/ bool SuperQuadricNLP::eval_f(Ipopt::Index n, const Ipopt::Number *x, bool new_x, Ipopt::Number &obj_value) { Vector c(3),s(3); c[0]=x[0]; c[1]=x[1]; c[2]=x[2]; const double &a=x[3]; s[0]=x[4]; s[1]=x[5]; s[2]=x[6]; const double &e1=x[7]; const double &e2=x[8]; Vector rot(4,0.0); rot[2]=1.0; rot[3]=a; Matrix T=axis2dcm(rot); T.setSubcol(c,0,3); T=SE3inv(T); obj_value=0.0; Vector p1(4,1.0); for (auto &p:points) { p1.setSubvector(0,p); p1=T*p1; double tx=pow(abs(p1[0]/s[0]),2.0/e2); double ty=pow(abs(p1[1]/s[1]),2.0/e2); double tz=pow(abs(p1[2]/s[2]),2.0/e1); double F1=pow(pow(tx+ty,e2/e1)+tz,e1)-1.0; double penalty=(F1<0.0?inside_penalty:1.0); obj_value+=F1*F1*penalty; } obj_value*=(s[0]*s[1]*s[2])/points.size(); return true; } /****************************************************************/ bool SuperQuadricNLP::eval_grad_f(Ipopt::Index n, const Ipopt::Number *x, bool new_x, Ipopt::Number *grad_f) { Vector c(3),s(3); c[0]=x[0]; c[1]=x[1]; c[2]=x[2]; const double &a=x[3]; s[0]=x[4]; s[1]=x[5]; s[2]=x[6]; const double &e1=x[7]; const double &e2=x[8]; Vector rot(4,0.0); rot[2]=1.0; rot[3]=a; Matrix T=axis2dcm(rot); T.setSubcol(c,0,3); T=SE3inv(T); for (Ipopt::Index i=0; i<n; i++) grad_f[i]=0.0; double coeff=s[0]*s[1]*s[2]; Vector p1(4,1.0); for (auto &p:points) { p1.setSubvector(0,p); p1=T*p1; double tx=pow(abs(p1[0]/s[0]),2.0/e2); double ty=pow(abs(p1[1]/s[1]),2.0/e2); double tz=pow(abs(p1[2]/s[2]),2.0/e1); double F1=pow(pow(tx+ty,e2/e1)+tz,e1)-1.0; double penalty=(F1<0.0?inside_penalty:1.0); double tmp1=2.0*coeff*F1*penalty; double tmp2=F1*F1*penalty; double t11=cos(a)*(c[0]-p[0])+sin(a)*(c[1]-p[1]); double t10=cos(a)*(c[1]-p[1])-sin(a)*(c[0]-p[0]); double t9=pow(abs(t11)/s[0],2.0/e2); double t8=pow(abs(t10)/s[1],2.0/e2); double t7=abs(c[2]-p[2])/s[2]; double t6=pow(t9+t8,e2/e1); double t5=pow(t7,2.0/e1-1.0); double t4=pow(abs(t11)/s[0],2.0/e2-1.0); double t3=pow(abs(t10)/s[1],2.0/e2-1.0); double t2=pow(t7,2.0/e1)+t6; double t1=pow(t9+t8,e2/e1-1.0); double t0=pow(t2,e1-1.0); grad_f[0]+=tmp1 * (-t1*t0*2.0*((sign(t10)*sin(a)*t3)/s[1]-(sign(t11)*cos(a)*t4)/s[0])); grad_f[1]+=tmp1 * (t1*t0*2.0*((sign(t11)*sin(a)*t4)/s[0]+(sign(t10)*cos(a)*t3)/s[1])); grad_f[2]+=tmp1 * ((sign(c[2]-p[2])*t0*t5*2.0)/s[2]); grad_f[3]+=tmp1 * (2.0*t1*t0*((sign(t11)*t4*t10)/s[0]-(sign(t10)*t3*t11)/s[1])); grad_f[4]+=tmp1 * (-(abs(t11)*t0*t4*t1*2.0)/(s[0]*s[0])) + tmp2 * s[1]*s[2]; grad_f[5]+=tmp1 * (-(abs(t10)*t0*t3*t1*2.0)/(s[1]*s[1])) + tmp2 * s[0]*s[2]; grad_f[6]+=tmp1 * (-(abs(c[2]-p[2])*t0*t5*2.0)/(s[2]*s[2])) + tmp2 * s[0]*s[1]; grad_f[7]+=tmp1 * ((log(t2)*pow(t2,e1)-t0*(log(t7)*pow(t7,2.0/e1)*2.0+e2*log(t9+t8)*t6)/e1)); grad_f[8]+=tmp1 * (t0*(log(t9+t8)*t6-2.0*t1*(log(abs(t11)/s[0])*t9+log(abs(t10)/s[1])*t8)/e2)); } for (Ipopt::Index i=0; i<n; i++) grad_f[i]/=points.size(); return true; } /****************************************************************/ bool SuperQuadricNLP::eval_g(Ipopt::Index n, const Ipopt::Number *x, bool new_x, Ipopt::Index m, Ipopt::Number *g) { g[0]=x[2]-x[6]; return true; } /****************************************************************/ bool SuperQuadricNLP::eval_jac_g(Ipopt::Index n, const Ipopt::Number *x, bool new_x, Ipopt::Index m, Ipopt::Index nele_jac, Ipopt::Index *iRow, Ipopt::Index *jCol, Ipopt::Number *values) { if (values==nullptr) { iRow[0]=0; jCol[0]=2; iRow[1]=0; jCol[1]=6; } else { values[0]=1.0; values[1]=-1.0; } return true; } /****************************************************************/ bool SuperQuadricNLP::eval_h(Ipopt::Index n, const Ipopt::Number *x, bool new_x, Ipopt::Number obj_factor, Ipopt::Index m, const Ipopt::Number *lambda, bool new_lambda, Ipopt::Index nele_hess, Ipopt::Index *iRow, Ipopt::Index *jCol, Ipopt::Number *values) { return true; } /****************************************************************/ void SuperQuadricNLP::finalize_solution(Ipopt::SolverReturn status, Ipopt::Index n, const Ipopt::Number *x, const Ipopt::Number *z_L, const Ipopt::Number *z_U, Ipopt::Index m, const Ipopt::Number *g, const Ipopt::Number *lambda, Ipopt::Number obj_value, const Ipopt::IpoptData *ip_data, Ipopt::IpoptCalculatedQuantities *ip_cq) { result.resize(n); for (Ipopt::Index i=0; i<n; i++) result[i]=x[i]; result[3]*=180.0/M_PI; } /****************************************************************/ SuperQuadricNLP::SuperQuadricNLP(const vector<Vector> &points_, const double inside_penalty_) : points(points_), inside_penalty(inside_penalty_) { bounds.resize(3,2); bounds(0,0)=bounds(1,0)=bounds(2,0)=numeric_limits<double>::infinity(); bounds(0,1)=bounds(1,1)=bounds(2,1)=-numeric_limits<double>::infinity(); for (auto &p:points) { if (p[0]<bounds(0,0)) bounds(0,0)=p[0]; if (p[0]>bounds(0,1)) bounds(0,1)=p[0]; if (p[1]<bounds(1,0)) bounds(1,0)=p[1]; if (p[1]>bounds(1,1)) bounds(1,1)=p[1]; if (p[2]<bounds(2,0)) bounds(2,0)=p[2]; if (p[2]>bounds(2,1)) bounds(2,1)=p[2]; } centroid.resize(3,0.0); for (unsigned int i=0; i<centroid.length(); i++) centroid[i]=0.5*(bounds(i,0)+bounds(i,1)); } /****************************************************************/ Vector SuperQuadricNLP::get_result() const { return result; } <|start_filename|>src/nlp.h<|end_filename|> /****************************************************************************** * * * Copyright (C) 2018 Fondazione Istituto Italiano di Tecnologia (IIT) * * All Rights Reserved. * * * ******************************************************************************/ /** * @file nlp.h * @authors: <NAME> <<EMAIL>> */ #ifndef NLP_H #define NLP_H #include <vector> #include <IpTNLP.hpp> #include <IpIpoptApplication.hpp> #include <yarp/sig/Vector.h> #include <yarp/sig/Matrix.h> /****************************************************************/ class SuperQuadricNLP : public Ipopt::TNLP { protected: const std::vector<yarp::sig::Vector> &points; double inside_penalty; yarp::sig::Vector centroid; yarp::sig::Matrix bounds; yarp::sig::Vector result; /****************************************************************/ bool get_nlp_info(Ipopt::Index &n, Ipopt::Index &m, Ipopt::Index &nnz_jac_g, Ipopt::Index &nnz_h_lag, IndexStyleEnum &index_style) override; /****************************************************************/ bool get_bounds_info(Ipopt::Index n, Ipopt::Number *x_l, Ipopt::Number *x_u, Ipopt::Index m, Ipopt::Number *g_l, Ipopt::Number *g_u) override; /****************************************************************/ bool get_starting_point(Ipopt::Index n, bool init_x, Ipopt::Number *x, bool init_z, Ipopt::Number *z_L, Ipopt::Number *z_U, Ipopt::Index m, bool init_lambda, Ipopt::Number *lambda) override; /****************************************************************/ bool eval_f(Ipopt::Index n, const Ipopt::Number *x, bool new_x, Ipopt::Number &obj_value) override; /****************************************************************/ bool eval_grad_f(Ipopt::Index n, const Ipopt::Number *x, bool new_x, Ipopt::Number *grad_f) override; /****************************************************************/ bool eval_g(Ipopt::Index n, const Ipopt::Number *x, bool new_x, Ipopt::Index m, Ipopt::Number *g) override; /****************************************************************/ bool eval_jac_g(Ipopt::Index n, const Ipopt::Number *x, bool new_x, Ipopt::Index m, Ipopt::Index nele_jac, Ipopt::Index *iRow, Ipopt::Index *jCol, Ipopt::Number *values) override; /****************************************************************/ bool eval_h(Ipopt::Index n, const Ipopt::Number *x, bool new_x, Ipopt::Number obj_factor, Ipopt::Index m, const Ipopt::Number *lambda, bool new_lambda, Ipopt::Index nele_hess, Ipopt::Index *iRow, Ipopt::Index *jCol, Ipopt::Number *values) override; /****************************************************************/ void finalize_solution(Ipopt::SolverReturn status, Ipopt::Index n, const Ipopt::Number *x, const Ipopt::Number *z_L, const Ipopt::Number *z_U, Ipopt::Index m, const Ipopt::Number *g, const Ipopt::Number *lambda, Ipopt::Number obj_value, const Ipopt::IpoptData *ip_data, Ipopt::IpoptCalculatedQuantities *ip_cq) override; public: /****************************************************************/ SuperQuadricNLP(const std::vector<yarp::sig::Vector> &points_, const double inside_penalty_); /****************************************************************/ yarp::sig::Vector get_result() const; }; #endif
pattacini/find-superquadric
<|start_filename|>vendor/github.com/splace/joysticks/modifiers.go<|end_filename|> package joysticks import ( "time" //"fmt" ) // TODO drag event // TODO move plus edge continue events (self generating) // TODO smoother from PID // TODO two pans to a coord // TODO coords to two pans // TODO 1-d integrator var DefaultRepeat = time.Second /4 var VelocityRepeat = time.Second / 10 // duplicate event onto two chan's func Duplicator(c chan Event)(chan Event,chan Event){ c1 := make(chan Event) c2 := make(chan Event) go func(){ for e:=range c{ c1 <- e c2 <- e } close(c1) close(c2) }() return c1,c2 } // creates a chan on which you get CoordsEvent's that are the time integration of the CoordsEvent's on the parameter chan. func PositionFromVelocity(c chan Event) chan Event{ extra := make(chan Event) var x,y,vx,vy float32 var startTime time.Time var startMoment time.Duration var m time.Duration var lt time.Time ticker:=time.NewTicker(VelocityRepeat) // receiving chan processor go func(){ e:= <-c startTime=time.Now() startMoment=e.Moment() lm:=startMoment for e:=range c{ if ce,ok:=e.(CoordsEvent);ok{ lt=time.Now() m=e.Moment() dt:=float32((m-lm).Seconds()) x+=vx*dt y+=vy*dt vx,vy=ce.X,ce.Y lm= m } } ticker.Stop() }() // output chan processor go func(){ var lx,ly,nx,ny,dt float32 for t:=range ticker.C{ dt=float32(t.Sub(lt).Seconds()) nx,ny=x+dt*vx,y+dt*vy if nx!=lx || ny!=ly { extra <-CoordsEvent{when{startMoment+t.Sub(startTime)},nx,ny} lx,ly=nx,ny } } }() return extra } // creates a channel that, after receiving any event on the first parameter chan, and until any event on second chan parameter, regularly receives 'when' events. // the repeat interval is DefaultRepeat, and is stored, so retriggering is not effected by changing DefaultRepeat. func Repeater(c1,c2 chan Event)(chan Event){ c := make(chan Event) go func(){ interval:=DefaultRepeat var ticker *time.Ticker for { e:= <-c1 go func(interval time.Duration, startTime time.Time){ ticker=time.NewTicker(interval) for t:=range ticker.C{ c <- when{e.Moment()+t.Sub(startTime)} } }(interval, time.Now()) <-c2 ticker.Stop() } }() return c }
rpoisel/AbbB23Energymeter
<|start_filename|>vuedemo-maoyan03/src/api/base.js<|end_filename|> import axios from 'axios' import { PATH } from './config' export class BaseApi { constructor() { this.hanlder = axios.create() this.hanlder.defaults.baseURL = PATH.maoyanPath } _transfromResponse(res) { const { data, status } = res if (status === 200) { return data } return res } get(url, config = {}) { const params = config.params || {} config = { ...config, params: { token: '', optimus_uuid: 'D5270AD0BD1511EA97EEB3F29AAFC0985406D52C78BB4E3A9378934129A15D03', optimus_risk_level: 71, optimus_code: 10, ...params } } return this.hanlder.get(url, config).then(this._transfromResponse) } post(url, data, config) { return this.handler.post(url, data, config).then(this._transfromResponse) } } <|start_filename|>vuedemo-maoyan02/src/api/config.js<|end_filename|> const URL = { baseUrl: 'http://www.softeem.xin', maoyanUrl: 'http://m.maoyan.com' } export const PATH = { basePath: '/maoyanApi/ajax', maoyanPath: '/ajax', citiesPath: '/dianying' } export default { base: URL.baseUrl + PATH.basePath, maoyan: URL.maoyanUrl + PATH.maoyanPath } <|start_filename|>vuedemo-maoyan04/src/main.js<|end_filename|> // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import store from './store' import Api from './api' Vue.prototype.$api = Api import pageTitle from './components/pageTitle' import pageFooter from './components/pageFooter' import loading from './layout/loading' import icon from './layout/icon' // 注册全局组件 Vue.component('pageTitle',pageTitle) Vue.component('pageFooter',pageFooter) Vue.component('loading',loading) Vue.component('icon',icon) // 图片懒加载 import VueLazyload from 'vue-lazyload' import errorImg from '../src/assets/img/error.png' import loadingImg from '../src/assets/img/loading.gif' // 加载图片懒加载插件 Vue.use(VueLazyload,{ error: errorImg, loading: loadingImg }) // 在生产环境下把注释全部去掉 Vue.config.productionTip = false // 是否启动代码检查,不要删除 /* eslint-disable no-new */ new Vue({ el: '#app', router, store, components: { App }, template: '<App/>' }) <|start_filename|>vuedemo-maoyan02/src/api/index.js<|end_filename|> import {BaseApi} from './base' class API extends BaseApi { getMovieOnInfoList() { return this.get('/movieOnInfoList') } getMostExpected() { return this.get('/mostExpected') } getComingList() { return this.get('/comingList') } getDetailMovie(params) { return this.get('/detailmovie', { params }) } getMoreList(params) { return this.get('/moreComingList', { params }) } getCities() { return this.get('/cities.json', { baseURL: '/dianying' }) } getCinemaList(params) { return this.get('/cinemaList', { params }) } search(params) { return this.get('/search', { params }) } filterCinemas(params) { return this.get('/filterCinemas', { params }) } } export default new API() <|start_filename|>vuedemo-maoyan03/src/assets/css/movie-list.css<|end_filename|> .movie-list{ width: 100%; padding: 5px 12px; } .movie-img>img{ height: 90px; width: 64px; float: left; margin-right: 8px; } .right-info{ display: flex; flex-direction: row; justify-content: space-between; align-items: center; border-bottom: 1px solid #ededed; padding: 0px 10px 5px 3px; } .right-info>ul{ width: calc(100% - 56px); display: flex; flex-direction: column; justify-content: space-between; align-items: left; padding: 5px 0px; font-size: 13px; color: #666; } .right-info>ul>li{ overflow: hidden; white-space: nowrap; text-overflow: ellipsis; margin-bottom: 3px; } .movie-info .name{ font-size: 16px; font-weight: bold; color: #000; } .movie-info .score>span{ font-weight: bold; font-size: 14px; color: #faaf00; } .btn>button{ width: 48px; padding: 5px 12px; border: none; border-radius: 5px; font-size: 12px; } .btn>.buy-btn{ background-color: #f03d37; color: #fff; } .btn>.pre-btn{ background-color: #3c9fe6; color: #fff; } <|start_filename|>vuedemo-maoyan03/src/main.js<|end_filename|> // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import Api from './api' Vue.prototype.$api = Api import pageTitle from './components/pageTitle' import loading from './layout/loading' // 注册全局组件 Vue.component('pageTitle',pageTitle) Vue.component('loading',loading) // 图片懒加载 import VueLazyload from 'vue-lazyload' import errorImg from '../src/assets/img/error.png' import loadingImg from '../src/assets/img/loading.gif' // 加载图片懒加载插件 Vue.use(VueLazyload,{ error: errorImg, loading: loadingImg }) // 在生产环境下把注释全部去掉 Vue.config.productionTip = false // 是否启动代码检查,不要删除 /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>' }) <|start_filename|>vuedemo-maoyan04/src/store/index.js<|end_filename|> import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { isLogin: 0, userNick: '', defaultHeadImg: 'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2363028509,190015165&fm=26&gp=0.jpg', userHeadImg: this.defaultHeadImg, // 模拟数据库用户信息 testInfo: [ { account: 'bjpengyuyan', password: '<PASSWORD>', userNick: '滨江彭于晏', userHeadImg: 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3279316276,2228302562&fm=26&gp=0.jpg', likeList: ['健身', '台球'] } ] }, getters: { testUserInfo: state => account => { let userinfoIndex = state.testInfo.findIndex(info => info.account === account) return userinfoIndex === -1 ? undefined : state.testInfo[userinfoIndex] } }, mutations: { loginOut(state) { state.isLogin = 0 state.userNick = '' state.userHeadImg = state.defaultHeadImg }, loginIn(state, payload) { state.isLogin = 1 state.userNick = payload.userNick state.userHeadImg = payload.userHeadImg || state.defaultHeadImg }, register: (state, payload) => state.testInfo.push(payload) } })
ahh666/vueDemo-maoyan
<|start_filename|>docs/make.bat<|end_filename|> @ECHO OFF pushd %~dp0 REM Command file for Sphinx documentation set PROJECT_DIR=snakeplane set PROJECT_NAME=snakeplane sphinx-build >NUL 2>NUL if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed. exit /b 1 ) if "%1" == "" ( goto help ) else if "%1" == "help" ( goto help ) else if "%1" == "clean" ( goto clean ) else if "%1" == "pdf" ( goto pdf ) else if "%1" == "html" ( goto html ) else if "%1" == "latex" ( goto latex ) else ( echo.Error: Invalid parameter %1 goto help ) :help echo.Usage: make "[help | html | latex | pdf | clean]" goto end :clean rmdir /s /q _build goto end :html :latex sphinx-apidoc -f -o source ../%PROJECT_DIR% sphinx-build -b %1 -c source source _build/%1 goto end :pdf sphinx-apidoc -f -o source ../%PROJECT_DIR% sphinx-build -b latex -c source source _build/latex pdflatex -output-directory=_build\pdf -include-directory=_build\latex _build\latex\%PROJECT_NAME%.tex goto end :end popd <|start_filename|>docs/Makefile<|end_filename|> # Makefile for Sphinx documentation clean: rm -rf _build %: Makefile sphinx-apidoc -f -o source ../snakeplane sphinx-build -b $@ -c . source _build/html <|start_filename|>pilot/env/setup_environ.bat<|end_filename|> set path=%~dp0 set cmdStr="C:\Program Files\Alteryx\bin\Miniconda3\python.exe" env\setup_environ.py %cmdStr%
cpitts1/snakeplane
<|start_filename|>src/h5psd.js<|end_filename|> /*<jdists encoding="ejs" data="../package.json">*/ /** * @file <%- name %> * * <%- description %> * @author <% (author instanceof Array ? author : [author]).forEach(function (item) { %> * <%- item.name %> (<%- item.url %>) <% }); %> * @version <%- version %> <% var now = new Date() %> * @date <%- [ now.getFullYear(), now.getMonth() + 101, now.getDate() + 100 ].join('-').replace(/-1/g, '-') %> */ /*</jdists>*/ var fs = require('fs'); var mkdirp = require('mkdirp'); var path = require('path'); var colors = require('colors/safe'); var crypto = require('crypto'); var psd = require('psd'); var jdists = require('jdists'); var url = require('url'); /** * 将 RGBA 转换成颜色表达式 * * @param {Array[4]} value rgba 值 * @return {string} 返回颜色表达式 */ function rgba2color(value) { if (value[3] === 255) { return '#' + value.slice(0, -1).map(function (value) { return (0x100 + parseInt(value)).toString(16).slice(1); }).join('').replace(/(.)\1(.)\2(.)\3/, '$1$2$3'); } else { return 'rgba(' + value.join() + ')'; } } /** * 编译 h5psd 文件 * * @param {string} filename 文件名或者是内容 * @param {Object} argv 配置项 * @param {boolean} argv.output 输出目录,如果没有指定则和为输入目录 */ function build(filename, argv) { filename = path.resolve('', filename || ''); if (!fs.existsSync(filename)) { console.warn( colors.blue('PSD file "%s" not exists.'), filename ); return; } template = argv.template || path.join(__dirname, '../tpl/page.html'); if (!fs.existsSync(template)) { console.warn( colors.blue('Template file "%s" not exists.'), template ); return; } // 处理默认值 argv = argv || {}; var output = argv.output || path.dirname(filename); var images = argv.images || 'images'; return psd.open(filename).then(function (context) { mkdirp.sync(path.join(output, images)); // 确保输出目录存在 var tree = context.tree(); var treeInfo = tree.export(); var h5 = { name: path.basename(filename), width: treeInfo.document.width, height: treeInfo.document.height, layers: [] }; // var promise = []; var layers = h5.layers; var md5dict = {}; var promises = []; var descendants = tree.descendants(); descendants.forEach(function (node, index) { if (node.isGroup() || node.hidden()) { return true; } var nodeInfo = node.export(); if (nodeInfo.width <= 0 || nodeInfo.height <= 0) { // 无效数据 return; } // 计算 MD5 戳 var buffer = new Buffer(node.toPng().data); var isBackground; var backgroundColor; if (index === descendants.length - 1 && nodeInfo.left === 0 && nodeInfo.top === 0 && nodeInfo.width === h5.width && nodeInfo.height === h5.height) { // 可能是背景 var lastRgba = [buffer[0], buffer[1], buffer[2], buffer[3]]; var fit = true; for (var i = 4; i < buffer.length; i += 4) { var currRgba = [buffer[i + 0], buffer[i + 1], buffer[i + 2], buffer[i + 3]]; if (Math.abs(currRgba[0] - lastRgba[0]) > 5 || Math.abs(currRgba[1] - lastRgba[1]) > 5 || Math.abs(currRgba[2] - lastRgba[2]) > 5 || Math.abs(currRgba[3] - lastRgba[3]) > 5 ) { fit = false; break; } lastRgba = currRgba; } isBackground = true; if (fit) { backgroundColor = rgba2color(lastRgba); } } var image; if (!backgroundColor) { var md5 = crypto.createHash('md5'); md5.update(buffer); var flag = md5.digest('hex'); image = path.join(images, flag.slice(1, 7) + '.png'); if (!md5dict[flag]) { // 内容没有出现过 md5dict[flag] = true; if (!nodeInfo.text) { // 非文本节点 var imageOutput = path.join(output, image); var exists = fs.existsSync(imageOutput); promises.push(node.saveAsPng(imageOutput).then(function () { if (exists) { console.warn( colors.blue('File %j overwrite.'), imageOutput ); } console.log(colors.green('Image %j output complete.'), imageOutput); })); } } } if (image) { image = url.format(image); // @see issues#1 处理 Windows 路径分隔符 } if (isBackground) { h5.background = { name: nodeInfo.name, color: backgroundColor, image: image, opacity: nodeInfo.opacity, text: nodeInfo.text }; } else { layers.unshift({ name: nodeInfo.name, image: image, left: nodeInfo.left, top: nodeInfo.top, width: nodeInfo.width, height: nodeInfo.height, opacity: nodeInfo.opacity, text: nodeInfo.text }); } }); if (argv.layer) { var layer = path.basename(filename, path.extname(filename)) + '.layer'; fs.writeFileSync(path.join(output, layer), JSON.stringify(h5, null, ' ')); } return Promise.all(promises).then(function () { var page = path.join(output, path.basename(filename, path.extname(filename)) + '.html'); fs.writeFileSync(page, jdists.build(template, { output: page }, function (scope) { scope.setVariant('context', { h5: h5, enableName: argv.name, output: path.resolve('', output) }); }) ); console.log(colors.green('Page %j output complete.'), page); }); }).catch(function (err) { console.log(colors.red(err.stack)); }); } exports.build = build; <|start_filename|>example/css/base.css<|end_filename|> html, body { width: 414px; max-height: 736px; height: 100%; margin: 0 auto; padding: 0; background-color: #fff; overflow: hidden; font-family: STHeiTi, Tahoma, Helvetica, Arial, sans-serif; } html { background-color: #ddd; } h1, h2, h3, h4, h5, h6, article, section, div, p { margin: 0; padding: 0; } .container { width: 100%; height: 100%; min-height: 500px; position: relative; overflow: visible; } .page { width: 100%; height: 100%; position: relative; background-size: cover !important; overflow: hidden; } .layer { position: absolute; z-index: 1; } <|start_filename|>test/page1.js<|end_filename|> var h5psd = require('../.'); var assert = require('should'); var fs = require('fs'); var util = require('util'); var path = require('path'); var rimraf = require('rimraf'); describe('coverage', function () { var output = 'test/page1'; it('psd/404.psd', function () { h5psd.build('test/psd/404.psd', { output: output }); }); it('$ h5psd psd/m1.psd -l -o ' + output, function (done) { h5psd.build('test/psd/m1.psd', { output: output, layer: true, title: true }).then(function () { assert.ok(fs.existsSync(path.join(output, 'm1.layer'))); assert.ok(fs.existsSync(path.join(output, 'm1.html'))); assert.ok(fs.existsSync(path.join(output, 'images/657d39.png'))); assert.ok(fs.existsSync(path.join(output, 'css/base.css'))); rimraf.sync(output); done(); }).catch(function () { console.log('error.'); rimraf.sync(output); done(); }); }); }); <|start_filename|>cli.js<|end_filename|> #!/usr/bin/env node 'use strict'; var h5psd = require('./'); var optimist = require('optimist'); var fs = require('fs'); var path = require('path'); var util = require('util'); var colors = require('colors'); var argv = optimist .usage('$0 <input.psd> [-o output] [-s img]') .alias('h', 'help') .describe('h', 'Show this help message and exit.') .string('h') .alias('o', 'output') .describe('o', 'Output directory.') .string('o') .alias('s', 'images') .describe('s', 'Images directory.') .string('s') .default('images') .alias('l', 'layer') .describe('l', 'Export "<name>.layer.json" file.') .boolean('l') .default(false) .alias('n', 'name') .describe('n', 'Enable the "name" attribute (default false).') .boolean('n') .default(false) .alias('t', 'template') .describe('t', 'Page jdists template file.') .string('t') .alias('v', 'version') .describe('v', 'Print version number and exit.') .wrap(80) .argv; if (argv._.length < 1) { if (argv.version) { var json = require('./package.json'); console.log(json.name + ' ' + json.version); return; } console.log( String(function () { /* Usage: #{h5,yellow}#{psd,blue} <input list> [options] Options: #{-v, --version,cyan} Output h5psd version. #{-o, --output,cyan} Output directory (default input directory). #{-s, --images,cyan} Images directory (default "images"). #{-l, --layer,cyan} Export "<name>.layer" file (default false). #{-n, --name,cyan} Enable the "name" attribute (default false). #{-t, --template,cyan} Page jdists template file. */ }) .replace(/[^]*\/\*!?\s*|\s*\*\/[^]*/g, '') .replace(/#\{(.*?),(\w+)\}/g, function (all, text, color) { return colors[color](text); }) ); return; } argv._.forEach(function (filename) { h5psd.build(filename, argv); }); <|start_filename|>index.js<|end_filename|> module.exports = require('./lib/h5psd.js');
zswang/h5psd
<|start_filename|>minimist_tests/stop_early.js<|end_filename|> var parse = require('../'); var test = require('tape'); test('stops parsing on the first non-option when stopEarly is set', function (t) { var argv = parse(['--aaa', 'bbb', 'ccc', '--ddd'], { stopEarly: true }); t.deepEqual(argv, { aaa: 'bbb', _: ['ccc', '--ddd'] }); t.end(); }); <|start_filename|>minimist_tests/num.js<|end_filename|> var parse = require('../'); var test = require('tape'); test('nums', function (t) { var argv = parse([ '-x', '1234', '-y', '5.67', '-z', '1e7', '-w', '10f', '--hex', '0xdeadbeef', '789' ]); t.deepEqual(argv, { x : 1234, y : 5.67, z : 1e7, w : '10f', hex : 0xdeadbeef, _ : [ 789 ] }); t.deepEqual(typeof argv.x, 'number'); t.deepEqual(typeof argv.y, 'number'); t.deepEqual(typeof argv.z, 'number'); t.deepEqual(typeof argv.w, 'string'); t.deepEqual(typeof argv.hex, 'number'); t.deepEqual(typeof argv._[0], 'number'); t.end(); }); test('already a number', function (t) { var argv = parse([ '-x', 1234, 789 ]); t.deepEqual(argv, { x : 1234, _ : [ 789 ] }); t.deepEqual(typeof argv.x, 'number'); t.deepEqual(typeof argv._[0], 'number'); t.end(); }); <|start_filename|>example/parse.js<|end_filename|> var argv = require('minimist2')(process.argv.slice(2)); console.dir(argv);
unional/minimist2
<|start_filename|>Dockerfile<|end_filename|> ############################# # 设置公共的变量 # ############################# ARG BASE_IMAGE_TAG=20.04 FROM ubuntu:${BASE_IMAGE_TAG} # 作者描述信息 MAINTAINER danxiaonuo # 时区设置 ARG TZ=Asia/Shanghai ENV TZ=$TZ # 语言设置 ARG LANG=en_US.UTF-8 ENV LANG=$LANG # 镜像变量 ARG DOCKER_IMAGE=danxiaonuo/mysql ENV DOCKER_IMAGE=$DOCKER_IMAGE ARG DOCKER_IMAGE_OS=ubuntu ENV DOCKER_IMAGE_OS=$DOCKER_IMAGE_OS ARG DOCKER_IMAGE_TAG=20.04 ENV DOCKER_IMAGE_TAG=$DOCKER_IMAGE_TAG # mysql版本号 ARG MYSQL_MAJOR=8.0 ENV MYSQL_MAJOR=$MYSQL_MAJOR ARG MYSQL_VERSION=${MYSQL_MAJOR}.27-18 ENV MYSQL_VERSION=$MYSQL_VERSION # 工作目录 ARG MYSQL_DIR=/var/lib/mysql ENV MYSQL_DIR=$MYSQL_DIR # 数据目录 ARG MYSQL_DATA=/var/lib/mysql ENV MYSQL_DATA=$MYSQL_DATA # 环境设置 ARG DEBIAN_FRONTEND=noninteractive ENV DEBIAN_FRONTEND=$DEBIAN_FRONTEND # 源文件下载路径 ARG DOWNLOAD_SRC=/tmp ENV DOWNLOAD_SRC=$DOWNLOAD_SRC # 安装依赖包 ARG PKG_DEPS="\ zsh \ bash \ bash-completion \ dnsutils \ iproute2 \ net-tools \ ncat \ git \ vim \ tzdata \ curl \ wget \ axel \ lsof \ zip \ unzip \ rsync \ iputils-ping \ telnet \ procps \ libaio1 \ numactl \ xz-utils \ gnupg2 \ psmisc \ libmecab2 \ debsums \ locales \ language-pack-zh-hans \ ca-certificates" ENV PKG_DEPS=$PKG_DEPS # ***** 安装依赖 ***** RUN set -eux && \ # 更新源地址并更新系统软件 apt-get update -qqy && apt-get upgrade -qqy && \ # 安装依赖包 apt-get install -qqy --no-install-recommends $PKG_DEPS && \ apt-get -qqy --no-install-recommends autoremove --purge && \ apt-get -qqy --no-install-recommends autoclean && \ rm -rf /var/lib/apt/lists/* && \ # 更新时区 ln -sf /usr/share/zoneinfo/${TZ} /etc/localtime && \ # 更新时间 echo ${TZ} > /etc/timezone && \ # 更改为zsh sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" || true && \ sed -i -e "s/bin\/ash/bin\/zsh/" /etc/passwd && \ sed -i -e 's/mouse=/mouse-=/g' /usr/share/vim/vim*/defaults.vim && \ locale-gen en_US.UTF-8 && localedef -f UTF-8 -i en_US en_US.UTF-8 && locale-gen && \ /bin/zsh # add gosu for easy step-down from root # https://github.com/tianon/gosu/releases ENV GOSU_VERSION 1.14 RUN set -eux; \ savedAptMark="$(apt-mark showmanual)"; \ dpkgArch="$(dpkg --print-architecture | awk -F- '{ print $NF }')"; \ wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch"; \ wget -O /usr/local/bin/gosu.asc "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch.asc"; \ export GNUPGHOME="$(mktemp -d)"; \ gpg --batch --keyserver hkps://keys.openpgp.org --recv-keys B42F6819007F00F88E364FD4036A9C25BF357DD4; \ gpg --batch --verify /usr/local/bin/gosu.asc /usr/local/bin/gosu; \ gpgconf --kill all; \ rm -rf "$GNUPGHOME" /usr/local/bin/gosu.asc; \ apt-mark auto '.*' > /dev/null; \ [ -z "$savedAptMark" ] || apt-mark manual $savedAptMark > /dev/null; \ apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false; \ chmod +x /usr/local/bin/gosu; \ gosu --version; \ gosu nobody true # ***** 拷贝文件 ***** COPY ["ps-entry.sh", "/docker-entrypoint.sh"] # ***** 下载mysql ***** RUN set -eux && \ # 设置mysql用户 groupadd -r mysql && useradd -r -g mysql mysql && \ # 下载mysql wget --no-check-certificate https://downloads.percona.com/downloads/Percona-Server-LATEST/Percona-Server-${MYSQL_VERSION}/binary/debian/focal/x86_64/percona-server-common_${MYSQL_VERSION}-1.focal_amd64.deb \ -O ${DOWNLOAD_SRC}/percona-server-common_${MYSQL_VERSION}-1.focal_amd64.deb && \ wget --no-check-certificate https://downloads.percona.com/downloads/Percona-Server-LATEST/Percona-Server-${MYSQL_VERSION}/binary/debian/focal/x86_64/percona-server-server_${MYSQL_VERSION}-1.focal_amd64.deb \ -O ${DOWNLOAD_SRC}/percona-server-server_${MYSQL_VERSION}-1.focal_amd64.deb && \ wget --no-check-certificate https://downloads.percona.com/downloads/Percona-Server-LATEST/Percona-Server-${MYSQL_VERSION}/binary/debian/focal/x86_64/percona-server-client_${MYSQL_VERSION}-1.focal_amd64.deb \ -O ${DOWNLOAD_SRC}/percona-server-client_${MYSQL_VERSION}-1.focal_amd64.deb && \ # 安装percona-mysql dpkg -i ${DOWNLOAD_SRC}/*.deb && \ # 删除临时文件 rm -rf /var/lib/apt/lists/* ${DOWNLOAD_SRC}/*.deb && \ rm -rf ${MYSQL_DIR} /etc/my.cnf /etc/mysql /etc/my.cnf.d && \ # 创建相关目录 mkdir -p ${MYSQL_DIR} /var/run/mysqld /docker-entrypoint-initdb.d && \ chown -R mysql:mysql ${MYSQL_DIR} /var/run/mysqld && \ chmod 1777 ${MYSQL_DIR} /var/run/mysqld /docker-entrypoint.sh && \ cp -arf /root/.oh-my-zsh ${MYSQL_DIR}/.oh-my-zsh && \ cp -arf /root/.zshrc ${MYSQL_DIR}/.zshrc && \ sed -i '5s#/root/.oh-my-zsh#${MYSQL_DIR}/.oh-my-zsh#' ${MYSQL_DIR}/.zshrc # ***** 拷贝文件 ***** COPY ["conf/mysql/", "/etc/mysql/"] # ***** 容器信号处理 ***** STOPSIGNAL SIGQUIT # ***** 监听端口 ***** EXPOSE 3306 33060 33061 # ***** 工作目录 ***** WORKDIR ${MYSQL_DIR} # ***** 挂载目录 ***** VOLUME ${MYSQL_DATA} # ***** 入口 ***** ENTRYPOINT ["/docker-entrypoint.sh"] # ***** 执行命令 ***** CMD ["mysqld"]
danxiaonuo/mysql-docker
<|start_filename|>domain_snapshot_test.go<|end_filename|> /* * This file is part of the libvirt-go-xml project * * 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. * * Copyright (C) 2017 Red Hat, Inc. * */ package libvirtxml import ( "strings" "testing" ) var domainSnapshotTestData = []struct { Object *DomainSnapshot Expected []string }{ { Object: &DomainSnapshot{ Description: "Snapshot", Disks: &DomainSnapshotDisks{ []DomainSnapshotDisk{ DomainSnapshotDisk{ Name: "/old", Source: &DomainDiskSource{ File: &DomainDiskSourceFile{ File: "/new", }, }, }, DomainSnapshotDisk{ Name: "vdb", Snapshot: "no", }, }, }, }, Expected: []string{ `<domainsnapshot>`, ` <description>Snapshot</description>`, ` <disks>`, ` <disk type="file" name="/old">`, ` <source file="/new"></source>`, ` </disk>`, ` <disk name="vdb" snapshot="no"></disk>`, ` </disks>`, `</domainsnapshot>`, }, }, { Object: &DomainSnapshot{ Name: "1270477159", Description: "Snapshot of OS install and updates", State: "running", CreationTime: "1270477159", Parent: &DomainSnapshotParent{ Name: "bare-os-install", }, Memory: &DomainSnapshotMemory{ Snapshot: "no", }, Disks: &DomainSnapshotDisks{ Disks: []DomainSnapshotDisk{ DomainSnapshotDisk{ Name: "vda", Snapshot: "external", Driver: &DomainDiskDriver{ Type: "qcow2", }, Source: &DomainDiskSource{ File: &DomainDiskSourceFile{ File: "/path/to/new", }, }, }, DomainSnapshotDisk{ Name: "vdb", Snapshot: "no", }, }, }, Domain: &Domain{ Name: "fedora", Memory: &DomainMemory{ Value: 1048576, }, Devices: &DomainDeviceList{ Disks: []DomainDisk{ DomainDisk{ Device: "disk", Driver: &DomainDiskDriver{ Name: "qemu", Type: "raw", }, Source: &DomainDiskSource{ File: &DomainDiskSourceFile{ File: "/path/to/old", }, }, Target: &DomainDiskTarget{ Dev: "vda", Bus: "virtio", }, }, DomainDisk{ Device: "disk", Snapshot: "external", Driver: &DomainDiskDriver{ Name: "qemu", Type: "raw", }, Source: &DomainDiskSource{ File: &DomainDiskSourceFile{ File: "/path/to/old2", }, }, Target: &DomainDiskTarget{ Dev: "vdb", Bus: "virtio", }, }, }, }, }, }, Expected: []string{ `<domainsnapshot>`, ` <name>1270477159</name>`, ` <description>Snapshot of OS install and updates</description>`, ` <state>running</state>`, ` <creationTime>1270477159</creationTime>`, ` <parent>`, ` <name>bare-os-install</name>`, ` </parent>`, ` <memory snapshot="no"></memory>`, ` <disks>`, ` <disk type="file" name="vda" snapshot="external">`, ` <driver type="qcow2"></driver>`, ` <source file="/path/to/new"></source>`, ` </disk>`, ` <disk name="vdb" snapshot="no"></disk>`, ` </disks>`, ` <domain>`, ` <name>fedora</name>`, ` <memory>1048576</memory>`, ` <devices>`, ` <disk type="file" device="disk">`, ` <driver name="qemu" type="raw"></driver>`, ` <source file="/path/to/old"></source>`, ` <target dev="vda" bus="virtio"></target>`, ` </disk>`, ` <disk type="file" device="disk" snapshot="external">`, ` <driver name="qemu" type="raw"></driver>`, ` <source file="/path/to/old2"></source>`, ` <target dev="vdb" bus="virtio"></target>`, ` </disk>`, ` </devices>`, ` </domain>`, `</domainsnapshot>`, }, }, } func TestDomainSnapshot(t *testing.T) { for _, test := range domainSnapshotTestData { doc, err := test.Object.Marshal() if err != nil { t.Fatal(err) } expect := strings.Join(test.Expected, "\n") if doc != expect { t.Fatal("Bad xml:\n", string(doc), "\n does not match\n", expect, "\n") } } } <|start_filename|>domain_test.go<|end_filename|> /* * This file is part of the libvirt-go-xml project * * 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. * * Copyright (C) 2016 Red Hat, Inc. * */ package libvirtxml import ( "reflect" "strings" "testing" ) type PCIAddress struct { Domain uint Bus uint Slot uint Function uint } type DriveAddress struct { Controller uint Bus uint Target uint Unit uint } type ISAAddress struct { IOBase uint } var domainID int = 3 var uhciIndex uint = 0 var uhciAddr = PCIAddress{0, 0, 1, 2} var nvmeAddr = PCIAddress{0, 1, 3, 0} var pciIndex uint = 0 var pciTargetChassisNr uint = 7 var pciTargetChassis uint = 23 var pciTargetPort uint = 78 var pciTargetBusNr uint = 2 var pciTargetIndex uint = 3 var pciTargetNUMANode uint = 2 var scsiIndex uint = 0 var scsiQueues uint = 3 var scsiCmdPerLUN uint = 8 var scsiMaxSectors uint = 512 var usbHostBus uint = 14 var usbHostDevice uint = 6 var pciHostDomain uint = 0 var pciHostBus uint = 3 var pciHostSlot uint = 14 var pciHostFunction uint = 5 var diskAddr = PCIAddress{0, 0, 3, 0} var ifaceAddr = PCIAddress{0, 0, 4, 0} var videoAddr = PCIAddress{0, 0, 5, 0} var fsAddr = PCIAddress{0, 0, 6, 0} var balloonAddr = PCIAddress{0, 0, 7, 0} var panicAddr = ISAAddress{0x505} var duplexAddr = PCIAddress{0, 0, 8, 0} var watchdogAddr = PCIAddress{0, 0, 8, 0} var rngAddr = PCIAddress{0, 0, 9, 0} var hostdevSCSI = DriveAddress{0, 0, 3, 0} var serialPort uint = 0 var parallelPort uint = 0 var tabletBus uint = 0 var tabletPort string = "1.1" var nicAverage int = 1000 var nicBurst int = 10000 var vcpuId0 uint = 0 var vcpuOrder0 uint = 1 var vcpuId1 uint = 1 var memorydevAddressSlot uint = 0 var memorydevAddressBase uint64 = 4294967296 var rebootTimeout int = 0 var cellID0 uint = 0 var cellID1 uint = 1 var ipv6Prefix uint = 24 var iothreadPriority int = -3 var vcpuPriority int = -5 var vepaManagerID uint = 5 var vepaTypeID uint = 3 var vepaTypeIDVersion uint = 12 var vepaInstanceID = "c7bb5ab2-d42f-4690-89d6-f590eb199d0f" var vntagProfileID = "c7bb5ab2-d42f-4690-89d6-f590eb199d0f" var ovsProfileID = "c7bb5ab2-d42f-4690-89d6-f590eb199d0f" var ovsInterfaceID = "73728ac4-53d9-44de-8438-8d8f90beca00" var midoInterfaceID = "73728ac4-53d9-44de-8438-8d8f90beca00" var nvramReg uint64 = 0x4000 var smartcardController uint = 0 var smartcardSlot uint = 7 var redirBus uint = 0 var redirPort string = "3" var redirfilterClass uint = 0x08 var redirfilterProduct uint = 0x2007 var redirfilterVendor uint = 0x15e1 var domainTestData = []struct { Object Document Expected []string }{ { Object: &Domain{ Type: "kvm", Name: "test", ID: &domainID, }, Expected: []string{ `<domain type="kvm" id="3">`, ` <name>test</name>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Title: "Test", Description: "A test guest config", Metadata: &DomainMetadata{ XML: "<myvalue xmlns='http://myapp.com/schemeas/my/1.0'><widget name='foo'/></myvalue>" + "<myothervalue xmlns='http://myotherapp.com/schemeas/my/1.0'><gizmo name='foo'/></myothervalue>", }, Devices: &DomainDeviceList{ Disks: []DomainDisk{ DomainDisk{ Device: "cdrom", Driver: &DomainDiskDriver{ Name: "qemu", Type: "qcow2", }, Source: &DomainDiskSource{ File: &DomainDiskSourceFile{ File: "/var/lib/libvirt/images/demo.qcow2", }, }, Target: &DomainDiskTarget{ Dev: "vda", Bus: "virtio", }, Serial: "fishfood", Boot: &DomainDeviceBoot{ Order: 1, }, }, DomainDisk{ Device: "disk", Driver: &DomainDiskDriver{ Name: "qemu", Type: "raw", }, Source: &DomainDiskSource{ Block: &DomainDiskSourceBlock{ Dev: "/dev/sda1", }, }, Target: &DomainDiskTarget{ Dev: "vdb", Bus: "virtio", }, Address: &DomainAddress{ PCI: &DomainAddressPCI{ Domain: &diskAddr.Domain, Bus: &diskAddr.Bus, Slot: &diskAddr.Slot, Function: &diskAddr.Function, }, }, }, DomainDisk{ Device: "disk", Auth: &DomainDiskAuth{ Username: "fred", Secret: &DomainDiskSecret{ Type: "ceph", UUID: "e49f09c9-119e-43fd-b5a9-000d41e65493", }, }, Source: &DomainDiskSource{ Network: &DomainDiskSourceNetwork{ Protocol: "rbd", Name: "somepool/somevol", Hosts: []DomainDiskSourceHost{ DomainDiskSourceHost{ Transport: "tcp", Name: "rbd1.example.com", Port: "3000", }, DomainDiskSourceHost{ Transport: "tcp", Name: "rbd2.example.com", Port: "3000", }, }, }, }, Target: &DomainDiskTarget{ Dev: "vdc", Bus: "virtio", }, }, DomainDisk{ Device: "disk", Source: &DomainDiskSource{ Network: &DomainDiskSourceNetwork{ Protocol: "nbd", Hosts: []DomainDiskSourceHost{ DomainDiskSourceHost{ Transport: "unix", Socket: "/var/run/nbd.sock", }, }, }, }, Target: &DomainDiskTarget{ Dev: "vdd", Bus: "virtio", }, Shareable: &DomainDiskShareable{}, }, DomainDisk{ Device: "cdrom", Driver: &DomainDiskDriver{ Cache: "none", IO: "native", ErrorPolicy: "stop", }, Source: &DomainDiskSource{ Volume: &DomainDiskSourceVolume{ Pool: "default", Volume: "myvolume", }, }, Target: &DomainDiskTarget{ Dev: "vde", Bus: "virtio", }, ReadOnly: &DomainDiskReadOnly{}, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <title>Test</title>`, ` <description>A test guest config</description>`, ` <metadata>` + `<myvalue xmlns='http://myapp.com/schemeas/my/1.0'><widget name='foo'/></myvalue>` + `<myothervalue xmlns='http://myotherapp.com/schemeas/my/1.0'><gizmo name='foo'/></myothervalue>` + `</metadata>`, ` <devices>`, ` <disk type="file" device="cdrom">`, ` <driver name="qemu" type="qcow2"></driver>`, ` <source file="/var/lib/libvirt/images/demo.qcow2"></source>`, ` <target dev="vda" bus="virtio"></target>`, ` <serial>fishfood</serial>`, ` <boot order="1"></boot>`, ` </disk>`, ` <disk type="block" device="disk">`, ` <driver name="qemu" type="raw"></driver>`, ` <source dev="/dev/sda1"></source>`, ` <target dev="vdb" bus="virtio"></target>`, ` <address type="pci" domain="0x0000" bus="0x00" slot="0x03" function="0x0"></address>`, ` </disk>`, ` <disk type="network" device="disk">`, ` <auth username="fred">`, ` <secret type="ceph" uuid="e49f09c9-119e-43fd-b5a9-000d41e65493"></secret>`, ` </auth>`, ` <source protocol="rbd" name="somepool/somevol">`, ` <host transport="tcp" name="rbd1.example.com" port="3000"></host>`, ` <host transport="tcp" name="rbd2.example.com" port="3000"></host>`, ` </source>`, ` <target dev="vdc" bus="virtio"></target>`, ` </disk>`, ` <disk type="network" device="disk">`, ` <source protocol="nbd">`, ` <host transport="unix" socket="/var/run/nbd.sock"></host>`, ` </source>`, ` <target dev="vdd" bus="virtio"></target>`, ` <shareable></shareable>`, ` </disk>`, ` <disk type="volume" device="cdrom">`, ` <driver cache="none" error_policy="stop" io="native"></driver>`, ` <source pool="default" volume="myvolume"></source>`, ` <target dev="vde" bus="virtio"></target>`, ` <readonly></readonly>`, ` </disk>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Devices: &DomainDeviceList{ Inputs: []DomainInput{ DomainInput{ Type: "tablet", Bus: "usb", Address: &DomainAddress{ USB: &DomainAddressUSB{ Bus: &tabletBus, Port: tabletPort, }, }, }, DomainInput{ Type: "keyboard", Bus: "ps2", }, }, Videos: []DomainVideo{ DomainVideo{ Model: DomainVideoModel{ Type: "cirrus", Heads: 1, Ram: 4096, VRam: 8192, VGAMem: 256, }, Address: &DomainAddress{ PCI: &DomainAddressPCI{ Domain: &videoAddr.Domain, Bus: &videoAddr.Bus, Slot: &videoAddr.Slot, Function: &videoAddr.Function, }, }, }, }, TPMs: []DomainTPM{ DomainTPM{ Model: "tpm-tis", Backend: &DomainTPMBackend{ Passthrough: &DomainTPMBackendPassthrough{ Device: &DomainTPMBackendDevice{ Path: "/dev/tpm0", }, }, }, }, }, Graphics: []DomainGraphic{ DomainGraphic{ VNC: &DomainGraphicVNC{}, }, }, MemBalloon: &DomainMemBalloon{ Model: "virtio", Address: &DomainAddress{ PCI: &DomainAddressPCI{ Domain: &balloonAddr.Domain, Bus: &balloonAddr.Bus, Slot: &balloonAddr.Slot, Function: &balloonAddr.Function, }, }, }, Panics: []DomainPanic{ DomainPanic{ Model: "hyperv", }, DomainPanic{ Model: "isa", Address: &DomainAddress{ ISA: &DomainAddressISA{ IOBase: &panicAddr.IOBase, }, }, }, }, Consoles: []DomainConsole{ DomainConsole{ Source: &DomainChardevSource{ Pty: &DomainChardevSourcePty{}, }, Target: &DomainConsoleTarget{ Type: "virtio", Port: &serialPort, }, }, }, Serials: []DomainSerial{ DomainSerial{ Source: &DomainChardevSource{ Pty: &DomainChardevSourcePty{}, }, Target: &DomainSerialTarget{ Type: "isa", Port: &serialPort, }, }, DomainSerial{ Source: &DomainChardevSource{ File: &DomainChardevSourceFile{ Path: "/tmp/serial.log", Append: "off", }, }, Target: &DomainSerialTarget{ Port: &serialPort, }, }, DomainSerial{ Source: &DomainChardevSource{ TCP: &DomainChardevSourceTCP{ Mode: "bind", Host: "127.0.0.1", Service: "1234", TLS: "yes", }, }, Protocol: &DomainChardevProtocol{ Type: "telnet", }, Target: &DomainSerialTarget{ Port: &serialPort, }, }, }, Channels: []DomainChannel{ DomainChannel{ Source: &DomainChardevSource{ Pty: &DomainChardevSourcePty{}, }, Target: &DomainChannelTarget{ VirtIO: &DomainChannelTargetVirtIO{ Name: "org.redhat.spice", State: "connected", }, }, }, }, Sounds: []DomainSound{ DomainSound{ Model: "ich6", Codec: []DomainSoundCodec{ DomainSoundCodec{ Type: "duplex", }, }, Address: &DomainAddress{ PCI: &DomainAddressPCI{ Domain: &duplexAddr.Domain, Bus: &duplexAddr.Bus, Slot: &duplexAddr.Slot, Function: &duplexAddr.Function, }, }, }, }, RedirDevs: []DomainRedirDev{ DomainRedirDev{ Bus: "usb", Source: &DomainChardevSource{ SpiceVMC: &DomainChardevSourceSpiceVMC{}, }, Address: &DomainAddress{ USB: &DomainAddressUSB{ Bus: &redirBus, Port: redirPort, }, }, }, }, RedirFilters: []DomainRedirFilter{ DomainRedirFilter{ USB: []DomainRedirFilterUSB{ DomainRedirFilterUSB{ Class: &redirfilterClass, Product: &redirfilterProduct, Vendor: &redirfilterVendor, Version: "1.10", Allow: "yes", }, DomainRedirFilterUSB{ Version: "1.10", Allow: "no", }, DomainRedirFilterUSB{ Allow: "yes", }, }, }, }, RNGs: []DomainRNG{ DomainRNG{ Model: "virtio", Rate: &DomainRNGRate{ Period: 2000, Bytes: 1234, }, Backend: &DomainRNGBackend{ EGD: &DomainRNGBackendEGD{ Source: &DomainChardevSource{ Dev: &DomainChardevSourceDev{ Path: "/dev/ttyS0", }, }, Protocol: &DomainChardevProtocol{ Type: "raw", }, }, }, }, }, Memorydevs: []DomainMemorydev{ DomainMemorydev{ Model: "dimm", Access: "private", Target: &DomainMemorydevTarget{ Size: &DomainMemorydevTargetSize{ Value: 1, Unit: "GiB", }, Node: &DomainMemorydevTargetNode{ Value: 0, }, }, Address: &DomainAddress{ DIMM: &DomainAddressDIMM{ Slot: &memorydevAddressSlot, Base: &memorydevAddressBase, }, }, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <devices>`, ` <serial type="pty">`, ` <target type="isa" port="0"></target>`, ` </serial>`, ` <serial type="file">`, ` <source path="/tmp/serial.log" append="off"></source>`, ` <target port="0"></target>`, ` </serial>`, ` <serial type="tcp">`, ` <source mode="bind" host="127.0.0.1" service="1234" tls="yes"></source>`, ` <protocol type="telnet"></protocol>`, ` <target port="0"></target>`, ` </serial>`, ` <console type="pty">`, ` <target type="virtio" port="0"></target>`, ` </console>`, ` <channel type="pty">`, ` <target type="virtio" name="org.redhat.spice" state="connected"></target>`, ` </channel>`, ` <input type="tablet" bus="usb">`, ` <address type="usb" bus="0" port="1.1"></address>`, ` </input>`, ` <input type="keyboard" bus="ps2"></input>`, ` <tpm model="tpm-tis">`, ` <backend type="passthrough">`, ` <device path="/dev/tpm0"></device>`, ` </backend>`, ` </tpm>`, ` <graphics type="vnc"></graphics>`, ` <sound model="ich6">`, ` <codec type="duplex"></codec>`, ` <address type="pci" domain="0x0000" bus="0x00" slot="0x08" function="0x0"></address>`, ` </sound>`, ` <video>`, ` <model type="cirrus" heads="1" ram="4096" vram="8192" vgamem="256"></model>`, ` <address type="pci" domain="0x0000" bus="0x00" slot="0x05" function="0x0"></address>`, ` </video>`, ` <redirdev type="spicevmc" bus="usb">`, ` <address type="usb" bus="0" port="3"></address>`, ` </redirdev>`, ` <redirfilter>`, ` <usbdev class="0x08" vendor="0x15e1" product="0x2007" version="1.10" allow="yes"></usbdev>`, ` <usbdev version="1.10" allow="no"></usbdev>`, ` <usbdev allow="yes"></usbdev>`, ` </redirfilter>`, ` <memballoon model="virtio">`, ` <address type="pci" domain="0x0000" bus="0x00" slot="0x07" function="0x0"></address>`, ` </memballoon>`, ` <rng model="virtio">`, ` <rate bytes="1234" period="2000"></rate>`, ` <backend model="egd" type="dev">`, ` <source path="/dev/ttyS0"></source>`, ` <protocol type="raw"></protocol>`, ` </backend>`, ` </rng>`, ` <panic model="hyperv"></panic>`, ` <panic model="isa">`, ` <address type="isa" iobase="0x505"></address>`, ` </panic>`, ` <memory model="dimm" access="private">`, ` <target>`, ` <size unit="GiB">1</size>`, ` <node>0</node>`, ` </target>`, ` <address type="dimm" slot="0" base="0x100000000"></address>`, ` </memory>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Memory: &DomainMemory{ Unit: "KiB", Value: 8192, DumpCore: "yes", }, CurrentMemory: &DomainCurrentMemory{ Unit: "KiB", Value: 4096, }, MaximumMemory: &DomainMaxMemory{ Unit: "KiB", Value: 16384, Slots: 2, }, MemoryBacking: &DomainMemoryBacking{ MemoryHugePages: &DomainMemoryHugepages{ Hugepages: []DomainMemoryHugepage{ { Size: 1, Unit: "G", Nodeset: "0-3,5", }, { Size: 2, Unit: "M", Nodeset: "4", }, }, }, MemoryNosharepages: &DomainMemoryNosharepages{}, MemoryLocked: &DomainMemoryLocked{}, MemorySource: &DomainMemorySource{ Type: "file", }, MemoryAccess: &DomainMemoryAccess{ Mode: "shared", }, MemoryAllocation: &DomainMemoryAllocation{ Mode: "immediate", }, }, OS: &DomainOS{ Type: &DomainOSType{ Arch: "x86_64", Machine: "pc", Type: "hvm", }, BootDevices: []DomainBootDevice{ DomainBootDevice{ Dev: "hd", }, }, Loader: &DomainLoader{ Readonly: "yes", Secure: "no", Type: "rom", Path: "/loader", }, DTB: "/some/path", ACPI: &DomainACPI{ Tables: []DomainACPITable{ DomainACPITable{ Type: "slic", Path: "/some/data", }, }, }, SMBios: &DomainSMBios{ Mode: "sysinfo", }, BIOS: &DomainBIOS{ UseSerial: "yes", RebootTimeout: &rebootTimeout, }, Init: "/bin/systemd", InitArgs: []string{ "--unit", "emergency.service", }, InitEnv: []DomainOSInitEnv{ DomainOSInitEnv{ Name: "HOME", Value: "/home/fred", }, DomainOSInitEnv{ Name: "USER", Value: "fred", }, }, InitUser: "fred", InitGroup: "fred", InitDir: "/home/fred", }, SysInfo: []DomainSysInfo{ DomainSysInfo{ SMBIOS: &DomainSysInfoSMBIOS{ BIOS: &DomainSysInfoBIOS{ Entry: []DomainSysInfoEntry{ DomainSysInfoEntry{ Name: "vendor", Value: "vendor", }, }, }, System: &DomainSysInfoSystem{ Entry: []DomainSysInfoEntry{ DomainSysInfoEntry{ Name: "manufacturer", Value: "manufacturer", }, DomainSysInfoEntry{ Name: "product", Value: "product", }, DomainSysInfoEntry{ Name: "version", Value: "version", }, }, }, BaseBoard: []DomainSysInfoBaseBoard{ DomainSysInfoBaseBoard{ Entry: []DomainSysInfoEntry{ DomainSysInfoEntry{ Name: "manufacturer", Value: "manufacturer", }, DomainSysInfoEntry{ Name: "product", Value: "product", }, DomainSysInfoEntry{ Name: "version", Value: "version", }, DomainSysInfoEntry{ Name: "serial", Value: "serial", }, }, }, }, }, }, DomainSysInfo{ FWCfg: &DomainSysInfoFWCfg{ Entry: []DomainSysInfoEntry{ DomainSysInfoEntry{ Name: "vendor", Value: "vendor", }, DomainSysInfoEntry{ Name: "installer", File: "/some/path.cfg", }, }, }, }, }, Clock: &DomainClock{ Offset: "variable", Basis: "utc", Adjustment: "28794", TimeZone: "Europe/Paris", Timer: []DomainTimer{ DomainTimer{ Name: "rtc", Track: "boot", TickPolicy: "catchup", CatchUp: &DomainTimerCatchUp{ Threshold: 123, Slew: 120, Limit: 10000, }, Frequency: 120, Mode: "auto", }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <maxMemory unit="KiB" slots="2">16384</maxMemory>`, ` <memory unit="KiB" dumpCore="yes">8192</memory>`, ` <currentMemory unit="KiB">4096</currentMemory>`, ` <memoryBacking>`, ` <hugepages>`, ` <page size="1" unit="G" nodeset="0-3,5"></page>`, ` <page size="2" unit="M" nodeset="4"></page>`, ` </hugepages>`, ` <nosharepages></nosharepages>`, ` <locked></locked>`, ` <source type="file"></source>`, ` <access mode="shared"></access>`, ` <allocation mode="immediate"></allocation>`, ` </memoryBacking>`, ` <sysinfo type="smbios">`, ` <bios>`, ` <entry name="vendor">vendor</entry>`, ` </bios>`, ` <system>`, ` <entry name="manufacturer">manufacturer</entry>`, ` <entry name="product">product</entry>`, ` <entry name="version">version</entry>`, ` </system>`, ` <baseBoard>`, ` <entry name="manufacturer">manufacturer</entry>`, ` <entry name="product">product</entry>`, ` <entry name="version">version</entry>`, ` <entry name="serial">serial</entry>`, ` </baseBoard>`, ` </sysinfo>`, ` <sysinfo type="fwcfg">`, ` <entry name="vendor">vendor</entry>`, ` <entry name="installer" file="/some/path.cfg"></entry>`, ` </sysinfo>`, ` <os>`, ` <type arch="x86_64" machine="pc">hvm</type>`, ` <init>/bin/systemd</init>`, ` <initarg>--unit</initarg>`, ` <initarg>emergency.service</initarg>`, ` <initenv name="HOME">/home/fred</initenv>`, ` <initenv name="USER">fred</initenv>`, ` <initdir>/home/fred</initdir>`, ` <inituser>fred</inituser>`, ` <initgroup>fred</initgroup>`, ` <loader readonly="yes" secure="no" type="rom">/loader</loader>`, ` <dtb>/some/path</dtb>`, ` <acpi>`, ` <table type="slic">/some/data</table>`, ` </acpi>`, ` <boot dev="hd"></boot>`, ` <bios useserial="yes" rebootTimeout="0"></bios>`, ` <smbios mode="sysinfo"></smbios>`, ` </os>`, ` <clock offset="variable" basis="utc" adjustment="28794" timezone="Europe/Paris">`, ` <timer name="rtc" track="boot" tickpolicy="catchup" frequency="120" mode="auto">`, ` <catchup threshold="123" slew="120" limit="10000"></catchup>`, ` </timer>`, ` </clock>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Clock: &DomainClock{ Offset: "variable", Basis: "utc", Adjustment: "reset", }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <clock offset="variable" basis="utc" adjustment="reset"></clock>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", OS: &DomainOS{ NVRam: &DomainNVRam{ Template: "/t.fd", NVRam: "/vars.fd", }, BootMenu: &DomainBootMenu{ Enable: "yes", Timeout: "3000", }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <os>`, ` <nvram template="/t.fd">/vars.fd</nvram>`, ` <bootmenu enable="yes" timeout="3000"></bootmenu>`, ` </os>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", BlockIOTune: &DomainBlockIOTune{ Weight: 900, Device: []DomainBlockIOTuneDevice{ DomainBlockIOTuneDevice{ Path: "/dev/sda", Weight: 500, ReadIopsSec: 300, WriteIopsSec: 200, ReadBytesSec: 3000, WriteBytesSec: 2000, }, DomainBlockIOTuneDevice{ Path: "/dev/sdb", Weight: 600, ReadIopsSec: 100, WriteIopsSec: 40, ReadBytesSec: 1000, WriteBytesSec: 400, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <blkiotune>`, ` <weight>900</weight>`, ` <device>`, ` <path>/dev/sda</path>`, ` <weight>500</weight>`, ` <read_iops_sec>300</read_iops_sec>`, ` <write_iops_sec>200</write_iops_sec>`, ` <read_bytes_sec>3000</read_bytes_sec>`, ` <write_bytes_sec>2000</write_bytes_sec>`, ` </device>`, ` <device>`, ` <path>/dev/sdb</path>`, ` <weight>600</weight>`, ` <read_iops_sec>100</read_iops_sec>`, ` <write_iops_sec>40</write_iops_sec>`, ` <read_bytes_sec>1000</read_bytes_sec>`, ` <write_bytes_sec>400</write_bytes_sec>`, ` </device>`, ` </blkiotune>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", MemoryTune: &DomainMemoryTune{ HardLimit: &DomainMemoryTuneLimit{ Value: 1024, Unit: "MiB", }, SoftLimit: &DomainMemoryTuneLimit{ Value: 1024, }, MinGuarantee: &DomainMemoryTuneLimit{ Value: 1024, }, SwapHardLimit: &DomainMemoryTuneLimit{ Value: 1024, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <memtune>`, ` <hard_limit unit="MiB">1024</hard_limit>`, ` <soft_limit>1024</soft_limit>`, ` <min_guarantee>1024</min_guarantee>`, ` <swap_hard_limit>1024</swap_hard_limit>`, ` </memtune>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", PM: &DomainPM{ SuspendToMem: &DomainPMPolicy{ Enabled: "no", }, SuspendToDisk: &DomainPMPolicy{ Enabled: "yes", }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <pm>`, ` <suspend-to-mem enabled="no"></suspend-to-mem>`, ` <suspend-to-disk enabled="yes"></suspend-to-disk>`, ` </pm>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", SecLabel: []DomainSecLabel{ DomainSecLabel{ Type: "dynamic", Model: "selinux", Relabel: "yes", Label: "system_u:system_r:svirt_t:s0:c143,c762", ImageLabel: "system_u:object_r:svirt_image_t:s0:c143,c762", BaseLabel: "system_u:system_r:svirt_t:s0", }, DomainSecLabel{ Type: "dynamic", Model: "dac", Relabel: "no", }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <seclabel type="dynamic" model="selinux" relabel="yes">`, ` <label>system_u:system_r:svirt_t:s0:c143,c762</label>`, ` <imagelabel>system_u:object_r:svirt_image_t:s0:c143,c762</imagelabel>`, ` <baselabel>system_u:system_r:svirt_t:s0</baselabel>`, ` </seclabel>`, ` <seclabel type="dynamic" model="dac" relabel="no"></seclabel>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", OS: &DomainOS{ Kernel: "/vmlinuz", Initrd: "/initrd", Cmdline: "arg", }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <os>`, ` <kernel>/vmlinuz</kernel>`, ` <initrd>/initrd</initrd>`, ` <cmdline>arg</cmdline>`, ` </os>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Resource: &DomainResource{ Partition: "/machines/production", }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <resource>`, ` <partition>/machines/production</partition>`, ` </resource>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", VCPU: &DomainVCPU{ Placement: "static", CPUSet: "1-4,^3,6", Current: 1, Value: 2, }, VCPUs: &DomainVCPUs{ VCPU: []DomainVCPUsVCPU{ DomainVCPUsVCPU{ Id: &vcpuId0, Enabled: "yes", Hotpluggable: "no", Order: &vcpuOrder0, }, DomainVCPUsVCPU{ Id: &vcpuId1, Enabled: "no", Hotpluggable: "yes", Order: nil, }, }, }, Devices: &DomainDeviceList{ Interfaces: []DomainInterface{ DomainInterface{ MAC: &DomainInterfaceMAC{ Address: "00:11:22:33:44:55", }, Model: &DomainInterfaceModel{ Type: "virtio", }, Source: &DomainInterfaceSource{ Network: &DomainInterfaceSourceNetwork{ Network: "default", }, }, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <vcpu placement="static" cpuset="1-4,^3,6" current="1">2</vcpu>`, ` <vcpus>`, ` <vcpu id="0" enabled="yes" hotpluggable="no" order="1"></vcpu>`, ` <vcpu id="1" enabled="no" hotpluggable="yes"></vcpu>`, ` </vcpus>`, ` <devices>`, ` <interface type="network">`, ` <mac address="00:11:22:33:44:55"></mac>`, ` <source network="default"></source>`, ` <model type="virtio"></model>`, ` </interface>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", CPU: &DomainCPU{ Match: "exact", Check: "none", Model: &DomainCPUModel{ Fallback: "allow", Value: "core2duo", VendorID: "LibvirtQEMU", }, Vendor: "Intel", Topology: &DomainCPUTopology{ Sockets: 1, Cores: 2, Threads: 1, }, Features: []DomainCPUFeature{ DomainCPUFeature{Policy: "disable", Name: "lahf_lm"}, }, Cache: &DomainCPUCache{ Level: 1, Mode: "emulate", }, Numa: &DomainNuma{ []DomainCell{ { ID: &cellID0, CPUs: "0-1", Memory: 512000, Unit: "KiB", MemAccess: "private", Distances: &DomainCellDistances{ Siblings: []DomainCellSibling{ DomainCellSibling{ ID: 1, Value: 20, }, }, }, }, { ID: &cellID1, CPUs: "2-3", Memory: 512000, Unit: "KiB", MemAccess: "private", Distances: &DomainCellDistances{ Siblings: []DomainCellSibling{ DomainCellSibling{ ID: 0, Value: 20, }, }, }, }, }, nil, }, }, Devices: &DomainDeviceList{ Emulator: "/bin/qemu-kvm", }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <cpu match="exact" check="none">`, ` <model fallback="allow" vendor_id="LibvirtQEMU">core2duo</model>`, ` <vendor>Intel</vendor>`, ` <topology sockets="1" cores="2" threads="1"></topology>`, ` <cache level="1" mode="emulate"></cache>`, ` <feature policy="disable" name="lahf_lm"></feature>`, ` <numa>`, ` <cell id="0" cpus="0-1" memory="512000" unit="KiB" memAccess="private">`, ` <distances>`, ` <sibling id="1" value="20"></sibling>`, ` </distances>`, ` </cell>`, ` <cell id="1" cpus="2-3" memory="512000" unit="KiB" memAccess="private">`, ` <distances>`, ` <sibling id="0" value="20"></sibling>`, ` </distances>`, ` </cell>`, ` </numa>`, ` </cpu>`, ` <devices>`, ` <emulator>/bin/qemu-kvm</emulator>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Devices: &DomainDeviceList{ Interfaces: []DomainInterface{ DomainInterface{ MAC: &DomainInterfaceMAC{ Address: "06:39:b4:00:00:46", }, Model: &DomainInterfaceModel{ Type: "virtio", }, Source: &DomainInterfaceSource{ Bridge: &DomainInterfaceSourceBridge{ Bridge: "private", }, }, Target: &DomainInterfaceTarget{ Dev: "vnet3", }, Alias: &DomainAlias{ Name: "net1", }, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <devices>`, ` <interface type="bridge">`, ` <mac address="06:39:b4:00:00:46"></mac>`, ` <source bridge="private"></source>`, ` <target dev="vnet3"></target>`, ` <model type="virtio"></model>`, ` <alias name="net1"></alias>`, ` </interface>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "vmware", Name: "test", Devices: &DomainDeviceList{ Interfaces: []DomainInterface{ DomainInterface{ MAC: &DomainInterfaceMAC{ Address: "06:39:b4:00:00:46", }, Model: &DomainInterfaceModel{ Type: "e1000", }, Source: &DomainInterfaceSource{ Bridge: &DomainInterfaceSourceBridge{ Bridge: "", }, }, }, }, }, }, Expected: []string{ `<domain type="vmware">`, ` <name>test</name>`, ` <devices>`, ` <interface type="bridge">`, ` <mac address="06:39:b4:00:00:46"></mac>`, ` <source bridge=""></source>`, ` <model type="e1000"></model>`, ` </interface>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Devices: &DomainDeviceList{ Interfaces: []DomainInterface{ DomainInterface{ MAC: &DomainInterfaceMAC{ Address: "52:54:00:39:97:ac", }, Model: &DomainInterfaceModel{ Type: "e1000", }, Source: &DomainInterfaceSource{ Network: &DomainInterfaceSourceNetwork{ Network: "default", }, }, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <devices>`, ` <interface type="network">`, ` <mac address="52:54:00:39:97:ac"></mac>`, ` <source network="default"></source>`, ` <model type="e1000"></model>`, ` </interface>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Devices: &DomainDeviceList{ Interfaces: []DomainInterface{ DomainInterface{ MAC: &DomainInterfaceMAC{ Address: "52:54:00:39:97:ac", }, Model: &DomainInterfaceModel{ Type: "virtio", }, Source: &DomainInterfaceSource{ UDP: &DomainInterfaceSourceUDP{ Address: "127.0.0.1", Port: 1234, Local: &DomainInterfaceSourceLocal{ Address: "127.0.0.1", Port: 1235, }, }, }, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <devices>`, ` <interface type="udp">`, ` <mac address="52:54:00:39:97:ac"></mac>`, ` <source address="127.0.0.1" port="1234">`, ` <local address="127.0.0.1" port="1235"></local>`, ` </source>`, ` <model type="virtio"></model>`, ` </interface>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Devices: &DomainDeviceList{ Interfaces: []DomainInterface{ DomainInterface{ Source: &DomainInterfaceSource{ Direct: &DomainInterfaceSourceDirect{ Dev: "eth0", Mode: "bridge", }, }, VirtualPort: &DomainInterfaceVirtualPort{ Params: &DomainInterfaceVirtualPortParams{ VEPA8021QBG: &DomainInterfaceVirtualPortParamsVEPA8021QBG{ ManagerID: &vepaManagerID, TypeID: &vepaTypeID, TypeIDVersion: &vepaTypeIDVersion, InstanceID: vepaInstanceID, }, }, }, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <devices>`, ` <interface type="direct">`, ` <source dev="eth0" mode="bridge"></source>`, ` <virtualport type="802.1Qbg">`, ` <parameters managerid="5" typeid="3" typeidversion="12" instanceid="c7bb5ab2-d42f-4690-89d6-f590eb199d0f"></parameters>`, ` </virtualport>`, ` </interface>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Devices: &DomainDeviceList{ Interfaces: []DomainInterface{ DomainInterface{ Source: &DomainInterfaceSource{ Direct: &DomainInterfaceSourceDirect{ Dev: "eth0", Mode: "bridge", }, }, VirtualPort: &DomainInterfaceVirtualPort{ Params: &DomainInterfaceVirtualPortParams{ VNTag8011QBH: &DomainInterfaceVirtualPortParamsVNTag8021QBH{ ProfileID: vntagProfileID, }, }, }, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <devices>`, ` <interface type="direct">`, ` <source dev="eth0" mode="bridge"></source>`, ` <virtualport type="802.1Qbh">`, ` <parameters profileid="c7bb5ab2-d42f-4690-89d6-f590eb199d0f"></parameters>`, ` </virtualport>`, ` </interface>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Devices: &DomainDeviceList{ Interfaces: []DomainInterface{ DomainInterface{ Source: &DomainInterfaceSource{ Direct: &DomainInterfaceSourceDirect{ Dev: "eth0", Mode: "bridge", }, }, VirtualPort: &DomainInterfaceVirtualPort{ Params: &DomainInterfaceVirtualPortParams{ OpenVSwitch: &DomainInterfaceVirtualPortParamsOpenVSwitch{ ProfileID: ovsProfileID, InterfaceID: ovsInterfaceID, }, }, }, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <devices>`, ` <interface type="direct">`, ` <source dev="eth0" mode="bridge"></source>`, ` <virtualport type="openvswitch">`, ` <parameters interfaceid="73728ac4-53d9-44de-8438-8d8f90beca00" profileid="c7bb5ab2-d42f-4690-89d6-f590eb199d0f"></parameters>`, ` </virtualport>`, ` </interface>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Devices: &DomainDeviceList{ Interfaces: []DomainInterface{ DomainInterface{ Source: &DomainInterfaceSource{ Direct: &DomainInterfaceSourceDirect{ Dev: "eth0", Mode: "bridge", }, }, VirtualPort: &DomainInterfaceVirtualPort{ Params: &DomainInterfaceVirtualPortParams{ MidoNet: &DomainInterfaceVirtualPortParamsMidoNet{ InterfaceID: midoInterfaceID, }, }, }, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <devices>`, ` <interface type="direct">`, ` <source dev="eth0" mode="bridge"></source>`, ` <virtualport type="midonet">`, ` <parameters interfaceid="73728ac4-53d9-44de-8438-8d8f90beca00"></parameters>`, ` </virtualport>`, ` </interface>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Devices: &DomainDeviceList{ Interfaces: []DomainInterface{ DomainInterface{ MAC: &DomainInterfaceMAC{ Address: "52:54:00:39:97:ac", }, Model: &DomainInterfaceModel{ Type: "virtio", }, Source: &DomainInterfaceSource{ User: &DomainInterfaceSourceUser{}, }, Link: &DomainInterfaceLink{ State: "up", }, Boot: &DomainDeviceBoot{ Order: 1, }, Driver: &DomainInterfaceDriver{ Name: "vhost", Queues: 5, }, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <devices>`, ` <interface type="user">`, ` <mac address="52:54:00:39:97:ac"></mac>`, ` <boot order="1"></boot>`, ` <model type="virtio"></model>`, ` <driver name="vhost" queues="5"></driver>`, ` <link state="up"></link>`, ` </interface>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Devices: &DomainDeviceList{ Interfaces: []DomainInterface{ DomainInterface{ MAC: &DomainInterfaceMAC{ Address: "52:54:00:39:97:ac", }, Model: &DomainInterfaceModel{ Type: "virtio", }, Source: &DomainInterfaceSource{ Server: &DomainInterfaceSourceServer{ Address: "127.0.0.1", Port: 1234, }, }, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <devices>`, ` <interface type="server">`, ` <mac address="52:54:00:39:97:ac"></mac>`, ` <source address="127.0.0.1" port="1234"></source>`, ` <model type="virtio"></model>`, ` </interface>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Devices: &DomainDeviceList{ Interfaces: []DomainInterface{ DomainInterface{ MAC: &DomainInterfaceMAC{ Address: "52:54:00:39:97:ac", }, Model: &DomainInterfaceModel{ Type: "virtio", }, Source: &DomainInterfaceSource{ Ethernet: &DomainInterfaceSourceEthernet{}, }, Script: &DomainInterfaceScript{ Path: "/etc/qemu-ifup", }, Address: &DomainAddress{ PCI: &DomainAddressPCI{ Domain: &ifaceAddr.Domain, Bus: &ifaceAddr.Bus, Slot: &ifaceAddr.Slot, Function: &ifaceAddr.Function, }, }, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <devices>`, ` <interface type="ethernet">`, ` <mac address="52:54:00:39:97:ac"></mac>`, ` <script path="/etc/qemu-ifup"></script>`, ` <model type="virtio"></model>`, ` <address type="pci" domain="0x0000" bus="0x00" slot="0x04" function="0x0"></address>`, ` </interface>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Devices: &DomainDeviceList{ Interfaces: []DomainInterface{ DomainInterface{ MAC: &DomainInterfaceMAC{ Address: "52:54:00:39:97:ac", }, Model: &DomainInterfaceModel{ Type: "virtio", }, Source: &DomainInterfaceSource{ VHostUser: &DomainChardevSource{ UNIX: &DomainChardevSourceUNIX{ Path: "/tmp/vhost0.sock", Mode: "server", }, }, }, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <devices>`, ` <interface type="vhostuser">`, ` <mac address="52:54:00:39:97:ac"></mac>`, ` <source type="unix" mode="server" path="/tmp/vhost0.sock"></source>`, ` <model type="virtio"></model>`, ` </interface>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Devices: &DomainDeviceList{ Interfaces: []DomainInterface{ DomainInterface{ MAC: &DomainInterfaceMAC{ Address: "52:54:00:39:97:ac", }, Model: &DomainInterfaceModel{ Type: "virtio", }, Source: &DomainInterfaceSource{ VHostUser: &DomainChardevSource{ UNIX: &DomainChardevSourceUNIX{ Path: "/tmp/vhost0.sock", Mode: "server", }, }, }, Bandwidth: &DomainInterfaceBandwidth{ Inbound: &DomainInterfaceBandwidthParams{ Average: &nicAverage, Burst: &nicBurst, }, Outbound: &DomainInterfaceBandwidthParams{ Average: new(int), Burst: new(int), }, }, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <devices>`, ` <interface type="vhostuser">`, ` <mac address="52:54:00:39:97:ac"></mac>`, ` <source type="unix" mode="server" path="/tmp/vhost0.sock"></source>`, ` <model type="virtio"></model>`, ` <bandwidth>`, ` <inbound average="1000" burst="10000"></inbound>`, ` <outbound average="0" burst="0"></outbound>`, ` </bandwidth>`, ` </interface>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Devices: &DomainDeviceList{ Interfaces: []DomainInterface{ DomainInterface{ MAC: &DomainInterfaceMAC{ Address: "52:54:00:39:97:ac", }, Source: &DomainInterfaceSource{ Hostdev: &DomainInterfaceSourceHostdev{ PCI: &DomainHostdevSubsysPCISource{ Address: &DomainAddressPCI{ Domain: &pciHostDomain, Bus: &pciHostBus, Slot: &pciHostSlot, Function: &pciHostFunction, }, }, }, }, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <devices>`, ` <interface type="hostdev">`, ` <mac address="52:54:00:39:97:ac"></mac>`, ` <source>`, ` <address type="pci" domain="0x0000" bus="0x03" slot="0x0e" function="0x5"></address>`, ` </source>`, ` </interface>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Devices: &DomainDeviceList{ Filesystems: []DomainFilesystem{ DomainFilesystem{ AccessMode: "mapped", Driver: &DomainFilesystemDriver{ Type: "path", WRPolicy: "immediate", }, Source: &DomainFilesystemSource{ Mount: &DomainFilesystemSourceMount{ Dir: "/home/user/test", }, }, Target: &DomainFilesystemTarget{ Dir: "user-test-mount", }, Address: &DomainAddress{ PCI: &DomainAddressPCI{ Domain: &fsAddr.Domain, Bus: &fsAddr.Bus, Slot: &fsAddr.Slot, Function: &fsAddr.Function, }, }, }, DomainFilesystem{ AccessMode: "passthrough", Driver: &DomainFilesystemDriver{ Name: "loop", Type: "raw", }, Source: &DomainFilesystemSource{ File: &DomainFilesystemSourceFile{ File: "/home/user/test.img", }, }, Target: &DomainFilesystemTarget{ Dir: "user-file-test-mount", }, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <devices>`, ` <filesystem type="mount" accessmode="mapped">`, ` <driver type="path" wrpolicy="immediate"></driver>`, ` <source dir="/home/user/test"></source>`, ` <target dir="user-test-mount"></target>`, ` <address type="pci" domain="0x0000" bus="0x00" slot="0x06" function="0x0"></address>`, ` </filesystem>`, ` <filesystem type="file" accessmode="passthrough">`, ` <driver type="raw" name="loop"></driver>`, ` <source file="/home/user/test.img"></source>`, ` <target dir="user-file-test-mount"></target>`, ` </filesystem>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Features: &DomainFeatureList{ PAE: &DomainFeature{}, ACPI: &DomainFeature{}, APIC: &DomainFeatureAPIC{}, HAP: &DomainFeatureState{}, PrivNet: &DomainFeature{}, HyperV: &DomainFeatureHyperV{ Relaxed: &DomainFeatureState{State: "on"}, VAPIC: &DomainFeatureState{State: "on"}, Spinlocks: &DomainFeatureHyperVSpinlocks{ DomainFeatureState{State: "on"}, 4096, }, VPIndex: &DomainFeatureState{State: "on"}, Runtime: &DomainFeatureState{State: "on"}, Synic: &DomainFeatureState{State: "on"}, Reset: &DomainFeatureState{State: "on"}, VendorId: &DomainFeatureHyperVVendorId{ DomainFeatureState{State: "on"}, "KVM Hv", }, }, KVM: &DomainFeatureKVM{ Hidden: &DomainFeatureState{State: "on"}, }, PVSpinlock: &DomainFeatureState{State: "on"}, GIC: &DomainFeatureGIC{Version: "2"}, Capabilities: &DomainFeatureCapabilities{ Policy: "default", MkNod: &DomainFeatureCapability{ State: "on", }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <features>`, ` <pae></pae>`, ` <acpi></acpi>`, ` <apic></apic>`, ` <hap></hap>`, ` <privnet></privnet>`, ` <hyperv>`, ` <relaxed state="on"></relaxed>`, ` <vapic state="on"></vapic>`, ` <spinlocks state="on" retries="4096"></spinlocks>`, ` <vpindex state="on"></vpindex>`, ` <runtime state="on"></runtime>`, ` <synic state="on"></synic>`, ` <reset state="on"></reset>`, ` <vendor_id state="on" value="KVM Hv"></vendor_id>`, ` </hyperv>`, ` <kvm>`, ` <hidden state="on"></hidden>`, ` </kvm>`, ` <pvspinlock state="on"></pvspinlock>`, ` <gic version="2"></gic>`, ` <capabilities policy="default">`, ` <mknod state="on"></mknod>`, ` </capabilities>`, ` </features>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Devices: &DomainDeviceList{ Controllers: []DomainController{ DomainController{ Type: "usb", Index: &uhciIndex, Model: "piix3-uhci", Address: &DomainAddress{ PCI: &DomainAddressPCI{ Domain: &uhciAddr.Domain, Bus: &uhciAddr.Bus, Slot: &uhciAddr.Slot, Function: &uhciAddr.Function, }, }, }, DomainController{ Type: "usb", Index: nil, Model: "ehci", USB: &DomainControllerUSB{ Master: &DomainControllerUSBMaster{ StartPort: 0, }, }, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <devices>`, ` <controller type="usb" index="0" model="piix3-uhci">`, ` <address type="pci" domain="0x0000" bus="0x00" slot="0x01" function="0x2"></address>`, ` </controller>`, ` <controller type="usb" model="ehci">`, ` <master startport="0"></master>`, ` </controller>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Devices: &DomainDeviceList{ Controllers: []DomainController{ DomainController{ Type: "pci", Index: &pciIndex, Model: "pci-expander-bus", PCI: &DomainControllerPCI{ Model: &DomainControllerPCIModel{ Name: "pxb", }, Target: &DomainControllerPCITarget{ ChassisNr: &pciTargetChassisNr, Chassis: &pciTargetChassis, Port: &pciTargetPort, BusNr: &pciTargetBusNr, Index: &pciTargetIndex, NUMANode: &pciTargetNUMANode, }, Hole64: &DomainControllerPCIHole64{ Size: 1024, }, }, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <devices>`, ` <controller type="pci" index="0" model="pci-expander-bus">`, ` <model name="pxb"></model>`, ` <target chassisNr="7" chassis="23" port="78" busNr="2" index="3">`, ` <node>2</node>`, ` </target>`, ` <pcihole64>1024</pcihole64>`, ` </controller>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Devices: &DomainDeviceList{ Controllers: []DomainController{ DomainController{ Type: "scsi", Index: &scsiIndex, Driver: &DomainControllerDriver{ Queues: &scsiQueues, CmdPerLUN: &scsiCmdPerLUN, MaxSectors: &scsiMaxSectors, IOEventFD: "yes", IOThread: 3, IOMMU: "yes", ATS: "no", }, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <devices>`, ` <controller type="scsi" index="0">`, ` <driver queues="3" cmd_per_lun="8" max_sectors="512" ioeventfd="yes" iothread="3" iommu="yes" ats="no"></driver>`, ` </controller>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Devices: &DomainDeviceList{ Hubs: []DomainHub{ DomainHub{ Type: "usb", }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <devices>`, ` <hub type="usb"></hub>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Devices: &DomainDeviceList{ IOMMU: &DomainIOMMU{ Model: "intel", Driver: &DomainIOMMUDriver{ EIM: "on", IntRemap: "on", CachingMode: "on", AWBits: 48, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <devices>`, ` <iommu model="intel">`, ` <driver intremap="on" caching_mode="on" eim="on" aw_bits="48"></driver>`, ` </iommu>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Perf: &DomainPerf{ Events: []DomainPerfEvent{ DomainPerfEvent{ Name: "cmt", Enabled: "yes", }, DomainPerfEvent{ Name: "mbmt", Enabled: "no", }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <perf>`, ` <event name="cmt" enabled="yes"></event>`, ` <event name="mbmt" enabled="no"></event>`, ` </perf>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Devices: &DomainDeviceList{ Leases: []DomainLease{ DomainLease{ Lockspace: "foo", Key: "bar", Target: &DomainLeaseTarget{ Path: "/some/file", Offset: 1024, }, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <devices>`, ` <lease>`, ` <lockspace>foo</lockspace>`, ` <key>bar</key>`, ` <target path="/some/file" offset="1024"></target>`, ` </lease>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "kvm", Name: "test", Devices: &DomainDeviceList{ NVRAM: &DomainNVRAM{ Address: &DomainAddress{ SpaprVIO: &DomainAddressSpaprVIO{ Reg: &nvramReg, }, }, }, }, }, Expected: []string{ `<domain type="kvm">`, ` <name>test</name>`, ` <devices>`, ` <nvram>`, ` <address type="spapr-vio" reg="0x4000"></address>`, ` </nvram>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Type: "qemu", Name: "test", QEMUCommandline: &DomainQEMUCommandline{ Args: []DomainQEMUCommandlineArg{ DomainQEMUCommandlineArg{Value: "-newarg"}, DomainQEMUCommandlineArg{Value: "-oldarg"}, }, Envs: []DomainQEMUCommandlineEnv{ DomainQEMUCommandlineEnv{Name: "QEMU_ENV", Value: "VAL"}, DomainQEMUCommandlineEnv{Name: "QEMU_VAR", Value: "VAR"}, }, }, }, Expected: []string{ `<domain type="qemu">`, ` <name>test</name>`, ` <commandline xmlns="http://libvirt.org/schemas/domain/qemu/1.0">`, ` <arg value="-newarg"></arg>`, ` <arg value="-oldarg"></arg>`, ` <env name="QEMU_ENV" value="VAL"></env>`, ` <env name="QEMU_VAR" value="VAR"></env>`, ` </commandline>`, `</domain>`, }, }, { Object: &Domain{ Type: "lxc", Name: "test", LXCNamespace: &DomainLXCNamespace{ ShareNet: &DomainLXCNamespaceMap{ Type: "netns", Value: "red", }, ShareIPC: &DomainLXCNamespaceMap{ Type: "pid", Value: "12345", }, ShareUTS: &DomainLXCNamespaceMap{ Type: "name", Value: "container1", }, }, }, Expected: []string{ `<domain type="lxc">`, ` <name>test</name>`, ` <namespace xmlns="http://libvirt.org/schemas/domain/lxc/1.0">`, ` <sharenet type="netns" value="red"></sharenet>`, ` <shareipc type="pid" value="12345"></shareipc>`, ` <shareuts type="name" value="container1"></shareuts>`, ` </namespace>`, `</domain>`, }, }, { Object: &Domain{ Type: "vmware", Name: "test", VMWareDataCenterPath: &DomainVMWareDataCenterPath{ Value: "folder1/folder2/datacenter1", }, }, Expected: []string{ `<domain type="vmware">`, ` <name>test</name>`, ` <datacenterpath xmlns="http://libvirt.org/schemas/domain/vmware/1.0">folder1/folder2/datacenter1</datacenterpath>`, `</domain>`, }, }, { Object: &Domain{ Name: "test", IOThreads: 4, IOThreadIDs: &DomainIOThreadIDs{ IOThreads: []DomainIOThread{ DomainIOThread{ ID: 0, }, DomainIOThread{ ID: 1, }, DomainIOThread{ ID: 2, }, DomainIOThread{ ID: 3, }, }, }, CPUTune: &DomainCPUTune{ Shares: &DomainCPUTuneShares{Value: 1024}, Period: &DomainCPUTunePeriod{Value: 500000}, Quota: &DomainCPUTuneQuota{Value: -1}, GlobalPeriod: &DomainCPUTunePeriod{Value: 500000}, GlobalQuota: &DomainCPUTuneQuota{Value: 500}, EmulatorPeriod: &DomainCPUTunePeriod{Value: 900000}, EmulatorQuota: &DomainCPUTuneQuota{Value: 100}, IOThreadPeriod: &DomainCPUTunePeriod{Value: 100000}, IOThreadQuota: &DomainCPUTuneQuota{Value: 2000}, VCPUPin: []DomainCPUTuneVCPUPin{ DomainCPUTuneVCPUPin{ VCPU: 0, CPUSet: "0-1", }, DomainCPUTuneVCPUPin{ VCPU: 1, CPUSet: "2-3", }, }, EmulatorPin: &DomainCPUTuneEmulatorPin{ CPUSet: "0-3", }, IOThreadPin: []DomainCPUTuneIOThreadPin{ DomainCPUTuneIOThreadPin{ IOThread: 0, CPUSet: "0-1", }, DomainCPUTuneIOThreadPin{ IOThread: 1, CPUSet: "2-3", }, }, VCPUSched: []DomainCPUTuneVCPUSched{ DomainCPUTuneVCPUSched{ VCPUs: "0-1", Scheduler: "fifo", Priority: &vcpuPriority, }, }, IOThreadSched: []DomainCPUTuneIOThreadSched{ DomainCPUTuneIOThreadSched{ IOThreads: "0-1", Scheduler: "fifo", Priority: &iothreadPriority, }, }, }, }, Expected: []string{ `<domain>`, ` <name>test</name>`, ` <iothreads>4</iothreads>`, ` <iothreadids>`, ` <iothread id="0"></iothread>`, ` <iothread id="1"></iothread>`, ` <iothread id="2"></iothread>`, ` <iothread id="3"></iothread>`, ` </iothreadids>`, ` <cputune>`, ` <shares>1024</shares>`, ` <period>500000</period>`, ` <quota>-1</quota>`, ` <global_period>500000</global_period>`, ` <global_quota>500</global_quota>`, ` <emulator_period>900000</emulator_period>`, ` <emulator_quota>100</emulator_quota>`, ` <iothread_period>100000</iothread_period>`, ` <iothread_quota>2000</iothread_quota>`, ` <vcpupin vcpu="0" cpuset="0-1"></vcpupin>`, ` <vcpupin vcpu="1" cpuset="2-3"></vcpupin>`, ` <emulatorpin cpuset="0-3"></emulatorpin>`, ` <iothreadpin iothread="0" cpuset="0-1"></iothreadpin>`, ` <iothreadpin iothread="1" cpuset="2-3"></iothreadpin>`, ` <vcpusched vcpus="0-1" scheduler="fifo" priority="-5"></vcpusched>`, ` <iothreadsched iothreads="0-1" scheduler="fifo" priority="-3"></iothreadsched>`, ` </cputune>`, `</domain>`, }, }, { Object: &Domain{ Name: "test", KeyWrap: &DomainKeyWrap{ Ciphers: []DomainKeyWrapCipher{ DomainKeyWrapCipher{ Name: "aes", State: "on", }, DomainKeyWrapCipher{ Name: "dea", State: "off", }, }, }, }, Expected: []string{ `<domain>`, ` <name>test</name>`, ` <keywrap>`, ` <cipher name="aes" state="on"></cipher>`, ` <cipher name="dea" state="off"></cipher>`, ` </keywrap>`, `</domain>`, }, }, { Object: &Domain{ Name: "test", IDMap: &DomainIDMap{ UIDs: []DomainIDMapRange{ DomainIDMapRange{ Start: 0, Target: 1000, Count: 50, }, DomainIDMapRange{ Start: 1000, Target: 5000, Count: 5000, }, }, GIDs: []DomainIDMapRange{ DomainIDMapRange{ Start: 0, Target: 1000, Count: 50, }, DomainIDMapRange{ Start: 1000, Target: 5000, Count: 5000, }, }, }, }, Expected: []string{ `<domain>`, ` <name>test</name>`, ` <idmap>`, ` <uid start="0" target="1000" count="50"></uid>`, ` <uid start="1000" target="5000" count="5000"></uid>`, ` <gid start="0" target="1000" count="50"></gid>`, ` <gid start="1000" target="5000" count="5000"></gid>`, ` </idmap>`, `</domain>`, }, }, { Object: &Domain{ Name: "test", NUMATune: &DomainNUMATune{ Memory: &DomainNUMATuneMemory{ Mode: "strict", Nodeset: "2-3", Placement: "static", }, MemNodes: []DomainNUMATuneMemNode{ DomainNUMATuneMemNode{ CellID: 0, Mode: "strict", Nodeset: "2", }, DomainNUMATuneMemNode{ CellID: 1, Mode: "strict", Nodeset: "3", }, }, }, }, Expected: []string{ `<domain>`, ` <name>test</name>`, ` <numatune>`, ` <memory mode="strict" nodeset="2-3" placement="static"></memory>`, ` <memnode cellid="0" mode="strict" nodeset="2"></memnode>`, ` <memnode cellid="1" mode="strict" nodeset="3"></memnode>`, ` </numatune>`, `</domain>`, }, }, /* Tests for sub-documents that can be hotplugged */ { Object: &DomainController{ Type: "usb", Index: &uhciIndex, Model: "piix3-uhci", Address: &DomainAddress{ PCI: &DomainAddressPCI{ Domain: &uhciAddr.Domain, Bus: &uhciAddr.Bus, Slot: &uhciAddr.Slot, Function: &uhciAddr.Function, }, }, }, Expected: []string{ `<controller type="usb" index="0" model="piix3-uhci">`, ` <address type="pci" domain="0x0000" bus="0x00" slot="0x01" function="0x2"></address>`, `</controller>`, }, }, { Object: &DomainDisk{ Device: "cdrom", Driver: &DomainDiskDriver{ Name: "qemu", Type: "qcow2", }, Source: &DomainDiskSource{ File: &DomainDiskSourceFile{ File: "/var/lib/libvirt/images/demo.qcow2", }, }, BackingStore: &DomainDiskBackingStore{ Index: 1, Format: &DomainDiskFormat{ Type: "qcow2", }, Source: &DomainDiskSource{ Block: &DomainDiskSourceBlock{ Dev: "/dev/HostVG/QEMUGuest", }, }, BackingStore: &DomainDiskBackingStore{ Index: 2, Format: &DomainDiskFormat{ Type: "qcow2", }, Source: &DomainDiskSource{ File: &DomainDiskSourceFile{ File: "/tmp/image2.qcow2", }, }, BackingStore: &DomainDiskBackingStore{ Index: 3, Format: &DomainDiskFormat{ Type: "raw", }, Source: &DomainDiskSource{ File: &DomainDiskSourceFile{ File: "/tmp/image3.iso", }, }, BackingStore: &DomainDiskBackingStore{}, }, }, }, Target: &DomainDiskTarget{ Dev: "vda", Bus: "virtio", }, Serial: "fishfood", WWN: "0123456789abcdef", }, Expected: []string{ `<disk type="file" device="cdrom">`, ` <driver name="qemu" type="qcow2"></driver>`, ` <source file="/var/lib/libvirt/images/demo.qcow2"></source>`, ` <backingStore type="block" index="1">`, ` <format type="qcow2"></format>`, ` <source dev="/dev/HostVG/QEMUGuest"></source>`, ` <backingStore type="file" index="2">`, ` <format type="qcow2"></format>`, ` <source file="/tmp/image2.qcow2"></source>`, ` <backingStore type="file" index="3">`, ` <format type="raw"></format>`, ` <source file="/tmp/image3.iso"></source>`, ` <backingStore></backingStore>`, ` </backingStore>`, ` </backingStore>`, ` </backingStore>`, ` <target dev="vda" bus="virtio"></target>`, ` <serial>fishfood</serial>`, ` <wwn>0123456789abcdef</wwn>`, `</disk>`, }, }, { Object: &DomainDisk{ Device: "cdrom", Driver: &DomainDiskDriver{ Name: "qemu", Type: "qcow2", }, Source: &DomainDiskSource{ Block: &DomainDiskSourceBlock{ Dev: "/dev/HostVG/QEMUGuest1", }, }, Mirror: &DomainDiskMirror{ Job: "copy", Ready: "yes", Source: &DomainDiskSource{ Block: &DomainDiskSourceBlock{ Dev: "/dev/HostVG/QEMUGuest1Copy", }, }, }, Target: &DomainDiskTarget{ Dev: "vda", Bus: "virtio", }, }, Expected: []string{ `<disk type="block" device="cdrom">`, ` <driver name="qemu" type="qcow2"></driver>`, ` <source dev="/dev/HostVG/QEMUGuest1"></source>`, ` <mirror type="block" job="copy" ready="yes">`, ` <source dev="/dev/HostVG/QEMUGuest1Copy"></source>`, ` </mirror>`, ` <target dev="vda" bus="virtio"></target>`, `</disk>`, }, }, { Object: &DomainDisk{ Device: "cdrom", Driver: &DomainDiskDriver{ Name: "qemu", Type: "qcow2", }, Source: &DomainDiskSource{ NVME: &DomainDiskSourceNVME{ PCI: &DomainDiskSourceNVMEPCI{ Managed: "yes", Namespace: 15, Address: &DomainAddressPCI{ Domain: &nvmeAddr.Domain, Bus: &nvmeAddr.Bus, Slot: &nvmeAddr.Slot, Function: &nvmeAddr.Function, }, }, }, }, Target: &DomainDiskTarget{ Dev: "vda", Bus: "virtio", }, }, Expected: []string{ `<disk type="nvme" device="cdrom">`, ` <driver name="qemu" type="qcow2"></driver>`, ` <source type="pci" managed="yes" namespace="15">`, ` <address domain="0x0000" bus="0x01" slot="0x03" function="0x0"></address>`, ` </source>`, ` <target dev="vda" bus="virtio"></target>`, `</disk>`, }, }, { Object: &DomainDisk{ Device: "cdrom", Driver: &DomainDiskDriver{ Name: "qemu", Type: "qcow2", }, Source: &DomainDiskSource{ File: &DomainDiskSourceFile{ File: "/var/lib/libvirt/images/demo.qcow2", }, }, Mirror: &DomainDiskMirror{ Job: "copy", Format: &DomainDiskFormat{ Type: "qcow2", }, Source: &DomainDiskSource{ File: &DomainDiskSourceFile{ File: "/var/lib/libvirt/images/demo-copy.qcow2", }, }, }, Target: &DomainDiskTarget{ Dev: "vda", Bus: "virtio", }, }, Expected: []string{ `<disk type="file" device="cdrom">`, ` <driver name="qemu" type="qcow2"></driver>`, ` <source file="/var/lib/libvirt/images/demo.qcow2"></source>`, ` <mirror type="file" file="/var/lib/libvirt/images/demo-copy.qcow2" format="qcow2" job="copy">`, ` <format type="qcow2"></format>`, ` <source file="/var/lib/libvirt/images/demo-copy.qcow2"></source>`, ` </mirror>`, ` <target dev="vda" bus="virtio"></target>`, `</disk>`, }, }, { Object: &DomainFilesystem{ AccessMode: "mapped", Driver: &DomainFilesystemDriver{ Type: "path", WRPolicy: "immediate", }, Source: &DomainFilesystemSource{ Mount: &DomainFilesystemSourceMount{ Dir: "/home/user/test", }, }, Target: &DomainFilesystemTarget{ Dir: "user-test-mount", }, Address: &DomainAddress{ PCI: &DomainAddressPCI{ Domain: &fsAddr.Domain, Bus: &fsAddr.Bus, Slot: &fsAddr.Slot, Function: &fsAddr.Function, }, }, }, Expected: []string{ `<filesystem type="mount" accessmode="mapped">`, ` <driver type="path" wrpolicy="immediate"></driver>`, ` <source dir="/home/user/test"></source>`, ` <target dir="user-test-mount"></target>`, ` <address type="pci" domain="0x0000" bus="0x00" slot="0x06" function="0x0"></address>`, `</filesystem>`, }, }, { Object: &DomainInterface{ MAC: &DomainInterfaceMAC{ Address: "00:11:22:33:44:55", }, Model: &DomainInterfaceModel{ Type: "virtio", }, Source: &DomainInterfaceSource{ Network: &DomainInterfaceSourceNetwork{ Network: "default", }, }, }, Expected: []string{ `<interface type="network">`, ` <mac address="00:11:22:33:44:55"></mac>`, ` <source network="default"></source>`, ` <model type="virtio"></model>`, `</interface>`, }, }, { Object: &DomainSerial{ Source: &DomainChardevSource{ Pty: &DomainChardevSourcePty{}, }, Target: &DomainSerialTarget{ Type: "isa", Port: &serialPort, Model: &DomainSerialTargetModel{ Name: "isa-serial", }, }, Log: &DomainChardevLog{ File: "/some/path", Append: "on", }, }, Expected: []string{ `<serial type="pty">`, ` <target type="isa" port="0">`, ` <model name="isa-serial"></model>`, ` </target>`, ` <log file="/some/path" append="on"></log>`, `</serial>`, }, }, { Object: &DomainParallel{ Source: &DomainChardevSource{ Pty: &DomainChardevSourcePty{}, }, Target: &DomainParallelTarget{ Type: "isa", Port: &parallelPort, }, Log: &DomainChardevLog{ File: "/some/path", Append: "on", }, }, Expected: []string{ `<parallel type="pty">`, ` <target type="isa" port="0"></target>`, ` <log file="/some/path" append="on"></log>`, `</parallel>`, }, }, { Object: &DomainConsole{ Source: &DomainChardevSource{ Pty: &DomainChardevSourcePty{}, }, Target: &DomainConsoleTarget{ Type: "virtio", Port: &serialPort, }, }, Expected: []string{ `<console type="pty">`, ` <target type="virtio" port="0"></target>`, `</console>`, }, }, { Object: &DomainSmartcard{ Host: &DomainSmartcardHost{}, Address: &DomainAddress{ CCID: &DomainAddressCCID{ Controller: &smartcardController, Slot: &smartcardSlot, }, }, }, Expected: []string{ `<smartcard mode="host">`, ` <address type="ccid" controller="0" slot="7"></address>`, `</smartcard>`, }, }, { Object: &DomainSmartcard{ Passthrough: &DomainChardevSource{ TCP: &DomainChardevSourceTCP{ Mode: "connect", Host: "localhost", Service: "12345", }, }, Protocol: &DomainChardevProtocol{ Type: "raw", }, Address: &DomainAddress{ CCID: &DomainAddressCCID{ Controller: &smartcardController, Slot: &smartcardSlot, }, }, }, Expected: []string{ `<smartcard mode="passthrough" type="tcp">`, ` <source mode="connect" host="localhost" service="12345"></source>`, ` <protocol type="raw"></protocol>`, ` <address type="ccid" controller="0" slot="7"></address>`, `</smartcard>`, }, }, { Object: &DomainSmartcard{ HostCerts: []DomainSmartcardHostCert{ DomainSmartcardHostCert{ File: "/some/cert1", }, DomainSmartcardHostCert{ File: "/some/cert2", }, DomainSmartcardHostCert{ File: "/some/cert3", }, }, Address: &DomainAddress{ CCID: &DomainAddressCCID{ Controller: &smartcardController, Slot: &smartcardSlot, }, }, }, Expected: []string{ `<smartcard mode="host-certificates">`, ` <certificate>/some/cert1</certificate>`, ` <certificate>/some/cert2</certificate>`, ` <certificate>/some/cert3</certificate>`, ` <address type="ccid" controller="0" slot="7"></address>`, `</smartcard>`, }, }, { Object: &DomainTPM{ Model: "tpm-tis", Backend: &DomainTPMBackend{ Passthrough: &DomainTPMBackendPassthrough{ Device: &DomainTPMBackendDevice{ Path: "/dev/tpm0", }, }, }, }, Expected: []string{ `<tpm model="tpm-tis">`, ` <backend type="passthrough">`, ` <device path="/dev/tpm0"></device>`, ` </backend>`, `</tpm>`, }, }, { Object: &DomainShmem{ Name: "demo", Size: &DomainShmemSize{ Value: 1, Unit: "GiB", }, Model: &DomainShmemModel{ Type: "ivshmem-doorbell", }, Server: &DomainShmemServer{ Path: "/some/server", }, MSI: &DomainShmemMSI{ Enabled: "yes", Vectors: 5, IOEventFD: "yes", }, }, Expected: []string{ `<shmem name="demo">`, ` <size unit="GiB">1</size>`, ` <model type="ivshmem-doorbell"></model>`, ` <server path="/some/server"></server>`, ` <msi enabled="yes" vectors="5" ioeventfd="yes"></msi>`, `</shmem>`, }, }, { Object: &DomainInput{ Type: "tablet", Bus: "usb", Address: &DomainAddress{ USB: &DomainAddressUSB{ Bus: &tabletBus, Port: tabletPort, }, }, }, Expected: []string{ `<input type="tablet" bus="usb">`, ` <address type="usb" bus="0" port="1.1"></address>`, `</input>`, }, }, { Object: &DomainVideo{ Driver: &DomainVideoDriver{ VGAConf: "io", }, Model: DomainVideoModel{ Type: "cirrus", Heads: 1, Ram: 4096, VRam: 8192, VRam64: 8192, VGAMem: 256, Primary: "yes", Accel: &DomainVideoAccel{ Accel3D: "yes", Accel2D: "no", }, }, Address: &DomainAddress{ PCI: &DomainAddressPCI{ Domain: &videoAddr.Domain, Bus: &videoAddr.Bus, Slot: &videoAddr.Slot, Function: &videoAddr.Function, MultiFunction: "on", }, }, }, Expected: []string{ `<video>`, ` <model type="cirrus" heads="1" ram="4096" vram="8192" vram64="8192" vgamem="256" primary="yes">`, ` <acceleration accel3d="yes" accel2d="no"></acceleration>`, ` </model>`, ` <driver vgaconf="io"></driver>`, ` <address type="pci" domain="0x0000" bus="0x00" slot="0x05" function="0x0" multifunction="on"></address>`, `</video>`, }, }, { Object: &DomainChannel{ Source: &DomainChardevSource{ Pty: &DomainChardevSourcePty{}, }, Target: &DomainChannelTarget{ VirtIO: &DomainChannelTargetVirtIO{ Name: "org.redhat.spice", State: "connected", }, }, }, Expected: []string{ `<channel type="pty">`, ` <target type="virtio" name="org.redhat.spice" state="connected"></target>`, `</channel>`, }, }, { Object: &DomainChannel{ Source: &DomainChardevSource{ Pty: &DomainChardevSourcePty{}, }, Target: &DomainChannelTarget{ Xen: &DomainChannelTargetXen{ Name: "org.redhat.spice", State: "connected", }, }, }, Expected: []string{ `<channel type="pty">`, ` <target type="xen" name="org.redhat.spice" state="connected"></target>`, `</channel>`, }, }, { Object: &DomainRedirDev{ Bus: "usb", Source: &DomainChardevSource{ SpiceVMC: &DomainChardevSourceSpiceVMC{}, }, Address: &DomainAddress{ USB: &DomainAddressUSB{ Bus: &redirBus, Port: redirPort, }, }, }, Expected: []string{ `<redirdev type="spicevmc" bus="usb">`, ` <address type="usb" bus="0" port="3"></address>`, `</redirdev>`, }, }, { Object: &DomainRedirDev{ Bus: "usb", Source: &DomainChardevSource{ TCP: &DomainChardevSourceTCP{ Mode: "connect", Host: "localhost", Service: "1234", }, }, Protocol: &DomainChardevProtocol{ Type: "raw", }, Boot: &DomainDeviceBoot{ Order: 1, }, Address: &DomainAddress{ USB: &DomainAddressUSB{ Bus: &redirBus, Port: redirPort, }, }, }, Expected: []string{ `<redirdev type="tcp" bus="usb">`, ` <source mode="connect" host="localhost" service="1234"></source>`, ` <protocol type="raw"></protocol>`, ` <boot order="1"></boot>`, ` <address type="usb" bus="0" port="3"></address>`, `</redirdev>`, }, }, { Object: &DomainChannel{ Source: &DomainChardevSource{ Pty: &DomainChardevSourcePty{}, }, Target: &DomainChannelTarget{ GuestFWD: &DomainChannelTargetGuestFWD{ Address: "192.168.1.1", Port: "123", }, }, }, Expected: []string{ `<channel type="pty">`, ` <target type="guestfwd" address="192.168.1.1" port="123"></target>`, `</channel>`, }, }, { Object: &Domain{ Name: "demo", Devices: &DomainDeviceList{ Graphics: []DomainGraphic{ DomainGraphic{ Spice: &DomainGraphicSpice{ Port: 5903, TLSPort: 5904, AutoPort: "no", Listen: "127.0.0.1", DefaultMode: "secure", Listeners: []DomainGraphicListener{ DomainGraphicListener{ Address: &DomainGraphicListenerAddress{ Address: "127.0.0.1", }, }, }, Channel: []DomainGraphicSpiceChannel{ DomainGraphicSpiceChannel{ Name: "main", Mode: "secure", }, DomainGraphicSpiceChannel{ Name: "inputs", Mode: "insecure", }, }, Image: &DomainGraphicSpiceImage{ Compression: "auto_glz", }, JPEG: &DomainGraphicSpiceJPEG{ Compression: "auto", }, ZLib: &DomainGraphicSpiceZLib{ Compression: "auto", }, Playback: &DomainGraphicSpicePlayback{ Compression: "on", }, Streaming: &DomainGraphicSpiceStreaming{ Mode: "filter", }, ClipBoard: &DomainGraphicSpiceClipBoard{ CopyPaste: "no", }, FileTransfer: &DomainGraphicSpiceFileTransfer{ Enable: "no", }, }, }, }, }, }, Expected: []string{ `<domain>`, ` <name>demo</name>`, ` <devices>`, ` <graphics type="spice" port="5903" tlsPort="5904" autoport="no" listen="127.0.0.1" defaultMode="secure">`, ` <listen type="address" address="127.0.0.1"></listen>`, ` <channel name="main" mode="secure"></channel>`, ` <channel name="inputs" mode="insecure"></channel>`, ` <image compression="auto_glz"></image>`, ` <jpeg compression="auto"></jpeg>`, ` <zlib compression="auto"></zlib>`, ` <playback compression="on"></playback>`, ` <streaming mode="filter"></streaming>`, ` <clipboard copypaste="no"></clipboard>`, ` <filetransfer enable="no"></filetransfer>`, ` </graphics>`, ` </devices>`, `</domain>`, }, }, { Object: &Domain{ Name: "demo", Devices: &DomainDeviceList{ Graphics: []DomainGraphic{ DomainGraphic{ VNC: &DomainGraphicVNC{ Port: 5903, AutoPort: "no", Listeners: []DomainGraphicListener{ DomainGraphicListener{}, }, }, }, }, }, }, Expected: []string{ `<domain>`, ` <name>demo</name>`, ` <devices>`, ` <graphics type="vnc" port="5903" autoport="no">`, ` <listen type="none"></listen>`, ` </graphics>`, ` </devices>`, `</domain>`, }, }, { Object: &DomainMemBalloon{ Model: "virtio", AutoDeflate: "on", Stats: &DomainMemBalloonStats{ Period: 10, }, Address: &DomainAddress{ PCI: &DomainAddressPCI{ Domain: &balloonAddr.Domain, Bus: &balloonAddr.Bus, Slot: &balloonAddr.Slot, Function: &balloonAddr.Function, }, }, }, Expected: []string{ `<memballoon model="virtio" autodeflate="on">`, ` <stats period="10"></stats>`, ` <address type="pci" domain="0x0000" bus="0x00" slot="0x07" function="0x0"></address>`, `</memballoon>`, }, }, { Object: &DomainWatchdog{ Model: "ib700", Action: "inject-nmi", Address: &DomainAddress{ PCI: &DomainAddressPCI{ Domain: &watchdogAddr.Domain, Bus: &watchdogAddr.Bus, Slot: &watchdogAddr.Slot, Function: &watchdogAddr.Function, }, }, }, Expected: []string{ `<watchdog model="ib700" action="inject-nmi">`, ` <address type="pci" domain="0x0000" bus="0x00" slot="0x08" function="0x0"></address>`, `</watchdog>`, }, }, { Object: &DomainSound{ Model: "ich6", Codec: []DomainSoundCodec{ DomainSoundCodec{ Type: "duplex", }, DomainSoundCodec{ Type: "micro", }, }, Address: &DomainAddress{ PCI: &DomainAddressPCI{ Domain: &duplexAddr.Domain, Bus: &duplexAddr.Bus, Slot: &duplexAddr.Slot, Function: &duplexAddr.Function, }, }, }, Expected: []string{ `<sound model="ich6">`, ` <codec type="duplex"></codec>`, ` <codec type="micro"></codec>`, ` <address type="pci" domain="0x0000" bus="0x00" slot="0x08" function="0x0"></address>`, `</sound>`, }, }, { Object: &DomainConsole{ Source: &DomainChardevSource{ Null: &DomainChardevSourceNull{}, }, }, Expected: []string{ `<console type="null"></console>`, }, }, { Object: &DomainConsole{ Source: &DomainChardevSource{ VC: &DomainChardevSourceVC{}, }, }, Expected: []string{ `<console type="vc"></console>`, }, }, { Object: &DomainConsole{ TTY: "/dev/pts/3", Source: &DomainChardevSource{ Pty: &DomainChardevSourcePty{ Path: "/dev/pts/3", }, }, }, Expected: []string{ `<console type="pty" tty="/dev/pts/3">`, ` <source path="/dev/pts/3"></source>`, `</console>`, }, }, { Object: &DomainConsole{ Source: &DomainChardevSource{ Dev: &DomainChardevSourceDev{ Path: "/dev/ttyS0", }, }, }, Expected: []string{ `<console type="dev">`, ` <source path="/dev/ttyS0"></source>`, `</console>`, }, }, { Object: &DomainConsole{ Source: &DomainChardevSource{ File: &DomainChardevSourceFile{ Path: "/tmp/file.log", }, }, }, Expected: []string{ `<console type="file">`, ` <source path="/tmp/file.log"></source>`, `</console>`, }, }, { Object: &DomainConsole{ Source: &DomainChardevSource{ Pipe: &DomainChardevSourcePipe{ Path: "/tmp/file.fifo", }, }, }, Expected: []string{ `<console type="pipe">`, ` <source path="/tmp/file.fifo"></source>`, `</console>`, }, }, { Object: &DomainConsole{ Source: &DomainChardevSource{ StdIO: &DomainChardevSourceStdIO{}, }, }, Expected: []string{ `<console type="stdio"></console>`, }, }, { Object: &DomainConsole{ Source: &DomainChardevSource{ UDP: &DomainChardevSourceUDP{ ConnectHost: "some.server", ConnectService: "4999", BindHost: "my.server", BindService: "5921", }, }, }, Expected: []string{ `<console type="udp">`, ` <source mode="bind" host="my.server" service="5921"></source>`, ` <source mode="connect" host="some.server" service="4999"></source>`, `</console>`, }, }, { Object: &DomainConsole{ Source: &DomainChardevSource{ TCP: &DomainChardevSourceTCP{ Mode: "connect", Host: "localhost", Service: "25", }, }, }, Expected: []string{ `<console type="tcp">`, ` <source mode="connect" host="localhost" service="25"></source>`, `</console>`, }, }, { Object: &DomainConsole{ Source: &DomainChardevSource{ UNIX: &DomainChardevSourceUNIX{ Mode: "connect", Path: "/tmp/myvm.sock", }, }, }, Expected: []string{ `<console type="unix">`, ` <source mode="connect" path="/tmp/myvm.sock"></source>`, `</console>`, }, }, { Object: &DomainConsole{ Source: &DomainChardevSource{ SpiceVMC: &DomainChardevSourceSpiceVMC{}, }, }, Expected: []string{ `<console type="spicevmc"></console>`, }, }, { Object: &DomainConsole{ Source: &DomainChardevSource{ SpicePort: &DomainChardevSourceSpicePort{ Channel: "org.qemu.console.serial.0", }, }, }, Expected: []string{ `<console type="spiceport">`, ` <source channel="org.qemu.console.serial.0"></source>`, `</console>`, }, }, { Object: &DomainConsole{ Source: &DomainChardevSource{ NMDM: &DomainChardevSourceNMDM{ Master: "/dev/nmdm0A", Slave: "/dev/nmdm0B", }, }, }, Expected: []string{ `<console type="nmdm">`, ` <source master="/dev/nmdm0A" slave="/dev/nmdm0B"></source>`, `</console>`, }, }, { Object: &DomainRNG{ Model: "virtio", Rate: &DomainRNGRate{ Period: 2000, Bytes: 1234, }, Backend: &DomainRNGBackend{ Random: &DomainRNGBackendRandom{ Device: "/dev/random", }, }, Address: &DomainAddress{ PCI: &DomainAddressPCI{ Domain: &rngAddr.Domain, Bus: &rngAddr.Bus, Slot: &rngAddr.Slot, Function: &rngAddr.Function, }, }, }, Expected: []string{ `<rng model="virtio">`, ` <rate bytes="1234" period="2000"></rate>`, ` <backend model="random">/dev/random</backend>`, ` <address type="pci" domain="0x0000" bus="0x00" slot="0x09" function="0x0"></address>`, `</rng>`, }, }, { Object: &DomainRNG{ Model: "virtio", Rate: &DomainRNGRate{ Period: 2000, Bytes: 1234, }, Backend: &DomainRNGBackend{ EGD: &DomainRNGBackendEGD{ Source: &DomainChardevSource{ UDP: &DomainChardevSourceUDP{ BindService: "1234", ConnectHost: "1.2.3.4", ConnectService: "1234", }, }, }, }, }, Expected: []string{ `<rng model="virtio">`, ` <rate bytes="1234" period="2000"></rate>`, ` <backend model="egd" type="udp">`, ` <source mode="bind" service="1234"></source>`, ` <source mode="connect" host="1.2.3.4" service="1234"></source>`, ` </backend>`, `</rng>`, }, }, { Object: &DomainHostdev{ SubsysSCSI: &DomainHostdevSubsysSCSI{ SGIO: "unfiltered", RawIO: "yes", Source: &DomainHostdevSubsysSCSISource{ Host: &DomainHostdevSubsysSCSISourceHost{ Adapter: &DomainHostdevSubsysSCSIAdapter{ Name: "scsi_host0", }, Address: &DomainAddressDrive{ Bus: &hostdevSCSI.Bus, Target: &hostdevSCSI.Target, Unit: &hostdevSCSI.Unit, }, }, }, }, Address: &DomainAddress{ Drive: &DomainAddressDrive{ Controller: &hostdevSCSI.Controller, Bus: &hostdevSCSI.Bus, Target: &hostdevSCSI.Target, Unit: &hostdevSCSI.Unit, }, }, }, Expected: []string{ `<hostdev mode="subsystem" type="scsi" sgio="unfiltered" rawio="yes">`, ` <source>`, ` <adapter name="scsi_host0"></adapter>`, ` <address bus="0" target="3" unit="0"></address>`, ` </source>`, ` <address type="drive" controller="0" bus="0" target="3" unit="0"></address>`, `</hostdev>`, }, }, { Object: &DomainHostdev{ SubsysSCSI: &DomainHostdevSubsysSCSI{ SGIO: "unfiltered", RawIO: "yes", Source: &DomainHostdevSubsysSCSISource{ ISCSI: &DomainHostdevSubsysSCSISourceISCSI{ Name: "iqn.1992-01.com.example:storage/1", Host: []DomainDiskSourceHost{ DomainDiskSourceHost{ Name: "example.org", Port: "3260", }, }, Auth: &DomainDiskAuth{ Username: "myname", Secret: &DomainDiskSecret{ Type: "iscsi", Usage: "mycluster_myname", }, }, }, }, }, Address: &DomainAddress{ Drive: &DomainAddressDrive{ Controller: &hostdevSCSI.Controller, Bus: &hostdevSCSI.Bus, Target: &hostdevSCSI.Target, Unit: &hostdevSCSI.Unit, }, }, }, Expected: []string{ `<hostdev mode="subsystem" type="scsi" sgio="unfiltered" rawio="yes">`, ` <source protocol="iscsi" name="iqn.1992-01.com.example:storage/1">`, ` <host name="example.org" port="3260"></host>`, ` <auth username="myname">`, ` <secret type="iscsi" usage="mycluster_myname"></secret>`, ` </auth>`, ` </source>`, ` <address type="drive" controller="0" bus="0" target="3" unit="0"></address>`, `</hostdev>`, }, }, { Object: &DomainHostdev{ SubsysSCSIHost: &DomainHostdevSubsysSCSIHost{ Source: &DomainHostdevSubsysSCSIHostSource{ Protocol: "vhost", WWPN: "naa.5123456789abcde0", }, }, }, Expected: []string{ `<hostdev mode="subsystem" type="scsi_host">`, ` <source protocol="vhost" wwpn="naa.5123456789abcde0"></source>`, `</hostdev>`, }, }, { Object: &DomainHostdev{ SubsysUSB: &DomainHostdevSubsysUSB{ Source: &DomainHostdevSubsysUSBSource{ Address: &DomainAddressUSB{ Bus: &usbHostBus, Device: &usbHostDevice, }, }, }, }, Expected: []string{ `<hostdev mode="subsystem" type="usb">`, ` <source>`, ` <address bus="14" device="6"></address>`, ` </source>`, `</hostdev>`, }, }, { Object: &DomainHostdev{ Managed: "yes", SubsysPCI: &DomainHostdevSubsysPCI{ Source: &DomainHostdevSubsysPCISource{ Address: &DomainAddressPCI{ Domain: &pciHostDomain, Bus: &pciHostBus, Slot: &pciHostSlot, Function: &pciHostFunction, }, }, }, }, Expected: []string{ `<hostdev mode="subsystem" type="pci" managed="yes">`, ` <source>`, ` <address domain="0x0000" bus="0x03" slot="0x0e" function="0x5"></address>`, ` </source>`, `</hostdev>`, }, }, { Object: &DomainHostdev{ SubsysMDev: &DomainHostdevSubsysMDev{ Model: "vfio-pci", Source: &DomainHostdevSubsysMDevSource{ Address: &DomainAddressMDev{ UUID: "53764d0e-85a0-42b4-af5c-2046b460b1dc", }, }, }, }, Expected: []string{ `<hostdev mode="subsystem" type="mdev" model="vfio-pci">`, ` <source>`, ` <address uuid="53764d0e-85a0-42b4-af5c-2046b460b1dc"></address>`, ` </source>`, `</hostdev>`, }, }, { Object: &DomainHostdev{ CapsStorage: &DomainHostdevCapsStorage{ Source: &DomainHostdevCapsStorageSource{ Block: "/dev/sda", }, }, }, Expected: []string{ `<hostdev mode="capabilities" type="storage">`, ` <source>`, ` <block>/dev/sda</block>`, ` </source>`, `</hostdev>`, }, }, { Object: &DomainHostdev{ CapsMisc: &DomainHostdevCapsMisc{ Source: &DomainHostdevCapsMiscSource{ Char: "/dev/kvm", }, }, }, Expected: []string{ `<hostdev mode="capabilities" type="misc">`, ` <source>`, ` <char>/dev/kvm</char>`, ` </source>`, `</hostdev>`, }, }, { Object: &DomainHostdev{ CapsNet: &DomainHostdevCapsNet{ Source: &DomainHostdevCapsNetSource{ Interface: "eth0", }, IP: []DomainIP{ DomainIP{ Address: "192.168.122.2", Family: "ipv4", }, DomainIP{ Address: "fdf8:f53e:61e4::18", Family: "ipv6", Prefix: &ipv6Prefix, }, }, Route: []DomainRoute{ DomainRoute{ Family: "ipv4", Address: "0.0.0.0", Gateway: "192.168.122.1", }, DomainRoute{ Family: "ipv6", Address: "::", Gateway: "fc00:db20:35b:7399::5", }, }, }, }, Expected: []string{ `<hostdev mode="capabilities" type="net">`, ` <source>`, ` <interface>eth0</interface>`, ` </source>`, ` <ip address="192.168.122.2" family="ipv4"></ip>`, ` <ip address="fdf8:f53e:61e4::18" family="ipv6" prefix="24"></ip>`, ` <route family="ipv4" address="0.0.0.0" gateway="192.168.122.1"></route>`, ` <route family="ipv6" address="::" gateway="fc00:db20:35b:7399::5"></route>`, `</hostdev>`, }, }, { Object: &DomainMemorydev{ Model: "dimm", Access: "private", Source: &DomainMemorydevSource{ PageSize: &DomainMemorydevSourcePagesize{ Value: 2048, Unit: "KiB", }, Path: "/tmp/nvdimm", NodeMask: "0-1", }, Target: &DomainMemorydevTarget{ Size: &DomainMemorydevTargetSize{ Value: 1, Unit: "GiB", }, Node: &DomainMemorydevTargetNode{ Value: 0, }, Label: &DomainMemorydevTargetLabel{ Size: &DomainMemorydevTargetSize{ Value: 200, Unit: "KiB", }, }, }, }, Expected: []string{ `<memory model="dimm" access="private">`, ` <source>`, ` <nodemask>0-1</nodemask>`, ` <pagesize unit="KiB">2048</pagesize>`, ` <path>/tmp/nvdimm</path>`, ` </source>`, ` <target>`, ` <size unit="GiB">1</size>`, ` <node>0</node>`, ` <label>`, ` <size unit="KiB">200</size>`, ` </label>`, ` </target>`, `</memory>`, }, }, /* Host Bootloader -- bhyve, Xen */ { Object: &Domain{ Type: "bhyve", Name: "test", Bootloader: "/usr/local/sbin/grub-bhyve", BootloaderArgs: "-r cd0 -m /tmp/test-device.map -M 1024M linuxguest", }, Expected: []string{ `<domain type="bhyve">`, ` <name>test</name>`, ` <bootloader>/usr/local/sbin/grub-bhyve</bootloader>`, ` <bootloader_args>-r cd0 -m /tmp/test-device.map -M 1024M linuxguest</bootloader_args>`, `</domain>`, }, }, { Object: &Domain{ Name: "demo", Devices: &DomainDeviceList{ Graphics: []DomainGraphic{ DomainGraphic{SDL: &DomainGraphicSDL{}}, DomainGraphic{VNC: &DomainGraphicVNC{}}, DomainGraphic{RDP: &DomainGraphicRDP{}}, DomainGraphic{Desktop: &DomainGraphicDesktop{}}, DomainGraphic{Spice: &DomainGraphicSpice{}}, }, }, }, Expected: []string{ `<domain>`, ` <name>demo</name>`, ` <devices>`, ` <graphics type="sdl"></graphics>`, ` <graphics type="vnc"></graphics>`, ` <graphics type="rdp"></graphics>`, ` <graphics type="desktop"></graphics>`, ` <graphics type="spice"></graphics>`, ` </devices>`, `</domain>`, }, }, } func TestDomain(t *testing.T) { for _, test := range domainTestData { doc, err := test.Object.Marshal() if err != nil { t.Fatal(err) } expect := strings.Join(test.Expected, "\n") if doc != expect { t.Fatal("Bad initial xml:\n", string(doc), "\n does not match\n", expect, "\n") } typ := reflect.ValueOf(test.Object).Elem().Type() newobj := reflect.New(typ) newdocobj, ok := newobj.Interface().(Document) if !ok { t.Fatalf("Could not clone %s", newobj.Interface()) } err = newdocobj.Unmarshal(expect) if err != nil { t.Fatal(err) } doc, err = newdocobj.Marshal() if err != nil { t.Fatal(err) } if doc != expect { t.Fatal("Bad roundtrip xml:\n", string(doc), "\n does not match\n", expect, "\n") } } }
arykalin/libvirt-go-xml
<|start_filename|>tensorflow/compiler/jit/encapsulate_subgraphs_pass.cc<|end_filename|> /* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/jit/encapsulate_subgraphs_pass.h" #include <functional> #include <numeric> #include "tensorflow/compiler/jit/graph_to_functiondef.h" #include "tensorflow/compiler/jit/legacy_flags/encapsulate_subgraphs_pass_flags.h" #include "tensorflow/compiler/jit/mark_for_compilation_pass.h" #include "tensorflow/compiler/tf2xla/const_analysis.h" #include "tensorflow/compiler/tf2xla/dump_graph.h" #include "tensorflow/core/common_runtime/function.h" #include "tensorflow/core/common_runtime/optimization_registry.h" #include "tensorflow/core/framework/function.h" #include "tensorflow/core/framework/graph_def_util.h" #include "tensorflow/core/framework/node_def_builder.h" #include "tensorflow/core/framework/node_def_util.h" #include "tensorflow/core/graph/algorithm.h" #include "tensorflow/core/graph/graph.h" #include "tensorflow/core/graph/tensor_id.h" #include "tensorflow/core/lib/gtl/flatset.h" #include "tensorflow/core/lib/gtl/map_util.h" #include "tensorflow/core/lib/hash/hash.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/public/session_options.h" #include "tensorflow/core/public/version.h" #include "tensorflow/core/util/device_name_utils.h" namespace tensorflow { const char* const kXlaCompiledKernelAttr = "_XlaCompiledKernel"; const char* const kXlaNumConstantArgsAttr = "_XlaNumConstantArgs"; const char* const kXlaNumResourceArgsAttr = "_XlaNumResourceArgs"; namespace { bool AreAllParentsConst(const Node& n, const gtl::FlatSet<const Node*>& runtime_const_nodes) { if (n.type_string() == "GuaranteeConst" || n.type_string() == "Const") { // If the current node is itself a cast-to-const, no need // to look at the incoming edges. return true; } bool all_parents_const = true; bool atleast_one_non_control_edge = false; for (const Edge* in : n.in_edges()) { atleast_one_non_control_edge = atleast_one_non_control_edge || !in->IsControlEdge(); if (!in->IsControlEdge() && runtime_const_nodes.count(in->src()) == 0) { all_parents_const = false; break; } } return all_parents_const && atleast_one_non_control_edge; } void MarkGuaranteedConstants( const Graph& graph, const std::vector<std::pair<Node*, Node*>>& src_arg_pairs) { gtl::FlatSet<const Node*> guaranteed_const_nodes; std::vector<Node*> srcs; srcs.reserve(src_arg_pairs.size()); for (const auto& src_arg : src_arg_pairs) { srcs.push_back(src_arg.first); } ReverseDFSFrom(graph, srcs, /*enter=*/nullptr, /*leave=*/[&guaranteed_const_nodes](Node* n) { // TODO(vinuraja): Doesn't work in the presence of loops. if (AreAllParentsConst(*n, guaranteed_const_nodes)) { guaranteed_const_nodes.insert(n); } }); for (auto& src_arg : src_arg_pairs) { if (guaranteed_const_nodes.count(src_arg.first) != 0) { VLOG(1) << "Guaranteed const found: " << src_arg.first->DebugString(); src_arg.second->AddAttr("_is_guaranteed_constant", true); } } } // A node/slot pair. // TODO(phawkins): is there a common definition of this? struct NodeSlot { NodeSlot() : node(nullptr), slot(-1) {} NodeSlot(const Node* node, int slot) : node(node), slot(slot) {} const Node* node; int slot; bool operator==(const NodeSlot& other) const { return node == other.node && slot == other.slot; } struct Hasher { uint64 operator()(NodeSlot const& s) const { return Hash64Combine(std::hash<const Node*>()(s.node), std::hash<int>()(s.slot)); } }; struct PairHasher { uint64 operator()(std::pair<NodeSlot, NodeSlot> const& s) const { return Hash64Combine(Hasher()(s.first), Hasher()(s.second)); } }; }; class Encapsulator { public: Encapsulator(string group_attribute, Graph const* graph_in) : group_attribute_(std::move(group_attribute)), graph_in_(graph_in) {} // Find subgraphs marked with 'group_attribute', and build a new // subgraph, one for each value of 'group_attribute'. Status SplitIntoSubgraphs(); // Build a FunctionDef for each subgraph, and add it 'library'. The values of // the 'group_attribute' annotations become the function names. // If 'reuse_existing_functions' is set, use an existing function with the // same name, if any. // If 'rewrite_subgraph_fn' is set, it is applied to each subgraph before // function conversion. Status BuildFunctionDefs(const RewriteSubgraphFn& rewrite_subgraph_fn, bool reuse_existing_functions, FunctionLibraryDefinition* library); // Write a copy of the input graph to 'graph_out', where the subgraphs are // replaced with calls to the new functions. Status BuildOutputGraph(bool parallel_checking, Graph* graph_out); private: // Returns the key attribute associated with a node. Returns the empty string // if no key attribute is found. string GetFunctionNameAttr(const Node* node) const; // A subgraph of the input, all marked with a common 'group_attribute' // value. struct Subgraph { // The subgraph extracted from the input graph, suitable for being turned // into a FunctionDef. Inputs are fed by _Arg nodes, and outputs are // returned by _Retval nodes. std::unique_ptr<Graph> graph; // Which device are these nodes on? Used to assign a device to the call // node. string device; // NodeDef for the function call node. NodeDef call_node_def; // Function call node(s) in the output graph. Not owned. // If parallel_checking is enabled, 'call_node_inputs' is the function call // node to which inputs should be fed, and 'call_node_outputs' is the // parallel check op from which outputs should be read. If parallel checking // is disabled, both point to the function call node. Node* call_node_inputs; Node* call_node_outputs; // Maps from source (producer node/slot) and destination // (consumer node/slot) tensors in the input graph to _Arg numbers in // the subgraph. The source map is one-to-one, whereas the dest map may be // many-to-one. std::unordered_map<NodeSlot, int, NodeSlot::Hasher> args_by_src; std::unordered_map<NodeSlot, int, NodeSlot::Hasher> args_by_dst; // The _Arg nodes in the subgraph, in order by argument number. std::vector<Node*> args; // Map from source tensor in the input graph to result #. std::unordered_map<NodeSlot, int, NodeSlot::Hasher> results; }; // Builds a ParallelCheck op that compares the output of the original subgraph // with the encapsulated subgraph. Status BuildParallelCheckOp( const std::unordered_map<const Node*, Node*>& node_images, const Subgraph& subgraph, Graph* graph_out, Node** parallel_check_op); const string group_attribute_; const Graph* graph_in_; std::unordered_map<string, Subgraph> subgraphs_; TF_DISALLOW_COPY_AND_ASSIGN(Encapsulator); }; // TODO(phawkins) add a canonical copy of these operator names and refactor // everything to use it. static const char* const kArgOp = "_Arg"; static const char* const kRetValOp = "_Retval"; // Returns the function name attached to 'node', or the empty string if there is // none. string Encapsulator::GetFunctionNameAttr(Node const* node) const { string attr; if (!GetNodeAttr(node->attrs(), group_attribute_, &attr).ok()) { attr.clear(); } return attr; } Status Encapsulator::SplitIntoSubgraphs() { Status s; // Map from input graph nodes to subgraph nodes. std::unordered_map<Node*, Node*> node_images; std::vector<std::pair<Node*, Node*>> src_arg_pairs; // Copy all marked nodes to a subgraph. Do nothing for unmarked nodes. for (Node* node : graph_in_->op_nodes()) { string func_id = GetFunctionNameAttr(node); if (func_id.empty()) continue; Subgraph& subgraph = subgraphs_[func_id]; if (!subgraph.graph) { subgraph.graph.reset(new Graph(graph_in_->op_registry())); subgraph.graph->set_versions(graph_in_->versions()); } Node* image = subgraph.graph->CopyNode(node); image->ClearAttr(group_attribute_); node_images[node] = image; if (subgraph.device.empty()) { subgraph.device = node->assigned_device_name().empty() ? node->requested_device() : node->assigned_device_name(); } } // Copy edges local to a subgraph. Add _Arg and _Retval nodes to subgraphs for // data edges that cross subgraph boundaries. for (const Edge* edge : graph_in_->edges()) { string src_func_id = GetFunctionNameAttr(edge->src()); string dst_func_id = GetFunctionNameAttr(edge->dst()); Node* src_image = gtl::FindWithDefault(node_images, edge->src(), nullptr); Node* dst_image = gtl::FindWithDefault(node_images, edge->dst(), nullptr); // Copy edges that are local to a subgraph. if (!src_func_id.empty() && src_func_id == dst_func_id) { Graph* g = subgraphs_[src_func_id].graph.get(); if (edge->IsControlEdge()) { g->AddControlEdge(src_image, dst_image); } else { g->AddEdge(src_image, edge->src_output(), dst_image, edge->dst_input()); } continue; } // Ignore cross-boundary control edges for right now. We will lift them // onto the enclosing call operators in BuildOutputGraph(). if (edge->IsControlEdge()) continue; // Add 'src' as an output of its subgraph, if applicable. if (!src_func_id.empty()) { Subgraph& src_subgraph = subgraphs_[src_func_id]; int ret_index = src_subgraph.results.size(); if (src_subgraph.results .emplace(NodeSlot(edge->src(), edge->src_output()), ret_index) .second) { // Create a new _Retval node DataType dtype = edge->src()->output_type(edge->src_output()); if (IsRefType(dtype)) { return errors::InvalidArgument( "Ref Tensors (e.g., Variables) are not supported: tensor ", edge->src()->name(), ":", edge->src_output()); } NodeDef ret_def; ret_def.set_op(kRetValOp); ret_def.set_name(strings::StrCat(edge->src()->name(), "_", edge->src_output(), "_retval")); AddNodeAttr("T", dtype, &ret_def); AddNodeAttr("index", ret_index, &ret_def); Node* ret = src_subgraph.graph->AddNode(ret_def, &s); if (!s.ok()) return s; // Add an edge from 'src' to _Retval. src_subgraph.graph->AddEdge(src_image, edge->src_output(), ret, 0); } } // Add 'dst' as an input of its subgraph, if applicable. if (!dst_func_id.empty()) { Subgraph& dst_subgraph = subgraphs_[dst_func_id]; // Create an _Arg node for this tensor, if none exists yet. std::unordered_map<NodeSlot, int, NodeSlot::Hasher>::iterator iter; bool inserted; std::tie(iter, inserted) = dst_subgraph.args_by_src.emplace( NodeSlot(edge->src(), edge->src_output()), dst_subgraph.args.size()); int arg_index = iter->second; if (inserted) { // This is the first time we have seen this tensor. Create an _Arg node. DataType dtype = edge->dst()->input_type(edge->dst_input()); if (IsRefType(dtype)) { return errors::InvalidArgument( "Ref Tensors (e.g., Variables) are not supported: tensor ", edge->src()->name(), ":", edge->src_output()); } NodeDef arg_def; NodeDefBuilder builder(strings::StrCat(edge->src()->name(), "_", edge->src_output(), "_arg"), kArgOp); builder.Attr("T", dtype); builder.Attr("index", arg_index); s = builder.Finalize(&arg_def); if (!s.ok()) return s; Node* arg = dst_subgraph.graph->AddNode(arg_def, &s); if (!s.ok()) return s; src_arg_pairs.push_back({edge->src(), arg}); dst_subgraph.args.push_back(arg); } // Add an edge from the _Arg node to 'dst' in the subgraph. dst_subgraph.args_by_dst[NodeSlot(edge->dst(), edge->dst_input())] = arg_index; dst_subgraph.graph->AddEdge(dst_subgraph.args[arg_index], 0, dst_image, edge->dst_input()); } } MarkGuaranteedConstants(*graph_in_, src_arg_pairs); for (auto& entry : subgraphs_) { FixupSourceAndSinkEdges(entry.second.graph.get()); } return s; } Status Encapsulator::BuildFunctionDefs( const RewriteSubgraphFn& rewrite_subgraph_fn, bool reuse_existing_functions, FunctionLibraryDefinition* library) { // For each subgraph, build a FunctionDef. for (auto& subgraph_entry : subgraphs_) { string name = subgraph_entry.first; Subgraph& subgraph = subgraph_entry.second; subgraph.call_node_def.set_op(name); subgraph.call_node_def.set_name(name); subgraph.call_node_def.set_device(subgraph.device); if (rewrite_subgraph_fn) { // Initialize the input and output permutations to the identity. std::vector<int> input_permutation(subgraph.args_by_src.size()); std::iota(input_permutation.begin(), input_permutation.end(), 0); std::vector<int> output_permutation(subgraph.results.size()); std::iota(output_permutation.begin(), output_permutation.end(), 0); TF_RETURN_IF_ERROR( rewrite_subgraph_fn(&subgraph.graph, &input_permutation, &output_permutation, &subgraph.call_node_def)); // Apply the input/output permutations to the 'args_by_...' and 'results' // mappings in 'subgraph', so when we build edges in BuildOutputGraph() we // connect them to the right input/output positions. if (input_permutation.size() != subgraph.args_by_src.size()) { return errors::InvalidArgument("Input permutation has incorrect size."); } if (output_permutation.size() != subgraph.results.size()) { return errors::InvalidArgument( "Output permutation has incorrect size."); } for (auto& arg : subgraph.args_by_src) { arg.second = input_permutation[arg.second]; } for (auto& arg : subgraph.args_by_dst) { arg.second = input_permutation[arg.second]; } for (auto& result : subgraph.results) { result.second = output_permutation[result.second]; } name = subgraph.call_node_def.op(); } FunctionDef fdef; TF_RETURN_IF_ERROR(GraphToFunctionDef(*subgraph.graph, name, &fdef)); if (VLOG_IS_ON(1)) { VLOG(2) << "Build function def " << name; dump_graph::DumpGraphToFile( strings::StrCat("encapsulate_fdef_graph_", name), *subgraph.graph, library); dump_graph::DumpFunctionDefToFile( strings::StrCat("encapsulate_fdef_", name), fdef); } if (!reuse_existing_functions || library->Find(name) == nullptr) { TF_RETURN_IF_ERROR(library->AddFunctionDef(fdef)); } } return Status::OK(); } Status Encapsulator::BuildParallelCheckOp( const std::unordered_map<const Node*, Node*>& node_images, const Encapsulator::Subgraph& subgraph, Graph* graph_out, Node** parallel_check_op) { // Build an index mapping output positions to node/slot pairs in the // original graph. std::vector<NodeSlot> results_by_num(subgraph.results.size()); for (const auto& entry : subgraph.results) { results_by_num[entry.second] = entry.first; } // Build a parallel check NodeDef. int num_results = results_by_num.size(); std::vector<DataType> result_dtypes(num_results); std::vector<NodeDefBuilder::NodeOut> expected_outputs(num_results); std::vector<NodeDefBuilder::NodeOut> actual_outputs(num_results); for (int i = 0; i < num_results; ++i) { const NodeSlot& node_slot = results_by_num[i]; result_dtypes[i] = node_slot.node->output_type(node_slot.slot); expected_outputs[i] = NodeDefBuilder::NodeOut(node_images.at(node_slot.node)->name(), node_slot.slot, result_dtypes[i]); actual_outputs[i] = NodeDefBuilder::NodeOut(subgraph.call_node_def.name(), i, result_dtypes[i]); } // Assign the parallel check op to a CPU on the same task as the cluster it is // checking. string device, dummy; if (!DeviceNameUtils::SplitDeviceName( subgraph.call_node_inputs->assigned_device_name(), &device, &dummy)) { return errors::InvalidArgument("Could not parse device name"); } strings::StrAppend(&device, "/cpu:0"); NodeDef check_def; TF_RETURN_IF_ERROR( NodeDefBuilder(graph_out->NewName(strings::StrCat( subgraph.call_node_def.name(), "_parallel_check")), "ParallelCheck") .Device(device) .Attr("T", result_dtypes) .Input(expected_outputs) .Input(actual_outputs) .Finalize(&check_def)); Status s; Node* check_op = graph_out->AddNode(check_def, &s); if (!s.ok()) return s; check_op->set_assigned_device_name(device); // TODO(phawkins): it seems redundant to call AddEdge as well as // pass Inputs to the NodeDefBuilder, but I have been unable to find a // way to avoid it. for (int i = 0; i < num_results; ++i) { const NodeSlot& node_slot = results_by_num[i]; graph_out->AddEdge(node_images.at(node_slot.node), node_slot.slot, check_op, i); graph_out->AddEdge(subgraph.call_node_inputs, i, check_op, num_results + i); } *parallel_check_op = check_op; return Status::OK(); } Status Encapsulator::BuildOutputGraph(bool parallel_checking, Graph* graph_out) { Status s; // Map from nodes in the input graph to nodes in the output graph. std::unordered_map<const Node*, Node*> node_images; // Copy all unmarked nodes to the output graph. for (Node* node : graph_in_->op_nodes()) { string func_id = GetFunctionNameAttr(node); // Don't copy nodes that going to be encapsulated, unless parallel checking // is enabled. if (!func_id.empty() && !parallel_checking) continue; Node* image = graph_out->CopyNode(node); node_images[node] = image; } node_images[graph_in_->source_node()] = graph_out->source_node(); node_images[graph_in_->sink_node()] = graph_out->sink_node(); // Add function call nodes for each subgraph. for (auto& subgraph_entry : subgraphs_) { Subgraph& subgraph = subgraph_entry.second; subgraph.call_node_inputs = graph_out->AddNode(subgraph.call_node_def, &s); if (!s.ok()) return s; // Copy the assigned device and the key_annotation over. subgraph.call_node_inputs->set_assigned_device_name(subgraph.device); subgraph.call_node_outputs = subgraph.call_node_inputs; if (parallel_checking) { TF_RETURN_IF_ERROR(BuildParallelCheckOp(node_images, subgraph, graph_out, &subgraph.call_node_outputs)); } } // Set of edges already added to the output graph, represented as (src, dst) // pairs. We use the set to deduplicate edges; multiple edges in the input // graph may map to one edge in the output graph. std::unordered_set<std::pair<NodeSlot, NodeSlot>, NodeSlot::PairHasher> edges_added; // Add edges to the graph_out graph. for (const Edge* edge : graph_in_->edges()) { string src_func_id = GetFunctionNameAttr(edge->src()); string dst_func_id = GetFunctionNameAttr(edge->dst()); // Ignore edges that are strictly contained within one subgraph, unless // we are constructing parallel check graphs. if (!src_func_id.empty() && src_func_id == dst_func_id) { if (parallel_checking) { Node* src_image = node_images.at(edge->src()); Node* dst_image = node_images.at(edge->dst()); if (edge->IsControlEdge()) { graph_out->AddControlEdge(src_image, dst_image); } else { graph_out->AddEdge(src_image, edge->src_output(), dst_image, edge->dst_input()); } } continue; } // We have an edge that crosses a cluster boundary. Node* src_image = src_func_id.empty() ? node_images.at(edge->src()) : subgraphs_.at(src_func_id).call_node_outputs; Node* dst_image = dst_func_id.empty() ? node_images.at(edge->dst()) : subgraphs_.at(dst_func_id).call_node_inputs; // Copy control edges. Lift control edges onto the enclosing call operator. if (edge->IsControlEdge()) { // Add the control edge, if we have not already added it. if (edges_added.emplace(NodeSlot(src_image, -1), NodeSlot(dst_image, -1)) .second) { graph_out->AddControlEdge(src_image, dst_image); } // If parallel checking is enabled, also add a control edge to the // corresponding parallel check op. if (parallel_checking) { graph_out->AddControlEdge(src_image, node_images.at(edge->dst())); } continue; } int src_output = edge->src_output(); if (!src_func_id.empty()) { // 'src' is in a subgraph. Use the corresponding call output instead. const Subgraph& src_subgraph = subgraphs_.at(src_func_id); src_output = src_subgraph.results.at(NodeSlot(edge->src(), edge->src_output())); } int dst_input = edge->dst_input(); if (!dst_func_id.empty()) { // 'dst' is in a subgraph. Use the corresponding call input instead. const Subgraph& dst_subgraph = subgraphs_.at(dst_func_id); dst_input = dst_subgraph.args_by_dst.at(NodeSlot(edge->dst(), edge->dst_input())); // If we are parallel checking, also feed the tensor as an input to the // corresponding parallel check subgraph. if (parallel_checking) { graph_out->AddEdge(src_image, src_output, node_images.at(edge->dst()), edge->dst_input()); } } // Add the edge, if we have not already added it. if (edges_added .emplace(NodeSlot(src_image, src_output), NodeSlot(dst_image, dst_input)) .second) { graph_out->AddEdge(src_image, src_output, dst_image, dst_input); } } return s; } } // anonymous namespace Status EncapsulateSubgraphsInFunctions( string group_attribute, const Graph& graph_in, const RewriteSubgraphFn& rewrite_subgraph_fn, bool parallel_checking, bool reuse_existing_functions, std::unique_ptr<Graph>* graph_out, FunctionLibraryDefinition* library) { Status s; Encapsulator encapsulator(std::move(group_attribute), &graph_in); s = encapsulator.SplitIntoSubgraphs(); if (!s.ok()) return s; s = encapsulator.BuildFunctionDefs(rewrite_subgraph_fn, reuse_existing_functions, library); if (!s.ok()) return s; std::unique_ptr<Graph> out(new Graph(library)); out->set_versions(graph_in.versions()); s = encapsulator.BuildOutputGraph(parallel_checking, out.get()); if (!s.ok()) return s; *graph_out = std::move(out); return s; } // Finds the types of the _Arg nodes, indexed by position. static Status GetArgTypes(const Graph& graph, DataTypeVector* types) { for (Node* n : graph.op_nodes()) { if (n->type_string() == kArgOp) { int index; TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), "index", &index)); if (index < 0 || index >= types->size()) { return errors::InvalidArgument("Invalid argument number"); } (*types)[index] = n->output_type(0); } } return Status::OK(); } // Renumber the indices of _Arg nodes in a graph, according to // 'permutation' that maps old indices to new indices. static Status RenumberArguments(Graph* graph, const std::vector<int>& permutation) { for (Node* n : graph->op_nodes()) { if (n->type_string() == kArgOp) { int index; TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), "index", &index)); if (index < 0 || index >= permutation.size()) { return errors::InvalidArgument("Invalid argument number"); } n->AddAttr("index", permutation[index]); } } return Status::OK(); } Status EncapsulateSubgraphsPass::Run( const GraphOptimizationPassOptions& options) { VLOG(1) << "EncapsulateSubgraphsPass::Run"; legacy_flags::EncapsulateSubgraphsPassFlags* flags = legacy_flags::GetEncapsulateSubgraphsPassFlags(); if (VLOG_IS_ON(1)) { dump_graph::DumpGraphToFile("before_encapsulate_subgraphs", **options.graph, options.flib_def); } std::unique_ptr<Graph> graph_out; FunctionLibraryDefinition* const library = options.flib_def; OptimizerOptions opts; std::unique_ptr<ProcessFunctionLibraryRuntime> pflr( new ProcessFunctionLibraryRuntime(nullptr, options.session_options->env, TF_GRAPH_DEF_VERSION, library, opts)); FunctionLibraryRuntime* flr = pflr->GetFLR(ProcessFunctionLibraryRuntime::kDefaultFLRDevice); auto rewrite_subgraph = [flr](std::unique_ptr<Graph>* subgraph, std::vector<int>* input_permutation, std::vector<int>* output_permutation, NodeDef* node) { // Optimize the subgraph. OptimizeGraph(flr, subgraph); const int num_args = input_permutation->size(); std::vector<bool> const_args(num_args); TF_RETURN_IF_ERROR(BackwardsConstAnalysis(**subgraph, &const_args)); DataTypeVector arg_types(num_args); TF_RETURN_IF_ERROR(GetArgTypes(**subgraph, &arg_types)); // Compute a permutation of the arguments such that the constant arguments // are first. const int num_consts = std::count(const_args.begin(), const_args.end(), true); const int num_resources = std::count(arg_types.begin(), arg_types.end(), DT_RESOURCE); const int num_nonconsts = num_args - num_resources - num_consts; if (num_nonconsts < 0) { return errors::Internal("num_nonconsts should be >= 0, was ", num_nonconsts); } int const_pos = 0; int arg_pos = num_consts; int resource_pos = num_consts + num_nonconsts; for (int i = 0; i < num_args; ++i) { if (const_args[i]) { if (arg_types[i] == DT_RESOURCE) { return errors::Internal( "Resource arguments cannot be constant (argument ", i, ")"); } (*input_permutation)[i] = const_pos; ++const_pos; } else if (arg_types[i] == DT_RESOURCE) { (*input_permutation)[i] = resource_pos; ++resource_pos; } else { (*input_permutation)[i] = arg_pos; ++arg_pos; } } // Renumber argument nodes in the graph. TF_RETURN_IF_ERROR(RenumberArguments(subgraph->get(), *input_permutation)); // TODO(phawkins): add a forward is-constant analysis, similarly split // outputs into host-memory constants and device-memory non-constants. AddNodeAttr(kXlaCompiledKernelAttr, true, node); AddNodeAttr(kXlaNumConstantArgsAttr, num_consts, node); AddNodeAttr(kXlaNumResourceArgsAttr, num_resources, node); return Status::OK(); }; TF_RETURN_IF_ERROR(EncapsulateSubgraphsInFunctions( kXlaClusterAttr, **options.graph, rewrite_subgraph, flags->tf_xla_parallel_checking, /*reuse_existing_functions=*/false, &graph_out, library)); if (VLOG_IS_ON(1)) { dump_graph::DumpGraphToFile("after_encapsulate_subgraphs", *graph_out, options.flib_def); } *options.graph = std::move(graph_out); return Status::OK(); } bool IsXlaCompiledKernel(const Node& node) { bool is_compiled = false; bool has_compilation_attr = GetNodeAttr(node.attrs(), kXlaCompiledKernelAttr, &is_compiled).ok() && is_compiled; return has_compilation_attr ? is_compiled : false; } } // namespace tensorflow <|start_filename|>tensorflow/compiler/xla/service/shaped_buffer.h<|end_filename|> /* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_COMPILER_XLA_SERVICE_SHAPED_BUFFER_H_ #define TENSORFLOW_COMPILER_XLA_SERVICE_SHAPED_BUFFER_H_ #include <memory> #include <ostream> #include <string> #include "tensorflow/compiler/xla/service/device_memory_allocator.h" #include "tensorflow/compiler/xla/shape_tree.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #include "tensorflow/core/lib/gtl/array_slice.h" #include "tensorflow/core/platform/stream_executor_no_cuda.h" #include "tensorflow/core/platform/types.h" namespace xla { // Class which encapsulates a buffer or set of buffers containing data of a // particular XLA shape. Used for zero-copy execution interface for a // XLA client running in the same process as the service (LocalClient), class ShapedBuffer { public: // Convenience method which creates a ShapedBuffer of array shape (not a // tuple). Its single buffer pointer is set to the given value "buffer". The // given buffer must be large enough to store the given shape as given by // ShapeUtil::ByteSizeOf. static StatusOr<std::unique_ptr<ShapedBuffer>> MakeArrayShapedBuffer( const Shape& shape, const perftools::gputools::Platform* platform, int device_ordinal, const perftools::gputools::DeviceMemoryBase& buffer); // Return a newly allocated ShapedBuffer of an arbitrary shape. Array buffers // (leaves in the shape) are allocated and uninitialized. Tuple buffers (if // any) are allocated and initialized to the backend-specific representation // of an array of pointers to the tuple elements. static StatusOr<std::unique_ptr<ShapedBuffer>> Allocate( const Shape& shape, DeviceMemoryAllocator* allocator, int device_ordinal, const std::function<int64(const Shape&)>& shape_size_fn); ShapedBuffer(const Shape& shape, const perftools::gputools::Platform* platform, int device_ordinal); const Shape& shape() const { return shape_; } const perftools::gputools::Platform* platform() const { return platform_; } int device_ordinal() const { return device_ordinal_; } // Returns the buffer at the given shape index where index is defined as in // ShapeUtil::GetSubshape. const perftools::gputools::DeviceMemoryBase& buffer( const ShapeIndex& index) const; perftools::gputools::DeviceMemoryBase* mutable_buffer( const ShapeIndex& index); // Returns the underlying structure which stores the buffer pointers. const std::vector<perftools::gputools::DeviceMemoryBase>& buffers() const { return buffers_; } std::vector<perftools::gputools::DeviceMemoryBase>* mutable_buffers() { return &buffers_; } // Returns the tree of indices which map to buffer pointers. const ShapeTree<size_t>& shape_index_to_buffer_entry() const { return shape_index_to_buffer_entry_; } ShapeTree<size_t>* mutable_shape_index_to_buffer_entry() { return &shape_index_to_buffer_entry_; } // Set all device memory pointers in the object to null. void clear(); // Adds a new buffer at the given shape index. void AddBufferAtIndex(const perftools::gputools::DeviceMemoryBase& buffer, const ShapeIndex& shape_index); string ToString() const; protected: // The shape of the device buffer with layout. const Shape shape_; // The platform the memory is allocated on. const perftools::gputools::Platform* platform_; // The device the memory is allocated on. const int device_ordinal_; // The list of DeviceMemoryBase pointers representing this shape. // Note that there can be a many to one relationship between tuple elements // and buffers. To account for this, shape_index_to_buffer_entry_ allows us // to make from a position in a shape to an index into this list. std::vector<perftools::gputools::DeviceMemoryBase> buffers_; // The tree of indices into buffers_. ShapeTree<size_t> shape_index_to_buffer_entry_; }; std::ostream& operator<<(std::ostream& out, const ShapedBuffer& buffer); // ShapedBuffer derived class which allocates all internal buffers on // construction and deallocates the memory when the object is // destructed. class ScopedShapedBuffer : public ShapedBuffer { public: // Identical to ShapedBuffer::Allocate. static StatusOr<std::unique_ptr<ScopedShapedBuffer>> Allocate( const Shape& shape, DeviceMemoryAllocator* allocator, int device_ordinal, const std::function<int64(const Shape&)>& shape_size_fn); // Takes a ShapedBuffer and returns a ScopedShapedBuffer which manages the // deallocation of the device memory held in the shaped buffer. All device // memory pointers in the given ShapedBuffer are set to null. static StatusOr<std::unique_ptr<ScopedShapedBuffer>> MakeScoped( ShapedBuffer* shaped_buffer, DeviceMemoryAllocator* allocator); // Return the allocator used to allocate the device memory held in this // ScopedShapedBuffer. DeviceMemoryAllocator* memory_allocator() const { return allocator_; } // Release all device memory owned by this ScopedShapedBuffer and return the // device memory pointers in the form of a ShapedBuffer. Device memory // pointers in this ScopedShapedBuffer object are set to null. This method is // analogous to std::unique_ptr::release(). std::unique_ptr<ShapedBuffer> release(); // All buffers in the shape are deallocated on destruction. virtual ~ScopedShapedBuffer(); protected: ScopedShapedBuffer(const Shape& shape, DeviceMemoryAllocator* allocator, int device_ordinal); ScopedShapedBuffer(const ScopedShapedBuffer&) = delete; void operator=(const ScopedShapedBuffer&) = delete; DeviceMemoryAllocator* allocator_; }; } // namespace xla #endif // TENSORFLOW_COMPILER_XLA_SERVICE_SHAPED_BUFFER_H_ <|start_filename|>tensorflow/core/lib/math/math_util.h<|end_filename|> /* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_LIB_MATH_MATH_UTIL_H_ #define TENSORFLOW_LIB_MATH_MATH_UTIL_H_ #include <type_traits> #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { class MathUtil { public: // ---------------------------------------------------------------------- // CeilOfRatio<IntegralType> // FloorOfRatio<IntegralType> // Returns the ceil (resp. floor) of the ratio of two integers. // // * IntegralType: any integral type, whether signed or not. // * numerator: any integer: positive, negative, or zero. // * denominator: a non-zero integer, positive or negative. // // This implementation is correct, meaning there is never any precision loss, // and there is never an overflow. However, if the type is signed, having // numerator == MathLimits<IntegralType>::kMin and denominator == -1 is not a // valid input, because kMin has a greater absolute value than kMax. // // Input validity is DCHECKed. When not in debug mode, invalid inputs raise // SIGFPE. // // This method has been designed and tested so that it should always be // preferred to alternatives. Indeed, there exist popular recipes to compute // the result, such as casting to double, but they are in general incorrect. // In cases where an alternative technique is correct, performance measurement // showed the provided implementation is faster. template <typename IntegralType> static IntegralType CeilOfRatio(IntegralType numerator, IntegralType denominator) { return CeilOrFloorOfRatio<IntegralType, true>(numerator, denominator); } template <typename IntegralType> static IntegralType FloorOfRatio(IntegralType numerator, IntegralType denominator) { return CeilOrFloorOfRatio<IntegralType, false>(numerator, denominator); } template <typename IntegralType, bool ceil> static IntegralType CeilOrFloorOfRatio(IntegralType numerator, IntegralType denominator); template <typename IntegralType> static IntegralType GCD(IntegralType x, IntegralType y); }; // ---- CeilOrFloorOfRatio ---- // This is a branching-free, cast-to-double-free implementation. // // Casting to double is in general incorrect because of loss of precision // when casting an int64 into a double. // // There's a bunch of 'recipes' to compute a integer ceil (or floor) on the web, // and most of them are incorrect. template <typename IntegralType, bool ceil> IntegralType MathUtil::CeilOrFloorOfRatio(IntegralType numerator, IntegralType denominator) { DCHECK_NE(0, denominator) << "Division by zero is not supported."; const IntegralType rounded_toward_zero = numerator / denominator; const IntegralType intermediate_product = rounded_toward_zero * denominator; if (ceil) { // Compile-time condition: not an actual branching // When rounded_toward_zero is negative, then an adjustment is never needed: // the real ratio is negative, and so rounded toward zero is the ceil. // When rounded_toward_zero is non-negative, an adjustment is needed if the // sign of the difference numerator - intermediate_product is the same as // the sign of the denominator. // // // Using a bool and then a static_cast to IntegralType is not strictly // necessary, but it makes the code clear, and anyway the compiler should // get rid of it. const bool needs_adjustment = (rounded_toward_zero >= 0) && ((denominator > 0 && numerator > intermediate_product) || (denominator < 0 && numerator < intermediate_product)); const IntegralType adjustment = static_cast<IntegralType>(needs_adjustment); const IntegralType ceil_of_ratio = rounded_toward_zero + adjustment; return ceil_of_ratio; } else { // Floor case: symmetrical to the previous one const bool needs_adjustment = (rounded_toward_zero <= 0) && ((denominator > 0 && numerator < intermediate_product) || (denominator < 0 && numerator > intermediate_product)); const IntegralType adjustment = static_cast<IntegralType>(needs_adjustment); const IntegralType floor_of_ratio = rounded_toward_zero - adjustment; return floor_of_ratio; } } template <typename IntegralType> IntegralType MathUtil::GCD(IntegralType a, IntegralType b) { static_assert(std::is_unsigned<IntegralType>::value, "signed GCD not supported!"); while (b != 0) { IntegralType r = a % b; a = b; b = r; } return a; } } // namespace tensorflow #endif // TENSORFLOW_LIB_MATH_MATH_UTIL_H_ <|start_filename|>tensorflow/core/lib/math/math_util_test.cc<|end_filename|> /* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/lib/math/math_util.h" #include <vector> #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/test.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { // Number of arguments for each test of the CeilOrRatio method const int kNumTestArguments = 4; template <typename IntegralType, typename TestDataType> void TestCeilOfRatio(const TestDataType test_data[][kNumTestArguments], int num_tests) { for (int i = 0; i < num_tests; ++i) { const IntegralType numerator = test_data[i][0]; const IntegralType denominator = test_data[i][1]; const IntegralType expected_floor = test_data[i][2]; const IntegralType expected_ceil = test_data[i][3]; // Make sure the two ways to compute the floor return the same thing. IntegralType floor_1 = MathUtil::FloorOfRatio(numerator, denominator); IntegralType floor_2 = MathUtil::CeilOrFloorOfRatio<IntegralType, false>( numerator, denominator); EXPECT_EQ(floor_1, floor_2); EXPECT_EQ(expected_floor, floor_1) << "FloorOfRatio fails with numerator = " << numerator << ", denominator = " << denominator << " " << (8 * sizeof(IntegralType)) << " bits"; IntegralType ceil_1 = MathUtil::CeilOfRatio(numerator, denominator); IntegralType ceil_2 = MathUtil::CeilOrFloorOfRatio<IntegralType, true>( numerator, denominator); EXPECT_EQ(ceil_1, ceil_2); EXPECT_EQ(expected_ceil, ceil_1) << "CeilOfRatio fails with numerator = " << numerator << ", denominator = " << denominator << " " << (8 * sizeof(IntegralType)) << " bits"; } } template <typename UnsignedIntegralType> void TestCeilOfRatioUnsigned(uint64 kMax) { const int kNumTests = 12; const uint64 kTestData[kNumTests][kNumTestArguments] = { // Numerator | Denominator | Expected floor of ratio | Expected ceil of // ratio | // When numerator = 0, the result is always zero {0, 1, 0, 0}, {0, 2, 0, 0}, {0, kMax, 0, 0}, // Try some non-extreme cases {1, 1, 1, 1}, {5, 2, 2, 3}, // Try with huge positive numerator {kMax, 1, kMax, kMax}, {kMax, 2, kMax / 2, kMax / 2 + ((kMax % 2 != 0) ? 1 : 0)}, {kMax, 3, kMax / 3, kMax / 3 + ((kMax % 3 != 0) ? 1 : 0)}, // Try with a huge positive denominator {1, kMax, 0, 1}, {2, kMax, 0, 1}, {3, kMax, 0, 1}, // Try with a huge numerator and a huge denominator {kMax, kMax, 1, 1}, }; TestCeilOfRatio<UnsignedIntegralType, uint64>(kTestData, kNumTests); } template <typename SignedInteger> void TestCeilOfRatioSigned(int64 kMin, int64 kMax) { const int kNumTests = 30; const int64 kTestData[kNumTests][kNumTestArguments] = { // Numerator | Denominator | Expected floor of ratio | Expected ceil of // ratio | // When numerator = 0, the result is always zero {0, 1, 0, 0}, {0, -1, 0, 0}, {0, 2, 0, 0}, {0, kMin, 0, 0}, {0, kMax, 0, 0}, // Try all four combinations of 1 and -1 {1, 1, 1, 1}, {-1, 1, -1, -1}, {1, -1, -1, -1}, {-1, -1, 1, 1}, // Try all four combinations of +/-5 divided by +/- 2 {5, 2, 2, 3}, {-5, 2, -3, -2}, {5, -2, -3, -2}, {-5, -2, 2, 3}, // Try with huge positive numerator {kMax, 1, kMax, kMax}, {kMax, -1, -kMax, -kMax}, {kMax, 2, kMax / 2, kMax / 2 + ((kMax % 2 != 0) ? 1 : 0)}, {kMax, 3, kMax / 3, kMax / 3 + ((kMax % 3 != 0) ? 1 : 0)}, // Try with huge negative numerator {kMin, 1, kMin, kMin}, {kMin, 2, kMin / 2 - ((kMin % 2 != 0) ? 1 : 0), kMin / 2}, {kMin, 3, kMin / 3 - ((kMin % 3 != 0) ? 1 : 0), kMin / 3}, // Try with a huge positive denominator {1, kMax, 0, 1}, {2, kMax, 0, 1}, {3, kMax, 0, 1}, // Try with a huge negative denominator {1, kMin, -1, 0}, {2, kMin, -1, 0}, {3, kMin, -1, 0}, // Try with a huge numerator and a huge denominator {kMin, kMin, 1, 1}, {kMin, kMax, -2, -1}, {kMax, kMin, -1, 0}, {kMax, kMax, 1, 1}, }; TestCeilOfRatio<SignedInteger, int64>(kTestData, kNumTests); } // ------------------------------------------------------------------------ // // Benchmarking CeilOrFloorOfRatio // // We compare with other implementations that are unsafe in general. // ------------------------------------------------------------------------ // // An implementation of CeilOfRatio that is correct for small enough values, // and provided that the numerator and denominator are both positive template <typename IntegralType> static IntegralType CeilOfRatioDenomMinusOne(IntegralType numerator, IntegralType denominator) { const IntegralType kOne(1); return (numerator + denominator - kOne) / denominator; } // An implementation of FloorOfRatio that is correct when the denominator is // positive and the numerator non-negative template <typename IntegralType> static IntegralType FloorOfRatioByDivision(IntegralType numerator, IntegralType denominator) { return numerator / denominator; } template <typename Integer, bool ComputeCeil> static Integer CeilOrFloorOfRatioArithmetic(Integer numerator, Integer denominator) { if (ComputeCeil) { return CeilOfRatioDenomMinusOne(numerator, denominator); } else { return FloorOfRatioByDivision(numerator, denominator); } } void TestThatCeilOfRatioDenomMinusOneIsIncorrect(int64 numerator, int64 denominator, int64 expected_error) { const int64 correct_result = MathUtil::CeilOfRatio(numerator, denominator); const int64 result_by_denom_minus_one = CeilOfRatioDenomMinusOne(numerator, denominator); EXPECT_EQ(result_by_denom_minus_one + expected_error, correct_result) << "numerator = " << numerator << " denominator = " << denominator << " expected error = " << expected_error << " Actual difference: " << (correct_result - result_by_denom_minus_one); } // Here we demonstrate why not to use CeilOfRatioDenomMinusOne void TestThatCeilOfRatioDenomMinusOneIsIncorrect() { // It does not work with negative values TestThatCeilOfRatioDenomMinusOneIsIncorrect(-1LL, -2LL, -1LL); // This would also fail if given kint64max because of signed integer overflow. } TEST(MathUtil, CeilOfRatio) { TestCeilOfRatioUnsigned<uint8>(kuint8max); TestCeilOfRatioUnsigned<uint16>(kuint16max); TestCeilOfRatioUnsigned<uint32>(kuint32max); TestCeilOfRatioUnsigned<uint64>(kuint64max); TestCeilOfRatioSigned<int8>(kint8min, kint8max); TestCeilOfRatioSigned<int16>(kint16min, kint16max); TestCeilOfRatioSigned<int32>(kint32min, kint32max); TestCeilOfRatioSigned<int64>(kint64min, kint64max); #if 0 TestThatCeilOfRatioDenomMinusOneIsIncorrect(); #endif } struct GCDTestCase { unsigned int x; unsigned int y; unsigned int gcd; }; TEST(MathUtil, GCD) { std::vector<GCDTestCase> testcases({ {10, 20, 10}, // {27, 8, 1}, // {4, 3, 1}, // {6, 8, 2}, // {5, 0, 5}, // {5, 5, 5}, // {0, 0, 0} // }); for (const auto& tc : testcases) { EXPECT_EQ(tc.gcd, MathUtil::GCD<uint32>(tc.x, tc.y)); EXPECT_EQ(tc.gcd, MathUtil::GCD<uint32>(tc.y, tc.x)); EXPECT_EQ(tc.gcd, MathUtil::GCD<uint64>(tc.x, tc.y)); EXPECT_EQ(tc.gcd, MathUtil::GCD<uint64>(tc.y, tc.x)); } const uint64 biggish_prime = 1666666667; EXPECT_EQ(biggish_prime, MathUtil::GCD<uint64>(biggish_prime * 3, biggish_prime * 4)); } } // namespace tensorflow <|start_filename|>tensorflow/compiler/xla/service/cpu/parallel_loop_emitter.cc<|end_filename|> /* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/cpu/parallel_loop_emitter.h" #include "tensorflow/compiler/xla/service/llvm_ir/llvm_loop.h" #include "tensorflow/compiler/xla/service/llvm_ir/llvm_util.h" #include "tensorflow/core/lib/strings/stringprintf.h" namespace xla { namespace cpu { ParallelLoopEmitter::ParallelLoopEmitter( const llvm_ir::ElementGenerator& target_element_generator, const llvm_ir::IrArray& target_array, const DynamicLoopBounds* dynamic_loop_bounds, llvm::IRBuilder<>* ir_builder) : LoopEmitter(target_element_generator, target_array, ir_builder), dynamic_loop_bounds_(dynamic_loop_bounds) {} llvm_ir::IrArray::Index ParallelLoopEmitter::EmitIndexAndSetExitBasicBlock( tensorflow::StringPiece loop_name) { CHECK(!ShapeUtil::IsTuple(shape_)); CHECK(!ShapeUtil::IsScalar(shape_)); llvm_ir::ForLoopNest loop_nest(loop_name, ir_builder_); const int64 num_dims = shape_.dimensions_size(); llvm_ir::IrArray::Index array_index(num_dims); // Add loops from outer-most to inner-most dimensions. for (int i = shape_.layout().minor_to_major_size() - 1; i >= 0; --i) { const int64 dimension = shape_.layout().minor_to_major(i); const int bounds_index = num_dims - 1 - i; if (bounds_index < dynamic_loop_bounds_->size()) { // Emit dynamic loop bounds for this dimension. Dynamic loop bounds // are read from ir function dynamic loop bounds argument. llvm::Value* start_index = (*dynamic_loop_bounds_)[bounds_index].first; llvm::Value* end_index = (*dynamic_loop_bounds_)[bounds_index].second; std::unique_ptr<llvm_ir::ForLoop> loop = loop_nest.AddLoop( /*suffix=*/tensorflow::strings::Printf("dim.%lld", dimension), start_index, end_index); array_index[dimension] = loop->GetIndVarValue(); } else { // Emit static loop bounds for this dimension. std::unique_ptr<llvm_ir::ForLoop> loop = loop_nest.AddLoop( /*start_index=*/0, /*end_index=*/shape_.dimensions(dimension), /*suffix=*/tensorflow::strings::Printf("dim.%lld", dimension)); array_index[dimension] = loop->GetIndVarValue(); } } // Point IR builder at inner loop BB. llvm_ir::SetToFirstInsertPoint(loop_nest.GetInnerLoopBodyBasicBlock(), ir_builder_); // Set exit_bb_ to the exit block of the loop nest. exit_bb_ = loop_nest.GetOuterLoopExitBasicBlock(); CHECK(exit_bb_ != nullptr); return array_index; } } // namespace cpu } // namespace xla
arnaldog12/tensorflow
<|start_filename|>Makefile<|end_filename|> venv/bin/python: virtualenv venv venv/bin/pip install -r requirements.txt .PHONY: run run: venv/bin/python venv/bin/python polycules.py .PHONY: test test: venv/bin/python venv/bin/flake8 --config=.flake8 venv/bin/nosetests --with-coverage --cover-erase --verbosity=2 --cover-package=polycules,model,migrations.hashify <|start_filename|>static/build.js<|end_filename|> 'use strict'; function attachEvents() { node .on('mouseover', function(d) { if (!mousedown_node || d === mousedown_node) { return; } // enlarge target node d3.select(this) .attr('transform', d3.select(this).attr('transform') + ' scale(1.1)'); }) .on('mouseout', function(d) { if (!mousedown_node || d === mousedown_node) { return; } // unenlarge target node d3.select(this) .attr('transform', d3.select(this).attr('transform').replace(' scale(1.1)', '')); }) .on('mousedown', function(d) { if (d3.event.ctrlKey) { return; } // select node mousedown_node = d; if (mousedown_node === selected_node) { selected_node = null; } else selected_node = mousedown_node; selected_link = null; // reposition drag line drag_line .classed('hidden', false) .attr({ 'x1': mousedown_node.x, 'y1': mousedown_node.y, 'x2': mousedown_node.x, 'y2': mousedown_node.y }); restart(); attachEvents() }) .on('mouseup', function(d) { if (!mousedown_node) { return; } // needed by FF drag_line .classed('hidden', true) .style('marker-end', ''); // check for drag-to-self mouseup_node = d; if (mouseup_node === mousedown_node) { editing = true; editNode(d); resetMouseVars(); return; } // unenlarge target node d3.select(this).attr('transform', ''); // add link to graph (update if exists) // NB: links are strictly source < target; arrows separately specified by booleans var source, target, source = mousedown_node; target = mouseup_node; var link = addLink(source, target) // select new link selected_link = link; selected_node = null; restart(); attachEvents(); }); path .on('mousedown', function(d) { if (d3.event.ctrlKey) { return; } // select link mousedown_link = d; if (mousedown_link === selected_link) { selected_link = null; } else { selected_link = mousedown_link; } selected_node = null; editLink(d); resetMouseVars(); restart(); }); } function resetMouseVars() { mousedown_node = null; mouseup_node = null; mousedown_link = null; } function resetMenus() { d3.select('#node-menu').style('display', 'none'); d3.select('#link-menu').style('display', 'none'); } function writeGraph() { d3.select('#graph-field').html(JSON.stringify(window.graph)); } function spliceLinksForNode(node) { var toSplice = window.graph.links.filter(function(l) { return (l.source === node || l.target === node); }); toSplice.map(function(l) { window.graph.links.splice(window.graph.links.indexOf(l), 1); }); } function mousedown() { // prevent I-bar on drag //d3.event.preventDefault(); // because :active only works in WebKit? svg.classed('active', true); if (d3.event.ctrlKey || d3.event.target.nodeName !== 'svg') { return; } // insert new node at point var point = d3.mouse(this) addNode(point); restart(); attachEvents(); } function addNode(point) { var newNode = { id: ++window.graph.lastId, name: 'New ' + window.graph.lastId, x: width / 2, y: height / 2, r: 12 }; if (point) { newNode.x = point[0]; newNode.y = point[1]; } window.graph.nodes.push(newNode); return newNode; } function addLink(source, target) { var link = window.graph.links.filter(function(l) { return (l.source === source && l.target === target) || (l.source === target && l.target === source); })[0]; if (link) { return link; } else { link = { source: source, target: target, strength: 10 }; window.graph.links.push(link); } } function mousemove() { if (!mousedown_node) { return; } // update drag line var point = d3.mouse(this); drag_line .attr({ 'x1': mousedown_node.x, 'y1': mousedown_node.y, 'x2': point[0], 'y2': point[1] }); attachEvents(); restart(); } function mouseup() { if (mousedown_node) { // hide drag line drag_line .classed('hidden', true) .style('marker-end', ''); } if (editing) { return; } // because :active only works in WebKit? svg.classed('active', false); // clear mouse event vars resetMouseVars(); } // only respond once per keydown var lastKeyDown = -1; function keydown() { if (lastKeyDown !== -1) { return; } lastKeyDown = d3.event.keyCode; // ctrl if(d3.event.keyCode === 17) { node.call(force.drag); svg.classed('ctrl', true); } } function keyup() { lastKeyDown = -1; // ctrl if (d3.event.keyCode === 17) { node .on('mousedown.drag', null) .on('touchstart.drag', null); svg.classed('ctrl', false); } } function editNode(d) { d3.select('#link-menu').style('display', 'none'); var nodeMenu = d3.select('#node-menu'); nodeMenu.style('display', 'block'); document.getElementById('edit-node-name').value = d.name; nodeMenu.select('#edit-node-name') .on('keyup', function() { window.graph.nodes.filter(function(node) { return node === d; })[0].name = this.value; restart(); }); document.getElementById('edit-node-r').value = d.r; nodeMenu.select('#edit-node-r') .on('input', function() { window.graph.nodes.filter(function(node) { return node.id === d.id; })[0].r = this.value; restart(); }); document.getElementById('edit-node-dashed').checked = d.dashed; nodeMenu.select('#edit-node-dashed') .on('change', function() { window.graph.nodes.filter(function(link) { return link === d; })[0].dashed = d3.select(this).property('checked'); restart(); }); nodeMenu.select('#delete-node') .on('click', function() { if (selected_node) { window.graph.nodes .splice(window.graph.nodes.indexOf(selected_node), 1); spliceLinksForNode(selected_node); } selected_link = null; selected_node = null; restart(); attachEvents(); nodeMenu.style('display', 'none'); }); } function editLink(d) { d3.select('#node-menu').style('display', 'none'); var linkMenu = d3.select('#link-menu'); linkMenu.style('display', 'block'); linkMenu.select('#source-name').text(d.source.name); linkMenu.select('#target-name').text(d.target.name); linkMenu.select('#edit-center-text') .attr('value', d.centerText ? d.centerText : '') .on('keyup', function() { window.graph.links.filter(function(link) { return link === d; })[0].centerText = this.value; restart(); }); linkMenu.select('#edit-source-text') .attr('value', d.sourceText ? d.sourceText : '') .on('keyup', function() { window.graph.links.filter(function(link) { return link === d; })[0].sourceText = this.value; restart(); }); linkMenu.select('#edit-target-text') .attr('value', d.targetText ? d.targetText : '') .on('keyup', function() { window.graph.links.filter(function(link) { return link === d; })[0].targetText = this.value; restart(); }); linkMenu.select('#edit-strength') .attr('value', d.strength) .on('input', function() { window.graph.links.filter(function(link) { return link === d; })[0].strength = this.value; restart(); }); linkMenu.select('#edit-link-dashed') .property('checked', d.dashed) .on('change', function() { window.graph.links.filter(function(link) { return link === d; })[0].dashed = d3.select(this).property('checked'); restart(); }); linkMenu.select('#delete-link') .on('click', function() { if (selected_link) { window.graph.links .splice(window.graph.links.indexOf(selected_link), 1); } selected_link = null; selected_node = null; restart(); attachEvents(); linkMenu.style('display', 'none'); }); } function addTemplate(template) { var parts = template.split(';'); var nodes = parts[0].split(','); var links = parts[1].split(','); var builtNodes = {}; nodes.forEach(function(d) { builtNodes[d] = addNode(null); }); links.forEach(function(d) { var linkParts = d.split('-'); addLink(builtNodes[linkParts[0]], builtNodes[linkParts[1]]); }) restart(); attachEvents(); } panel.on('mousedown', mousedown) .on('mousemove', mousemove) .on('mouseup', mouseup); d3.select(window) .on('keydown', keydown) .on('keyup', keyup); d3.select('.expand-help').on('click', function(e) { d3.event.preventDefault(); var body = d3.select('.instructions .body'); body.classed('hidden', !body.classed('hidden')); }); <|start_filename|>static/style.css<|end_filename|> body, input, button { font-family: "Ubuntu Mono", monospace; color: #333; } a, a:visited, a:active, a:hover { text-decoration: none; color: #aaa; } .hidden { display: none; } .wrapper { width: 960px; margin: 0 auto; position: relative; vertical-align: top; } .flex { display: flex; justify-content: space-around; flex-wrap: wrap; } form { padding-top: 1em; text-align: center; } .form-group { flex: 0 0 calc(50% - 1rem); text-align: left; padding: inherit 0.5rem; } .help-block { color: #999; } #graph { position: relative; border: 2px solid #eee; box-shadow: 5px 5px 10px #eee; width: 960px; margin: 0 auto; margin-bottom: 2rem; overflow: visible; } #graph p { color: #888; margin-left: 1em; } #graph .menu { display: none; position: absolute; top: 1em; right: 1em; } #graph .instructions { position: absolute; top: 1em; left: 1em; } #graph .instructions .expand-help .caret { display: inline-block; width: 0; height: 0; vertical-align: middle; border-top: 5px dashed; border-top: 5px solid ~"\9"; border-right: 5px solid transparent; border-left: 5px solid transparent; } #graph .link line { stroke: rgba(0,0,0,0.25); cursor: pointer; } #graph .link .meaning { fill: #88F; font: 10px "Ubuntu Mono", monospace; text-anchor: middle; } #graph .node { cursor: grab; cursor: -moz-grab; cursor: -webkit-grab; } #graph .node circle { fill: #888; stroke: #888; stroke-width: 1px; } #graph .node text { pointer-events: none; font: 10px "Ubuntu Mono", monospace; } #graph.build { cursor: crosshair; user-select:none; } #graph.build .node { cursor: pointer; } #graph.build .node.selected circle { stroke: #44f; stroke-width: 2px; fill: #88f; } #graph.build .dragline { stroke: #44f; stroke-width: 2px; } #graph .templates { position: absolute; bottom: 0px; left: 5px; } #graph .templates .template { cursor: pointer; border: 1px solid rgba(0,0,0,0.25); border-radius: 5px; padding: 2px; margin-right: 2px; display: inline-block; } #graph .templates .template line { stroke: #888; stroke-width: 3px; } #graph .templates .template circle { fill: #888; } #graph .templates .template text { text-anchor: middle; fill: #888; font: 10px "Ubuntu Mono", monospace; } #graph #panzoom { position: absolute; bottom: 20px; right: 10px; color: #888; } #graph #panzoom small { display: block; text-align: center; } #graph #panzoom #in, #graph #panzoom #out { font-size: 20pt; border: 1px solid #ccc; width: 30px; height: 30px; text-align: center; vertical-align: top; margin: 5px; cursor: pointer; margin: 0 auto; } #graph #panzoom #in { border-bottom-width: 0px; border-radius: 5px 5px 0px 0px; } #graph #panzoom #out { border-top: none; border-radius: 0px 0px 5px 5px; } #graph #pan { position: relative; border: 1px solid #ccc; border-radius: 30px; width: 60px; height: 60px; padding: 0px; margin: -5px 0px; } #graph #pan #up { cursor: pointer; text-align: center; font-size: 20px; position: absolute; width: 20px; height: 20px; top: -4; left: 20px; } #graph #pan #left { cursor: pointer; text-align: center; font-size: 20px; position: absolute; width: 20px; height: 20px; top: 16px; left: 0px; } #graph #pan #right { cursor: pointer; text-align: center; font-size: 20px; vertical-align: middle; position: absolute; width: 20px; height: 20px; top: 16px; right: 0px; } #graph #pan #down { cursor: pointer; text-align: center; font-size: 20px; position: absolute; width: 20px; height: 20px; bottom: 4px; left: 20px; } #graph #shortcuts { background-color: #fff; color: #888; border: 2px solid #eee; border-top: none;; border-radius: 0 0 4px 4px; box-shadow: 5px 10px 10px -1px #eee; position: absolute; bottom: -24px; right: -2px; padding: 0px 3px 3px 3px; } <|start_filename|>static/polycule.js<|end_filename|> 'use strict'; // set up SVG for D3 var width = 960, height = 500, selected_node = null, selected_link = null, mousedown_link = null, mousedown_node = null, mouseup_node = null, editing = false, scale = window.graph.scale || 1, translate = window.graph.translate || [0, 0]; var panel = d3.select('#panel') .attr('oncontextmenu', 'return false;') .attr('width', width) .attr('height', height); var translateContainer = panel.append('g') .attr('transform', 'translate(' + translate + ')'); var scaleContainer = translateContainer.append('g') .attr('transform', 'scale(' + scale + ')'); var svg = scaleContainer.append('g'); function zoom(newScale) { var oldscale = scale; scale += newScale; window.graph.scale = scale; scaleContainer.attr('transform', 'scale(' + scale + ')'); translate = [ translate[0] + ((width * oldscale) - (width * scale)), translate[1] + ((height * oldscale) - (height * scale)) ]; window.graph.translate = translate; translateContainer.attr('transform', 'translate(' + translate + ')'); try { writeGraph(); } catch (e) { // } } function pan(vert, horiz) { translate = [ translate[0] + horiz, translate[1] + vert ]; window.graph.translate = translate; translateContainer.attr('transform', 'translate(' + translate + ')'); try { writeGraph(); } catch (e) { // } } window.graph.links.forEach(function(link) { window.graph.nodes.forEach(function(node) { if (node.id === link.source.id) { link.source = node; } if (node.id === link.target.id) { link.target = node; } }); }); d3.select('#in') .on('click', function() { zoom(0.1); }); d3.select('#out') .on('click', function() { zoom(-0.1); }); d3.select('#up') .on('click', function() { pan(10, 0); }); d3.select('#down') .on('click', function() { pan(-10, 0); }); d3.select('#left') .on('click', function() { pan(0, 10); }); d3.select('#right') .on('click', function() { pan(0, -10); }); // init D3 force layout var force = d3.layout.force() .nodes(window.graph.nodes) .links(window.graph.links) .size([width / scale, height / scale]) .linkDistance(function(d) { return Math.log(3 / d.strength * 10) * 50; }) .charge(-500) .on('tick', tick) // line displayed when dragging new nodes var drag_line = svg.append('line') .attr('class', 'link dragline hidden'); // handles to link and node element groups var path = svg.append('g').selectAll('.link'), node = svg.append('g').selectAll('.node'); // update force layout (called automatically each iteration) function tick() { if (!drag_line.classed('hidden')) { return; } path.select('line') .attr('x1', function(d) { return d.source.x; }) .attr('y1', function(d) { return d.source.y; }) .attr('x2', function(d) { return d.target.x; }) .attr('y2', function(d) { return d.target.y; }) path.select('.source-text') .attr('dx', function(d) { return d.source.x}) .attr('dy', function(d) { return d.source.y + d.source.r * 2}); path.select('.target-text') .attr('dx', function(d) { return d.target.x}) .attr('dy', function(d) { return d.target.y + d.target.r * 2}); path.select('.center-text') .attr('dx', function(d) { return (d.source.x + ((d.target.x - d.source.x) / 2)); }) .attr('dy', function(d) { return (d.source.y + ((d.target.y - d.source.y) / 2)) - 10; }); node.attr('transform', function(d) { return 'translate(' + d.x + ',' + d.y + ')'; }); } // update graph (called when needed) function restart() { // path (link) group path = path.data(window.graph.links); // update existing links path.classed('selected', function(d) { return d === selected_link; }); // add new links var pathG = path.enter() .append('g') .classed('link', true) .classed('selected', function(d) { return d === selected_link; }); pathG.append('line') .attr('x1', function(d) { return d.source.x; }) .attr('y1', function(d) { return d.source.y; }) .attr('x2', function(d) { return d.target.x; }) .attr('y2', function(d) { return d.target.y; }) .attr('stroke-width', function(d) { return d.strength; }) .attr('stroke-dasharray', function(d) { if (d.dashed) { return '' + [d.strength / 1.5, d.strength / 1.5]; } }); pathG.append('text') .attr('class', 'center-text meaning hidden'); pathG.append('text') .attr('class', 'source-text meaning hidden'); pathG.append('text') .attr('class', 'target-text meaning hidden'); // remove old links path.exit().remove(); path.select('line') .attr('stroke-width', function(d) { return d.strength; }) .attr('stroke-dasharray', function(d) { if (d.dashed) { return '' + [d.strength / 1.5, d.strength / 1.5]; } }); path.select('.center-text') .text(function(d) { return d.centerText; }); path.select('.source-text') .text(function(d) { return d.sourceText; }); path.select('.target-text') .text(function(d) { return d.targetText; }); path.on('mouseover', function(d) { d3.select(this).selectAll('.meaning') .classed('hidden', false); }) .on('mouseout', function(d) { d3.select(this).selectAll('.meaning') .classed('hidden', true); }); // circle (node) group // NB: the function arg is crucial here! nodes are known by id, not by index! node = node.data(window.graph.nodes, function(d) { return d.id; }); // add new nodes var nodeG = node.enter() .append('g') .classed('node', true); nodeG.append('circle') .attr('class', 'node') .attr('r', function(d) { return d.r; }) .attr('style', function(d) { if (d.dashed) { return 'fill:#ccc!important'; } }) .attr('stroke-dasharray', function(d) { if (d.dashed) { return '' + [d.r / 4, d.r / 4]; } }); // show node IDs nodeG.append('text') .attr('x', 0) .attr('y', function(d) { return -d.r - 2; }) .attr('class', 'id') .attr('text-anchor', 'middle') .text(function(d) { return d.name; }); node.select('circle') .attr('r', function(d) { return d.r; }) .attr('style', function(d) { if (d.dashed) { return 'fill:#ccc!important'; } }) .attr('stroke-dasharray', function(d) { if (d.dashed) { return '' + [d.r / 4, d.r / 4]; } }); node.select('.id') .attr('y', function(d) { return -d.r - 2; }) .text(function(d) { return d.name; }); // remove old nodes node.exit().remove(); // set the graph in motion force.start(); try { writeGraph(); } catch(e) { node.call(force.drag); } } function panzoom() { d3.event.preventDefault() switch (d3.event.key) { case 'ArrowUp': case 'w': case 'k': pan(10, 0); break; case 'ArrowDown': case 's': case 'j': pan(-10, 0); break; case 'ArrowLeft': case 'a': case 'h': pan(0, 10); break; case 'ArrowRight': case 'd': case 'l': pan(0, -10); break; case '+': zoom(0.1); break; case '-': zoom(-0.1); break; } } d3.select(window) .on('keydown', panzoom); // app starts here restart();
mlunax/polycul.es
<|start_filename|>test/Bench.hpp<|end_filename|> #pragma once #include <chrono> // Measures the time it takes to execute a execute a function template< typename TimeT = std::chrono::nanoseconds > struct Bench { template< typename FunctionT, typename ...ArgsT > static TimeT Duration(FunctionT&& Func, ArgsT&&... Arguments) { // Start time const auto Start = std::chrono::high_resolution_clock::now(); // Run function, perfect-forward arguments std::forward<decltype(Func)>(Func)(std::forward<ArgsT>(Arguments)...); // Return executation time. return std::chrono::duration_cast<TimeT>( std::chrono::high_resolution_clock::now() - Start ); } }; <|start_filename|>source/qTriangle/qTriangle-x86.hpp<|end_filename|> #include <qTriangle/qTriangle.hpp> #include <x86intrin.h> template<std::uint8_t WidthExp2> inline void CrossProductMethod( const glm::i32vec2 Points[], std::uint8_t Results[], std::size_t Count, const qTri::Triangle& Tri ); template<std::uint8_t WidthExp2> inline void BarycentricMethod( const glm::i32vec2 Points[], std::uint8_t Results[], std::size_t Count, const qTri::Triangle& Tri ); #if defined(__SSE4_1__) // Serial template<> inline void CrossProductMethod<0>( const glm::i32vec2 Points[], std::uint8_t Results[], std::size_t Count, const Triangle& Tri ) { // [ Tri[1].y, Tri[1].x, Tri[0].y, Tri[0].x] const __m128i Tri10 = _mm_loadu_si128( reinterpret_cast<const __m128i*>(Tri.data()) ); // [ Tri[2].y, Tri[2].x, Tri[2].y, Tri[2].x] const __m128i Tri22 = _mm_set1_epi64x( *reinterpret_cast<const std::uint64_t*>(Tri.data() + 2) ); // unpacklo(above) // [ Tri[2].y, Tri[0].y, Tri[2].x, Tri[0].x] // unpackhi(above) // [ Tri[2].y, Tri[1].y, Tri[2].x, Tri[1].x] const __m128i Tri20yyxx = _mm_unpacklo_epi32( Tri10, Tri22 ); const __m128i Tri21yyxx = _mm_unpackhi_epi32( Tri10, Tri22 ); // unpacklo(above) // [ Tri[2].x, Tri[2].x, Tri[1].x, Tri[0].x] // unpackhi(above) // [ Tri[2].y, Tri[2].y, Tri[1].y, Tri[0].y] const __m128i Tri2210x = _mm_unpacklo_epi32( Tri20yyxx, Tri21yyxx ); const __m128i Tri2210y = _mm_unpackhi_epi32( Tri20yyxx, Tri21yyxx ); // [ Tri[2].x, Tri[2].x, Tri[1].x, Tri[0].x] // - // [ Tri[2].x, Tri[1].x, Tri[0].x, Tri[2].x] // ^ alignr_epi8([ Tri[2].x, Tri[2].x, Tri[1].x, Tri[0].x],12) const __m128i EdgeDirx = _mm_sub_epi32( Tri2210x, _mm_alignr_epi8( Tri2210x,Tri2210x, 12 ) ); // [ Tri[2].y, Tri[2].y, Tri[1].y, Tri[0].y] // - // [ Tri[2].y, Tri[1].y, Tri[0].y, Tri[2].y] // ^ alignr_epi8([ Tri[2].y, Tri[2].y, Tri[1].y, Tri[0].y],12) const __m128i EdgeDiry = _mm_sub_epi32( Tri2210y, _mm_alignr_epi8( Tri2210y,Tri2210y, 12 ) ); for( std::size_t i = 0; i < Count; ++i ) { const __m128i CurPoint = _mm_loadl_epi64( reinterpret_cast<const __m128i*>(&Points[i]) ); const __m128i CurPointx = _mm_shuffle_epi32( CurPoint, 0b00'00'00'00 ); const __m128i CurPointy = _mm_shuffle_epi32( CurPoint, 0b01'01'01'01 ); // PointDirx = Point[i].x - Tri2210x // PointDiry = Point[i].y - Tri2210y const __m128i PointDirx = _mm_sub_epi32( CurPointx, Tri2210x ); const __m128i PointDiry = _mm_sub_epi32( CurPointy, Tri2210y ); // | -- | EdgeDir[2].x | EdgeDir[1].x | EdgeDir[0].x | < EdgeDirX // | mul | // | -- | PointDir[2].y | PointDir[1].y | PointDir[0].y | < PointDiry // | sub | // | -- | EdgeDir[2].y | EdgeDir[1].y | EdgeDir[0].y | < EdgeDiry // | mul | // | -- | PointDir[2].x | PointDir[1].x | PointDir[0].x | < PointDirx // We're only checking if the signs are >=0 so there is a lot of // optimization that can be done, such as eliminating the subtraction // in the determinant to just comparing the two products directly // ex: a.x*b.y - a.y*b.x >= 0 // a.x*b.y >= a.y*b.x // DetHi = EdgeDirx * PointDiry // DetLo = EdgeDiry * PointDirx const __m128i DetHi = _mm_mullo_epi32( EdgeDirx, PointDiry ); const __m128i DetLo = _mm_mullo_epi32( EdgeDiry, PointDirx ); const std::uint16_t CheckMask = _mm_movemask_epi8( _mm_cmplt_epi32( DetHi, DetLo ) ) & 0x0'F'F'F; // Check = DetHi >= DetLo = -(DetHi < DetLo) Results[i] |= CheckMask == 0x0'0'0'0; } } #if defined(__AVX2__) // Two at a time template<> inline void CrossProductMethod<1>( const glm::i32vec2 Points[], std::uint8_t Results[], std::size_t Count, const Triangle& Tri ) { // [ Tri[1].y, Tri[1].x, Tri[0].y, Tri[0].x] const __m128i Tri10 = _mm_loadu_si128( reinterpret_cast<const __m128i*>(Tri.data()) ); // [ Tri[2].y, Tri[2].x, Tri[2].y, Tri[2].x] const __m128i Tri22 = _mm_set1_epi64x( *reinterpret_cast<const std::uint64_t*>(Tri.data() + 2) ); // unpacklo(above) // [ Tri[2].y, Tri[0].y, Tri[2].x, Tri[0].x] // unpackhi(above) // [ Tri[2].y, Tri[1].y, Tri[2].x, Tri[1].x] const __m128i Tri20yyxx = _mm_unpacklo_epi32( Tri10, Tri22 ); const __m128i Tri21yyxx = _mm_unpackhi_epi32( Tri10, Tri22 ); // unpacklo(above) // [ Tri[2].x, Tri[2].x, Tri[1].x, Tri[0].x] // unpackhi(above) // [ Tri[2].y, Tri[2].y, Tri[1].y, Tri[0].y] const __m256i Tri2210x2x = _mm256_broadcastsi128_si256( _mm_unpacklo_epi32( Tri20yyxx, Tri21yyxx ) ); const __m256i Tri2210x2y = _mm256_broadcastsi128_si256( _mm_unpackhi_epi32( Tri20yyxx, Tri21yyxx ) ); // [ Tri[2].x, Tri[2].x, Tri[1].x, Tri[0].x] // - // [ Tri[2].x, Tri[1].x, Tri[0].x, Tri[2].x] // ^ alignr_epi8([ Tri[2].x, Tri[2].x, Tri[1].x, Tri[0].x],12) const __m256i EdgeDirx2x = _mm256_sub_epi32( Tri2210x2x, _mm256_alignr_epi8( Tri2210x2x,Tri2210x2x, 12 ) ); // [ Tri[2].y, Tri[2].y, Tri[1].y, Tri[0].y] // - // [ Tri[2].y, Tri[1].y, Tri[0].y, Tri[2].y] // ^ alignr_epi8([ Tri[2].y, Tri[2].y, Tri[1].y, Tri[0].y],12) const __m256i EdgeDirx2y = _mm256_sub_epi32( Tri2210x2y, _mm256_alignr_epi8( Tri2210x2y,Tri2210x2y, 12 ) ); for( std::size_t i = 0; i < Count; i += 2 ) { const __m256i CurPointx2 = _mm256_permute4x64_epi64( _mm256_castsi128_si256( _mm_loadu_si128( reinterpret_cast<const __m128i*>(&Points[i]) ) ), 0b01'01'00'00 ); const __m256i CurPointx2x = _mm256_shuffle_epi32( CurPointx2, 0b00'00'00'00 ); const __m256i CurPointx2y = _mm256_shuffle_epi32( CurPointx2, 0b01'01'01'01 ); const __m256i PointDirx2x = _mm256_sub_epi32( CurPointx2x, Tri2210x2x ); const __m256i PointDirx2y = _mm256_sub_epi32( CurPointx2y, Tri2210x2y ); const __m256i DetHix2 = _mm256_mullo_epi32( EdgeDirx2x, PointDirx2y ); const __m256i DetLox2 = _mm256_mullo_epi32( EdgeDirx2y, PointDirx2x ); // Check = DetHi >= DetLo = -(DetHi < DetLo) = ~(DetLo > DetHi) const std::uint32_t CheckMaskx2 = (~_mm256_movemask_epi8( _mm256_cmpgt_epi32( DetLox2, DetHix2 ) ) & 0x0'F'F'F'0'F'F'F) + 0x0001'0001; *reinterpret_cast<std::uint16_t*>(Results + i) |= static_cast<std::uint16_t>( 0x0101'0100'0001'0000 >> (_pext_u32( CheckMaskx2, 0x1000'1000) * 16) ); // Results[i + 0] |= (CheckMaskx2 & 0x0000FFFF) == 0; // Results[i + 1] |= (CheckMaskx2 & 0xFFFF0000) == 0; } CrossProductMethod<0>( Points, Results, Count, Tri ); } #endif template<> inline void BarycentricMethod<0>( const glm::i32vec2 Points[], std::uint8_t Results[], std::size_t Count, const qTri::Triangle& Tri ) { // [ Tri[1].y, Tri[1].x, Tri[0].y, Tri[0].x] const __m128i Tri10 = _mm_loadu_si128( reinterpret_cast<const __m128i*>(Tri.data()) ); // [ Tri[2].y, Tri[2].x, Tri[2].y, Tri[2].x] const __m128i Tri22 = _mm_set1_epi64x( *reinterpret_cast<const std::uint64_t*>(Tri.data() + 2) ); // [ Tri[2].y, Tri[2].x, Tri[1].y, Tri[1].x] const __m128i Tri21 = _mm_alignr_epi8( Tri22, Tri10, 8 ); // | Tri[1].x | Tri[0].y | Tri[2].y | Tri[0].x | const __m128i ConstVec_1x0y2y0x = _mm_blend_epi32( _mm_shuffle_epi32(Tri10,0b10'01'00'00),// 1x0y__0x Tri22, // ____2y__ 0b0010 ); // | Tri[1].y | Tri[0].x | Tri[2].x | Tri[0].y | const __m128i ConstVec_1y0x2x0y = _mm_blend_epi32( _mm_shuffle_epi32(Tri10,0b11'00'00'01),// 1y0x__0y _mm_shuffle_epi32(Tri22,0b00'00'00'00),// ____2x__ 0b0010 ); // Det01: Tri[1].y * Tri[0].x - Tri[0].y * Tri[1].x // Det20: Tri[2].x * Tri[0].y - Tri[0].x * Tri[2].y // | Tri[1].y | Tri[2].x | Tri[1].y | Tri[2].x | // | * | * | * | * | // | Tri[0].x | Tri[0].y | Tri[0].x | Tri[0].y | // | - | - | - | - | // | Tri[0].y | Tri[0].x | Tri[0].y | Tri[0].x | // | * | * | * | * | // | Tri[1].x | Tri[2].y | Tri[1].x | Tri[2].y | // [ Det01 , Det20 , Det01 , Det20 ] const __m128i Det0120 = _mm_sub_epi32( _mm_mullo_epi32( _mm_shuffle_epi32(Tri21,0b01'10'01'10), _mm_shuffle_epi32(Tri10,0b00'01'00'01) ), _mm_mullo_epi32( _mm_shuffle_epi32(Tri10,0b01'00'01'00), _mm_shuffle_epi32(Tri21,0b00'11'00'11) ) ); // Area: Tri[2].y * Tri[1].x - Tri[2].x * Tri[1].y // + Det20 + Det01 // | Tri[2].x | Tri[2].y | Tri[2].x | Tri[2].y | // | * | * | * | * | // | Tri[1].y | Tri[1].x | Tri[1].y | Tri[1].x | // | hsub | hsub | // | + | + | + | + | // [ Det01 | Det01 | Det01 | Det01 ] // | + | + | + | + | // [ Det20 | Det20 | Det20 | Det20 ] // [ Area | Area | Area | Area ] const __m128i AreaProduct = _mm_mullo_epi32( _mm_shuffle_epi32( Tri22, 0b00'01'00'01 ), _mm_shuffle_epi32( Tri10, 0b11'10'11'10 ) ); const __m128i Area = _mm_add_epi32( _mm_hsub_epi32( AreaProduct, AreaProduct ), _mm_hadd_epi32( Det0120,Det0120 ) ); // [Area-1, Area-1, 0,0] const __m128i CheckConst = _mm_blend_epi16( _mm_setzero_si128(), _mm_sub_epi32( // Area - 1 Area, _mm_set1_epi32(1) ), 0b11'11'00'00 ); for( std::size_t i = 0; i < Count; ++i ) { // YXYX const __m128i Point = _mm_loadl_epi64( reinterpret_cast<const __m128i*>(Points + i) ); const __m128i PointYXXY= _mm_shuffle_epi32( Point, 0b01'00'00'01 ); const __m128i PointXYYX = _mm_alignr_epi8( PointYXXY,PointYXXY,8 ); // U: // Point.y * Tri[0].x - Point.x * Tri[0].y // + // Point.x * Tri[2].y - Point.y * Tri[2].x // + Det20 // V: // Point.x * Tri[0].y - Point.y * Tri[0].x // + // Point.y * Tri[1].x - Point.x * Tri[1].y // + Det01 // If I wanted to do two at a time, I could fit // two UVs into one 128-bit lane. Putting this // here for reference // | Point.x | Point.y | Point.x | Point.y | // | * | * | * | * | // [ Tri[0].y | Tri[0].x | Tri[0].y | Tri[0].x ] < const // | - | - | - | - | // | Point.y | Point.x | Point.y | Point.x | // | * | * | * | * | // [ Tri[0].x | Tri[0].y | Tri[0].x | Tri[0].y ] < const // | + | + | + | + | // | Point.y | Point.x | Point.y | Point.x | // | * | * | * | * | // [ Tri[1].x | Tri[2].y | Tri[1].x | Tri[2].y ] < const // | - | - | - | - | // | Point.x | Point.y | Point.x | Point.y | // | * | * | * | * | // [ Tri[1].y | Tri[2].x | Tri[1].y | Tri[2].x ] < const // | + | + | + | + | // [ Det01 | Det20 | Det01 | Det20 ] < const // | V1 | U1 | V0 | U0 | // If I wanted to do 1 at a time though, // I could utilize more lanes to do // independent calculations in parallel // Such as the adds and multplications // | Point.x | Point.y | xy // | * | * | // | Tri[0].y | Tri[0].x ] < const // | - | - | // | Point.y | Point.x | yx // | * | * | // | Tri[0].x | Tri[0].y ] < const // | + | + | // | Point.y | Point.x | yx // | * | * | // | Tri[1].x | Tri[2].y ] < const // | - | - | // | Point.x | Point.y | xy // | * | * | // | Tri[1].y | Tri[2].x ] < const // | + | + | // | Det01 | Det20 ] < const // | V | U | // // V Utilizing all four lanes V // !Four determinants at once! // | Point.y | Point.x | Point.x | Point.y | yxxy // | * | * | * | * | mul // | Tri[1].x | Tri[0].y | Tri[2].y | Tri[0].x | < const // | - | - | - | - | sub // | Point.x | Point.y | Point.y | Point.x | xyyx // | * | * | * | * | mul // | Tri[1].y | Tri[0].x | Tri[2].x | Tri[0].y | < const // | hadd | hadd | hadd // | + | + | + | + | add // [ Det01 | Det20 | Det01 | Det20 ] < const // | V | U | V | U | __m128i VU = _mm_sub_epi32( _mm_mullo_epi32( PointYXXY, ConstVec_1x0y2y0x //1x'0y'2y'0x ), _mm_mullo_epi32( PointXYYX, ConstVec_1y0x2x0y //1y'0x'2x'0y ) ); VU = _mm_add_epi32( _mm_hadd_epi32( VU, VU ), Det0120 ); // Area = (blah) + Det20 + Det01 // U + V < Area ; U + V <= Area - 1 // U + V - Area < 0 // const auto AreaCheck = _mm_cmplt_epi32( // _mm_hadd_epi32( // VU, VU // ), // Area // ); // -U = U + (- 2 * U ) // |_mm_unpacklo_epi32(0,sign(VU,(-1,-1,-1,-1)))| ( little waste) // hadd[ ( V,U,V,U) | (0,-V,0,-U) ] // | V+U | U+V | -V | -U | const __m128i CheckValues = _mm_hadd_epi32( _mm_unpacklo_epi32( _mm_sign_epi32( VU, _mm_set_epi32(-1,-1,-1,-1) ), _mm_setzero_si128() ), VU ); // X <= Y;!( X > Y ); !( Y < X ) const __m128i CheckParallel = _mm_cmplt_epi32( CheckConst, CheckValues ); const std::uint16_t Mask = ~_mm_movemask_epi8(CheckParallel); Results[i] |= Mask == 0xFFFF; // | <= | <= | <= | <= | // | Area-1 | Area-1 | 0 | 0 | < const // U = (blah) + Det20; U >= 0; U >= -Det20; -U <= Det20 // V = (blah) + Det01; V >= 0; V >= -Det01; -V <= Det01 // X >= 0 : !(X < 0) // const auto SignCheck = _mm_cmplt_epi32( // VU, _mm_setzero_si128() // ); // const auto AreaSignCheck = _mm_andnot_si128( // SignCheck, AreaCheck // ); // Results[i] |= _mm_movemask_epi8( // AreaSignCheck // ) == 0xFFFF; } } #endif <|start_filename|>include/qTriangle/qTriangle.hpp<|end_filename|> #pragma once #include <cstddef> #include <cstdint> #include <algorithm> #include <vector> #include <tuple> #include "Types.hpp" #include "Util.hpp" namespace qTri { extern const std::vector< std::pair< void(* const)( const glm::i32vec2 Points[], std::uint8_t Results[], std::size_t Count, const Triangle& Tri ), const char* > > FillAlgorithms; } <|start_filename|>source/qTriangle/Util.cpp<|end_filename|> #include <qTriangle/Util.hpp> #include <qTriangle/Types.hpp> namespace qTri { namespace Util { void Draw(const qTri::Image& Frame) { for( std::size_t y = 0; y < Frame.Height; ++y ) { std::fputs("\033[0;35m|\033[1;36m", stdout); for( std::size_t x = 0; x < Frame.Width; ++x ) { std::putchar( " @"[Frame.Pixels[x + y * Frame.Width] & 1] ); } std::fputs("\033[0;35m|\n", stdout); } std::fputs("\033[0m", stdout); } } } <|start_filename|>source/qTriangle/qTriangle.cpp<|end_filename|> #include <qTriangle/qTriangle.hpp> #define GLM_ENABLE_EXPERIMENTAL #include <glm/glm.hpp> #include <glm/gtx/component_wise.hpp> namespace qTri { // Get Cross-Product Z component from two directional vectors inline std::int32_t Det( const glm::i32vec2& Top, const glm::i32vec2& Bottom ) { return Top.x * Bottom.y - Top.y * Bottom.x; } //// Cross Product Method template<std::uint8_t WidthExp2> inline void CrossProductMethod( const glm::i32vec2 Points[], std::uint8_t Results[], std::size_t Count, const Triangle& Tri ) { CrossProductMethod<WidthExp2-1>( Points, Results, Count, Tri ); } //// Barycentric Method template<std::uint8_t WidthExp2> inline void BarycentricMethod( const glm::i32vec2 Points[], std::uint8_t Results[], std::size_t Count, const Triangle& Tri ) { BarycentricMethod<WidthExp2-1>( Points, Results, Count, Tri ); } #if defined(__x86_64__) || defined(_M_X64) #include "qTriangle-x86.hpp" #else template<> inline void CrossProductMethod<0>( const glm::i32vec2 Points[], std::uint8_t Results[], std::size_t Count, const Triangle& Tri ) { // Directional vectors along all three triangle edges const glm::i32vec2 EdgeDir[3] = { Tri[1] - Tri[0], Tri[2] - Tri[1], Tri[0] - Tri[2] }; for( std::size_t i = 0; i < Count; ++i ) { const glm::i32vec2 PointDir[3] = { Points[i] - Tri[0], Points[i] - Tri[1], Points[i] - Tri[2] }; const glm::i32vec3 Crosses = glm::vec3( Det( EdgeDir[0], PointDir[0] ), Det( EdgeDir[1], PointDir[1] ), Det( EdgeDir[2], PointDir[2] ) ); Results[i] |= glm::all( glm::greaterThanEqual( Crosses, glm::i32vec3(0) ) ); } } template<> inline void BarycentricMethod<0>( const glm::i32vec2 Points[], std::uint8_t Results[], std::size_t Count, const Triangle& Tri ) { const std::int32_t Det01 = Det( Tri[0], Tri[1] ); const std::int32_t Det20 = Det( Tri[2], Tri[0] ); const std::int32_t Area = Det( Tri[1], Tri[2] ) + Det20 + Det01; for( std::size_t i = 0; i < Count; ++i ) { const std::int32_t U = Det20 + Det( Tri[0], Points[i] ) + Det( Points[i], Tri[2] ); const std::int32_t V = Det01 + Det( Tri[1], Points[i] ) + Det( Points[i], Tri[0] ); Results[i] |= (U + V) < Area && U >= 0 && V >= 0; } } #endif //// Exports const std::vector< std::pair< void(* const)( const glm::i32vec2 Points[], std::uint8_t Results[], std::size_t Count, const Triangle& Tri ), const char* > > FillAlgorithms = { // Cross-Product methods {CrossProductMethod< 0>, "Serial-CrossProduct"}, {CrossProductMethod< -1>, "CrossProductMethod"}, // Barycentric methods {BarycentricMethod< 0>, "Serial-Barycentric"}, {BarycentricMethod< -1>, "BarycentricMethod"}, }; } <|start_filename|>include/qTriangle/Util.hpp<|end_filename|> #pragma once namespace qTri { class Image; namespace Util { void Draw(const qTri::Image& Frame); } } <|start_filename|>test/Benchmark.cpp<|end_filename|> #include <cstddef> #include <cstdint> #include <cstdlib> #include <type_traits> #include <algorithm> #include <random> #include <glm/glm.hpp> #include <qTriangle/qTriangle.hpp> #include "Bench.hpp" #ifdef _WIN32 #define NOMINMAX #include <Windows.h> // Statically enables "ENABLE_VIRTUAL_TERMINAL_PROCESSING" for the terminal // at runtime to allow for unix-style escape sequences. static const bool _WndV100Enabled = []() -> bool { const auto Handle = GetStdHandle(STD_OUTPUT_HANDLE); DWORD ConsoleMode; GetConsoleMode( Handle, &ConsoleMode ); SetConsoleMode( Handle, ConsoleMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING ); GetConsoleMode( Handle, &ConsoleMode ); return ConsoleMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING; }(); #endif constexpr std::size_t Width = 80; constexpr std::size_t Height = 50; constexpr std::size_t Loops = 5; static qTri::Triangle Triangles[100'000]; int main() { // Generate random triangles std::random_device RandomDevice; std::mt19937 RandomEngine(RandomDevice()); std::uniform_int_distribution<std::int32_t> WidthDis(0, Width); std::uniform_int_distribution<std::int32_t> HeightDis(0, Height); for( qTri::Triangle& CurTriangle : Triangles ) { glm::i32vec2 Center{}; // Randomly place vertices for( glm::i32vec2& CurVert : CurTriangle ) { CurVert.x = WidthDis(RandomEngine); CurVert.y = HeightDis(RandomEngine); Center += CurVert; } // Sort points in clockwise order Center /= 3; std::sort( std::begin(CurTriangle), std::end(CurTriangle), [&Center](const glm::i32vec2& A, const glm::i32vec2& B) -> bool { // Sort points by its angle from the center const glm::i32vec2 DirectionA = Center - A; const glm::i32vec2 DirectionB = Center - B; const auto AngleA = glm::atan<glm::float32_t>(DirectionA.y, DirectionA.x); const auto AngleB = glm::atan<glm::float32_t>(DirectionB.y, DirectionB.x); return AngleA < AngleB; } ); } std::printf( "%zu Triangles x %zu times\n" "%zu x %zu Image map\n", std::extent<decltype(Triangles)>::value, Loops, Width, Height ); std::printf( "Algorithm | Average per triangle(ns)\n" ); // Generate 2d grid of points to test against std::vector<glm::i32vec2> FragCoords; for( std::size_t y = 0; y < Height; ++y ) { for( std::size_t x = 0; x < Width; ++x ) { FragCoords.emplace_back(x,y); } } // Benchmark each algorithm against all triangles for( const auto& FillAlgorithm : qTri::FillAlgorithms ) { std::printf( "%s\t", FillAlgorithm.second ); qTri::Image CurFrame(Width, Height); std::size_t ExecTime = 0; for( std::size_t i = 0; i < Loops; ++i) { for( const qTri::Triangle& CurTriangle : Triangles ) { ExecTime += Bench<>::Duration( FillAlgorithm.first, FragCoords.data(), CurFrame.Pixels.data(), FragCoords.size(), CurTriangle ).count(); } } ExecTime /= std::extent<decltype(Triangles)>::value * Loops; std::printf( "| %zu ns\n", ExecTime ); } return EXIT_SUCCESS; } <|start_filename|>test/FillShape.cpp<|end_filename|> #include <cstddef> #include <cstdint> #include <cstdlib> #include <type_traits> #include <algorithm> #include <numeric> #include <experimental/filesystem> namespace fs = std::experimental::filesystem; #include <glm/glm.hpp> #include <glm/gtc/constants.hpp> #include <glm/trigonometric.hpp> #include <qTriangle/qTriangle.hpp> #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" constexpr std::size_t Width = 300; constexpr std::size_t Height = 300; int main() { // "a" const glm::i32vec2 Edges[] = { glm::i32vec2{235,152}, glm::i32vec2{176,165}, glm::i32vec2{144,173}, glm::i32vec2{129,184}, glm::i32vec2{124,202}, glm::i32vec2{135,226}, glm::i32vec2{168,235}, glm::i32vec2{206,226}, glm::i32vec2{230,201}, glm::i32vec2{236,165}, glm::i32vec2{235,152}, glm::i32vec2{238,233}, glm::i32vec2{200,257}, glm::i32vec2{159,264}, glm::i32vec2{105,247}, glm::i32vec2{86,203}, glm::i32vec2{93,174}, glm::i32vec2{112,153}, glm::i32vec2{138,141}, glm::i32vec2{171,136}, glm::i32vec2{236,123}, glm::i32vec2{236,114}, glm::i32vec2{226,82}, glm::i32vec2{184,70}, glm::i32vec2{146,79}, glm::i32vec2{128,111}, glm::i32vec2{92,106}, glm::i32vec2{108,69}, glm::i32vec2{140,48}, glm::i32vec2{189,40}, glm::i32vec2{234,47}, glm::i32vec2{259,63}, glm::i32vec2{270,87}, glm::i32vec2{272,121}, glm::i32vec2{272,169}, glm::i32vec2{274,233}, glm::i32vec2{283,259}, glm::i32vec2{246,259}, glm::i32vec2{238,233}, }; qTri::Triangle Triangles[std::extent<decltype(Edges)>::value]; for( std::size_t i = 0; i < std::extent<decltype(Edges)>::value; ++i ) { Triangles[i] = qTri::Triangle{ { {0, 0}, Edges[i], Edges[(i + 1) % std::extent<decltype(Edges)>::value] } }; const glm::i32vec2 Center = std::accumulate( std::cbegin(Triangles[i]), std::cend(Triangles[i]), glm::i32vec2{0,0} ) / 3; std::sort( std::begin(Triangles[i]), std::end(Triangles[i]), [&Center](const glm::i32vec2& A, const glm::i32vec2& B) -> bool { // Sort points by its angle from the center const glm::i32vec2 DirectionA = Center - A; const glm::i32vec2 DirectionB = Center - B; const auto AngleA = glm::atan<glm::float32_t>(DirectionA.y, DirectionA.x); const auto AngleB = glm::atan<glm::float32_t>(DirectionB.y, DirectionB.x); return AngleA < AngleB; } ); } // Generate 2d grid of points to test against std::vector<glm::i32vec2> FragCoords; for( std::size_t y = 0; y < Height; ++y ) { for( std::size_t x = 0; x < Width; ++x ) { FragCoords.emplace_back(x,y); } } for( const auto& FillAlgorithm : qTri::FillAlgorithms ) { std::printf( "%s:\n", FillAlgorithm.second ); const auto FrameFolder = fs::path("Frames") / FillAlgorithm.second; fs::create_directories(FrameFolder); qTri::Image Frame(Width, Height); std::size_t FrameIdx = 0; for( const qTri::Triangle& CurTriangle : Triangles ) { qTri::Image CurInversion(Width, Height); // Render triangle to inversion mask FillAlgorithm.first( FragCoords.data(), CurInversion.Pixels.data(), FragCoords.size(), CurTriangle ); // Append inversion mask for( std::size_t i = 0; i < Width * Height; ++i ) { Frame.Pixels[i] = CurInversion.Pixels[i] ? ~Frame.Pixels[i] : Frame.Pixels[i]; } stbi_write_png( ((FrameFolder / std::to_string(FrameIdx)).string() + ".png").c_str(), Width, Height, 1, Frame.Pixels.data(), 0 ); // Write an image of the current triangle // Post-process from [0x00,0x01] to [0x00,0xFF] // Compiler vectorization loves loops like this for( std::size_t i = 0; i < Width * Height; ++i ) { CurInversion.Pixels[i] *= 0xFF; } stbi_write_png( (FrameFolder / ("Tri" + std::to_string(FrameIdx) + ".png")).c_str(), Width, Height, 1, CurInversion.Pixels.data(), 0 ); // ffmpeg -f image2 -framerate 2 -i %d.png -vf "scale=iw*2:ih*2" -sws_flags neighbor Anim.gif ++FrameIdx; } } return EXIT_SUCCESS; } <|start_filename|>include/qTriangle/Types.hpp<|end_filename|> #pragma once #include <tuple> #include <vector> #include <array> #include <glm/fwd.hpp> #include <glm/vec2.hpp> namespace qTri { class Image { public: Image(std::size_t Width, std::size_t Height) : Width(Width), Height(Height) { Pixels.resize(Width * Height); } std::size_t Width; std::size_t Height; std::vector<std::uint8_t> Pixels; }; using Triangle = std::array<glm::i32vec2,3>; }
Wunkolo/qTriangle
<|start_filename|>enhanced/archive/classlib/java6/modules/awt/src/main/java/common/org/apache/harmony/awt/wtk/ShutdownThread.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author <NAME>, <NAME> * @version $Revision$ */ package org.apache.harmony.awt.wtk; import org.apache.harmony.awt.internal.nls.Messages; public final class ShutdownThread extends Thread { public static final class Watchdog { } public ShutdownThread() { setName("AWT-Shutdown"); //$NON-NLS-1$ setDaemon(false); } private boolean shouldStop = false; @Override public void run() { synchronized (this) { notifyAll(); // synchronize the startup while (true) { try { wait(); } catch (InterruptedException e) { } if (shouldStop) { notifyAll(); // synchronize the shutdown return; } } } } @Override public void start() { synchronized (this) { super.start(); try { wait(); } catch (InterruptedException e) { // awt.26=Shutdown thread was interrupted while starting throw new RuntimeException( Messages.getString("awt.26")); //$NON-NLS-1$ } } } public void shutdown() { synchronized (this) { shouldStop = true; notifyAll(); try { wait(); } catch (InterruptedException e) { // awt.27=Shutdown thread was interrupted while stopping throw new RuntimeException( Messages.getString("awt.27")); //$NON-NLS-1$ } } } } <|start_filename|>enhanced/archive/classlib/java6/modules/awt/src/main/java/common/org/apache/harmony/awt/wtk/NativeEvent.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author <NAME> * @version $Revision$ */ package org.apache.harmony.awt.wtk; import java.awt.Insets; import java.awt.Rectangle; import java.awt.Point; import java.awt.event.KeyEvent; import org.apache.harmony.awt.gl.MultiRectArea; /** * The interface describing cross-platform translation of system * messages. * * <p/>Some messages can appear only on specific platform, * but they still can have cross-platform interpretation if the * application should be aware of them and can react using * cross-platform API. * */ public abstract class NativeEvent { /** * Message has no common cross-platform * interpretation and should be skipped. */ public static final int ID_PLATFORM = 0; /** * Window bounds have changed. */ public static final int ID_BOUNDS_CHANGED = -1; /** * Window decoration size has changed. */ public static final int ID_INSETS_CHANGED = -2; /** * Window was just created (WM_CREATE on Windows) */ public static final int ID_CREATED = -3; /** * Mouse grab was canceled by the native system */ public static final int ID_MOUSE_GRAB_CANCELED = -4; /** * System color scheme or visual theme was changed */ public static final int ID_THEME_CHANGED = -5; protected long windowId; protected int eventId; protected long otherWindowId; protected Point screenPos; protected Point localPos; protected Rectangle windowRect; protected int modifiers; protected int mouseButton; protected int wheelRotation; protected KeyInfo keyInfo = new KeyInfo(); protected int windowState = -1; protected long time; /** * Returns the system window id of the event recipient. * @return HWND on Windows, xwindnow on X */ public long getWindowId() { return windowId; } /** * Returns cross-platform event id * should be one of ID_* constants or * id constants from java.awt.AWTEvent subclasess * @return cross-platform event id */ public int getEventId() { return eventId; } /** * Returns the position of cursor when event occured relative to * top-left corner of recipient window * @return position of cursor in local coordinates */ public Point getLocalPos() { return localPos; } /** * Returns the position of cursor when event occured * in screen coordinates. * @return position of cursor in screen coordinates */ public Point getScreenPos() { return screenPos; } /** * The recipient window bounds when the event occured * @return window bounds */ public Rectangle getWindowRect() { return windowRect; } /** * Returns the state of keyboard and mouse buttons when the event * occured if event from mouse or keyboard, for other events can * return junk values. The value is bitwise OR of * java.awt.event.InputEvent *_DOWN constants. * * Method is aware of system mouse button swap for left-hand * mouse and return swapped values. * @return bitwise OR of java.awt.event.InputEvent *_DOWN constants */ public int getInputModifiers() { return modifiers; } /** * Returns the iconified/maximized state of recipient window if * event is state related, for other events can junk values. * The value has the same meaning as Frame.getExtendedState * It's bitwise OR of ICONIFIED, MAXIMIZED_HORIZ, MAXIMIZED_VERT * @return bitwise OR of ICONIFIED, MAXIMIZED_HORIZ, MAXIMIZED_VERT */ public int getWindowState() { return windowState; } /** * The same meaning as java.awt.event.getKeyCode * @return java.awt.event VK_* constant */ public int getVKey() { return (keyInfo != null) ? keyInfo.vKey : KeyInfo.DEFAULT_VKEY; } /** * The same meaning as java.awt.event.getKeyLocation * @return java.awt.event KEY_LOCATION_* constant */ public int getKeyLocation() { return (keyInfo != null) ? keyInfo.keyLocation : KeyInfo.DEFAULT_LOCATION; } /** * Return the string of characters associated with the event * Has meaning only for KEY_PRESSED as should be translated to * serie of KEY_TYPED events. For dead keys and input methods * one key press can generate multiple key chars. * @return string of characters */ public StringBuffer getKeyChars() { if (keyInfo == null) { return null; } if (keyInfo.vKey == KeyEvent.VK_ENTER) { keyInfo.keyChars.setLength(0); keyInfo.setKeyChars('\n'); } return keyInfo.keyChars; } public char getLastChar() { if (keyInfo == null || keyInfo.keyChars.length() == 0) { return KeyEvent.CHAR_UNDEFINED; } return keyInfo.keyChars.charAt(keyInfo.keyChars.length()-1); } /** * Returns the number of mouse button which changed it's state, * otherwise 0. * Left button is 1, middle button is 2, right button is 3. * * Method is aware of system mouse button swap for left-hand * mouse and return swapped values. * @return mouse button number */ public int getMouseButton() { return mouseButton; } /** * Returns time when the message was received * @return time in milliseconds */ public long getTime() { return time; } /** * For the focus event contains the oposite window. * This means it lost focus if recipient gains it, * or will gain focus if recipient looses it. * @return HWND on Windows, xwindnow on X */ public long getOtherWindowId() { return otherWindowId; } /** * Returns the "dirty" area of the window as set of non-intersecting * rectangles. This area is to be painted. * @return non-empty array of null if empty */ public abstract MultiRectArea getClipRects(); /** * Returns the "dirty" area of the window as one rectangle. * This area is to be painted. * @return non-null Rectangle */ public abstract Rectangle getClipBounds(); /** * Returns the window insets. Insets is area which belongs to * window somehow but is outside of it's client area, * it usually contains system provided border and titlebar. * @return non-null java.awt.Insets */ public abstract Insets getInsets(); /** * Returns true if event is popup menu trigger. * @return boolean flag */ public abstract boolean getTrigger(); /** * Returns the number of "clicks" the mouse wheel was rotated. * @return negative values if the mouse wheel was rotated up/away from the user, * and positive values if the mouse wheel was rotated down/ towards the user */ public int getWheelRotation() { return wheelRotation; } } <|start_filename|>enhanced/archive/classlib/java6/modules/awt/src/main/java/common/org/apache/harmony/awt/wtk/NativeCursor.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author <NAME> * @version $Revision$ */ package org.apache.harmony.awt.wtk; /** * The interface provides access to platform dependent functionality * for the class java.awt.Cursor. */ public interface NativeCursor { /** * Sets the current cursor shape * to this cursor when a pointer is inside * @param winID - window(currently used only on X11) */ void setCursor(long winID); /** * Destroys the native resource associated with * this cursor */ void destroyCursor(); /** * @return Native handle associated with this cursor */ long getId(); } <|start_filename|>enhanced/archive/classlib/java6/modules/awt/src/main/java/common/org/apache/harmony/awt/gl/render/NativeImageBlitter.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author <NAME> * @version $Revision$ * Created on 26.11.2005 * */ package org.apache.harmony.awt.gl.render; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Composite; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import org.apache.harmony.awt.gl.ImageSurface; import org.apache.harmony.awt.gl.MultiRectArea; import org.apache.harmony.awt.gl.Surface; import org.apache.harmony.awt.gl.XORComposite; /** * This kind of blitters is intended for drawing one image on the buffered * or volatile image. For the moment we can blit natively Buffered Images which * have sRGB, Linear_RGB, Linear_Gray Color Space and type different * from BufferedImage.TYPE_CUSTOM, Volatile Images and Images which received * using Toolkit and Component classes. */ public class NativeImageBlitter implements Blitter { final static NativeImageBlitter inst = new NativeImageBlitter(); public static NativeImageBlitter getInstance(){ return inst; } public void blit(int srcX, int srcY, Surface srcSurf, int dstX, int dstY, Surface dstSurf, int width, int height, AffineTransform sysxform, AffineTransform xform, Composite comp, Color bgcolor, MultiRectArea clip) { if(!srcSurf.isNativeDrawable()){ JavaBlitter.inst.blit(srcX, srcY, srcSurf, dstX, dstY, dstSurf, width, height, sysxform, xform, comp, bgcolor, clip); }else{ if(xform == null){ blit(srcX, srcY, srcSurf, dstX, dstY, dstSurf, width, height, sysxform, comp, bgcolor, clip); }else{ double scaleX = xform.getScaleX(); double scaleY = xform.getScaleY(); double scaledX = dstX / scaleX; double scaledY = dstY / scaleY; AffineTransform at = new AffineTransform(); at.setToTranslation(scaledX, scaledY); xform.concatenate(at); sysxform.concatenate(xform); blit(srcX, srcY, srcSurf, 0, 0, dstSurf, width, height, sysxform, comp, bgcolor, clip); } } } public void blit(int srcX, int srcY, Surface srcSurf, int dstX, int dstY, Surface dstSurf, int width, int height, AffineTransform sysxform, Composite comp, Color bgcolor, MultiRectArea clip) { if(!srcSurf.isNativeDrawable()){ JavaBlitter.inst.blit(srcX, srcY, srcSurf, dstX, dstY, dstSurf, width, height, sysxform, comp, bgcolor, clip); }else{ int type = sysxform.getType(); switch(type){ case AffineTransform.TYPE_TRANSLATION: dstX += sysxform.getTranslateX(); dstY += sysxform.getTranslateY(); case AffineTransform.TYPE_IDENTITY: blit(srcX, srcY, srcSurf, dstX, dstY, dstSurf, width, height, comp, bgcolor, clip); break; default: // TODO Need to realize Affine Transformation if(srcSurf instanceof ImageSurface){ JavaBlitter.inst.blit(srcX, srcY, srcSurf, dstX, dstY, dstSurf, width, height, sysxform, comp, bgcolor, clip); }else{ int w = srcSurf.getWidth(); int h = srcSurf.getHeight(); BufferedImage tmp = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Surface tmpSurf = Surface.getImageSurface(tmp); blit(0, 0, srcSurf, 0, 0, tmpSurf, w, h, AlphaComposite.SrcOver, null, null); JavaBlitter.inst.blit(srcX, srcY, tmpSurf, dstX, dstY, dstSurf, width, height, sysxform, comp, bgcolor, clip); } } } } public void blit(int srcX, int srcY, Surface srcSurf, int dstX, int dstY, Surface dstSurf, int width, int height, Composite comp, Color bgcolor, MultiRectArea clip) { if(!srcSurf.isNativeDrawable()){ JavaBlitter.inst.blit(srcX, srcY, srcSurf, dstX, dstY, dstSurf, width, height, comp, bgcolor, clip); }else{ long dstSurfStruct = dstSurf.getSurfaceDataPtr(); Object dstData = dstSurf.getData(); int clipRects[]; if(clip != null){ clipRects = clip.rect; }else{ clipRects = new int[]{5, 0, 0, dstSurf.getWidth(), dstSurf.getHeight()}; } if(!(srcSurf instanceof ImageSurface)){ srcSurf = srcSurf.getImageSurface(); if(bgcolor != null){ bgcolor = null; } } long srcSurfStruct = srcSurf.getSurfaceDataPtr(); Object srcData = srcSurf.getData(); if(comp instanceof AlphaComposite){ AlphaComposite ac = (AlphaComposite) comp; int compType = ac.getRule(); float alpha = ac.getAlpha(); if(bgcolor != null){ bltBG(srcX, srcY, srcSurfStruct, srcData, dstX, dstY, dstSurfStruct, dstData, width, height, bgcolor.getRGB(), compType, alpha, clipRects, srcSurf.invalidated()); dstSurf.invalidate(); srcSurf.validate(); }else{ blt(srcX, srcY, srcSurfStruct, srcData, dstX, dstY, dstSurfStruct, dstData, width, height, compType, alpha, clipRects, srcSurf.invalidated()); dstSurf.invalidate(); srcSurf.validate(); } }else if(comp instanceof XORComposite){ XORComposite xcomp = (XORComposite) comp; xor(srcX, srcY, srcSurfStruct, srcData, dstX, dstY, dstSurfStruct, dstData, width, height, xcomp.getXORColor().getRGB(), clipRects, srcSurf.invalidated()); dstSurf.invalidate(); srcSurf.validate(); }else{ if(srcSurf instanceof ImageSurface){ JavaBlitter.inst.blit(srcX, srcY, srcSurf, dstX, dstY, dstSurf, width, height, comp, bgcolor, clip); }else{ int w = srcSurf.getWidth(); int h = srcSurf.getHeight(); BufferedImage tmp = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Surface tmpSurf = Surface.getImageSurface(tmp); long tmpSurfStruct = tmpSurf.getSurfaceDataPtr(); Object tmpData = tmpSurf.getData(); int tmpClip[] = new int[]{5, 0, 0, srcSurf.getWidth(), srcSurf.getHeight()}; blt(0, 0, srcSurfStruct, srcData, 0, 0, tmpSurfStruct, tmpData, w, h, AlphaComposite.SRC_OVER, 1.0f, tmpClip, srcSurf.invalidated()); srcSurf.validate(); JavaBlitter.inst.blit(srcX, srcY, tmpSurf, dstX, dstY, dstSurf, width, height, comp, bgcolor, clip); } } } } private native void bltBG(int srcX, int srcY, long srsSurfDataPtr, Object srcData, int dstX, int dstY, long dstSurfDataPtr, Object dstData, int width, int height, int bgcolor, int compType, float alpha, int clip[], boolean invalidated); private native void blt(int srcX, int srcY, long srsSurfDataPtr, Object srcData, int dstX, int dstY, long dstSurfDataPtr, Object dstData, int width, int height, int compType, float alpha, int clip[], boolean invalidated); private native void xor(int srcX, int srcY, long srsSurfDataPtr, Object srcData, int dstX, int dstY, long dstSurfDataPtr, Object dstData, int width, int height, int xorcolor, int clip[], boolean invalidated); } <|start_filename|>enhanced/archive/classlib/java6/modules/awt/src/main/java/common/org/apache/harmony/awt/wtk/SystemProperties.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author <NAME> * @version $Revision$ */ package org.apache.harmony.awt.wtk; import java.awt.Font; import java.awt.font.TextAttribute; import java.awt.im.InputMethodHighlight; import java.util.Map; /** * NativeProperties */ public interface SystemProperties { /** * Get current value of a system color * @param index - one of java.awt.SystemColor constants * @return ARGB value of requested system color */ int getSystemColorARGB(int index); /** * Get default font for GUI elements such as menus and buttons * @return the font object */ Font getDefaultFont(); /** * Fill the given Map with system properties */ void init(Map<String, ?> desktopProperties); /** * Fills the given map with system-dependent visual text * attributes for the abstract description * of the given input method highlight * @see java.awt.Toolkit.mapInputMethodHighlight() */ void mapInputMethodHighlight(InputMethodHighlight highlight, Map<TextAttribute, ?> map); } <|start_filename|>enhanced/archive/classlib/java6/modules/awt/src/main/java/common/org/apache/harmony/awt/gl/image/JpegDecoder.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author <NAME> * @version $Revision$ */ package org.apache.harmony.awt.gl.image; import java.awt.image.*; import java.awt.color.ColorSpace; import java.awt.*; import java.io.IOException; import java.io.InputStream; import java.util.Hashtable; import org.apache.harmony.awt.internal.nls.Messages; public class JpegDecoder extends ImageDecoder { // Only 2 output colorspaces expected. Others are converted into // these ones. // 1. Grayscale public static final int JCS_GRAYSCALE = 1; // 2. RGB public static final int JCS_RGB = 2; // Flags for the consumer, progressive JPEG private static final int hintflagsProgressive = ImageConsumer.SINGLEFRAME | // JPEG is a static image ImageConsumer.TOPDOWNLEFTRIGHT | // This order is only one possible ImageConsumer.COMPLETESCANLINES; // Don't deliver incomplete scanlines // Flags for the consumer, singlepass JPEG private static final int hintflagsSingle = ImageConsumer.SINGLEPASS | hintflagsProgressive; // Buffer for the stream private static final int BUFFER_SIZE = 1024; private byte buffer[] = new byte[BUFFER_SIZE]; // 3 possible color models only private static ColorModel cmRGB; private static ColorModel cmGray; // initializes proper field IDs private static native void initIDs(); // Pointer to native structure which store decoding state // between subsequent decoding/IO-suspension cycles private long hNativeDecoder = 0; // NULL initially private boolean headerDone = false; // Next 4 members are filled by the native method (decompress). // We can simply check if imageWidth is still negative to find // out if they are already filled. private int imageWidth = -1; private int imageHeight = -1; private boolean progressive = false; private int jpegColorSpace = 0; // Stores number of bytes consumed by the native decoder private int bytesConsumed = 0; // Stores current scanline returned by the decoder private int currScanline = 0; private ColorModel cm = null; static { System.loadLibrary("jpegdecoder"); //$NON-NLS-1$ cmGray = new ComponentColorModel( ColorSpace.getInstance(ColorSpace.CS_GRAY), false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE ); // Create RGB color model cmRGB = new DirectColorModel(24, 0xFF0000, 0xFF00, 0xFF); initIDs(); } public JpegDecoder(DecodingImageSource src, InputStream is) { super(src, is); } /* public JpegDecoder(InputStream iStream, ImageConsumer iConsumer) { inputStream = iStream; consumer = iConsumer; } */ /** * @return - not NULL if call is successful */ private native Object decode( byte[] input, int bytesInBuffer, long hDecoder); private static native void releaseNativeDecoder(long hDecoder); @Override public void decodeImage() throws IOException { try { int bytesRead = 0, dataLength = 0; boolean eosReached = false; int needBytes, offset, bytesInBuffer = 0; byte byteOut[] = null; int intOut[] = null; // Read from the input stream for (;;) { needBytes = BUFFER_SIZE - bytesInBuffer; offset = bytesInBuffer; bytesRead = inputStream.read(buffer, offset, needBytes); if (bytesRead < 0) { bytesRead = 0;//break; eosReached = true; } // Don't break, maybe something left in buffer // Keep track on how much bytes left in buffer bytesInBuffer += bytesRead; // Here we pass overall number of bytes left in the java buffer // (bytesInBuffer) since jpeg decoder has its own buffer and consumes // as many bytes as it can. If there are any unconsumed bytes // it didn't add them to its buffer... Object arr = decode( buffer, bytesInBuffer, hNativeDecoder); // Keep track on how much bytes left in buffer bytesInBuffer -= bytesConsumed; if (!headerDone && imageWidth != -1) { returnHeader(); headerDone = true; } if (bytesConsumed < 0) { break; // Error exit } if (arr instanceof byte[]) { byteOut = (byte[]) arr; dataLength = byteOut.length; returnData(byteOut, currScanline); } else if (arr instanceof int[]) { intOut = (int[]) arr; dataLength = intOut.length; returnData(intOut, currScanline); } else { dataLength = 0; } if (hNativeDecoder == 0) { break; } if (dataLength == 0 && eosReached) { releaseNativeDecoder(hNativeDecoder); break; // Probably image is truncated } } imageComplete(ImageConsumer.STATICIMAGEDONE); } catch (IOException e) { throw e; } finally { closeStream(); } } public void returnHeader() { setDimensions(imageWidth, imageHeight); switch (jpegColorSpace) { case JCS_GRAYSCALE: cm = cmGray; break; case JCS_RGB: cm = cmRGB; break; default: // awt.3D=Unknown colorspace throw new IllegalArgumentException(Messages.getString("awt.3D")); //$NON-NLS-1$ } setColorModel(cm); setHints(progressive ? hintflagsProgressive : hintflagsSingle); setProperties(new Hashtable<Object, Object>()); // Empty } // Send the data to the consumer public void returnData(int data[], int currScanLine) { // Send 1 or more scanlines to the consumer. int numScanlines = data.length / imageWidth; if (numScanlines > 0) { setPixels( 0, currScanLine - numScanlines, imageWidth, numScanlines, cm, data, 0, imageWidth ); } } public void returnData(byte data[], int currScanLine) { int numScanlines = data.length / imageWidth; if (numScanlines > 0) { setPixels( 0, currScanLine - numScanlines, imageWidth, numScanlines, cm, data, 0, imageWidth ); } } } <|start_filename|>enhanced/archive/classlib/java6/modules/awt/src/main/java/common/org/apache/harmony/awt/gl/image/BufferedImageSource.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author <NAME> * @version $Revision$ */ package org.apache.harmony.awt.gl.image; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.ComponentColorModel; import java.awt.image.DataBuffer; import java.awt.image.DataBufferByte; import java.awt.image.DataBufferInt; import java.awt.image.DirectColorModel; import java.awt.image.ImageConsumer; import java.awt.image.ImageProducer; import java.awt.image.IndexColorModel; import java.awt.image.WritableRaster; import java.util.Hashtable; public class BufferedImageSource implements ImageProducer { private Hashtable<?, ?> properties; private ColorModel cm; private WritableRaster raster; private int width; private int height; private ImageConsumer ic; public BufferedImageSource(BufferedImage image, Hashtable<?, ?> properties){ if(properties == null) { this.properties = new Hashtable<Object, Object>(); } else { this.properties = properties; } width = image.getWidth(); height = image.getHeight(); cm = image.getColorModel(); raster = image.getRaster(); } public BufferedImageSource(BufferedImage image){ this(image, null); } public boolean isConsumer(ImageConsumer ic) { return (this.ic == ic); } public void startProduction(ImageConsumer ic) { addConsumer(ic); } public void requestTopDownLeftRightResend(ImageConsumer ic) { } public void removeConsumer(ImageConsumer ic) { if (this.ic == ic) { this.ic = null; } } public void addConsumer(ImageConsumer ic) { this.ic = ic; startProduction(); } private void startProduction(){ try { ic.setDimensions(width, height); ic.setProperties(properties); ic.setColorModel(cm); ic.setHints(ImageConsumer.TOPDOWNLEFTRIGHT | ImageConsumer.COMPLETESCANLINES | ImageConsumer.SINGLEFRAME | ImageConsumer.SINGLEPASS); if(cm instanceof IndexColorModel && raster.getTransferType() == DataBuffer.TYPE_BYTE || cm instanceof ComponentColorModel && raster.getTransferType() == DataBuffer.TYPE_BYTE && raster.getNumDataElements() == 1){ DataBufferByte dbb = (DataBufferByte) raster.getDataBuffer(); byte data[] = dbb.getData(); int off = dbb.getOffset(); ic.setPixels(0, 0, width, height, cm, data, off, width); }else if(cm instanceof DirectColorModel && raster.getTransferType() == DataBuffer.TYPE_INT){ DataBufferInt dbi = (DataBufferInt) raster.getDataBuffer(); int data[] = dbi.getData(); int off = dbi.getOffset(); ic.setPixels(0, 0, width, height, cm, data, off, width); }else if(cm instanceof DirectColorModel && raster.getTransferType() == DataBuffer.TYPE_BYTE){ DataBufferByte dbb = (DataBufferByte) raster.getDataBuffer(); byte data[] = dbb.getData(); int off = dbb.getOffset(); ic.setPixels(0, 0, width, height, cm, data, off, width); }else{ ColorModel rgbCM = ColorModel.getRGBdefault(); int pixels[] = new int[width]; Object pix = null; for(int y = 0; y < height; y++){ for(int x = 0 ; x < width; x++){ pix = raster.getDataElements(x, y, pix); pixels[x] = cm.getRGB(pix); } ic.setPixels(0, y, width, 1, rgbCM, pixels, 0, width); } } ic.imageComplete(ImageConsumer.STATICIMAGEDONE); }catch (NullPointerException e){ if (ic != null) { ic.imageComplete(ImageConsumer.IMAGEERROR); } } } } <|start_filename|>enhanced/archive/classlib/java6/modules/awt/src/main/java/common/org/apache/harmony/awt/gl/CommonGraphics2DFactory.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author <NAME>, <NAME> * @version $Revision$ */ package org.apache.harmony.awt.gl; import java.awt.Font; import java.awt.FontMetrics; import java.awt.peer.FontPeer; import org.apache.harmony.awt.gl.font.FontMetricsImpl; import org.apache.harmony.awt.wtk.GraphicsFactory; /** * Common GraphicsFactory implementation * */ public abstract class CommonGraphics2DFactory implements GraphicsFactory { // static instance of CommonGraphics2DFactory public static CommonGraphics2DFactory inst; /** * Returns FontMetrics object that keeps metrics of the specified font. * * @param font specified Font * @return FontMetrics object corresponding to the specified Font object */ public FontMetrics getFontMetrics(Font font) { FontMetrics fm; for (FontMetrics element : cacheFM) { fm = element; if (fm == null){ break; } if (fm.getFont().equals(font)){ return fm; } } fm = new FontMetricsImpl(font); System.arraycopy(cacheFM, 0, cacheFM, 1, cacheFM.length -1); cacheFM[0] = fm; return fm; } // Font methods public FontPeer getFontPeer(Font font) { return getFontManager().getFontPeer(font.getName(), font.getStyle(), font.getSize()); } /** * Embeds font from gile with specified path into the system. * * @param fontFilePath path to the font file * @return Font object that was created from the file. */ public abstract Font embedFont(String fontFilePath); } <|start_filename|>enhanced/archive/classlib/java6/modules/awt/src/main/java/common/org/apache/harmony/awt/gl/font/FontFinder.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author <NAME> * @version $Revision$ * * @date: Jul 12, 2005 */ package org.apache.harmony.awt.gl.font; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.util.List; import java.util.Map; /** * This class chooses the default font for the given text. * If it finds the character which current font is unable to display * it starts the next font run and looks for the font which is able to * display the current character. It also caches the font mappings * (index in the array containing all fonts) for the characters, * using that fact that scripts are mainly contiguous in the UTF-16 encoding * and there's a high probability that the upper byte will be the same for the * next character as for the previous. This allows to save the space used for the cache. */ public class FontFinder { private static final float DEFAULT_FONT_SIZE = 12; private static final Font fonts[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); private static final int NUM_BLOCKS = 256; private static final int BLOCK_SIZE = 256; private static final int INDEX_MASK = 0xFF; private static final int BLOCK_SHIFT = 8; // Maps characters into the fonts array private static final int blocks[][] = new int[NUM_BLOCKS][]; /** * Finds the font which is able to display the given character * and saves the font mapping for this character * @param c - character * @return font */ static Font findFontForChar(char c) { int blockNum = c >> BLOCK_SHIFT; int index = c & INDEX_MASK; if (blocks[blockNum] == null) { blocks[blockNum] = new int[BLOCK_SIZE]; } if (blocks[blockNum][index] == 0) { blocks[blockNum][index] = 1; for (int i=0; i<fonts.length; i++) { if (fonts[i].canDisplay(c)) { blocks[blockNum][index] = i+1; break; } } } return getDefaultSizeFont(blocks[blockNum][index]-1); } /** * Derives the default size font * @param i - index in the array of all fonts * @return derived font */ static Font getDefaultSizeFont(int i) { if (fonts[i].getSize() != DEFAULT_FONT_SIZE) { fonts[i] = fonts[i].deriveFont(DEFAULT_FONT_SIZE); } return fonts[i]; } /** * Assigns default fonts for the given text run. * First three parameters are input, last three are output. * @param text - given text * @param runStart - start of the text run * @param runLimit - end of the text run * @param runStarts - starts of the resulting font runs * @param fonts - mapping of the font run starts to the fonts */ static void findFonts(char text[], int runStart, int runLimit, List<Integer> runStarts, Map<Integer, Font> fonts) { Font prevFont = null; Font currFont; for (int i = runStart; i < runLimit; i++) { currFont = findFontForChar(text[i]); if (currFont != prevFont) { prevFont = currFont; Integer idx = new Integer(i); fonts.put(idx, currFont); if (i != runStart) { runStarts.add(idx); } } } } } <|start_filename|>enhanced/archive/classlib/java6/modules/awt/src/main/java/common/org/apache/harmony/awt/wtk/WTK.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author <NAME> * @version $Revision$ */ package org.apache.harmony.awt.wtk; import java.awt.GraphicsDevice; public abstract class WTK { public abstract GraphicsFactory getGraphicsFactory(); public abstract NativeEventQueue getNativeEventQueue(); public abstract WindowFactory getWindowFactory(); /** * Returns platform specific implementation of the interface * org.apache.harmony.awt.wtk.CursorFactory. * @return implementation of CursorFactory */ public abstract CursorFactory getCursorFactory(); /** * Returns platform specific implementation of the interface * org.apache.harmony.awt.wtk.NativeMouseInfo. * @return implementation of NativeMouseInfo */ public abstract NativeMouseInfo getNativeMouseInfo(); public abstract SystemProperties getSystemProperties(); /** * Returns platform specific implementation of the interface * org.apache.harmony.awt.wtk.NativeRobot. * @return implementation of NativeRobot */ public abstract NativeRobot getNativeRobot(GraphicsDevice screen); /** * Returns platform specific implementation of the abstract * class org.apache.harmony.awt.wtk.NativeIM. * @return implementation of NativeIM */ public abstract NativeIM getNativeIM(); } <|start_filename|>enhanced/archive/classlib/java6/modules/awt/src/main/java/common/org/apache/harmony/awt/gl/font/TextDecorator.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * @author <NAME> * @version $Revision$ */ package org.apache.harmony.awt.gl.font; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.font.TextAttribute; import java.awt.geom.Area; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.text.AttributedCharacterIterator.Attribute; import java.util.Map; /** * This class is responsible for rendering text decorations like * underline, strikethrough, text with background, etc. */ public class TextDecorator { private static final TextDecorator inst = new TextDecorator(); private TextDecorator() {} static TextDecorator getInstance() { return inst; } /** * This class encapsulates a set of decoration attributes for a single text run. */ static class Decoration { private static final BasicStroke UNDERLINE_LOW_ONE_PIXEL_STROKE = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10); private static final BasicStroke UNDERLINE_LOW_TWO_PIXEL_STROKE = new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10); private static final BasicStroke UNDERLINE_LOW_DOTTED_STROKE = new BasicStroke( 1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10, new float[] { 1, 1 }, 0 ); private static final BasicStroke UNDERLINE_LOW_DOTTED_STROKE2 = new BasicStroke( 1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10, new float[] { 1, 1 }, 1 ); private static final BasicStroke UNDERLINE_LOW_DASHED_STROKE = new BasicStroke( 1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10, new float[] { 4, 4 }, 0 ); boolean ulOn = false; // Have standard underline? BasicStroke ulStroke; BasicStroke imUlStroke; // Stroke for INPUT_METHOD_UNDERLINE BasicStroke imUlStroke2; // Specially for UNDERLINE_LOW_GRAY boolean strikeThrough; BasicStroke strikeThroughStroke; boolean haveStrokes = false; // Strokes already created? boolean swapBfFg; Paint bg; // background color Paint fg; // foreground color Paint graphicsPaint; // Slot for saving current paint Decoration( Integer imUl, boolean swap, boolean sth, Paint bg, Paint fg, boolean ulOn) { if (imUl != null) { // Determine which stroke to use if (imUl == TextAttribute.UNDERLINE_LOW_ONE_PIXEL) { this.imUlStroke = Decoration.UNDERLINE_LOW_ONE_PIXEL_STROKE; } else if (imUl == TextAttribute.UNDERLINE_LOW_TWO_PIXEL) { this.imUlStroke = Decoration.UNDERLINE_LOW_TWO_PIXEL_STROKE; } else if (imUl == TextAttribute.UNDERLINE_LOW_DOTTED) { this.imUlStroke = Decoration.UNDERLINE_LOW_DOTTED_STROKE; } else if (imUl == TextAttribute.UNDERLINE_LOW_GRAY) { this.imUlStroke = Decoration.UNDERLINE_LOW_DOTTED_STROKE; this.imUlStroke2 = Decoration.UNDERLINE_LOW_DOTTED_STROKE2; } else if (imUl == TextAttribute.UNDERLINE_LOW_DASHED) { this.imUlStroke = Decoration.UNDERLINE_LOW_DASHED_STROKE; } } this.ulOn = ulOn; // Has underline this.swapBfFg = swap; this.strikeThrough = sth; this.bg = bg; this.fg = fg; } /** * Creates strokes of proper width according to the info * stored in the BasicMetrics * @param metrics - basic metrics */ private void getStrokes(BasicMetrics metrics) { if (!haveStrokes) { if (strikeThrough) { strikeThroughStroke = new BasicStroke( metrics.strikethroughThickness, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10 ); } if (ulOn) { ulStroke = new BasicStroke( metrics.underlineThickness, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10 ); } haveStrokes = true; } } } /** * Creates Decoration object from the set of text attributes * @param attributes - text attributes * @return Decoration object */ static Decoration getDecoration(Map<? extends Attribute, ?> attributes) { if (attributes == null) { return null; // It is for plain text } Object underline = attributes.get(TextAttribute.UNDERLINE); boolean hasStandardUnderline = underline == TextAttribute.UNDERLINE_ON; Object imUnderline = attributes.get(TextAttribute.INPUT_METHOD_UNDERLINE); Integer imUl = (Integer) imUnderline; boolean swapBgFg = TextAttribute.SWAP_COLORS_ON.equals( attributes.get(TextAttribute.SWAP_COLORS) ); boolean strikeThrough = TextAttribute.STRIKETHROUGH_ON.equals( attributes.get(TextAttribute.STRIKETHROUGH) ); Paint fg = (Paint) attributes.get(TextAttribute.FOREGROUND); Paint bg = (Paint) attributes.get(TextAttribute.BACKGROUND); if ( !hasStandardUnderline && imUnderline == null && fg == null && bg == null && !swapBgFg && !strikeThrough ) { return null; } return new Decoration(imUl, swapBgFg, strikeThrough, bg, fg, hasStandardUnderline); } /** * Fills the background before drawing if needed. * * @param trs - text segment * @param g2d - graphics to draw to * @param xOffset - offset in X direction to the upper left corner of the * layout from the origin of the graphics * @param yOffset - offset in Y direction to the upper left corner of the * layout from the origin of the graphics */ static void prepareGraphics( TextRunSegment trs, Graphics2D g2d, float xOffset, float yOffset ) { Decoration d = trs.decoration; if (d.fg == null && d.bg == null && d.swapBfFg == false) { return; // Nothing to do } d.graphicsPaint = g2d.getPaint(); if (d.fg == null) { d.fg = d.graphicsPaint; } if (d.swapBfFg) { // Fill background area g2d.setPaint(d.fg); Rectangle2D bgArea = trs.getLogicalBounds(); Rectangle2D toFill = new Rectangle2D.Double( bgArea.getX() + xOffset, bgArea.getY() + yOffset, bgArea.getWidth(), bgArea.getHeight() ); g2d.fill(toFill); // Set foreground color g2d.setPaint(d.bg == null ? Color.WHITE : d.bg); } else { if (d.bg != null) { // Fill background area g2d.setPaint(d.bg); Rectangle2D bgArea = trs.getLogicalBounds(); Rectangle2D toFill = new Rectangle2D.Double( bgArea.getX() + xOffset, bgArea.getY() + yOffset, bgArea.getWidth(), bgArea.getHeight() ); g2d.fill(toFill); } // Set foreground color g2d.setPaint(d.fg); } } /** * Restores the original state of the graphics if needed * @param d - decoration * @param g2d - graphics */ static void restoreGraphics(Decoration d, Graphics2D g2d) { if (d.fg == null && d.bg == null && d.swapBfFg == false) { return; // Nothing to do } g2d.setPaint(d.graphicsPaint); } /** * Renders the text decorations * @param trs - text run segment * @param g2d - graphics to render to * @param xOffset - offset in X direction to the upper left corner * of the layout from the origin of the graphics * @param yOffset - offset in Y direction to the upper left corner * of the layout from the origin of the graphics */ static void drawTextDecorations( TextRunSegment trs, Graphics2D g2d, float xOffset, float yOffset ) { Decoration d = trs.decoration; if (!d.ulOn && d.imUlStroke == null && !d.strikeThrough) { return; // Nothing to do } float left = xOffset + (float) trs.getLogicalBounds().getMinX(); float right = xOffset + (float) trs.getLogicalBounds().getMaxX(); Stroke savedStroke = g2d.getStroke(); d.getStrokes(trs.metrics); if (d.strikeThrough) { float y = trs.y + yOffset + trs.metrics.strikethroughOffset; g2d.setStroke(d.strikeThroughStroke); g2d.draw(new Line2D.Float(left, y, right, y)); } if (d.ulOn) { float y = trs.y + yOffset + trs.metrics.underlineOffset; g2d.setStroke(d.ulStroke); g2d.draw(new Line2D.Float(left, y, right, y)); } if (d.imUlStroke != null) { float y = trs.y + yOffset + trs.metrics.underlineOffset; g2d.setStroke(d.imUlStroke); g2d.draw(new Line2D.Float(left, y, right, y)); if (d.imUlStroke2 != null) { y++; g2d.setStroke(d.imUlStroke2); g2d.draw(new Line2D.Float(left, y, right, y)); } } g2d.setStroke(savedStroke); } /** * Extends the visual bounds of the text run segment to * include text decorations. * @param trs - text segment * @param segmentBounds - bounds of the undecorated text * @param d - decoration * @return extended bounds */ static Rectangle2D extendVisualBounds( TextRunSegment trs, Rectangle2D segmentBounds, Decoration d ) { if (d == null) { return segmentBounds; } double minx = segmentBounds.getMinX(); double miny = segmentBounds.getMinY(); double maxx = segmentBounds.getMaxX(); double maxy = segmentBounds.getMaxY(); Rectangle2D lb = trs.getLogicalBounds(); if (d.swapBfFg || d.bg != null) { minx = Math.min(lb.getMinX() - trs.x, minx); miny = Math.min(lb.getMinY() - trs.y, miny); maxx = Math.max(lb.getMaxX() - trs.x, maxx); maxy = Math.max(lb.getMaxY() - trs.y, maxy); } if (d.ulOn || d.imUlStroke != null || d.strikeThrough) { minx = Math.min(lb.getMinX() - trs.x, minx); maxx = Math.max(lb.getMaxX() - trs.x, maxx); d.getStrokes(trs.metrics); if (d.ulStroke != null) { maxy = Math.max( maxy, trs.metrics.underlineOffset + d.ulStroke.getLineWidth() ); } if (d.imUlStroke != null) { maxy = Math.max( maxy, trs.metrics.underlineOffset + d.imUlStroke.getLineWidth() + (d.imUlStroke2 == null ? 0 : d.imUlStroke2.getLineWidth()) ); } } return new Rectangle2D.Double(minx, miny, maxx-minx, maxy-miny); } /** * Extends the outline of the text run segment to * include text decorations. * @param trs - text segment * @param segmentOutline - outline of the undecorated text * @param d - decoration * @return extended outline */ static Shape extendOutline( TextRunSegment trs, Shape segmentOutline, Decoration d ) { if (d == null || !d.ulOn && d.imUlStroke == null && !d.strikeThrough) { return segmentOutline; // Nothing to do } Area res = new Area(segmentOutline); float left = (float) trs.getLogicalBounds().getMinX() - trs.x; float right = (float) trs.getLogicalBounds().getMaxX() - trs.x; d.getStrokes(trs.metrics); if (d.strikeThrough) { float y = trs.metrics.strikethroughOffset; res.add(new Area(d.strikeThroughStroke.createStrokedShape( new Line2D.Float(left, y, right, y) ))); } if (d.ulOn) { float y = trs.metrics.underlineOffset; res.add(new Area(d.ulStroke.createStrokedShape( new Line2D.Float(left, y, right, y) ))); } if (d.imUlStroke != null) { float y = trs.metrics.underlineOffset; res.add(new Area(d.imUlStroke.createStrokedShape( new Line2D.Float(left, y, right, y) ))); if (d.imUlStroke2 != null) { y++; res.add(new Area(d.imUlStroke2.createStrokedShape( new Line2D.Float(left, y, right, y) ))); } } return res; } } <|start_filename|>enhanced/java/classlib/modules/luni/src/main/java/java/util/AbstractMap.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package java.util; /** * This class is an abstract implementation of the {@code Map} interface. This * implementation does not support adding. A subclass must implement the * abstract method entrySet(). * * @since 1.2 */ public abstract class AbstractMap<K, V> implements Map<K, V> { // Lazily initialized key set. Set<K> keySet; Collection<V> valuesCollection; /** * Constructs a new instance of this {@code AbstractMap}. */ protected AbstractMap() { super(); } /** * Removes all elements from this map, leaving it empty. * * @throws UnsupportedOperationException * if removing from this map is not supported. * @see #isEmpty() * @see #size() */ public void clear() { entrySet().clear(); } /** * Returns whether this map contains the specified key. * * @param key * the key to search for. * @return {@code true} if this map contains the specified key, * {@code false} otherwise. */ public boolean containsKey(Object key) { Iterator<Map.Entry<K, V>> it = entrySet().iterator(); if (key != null) { while (it.hasNext()) { if (key.equals(it.next().getKey())) { return true; } } } else { while (it.hasNext()) { if (it.next().getKey() == null) { return true; } } } return false; } /** * Returns whether this map contains the specified value. * * @param value * the value to search for. * @return {@code true} if this map contains the specified value, * {@code false} otherwise. */ public boolean containsValue(Object value) { Iterator<Map.Entry<K, V>> it = entrySet().iterator(); if (value != null) { while (it.hasNext()) { if (value.equals(it.next().getValue())) { return true; } } } else { while (it.hasNext()) { if (it.next().getValue() == null) { return true; } } } return false; } /** * Returns a set containing all of the mappings in this map. Each mapping is * an instance of {@link Map.Entry}. As the set is backed by this map, * changes in one will be reflected in the other. * * @return a set of the mappings. */ public abstract Set<Map.Entry<K, V>> entrySet(); /** * Compares the specified object to this instance, and returns {@code true} * if the specified object is a map and both maps contain the same mappings. * * @param object * the object to compare with this object. * @return boolean {@code true} if the object is the same as this object, * and {@code false} if it is different from this object. * @see #hashCode() * @see #entrySet() */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object instanceof Map) { Map<?, ?> map = (Map<?, ?>) object; if (size() != map.size()) { return false; } try { for (Entry<K, V> entry : entrySet()) { K key = entry.getKey(); V mine = entry.getValue(); Object theirs = map.get(key); if (mine == null) { if (theirs != null || !map.containsKey(key)) { return false; } } else if (!mine.equals(theirs)) { return false; } } } catch (NullPointerException ignored) { return false; } catch (ClassCastException ignored) { return false; } return true; } return false; } /** * Returns the value of the mapping with the specified key. * * @param key * the key. * @return the value of the mapping with the specified key, or {@code null} * if no mapping for the specified key is found. */ public V get(Object key) { Iterator<Map.Entry<K, V>> it = entrySet().iterator(); if (key != null) { while (it.hasNext()) { Map.Entry<K, V> entry = it.next(); if (key.equals(entry.getKey())) { return entry.getValue(); } } } else { while (it.hasNext()) { Map.Entry<K, V> entry = it.next(); if (entry.getKey() == null) { return entry.getValue(); } } } return null; } /** * Returns the hash code for this object. Objects which are equal must * return the same value for this method. * * @return the hash code of this object. * @see #equals(Object) */ @Override public int hashCode() { int result = 0; Iterator<Map.Entry<K, V>> it = entrySet().iterator(); while (it.hasNext()) { result += it.next().hashCode(); } return result; } /** * Returns whether this map is empty. * * @return {@code true} if this map has no elements, {@code false} * otherwise. * @see #size() */ public boolean isEmpty() { return size() == 0; } /** * Returns a set of the keys contained in this map. The set is backed by * this map so changes to one are reflected by the other. The returned set * does not support adding. * * @return a set of the keys. */ public Set<K> keySet() { if (keySet == null) { keySet = new AbstractSet<K>() { @Override public boolean contains(Object object) { return containsKey(object); } @Override public int size() { return AbstractMap.this.size(); } @Override public Iterator<K> iterator() { return new Iterator<K>() { Iterator<Map.Entry<K, V>> setIterator = entrySet() .iterator(); public boolean hasNext() { return setIterator.hasNext(); } public K next() { return setIterator.next().getKey(); } public void remove() { setIterator.remove(); } }; } }; } return keySet; } /** * Maps the specified key to the specified value. * * @param key * the key. * @param value * the value. * @return the value of any previous mapping with the specified key or * {@code null} if there was no mapping. * @throws UnsupportedOperationException * if adding to this map is not supported. * @throws ClassCastException * if the class of the key or value is inappropriate for this * map. * @throws IllegalArgumentException * if the key or value cannot be added to this map. * @throws NullPointerException * if the key or value is {@code null} and this Map does not * support {@code null} keys or values. */ public V put(K key, V value) { throw new UnsupportedOperationException(); } /** * Copies every mapping in the specified map to this map. * * @param map * the map to copy mappings from. * @throws UnsupportedOperationException * if adding to this map is not supported. * @throws ClassCastException * if the class of a key or value is inappropriate for this * map. * @throws IllegalArgumentException * if a key or value cannot be added to this map. * @throws NullPointerException * if a key or value is {@code null} and this map does not * support {@code null} keys or values. */ public void putAll(Map<? extends K, ? extends V> map) { for (Map.Entry<? extends K, ? extends V> entry : map.entrySet()) { put(entry.getKey(), entry.getValue()); } } /** * Removes a mapping with the specified key from this Map. * * @param key * the key of the mapping to remove. * @return the value of the removed mapping or {@code null} if no mapping * for the specified key was found. * @throws UnsupportedOperationException * if removing from this map is not supported. */ public V remove(Object key) { Iterator<Map.Entry<K, V>> it = entrySet().iterator(); if (key != null) { while (it.hasNext()) { Map.Entry<K, V> entry = it.next(); if (key.equals(entry.getKey())) { it.remove(); return entry.getValue(); } } } else { while (it.hasNext()) { Map.Entry<K, V> entry = it.next(); if (entry.getKey() == null) { it.remove(); return entry.getValue(); } } } return null; } /** * Returns the number of elements in this map. * * @return the number of elements in this map. */ public int size() { return entrySet().size(); } /** * Returns the string representation of this map. * * @return the string representation of this map. */ @Override public String toString() { if (isEmpty()) { return "{}"; //$NON-NLS-1$ } StringBuilder buffer = new StringBuilder(size() * 28); buffer.append('{'); Iterator<Map.Entry<K, V>> it = entrySet().iterator(); while (it.hasNext()) { Map.Entry<K, V> entry = it.next(); Object key = entry.getKey(); if (key != this) { buffer.append(key); } else { buffer.append("(this Map)"); //$NON-NLS-1$ } buffer.append('='); Object value = entry.getValue(); if (value != this) { buffer.append(value); } else { buffer.append("(this Map)"); //$NON-NLS-1$ } if (it.hasNext()) { buffer.append(", "); //$NON-NLS-1$ } } buffer.append('}'); return buffer.toString(); } /** * Returns a collection of the values contained in this map. The collection * is backed by this map so changes to one are reflected by the other. The * collection supports remove, removeAll, retainAll and clear operations, * and it does not support add or addAll operations. * <p> * This method returns a collection which is the subclass of * AbstractCollection. The iterator method of this subclass returns a * "wrapper object" over the iterator of map's entrySet(). The {@code size} * method wraps the map's size method and the {@code contains} method wraps * the map's containsValue method. * <p> * The collection is created when this method is called for the first time * and returned in response to all subsequent calls. This method may return * different collections when multiple concurrent calls occur to this * method, since no synchronization is performed. * * @return a collection of the values contained in this map. */ public Collection<V> values() { if (valuesCollection == null) { valuesCollection = new AbstractCollection<V>() { @Override public int size() { return AbstractMap.this.size(); } @Override public boolean contains(Object object) { return containsValue(object); } @Override public Iterator<V> iterator() { return new Iterator<V>() { Iterator<Map.Entry<K, V>> setIterator = entrySet() .iterator(); public boolean hasNext() { return setIterator.hasNext(); } public V next() { return setIterator.next().getValue(); } public void remove() { setIterator.remove(); } }; } }; } return valuesCollection; } /** * Returns a new instance of the same class as this instance, whose slots * have been filled in with the values of the slots of this instance. * * @return a shallow copy of this object. * @throws CloneNotSupportedException * if the receiver's class does not implement the interface * {@code Cloneable}. */ @Override @SuppressWarnings("unchecked") protected Object clone() throws CloneNotSupportedException { AbstractMap<K, V> result = (AbstractMap<K, V>) super.clone(); result.keySet = null; result.valuesCollection = null; return result; } } <|start_filename|>enhanced/archive/classlib/java6/modules/awt/src/main/java/common/org/apache/harmony/awt/gl/font/TextRunSegmentImpl.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author <NAME> * @version $Revision$ * */ package org.apache.harmony.awt.gl.font; import java.awt.*; import java.awt.font.*; import java.awt.geom.Rectangle2D; import java.awt.geom.GeneralPath; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; // XXX - TODO - bidi not implemented yet //import java.text.Bidi; import java.util.Arrays; import org.apache.harmony.awt.internal.nls.Messages; /** * Date: Apr 25, 2005 * Time: 4:33:18 PM * * This class contains the implementation of the behavior of the * text run segment with constant text attributes and direction. */ public class TextRunSegmentImpl { /** * This class contains basic information required for creation * of the glyph-based text run segment. */ public static class TextSegmentInfo { // XXX - TODO - bidi not implemented yet //Bidi bidi; Font font; FontRenderContext frc; char text[]; int start; int end; int length; int flags = 0; byte level = 0; TextSegmentInfo( byte level, Font font, FontRenderContext frc, char text[], int start, int end ) { this.font = font; this.frc = frc; this.text = text; this.start = start; this.end = end; this.level = level; length = end - start; } } /** * This class represents a simple text segment backed by the glyph vector */ public static class TextRunSegmentCommon extends TextRunSegment { TextSegmentInfo info; private GlyphVector gv; private float advanceIncrements[]; private int char2glyph[]; private GlyphJustificationInfo gjis[]; // Glyph justification info TextRunSegmentCommon(TextSegmentInfo i, TextDecorator.Decoration d) { // XXX - todo - check support bidi i.flags &= ~0x09; // Clear bidi flags if ((i.level & 0x1) != 0) { i.flags |= Font.LAYOUT_RIGHT_TO_LEFT; } info = i; this.decoration = d; LineMetrics lm = i.font.getLineMetrics(i.text, i.start, i.end, i.frc); this.metrics = new BasicMetrics(lm, i.font); if (lm.getNumChars() != i.length) { // XXX todo - This should be handled // awt.41=Font returned unsupported type of line metrics. This case is known, but not supported yet. throw new UnsupportedOperationException( Messages.getString("awt.41")); //$NON-NLS-1$ } } @Override public Object clone() { return new TextRunSegmentCommon(info, decoration); } /** * Creates glyph vector from the managed text if needed * @return glyph vector */ private GlyphVector getGlyphVector() { if (gv==null) { gv = info.font.layoutGlyphVector( info.frc, info.text, info.start, info.end - info.start, // NOTE: This parameter violates // spec, it is count, // not limit as spec states info.flags ); } return gv; } /** * Renders this text run segment * @param g2d - graphics to render to * @param xOffset - X offset from the graphics origin to the * origin of the text layout * @param yOffset - Y offset from the graphics origin to the * origin of the text layout */ @Override void draw(Graphics2D g2d, float xOffset, float yOffset) { if (decoration == null) { g2d.drawGlyphVector(getGlyphVector(), xOffset + x, yOffset + y); } else { TextDecorator.prepareGraphics(this, g2d, xOffset, yOffset); g2d.drawGlyphVector(getGlyphVector(), xOffset + x, yOffset + y); TextDecorator.drawTextDecorations(this, g2d, xOffset, yOffset); TextDecorator.restoreGraphics(decoration, g2d); } } /** * Returns visual bounds of this segment * @return visual bounds */ @Override Rectangle2D getVisualBounds() { if (visualBounds == null) { visualBounds = TextDecorator.extendVisualBounds( this, getGlyphVector().getVisualBounds(), decoration ); visualBounds.setRect( x + visualBounds.getX(), y + visualBounds.getY(), visualBounds.getWidth(), visualBounds.getHeight() ); } return (Rectangle2D) visualBounds.clone(); } /** * Returns logical bounds of this segment * @return logical bounds */ @Override Rectangle2D getLogicalBounds() { if (logicalBounds == null) { logicalBounds = getGlyphVector().getLogicalBounds(); logicalBounds.setRect( x + logicalBounds.getX(), y + logicalBounds.getY(), logicalBounds.getWidth(), logicalBounds.getHeight() ); } return (Rectangle2D) logicalBounds.clone(); } @Override float getAdvance() { return (float) getLogicalBounds().getWidth(); } /** * Attemts to map each character to the corresponding advance increment */ void initAdvanceMapping() { GlyphVector gv = getGlyphVector(); int charIndicies[] = gv.getGlyphCharIndices(0, gv.getNumGlyphs(), null); advanceIncrements = new float[info.length]; for (int i=0; i<charIndicies.length; i++) { advanceIncrements[charIndicies[i]] = gv.getGlyphMetrics(i).getAdvance(); } } /** * Calculates advance delta between two characters * @param start - 1st position * @param end - 2nd position * @return advance increment between specified positions */ @Override float getAdvanceDelta(int start, int end) { // Get coordinates in the segment context start -= info.start; end -= info.start; if (advanceIncrements == null) { initAdvanceMapping(); } if (start < 0) { start = 0; } if (end > info.length) { end = info.length; } float sum = 0; for (int i=start; i<end; i++) { sum += advanceIncrements[i]; } return sum; } /** * Calculates index of the character which advance is equal to * the given. If the given advance is greater then the segment * advance it returns the position after the last character. * @param advance - given advance * @param start - character, from which to start measuring advance * @return character index */ @Override int getCharIndexFromAdvance(float advance, int start) { // XXX - todo - probably, possible to optimize // Add check if the given advance is greater then // the segment advance in the beginning. In this case // we don't need to run through all increments if (advanceIncrements == null) { initAdvanceMapping(); } start -= info.start; if (start < 0) { start = 0; } int i = start; for (; i<info.length; i++) { advance -= advanceIncrements[i]; if (advance < 0) { break; } } return i + info.start; } @Override int getStart() { return info.start; } @Override int getEnd() { return info.end; } @Override int getLength() { return info.length; } /** * Attemts to create mapping of the characters to glyphs in the glyph vector. * @return array where for each character index stored corresponding glyph index */ private int[] getChar2Glyph() { if (char2glyph == null) { GlyphVector gv = getGlyphVector(); char2glyph = new int[info.length]; Arrays.fill(char2glyph, -1); // Fill glyph indicies for first characters corresponding to each glyph int charIndicies[] = gv.getGlyphCharIndices(0, gv.getNumGlyphs(), null); for (int i=0; i<charIndicies.length; i++) { char2glyph[charIndicies[i]] = i; } // If several characters corresponds to one glyph, create mapping for them // Suppose that these characters are going all together int currIndex = 0; for (int i=0; i<char2glyph.length; i++) { if (char2glyph[i] < 0) { char2glyph[i] = currIndex; } else { currIndex = char2glyph[i]; } } } return char2glyph; } /** * Creates black box bounds shape for the specified range * @param start - range sart * @param limit - range end * @return black box bounds shape */ @Override Shape getCharsBlackBoxBounds(int start, int limit) { start -= info.start; limit -= info.start; if (limit > info.length) { limit = info.length; } GeneralPath result = new GeneralPath(); int glyphIndex = 0; for (int i=start; i<limit; i++) { glyphIndex = getChar2Glyph()[i]; result.append(getGlyphVector().getGlyphVisualBounds(glyphIndex), false); } // Shift to the segment's coordinates result.transform(AffineTransform.getTranslateInstance(x, y)); return result; } /** * Calculates position of the character on the screen * @param index - character index * @return X coordinate of the character position */ @Override float getCharPosition(int index) { index -= info.start; if (index > info.length) { index = info.length; } float result = 0; int glyphIndex = getChar2Glyph()[index]; result = (float) getGlyphVector().getGlyphPosition(glyphIndex).getX(); // Shift to the segment's coordinates result += x; return result; } /** * Returns the advance of the individual character * @param index - character index * @return character advance */ @Override float getCharAdvance(int index) { if (advanceIncrements == null) { initAdvanceMapping(); } return advanceIncrements[index - this.getStart()]; } /** * Returns the outline shape * @return outline */ @Override Shape getOutline() { AffineTransform t = AffineTransform.getTranslateInstance(x, y); return t.createTransformedShape( TextDecorator.extendOutline( this, getGlyphVector().getOutline(), decoration ) ); } /** * Checks if the character doesn't contribute to the text advance * @param index - character index * @return true if the character has zero advance */ @Override boolean charHasZeroAdvance(int index) { if (advanceIncrements == null) { initAdvanceMapping(); } return advanceIncrements[index - this.getStart()] == 0; } /** * Creates text hit info from the hit position * @param hitX - X coordinate relative to the origin of the layout * @param hitY - Y coordinate relative to the origin of the layout * @return hit info */ @Override TextHitInfo hitTest(float hitX, float hitY) { hitX -= x; float glyphPositions[] = getGlyphVector().getGlyphPositions(0, info.length+1, null); int glyphIdx; boolean leading = false; for (glyphIdx = 1; glyphIdx <= info.length; glyphIdx++) { if (glyphPositions[(glyphIdx)*2] >= hitX) { float advance = glyphPositions[(glyphIdx)*2] - glyphPositions[(glyphIdx-1)*2]; leading = glyphPositions[(glyphIdx-1)*2] + advance/2 > hitX ? true : false; glyphIdx--; break; } } if (glyphIdx == info.length) { glyphIdx--; } int charIdx = getGlyphVector().getGlyphCharIndex(glyphIdx); return (leading) ^ ((info.level & 0x1) == 0x1)? TextHitInfo.leading(charIdx + info.start) : TextHitInfo.trailing(charIdx + info.start); } /** * Collects GlyphJustificationInfo objects from the glyph vector * @return array of all GlyphJustificationInfo objects */ private GlyphJustificationInfo[] getGlyphJustificationInfos() { if (gjis == null) { GlyphVector gv = getGlyphVector(); int nGlyphs = gv.getNumGlyphs(); int charIndicies[] = gv.getGlyphCharIndices(0, nGlyphs, null); gjis = new GlyphJustificationInfo[nGlyphs]; // Patch: temporary patch, getGlyphJustificationInfo is not implemented float fontSize = info.font.getSize2D(); GlyphJustificationInfo defaultInfo = new GlyphJustificationInfo( 0, // weight false, GlyphJustificationInfo.PRIORITY_NONE, 0, 0, // grow false, GlyphJustificationInfo.PRIORITY_NONE, 0, 0); // shrink GlyphJustificationInfo spaceInfo = new GlyphJustificationInfo( fontSize, // weight true, GlyphJustificationInfo.PRIORITY_WHITESPACE, 0, fontSize, // grow true, GlyphJustificationInfo.PRIORITY_WHITESPACE, 0, fontSize); // shrink //////// // Temporary patch, getGlyphJustificationInfo is not implemented for (int i = 0; i < nGlyphs; i++) { //gjis[i] = getGlyphVector().getGlyphJustificationInfo(i); char c = info.text[charIndicies[i] + info.start]; if (Character.isWhitespace(c)) { gjis[i] = spaceInfo; } else { gjis[i] = defaultInfo; } // End patch } } return gjis; } /** * Collects justification information into JustificationInfo object * @param jInfo - JustificationInfo object */ @Override void updateJustificationInfo(TextRunBreaker.JustificationInfo jInfo) { int lastChar = Math.min(jInfo.lastIdx, info.end) - info.start; boolean haveFirst = info.start <= jInfo.firstIdx; boolean haveLast = info.end >= (jInfo.lastIdx + 1); int prevGlyphIdx = -1; int currGlyphIdx; if (jInfo.grow) { // Check how much we can grow/shrink on current priority level for (int i=0; i<lastChar; i++) { currGlyphIdx = getChar2Glyph()[i]; if (currGlyphIdx == prevGlyphIdx) { // Several chars could be represented by one glyph, // suppose they are contiguous continue; } prevGlyphIdx = currGlyphIdx; GlyphJustificationInfo gji = getGlyphJustificationInfos()[currGlyphIdx]; if (gji.growPriority == jInfo.priority) { jInfo.weight += gji.weight * 2; jInfo.growLimit += gji.growLeftLimit; jInfo.growLimit += gji.growRightLimit; if (gji.growAbsorb) { jInfo.absorbedWeight += gji.weight * 2; } } } } else { for (int i=0; i<lastChar; i++) { currGlyphIdx = getChar2Glyph()[i]; if (currGlyphIdx == prevGlyphIdx) { continue; } prevGlyphIdx = currGlyphIdx; GlyphJustificationInfo gji = getGlyphJustificationInfos()[currGlyphIdx]; if (gji.shrinkPriority == jInfo.priority) { jInfo.weight += gji.weight * 2; jInfo.growLimit -= gji.shrinkLeftLimit; jInfo.growLimit -= gji.shrinkRightLimit; if (gji.shrinkAbsorb) { jInfo.absorbedWeight += gji.weight * 2; } } } } if (haveFirst) { // Don't add padding before first char GlyphJustificationInfo gji = getGlyphJustificationInfos()[getChar2Glyph()[0]]; jInfo.weight -= gji.weight; if (jInfo.grow) { jInfo.growLimit -= gji.growLeftLimit; if (gji.growAbsorb) { jInfo.absorbedWeight -= gji.weight; } } else { jInfo.growLimit += gji.shrinkLeftLimit; if (gji.shrinkAbsorb) { jInfo.absorbedWeight -= gji.weight; } } } if (haveLast) { // Don't add padding after last char GlyphJustificationInfo gji = getGlyphJustificationInfos()[getChar2Glyph()[lastChar]]; jInfo.weight -= gji.weight; if (jInfo.grow) { jInfo.growLimit -= gji.growRightLimit; if (gji.growAbsorb) { jInfo.absorbedWeight -= gji.weight; } } else { jInfo.growLimit += gji.shrinkRightLimit; if (gji.shrinkAbsorb) { jInfo.absorbedWeight -= gji.weight; } } } } /** * Performs justification of the segment. * Updates positions of individual characters. * @param jInfos - justification information, gathered by the previous passes * @return amount of growth or shrink of the segment */ @Override float doJustification(TextRunBreaker.JustificationInfo jInfos[]) { int lastPriority = jInfos[jInfos.length-1] == null ? -1 : jInfos[jInfos.length-1].priority; // Get the highest priority int highestPriority = 0; for (; highestPriority<jInfos.length; highestPriority++) { if (jInfos[highestPriority] != null) { break; } } if (highestPriority == jInfos.length) { return 0; } TextRunBreaker.JustificationInfo firstInfo = jInfos[highestPriority]; TextRunBreaker.JustificationInfo lastInfo = lastPriority > 0 ? jInfos[lastPriority] : null; boolean haveFirst = info.start <= firstInfo.firstIdx; boolean haveLast = info.end >= (firstInfo.lastIdx + 1); // Here we suppose that GLYPHS are ordered LEFT TO RIGHT int firstGlyph = haveFirst ? getChar2Glyph()[firstInfo.firstIdx - info.start] : getChar2Glyph()[0]; int lastGlyph = haveLast ? getChar2Glyph()[firstInfo.lastIdx - info.start] : getChar2Glyph()[info.length - 1]; if (haveLast) { lastGlyph--; } TextRunBreaker.JustificationInfo currInfo; float glyphOffset = 0; float positionIncrement = 0; float sideIncrement = 0; if (haveFirst) { // Don't add padding before first char GlyphJustificationInfo gji = getGlyphJustificationInfos()[firstGlyph]; currInfo = jInfos[gji.growPriority]; if (currInfo != null) { if (currInfo.useLimits) { if (currInfo.absorb) { glyphOffset += gji.weight * currInfo.absorbedGapPerUnit; } else if ( lastInfo != null && lastInfo.priority == currInfo.priority ) { glyphOffset += gji.weight * lastInfo.absorbedGapPerUnit; } glyphOffset += firstInfo.grow ? gji.growRightLimit : -gji.shrinkRightLimit; } else { glyphOffset += gji.weight * currInfo.gapPerUnit; } } firstGlyph++; } if (firstInfo.grow) { for (int i=firstGlyph; i<=lastGlyph; i++) { GlyphJustificationInfo gji = getGlyphJustificationInfos()[i]; currInfo = jInfos[gji.growPriority]; if (currInfo == null) { // We still have to increment glyph position Point2D glyphPos = getGlyphVector().getGlyphPosition(i); glyphPos.setLocation(glyphPos.getX() + glyphOffset, glyphPos.getY()); getGlyphVector().setGlyphPosition(i, glyphPos); continue; } if (currInfo.useLimits) { glyphOffset += gji.growLeftLimit; if (currInfo.absorb) { sideIncrement = gji.weight * currInfo.absorbedGapPerUnit; glyphOffset += sideIncrement; positionIncrement = glyphOffset; glyphOffset += sideIncrement; } else if (lastInfo != null && lastInfo.priority == currInfo.priority) { sideIncrement = gji.weight * lastInfo.absorbedGapPerUnit; glyphOffset += sideIncrement; positionIncrement = glyphOffset; glyphOffset += sideIncrement; } else { positionIncrement = glyphOffset; } glyphOffset += gji.growRightLimit; } else { sideIncrement = gji.weight * currInfo.gapPerUnit; glyphOffset += sideIncrement; positionIncrement = glyphOffset; glyphOffset += sideIncrement; } Point2D glyphPos = getGlyphVector().getGlyphPosition(i); glyphPos.setLocation(glyphPos.getX() + positionIncrement, glyphPos.getY()); getGlyphVector().setGlyphPosition(i, glyphPos); } } else { for (int i=firstGlyph; i<=lastGlyph; i++) { GlyphJustificationInfo gji = getGlyphJustificationInfos()[i]; currInfo = jInfos[gji.shrinkPriority]; if (currInfo == null) { // We still have to increment glyph position Point2D glyphPos = getGlyphVector().getGlyphPosition(i); glyphPos.setLocation(glyphPos.getX() + glyphOffset, glyphPos.getY()); getGlyphVector().setGlyphPosition(i, glyphPos); continue; } if (currInfo.useLimits) { glyphOffset -= gji.shrinkLeftLimit; if (currInfo.absorb) { sideIncrement = gji.weight * currInfo.absorbedGapPerUnit; glyphOffset += sideIncrement; positionIncrement = glyphOffset; glyphOffset += sideIncrement; } else if (lastInfo != null && lastInfo.priority == currInfo.priority) { sideIncrement = gji.weight * lastInfo.absorbedGapPerUnit; glyphOffset += sideIncrement; positionIncrement = glyphOffset; glyphOffset += sideIncrement; } else { positionIncrement = glyphOffset; } glyphOffset -= gji.shrinkRightLimit; } else { sideIncrement = gji.weight * currInfo.gapPerUnit; glyphOffset += sideIncrement; positionIncrement = glyphOffset; glyphOffset += sideIncrement; } Point2D glyphPos = getGlyphVector().getGlyphPosition(i); glyphPos.setLocation(glyphPos.getX() + positionIncrement, glyphPos.getY()); getGlyphVector().setGlyphPosition(i, glyphPos); } } if (haveLast) { // Don't add padding after last char lastGlyph++; GlyphJustificationInfo gji = getGlyphJustificationInfos()[lastGlyph]; currInfo = jInfos[gji.growPriority]; if (currInfo != null) { if (currInfo.useLimits) { glyphOffset += firstInfo.grow ? gji.growLeftLimit : -gji.shrinkLeftLimit; if (currInfo.absorb) { glyphOffset += gji.weight * currInfo.absorbedGapPerUnit; } else if (lastInfo != null && lastInfo.priority == currInfo.priority) { glyphOffset += gji.weight * lastInfo.absorbedGapPerUnit; } } else { glyphOffset += gji.weight * currInfo.gapPerUnit; } } // Ajust positions of all glyphs after last glyph for (int i=lastGlyph; i<getGlyphVector().getNumGlyphs()+1; i++) { Point2D glyphPos = getGlyphVector().getGlyphPosition(i); glyphPos.setLocation(glyphPos.getX() + glyphOffset, glyphPos.getY()); getGlyphVector().setGlyphPosition(i, glyphPos); } } else { // Update position after last glyph in glyph vector - // to get correct advance for it Point2D glyphPos = getGlyphVector().getGlyphPosition(lastGlyph+1); glyphPos.setLocation(glyphPos.getX() + glyphOffset, glyphPos.getY()); getGlyphVector().setGlyphPosition(lastGlyph+1, glyphPos); } gjis = null; // We don't need justification infos any more // Also we have to reset cached bounds and metrics this.visualBounds = null; this.logicalBounds = null; return glyphOffset; // How much our segment grown or shrunk } } public static class TextRunSegmentGraphic extends TextRunSegment { GraphicAttribute ga; int start; int length; float fullAdvance; TextRunSegmentGraphic(GraphicAttribute attr, int len, int start) { this.start = start; length = len; ga = attr; metrics = new BasicMetrics(ga); fullAdvance = ga.getAdvance() * length; } @Override public Object clone() { return new TextRunSegmentGraphic(ga, length, start); } // Renders this text run segment @Override void draw(Graphics2D g2d, float xOffset, float yOffset) { if (decoration != null) { TextDecorator.prepareGraphics(this, g2d, xOffset, yOffset); } float xPos = x + xOffset; float yPos = y + yOffset; for (int i=0; i < length; i++) { ga.draw(g2d, xPos, yPos); xPos += ga.getAdvance(); } if (decoration != null) { TextDecorator.drawTextDecorations(this, g2d, xOffset, yOffset); TextDecorator.restoreGraphics(decoration, g2d); } } // Returns visual bounds of this segment @Override Rectangle2D getVisualBounds() { if (visualBounds == null) { Rectangle2D bounds = ga.getBounds(); // First and last chars can be out of logical bounds, so we calculate // (bounds.getWidth() - ga.getAdvance()) which is exactly the difference bounds.setRect( bounds.getMinX() + x, bounds.getMinY() + y, bounds.getWidth() - ga.getAdvance() + getAdvance(), bounds.getHeight() ); visualBounds = TextDecorator.extendVisualBounds(this, bounds, decoration); } return (Rectangle2D) visualBounds.clone(); } @Override Rectangle2D getLogicalBounds() { if (logicalBounds == null) { logicalBounds = new Rectangle2D.Float( x, y - metrics.ascent, getAdvance(), metrics.ascent + metrics.descent ); } return (Rectangle2D) logicalBounds.clone(); } @Override float getAdvance() { return fullAdvance; } @Override float getAdvanceDelta(int start, int end) { return ga.getAdvance() * (end - start); } @Override int getCharIndexFromAdvance(float advance, int start) { start -= this.start; if (start < 0) { start = 0; } int charOffset = (int) (advance/ga.getAdvance()); if (charOffset + start > length) { return length + this.start; } return charOffset + start + this.start; } @Override int getStart() { return start; } @Override int getEnd() { return start + length; } @Override int getLength() { return length; } @Override Shape getCharsBlackBoxBounds(int start, int limit) { start -= this.start; limit -= this.start; if (limit > length) { limit = length; } Rectangle2D charBounds = ga.getBounds(); charBounds.setRect( charBounds.getX() + ga.getAdvance() * start + x, charBounds.getY() + y, charBounds.getWidth() + ga.getAdvance() * (limit - start), charBounds.getHeight() ); return charBounds; } @Override float getCharPosition(int index) { index -= start; if (index > length) { index = length; } return ga.getAdvance() * index + x; } @Override float getCharAdvance(int index) { return ga.getAdvance(); } @Override Shape getOutline() { AffineTransform t = AffineTransform.getTranslateInstance(x, y); return t.createTransformedShape( TextDecorator.extendOutline(this, getVisualBounds(), decoration) ); } @Override boolean charHasZeroAdvance(int index) { return false; } @Override TextHitInfo hitTest(float hitX, float hitY) { hitX -= x; float tmp = hitX / ga.getAdvance(); int hitIndex = Math.round(tmp); if (tmp > hitIndex) { return TextHitInfo.leading(hitIndex + this.start); } return TextHitInfo.trailing(hitIndex + this.start); } @Override void updateJustificationInfo(TextRunBreaker.JustificationInfo jInfo) { // Do nothing } @Override float doJustification(TextRunBreaker.JustificationInfo jInfos[]) { // Do nothing return 0; } } } <|start_filename|>enhanced/archive/classlib/java6/modules/awt/src/main/java/common/org/apache/harmony/awt/gl/color/NativeCMM.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author <NAME> * @version $Revision$ */ package org.apache.harmony.awt.gl.color; import java.awt.color.ICC_Profile; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.HashMap; /** * This class is a wrapper for the native CMM library */ public class NativeCMM { /** * Storage for profile handles, since they are private * in ICC_Profile, but we need access to them. */ private static HashMap<ICC_Profile, Long> profileHandles = new HashMap<ICC_Profile, Long>(); private static boolean isCMMLoaded; public static void addHandle(ICC_Profile key, long handle) { profileHandles.put(key, new Long(handle)); } public static void removeHandle(ICC_Profile key) { profileHandles.remove(key); } public static long getHandle(ICC_Profile key) { return profileHandles.get(key).longValue(); } /* ICC profile management */ public static native long cmmOpenProfile(byte[] data); public static native void cmmCloseProfile(long profileID); public static native int cmmGetProfileSize(long profileID); public static native void cmmGetProfile(long profileID, byte[] data); public static native int cmmGetProfileElementSize(long profileID, int signature); public static native void cmmGetProfileElement(long profileID, int signature, byte[] data); public static native void cmmSetProfileElement(long profileID, int tagSignature, byte[] data); /* ICC transforms */ public static native long cmmCreateMultiprofileTransform( long[] profileHandles, int[] renderingIntents ); public static native void cmmDeleteTransform(long transformHandle); public static native void cmmTranslateColors(long transformHandle, NativeImageFormat src, NativeImageFormat dest); static void loadCMM() { if (!isCMMLoaded) { AccessController.doPrivileged( new PrivilegedAction<Void>() { public Void run() { System.loadLibrary("lcmm"); //$NON-NLS-1$ return null; } } ); isCMMLoaded = true; } } /* load native CMM library */ static { loadCMM(); } } <|start_filename|>enhanced/archive/classlib/java6/modules/awt/src/main/java/common/org/apache/harmony/awt/gl/CommonGraphics2D.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author <NAME> * @version $Revision$ */ package org.apache.harmony.awt.gl; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Paint; import java.awt.PaintContext; import java.awt.Point; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.Toolkit; import java.awt.font.FontRenderContext; import java.awt.font.GlyphVector; import java.awt.image.AffineTransformOp; import java.awt.image.ImageObserver; import java.awt.image.BufferedImage; import java.awt.image.BufferedImageOp; import java.awt.image.Raster; import java.awt.image.RenderedImage; import java.awt.image.WritableRaster; import java.awt.image.renderable.RenderableImage; import java.awt.geom.AffineTransform; import java.awt.geom.Arc2D; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.PathIterator; import java.awt.geom.RoundRectangle2D; import java.text.AttributedCharacterIterator; import java.util.Map; import org.apache.harmony.awt.gl.Surface; import org.apache.harmony.awt.gl.image.OffscreenImage; import org.apache.harmony.awt.gl.render.Blitter; import org.apache.harmony.awt.gl.render.JavaArcRasterizer; import org.apache.harmony.awt.gl.render.JavaLineRasterizer; import org.apache.harmony.awt.gl.render.JavaShapeRasterizer; import org.apache.harmony.awt.gl.render.JavaTextRenderer; import org.apache.harmony.awt.gl.render.NullBlitter; /* * List of abstract methods to implement in subclusses * Graphics.copyArea(int x, int y, int width, int height, int dx, int dy) * Graphics.create() * Graphics2D.getDeviceConfiguration() * CommonGraphics2D.fillMultiRectAreaColor(MultiRectArea mra); * CommonGraphics2D.fillMultiRectAreaPaint(MultiRectArea mra); */ /** * CommonGraphics2D class is a super class for all system-dependent * implementations. It implements major part of Graphics and Graphics2D * abstract methods. * <h2>CommonGraphics2D Class Internals</h2> * <h3>Line and Shape Rasterizers</h3> * <p> * The CommonGraphics2D class splits all shapes into a set of rectangles * to unify the drawing process for different operating systems and architectures. * For this purpose Java 2D* uses the JavaShapeRasterizer and the JavaLineRasterizer * classes from the org.apache.harmony.awt.gl.render package. The JavaShapeRasterizer * class splits an object implementing a Shape interface into a set of rectangles and * produces a MultiRectArea object. The JavaLineRasterizer class makes line drawing * more accurate and processes lines with strokes, which are instances of the BasicStroke * class. * </p> * <p> * To port the shape drawing to another platform you just need to override * rectangle-drawing methods. However, if your operating system has functions to draw * particular shapes, you can optimize your subclass of the CommonGraphics2D class by * using this functionality in overridden methods. * </p> * <h3>Blitters</h3> * <p> * Blitter classes draw images on the display or buffered images. All blitters inherit * the org.apache.harmony.awt.gl.render.Blitter interface. * </p> * <p>Blitters are divided into: * <ul> * <li>Native blitters for simple types of images, which the underlying native library * can draw.</li> * <li>Java* blitters for those types of images, which the underlying native library * cannot handle.</li> * </ul></p> * <p> * DRL Java 2D* also uses blitters to fill the shapes and the user-defined subclasses * of the java.awt.Paint class with paints, which the system does not support. * </p> * *<h3>Text Renderers</h3> *<p> *Text renderers draw strings and glyph vectors. All text renderers are subclasses *of the org.apache.harmony.awt.gl.TextRenderer class. *</p> * */ public abstract class CommonGraphics2D extends Graphics2D { protected Surface dstSurf = null; protected Blitter blitter = NullBlitter.getInstance(); protected RenderingHints hints = new RenderingHints(null); // Clipping things protected MultiRectArea clip = null; protected Paint paint = Color.WHITE; protected Color fgColor = Color.WHITE; protected Color bgColor = Color.BLACK; protected Composite composite = AlphaComposite.SrcOver; protected Stroke stroke = new BasicStroke(); //TODO: Think more about FontRenderContext protected FontRenderContext frc = new FontRenderContext(null, false, false); protected JavaShapeRasterizer jsr = new JavaShapeRasterizer(); protected Font font = new Font("Dialog", Font.PLAIN, 12);; //$NON-NLS-1$ protected TextRenderer jtr = JavaTextRenderer.inst; // Current graphics transform protected AffineTransform transform = new AffineTransform(); protected double[] matrix = new double[6]; // Original user->device translation as transform and point //public AffineTransform origTransform = new AffineTransform(); public Point origPoint = new Point(0, 0); // Print debug output or not protected static final boolean debugOutput = "1".equals(System.getProperty("g2d.debug")); //$NON-NLS-1$ //$NON-NLS-2$ // Constructors protected CommonGraphics2D() { } protected CommonGraphics2D(int tx, int ty) { this(tx, ty, null); } protected CommonGraphics2D(int tx, int ty, MultiRectArea clip) { setTransform(AffineTransform.getTranslateInstance(tx, ty)); //origTransform = AffineTransform.getTranslateInstance(tx, ty); origPoint = new Point(tx, ty); setClip(clip); } // Public methods @Override public void addRenderingHints(Map<?,?> hints) { this.hints.putAll(hints); } @Override public void clearRect(int x, int y, int width, int height) { Color c = getColor(); Paint p = getPaint(); setColor(getBackground()); fillRect(x, y, width, height); setColor(c); setPaint(p); if (debugOutput) { System.err.println("CommonGraphics2D.clearRect("+x+", "+y+", "+width+", "+height+")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ } } @Override public void clipRect(int x, int y, int width, int height) { clip(new Rectangle(x, y, width, height)); } @Override public void clip(Shape s) { if (s == null) { clip = null; return; } MultiRectArea mra = null; if (s instanceof MultiRectArea) { mra = new MultiRectArea((MultiRectArea)s); mra.translate((int)transform.getTranslateX(), (int)transform.getTranslateY()); } else { int type = transform.getType(); if(s instanceof Rectangle && (type & (AffineTransform.TYPE_IDENTITY | AffineTransform.TYPE_TRANSLATION)) != 0){ mra = new MultiRectArea((Rectangle)s); if(type == AffineTransform.TYPE_TRANSLATION){ mra.translate((int)transform.getTranslateX(), (int)transform.getTranslateY()); } } else { s = transform.createTransformedShape(s); mra = jsr.rasterize(s, 0.5); } } if (clip == null) { setTransformedClip(mra); } else { clip.intersect(mra); setTransformedClip(clip); } } @Override public void dispose() { // Do nothing for Java only classes } /*************************************************************************** * * Draw methods * ***************************************************************************/ @Override public void draw(Shape s) { if (stroke instanceof BasicStroke && ((BasicStroke)stroke).getLineWidth() <= 1) { //TODO: Think about drawing the shape in one fillMultiRectArea call BasicStroke bstroke = (BasicStroke)stroke; JavaLineRasterizer.LineDasher ld = (bstroke.getDashArray() == null)?null:new JavaLineRasterizer.LineDasher(bstroke.getDashArray(), bstroke.getDashPhase()); PathIterator pi = s.getPathIterator(transform, 0.5); float []points = new float[6]; int x1 = Integer.MIN_VALUE; int y1 = Integer.MIN_VALUE; int cx1 = Integer.MIN_VALUE; int cy1 = Integer.MIN_VALUE; while (!pi.isDone()) { switch (pi.currentSegment(points)) { case PathIterator.SEG_MOVETO: x1 = (int)Math.floor(points[0]); y1 = (int)Math.floor(points[1]); cx1 = x1; cy1 = y1; break; case PathIterator.SEG_LINETO: int x2 = (int)Math.floor(points[0]); int y2 = (int)Math.floor(points[1]); fillMultiRectArea(JavaLineRasterizer.rasterize(x1, y1, x2, y2, null, ld, false)); x1 = x2; y1 = y2; break; case PathIterator.SEG_CLOSE: x2 = cx1; y2 = cy1; fillMultiRectArea(JavaLineRasterizer.rasterize(x1, y1, x2, y2, null, ld, false)); x1 = x2; y1 = y2; break; } pi.next(); } } else { s = stroke.createStrokedShape(s); s = transform.createTransformedShape(s); fillMultiRectArea(jsr.rasterize(s, 0.5)); } } @Override public void drawArc(int x, int y, int width, int height, int sa, int ea) { if (stroke instanceof BasicStroke && ((BasicStroke)stroke).getLineWidth() <= 1 && ((BasicStroke)stroke).getDashArray() == null && (transform.isIdentity() || transform.getType() == AffineTransform.TYPE_TRANSLATION)) { Point p = new Point(x, y); transform.transform(p, p); MultiRectArea mra = JavaArcRasterizer.rasterize(x, y, width, height, sa, ea, clip); fillMultiRectArea(mra); return; } draw(new Arc2D.Float(x, y, width, height, sa, ea, Arc2D.OPEN)); } @Override public boolean drawImage(Image image, int x, int y, Color bgcolor, ImageObserver imageObserver) { if(image == null) { return true; } boolean done = false; boolean somebits = false; Surface srcSurf = null; if(image instanceof OffscreenImage){ OffscreenImage oi = (OffscreenImage) image; if((oi.getState() & ImageObserver.ERROR) != 0) { return false; } done = oi.prepareImage(imageObserver); somebits = (oi.getState() & ImageObserver.SOMEBITS) != 0; srcSurf = oi.getImageSurface(); }else{ done = true; srcSurf = Surface.getImageSurface(image); } if(done || somebits) { int w = srcSurf.getWidth(); int h = srcSurf.getHeight(); blitter.blit(0, 0, srcSurf, x, y, dstSurf, w, h, (AffineTransform) transform.clone(), composite, bgcolor, clip); } return done; } @Override public boolean drawImage(Image image, int x, int y, ImageObserver imageObserver) { return drawImage(image, x, y, null, imageObserver); } @Override public boolean drawImage(Image image, int x, int y, int width, int height, Color bgcolor, ImageObserver imageObserver) { if(image == null) { return true; } if(width == 0 || height == 0) { return true; } boolean done = false; boolean somebits = false; Surface srcSurf = null; if(image instanceof OffscreenImage){ OffscreenImage oi = (OffscreenImage) image; if((oi.getState() & ImageObserver.ERROR) != 0) { return false; } done = oi.prepareImage(imageObserver); somebits = (oi.getState() & ImageObserver.SOMEBITS) != 0; srcSurf = oi.getImageSurface(); }else{ done = true; srcSurf = Surface.getImageSurface(image); } if(done || somebits) { int w = srcSurf.getWidth(); int h = srcSurf.getHeight(); if(w == width && h == height){ blitter.blit(0, 0, srcSurf, x, y, dstSurf, w, h, (AffineTransform) transform.clone(), composite, bgcolor, clip); }else{ AffineTransform xform = new AffineTransform(); xform.setToScale((float)width / w, (float)height / h); blitter.blit(0, 0, srcSurf, x, y, dstSurf, w, h, (AffineTransform) transform.clone(), xform, composite, bgcolor, clip); } } return done; } @Override public boolean drawImage(Image image, int x, int y, int width, int height, ImageObserver imageObserver) { return drawImage(image, x, y, width, height, null, imageObserver); } @Override public boolean drawImage(Image image, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver imageObserver) { if(image == null) { return true; } if(dx1 == dx2 || dy1 == dy2 || sx1 == sx2 || sy1 == sy2) { return true; } boolean done = false; boolean somebits = false; Surface srcSurf = null; if(image instanceof OffscreenImage){ OffscreenImage oi = (OffscreenImage) image; if((oi.getState() & ImageObserver.ERROR) != 0) { return false; } done = oi.prepareImage(imageObserver); somebits = (oi.getState() & ImageObserver.SOMEBITS) != 0; srcSurf = oi.getImageSurface(); }else{ done = true; srcSurf = Surface.getImageSurface(image); } if(done || somebits) { int dstX = dx1; int dstY = dy1; int srcX = sx1; int srcY = sy1; int dstW = dx2 - dx1; int dstH = dy2 - dy1; int srcW = sx2 - sx1; int srcH = sy2 - sy1; if(srcW == dstW && srcH == dstH){ blitter.blit(srcX, srcY, srcSurf, dstX, dstY, dstSurf, srcW, srcH, (AffineTransform) transform.clone(), composite, bgcolor, clip); }else{ AffineTransform xform = new AffineTransform(); xform.setToScale((float)dstW / srcW, (float)dstH / srcH); blitter.blit(srcX, srcY, srcSurf, dstX, dstY, dstSurf, srcW, srcH, (AffineTransform) transform.clone(), xform, composite, bgcolor, clip); } } return done; } @Override public boolean drawImage(Image image, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver imageObserver) { return drawImage(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, null, imageObserver); } @Override public void drawImage(BufferedImage bufImage, BufferedImageOp op, int x, int y) { if(bufImage == null) { return; } if(op == null) { drawImage(bufImage, x, y, null); } else if(op instanceof AffineTransformOp){ AffineTransformOp atop = (AffineTransformOp) op; AffineTransform xform = atop.getTransform(); Surface srcSurf = Surface.getImageSurface(bufImage); int w = srcSurf.getWidth(); int h = srcSurf.getHeight(); blitter.blit(0, 0, srcSurf, x, y, dstSurf, w, h, (AffineTransform) transform.clone(), xform, composite, null, clip); } else { bufImage = op.filter(bufImage, null); Surface srcSurf = Surface.getImageSurface(bufImage); int w = srcSurf.getWidth(); int h = srcSurf.getHeight(); blitter.blit(0, 0, srcSurf, x, y, dstSurf, w, h, (AffineTransform) transform.clone(), composite, null, clip); } } @Override public boolean drawImage(Image image, AffineTransform trans, ImageObserver imageObserver) { if(image == null) { return true; } if(trans == null || trans.isIdentity()) { return drawImage(image, 0, 0, imageObserver); } boolean done = false; boolean somebits = false; Surface srcSurf = null; if(image instanceof OffscreenImage){ OffscreenImage oi = (OffscreenImage) image; if((oi.getState() & ImageObserver.ERROR) != 0) { return false; } done = oi.prepareImage(imageObserver); somebits = (oi.getState() & ImageObserver.SOMEBITS) != 0; srcSurf = oi.getImageSurface(); }else{ done = true; srcSurf = Surface.getImageSurface(image); } if(done || somebits) { int w = srcSurf.getWidth(); int h = srcSurf.getHeight(); AffineTransform xform = (AffineTransform) transform.clone(); xform.concatenate(trans); blitter.blit(0, 0, srcSurf, 0, 0, dstSurf, w, h, xform, composite, null, clip); } return done; } @Override public void drawLine(int x1, int y1, int x2, int y2) { if (debugOutput) { System.err.println("CommonGraphics2D.drawLine("+x1+", "+y1+", "+x2+", "+y2+")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ } if (stroke instanceof BasicStroke && ((BasicStroke)stroke).getLineWidth() <= 1) { BasicStroke bstroke = (BasicStroke)stroke; Point p1 = new Point(x1, y1); Point p2 = new Point(x2, y2); transform.transform(p1, p1); transform.transform(p2, p2); JavaLineRasterizer.LineDasher ld = (bstroke.getDashArray() == null)?null:new JavaLineRasterizer.LineDasher(bstroke.getDashArray(), bstroke.getDashPhase()); MultiRectArea mra = JavaLineRasterizer.rasterize(p1.x, p1.y, p2.x, p2.y, null, ld, false); fillMultiRectArea(mra); return; } draw(new Line2D.Float(x1, y1, x2, y2)); } @Override public void drawOval(int x, int y, int width, int height) { if (stroke instanceof BasicStroke && ((BasicStroke)stroke).getLineWidth() <= 1 && ((BasicStroke)stroke).getDashArray() == null && (transform.isIdentity() || transform.getType() == AffineTransform.TYPE_TRANSLATION)) { Point p = new Point(x, y); transform.transform(p, p); MultiRectArea mra = JavaArcRasterizer.rasterize(x, y, width, height, 0, 360, clip); fillMultiRectArea(mra); return; } draw(new Ellipse2D.Float(x, y, width, height)); } @Override public void drawPolygon(int[] xpoints, int[] ypoints, int npoints) { draw(new Polygon(xpoints, ypoints, npoints)); } @Override public void drawPolygon(Polygon polygon) { draw(polygon); } @Override public void drawPolyline(int[] xpoints, int[] ypoints, int npoints) { for (int i = 0; i < npoints-1; i++) { drawLine(xpoints[i], ypoints[i], xpoints[i+1], ypoints[i+1]); } } @Override public void drawRenderableImage(RenderableImage img, AffineTransform xform) { if (img == null) { return; } double scaleX = xform.getScaleX(); double scaleY = xform.getScaleY(); if (scaleX == 1 && scaleY == 1) { drawRenderedImage(img.createDefaultRendering(), xform); } else { int width = (int)Math.round(img.getWidth()*scaleX); int height = (int)Math.round(img.getHeight()*scaleY); xform = (AffineTransform)xform.clone(); xform.scale(1, 1); drawRenderedImage(img.createScaledRendering(width, height, null), xform); } } @Override public void drawRenderedImage(RenderedImage rimg, AffineTransform xform) { if (rimg == null) { return; } Image img = null; if (rimg instanceof Image) { img = (Image)rimg; } else { //TODO: Create new class to provide Image interface for RenderedImage or rewrite this method img = new BufferedImage(rimg.getColorModel(), rimg.copyData(null), false, null); } drawImage(img, xform, null); } @Override public void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { if (debugOutput) { System.err.println("CommonGraphics2D.drawRoundRect("+x+", "+y+", "+width+", "+height+","+arcWidth+", "+arcHeight+")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ } draw(new RoundRectangle2D.Float(x, y, width, height, arcWidth, arcHeight)); } /*************************************************************************** * * String methods * ***************************************************************************/ @Override public void drawString(AttributedCharacterIterator iterator, float x, float y) { GlyphVector gv = font.createGlyphVector(frc, iterator); drawGlyphVector(gv, x, y); } @Override public void drawString(AttributedCharacterIterator iterator, int x, int y) { drawString(iterator, (float)x, (float)y); } @Override public void drawString(String str, int x, int y) { drawString(str, (float)x, (float)y); } @Override public void drawString(String str, float x, float y) { if (debugOutput) { System.err.println("CommonGraphics2D.drawString("+str+", "+x+", "+y+")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } AffineTransform at = (AffineTransform)this.getTransform().clone(); AffineTransform fontTransform = font.getTransform(); at.concatenate(fontTransform); double[] matrix = new double[6]; if (!at.isIdentity()){ int atType = at.getType(); at.getMatrix(matrix); // TYPE_TRANSLATION if (atType == AffineTransform.TYPE_TRANSLATION){ jtr.drawString(this, str, (float)(x+fontTransform.getTranslateX()), (float)(y+fontTransform.getTranslateY())); return; } // TODO: we use slow type of drawing strings when Font object // in Graphics has transforms, we just fill outlines. New textrenderer // is to be implemented. Shape sh = font.createGlyphVector(this.getFontRenderContext(), str).getOutline(x, y); this.fill(sh); } else { jtr.drawString(this, str, x, y); } } @Override public void drawGlyphVector(GlyphVector gv, float x, float y) { AffineTransform at = gv.getFont().getTransform(); double[] matrix = new double[6]; if ((at != null) && (!at.isIdentity())){ int atType = at.getType(); at.getMatrix(matrix); // TYPE_TRANSLATION if ((atType == AffineTransform.TYPE_TRANSLATION) && ((gv.getLayoutFlags() & GlyphVector.FLAG_HAS_TRANSFORMS) == 0)){ jtr.drawGlyphVector(this, gv, (int)(x+matrix[4]), (int)(y+matrix[5])); return; } } else { if (((gv.getLayoutFlags() & GlyphVector.FLAG_HAS_TRANSFORMS) == 0)){ jtr.drawGlyphVector(this, gv, x, y); return; } } // TODO: we use slow type of drawing strings when Font object // in Graphics has transforms, we just fill outlines. New textrenderer // is to be implemented. Shape sh = gv.getOutline(x, y); this.fill(sh); } /*************************************************************************** * * Fill methods * ***************************************************************************/ @Override public void fill(Shape s) { s = transform.createTransformedShape(s); MultiRectArea mra = jsr.rasterize(s, 0.5); fillMultiRectArea(mra); } @Override public void fillArc(int x, int y, int width, int height, int sa, int ea) { fill(new Arc2D.Float(x, y, width, height, sa, ea, Arc2D.PIE)); } @Override public void fillOval(int x, int y, int width, int height) { fill(new Ellipse2D.Float(x, y, width, height)); } @Override public void fillPolygon(int[] xpoints, int[] ypoints, int npoints) { fill(new Polygon(xpoints, ypoints, npoints)); } @Override public void fillPolygon(Polygon polygon) { fill(polygon); } @Override public void fillRect(int x, int y, int width, int height) { if (debugOutput) { System.err.println("CommonGraphics2D.fillRect("+x+", "+y+", "+width+", "+height+")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ } fill(new Rectangle(x, y, width, height)); } @Override public void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { if (debugOutput) { System.err.println("CommonGraphics2D.fillRoundRect("+x+", "+y+", "+width+", "+height+","+arcWidth+", "+arcHeight+")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ } fill(new RoundRectangle2D.Float(x, y, width, height, arcWidth, arcHeight)); } /*************************************************************************** * * Get methods * ***************************************************************************/ @Override public Color getBackground() { return bgColor; } @Override public Shape getClip() { if (clip == null) { return null; } MultiRectArea res = new MultiRectArea(clip); res.translate(-Math.round((float)transform.getTranslateX()), -Math.round((float)transform.getTranslateY())); return res; } @Override public Rectangle getClipBounds() { if (clip == null) { return null; } Rectangle res = (Rectangle) clip.getBounds().clone(); res.translate(-Math.round((float)transform.getTranslateX()), -Math.round((float)transform.getTranslateY())); return res; } @Override public Color getColor() { return fgColor; } @Override public Composite getComposite() { return composite; } @Override public Font getFont() { return font; } @SuppressWarnings("deprecation") @Override public FontMetrics getFontMetrics(Font font) { return Toolkit.getDefaultToolkit().getFontMetrics(font); } @Override public FontRenderContext getFontRenderContext() { return frc; } @Override public Paint getPaint() { return paint; } @Override public Object getRenderingHint(RenderingHints.Key key) { return hints.get(key); } @Override public RenderingHints getRenderingHints() { return hints; } @Override public Stroke getStroke() { return stroke; } @Override public AffineTransform getTransform() { return (AffineTransform)transform.clone(); } @Override public boolean hit(Rectangle rect, Shape s, boolean onStroke) { //TODO: Implement method.... return false; } /*************************************************************************** * * Transformation methods * ***************************************************************************/ @Override public void rotate(double theta) { transform.rotate(theta); transform.getMatrix(matrix); } @Override public void rotate(double theta, double x, double y) { transform.rotate(theta, x, y); transform.getMatrix(matrix); } @Override public void scale(double sx, double sy) { transform.scale(sx, sy); transform.getMatrix(matrix); } @Override public void shear(double shx, double shy) { transform.shear(shx, shy); transform.getMatrix(matrix); } @Override public void transform(AffineTransform at) { transform.concatenate(at); transform.getMatrix(matrix); } @Override public void translate(double tx, double ty) { if (debugOutput) { System.err.println("CommonGraphics2D.translate("+tx+", "+ty+")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } transform.translate(tx, ty); transform.getMatrix(matrix); } @Override public void translate(int tx, int ty) { if (debugOutput) { System.err.println("CommonGraphics2D.translate("+tx+", "+ty+")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } transform.translate(tx, ty); transform.getMatrix(matrix); } /*************************************************************************** * * Set methods * ***************************************************************************/ @Override public void setBackground(Color color) { bgColor = color; } @Override public void setClip(int x, int y, int width, int height) { setClip(new Rectangle(x, y, width, height)); } @Override public void setClip(Shape s) { if (s == null) { setTransformedClip(null); if (debugOutput) { System.err.println("CommonGraphics2D.setClip(null)"); //$NON-NLS-1$ } return; } if (debugOutput) { System.err.println("CommonGraphics2D.setClip("+s.getBounds()+")"); //$NON-NLS-1$ //$NON-NLS-2$ } if (s instanceof MultiRectArea) { MultiRectArea nclip = new MultiRectArea((MultiRectArea)s); nclip.translate(Math.round((float)transform.getTranslateX()), Math.round((float)transform.getTranslateY())); setTransformedClip(nclip); } else { int type = transform.getType(); if(s instanceof Rectangle && (type & (AffineTransform.TYPE_IDENTITY | AffineTransform.TYPE_TRANSLATION)) != 0){ MultiRectArea nclip = new MultiRectArea((Rectangle)s); if(type == AffineTransform.TYPE_TRANSLATION){ nclip.translate((int)transform.getTranslateX(), (int)transform.getTranslateY()); } setTransformedClip(nclip); } else { s = transform.createTransformedShape(s); setTransformedClip(jsr.rasterize(s, 0.5)); } } } @Override public void setColor(Color color) { if (color != null) { fgColor = color; paint = color; } } @Override public void setComposite(Composite composite) { this.composite = composite; } @Override public void setFont(Font font) { this.font = font; } @Override public void setPaint(Paint paint) { if (paint == null) return; this.paint = paint; if (paint instanceof Color) { fgColor = (Color)paint; } } @Override public void setPaintMode() { composite = AlphaComposite.SrcOver; } @Override public void setRenderingHint(RenderingHints.Key key, Object value) { hints.put(key, value); } @Override public void setRenderingHints(Map<?,?> hints) { this.hints.clear(); this.hints.putAll(hints); } @Override public void setStroke(Stroke stroke) { this.stroke = stroke; } @Override public void setTransform(AffineTransform transform) { this.transform = transform; transform.getMatrix(matrix); } @Override public void setXORMode(Color color) { composite = new XORComposite(color); } // Protected methods protected void setTransformedClip(MultiRectArea clip) { this.clip = clip; } /** * This method fills the given MultiRectArea with current paint. * It calls fillMultiRectAreaColor and fillMultiRectAreaPaint * methods depending on the type of current paint. * @param mra MultiRectArea to fill */ protected void fillMultiRectArea(MultiRectArea mra) { if (clip != null) { mra.intersect(clip); } // Return if all stuff is clipped if (mra.rect[0] < 5) { return; } if (debugOutput) { System.err.println("CommonGraphics2D.fillMultiRectArea("+mra+")"); //$NON-NLS-1$ //$NON-NLS-2$ } if (paint instanceof Color){ fillMultiRectAreaColor(mra); }else{ fillMultiRectAreaPaint(mra); } } /** * This method fills the given MultiRectArea with solid color. * @param mra MultiRectArea to fill */ protected void fillMultiRectAreaColor(MultiRectArea mra) { fillMultiRectAreaPaint(mra); } /** * This method fills the given MultiRectArea with any paint. * @param mra MultiRectArea to fill */ protected void fillMultiRectAreaPaint(MultiRectArea mra) { Rectangle rec = mra.getBounds(); int x = rec.x; int y = rec.y; int w = rec.width; int h = rec.height; if(w <= 0 || h <= 0) { return; } PaintContext pc = paint.createContext(null, rec, rec, transform, hints); Raster r = pc.getRaster(x, y, w, h); WritableRaster wr; if(r instanceof WritableRaster){ wr = (WritableRaster) r; }else{ wr = r.createCompatibleWritableRaster(); wr.setRect(r); } Surface srcSurf = new ImageSurface(pc.getColorModel(), wr); blitter.blit(0, 0, srcSurf, x, y, dstSurf, w, h, composite, null, mra); srcSurf.dispose(); } /** * Copies graphics class fields. * Used in create method * * @param copy Graphics class to copy */ protected void copyInternalFields(CommonGraphics2D copy) { if (clip == null) { copy.setTransformedClip(null); } else { copy.setTransformedClip(new MultiRectArea(clip)); } copy.setBackground(bgColor); copy.setColor(fgColor); copy.setPaint(paint); copy.setComposite(composite); copy.setStroke(stroke); copy.setFont(font); copy.setTransform(new AffineTransform(transform)); //copy.origTransform = new AffineTransform(origTransform); copy.origPoint = new Point(origPoint); } } <|start_filename|>enhanced/archive/classlib/java6/modules/awt/src/main/java/common/org/apache/harmony/awt/wtk/Synchronizer.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author <NAME> * @version $Revision$ */ package org.apache.harmony.awt.wtk; import java.util.Hashtable; import java.util.LinkedList; import org.apache.harmony.awt.internal.nls.Messages; /** * Class synchronizer is to protect AWT state integrity in multithreading environment. * It is supposed to have a child class per native platform. * The only instance is created on the first use of one of the core AWT classes. * Registers WTK on the dispatch thread startup. * It is just a special kind of mutex. * */ public class Synchronizer { //TODO: think about java.util.concurrent use for faster blocking/awaking operations //TODO: think about all synchronized methods. Is there need to synchronize everything? /** * This field holds the counter of lock operation. * To free synchronizer unlock method must be called $acquestCounter times. * Equals to 0 when synchronizer is free. */ protected int acquestCounter; /** * This field holds the owner of synchronizer. * Owner of synchronizer is a last thread that successfully locked synchronizer and * still havn't freed it. Equals to null when synchronizer is free. */ protected Thread owner; /** * This field holds the wait queue. * Wait queue is a queue where thread wait for synchronizer access. * Empty when synchronizer is free. */ protected final LinkedList<Thread> waitQueue = new LinkedList<Thread>(); /** * The event dispatch thread */ protected Thread dispatchThread; private final Hashtable<Thread, Integer> storedStates = new Hashtable<Thread, Integer>(); /** * Acquire the lock for this synchronizer. Nested lock is supported. * If the mutex is already locked by another thread, the current thread will be put * into wait queue until the lock becomes available. * All user threads are served in FIFO order. Dispatch thread has higher priority. * Supposed to be used in Toolkit.lockAWT() only. */ public void lock() { synchronized (this) { Thread curThread = Thread.currentThread(); if (acquestCounter == 0) { acquestCounter = 1; owner = curThread; } else { if (owner == curThread) { acquestCounter++; } else { if (curThread == dispatchThread) { waitQueue.addFirst(curThread); } else { waitQueue.addLast(curThread); } try { wait(); } catch (InterruptedException e) { if (owner != curThread) { waitQueue.remove(curThread); // awt.1F=Waiting for resource access thread interrupted not from unlock method. throw new RuntimeException(Messages .getString("awt.1F")); //$NON-NLS-1$ } } } } } } /** * Release the lock for this synchronizer. * If wait queue is not empty the first waiting thread acquires the lock. * Supposed to be used in Toolkit.unlockAWT() only. */ public void unlock() { synchronized (this) { if (acquestCounter == 0) { // awt.20=Can't unlock not locked resource. throw new RuntimeException(Messages.getString("awt.20")); //$NON-NLS-1$ } if (owner != Thread.currentThread()) { // awt.21=Not owner can't unlock resource. throw new RuntimeException(Messages.getString("awt.21")); //$NON-NLS-1$ } acquestCounter--; if (acquestCounter == 0) { if (waitQueue.size() > 0) { acquestCounter = 1; owner = waitQueue.removeFirst(); owner.interrupt(); } else { owner = null; } } } } /** * Stores state of this synchronizer and frees it. * Supposed to be used in Toolkit.unsafeInvokeAndWaitUnderAWTLock() only in pair with * lockAndRestoreState(). * Do not call it directly. */ public void storeStateAndFree() { synchronized (this) { Thread curThread = Thread.currentThread(); if (owner != curThread) { // awt.22=Not owner can't free resource. throw new RuntimeException(Messages.getString("awt.22")); //$NON-NLS-1$ } if (storedStates.containsKey(curThread)) { // awt.23=One thread can't store state several times in a row. throw new RuntimeException(Messages.getString("awt.23")); //$NON-NLS-1$ } storedStates.put(curThread, new Integer(acquestCounter)); acquestCounter = 1; unlock(); } } /** * Locks this synchronizer and restores it's state. * Supposed to be used in Toolkit.unsafeInvokeAndWaitUnderAWTLock() only in pair with * storeStateAndFree(). * Do not call it directly. */ public void lockAndRestoreState() { synchronized (this) { Thread curThread = Thread.currentThread(); if (owner == curThread) { // awt.24=Owner can't overwrite resource state. Lock operations may be lost. throw new RuntimeException( Messages.getString("awt.24")); //$NON-NLS-1$ } if (!storedStates.containsKey(curThread)) { // awt.25=No state stored for current thread. throw new RuntimeException(Messages.getString("awt.25")); //$NON-NLS-1$ } lock(); acquestCounter = storedStates.get(curThread).intValue(); storedStates.remove(curThread); } } /** * Sets references to WTK and event dispatch thread. * Called on toolkit startup. * * @param wtk - reference to WTK instance * @param dispatchThread - reference to event dispatch thread */ public void setEnvironment(WTK wtk, Thread dispatchThread) { synchronized (this) { this.dispatchThread = dispatchThread; } } } <|start_filename|>enhanced/archive/classlib/java6/modules/luni/src/main/native/include/shared/jni_types.h<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Intel, <NAME> * @version $Revision: 1.1.2.1.4.3 $ */ #ifndef _JNI_TYPES_H_ #define _JNI_TYPES_H_ /* * @file JNI types used for OPEN interface */ #if defined (_WIN32) || defined (__WIN32__) || defined (WIN32) #define JNIEXPORT __declspec(dllexport) #define JNIIMPORT __declspec(dllimport) #define JNICALL __stdcall typedef signed __int64 jlong; #else #define JNIEXPORT #define JNIIMPORT #define JNICALL typedef signed long long jlong; #endif /* * Primitive types */ typedef unsigned char jboolean; typedef signed char jbyte; typedef unsigned short jchar; typedef signed short jshort; typedef signed int jint; typedef float jfloat; typedef double jdouble; typedef jint jsize; /* * Java types */ struct _jobject; typedef struct _jobject* jobject; typedef jobject jclass; typedef jobject jstring; typedef jobject jarray; typedef jarray jobjectArray; typedef jarray jbooleanArray; typedef jarray jbyteArray; typedef jarray jcharArray; typedef jarray jshortArray; typedef jarray jintArray; typedef jarray jlongArray; typedef jarray jfloatArray; typedef jarray jdoubleArray; typedef jobject jthrowable; typedef jobject jweak; typedef union jvalue { jboolean z; jbyte b; jchar c; jshort s; jint i; jlong j; jfloat f; jdouble d; jobject l; } jvalue; struct _jfieldID; typedef struct _jfieldID* jfieldID; struct _jmethodID; typedef struct _jmethodID* jmethodID; /* * Constants */ /* * Boolean constants */ #define JNI_FALSE 0 #define JNI_TRUE 1 /* * Return values */ #define JNI_OK 0 #define JNI_ERR (-1) #define JNI_EDETACHED (-2) #define JNI_EVERSION (-3) #define JNI_ENOMEM (-4) #define JNI_EEXIST (-5) #define JNI_EINVAL (-6) /* * Release modes for working with arrays. */ #define JNI_COMMIT 1 #define JNI_ABORT 2 /* * Used as a generic pointer to a function. */ typedef struct { char *name; char *signature; void *fnPtr; } JNINativeMethod; /* * JNI Native Method Interface */ struct JNINativeInterface_; struct JNIEnv_External; #ifdef __cplusplus typedef JNIEnv_External JNIEnv; #else typedef const struct JNINativeInterface_ *JNIEnv; #endif /* * JNI Invocation Interface */ struct JNIInvokeInterface_; struct JavaVM_External; #ifdef __cplusplus typedef JavaVM_External JavaVM; #else typedef const struct JNIInvokeInterface_ *JavaVM; #endif #endif /* _JNI_TYPES_H_ */ <|start_filename|>enhanced/archive/classlib/java6/modules/awt/src/main/java/common/org/apache/harmony/awt/wtk/ShutdownWatchdog.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author <NAME> * @version $Revision$ */ package org.apache.harmony.awt.wtk; /** * Shutdown Watchdog */ public final class ShutdownWatchdog { private boolean nativeQueueEmpty = true; private boolean awtQueueEmpty = true; private boolean windowListEmpty = true; private boolean forcedShutdown = false; private ShutdownThread thread; public synchronized void setNativeQueueEmpty(boolean empty) { nativeQueueEmpty = empty; checkShutdown(); } public synchronized void setAwtQueueEmpty(boolean empty) { awtQueueEmpty = empty; checkShutdown(); } public synchronized void setWindowListEmpty(boolean empty) { windowListEmpty = empty; checkShutdown(); } public synchronized void forceShutdown() { forcedShutdown = true; shutdown(); } public synchronized void start() { keepAlive(); } private void checkShutdown() { if (canShutdown()) { shutdown(); } else { keepAlive(); } } private boolean canShutdown() { return (nativeQueueEmpty && awtQueueEmpty && windowListEmpty) || forcedShutdown; } private void keepAlive() { if (thread == null) { thread = new ShutdownThread(); thread.start(); } } private void shutdown() { if (thread != null) { thread.shutdown(); thread = null; } } }
qinFamily/freeVM
<|start_filename|>src/Proto3/Suite/DotProto/Internal.hs<|end_filename|> -- | This module provides misc internal helpers and utilities {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ViewPatterns #-} module Proto3.Suite.DotProto.Internal where import Control.Applicative import qualified Control.Foldl as FL import Control.Lens (Lens', lens, over) import Control.Lens.Cons (_head) import Control.Monad import Control.Monad.Except import Data.Bifunctor (first) import Data.Char import Data.Coerce import Data.Either import Data.Foldable import Data.Functor.Compose import Data.Int (Int32) import Data.List (intercalate) import qualified Data.List.NonEmpty as NE import qualified Data.Map as M import Data.Maybe (fromMaybe) import qualified Data.Text as T import Data.Tuple (swap) import Filesystem.Path.CurrentOS ((</>)) import qualified Filesystem.Path.CurrentOS as FP import qualified NeatInterpolation as Neat import Prelude hiding (FilePath) import Proto3.Suite.DotProto.AST import Proto3.Suite.DotProto.AST.Lens import Proto3.Suite.DotProto.Parsing import Proto3.Wire.Types (FieldNumber (..)) import System.FilePath (isPathSeparator) import Text.Parsec (ParseError) import qualified Turtle import Turtle (ExitCode (..), FilePath, Text) import Turtle.Format ((%)) import qualified Turtle.Format as F ------------------------------------------------------------------------------- -- -- * Utilities -- #if !(MIN_VERSION_mtl(2,2,2)) liftEither :: MonadError e m => Either e a -> m a liftEither = either throwError pure #endif -- | Like 'foldMap', but with an effectful projection. foldMapM :: (Foldable t, Monad m, Monoid b, Semigroup b) => (a -> m b) -> t a -> m b foldMapM f = foldM (\b a -> (b <>) <$> f a) mempty -- | Like 'Control.Lens.Getter.Getting', but allows for retrieving the 'r' -- element in some Applicative context 'm'. type GettingM r s a = forall m. Applicative m => (a -> Compose m (Const r) a) -> s -> Compose m (Const r) s -- | Given an effectful projection from 'a' into a monoid 'r', retrieve the sum -- of all 'a' values in an 's' structure as targetted by the 'GettingM' optic. -- Note that the Monoid constraint on 'r' is implicit via 'Const', but we -- note it in the type for clarity. foldMapOfM :: (Applicative m, Monoid r) => GettingM r s a -> (a -> m r) -> s -> m r foldMapOfM l f = fmap getConst . getCompose . l (Compose . fmap Const . f) mapKeysM :: (Monad m, Ord k2) => (k1 -> m k2) -> M.Map k1 a -> m (M.Map k2 a) mapKeysM f = fmap M.fromList . traverse (fmap swap . traverse f . swap) . M.assocs -- $setup -- >>> :set -XOverloadedStrings dieLines :: MonadIO m => Text -> m a dieLines (Turtle.textToLines -> msg) = do mapM_ Turtle.err msg Turtle.exit (ExitFailure 1) -------------------------------------------------------------------------------- -- -- * Reading files -- -- | toModulePath takes an include-relative path to a .proto file and produces a -- "module path" which is used during code generation. -- -- Note that, with the exception of the '.proto' portion of the input filepath, -- this function interprets '.' in the filename components as if they were -- additional slashes (assuming that the '.' is not the first character, which -- is merely ignored). So e.g. "google/protobuf/timestamp.proto" and -- "google.protobuf.timestamp.proto" map to the same module path. -- -- >>> toModulePath "/absolute/path/fails.proto" -- Left "expected include-relative path" -- -- >>> toModulePath "relative/path/to/file_without_proto_suffix_fails" -- Left "expected .proto suffix" -- -- >>> toModulePath "relative/path/to/file_without_proto_suffix_fails.txt" -- Left "expected .proto suffix" -- -- >>> toModulePath "../foo.proto" -- Left "expected include-relative path, but the path started with ../" -- -- >>> toModulePath "foo..proto" -- Left "path contained unexpected .. after canonicalization, please use form x.y.z.proto" -- -- >>> toModulePath "foo/bar/baz..proto" -- Left "path contained unexpected .. after canonicalization, please use form x.y.z.proto" -- -- >>> toModulePath "foo.bar../baz.proto" -- Left "path contained unexpected .. after canonicalization, please use form x.y.z.proto" -- -- >>> toModulePath "google/protobuf/timestamp.proto" -- Right (Path {components = "Google" :| ["Protobuf","Timestamp"]}) -- -- >>> toModulePath "a/b/c/google.protobuf.timestamp.proto" -- Right (Path {components = "A" :| ["B","C","Google","Protobuf","Timestamp"]}) -- -- >>> toModulePath "foo/FiLeName_underscore.and.then.some.dots.proto" -- Right (Path {components = "Foo" :| ["FiLeName_underscore","And","Then","Some","Dots"]}) -- -- >>> toModulePath "foo/bar/././baz/../boggle.proto" -- Right (Path {components = "Foo" :| ["Bar","Boggle"]}) -- -- >>> toModulePath "./foo.proto" -- Right (Path {components = "Foo" :| []}) -- -- NB: We ignore preceding single '.' characters -- >>> toModulePath ".foo.proto" -- Right (Path {components = "Foo" :| []}) toModulePath :: FilePath -> Either String Path toModulePath fp0@(fromMaybe fp0 . FP.stripPrefix "./" -> fp) | Turtle.absolute fp = Left "expected include-relative path" | Turtle.extension fp /= Just "proto" = Left "expected .proto suffix" | otherwise = case FP.stripPrefix "../" fp of Just{} -> Left "expected include-relative path, but the path started with ../" Nothing | T.isInfixOf ".." . Turtle.format F.fp . FP.collapse $ fp -> Left "path contained unexpected .. after canonicalization, please use form x.y.z.proto" | otherwise -> maybe (Left "empty path after canonicalization") (Right . Path) . NE.nonEmpty . dropWhile null -- Remove a potential preceding empty component which -- arose from a preceding '.' in the input path, which we -- want to ignore. E.g. ".foo.proto" => ["","Foo"]. . fmap (T.unpack . over _head toUpper) . concatMap (T.splitOn ".") . T.split isPathSeparator . Turtle.format F.fp . FP.collapse . Turtle.dropExtension $ fp -- | @importProto searchPaths toplevel inc@ attempts to import include-relative -- @inc@ after locating it somewhere in the @searchPaths@; @toplevel@ is simply -- the path of toplevel .proto being processed so we can report it in an error -- message. This function terminates the program if it cannot find the file to -- import or if it cannot construct a valid module path from it. importProto :: (MonadIO m, MonadError CompileError m) => [FilePath] -> FilePath -> FilePath -> m DotProto importProto paths toplevelProto protoFP = findProto paths protoFP >>= \case Left e -> dieLines (badModulePathErrorMsg protoFP e) Right Nothing | toplevelProto == protoFP -> dieLines (toplevelNotFoundErrorMsg paths toplevelProto) | otherwise -> dieLines (importNotFoundErrorMsg paths toplevelProto protoFP) Right (Just (mp, fp)) -> liftEither . first CompileParseError =<< parseProtoFile mp fp type FindProtoResult = Either String (Maybe (Path, FilePath)) -- | Attempts to locate the first (if any) filename that exists on the given -- search paths, and constructs the "module path" from the given -- include-relative filename (2nd parameter). Terminates the program with an -- error if the given pathname is not relative. findProto :: MonadIO m => [FilePath] -> FilePath -> m FindProtoResult findProto searchPaths protoFP | Turtle.absolute protoFP = dieLines absolutePathErrorMsg | otherwise = forM (toModulePath protoFP) $ \mp -> flip Turtle.fold FL.head $ do sp <- Turtle.select searchPaths let fp = sp </> protoFP True <- Turtle.testfile fp pure (mp, fp) -- * Pretty Error Messages badModulePathErrorMsg :: FilePath -> String -> T.Text badModulePathErrorMsg (Turtle.format F.fp -> fp) (T.pack -> rsn) = [Neat.text| Error: failed when computing the "module path" for "${fp}": ${rsn} Please ensure that the provided path to a .proto file is specified as relative to some --includeDir path and that it has the .proto suffix. |] importNotFoundErrorMsg :: [FilePath] -> FilePath -> FilePath -> T.Text importNotFoundErrorMsg paths toplevelProto protoFP = [Neat.text| Error: while processing include statements in "${toplevelProtoText}", failed to find the imported file "${protoFPText}", after looking in the following locations (controlled via the --includeDir switch(es)): $pathsText |] where pathsText = T.unlines (Turtle.format (" "%F.fp) . (</> protoFP) <$> paths) toplevelProtoText = Turtle.format F.fp toplevelProto protoFPText = Turtle.format F.fp protoFP toplevelNotFoundErrorMsg :: [FilePath] -> FilePath -> T.Text toplevelNotFoundErrorMsg searchPaths toplevelProto = [Neat.text| Error: failed to find file "${toplevelProtoText}", after looking in the following locations (controlled via the --includeDir switch(es)): $searchPathsText |] where searchPathsText = T.unlines (Turtle.format (" "%F.fp) . (</> toplevelProto) <$> searchPaths) toplevelProtoText = Turtle.format F.fp toplevelProto absolutePathErrorMsg :: T.Text absolutePathErrorMsg = [Neat.text| Error: Absolute paths to .proto files, whether on the command line or in include directives, are not currently permitted; rather, all .proto filenames must be relative to the current directory, or relative to some search path specified via --includeDir. This is because we currently use the include-relative name to decide the structure of the Haskell module tree that we emit during code generation. |] -------------------------------------------------------------------------------- -- -- * Type context -- -- | A mapping from .proto type identifiers to their type information type TypeContext = M.Map DotProtoIdentifier DotProtoTypeInfo -- | Information about messages and enumerations data DotProtoTypeInfo = DotProtoTypeInfo { dotProtoTypeInfoPackage :: DotProtoPackageSpec -- ^ The package this type is defined in , dotProtoTypeInfoParent :: DotProtoIdentifier -- ^ The message this type is nested under, or 'Anonymous' if it's top-level , dotProtoTypeChildContext :: TypeContext -- ^ The context that should be used for declarations within the -- scope of this type , dotProtoTypeInfoKind :: DotProtoKind -- ^ Whether this type is an enumeration or message , dotProtoTypeInfoModulePath :: Path -- ^ The include-relative module path used when importing this module } deriving Show tiParent :: Lens' DotProtoTypeInfo DotProtoIdentifier tiParent = lens dotProtoTypeInfoParent (\d p -> d{ dotProtoTypeInfoParent = p }) -- | Whether a definition is an enumeration or a message data DotProtoKind = DotProtoKindEnum | DotProtoKindMessage deriving (Show, Eq, Ord, Enum, Bounded) -- ** Generating type contexts from ASTs dotProtoTypeContext :: MonadError CompileError m => DotProto -> m TypeContext dotProtoTypeContext DotProto{..} = foldMapM (definitionTypeContext (metaModulePath protoMeta)) protoDefinitions definitionTypeContext :: MonadError CompileError m => Path -> DotProtoDefinition -> m TypeContext definitionTypeContext modulePath (DotProtoMessage _ msgIdent parts) = do let updateParent = tiParent (concatDotProtoIdentifier msgIdent) childTyContext <- foldMapOfM (traverse . _DotProtoMessageDefinition) (definitionTypeContext modulePath >=> traverse updateParent) parts qualifiedChildTyContext <- mapKeysM (concatDotProtoIdentifier msgIdent) childTyContext let tyInfo = DotProtoTypeInfo { dotProtoTypeInfoPackage = DotProtoNoPackage , dotProtoTypeInfoParent = Anonymous , dotProtoTypeChildContext = childTyContext , dotProtoTypeInfoKind = DotProtoKindMessage , dotProtoTypeInfoModulePath = modulePath } pure $ M.singleton msgIdent tyInfo <> qualifiedChildTyContext definitionTypeContext modulePath (DotProtoEnum _ enumIdent _) = do let tyInfo = DotProtoTypeInfo { dotProtoTypeInfoPackage = DotProtoNoPackage , dotProtoTypeInfoParent = Anonymous , dotProtoTypeChildContext = mempty , dotProtoTypeInfoKind = DotProtoKindEnum , dotProtoTypeInfoModulePath = modulePath } pure (M.singleton enumIdent tyInfo) definitionTypeContext _ _ = pure mempty isMessage :: TypeContext -> DotProtoIdentifier -> Bool isMessage ctxt n = Just DotProtoKindMessage == (dotProtoTypeInfoKind <$> M.lookup n ctxt) isPacked :: [DotProtoOption] -> Bool isPacked opts = case find (\(DotProtoOption name _) -> name == Single "packed") opts of Just (DotProtoOption _ (BoolLit x)) -> x _ -> False isUnpacked :: [DotProtoOption] -> Bool isUnpacked opts = case find (\(DotProtoOption name _) -> name == Single "packed") opts of Just (DotProtoOption _ (BoolLit x)) -> not x _ -> False -- | Returns 'True' if the given primitive type is packable. The 'TypeContext' -- is used to distinguish Named enums and messages, only the former of which are -- packable. isPackable :: TypeContext -> DotProtoPrimType -> Bool isPackable _ Bytes = False isPackable _ String = False isPackable _ Int32 = True isPackable _ Int64 = True isPackable _ SInt32 = True isPackable _ SInt64 = True isPackable _ UInt32 = True isPackable _ UInt64 = True isPackable _ Fixed32 = True isPackable _ Fixed64 = True isPackable _ SFixed32 = True isPackable _ SFixed64 = True isPackable _ Bool = True isPackable _ Float = True isPackable _ Double = True isPackable ctxt (Named tyName) = Just DotProtoKindEnum == (dotProtoTypeInfoKind <$> M.lookup tyName ctxt) isMap :: DotProtoType -> Bool isMap Map{} = True isMap _ = False -------------------------------------------------------------------------------- -- -- * Name resolution -- concatDotProtoIdentifier :: MonadError CompileError m => DotProtoIdentifier -> DotProtoIdentifier -> m DotProtoIdentifier concatDotProtoIdentifier i1 i2 = case (i1, i2) of (Qualified{} , _ ) -> internalError "concatDotProtoIdentifier: Qualified" (_ , Qualified{} ) -> internalError "concatDotProtoIdentifier Qualified" (Anonymous , Anonymous ) -> pure Anonymous (Anonymous , b ) -> pure b (a , Anonymous ) -> pure a (Single a , b ) -> concatDotProtoIdentifier (Dots (Path (pure a))) b (a , Single b ) -> concatDotProtoIdentifier a (Dots (Path (pure b))) (Dots (Path a), Dots (Path b)) -> pure (Dots (Path (a <> b))) -- | @'toPascalCase' xs'@ sends a snake-case string @xs@ to a pascal-cased string. Trailing underscores are not dropped -- from the input string and exactly double underscores are replaced by a single underscore. toPascalCase :: String -> String toPascalCase xs = foldMap go (segmentBy (== '_') xs) where go (Left seg) = toUpperFirst seg go (Right seg) | seg == "__" = "_" | otherwise = "" -- | @'toCamelCase' xs@ sends a snake-case string @xs@ to a camel-cased string. toCamelCase :: String -> String toCamelCase xs = case toPascalCase xs of "" -> "" x : xs' -> toLower x : xs' -- | @'toUpperFirst' xs@ sends the first character @x@ in @xs@ to be upper case, @'toUpperFirst' "" = ""@. toUpperFirst :: String -> String toUpperFirst [] = [] toUpperFirst (x : xs) = toUpper x : xs -- | @'segmentBy' p xs@ partitions @xs@ into segments of @'Either' [a] [a]@ where @'Right' xs'@ satisfy @p@ and -- @'Left' xs'@ segments satisfy @'not' . p@. segmentBy :: (a -> Bool) -> [a] -> [Either [a] [a]] segmentBy p xs = case span p xs of ([], []) -> [] (ys, []) -> [Right ys] ([], ys) -> Left seg : segmentBy p ys' where (seg, ys') = break p ys (xs', ys) -> Right xs' : Left seg : segmentBy p ys' where (seg, ys') = break p ys -- | @'suffixBy' p xs@ yields @'Right' (xs', suf)@ if @suf@ is the longest suffix satisfying @p@ and @xs'@ is the rest -- of the rest, otherwise the string is given back as @'Left' xs@ signifying @xs@ had no suffix satisfying @p@. suffixBy :: forall a. (a -> Bool) -> [a] -> Either [a] ([a], [a]) suffixBy p xs' = do (pref, suf) <- foldr go (Left []) xs' if null suf then Left pref else return (pref, suf) where go :: a -> Either [a] ([a], [a]) -> Either [a] ([a], [a]) go x (Right (xs, suf)) = Right (x : xs, suf) go x (Left xs) | p x = Left (x : xs) | otherwise = Right ([x], xs) -- | @'typeLikeName' xs@ produces either the pascal-cased version of the string @xs@ if it begins with an alphabetical -- character or underscore - which is replaced with 'X'. A 'CompileError' is emitted if the starting character is -- non-alphabetic or if @xs == ""@. typeLikeName :: MonadError CompileError m => String -> m String typeLikeName "" = invalidTypeNameError "<empty name>" typeLikeName s@(x : xs) | isAlpha x = pure $ case suffixBy (== '_') s of Left xs' -> invalidToCamelCase $ toPascalCase xs' Right (xs', suf) -> invalidToCamelCase $ toPascalCase xs' <> suf | x == '_' = pure $ case suffixBy (== '_') xs of Left xs' -> invalidToCamelCase $ 'X' : toPascalCase xs' Right (xs', suf) -> invalidToCamelCase $ 'X' : (toPascalCase xs' <> suf) | otherwise = invalidTypeNameError s where -- Transforms special characters that are not valid as a part of a Haskell name to CamelCase. -- For instance “foo-bar---baz” will become “FooBarBaz”. -- This function presumes that the first character of the initial value satisfies "isAlpha". -- This must be checked outside of this function. invalidToCamelCase a = case span isValidNameChar a of ("", "") -> "" ("", cs) -> invalidToCamelCase . dropWhile (not . isValidNameChar) $ cs (b : bs, cs) -> toUpper b : bs <> invalidToCamelCase cs -- Only valid as a secondary character. -- First character of a Haskell name can only be "isAlpha". isValidNameChar x = isAlphaNum x || x == '_' -- | @'fieldLikeName' field@ is the casing transformation used to produce record selectors from message fields. If -- @field@ is prefixed by a span of uppercase characters then that prefix will be lowercased while the remaining string -- is left unchanged. fieldLikeName :: String -> String fieldLikeName "" = "" fieldLikeName (x : xs) | isUpper x = map toLower prefix ++ suffix | otherwise = x : xs where (prefix, suffix) = span isUpper (x : xs) prefixedEnumFieldName :: String -> String -> String prefixedEnumFieldName enumName enumItem = enumName ++ enumItem prefixedConName :: MonadError CompileError m => String -> String -> m String prefixedConName msgName conName = do constructor <- typeLikeName conName return (msgName ++ constructor) -- | @'prefixedMethodName' service method@ produces a Haskell record selector name for the service method @method@ by -- joining the names @service@, @method@ under concatenation on a camel-casing transformation. prefixedMethodName :: MonadError CompileError m => String -> String -> m String prefixedMethodName _ "" = invalidTypeNameError "<empty name>" prefixedMethodName serviceName (x : xs) | isLower x = return (fieldLikeName serviceName ++ fieldLikeName (x : xs)) | otherwise = do method <- typeLikeName (x : xs) return (fieldLikeName serviceName ++ method) -- | @'prefixedFieldName' prefix field@ constructs a Haskell record selector name by prepending @prefix@ in camel-case -- to the message field/service method name @field@. prefixedFieldName :: MonadError CompileError m => String -> String -> m String prefixedFieldName msgName fieldName = do field <- typeLikeName fieldName return (fieldLikeName msgName ++ field) dpIdentUnqualName :: MonadError CompileError m => DotProtoIdentifier -> m String dpIdentUnqualName (Single name) = pure name dpIdentUnqualName (Dots (Path names)) = pure (NE.last names) dpIdentUnqualName (Qualified _ next) = dpIdentUnqualName next dpIdentUnqualName Anonymous = internalError "dpIdentUnqualName: Anonymous" dpIdentQualName :: MonadError CompileError m => DotProtoIdentifier -> m String dpIdentQualName (Single name) = pure name dpIdentQualName (Dots (Path names)) = pure (intercalate "." (NE.toList names)) dpIdentQualName (Qualified _ _) = internalError "dpIdentQualName: Qualified" dpIdentQualName Anonymous = internalError "dpIdentQualName: Anonymous" -- | Given a 'DotProtoIdentifier' for the parent type and the unqualified name -- of this type, generate the corresponding Haskell name nestedTypeName :: MonadError CompileError m => DotProtoIdentifier -> String -> m String nestedTypeName Anonymous nm = typeLikeName nm nestedTypeName (Single parent) nm = intercalate "_" <$> traverse typeLikeName [parent, nm] nestedTypeName (Dots (Path parents)) nm = intercalate "_" . (<> [nm]) <$> traverse typeLikeName (NE.toList parents) nestedTypeName (Qualified {}) _ = internalError "nestedTypeName: Qualified" qualifiedMessageName :: MonadError CompileError m => DotProtoIdentifier -> DotProtoIdentifier -> m String qualifiedMessageName parentIdent msgIdent = nestedTypeName parentIdent =<< dpIdentUnqualName msgIdent qualifiedMessageTypeName :: MonadError CompileError m => TypeContext -> DotProtoIdentifier -> DotProtoIdentifier -> m String qualifiedMessageTypeName ctxt parentIdent msgIdent = do xs <- parents parentIdent [] case xs of [] -> nestedTypeName parentIdent =<< dpIdentUnqualName msgIdent x : xs' -> nestedTypeName (Dots . Path $ x NE.:| xs') =<< dpIdentUnqualName msgIdent where parents par@(Single x) xs = case M.lookup par ctxt of Just (DotProtoTypeInfo { dotProtoTypeInfoParent = parentIdent' }) -> parents parentIdent' $ x : xs Nothing -> pure $ x : xs parents Anonymous xs = pure xs parents par _ = internalError $ "qualifiedMessageTypeName: wrong parent " <> show par -------------------------------------------------------------------------------- -- -- ** Codegen bookkeeping helpers -- -- | Bookeeping for qualified fields data QualifiedField = QualifiedField { recordFieldName :: FieldName , fieldInfo :: FieldInfo } deriving Show -- | Bookkeeping for fields data FieldInfo = FieldOneOf OneofField | FieldNormal FieldName FieldNumber DotProtoType [DotProtoOption] deriving Show -- | Bookkeeping for oneof fields data OneofField = OneofField { oneofType :: String , subfields :: [OneofSubfield] } deriving Show -- | Bookkeeping for oneof subfields data OneofSubfield = OneofSubfield { subfieldNumber :: FieldNumber , subfieldConsName :: String , subfieldName :: FieldName , subfieldType :: DotProtoType , subfieldOptions :: [DotProtoOption] } deriving Show getQualifiedFields :: MonadError CompileError m => String -> [DotProtoMessagePart] -> m [QualifiedField] getQualifiedFields msgName msgParts = flip foldMapM msgParts $ \case DotProtoMessageField DotProtoField{..} -> do fieldName <- dpIdentUnqualName dotProtoFieldName qualName <- prefixedFieldName msgName fieldName pure . (:[]) $ QualifiedField { recordFieldName = coerce qualName , fieldInfo = FieldNormal (coerce fieldName) dotProtoFieldNumber dotProtoFieldType dotProtoFieldOptions } DotProtoMessageOneOf _ [] -> throwError (InternalError "getQualifiedFields: encountered oneof with no oneof fields") DotProtoMessageOneOf oneofIdent fields -> do ident <- dpIdentUnqualName oneofIdent oneofName <- prefixedFieldName msgName ident oneofTypeName <- prefixedConName msgName ident let mkSubfield DotProtoField{..} = do s <- dpIdentUnqualName dotProtoFieldName c <- prefixedConName oneofTypeName s pure [OneofSubfield dotProtoFieldNumber c (coerce s) dotProtoFieldType dotProtoFieldOptions] mkSubfield DotProtoEmptyField = pure [] fieldElems <- foldMapM mkSubfield fields pure . (:[]) $ QualifiedField { recordFieldName = coerce oneofName , fieldInfo = FieldOneOf (OneofField ident fieldElems) } _ -> pure [] -- | Project qualified fields, given a projection function per field type. foldQF :: (FieldName -> FieldNumber -> a) -- ^ projection for normal fields -> (OneofField -> a) -- ^ projection for oneof fields -> QualifiedField -> a foldQF f _ (QualifiedField _ (FieldNormal fldName fldNum _ _)) = f fldName fldNum foldQF _ g (QualifiedField _ (FieldOneOf fld)) = g fld fieldBinder :: FieldNumber -> String fieldBinder = ("f" ++) . show oneofSubBinder :: OneofSubfield -> String oneofSubBinder = fieldBinder . subfieldNumber oneofSubDisjunctBinder :: [OneofSubfield] -> String oneofSubDisjunctBinder = intercalate "_or_" . fmap oneofSubBinder -------------------------------------------------------------------------------- -- -- * Errors -- data CompileError = CircularImport FilePath | CompileParseError ParseError | InternalError String | InvalidPackageName DotProtoIdentifier | InvalidMethodName DotProtoIdentifier | InvalidTypeName String | InvalidMapKeyType String | NoPackageDeclaration | NoSuchType DotProtoIdentifier | NonzeroFirstEnumeration String DotProtoIdentifier Int32 | EmptyEnumeration String | Unimplemented String deriving (Show, Eq) internalError :: MonadError CompileError m => String -> m a internalError = throwError . InternalError invalidTypeNameError :: MonadError CompileError m => String -> m a invalidTypeNameError = throwError . InvalidTypeName _unimplementedError :: MonadError CompileError m => String -> m a _unimplementedError = throwError . Unimplemented invalidMethodNameError :: MonadError CompileError m => DotProtoIdentifier -> m a invalidMethodNameError = throwError . InvalidMethodName noSuchTypeError :: MonadError CompileError m => DotProtoIdentifier -> m a noSuchTypeError = throwError . NoSuchType protoPackageName :: MonadError CompileError m => DotProtoPackageSpec -> m DotProtoIdentifier protoPackageName (DotProtoPackageSpec name) = pure name protoPackageName DotProtoNoPackage = throwError NoPackageDeclaration <|start_filename|>src/no-swagger-wrapper-format/Proto3/Suite/DotProto/Generate/Swagger/Wrappers.hs<|end_filename|> module Proto3.Suite.DotProto.Generate.Swagger.Wrappers where <|start_filename|>tests/SimpleEncodeDotProto.hs<|end_filename|> {-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Main where import qualified Data.ByteString.Lazy as BL import qualified Data.Map as M import Proto3.Suite import TestProto import qualified TestProtoImport import qualified TestProtoOneof import qualified TestProtoOneofImport outputMessage :: Message a => a -> IO () outputMessage msg = let encoded = toLazyByteString msg in putStrLn (show (BL.length encoded)) >> BL.putStr encoded testCase1 :: IO () testCase1 = let trivial = Trivial 0x7BADBEEF in outputMessage trivial testCase2 :: IO () testCase2 = do outputMessage (MultipleFields 1.125 1e9 0x1135 0x7FFAFABADDEAFFA0 "Goodnight moon" False) testCaseSignedInts :: IO () testCaseSignedInts = do outputMessage (SignedInts 0 0) outputMessage (SignedInts 42 84) outputMessage (SignedInts (-42) (-84)) outputMessage (SignedInts minBound minBound) outputMessage (SignedInts maxBound maxBound) testCase3 :: IO () testCase3 = do outputMessage (WithEnum (Enumerated (Right WithEnum_TestEnumENUM1))) outputMessage (WithEnum (Enumerated (Right WithEnum_TestEnumENUM2))) outputMessage (WithEnum (Enumerated (Right WithEnum_TestEnumENUM3))) outputMessage (WithEnum (Enumerated (Left 0xBEEF))) testCase4 :: IO () testCase4 = do let nested = WithNesting_Nested "testCase4 nestedField1" 0xABCD [] [] outputMessage (WithNesting (Just nested)) outputMessage (WithNesting Nothing) testCase5 :: IO () testCase5 = do let nested1 = WithNestingRepeated_Nested "testCase5 nestedField1" 0xDCBA [1, 1, 2, 3, 5] [0xB, 0xABCD, 0xBADBEEF, 0x10203040] nested2 = WithNestingRepeated_Nested "Hello world" 0x7FFFFFFF [0, 0, 0] [] nested3 = WithNestingRepeated_Nested "" 0x0 [] [] outputMessage (WithNestingRepeated [nested1, nested2, nested3]) outputMessage (WithNestingRepeated []) testCase6 :: IO () testCase6 = do let nested1 = NestedInts 636513 619021 nested2 = NestedInts 423549 687069 nested3 = NestedInts 545506 143731 nested4 = NestedInts 193605 385360 outputMessage (WithNestingRepeatedInts [nested1]) outputMessage (WithNestingRepeatedInts []) outputMessage (WithNestingRepeatedInts [nested1, nested2, nested3, nested4]) testCase7 :: IO () testCase7 = do outputMessage (WithRepetition []) outputMessage (WithRepetition [1..10000]) testCase8 :: IO () testCase8 = do outputMessage (WithFixed 0 0 0 0) outputMessage (WithFixed maxBound maxBound maxBound maxBound) outputMessage (WithFixed minBound minBound minBound minBound) testCase9 :: IO () testCase9 = do outputMessage (WithBytes "\x00\x00\x00\x01\x02\x03\xFF\xFF\x0\x1" ["", "\x01", "\xAB\xBAhello", "\xBB"]) outputMessage (WithBytes "Hello world" []) outputMessage (WithBytes "" ["Hello", "\x00world", "\x00\x00"]) outputMessage (WithBytes "" []) testCase10 :: IO () testCase10 = do outputMessage (WithPacking [] []) outputMessage (WithPacking [100, 2000, 300, 4000, 500, 60000, 7000] []) outputMessage (WithPacking [] [100, 2000, 300, 4000, 500, 60000, 7000]) outputMessage (WithPacking [1, 2, 3, 4, 5] [5, 4, 3, 2, 1]) testCase11 :: IO () testCase11 = do outputMessage $ AllPackedTypes [] [] [] [] [] [] [] [] [] [] [] [] [] outputMessage $ AllPackedTypes [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [False][efld0] [efld0] outputMessage $ AllPackedTypes [1] [2] [-3] [-4] [5] [6] [-7] [-8] [-9] [-10] [True] [efld1] [efld1] outputMessage $ AllPackedTypes [1..10000] [1..10000] [1..10000] [1..10000] [1..10000] [1..10000] [1,1.125..10000] [1,1.125..10000] [1..10000] [1..10000] [False,True] [efld0,efld1] [efld0,efld1] where efld0 = Enumerated (Right EFLD0) efld1 = Enumerated (Right EFLD1) testCase12 :: IO () testCase12 = do outputMessage (OutOfOrderFields [] "" maxBound []) outputMessage (OutOfOrderFields [1,7..100] "This is a test" minBound ["This", "is", "a", "test"]) testCase13 :: IO () testCase13 = do outputMessage (ShadowedMessage "name" 0x7DADBEEF) outputMessage (MessageShadower (Just (MessageShadower_ShadowedMessage "name" "string value")) "another name") outputMessage (MessageShadower_ShadowedMessage "another name" "another string") testCase14 :: IO () testCase14 = outputMessage (WithQualifiedName (Just (ShadowedMessage "int value" 42)) (Just (MessageShadower_ShadowedMessage "string value" "hello world"))) testCase15 :: IO () testCase15 = outputMessage TestProtoImport.WithNesting { TestProtoImport.withNestingNestedMessage1 = Just TestProtoImport.WithNesting_Nested { TestProtoImport.withNesting_NestedNestedField1 = 1 , TestProtoImport.withNesting_NestedNestedField2 = 2 } , TestProtoImport.withNestingNestedMessage2 = Nothing } testCase16 :: IO () testCase16 = outputMessage (UsingImported { usingImportedImportedNesting = Just (TestProtoImport.WithNesting (Just (TestProtoImport.WithNesting_Nested 1 2)) (Just (TestProtoImport.WithNesting_Nested 3 4))) , usingImportedLocalNesting = Just (WithNesting (Just (WithNesting_Nested "field" 0xBEEF [] []))) }) testCase17 :: IO () testCase17 = do let emit v a p = outputMessage TestProtoOneof.Something { TestProtoOneof.somethingValue = v , TestProtoOneof.somethingAnother = a , TestProtoOneof.somethingPickOne = p } -- Send default values for oneof subfields emit 1 2 $ Just $ TestProtoOneof.SomethingPickOneName "" emit 3 4 $ Just $ TestProtoOneof.SomethingPickOneSomeid 0 emit 5 6 $ Just $ TestProtoOneof.SomethingPickOneDummyMsg1 $ TestProtoOneof.DummyMsg 0 emit 7 8 $ Just $ TestProtoOneof.SomethingPickOneDummyMsg2 $ TestProtoOneof.DummyMsg 0 emit 9 10 $ Just $ TestProtoOneof.SomethingPickOneDummyEnum $ Enumerated $ Right $ TestProtoOneof.DummyEnumDUMMY0 -- Send non-default values for oneof subfields emit 1 2 $ Just $ TestProtoOneof.SomethingPickOneName "hello world" emit 3 4 $ Just $ TestProtoOneof.SomethingPickOneSomeid 42 emit 5 6 $ Just $ TestProtoOneof.SomethingPickOneDummyMsg1 $ TestProtoOneof.DummyMsg 66 emit 7 8 $ Just $ TestProtoOneof.SomethingPickOneDummyMsg2 $ TestProtoOneof.DummyMsg 67 emit 9 10 $ Just $ TestProtoOneof.SomethingPickOneDummyEnum $ Enumerated $ Right $ TestProtoOneof.DummyEnumDUMMY1 -- Send with oneof not set emit 11 12 Nothing testCase18 :: IO () testCase18 = do let emit = outputMessage . TestProtoOneof.WithImported let emitWithOneof = emit . Just . TestProtoOneof.WithImportedPickOneWithOneof . TestProtoOneofImport.WithOneof emit $ Just $ TestProtoOneof.WithImportedPickOneDummyMsg1 $ TestProtoOneof.DummyMsg 0 emit $ Just $ TestProtoOneof.WithImportedPickOneDummyMsg1 $ TestProtoOneof.DummyMsg 68 emitWithOneof Nothing emitWithOneof $ Just $ TestProtoOneofImport.WithOneofPickOneA "" emitWithOneof $ Just $ TestProtoOneofImport.WithOneofPickOneB 0 emitWithOneof $ Just $ TestProtoOneofImport.WithOneofPickOneA "foo" emitWithOneof $ Just $ TestProtoOneofImport.WithOneofPickOneB 19 emit Nothing testCase19 :: IO () testCase19 = do let wt = Just . WrappedTrivial . Just . Trivial outputMessage MapTest{ mapTestPrim = M.fromList [("foo", 1),("bar", 42),("baz", 1234567)] , mapTestTrivial = M.fromList [(1, wt 1),(2, wt 42),(101, wt 1234567), (79, Nothing)] , mapTestSigned = M.fromList [(1,2),(3,4),(5,6)] } main :: IO () main = do testCase1 testCase2 testCaseSignedInts testCase3 testCase4 testCase5 testCase6 testCase7 testCase8 testCase9 testCase10 testCase11 testCase12 testCase13 testCase14 -- Tests using imported messages testCase15 testCase16 -- Oneof tests testCase17 testCase18 -- Map tests testCase19 outputMessage (MultipleFields 0 0 0 0 "All tests complete" False) <|start_filename|>src/swagger-wrapper-format/Proto3/Suite/DotProto/Generate/Swagger/Wrappers.hs<|end_filename|> {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# OPTIONS_GHC -Wno-orphans #-} module Proto3.Suite.DotProto.Generate.Swagger.Wrappers where #if MIN_VERSION_swagger2(2,4,0) import Control.Lens ((?~)) #else import Control.Lens ((.~)) #endif import Data.Functor ((<&>)) import Data.Int (Int32, Int64) import Data.Proxy (Proxy (..)) import Data.Swagger ( Definitions , NamedSchema (..) , Schema , ToSchema (..) , byteSchema , format , paramSchema , schema ) import Data.Swagger.Declare (Declare) import Data.Word (Word32, Word64) import {-# SOURCE #-} Proto3.Suite.DotProto.Generate.Swagger (OverrideToSchema (..)) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import qualified Data.Text as T import qualified Data.Text.Lazy as TL -- | Wrapped Type Schemas setFormat :: T.Text -> Declare (Definitions Schema) NamedSchema -> Declare (Definitions Schema) NamedSchema setFormat formatValue namedSchema = namedSchema #if MIN_VERSION_swagger2(2,4,0) <&> schema . paramSchema . format ?~ formatValue #else <&> schema . paramSchema . format .~ formatValue #endif declareWrapperNamedSchema :: forall a . ToSchema a => T.Text -> Proxy (OverrideToSchema a) -> Declare (Definitions Schema) NamedSchema declareWrapperNamedSchema formatValue _ = setFormat formatValue (declareNamedSchema (Proxy :: Proxy a)) instance {-# OVERLAPPING #-} ToSchema (OverrideToSchema (Maybe Double)) where declareNamedSchema = declareWrapperNamedSchema "DoubleValue" instance {-# OVERLAPPING #-} ToSchema (OverrideToSchema (Maybe Float)) where declareNamedSchema = declareWrapperNamedSchema "FloatValue" instance {-# OVERLAPPING #-} ToSchema (OverrideToSchema (Maybe Int64)) where declareNamedSchema = declareWrapperNamedSchema "Int64Value" instance {-# OVERLAPPING #-} ToSchema (OverrideToSchema (Maybe Word64)) where declareNamedSchema = declareWrapperNamedSchema "UInt64Value" instance {-# OVERLAPPING #-} ToSchema (OverrideToSchema (Maybe Int32)) where declareNamedSchema = declareWrapperNamedSchema "Int32Value" instance {-# OVERLAPPING #-} ToSchema (OverrideToSchema (Maybe Word32)) where declareNamedSchema = declareWrapperNamedSchema "UInt32Value" instance {-# OVERLAPPING #-} ToSchema (OverrideToSchema (Maybe Bool)) where declareNamedSchema = declareWrapperNamedSchema "BoolValue" instance {-# OVERLAPPING #-} ToSchema (OverrideToSchema (Maybe T.Text)) where declareNamedSchema = declareWrapperNamedSchema "StringValue" instance {-# OVERLAPPING #-} ToSchema (OverrideToSchema (Maybe TL.Text)) where declareNamedSchema = declareWrapperNamedSchema "StringValue" instance {-# OVERLAPPING #-} ToSchema (OverrideToSchema (Maybe B.ByteString)) where declareNamedSchema _ = setFormat "BytesValue" (pure (NamedSchema Nothing byteSchema)) instance {-# OVERLAPPING #-} ToSchema (OverrideToSchema (Maybe BL.ByteString)) where declareNamedSchema _ = setFormat "BytesValue" (pure (NamedSchema Nothing byteSchema)) <|start_filename|>src/Proto3/Suite/DotProto/Rendering.hs<|end_filename|> -- | This module provides types and functions to generate .proto files. {-# LANGUAGE CPP #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Proto3.Suite.DotProto.Rendering ( renderDotProto , defRenderingOptions , defSelectorName , defEnumMemberName , packageFromDefs , toProtoFile , toProtoFileDef , RenderingOptions(..) , Pretty(..) ) where import Data.Char import qualified Data.List.NonEmpty as NE import qualified Data.Text as T import Filesystem.Path.CurrentOS (toText) #if (MIN_VERSION_base(4,11,0)) import Prelude hiding ((<>)) #endif import Proto3.Suite.DotProto.AST import Proto3.Wire.Types (FieldNumber (..)) import Text.PrettyPrint (($$), (<+>), (<>)) import qualified Text.PrettyPrint as PP import Text.PrettyPrint.HughesPJClass (Pretty(..)) -- | Options for rendering a @.proto@ file. data RenderingOptions = RenderingOptions { roSelectorName :: DotProtoIdentifier -> DotProtoIdentifier -> FieldNumber -> PP.Doc -- ^ This function will be applied to each -- record selector name to turn it into a protobuf -- field name (default: uses the selector name, unchanged). , roEnumMemberName :: DotProtoIdentifier -> DotProtoIdentifier -> PP.Doc -- ^ This function will be applied to each -- enum member name to turn it into a protobuf -- field name (default: uses the field name, unchanged). } -- | Default rendering options. defRenderingOptions :: RenderingOptions defRenderingOptions = RenderingOptions { roSelectorName = defSelectorName , roEnumMemberName = defEnumMemberName } -- | The default choice of field name for a selector. defSelectorName :: DotProtoIdentifier -> DotProtoIdentifier -> FieldNumber -> PP.Doc defSelectorName _ fieldName _ = pPrint fieldName -- | The default choice of enum member name for an enum defEnumMemberName :: DotProtoIdentifier -> DotProtoIdentifier -> PP.Doc defEnumMemberName = const pPrint -- | Traverses a DotProto AST and generates a .proto file from it renderDotProto :: RenderingOptions -> DotProto -> PP.Doc renderDotProto opts DotProto{..} = PP.text "syntax = \"proto3\";" $$ pPrint protoPackage $$ (PP.vcat $ pPrint <$> protoImports) $$ (PP.vcat $ topOption <$> protoOptions) $$ (PP.vcat $ prettyPrintProtoDefinition opts <$> protoDefinitions) instance Pretty DotProtoPackageSpec where pPrint (DotProtoPackageSpec p) = PP.text "package" <+> pPrint p <> PP.text ";" pPrint (DotProtoNoPackage) = PP.empty instance Pretty DotProtoImport where pPrint (DotProtoImport q i) = PP.text "import" <+> pPrint q <+> PP.text fp <> PP.text ";" where fp = case T.unpack . either id id . toText $ i of [] -> show ("" :: String) x -> x instance Pretty DotProtoImportQualifier where pPrint DotProtoImportDefault = PP.empty pPrint DotProtoImportPublic = PP.text "public" pPrint DotProtoImportWeak = PP.text "weak" optionAnnotation :: [DotProtoOption] -> PP.Doc optionAnnotation [] = PP.empty optionAnnotation os = PP.brackets . PP.hcat . PP.punctuate (PP.text ", ") $ pPrint <$> os topOption :: DotProtoOption -> PP.Doc topOption o = PP.text "option" <+> pPrint o <> PP.text ";" instance Pretty DotProtoOption where pPrint (DotProtoOption key value) = pPrint key <+> PP.text "=" <+> pPrint value renderComment :: String -> PP.Doc renderComment = PP.vcat . map ((PP.text "//" <+>) . textIfNonempty) . lines where textIfNonempty [] = PP.empty textIfNonempty text = PP.text text -- Put the final closing brace on the next line. -- This is important, since the final field might have a comment, and -- the brace cannot be part of the comment. -- We could use block comments instead, once the parser/lexer supports them. vbraces :: PP.Doc -> PP.Doc -> PP.Doc vbraces header body = header <+> PP.char '{' $$ PP.nest 2 body $$ PP.char '}' prettyPrintProtoDefinition :: RenderingOptions -> DotProtoDefinition -> PP.Doc prettyPrintProtoDefinition opts = defn where defn :: DotProtoDefinition -> PP.Doc defn (DotProtoMessage comment name parts) = renderComment comment $$ vbraces (PP.text "message" <+> pPrint name) (PP.vcat $ msgPart name <$> parts) defn (DotProtoEnum comment name parts) = renderComment comment $$ vbraces (PP.text "enum" <+> pPrint name) (PP.vcat $ enumPart name <$> parts) defn (DotProtoService comment name parts) = renderComment comment $$ vbraces (PP.text "service" <+> pPrint name) (PP.vcat $ pPrint <$> parts) msgPart :: DotProtoIdentifier -> DotProtoMessagePart -> PP.Doc msgPart msgName (DotProtoMessageField f) = field msgName f msgPart _ (DotProtoMessageDefinition definition) = defn definition msgPart _ (DotProtoMessageReserved reservations) = PP.text "reserved" <+> (PP.hcat . PP.punctuate (PP.text ", ") $ pPrint <$> reservations) <> PP.text ";" msgPart msgName (DotProtoMessageOneOf name fields) = vbraces (PP.text "oneof" <+> pPrint name) (PP.vcat $ field msgName <$> fields) msgPart _ (DotProtoMessageOption opt) = PP.text "option" <+> pPrint opt <> PP.text ";" field :: DotProtoIdentifier -> DotProtoField -> PP.Doc field msgName (DotProtoField number mtype name options comments) = pPrint mtype <+> roSelectorName opts msgName name number <+> PP.text "=" <+> pPrint number <+> optionAnnotation options <> PP.text ";" $$ PP.nest 2 (renderComment comments) field _ DotProtoEmptyField = PP.empty enumPart :: DotProtoIdentifier -> DotProtoEnumPart -> PP.Doc enumPart msgName (DotProtoEnumField name value options) = roEnumMemberName opts msgName name <+> PP.text "=" <+> pPrint (fromIntegral value :: Int) <+> optionAnnotation options <> PP.text ";" enumPart _ (DotProtoEnumOption opt) = PP.text "option" <+> pPrint opt <> PP.text ";" enumPart _ DotProtoEnumEmpty = PP.empty instance Pretty DotProtoServicePart where pPrint (DotProtoServiceRPCMethod RPCMethod{..}) = PP.text "rpc" <+> pPrint rpcMethodName <+> PP.parens (pPrint rpcMethodRequestStreaming <+> pPrint rpcMethodRequestType) <+> PP.text "returns" <+> PP.parens (pPrint rpcMethodResponseStreaming <+> pPrint rpcMethodResponseType) <+> case rpcMethodOptions of [] -> PP.text ";" _ -> PP.braces . PP.vcat $ topOption <$> rpcMethodOptions pPrint (DotProtoServiceOption option) = topOption option pPrint DotProtoServiceEmpty = PP.empty instance Pretty Streaming where pPrint Streaming = PP.text "stream" pPrint NonStreaming = PP.empty instance Pretty DotProtoIdentifier where pPrint (Single name) = PP.text name pPrint (Dots (Path names)) = PP.hcat . PP.punctuate (PP.text ".") $ PP.text <$> NE.toList names pPrint (Qualified qualifier identifier) = PP.parens (pPrint qualifier) <> PP.text "." <> pPrint identifier pPrint Anonymous = PP.empty instance Pretty DotProtoValue where pPrint (Identifier value) = pPrint value pPrint (StringLit value) = PP.text $ show value pPrint (IntLit value) = PP.text $ show value pPrint (FloatLit value) = PP.text $ show value pPrint (BoolLit value) = PP.text $ toLower <$> show value instance Pretty DotProtoType where pPrint (Prim ty) = pPrint ty pPrint (Repeated ty) = PP.text "repeated" <+> pPrint ty pPrint (NestedRepeated ty) = PP.text "repeated" <+> pPrint ty pPrint (Map keyty valuety) = PP.text "map<" <> pPrint keyty <> PP.text ", " <> pPrint valuety <> PP.text ">" instance Pretty DotProtoPrimType where pPrint (Named i) = pPrint i pPrint Int32 = PP.text "int32" pPrint Int64 = PP.text "int64" pPrint SInt32 = PP.text "sint32" pPrint SInt64 = PP.text "sint64" pPrint UInt32 = PP.text "uint32" pPrint UInt64 = PP.text "uint64" pPrint Fixed32 = PP.text "fixed32" pPrint Fixed64 = PP.text "fixed64" pPrint SFixed32 = PP.text "sfixed32" pPrint SFixed64 = PP.text "sfixed64" pPrint String = PP.text "string" pPrint Bytes = PP.text "bytes" pPrint Bool = PP.text "bool" pPrint Float = PP.text "float" pPrint Double = PP.text "double" instance Pretty FieldNumber where pPrint = PP.text . show . getFieldNumber instance Pretty DotProtoReservedField where pPrint (SingleField num) = PP.text $ show num pPrint (FieldRange start end) = (PP.text $ show start) <+> PP.text "to" <+> (PP.text $ show end) pPrint (ReservedIdentifier i) = PP.text $ show i -- | Render protobufs metadata as a .proto file stringy toProtoFile :: RenderingOptions -> DotProto -> String toProtoFile opts = PP.render . renderDotProto opts -- | Render protobufs metadata as a .proto file string, -- using the default rendering options. toProtoFileDef :: DotProto -> String toProtoFileDef = toProtoFile defRenderingOptions packageFromDefs :: String -> [DotProtoDefinition] -> DotProto packageFromDefs package defs = DotProto [] [] (DotProtoPackageSpec $ Single package) defs (DotProtoMeta fakePath)
VitalBio/proto3-suite
<|start_filename|>src/lib/validate-action.js<|end_filename|> const validateAction = action => { if(!action || typeof action !== 'object' || Array.isArray(action)) throw new Error('Action must be an object!'); if(typeof action.type === 'undefined') throw new Error('Action must be a type!'); }; export default validateAction;
ghoshnirmalya/building-redux-from-scratch
<|start_filename|>lib/ManifestLoader.js<|end_filename|> 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _webfontloader = require('webfontloader'); var _webfontloader2 = _interopRequireDefault(_webfontloader); var _AssetLoader = require('./AssetLoader'); var _AssetLoader2 = _interopRequireDefault(_AssetLoader); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var ManifestLoader = function (_Phaser$Plugin) { _inherits(ManifestLoader, _Phaser$Plugin); function ManifestLoader() { _classCallCheck(this, ManifestLoader); return _possibleConstructorReturn(this, (ManifestLoader.__proto__ || Object.getPrototypeOf(ManifestLoader)).apply(this, arguments)); } _createClass(ManifestLoader, [{ key: 'init', value: function init(req) { this.req = req; } /** * [loadManifest loads a manifest of assets] */ }, { key: 'loadManifest', value: function loadManifest(manifest) { var assetPostfix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; return Promise.all([this._loadAssets(manifest, assetPostfix), this._loadWebFonts(manifest.fonts)]); } }, { key: '_loadAssets', value: function _loadAssets(manifest, assetPostfix) { var _this2 = this; return new Promise(function (resolve) { var assetLoader = _this2.game.plugins.add(_AssetLoader2.default, _this2.req); assetLoader.loadManifest(manifest, assetPostfix).then(function () { _this2.game.plugins.remove(assetLoader); resolve(); }); }); } }, { key: '_loadWebFonts', value: function _loadWebFonts(fonts) { return new Promise(function (resolve) { if (!fonts) { resolve(); } else { _webfontloader2.default.load(Object.assign({}, fonts, { active: function active() { resolve(); } })); } }); } }]); return ManifestLoader; }(Phaser.Plugin); exports.default = ManifestLoader; <|start_filename|>lib/AssetLoader.js<|end_filename|> 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _isString = require('lodash/isString'); var _isString2 = _interopRequireDefault(_isString); var _isObject = require('lodash/isObject'); var _isObject2 = _interopRequireDefault(_isObject); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function warn(type, key) { console.warn('phaser-manifest-loader: could not find ' + type + ' with key : ' + key); } var AssetLoader = function (_Phaser$Plugin) { _inherits(AssetLoader, _Phaser$Plugin); function AssetLoader() { _classCallCheck(this, AssetLoader); return _possibleConstructorReturn(this, (AssetLoader.__proto__ || Object.getPrototypeOf(AssetLoader)).apply(this, arguments)); } _createClass(AssetLoader, [{ key: 'init', value: function init(req) { this.req = req; this.loaders = { 'audio': this.loadAudio, 'spritesheets': this.loadSpriteSheet, 'images': this.loadImage, 'bitmap_fonts': this.loadBitmapFont }; } }, { key: 'destroy', value: function destroy() { this.loaders = null; _get(AssetLoader.prototype.__proto__ || Object.getPrototypeOf(AssetLoader.prototype), 'destroy', this).call(this); } }, { key: 'loadManifest', value: function loadManifest(manifest) { var _this2 = this; var assetPostfix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; return new Promise(function (resolve) { Object.keys(_this2.loaders).forEach(function (assetType) { var assets = manifest[assetType]; if (!assets) return; assets.forEach(function (assetKey) { _this2.loaders[assetType].call(_this2, assetKey, assetPostfix); }); }); _this2.game.load.onLoadComplete.addOnce(function () { resolve(); }); _this2.game.load.start(); }); } }, { key: 'loadAudio', value: function loadAudio(key) { var urls = []; try { urls.push(this.req('./audio/' + key + '.mp3')); } catch (e) {} try { urls.push(this.req('./audio/' + key + '.ogg')); } catch (e) {} try { urls.push(this.req('./audio/' + key + '.m4a')); } catch (e) {} try { urls.push(this.req('./audio/' + key + '.wav')); } catch (e) {} if (urls.length === 0) { warn('audio', key); } else { this.game.load.audio(key, urls); } } }, { key: 'loadSpriteSheet', value: function loadSpriteSheet(key, assetPostfix) { var imageUrl = void 0, json = void 0; try { imageUrl = this.req('./spritesheets/' + key + assetPostfix + '.png'); } catch (e) {} try { json = this.req('./spritesheets/' + key + assetPostfix + '.json'); } catch (e) {} if (!imageUrl) warn('spriteSheet image', key); if (!json) warn('spriteSheet json', key); this.game.load.atlasJSONArray(key, imageUrl, (0, _isString2.default)(json) && json, (0, _isObject2.default)(json) && json); } }, { key: 'loadImage', value: function loadImage(key, assetPostfix) { var urls = []; try { urls.push(this.req('./images/' + key + assetPostfix + '.jpg')); } catch (e) {} try { urls.push(this.req('./images/' + key + assetPostfix + '.png')); } catch (e) {} if (urls.length === 0) { warn('image', key); } else { this.game.load.image(key, urls[0]); } } }, { key: 'loadBitmapFont', value: function loadBitmapFont(key, assetPostfix) { var imageUrl = void 0, xmlUrl = void 0; try { imageUrl = this.req('./bitmap_fonts/' + key + assetPostfix + '.png'); } catch (e) {} try { xmlUrl = this.req('./bitmap_fonts/' + key + assetPostfix + '.xml'); } catch (e) {} if (!imageUrl) warn('bitmapFont image', key); if (!xmlUrl) warn('bitmapFont xml', key); this.game.load.bitmapFont(key, imageUrl, xmlUrl); } }]); return AssetLoader; }(Phaser.Plugin); exports.default = AssetLoader; <|start_filename|>demo/states/BootState.js<|end_filename|> import Phaser from 'phaser' import loaderImage from 'assets/images/loader.png' export default class extends Phaser.State { init () { this.stage.backgroundColor = '#2d2d2d' } preload () { this.game.load.image('loader', loaderImage) } create () { this.game.state.start('Loader') } } <|start_filename|>src/AssetLoader.js<|end_filename|> import isString from 'lodash/isString' import isObject from 'lodash/isObject' function warn (type, key) { console.warn(`phaser-manifest-loader: could not find ${type} with key : ${key}`) } export default class AssetLoader extends Phaser.Plugin { init (req) { this.req = req this.loaders = { 'audio': this.loadAudio, 'spritesheets': this.loadSpriteSheet, 'images': this.loadImage, 'bitmap_fonts': this.loadBitmapFont } } destroy () { this.loaders = null super.destroy() } loadManifest (manifest, assetPostfix = '') { return new Promise((resolve) => { Object.keys(this.loaders).forEach((assetType) => { const assets = manifest[assetType] if (!assets) return assets.forEach((assetKey) => { this.loaders[assetType].call(this, assetKey, assetPostfix) }) }) this.game.load.onLoadComplete.addOnce(() => { resolve() }) this.game.load.start() }) } loadAudio (key) { const urls = [] try { urls.push(this.req(`./audio/${key}.mp3`)) } catch (e) {} try { urls.push(this.req(`./audio/${key}.ogg`)) } catch (e) {} try { urls.push(this.req(`./audio/${key}.m4a`)) } catch (e) {} try { urls.push(this.req(`./audio/${key}.wav`)) } catch (e) {} if (urls.length === 0) { warn('audio', key) } else { this.game.load.audio(key, urls) } } loadSpriteSheet (key, assetPostfix) { let imageUrl, json try { imageUrl = this.req(`./spritesheets/${key}${assetPostfix}.png`) } catch (e) {} try { json = this.req(`./spritesheets/${key}${assetPostfix}.json`) } catch (e) {} if (!imageUrl) warn('spriteSheet image', key) if (!json) warn('spriteSheet json', key) this.game.load.atlasJSONArray(key, imageUrl, isString(json) && json, isObject(json) && json) } loadImage (key, assetPostfix) { const urls = [] try { urls.push(this.req(`./images/${key}${assetPostfix}.jpg`)) } catch (e) {} try { urls.push(this.req(`./images/${key}${assetPostfix}.png`)) } catch (e) {} if (urls.length === 0) { warn('image', key) } else { this.game.load.image(key, urls[0]) } } loadBitmapFont (key, assetPostfix) { let imageUrl, xmlUrl try { imageUrl = this.req(`./bitmap_fonts/${key}${assetPostfix}.png`) } catch (e) {} try { xmlUrl = this.req(`./bitmap_fonts/${key}${assetPostfix}.xml`) } catch (e) {} if (!imageUrl) warn('bitmapFont image', key) if (!xmlUrl) warn('bitmapFont xml', key) this.game.load.bitmapFont(key, imageUrl, xmlUrl) } } <|start_filename|>demo/main.js<|end_filename|> import 'pixi' import 'p2' import Phaser from 'phaser' import BootState from './states/BootState' import LoaderState from './states/LoaderState' import MainState from './states/MainState' class Game extends Phaser.Game { constructor () { const docElement = document.documentElement const width = docElement.clientWidth const height = docElement.clientHeight super(width, height, Phaser.CANVAS, 'content', null) this.state.add('Boot', BootState, false) this.state.add('Loader', LoaderState, false) this.state.add('Main', MainState, false) this.state.start('Boot') } } window.game = new Game() <|start_filename|>assets/fonts/bebas/stylesheet.css<|end_filename|> /* Generated by Font Squirrel (https://www.fontsquirrel.com) on May 10, 2016 */ @font-face { font-family: 'bebas_neuebold'; src: url('bebasneue_bold-webfont.woff2') format('woff2'), url('bebasneue_bold-webfont.woff') format('woff'), url('bebasneue_bold-webfont.ttf') format('truetype'), url('bebasneue_bold-webfont.svg#bebas_neuebold') format('svg'); font-weight: normal; font-style: normal; } <|start_filename|>webpack.config.js<|end_filename|> var path = require('path') var webpack = require('webpack') var BrowserSyncPlugin = require('browser-sync-webpack-plugin') // Phaser webpack config var phaserModule = path.join(__dirname, '/node_modules/phaser-ce/') var phaser = path.join(phaserModule, 'build/custom/phaser-split.js') var pixi = path.join(phaserModule, 'build/custom/pixi.js') var p2 = path.join(phaserModule, 'build/custom/p2.js') const isProd = process.env.NODE_ENV === 'production' console.log('isProd', isProd) module.exports = { entry: { app: ['babel-polyfill', path.resolve(__dirname, 'demo/main.js')], vendor: ['pixi', 'p2', 'phaser', 'webfontloader'] }, devtool: 'cheap-source-map', output: { pathinfo: true, path: path.resolve(__dirname, 'dist'), publicPath: './dist/', filename: 'bundle.js' }, watch: !isProd, plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: 'vendor' /* chunkName= */, filename: 'vendor.bundle.js' /* filename= */ }), new webpack.ProvidePlugin({ Promise: 'imports-loader?this=>global!exports-loader?global.Promise!es6-promise' }) ].concat( !isProd ? [ new BrowserSyncPlugin({ host: process.env.IP || 'localhost', port: process.env.PORT || 3000, server: { baseDir: ['./'] } }) ] : [] ), module: { rules: [ { test: /\.json$/, use: 'file-loader' }, { test: /\.js$/, use: ['babel-loader'], include: [path.join(__dirname, 'src'), path.join(__dirname, 'demo')] }, { test: /pixi\.js/, use: ['expose-loader?PIXI'] }, { test: /phaser-split\.js$/, use: ['expose-loader?Phaser'] }, { test: /p2\.js/, use: ['expose-loader?p2'] }, { test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /\.woff|\.woff2|\.svg|.eot|\.ttf/, use: 'url-loader?prefix=font/&limit=10000&name=[name]-[hash].[ext]' }, { test: /\.mp3$/, use: 'file-loader?hash=sha512&digest=hex&name=[name]-[hash].[ext]' }, { test: /\.(gif|png|svg)$/i, use: [ { loader: 'file-loader', options: { hash: 'sha512', digest: 'hex', name: '[hash].[ext]' } }, { loader: 'image-webpack-loader', options: { mozjpeg: { progressive: true }, optipng: { optimizationLevel: 7 }, gifsicle: { interlaced: false } } } ] }, { test: /\.(jpg)$/, use: 'url-loader?limit=25000&name=[name]-[hash].[ext]' }, { test: /\.xml$/, use: 'file-loader?hash=sha512&digest=hex&name=[name]-[hash].[ext]' } ] }, node: { fs: 'empty', net: 'empty', tls: 'empty' }, resolve: { alias: { phaser: phaser, pixi: pixi, p2: p2, assets: path.join(__dirname, 'assets') } } } <|start_filename|>demo/Manifest.js<|end_filename|> const Manifest = { spritesheets: [ 'creature1', 'creature2' ], 'bitmap_fonts': [ 'bitmapfont' ], 'audio': [ 'blip', 'bottle_pop', 'click_slip', 'swoosh_fast', 'blup', 'cancel', 'select', 'swoosh_short' ], 'images': [ 'phaser_logo', 'webpack_logo', 'yellow_circle' ], fonts: { custom: { families: [ 'bebas_neuebold' ] }, google: { families: [ 'Bangers' ] } } } export default Manifest <|start_filename|>lib/index.js<|end_filename|> 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.AssetLoader = undefined; var _ManifestLoader = require('./ManifestLoader'); var _ManifestLoader2 = _interopRequireDefault(_ManifestLoader); var _AssetLoader = require('./AssetLoader'); var _AssetLoader2 = _interopRequireDefault(_AssetLoader); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.AssetLoader = _AssetLoader2.default; exports.default = _ManifestLoader2.default; <|start_filename|>src/ManifestLoader.js<|end_filename|> import WebFont from 'webfontloader' import AssetLoader from './AssetLoader' type Manifest = { spritesheets: Array<string>, images: Array<string>, audio: Array<string>, bitmap_fonts: Array<string>, fonts: { custom: { families: Array<string>, }, google: { families: Array<string>, }, }, } type RequireContext = { resolve: () => any, keys: () => Array<string>, } class ManifestLoader extends Phaser.Plugin { init (req: RequireContext) { this.req = req; } /** * [loadManifest loads a manifest of assets] */ loadManifest (manifest: Manifest, assetPostfix: string = ''): Promise { return Promise.all([ this._loadAssets(manifest, assetPostfix), this._loadWebFonts(manifest.fonts) ]) } _loadAssets (manifest, assetPostfix) { return new Promise((resolve) => { const assetLoader = this.game.plugins.add(AssetLoader, this.req) assetLoader.loadManifest(manifest, assetPostfix).then(() => { this.game.plugins.remove(assetLoader) resolve() }) }) } _loadWebFonts (fonts) { return new Promise((resolve) => { if (!fonts) { resolve() } else { WebFont.load(Object.assign({}, fonts, { active: () => { resolve() } })) } }) } } export default ManifestLoader <|start_filename|>demo/states/LoaderState.js<|end_filename|> import Phaser from 'phaser' import ManifestLoader from '../../src/ManifestLoader' import 'assets/fonts/bebas/stylesheet.css' import Manifest from '../Manifest' export default class extends Phaser.State { init () { this.stage.backgroundColor = '#2d2d2d' } create () { const req = require.context( '../../assets', true, /.*\.png|json|ttf|woff|woff2|xml|mp3|jpg|jpeg$/ ) this.manifestLoader = this.game.plugins.add(ManifestLoader, req) // What I like about the ManifestLoader is that `loadManifest` returns // a promise, so we have more control over it. Promise.all([ this.manifestLoader.loadManifest(Manifest), this.startLoadingAnimation() ]).then(() => { this.game.state.start('Main') }) } startLoadingAnimation () { return new Promise((resolve, reject) => { const spinner = this.add.image( this.world.centerX, this.world.centerY, 'loader' ) spinner.anchor.set(0.5) this.add .tween(spinner) .to({ angle: 360 }, 1000, 'Linear', true, 0, -1, false) // If the assets are found in the browser cache they will probably load in < 1 second // typically causing a flash where the user sees the loading animation for a split second // Here we ensure the loading will be visible for at least 2 seconds so there is no flash setTimeout(() => { resolve() }, 2000) }) } } <|start_filename|>src/index.js<|end_filename|> import ManifestLoader from './ManifestLoader' import AssetLoader from './AssetLoader' export { AssetLoader } export default ManifestLoader <|start_filename|>demo/states/MainState.js<|end_filename|> import Phaser from 'phaser' export default class extends Phaser.State { create () { this.stage.backgroundColor = '#2d2d2d' // add text with web font const style = { font: 'bebas_neuebold', fill: 'red', fontSize: 28, align: 'left', wordWrapWidth: this.world.width, wordWrap: true } const txt = this.add.text(0, 0, 'All these assets were loaded easily and elegantly with ManifestLoader!', style) txt.pivot.x = txt.width / 2 txt.x = this.world.centerX // add bitmap text const bmpTxt = this.add.bitmapText(10, txt.height + 10, 'bitmapfont', 'oh hi bitmap text!', 30) // add images const phaserLogo = this.game.add.image(this.world.centerX - 100, bmpTxt.y + bmpTxt.height + 60, 'phaser_logo') phaserLogo.scale.set(0.5) phaserLogo.anchor.set(0.5) this.add.tween(phaserLogo).to({alpha: 0}, 2000, 'Linear', true, 0, -1, true) const yellowCircle = this.add.image(this.world.centerX, bmpTxt.y + bmpTxt.height + 60, 'yellow_circle') yellowCircle.scale.set(0.3) yellowCircle.anchor.set(0.5) const webpackLogo = this.game.add.image(this.world.centerX + 100, bmpTxt.y + bmpTxt.height + 60, 'webpack_logo') webpackLogo.scale.set(0.5) webpackLogo.anchor.set(0.5) webpackLogo.angle = -45 this.add.tween(webpackLogo).to({angle: 45}, 2000, Phaser.Easing.Quadratic.InOut, true, 0, -1, true) // add spritesheets const creature2 = this.game.add.sprite(this.world.width - 50, this.world.height - 100, 'creature2') creature2.animations.add('walk', Phaser.Animation.generateFrameNames('creature2_frame_', 0, 13), 30, true) creature2.animations.play('walk') creature2.anchor.set(0.3, 0) this.add.tween(creature2) .to({x: 50}, 2000, Phaser.Easing.Quadratic.InOut, true, 200, -1, true) .onLoop.add(() => { creature2.scale.x = creature2.scale.x === 1 ? -1 : 1 }) const creature1 = this.game.add.sprite(this.world.width - 50, this.world.height - 100, 'creature1') creature1.animations.add('walk', Phaser.Animation.generateFrameNames('creature1_frame_', 0, 13), 30, true) creature1.animations.play('walk') creature1.anchor.set(0.3, 0) this.add.tween(creature1) .to({x: 50}, 2000, Phaser.Easing.Quadratic.InOut, true, 0, -1, true) .onLoop.add(() => { creature1.scale.x = creature1.scale.x === 1 ? -1 : 1 }) } }
jjwallace/phaser-manifest-loader
<|start_filename|>make_windows.cmd<|end_filename|> @echo off set DIR=%CD% cd %~dp0 set PYTHONPATH=./src pyinstaller -F --distpath ./dist --workpath ./build --icon ./resource/nzb-monkey-icons.ico --noupx --clean ./src/nzbmonkey.py cd %DIR% goto EOF :EOF timeout 5
SoWx4/nzb-monkey
<|start_filename|>index.html<|end_filename|> <!doctype html> <html class="no-js"> <head> <meta charset="utf-8"> <title>Typescript, Webpack and Hot Module Replacement</title> </head> <body> <h1>Typescript, Webpack and Hot Module Replacement</h1> <p>This is a very basic example to demonstrate hot module reloading with webpack and typescript.</p> <p>The following div contains the result of a function from a.ts. Change a.ts, save it and and hot module replacement will update the module. We're notified and can update the div contents with the new value. No page reload is neccessary to use the new function.</p> <div id="a_contents" style="background-color:#f99"> </div><script src="dist/main.js"></script> </body> </html>
krausest/ts-webpack-hmr
<|start_filename|>src/examples/example02/PojoParseToJsonString.java<|end_filename|> package example02; import java.util.Arrays; import java.util.List; import com.shimizukenta.jsonhub.JsonHub; public class PojoParseToJsonString { public int num; public String str; public boolean bool; public Object nul; public List<String> list; protected float not_parse_because_not_public; public static long not_parse_because_static = -1L; public PojoParseToJsonString() { num = 1; str = "STRING"; bool = true; nul = null; list = Arrays.asList("a", "b", "c"); not_parse_because_not_public = -1.0F; } public static void main(String[] args) { PojoParseToJsonString pojo = new PojoParseToJsonString(); String json = JsonHub.fromPojo(pojo).toJson(); System.out.println(json); } } <|start_filename|>src/examples/example08/ForEachJsonHub.java<|end_filename|> package example08; import java.util.Arrays; import java.util.List; import com.shimizukenta.jsonhub.JsonHub; import com.shimizukenta.jsonhub.JsonHubType; import com.shimizukenta.jsonhub.JsonString; public class ForEachJsonHub { public int num; public String str; public boolean bool; public Object nul; public List<String> list; protected float not_parse_because_not_public; public static long not_parse_because_static = -1L; public ForEachJsonHub() { num = 1; str = "STRING"; bool = true; nul = null; list = Arrays.asList("a", "b", "c"); not_parse_because_not_public = -1.0F; } public static void main(String[] args) { ForEachJsonHub pojo = new ForEachJsonHub(); JsonHub jh = JsonHub.fromPojo(pojo); forEachEcho(jh, "", ""); } private static void forEachEcho(JsonHub jh, String name, String indent) { JsonHubType type = jh.type(); final String typeTag = "<" + type + "> "; final String nameTag = name.isEmpty() ? "" : "\"" + name + "\" is "; final String deepIndent = indent + "\t"; switch ( type ) { case NULL: { echo(indent, typeTag, nameTag, jh.toString()); break; } case TRUE: case FALSE: { echo(indent, typeTag, nameTag, jh.booleanValue()); break; } case NUMBER: { echo(indent, typeTag, nameTag, jh.optionalNubmer().get()); break; } case STRING: { echo(indent, typeTag, nameTag, jh.toString()); break; } case ARRAY: { echo(indent, typeTag, nameTag, "["); jh.forEach((JsonHub v) -> { forEachEcho(v, "", deepIndent); }); echo(indent, "]"); break; } case OBJECT: { echo(indent, typeTag, nameTag, "{"); jh.forEach((JsonString n, JsonHub v) -> { forEachEcho(v, n.toString(), deepIndent); }); echo(indent, "}"); break; } } } private static void echo(Object... oo) { for ( Object o : oo ) { System.out.print(o); } System.out.println(); } } <|start_filename|>src/examples/example06/PojoWritePrettyPrintJsonToFile.java<|end_filename|> package example06; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import com.shimizukenta.jsonhub.JsonHub; public class PojoWritePrettyPrintJsonToFile { public int num; public String str; public boolean bool; public Object nul; public List<String> list; protected float not_parse_because_not_public; public static long not_parse_because_static = -1L; public PojoWritePrettyPrintJsonToFile() { num = 1; str = "STRING"; bool = true; nul = null; list = Arrays.asList("a", "b", "c"); not_parse_because_not_public = -1.0F; } public static void main(String[] args) { Path path = Paths.get("path_to_file.json"); PojoWritePrettyPrintJsonToFile pojo = new PojoWritePrettyPrintJsonToFile(); try { JsonHub.fromPojo(pojo).prettyPrint(path); System.out.println("wrote to " + path.toAbsolutePath()); } catch ( IOException e ) { e.printStackTrace(); System.out.println("write failed"); } } } <|start_filename|>src/examples/example04/ReadJsonFileParseToPojo.java<|end_filename|> package example04; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import com.shimizukenta.jsonhub.JsonHub; public class ReadJsonFileParseToPojo { public int num; public String str; public boolean bool; public Object nul; public List<String> list; protected float not_parse_because_not_public; public static long not_parse_because_static = -1L; public ReadJsonFileParseToPojo() { num = 1; str = "STRING"; bool = true; nul = null; list = Arrays.asList("a", "b", "c"); not_parse_because_not_public = -1.0F; } @Override public String toString() { return "{" + "num: " + num + ", str: \"" + str + "\", bool: " + bool + ", nul: " + nul + ", list.size(): " + (list == null ? -1 : list.size()) + "}"; } public static void main(String[] args) { Path path = Paths.get("path_to_file.json"); try { ReadJsonFileParseToPojo pojo = JsonHub.fromFile(path).toPojo(ReadJsonFileParseToPojo.class); System.out.println(pojo); } catch ( IOException e ) { e.printStackTrace(); } } } <|start_filename|>src/examples/example03/PojoWriteJsonToFile.java<|end_filename|> package example03; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import com.shimizukenta.jsonhub.JsonHub; public class PojoWriteJsonToFile { public int num; public String str; public boolean bool; public Object nul; public List<String> list; protected float not_parse_because_not_public; public static long not_parse_because_static = -1L; public PojoWriteJsonToFile() { num = 1; str = "STRING"; bool = true; nul = null; list = Arrays.asList("a", "b", "c"); not_parse_because_not_public = -1.0F; } public static void main(String[] args) { Path path = Paths.get("path_to_file.json"); PojoWriteJsonToFile pojo = new PojoWriteJsonToFile(); try { JsonHub.fromPojo(pojo).writeFile(path); System.out.println("wrote to " + path.toAbsolutePath()); } catch ( IOException e ) { e.printStackTrace(); System.out.println("write failed"); } } } <|start_filename|>src/examples/example05/PojoParseToPrettyPrintJsonString.java<|end_filename|> package example05; import java.util.Arrays; import java.util.List; import com.shimizukenta.jsonhub.JsonHub; public class PojoParseToPrettyPrintJsonString { public int num; public String str; public boolean bool; public Object nul; public List<String> list; protected float not_parse_because_not_public; public static long not_parse_because_static = -1L; public PojoParseToPrettyPrintJsonString() { num = 1; str = "STRING"; bool = true; nul = null; list = Arrays.asList("a", "b", "c"); not_parse_because_not_public = -1.0F; } public static void main(String[] args) { PojoParseToPrettyPrintJsonString pojo = new PojoParseToPrettyPrintJsonString(); String prettyPrintJson = JsonHub.fromPojo(pojo).prettyPrint(); System.out.println(prettyPrintJson); } } <|start_filename|>src/examples/example09/ChangePrettyPrintFormat.java<|end_filename|> package example09; import java.util.Arrays; import java.util.List; import com.shimizukenta.jsonhub.JsonHub; import com.shimizukenta.jsonhub.JsonHubPrettyPrinterConfig; public class ChangePrettyPrintFormat { public int num; public String str; public boolean bool; public Object nul; public List<String> list; protected float not_parse_because_not_public; public static long not_parse_because_static = -1L; public ChangePrettyPrintFormat() { num = 1; str = "STRING"; bool = true; nul = null; list = Arrays.asList("a", "b", "c"); not_parse_because_not_public = -1.0F; } public static void main(String[] args) { ChangePrettyPrintFormat pojo = new ChangePrettyPrintFormat(); JsonHub jh = JsonHub.fromPojo(pojo); { System.out.println("Defualt prettyPrint"); System.out.println(jh.prettyPrint()); } System.out.println(); { JsonHubPrettyPrinterConfig config = JsonHubPrettyPrinterConfig.defaultConfig(); config.noneNullInObject(true); config.indent("\t"); config.lineSeparator(System.lineSeparator()); config.prefixValueSeparator(""); config.suffixValueSeparator(" "); config.prefixNameSeparator(" "); config.suffixNameSeparator(" "); config.lineSeparateBeforeValueSeparator(true); config.lineSeparateAfterValueSeparator(false); config.lineSeparateIfBlank(true); System.out.println("Changed prettyPrint"); System.out.println(jh.prettyPrint(config)); } } } <|start_filename|>src/examples/example07/CreateJsonStringByBuilder.java<|end_filename|> package example07; import com.shimizukenta.jsonhub.JsonHub; import com.shimizukenta.jsonhub.JsonHubBuilder; public class CreateJsonStringByBuilder { public CreateJsonStringByBuilder() { /* Nothign */ } public static void main(String[] args) { JsonHubBuilder bb = JsonHub.getBuilder(); JsonHub jh = bb.object( bb.pair("num", 100), bb.pair("str", "STRING"), bb.pair("bool", true), bb.pair("nul", null), bb.pair("list", bb.array( bb.build("a"), bb.build("b"), bb.build("c") )) ); System.out.println(jh.toJson()); } } <|start_filename|>src/examples/example01/JsonStringParseToPojo.java<|end_filename|> package example01; import java.util.List; import com.shimizukenta.jsonhub.JsonHub; public class JsonStringParseToPojo { public int num; public String str; public boolean bool; public Object nul; public List<String> list; protected float not_parse_because_not_public; public static long not_parse_because_static = -1L; public JsonStringParseToPojo() { not_parse_because_not_public = -1.0F; } @Override public String toString() { return "{" + "num: " + num + ", str: \"" + str + "\", bool: " + bool + ", nul: " + nul + ", list.size(): " + (list == null ? -1 : list.size()) + "}"; } public static void main(String[] args) { String json = "{\"num\": 100, \"str\": \"string\", \"bool\": true, \"nul\": null, \"list\": [\"a\", \"b\", \"c\"]}"; System.out.println(json); JsonStringParseToPojo pojo = JsonHub.fromJson(json).toPojo(JsonStringParseToPojo.class); System.out.println(pojo); } } <|start_filename|>src/main/java/module-info.java<|end_filename|> module com.shimizukenta.jsonhub { exports com.shimizukenta.jsonhub; }
kenta-shimizu/json4java8
<|start_filename|>example/lib/dialog/develop_dialog.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:flutter_custom_dialog/flutter_custom_dialog.dart'; YYDialog YYFixTextFieldDialog() { return YYDialog().build() ..width = 120 ..height = 110 ..backgroundColor = Colors.white ..borderRadius = 10.0 ..gravity = Gravity.bottom ..widget( Padding( padding: EdgeInsets.all(24), child: TextField(), ), ) ..show(); } <|start_filename|>example/lib/dialog/listview_dialog.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:flutter_custom_dialog/flutter_custom_dialog.dart'; var listTileItems = [ ListTileItem( padding: EdgeInsets.fromLTRB(16.0, 6.0, 16.0, 6.0), leading: ClipOval( child: Image.network( "https://imgavater.ui.cn/avatar/3/3/4/9/1269433.jpg?imageMogr2/auto-orient/crop/!1219x1219a12a0/thumbnail/148x148", height: 50, width: 50, fit: BoxFit.cover, ), ), text: "<EMAIL>", color: Colors.grey, fontSize: 16.0, ), ListTileItem( padding: EdgeInsets.fromLTRB(16.0, 6.0, 16.0, 6.0), leading: ClipOval( child: Image.network( "https://imgavater.ui.cn/avatar/1/4/7/8/958741.jpg?imageMogr2/auto-orient/crop/!563x563a377a167/thumbnail/60x60", height: 50, width: 50, fit: BoxFit.cover, ), ), text: "<EMAIL>", color: Colors.grey, fontSize: 16.0, ), ListTileItem( padding: EdgeInsets.fromLTRB(16.0, 6.0, 16.0, 6.0), leading: ClipOval( child: Image.network( "https://imgavater.ui.cn/avatar/6/0/7/5/165706.png?imageMogr2/auto-orient/crop/!798x798a109a100/thumbnail/148x148", height: 50, width: 50, fit: BoxFit.cover, ), ), text: "<EMAIL>", color: Colors.grey, fontSize: 16.0, ), ListTileItem( padding: EdgeInsets.fromLTRB(16.0, 6.0, 16.0, 6.0), leading: ClipOval( child: Container( width: 50, height: 50, child: Icon(Icons.add, size: 30, color: Colors.white), color: Colors.grey[500], )), text: "Add account", color: Colors.grey, fontSize: 16.0, ), ]; var radioItems = [ RadioItem( padding: EdgeInsets.only(left: 6.0), text: "None", color: Colors.black, fontSize: 16.0, ), RadioItem( padding: EdgeInsets.only(left: 6.0), text: "Callisto", color: Colors.black, fontSize: 16.0, ), RadioItem( padding: EdgeInsets.only(left: 6.0), text: "Ganymede", color: Colors.black, fontSize: 16.0, ), RadioItem( padding: EdgeInsets.only(left: 6.0), text: "Luna", color: Colors.black, fontSize: 16.0, ), RadioItem( padding: EdgeInsets.only(left: 6.0), text: "Oberon", color: Colors.black, fontSize: 16.0, ), RadioItem( padding: EdgeInsets.only(left: 6.0), text: "Phobos", color: Colors.black, fontSize: 16.0, ), RadioItem( padding: EdgeInsets.only(left: 6.0), text: "Dione", color: Colors.black, fontSize: 16.0, ), RadioItem( padding: EdgeInsets.only(left: 6.0), text: "James", color: Colors.black, fontSize: 16.0, ), RadioItem( padding: EdgeInsets.only(left: 6.0), text: "Lina", color: Colors.black, fontSize: 16.0, ), ]; YYDialog YYListViewDialogListTile() { return YYDialog().build() ..width = 280 ..borderRadius = 4.0 ..text( padding: EdgeInsets.fromLTRB(18.0, 18.0, 18.0, 12.0), text: "Set backup account", color: Colors.black, fontSize: 18.0, fontWeight: FontWeight.w500, ) ..listViewOfListTile( items: listTileItems, onClickItemListener: (index) { var listTileItem = listTileItems[index]; print(listTileItem.text + " is on click"); }) ..show(); } YYDialog YYListViewDialogListRadio() { return YYDialog().build() ..width = 280 ..borderRadius = 4.0 ..text( padding: EdgeInsets.fromLTRB(18.0, 22.0, 18.0, 18.0), text: "Phone ringtone", color: Colors.black, fontSize: 18.0, fontWeight: FontWeight.w500, ) ..divider() ..listViewOfRadioButton( items: radioItems, height: 370, intialValue: 2, color: Colors.white, activeColor: Colors.deepPurpleAccent, onClickItemListener: (index) { var radioItem = radioItems[index]; print(radioItem.text + " is on click"); }) ..divider() ..doubleButton( padding: EdgeInsets.only(top: 8.0, bottom: 8.0), gravity: Gravity.right, text1: "CANCEL", color1: Colors.deepPurpleAccent, fontSize1: 14.0, fontWeight1: FontWeight.bold, text2: "OK", color2: Colors.deepPurpleAccent, fontSize2: 14.0, fontWeight2: FontWeight.bold, ) ..show(); }
fajarcahyoprabowo/flutter-custom-dialog
<|start_filename|>vendor/github.com/ViaQ/logerr/log/log.go<|end_filename|> package log import ( "fmt" "io" "os" "sync" "github.com/ViaQ/logerr/kverrors" "github.com/go-logr/logr" ) // ErrUnknownLoggerType is returned when trying to perform a *Logger only function // that is incompatible with logr.Logger interface var ErrUnknownLoggerType = kverrors.New("unknown error type") var ( defaultOutput io.Writer = os.Stdout defautLogLevel = 0 // logLevel sets the level at which you want logs to be displayed // By default the verbosity is set to 0 and all logs that do not // use V(...) will be printed. To increase logging verbosity logLevel = defautLogLevel mtx sync.RWMutex logger logr.Logger = NewLogger("", os.Stdout, 0, JSONEncoder{}) ) // Init initializes the logger. This is required to use logging correctly // component is the name of the component being used to log messages. // Typically this is your application name. // // keyValuePairs are key/value pairs to be used with all logs in the future func Init(component string, keyValuePairs ...interface{}) { InitWithOptions(component, nil, keyValuePairs...) } // MustInit calls Init and panics if it returns an error func MustInit(component string, keyValuePairs ...interface{}) { Init(component, keyValuePairs...) } // InitWithOptions inits the logger with the provided opts func InitWithOptions(component string, opts []Option, keyValuePairs ...interface{}) { mtx.Lock() defer mtx.Unlock() ll := NewLogger(component, defaultOutput, 0, JSONEncoder{}, keyValuePairs...) for _, opt := range opts { opt(ll) } // don't lock because we already have a lock useLogger(ll) } // MustInitWithOptions calls InitWithOptions and panics if an error is returned func MustInitWithOptions(component string, opts []Option, keyValuePairs ...interface{}) { InitWithOptions(component, opts, keyValuePairs...) } // GetLogger returns the root logger used for logging func GetLogger() logr.Logger { return logger } // UseLogger bypasses the requirement for Init and sets the logger to l func UseLogger(l logr.Logger) { mtx.Lock() defer mtx.Unlock() useLogger(l) } // useLogger sets the logger to l without mtx.Lock() // To use mtx.Lock see UseLogger func useLogger(l logr.Logger) { logger = l } // Info logs a non-error message with the given key/value pairs as context. // // The msg argument should be used to add some constant description to // the log line. The key/value pairs can then be used to add additional // variable information. The key/value pairs should alternate string // keys and arbitrary values. func Info(msg string, keysAndValues ...interface{}) { mtx.RLock() defer mtx.RUnlock() logger.Info(msg, keysAndValues...) } // Error logs an error, with the given message and key/value pairs as context. // It functions similarly to calling Info with the "error" named value, but may // have unique behavior, and should be preferred for logging errors (see the // package documentations for more information). // // The msg field should be used to add context to any underlying error, // while the err field should be used to attach the actual error that // triggered this log line, if present. func Error(err error, msg string, keysAndValues ...interface{}) { mtx.RLock() defer mtx.RUnlock() logger.Error(err, msg, keysAndValues...) } // WithValues adds some key-value pairs of context to a logger. // See Info for documentation on how key/value pairs work. func WithValues(keysAndValues ...interface{}) logr.Logger { mtx.RLock() defer mtx.RUnlock() return logger.WithValues(keysAndValues...) } // SetLogLevel sets the output verbosity func SetLogLevel(v int) { mtx.Lock() defer mtx.Unlock() logLevel = v } // SetOutput sets the logger output to w if the root logger is *log.Logger // otherwise it returns ErrUnknownLoggerType func SetOutput(w io.Writer) error { mtx.RLock() defer mtx.RUnlock() switch ll := logger.(type) { case *Logger: ll.SetOutput(w) default: return kverrors.Add(ErrUnknownLoggerType, "logger_type", fmt.Sprintf("%T", logger), "expected_type", fmt.Sprintf("%T", &Logger{}), ) } return nil } // WithName adds a new element to the logger's name. // Successive calls with WithName continue to append // suffixes to the logger's name. It's strongly recommended // that name segments contain only letters, digits, and hyphens // (see the package documentation for more information). func WithName(name string) logr.Logger { mtx.RLock() defer mtx.RUnlock() return logger.WithName(name) } // V returns an Logger value for a specific verbosity level, relative to // this Logger. In other words, V values are additive. V higher verbosity // level means a log message is less important. // V(level uint8) Logger func V(level int) logr.Logger { mtx.RLock() defer mtx.RUnlock() return logger.V(level) } <|start_filename|>vendor/github.com/ViaQ/logerr/log/options.go<|end_filename|> package log import ( "io" ) // Option is a configuration option type Option func(*Logger) // WithOutput sets the output to w func WithOutput(w io.Writer) Option { return func(l *Logger) { l.SetOutput(w) } } // WithLogLevel sets the output log level and controls which verbosity logs are printed func WithLogLevel(v int) Option { return func(*Logger) { logLevel = v } } <|start_filename|>internal/metrics/metrics.go<|end_filename|> package metrics import ( "github.com/prometheus/client_golang/prometheus" "sigs.k8s.io/controller-runtime/pkg/metrics" ) const ( CertRestart string = "cert_restart" RollingRestart string = "rolling_restart" ScheduledRestart string = "scheduled_restart" ManagedState string = "managed" UnmanagedState string = "unmanaged" ) var ( restartCounter = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "eo_elasticsearch_cr_restart_total", Help: "Total number of times the nodes restarted due to Cert Restart or Rolling Restart or Scheduled Restart.", }, []string{"reason"}) esClusterManagementState = prometheus.NewGaugeVec( prometheus.GaugeOpts{ Name: "eo_elasticsearch_cr_cluster_management_state", Help: "Number of Elasticsearch cluster that are in Managed state or Unmanaged state.", }, []string{"state"}) metricList = []prometheus.Collector{ restartCounter, esClusterManagementState, } ) // This function registers the custom metrics to the kubernetes controller-runtime default metrics. func RegisterCustomMetrics() { for _, metric := range metricList { metrics.Registry.MustRegister(metric) } } // Increment the metric value by "1" when the node restarts due to cert. func IncrementRestartCounterCert() { restartCounter.With(prometheus.Labels{ "reason": CertRestart, }).Inc() } // Increment the metric value by "1" when the node restarts due to rolling. func IncrementRestartCounterRolling() { restartCounter.With(prometheus.Labels{ "reason": RollingRestart, }).Inc() } // Increment the metric value by "1" when the node is scheduled for cert restart or rolling restart. func IncrementRestartCounterScheduled() { restartCounter.With(prometheus.Labels{ "reason": ScheduledRestart, }).Inc() } // Sets the metric value to "n" when the ES Cluster Management State is Managed. func SetEsClusterManagementStateManaged() { esClusterManagementState.With(prometheus.Labels{ "state": ManagedState, }).Set(1) esClusterManagementState.With(prometheus.Labels{ "state": UnmanagedState, }).Set(0) } // Sets the metric value to "n" when the ES Cluster Management State is Unmanaged. func SetEsClusterManagementStateUnmanaged() { esClusterManagementState.With(prometheus.Labels{ "state": ManagedState, }).Set(0) esClusterManagementState.With(prometheus.Labels{ "state": UnmanagedState, }).Set(1) } <|start_filename|>vendor/github.com/ViaQ/logerr/kverrors/doc.go<|end_filename|> // Package kverrors provides structured errors // // errors can be used with pkg/log to further enhance structured logging package kverrors <|start_filename|>vendor/github.com/ViaQ/logerr/log/doc.go<|end_filename|> // Package log provides structured logging package log
sreber84/elasticsearch-operator
<|start_filename|>android/playground/app/src/main/java/com/alibaba/weex/extend/module/location/LocationFactory.java<|end_filename|> package com.alibaba.weex.extend.module.location; import com.taobao.weex.WXSDKInstance; /** */ public class LocationFactory { public static ILocatable getLocationProvider(WXSDKInstance context){ return new DefaultLocation(context); } } <|start_filename|>android/playground/app/src/main/java/com/alibaba/weex/extend/module/location/ILocatable.java<|end_filename|> package com.alibaba.weex.extend.module.location; import com.taobao.weex.WXSDKInstance; /** */ public interface ILocatable { int REQUEST_CUR_PERMISSION_CODE = 0x12; int REQUEST_WATCH_PERMISSION_CODE = 0x13; String REQUEST_PERMISSION_CODE = "requestCode"; String ERROR_CODE = "errorCode"; String ERROR_MSG = "errorMsg"; String COORDS = "coords"; String ADDRESS = "address"; String WATCH_ID = "watchId"; interface ErrorCode { int SUCCESS = 90000; int NO_PERMISSION_ERROR = 90001; int PARAMS_ERROR = 90002; int LOCATION_ERROR = 9003; int LOCATION_TIME_OUT = 9004; } interface ErrorMsg { String NO_PERMISSION_ERROR = "NO PERMISSION"; String PARAMS_ERROR = "PARAMS_ERROR"; String LOCATION_ERROR = "LOCATION_FAIL"; String LOCATION_TIME_OUT = "LOCATION_TIME_OUT"; String SUCCESS = "SUCCESS"; } /** * Get current location information, the callback only once * * @param successCallback success callback function id. * @param errorCallback error callback function id.(example:no persimmon) * @param params JSON parameter(example:address). */ void getCurrentPosition(String successCallback, String errorCallback, String params); /** * register global location listener,if location change,you will be notify. * * @param successCallback location success callback function id. * @param errorCallback location error callback (example:no persimmon). * @param params JSON parameter(example:address). */ void watchPosition(String successCallback, String errorCallback, String params); /** * remove global location listener. * * @param watchId register id,you can get from watchPosition method。 */ void clearWatch(String watchId); /** * set instance * * @param instance instance */ void setWXSDKInstance(WXSDKInstance instance); /** * this method will call when module destroy. */ void destroy(); }
sukeyang/weex
<|start_filename|>examples/lines.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (defun main (size fn) (let ((mid (* 0.5d0 size)) (repeat 15) (grains 3) (itt 1000) (sand (sandpaint:make size :fg (pigment:black 0.01) :bg (pigment:white)))) (loop for i in (math:linspace repeat 100d0 900d0) for j from 1 to repeat do (print-every j 2) (let ((snk (snek:make)) (va (vec:vec 0d0 0d0)) (vb (vec:vec 0d0 0d0)) (p1 (vec:vec 100d0 i)) (p2 (vec:vec 900d0 i))) (loop for s in (math:linspace itt 0d0 1d0) do (let ((v1 (snek:add-vert! snk (vec:on-line s p1 p2))) (v2 (snek:add-vert! snk (vec:add va (vec:on-line s p1 p2))))) (setf va (vec:add va (rnd:in-circ (* 0.7d0 j)))) (setf vb (vec:add vb (rnd:in-circ (* 0.001d0 j)))) (snek:cwith (snk %) (snek:itr-grp-verts (snk v :collect nil) (% (snek:move-vert? v (vec:add (rnd:in-circ 0.1d0) vb)))) (% (snek:add-edge? v1 v2))) (snek:draw-edges snk sand grains) (snek:draw-verts snk sand))))) (sandpaint:pixel-hack sand) ;(sandpaint:chromatic-aberration sand (list mid mid) :s 100.0) (sandpaint:save sand fn))) (time (main 1000 (second (cmd-args)))) <|start_filename|>examples/scratch.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (defun sum-alter-velocity (velocities a num) (loop for i from 1 to (1- num) do (vec:sarr-set velocities i (vec:add (rnd:in-circ a) (vec:sarr-get velocities (1- i)))))) (defun make-lattice (n a b) (apply #'append (loop for x in (math:linspace n a b) collect (loop for y in (math:linspace n a b) collect (vec:vec x y))))) (defun main (size fn) (let ((snk (snek:make)) (verts nil) (grains 4) (velocities (make-array 200 :initial-element 0d0 :element-type 'double-float)) (lattice (make-lattice 50 100d0 900d0)) (noise 1.5d0) (itt 8000) (sand (sandpaint:make size :fg (pigment:black 0.08) :bg (pigment:white)))) (setf verts (loop for i from 1 to 100 collect (snek:add-vert! snk (rnd:rndget lattice)))) (loop for i from 0 to itt do (if (eql (mod i 100) 0) (format t "~a~%" i)) (destructuring-bind (p1 p2) (list (rnd:rndget verts) (rnd:rndget verts)) (if (< (vec:dst (snek:get-vert snk p1) (snek:get-vert snk p2)) 100.0) (progn (sum-alter-velocity velocities noise 100) (snek:with (snk) ; TODO mutate was used here. implement later. (snek:add-edge? p1 p2) (snek:itr-grp-verts (snk v) (snek:move-vert? v (vec:sarr-get velocities v))))))) (snek:draw-edges snk sand grains)) (sandpaint:pixel-hack sand) (sandpaint:save sand fn))) (time (main 1000 (second (cmd-args)))) <|start_filename|>examples/spline-script.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (load "../utils/text") (load "../utils/text-sample") (load "../utils/spline-script") (load "../utils/state") (defvar *alphabet* "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.,?-—:'") (defun scale () (if (< (rnd:rnd) 0.15) (vec:vec 1.1d0 3.9d0) (vec:vec 1d0 1d0))) (defun swap (l) (let* ((ll (loop for k in l collect k)) (n (length l)) (a (rnd:rndi n)) (b (rnd:rndi n))) (setf (nth a ll) (nth b l) (nth b ll) (nth a l)) ll)) (defun shape (n bx by) ;(rnd:nin-box n bx by) (vec:lmult* (rnd:nin-circ n 1d0) (vec:vec bx by))) (defun draw-pix (sand bzs grains) (sandpaint:bzspl-stroke sand bzs (* grains (bzspl::bzspl-n bzs)))) (defun draw-varying-pix (sand bzs grains) (sandpaint:pix sand (bzspl:pos* bzs (mapcar (lambda (x) (expt x 0.6d0)) (rnd:rndspace (* grains (bzspl::bzspl-n bzs)) 0d0 1d0))))) (defun draw (snk sand) (let ((state-gen (get-walker-state-gen (lambda () (rnd:get-acc-circ-stp*)))) (grains 15) (drift (vec:scale (vec:sin-cos -0.1d0) 0.009d0))) (loop for p in (math:linspace 500 0d0 1d0) and i from 0 do (snek:with (snk) (snek:itr-verts (snk v) (snek:move-vert? v drift) (snek:move-vert? v (rnd:in-circ 0.1d0)) ;(snek:move-vert? v (funcall state-gen v 0.000008d0)) )) ;(sandpaint:set-fg-color sand (pigment:hsv 0.55 (- 1.0 i) (- 1.0 i) 0.009)) (snek:itr-grps (snk g :collect nil) (aif (snek:get-grp-as-bzspl snk g) ;(draw-pix sand it grains) (draw-varying-pix sand it grains)))))) (defun main (size fn) (let ((trbl (list 70d0 950d0 950d0 55d0)) (bbox (vec:vec 20d0 25d0)) (spacebox (vec:vec 10d0 25d0)) (sand (sandpaint:make size :fg (pigment:black 0.009) :bg (pigment:white)))) (labels ((get-bbox-fxn () (let ((bbox (vec:mult bbox (scale)))) (vec:with-xy ((vec:scale bbox 0.5d0) bx by) (lambda (n) (mapcar (lambda (v) (vec:rot v (* PI 0.2d0))) (shape n bx by)))))) (estimate-nc-ncn-fxn (bbox-fxn) (let* ((samples (funcall bbox-fxn 1000)) (mid (vec:lmid samples)) (area (apply #'max (mapcar (lambda (a) (vec:dst a mid)) samples)))) (if (< area 30d0) (list area 4 1) (list area 7 1)))) (sort-centroids-fxn () (let ((f (if (< (rnd:rnd)) #'< #'>)) (rot (rnd:rnd PII))) (lambda (centroids) (let ((res (sort (loop for c in centroids collect (list (+ rot (apply #'atan (reverse (vec:tolist c)))) c)) f :key #'first))) (if (< (rnd:rnd) 0.6) (swap res) res)))))) (let ((alphabet (show-alphabet (get-alphabet *alphabet* :get-bbox-fxn #'get-bbox-fxn :nc-ncn-fxn #'estimate-nc-ncn-fxn :sort-fxn #'sort-centroids-fxn :min-dst 5d0))) (words (remove-if (lambda (x) (= 0 (second x))) (apply #'append (get-words* *alice*))) ) (wind 0)) (block draw-loop (loop for k from 0 do (let ((snk (snek:make)) (txt (subseq words wind))) (incf wind (aif (do-write snk alphabet spacebox trbl txt) it (return-from draw-loop))) (draw snk sand)) (sandpaint:pixel-hack sand) (sandpaint:save sand (append-postfix fn (format nil "-~3,'0d" k)) :gamma 1.5) (sandpaint:clear sand (pigment:white)))))))) (time (main 1000 (second (cmd-args)))) <|start_filename|>src/load.lisp<|end_filename|> (setf *efficiency-note-cost-threshold* 14) (declaim (optimize (speed 3))) ;(declaim (optimize (safety 3))) ;(declaim (optimize (space 3))) ;(declaim (optimize (debug 3))) (declaim (inline last1 single append1 conc1 mklist)) (load "~/quicklisp/setup.lisp") (ql:quickload "zpng") (ql:quickload "png") (ql:quickload "cl-svg") (asdf:defsystem "snek" :description "A System for Making Generative Systems" :version "2.69.0" :author "inconvergent" :licence "MIT" :serial t :depends-on ("zpng" "cl-svg" "png") :components ((:file "pg-utils") (:file "various") (:file "packages") (:file "rnd") (:file "state") (:file "vec") (:file "math") (:file "math-extra") (:file "pigment") (:file "hset") (:file "rnd-extra") (:file "graph") (:file "bzspline") (:file "linear-path") (:file "sandpaint") (:file "sandpaint-flip-reflect") (:file "sandpaint-extra") (:file "draw-svg") (:file "draw-tile-svg") (:file "obj") (:file "zonemap") (:file "snek-macros") (:file "snek") (:file "snek-utils") (:file "snek-alterations") (:file "snek-extra"))) (asdf:load-system "snek") (setf *random-state* (make-random-state t)) (setf *print-pretty* t) <|start_filename|>utils/three-point.lisp<|end_filename|> (defun -make-front-path (aa bb cc as bs) (let ((p1 (vec:add cc (vec:scale (vec:sub aa cc) as))) (p2 (vec:add cc (vec:scale (vec:sub bb cc) bs)))) (list p1 cc p2))) (defun -make-full-path (aa bb cc as bs) (let ((p1 (vec:add cc (vec:scale (vec:sub aa cc) as))) (p2 (vec:add cc (vec:scale (vec:sub bb cc) bs)))) (list p1 cc p2 (vec:add p2 (vec:scale (vec:sub aa p2) as)) p1))) (defun make-perspective-transform (a b c) (lambda (p a* b* u* d*) (let ((pc (vec:sub c p))) (let ((u (vec:sub p (vec:scale pc u*))) (d (vec:add p (vec:scale pc d*)))) (append (-make-full-path a b u a* b*) (-make-full-path a b d a* b*)))))) <|start_filename|>examples/grp.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load.lisp") (defun init (snk rep rad) (loop for x in (math:linspace rep 200d0 800d0) for i from 0 do (loop for y in (math:linspace rep 200d0 800d0) for j from 0 do (let ((g (snek:add-grp! snk :type 'path))) (snek:add-polygon! snk (rnd:rndi 3 6) rad :xy (vec:vec x y) :g g))))) (defun main (size fn) (let ((grains 4) (itt 10000) (noise 0.000000018d0) (rep 10) (rad 25d0) (snk (snek:make :max-verts 10000)) (sand (sandpaint:make size :fg (pigment:white 0.005) :bg (pigment:gray 0.1d0)))) (init snk rep rad) (let ((grp-states (make-hash-table :test #'equal))) (snek:itr-grps (snk g) (setf (gethash g grp-states) (rnd:get-acc-circ-stp*))) (loop for i from 0 to itt do (print-every i 1000) (snek:with (snk) (snek:itr-grps (snk g) (let ((ns (funcall (gethash g grp-states) noise))) (snek:itr-grp-verts (snk v :g g) (snek:move-vert? v (vec:add ns (rnd:in-circ 0.05d0))))))) (snek:itr-grps (snk g :collect nil) (snek:draw-edges snk sand grains :g g)))) ;(sandpaint:chromatic-aberration sand) (sandpaint:pixel-hack sand) (sandpaint:save sand fn))) (time (main 1000 (second (cmd-args)))) <|start_filename|>test/tools.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (load "../utils/test") (defun test-utils () (do-test (vec:norm (vec:vec 3.0d0 0.0d0)) (vec:vec 1.0d0 0.0d0)) (do-test (vec:sub (vec:vec 1.0d0 2.0d0) (vec:vec 2.0d0 3.0d0)) (vec:vec -1.d0 -1.d0)) (do-test (vec:add (vec:vec 1.0d0 2.0d0) (vec:vec 2.0d0 3.0d0)) (vec:vec 3.0d0 5.0d0)) (do-test (vec:nsub (vec:vec 1.0d0 2.0d0) (vec:vec 2.0d0 10.0d0)) (vec:vec -0.12403473458920847d0 -0.9922778767136677d0)) (do-test (vec:len2 (vec:vec 1.0d0 2.0d0)) 5) (do-test (vec:len (vec:vec 1.0d0 2.0d0)) 2.23606797749979d0) (do-test (vec:len (vec:vec 1.0d0 2.0d0)) 2.23606797749979d0) (do-test (vec:dst (vec:vec 1.0d0 2.0d0) (vec:vec 1.0d0 3.0d0)) 1.0d0) (do-test (vec:mid (vec:vec 1.0d0 2.0d0) (vec:vec 3.0d0 4.0d0)) (vec:vec 2.0d0 3.0d0)) (do-test (vec:sum (list (vec:vec 1.0d0 2.0d0) (vec:vec 0.5d0 4.322d0))) (vec:vec 1.5d0 6.322d0)) (do-test (vec:on-line 0.34d0 (vec:vec 33d0 88d0) (vec:vec 32d0 733d0)) (vec:vec 32.66d0 307.3d0)) (do-test (vec:on-circ 0.34d0 388d0 :xy (vec:vec 32d0 733d0)) (vec:vec -175.9007964518508d0 1060.5992350947818d0)) (do-test (to-list (math:path-tangents (list (vec:vec 1.0d0 2.0d0) (vec:vec 1.0d0 2.0d0) (vec:vec 0.5d0 4.322d0)))) (list (vec:vec 0d0) (vec:vec -0.21050655592417808d0 0.977592445711883d0))) (do-test (math:inc 0.1d0 0.4d0) 0.5d0) (do-test (math:inc 0.1d0 -0.4d0) 0.7d0) (do-test (math:linspace 1 0d0 10d0) (list 0.0)) (do-test (math:linspace 3 0d0 10d0) (list 0.0 5.0 10.0)) (do-test (math:linspace 2 0d0 10d0 :end nil) (list 0.0 5.0)) (do-test (math:linspace 2 0d0 10d0 :end t) (list 0.0 10.0)) (do-test (math:range 2 5) (list 2 3 4)) (do-test (math:range 5) (list 0 1 2 3 4)) (do-test (let ((a (list))) (math:with-linspace (10 0d0 7d0 v) (setf a (append a (list v)))) a) '(0.0d0 0.7777777777777778d0 1.5555555555555556d0 2.3333333333333335d0 3.111111111111111d0 3.888888888888889d0 4.666666666666667d0 5.444444444444445d0 6.222222222222222d0 7.0d0)) (do-test (let ((a (list))) (math:with-linspace (10 0d0 7d0 v :end nil) (setf a (append a (list v)))) a) '(0.0d0 0.7d0 1.4d0 2.0999999999999996d0 2.8d0 3.5d0 4.199999999999999d0 4.8999999999999995d0 5.6d0 6.3d0)) (do-test (vec:segdst (list (vec:vec 0d0 0d0) (vec:vec 100d0 0d0)) (vec:vec 0d0 200d0)) 200d0) (do-test (vec:segdst (list (vec:vec 0d0 0d0) (vec:vec 100d0 3d0)) (vec:vec 41d0 202d0)) 200.67971443818558d0) (do-test (multiple-value-bind (x s) (vec:segx (list (vec:vec 1.1d0) (vec:vec 11d0 12.3d0)) (list (vec:vec 0.1d0 10d0) (vec:vec 8d0 -1.1d0))) (list x s)) (list t 0.2984826334627212d0)) (do-test (vec:segx (list (vec:vec 0d0 0d0) (vec:vec 100d0 0d0)) (list (vec:vec 0d0 1d0) (vec:vec 100d0 1d0)) :parallel :par) :par) (do-test (vec:segx (list (vec:vec 0d0 0d0) (vec:vec 1d0 1d0)) (list (vec:vec 0d0 1d0) (vec:vec 1d0 0d0)) :parallel :par) t) (do-test (vec:cross (vec:vec 1d0 2d0) (vec:vec 3d0 -7.1d0)) -13.1d0)) (defun test-rnd () (rnd:set-rnd-state 1) (do-test (length (rnd:rndspace 10 0d0 10d0)) 10) (do-test (rnd:rndspace 10 0d0 10d0) '(8.383887417540674d0 3.704390759927394d0 4.089044985321939d0 7.5623438794824605d0 0.5477479401961061d0 3.409356250400757d0 8.3460946770173d0 1.1737959928376207d0 2.8077405846385473d0 3.962028297321658d0)) (do-test (rnd:rndspace 10 0d0 10d0 :order t) '(0.7810904793737161d0 1.700886055024764d0 3.396607010299655d0 3.8464500251059364d0 6.014897498803242d0 6.268483093269445d0 7.527788782312825d0 7.562853532104885d0 7.892139712781054d0 9.365232493948968d0)) (do-test (rnd:rndspacei 10 0 10) '(7 3 6 5 1 9 3 4 8 1)) (do-test (rnd:rndspacei 10 0 10 :order t) '(0 0 2 2 3 4 4 7 9 9)) (do-test (length (rnd:nrndi 9 4)) 9) (do-test (length (rnd:nrnd 11 4d0)) 11) (do-test (length (rnd:nrnd 12 4d0)) 12) (do-test (length (rnd:nrnd* 12 4d0)) 12) (do-test (rnd:bernoulli 4 0.5d0) '(0.0d0 0.0d0 0.0d0 0.0d0)) (do-test (let ((a (list))) (rnd:with-rndspace (10 0d0 7d0 v) (setf a (append a (list v)))) a) '(6.507759172138558d0 2.2881798617968423d0 1.7037377515259524d0 1.6064438902476477d0 6.2928480610573665d0 6.298771369144957d0 1.097454636438975d0 5.713911684630423d0 3.318378773155661d0 5.647317315258949d0)) (do-test (let ((a (list))) (rnd:with-on-line (10 (vec:vec 1d0 1d0) (vec:vec 4d0 3d0) v) (setf a (append a (list v)))) a) (list (vec:vec 1.4420775452437415d0 1.2947183634958277d0) (vec:vec 1.0172227079557705d0 1.011481805303847d0) (vec:vec 1.702867945470302d0 1.4685786303135346d0) (vec:vec 2.9598710402505835d0 2.306580693500389d0) (vec:vec 1.1623459120025506d0 1.1082306080017004d0) (vec:vec 3.3156539222026513d0 2.543769281468434d0) (vec:vec 3.143617069170394d0 2.429078046113596d0) (vec:vec 3.4512122094895474d0 2.6341414729930315d0) (vec:vec 1.7401594182758866d0 1.4934396121839244d0) (vec:vec 1.0949266500503054d0 1.0632844333668703d0))) (do-test (let ((a (list))) (rnd:with-in-circ (10 4d0 v) (setf a (append a (list v)))) a) (list (vec:vec -3.2289266618005463d0 1.173326893900633d0) (vec:vec -2.267965042218162d0 3.268859019509251d0) (vec:vec -1.4143813501406504d0 3.1585446412766736d0) (vec:vec -0.8043636451397664d0 1.3535842643178702d0) (vec:vec 2.0421463502216497d0 -0.07975392718826195d0) (vec:vec -3.384193548911458d0 -6.350251329993679d-4) (vec:vec 0.5328441305158991d0 0.8393134784537689d0) (vec:vec 0.20238689972914906d0 -0.101591706130127d0) (vec:vec -1.162668476292421d0 -2.635125988346128d0) (vec:vec -0.039436399757947375d0 -0.42073258274167163d0))) (do-test (rnd:on-line (vec:vec 101d0 204d0) (vec:vec 433d0 454d0)) (vec:vec 328.1083568590696d0 375.01532896014277d0)) (do-test (rnd:on-circ 303d0 :xy (vec:vec 303d0 73d0)) (vec:vec 306.14778707543655d0 375.98364879400293d0)) (do-test (rnd:in-circ 303d0 :xy (vec:vec 303d0 73d0)) (vec:vec 243.51609955461907d0 231.38334433095946d0)) (do-test (rnd:non-line 5 (vec:vec 101d0 204d0) (vec:vec 433d0 454d0)) (list (vec:vec 412.8114993587596d0 438.7978157821985d0) (vec:vec 141.5239773978766d0 234.51504322129261d0) (vec:vec 113.3819941657358d0 213.32379078745166d0) (vec:vec 300.62005634338436d0 354.3163074874882d0) (vec:vec 255.69499795342622d0 320.487197254086d0))) (do-test (rnd:nin-circ 5 20d0 :xy (vec:vec 433d0 454d0)) (list (vec:vec 437.0273521546584d0 439.0174212934645d0) (vec:vec 426.7886779194167d0 440.85162023013874d0) (vec:vec 428.35235989996613d0 456.86207789540106d0) (vec:vec 428.149958120093d0 454.189520107701d0) (vec:vec 429.3064265983025d0 456.20125820264457d0)))) (defun test-bzspl () (let ((pts-a (list (vec:vec -20.0d0 99.0d0) (vec:vec 0.0d0 1.0d0) (vec:vec 10.0d0 20.0d0) (vec:vec 100.0d0 100.0d0))) (pts-b (list (vec:vec -20.0d0 99.0d0) (vec:vec 0.0d0 1.0d0) (vec:vec 10.0d0 20.0d0) (vec:vec 100.0d0 100.0d0) (vec:vec -3.0d0 -17.0d0) (vec:vec 0.0d0 4.0d0))) (pts-c (list (vec:vec -32.0d0 79.0d0) (vec:vec 0.3d0 3.0d0) (vec:vec 10.1d0 25.0d0)))) (do-test (bzspl:pos* (bzspl:make pts-c) (math:linspace 5 0d0 1d0)) (list (vec:vec -32.0d0 79.0d0) (vec:vec -17.256249999999998d0 47.125d0) (vec:vec -5.324999999999999d0 27.5d0) (vec:vec 3.7937499999999993d0 20.125d0) (vec:vec 10.1d0 25.0d0))) (do-test (bzspl:pos* (bzspl:make pts-c :closed t) (math:linspace 5 0d0 1d0)) (list (vec:vec -15.85d0 41.0d0) (vec:vec 2.046875d0 11.5625d0) (vec:vec 3.6125d0 29.0d0) (vec:vec -19.150000000000002d0 61.4375d0) (vec:vec -15.85d0 41.0d0))) (do-test (bzspl:pos* (bzspl:make pts-a) (math:linspace 10 0d0 1d0)) (list (vec:vec -20.0d0 99.0d0) (vec:vec -11.851851851851853d0 60.75308641975309d0) (vec:vec -5.185185185185186d0 33.12345679012346d0) (vec:vec -8.881784197001252d-16 16.111111111111114d0) (vec:vec 3.7037037037037024d0 9.716049382716054d0) (vec:vec 7.160493827160495d0 13.481481481481485d0) (vec:vec 17.777777777777775d0 24.666666666666664d0) (vec:vec 36.7901234567901d0 42.814814814814795d0) (vec:vec 64.19753086419752d0 67.92592592592591d0) (vec:vec 100.0d0 100.0d0))) (do-test (bzspl:pos* (bzspl:make pts-b) (math:linspace 10 0d0 1d0)) (list (vec:vec -20.0d0 99.0d0) (vec:vec -5.185185185185186d0 33.12345679012346d0) (vec:vec 3.7037037037037024d0 9.716049382716054d0) (vec:vec 12.777777777777775d0 20.22222222222222d0) (vec:vec 36.9753086419753d0 43.728395061728385d0) (vec:vec 70.23456790123457d0 72.91358024691358d0) (vec:vec 72.11111111111111d0 69.55555555555556d0) (vec:vec 37.728395061728435d0 29.481481481481524d0) (vec:vec 8.098765432098773d0 1.0370370370370405d0) (vec:vec 0.0d0 4.0d0))) (do-test (bzspl:pos* (bzspl:make pts-a :closed t) (math:linspace 10 0d0 1d0)) (list (vec:vec -10.0d0 50.0d0) (vec:vec -2.098765432098766d0 18.000000000000004d0) (vec:vec 3.8271604938271597d0 9.111111111111114d0) (vec:vec 12.777777777777775d0 20.22222222222222d0) (vec:vec 36.9753086419753d0 43.728395061728385d0) (vec:vec 69.81481481481482d0 75.77777777777779d0) (vec:vec 68.33333333333334d0 95.33333333333331d0) (vec:vec 27.53086419753091d0 98.79012345679014d0) (vec:vec -5.061728395061721d0 83.97530864197533d0) (vec:vec -10.0d0 50.0d0))) (do-test (bzspl:pos* (bzspl:make pts-b :closed t) (math:linspace 10 0d0 1d0)) (list (vec:vec -10.0d0 50.0d0) (vec:vec 1.1111111111111107d0 10.666666666666668d0) (vec:vec 12.777777777777775d0 20.22222222222222d0) (vec:vec 55.0d0 60.0d0) (vec:vec 72.11111111111111d0 69.55555555555556d0) (vec:vec 20.055555555555546d0 10.166666666666655d0) (vec:vec -1.5d0 -6.5d0) (vec:vec -4.611111111111104d0 23.9444444444444d0) (vec:vec -14.444444444444443d0 72.44444444444443d0) (vec:vec -10.0d0 50.0d0))) (rnd:set-rnd-state 1) (do-test (let ((a (list))) (bzspl:with-rndpos ((bzspl:make pts-b :closed t) 5 v) (setf a (append a (list v)))) a) (list (vec:vec -10.08497035719275d0 51.90358188928061d0) (vec:vec 72.94161639142136d0 70.67347981875085d0) (vec:vec -9.972643319179285d0 49.866015920500494d0) (vec:vec 4.718551216740959d0 -4.763338116541952d0) (vec:vec 35.77978017789251d0 42.626750166588465d0))) (do-test (length (bzspl:adaptive-pos (bzspl:make pts-a))) 33) (do-test (bzspl:adaptive-pos (bzspl:make (list (vec:vec 0d0 0d0) (vec:vec 1d0 2d0) (vec:vec -3d0 5d0)))) (list (vec:vec 0.0d0 0.0d0) (vec:vec 0.1895973615640955d0 1.042776855565451d0) (vec:vec -0.14081675743371164d0 2.0569202817306174d0) (vec:vec -1.271394338241913d0 3.5211678214274826d0) (vec:vec -3.0d0 5.0d0))) (do-test (bzspl:adaptive-pos (bzspl:make (list (vec:vec 0d0 0d0) (vec:vec 1d0 2d0) (vec:vec -3d0 5d0)) :closed t)) (list (vec:vec 0.5d0 1.0d0) (vec:vec 0.5466485088794749d0 1.7520555605018526d0) (vec:vec -0.0768795322457066d0 2.70011988412611d0) (vec:vec -1.4086621517704143d0 3.78880784996485d0) (vec:vec -2.141365961440698d0 3.938894951364712d0) (vec:vec -1.7741792177500624d0 2.9768006077921783d0) (vec:vec -0.8206885873818279d0 1.4794187045941596d0) (vec:vec -0.07628486044613761d0 0.7674853325576549d0) (vec:vec 0.5d0 1.0d0))) (do-test (bzspl:len (bzspl:make pts-a)) 225.04969225489305d0) (do-test (bzspl:len (bzspl:make pts-a :closed t)) 275.0529848703631d0))) (defun test-hset () (let ((hs (hset:make))) (do-test (hset:add hs 1) t) (do-test (hset:add hs 1) nil) (do-test (hset:add hs 20) t) (do-test (hset:add hs 40) t) (do-test (hset:add hs 73) t) (do-test (hset:num hs) 4) (do-test (hset:del hs 1) t) (do-test (hset:del hs 1) nil) (do-test (hset:mem hs 40) t) (do-test (hset:mem* hs (list 40 88)) (list t nil)) (do-test (sort (hset:to-list hs) #'<) (list 20 40 73))) (let ((hs (hset:make :init (list 1 2 3)))) (do-test (hset:to-list hs) (list 1 2 3)))) (defun test-graph () (let ((grph (graph:make))) (do-test (graph:add grph 1 1) t) (do-test (graph:add grph 1 2) t) (do-test (graph:add grph 1 2) nil) (do-test (graph:add grph 2 1) nil) (do-test (graph:get-num-edges grph) 4) (do-test (graph:get-edges grph) '#((1 1) (1 2))) (do-test (graph:add grph 20 5) t) (do-test (graph:get-edges grph) '#((1 1) (1 2) (5 20))) (do-test (graph:del grph 1 2) t) (do-test (graph:del grph 1 2) nil) (do-test (graph:get-edges grph) '#((1 1) (5 20))) (do-test (graph:get-num-edges grph) 4) (do-test (graph:mem grph 1 4) nil) (do-test (graph:mem grph 1 1) t) (do-test (sort (graph:get-verts grph) #'<) '(1 5 20)) (do-test (graph:del grph 1 1) t) (do-test (graph:get-edges grph) '#((5 20))) (do-test (sort (graph:get-verts grph) #'<) '(5 20)) (do-test (graph:del grph 5 20) t) (do-test (sort (graph:get-verts grph) #'<) nil)) (let ((grph (graph:make :closed t))) (do-test (graph:get-loop grph) nil) (graph:add grph 1 0) (graph:add grph 1 2) (graph:add grph 2 0) (do-test (to-list (graph:get-loop grph)) (list 1 0 2)) (graph:add grph 2 9) (do-test (graph:get-loop grph) nil))) (defun test-linear-path () (rnd:set-rnd-state 1) (let ((apath (lin-path:make (rnd:nin-box 33 300d0 300d0)))) (do-test (lin-path:pos* apath (rnd:rndspace 20 0d0 1d0)) (list (vec:vec -9.438347648872167d0 -175.225149152222d0) (vec:vec 116.89881659438566d0 -26.809245714782996d0) (vec:vec -65.36161703283702d0 185.74828332183736d0) (vec:vec -105.48322687473d0 -9.890268437414548d0) (vec:vec 267.68539603378895d0 81.3043899209714d0) (vec:vec -132.40421434059442d0 195.15630286314308d0) (vec:vec -97.44930816032483d0 177.55858394044853d0) (vec:vec 266.5652538517507d0 -0.12485684153419593d0) (vec:vec 164.1995002008751d0 105.86496577929238d0) (vec:vec -26.728304107996706d0 -204.3541153362095d0) (vec:vec -177.47950464695646d0 150.76511064797404d0) (vec:vec 14.766557204046116d0 -93.04887526533449d0) (vec:vec 91.93635520751945d0 -108.1690462450528d0) (vec:vec 170.5374458058014d0 143.51512360627012d0) (vec:vec -104.24865074429103d0 64.19229247140761d0) (vec:vec 13.85574261994833d0 168.04649139453574d0) (vec:vec 90.01632000058807d0 -106.09734739384757d0) (vec:vec 33.09742525543997d0 -109.45542035126164d0) (vec:vec -190.2979189072196d0 196.3589224835634d0) (vec:vec 125.93727427384897d0 112.82256366840846d0))) (do-test (lin-path:pos* apath (rnd:rndspace 5 0d0 1d0)) (list (vec:vec -187.5705364827427d0 158.41359771733312d0) (vec:vec 187.35293276640311d0 -29.852529549097056d0) (vec:vec -5.522855469879147d0 -168.62858891534736d0) (vec:vec 55.13044208493619d0 156.21422990619857d0) (vec:vec 200.2368412092638d0 114.61642591669907d0)))) (let ((apath (lin-path:make (rnd:nin-box 12 300d0 300d0) :closed t))) (do-test (lin-path:pos* apath (rnd:rndspace 20 0d0 1d0)) (list (vec:vec 27.920854552669738d0 72.74990940914415d0) (vec:vec 20.347116016838214d0 60.03424910291827d0) (vec:vec 90.54515305308234d0 56.63138904522498d0) (vec:vec -25.3222203310782d0 -183.1677471273439d0) (vec:vec 211.41460164089594d0 295.28993948962716d0) (vec:vec -55.15685103609334d0 -219.1553983499264d0) (vec:vec 3.5116120355960163d0 -212.55092858244558d0) (vec:vec 22.934457423851427d0 -210.36444561614667d0) (vec:vec -16.230443414179007d0 -1.3763499500023784d0) (vec:vec -114.29745056967332d0 -38.66755954976239d0) (vec:vec 120.46277829407285d0 -199.3854150955505d0) (vec:vec 161.48480036064814d0 -188.4310964342001d0) (vec:vec -250.3371679969546d0 59.6286189885981d0) (vec:vec 211.5358543713892d0 296.19316067596804d0) (vec:vec 141.119808254249d0 262.8012870055113d0) (vec:vec 76.43639032666181d0 -34.81227407014987d0) (vec:vec -83.50672601072395d0 -3.0479216467079766d0) (vec:vec 84.97443810482987d0 -186.13693462985242d0) (vec:vec -66.5778671576494d0 -220.44109345321482d0) (vec:vec -3.2600089472467175d0 192.22456394293548d0))) (do-test (lin-path:pos* apath (rnd:rndspace 5 0d0 1d0)) (list (vec:vec -79.39852989264577d0 -107.43017344211452d0) (vec:vec -55.656453545073305d0 162.25392644684086d0) (vec:vec 96.08643196039844d0 -190.68148658414955d0) (vec:vec -87.73518977972896d0 -57.86025399494548d0) (vec:vec -11.885662338531773d0 5.918166490124946d0))) (do-test (lin-path:rndpos apath 5) (list (vec:vec 129.62232574809065d0 -187.47570071925472d0) (vec:vec 196.2965520484057d0 182.6743915136004d0) (vec:vec 95.34514262347875d0 -186.44790001400926d0) (vec:vec 201.75690539451068d0 272.4593392134565d0) (vec:vec 173.48377006092858d0 -193.41669665923908d0))))) (defun main () (test-title (test-utils)) (test-title (test-rnd)) (test-title (test-bzspl)) (test-title (test-hset)) (test-title (test-graph)) (test-title (test-linear-path)) (test-title (test-summary))) (main) <|start_filename|>src/pg-utils.lisp<|end_filename|> ; below code is from from On Lisp by <NAME>. ; http://ep.yimg.com/ty/cdn/paulgraham/onlisp.lisp ; This code is copyright 1993 by <NAME>, but anyone who wants ; to use the code in any nonprofit activity, or distribute free ; verbatim copies (including this notice), is encouraged to do so. (defmacro aif (test-form then-form &optional else-form) `(let ((it ,test-form)) (if it ,then-form ,else-form))) (defmacro awhen (test-form &body body) `(aif ,test-form (progn ,@body))) (defun flatten (x) (labels ((rec (x acc) (cond ((null x) acc) ((atom x) (cons x acc)) (t (rec (car x) (rec (cdr x) acc)))))) (rec x nil))) (defun group (source n) (if (zerop n) (error "zero length")) (labels ((rec (source acc) (let ((rest (nthcdr n source))) (if (consp rest) (rec rest (cons (subseq source 0 n) acc)) (nreverse (cons source acc)))))) (if source (rec source nil) nil))) (defun mkstr (&rest args) (with-output-to-string (s) (dolist (a args) (princ a s)))) (defun symb (&rest args) (values (intern (apply #'mkstr args)))) (defmacro with-gensyms (syms &body body) `(let ,(mapcar #'(lambda (s) `(,s (gensym))) syms) ,@body)) (defmacro mac (expr) `(pprint (macroexpand-1 ',expr))) (defmacro with-struct ((name . fields) struct &body body) (let ((gs (gensym))) `(let ((,gs ,struct)) (let ,(mapcar #'(lambda (f) `(,f (,(symb name f) ,gs))) fields) ,@body)))) (defmacro abbrev (short long) `(defmacro ,short (&rest args) `(,',long ,@ARGS))) <|start_filename|>examples/bzspl.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (defun init-snek (n m s xy) ; a group (grp) is a collection of edges. ; make m grps with n verts in each grp. (let ((snk (snek:make))) (mapcar (lambda (g) (snek:add-path! snk (math:rep (p (math:linspace n 0d0 1d0)) (vec:on-circ p 600d0 :xy xy)) :g g)) (math:nrep m (snek:add-grp! snk))) snk)) (defun get-walkers-state-gen (snk) (let ((walkers (make-hash-table :test #'equal))) ; iterate all verts in all grps (snek:itr-grps (snk g) (snek:itr-grp-verts (snk v :g g) ; associate a random 2d walker with this vert. ; these walkers have a randomly changing ; acceleration, which gives intersting behaviour (setf (gethash v walkers) (rnd:get-acc-circ-stp*)))) ; function that generates a move vert alteration based on the ; state of the corresponding walker (lambda (v noise) (snek:move-vert? v (funcall (gethash v walkers) noise))))) (defun main (size fn) (let ((itt 1000000) (noise 0.000000000007d0) (grains 10) (snk (init-snek 40 1 (half size) (vec:rep (* 0.5d0 size)))) (sand (sandpaint:make size :fg (pigment:white 0.05) :bg (pigment:dark)))) (let ((state-gen (get-walkers-state-gen snk))) (loop for i from 0 below itt do (print-every i 100000) (snek:with (snk) (snek:itr-grps (snk g) (snek:itr-grp-verts (snk v :g g) ; get an alteration for vert v (funcall state-gen v noise)))) ;(sandpaint:set-fg-color sand (pigment:hsv 0.51 1 1 0.05)) (snek:itr-grps (snk g :collect nil) ; draw random dots along the bezier spline. (sandpaint:bzspl-stroke sand (bzspl:make (snek:get-grp-verts snk :g g) :closed t) grains)))) (sandpaint:save sand fn :gamma 1.5))) (time (main 2000 (second (cmd-args)))) <|start_filename|>utils/grid.lisp<|end_filename|> (defun get-grid (size edge ngrid) (loop for x of-type double-float in (math:linspace ngrid edge (- size edge)) collect (loop for y of-type double-float in (math:linspace ngrid edge (- size edge)) collect (vec:vec x y)))) (defun get-grid* (sx sy numx numy) (loop for x of-type double-float in (math:linspace numx (first sx) (second sx)) collect (loop for y in (math:linspace numy (first sy) (second sy)) collect (vec:vec x y)))) (defun get-rnd-grid (size edge ngrid) (let ((a (- edge)) (b (+ size edge))) (loop for x of-type double-float in (rnd:rndspace ngrid a b :order t) collect (loop for y of-type double-float in (rnd:rndspace ngrid a b :order t) collect (vec:vec x y))))) (defun get-stroke-grid (n m rad angle v w) (loop for i of-type double-float in (math:linspace n 0d0 1d0) collect (let* ((ivw (vec:on-line i v w)) (p (vec:add ivw (vec:scale (vec:cos-sin angle) rad)))) (loop for ip of-type double-float in (math:linspace m 0d0 1d0) collect (vec:on-line ip ivw p))))) (defun get-v-grid (xy width height nums) (let ((inside (make-adjustable-vector)) (outside (make-adjustable-vector)) (all (make-adjustable-vector))) (vec:with-xy (xy x y) (loop for b of-type double-float in (math:linspace (first nums) (- y height) (+ y height)) and bi of-type fixnum from 0 do (loop for a of-type double-float in (math:linspace (second nums) (- x width) (+ x width)) and ai of-type fixnum from 0 do (vextend (vec:vec a b) all) (if (or (< ai 1) (> ai (- (second nums) 2))) (vextend (vec:vec a b) outside) (vextend (vec:vec a b) inside))))) (values all inside outside))) <|start_filename|>examples/cells.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (load "../utils/force") (defun init-snek (n m size xy) (let ((snk (snek:make :max-verts 5000))) (mapcar (lambda (g) (let ((mid (rnd:in-circ (* 0.5d0 (- size 200d0)) :xy xy))) (snek:add-path! snk (math:rep (p (math:linspace n 0d0 1d0 :end nil)) (vec:on-circ p 20d0 :xy mid)) :g g :closed t))) (math:nrep m (snek:add-grp! snk))) snk)) (defun main (size fn) (let ((itt 1000) (grains 30) (snk (init-snek 5 800 size (vec:rep (* 0.5d0 size)))) (sand (sandpaint:make size :fg (pigment:white 0.05) :bg (pigment:dark)))) (loop for i from 0 below itt do (print-every i 100) (snek:with (snk :zwidth 60.0d0) (snek:itr-verts (snk v) (map 'list (lambda (w) (force? snk v w -0.05)) (snek:verts-in-rad snk (snek:get-vert snk v) 60.0d0)) ;(snek:with-verts-in-rad (snk (snek:get-vert snk v) 60d0 w) ; (cons)) ) (snek:itr-grps (snk g) (snek:itr-edges (snk e :g g) (force? snk (first e) (second e) 0.1)))) (snek:itr-grps (snk g :collect nil) (sandpaint:bzspl-stroke sand (bzspl:make (snek:get-grp-verts snk :g g) :closed t) grains))) (sandpaint:save sand fn :gamma 1.5))) (time (main 1000 (second (cmd-args)))) <|start_filename|>src/obj.lisp<|end_filename|> (in-package :obj) (defstruct obj (verts nil :type vector :read-only t) (faces nil :type vector :read-only t) (lines nil :type vector :read-only t) (num-verts 0 :type fixnum :read-only nil) (num-lines 0 :type fixnum :read-only nil) (num-faces 0 :type fixnum :read-only nil)) (defun make () (make-obj :verts (make-adjustable-vector) :lines (make-adjustable-vector) :faces (make-adjustable-vector))) (defun add-verts-from-vec (o new &optional (z 0d0)) (declare (obj o) (list new) (double-float z)) (with-struct (obj- verts) o (setf (obj-num-verts o) (incf (obj-num-verts o) (length new))) (loop with n = (length verts) for v in new and i from n do (vextend (list (vec::vec-x v) (vec::vec-y v) z) verts) collect i))) (defun add-face (o new) (declare (obj o) (list new)) (with-struct (obj- faces) o (setf (obj-num-faces o) (incf (obj-num-faces o))) (vextend new faces))) (defun add-line (o new) (declare (obj o) (list new)) (with-struct (obj- lines) o (setf (obj-num-lines o) (incf (obj-num-lines o))) (vextend new lines))) (defun save (o fn &key (mesh-name "mesh")) (declare (obj o)) (with-struct (obj- verts faces lines) o (with-open-file (fstream (ensure-filename fn ".obj") :direction :output :if-exists :supersede) (declare (stream fstream)) (format fstream "o ~a~%" mesh-name) (loop for ll of-type list across verts do (destructuring-bind (x y z) ll (declare (double-float x y z)) (format fstream "v ~f ~f ~f~%" x y z))) (loop for ee of-type list across faces do (destructuring-bind (a b c) (math:add ee '(1 1 1)) (declare (fixnum a b c)) (format fstream "f ~d ~d ~d~%" a b c))) (loop for ll of-type list across lines do (format fstream "l") (loop for l of-type fixnum in (math:add ll '(1 1 1)) do (format fstream " ~d" l)) (format fstream "~%"))))) <|start_filename|>src/sandpaint.lisp<|end_filename|> (in-package :sandpaint) (declaim (optimize (speed 3))) (defmacro -inside-round ((size xy x y) &body body) (declare (symbol x y)) (with-gensyms (sname) `(let ((,sname ,size)) (declare (fixnum ,sname)) (multiple-value-bind (,x ,y) (vec::-vround* ,xy) (declare (fixnum ,x ,y)) (when (and (< -1 ,x ,sname) (< -1 ,y ,sname)) (progn ,@body)))))) (defmacro -inside-floor ((size xy x y) &body body) (declare (symbol x y)) (with-gensyms (sname) `(let ((,sname ,size)) (declare (fixnum ,sname)) (multiple-value-bind (,x ,y) (vec::-vfloor* ,xy) (declare (fixnum ,x ,y)) (when (and (< -1 ,x ,sname) (< -1 ,y ,sname)) (progn ,@body)))))) (defmacro -square-loop ((x y n) &body body) (declare (symbol x y)) (with-gensyms (nname) `(let ((,nname ,n)) (loop for ,y of-type fixnum from 0 below ,nname do (loop for ,x of-type fixnum from 0 below ,nname do (progn ,@body)))))) (defmacro -do-op ((sand size vals indfx &key name) &body body) (declare (symbol sand size vals indfx)) (with-gensyms (sname) `(let* ((,sname ,sand) (,size (sandpaint-size ,sname)) (,vals (sandpaint-vals ,sname)) (,indfx (sandpaint-indfx ,sname))) (declare (type (simple-array double-float) ,vals) (function ,indfx) (fixnum ,size)) ,(when name `(format t "applying:~a...~%" ,name)) (progn ,@body) ,(when name `(format t "done.~%"))))) (defmacro -do-op* ((sand size vals indfx) &body body) (declare (symbol sand size vals indfx)) (with-gensyms (sname) `(let* ((,sname ,sand) (,size (sandpaint-size ,sname)) (,vals (sandpaint-vals ,sname)) (,indfx (sandpaint-indfx ,sname))) (declare (type (simple-array double-float) ,vals) (function ,indfx) (fixnum ,size)) (progn ,@body)))) (defun get-ind-fx (size) (declare (fixnum size)) (lambda (x y &optional (c 0)) (declare (optimize (safety 0) speed (debug 0)) (fixnum x y c)) (+ c (the fixnum (* 4 (the fixnum (+ x (the fixnum (* size y))))))))) (defstruct sandpaint (size nil :type fixnum :read-only t) (vals nil :type (simple-array double-float) :read-only t) (fg nil :type pigment:rgba :read-only nil) (bg nil :type pigment:rgba :read-only nil) (indfx nil :type function :read-only t)) (defun make-rgba-array (size &key (init 0d0)) (declare (fixnum size)) (make-array (* size size 4) :adjustable nil :initial-element init :element-type 'double-float)) (defun -rgb-from (vals ind &optional (a 1d0)) (declare (optimize (safety 0) speed (debug 0)) (fixnum ind) (type (simple-array double-float (*)) vals)) (pigment:rgb (aref vals ind) (aref vals (1+ ind)) (aref vals (+ ind 2)) a)) (defun sample (sand xy &key (alpha 1d0)) (-do-op* (sand size vals indfx) (-inside-floor (size xy x y) (let* ((ind (funcall indfx x y)) (a (aref vals (+ ind 3)))) (pigment:rgb (/ (aref vals ind) a) (/ (aref vals (1+ ind)) a) (/ (aref vals (+ ind 2)) a) alpha))))) (defun get-size (sand) (sandpaint-size sand)) (declaim (inline -scale-convert)) (defun -scale-convert (v &key (s 1d0) (gamma 1d0)) (declare (double-float s gamma)) (setf v (expt (max 0d0 (/ v s)) gamma))) (declaim (inline -operator-over)) (defun -operator-over (indfx vals x y fg) (declare (optimize (safety 0) speed (debug 0)) (function indfx) (type (simple-array double-float (*)) vals) (fixnum x y) (pigment:rgba fg)) (pigment:with (fg r g b a) (let ((ind (funcall indfx x y)) (ia (- 1d0 a))) (declare (fixnum ind) (double-float ia)) (setf (aref vals ind) (the double-float (+ (the double-float (* (the double-float (aref vals ind)) ia)) r)) (aref vals (+ ind 1)) (the double-float (+ (the double-float (* (the double-float (aref vals (+ ind 1))) ia)) g)) (aref vals (+ ind 2)) (the double-float (+ (the double-float (* (the double-float (aref vals (+ ind 2))) ia)) b)) (aref vals (+ ind 3)) (the double-float (+ (the double-float (* (the double-float (aref vals (+ ind 3))) ia)) a)))))) (defun -draw-stroke (indfx vals size grains v1 v2 fg) (declare (function indfx) (type (simple-array double-float) vals) (fixnum size grains) (pigment:rgba fg)) (rnd:with-on-line (grains v1 v2 rn) (-inside-round (size rn x y) (-operator-over indfx vals x y fg)))) (defun -draw-stroke-overlap (indfx vals size grains v1 v2 fg) (declare (function indfx) (type (simple-array double-float) vals) (fixnum size grains) (pigment:rgba fg)) (rnd:with-on-line (grains v1 v2 pt) (-pix-overlap indfx vals size pt fg))) (defun -draw-dens-stroke (indfx vals size dens v1 v2 fg) (declare (function indfx) (type (simple-array double-float) vals) (fixnum size) (double-float dens) (pigment:rgba fg)) (rnd:with-on-line ((ceiling (* dens (vec:dst v1 v2))) v1 v2 rn) (-inside-round (size rn x y) (-operator-over indfx vals x y fg)))) (defun -draw-circ (indfx vals size xy rad grains fg) (declare (function indfx) (type (simple-array double-float) vals) (fixnum size grains) (double-float rad) (pigment:rgba fg)) (rnd:with-in-circ (grains rad p :xy xy) (-inside-round (size p x y) (-operator-over indfx vals x y fg)))) (declaim (inline -u8) (ftype (function (double-float) fixnum) -u8)) (defun -u8 (v) (declare (optimize (safety 0) speed (debug 0)) (double-float v)) (cond ((> v 1d0) 255) ((< v 0d0) 0) (t (floor (the float (* 255 v)))))) (declaim (inline -ui8) (ftype (function (fixnum) double-float) -ui8)) (defun -ui8 (v) (declare (optimize (safety 0) speed (debug 0)) (fixnum v)) (cond ((>= v 255) 1d0) ((< v 0) 0d0) (t (/ (math:dfloat v) 255d0)))) (declaim (inline -u16) (ftype (function (double-float) fixnum) -u16)) (defun -u16 (v) (declare (optimize (safety 0) speed (debug 0)) (double-float v)) (cond ((> v 1d0) 65535) ((< v 0d0) 0) (t (floor (the float (* 65535d0 v)))))) (declaim (inline -png-vals)) (defun -png-vals (indfx vals x y g bitfx) (declare (function indfx bitfx) (type (simple-array double-float) vals) (fixnum x y) (double-float g)) (let* ((ind (funcall indfx x y)) (a (aref vals (+ 3 ind)))) (declare (double-float a) (fixnum ind)) (if (> a 0d0) (values (funcall bitfx (-scale-convert (aref vals (+ ind 0)) :s a :gamma g)) (funcall bitfx (-scale-convert (aref vals (+ ind 1)) :s a :gamma g)) (funcall bitfx (-scale-convert (aref vals (+ ind 2)) :s a :gamma g)) (funcall bitfx (-scale-convert a :gamma g))) (values 0 0 0 0)))) (defun clear (sand &optional c) (declare (sandpaint sand)) (pigment:with ((if c c (sandpaint-bg sand)) r g b a) (-do-op (sand size vals indfx) (-square-loop (x y size) (let ((ind (funcall indfx x y))) (declare (fixnum ind)) (setf (aref vals ind) r (aref vals (+ ind 1)) g (aref vals (+ ind 2)) b (aref vals (+ ind 3)) a)))))) (defun make (size &key (fg (pigment:rgb 0.0d0 0.0d0 0.0d0)) (bg (pigment:rgb 1.0d0 1.0d0 1.0d0))) (pigment:with (bg r g b a) (let ((vals (make-rgba-array size)) (indfx (get-ind-fx size))) (declare (function indfx)) (-square-loop (x y size) (let ((ind (funcall indfx x y))) (declare (fixnum ind)) (setf (aref vals ind) r (aref vals (+ ind 1)) g (aref vals (+ ind 2)) b (aref vals (+ ind 3)) a))) (make-sandpaint :size size :fg fg :bg bg :vals vals :indfx indfx)))) (defun set-fg-color (sand c) (declare (pigment:rgba c)) (setf (sandpaint-fg sand) c)) (defun set-bg-color (sand c) (declare (pigment:rgba c)) (setf (sandpaint-bg sand) c)) (defun pix (sand vv) (declare (list vv)) (-do-op (sand size vals indfx) (loop with fg = (sandpaint-fg sand) for v of-type vec:vec in vv do (-inside-round (size v x y) (-operator-over indfx vals x y fg))))) (defun arr-pix (sand vv n) (declare (fixnum n)) (-do-op (sand size vals indfx) (loop with fg = (sandpaint-fg sand) for i of-type fixnum from 0 below n do (-inside-round (size (vec:sarr-get vv i) x y) (-operator-over indfx vals x y fg))))) (declaim (inline -floor-fract) (ftype (function (vec:vec) (values fixnum fixnum double-float double-float)) -floor-fract)) (defun -floor-fract (pt) (declare (optimize (safety 0) speed (debug 0)) (vec:vec pt)) (vec:with-xy (pt x y) (multiple-value-bind (ix fx) (floor x) (declare (fixnum ix) (double-float fx)) (multiple-value-bind (iy fy) (floor y) (declare (fixnum iy) (double-float fy)) (values ix iy fx fy))))) (declaim (inline -fract-overlap) (ftype (function (double-float double-float) (values double-float double-float double-float double-float)) -fract-overlap)) (defun -fract-overlap (x y) (declare (optimize (safety 0) speed (debug 0)) (double-float x y)) (let ((x2 (- 1 x)) (y2 (- 1 y))) (declare (double-float x2 y2)) (values (* x2 y2) (* x y2) (* x2 y) (* x y)))) ;suggested by ;https://twitter.com/porglezomp/status/1014612499315003392 (defun -pix-overlap (indfx vals size pt fg) (declare (type (simple-array double-float) vals) (fixnum size) (function indfx) (vec:vec pt) (pigment:rgba fg)) (pigment:with (fg r g b a) (labels ((-operator-over-overlap (ix iy s) (declare (optimize (safety 0) speed (debug 0)) (fixnum ix iy) (double-float s)) (when (and (< -1 ix size) (< -1 iy size)) (-operator-over indfx vals ix iy (pigment::-make-rgba :r (* s r) :g (* s g) :b (* s b) :a (* s a)))))) (multiple-value-bind (ix iy fx fy) (-floor-fract pt) (multiple-value-bind (s1 s2 s3 s4) (-fract-overlap fx fy) (declare (double-float s1 s2 s3 s4)) (-operator-over-overlap ix iy s1) (-operator-over-overlap #1=(+ ix 1) iy s2) (-operator-over-overlap ix #2=(+ iy 1) s3) (-operator-over-overlap #1# #2# s4)))))) (defun pix-overlap (sand pts) (declare (sandpaint sand) (list pts)) (-do-op (sand size vals indfx) (loop with fg = (sandpaint-fg sand) for pt of-type vec:vec in pts do (-pix-overlap indfx vals size pt fg)))) (defun pix-overlap* (sand pt) (declare (sandpaint sand) (vec:vec pt)) (-do-op (sand size vals indfx) (-pix-overlap indfx vals size pt (sandpaint-fg sand)))) (defun circ (sand vv rad n) (declare (list vv) (double-float rad) (fixnum n)) (-do-op (sand size vals indfx) (loop with fg = (sandpaint-fg sand) for v of-type vec:vec in vv do (-draw-circ indfx vals size v rad n fg)))) (defun bzspl-stroke (sand bz n) (declare (fixnum n)) (-do-op (sand size vals indfx) (let ((fg (sandpaint-fg sand))) (bzspl:with-rndpos (bz n v) (-inside-round (size v x y) (-operator-over indfx vals x y fg)))))) (defun arr-circ (sand vv num rad grains) (declare (type (simple-array double-float) vv) (fixnum grains num) (double-float rad)) (-do-op (sand size vals indfx) (loop with fg = (sandpaint-fg sand) for i of-type fixnum from 0 below num do (-draw-circ indfx vals size (vec:sarr-get vv i) rad grains fg)))) (defun strokes (sand lines grains) (declare (fixnum grains) (list lines)) (-do-op (sand size vals indfx) (loop with fg = (sandpaint-fg sand) for (u v) in lines do (-draw-stroke indfx vals size grains u v fg)))) (defun stroke (sand line grains &key overlap) (declare (fixnum grains) (list line)) (-do-op (sand size vals indfx) (destructuring-bind (u v) line (if overlap (-draw-stroke-overlap indfx vals size grains u v (sandpaint-fg sand)) (-draw-stroke indfx vals size grains u v (sandpaint-fg sand)))))) (defun dens-stroke (sand line &optional (dens 1d0)) (declare (double-float dens) (list line)) (-do-op (sand size vals indfx) (destructuring-bind (u v) line (-draw-dens-stroke indfx vals size dens u v (sandpaint-fg sand))))) (defun lin-path (sand path rad grains &key (dens 1d0)) (declare (double-float rad dens) (fixnum grains)) (-do-op (sand size vals indfx) (loop with fg = (sandpaint-fg sand) for u of-type vec:vec in path and w of-type vec:vec in (cdr path) do (math:with-linspace ((* (vec:dst u w) dens) 0d0 1d0 p :end nil) (-draw-circ indfx vals size (vec:on-line p u w) rad grains fg))))) (defun -save8 (sand fn &key gamma) " save as 8 bits. supports alpha. " (-do-op (sand size vals indfx) (let ((png (make-instance 'zpng::pixel-streamed-png :color-type :truecolor-alpha :width size :height size))) (with-open-file (fstream (ensure-filename fn ".png") :direction :output :if-exists :supersede :if-does-not-exist :create :element-type '(unsigned-byte 8)) (declare (stream fstream)) (zpng:start-png png fstream) (-square-loop (x y size) (multiple-value-bind (r g b a) (-png-vals indfx vals x y gamma #'-u8) (declare (fixnum r g b)) (zpng:write-pixel (list r g b a) png))) (zpng:finish-png png))))) (defun -save16 (sand fn &key gamma) " save as 16 bits. does not support alpha. " (-do-op (sand size vals indfx) (let ((img (png:make-image size ;width size ;height 3 16))) (-square-loop (x y size) (multiple-value-bind (r g b) (-png-vals indfx vals x y gamma #'-u16) (declare (fixnum r g b)) (setf (aref img y x 0) r (aref img y x 1) g (aref img y x 2) b))) (with-open-file (output (ensure-filename fn ".png") :element-type '(unsigned-byte 8) :direction :output :if-exists :supersede) (png:encode img output))))) (defun save (sand fn &key (gamma 1d0) (bits 8) &aux (gamma* (math:dfloat gamma))) (declare (sandpaint sand) (fixnum bits)) (case bits (8 (-save8 sand fn :gamma gamma*)) (16 (-save16 sand fn :gamma gamma*)) (otherwise (error "bits must be 8 or 16. default is 8.")))) (defun -init-rgb-from-png (indfx vals img s) (loop for i from 0 below s do (loop for j from 0 below s do (setf (aref vals (funcall indfx j i 0)) (-ui8 (aref img i j 0)) (aref vals (funcall indfx j i 1)) (-ui8 (aref img i j 1)) (aref vals (funcall indfx j i 2)) (-ui8 (aref img i j 2)) (aref vals (funcall indfx j i 3)) 1d0)))) ; TODO: indexed/grayscale channel only (defun png-open (fn) "read a png image." (let ((img (with-open-file (input fn :element-type '(unsigned-byte 8)) (png:decode input)))) (destructuring-bind (h w c) (array-dimensions img) (declare (ignore c)) (when (not (= h w)) (error "can only load square images")) (let ((sand (make h))) (-init-rgb-from-png (sandpaint-indfx sand) (sandpaint-vals sand) img h) sand)))) <|start_filename|>examples/hyphae.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") ; TODO: where does this go? (defmacro inside-border ((size xy b) &body body) (with-gensyms (xyname sname small large) `(let* ((,xyname ,xy) (,sname ,size) (,small ,b) (,large (- ,sname ,small))) (if (and (>= (vec::vec-x ,xyname) ,small) (< (vec::vec-x ,xyname) ,large) (>= (vec::vec-y ,xyname) ,small) (< (vec::vec-y ,xyname) ,large)) (progn ,@body))))) (defun hyphae (sand size fn itt rad mid) (let ((curr (make-hash-table :test #'equal)) (hits 0)) (labels ((init (snk n) (loop for i from 0 below n do (setf (gethash (snek:add-vert! snk (rnd:in-box 250d0 250d0 :xy (vec:vec 250d0 250d0))) curr) 0))) (draw (snk a w) (sandpaint:set-fg-color sand (pigment:rgb 0.0 0.7 0.7 0.1)) (sandpaint:circ sand (list (snek::append-edge-alt-xy a)) 4d0 300) (sandpaint:set-fg-color sand (pigment:black 0.1)) (sandpaint:lin-path sand (snek:get-verts snk (list w (snek::append-edge-alt-v a))) 2d0 50)) (count-control (v) (multiple-value-bind (c exists) (gethash v curr) (when exists (if (> c 20) (print (remhash v curr)) (incf (gethash v curr)))))) (do-append-edge-alt* (snk a) (let ((v (snek::append-edge-alt-v a))) (count-control v) (inside-border (size (snek::append-edge-alt-xy a) 10) (if (<= (length (snek:verts-in-rad snk (snek::append-edge-alt-xy a) rad)) 1) (aif (snek::do-append-edge-alt snk a) (progn (incf hits) (setf (gethash it curr) 0) (draw snk a it)))))))) (let ((snk (snek:make :max-verts itt :alts `((snek::append-edge-alt ,#'do-append-edge-alt*))))) (init snk 20) (loop for i from 0 below itt do (snek:with (snk :zwidth rad) (loop for k being the hash-keys in curr collect (snek:append-edge? k (vec:add (snek:get-vert snk k) (rnd:in-circ rad)) :rel nil)) (sandpaint:save sand (append-number fn hits)))))))) (defun main (size fn) (let ((sand (sandpaint:make size :fg (pigment:black 0.01) :bg (pigment:white)))) (hyphae sand size fn 1000 10.0d0 (vec:vec 250d0 250d0)))) (time (main 500 (second (cmd-args)))) <|start_filename|>src/rnd.lisp<|end_filename|> (in-package :rnd) (defconstant PII (* PI 2d0)) (declaim (type double-float PII)) (declaim (optimize (speed 3))) ;(declaim (optimize (safety 0))) ; MACROS (defmacro -nrep (n &body body) (with-gensyms (nname) `(let ((,nname ,n)) (loop repeat ,nname collect (progn ,@body))))) ; TODO: deprecated (defmacro with-prob (p &body body) " executes body with probability p. " (with-gensyms (pname) `(let ((,pname ,p)) (when (< (random 1d0) ,p) (list ,@body))))) (defmacro prob (p a &optional b) " executes body with probability p. " `(if (< (rnd) ,p) ,a ,b)) (defmacro either (a b) " excecutes either a or b with a probablility of 0.5 " `(prob 0.5d0 ,a ,b)) (defmacro rcond (&rest clauses) " executes the forms in clauses according to the weighted sum of all p1, p2 ... clauses should be on this form: ((p1 form) (p2 form)) " (with-gensyms (val) (let* ((tot 0d0) (clauses* (loop for (prob . body) in clauses do (incf tot (coerce prob 'double-float)) collect `((< ,val ,tot) ,@body)))) `(let ((,val (rnd ,tot))) (cond ,@clauses*))))) (defmacro rep (n &body body) " repeat body at most n-1 times " `(loop repeat (rndi ,n) do (progn ,@body))) (defmacro rep* (a b &body body) " repeat body between [a b) times. " `(loop repeat (rndi ,a ,b) do (progn ,@body))) (defmacro with-rndspace ((n a b rn &key collect) &body body) " repeat body where rn is n numbers between (a b) " (declare (symbol rn)) (with-gensyms (a* b* d) `(destructuring-bind (,a* ,b*) (sort (list (coerce ,a 'double-float) (coerce ,b 'double-float)) #'<) (let ((,d (- ,b* ,a*))) (loop repeat ,n ,(if collect 'collect 'do) (let ((,rn (+ ,a* (random ,d)))) (declare (double-float ,rn)) (progn ,@body))))))) (declaim (ftype (function (&optional double-float) double-float) rnd rnd*)) (declaim (ftype (function (double-float double-float) double-float) rndbtwn)) (declaim (ftype (function (fixnum &optional fixnum) fixnum) rndi)) (defun set-rnd-state (i) (declare (fixnum i)) (if (or #+SBCL t nil) (setf *random-state* (sb-ext:seed-random-state i)) (warn "rnd:state is only implemented for SBCL. see src/rnd.lisp to implement state for your environment."))) (defun make-rnd-state () (setf *random-state* (make-random-state t))) (defun -inc (x stp) (mod (+ x stp) 1d0)) ; GENERIC (defun rndget (l) (if (eql (type-of l) 'cons) (nth (random (length l)) l) (aref l (random (length l))))) (defun probsel (p a &aux (a* (ensure-vector a))) (declare (double-float p)) (loop with res = (make-adjustable-vector) for i across a* do (prob p (vextend i res)) finally (return res))) ; NUMBERS AND RANGES ; TODO: deprecate optional arg (defun rndi (a &optional b &aux (b* (if b (the fixnum b) 0))) (declare (fixnum a b*)) (if (not b) (random a) (+ a (the fixnum (random (the fixnum (- b* a))))))) (defun nrndi (n a &optional b) (declare (fixnum n a)) (loop repeat n collect (rndi a b))) (defun rndi* (ab) (declare (list ab)) (destructuring-bind (a b) ab (declare (fixnum a b)) (+ a (random (- b a))))) (defun nrndi* (n a) (declare (fixnum n a)) (loop repeat n collect (rndi a))) (defun rnd (&optional (x 1d0)) (declare (double-float x)) (random x)) (defun nrnd (n &optional (x 1d0)) (declare (fixnum n) (double-float x)) (loop repeat n collect (rnd x))) ; TODO: nnorm, with-norm (defun norm (&key (mu 0d0) (sigma 1d0)) " box-muller transform " (declare (double-float mu sigma)) (let ((s (* sigma (sqrt (* -2d0 (log (rnd)))))) (u (* PII (rnd)))) (declare (double-float s u)) (values (+ mu (* s (cos u))) (+ mu (* s (sin u)))))) (defun rndbtwn (a b) (declare (double-float a b)) (+ a (random (- b a)))) (defun nrndbtwn (n a b) (declare (fixnum n) (double-float a b)) (loop for i from 0 below n collect (rndbtwn a b))) (defun rnd* (&optional (x 1d0)) (declare (double-float x)) (- x (* 2d0 (random x)))) (defun nrnd* (n &optional (x 1d0)) (declare (fixnum n) (double-float x)) (loop repeat n collect (rnd* x))) (defun rndspace (n a b &key order) (declare (fixnum n) (double-float a b)) (destructuring-bind (a b) (sort (list a b) #'<) (declare (double-float a b)) (let ((d (- b a))) (declare (double-float d)) (let ((res (-nrep n (+ a (random d))))) (if order (sort res #'<) res))))) (defun rndspacei (n a b &key order) (declare (fixnum n a b)) (destructuring-bind (a b) (sort (list a b) #'<) (declare (fixnum a b)) (let ((d (- b a))) (declare (fixnum d)) (let ((res (-nrep n (+ a (random d))))) (if order (sort res #'<) res))))) (defun bernoulli (n p) (declare (fixnum n) (double-float p)) (loop repeat n collect (if (< (rnd:rnd) p) 1d0 0d0))) <|start_filename|>utils/box-extrude.lisp<|end_filename|> (defun get-extrude (n) (rnd:rndi n)) (defun do-extrude (n a) (let ((res (make-adjustable-vector))) (loop for i from 0 while (<= i a) do (vextend i res)) (vextend (list a (mod (1+ a) n)) res) (loop for i from (1+ a) while (<= i n) do (vextend (mod i n) res)) res)) (defun normal-offset (av bv o) (vec:ladd* (list av bv) (vec:scale (vec:cos-sin (- (vec:angle (vec:sub bv av)) (* PI 0.5d0))) o))) (defun rot-offset (av bv o) (let* ((m (vec:mid av bv)) (d (vec:sub bv av)) (pt (vec:add m (vec:scale (vec:cos-sin (- (vec:angle d) (* PI 0.5d0))) o))) (rot (vec:scale (vec:rot d (rnd:rnd 0.5d0)) 0.5d0))) (list (vec:sub pt rot) (vec:add pt rot)))) (defun get-offsets (pts ab offset) (destructuring-bind (a b) ab (let ((av (aref pts a)) (bv (aref pts b))) (rnd:prob 0.5 (rot-offset av bv offset) (normal-offset av bv (* offset 0.8d0)))))) (defun -ind-to-pts (pts inds offset) (let ((offset* nil)) (values (to-vector (flatten (loop for i across inds collect (if (eql (type-of i) 'cons) (setf offset* (get-offsets pts i offset)) (aref pts i))))) offset*))) (defun extrude (pts offset &key fxn &aux (n (1- (length pts)))) (let* ((ind (get-extrude n)) (extruded (do-extrude n ind))) (multiple-value-bind (res extruded-pts) (-ind-to-pts pts extruded offset) (when fxn (funcall fxn pts ind extruded-pts)) res))) <|start_filename|>examples/forces.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (load "../utils/force") (defun main (size fn) (let ((mid (half size)) (itt 500) (snk (snek:make)) (grains 100) (rad 1d0) (sand (sandpaint:make size :fg (pigment:white 0.024) :bg (pigment:vdark)))) (math:nrep 3000 (snek:add-vert! snk (rnd:on-line (vec:vec 200d0 200d0) (vec:vec 800d0 800d0)))) (math:nrep 3000 (snek:add-vert! snk (rnd:on-line (vec:vec 800d0 200d0) (vec:vec 200d0 800d0)))) (loop for k from 1 to itt do (print-every k 100) (snek:with (snk :zwidth 10.0d0) (snek:itr-verts (snk v) (snek:move-vert? v (rnd:in-circ 1d0)) (map 'list (lambda (u) (force? snk u v -0.1d0)) (snek:verts-in-rad snk (snek:get-vert snk v) 10.0d0))))) (snek:draw-circ snk sand rad grains) (sandpaint:pixel-hack sand) (sandpaint:save sand fn :gamma 1.3))) (time (main 1000 (second (cmd-args)))) <|start_filename|>examples/step.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (defun main (size fn) (let ((sand (sandpaint:make size :fg (pigment:black 0.01) :bg (pigment:white))) (path-a (close-path (rnd:nin-box 10 500d0 500d0 :xy (vec:vec 500d0 500d0)))) (path-b (close-path (rnd:nin-box 4 500d0 500d0 :xy (vec:vec 500d0 500d0)))) (na (rnd:get-lin-stp)) (nb (rnd:get-lin-stp)) (pa (random 1.0d0)) (pb (random 1.0d0)) (noise 0.000000001d0)) (let ((fa (bzspl:make path-a)) (fb (bzspl:make path-b))) (loop for i from 0 to 1000000 do (print-every i 10000) (setf pa (math:inc pa (funcall na noise))) (setf pb (math:inc pb (funcall nb noise))) (let ((a (bzspl:pos fa pa)) (b (bzspl:pos fb pb))) (sandpaint:strokes sand (list (list a b)) 20)))) ;(sandpaint:chromatic-aberration sand (list 500 500) :s 200.0) (sandpaint:save sand fn))) (time (main 1000 (second (cmd-args)))) <|start_filename|>examples/bryozoa.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (load "../utils/state") (defun roll-once (aa) (butlast (append (last aa) aa) 1)) (defun init-vertical (n size xy border) (let ((snk (snek:make :max-verts (* n n)))) (loop for x in (math:linspace n border (- size border)) collect (snek:add-path! snk (math:rep (y (math:linspace n border (- size border))) (vec:vec x y)) :g (snek:add-grp! snk))) snk)) (defun init-fan (n size xy) (let ((snk (snek:make :max-verts (* n n)))) (loop for a in (math:linspace n pi (* 2d0 pi)) collect (snek:add-path! snk (math:rep (rad (math:linspace n 0d0 size)) (vec:add (vec:scale (vec:cos-sin a) rad) xy)) :g (snek:add-grp! snk))) snk)) ;(defun init-spiral (snum n rad xy) ; (let ((snk (snek:make :max-verts (* snum n)))) ; (loop for rot in (math:linspace snum 0d0 (* 2d0 pi) :end nil) collect ; (snek:add-path! snk (math:rep (p (math:linspace n 0d0 10d0)) ; (vec:on-spiral p rad :rot rot :xy xy)) ; :g (snek:add-grp! snk))) ; snk)) (defun main (size fn) (let ((itt 4000) ;(hgrains 15) (vgrains 10) (vnoise 0.0000001d0) (hnoise 0.000001d0) (dens 0.25d0) ;(snk (init-vertical 20 (math:dfloat size) (vec:vec (* 0.5d0 size) ; (math:dfloat (- size 100d0))) ; 100d0)) (snk (init-fan 40 1400d0 (vec:vec 500d0 1300d0))) ;(snk (init-spiral 20 20 800d0 (vec:vec 500d0 500d0))) (v-state-gen (get-walker-state-gen (lambda () (rnd:get-acc-circ-stp*)))) (h-state-gen (get-walker-state-gen (lambda () (rnd:get-acc-lin-stp (rnd:rnd))))) (sand (sandpaint:make size :fg (pigment:white 0.01) :bg (pigment:black)))) (snek:with (snk) (snek:itr-verts (snk v) (snek:move-vert? v (rnd:in-circ 9d0)))) (let ((grps (snek:get-all-grps snk))) (loop for i from 0 below itt do (print-every i 100) (snek:with (snk) (snek:itr-verts (snk v) (snek:move-vert? v (funcall v-state-gen v vnoise)) (snek:move-vert? v (rnd:in-circ 0.07d0)))) (loop for ga in grps and gb in (cdr grps) do (loop for p in (math:range 0 45) do (let ((m (funcall h-state-gen (list ga gb p) hnoise)) (bza (snek:get-grp-as-bzspl snk ga)) (bzb (snek:get-grp-as-bzspl snk gb))) (sandpaint:dens-stroke sand (list (bzspl:pos bza m) (bzspl:pos bzb m)) dens ) (sandpaint:bzspl-stroke sand bza vgrains) (sandpaint:bzspl-stroke sand bzb vgrains)))))) (sandpaint:save sand fn :gamma 1.1))) (time (main 1000 (second (cmd-args)))) <|start_filename|>examples/rnd-path.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (load "../utils/snek-alterations-mutate") (defmacro mutate ((mutate) &body body) (with-gensyms (bd mut a) `(let ((,bd (flatten (list ,@body))) (,mut ,mutate)) (mapcar (lambda (,a) (if (< (rnd:rnd) (snek::mutate-prob ,mut)) (progn (setf (snek::mutate-ind ,mut) (snek::-ok-ind (+ (snek::mutate-ind ,mut) (rnd:rndi -1 2)))) ;(setf (mutate-xy ,mut) ; (vec:add (mutate-xy ,mut) (rnd:rnd:in-circ 2.0d0))) (snek::do-mutate (snek::mutate-rules ,mut) ,a ,mut)) ,a)) ,bd)))) (defun circ-stroke (sand vv) (sandpaint:circ sand (lin-path:pos* (lin-path:make vv) (math:linspace 10000 0d0 1d0 :end nil)) 1 20)) (defun rnd-path (n) (let ((curr nil)) (labels ((do-append-edge-alt* (snk a) (if (> (vec:dst (append-edge-alt-xy a) (snek:get-vert snk (append-edge-alt-v a))) 200d0) (aif (do-append-edge-alt snk a) (setf curr it))))) (let ((snk (snek:make :alts `((append-edge-alt ,#'do-append-edge-alt*))))) (setf curr (snek:add-vert! snk (rnd:in-box 1000d0 1000d0 :xy (vec:vec 500d0 500d0)))) (loop for i from 0 below n do (snek:with (snk) (snek:append-edge? curr (rnd:in-box 1000d0 1000d0 :xy (vec:vec 500d0 500d0)) :rel nil))) (snek:get-grp-verts snk))))) (defun main (size fn) (let ((itt 100000) (noise 0.00000005d0) (snk (snek:make)) (sand (sandpaint:make size :fg (pigment:white 0.01) :bg (pigment:rgb 0.05 0.05 0.05))) (pa (lin-path:make (rnd-path 4))) (pb (lin-path:make (rnd-path 4))) (lsa (rnd:get-acc-lin-stp (rnd:rnd))) (lsb (rnd:get-acc-lin-stp (rnd:rnd))) (mut (snek:make-mutate :noise 100))) (let ((v1 (snek:add-vert! snk (vec:vec 0d0 0d0))) (v2 (snek:add-vert! snk (vec:vec 0d0 0d0)))) (snek:add-edge! snk v1 v2) (loop for p in (math:linspace itt 0d0 1d0 :end nil) do (snek:with (snk) (mutate (mut) (list (snek:move-vert? v1 (lin-path:pos pa (funcall lsa noise)) :rel nil) (snek:move-vert? v2 (lin-path:pos pb (funcall lsb noise)) :rel nil)))) (snek:draw-edges snk sand 100))) (sandpaint:save sand fn))) (time (main 1000 (second (cmd-args)))) <|start_filename|>test/chromatic.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (rnd:set-rnd-state 1) (defun main (size fn) (let ((snk (snek:make)) (sand (sandpaint:make size :fg (pigment:white 0.1d0) :bg (pigment:gray 0.1d0)))) (loop for x in (math:linspace 9 200d0 1800d0) do (loop for y in (math:linspace 9 200d0 1800d0) do (sandpaint:set-fg-color sand (pigment:white 0.3d0)) (sandpaint:circ sand (list (vec:vec x y)) 120d0 300000) (sandpaint:set-fg-color sand (pigment:black)) (sandpaint:circ sand (list (vec:vec x y)) 100d0 300000))) (sandpaint:set-fg-color sand (pigment:white 0.3d0)) (sandpaint:circ sand (list (vec:vec 1000d0)) 5d0 30000) (sandpaint:chromatic-aberration sand :s 10d0) (sandpaint:pixel-hack sand) (sandpaint:save sand "chromatic"))) (time (main 2000 (second (cmd-args)))) <|start_filename|>test/speed-linpath.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (setf *print-pretty* t) (rnd:set-rnd-state 1) (defun main () (let* ((itt 500000)) ;(snek:with (snk :zwidth farl) ; (print (snek:verts-in-rad snk (nrep 2 (rnd:rnd size)) farl))) (format t "make 10") (time (loop for i from 0 below itt do (lin-path:make (rnd:nin-box 10 500d0 500d0 :xy (vec:vec 500d0))))) (format t "make 100") (time (loop for i from 0 below itt do (lin-path:make (rnd:nin-box 100 500d0 500d0 :xy (vec:vec 500d0))))) (format t "pos 10") (time (loop with pos = (rnd:nrnd 100) with lp = (lin-path:make (rnd:nin-box 10 500d0 500d0 :xy (vec:vec 500d0))) for i from 0 below itt do (lin-path:pos* lp pos))) ;(format t "pos 100") ;(time ; (loop pos = (rnd:nrnd 100) ; with bz = (bzspl:make (rnd:nin-box 100 500d0 500d0 :xy (vec:vec 500d0))) ; for i from 0 below itt ; do (bzspl:pos (rnd:rnd)))) )) (require :sb-sprof) (sb-sprof:with-profiling (:max-samples 200000 :mode :cpu ;:mode :alloc ;:mode :time :report :graph) (main)) <|start_filename|>src/snek-extra.lisp<|end_filename|> (in-package :snek) (defun -roll-once (aa) (butlast (append (last aa) aa) 1)) ; TODO: move this to primitives? (defun get-grp-as-bzspl (snk g) (let ((pts (snek:get-grp-verts snk :g g))) (when (> (length pts) 3) (bzspl:make pts)))) (defun -dst2 (verts u v) (declare (optimize (safety 0) speed (debug 0)) (type (simple-array double-float) verts) (fixnum u v)) (+ (expt (- (the double-float (aref verts #3=(* 2 u))) (the double-float (aref verts #4=(* 2 v)))) 2d0) (expt (- (the double-float (aref verts (1+ #3#))) (the double-float (aref verts (1+ #4#)))) 2d0))) (defun edge-length (snk a b) " returns the length of edge (a b). " (declare (snek snk) (fixnum a b)) (with-struct (snek- verts) snk (sqrt (-dst2 verts a b)))) (defun ledge-length (snk e) " returns the length of edge e=(a b). " (declare (snek snk) (list e)) (destructuring-bind (a b) e (declare (fixnum a b)) (edge-length snk a b))) (defun prune-edges-by-len! (snk lim &optional (fx #'>)) " remove edges longer than lim, use fx #'< to remove edges shorter than lim. " (declare (snek snk) (double-float lim) (function fx)) (with (snk) (itr-edges (snk e) (when (funcall (the function fx) (ledge-length snk e) lim) (ldel-edge? e))))) (defun center! (snk &key (xy vec:*zero*)) " center the verts of snk on xy. returns the previous center. " (with-struct (snek- verts num-verts) snk (loop for i of-type fixnum from 0 below (* 2 num-verts) by 2 minimizing (aref verts i) into minx of-type double-float maximizing (aref verts i) into maxx of-type double-float minimizing (aref verts (1+ i)) into miny of-type double-float maximizing (aref verts (1+ i)) into maxy of-type double-float finally (let ((mx (* 0.5d0 (+ minx maxx))) (my (* 0.5d0 (+ miny maxy)))) (declare (double-float mx my)) (itr-verts (snk v) (vec:with-xy ((get-vert snk v) vx vy) (snek:move-vert! snk v (vec:vec (+ (vec::vec-x xy) (- vx mx)) (+ (vec::vec-y xy) (- vy my))) :rel nil))) (vec:vec mx my))))) (defun -is-rel-neigh (verts u v near) (declare (optimize (safety 0) speed (debug 0)) (type (simple-array double-float) verts) (fixnum u v) (vector near)) (loop with d of-type double-float = (-dst2 verts u v) for w of-type fixnum across near if (not (> (the double-float (max (the double-float (-dst2 verts u w)) (the double-float (-dst2 verts v w)))) d)) summing 1 into c of-type fixnum ; TODO: avoid this by stripping u from near if (> c 1) do (return-from -is-rel-neigh nil)) t) ; TODO: this is stil more than a little inefficient (defun relative-neighborhood! (snk rad &key g) " find the relative neigborhood graph (limited by the radius rad) of verts in snk. the graph is made in grp g. " (declare (optimize (safety 0) speed (debug 0)) (snek snk) (double-float rad)) (let ((c 0) (tested (make-hash-table :test #'equal))) (declare (fixnum c)) (zwith (snk (max 5d0 rad)) (itr-verts (snk v :collect nil) (loop with verts of-type (simple-array double-float) = (snek-verts snk) with near of-type vector = (remove-if (lambda (x) (= x v)) (verts-in-rad snk (get-vert snk v) rad)) ; TODO: strip u from near for u of-type fixnum across near if (< u v) do (let ((key (list u v))) (if (and ; if tested is true: don't perform test. (not (gethash key tested)) (-is-rel-neigh verts u v near)) (when (ladd-edge! snk key :g g) (incf c)) ; if not rel neigh: update tested (setf (gethash key tested) t)))))) c)) ; primitives? (defun add-circ! (snk num rad &key (xy vec:*zero*) g) (let ((vv (loop for p of-type double-float in (math:linspace num 0.0d0 1.0d0) collect (add-vert! snk (vec:on-circ p rad :xy xy))))) (loop for a of-type fixnum in vv and b of-type fixnum in (-roll-once vv) collect (add-edge! snk a b :g g)))) ; primitives? (defun add-polygon! (snk n rad &key (xy vec:*zero*) (rot (* 0.25d0 PI)) g) (let ((vv (loop for v of-type vec:vec in (vec:polygon n rad :xy xy :rot rot) collect (add-vert! snk v)))) (loop for a of-type fixnum in vv and b of-type fixnum in (-roll-once vv) collect (add-edge! snk a b :g g)))) ; primitives? (defun add-path! (snk points &key g closed) (let ((vv (add-verts! snk points))) (if closed (loop for a of-type fixnum in vv and b of-type fixnum in (-roll-once vv) collect (add-edge! snk a b :g g)) (loop for a of-type fixnum in vv and b of-type fixnum in (cdr vv) collect (add-edge! snk a b :g g))))) ; primitives? (defun add-path*! (snk vv &key g closed) (if closed (loop for a of-type fixnum in vv and b of-type fixnum in (-roll-once vv) collect (add-edge! snk a b :g g)) (loop for a of-type fixnum in vv and b of-type fixnum in (cdr vv) collect (add-edge! snk a b :g g)))) ; PRIMITIVES (defun psvg-get-prm-types (psvg) (declare (type draw-svg::draw-svg psvg)) (labels ((stdfx (type fxn) (list type (lambda (snk p &optional ea) (exec-with-args fxn (list psvg (snek:get-prm-verts snk :p p)) ea)))) (circfx (snk p &optional ea) (declare (ignore ea)) (exec-with-args #'draw-svg:circ (list psvg (first (get-prm-verts snk :p p)) (get-prm-props snk :p p)))) (circsfx (snk p &optional ea) (declare (ignore ea)) (exec-with-args #'draw-svg:circs (list psvg (get-prm-verts snk :p p) (get-prm-props snk :p p))))) (append (mapcar #'stdfx (list :bzspl :path :hatch) (list #'draw-svg:bzspl #'draw-svg:path #'draw-svg:hatch)) (list (list :circs #'circsfx) (list :circ #'circfx))))) ; SANDPAINT (defun draw-edges (snk sand grains &key g) (with-struct (snek- verts) snk (sandpaint:strokes sand (map 'list (lambda (ab) (mapcar (lambda (i) (vec:sarr-get verts i)) ab)) (get-edges snk :g g)) grains))) (defun draw-verts (snk sand) (with-struct (snek- verts num-verts) snk (sandpaint:arr-pix sand verts num-verts))) (defun draw-circ (snk sand rad grains) (with-struct (snek- verts num-verts) snk (sandpaint:arr-circ sand verts num-verts rad grains))) <|start_filename|>test/draw.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (load "../utils/test") (setf *print-pretty* t) (rnd:set-rnd-state 1) (defun test-pigment () (do-test (pigment:rgb 0.1 1.0 0.5) (pigment:rgb 0.1 1.0 0.5)) (do-test (pigment:to-list(pigment:rgb 0.1 1.0 0.5 0.2)) (list 0.10000000149011612d0 1.0d0 0.5d0 0.20000000298023224d0)) (do-test (pigment:hsv 0.5 1.0 1.0) (pigment:rgb 0 1.0 1.0)) (do-test (pigment:to-list (pigment:rgb 0 1.0 1.0 0.5)) (list 0.0d0 1.0d0 1.0d0 0.5d0)) (do-test (pigment:to-list* (pigment:rgb 0 1.0 1.0 0.5)) (list 0.0d0 0.5d0 0.5d0 0.5d0)) (do-test (pigment:cmyk 1 0 0 0) (pigment:rgb 0 1.0 1.0)) (do-test (pigment:cmyk 0.5 0 0 0.5) (pigment:rgb 0.25 0.5 0.5)) (do-test (pigment:to-hex (pigment:rgb 1d0 0d0 1d0)) "#FF00FF") (do-test (pigment:to-hex (pigment:rgb 1d0 0.5d0 1d0)) "#FF80FF") (do-test (pigment:to-hex (pigment:rgb 0d0 0d0 0d0)) "#000000") (do-test (pigment:to-hex (pigment:rgb 0d0 0.03d0 0.01d0)) "#000702")) (defun get-sample-pix (sand) (let ((vals (sandpaint::sandpaint-vals sand)) (indfx (sandpaint::sandpaint-indfx sand))) (flatten (loop for i in (list 10 45 45 92 23) and j in (list 39 78 49 92 89) collect (list (aref vals (funcall indfx i j 0)) (aref vals (funcall indfx i j 1)) (aref vals (funcall indfx i j 2)) (aref vals (funcall indfx i j 3))))))) (defun test-sandpaint () (let ((sand (sandpaint:make 100 :fg (pigment:black) :bg (pigment:white)))) (loop for p in (rnd:nin-box 100000 50d0 50d0 :xy (vec:vec 50d0 50d0)) do (sandpaint:set-fg-color sand (pigment:rgb (rnd:rnd) (rnd:rnd) (rnd:rnd) 0.004)) (sandpaint:pix sand (list p))) (do-test (get-sample-pix sand) (list 0.9681936465458644d0 0.9853978043949597d0 0.9779575571520513d0 1.0d0 0.9850031698578189d0 0.9847191146807868d0 0.9818651665563702d0 1.0d0 0.9810825011577217d0 0.9774148613591062d0 0.9785530577286031d0 1.0d0 0.9617585443476347d0 0.9684279445612141d0 0.9686700238368381d0 1.0d0 0.9829785654522593d0 0.9840476095774362d0 0.9852693651002268d0 1.0d0))) (let ((sand (sandpaint:make 100 :fg (pigment:black) :bg (pigment:transparent)))) (sandpaint:set-fg-color sand (pigment:rgb (rnd:rnd) (rnd:rnd) (rnd:rnd) 0.3d0)) (sandpaint:pix sand (rnd:nin-box 100000 40d0 50d0 :xy (vec:vec 50d0 50d0))) (sandpaint:set-fg-color sand (pigment:rgb (rnd:rnd) (rnd:rnd) (rnd:rnd) 0.3d0)) (sandpaint:pix sand (rnd:nin-box 100000 50d0 20d0 :xy (vec:vec 50d0 50d0))) (sandpaint:set-fg-color sand (pigment:rgb (rnd:rnd) (rnd:rnd) (rnd:rnd) 1d0)) (sandpaint:pix sand (rnd:nin-box 100000 20d0 50d0 :xy (vec:vec 50d0 50d0))) (do-test (get-sample-pix sand) (list 0.6428169411853405d0 0.13168206068658486d0 0.6498467311662349d0 0.9999945883043961d0 0.5129926107428067d0 0.37464299479913565d0 0.15938469273885625d0 1.0d0 0.5129926107428067d0 0.37464299479913565d0 0.15938469273885625d0 1.0d0 0.0d0 0.0d0 0.0d0 0.0d0 0.8828667582669707d0 0.0037578027642338877d0 0.04668942596643424d0 0.9596463929999997d0)) (sandpaint:save sand "draw-8") (sandpaint:save sand "draw-16" :bits 16))) (defun main () (test-title (test-pigment)) (test-title (test-sandpaint)) (test-title (test-summary))) (main) <|start_filename|>test/snek.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (load "../utils/test") (setf *print-pretty* t) (rnd:set-rnd-state 1) (defun test-snek (snk) (do-test (snek:add-vert! snk (vec:vec 0d0 0d0)) 0) (do-test (snek:add-vert! snk (vec:vec 10d0 0d0)) 1) (do-test (snek:add-vert! snk (vec:vec 3d0 3d0)) 2) (do-test (snek:add-vert! snk (vec:vec 4d0 3d0)) 3) (do-test (snek:add-vert! snk (vec:vec 7d0 200d0)) 4) (do-test (snek:add-vert! snk (vec:vec 2d0 10d0)) 5) (do-test (snek:add-vert! snk (vec:vec 4d0 11d0)) 6) (do-test (snek:add-vert! snk (vec:vec 3d0 10d0)) 7) (do-test (snek:add-vert! snk (vec:vec 0d0 0.5d0)) 8) (do-test (snek:add-vert! snk (vec:vec 2d0 1.0d0)) 9) (do-test (snek:add-vert! snk (vec:vec 3.0d0 10d0)) 10) (do-test (snek:ladd-edge! snk '(0 0)) nil) (do-test (snek:ladd-edge! snk '(0 2)) '(0 2)) (do-test (snek:ladd-edge! snk '(0 1)) '(0 1)) (do-test (snek:ladd-edge! snk '(5 0)) '(0 5)) (do-test (snek:ladd-edge! snk '(1 0)) nil) (do-test (snek:ladd-edge! snk '(5 0)) nil) (do-test (snek:ladd-edge! snk '(0 2)) nil) (do-test (snek:add-edge! snk 5 2) '(2 5)) (do-test (snek:add-edge! snk 4 1) '(1 4)) (do-test (snek:ladd-edge! snk '(4 0)) '(0 4)) (do-test (snek:ladd-edge! snk '(5 1)) '(1 5)) (do-test (snek:ladd-edge! snk '(9 9)) nil) (do-test (snek:ladd-edge! snk '(3 9)) '(3 9)) (do-test (snek:ladd-edge! snk '(0 1)) nil) (do-test (snek:ladd-edge! snk '(0 4)) nil) (do-test (snek:ladd-edge! snk '(10 9)) '(9 10)) (do-test (snek:edge-exists snk '(0 2)) t) (do-test (snek:edge-exists snk '(5 0)) t) (do-test (snek:edge-exists snk '(9 2)) nil) (do-test (snek:edge-exists snk '(2 2)) nil) (do-test (snek:get-vert snk 2) (vec:vec 3.0d0 3.0d0)) (do-test (snek:add-vert! snk (vec:vec 0d0 1d0)) 11) (do-test (snek:ladd-edge! snk '(0 1)) nil) (do-test (snek:add-vert! snk (vec:vec 0d0 7d0)) 12) (do-test (snek:ledge-length snk '(0 4)) 200.12246250733574d0) (do-test (snek:edge-length snk 2 5) 7.0710678118654755d0) (do-test (snek:ledge-length snk '(1 2)) 7.615773105863909d0) (do-test (snek:move-vert! snk 3 (vec:vec 1d0 3d0)) (vec:vec 5d0 6d0)) (do-test (snek:move-vert! snk 3 (vec:vec 0.5d0 0.6d0) :rel t) (vec:vec 5.5d0 6.6d0)) (do-test (snek:get-vert snk 3) (vec:vec 5.5d0 6.6d0))) (defun test-snek-2 (snk) (do-test (snek:add-vert! snk (vec:vec 0d0 0d0)) 0) (do-test (snek:add-vert! snk (vec:vec 20d0 20d0)) 1) (do-test (snek:add-vert! snk (vec:vec 30d0 30d0)) 2) (do-test (snek:add-vert! snk (vec:vec 40d0 40d0)) 3) (do-test (snek:ladd-edge! snk '(0 1)) '(0 1)) (do-test (snek:ladd-edge! snk '(1 2)) '(1 2)) (do-test (snek:ladd-edge! snk '(2 3)) '(2 3)) (do-test (snek:get-edges snk) '#((0 1) (1 2) (2 3))) (do-test (snek:del-edge! snk 0 1) t) (do-test (snek:ldel-edge! snk '(0 1)) nil) (do-test (snek:ldel-edge! snk '(3 2)) t) (do-test (snek:ldel-edge! snk '(1 2)) t) (do-test (snek:get-num-edges snk) 0) (do-test (snek::snek-num-verts snk) 4)) (defun test-snek-3 (snk) (do-test (snek:add-vert! snk (vec:vec 10d0 10d0)) 0) (do-test (snek:add-vert! snk (vec:vec 20d0 10d0)) 1) (do-test (snek:add-vert! snk (vec:vec 30d0 10d0)) 2) (do-test (snek:add-vert! snk (vec:vec 40d0 10d0)) 3) (do-test (snek:ladd-edge! snk '(0 1)) '(0 1)) (do-test (snek:ladd-edge! snk '(1 2)) '(1 2)) (do-test (snek:ladd-edge! snk '(2 3)) '(2 3)) (do-test (snek:ladd-edge! snk '(2 3)) nil)) (defun init-snek () (let ((snk (snek:make :max-verts 16))) (snek:add-vert! snk (vec:vec 0d0 2d0)) (snek:add-vert! snk (vec:vec 2d0 3d0)) (snek:add-vert! snk (vec:vec 3d0 4d0)) (snek:add-vert! snk (vec:vec 4d0 7d0)) (snek:add-vert! snk (vec:vec 5d0 4d0)) (snek:add-vert! snk (vec:vec 0d0 6d0)) (snek:add-vert! snk (vec:vec -1d0 7d0)) (snek:add-vert! snk (vec:vec 0d0 8d0)) (snek:add-vert! snk (vec:vec 0d0 9d0)) (snek:add-vert! snk (vec:vec 10d0 1d0)) (snek:add-vert! snk (vec:vec 3d0 1d0)) (snek:ladd-edge! snk '(1 2)) (snek:ladd-edge! snk '(0 1)) (snek:ladd-edge! snk '(3 1)) (snek:ladd-edge! snk '(5 6)) (snek:ladd-edge! snk '(7 3)) snk)) (defun test-snek-incident () (let ((snk (init-snek))) (do-test (snek:get-incident-edges snk 1) '((1 2) (0 1) (1 3))) (do-test (snek:get-incident-edges snk 100) nil))) (defun test-snek-with () (let ((snk (init-snek))) (snek:with (snk) (snek:add-vert? (vec:vec 11d0 3d0)) (list 4.5 (snek:move-vert? 0 (vec:vec 1d0 0d0)) nil t (list 5 (snek:add-vert? (vec:vec 12d0 3d0)) (snek:add-vert? (vec:vec 13d0 3d0))) (list nil) (list (list)))) (do-test (sort (snek:get-vert-inds snk) #'<) (list 0 1 2 3 5 6 7))) (let ((snk (init-snek))) (do-test (snek:edge-exists snk '(7 2)) nil) (snek:cwith (snk %) (list) 1 nil (% (snek:add-vert? (vec:vec 12d0 3d0))) (% (snek:add-vert? (vec:vec 13d0 6d0))) (% (snek:add-edge? 1 2)) (% (snek:add-edge? 2 7)) (% nil)) (do-test (snek:get-vert snk 12) (vec:vec 13d0 6d0)) (do-test (snek:get-vert snk 11) (vec:vec 12d0 3d0)) (do-test (snek:edge-exists snk '(1 2)) t) (do-test (snek:edge-exists snk '(2 7)) t) (do-test (snek:edge-exists snk '(7 2)) t))) (defun test-snek-add () (let ((snk (init-snek))) (snek:with (snk) (snek:add-vert? (vec:vec 10d0 3d0))) (do-test (snek:get-vert snk 11) (vec:vec 10d0 3d0)) (do-test (snek:with (snk :collect t) (snek:add-vert? (vec:vec 80d0 3d0)) (snek:add-vert? (vec:vec 70d0 3d0))) '(12 13)) (do-test (snek::snek-num-verts snk) 14) (snek:with (snk) (snek:vadd-edge? (vec:vec 7d0 3d0) (vec:vec 100d0 0.99d0))) (do-test (snek:get-edges snk) '#((1 2) (1 3) (0 1) (3 7) (5 6) (14 15))))) (defun test-snek-move () (let ((snk (init-snek))) (do-test (snek:with (snk :collect t) (snek:move-vert? 0 (vec:vec 3d0 3d0)) (snek:move-vert? 1 (vec:vec 1d0 3d0)) (snek:move-vert? 3 (vec:vec 2d0 3d0) :rel nil) (snek:move-vert? 2 (vec:vec 3d0 4d0))) (list (vec:vec 3.0d0 5.0d0) (vec:vec 3.0d0 6.0d0) (vec:vec 2.0d0 3.0d0) (vec:vec 6.0d0 8.0d0))) (do-test (snek:get-vert snk 0) (vec:vec 3d0 5d0)) (do-test (snek:get-vert snk 1) (vec:vec 3d0 6d0)) (do-test (snek:get-vert snk 3) (vec:vec 2d0 3d0)) (do-test (snek:get-vert snk 2) (vec:vec 6d0 8d0)))) (defun test-snek-join () (let ((snk (init-snek))) (snek:with (snk) (snek:add-edge? 3 3) (snek:add-edge? 3 3) (snek:add-edge? 3 6) (snek:add-edge? 7 1)) (do-test (snek:get-num-edges snk) 14) (do-test (snek:with (snk :collect t) (snek:add-edge? 3 3) (snek:add-edge? 1 6) (snek:add-edge? 1 100)) '(nil (1 6) nil)))) (defun test-snek-append () (let ((snk (init-snek))) (do-test (snek::snek-num-verts snk) 11) (do-test (snek:with (snk :collect t) (snek:append-edge? 3 (vec:vec 3d0 4d0)) (snek:append-edge? 3 (vec:vec 8d0 5d0) :rel nil) (snek:append-edge? 7 (vec:vec 1d0 2d0))) '(11 12 13)) (do-test (snek:get-num-edges snk) 16) (do-test (snek::snek-num-verts snk) 14) (do-test (to-list (snek::snek-verts snk)) (list 0.0d0 2.0d0 2.0d0 3.0d0 3.0d0 4.0d0 4.0d0 7.0d0 5.0d0 4.0d0 0.0d0 6.0d0 -1.0d0 7.0d0 0.0d0 8.0d0 0.0d0 9.0d0 10.0d0 1.0d0 3.0d0 1.0d0 7.0d0 11.0d0 8.0d0 5.0d0 1.0d0 10.0d0 0.0d0 0.0d0 0.0d0 0.0d0)))) (defun test-snek-split () (let ((snk (init-snek))) (do-test (snek:with (snk :collect t) (snek:split-edge? 1 2) (snek:lsplit-edge? '(1 2)) (snek:lsplit-edge? '(5 6))) '(((1 11) (2 11)) NIL ((5 12) (6 12)))) (do-test (snek:get-num-edges snk) 14) (do-test (snek::snek-num-verts snk) 13) (do-test (to-list (snek::snek-verts snk)) (list 0.0d0 2.0d0 2.0d0 3.0d0 3.0d0 4.0d0 4.0d0 7.0d0 5.0d0 4.0d0 0.0d0 6.0d0 -1.0d0 7.0d0 0.0d0 8.0d0 0.0d0 9.0d0 10.0d0 1.0d0 3.0d0 1.0d0 2.5d0 3.5d0 -0.5d0 6.5d0 0.0d0 0.0d0 0.0d0 0.0d0 0.0d0 0.0d0)))) (defun test-snek-itrs () (let ((snk (init-snek))) (snek:with (snk) (snek:with-rnd-vert (snk v) (snek:append-edge? v (vec:vec 3d0 2d0)) (snek:move-vert? v (vec:vec 2d0 2d0)))) (do-test (snek:get-num-edges snk) 12) (do-test (snek::snek-num-verts snk) 12) (do-test (snek::snek-wc snk) 1) (snek:with (snk) (snek:itr-verts (snk v) (snek:move-vert? v (vec:vec 2d0 2d0)))) (do-test (sort (flatten (snek:itr-verts (snk i) i)) #'<) '(0 1 2 3 4 5 6 7 8 9 10 11)) (do-test (flatten (snek:itr-verts (snk i :collect nil) i)) nil) (do-test (sort (flatten (snek:itr-grp-verts (snk i) i)) #'<) '(0 1 2 3 5 6 7 11)) (do-test (snek:itr-edges (snk e) e) '(((1 2)) ((1 3)) ((0 1)) ((3 7)) ((5 6)) ((5 11)))) (do-test (sort (flatten (snek:itr-edges (snk e) (snek:ledge-length snk e))) #'<) '(1.0d0 1.4142135623730951d0 2.23606797749979d0 3.1622776601683795d0 4.123105625617661d0 4.47213595499958d0)) (do-test (snek::snek-wc snk) 2) (snek:with (snk) (snek:with-rnd-edge (snk e) (snek:lsplit-edge? e))) (do-test (snek:get-num-edges snk) 14) (do-test (snek::snek-num-verts snk) 13))) (defun test-snek-zmap () (let ((snk (snek:make))) (snek:add-vert! snk (vec:vec 100d0 200d0)) (snek:add-vert! snk (vec:vec 200d0 300d0)) (snek:add-vert! snk (vec:vec 300d0 400d0)) (snek:add-vert! snk (vec:vec 400d0 500d0)) (snek:add-vert! snk (vec:vec 500d0 600d0)) (snek:add-vert! snk (vec:vec 600d0 700d0)) (snek:add-vert! snk (vec:vec 700d0 800d0)) (snek:add-vert! snk (vec:vec 800d0 900d0)) (zmap:make (snek::snek-verts snk) (snek::snek-num-verts snk) 100.0d0) (snek:with (snk :zwidth 50.0d0) (do-test (sort (snek:verts-in-rad snk (vec:vec 500d0 500d0) 50.0d0) #'<) #()) (do-test (sort (snek:verts-in-rad snk (vec:vec -500d0 500d0) 50.0d0) #'<) #())) (snek:with (snk :zwidth 200.0d0) (do-test (sort (snek:verts-in-rad snk (vec:vec 800d0 800d0) 200.0d0) #'<) #(6 7)) (do-test (let ((a (list))) (snek:with-verts-in-rad (snk (vec:vec 800d0 800d0) 200d0 v) (setf a (append a (list v)))) a) (list 6 7)) (do-test (sort (snek:verts-in-rad snk (vec:vec 500d0 500d0) 200.0d0) #'<) #(3 4)) (do-test (let ((a (list))) (snek:with-verts-in-rad (snk (vec:vec 500d0 500d0) 200d0 v) (setf a (append a (list v)))) a) (list 3 4))) (snek:with (snk :zwidth 1000.0d0) (do-test (sort (snek:verts-in-rad snk (vec:vec 500d0 500d0) 1000.0d0) #'<) #(0 1 2 3 4 5 6 7))))) (defun test-snek-grp () (let ((snk (snek:make :max-verts 22 :grp-size 30))) (let ((g1 (snek:add-grp! snk :type 'path)) (g2 (snek:add-grp! snk)) (g3 (snek:add-grp! snk :type 'path))) (snek:add-vert! snk (vec:vec 100d0 200d0)) (snek:add-vert! snk (vec:vec 200d0 300d0)) (snek:add-vert! snk (vec:vec 300d0 400d0)) (snek:add-vert! snk (vec:vec 400d0 500d0)) (snek:add-vert! snk (vec:vec 600d0 700d0)) (snek:add-vert! snk (vec:vec 700d0 800d0)) (snek:add-vert! snk (vec:vec 800d0 900d0)) (snek:add-vert! snk (vec:vec 500d0 600d0)) (snek:add-vert! snk (vec:vec 900d0 600d0)) (snek:ladd-edge! snk '(1 2) :g g1) (snek:ladd-edge! snk '(1 2)) (snek:ladd-edge! snk '(1 2) :g g2) (snek:ladd-edge! snk '(3 2) :g g2) (snek:ladd-edge! snk '(1 5) :g g3) (do-test (sort (flatten (snek:itr-grp-verts (snk i :g g2) i)) #'<) '(1 2 3)) (do-test (sort (flatten (snek:itr-grp-verts (snk i :g nil) i)) #'<) '(1 2)) (do-test (sort (flatten (snek:itr-edges (snk e :g g1) e)) #'<) '(1 2)) (do-test (sort (snek:get-vert-inds snk :g g1) #'<) '(1 2)) (do-test (sort (snek:get-vert-inds snk :g g3) #'<) '(1 5)) (do-test (length (snek:get-vert-inds snk)) 2) (do-test (length (snek:itr-grps (snk g) g)) 3))) (let* ((snk (snek:make)) (g (snek:add-grp! snk :type :closed))) (snek:add-vert! snk (vec:vec 1d0 1d0)) (snek:add-vert! snk (vec:vec 1d0 1d0)) (snek:add-vert! snk (vec:vec 1d0 1d0)) (do-test (snek:get-grp-loop snk :g g) nil) (snek:ladd-edge! snk (list 2 0) :g g) (do-test (snek:get-grp-loop snk :g g) nil) (snek:ladd-edge! snk (list 1 2) :g g) (snek:ladd-edge! snk (list 1 0) :g g) (do-test (to-list (snek:get-grp-loop snk :g g )) (list 2 0 1)))) (defun test-snek-prm () (let ((snk (snek:make :max-verts 22 :grp-size 30 :prms (list (list :path (lambda (snk p &optional extra-args) (snek:get-prm-vert-inds snk :p p))))))) (let ((p1 (snek:add-prm! snk :type :path)) (p2 (snek:add-prm! snk)) (p3 (snek:add-prm! snk :type :path))) (snek:add-vert! snk (vec:vec 100d0 200d0) :p p1) (snek:add-vert! snk (vec:vec 200d0 300d0) :p p2) (snek:add-vert! snk (vec:vec 300d0 400d0) :p p3) (snek:add-vert! snk (vec:vec 400d0 500d0) :p p1) (snek:add-vert! snk (vec:vec 600d0 700d0) :p p1) (snek:add-vert! snk (vec:vec 700d0 800d0) :p p2) (do-test (flatten (snek:itr-prm-verts (snk i :p p2) i)) '(1 5)) (do-test (flatten (snek:itr-prm-verts (snk i :p p1) i)) '(0 3 4)) (do-test (snek:get-prm-verts snk :p p1) (list (vec:vec 100.0d0 200.0d0) (vec:vec 400.0d0 500.0d0) (vec:vec 600.0d0 700.0d0))) (do-test (to-list (snek:prmr snk :p p1)) '(0 3 4)) (do-test (to-list (snek:prmr snk :p p2)) '(1 5)) (do-test (length (snek:itr-prms (snk p) p)) 3)))) (defun main () (test-title (test-snek (snek:make))) (test-title (test-snek-2 (snek:make))) (test-title (test-snek-3 (snek:make))) (test-title (test-snek-incident)) (test-title (test-snek-with)) (test-title (test-snek-add)) (test-title (test-snek-move)) (test-title (test-snek-join)) (test-title (test-snek-append)) (test-title (test-snek-split)) (test-title (test-snek-itrs)) (test-title (test-snek-zmap)) (test-title (test-snek-grp)) (test-title (test-snek-prm)) (test-title (test-summary))) (main) <|start_filename|>src/hset.lisp<|end_filename|> (in-package :hset) " this is a naive wrapper around hash-map. not sure how efficient it will be? " (defun add (s e) (declare (fixnum e)) (multiple-value-bind (val exists) (gethash e s) (declare (ignore val)) (if exists nil (setf (gethash e s) t)))) (defun add* (s ee) (loop for e of-type fixnum in ee collect (add s e))) (defun del (s e) (declare (fixnum e)) (remhash e s)) (defun del* (s ee) (loop for e of-type fixnum in ee collect (remhash e s))) (defun mem (s e) (declare (fixnum e)) (multiple-value-bind (v exists) (gethash e s) (declare (ignore v)) exists)) (defun mem* (s ee) (loop for e in ee collect (multiple-value-bind (v exists) (gethash e s) (declare (ignore v)) exists))) (defun num (s) (hash-table-count s)) (defun to-list (s) (loop for e of-type fixnum being the hash-keys of s collect e)) (defun make (&key init (size 1000) (inc 1.5)) (let ((s (make-hash-table :test #'eql :size size :rehash-size inc))) (when init (add* s init)) s)) <|start_filename|>utils/color.lisp<|end_filename|> (defun get-color-walker (n alpha &optional closed) (let ((spla (bzspl:make (rnd:nin-box n 0.5d0 0.5d0 :xy (vec:vec 0.5d0)) :closed closed)) (splb (bzspl:make (rnd:nin-box n 0.5d0 0.5d0 :xy (vec:vec 0.5d0)) :closed closed))) (lambda (i) (vec:with-xy ((bzspl:pos spla i) h s) (vec:with-xy ((bzspl:pos splb i) v _) (pigment:hsv h s v alpha)))))) <|start_filename|>examples/differential-line.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (load "../utils/time") (defun init-snek (n size xy) (let ((snk (snek:make :max-verts 5000000))) (snek:add-path! snk (math:rep (p (math:linspace n 0d0 1d0 :end nil)) (vec:on-circ p 20d0 :xy xy)) :closed t) snk)) (defun main (size fn) (let ((itt 1100) (grains 30) (snk (init-snek 20 size (vec:rep (math:dfloat (half size))))) (farl 100d0) (stp 0.004d0) (sand (sandpaint:make size :fg (pigment:white 0.05) :bg (pigment:dark)))) (start-timer "total") (loop for i from 0 below itt do (start-timer "with") (snek:with (snk :zwidth farl) (start-timer "in-with") (snek:itr-verts (snk v) (snek:move-vert? v (rnd:in-circ (* stp 5d0))) (map 'list (lambda (w) (with-timer ("snek:with-dx") (snek:with-dx (snk (list v w) dx d) (let ((ndx (vec:iscale dx d)) (s (* (- 1.0d0 (/ d farl)) stp))) (list (snek:move-vert? v (vec:scale ndx (* -1 s))) (snek:move-vert? w (vec:scale ndx s))))))) (with-timer ("in-rad") (snek:verts-in-rad snk (snek:get-vert snk v) farl)))) (snek:itr-edges (snk e) (snek:with-dx (snk e dx d) (let ((ndx (vec:iscale dx d))) (cond ((> d 8.d0) (snek:lsplit-edge? e)) ((> d 2.d0) (list (snek:move-vert? (first e) (vec:scale ndx stp)) (snek:move-vert? (second e) (vec:scale ndx (* -1 stp))))))))) (sum-timer "in-with")) (sum-timer "with") (if (= (mod i 100) 0) (progn (format t "itt ~a, num verts ~a ~%" i (snek::snek-num-verts snk)) ;(snek:itr-edges (snk e) ; (sandpaint:lin-path sand ; (close-path (snek:get-verts snk e)) ; 3 grains)) ;(sandpaint:save sand (append-number fn i) :gamma 1.5) ;(sandpaint:save sand fn :gamma 1.5) ;(sandpaint:clear sand (pigment:dark)) ))) (sum-timer "total") (show-timers))) ;(time (main 1000 (second (cmd-args)))) ;(sb-profile:profile "common-lisp-user.snek:move-vert?") ;(main 1000 "asdf") ;(sb-profile:report) (require :sb-sprof) (sb-sprof:with-profiling (:max-samples 200000 :mode :cpu ;:mode :alloc ;:mode :time :report :graph) (time (main 1000 "asdf"))) <|start_filename|>examples/facade.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (defun mpath (lines p) (mapcar (lambda (l) (lin-path:pos (lin-path:make l) p)) lines)) (defun get-lines (a b n) (loop for x in (rnd:rndspace n a b :order t) collect (loop for y in (rnd:rndspace n a b) collect (vec:vec x y)))) (defun main (size fn) (let ((itt 100000) (nlines 300) (nsteps 1000) (grains 50) (sand (sandpaint:make size :fg (pigment:white 0.05) :bg (pigment:dark)))) (let ((lines (get-lines -500d0 1500d0 40))) (loop for u in (rnd:rndspace nlines 0d0 1d0) do (let ((pa (lin-path:make (mpath lines u))) (pb (lin-path:make (mpath lines (+ (rnd:rnd* 0.05d0) u))))) (let ((r1 (rnd:rnd)) (r2 (rnd:rnd))) ;(sandpaint:lin-path sand (lin-path:pos* pa (math:linspace 100 r1 r2)) 1.0 20) ;(sandpaint:lin-path sand (lin-path:pos* pb (math:linspace 100 r1 r2)) 1.0 20) (rnd:with-rndspace (nsteps r1 r2 v) (sandpaint:stroke sand (list (lin-path:pos pa v) (lin-path:pos pb v)) grains)))))) (sandpaint:save sand fn))) (time (main 1000 (second (cmd-args)))) <|start_filename|>examples/grid-rotate.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (load "../utils/state") (load "../utils/grid") (defun place-grid (snk small large mid) (let* ((df (math:dfloat (half (- large small)))) (a (rnd:in-box df df :xy mid)) (b (rnd:in-box df df :xy mid)) (angle (rnd:rnd (* 2d0 PI))) (num (floor (* 0.1d0 (vec:dst a b))))) (loop for path in (get-stroke-grid num 100 2000d0 angle a b) do (snek:add-path! snk path :g (snek:add-grp! snk))))) (defun main (size fn) (let* ((ngrid 100) (snk (snek:make :max-verts 100000)) (state-gen (get-walker-state-gen (lambda () (rnd:get-circ-stp*)))) (sand (sandpaint:make size :fg (pigment:black 0.05) :bg (pigment:white)))) (loop for i from 0 below 10 do (place-grid snk 0 size (vec:vec 500d0 500d0))) (loop for i from 0 below 50 do (print-every i 100) (snek:with (snk) (snek:itr-verts (snk v) ;(snek:move-vert? v (funcall state-gen v 0.0009d0)) (snek:move-vert? v (rnd:in-circ 0.5d0)))) ;(snek:itr-grps (snk g) ; (sandpaint:pix sand ; (bzspl:rndpos (snek:get-grp-as-bzspl snk g) 500))) ) (snek:itr-grps (snk g) (sandpaint:lin-path sand (bzspl:rndpos (snek:get-grp-as-bzspl snk g) 10000 :order t) 1d0 10)) (sandpaint:pixel-hack sand) (sandpaint:save sand fn))) (time (main 1000 (second (cmd-args)))) <|start_filename|>utils/convex-split.lisp<|end_filename|> (defun get-splits (n) (let ((a -1) (b -1)) (loop until (not (= a b)) do (setf a (rnd:rndi (1- n)) b (rnd:rndi (1- n)))) (sort (list a b) #'<))) (defun get-left (a b n) (let ((res (make-adjustable-vector))) (loop for i from 0 while (<= i a) do (vextend i res)) (vextend (list a (1+ a)) res) (vextend (list b (1+ b)) res) (loop for i from (1+ b) while (< i n) do (vextend (mod i (1- n)) res)) res)) (defun get-right (a b n) (let ((res (make-adjustable-vector))) (loop for i from (1+ a) while (<= i b) do (vextend i res)) (vextend (list b (1+ b)) res) (vextend (list a (1+ a)) res) (loop for i from (1+ a) while (<= (mod i n) (1+ a)) do (vextend i res)) res)) (defun do-mid (a b &optional (s 0.5d0)) (mapcar (lambda (l r) (+ l (* s (- r l)))) a b)) (defun ind-to-pts (pts inds s) (to-vector (loop for i across inds collect (if (eql (type-of i) 'cons) (do-mid (aref pts (first i)) (aref pts (second i)) s) (aref pts i))))) (defun split (pts &optional s (lim 0d0) &aux (s* (if (not s) (lambda () 0.5d0) s)) (n (length pts))) (if (> (loop for i from 0 below (1- n) minimizing (math:ddst (aref pts i) (aref pts (1+ i)))) lim) ; do split (destructuring-bind (a b) (get-splits n) (let ((sval (funcall s*))) (list t (ind-to-pts pts (get-left a b n) sval) (ind-to-pts pts (get-right a b n) sval)))) ; do not split (list nil pts))) <|start_filename|>src/math-extra.lisp<|end_filename|> ; PATHS (in-package :math) (defun line-from (a r &optional (s 1d0)) (declare (vec:vec a r) (double-float s)) (list a (vec:from a r s))) (defun path-tangents (aa &key closed (default (vec:vec 0d0)) &aux (aa* (if (equal (type-of aa) 'cons) (make-adjustable-vector :init aa :type 'vec) aa))) (when closed (vextend (aref aa* 0) aa*)) (loop with res = (make-adjustable-vector :type 'vec) for i from 0 below (length-1 aa*) do (vextend (vec:nsub (aref aa* (1+ i)) (aref aa* i) :default default) res) finally (return res))) (defun path-angles (pts) (loop with res = (make-adjustable-vector) for i from 0 below (length-1 pts) do (vextend (vec:norm (vec:sub (aref pts (1+ i)) (aref pts i))) res) finally (vextend (aref res (length-1 res)) res) (return res))) (defun -path-simplify (pts lim &optional left right) (declare (double-float lim)) (let ((res (make-adjustable-vector)) (dmax -1d0) (index 0)) (let* ((l (if (not left) 0 left)) (r (if (not right) (length-1 pts) right)) (seg (list (aref pts l) (aref pts r)))) (loop for i from (1+ l) below r do (let ((d (vec:segdst seg (aref pts i)))) (when (> d dmax) (setf dmax d index i)))) (if (> dmax lim) (progn (loop with ps = (-path-simplify pts lim l index) for i from 0 below (length-1 ps) do (vextend (aref ps i) res)) (loop for i across (-path-simplify pts lim index r) do (vextend i res))) (progn (vextend l res) (vextend r res)))) (sort res #'<))) (defun path-simplify (pts lim) ;https://hydra.hull.ac.uk/resources/hull:8338 (let ((pts* (ensure-vector pts))) (loop for i across (-path-simplify pts* lim) collect (aref pts* i)))) (defun -scale-offset (w a b &key (fxn #'sin)) (declare (double-float w) (vec:vec a b) (function fxn)) (let ((s (abs (funcall fxn (abs (- (vec:angle a) (vec:angle b))))))) (declare (double-float s)) (if (< s 0.05d0) w (/ w s)))) (defun -offset (v o) (list (vec:add v o) (vec:sub v o))) (defun -chamfer (width diag pa na aa aa-) (let* ((x (< (vec:cross aa aa-) 0d0)) (corner (if x (second diag) (first diag))) (s (-scale-offset width aa- na :fxn #'cos))) (loop for v in (-offset pa (vec:scale (vec:perp na) s)) collect (if x (list v corner) (list corner v))))) (defun -regular-perp (a b) (declare (vec:vec a b)) (vec:perp (vec:norm (vec:add a b)))) (defun -sharp-perp (a) (declare (vec:vec a)) (vec:perp a)) (defun -make-test-fxn-closed (angles clim slim) (declare (vector angles) (double-float clim slim)) (let ((n- (length-1 angles))) (lambda (i) (let ((a (aref angles i)) (a- (aref angles (if (< i 1) n- (1- i))))) (let ((dt (vec:dot a- a))) (cond ((<= dt slim) (list :sharp (-sharp-perp a-))) ((< dt clim) (list :chamfer (-regular-perp a- a))) (t (list :regular (-regular-perp a- a))))))))) (defun -make-test-fxn-open (angles clim slim) (declare (vector angles) (double-float clim slim)) (let ((n- (length-1 angles))) (lambda (i) (let ((a (aref angles i))) (if (> n- i 0) (let ((dt (vec:dot (aref angles (1- i)) a))) (cond ((<= dt slim) (list :sharp (-sharp-perp (aref angles (1- i))))) ((< dt clim) (list :chamfer (-regular-perp (aref angles (1- i)) a))) (t (list :regular (-regular-perp (aref angles (1- i)) a))))) (cond ((< i 1) (list :regular (vec:perp a))) (t (list :regular (vec:perp a))))))))) (defun -get-diagonals (pts width clim slim closed ) (let* ((res (make-adjustable-vector)) (n (length pts)) (angles (math:path-angles pts)) (corner-test (if closed (-make-test-fxn-closed angles clim slim) (-make-test-fxn-open angles clim slim)))) (loop for i from 0 below (if closed (1- n) n) do (destructuring-bind (corner na) (funcall corner-test i) (let ((diag (-offset (aref pts i) (vec:scale na (-scale-offset width (aref angles i) na))))) (mapcar (lambda (d) (vextend d res)) (case corner (:chamfer (-chamfer width diag (aref pts i) na (aref angles i) (aref angles (math:mod- i n)))) (:regular (list diag)) (:sharp (list (progn diag) (reverse diag)))))))) ; hack to handle closed path chamfering (when closed (vextend (aref res 0) res)) res)) (defun path-offset (pts width &key (s 1d0) closed (clim -0.5d0) (slim -0.95d0) (simplify 1d0)) (let ((diag (-get-diagonals (to-vector (path-simplify pts simplify)) width clim slim closed))) (loop for d across diag collect (vec:on-line* s d)))) ; ----- STITCH ----- (defun stitch (lines) " randomly mix the hatches in lines according to where the lines intersect. this is somewhat inefficient " (let ((res (make-adjustable-vector))) (loop for i from 0 below (length lines) do (let ((ss (make-adjustable-vector)) (curr (aref lines i))) (vextend 0d0 ss) (vextend 1d0 ss) (loop for j from 0 below (length lines) do (multiple-value-bind (x s) (vec:segx curr (aref lines j)) (if x (vextend s ss)))) (setf ss (sort ss (if (< (rnd:rnd) 0.5d0) #'< #'>))) (loop for k from (rnd:rndi 2) below (length-1 ss) by 2 do (vextend (list (vec:on-line* (aref ss k) curr) (vec:on-line* (aref ss (1+ k)) curr)) res)))) res)) (defun mid-rad (pts &aux (pts* (to-list pts))) (let ((mid (vec:lmid pts*))) (values mid (loop for p in pts* maximize (vec:dst mid p))))) ; ----- HATCH ----- (defun -get-lines (n mid dst angle steps rnd) (let ((lines (make-adjustable-vector)) (slide (vec:scale (vec:cos-sin (- angle (* 0.5 PI))) dst)) (offset (vec:scale (vec:cos-sin angle) dst))) (loop for s in (funcall steps n) do (let ((xy (vec:on-line s (vec:add mid offset) (vec:sub mid offset)))) (vextend (funcall rnd (list (vec:add xy slide) (vec:sub xy slide))) lines))) lines)) (defun -line-hatch (line pts) (let ((ixs (make-adjustable-vector)) (res (make-adjustable-vector))) (loop for i from 0 below (length-1 pts) do (multiple-value-bind (x s) (vec:segx line (list (aref pts i) (aref pts (1+ i)))) (if x (vextend s ixs)))) (setf ixs (sort ixs #'<)) (loop for i from 0 below (length-1 ixs) by 2 do (vextend (list (vec:on-line* (aref ixs i) line) (vec:on-line* (aref ixs (1+ i)) line)) res)) res)) (defun hatch (pts &key (angles (list 0d0 (* 0.5d0 PI))) (steps (lambda (n) (math:linspace n 0d0 1d0))) (rs 0.25d0) (rnd #'identity)) " draw hatches at angles inside the area enclosed by the path in pts " (multiple-value-bind (mid dst) (mid-rad pts) (let ((res (make-adjustable-vector))) (loop for a in angles do (loop for line across (-get-lines (math:int (ceiling (* 2.40 rs dst))) mid (* 1.2d0 dst) a steps rnd) do (let ((hh (-line-hatch line pts))) (if (> (length hh) 0) (loop for h across (remove-if-not (lambda (h) (every #'identity h)) hh) do (vextend h res)))))) res))) ; ----- CONVEX SPLIT ----- (defun -get-splits (n pts &aux (n- (1- n))) (let ((len (loop for i from 0 below (1- n) and ii from 1 summing (vec:dst (aref pts i) (aref pts ii))))) (flet ((lenok (i) (< (rnd:rnd) (/ (vec:dst (aref pts i) (aref pts (1+ i))) len)))) (loop with a with b do (setf a (rnd:rndi n-) b (rnd:rndi n-)) until (and (not (= a b)) (funcall #'lenok a) (funcall #'lenok b)) finally (return (sort (list a b) #'<)))))) (defun -split-get-left (a b n) (let ((res (make-adjustable-vector))) (loop for i from 0 while (<= i a) do (vextend i res)) (vextend (list a (1+ a)) res) (vextend (list b (1+ b)) res) (loop for i from (1+ b) while (< i n) do (vextend (mod i (1- n)) res)) res)) (defun -split-get-right (a b n) (let ((res (make-adjustable-vector))) (loop for i from (1+ a) while (<= i b) do (vextend i res)) (vextend (list b (1+ b)) res) (vextend (list a (1+ a)) res) (loop for i from (1+ a) while (<= (mod i n) (1+ a)) do (vextend i res)) res)) (defun -split-ind-to-pts (pts inds s) (to-vector (loop for i across inds collect (if (eql (type-of i) 'cons) (destructuring-bind (a b) (mapcar (lambda (i*) (aref pts i*)) i) (vec:add a (vec:scale (vec:sub b a) s))) (aref pts i))))) (defun convex-split (pts &key (s 0.5d0) (lim 0d0) &aux (n (length pts))) (if (< (loop for i from 0 below (1- n) minimizing (vec:dst (aref pts i) (aref pts (1+ i)))) lim) (return-from convex-split (list pts nil))) (destructuring-bind (a b) (-get-splits n pts) (list (-split-ind-to-pts pts (-split-get-left a b n) s) (-split-ind-to-pts pts (-split-get-right a b n) s)))) ; ----- STIPPLE ----- ; more or less as suggested in ; https://gist.github.com/evanmiltenburg/dfd571f27372477487cb14f2bdf8b35c (defun -stipple-get-lengths (num-lines len) (let* ((lens (rnd:nrnd num-lines)) (s (dsum lens))) (loop for l in lens collect (/ (* l len) s)))) (defun stipple (num-lines len) " draw num-lines stipples between (0 1) the stipples will have a total length of len " (declare (double-float len)) (let ((lengths (-stipple-get-lengths num-lines len)) (gaps (-stipple-get-lengths (1- num-lines) (- 1d0 len)))) (loop with curr = (first lengths) with res = (to-adjustable-vector (list (list 0d0 curr)) :type 'vec:vec) for l of-type double-float in (cdr lengths) and g of-type double-float in gaps do (vextend (list curr (+ curr l)) res) (incf curr (+ l g)) finally (return res)))) ; ----- CURVATURE OFFSET EXPERIMENTAL ----- ;TODO: add first order estimations on boundary points? (defun ddxy (pts i &aux (n (length pts))) " calculate first and second derivatives of pts wrt t (the parametrisation variable). assumes that pts is parameterised from 0 to 1, and evenly sampled in t. " (declare (vector pts) (fixnum i)) (let ((s (/ 2d0 (math:dfloat (1- n)))) (p- (aref pts (1- i))) (p+ (aref pts (1+ i))) (p (aref pts i))) (declare (vec:vec p- p+ p) (double-float s)) (values (/ (- (vec::vec-x p+) (vec::vec-x p-)) s) (/ (- (vec::vec-y p+) (vec::vec-y p-)) s) (/ (+ (vec::vec-x p+) (vec::vec-x p-) (* -2d0 (vec::vec-x p))) #1=(expt s 2d0)) (/ (+ (vec::vec-y p+) (vec::vec-y p-) (* -2d0 (vec::vec-y p))) #1#)))) (defun kappa (pts i) " estimate curvature based on pts. " (declare (vector pts) (fixnum i)) (multiple-value-bind (dx dy ddx ddy) (ddxy pts i) (declare (double-float dx dy ddx ddy)) (/ (abs (- (* dx ddy) (* dy ddx))) (expt (+ (* dx dx) (* dy dy)) (the double-float (/ 3d0 2d0)))))) (defun -coffset (pts angles i) (let* ((va (aref angles (1- i))) (vb (aref angles i)) (ab (vec:angle vb))) (declare (vec:vec va vb) (double-float ab)) (list (kappa pts i) (aref pts i) (if (<= (the double-float (vec:cross va vb)) 0d0) (vec:cos-sin (+ ab PI5)) (vec:cos-sin (- ab PI5)))))) (defun -pad-offsets (pts) (let ((res (make-adjustable-vector :type 'vec:vec))) (vextend (aref pts 0) res) (loop for l across pts do (vextend l res)) (vextend (vector-last res) res) res)) ; TODO: closed version (defun curvature-offsets (pts &aux (pts* (ensure-vector pts))) " offset pts according to estimated curvature. pts must be evenly distributed " (declare (sequence pts) (vector pts*)) (-pad-offsets (to-vector (loop with angles of-type vector = (math:path-angles pts*) for i of-type fixnum from 1 below (length-1 pts*) collect (-coffset pts* angles i ))))) (defun -do-split-num (res rs curvefx curr c a b) (let* ((cw (funcall curvefx c)) (n (math:int (ceiling (* rs cw))))) (declare (double-float cw) (fixnum n)) (when (> (length res) 0) (vextend (list n cw a b) (vector-last res))) (when (not (= n curr)) (vextend (make-adjustable-vector :init (list (list n cw a b))) res)) n)) (defun -split-num (offsets rs curvefx) (loop with curr of-type fixnum = -1 with res = (make-adjustable-vector) for (c a b) across offsets do (setf curr (-do-split-num res rs curvefx curr c a b)) finally (return res))) ; TODO: closed? (defun curvature-offset-paths (pts &key (rs 0.1d0) (curvefx (lambda (c) (* 500d0 (expt c 0.6d0)))) (spacefx (lambda (n) (math:linspace n 0d0 1d0)))) " offset pts according to curvature. pts must be evenly sampled for this to work properly. experimental. " (declare (list pts) (double-float rs) (function curvefx spacefx)) (let ((res (make-adjustable-vector)) (offsets (math:curvature-offsets pts))) (loop for offset of-type vector across (-split-num offsets rs curvefx) do (loop with n of-type fixnum = (first (aref offset 0)) for s of-type double-float in (funcall spacefx n) do (vextend (list n (loop for (_ c a b) across offset collect (vec:on-line s a (vec:from a b c)) of-type vec:vec)) res))) res)) <|start_filename|>src/linear-path.lisp<|end_filename|> (in-package :lin-path) (defstruct path (n nil :type fixnum :read-only t) (closed nil :type boolean) (pts nil :type (simple-array double-float) :read-only t) (lens nil :type (simple-array double-float) :read-only t)) (defun -diff-scale (a b s) (declare (optimize (debug 0) speed (safety 0)) (double-float a b s)) (/ (- b a) s)) (defun -get-len (pts i &aux (ii (* 2 i))) (declare (optimize (debug 0) speed (safety 0)) (type (simple-array double-float) pts) (fixnum i ii)) (expt (+ (expt (- (aref pts (+ ii 2)) (aref pts ii)) 2d0) (expt (- (aref pts (+ ii 3)) (aref pts (+ ii 1))) 2d0)) 0.5d0)) (defun -set-path-lens (pts lens n) (declare (optimize (debug 0) speed (safety 0)) (type (simple-array double-float) pts lens) (fixnum n)) (loop with tot of-type double-float = (loop for i of-type fixnum from 0 below (1- n) sum (-get-len pts i) into tot of-type double-float do (setf (aref lens (1+ i)) tot) finally (return tot)) for i of-type fixnum from 1 below n do (setf (aref lens i) (/ (aref lens i) tot)))) (defun -find-seg-ind (lens f n) (declare (optimize (debug 0) speed (safety 0)) (type (simple-array double-float) lens) (fixnum n) (double-float f)) (loop with l of-type fixnum = 0 with r of-type fixnum = (- n 1) with mid of-type fixnum = 0 until (<= (aref lens mid) f (aref lens (1+ mid))) do (setf mid (floor (+ l r) 2)) (cond ((> f (aref lens mid)) (setf l (progn mid))) ((< f (aref lens mid)) (setf r (1+ mid)))) finally (return (the fixnum (1+ mid))))) (defun -calc-pos (pts lens n f) (declare (optimize (debug 0) speed (safety 0)) (type (simple-array double-float) pts lens) (fixnum n) (double-float f)) (let* ((i (-find-seg-ind lens f n)) (bi (* 2 i)) (ai (- bi 2)) (s (-diff-scale (aref lens (1- i)) f (- (aref lens i) (aref lens (1- i)))))) (declare (fixnum i ai bi) (double-float s)) (vec:vec (+ (aref pts ai) (* (- (aref pts bi) (aref pts ai)) s)) (+ (aref pts (1+ ai)) (* (- (aref pts (1+ bi)) (aref pts (1+ ai))) s))))) (defun pos (pth f) (declare (path pth) (double-float f)) (with-struct (path- lens pts n) pth (-calc-pos pts lens n (mod f 1d0)))) (defun pos* (pth ff) (declare (path pth) (list ff)) (with-struct (path- lens pts n) pth (mapcar (lambda (f) (declare (double-float f)) (-calc-pos pts lens n (mod f 1d0))) ff))) (defun rndpos (pth n) (rnd:with-rndspace (n 0d0 1d0 p :collect t) (pos pth p))) (defun make (pts &key closed &aux (n (if closed (+ (length pts) 1) (length pts)))) (declare (list pts)) (let ((p (make-array (* 2 n) :initial-element 0d0 :element-type 'double-float)) (l (make-array n :initial-element 0d0 :element-type 'double-float))) (loop for pt of-type vec:vec in pts and i of-type fixnum from 0 do (vec:sarr-set p i pt)) (when closed (vec:sarr-set p (1- n) (first pts))) (-set-path-lens p l n) (make-path :n n :pts p :lens l :closed closed))) <|start_filename|>utils/count.lisp<|end_filename|> (defun make-counter (&optional ll) (let ((c (make-hash-table :test #'equal))) (loop for a in ll do (counter-add c a)) c)) (defun counter-add (c a) (incf (gethash a c 0))) (defun counter-show (c) (loop with tot = (float (loop for n being the hash-values of c summing n)) for a being the hash-keys of c using (hash-value n) do (format t "~a: ~a, ~a~%" a n (/ (gethash a c) tot)))) <|start_filename|>examples/grid-bz-walk.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (load "../utils/grid") (defun mixed (x f) (declare (double-float x f)) (+ (random (* f x)) (- x (* 2.0d0 (random x))))) (defun rnd-dir () (nth (rnd:rndi 4) (list (list 0 -1) (list 0 1) (list -1 0) (list 1 0)))) (defmacro -swap (n m n* m*) (with-gensyms (h w) `(progn (setf ,n ,n*) (setf ,m ,m*) (destructuring-bind (,h ,w) (rnd-dir) (setf ,n* (+ ,n ,h)) (setf ,m* (+ ,m ,w)))))) (defun get-walker (grid) (let ((ngrid (length grid))) (let ((x 0.d0) (n (rnd:rndi ngrid)) (m (rnd:rndi ngrid))) (destructuring-bind (n* m*) (math:add (list n m) (rnd-dir)) (lambda (noise) (incf x (mixed noise 0.2d0)) (when (> x 1.0d0) (-swap n m n* m*)) (when (< x 0.0d0) (-swap n* m* n m)) (setf x (mod x 1.0d0)) (vec:on-line x (nth (mod m ngrid) (nth (mod n ngrid) grid)) (nth (mod m* ngrid) (nth (mod n* ngrid) grid)))))))) (defun main (size fn) (let ((itt 1000000) (ngrid 7) (nwalkers 4) (noise 0.00001d0) (grains 10) (edge 60d0) (sand (sandpaint:make size :fg (pigment:white 0.05) :bg (pigment:dark)))) (let* ((grid (get-grid (math:dfloat size) edge 5)) (walkers-a (math:nrep nwalkers (get-walker grid))) (walkers-b (math:nrep nwalkers (get-walker grid)))) (loop for i from 0 below itt do (print-every i 100000) (sandpaint:set-fg-color sand (pigment:hsv 0.51 1 1 0.05)) (sandpaint:bzspl-stroke sand (bzspl:make (loop for w in walkers-a collect (funcall w noise)) :closed t) grains) (sandpaint:set-fg-color sand (pigment:hsv 0.91 1 1 0.05)) (sandpaint:bzspl-stroke sand (bzspl:make (loop for w in walkers-b collect (funcall w noise)) :closed t) grains))) (sandpaint:save sand fn :gamma 1.5))) (time (main 2000 (second (cmd-args)))) <|start_filename|>examples/prm.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (defun main (size fn) (let* ((psvg (draw-svg:make* :width 1000d0 :height 1000d0 :stroke-width 1d0)) (left 150d0) (right 850d0) (n 7) (bs 50d0)) (vec:with-loop-grid ((math:linspace n left right) xy) (let* ((snk (snek:make :prms (snek:psvg-get-prm-types psvg))) (p (snek:add-prm! snk :type :bzspl :props 3d0))) (snek:add-verts! snk (rnd:nin-box 3 bs bs :xy xy) :p p) (loop repeat 10 do (snek:with (snk) (snek:add-vert? (rnd:in-box bs bs :xy xy) :p p)) (snek:prmr snk :p p)) (print (snek:prmr snk :p p :type :v)) (print (snek:prmr snk :p p :type :vv)) (print (snek:get-prm-props snk :p p)) (snek:prmr snk :p p :type :circs) (snek:prmr snk :p p :type :hatch :args (list :closed t :rs 0.2 :angles (rnd:nrnd 2))))) (draw-svg:save psvg fn))) (time (main 1000 (second (cmd-args)))) <|start_filename|>examples/asemic-2.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (defun get-make-chr (vert-num* char-rad scale) (lambda (p) (loop for xy in (rnd:nin-circ (rnd:rndi* vert-num*) (rnd:rnd char-rad)) collect (vec:add p (vec:mult xy scale))))) (defun get-make-word (make-chr char-num* char-rad) (lambda (p) (vec:with-xy (p x y) (let ((char-num (rnd:rndi* char-num*))) (let ((char-pos-x (math:linspace char-num x (+ x (* char-num char-rad))))) (list (first (reverse char-pos-x)) (loop for x* in char-pos-x collect (funcall make-chr (vec:vec x* y))))))))) (defun get-make-words (make-word space-width) (lambda (num-words p) (vec:with-xy (p x y) (let ((x* x)) (loop for i from 0 below num-words collect (destructuring-bind (last-x-pos word) (funcall make-word (vec:vec x* y)) (setf x* (+ space-width last-x-pos)) (flatten word))))))) (defun main (size fn) (let ((border 100d0) (char-rad 18d0) (line-num 20) (num-words 10) (char-scale (vec:vec 0.5d0 1.5d0)) (sand (sandpaint:make size :fg (pigment:black 0.009) :bg (pigment:white)))) (loop for y in (math:linspace line-num border (- size border)) do (format t "~a ~%" y) (let* ((drift (rnd:get-acc-circ-stp*)) (snk (snek:make)) (get-words (get-make-words (get-make-word (get-make-chr (list 2 4) char-rad char-scale) (list 3 10) (* 0.5 char-rad)) char-rad))) ;(snek:with (snk) ; (snek:itr-verts (snk v) ; (snek:move-vert? v (funcall drift 0.04d0)))) (loop for word in (funcall get-words num-words (vec:vec border y)) do (snek:add-path! snk word :g (snek:add-grp! snk))) (loop for i from 0 below 200 do (snek:with (snk) (snek:itr-verts (snk v) (snek:move-vert? v (rnd:in-circ 0.4d0)))) (snek:itr-grps (snk g :collect nil) (sandpaint:bzspl-stroke sand (bzspl:make (snek:get-grp-verts snk :g g)) 200))))) (sandpaint:save sand fn :gamma 1.5))) (time (main 1000 (second (cmd-args)))) <|start_filename|>src/zonemap.lisp<|end_filename|> (in-package :zmap) ; this macro exists so we can use the code externally in the same way ; regardless of whether we are using the parallel version of zmap (not yet ; implemented) (defmacro with* ((zw verts num-verts context-fxn) &body body) (with-gensyms (zw* verts* num-verts*) `(let ((,zw* ,zw)) (when ,zw* (let ((,num-verts* ,num-verts) (,verts* ,verts)) (declare (type (simple-array double-float) ,verts*) (fixnum ,num-verts*)) (funcall ,context-fxn (make ,verts* ,num-verts* ,zw*)))) (progn ,@body)))) ;TODO: test this ;http://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function ;https://github.com/perrygeo/pairing/blob/master/pairing/main.py ;(defun pair (zw i j &aux (x (truncate i zw)) (y (truncate j zw)) ) ; (declare (optimize (safety 0) speed (debug 0)) ; (fixnum x y) ; (double-float zw i j)) ; (truncate (/ (+ (* (+ x y) (+ x y 1)) y) 2))) ;(defun unpair (z) ; (declare (optimize (safety 0) speed (debug 0)) (fixnum z)) ; (let* ((w (truncate (/ (expt (1+ (+ (* 8 z) 1)) 2)))) ; (tt (/ (+ (expt w 2) w) 2))) ; (list (truncate #1=(- z tt)) ; (truncate (- w #1#))))) (defun -xy-to-zone (zwidth x y) (declare (double-float zwidth x y)) (values (the fixnum (floor x zwidth)) (the fixnum (floor y zwidth)))) (defstruct (zmap (:constructor -make-zmap)) (zwidth nil :type double-float :read-only t) (num-verts nil :type fixnum :read-only t) (zone-to-verts nil :type hash-table :read-only t)) (defun make (verts num-verts zwidth) (declare (optimize (safety 0) speed (debug 0)) (double-float zwidth) (fixnum num-verts) (type (simple-array double-float) verts)) (let ((zone-to-verts (make-hash-table :test #'equal))) (loop for v of-type fixnum from 0 below num-verts do ; add v to zone (let ((z (list (floor (aref verts #1=(* 2 v)) zwidth) (floor (aref verts (1+ #1#)) zwidth)))) (declare (list z)) (multiple-value-bind (vals exists) (gethash z zone-to-verts) (when (not exists) (setf vals (make-adjustable-vector :type 'fixnum) (gethash z zone-to-verts) vals)) (vextend v vals)))) (-make-zmap :zwidth zwidth :num-verts num-verts :zone-to-verts zone-to-verts))) (defmacro with-verts-in-rad ((zm verts xy rad v) &body body) (with-gensyms (rad2 zm* zwidth zone-to-verts xy* za zai zb vals verts* exists i j xx yy) `(let* ((,rad2 (expt ,rad 2d0)) (,verts* ,verts) (,xy* ,xy) (,xx (vec::vec-x ,xy*)) (,yy (vec::vec-y ,xy*)) (,zm* ,zm) (,zwidth (zmap-zwidth ,zm*)) (,zone-to-verts (zmap-zone-to-verts ,zm*))) (declare (double-float ,rad2 ,zwidth ,xx ,yy) (type (simple-array double-float) ,verts*) (hash-table ,zone-to-verts) (vec:vec ,xy*)) (multiple-value-bind (,za ,zb) (-xy-to-zone ,zwidth ,xx ,yy) (declare (fixnum ,za ,zb)) (loop for ,i of-type fixnum from -1 below 2 do (loop with ,zai of-type fixnum = (+ ,za ,i) for ,j of-type fixnum from -1 below 2 do (multiple-value-bind (,vals ,exists) (gethash (list ,zai (+ ,j ,zb)) ,zone-to-verts) (when ,exists (loop for ,v of-type fixnum across ,vals if (< (+ (expt (- ,xx (aref ,verts #2=(* 2 ,v))) 2d0) (expt (- ,yy (aref ,verts (1+ #2#))) 2d0)) ,rad2) do (progn ,@body)))))))))) (defun verts-in-rad (zm verts xy rad) (declare (optimize (safety 0) speed (debug 0)) (type (simple-array double-float) verts) (zmap zm) (vec:vec xy) (double-float rad)) (let ((inds (make-adjustable-vector :type 'fixnum))) (declare (vector inds)) (with-verts-in-rad (zm verts xy rad v) (vextend v inds)) inds)) <|start_filename|>examples/zones.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (defun main (size fn) (let ((mid (math:dfloat (half size))) (noise (+ 0.015d0 (rnd:rnd 0.03d0))) (itt 5000) (snk (snek:make)) (grains 3) (sand (sandpaint:make size :fg (pigment:black 0.01) :bg (pigment:white)))) (math:nrep 1000 (snek:add-vert! snk (rnd:in-box 500d0 500d0 :xy (vec:vec mid mid)))) (loop for k from 1 to itt do (print-every k 100) (snek:with (snk :zwidth 40.0d0) (snek:itr-verts (snk v) (snek:move-vert? v (rnd:in-circ 0.7d0)) (let ((verts (snek:verts-in-rad snk (snek:get-vert snk v) 40.0d0))) (if (> (length verts) 0) (snek:add-edge? v (rnd:rndget verts)))))) (snek:draw-edges snk sand grains)) (sandpaint:pixel-hack sand) (sandpaint:save sand fn))) (time (main 1000 (second (cmd-args)))) <|start_filename|>test/speed-rnd.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (setf *print-pretty* t) (rnd:set-rnd-state 1) (defun main () (let ((num 1000000) (rep 1000)) (format t "rndspace:~%") (time (loop repeat rep do (rnd:rndspace num 0d0 1d0))) (format t "with-rndspace:~%") (time (loop repeat rep do (rnd:with-rndspace (num 0d0 1d0 v) v))))) ;(require :sb-sprof) ;(sb-sprof:with-profiling (:max-samples 200000 ; :mode :cpu ; ;:mode :alloc ; ;:mode :time ; :report :graph) ; (main)) (main) <|start_filename|>examples/spline-script-svg.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (load "../utils/text") (load "../utils/text-sample") (load "../utils/spline-script") (load "../utils/state") (defvar *alphabet* "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.,?-—:'") (defun scale () (if (< (rnd:rnd) 0.15) (vec:vec 1.1d0 3.9d0) (vec:vec 1d0 1d0))) (defun swap (l) (let* ((ll (loop for k in l collect k)) (n (length l)) (a (rnd:rndi n)) (b (rnd:rndi n))) (setf (nth a ll) (nth b l) (nth b ll) (nth a l)) ll)) (defun shape (n bx by) ;(rnd:nin-box n bx by) (vec:lmult* (rnd:nin-circ n 1d0) (vec:vec bx by))) (defun draw (snk psvg) (let ((state-gen (get-walker-state-gen (lambda () (rnd:get-acc-circ-stp*)))) (drift (vec:scale (vec:sin-cos -0.1d0) 0.009d0))) (loop for p in (math:linspace 200 0d0 1d0) and i from 0 do (snek:with (snk) (snek:itr-verts (snk v) ;(snek:move-vert? v (funcall state-gen v 0.000008d0)) (snek:move-vert? v drift) (snek:move-vert? v (rnd:in-circ 0.1d0))))) (snek:itr-grps (snk g :collect nil) (let ((pts (snek:get-grp-verts snk :g g))) (when (> (length pts) 2) (draw-svg:bzspl psvg pts)))))) (defun main (size fn) (let ((trbl (list 70d0 950d0 950d0 55d0)) (bbox (vec:vec 20d0 25d0)) (spacebox (vec:vec 10d0 25d0))) (labels ((get-bbox-fxn () (let ((bbox (vec:mult bbox (scale)))) (vec:with-xy ((vec:scale bbox 0.5d0) bx by) (lambda (n) (mapcar (lambda (v) (vec:rot v (* PI 0.2d0))) (shape n bx by)))))) (estimate-nc-ncn-fxn (bbox-fxn) (let* ((samples (funcall bbox-fxn 1000)) (mid (vec:lmid samples)) (area (apply #'max (mapcar (lambda (a) (vec:dst a mid)) samples)))) (if (< area 30d0) (list area 4 1) (list area 7 1)))) (sort-centroids-fxn () (let ((f (if (< (rnd:rnd)) #'< #'>)) (rot (rnd:rnd PII))) (lambda (centroids) (let ((res (sort (loop for c in centroids collect (list (+ rot (apply #'atan (reverse (vec:tolist c)))) c)) f :key #'first))) (if (< (rnd:rnd) 0.6) (swap res) res)))))) (let ((alphabet (show-alphabet (get-alphabet *alphabet* :get-bbox-fxn #'get-bbox-fxn :nc-ncn-fxn #'estimate-nc-ncn-fxn :sort-fxn #'sort-centroids-fxn :min-dst 5d0))) (words (remove-if (lambda (x) (= 0 (second x))) (apply #'append (get-words* *alice*))) ) (wind 0)) (block draw-loop (loop for k from 0 do (let ((snk (snek:make)) (psvg (draw-svg:make :layout :a4-landscape)) (txt (subseq words wind))) (incf wind (aif (do-write snk alphabet spacebox trbl txt) it (return-from draw-loop))) (draw snk psvg) (draw-svg:save psvg (append-postfix fn (format nil "-~3,'0d" k)))))))))) (time (main 1000 (second (cmd-args)))) <|start_filename|>utils/spline-script.lisp<|end_filename|> (defstruct spline-glyph (name nil :type character :read-only t) (area 0d0 :type double-float :read-only t) (nc 4 :type fixnum :read-only t) (ncn 1 :type fixnum :read-only t) (min-dst 0d0 :type double-float :read-only t) (centroids nil :type list) (bbox-fxn nil :type function) (sort-fxn nil :type function) (fxn (lambda (x) nil) :type function)) (defun test-centroids (counts nc ncn) (loop for i of-type fixnum from 0 below nc always (multiple-value-bind (val exists) (gethash i counts) (and exists (>= val ncn))))) (defun get-dst (centroids cand) (first (sort (loop for c of-type vec:vec in centroids and i of-type fixnum from 0 collect (list i (vec:dst cand c))) #'< :key #'second))) (defun get-centroids (bbox-fxn dst nc) (let ((hits 1) (centroids (funcall bbox-fxn 1))) (loop for i of-type fixnum from 0 do (let ((cand (first (funcall bbox-fxn 1)))) (if (every (lambda (d) (> d dst)) (vec:ldst* centroids cand)) (progn (setf centroids (append (list cand) centroids)) (incf hits)))) until (>= hits nc)) centroids)) (defun -do-test-cand (gl centroid-pts counts cand) (destructuring-bind (c dst) (get-dst (spline-glyph-centroids gl) cand) (multiple-value-bind (val exists) (gethash c counts) (cond ((and exists (< val (spline-glyph-ncn gl))) (setf (gethash c centroid-pts) (append (list cand) (gethash c centroid-pts))) (incf (gethash c counts))) ((not exists) (setf (gethash c centroid-pts) (list cand) (gethash c counts) 1)))))) ;else: exists and has too many pts (defun make-glyph (name bbox-fxn nc-ncn-fxn sort-fxn &key (min-dst 0d0)) (destructuring-bind (area nc ncn) (funcall nc-ncn-fxn bbox-fxn) (let ((gl (make-spline-glyph :name name :area area :nc nc :ncn ncn :min-dst min-dst :centroids (mapcar #'second (funcall sort-fxn (get-centroids bbox-fxn min-dst nc))) :bbox-fxn bbox-fxn :sort-fxn sort-fxn))) (setf (spline-glyph-fxn gl) (lambda () (let ((counts (make-hash-table :test #'equal)) (centroid-pts (make-hash-table :test #'equal)) ) (loop for i of-type fixnum from 0 do (-do-test-cand gl centroid-pts counts (first (funcall (spline-glyph-bbox-fxn gl) 1))) until (test-centroids counts nc ncn)) (apply #'append (loop for i of-type fixnum from 0 below nc collect (gethash i centroid-pts)))))) gl))) (defun get-alphabet (letters &key get-bbox-fxn nc-ncn-fxn sort-fxn (min-dst 0d0)) (let ((alphabet (make-hash-table :test #'equal))) (loop for c across letters do (setf (gethash c alphabet) (make-glyph c (funcall get-bbox-fxn) nc-ncn-fxn (funcall sort-fxn) :min-dst min-dst))) alphabet)) (defun show-alphabet (alphabet) (format t "~%") (loop for c being the hash-keys in alphabet do (let ((a (gethash c alphabet))) (format t "char: ~a area: ~,1f nc: ~a ncn: ~a min-dst: ~,1f~%" (spline-glyph-name a) (spline-glyph-area a) (spline-glyph-nc a) (spline-glyph-ncn a) (spline-glyph-min-dst a)))) (format t "~%") alphabet) (defun do-write (snk alphabet bbox trbl words &key (tweak-fxn)) (destructuring-bind (top right bottom left) trbl (vec:with-xy ((vec:scale bbox 2d0) bx by) (let ((g nil) (cursor (vec:vec left top))) (block outer (loop for (word wl) in words and i from 0 do (if (> (+ (vec::vec-x cursor) (* (+ 1 wl) bx)) right) (progn (format t "~%") (setf cursor (vec:vec left (+ by (vec::vec-y cursor)))))) (when (> (vec::vec-y cursor) bottom) (return-from outer i)) (setf g (snek:add-grp! snk)) (loop for c across word do (format t "~a" c) (aif (gethash c alphabet) (snek:add-path! snk (vec:ladd* (funcall (spline-glyph-fxn it)) cursor) :g g)) (setf cursor (vec:add cursor (vec:vec bx 0d0)))) (setf cursor (vec:add cursor (vec:vec bx 0d0))) (format t " "))))))) <|start_filename|>src/draw-tile-svg.lisp<|end_filename|> (in-package :draw-tile-svg) ; export svg drawings across tiled sheets of paper. ; this functinality is experimental and has limited features. (defstruct draw-tile-svg (nxny nil :type list :read-only t) (stroke-width nil :type double-float :read-only t) (dw 0d0 :type double-float :read-only t) (dh 0d0 :type double-float :read-only t) (overview nil :read-only t) (grid nil :read-only t) (paper-id-fx nil :type function :read-only t) (paper-fx nil :type function :read-only t) (papers nil :read-only t)) (defun -make-papers (nxny stroke-width) (destructuring-bind (nx ny) nxny (loop with papers = (make-hash-table :test #'equal) for x from 0 below nx do (loop for y from 0 below ny do (setf (gethash (list x y) papers) (draw-svg:make :layout :a3-landscape :stroke-width stroke-width))) finally (return papers)))) (defun -make-grid (nxny dw dh) (destructuring-bind (nx ny) nxny (let ((res (make-adjustable-vector))) (vextend* (loop for x in (math:linspace (1+ nx) 0d0 dw) collect (list (vec:vec x 0d0) (vec:vec x dh))) res) (vextend* (loop for y in (math:linspace (1+ ny) 0d0 dh) collect (list (vec:vec 0d0 y) (vec:vec dw y))) res ) res))) (defun -make-paper-id-fx (dw dh nxny) (destructuring-bind (nx ny) nxny (lambda (segment) (vec:with-xy ((vec:div (vec:lmid segment) (vec:vec dw dh)) x y) (list (floor (* x nx)) (floor (* y ny))))))) (defun -make-paper-fx (rpw rph dw dh) (lambda (pt paperid) (destructuring-bind (idx idy) paperid (vec:with-xy (pt x y) (vec:vec (* (/ (- x (* idx rpw)) rpw) dw) (* (/ (- y (* idy rph)) rph) dh)))))) (defun make (&key (nxny (list 2 2)) (stroke-width 1.1d0)) (let* ((overview (draw-svg:make :layout :a3-landscape :stroke-width stroke-width)) (dw (draw-svg::draw-svg-width overview)) (dh (draw-svg::draw-svg-height overview)) (rpw (/ dw (first nxny))) (rph (/ dh (second nxny)))) (make-draw-tile-svg :nxny nxny :stroke-width stroke-width :overview overview :dw dw :dh dh :paper-id-fx (-make-paper-id-fx dw dh nxny) :paper-fx (-make-paper-fx rpw rph dw dh) :grid (-make-grid nxny dw dh) :papers (-make-papers nxny stroke-width)))) (defun -path-segments (pts) (loop with res = (make-adjustable-vector) for i from 0 below (length-1 pts) collect (vextend (list (aref pts i) (aref pts (1+ i))) res) finally (return res))) (defun -make-linear-ratios (segment grid) (let ((res (make-adjustable-vector))) (vextend* (list 0d0 1d0) res) (loop for g across grid do (multiple-value-bind (x p) (vec:segx segment g) (when x (vextend p res)))) (sort res #'<))) (defun -split-segment (segment grid) (loop with res = (make-adjustable-vector) for s across (-make-linear-ratios segment grid) do (vextend (vec:on-line* s segment) res) finally (return res))) (defun -split-path-segments-on-grid (grid pts) (loop with res = (make-adjustable-vector) for segment across pts do (loop with subseg = (-split-segment segment grid) for i from 0 below (1- (length subseg)) do (vextend (list (aref subseg i) (aref subseg (1+ i))) res)) finally (return res))) (defun -append-paper-id (paper-id-fx segments) (loop for segment across segments collect (list segment (funcall paper-id-fx segment)))) (defun -inside (paperid nxny) (destructuring-bind (nx ny) nxny (destructuring-bind (idx idy) paperid (and (< -1 idx nx) (< -1 idy ny))))) (defun path (msvg pts &key sw (stroke "black") closed &aux (pts* (ensure-vector pts :fx #'to-adjustable-vector))) " draw path " (declare (draw-tile-svg msvg) (list pts)) (with-struct (draw-tile-svg- paper-id-fx paper-fx grid papers overview nxny) msvg (draw-svg:path overview pts :sw sw :stroke stroke :closed closed) (when closed (vextend (aref pts* 0) pts*)) (loop for (segment paperid) in (-append-paper-id paper-id-fx (-split-path-segments-on-grid grid (-path-segments pts*))) if (-inside paperid nxny) do (draw-svg:path (gethash paperid papers) (mapcar (lambda (pt) (funcall paper-fx pt paperid)) segment) :sw sw :stroke stroke)))) (defun lstipple (msvg line &key (len 0.5d0) (num 10) sw (stroke "black")) " draw num stipples along line. the total length of the stipples will be len note that len is a ratio of the full length of line (a number between 0 and 1) " (declare (draw-tile-svg msvg) (list line) (double-float len)) (let ((stip (math:stipple num len))) (loop for (a b) across stip do (path msvg (list (vec:on-line* a line) (vec:on-line* b line)) :sw sw :stroke stroke)))) (defun lstipple* (msvg line &key (len 100d0) (num 10) sw (stroke "black")) " draw num stipples along line. the length of the stipples is limited to the (absolute) length len. if the length of the line is shorter than len, a single line (no stipples) will be drawn. " (declare (draw-tile-svg msvg) (list line) (double-float len)) (let ((d (vec:dst* line))) (if (<= d len) (path msvg line :sw sw :stroke stroke) (lstipple msvg line :len (/ len d) :num num :sw sw :stroke stroke)))) (defun rstipple (msvg n pts &key sw (stroke "black") closed) " draw n stipples along path pts WARN: this is incomplete and will probably not perform as expected " (declare (draw-tile-svg msvg) (list pts) (fixnum n)) (loop with all = (to-vector (lin-path:pos* (lin-path:make pts :closed closed) (sort (rnd:nrnd (* 2 n)) (rnd:either #'< #'>)))) for i from 0 below (* 2 n) by 2 do (path msvg (list (aref all i) (aref all (1+ i))) :sw sw :stroke stroke))) (defun bzspl (msvg pts &key sw (stroke "black") closed) (declare (draw-tile-svg msvg)) (path msvg (bzspl:adaptive-pos (bzspl:make pts :closed closed)) :sw sw :stroke stroke)) (defun save (msvg fn) (declare (draw-tile-svg msvg)) (with-struct (draw-tile-svg- papers overview grid) msvg (draw-svg:show-crop overview) (loop for path across grid do (draw-svg:path overview path :stroke "blue")) (loop for (nx ny) being the hash-keys of papers using (hash-value paper) do (draw-svg:show-crop paper) (draw-svg:save paper (ensure-filename fn (format nil "-part-~ax~a" nx ny) t))) (draw-svg:save overview (append-postfix (ensure-filename fn "" t) "-overview")))) <|start_filename|>src/pigment.lisp<|end_filename|> (in-package :pigment) """ Colors are stored internally with premultiplied alpha. Package was renamed from 'color' because of a package name collision. """ (defmacro with ((c r g b a) &body body) (with-gensyms (c*) `(let* ((,c* ,c) (,r (rgba-r ,c*)) (,g (rgba-g ,c*)) (,b (rgba-b ,c*)) (,a (rgba-a ,c*))) (declare (double-float ,r ,g ,b ,a)) (progn ,@body)))) (defstruct (rgba (:constructor -make-rgba)) (r 0d0 :type double-float :read-only t) (g 0d0 :type double-float :read-only t) (b 0d0 :type double-float :read-only t) (a 1d0 :type double-float :read-only t)) (defun make-rgba (r g b &optional (a 1d0) &aux (r* (math:dfloat r)) (g* (math:dfloat g)) (b* (math:dfloat b)) (a* (math:dfloat a))) (-make-rgba :r (* a* r*) :g (* a* g*) :b (* a* b*) :a a*)) (defun show (c) (declare (rgba c)) (let ((a (rgba-a c))) (format nil "(r ~A g ~A b ~A a ~A" (/ (rgba-r c) a) (/ (rgba-g c) a) (/ (rgba-b c) a) a)) c) (defun to-list (c) (declare (rgba c)) (let ((a (rgba-a c))) (list (/ (rgba-r c) a) (/ (rgba-g c) a) (/ (rgba-b c) a) a))) (defun to-list* (c) (declare (rgba c)) (list (rgba-r c) (rgba-g c) (rgba-b c) (rgba-a c))) (defun white (&optional (a 1d0)) (make-rgba 1d0 1d0 1d0 a)) (defun black (&optional (a 1d0)) (make-rgba 0.0d0 0.0d0 0.0d0 a)) (defun mdark (&optional (a 1d0)) (make-rgba 0.3d0 0.3d0 0.3d0 a)) (defun dark (&optional (a 1d0)) (make-rgba 0.2d0 0.2d0 0.2d0 a)) (defun vdark (&optional (a 1d0)) (make-rgba 0.1d0 0.1d0 0.1d0 a)) (defun gray (v &optional (a 1d0)) (make-rgba v v v a)) (defun transparent (&optional (v 1d0)) (make-rgba v v v 0d0)) (defun rgb (r g b &optional (a 1d0)) (make-rgba r g b a)) (defun -hex (d) (declare (double-float d)) (let ((res (format nil "~X" (min 255 (max 0 (floor (* d 256))))))) (if (< (length res) 2) (concatenate 'string "0" res) res))) (defun to-hex (c) (declare (rgba c)) (destructuring-bind (r g b a) (to-list c) (values (apply #'concatenate 'string (list "#" (-hex r) (-hex g) (-hex b))) a))) (defun cmyk (c m y k &optional (a 1d0)) (let ((ik (- 1d0 (math:dfloat k)))) (make-rgba (* (- 1d0 (math:dfloat c)) ik) (* (- 1d0 (math:dfloat m)) ik) (* (- 1d0 (math:dfloat y)) ik) a))) (defun hsv (h s v &optional (a 1d0)) (destructuring-bind (h s v) (math:dfloat* (list h s v)) (let* ((c (* v s)) (x (* c (- 1d0 (abs (- (mod (* 6d0 h) 2d0) 1d0))))) (m (- v c))) (destructuring-bind (r g b) (math:dadd (list m m m) (case (floor (mod (* h 6d0) 6d0)) (0 (list c x 0d0)) (1 (list x c 0d0)) (2 (list 0d0 c x)) (3 (list 0d0 x c)) (4 (list x 0d0 c)) (5 (list c 0d0 x)))) (make-rgba r g b a))))) <|start_filename|>test/speed-snek-zmap.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (setf *print-pretty* t) (rnd:set-rnd-state 1) (defun init-snek (n mid) (let ((snk (snek:make :max-verts 5000000 :grp-size 500000))) (math:nrep n (snek:add-vert! snk (rnd:in-box mid mid :xy (vec:vec mid)))) snk)) (defun main () (let* ((itt 10000) (size 1000) (num 20000) (farl 100.d0) (snk (init-snek num (* 0.5d0 size)))) ;(snek:with (snk :zwidth farl) ; (print (snek:verts-in-rad snk (nrep 2 (rnd:rnd size)) farl))) (time (loop for i from 0 below itt do (print-every i 2000) (snek:with (snk :zwidth farl) (let ((v (rnd:rndi num))) (map nil (lambda (w) (snek:with-dx (snk (list v w) dx d) (list dx d))) (snek:verts-in-rad snk (snek:get-vert snk v) farl)))))) (time (loop for i from 0 below itt do (print-every i 2000) (snek:with (snk :zwidth farl) (let ((v (rnd:rndi num))) (snek:with-verts-in-rad (snk (snek:get-vert snk v) farl w) (snek:with-dx (snk (list v w) dx d) (list dx d))))))) (format t "verts: ~a~%" (snek::snek-num-verts snk)))) (require :sb-sprof) (sb-sprof:with-profiling (:max-samples 200000 :mode :cpu ;:mode :alloc ;:mode :time :report :graph) (main)) <|start_filename|>utils/nbody.lisp<|end_filename|> (defstruct body (xy nil :type vec:vec :read-only t) (v nil :type vec:vec :read-only t) (m 1d0 :type double-float :read-only t)) (defun init-square (rad n v) (loop for vel in (rnd:nin-circ n v) ;(vec:polygon n v) for i from 0 for p in (lin-path:pos* (lin-path:make (vec:rect rad rad) :closed t) (math:daddmod* (math:linspace n 0d0 1d0 :end nil) (rnd:rnd) 1d0)) collect (make-adjustable-vector :init (list (make-body :xy p :v (rnd:in-circ (* 0.5 v) :xy vel) :m (if (= i 0) 3d0 1d0)))))) ; NOTE ; i don't think the below force calculation uses the correct formula. ; the correct equation is probably: ; s* = (* (/ (expt d2 1.5d0)) s (body-m att)) ; so that we normalise the direction vectors and divide by distance squared. ; however, the current version yields nicer results. ; also, we only multiply by attracting mass (M/bj) because ; F = ma = const * mM / r² ; means that ; a = const * M / r² ; so that the the affected mass is not present in the equation. (defun force (curr att s) (let* ((cxy (body-xy curr)) (axy (body-xy att)) (dx (- (vec::vec-x axy) (vec::vec-x cxy))) (dy (- (vec::vec-y axy) (vec::vec-y cxy))) (d2 (+ (* dx dx) (* dy dy)))) ; this is not entirely correct, but it causes the force to be zero when ; curr == att. it also eliminates other div0 errors. (if (<= d2 0.0000001d0) vec:*zero* (let ((s* (* (/ (sqrt d2)) s (body-m att)))) (vec:vec (* dx s*) (* dy s*)))))) (defun dostep (bodies body s) (let* ((curr (vector-last body)) (acc (vec:sum (loop for b in bodies collect (force curr (vector-last b) s)))) (new-vel (vec:add (vec:scale (body-v curr) 0.999d0) acc))) (make-body :xy (vec:add (body-xy curr) new-vel) :v new-vel :m (body-m curr)))) (defun all-steps (bodies s) (loop for body in bodies collect (dostep bodies body s) into new-steps finally (loop for new in new-steps and body in bodies do (vextend new body)))) <|start_filename|>examples/path-step.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (defun main (size fn) (let ((grains 60) (itt 300000) (lsa (rnd:get-acc-lin-stp)) (lsb (rnd:get-acc-lin-stp)) (lsc (rnd:get-acc-lin-stp)) (noise 0.00000002d0) (snk (snek:make)) (points-a (close-path (rnd:nin-box 3 1500d0 1500d0 :xy (vec:vec 1000d0 1000d0)))) (points-b (close-path (rnd:nin-box 3 1500d0 1500d0 :xy (vec:vec 1000d0 1000d0)))) (points-c (close-path (rnd:nin-box 3 1500d0 1500d0 :xy (vec:vec 1000d0 1000d0)))) (sand (sandpaint:make size :fg (pigment:black 0.01d0) :bg (pigment:white)))) (let ((v1 (snek:add-vert! snk (vec:vec 0d0 0d0))) (v2 (snek:add-vert! snk (vec:vec 0d0 0d0))) (v3 (snek:add-vert! snk (vec:vec 0d0 0d0))) (path-a (lin-path:make points-a)) (path-b (lin-path:make points-b)) (path-c (lin-path:make points-c))) (snek:add-edge! snk v1 v2) (snek:add-edge! snk v2 v3) (snek:add-edge! snk v3 v1) (loop for i from 0 to itt do (snek:with (snk) ;(lin-path:move path-a (rnd:nin-circ 4 0.3d0) t) ;(lin-path:move path-b (rnd:nin-circ 4 0.3d0) t) ;(lin-path:move path-c (rnd:nin-circ 4 0.1d0) t) (snek:move-vert? v1 (lin-path:pos path-a (funcall lsa noise)) :rel nil) (snek:move-vert? v2 (lin-path:pos path-b (funcall lsb noise)) :rel nil) (snek:move-vert? v3 (lin-path:pos path-c (funcall lsc noise)) :rel nil)) (snek:draw-edges snk sand grains)) ;(sandpaint:set-fg-color sand (list 1 0 0 0.01)) ;(sandpaint:pix sand (lin-path:pos* path-a (rnd:rndspace 10 0d0 1d0))) ;(sandpaint:pix sand (lin-path:pos* path-c (rnd:rndspace 10 0d0 1d0))) (sandpaint:pixel-hack sand) (sandpaint:save sand fn :gamma 1.3)))) (time (main 2000 (second (cmd-args)))) <|start_filename|>utils/force.lisp<|end_filename|> (defun -get-force-alterations (u v f) (list (snek:move-vert? v f) (snek:move-vert? u (vec:scale f -1.0d0)))) (defmacro force? (snk v1 v2 r) " creates relative movement (move-vert alteration) between verts v1 and v2. " (with-gensyms (vname v1name v2name rname) `(let ((,vname (snek::snek-verts ,snk)) (,v1name ,v1) (,v2name ,v2) (,rname (math:dfloat ,r))) (-get-force-alterations ,v1name ,v2name (vec:scale (vec:nsub (vec:sarr-get ,vname ,v1name) (vec:sarr-get ,vname ,v2name)) ,rname))))) <|start_filename|>test/pix-overlap.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (rnd:set-rnd-state 1) (defun main (size) (let ((snk (snek:make)) (sand (sandpaint:make size :fg (pigment:white 1d0) :bg (pigment:gray 0.1d0)))) (sandpaint:pix-overlap sand (list (vec:vec 101.1d0 101.1d0) (vec:vec 105.0d0 101.1d0) (vec:vec 111.7d0 101.1d0) (vec:vec 101.1d0 105.0d0) (vec:vec 105.0d0 105.0d0) (vec:vec 111.7d0 105.0d0) (vec:vec 101.1d0 111.7d0) (vec:vec 105.0d0 111.7d0) (vec:vec 111.7d0 111.7d0))) (sandpaint:set-fg-color sand (pigment:rgb 0d0 1d0 0d0)) (sandpaint:pix-overlap sand (list (vec:vec 151.7d0 151.7d0) (vec:vec 155.0d0 151.7d0) (vec:vec 161.1d0 151.7d0) (vec:vec 151.7d0 155.0d0) (vec:vec 155.0d0 155.0d0) (vec:vec 161.1d0 155.0d0) (vec:vec 151.7d0 161.1d0) (vec:vec 155.0d0 161.1d0) (vec:vec 161.1d0 161.1d0))) (loop for v in (rnd:nin-box 5000000 50d0 50d0 :xy (vec:vec 240d0)) do (sandpaint:set-fg-color sand (pigment:rgb (rnd:rnd) (rnd:rnd) (rnd:rnd))) (sandpaint:pix-overlap* sand v)) (loop for v in (rnd:nin-box 5000000 50d0 50d0 :xy (vec:vec 240d0)) do (sandpaint:set-fg-color sand (pigment:rgb (rnd:rnd) (rnd:rnd) (rnd:rnd))) (sandpaint:pix-overlap* sand v)) (sandpaint:save sand "pix-overlap"))) (require :sb-sprof) (sb-sprof:with-profiling (:max-samples 200000 :mode :cpu ;:mode :alloc ;:mode :time :report :graph) (main 300)) ;(time (main 300)) <|start_filename|>src/various.lisp<|end_filename|> (abbrev vextend vector-push-extend) (defconstant PII (the double-float (* PI 2d0))) (defconstant PI5 (the double-float (* PI 0.5d0))) (declaim (type double-float PII PI5)) ;http://cl-cookbook.sourceforge.net/os.html (defun cmd-args () (or #+SBCL *posix-argv* #+LISPWORKS system:*line-arguments-list* #+CMU extensions:*command-line-words* nil)) (defun append-postfix (fn postfix) (declare (string fn postfix)) (concatenate 'string fn postfix)) (defun append-number (fn i) (declare (string fn) (fixnum i)) (format nil "~a-~8,'0d" fn i)) (defun ensure-filename (fn &optional (postfix "") (silent nil)) (let ((fn* (append-postfix (if fn fn "tmp") postfix))) (declare (string fn*)) (format (not silent) "~%file: ~a~%~%" fn*) fn*)) (defun print-every (i n) (declare (fixnum i n)) (when (= 0 (mod i n)) (format t "~%itt: ~a~%" i))) (defun string-list-concat (l) (declare (list l)) (format nil "~{~a~}" l)) (defun numshow (a) (declare (double-float a)) (if (< 1d-6 (the double-float (abs a)) 1d6) (format nil "~,6f " a) (format nil "~,1e " a))) (defun exec-with-args (fxn args &optional ea) (declare (function fxn) (list args ea)) (apply fxn (if ea (append args ea) args))) (defun dhalf (l) (declare (double-float l)) (coerce (* l 0.5d0) 'double-float)) (defun half (l) (declare (number l)) (coerce (/ (coerce l 'double-float) 2d0) 'double-float)) (defun length-1 (a) (declare (sequence a)) (1- (the fixnum (length a)))) (defun vector-last (a) (declare (vector a)) (aref a (the fixnum (length-1 a)))) (defun vector-first (a) (declare (vector a)) (aref a 0)) (defun -vector-add (a vv) (declare (vector a) (sequence vv)) (if (eql (type-of vv) 'cons) (loop for v in vv do (vextend v a)) (loop for v across vv do (vextend v a)))) (defun make-adjustable-vector (&key init (type t) (size 256)) (let ((res (if init (make-array (length init) :fill-pointer 0 :initial-contents init :element-type type :adjustable t) (make-array size :fill-pointer 0 :element-type type :adjustable t)))) (when init (-vector-add res init)) res)) (defun to-vector (init) (declare (list init)) (make-array (length init) :initial-contents init)) (defun ensure-vector (o &key (fx #'to-vector)) (declare (sequence o) (function fx)) (if (equal (type-of o) 'cons) (funcall fx o) o)) ; TODO: array push macro? (defun vextend* (xx arr) (declare (sequence xx) (vector arr)) (if (eql (type-of xx) 'cons) (loop for x in xx do (vextend x arr)) (loop for x across xx do (vextend x arr)))) (defun to-adjustable-vector (init &key (type t)) (declare (sequence init)) (make-array (length init) :fill-pointer (length init) :initial-contents init :element-type type :adjustable t)) (defun make-generic-hash-table (&key init (test #'equal)) (declare (sequence init) (function test)) (if (< (length init) 1) (make-hash-table :test test) (if (equal (type-of init) 'cons) (loop with res = (make-hash-table :test test) for (k v) in init do (setf (gethash k res) v) finally (return res)) (loop with res = (make-hash-table :test test) for (k v) across init do (setf (gethash k res) v) finally (return res))))) (defun count-things (data &key (test #'equal) (getter (lambda (x) x)) (key (lambda (x) (second x))) (compare #'>) &aux (data* (ensure-vector data :fx #'to-adjustable-vector))) (declare (function test compare getter key)) (loop with res = (make-hash-table :test test) for d across data* do (incf (gethash (funcall getter d) res 0)) finally (return (sort (loop for k being the hash-keys of res using (hash-value v) collect (list k v)) compare :key key)))) (defun to-list (a) (declare (sequence a)) (coerce a 'list)) (defun close-path (p) (declare (list p)) (append p (list (nth 0 p)))) <|start_filename|>examples/slope.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (defun main (size fn) (let ((p1 (rnd:in-circ 100d0 :xy (vec:vec 800d0 200d0))) (p2 (rnd:in-circ 100d0 :xy (vec:vec 200d0 800d0)))) (let ((va (vec:add (vec:scale (vec:norm (vec:mult (vec:flip (vec:sub p1 p2)) (vec:vec -1d0 1d0))) 40d0) (rnd:on-circ 20d0 :xy (vec:zero)))) (repeat 10) (noise (rnd:rnd 4d0)) (grains 70) (itt 6000) (sand (sandpaint:make size :fg (pigment:black 0.01) :bg (pigment:white)))) (loop for j from 1 to repeat do (print-every j 2) (let ((snk (snek:make))) (setf va (vec:add va (rnd:in-circ noise :xy (vec:zero)))) (loop for k from 1 to itt do (snek:with (snk) (snek:add-vert? (rnd:on-line p1 p2)) (snek:with-rnd-vert (snk v) (snek:append-edge? v va)) (snek:with-rnd-vert (snk v) (snek:with-rnd-vert (snk w) (snek:add-edge? w v))))) (snek:draw-edges snk sand grains))) (sandpaint:pixel-hack sand) (sandpaint:save sand fn)))) (time (main 1000 (second (cmd-args)))) <|start_filename|>src/snek-alterations.lisp<|end_filename|> (in-package :snek) ; ADD VERT (defstruct (add-vert-alt (:constructor add-vert? (xy &key p)) (:predicate add-vert-alt-p*)) (xy nil :type vec:vec :read-only t) (p nil :type symbol :read-only t)) (defun do-add-vert-alt (snk a) " add new vert at xy. returns the new vert ind. " (declare (snek snk) (add-vert-alt a)) (with-struct (add-vert-alt- xy p) a (add-vert! snk xy :p p))) ; ADD EDGE (defstruct (vadd-edge-alt (:constructor vadd-edge? (xya xyb &key g))) (xya nil :type vec:vec :read-only t) (xyb nil :type vec:vec :read-only t) (g nil :type symbol :read-only t)) (defun do-vadd-edge-alt (snk a) " add verts xya and xyb, and creates an edge (in grp g) between them. " (declare (snek snk) (vadd-edge-alt a)) (with-struct (vadd-edge-alt- xya xyb g) a (add-edge! snk (add-vert! snk xya) (add-vert! snk xyb) :g g))) ; MOVE VERT (defstruct (move-vert-alt (:constructor move-vert? (v xy &key (rel t)))) (rel t :type boolean :read-only t) (xy nil :type vec:vec :read-only t) (v nil :type fixnum :read-only t)) (defun do-move-vert-alt (snk a) " move vert v. if rel: move relative to original position. else: move to xy. " (declare (snek snk) (move-vert-alt a)) (with-struct (snek- verts num-verts) snk (declare (type (simple-array double-float) verts)) (with-struct (move-vert-alt- v xy rel) a (declare (fixnum v) (vec:vec xy) (boolean rel)) (-valid-vert (num-verts v :err nil) (let ((x (vec::vec-x xy)) (y (vec::vec-y xy)) (i (* 2 v)) (ii (1+ (* 2 v)))) (declare (double-float x y) (fixnum i ii)) (if rel (setf (aref verts i) (+ (aref verts i) x) (aref verts ii) (+ (aref verts ii) y)) (setf (aref verts i) x (aref verts ii) y)) (vec:vec (aref verts i) (aref verts ii))))))) ; APPEND EDGE (defstruct (append-edge-alt (:constructor append-edge? (v xy &key (rel t) g))) (xy nil :type vec:vec :read-only t) (v nil :type fixnum :read-only t) (g nil :type symbol :read-only t) (rel t :type boolean :read-only t)) (defun do-append-edge-alt (snk a) " add edge between vert v and new vert xy " (declare (snek snk) (append-edge-alt a)) (with-struct (snek- num-verts) snk (with-struct (append-edge-alt- v xy rel g) a (-valid-vert (num-verts v :err nil) (let ((w (if rel (add-vert! snk (vec:add (get-vert snk v) xy)) (add-vert! snk xy)))) (declare (fixnum w)) (add-edge! snk v w :g g) w))))) (defstruct (append-edge-segx-alt (:constructor append-edge-segx? (v xy &key (rel t) x g))) (xy nil :type vec:vec :read-only t) (v nil :type fixnum :read-only t) (g nil :type symbol :read-only t) (x nil :type symbol :read-only t) (rel t :type boolean :read-only t)) (defun -line-segx-edges (snk line &key g) (declare (snek snk) (list line)) (loop for e of-type list across (get-edges snk :g g) if (multiple-value-bind (x s) (vec:segx line (get-verts snk e)) (and x (> s 1d-7))) do (return t))) (defun do-append-edge-segx-alt (snk a) " add edge between vert v and new vert xy, if the new edge does not intersect any of the existing edges (in grp g). if x, the new edge is only added if it intersects (the converse). " (declare (snek snk) (append-edge-segx-alt a)) (with-struct (append-edge-segx-alt- v xy rel x g) a (let* ((p1 (get-vert snk v)) (p2 (if rel (vec:add p1 xy) xy)) (hit (-line-segx-edges snk (list p1 p2) :g g))) (when (or (and (not x) (not hit)) (and x hit)) (add-edge! snk v (add-vert! snk p2) :g g))))) ; JOIN VERTS (defstruct (add-edge-alt (:constructor add-edge? (v w &key g))) (v nil :type fixnum :read-only t) (w nil :type fixnum :read-only t) (g nil :type symbol :read-only t)) (defun do-add-edge-alt (snk a) " create edge between valid verts v and w (in grp g). " (declare (snek snk) (add-edge-alt a)) (with-struct (snek- num-verts) snk (with-struct (add-edge-alt- v w g) a (-valid-vert (num-verts v :err nil) (-valid-vert (num-verts w :err nil) (ladd-edge! snk (list v w) :g g)))))) (defun ladd-edge? (ll &key g) (destructuring-bind (a b) ll (declare (fixnum a b)) (add-edge? a b :g g))) ; DEL EDGE (defstruct (del-edge-alt (:constructor del-edge? (v w &key g))) (v nil :type fixnum :read-only t) (w nil :type fixnum :read-only t) (g nil :type symbol :read-only t)) (defun do-del-edge-alt (snk a) " del edge (v w) (of grp g). " (declare (snek snk) (del-edge-alt a)) (with-struct (del-edge-alt- v w g) a (del-edge! snk v w :g g))) (defun ldel-edge? (ll &key g) (declare (list ll)) (destructuring-bind (a b) ll (declare (fixnum a b)) (del-edge? a b :g g))) ; SPLIT EDGE (defstruct (split-edge-alt (:constructor split-edge? (v w &key xy g))) (v nil :type fixnum :read-only t) (w nil :type fixnum :read-only t) (xy nil :read-only t) (g nil :type symbol :read-only t)) (defun do-split-edge-alt (snk a) " insert a vert, v, at the middle of edge e = (v w) if xy is not nil v will be positioned at xy. such that we get edges (a v) and (v b). returns the new edges (or nil). " (declare (snek snk) (split-edge-alt a)) (with-struct (split-edge-alt- v w xy g) a (let ((res (del-edge! snk v w :g g)) (verts (snek-verts snk))) (declare (type (simple-array double-float) verts)) (when res (let ((c (add-vert! snk (if xy xy (vec:mid (vec:sarr-get verts v) (vec:sarr-get verts w)))))) (list (add-edge! snk v c :g g) (add-edge! snk c w :g g))))))) (defun lsplit-edge? (ll &key xy g) (declare (list ll)) (destructuring-bind (a b) ll (declare (fixnum a b)) (split-edge? a b :xy xy :g g))) ; ALT THEN (defstruct (alt-then (:constructor alt-then? (alt &key (then (lambda (a r) (list a r))) (else #'identity)))) (alt nil :read-only t) (then nil :type function :read-only t) (else nil :type function :read-only t)) (defun do-alt-then (snk a) " execute then if alteration is successful, otherwise execute else. then gets the alteration and its result as arguments. else gets the alteration as its argument. " (declare (snek snk) (alt-then a)) (with-struct (alt-then- alt then else) a (declare (function then else)) (let ((r (funcall (gethash (type-of alt) (snek-alt-names snk)) snk alt))) (if r (funcall then alt r) (funcall else alt))))) <|start_filename|>src/snek-macros.lisp<|end_filename|> (in-package :snek) (defmacro with ((snk &key zwidth collect include-alts) &body body) " creates a context for manipulating snek via alterations. all alterations created in this context will be flattened and applied to snk at the end of the context. " (declare (symbol snk) (type boolean collect include-alts)) (with-gensyms (sname zw aname rec x y resalts) (let* ((do-funcall `(funcall (gethash (type-of ,x) ,aname) ,sname ,x)) (wrap-funcall (cond ((and collect include-alts) `(vextend (list ,do-funcall ,x) ,resalts)) (collect `(vextend ,do-funcall ,resalts)) (t do-funcall))) (finally (if collect `(to-list ,resalts) nil))) `(let* ((,sname ,snk) (,zw ,zwidth) (,resalts (make-adjustable-vector)) (,aname (snek-alt-names ,sname))) (incf (snek-wc ,sname)) (labels ((,rec (,x) (cond ((null ,x)) ((atom ,x) ; if atom is also alteration (else ignore): (when (gethash (type-of ,x) ,aname) ,wrap-funcall)) (t (,rec (car ,x)) (,rec (cdr ,x)))))) (zmap::with* (,zw (snek-verts ,sname) (snek-num-verts ,sname) (lambda (,y) (setf (snek-zmap ,sname) ,y))) ; this lets @body be executed in the context of zmap:with; ; useful if we want to have a parallel context inside zmap. (,rec (list ,@body)))) (setf (snek-zmap ,sname) nil) ,finally)))) (defmacro cwith ((snk accfx &key zwidth) &body body) " creates a context for manipulating snek via alterations. example: (snek:cwith (snk c) (c (snek:add-edge? ...))) all calls to c inside cwith will cause the alteration inside the c form to be executed. if the form is nil nothing happens. this can be more efficient than snek:with in some cases. " (declare (symbol snk accfx)) (with-gensyms (sname zw aname x y res do-res) `(let* ((,sname ,snk) (,zw ,zwidth) (,res (make-adjustable-vector)) (,aname (snek-alt-names ,sname))) (incf (snek-wc ,sname)) (labels ((,do-res () (loop for ,x across ,res do (funcall (gethash (type-of ,x) ,aname) ,sname ,x))) (,accfx (,x) (when ,x (vextend ,x ,res)))) (zmap::with* (,zw (snek-verts ,sname) (snek-num-verts ,sname) (lambda (,y) (setf (snek-zmap ,sname) ,y))) ; this lets @body be executed in the context of zmap:with; ; useful if we want to have a parallel context inside zmap. (progn ,@body)) (,do-res)) (setf (snek-zmap ,sname) nil)))) (defmacro zwith ((snk zwidth) &body body) " creates a snek context. the zmap is constant inside this context. " (declare (symbol snk)) (with-gensyms (sname zw y res) `(let ((,sname ,snk) (,zw ,zwidth)) (zmap::with* (,zw (snek-verts ,sname) (snek-num-verts ,sname) (lambda (,y) (setf (snek-zmap ,sname) ,y))) (let ((,res (progn ,@body))) (setf (snek-zmap ,sname) nil) ,res))))) (defmacro with-verts-in-rad ((snk xy rad v) &body body) (declare (symbol snk)) (with-gensyms (sname) `(let ((,sname ,snk)) (zmap:with-verts-in-rad ((snek-zmap ,sname) (snek-verts ,sname) ,xy ,rad ,v) (progn ,@body))))) (defmacro with-dx ((snk vv dx d) &body body) (declare (symbol snk)) (with-gensyms (sname) `(let ((,sname ,snk)) (let* ((,dx (apply #'vec:isub (get-verts ,sname ,vv))) (,d (vec:len ,dx))) (declare (double-float ,d) (vec:vec ,dx)) (when (> ,d 0d0) (list ,@body)))))) (defmacro with-grp ((snk g* g) &body body) " select grp g from snek instance. g will be available in this context as g*. " (declare (symbol snk)) (with-gensyms (grps exists gname sname) `(let ((,sname ,snk) (,gname ,g)) (let ((,grps (snek-grps ,sname))) (multiple-value-bind (,g* ,exists) (gethash ,gname ,grps) (unless ,exists (error "attempted to access invalid group: ~a" ,gname)) (progn ,@body)))))) (defmacro with-rnd-edge ((snk i &key g) &body body) " select an arbitrary edge from a snek instance. the edge will be available in the context as i. if a grp is supplied it will select an edge from g, otherwise it will use the main grp. " (declare (symbol snk)) (with-gensyms (grp edges grph ln) `(with-grp (,snk ,grp ,g) (let ((,grph (grp-grph ,grp))) (let* ((,edges (graph:get-edges ,grph)) (,ln (length ,edges))) (declare (fixnum ,ln)) (when (> ,ln 0) (let ((,i (aref ,edges (rnd:rndi ,ln)))) (declare (list ,i)) (list ,@body)))))))) (defmacro with-rnd-vert ((snk i) &body body) " select an arbitrary vert from a snek instance. the vert will be available in the context as i. " (declare (symbol snk)) (with-gensyms (num) `(let ((,num (snek-num-verts ,snk))) (when (> ,num 0) (let ((,i (rnd:rndi ,num))) (declare (fixnum ,i)) (list ,@body)))))) (defmacro itr-verts ((snk i &key (collect t)) &body body) " iterates over ALL verts in snk as i. " (declare (symbol snk) (type boolean collect)) (with-gensyms (sname) `(let ((,sname ,snk)) (loop for ,i of-type fixnum from 0 below (snek-num-verts ,sname) ,(if collect 'collect 'do) (list ,@body))))) (defmacro itr-grp-verts ((snk i &key g (collect t)) &body body) " iterates over all verts in grp g as i. NOTE: this will only yield vertices that belong to at least one edge that is part of g. if you want all vertices in snek you should use itr-verts instead. itr-verts is also faster, since it does not rely on the underlying graph structure. if g is not provided, the main grp wil be used. " (declare (symbol snk) (type boolean collect)) (with-gensyms (grp sname) `(let ((,sname ,snk)) (with-grp (,sname ,grp ,g) (map ',(if collect 'list 'nil) (lambda (,i) (declare (fixnum ,i)) (list ,@body)) (graph:get-verts (grp-grph ,grp))))))) (defmacro itr-prm-verts ((snk i &key p (collect t)) &body body) " iterates over all verts in prm p as i. " (declare (symbol snk) (type boolean collect)) (with-gensyms (sname) `(let* ((,sname ,snk)) (map ',(if collect 'list 'nil) (lambda (,i) (declare (fixnum ,i)) (list ,@body)) (get-prm-vert-inds ,sname :p ,p))))) (defmacro itr-edges ((snk i &key g (collect t)) &body body) " iterates over all edges in grp g as i. if g is not provided, the main grp will be used. " (declare (symbol snk) (type boolean collect)) (with-gensyms (grp grph) `(with-grp (,snk ,grp ,g) (let ((,grph (grp-grph ,grp))) (map ',(if collect 'list 'nil) (lambda (,i) (list ,@body)) (graph:get-edges ,grph)))))) (defmacro itr-grps ((snk g &key (collect t) main) &body body) " iterates over all grps of snk as g. " (declare (symbol snk) (type boolean collect)) (with-gensyms (grps sname main*) `(let ((,sname ,snk) (,main* ,main)) (let ((,grps (snek-grps ,sname))) (loop for ,g being the hash-keys of ,grps if (or ,main* ,g) ,(if collect 'collect 'do) (list ,@body)))))) (defmacro itr-prms ((snk p &key (collect t)) &body body) " iterates over all prms of snk as p. " (declare (symbol snk) (type boolean collect)) (with-gensyms (prms sname) `(let ((,sname ,snk)) (let ((,prms (snek-prms ,sname))) (loop for ,p being the hash-keys of ,prms ,(if collect 'collect 'do) (list ,@body)))))) <|start_filename|>test/speed-sandpaint.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (setf *print-pretty* t) (rnd:set-rnd-state 1) (defun main () (let* ((num 1000000) (pix-num 1000000) (grains 100) (sand (sandpaint:make 1000 :fg (pigment:black 0.01) :bg (pigment:white)))) (format t "strokes:~%") (time (sandpaint:strokes sand (math:nrep num (list (rnd:in-box 500d0 500d0 :xy (vec:vec 500d0)) (rnd:in-box 500d0 500d0 :xy (vec:vec 500d0)))) grains)) (format t "pix:~%") (time (loop repeat 100 do (sandpaint:pix sand (math:nrep pix-num (rnd:in-box 500d0 500d0 :xy (vec:vec 500d0)))))) (format t "lin-path:~%") (time (loop repeat 500 do (sandpaint:lin-path sand (rnd:nin-box 5 500d0 500d0 :xy (vec:vec 500d0)) 3d0 grains))) )) ;(require :sb-sprof) ;(sb-sprof:with-profiling (:max-samples 200000 ; :mode :cpu ; ;:mode :alloc ; ;:mode :time ; :report :graph) ; (main)) (main) <|start_filename|>examples/cluster-vis.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (defun get-dst (centroids cand) (first (sort (loop for c in centroids and i from 0 collect (list i (vec:dst cand c))) #'< :key #'second))) (defun get-pt (w size) (rnd:in-box w w :xy (vec:rep (* 0.5d0 size)))) (defun get-distributed-pts (centroids size w n) (let ((res (make-adjustable-vector)) (scale (sqrt (* 2d0 (expt size 2d0))))) (loop for k from 0 below n do (let ((pt (get-pt w size))) (destructuring-bind (i dst) (get-dst centroids pt) (if (> (expt (rnd:rnd) 10d0) (* 3d0 (/ dst scale))) (vector-push-extend pt res))))) (coerce res 'list))) (defun draw-circ (sand colors circs) (loop for c in circs and color in colors do (sandpaint:set-fg-color sand color) (sandpaint:circ sand (list c) 15d0 10000))) (defun main (size fn) (let ((border 50d0) (grains 10) (centroids (math:nrep 20 (get-pt 450d0 size))) (colors (math:nrep 20 (pigment:hsv (rnd:rnd) 0.7 0.8 0.09)))) (let ((sand (sandpaint:make size :fg (pigment:black 0.08) :bg (pigment:white)))) (sandpaint:set-fg-color sand (pigment:black 0.009)) (loop for pt in (get-distributed-pts centroids size 450d0 300000) do (destructuring-bind (i dst) (get-dst centroids pt) (sandpaint:circ sand (list pt) 3d0 1300))) (draw-circ sand colors centroids) (sandpaint:pixel-hack sand) (sandpaint:save sand (append-postfix fn "-1") :gamma 1.5)) (let ((sand (sandpaint:make size :fg (pigment:black 0.08) :bg (pigment:white)))) (sandpaint:set-fg-color sand (pigment:black 0.009)) (loop for pt in (get-distributed-pts centroids size 450d0 300000) do (destructuring-bind (i dst) (get-dst centroids pt) (sandpaint:stroke sand (list (nth i centroids) pt) 700))) (draw-circ sand colors centroids) (sandpaint:pixel-hack sand) (sandpaint:save sand fn :gamma 1.5)))) (time (main 1000 (second (cmd-args)))) <|start_filename|>utils/text.lisp<|end_filename|> (ql:quickload "split-sequence") (defun get-words (txt) (loop for word in (split-sequence:split-sequence #\ txt) collect (list word (length word)))) (defun get-words* (txt) (loop for section in (split-sequence:split-sequence #\NewLine txt) collect (get-words section))) (defun show-sections (words) (loop for section in words do (print "---------------------------------------------------------") (print section))) <|start_filename|>examples/grp-path.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (defun init (snk rep rad) (loop for x in (math:linspace rep 200d0 800d0) for i from 0 do (loop for y in (math:linspace rep 200d0 800d0) for j from 0 do (let ((g (snek:add-grp! snk :type 'path))) (snek:add-path! snk (rnd:nin-box 8 rad rad :xy (vec:vec x y)) :closed t :g g) ;(add-verts ; snk ; (rnd:nin-box 7 rad rad :xy (list x y)) ; :g g) )))) (defun main (size fn) (let ((grains 15) (itt 30000) (noise 0.0000002d0) (rep 5) (rad 85d0) (snk (snek:make :max-verts 10000)) (sand (sandpaint:make size :fg (pigment:black 0.005) :bg (pigment:white)))) (init snk rep rad) (let ((grp-states (make-hash-table :test #'equal))) (snek:itr-grps (snk g) (setf (gethash g grp-states) (list (lin-path:make (snek:get-grp-verts snk :g g)) (rnd:get-acc-lin-stp* (rnd:rnd)) (rnd:get-acc-lin-stp* (rnd:rnd))))) (loop for i from 0 to itt do (print-every i 1000) (snek:itr-grps (snk g :collect nil) (destructuring-bind (path lina linb) (gethash g grp-states) (sandpaint:stroke sand (lin-path:pos* path (list (funcall linb noise) (funcall lina noise))) grains)))) ;(sandpaint:chromatic-aberration sand (list 500 500) :s 200.0) (sandpaint:pixel-hack sand) (sandpaint:save sand fn)))) (time (main 1000 (second (cmd-args)))) <|start_filename|>examples/squares-step.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (rnd:set-rnd-state 1) (defun main (size fn) (let ((grains 220) (itt 20000) (noise 0.0000018d0) (rep 5) (rad 185d0) (snk (snek:make)) (sand (sandpaint:make size :fg (pigment:white 0.005) :bg (pigment:gray 0.1d0)))) (loop for x in (math:linspace rep 200d0 1800d0) for i from 0 do (loop for y in (math:linspace rep 200d0 1800d0) for j from 0 do (let ((g (snek:add-grp! snk :type 'path))) (snek:add-polygon! snk 4 rad :xy (vec:vec x y) :g g)))) (let ((grp-states (make-hash-table :test #'equal)) (c 1)) (snek:itr-grps (snk g) (incf c) (setf (gethash g grp-states) (list (lin-path:make (snek:get-grp-verts snk :g g)) (rnd:get-acc-lin-stp* (rnd:rnd)) (rnd:get-acc-lin-stp* (rnd:rnd)) noise))) ;(sandpaint:stroke sand (list (vec:vec 100d0) (vec:vec 900d0 100d0) ) 100000) (loop for i from 0 to itt do (print-every i 1000) ;(snek:with (snk) ; (snek:itr-grps (snk g) ; (snek:itr-grp-verts (snk v :g g) ; (snek:move-vert? v (rnd:in-circ 0.3d0) :rel t)))) (snek:itr-grps (snk g :collect nil) (destructuring-bind (path lina linb ns) (gethash g grp-states) ;(lin-path:move path (get-grp-vert-vals snk :g g) :rel nil) ;closed must be set in constr. (sandpaint:stroke sand (lin-path:pos* path (list (funcall linb ns) (funcall lina ns))) grains))))) (sandpaint:chromatic-aberration sand :s 50d0) (sandpaint:pixel-hack sand) (sandpaint:save sand fn))) (time (main 2000 (second (cmd-args)))) <|start_filename|>examples/bz-walk.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (defun main (size fn) (let ((itt 1000000) (noise 0.000000005d0) (grains 20) (sand (sandpaint:make size :fg (pigment:white 0.05) :bg (pigment:dark)))) (let* ( (pts-1 (rnd:nin-box 6 1500d0 1500d0 :xy (vec:vec 1000d0 1000d0))) (pts (rnd:nin-box 6 1500d0 1500d0 :xy (vec:vec 1000d0 1000d0))) ;(pts-a (math:nrep 5 (list 50.0d0 (rnd:rndbtwn 50 1950)))) (pts-a (math:rep (p (math:linspace 5 50d0 1950d0)) (vec:vec 50.0d0 p))) ;(pts-b (math:nrep 5 (list 1950.0d0 (rnd:rndbtwn 50 1950)))) (pts-b (math:rep (p (math:linspace 5 50d0 1950d0)) (vec:vec 50.0d0 p))) (b (bzspl:make pts :closed t)) (b-1 (bzspl:make pts-1 :closed t)) (ba (bzspl:make pts-a :closed t)) (bb (bzspl:make pts-b :closed t)) (wa (rnd:get-acc-lin-stp (rnd:rnd))) (wb (rnd:get-acc-lin-stp (rnd:rnd)))) (loop for p in (math:linspace itt 0d0 1d0 :end nil) for i from 0 do (print-every i 100000) (sandpaint:set-fg-color sand (pigment:hsv p 1 1 0.05)) (sandpaint:stroke sand (list (bzspl:pos b p) (bzspl:pos b-1 p)) grains))) (sandpaint:save sand fn :gamma 1.5))) (time (main 2000 (second (cmd-args)))) <|start_filename|>examples/grid-walk.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (load "../utils/grid") (defun mixed (x f) (declare (double-float x f)) (+ (random (* f x)) (- x (* 2.0d0 (random x))))) (defun rnd-dir () (nth (rnd:rndi 4) (list (list 0 -1) (list 0 1) (list -1 0) (list 1 0)))) (defmacro -swap (n m n* m*) (with-gensyms (h w) `(progn (setf ,n ,n*) (setf ,m ,m*) (destructuring-bind (,h ,w) (rnd-dir) (setf ,n* (+ ,n ,h)) (setf ,m* (+ ,m ,w)))))) (defun get-walker (grid) (let ((ngrid (length grid))) (let ((x 0.d0) (n (rnd:rndi ngrid)) (m (rnd:rndi ngrid))) (destructuring-bind (n* m*) (math:add (list n m) (rnd-dir)) (lambda (noise) (incf x (mixed noise 0.2d0)) (when (> x 1.0d0) (-swap n m n* m*)) (when (< x 0.0d0) (-swap n* m* n m)) (setf x (mod x 1.0d0)) (vec:on-line x (nth (mod m ngrid) (nth (mod n ngrid) grid)) (nth (mod m* ngrid) (nth (mod n* ngrid) grid)))))))) (defun main (size fn) (let ((itt 10000000) (ngrid 7) (nwalkers 2) (noise 0.00002d0) (grains 2) (edge 0d0) (sand (sandpaint:make size :fg (pigment:white 0.05) :bg (pigment:dark)))) (let* ((grid (get-grid size edge (rnd:rndi 5 11))) (walkers (math:nrep nwalkers (get-walker grid)))) (loop for i from 0 below itt do (print-every i 100000) ;(sandpaint:circ sand ; (loop for w in walkers collect ; (funcall w (* ngrid 0.00000001d0))) ; 2.0 ; 1) (sandpaint:stroke sand (loop for w in walkers collect (funcall w noise)) grains))) (sandpaint:save sand fn :gamma 2.2))) (time (main 2000 (second (cmd-args)))) <|start_filename|>utils/test.lisp<|end_filename|> (defvar *tests* 0) (defvar *fails* 0) (defvar *passes* 0) ; TODO: approximately similar to (defmacro test-title (&body body) `(progn (format t "~%~%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@> ~a~%" ',@body) ,@body)) (defmacro do-test (a b) (with-gensyms (aname bname) `(let ((,aname ,a) (,bname ,b)) (incf *tests*) (if (funcall #'equalp ,aname ,bname) (progn (incf *passes*) (format t "~%~a ~%-----------------------------------------> ok" ',a :pretty t)) (progn (incf *fails*) (format t "~%~a ~%#########################################> not ok ~%-- wanted: ~% ~a ~%-- got: ~% ~a~%-----------------------------------------~%" ',a ',b ,aname :pretty t)))))) (defun test-summary () (format t "~% tests: ~a~% fails: ~a~% passes: ~a~%" *tests* *fails* *passes*)) <|start_filename|>test/plot-simplify.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (setf *print-pretty* t) (rnd:set-rnd-state 1) (defun main (size fn) (let ((psvg (draw-svg:make* :width 1000d0 :height 1000d0 :stroke-width 1d0 :rep-scale 0.5d0))) (loop for x in (math:linspace 7 80d0 920d0) do (loop for y in (math:linspace 7 80d0 920d0) do (let ((path (rnd:nin-box 5 40d0 40d0 :xy (vec:vec x y)))) (draw-svg:path psvg (vec:ladd* path (vec:vec 20d0 0d0))) (draw-svg:cpath psvg (vec:ladd* path (vec:vec -20d0 0d0)) :simplify 10d0 :width 10d0)))) (draw-svg:save psvg "plot-simplify"))) (time (main 1000 (second (cmd-args)))) <|start_filename|>utils/time.lisp<|end_filename|> (defvar *t*) (defvar *tsum*) (setf *t* (make-hash-table :test #'equal)) (setf *tsum* (make-hash-table :test #'equal)) (defun start-timer (tname) (multiple-value-bind (val exists) (gethash tname *tsum*) (if (not exists) (setf (gethash tname *tsum*) 0))) (setf (gethash tname *t*) (get-internal-real-time))) (defun sum-timer (tname) (multiple-value-bind (val exists) (gethash tname *t*) (incf (gethash tname *tsum*) (- (get-internal-real-time) val))) (start-timer tname)) (defun show-timers () (format t "~%timers: ~%") (loop for ti being the hash-keys of *tsum* do (format t " ~a: ~a ~%" ti (gethash ti *tsum*)))) (defmacro with-timer ((name) &body body) (with-gensyms (bname tname) `(let ((,tname ,name)) (start-timer ,tname) (let ((,bname (progn ,@body))) (sum-timer ,tname) ,bname)))) <|start_filename|>examples/modules.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (defun run-join (snk) (snek:with (snk :zwidth 100.0d0) (snek:with-rnd-vert (snk v) (snek:add-edge? (rnd:rndget (snek:verts-in-rad snk (snek:get-vert snk v) 100.0d0)) v)))) (defun run-move (snk) (snek:with (snk) (snek:with-rnd-vert (snk v) (snek:move-vert? v (rnd:in-circ 20d0))))) (defun main (size fn) (let ((grains 2) (itt 100000) (noise 0.1) (rep 7) (snk (snek:make :max-verts 100000)) (sand (sandpaint:make size :fg (pigment:black 0.01) :bg (pigment:white)))) (snek:add-verts! snk (rnd:nin-box 100 450d0 450d0 :xy (vec:vec 500d0 500d0))) (let ((fns (list 'run-join 'run-move))) (loop for i from 0 to itt do (print-every i 1000) (funcall (rnd:rndget fns) snk))) (snek:draw-edges snk sand 1000) (sandpaint:pixel-hack sand) (sandpaint:save sand fn :gamma 1.5))) (time (main 1000 (second (cmd-args)))) <|start_filename|>src/math.lisp<|end_filename|> (in-package :math) (declaim (ftype (function (number) double-float) dfloat)) (declaim (ftype (function (number) fixnum) int)) (declaim (ftype (function (number) float) sfloat)) ; TYPES (defun int (x) (declare (number x)) (the fixnum (coerce (floor x) 'fixnum))) (defun int* (xx) (declare (list xx)) (mapcar (lambda (x) (int (the fixnum (floor x)))) xx)) (defun sfloat (x) (declare (number x)) (the float (coerce x 'float))) (defun sfloat* (xx) (declare (list xx)) (mapcar (lambda (x) (sfloat x)) xx)) (defun dfloat (x) (declare (number x)) (the double-float (coerce x 'double-float))) (defun dfloat* (xx) (declare (list xx)) (mapcar (lambda (x) (dfloat x)) xx)) (defun clamp (v mi ma) (declare (double-float v mi ma)) (cond ((< v mi) mi) ((< v ma) v) (t ma))) ; RANGES (defmacro rep ((i itt) &body body) `(loop for ,i in ,itt collect (progn ,@body))) (defmacro nrep (n &body body) (with-gensyms (nname) `(let ((,nname ,n)) (loop repeat ,nname collect (progn ,@body))))) (defun range (a &optional (b nil)) (declare (fixnum a)) (if (not b) (loop for x of-type fixnum from 0 below a collect x) (loop for x of-type fixnum from a below (the fixnum b) collect x))) (defun lget (l ii) " get indices ii from l " (declare (list l ii)) (loop with arr = (to-vector l) for i of-type fixnum in ii collect (aref arr i))) (defmacro with-linspace ((n a b rn &key (end t) collect) &body body) (declare (symbol rn)) (with-gensyms (a* b* n* nn i ba) `(let* ((,n* (int ,n)) (,nn (dfloat (if ,end (1- ,n*) ,n*))) (,a* (dfloat ,a)) (,b* (dfloat ,b)) (,ba (- ,b* ,a*))) (loop for ,i from 0 below ,n* ,(if collect 'collect 'do) (let ((,rn (dfloat (+ ,a* (* ,i (/ ,ba ,nn)))))) (declare (double-float ,rn)) (progn ,@body)))))) (defun linspace (n a b &key (end t)) (declare (fixnum n) (double-float a b) (boolean end)) (if (> n 1) (let ((ban (dfloat (/ (- b a) (if end (dfloat (1- n)) (dfloat n)))))) (declare (double-float ban)) (loop for i of-type fixnum from 0 below n collect (the double-float (+ a (the double-float (* (dfloat i) ban)))))) (list a))) ; LIST INTEGER MATH (defun add (aa bb) (declare (list aa bb)) (loop for a of-type fixnum in aa and b of-type fixnum in bb collect (the fixnum (+ a b)))) (defun sub (aa bb) (declare (list aa bb)) (loop for a of-type fixnum in aa and b of-type fixnum in bb collect (the fixnum (- a b)))) (defun mult (aa bb) (declare (list aa bb)) (loop for a of-type fixnum in aa and b of-type fixnum in bb collect (the fixnum (* a b)))) (defun mod- (i n) (declare (fixnum i n)) (mod (the fixnum (+ n i -1)) n)) (defun mod+ (i n) (declare (fixnum i n)) (mod (the fixnum (+ n i 1)) n)) (defun mod2 (i) (declare (fixnum i)) (mod i 2)) ; LIST DOUBLE FLOAT MATH (defun dop (aa op) (declare (list aa) (function op)) (loop for a of-type double-float in aa collect (funcall op a) of-type double-float)) (defun dadd (aa bb) (declare (list aa bb)) (loop for a of-type double-float in aa and b of-type double-float in bb collect (+ a b) of-type double-float)) (defun dsub (aa bb) (declare (list aa bb)) (loop for a of-type double-float in aa and b of-type double-float in bb collect (- a b) of-type double-float)) (defun dmult (aa bb) (declare (list aa bb)) (loop for a of-type double-float in aa and b of-type double-float in bb collect (* a b) of-type double-float)) (defun daddmod* (aa b &optional (m 1d0)) (declare (list aa) (double-float b m)) (mapcar (lambda (a) (declare (double-float a)) (the double-float (mod (the double-float (+ a b)) m))) aa)) (defun ddst (aa bb) (declare (list aa bb)) (sqrt (the double-float (loop for a in aa and b in bb sum (expt (the double-float (- a b)) 2d0) of-type double-float )))) (defun ddiv (aa bb) (declare (list aa bb)) (loop for a of-type double-float in aa and b of-type double-float in bb collect (/ a b) of-type double-float)) (defun dscale (aa bb) (declare (list aa bb)) (mapcar (lambda (a b) (declare (double-float a b)) (* a b)) aa bb)) (defun dscale* (aa s) (declare (list aa) (double-float s)) (mapcar (lambda (a) (declare (double-float a)) (* a s)) aa)) (defun dsum (aa) (declare (list aa)) (loop for a of-type double-float in aa summing a of-type double-float)) (defun dmean (aa) (declare (list aa)) (/ (dsum aa) (math:dfloat (length aa)))) (defun inc (x stp) (declare (double-float x stp)) (mod (the double-float (+ x stp)) 1d0)) (defun on-line (p aa bb) (declare (optimize (safety 0) speed (debug 0)) (list aa bb)) (loop for a in aa and b in bb collect (+ a (* p (- b a))))) ; OTHER (defun copy-sort (a fx &key (key #'identity)) (declare (list a)) (sort (copy-seq a) fx :key key)) (defun percentiles (aa) (declare (list aa)) (let ((n (length aa)) (percentiles (list 0.05d0 0.1d0 0.5d0 0.9d0 0.95d0)) (srt (make-adjustable-vector :init (copy-sort aa #'>)))) (to-vector (append (list (aref srt 0)) (loop for m in percentiles collect (aref srt (floor (* n m)))) (list (vector-last srt)))))) ; TODO: expt, sqrt, ... (defun range-search (ranges f &aux (n (1- (length ranges))) (ranges* (ensure-vector ranges))) " binary range search. range must be sorted in ascending order. f is a value inside the range you are looking for. " (if (or (< f (aref ranges* 0)) (> f (aref ranges* n))) (error "querying position outside range: ~a" f)) (loop with l of-type fixnum = 0 with r of-type fixnum = n with m of-type fixnum = 0 until (<= (aref ranges* m) f (aref ranges* (1+ m))) do (setf m (floor (+ l r) 2)) (cond ((> f (aref ranges* m)) (setf l (progn m))) ((< f (aref ranges* m)) (setf r (1+ m)))) finally (return m))) <|start_filename|>src/snek-utils.lisp<|end_filename|> (in-package :snek) (defun add-grp! (snk &key type name props &aux (name* (if name name (gensym)))) " constructor for grp instances. grps are edge graphs. nil is the default grp. as such, nil is not an allowed grp name (there is always a default grp named nil). if name is nil, the name will be a gensym. edges can be associated with multiple grps. verts are global. that is, they do not belong to any grp on their own. however, if a vert is associated with an edge, that vert is also associated with whatever grp that edge belongs to. - to get verts in a grp: (get-grp-verts snk :g g). - to get indices of verts (in a grp): (get-vert-inds snk :g g) - ... use :type :closed to create a closed graph, which allows looking up a closed loop. the grp functionality is still experimental. " (declare (snek snk)) (with-struct (snek- grps grp-size) snk (multiple-value-bind (v exists) (gethash name* grps) (declare (ignore v) (boolean exists)) (when exists (error "grp name already exists: ~a" name*))) (setf (gethash name* grps) (-make-grp :name name* :type type :grph (graph:make :size grp-size :closed (equal type :closed)) :props props))) name*) (defun add-prm! (snk &key name type props args &aux (name* (if name name (gensym)))) " constructor for prms (primitives). prms are generic entities of a particular type. eg. a primitive is a path, a bzspl or a circle. nil is not an allowed prm name. if name is nil, the name will be a gensym. the default type is nil. a given prm can be 'rendered' using (snek:prmr snk :p p). the behaviour of (snek:prmr...) is determined by the rfxn functions. these functions are either the default function or whatever functions are provided by to the :prms when creating a snek instance the prm functionality is experimental. " (declare (snek snk)) (with-struct (snek- prms) snk (multiple-value-bind (v exists) (gethash name* prms) (declare (ignore v) (boolean exists)) (when exists (error "prm name already exists: ~a" name*))) (setf (gethash name* prms) (-make-prm :name name* :type type :props props :args args))) name*) (defmacro -valid-vert ((num vv &key (err t)) &body body) (with-gensyms (v) `(let ((,v ,vv)) (declare (fixnum ,v)) (if (and (> ,v -1) (< ,v ,num)) (progn ,@body) (when ,err (error "vert does not exist: ~a" ,v)))))) (defmacro -valid-verts ((num vv v) &body body) (with-gensyms (vv*) `(let ((,vv* ,vv)) (loop for ,v of-type fixnum in ,vv* if (and (> ,v -1) (< ,v ,num)) collect (progn ,@body))))) (defun add-vert! (snk xy &key p name) " adds a new vertex to snek returns the new vert ind. " (declare (snek snk) (vec:vec xy)) (with-struct (snek- verts num-verts) snk (declare (type (simple-array double-float) verts)) (vec:sarr-set verts num-verts xy)) (let ((i (1- (incf (snek-num-verts snk))))) (when name (multiple-value-bind (v exists) (gethash name (snek-vert-names snk)) (declare (ignore v) (boolean exists)) (when exists (error "vert name already exists: ~a" name)) (setf (gethash name (snek-vert-names snk)) i))) (when p (with-struct (prm- verts) (gethash p (snek-prms snk)) (vextend i verts) (incf (prm-num-verts (gethash p (snek-prms snk)))))) i)) (defun add-verts! (snk vv &key p names) " adds new vertices to snek returns the ids of the new vertices " (declare (snek snk) (list vv names)) (if names (progn (if (not (= (length names) (length vv))) (error "must provide same number of verts and names")) (loop for xy of-type vec:vec in vv and name in names collect (add-vert! snk xy :p p :name name))) (loop for xy of-type vec:vec in vv collect (add-vert! snk xy :p p)))) (defun get-prm-props (snk &key p) (declare (snek snk)) (prm-props (get-prm snk :p p))) (defun get-grp-props (snk &key g) (declare (snek snk)) (grp-props (get-grp snk :g g))) (defun get-grp-loop (snk &key g) (declare (snek snk)) (with-grp (snk g* g) (unless (equal (grp-type g*) :closed) (error "error in get-grp-loop: grp is not of type :closed.")) (graph:get-loop (grp-grph g*)))) (defun set-prm-props! (snk v &key p) (declare (snek snk)) (setf (prm-props (get-prm snk :p p)) v)) (defun set-grp-props! (snk v &key g) (declare (snek snk)) (setf (grp-props (get-grp snk :g g)) v)) (defun get-args (snk &key p) (declare (snek snk)) (prm-args (get-prm snk :p p))) (defun get-vert (snk v) " get the coordinate (vec) of vert v. " (declare (snek snk) (fixnum v)) (with-struct (snek- verts num-verts) snk (declare (type (simple-array double-float) verts) (fixnum num-verts)) (-valid-vert (num-verts v) (vec:sarr-get verts v)))) (defun get-verts (snk vv &aux (vv* (if (equal (type-of vv) 'cons) vv (to-list vv)))) " get the coordinates (vec) of verts in vv " (declare (snek snk) (sequence vv)) (with-struct (snek- verts num-verts) snk (declare (type (simple-array double-float) verts)) (-valid-verts (num-verts vv* v) (vec:sarr-get verts v)))) (defun get-all-verts (snk) " returns the coordinates (vec) of all vertices. " (declare (snek snk)) (with-struct (snek- verts num-verts) snk (declare (type (simple-array double-float) verts)) (loop for v of-type fixnum from 0 below num-verts collect (vec:sarr-get verts v)))) (defun move-vert! (snk v xy &key (rel t) &aux (v* (* 2 v))) (declare (snek snk) (fixnum v) (vec:vec xy) (boolean rel)) (with-struct (snek- verts num-verts) snk (when (>= v num-verts) (error "attempting to move invalid vert, ~a (~a)" v num-verts)) (vec:sarr-set verts v (if rel (vec:vec (+ (aref verts v*) (vec::vec-x xy)) (+ (aref verts (1+ v*)) (vec::vec-y xy))) xy)))) (defun get-all-grps (snk &key main) " returns all grps. use :main t to include main/nil grp. " (declare (snek snk) (boolean main)) (loop for g being the hash-keys of (snek-grps snk) ; ignores nil (main) grp unless overridden if (or g main) collect g)) (defun get-grp (snk &key g) " returns the grp g. if g is not provided, the main/nil grp will be returned. " (declare (snek snk)) (gethash g (snek-grps snk))) (defun get-all-prms (snk) " returns all prms. " (declare (snek snk)) (loop for g being the hash-keys of (snek-prms snk) collect g)) (defun get-prm (snk &key p) " get a single prm. there is no nil prm. " (declare (snek snk)) (when (not p) (error "must provide a prm name.")) (gethash p (snek-prms snk))) (defun get-grp-verts (snk &key g) " returns all vertices in grp g. " (declare (snek snk)) (get-verts snk (get-vert-inds snk :g g))) (defun get-prm-verts (snk &key p) " returns all vertices in prm p. " (declare (snek snk)) (when (not p) (error "must provide a prm name.")) (get-verts snk (get-prm-vert-inds snk :p p))) (defun sel-args (snk p ea) (if ea ea (get-args snk :p p))) (defun prmr (snk &key p type args) (declare (snek snk)) (when (not p) (error "must provide a prm name.")) (let* ((p* (gethash p (snek-prms snk))) (type* (if type type (prm-type p*)))) (when p* (multiple-value-bind (fxn exists) (gethash type* (snek-prm-names snk)) (when (not exists) (error "trying to use undefined prm type: ~a" type*)) (funcall (the function fxn) snk p (snek:sel-args snk p args)))))) (defun get-prm-vert-inds (snk &key p) (declare (snek snk)) (when (not p) (error "must provide a prm name.")) (multiple-value-bind (p* exists) (gethash p (snek-prms snk)) (when (not exists) (error "prm does not exist: ~a" p)) (prm-verts p*))) (defun is-vert-in-grp (snk v &key g) " tests whether v is in grp g " (declare (snek snk) (fixnum v)) (with-struct (snek- grps) snk (multiple-value-bind (g* exists) (gethash g grps) (if exists (graph:vmem (grp-grph g*) v) (error "grp does not exist: ~a" g))))) (defun get-vert-inds (snk &key g) " returns all vertex indices that belongs to a grp " (declare (snek snk)) (with-struct (snek- grps) snk (multiple-value-bind (g* exists) (gethash g grps) (if exists (graph:get-verts (grp-grph g*)) (error "grp does not exist: ~a" g))))) (defun get-vert-ind-by-name (snk &key name) (declare (snek snk)) (multiple-value-bind (i exists) (gethash name (snek-vert-names snk)) (when exists i))) (defun get-vert-by-name (snk &key name) (declare (snek snk)) (multiple-value-bind (i exists) (gethash name (snek-vert-names snk)) (when exists (get-vert snk i)))) (defun get-verts-by-name (snk &key names) (declare (snek snk) (list names)) (loop for name in names collect (get-vert-by-name snk :name name))) (defun get-vert-inds-by-name (snk &key names) (declare (snek snk) (list names)) (loop for name in names collect (get-vert-ind-by-name snk :name name))) (defun get-num-verts (snk) (declare (snek snk)) (snek-num-verts snk)) (defun get-grp-num-verts (snk &key g) (declare (snek snk)) (with-grp (snk g* g) (graph:get-num-verts (grp-grph g*)))) (defun get-num-edges (snk &key g) (declare (snek snk)) (with-grp (snk g* g) (graph:get-num-edges (grp-grph g*)))) ; TODO: option to include both directions? (defun get-edges (snk &key g) (declare (snek snk)) (with-grp (snk g* g) (graph:get-edges (grp-grph g*)))) ; TODO: get-all-incident-edges (not just in grp g)? (defun get-incident-edges (snk v &key g) (declare (snek snk) (fixnum v)) (with-grp (snk g* g) (graph:get-incident-edges (grp-grph g*) v))) (defun edge-exists (snk ee &key g) (declare (snek snk) (list ee)) (with-grp (snk g* g) (destructuring-bind (a b) ee (declare (fixnum a b)) (graph:mem (grp-grph g*) a b)))) (defun add-edge! (snk a b &key g) " adds a new edge to snek. provided the edge is valid. otherwise it returns nil. returns nil if the edge exists already. " (declare (snek snk) (fixnum a b)) (when (= a b) (return-from add-edge! nil)) (with-grp (snk g* g) (with-struct (snek- num-verts) snk (declare (fixnum num-verts)) (with-struct (grp- grph) g* (when (and (< a num-verts) (< b num-verts)) (when (graph:add grph a b) (sort (list a b) #'<))))))) (defun ladd-edge! (snk ee &key g) (declare (snek snk) (list ee)) (destructuring-bind (a b) ee (declare (fixnum a b)) (add-edge! snk a b :g g))) (defun add-edges! (snk ee &key g) " adds multiple edges (see above). returns a list of the results. " (declare (snek snk) (list ee)) (loop for e of-type list in ee collect (ladd-edge! snk e :g g))) (defun del-edge! (snk a b &key g) (declare (snek snk) (fixnum a b)) (with-grp (snk g* g) (with-struct (grp- grph) g* (graph:del grph a b)))) (defun ldel-edge! (snk ee &key g) (declare (snek snk) (list ee)) (with-grp (snk g* g) (with-struct (grp- grph) g* (destructuring-bind (a b) ee (declare (fixnum a b)) (graph:del grph a b))))) (defun split-edge! (snk u v &key xy g &aux (xy* (if xy xy (vec:on-line* 0.5d0 (get-verts snk (list u v)))))) " split edge at xy (or middle if xy is nil). returns new vert ind (and new edges). " (declare (snek snk) (fixnum u v)) (snek:del-edge! snk u v :g g) (let ((c (add-vert! snk xy*))) (declare (fixnum c)) (let ((edges (list (snek:add-edge! snk c u :g g) (snek:add-edge! snk c v :g g)))) (declare (list edges)) (values c edges)))) (defun lsplit-edge! (snk ll &key xy g) (declare (snek snk) (list ll)) (destructuring-bind (a b) ll (declare (fixnum a b)) (split-edge! snk a b :xy xy :g g))) (defun verts-in-rad (snk xy rad) (declare (snek snk) (vec:vec xy) (double-float rad)) (with-struct (snek- verts zmap) snk (declare (type (simple-array double-float) verts)) (zmap:verts-in-rad zmap verts xy rad))) <|start_filename|>examples/asemic-3.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (load "../utils/state") (defun test-centroids (counts nc ncn) (reduce (lambda (x y) (and x y)) (loop for i from 0 below nc collect (multiple-value-bind (val exists) (gethash i counts) (and exists (>= val ncn)))))) (defun get-dst (centroids cand) (first (sort (loop for c in centroids and i from 0 collect (list i (vec:dst cand c))) #'< :key #'second))) (defun -glyph-generate-pts (xy bbox centroids nc ncn) (let ((counts (make-hash-table :test #'equal)) (centroid-pts (make-hash-table :test #'equal))) (loop for i from 0 do (vec:with-xy (bbox bx by) (let ((cand (rnd:in-box bx by :xy xy))) (destructuring-bind (c dst) (get-dst centroids cand) (multiple-value-bind (val exists) (gethash c counts) (cond ((and exists (< val ncn)) (progn (setf (gethash c centroid-pts) (append (list cand) (gethash c centroid-pts))) (incf (gethash c counts)))) ((not exists) (progn (setf (gethash c centroid-pts) (list cand)) (setf (gethash c counts) 1)))))))) until (test-centroids counts nc ncn)) (let ((pts (loop for i from 0 below nc collect (gethash i centroid-pts)))) (apply #'append pts)))) (defun make-glyph (xy bbox nc ncn) (vec:with-xy ((vec:scale bbox 0.5d0) bx by) (-glyph-generate-pts xy bbox (rnd:nin-box nc bx by :xy xy) nc ncn))) (defun init-line (width line-chars sxy bbox) (let ((snk (snek:make))) (vec:with-xy (sxy sx sy) (vec:with-xy (bbox bx yy) (loop for px in (math:linspace line-chars sx (+ sx width)) collect (snek:add-path! snk (make-glyph (vec:vec px sy) bbox 2 2) :g (snek:add-grp! snk))))) snk)) (defun draw-grid (size border line-chars line-num sx sy rad grains sand) (loop for x in (math:linspace line-chars border (- size border)) do (loop for y in (math:linspace line-num border (- size border)) do (sandpaint:lin-path sand (list (vec:vec (- x sx) (- y sy)) (vec:vec (+ x sx) (- y sy)) (vec:vec (+ x sx) (+ y sy)) (vec:vec (- x sx) (+ y sy)) (vec:vec (- x sx) (- y sy))) rad grains)))) (defun draw-block-grid (size border line-chars line-num sx sy grains sand) (loop for x in (math:linspace line-chars border (- size border)) do (loop for y in (math:linspace line-num border (- size border)) do (sandpaint:pix sand (rnd:nin-box grains sx sy :xy (vec:vec x y)))))) (defun main (size fn) (let ((border 110d0) (char-rad 46d0) (line-chars 20) (line-num 10) (grains 95) (sand (sandpaint:make size :fg (pigment:white 0.009) :bg (pigment:white)))) (sandpaint:set-fg-color sand (pigment:vdark 0.009)) (draw-block-grid size border line-chars line-num 19d0 34d0 600000 sand) (sandpaint:set-fg-color sand (pigment:white 0.009)) (loop for y in (math:linspace line-num border (- size border)) do (format t "~a ~%" y) (let ((snk (init-line (- size (* 2.0 border)) line-chars (vec:vec border y) (vec:vec 17d0 30d0))) (state-gen (get-walker-state-gen (lambda () (rnd:get-acc-circ-stp*))))) (loop for i from 0 below 500 do (snek:with (snk) (snek:itr-verts (snk v) (snek:move-vert? v (rnd:in-circ 0.1d0)) (snek:move-vert? v (funcall state-gen v 0.00001d0)))) (snek:itr-grps (snk g :collect nil) (sandpaint:bzspl-stroke sand (snek:get-grp-as-bzspl snk g) grains))))) ;(draw-grid size border line-chars line-num 18d0 33d0 0.8d0 60 sand) (sandpaint:pixel-hack sand) (sandpaint:save sand fn :gamma 1.5 :bits 16))) (time (main 1000 (second (cmd-args)))) <|start_filename|>src/state.lisp<|end_filename|> (in-package :state) (defmacro awith ((st key &key default) &body body) " access key of state as state::it, the final form of body is assigned to state key of state " (with-gensyms (sname kname res dname s) `(let* ((,sname ,st) (,dname ,default) (,kname ,key) (,s (state-s ,sname)) (it (gethash ,kname (state-s ,sname) ,dname)) (,res (progn ,@body))) (setf (gethash ,kname (state-s ,sname)) ,res)))) (defstruct (state (:constructor make ())) (s (make-hash-table :test #'equal) :type hash-table)) (defun sget (st key &key default) " get key of state (or default) " (declare (state st)) (gethash key (state-s st) default)) (defun mget (st keys &key default) " get keys of state (or default) " (declare (state st) (list keys)) (loop for key in keys collect (gethash key (state-s st) default))) (defun sset (st key v) " set key of st to v, returns v " (declare (state st)) (setf (gethash key (state-s st)) v)) (defun mset (st keys v) " set keys of st to v. returns keys. " (declare (state st) (list keys)) (loop for k in keys do (setf (gethash k (state-s st)) v)) keys) (defun kset (st key v) " same as sset, returns key " (declare (state st)) (sset st key v) key) <|start_filename|>src/snek.lisp<|end_filename|> (in-package :snek) (defstruct (snek (:constructor -make-snek)) (name nil :type symbol :read-only t) (wc 0 :type fixnum) (verts nil :type simple-array) (num-verts 0 :type fixnum) (zmap nil) (prm-names nil :read-only t) (alt-names nil :read-only t) (grps (make-hash-table :test #'equal)) (prms (make-hash-table :test #'equal)) (vert-names (make-hash-table :test #'equal)) (max-verts nil :type fixnum :read-only t) (grp-size nil :type fixnum :read-only t)) ; ----- GROUPS AND PRIMITIVES ----- (defstruct (grp (:constructor -make-grp)) (name nil :type symbol :read-only t) (grph nil :type graph::graph) (type nil :type symbol :read-only t) (props nil)) (defstruct (prm (:constructor -make-prm)) (name nil :type symbol :read-only t) (type nil :type symbol :read-only t) (verts (make-adjustable-vector :type 'fixnum) :read-only nil) (num-verts 0 :type fixnum) (args nil :type list :read-only nil) (props nil)) ; ----- END ----- (defun -make-fxns (defaults &optional extras) (loop with res = (make-generic-hash-table :init defaults) for (a fx of-type function) in extras do (setf (gethash a res) fx) finally (return res))) (defun make (&key (max-verts 100000) (grp-size 100) name prms alts) " constructor for snek instances. - max-verts is the maximum number of verts in snek (across all grps). - alts is a list of tuples: (('alt-x #'do-alt-x) ('alt-y #'do-alt-y) ...) where alt-x is the name of an alteration struct and do-alt-x is the name of a function that applies alt-x to snek. see snek-alterations for examples. - prms is a list of tuples: (('type1 #'type1-rfx) ('type2 #'type2-rfx) ...) with prm types and corresponding rfxns used to render that prm type. " (declare (fixnum max-verts grp-size) (list prms alts) (symbol name)) (-make-snek :name name :verts (make-array (* max-verts 2) :initial-element 0d0 :element-type 'double-float) :max-verts max-verts :grp-size grp-size :alt-names (-make-fxns (list '(add-edge-alt do-add-edge-alt) '(add-vert-alt do-add-vert-alt) '(move-vert-alt do-move-vert-alt) '(append-edge-alt do-append-edge-alt) '(append-edge-segx-alt do-append-edge-segx-alt) '(split-edge-alt do-split-edge-alt) '(del-edge-alt do-del-edge-alt) '(vadd-edge-alt do-vadd-edge-alt) '(alt-then do-alt-then) '(alt-then* do-alt-then*)) alts) :prm-names (-make-fxns (list (list nil (lambda (snk p &optional ea) (declare (ignore ea)) (get-prm-vert-inds snk :p p))) (list :v (lambda (snk p &optional ea) (declare (ignore ea)) (get-prm-vert-inds snk :p p))) (list :vv (lambda (snk p &optional ea) (declare (ignore ea)) (get-prm-verts snk :p p)))) prms) :grps (make-generic-hash-table :init (list (list nil (-make-grp :name :main :type :main :grph (graph:make :size grp-size))))))) <|start_filename|>src/packages.lisp<|end_filename|> (defpackage :vec (:use :common-lisp) (:export :*half* :*one* :*zero* :add :all-inside :angle :copy :cos-sin :cross :div :dot :dst :dst* :dst2 :fan :flip :from :idiv :iscale :isub :ladd :ladd* :ldiv :ldiv* :ldot :ldst :ldst* :len :len2 :lmid :lmid :lmult :lmult* :lon-line* :lrot :lround :lscale* :lsub :lsub* :mid :mult :neg :norm :nsub :on-circ :on-line :on-line* :on-spiral :one :op :perp :polygon :psegx :ptinside :rect :rep :rot :sarr-get :sarr-set :scale :segdst :segx :segx* :shift-scale :shift-scale* :sin-cos :square :sub :sum :tolist :vec :vec* :vec-coerce :with-loop-grid :with-loop-grid* :with-xy :with-xy-short :zero) (:import-from :common-lisp-user :vextend :close-path :ensure-vector :make-adjustable-vector :with-gensyms)) (defpackage :math (:use :common-lisp) (:export :add :clamp :close-path :convex-split :copy-sort :cpath :curvature-offset-paths :curvature-offsets :dadd :daddmod* :ddiv :ddst :ddxy :dfloat :dfloat* :dmult :dop :dscale :dscale* :dsub :dsum :hatch :inc :int :int* :kappa :lget :line-from :linspace :mid-rad :mod+ :mod- :mod2 :nrep :on-line :path-angles :path-normals-closed :path-normals-open :path-offset :path-simplify :path-tangents :percentiles :range :range-search :rep :sfloat :sfloat* :stipple :stitch :sub :with-linspace) (:import-from :common-lisp-user :PI5 :ensure-vector :length-1 :make-adjustable-vector :to-adjustable-vector :to-list :to-vector :vector-last :vextend :with-gensyms)) (defpackage :rnd (:use :common-lisp) (:export :array-split :bernoulli :either :get-acc-circ-stp* :get-acc-lin-stp :get-acc-lin-stp* :get-circ-stp* :get-lin-stp :get-lin-stp* :in-box :in-circ :make-rnd-state :nin-box :nin-circ :non-circ :non-line :non-line* :norm :nrnd :nrnd* :nrnd-from :nrnd-u-from :nrndbtwn :nrndi :nrndi* :on-circ :on-line :on-line* :prob :probsel :rcond :rep :rep* :rnd :rnd* :rndbtwn :rndget :rndi :rndi* :rndspace :rndspacei :set-rnd-state :shuffle :with-in-box :with-in-circ :with-on-line :with-prob :with-rndspace) (:import-from :common-lisp-user :ensure-vector :make-adjustable-vector :to-vector :vextend :with-gensyms)) (defpackage :state (:use :common-lisp) (:export :awith :kset :make :mget :mset :sget :sset :with) (:import-from :common-lisp-user :with-gensyms)) (defpackage :pigment (:use :common-lisp) (:export :black :cmyk :dark :from-list :gray :hsv :mdark :rgb :rgba :show :show :to-hex :to-list :to-list* :transparent :vdark :white :with :with*) (:import-from :common-lisp-user :ensure-vector :with-gensyms)) (defpackage :hset (:use :common-lisp) (:export :add :add* :del :del* :make :mem :mem* :num :to-list)) (defpackage :graph (:use :common-lisp) (:export :add :del :get-edges :get-incident-edges :get-loop :get-num-edges :get-num-verts :get-verts :make :mem :to-list :vmem :with-graph-edges) (:import-from :common-lisp-user :flatten :make-adjustable-vector :vector-last :vextend :with-gensyms :with-struct)) (defpackage :bzspl (:use :common-lisp) (:export :adaptive-pos :bzx :len :make :normal :pos :pos* :rndpos :tangent :with-rndpos) (:import-from :common-lisp-user :PI5 :length-1 :make-adjustable-vector :to-list :to-vector :vector-last :vextend :with-gensyms :with-struct)) (defpackage :lin-path (:use :common-lisp) (:export :make :move :pos :pos* :rndpos) (:import-from :common-lisp-user :with-struct)) (defpackage :zmap (:use :common-lisp) (:export :make :verts-in-rad :with-verts-in-rad) (:import-from :common-lisp-user :make-adjustable-vector :vextend :with-gensyms :with-struct)) (defpackage :sandpaint (:use :common-lisp) (:export :arr-circ :arr-pix :bzspl-stroke :chromatic-aberration :circ :clear :dens-stroke :filter-walk :flip-x :flip-y :get-size :lin-path :make :pix :pix-overlap :pix-overlap* :pixel-hack :png-open :reflect-diag :reflect-x :reflect-y :rnd-copy-rect :rot :sample :save :set-bg-color :set-fg-color :stroke :strokes) (:import-from :common-lisp-user :ensure-filename :with-gensyms :with-struct)) (defpackage :draw-svg (:use :common-lisp) (:export :*short* :*long* :bzspl :circ :circs :cpath :hatch :make :make* :mhatch :path :save :set-rep-scale :set-stroke :set-stroke-width :show-boundary :show-crop :wbzspl :wcirc :wcircs :wpath) (:import-from :common-lisp-user :close-path :ensure-filename :make-adjustable-vector :to-list :to-vector :vector-last :vextend :with-struct)) (defpackage :draw-tile-svg (:use :common-lisp) (:export :lstipple :lstipple* :make :path :rstipple :save) (:import-from :common-lisp-user :append-postfix :ensure-filename :ensure-vector :length-1 :make-adjustable-vector :to-adjustable-vector :to-vector :vextend :vextend* :with-struct)) (defpackage :obj (:use :common-lisp) (:export :add-face :add-verts-from-vec :add-line :make :save) (:import-from :common-lisp-user :vextend :ensure-filename :make-adjustable-vector :with-struct)) (defpackage :snek (:use :common-lisp) (:export :add-edge! :add-edge? :add-edges! :add-grp! :add-path! :add-path*! :add-polygon! :add-prm! :add-vert! :add-vert? :add-verts! :alt-then? :append-edge-segx? :append-edge? :center! :cwith :del-edge! :del-edge? :draw-circ :draw-edges :draw-verts :edge-exists :edge-length :get-all-grps :get-all-prms :get-all-verts :get-edges :get-grp :get-grp-as-bzspl :get-grp-loop :get-grp-num-verts :get-grp-props :get-grp-verts :get-incident-edges :get-num-edges :get-num-verts :get-prm :get-prm-props :get-prm-vert-inds :get-prm-verts :get-vert :get-vert-by-name :get-vert-ind-by-name :get-vert-inds :get-vert-inds-by-name :get-verts :get-verts-by-name :is-vert-in-grp :itr-edges :itr-grp-verts :itr-grps :itr-prm-verts :itr-prms :itr-verts :ladd-edge! :ladd-edge? :ldel-edge! :ldel-edge? :ledge-length :lsplit-edge! :lsplit-edge? :make :make-mutate :move-vert! :move-vert? :mutate :prmf :prmr :prune-edges-by-len! :psvg-get-prm-types :relative-neighborhood! :sel-args :set-grp-props! :set-prm-props! :split-edge! :split-edge? :vadd-edge? :verts-in-rad :with :with-dx :with-rnd-edge :with-rnd-vert :with-verts-in-rad :zwith) (:import-from :common-lisp-user :append-postfix :close-path :exec-with-args :flatten :make-adjustable-vector :make-generic-hash-table :to-list :vextend :with-gensyms :with-struct)) ;(declaim (inline rnd:rnd rnd:rndi rnd:rnd* rnd:rndbtwn rnd:on-line rnd:in-circ)) ;(declaim (inline vec:zero vec:one vec:vec vec:cos-sin vec:sin-cos vec:scale ; vec:iscale vec:from vec:dot vec:cross vec:dst vec:dst2 ; vec:add vec:sub vec:mult vec:mid vec:div vec:perp vec:flip ; vec:copy vec:neg vec:on-line)) <|start_filename|>src/draw-svg.lisp<|end_filename|> (in-package :draw-svg) (defparameter *short* 1000d0) (defparameter *long* 1414.285d0) (declaim (type double-float *short* *long*)) (defstruct draw-svg (layout nil :type symbol :read-only t) (width 0d0 :type double-float :read-only t) (height 0d0 :type double-float :read-only t) (stroke "black" :type string :read-only nil) (stroke-width 1.1d0 :type double-float :read-only nil) (rep-scale 1d0 :type double-float :read-only nil) (scene nil :read-only nil)) (defun -view-box (width height) (format nil "0 0 ~f ~f" width height)) (defun -get-scene (layout) (case layout (:a4-landscape (cl-svg:make-svg-toplevel 'cl-svg:svg-1.1-toplevel :height "210mm" :width "297mm" :view-box (-view-box *long* *short*))) (:a4-portrait (cl-svg:make-svg-toplevel 'cl-svg:svg-1.1-toplevel :height "297mm" :width "210mm" :view-box (-view-box *short* *long*))) (:a3-landscape (cl-svg:make-svg-toplevel 'cl-svg:svg-1.1-toplevel :height "297mm" :width "420mm" :view-box (-view-box *long* *short*))) (:a3-portrait (cl-svg:make-svg-toplevel 'cl-svg:svg-1.1-toplevel :height "420mm" :width "297mm" :view-box (-view-box *short* *long*))) (otherwise (error "invalid layout. use: :a4-portrait, :a4-landscape, :a3-landscape or :a3-portrait.")))) (defun -get-width-height (layout) (case layout (:a4-landscape (list *long* *short*)) (:a4-portrait (list *short* *long*)) (:a3-landscape (list *long* *short*)) (:a3-portrait (list *short* *long*)))) (defun -coerce-hex (c) (if (equal (type-of c) 'pigment:rgba) (pigment:to-hex c) c)) (defun make (&key (layout :a4-landscape) stroke (stroke-width 1.1d0) (rep-scale 1d0)) (destructuring-bind (width height) (-get-width-height layout) (make-draw-svg :layout layout :stroke-width stroke-width :stroke (-coerce-hex (if stroke stroke "black")) :rep-scale rep-scale :height height :width width :scene (-get-scene layout)))) (defun make* (&key (height 1000d0) (width 1000d0) stroke (stroke-width 1.1d0) (rep-scale 1d0)) (make-draw-svg :layout 'custom :stroke-width stroke-width :rep-scale rep-scale :stroke (-coerce-hex (if stroke stroke "black")) :height height :width width :scene (cl-svg:make-svg-toplevel 'cl-svg:svg-1.1-toplevel :height height :width width))) (defun set-stroke (psvg stroke) (declare (draw-svg psvg)) (setf (draw-svg-stroke psvg) (-coerce-hex stroke))) (defun set-stroke-width (psvg sw) (declare (draw-svg psvg) (double-float sw)) (setf (draw-svg-stroke-width psvg) sw)) (defun set-rep-scale (psvg rs) (declare (draw-svg psvg) (double-float rs)) (setf (draw-svg-stroke-width psvg) rs)) (defun show-boundary (psvg &key sw (stroke "red")) (declare (draw-svg psvg)) (with-struct (draw-svg- width height) psvg (let ((mw (* 0.5d0 width)) (mh (* 0.5d0 height))) (path psvg (vec:rect mw mh :xy (vec:vec mw mh)) :closed t :sw sw :stroke stroke)))) (defun -select-stroke (psvg stroke) (if stroke stroke (draw-svg-stroke psvg))) (defun -select-rep-scale (psvg rs) (if rs rs (draw-svg-rep-scale psvg))) (defun -select-fill (fill) (if fill fill "none")) (defun show-crop (psvg &key (len 3d0) sw (stroke "red")) (declare (draw-svg psvg)) (with-struct (draw-svg- width height) psvg (loop for m in (list (list (vec:vec 0d0 0d0) (vec:vec len 0d0)) (list (vec:vec width 0d0) (vec:vec (- width len) 0d0)) (list (vec:vec 0d0 height) (vec:vec len height)) (list (vec:vec width height) (vec:vec (- width len) height))) do (path psvg m :closed t :sw sw :stroke stroke)))) (defun accumulate-path (pth a &optional b (offset (vec:zero))) (declare (vector pth) (vec:vec a)) (vextend (vec:with-xy-short ((vec:add a offset) x y) (if (> (length pth) 0) (cl-svg:line-to x y) (cl-svg:move-to x y))) pth) (when b (vextend (vec:with-xy-short ((vec:add b offset) x y) (cl-svg:line-to x y)) pth))) (defun finalize-path (pth) (loop with res = (cl-svg:make-path) for x across pth do (cl-svg:with-path res x) finally (return res))) (defun path (psvg pts &key sw fill stroke (fo 1d0) (so 1d0) closed (simplify nil)) (declare (draw-svg psvg) (list pts)) (with-struct (draw-svg- scene stroke-width) psvg (cl-svg:draw scene (:path :d (cl-svg:path (finalize-path (loop with pth of-type vector = (make-adjustable-vector) for p of-type vec:vec in (if simplify (math:path-simplify pts simplify) pts) do (accumulate-path pth p) finally (progn (when closed (vextend "Z" pth)) (return pth)))))) :fill (-select-fill fill) :fill-opacity fo :stroke-opacity so :stroke (-select-stroke psvg stroke) :stroke-width (if sw sw stroke-width)))) (defun -move-to (res p) (declare (vector res) (vec:vec p)) (vec:with-xy-short (p x y) (vextend (format nil "M~a,~a " x y) res))) (defun -quadratric (res p q) (declare (vector res) (vec:vec p q)) (vec:with-xy-short (p ax ay) (vec:with-xy-short (q bx by) (vextend (format nil "Q~a,~a ~a,~a " ax ay bx by) res)))) ; ----- HATCH ----- (defun -get-pts (pts closed) (declare (sequence pts)) (let ((res (make-adjustable-vector)) (is-cons (equal (type-of pts) 'cons))) (declare (vector res)) (if is-cons (loop for p of-type vec:vec in pts do (vextend p res)) (loop for p of-type vec:vec across pts do (vextend p res))) (when closed (vextend (if is-cons (first pts) (aref pts 0)) res)) res)) (defun hatch (psvg pts &key (angles (list 0d0 (* 0.5d0 PI))) (rnd #'identity) (steps (lambda (n) (math:linspace n 0d0 1d0))) stitch drop closed rs sw &aux (draw (if drop (lambda (p) (rnd:prob drop nil (draw-svg:path psvg p :sw sw))) (lambda (p) (draw-svg:path psvg p :sw sw))))) (declare (function draw)) (let ((res (math:hatch (-get-pts pts closed) :angles angles :steps steps :rs (-select-rep-scale psvg rs) :rnd rnd))) (loop for h across (if stitch (math:stitch res) res) do (if (and (> (length h) 0) (every #'identity h)) (funcall draw h))))) (defun mhatch (psvg mpts &key (angles (list 0d0 (* 0.5d0 PI))) (rnd #'identity) (steps (lambda (n) (math:linspace n 0d0 1d0))) stitch drop closed rs sw &aux (draw (if drop (lambda (p) (rnd:prob drop nil (draw-svg:path psvg p :sw sw))) (lambda (p) (draw-svg:path psvg p :sw sw))))) (declare (draw-svg psvg)) (let ((res (make-adjustable-vector))) (loop for pts across mpts do (loop for h across (math:hatch (-get-pts pts closed) :angles angles :steps steps :rs (-select-rep-scale psvg rs) :rnd rnd) do (vextend h res))) (loop for h across (if stitch (math:stitch res) res) do (when (and (> (length h) 0) (every #'identity h)) (funcall draw h))))) ; ----- BZSPL ----- (defun -fl (a) (declare (list a)) (first (last a))) (defun -roll-once (a) (declare (list a)) (append (subseq a 1) (list (first a)))) (defun -do-open (pts pth) (-move-to pth (first pts)) (if (= (length pts) 3) ; 3 pts (-quadratric pth (second pts) (third pts)) ; more than 3 pts (let ((inner (subseq pts 1 (1- (length pts))))) (loop for a in inner and b in (cdr inner) do (-quadratric pth a (vec:mid a b))) (-quadratric pth (-fl inner) (-fl pts))))) (defun -do-closed (pts pth) (-move-to pth (vec:mid (-fl pts) (first pts))) (loop for a in pts and b in (-roll-once pts) do (-quadratric pth a (vec:mid a b)))) (defun bzspl (psvg pts &key closed sw stroke (so 1d0)) (declare (draw-svg psvg)) (when (< (length pts) 3) (error "needs at least 3 pts.")) (with-struct (draw-svg- scene stroke-width) psvg (let ((pth (make-adjustable-vector))) (if closed (-do-closed pts pth) (-do-open pts pth)) (cl-svg:draw scene (:path :d (cl-svg:path (finalize-path pth))) :fill "none" :stroke (-select-stroke psvg stroke) :stroke-opacity so :stroke-width (if sw sw stroke-width))))) (defun wbzspl (psvg pts offset &key (width 1d0) closed sw rs) (declare (draw-svg psvg)) (loop for s in (math:linspace (math:int (ceiling (* (-select-rep-scale psvg rs) width))) (- (/ width 2d0)) (/ width 2d0)) do (bzspl psvg (vec:lsub* pts (vec:scale offset s)) :closed closed :sw sw))) ; ----- WPATH ----- (defun wpath (psvg pts &key width sw rs (simplify nil) (opposite t) stroke (so 1d0)) (declare (draw-svg psvg) (list pts) (boolean simplify opposite)) (with-struct (draw-svg- scene stroke-width) psvg (if (or (not width) (<= width 1d0)) ; single path (path psvg pts :sw sw :simplify simplify :stroke stroke :so so) ; multi path (let ((pth (make-adjustable-vector)) (rep (math:int (ceiling (* (-select-rep-scale psvg rs) width)))) (rup (* width 0.5d0)) (rdown (- (* width 0.5d0)))) (when (< rep 2) (setf rep 2)) (when (and opposite (= 0 (math:mod2 rep))) (setf rep (1+ rep))) (loop with pts* = (if simplify (math:path-simplify pts simplify) pts) for a in pts* and b in (cdr pts*) do (when opposite (accumulate-path pth a)) (loop for s in (math:linspace rep rdown rup) and i from 0 do (accumulate-path pth (if (= (math:mod2 i) 0) a b) (if (= (math:mod2 i) 0) b a) (vec:scale (vec:norm (vec:perp (vec:sub b a))) s))) (when opposite (accumulate-path pth b))) (cl-svg:draw scene (:path :d (cl-svg:path (finalize-path pth))) :fill "none" :stroke (-select-stroke psvg stroke) :stroke-opacity so :stroke-width (if sw sw stroke-width)))))) ; ----- CPATH ----- (defun -accumulate-cpath (diagonals rep closed &aux (n (length diagonals))) (loop with res of-type vector = (make-adjustable-vector) for s of-type double-float in (math:linspace rep 0d0 1d0) and k of-type fixnum from 0 do (loop for i of-type fixnum from 0 below n and i- of-type fixnum downfrom (1- n) do (vextend (vec:on-line* s (aref diagonals (if closed i (if (= (math:mod2 k) 0) i i-)))) res)) finally (return (to-list res)))) (defun cpath (psvg pts &key (width 1d0) closed (clim -0.5d0) stroke (slim -0.95d0) (simplify 1d0) sw rs (so 1d0) &aux (pts* (to-vector (if closed (close-path pts) pts))) (width* (* width 0.5d0))) (declare (draw-svg psvg) (list pts)) (let ((rep (math:int (ceiling (* (-select-rep-scale psvg rs) width)))) (diagonals (math::-get-diagonals (to-vector (math:path-simplify pts* simplify)) width* clim slim closed))) (path psvg (-accumulate-cpath diagonals rep closed) :stroke stroke :sw sw :so so))) ; ----- CIRC ----- ; draw circle with arc. (defun -arccirc (x y r*) (let* ((r (math:sfloat r*)) (r2 (* 2 r))) (declare (float r r2)) (format nil "M~a,~a m -~a,0 a ~a,~a 0 1,0 ~a 0 a ~a,~a 0 1,0 -~a 0" x y r r r r2 r r r2))) (defun circ (psvg xy rad &key fill sw aspath stroke (so 1d0) (fo 1d0)) (declare (draw-svg psvg) (vec:vec xy) (double-float rad)) (with-struct (draw-svg- scene stroke-width) psvg (vec:with-xy-short (xy x y) (let ((sw* (if sw sw stroke-width))) (if aspath (cl-svg:draw scene (:path :d (-arccirc x y rad)) :fill (-select-fill fill) :stroke (-select-stroke psvg stroke) :stroke-width sw* :fill-opacity fo :stroke-opacity so) (cl-svg:draw scene (:circle :cx x :cy y :r rad) :fill (-select-fill fill) :stroke (-select-stroke psvg stroke) :stroke-width sw* :fill-opacity fo :stroke-opacity so)))))) ; TODO: fxn to do this with multiple rads? (defun circs (psvg vv rad &key fill stroke sw aspath (fo 1d0) (so 1d0)) (declare (draw-svg psvg) (list vv) (double-float rad)) (loop for xy of-type vec:vec in vv do (circ psvg xy rad :fill fill :sw sw :stroke stroke :aspath aspath :fo fo :so so))) ; ----- WCIRC ----- (defun wcirc (psvg xy rad &key outer-rad rs aspath stroke (so 1d0) (fo 1d0)) (declare (draw-svg psvg)) (let* ((inner-rad (max 0.01d0 (if outer-rad rad 0.01d0))) (outer-rad* (if outer-rad outer-rad rad)) (n (math:int (* (ceiling (abs (- outer-rad* inner-rad))) (-select-rep-scale psvg rs))))) (loop for r of-type double-float in (math:linspace n inner-rad outer-rad*) do (circ psvg xy r :aspath aspath :so so :fo fo :stroke (-select-stroke psvg stroke))))) (defun wcircs (psvg pts rad &key outer-rad rs aspath stroke (so 1d0) (fo 1d0)) (declare (draw-svg psvg)) (loop for pt of-type vec:vec in pts do (wcirc psvg pt rad :outer-rad outer-rad :rs rs :stroke stroke :aspath aspath :so so :fo fo))) (defun save (psvg fn) (declare (draw-svg psvg)) (with-struct (draw-svg- scene) psvg (with-open-file (fstream (ensure-filename fn ".svg") :direction :output :if-exists :supersede) (declare (stream fstream)) (cl-svg:stream-out fstream scene)))) <|start_filename|>examples/asemic.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (load "../utils/state") (defun init-line (sxy width line-chars char-num char-rad) (let ((snk (snek:make))) (vec:with-xy (sxy sx sy) (loop for char-pos-x in (rnd:rndspace line-chars sx (+ sx width) :order t) for char-pos-y in (rnd:rndspace line-chars (- sy 10d0) (+ sy 10d0)) for char-height in (math:add (rnd:rndspace line-chars 0.4d0 1d0) (math:dscale* (rnd:bernoulli line-chars 0.05d0) 2d0)) collect (snek:add-verts! snk (mapcar (lambda (v) (vec:add (vec:mult v (vec:vec 2.0d0 char-height)) (vec:vec char-pos-x char-pos-y))) (rnd:nin-circ (rnd:rndi* char-num) (rnd:rnd char-rad)))))) snk)) (defun main (size fn) (let ((border 100d0) (char-num (list 1 7)) (char-rad 22d0) (line-chars 30) (line-num 20) (sand (sandpaint:make size :fg (pigment:black 0.009) :bg (pigment:white)))) (loop for y in (math:linspace line-num border (- size border)) do (format t "~a ~%" y) (let ((snk (init-line (vec:vec border y) (- size (* 2.0 border)) line-chars char-num char-rad)) (drift (rnd:get-acc-circ-stp*)) (state-gen (get-walker-state-gen (lambda () (rnd:get-acc-circ-stp*))))) (snek:with (snk) (snek:itr-verts (snk v) (snek:move-vert? v (funcall drift 0.04d0)))) (loop for i from 0 below 200 do (snek:with (snk) (snek:itr-verts (snk v) ;(snek:move-vert? v (funcall state-gen v 0.00009d0)) (snek:move-vert? v (rnd:in-circ 0.4d0)))) (sandpaint:bzspl-stroke sand (bzspl:make (snek:get-all-verts snk)) 2500)))) (sandpaint:save sand fn :gamma 1.5))) (time (main 1000 (second (cmd-args)))) <|start_filename|>src/graph.lisp<|end_filename|> (in-package :graph) " a simple (undirected) graph structure based on adjacency lists. " (defstruct (graph (:constructor -make-graph)) (size 0 :type fixnum :read-only t) (inc 0 :type float :read-only t) (num-edges 0 :type fixnum) (adj nil :type hash-table) (verts nil :type hash-table) (closed nil :type boolean) (make-hset nil :read-only t)) (defun make (&key (closed nil) (size 1000) (inc 1.5)) (-make-graph :size size :inc inc :num-edges 0 :adj (make-hash-table :test #'eql :size size :rehash-size inc) :verts (hset:make :size size :inc inc) :closed closed :make-hset (lambda (x) (hset:make :init x :size size :inc inc)))) (defun -add (make adj a b) (declare (fixnum a b)) (multiple-value-bind (val exists) (gethash a adj) (if (not exists) (progn (setf val (funcall make (list b)) (gethash a adj) val) t) (hset:add val b)))) (defun add (grph a b) (declare (graph grph) (fixnum a b)) (with-struct (graph- adj make-hset verts) grph (if (progn (hset:add* verts (list a b)) (reduce (lambda (x y) (or x y)) (list (-add make-hset adj a b) (-add make-hset adj b a)))) (progn (incf (graph-num-edges grph) 2) t)))) (defun -del (adj a b) (declare (fixnum a b)) (multiple-value-bind (val exists) (gethash a adj) (when exists (hset:del val b)))) (defun -prune (adj verts a) (declare (fixnum a)) (multiple-value-bind (val exists) (gethash a adj) (if (not exists) (hset:del verts a) (when (< (hset:num val) 1) (progn (remhash a adj) (hset:del verts a)))))) (defun del (grph a b) (declare (graph grph) (fixnum a b)) (with-struct (graph- adj verts) grph (if (reduce (lambda (x y) (or x y)) (list (-del adj a b) (-del adj b a))) (progn (-prune adj verts a) (-prune adj verts b) (incf (graph-num-edges grph) -2) t)))) (defun get-num-edges (grph) (declare (graph grph)) (graph-num-edges grph)) (defun get-num-verts (grph) (declare (graph grph)) (hset:num (graph-verts grph))) (defun mem (grph a b) (declare (graph grph) (fixnum a b)) (with-struct (graph- adj) grph (multiple-value-bind (val exists) (gethash a adj) (when exists (hset:mem val b))))) (defun get-edges (grph) (declare (graph grph)) (let ((res (make-adjustable-vector :size (graph-size grph))) (adj (graph-adj grph))) (declare (type (array list) res) (hash-table adj)) (loop for a of-type fixnum being the hash-keys of adj do (loop for b of-type fixnum being the hash-keys of (gethash a adj) if (<= a b) do (vextend (list a b) res))) res)) (defun get-incident-edges (grph v) (declare (graph grph) (fixnum v)) (with-struct (graph- adj) grph (let ((a (gethash v adj))) (when a (loop for w of-type fixnum being the hash-keys of a collect (sort (list v w) #'<)))))) (defun -do-loop-walk (grph visited path) (declare (graph grph) (hash-table visited) (vector path)) (let ((edges (get-incident-edges grph (vector-last path)))) (when (not (= (length edges) 2)) (return-from -do-loop-walk nil)) (loop named lp for v of-type fixnum being the hash-keys of (hset:make :init (flatten edges)) if (not (hset:mem visited v)) do (vextend v path) (hset:add visited v) (return-from lp t)))) (defun get-loop (grph) " if the graph is closed this will return the indices of nodes that construct the closed loop, or nil, if there is not a single loop. " (declare (graph grph)) (with-struct (graph- closed adj) grph (when (not closed) (error "graph is not closed. use (graph:make ... :closed t)")) (when (< (hash-table-count adj) 1) (return-from get-loop nil)) (let* ((s (loop for k of-type fixnum being the hash-keys of adj repeat 1 return k)) (path (make-adjustable-vector :init (list s) :type 'fixnum)) (visited (hset:make :init (list s)))) (declare (vector path)) (loop with n of-type fixnum = (hash-table-count adj) until (= (length path) n) if (not (-do-loop-walk grph visited path)) do (return-from get-loop nil)) ;TODO: return this? ;(values path ok) path))) (defun get-verts (grph) (declare (graph grph)) (hset:to-list (graph-verts grph))) (defun vmem (grph v) (declare (graph grph) (fixnum v)) (hset:mem (graph-verts grph) v)) ; TODO: the collects here seem strange. improve? (defmacro with-graph-edges ((grph e) &body body) (with-gensyms (adj a b) `(let ((,adj (graph-adj ,grph))) (loop for ,a of-type fixnum being the hash-keys of ,adj collect (loop for ,b of-type fixnum being the hash-keys of (gethash ,a ,adj) do (setf ,e (list ,a ,b)) collect (list ,@body)))))) <|start_filename|>test/speed-snek-join.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (setf *print-pretty* t) (defun init-snek (n) (rnd:set-rnd-state 1) (let ((snk (snek:make :max-verts 500000 :grp-size 100))) (math:nrep n (snek:add-vert! snk (vec:rep (rnd:rnd 100d0)))) snk)) (defun main () (let* ((itt 1000000) (num 10000) (snk (init-snek num))) (time (loop for i from 0 below itt do (when (= (mod i 100000) 0) (format t "itt ~a edges ~a ~%" i (length (snek:get-edges snk)))) (snek:with (snk) (snek:add-edge? (rnd:rndi num) (rnd:rndi num)) (snek:del-edge? (rnd:rndi num) (rnd:rndi num))))) (setf snk (init-snek num)) (time (loop for i from 0 below itt do (when (= (mod i 100000) 0) (format t "itt ~a edges ~a ~%" i (length (snek:get-edges snk)))) (snek:cwith (snk %) (% (snek:add-edge? (rnd:rndi num) (rnd:rndi num))) (% (snek:del-edge? (rnd:rndi num) (rnd:rndi num)))))))) (require :sb-sprof) (sb-sprof:with-profiling (:max-samples 200000 :mode :cpu ;:mode :alloc ;:mode :time :report :graph) (main)) <|start_filename|>utils/state.lisp<|end_filename|> (defun get-walker-state-gen (get-state-fun) (let ((state (make-hash-table :test #'equal))) (lambda (i noise) (multiple-value-bind (curr exists) (gethash i state) (if (not exists) (setf (gethash i state) (setf curr (funcall get-state-fun)))) (funcall curr noise))))) <|start_filename|>utils/hypercube.lisp<|end_filename|> (defun get-projection-fxn (proj mid s) (lambda (x) (vec:add mid (vec:mult (vec:sum (loop for px in proj and ix in x collect (vec:scale px (math:dfloat ix)))) s)))) (defun do-count (state ind &optional (c 1)) (multiple-value-bind (val exists) (gethash ind state) (when (not exists) (setf val 0)) (setf (gethash ind state) (+ val c)))) (defun hypercube-edges (cube) (let ((edges (make-adjustable-vector)) (n (length (aref cube 0)))) (loop for a across cube do (loop for b across cube do (when (= (1- n) (loop for ai in a and bi in b count (= ai bi))) (vextend (list a b) edges)))) edges)) (defun hypercube (grid &optional init sel) (let ((n (length grid)) (respts (make-adjustable-vector))) (vextend (if init init (loop for g in grid collect (rnd:rndi 1 (1- g)))) respts) (loop for i from 0 below n do (let* ((pt (aref respts 0)) (val (+ (if sel (funcall sel) (expt -1 (rnd:rndi 2))) (nth i pt)))) (loop for x across respts do (let ((new (loop for p in x and j from 0 collect (if (= j i) val p)))) (vextend new respts))))) (values respts (hypercube-edges respts)))) (defun -walk (pp) (let ((ind (rnd:rndi 0 (length pp)))) (loop for p in pp and i from 0 collect (if (= i ind) (+ p (expt -1 (rnd:rndi 0 2))) p)))) (defun surface-walk (n pts) ; this is a little inefficient since it wont always select viable pts. ; it is fast enough. (let ((res (make-adjustable-vector)) (pts* (make-hash-table :test #'equal))) (loop for p across pts do (setf (gethash p pts*) t)) (vextend (rnd:rndget pts) res) (loop until (>= (length res) n) do (let ((new (-walk (aref res (1- (length res)))))) (multiple-value-bind (val exists) (gethash new pts*) (if exists (vextend new res))))) (to-list res))) ; RENDER FXNS (defun show-dots (psvg visited proj &optional (rad 1d0)) (loop for k being the hash-keys of visited do (draw-svg:circ psvg (funcall proj k) rad))) (defun tris (psvg proj n abc) (destructuring-bind (a b c) abc (loop for s in (math:linspace n 0d0 1d0) do (draw-svg:path psvg (list (vec:on-line s (funcall proj a) (funcall proj b)) (vec:on-line s (funcall proj a) (funcall proj c))))))) (defun quads (psvg proj n abcd) (destructuring-bind (a b c d) abcd (loop for s in (math:linspace n 0d0 1d0) do (draw-svg:path psvg (list (vec:on-line s (funcall proj a) (funcall proj b)) (vec:on-line s (funcall proj c) (funcall proj d))))))) (defun path (visited state pts selected) (loop for a in selected and b in (cdr selected) do (do-count state (list a b) (rnd:prob 0.1 3 1)) (setf (gethash a visited) t) (setf (gethash b visited) t))) (defun path-simple (state pts selected) (loop for a in selected and b in (cdr selected) do (do-count state (list a b) (rnd:prob 0.1 3 1)))) (defun path* (visited state pts selected) (loop for a in selected and b in (cdr selected) do (do-count state (list a b) 1) (setf (gethash a visited) t) (setf (gethash b visited) t))) (defun bzspl (psvg proj visited pts) (draw-svg:bzspl psvg (mapcar (lambda (x) (funcall proj x)) pts)) (setf (gethash (first pts) visited) t) (setf (gethash (first (last pts)) visited) t)) (defun wbzspl (psvg proj visited pts w) (print :hi) (draw-svg:wbzspl psvg (mapcar (lambda (x) (funcall proj x)) pts) (vec:vec 1d0 0d0) :width w) (setf (gethash (first pts) visited) t) (setf (gethash (first (last pts)) visited) t)) <|start_filename|>src/vec.lisp<|end_filename|> (in-package :vec) (declaim (optimize (speed 3))) (defconstant PII (* PI 2d0)) (declaim (type double-float PII)) (defmacro with-xy ((v x y) &body body) (declare (symbol x y)) (with-gensyms (vname) `(let* ((,vname ,v) (,x (vec-x ,vname)) (,y (vec-y ,vname))) (declare (double-float ,x ,y)) (progn ,@body)))) (defmacro with-xy-short ((v x y) &body body) (declare (symbol x y)) (with-gensyms (vname) `(let* ((,vname ,v) (,x (math:sfloat (vec-x ,vname))) (,y (math:sfloat (vec-y ,vname)))) (progn ,@body)))) (defmacro with-loop-grid ((grid xy) &body body) " loop over grid as xy in a 2d grid. " (declare (symbol xy)) (with-gensyms (grid* x y) `(let ((,grid* ,grid)) (loop for ,y of-type double-float in ,grid* do (loop for ,x of-type double-float in ,grid* do (let ((,xy (vec ,x ,y))) (progn ,@body))))))) (defmacro with-loop-grid* ((grid xy) &body body) " loop over grid as xy in a 2d grid. grid form is executed independently for each dimension. " (declare (symbol xy)) (with-gensyms (x y) `(loop for ,y of-type double-float in ,grid do (loop for ,x of-type double-float in ,grid do (let ((,xy (vec ,x ,y))) (progn ,@body)))))) (defmacro rep (&body body) `(vec (progn ,@body) (progn ,@body))) (defstruct (vec (:constructor -make-vec)) (x nil :type double-float :read-only t) (y nil :type double-float :read-only t)) (declaim (ftype (function () vec) zero one)) (declaim (ftype (function (double-float &optional double-float) vec) vec)) (declaim (ftype (function (double-float) vec) cos-sin sin-cos)) (declaim (ftype (function (vec double-float) vec) scale iscale)) (declaim (ftype (function (vec vec double-float) vec) from)) (declaim (ftype (function (vec vec) double-float) dot cross dst dst2)) (declaim (ftype (function (vec vec) vec) sub add mult div mid)) (declaim (ftype (function (vec) double-float) angle)) (declaim (ftype (function (vec) vec) perp flip copy neg)) (declaim (ftype (function (double-float vec vec) vec) on-line)) (defun vec (x &optional y) (declare (optimize (safety 0) speed (debug 0)) (double-float x)) (if y (-make-vec :x x :y y) (-make-vec :x x :y x))) (defun zero () (vec 0d0 0d0)) (defun one () (vec 1d0 1d0)) (defparameter *one* (vec:vec 1d0)) (defparameter *half* (vec:vec 0.5d0)) (defparameter *zero* (vec:vec 0d0)) (declaim (type vec *one* *half* *zero*)) (defun copy (v) (declare (vec v)) (vec (vec-x v) (vec-y v))) (defun tolist (v) (declare (vec v)) (list (vec-x v) (vec-y v))) (defun vec-coerce (x y) (vec (math:dfloat x) (math:dfloat y))) (defun flip (v) (declare (vec v)) (vec (vec-y v) (vec-x v))) (defun perp (v) (declare (vec v)) (vec (vec-y v) (- (vec-x v)))) ; TODO: this is probably unexpected behaviour (returning list, not vec) (defun vround (v) (declare (vec v)) (list (round (vec-x v)) (round (vec-y v)))) (declaim (inline -vfloor*) (ftype (function (vec) (values fixnum fixnum)) -vround*)) (defun -vround* (v) (declare (optimize (safety 0) speed (debug 0)) (vec v)) (values (round (vec-x v)) (round (vec-y v)))) (declaim (inline -vfloor*) (ftype (function (vec) (values fixnum fixnum)) -vfloor*)) (defun -vfloor* (v) (declare (optimize (safety 0) speed (debug 0)) (vec v)) (values (floor (vec-x v)) (floor (vec-y v)))) ;(defun -voutward-round (xy mid) ; (declare (vec xy mid)) ; (with-xy (mid mx my) ; (with-xy (xy x y) ; (values (math:int (if (<= x mx) (floor x) (ceiling x))) ; (math:int (if (<= y my) (floor y) (ceiling y))))))) (defun vec* (xy) " create (coerce) vec from list " (declare (optimize (safety 0) speed (debug 0)) (list xy)) (destructuring-bind (x y) (math:dfloat* xy) (declare (double-float x y)) (vec x y))) (defun sarr-get (a i &aux (ii (* 2 i))) " returns simple array (as 2d array) ind i. " (declare (optimize (safety 0) speed (debug 0)) (fixnum i ii) (type (simple-array double-float) a)) (vec (aref a ii) (aref a (1+ ii)))) (defun sarr-set (a i v &aux (ii (* 2 i))) " set simple array (as 2d array) in i to vec v. returns v. " (declare (optimize (safety 0) speed (debug 0)) (vec v) (fixnum i ii) (type (simple-array double-float) a)) (setf (aref a ii) (the double-float (vec-x v)) (aref a (1+ ii)) (the double-float (vec-y v))) v) ; MATHS (defun cos-sin (a) (declare (optimize (safety 0) speed (debug 0)) (double-float a)) (vec (cos a) (sin a))) (defun sin-cos (a) (declare (optimize (safety 0) speed (debug 0)) (double-float a)) (vec (sin a) (cos a))) (defun angle (v) (declare (optimize (safety 0) speed (debug 0)) (vec v)) (with-xy ((norm v) x y) (atan y x))) (defun from (a b s) (declare (optimize (safety 0) speed (debug 0)) (double-float s) (vec a b)) (vec (+ (vec-x a) (* s (vec-x b))) (+ (vec-y a) (* s (vec-y b))))) (declaim (inline scale)) (defun scale (a s) (declare (optimize (safety 0) speed (debug 0)) (vec a) (double-float s)) (vec (* (vec-x a) s) (* (vec-y a) s))) (defun neg (a) (declare (optimize (safety 0) speed (debug 0)) (vec a)) (scale a -1d0)) (defun iscale (a s) (declare (optimize (safety 0) speed (debug 0)) (vec a) (double-float s)) (vec (/ (vec-x a) s) (/ (vec-y a) s))) (declaim (inline sub)) (defun sub (a b) (declare (optimize (safety 0) speed (debug 0)) (vec a b)) (vec (- (vec-x a) (vec-x b)) (- (vec-y a) (vec-y b)))) (defun lsub (aa bb) (declare (optimize (safety 0) speed (debug 0)) (list aa bb)) (mapcar (lambda (a b) (declare (type vec a b)) (sub a b)) aa bb)) (defun lsub* (aa b) (declare (optimize (safety 0) speed (debug 0)) (list aa) (vec b)) (mapcar (lambda (a) (declare (type vec a)) (sub a b)) aa)) (defun isub (a b) (declare (optimize (safety 0) speed (debug 0)) (vec a b)) (vec (- (vec-x b) (vec-x a)) (- (vec-y b) (vec-y a)))) (defun op (fx a b) (declare (optimize (safety 0) speed (debug 0)) (vec a b)) (vec (funcall fx (vec-x a) (vec-x b)) (funcall fx (vec-y a) (vec-y b)))) (defun vabs (a) (declare (optimize (safety 0) speed (debug 0)) (vec a)) (vec (abs (vec-x a)) (abs (vec-y a)))) (declaim (inline add)) (defun add (a b) (declare (optimize (safety 0) speed (debug 0)) (vec a b)) (vec (+ (vec-x a) (vec-x b)) (+ (vec-y a) (vec-y b)))) (defun ladd (aa bb) (declare (optimize (safety 0) speed (debug 0)) (list aa bb)) (mapcar (lambda (a b) (declare (type vec a b)) (add a b)) aa bb)) (defun ladd* (aa b) (declare (optimize (safety 0) speed (debug 0)) (list aa) (vec b)) (mapcar (lambda (a) (declare (type vec a)) (add a b)) aa)) (defun lscale* (aa s) (declare (optimize (safety 0) speed (debug 0)) (list aa) (double-float s)) (mapcar (lambda (a) (declare (type vec a)) (scale a s)) aa)) (defun mult (a b) (declare (optimize (safety 0) speed (debug 0)) (vec a b)) (vec (* (vec-x a) (vec-x b)) (* (vec-y a) (vec-y b)))) (defun lmult (aa bb) (declare (optimize (safety 0) speed (debug 0)) (list aa bb)) (mapcar (lambda (a b) (declare (type vec a b)) (mult a b)) aa bb)) (defun lmult* (aa b) (declare (optimize (safety 0) speed (debug 0)) (list aa) (vec b)) (mapcar (lambda (a) (declare (type vec a)) (mult a b)) aa)) (defun dot (a b) (declare (optimize (safety 0) speed (debug 0)) (vec a b)) (+ (* (vec-x a) (vec-x b)) (* (vec-y a) (vec-y b)))) (defun ldot (aa bb) (declare (optimize (safety 0) speed (debug 0)) (list aa bb)) (mapcar (lambda (a b) (declare (type vec a b)) (dot a b)) aa bb)) (defun div (a b) (declare (optimize (safety 0) speed (debug 0)) (vec a b)) (vec (/ (vec-x a) (vec-x b)) (/ (vec-y a) (vec-y b)))) (defun ldiv (aa bb) (declare (optimize (safety 0) speed (debug 0)) (list aa bb)) (mapcar (lambda (a b) (declare (type vec a b)) (div a b)) aa bb)) (defun ldiv* (aa b) (declare (optimize (safety 0) speed (debug 0)) (list aa) (vec b)) (mapcar (lambda (a) (declare (type vec a)) (div a b)) aa)) (defun idiv (a b) (declare (optimize (safety 0) speed (debug 0)) (vec a b)) (vec (/ (vec-x b) (vec-x a)) (/ (vec-y b) (vec-y a)))) (defun len2 (a) (declare (optimize (safety 0) speed (debug 0)) (vec a)) (+ (expt (vec-x a) 2) (expt (vec-y a) 2))) (defun len (a) (declare (optimize (safety 0) speed (debug 0)) (vec a)) (sqrt (len2 a))) (defun mid (a b) (declare (optimize (safety 0) speed (debug 0)) (vec a b)) (iscale (add a b) 2d0)) (defun lmid (aa) (declare (optimize (safety 0) speed (debug 0)) (list aa)) (let ((n 1)) (iscale (reduce (lambda (a b) (declare (type vec a b)) (incf n) (add a b)) aa) (math:dfloat n)))) (defun dst2 (a b) (declare (optimize (safety 0) speed (debug 0)) (vec a b)) (+ (expt (- (vec-x a) (vec-x b)) 2d0) (expt (- (vec-y a) (vec-y b)) 2d0))) (defun dst (a b) (declare (optimize (safety 0) speed (debug 0)) (vec a b)) (sqrt (dst2 a b))) (defun dst* (aa) (declare (optimize (safety 0) speed (debug 0)) (list aa)) (dst (first aa) (second aa))) (defun ldst (a b) (declare (optimize (safety 0) speed (debug 0)) (list a b)) (mapcar #'dst a b)) (defun ldst* (aa b) (declare (optimize (safety 0) speed (debug 0)) (list aa) (vec b)) (loop for a of-type vec in aa collect (dst a b))) (defun norm (a &key (s 1d0) (default *zero*)) (declare (optimize (safety 0) speed (debug 0)) (vec a) (double-float s)) (let ((l (len a))) (if (> l 0d0) (scale a (/ s l)) default))) (defun nsub (a b &key (s 1d0) (default *zero*)) (declare (vec a b)) (norm (sub a b) :s s :default default)) (defun sum (aa) (declare (optimize (safety 0) speed (debug 0)) (list aa)) (reduce (lambda (a b) (declare (vec a b)) (add a b)) aa)) (defun rot (v a &key (xy *zero*)) (declare (vec v) (double-float a)) (let ((cosa (cos a)) (sina (sin a))) (with-xy ((sub v xy) x y) (add xy (vec (- (* x cosa) (* y sina)) (+ (* x sina) (* y cosa))))))) (defun lrot (pts a &key (xy *zero*)) (declare (list pts) (double-float a)) (mapcar (lambda (p) (declare (vec p)) (rot p a :xy xy)) pts)) (defun shift-scale (pt shift s &optional (unshift *zero*)) "shift scale (unshift)" (declare (vec pt shift) (double-float s)) (add (scale (sub pt shift) s) unshift)) (defun shift-scale* (pts shift s &optional unshift) (declare (list pts) (vec shift) (double-float s)) (mapcar (lambda (pt) (declare (vec pt)) (shift-scale pt shift s unshift)) pts)) (defun all-inside (path &optional (lim 1d6)) (if (every #'identity (loop for v in path collect (and (>= (vec-x v) (- lim)) (<= (vec-x v) lim) (>= (vec-y v) (- lim)) (<= (vec-y v) lim)))) path nil)) (defun segdst (line v) " find distance between line and v. returns values (distance s) where is is the interpolation value that will yield the closest point on line. " (declare (list line) (vec v)) (destructuring-bind (va vb) line (let ((l2 (dst2 va vb))) (if (<= l2 0d0) ; line is a point (values (dst va v) 0d0) ; else (let ((tt (/ (+ (* (- (vec-x v) (vec-x va)) (- (vec-x vb) (vec-x va))) (* (- (vec-y v) (vec-y va)) (- (vec-y vb) (vec-y va)))) l2))) (if (> tt 1d0) (setf tt 1d0)) (if (< tt 0d0) (setf tt 0d0)) (values (dst v (on-line tt va vb)) tt)))))) ; TODO: this is slow? (defun segx (aa bb &key parallel) (declare (list aa bb)) (destructuring-bind (a1 a2) aa (declare (vec:vec a1 a2)) (destructuring-bind (b1 b2) bb (declare (vec:vec b1 b2)) (let* ((sa (sub a2 a1)) (sb (sub b2 b1)) (u (vec:cross sa sb))) (declare (vec:vec sa sb) (double-float u)) (if (<= (abs u) 0d0) ; return parallel if the lines are parallel (default: nil) ; this is just a div0 guard. it's not a good way to test. (values parallel nil nil) ; otherwise check if they intersect (let ((p (/ (vec:cross sa #1=(vec:sub a1 b1)) u)) (q (/ (vec:cross sb #1#) u))) (declare (double-float p q)) ; t if intersection ; nil otherwise (values (and (>= p 0d0) (<= p 1d0) (>= q 0d0) (<= q 1d0)) q p))))))) (defun segx* (l &key parallel) (declare (list l)) (destructuring-bind (a b) l (segx a b :parallel parallel))) ; TODO: this is slow? (defun psegx (aa bb &key parallel &aux (aa* (ensure-vector aa)) (bb* (ensure-vector bb))) (loop with res = (make-adjustable-vector) for i of-type fixnum from 0 below (1- (length aa*)) do (loop for j of-type fixnum from 0 below (1- (length bb*)) do (multiple-value-bind (x s p) (vec:segx (list (aref aa* i) (aref aa* (1+ i))) (list (aref bb* j) (aref bb* (1+ j))) :parallel parallel) (when x (vextend (list i j s p) res)))) finally (return (if (> (length res) 0) res nil)))) ; TODO: incomplete ;(defun lsegx* (lines line &key parallel) ; (declare (list lines line)) ; (loop with res = (make-adjustable-vector) ; for l of-type list in lines ; ; TODO: sort and rearrange ; do (multiple-value-bind (x p q) (segx l line) ; (when x (vextend (list x p q) res))) ; finally (return res))) (defun cross (a b) (declare (vec a b)) (- (* (vec-x a) (vec-y b)) (* (vec-y a) (vec-x b)))) (defun ptinside (convex v) (declare (list convex) (vec v)) (loop for a of-type vec in (close-path convex) and b of-type vec in (cdr (close-path convex)) always (>= (cross (sub b a) (sub v b)) 0d0))) ; SHAPES (defun on-circ (p rad &key (xy *zero*)) (declare (double-float p rad) (vec xy)) (from xy (cos-sin (* p PII)) rad)) (defun on-line (p a b) (declare (optimize (safety 0) speed (debug 0)) (double-float p) (vec a b)) (vec (+ (vec-x a) (* p (- (vec-x b) (vec-x a)))) (+ (vec-y a) (* p (- (vec-y b) (vec-y a)))))) (defun on-line* (p ab) (declare (double-float p) (list ab)) (destructuring-bind (a b) ab (on-line p a b))) (defun lon-line* (pp ab) (declare (sequence pp) (list ab)) (destructuring-bind (a b) ab (if (equal (type-of pp) 'cons) (loop for p of-type double-float in pp collect (on-line p a b)) (loop for p of-type double-float across pp collect (on-line p a b))))) (defun on-spiral (p rad &key (xy *zero*) (rot 0d0)) (declare (double-float p rad rot) (vec xy)) (add xy (scale (cos-sin (+ rot (* p PII))) (* p rad)))) (defun rect (w h &key (xy *zero*)) (declare (double-float w h) (vec xy)) (list (add xy (vec w (- h))) (add xy (vec w h)) (add xy (vec (- w) h)) (sub xy (vec w h)))) (defun square (bs &key xy) (declare (double-float bs) (vec xy)) (rect bs bs :xy xy)) (defun polygon (n rad &key (xy *zero*) (rot 0d0)) (declare (fixnum n) (double-float rad rot) (vec xy)) (loop for i from 0 below n collect (from xy (cos-sin (+ rot (* (/ (math:dfloat i) n) PII))) rad))) (defun fan (n rad &key (xy *zero*) (rot 0d0)) (declare (fixnum n) (double-float rad rot) (vec xy)) (loop for p in (polygon n rad :xy xy :rot rot) collect (list xy p))) <|start_filename|>examples/custom-alt.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (defun circ-stroke (sand vv) (sandpaint:circ sand (lin-path:pos* (lin-path:make vv) (math:linspace 100 0d0 0.99d0)) 1d0 20)) (defun draw-path (sand fn n rad mid) (let ((curr nil) (i 0)) (labels ((new-append-edge-alt* (snk a) (if (<= (length (snek:verts-in-rad snk (snek::append-edge-alt-xy a) rad)) 1) (aif (snek::do-append-edge-alt snk a) (progn (incf i) (setf curr it) (sandpaint:set-fg-color sand (pigment:rgb 0.0 0.7 0.7 0.01)) (sandpaint:circ sand (list (snek::append-edge-alt-xy a)) 4d0 3000) (sandpaint:set-fg-color sand (pigment:black 0.01)) (circ-stroke sand (snek:get-verts snk (list it (snek::append-edge-alt-v a)))) (sandpaint:save sand (format nil "~a-~3,'0d" fn i))))))) (let ((snk (snek:make :max-verts n :alts `((snek::append-edge-alt ,#'new-append-edge-alt*))))) (setf curr (snek:add-vert! snk mid)) (loop for i from 0 below n do (snek:with (snk :zwidth rad) (snek:append-edge? curr (vec:add (snek:get-vert snk curr) (rnd:in-circ rad)) :rel nil))))))) (defun main (size fn) (let ((sand (sandpaint:make size :fg (pigment:black 0.01) :bg (pigment:white)))) (draw-path sand fn 5000 10.0d0 (vec:vec 250d0 250d0)))) (time (main 500 (second (cmd-args)))) <|start_filename|>src/sandpaint-extra.lisp<|end_filename|> (in-package :sandpaint) (defun pixel-hack (sand &optional (sa 0.9d0)) " scale opacity of pix (0 0) by sa. " (let ((vals (sandpaint-vals sand))) (destructuring-bind (r g b a) (loop for i from 0 below 4 collect (aref vals i)) (declare (double-float r g b a)) (if (>= a 1.0d0) (let ((na (* a (math:dfloat sa)))) (declare (double-float na)) (setf (aref vals 0) (* (/ r a) na) (aref vals 1) (* (/ g a) na) (aref vals 2) (* (/ b a) na) (aref vals 3) na)))))) (defun copy-rgba-array-to-from (target source size) (declare (optimize (safety 0) speed (debug 0)) (type (simple-array double-float) target source) (fixnum size)) (loop for i of-type fixnum from 0 below (* size size 4) do (setf (aref target i) (the double-float (aref source i))))) (defun copy-scale-rgba-array-to-from (target source scale size) (declare (optimize (safety 0) speed (debug 0)) (type (simple-array double-float) target source) (fixnum size)) (loop for i of-type fixnum from 0 below (* size size 4) do (if (<= (aref scale i) 0) (setf (aref target i) (aref source i)) (setf (aref target i) (/ (aref source i) (aref scale i)))))) ;TODO something ...? (defun nvecstep (n v &key (end t)) (if (> n 1) (let ((nn (if end (1- n) n))) (loop for i from 0 below n collect (vec:scale v (math:dfloat (expt (* i (/ 1d0 nn)) 3d0))))) (if end (list v) (list vec:*zero*)))) ; EXPERIMENTAL ; TODO there is a bug here. good luck. (defun chromatic-aberration (sand &key mid (s 1d0)) (declare (optimize (safety 0) speed (debug 0))) (format t "WARN: CA is currently not working and will produce strange results.~%") (-do-op (sand size vals indfx :name "chromatic-aberration") (labels ((-channel-operator-over (new-vals new-counts sx sy ix iy w channel) (when (and (< -1 sx size) (< -1 sy size) (< -1 ix size) (< -1 iy size)) (let ((sind (funcall indfx sx sy channel)) (ind (funcall indfx ix iy channel)) (iw (- 1d0 w))) ;(setf (aref new-vals ind) (+ (* (aref vals sind)) ; (* (aref vals ind) w))) ;(setf (aref new-vals ind) (aref vals sind)) ;(+ (* (aref vals ind) ia) (aref vals sind)) (if (<= (aref new-counts ind) 0d0) (setf (aref new-vals ind) (* (aref vals sind) w) (aref new-counts ind) w) (setf (aref new-vals ind) (+ (* (aref vals ind) iw) (* (aref vals sind) w)) (aref new-counts ind) (+ (aref new-counts ind) w)))))) (-point-sample-channel (new-vals new-counts sx sy pt dx channel) (declare (optimize (safety 0) speed (debug 0)) (type (simple-array double-float) new-vals) (fixnum channel) (vec:vec pt dx)) (loop ;with len = (vec:len dx) ;for dpt in (nvecstep (ceiling (* 3d0 len)) dx) for dpt in (nvecstep 1 dx :end t) do (multiple-value-bind (ix iy fx fy) (-floor-fract (rnd:in-circ 0.25d0 :xy (vec:add pt dpt))) (multiple-value-bind (w1 w2 w3 w4) (-fract-overlap fx fy) (declare (double-float w1 w2 w3 w4)) (-channel-operator-over new-vals new-counts sx sy ix iy w1 channel) (-channel-operator-over new-vals new-counts sx sy #1=(+ ix 1) iy w2 channel) (-channel-operator-over new-vals new-counts sx sy ix #2=(+ iy 1) w3 channel) (-channel-operator-over new-vals new-counts sx sy #1# #2# w4 channel)))))) (let ((center (if mid mid (vec:vec (* 0.5d0 (sandpaint-size sand))))) (new-vals (make-rgba-array size :init 1d0)) (new-counts (make-rgba-array size :init 0d0)) (base-size (/ s (math:dfloat size) 2d0))) (copy-rgba-array-to-from new-vals vals size) (-square-loop (sx sy size) (let* ((pt (vec:add vec:*half* (vec:vec-coerce sx sy))) (dx (vec:scale (vec:sub pt center) base-size))) (-point-sample-channel new-vals new-counts sx sy pt dx 0) ;(-point-sample-channel new-vals sx sy pt vec:*zero* 1) (-point-sample-channel new-vals new-counts sx sy pt (vec:neg dx) 2))) (copy-scale-rgba-array-to-from vals new-vals new-counts size))))) ; EXPERIMENTAL ;(defun filter-walk (sand walker noise &key (alpha 0.5d0)) ; (declare (optimize (safety 0) speed (debug 0))) ; (-do-op (sand size vals indfx :name "rot-cw") ; (loop for j from 0 below size ; do (loop for i from 0 to (/ size 2) ; do (let ((v (funcall walker noise))) ; (vec:with-xy ((vec:add (vec:vec-coerce i j) v) x y) ; (-inside-round (size (vec:vec x y) xx yy) ; (-operator-over indfx vals xx yy ; (-rgb-from vals (funcall indfx i j) alpha))))))))) ; EXPERIMENTAL (defun rnd-copy-rect (sand n sx sy &key from to) (declare (optimize (safety 0) speed (debug 0))) (-do-op (sand size vals indfx :name nil) (let ((angle (rnd:rnd* PI))) (rnd:with-in-box (n sx sy pxy) (-inside-floor (size (vec:add to (vec:rot pxy angle)) ax ay) (-inside-floor (size (vec:add from pxy) bx by) (let ((pa (funcall indfx ax ay 0)) (pb (funcall indfx bx by 0))) (-swap vals pa pb)))))))) <|start_filename|>test/speed-snek-move.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (setf *print-pretty* t) (rnd:set-rnd-state 1) (defun init-snek (n) (let ((snk (snek:make :max-verts 10000 :grp-size 100))) (math:nrep n (snek:add-vert! snk (vec:vec (rnd:rnd 100d0) (rnd:rnd 100d0)))) snk)) (defun main () (let* ((itt 5000) (num 10000) (ww (vec:vec 10d0 33.3d0)) (uu (vec:vec 1d0 3.2d0)) (snk (init-snek num))) (time (loop for i from 0 below itt do (snek:with (snk) (snek:itr-verts (snk v) nil (snek:move-vert? v ww) (snek:move-vert? v uu))))) (time (loop for i from 0 below itt do (snek:cwith (snk %) (snek:itr-verts (snk v :collect nil) (% nil) (% (snek:move-vert? v ww)) (% (snek:move-vert? v uu)))))))) (require :sb-sprof) (sb-sprof:with-profiling (:max-samples 200000 ;:mode :cpu ;:mode :alloc :mode :time :report :graph) (time (main))) <|start_filename|>src/sandpaint-flip-reflect.lisp<|end_filename|> (in-package :sandpaint) (declaim (optimize (speed 3))) (defun -swap (vals i j) (declare (optimize (safety 0) speed (debug 0)) (type (simple-array double-float) vals)) (let ((ri (aref vals i)) (bi (aref vals (1+ i))) (gi (aref vals (+ i 2))) (ai (aref vals (+ i 3)))) (declare (double-float ri bi gi ai)) (setf (aref vals i) (aref vals j) (aref vals (1+ i)) (aref vals (1+ j)) (aref vals (+ i 2)) (aref vals (+ j 2)) (aref vals (+ i 3)) (aref vals (+ j 3)) (aref vals j) ri (aref vals (1+ j)) bi (aref vals (+ j 2)) gi (aref vals (+ j 3)) ai))) (defun reflect-y (sand &key (alpha 1d0) (align t)) (declare (optimize (safety 0) speed (debug 0))) (-do-op (sand size vals indfx :name "reflect-y") (let* ((pa (list (vec:vec 0d0 (math:dfloat size)) vec:*zero*)) (pb (list (vec:vec (math:dfloat size)) (vec:vec (math:dfloat size) 0d0)))) (loop with ls = (math:linspace size 0d0 1d0 :end (not align)) for i in ls and ii from 0 do (loop with line = (list (vec:on-line* i pa) (vec:on-line* i pb)) for j in ls and jj from 0 do (-pix-overlap indfx vals size (vec:on-line* j line) (-rgb-from vals (funcall indfx jj ii 0) alpha))))))) (defun reflect-x (sand &key (alpha 1d0) (align t)) (declare (optimize (safety 0) speed (debug 0))) (-do-op (sand size vals indfx :name "reflect-x") (let* ((pa (list vec:*zero* (vec:vec (math:dfloat size) 0d0))) (pb (list (vec:vec 0d0 (math:dfloat size)) (vec:vec (math:dfloat size))))) (loop with ls = (math:linspace size 0d0 1d0 :end (not align)) for i in ls and ii from 0 do (loop with line = (list (vec:on-line* i pa) (vec:on-line* i pb)) for j in ls and jj from 0 do (-pix-overlap indfx vals size (vec:on-line* j line) (-rgb-from vals (funcall indfx (- size ii 1) jj 0) alpha))))))) (defun flip-x (sand) (declare (optimize (safety 0) speed (debug 0))) (-do-op (sand size vals indfx :name "flip-x") (loop for i from 0 below size do (loop for j from 0 to (/ size 2) do (-swap vals (funcall indfx j i) (funcall indfx (- size j 1) i)))))) (defun flip-y (sand) (declare (optimize (safety 0) speed (debug 0))) (-do-op (sand size vals indfx :name "flip-y") (loop for i from 0 below size do (loop for j from 0 to (/ size 2) do (-swap vals (funcall indfx i j) (funcall indfx i (- size j 1))))))) (defun -rot (va vb a b) (declare (type (simple-array double-float) va vb) (fixnum a b)) (setf (aref vb b) (aref va a) (aref vb (1+ b)) (aref va (1+ a)) (aref vb (+ b 2)) (aref va (+ a 2)) (aref vb (+ b 3)) (aref va (+ a 3)))) (defun rot (sand dir) (declare (optimize (safety 0) speed (debug 0))) (-do-op (sand size vals indfx :name "rot") (let ((new-vals (make-rgba-array size :init 0d0))) (case dir (:cw (-square-loop (i j size) (-rot vals new-vals (funcall indfx i j) (funcall indfx (- size j 1) i)))) (:ccw (-square-loop (i j size) (-rot vals new-vals (funcall indfx i j) (funcall indfx j (- size i 1))))) (:twice (-square-loop (i j size) (-rot vals new-vals (funcall indfx i j) (funcall indfx (- size i 1) (- size j 1))))) (otherwise (error "use :cw :ccw or :twice"))) (copy-rgba-array-to-from vals new-vals size)))) <|start_filename|>utils/line-intersect.lisp<|end_filename|> (defvar *grid-near-all* (list (list -1 0) (list 1 0) (list 0 -1) (list 0 1) (list 1 1) (list -1 -1) (list 1 -1) (list -1 1))) (defvar *grid-near-obliq* (list (list 0 0) (list 1 0) (list 1 1) (list 0 1))) (defvar *grid-near* (list (list -1 0) (list 1 0) (list 0 -1) (list 0 1))) (defun make-dims (n left right) (let ((w (* 0.5d0 (- right left))) (mid (* 0.5d0 (+ right left)))) (to-vector (loop for i from 0 below n collect (list (rnd:in-box w w :xy (vec:vec mid)) (rnd:on-circ 1d0)))))) (defun make-lines (left right len noise dims &key xspace) (let ((w (* 0.5d0 (- right left))) (mid (* 0.5d0 (+ right left)))) (to-vector (loop for (xy dim) across dims collect (let ((offset (vec:scale dim len)) (perp (vec:scale (vec:perp dim) len)) (wa (rnd:get-acc-lin-stp* 0.5d0)) (wb (rnd:get-acc-lin-stp* 0.5d0))) (to-vector (loop for d in xspace collect (let ((p (vec:on-line* d (vec:ladd* (list (vec:neg offset) offset) xy)))) (list (vec:add p (vec:scale perp (funcall wa noise))) (vec:sub p (vec:scale perp (funcall wb noise)))) ;(list (vec:add p perp) ; (vec:sub p perp)) )))))))) (defun -isect (res lu lw) (loop for u across lu and ui from 0 do (loop for w across lw and wi from 0 do (multiple-value-bind (x us ws) (vec:segx u w) (when x (vextend (list ui wi us ws) res)))))) (defun get-intersects (lines) (loop with res = (make-adjustable-vector) for i from 0 below (length lines) do (loop for j from (1+ i) below (length lines) do (-isect res (aref lines i) (aref lines j))) finally (return res))) (defun -memtest (gm key near nearsel) (loop for (i j) in nearsel do (let ((k (math:add key (list i j)))) (multiple-value-bind (val exists) (gethash k gm) (when exists (vextend k near)))))) (defun make-grid-map (lines intersects nearsel &key distortfxn &aux (distortfxn* (if (not distortfxn) (lambda (x) x) distortfxn))) (let ((gm (make-hash-table :test #'equal)) (points (make-hash-table :test #'equal))) (loop for (ui wi us ws) across intersects do (let ((key (list ui wi))) (multiple-value-bind (val exists) (gethash key gm) (when (not exists) (setf (gethash key gm) (make-adjustable-vector) (gethash key points) (funcall distortfxn* (vec:on-line* us (aref (aref lines 0) ui)))))))) (loop for (ui wi us ws) across intersects do (let ((key (list ui wi))) (multiple-value-bind (val exists) (gethash key gm) (-memtest gm key val nearsel)))) (values gm points))) <|start_filename|>examples/grid-distort.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (load "../utils/state") (load "../utils/grid") (defun up-down (p n) (if (< (rnd:rnd) p) (* n (expt -1 (rnd:rndi 2))) 0)) (defun main (size fn) (let* ((ngrid 80) (snk (snek:make :max-verts 10000)) (grid (get-grid size 50d0 ngrid)) (state-gen (get-walker-state-gen (lambda () (rnd:get-acc-circ-stp*)))) (sand (sandpaint:make size :fg (pigment:white 0.05) :bg (pigment:dark)))) (snek:add-verts! snk (flatten grid)) (loop for i from 3 below (- ngrid 3) do (snek:add-path*! snk (mapcar (lambda (k) (+ i (up-down 0.1 1) (* k ngrid))) (math:range 0 ngrid)) :g (snek:add-grp! snk))) (loop for i from (/ ngrid 2) below (- ngrid 3) do (snek:add-path*! snk (mapcar (lambda (k) (+ k (up-down 0.1 ngrid) (* ngrid i))) (math:range 0 ngrid)) :g (snek:add-grp! snk))) (loop for i from 0 below 500 do (print-every i 100) (snek:with (snk) (snek:itr-verts (snk v) (snek:move-vert? v (funcall state-gen v 0.000009d0)) ;(snek:move-vert? v (rnd:in-circ 0.4d0)) )) (snek:itr-grps (snk g :collect nil) (sandpaint:bzspl-stroke sand (snek:get-grp-as-bzspl snk g) 100))) (snek:itr-grps (snk g :collect nil) (sandpaint:bzspl-stroke sand (snek:get-grp-as-bzspl snk g) 50000)) ;(snek:itr-grps (snk g :collect nil) ; (sandpaint:lin-path sand ; (bzspl:rndpos (snek:get-grp-as-bzspl snk g) 1000 :order t) ; 1.2d0 40)) ;(sandpaint:set-fg-color sand (pigment:hsv 0.5 0.8 0.8 0.05)) ;(sandpaint:circ sand (snek:get-all-verts snk) 2d0 300) ;(let ((grps (snek:get-all-grps snk))) ; (loop for a in grps and b in (cdr grps) do ; (let ((ga (snek:get-grp-as-bzspl snk a)) ; (gb (snek:get-grp-as-bzspl snk b))) ; (loop for k in (math:linspace 10000 0 1) do ; (sandpaint:stroke sand (list (bzspl:pos ga k) ; (bzspl:pos gb k)) ; 10))))) (sandpaint:pixel-hack sand) (sandpaint:save sand fn :gamma 1.5d0))) (time (main 1000 (second (cmd-args)))) <|start_filename|>utils/2obj.lisp<|end_filename|> (defun export-2obj (snk fn) (let ((verts (snek:get-all-verts snk)) (edges (snek:get-edges snk)) (fnobj (append-postfix fn ".2obj"))) (with-open-file (stream fnobj :direction :output :if-exists :supersede) (format stream "o mesh~%") (dolist (ll verts) (format stream "v ~f ~f~%" (vec::vec-x ll) (vec::vec-y ll))) (dolist (ll (coerce edges 'list)) (destructuring-bind (a b) (math:add ll '(1 1)) (format stream "e ~d ~d~%" a b)))) (format t "~%num verts: ~a ~%" (length verts)) (format t "num edges: ~a ~%" (length edges)) (format t "~%file: ~a" fnobj))) <|start_filename|>test/speed-bzspl.lisp<|end_filename|> #!/usr/bin/sbcl --script (load "../src/load") (setf *print-pretty* t) (rnd:set-rnd-state 1) (defun main () (let* ((itt 500000)) (format t "make 100") (time (loop with pts = (rnd:nin-box 100 500d0 500d0 :xy (vec:vec 500d0)) for i from 0 below itt do (bzspl:make pts))) (format t "make 1000") (time (loop with pts = (rnd:nin-box 1000 500d0 500d0 :xy (vec:vec 500d0)) for i from 0 below itt do (bzspl:make pts))) (format t "pos 500") (time (loop with pos = (rnd:nrnd 500) with bz = (bzspl:make (rnd:nin-box 100 500d0 500d0 :xy (vec:vec 500d0))) for i from 0 below itt do (bzspl:pos* bz pos))) (format t "adaptive") (time (loop with bz = (bzspl:make (rnd:nin-box 5 500d0 500d0 :xy (vec:vec 500d0))) for i from 0 below 40000 do (bzspl:adaptive-pos bz))))) (require :sb-sprof) (sb-sprof:with-profiling (:max-samples 200000 ;:mode :cpu ;:mode :alloc :mode :time :report :graph) (main)) <|start_filename|>utils/snek-alterations-mutate.lisp<|end_filename|> (in-package :snek) (defstruct (mutate (:constructor -make-mutate)) (rules nil) (xy nil :type vec:vec) (prob 0.0d0 :type double-float) (noise 0.0d0 :type double-float) (ind nil :type fixnum)) (defun make-mutate (&key (prob 0.1d0) (noise 100.0d0) (xy vec:*zero*) (ind 0)) (let ((rules (make-hash-table :test #'equal))) (setf (gethash 'append-edge-alt rules) #'mutate-append-edge-alt) (setf (gethash 'add-edge-alt rules) #'mutate-add-edge-alt) (setf (gethash 'move-vert-alt rules) #'mutate-move-vert-alt) (setf (gethash 'add-vert-alt rules) #'mutate-add-vert-alt) (-make-mutate :rules rules :prob (math:dfloat prob) :ind ind :noise (math:dfloat noise) :xy xy))) (defun -ok-ind (i) (if (> i -1) i 0)) (defun do-mutate (rules a mut) (multiple-value-bind (mut-f exists) (gethash (type-of a) rules) (if exists (funcall mut-f a mut) a))) (defun change-ind (i &optional (o 1)) (let ((ii (+ i (rnd:rndi (* -1 o) (+ 1 o))))) (if (> ii -1) ii 0))) (defun mutate-add-vert-alt (a mut) (with-struct (add-vert-alt- xy) a (add-vert? (vec:add xy (rnd:in-circ (rnd:rnd (mutate-noise mut))))))) (defun mutate-move-vert-alt (a mut) (with-struct (move-vert-alt- v xy rel) a (move-vert? v (vec:add xy (rnd:in-circ (mutate-noise mut))) :rel rel))) (defun mutate-append-edge-alt (a mut) (with-struct (mutate- ind) mut (with-struct (append-edge-alt- xy rel) a (append-edge? ind xy :rel rel)))) (defun mutate-add-edge-alt (a mut) (with-struct (mutate- ind) mut (with-struct (add-edge-alt- w) a (add-edge? ind w)))) <|start_filename|>src/rnd-extra.lisp<|end_filename|> (in-package :rnd) (defmacro with-in-circ ((n rad v &key xy) &body body) (declare (symbol v)) (with-gensyms (rad* xy* m) `(let* ((,rad* ,rad) (,xy* ,xy) (,m (if ,xy* ,xy* vec:*zero*))) (declare (vec:vec ,m)) (loop repeat ,n do (let ((,v (in-circ ,rad* :xy ,m))) (declare (vec:vec ,v)) (progn ,@body)))))) (defmacro with-in-box ((n sx sy v &key xy) &body body) (declare (symbol v)) (with-gensyms (sx* sy* xy* m) `(let* ((,sx* ,sx) (,sy* ,sy) (,xy* ,xy) (,m (if ,xy* ,xy* vec:*zero*))) (declare (vec:vec ,m)) (loop repeat ,n do (let ((,v (in-box ,sx* ,sy* :xy ,m))) (declare (vec:vec ,v)) (progn ,@body)))))) (defmacro with-on-line ((n a b rn) &body body) (declare (symbol rn)) (with-gensyms (sub a*) `(let* ((,a* ,a) (,sub (vec:sub ,b ,a*))) (loop repeat ,n do (let ((,rn (vec:from ,a* ,sub (random 1d0)))) (declare (vec:vec ,rn)) (progn ,@body)))))) (declaim (ftype (function (double-float double-float &key (:xy vec:vec)) vec:vec) in-box)) (declaim (ftype (function (vec:vec vec:vec) vec:vec) on-line)) (declaim (ftype (function (double-float &key (:xy vec:vec)) vec:vec) in-circ on-circ)) ; TODO: move to math? (defun -swap (a i j) (declare (vector a) (fixnum i j)) (let ((tmp (aref a i))) (setf (aref a i) (aref a j) (aref a j) tmp))) ; https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle (defun shuffle (a &aux (a* (ensure-vector a)) (n (length a))) (declare (sequence a) (vector a*)) (loop for i of-type fixnum from 0 to (- n 2) do (-swap a* i (rndi i n))) a*) (defun nrnd-u-from (n a) (let* ((a* (ensure-vector a)) (resind nil) (anum (length a*))) (when (> n anum) (error "not enough distinct elements in a.")) (loop until (>= (hset:num (hset:make :init resind)) n) do (setf resind (nrndi n 0 anum))) (loop for i in resind collect (aref a* i)))) (defun nrnd-from (n a) (loop for i in (nrndi n 0 (length a)) collect (aref a i))) (defun array-split (arr p) (let ((res (make-adjustable-vector))) (vextend (make-adjustable-vector :init (list (aref arr 0))) res) (loop for i of-type fixnum from 1 below (length arr) do (prob p (vextend (make-adjustable-vector :init (list (aref arr i))) res) (vextend (aref arr i) (aref res (1- (length res)))))) res)) ; SHAPES ; TODO: this can be optimized (defun on-circ (rad &key (xy vec:*zero*)) (declare (double-float rad) (vec:vec xy)) (vec:from xy (vec:cos-sin (random PII)) rad)) (defun non-circ (n rad &key (xy vec:*zero*)) (declare (fixnum n) (double-float rad)) (loop repeat n collect (on-circ rad :xy xy))) (defun in-circ (rad &key (xy vec:*zero*)) (declare (double-float rad)) (let ((a (random 1d0)) (b (random 1d0))) (declare (double-float a b)) (vec:with-xy (xy x y) (if (< a b) (vec:vec (+ x (* (cos #1=(* PII (/ a b))) #3=(* b rad))) (+ y (* (sin #1#) #3#))) (vec:vec (+ x (* (cos #2=(* PII (/ b a))) #4=(* a rad))) (+ y (* (sin #2#) #4#))))))) (defun nin-circ (n rad &key (xy vec:*zero*)) (declare (fixnum n) (double-float rad)) (loop repeat n collect (in-circ rad :xy xy))) (defun in-box (sx sy &key (xy vec:*zero*)) (declare (double-float sx sy) (vec:vec xy)) (vec:add xy (vec:vec (rnd* sx) (rnd* sy)))) (defun nin-box (n sx sy &key (xy vec:*zero*)) (declare (fixnum n) (double-float sx sy) (vec:vec xy)) (loop repeat n collect (in-box sx sy :xy xy))) (defun on-line (a b) (declare (vec:vec a b)) (vec:from a (vec:sub b a) (random 1d0))) (defun on-line* (ab) (declare (list ab)) (destructuring-bind (a b) ab (declare (vec:vec a b)) (on-line a b))) (defun non-line (n a b) (declare (fixnum n) (vec:vec a b)) (loop with ba = (vec:sub b a) repeat n collect (vec:from a ba (random 1d0)))) (defun non-line* (n ab) (declare (fixnum n) (list ab)) (destructuring-bind (a b) ab (declare (vec:vec a b)) (non-line n a b))) ; WALKERS (defun get-lin-stp (&optional (init 0.0d0)) " random linear walker limited to (0 1) " (declare (double-float init)) (let ((x init)) (lambda (stp) (declare (double-float stp)) (setf x (-inc x (rnd* stp)))))) (defun get-lin-stp* (&optional (init 0d0)) " random linear walker " (declare (double-float init)) (let ((x init)) (lambda (stp) (declare (double-float stp)) (incf x (rnd* stp))))) (defun get-acc-lin-stp (&optional (init-x 0d0) (init-a 0d0)) " random accelerated linear walker limited to (0 1) " (declare (double-float init-x init-a)) (let ((a init-a) (x init-x)) (lambda (stp) (declare (double-float stp)) (setf x (-inc x (incf a (rnd* stp))))))) (defun get-acc-lin-stp* (&optional (init-x 0d0) (init-a 0d0)) " random accelerated linear walker " (declare (double-float init-x init-a)) (let ((a init-a) (x init-x)) (lambda (stp) (declare (double-float stp)) (incf x (incf a (rnd* stp)))))) (defun get-circ-stp* (&optional (init vec:*zero*)) (declare (vec:vec init)) (let ((xy (vec:copy init))) (lambda (stp) (declare (double-float stp)) (setf xy (vec:add xy (in-circ stp)))))) (defun get-acc-circ-stp* (&optional (init vec:*zero*) (init-a vec:*zero*)) (declare (vec:vec init init-a)) (let ((a (vec:copy init-a)) (xy (vec:copy init))) (lambda (stp) (declare (double-float stp)) (setf xy (vec:add xy (setf a (vec:add a (in-circ stp))))))))
inconvergent/snek
<|start_filename|>cursor_test.go<|end_filename|> package minquery import ( "testing" "time" "github.com/globalsign/mgo/bson" "github.com/icza/mighty" ) func TestDefaultCodec(t *testing.T) { eq, neq, expDeq := mighty.Eq(t), mighty.Neq(t), mighty.ExpDeq(t) cc := cursorCodec{} cd := bson.D{ {Name: "a", Value: 1}, {Name: "b", Value: "2"}, {Name: "c", Value: time.Date(3, 0, 0, 0, 0, 0, 0, time.UTC)}, } cursor, err := cc.CreateCursor(cd) eq(nil, err) expDeq(cd)(cc.ParseCursor(cursor)) _, err = cc.ParseCursor("%^&") neq(nil, err) _, err = cc.ParseCursor("ValidBas64ButInvalidCursor") neq(nil, err) } <|start_filename|>doc.go<|end_filename|> /* Package minquery provides a mgo-like Query type called MinQuery, which supports efficient query pagination (cursors to continue listing documents where we left off). Example using MinQuery Let's say we have a users collection in MongoDB modeled with this Go struct: type User struct { ID bson.ObjectId `bson:"_id"` Name string `bson:"name"` Country string `bson:"country"` } To query users having country=USA, sorted by Name and ID: q := minquery.New(session.DB(""), "users", bson.M{"country" : "USA"}). Sort("name", "_id").Limit(10) // If this is not the first page, set cursor: // getLastCursor() represents your logic how you acquire the last cursor. if cursor := getLastCursor(); cursor != "" { q = q.Cursor(cursor) } var users []*User newCursor, err := q.All(&users, "country", "name", "_id") And that's all. newCursor is the cursor to be used to fetch the next batch. Note #1: When calling MinQuery.All(), you have to provide the names of the cursor fields, this will be used to build the cursor data (and ultimately the cursor string) from. Note #2: If you're retrieving partial results (by using MinQuery.Select()), you have to include all the fields that are part of the cursor (the index entry) even if you don't intend to use them directly, else MinQuery.All() will not have all the values of the cursor fields, and so it will not be able to create the proper cursor value. */ package minquery
limianwang/minquery
<|start_filename|>plugin/coc.lua<|end_filename|> -- Snippets vim.g.coc_snippet_next = '<c-j>' vim.g.coc_snippet_prev = '<c-k>' vim.cmd("autocmd CursorHold * silent call CocActionAsync('highlight')") <|start_filename|>plugin/mappings.lua<|end_filename|> -- Mapping helper local mapper = function(mode, key, result) vim.api.nvim_set_keymap(mode, key, result, { noremap = true, silent = true, expr = false }) end -- Expressive Mapping helper local expressive_mapper = function(mode, key, result) vim.api.nvim_set_keymap(mode, key, result, { silent = true, expr = true }) end -- Default Mapping helper local plug_mapper = function(mode, key, result) vim.api.nvim_set_keymap(mode, key, result, {}) end -- Define Mapleader vim.g.mapleader = ' ' -- Escape from insert mode mapper('i', '<C-c>', '<Esc>') -- Save for muggles mapper('n', '<C-s>', ':w<CR>') -- Nice mapper('n', 'ZE', ':qa!<CR>') -- Duplitcate Line mapper('n', 'tt', ':t.<CR>') -- Toggle Numbers mapper('n', '<leader>n', ':set nu! rnu!<CR>') -- use ESC to turn off search highlighting mapper('n', '<Esc>', ':noh<CR>') -- Get out of the Terminal mapper('t', '<Esc>', '<C-\\><C-n>') -- Resize with arrows mapper('n', '<C-Up>', ':resize -2<CR>') mapper('n', '<C-Down>', ':resize +2<CR>') mapper('n', '<C-Left>', ':vertical resize -2<CR>') mapper('n', '<C-Right>', ':vertical resize +2<CR>') -- Copy to OS clipboard. mapper('n', '<Leader>y', '"+y') mapper('v', '<Leader>y', '"+y') mapper('n', '<Leader>yy', '"+yy') -- Paste from OS clipboard mapper('n', '<Leader>p', '"+p') mapper('n', '<Leader>P', '"+P') mapper('v', '<Leader>p', '"+p') mapper('v', '<Leader>P', '"+P"`"`"') mapper('n', 'J', 'mzJ`z') -- Plugins Mappings ↓ -- Telescope mapper('n', '<C-F>', ':Telescope live_grep<CR>') mapper('n', '<C-P>', ':Telescope find_files<CR>') -- Tree mapper('n', '<C-n>', ':NvimTreeToggle<CR>') -- Hop.nvim mapper('n', '<Leader>f', ':HopWord<CR>') mapper('n', '<Leader>o', ':HopPattern<CR>') -- Switch Theme mapper('n', '<leader>mm', [[<Cmd>lua require('material.functions').toggle_style()<CR>]]) -- Coc.nvim mapper('n', '<F12>', ':CocCommand terminal.Toggle<CR>') mapper('n', '<F3>', ':Format<CR>') plug_mapper('n', '<leader>rn', '<Plug>(coc-rename)') plug_mapper('n', 'gd', '<Plug>(coc-definition)') plug_mapper('n', 'gr', '<Plug>(coc-references)') plug_mapper('n', '<leader>ca', '<Plug>(coc-codeaction)') plug_mapper('n', '<leader>ga', '<Plug>(coc-codeaction-cursor)') plug_mapper('x', '<leader>ga', '<Plug>(coc-codeaction-selected)') plug_mapper('n', '<leader>kf', '<Plug>(coc-fix-current)') plug_mapper('n', '<Right>', '<Plug>(coc-diagnostic-prev)') plug_mapper('n', '<Left>', '<Plug>(coc-diagnostic-next)') expressive_mapper('i', '<C-space>', 'coc#refresh()') -- TODO: Pass to Lua vim.cmd([[ nnoremap <silent> <M-Up> :<C-U>exec "exec 'norm m`' \| move -" . (1+v:count1)<CR>`` nnoremap <silent> <M-Down> :<C-U>exec "exec 'norm m`' \| move +" . (0+v:count1)<CR>`` vnoremap <silent> <M-Up> :<C-U>exec "'<,'>move '<-" . (1+v:count1)<CR>gv vnoremap <silent> <M-Down> :<C-U>exec "'<,'>move '>+" . (0+v:count1)<CR>gv nnoremap <silent> <tab> :if &modifiable && !&readonly && &modified <CR> :write<CR> :endif<CR>:bnext<CR> ]]) <|start_filename|>ftplugin/rust.lua<|end_filename|> vim.cmd([[ command! -buffer -bar Run :!rustc % -o main && ./main && rm main ]]) vim.cmd([[ command! -buffer -bar RunTest :!rustc --test % -o main && ./main && rm main ]]) vim.api.nvim_buf_set_keymap(0, 'n', '<Leader>rp', ':Run<CR>', { noremap = true, expr = false, silent = true }) vim.api.nvim_buf_set_keymap(0, 'n', '<Leader>rt', ':RunTest<CR>', { noremap = true, expr = false, silent = true }) <|start_filename|>plugin/tabs.lua<|end_filename|> require('bufferline').setup({ options = { indicator_icon = ' ', buffer_close_icon = '', modified_icon = '●', close_icon = '', close_command = 'Bdelete %d', right_mouse_command = 'Bdelete! %d', left_trunc_marker = '', right_trunc_marker = '', offsets = { { filetype = 'NvimTree', text = 'EXPLORER', text_align = 'center' }, }, show_tab_indicators = true, show_close_icon = false, }, })
UltiRequiem/UltiVim
<|start_filename|>ANSIEscapes.hs<|end_filename|> module ANSIEscapes where data Dir = DU | DD | DL | DR instance Show Dir where show DU = "A" show DD = "B" show DR = "C" show DL = "D" upLine = putStr "\ESC[1A" downLine = putStr "\ESC[1B" up = moveCursor DU down = moveCursor DD backward = moveCursor DL forward = moveCursor DR moveCursor :: Dir -> Int -> IO () moveCursor dir 0 = return () moveCursor dir n = putStr $ "\ESC[" ++ show n ++ show dir killLine = escape "K" restoreCursor = escape "u" saveCursor = escape "s" clearScreen = escape "2J" initTermSize = (escape "[=3h") resetCursor = escape "0;0H" escape e = putStr $ "\ESC[" ++ e yellow str = "\ESC[1;33m" ++ str ++ "\ESC[0m" brown str = "\ESC[0;33m" ++ str ++ "\ESC[0m" blue str = "\ESC[1;34m" ++ str ++ "\ESC[0m" red str = "\ESC[1;31m" ++ str ++ "\ESC[0m" green str = "\ESC[1;32m" ++ str ++ "\ESC[0m" purple str = "\ESC[1;35m" ++ str ++ "\ESC[0m" white str = "\ESC[37m" ++ str ++ "\ESC[0m" --Be careful, these assume someone else will reset the background colour yellowOnGrey str = "\ESC[1;33m\ESC[47m" ++ str ++ "\ESC[0m\ESC[47m" brownOnGrey str = "\ESC[0;33m\ESC[47m" ++ str ++ "\ESC[0m\ESC[47m" blueOnGrey str = "\ESC[1;34m\ESC[47m" ++ str ++ "\ESC[0m\ESC[47m" redOnGrey str = "\ESC[1;31m\ESC[47m" ++ str ++ "\ESC[0m\ESC[47m" greenOnGrey str = "\ESC[1;32m\ESC[47m" ++ str ++ "\ESC[0m\ESC[47m" purpleOnGrey str = "\ESC[1;35m\ESC[47m" ++ str ++ "\ESC[0m\ESC[47m" whiteOnGrey str = "\ESC[37m" ++ str ++ "\ESC[0m" onBlack str = "\ESC[40m" ++ str ++ "\ESC[0m" onGrey str = onGreyEsc ++ str ++ onWhiteEsc onGreyEsc = "\ESC[47m" onWhiteEsc = "\ESC[0m" orange str = str
clarkdm/CS410
<|start_filename|>rrt_planners/include/rrt_planners/ros/ValidityChecker3.h<|end_filename|> #ifndef UPO_RRT_CHECKER3_ #define UPO_RRT_CHECKER3_ //upo RRT library #include <upo_rrt_planners/StateChecker.h> //C++ #include <vector> #include <list> #include <cmath> #include <math.h> #include <iostream> #include <stdio.h> /* printf, fgets */ #include <stdlib.h> /* atof */ #include <exception> // std::exception #include <time.h> /* time */ #include <sys/time.h> //ROS #include <ros/ros.h> #include <ros/package.h> #include <visualization_msgs/Marker.h> #include <tf/transform_datatypes.h> #include <tf/transform_listener.h> #include <nav_msgs/OccupancyGrid.h> #include <geometry_msgs/PointStamped.h> #include <geometry_msgs/Pose2D.h> #include <upo_msgs/PersonPoseUPO.h> #include <upo_msgs/PersonPoseArrayUPO.h> #include <geometry_msgs/PoseStamped.h> #include <sensor_msgs/PointCloud.h> #include <sensor_msgs/PointCloud2.h> #include <sensor_msgs/point_cloud_conversion.h> #include <laser_geometry/laser_geometry.h> #include <nav_msgs/GetMap.h> //PCL #include <pcl/common/transforms.h> #include <pcl/point_types.h> #include <pcl_ros/point_cloud.h> #include "pcl_ros/transforms.h" #include <pcl/register_point_struct.h> //creation of network input #include <upo_rrt_planners/ros/capture.h> //Service for network prediction #include <path_prediction/PathPrediction.h> //#include <boost/thread.hpp> /* Mutex */ #include <mutex> //OpenCV #include <opencv2/opencv.hpp> #include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" using namespace std; namespace upo_RRT_ros { class ValidityChecker3 : public upo_RRT::StateChecker { public: ValidityChecker3(tf::TransformListener* tf, float resol, int width, int height, unsigned int dimensions, int distType); //ValidityChecker3(tf::TransformListener* tf, unsigned int dimensions, int distType); virtual ~ValidityChecker3(); void setup(); void goalCallback(const geometry_msgs::PoseStamped::ConstPtr& msg); void peopleCallback(const upo_msgs::PersonPoseArrayUPO::ConstPtr& msg); void pcCallback(const sensor_msgs::PointCloud::ConstPtr& pc_in); //PointCloud void pc2Callback(const sensor_msgs::PointCloud2::ConstPtr& pc_in); //PointCloud2 void setObstacles(sensor_msgs::PointCloud2 obs); void setupStaticMap(ros::NodeHandle nh); void setupNoMapProjection(); void updateDistTransform(); bool predictionService(vector<int> input, int rows, int cols); //vector<> get_prediction_points(); bool isValid(upo_RRT::State* s) const; //Distance function between two states float distance(upo_RRT::State* s1, upo_RRT::State* s2) const; float getCost(upo_RRT::State* s); //std::vector<float> getFeatures(upo_RRT::State* s); void setGoal2(upo_RRT::State* g) { goal_mutex_.lock(); goal_.header.frame_id = "base_link"; goal_.header.stamp = ros::Time(); goal_.pose.position.x = g->getX(); goal_.pose.position.y = g->getY(); goal_.pose.position.z = 0.0; goal_.pose.orientation = tf::createQuaternionMsgFromYaw(g->getYaw()); goal_mutex_.unlock(); } void setGoal(geometry_msgs::PoseStamped g) { goal_mutex_.lock(); goal_ = g; goal_mutex_.unlock(); } //Implemented for learning purposes //void setPeople(upo_msgs::PersonPoseArrayUPO p); geometry_msgs::PoseStamped transformPoseTo(geometry_msgs::PoseStamped* pose_in, string frame_out, bool usetime) const; bool isQuaternionValid(const geometry_msgs::Quaternion q); vector<int> worldToMap(geometry_msgs::Point32* world_point, nav_msgs::MapMetaData* map_metadata) const; vector<int> BaseLinkWorldToImg(geometry_msgs::Point32* point) const; vector<int> poseToCostmapCell(vector<float> pose) const; vector<float> costmapCellToPose(vector<int> cell) const; //Pre-computations needed just before starting planning void preplanning_computations(); vector<upo_RRT::State> getPredictedPointList(); void setInitialTime(ros::Time t) { time_ = t; } void publish_costmap_ros(ros::Time t); inline float normalizeAngle(float val, float min, float max) const { float norm = 0.0; if (val >= min) norm = min + fmod((val - min), (max-min)); else norm = max - fmod((min - val), (max-min)); return norm; } private: Capture* capture_; ros::ServiceClient cnn_client_; tf::TransformListener* tf_; //Local costmap vector<float> costmap_; mutex costmap_mutex_; float cm_resolution_; float cm_width_; //m float cm_height_; //m int cm_width_pixs_; int cm_height_pixs_; vector<float> cm_origin_; ros::Publisher costmap_pub_; float path_threshold_; //Static map nav_msgs::MapMetaData map_metadata_; double map_resolution_; vector<float> map_origin_; cv::Mat map_image_; mutex dt_mutex_; cv::Mat distance_transform_; bool project_onto_map_; int people_paint_area_; //Point cloud ros::Subscriber sub_pc_; sensor_msgs::PointCloud2 laser_cloud_; mutex pc_mutex_; // list of person objects std::vector<upo_msgs::PersonPoseUPO> people_; ros::Subscriber sub_people_; mutex people_mutex_; //Goal geometry_msgs::PoseStamped goal_; mutex goal_mutex_; ros::Subscriber goal_sub_; ros::Time time_; unsigned int dimensions_; int distanceType_; double insc_radius_robot_; }; } #endif <|start_filename|>rrt_planners/src/planners/simple/SimpleQuickRRTstar.cpp<|end_filename|> #include <rrt_planners/planners/simple/SimpleQuickRRTstar.h> RRT::SimpleQuickRRTstar::SimpleQuickRRTstar() : Planner() { maxRange_ = 0.5; useKnearest_ = false; depth_ = 1; k_rrt_ = 0.0; r_rrt_ = 0.0; rewire_factor_ = 1.1; // useFirstPathBiasing_ = false; // pathBias_ = 0.0; // pathBias_stddev_ = 0.0; } RRT::SimpleQuickRRTstar::~SimpleQuickRRTstar() { } RRT::State* RRT::SimpleQuickRRTstar::steer(State* fromState, State* toState, std::vector<State>& istates) { return steering_->simple3dSteer(fromState, toState, istates); } bool RRT::SimpleQuickRRTstar::collisionFree(State* fromState, State* toState, std::vector<State>& istates) { return steering_->simple3dCollisionFree(fromState, toState, istates); } std::vector<RRT::Node> RRT::SimpleQuickRRTstar::solve(float secs) { /****************************************************************************************** V<-{Xinit}, E<-0; for int i=0,...,n do Xrand <- SampleFree; Xnearest <- Nearest(G=(V,E), Xrand); {(Xnew, Unew, Tnew)} <- Steer(Xnearest, Xrand); if(ObstacleFree(Xnearest, Xnew)) then Xs_near <- Near(G=(V,E), Xnew, min{gamma(log(Card(V)/Card(V))^(1/d), eta}); V <- V U {Xnew} Xmin <- Xnearest; Cmin <- Cost(Xnearest) + C(Line(Xnearest, Xnew)); for each Xnear in Xs_near do //Connect along a minimum-cost path if CollisionFree(Xnear, Xnew) && Cost(Xnear)+C(Line(Xnear, Xnew)) < Cmin then Xmin <- Xnear; Cmin <- Cost(Xnear) + C(Line(Xnear, Xnear)); E <- E U {(Xmin, Xnew)}; for each Xnear in Xs_near do //Rewire the tree if CollisionFree(Xnew, Xnear) && Cost(Xnew) + C(Line(Xnew, Xnear)) < Cost(Xnear) then Xparent <- Parent(Xnear); E <- (E\{(Xparent, Xnear)}) U {(Xnew, Xnear)}; return G=(V,E); ***********************************************************************************************/ // Clear datastructure and initilize it // nn_->clear(); KDTree<RRT::Node> nn(dimensions_); Node ini(*start_); // Node* ini = new Node(*start_); float singleCost = space_->getCost(start_); ini.setCost(singleCost); ini.setIncCost(singleCost); ini.setAccCost(singleCost); nn.add(ini); calculateParamsNearest(); tree_.clear(); // first_path_.clear(); // Statistics unsigned int total_samples = 0; unsigned int valid_samples = 0; unsigned int goal_samples = 0; unsigned int tree_nodes = 1; unsigned int path_nodes = 0; float time = 0.0; float first_sol_time = 0.0; bool solved = false; bool end = false; bool first_sol = true; // Node* solution = NULL; // Node* approxSolution = NULL; Node solution; Node approxSolution; float approxDist = std::numeric_limits<float>::max(); // Goal node Node* goalNode; if (!exploration_) { goalNode = new Node(*goal_); goalNode->setCost(space_->getCost(goal_)); } // printf("Solve. After getting the cost of the goal\n"); // if(first_path_.empty()) // printf("\nSimpleRRTStar. first path is empty!!!!!!!!\n\n"); // Node* randNode = NULL; unsigned int cont_null = 0; double t1, t2; struct timeval stop, start, first_stop; gettimeofday(&start, NULL); t1 = start.tv_sec + (start.tv_usec / 1000000.0); while (!end) { State randState; // sample goal according to the bias parameter if (first_sol && space_->sampleUniform() < goalBias_ && !exploration_) { randState = *goalNode->getState(); goal_samples++; valid_samples++; total_samples++; } else { // Sample a random valid state unsigned int cont = 0; do { // Regular state sampling randState = *space_->sampleState(); cont++; if (cont > 1) total_samples++; else { valid_samples++; total_samples++; } //} while(!space_->isStateValid(&randState)); } while (!space_->getValid3dState(&randState)); } // printf("SimpleRRTStar. sample valid x:%.1f, y:%.1f, z:%.1f\n", randState.getX(), // randState.getY(), randState.getZ()); // if(randNode) // delete randNode; // randNode = new Node(*randState); Node randNode(randState); // delete randState; // printf("SimpleRRTStar. randNode z: %.3f\n", randNode.getState()->getZ()); // Find nearest node in the tree // Node* nearNode = nn_->nearest(&randNode); std::shared_ptr<Node> nearNode = std::make_shared<Node>(nn.nearest(randNode)); // if(nearNode == NULL) // printf("SimpleRRTStar. nearNode = NULL\n"); // printf("SimpleRRTstar. nearNode x:%.2f, y:%.2f, z:%.2f \n", // nearNode->getState()->getX(), nearNode->getState()->getY(), // nearNode->getState()->getZ()); // Steer from nearState to randState and reach the new state std::vector<State> inter_states; State* newState = steer(nearNode->getState(), randNode.getState(), inter_states); // delete randNode; // printf("SimpleRRTStar. After steer\n"); if (newState != nullptr) { // printf("SimpleRRTstar. newState z:%.2f \n", newState->getZ()); // Node* newNode = new Node(*newState); Node newNode(*newState); newNode.setIntermediateStates(inter_states); newNode.setCost(space_->getCost(newNode.getState())); // newState // Use the neighbors of the new node to find the best parent // std::vector<RRT::Node*> nbrs; std::vector<RRT::Node> nbrs; getNearestNeighbors(nn, newNode, nbrs); // printf("Neighbors obtained: %u\n", (unsigned int)nbrs.size()); // Quick RRT* - Add the parents of the nearest neighbors getAncestors(nbrs, depth_); Node* node_min = nearNode.get(); float inc_cost = steering_->motionCost(nearNode.get(), &newNode); float cost_min = nearNode->getAccCost() + inc_cost; // Check the nodes costs to chose the parent with // a lower connection cost // std::vector<RRT::Node*> nbrs_aux; // nbrs_aux.push_back(nearNode); std::vector<unsigned int> nbrs_ind; std::vector<State> intermediates; intermediates = inter_states; for (unsigned int i = 0; i < nbrs.size(); i++) { // CAMBIAR ESTO!!! PRIMERO COMPROBAR SI EL COSTE ES MENOR QUE EL COSTE MINIMO // ACTUAL. // SI LO ES, ENTONCES COMPROBAR EL COLLISION FREE EN LUGAR DE COMPROBAR LA // COLLISION PRIMERO SIEMPRE!!!! /*if(nbrs[i]!=nearNode && collisionFree(nbrs[i]->getState(), newNode->getState(), inter_states)) //newState { nbrs_aux.push_back(nbrs[i]); float total_cost = nbrs[i]->getAccCost() + steering_->motionCost(nbrs[i], newNode); if(total_cost < cost_min) { node_min = nbrs[i]; cost_min = total_cost; intermediates = inter_states; } }*/ if ((&nbrs[i]) != nearNode.get()) // newState { // nbrs_aux.push_back(nbrs[i]); float total_cost = nbrs[i].getAccCost() + steering_->motionCost(&nbrs[i], &newNode); if (total_cost < cost_min) { if (collisionFree(nbrs[i].getState(), newNode.getState(), inter_states)) { // nbrs_aux.push_back(nbrs[i]); nbrs_ind.push_back(i); node_min = &nbrs[i]; cost_min = total_cost; intermediates = inter_states; } } } } newNode.setParent(node_min); newNode.setIncCost(steering_->motionCost(node_min, &newNode)); newNode.setAccCost(cost_min); newNode.setIntermediateStates(intermediates); // Add the new node to the tree nn.add(newNode); tree_nodes++; // Rewire the tree /*for(unsigned int i=0; i<nbrs_aux.size(); i++) { if(nbrs_aux[i] != node_min) //&& collisionFree(newState, nbrs_aux[i]->getState()) //Only valid for non-kinematics RRT* { float total_cost = newNode->getAccCost() + steering_->motionCost(newNode, nbrs_aux[i]); if(total_cost < nbrs_aux[i]->getAccCost()) { //printf("¡¡¡¡performing a rewiring!!!\n"); //newNode->setChildren(nbrs[i]); nbrs_aux[i]->setParent(newNode); nbrs_aux[i]->setIncCost(steering_->motionCost(newNode, nbrs_aux[i])); nbrs_aux[i]->setAccCost(total_cost); } } }*/ for (unsigned int i = 0; i < nbrs.size(); i++) { if (&nbrs[i] != node_min) //&& collisionFree(newState, nbrs_aux[i]->getState()) ////Only valid for non-kinematics RRT* { float total_cost = newNode.getAccCost() + steering_->motionCost(&newNode, &nbrs[i]); if (total_cost < nbrs[i].getAccCost()) { bool colfree = false; for (unsigned int f = 0; f < nbrs_ind.size(); f++) { if (nbrs_ind[f] == i) { colfree = true; break; } } if (colfree || collisionFree(newNode.getState(), nbrs[i].getState(), inter_states)) { // printf("¡¡¡¡performing a rewiring!!!\n"); // newNode->setChildren(nbrs[i]); nbrs[i].setParent(&newNode); nbrs[i].setIncCost(steering_->motionCost(&newNode, &nbrs[i])); nbrs[i].setAccCost(total_cost); } } } } if (!exploration_) { float dist = 0.0; solved = space_->isSimpleGoalToleranceSatisfied(newNode.getState(), dist); // newState // printf("SimpleRRTPlanner. After rewiring\n"); if (solved) { approxDist = dist; solution = newNode; if (first_sol) { gettimeofday(&first_stop, NULL); double t3 = first_stop.tv_sec + (first_stop.tv_usec / 1000000.0); first_sol_time = (t3 - t1); // Store the first solution to draw samples from it. /*if(useFirstPathBiasing_) { Node* current = solution; while (current != NULL) { State state = *current->getState(); //copyState(&state, current->getState()); first_path_.push_back(state); current = current->getParent(); } }*/ first_sol = false; } } else if (dist < approxDist) { approxDist = dist; approxSolution = newNode; } } } else { // printf("SimpleRRTstar. newState = NULL\n"); cont_null++; } // delete newState; gettimeofday(&stop, NULL); t2 = stop.tv_sec + (stop.tv_usec / 1000000.0); time = t2 - t1; // printf("Time: %.3f, fin: %.3f\n", time, secs); if (time >= secs) { end = true; } } if (!solved && !exploration_) { printf("\nRRT. Approximate solution found. dist to goal: %.3f\n", approxDist); solution = approxSolution; } else { printf("\nRRT. Algorithm executed for %.6f secs\n", time); } // printf("Number of null states: %u\n", cont_null); if (storeTree_) { std::vector<Node> nodes; nn.list(nodes); storeTree(nodes); if (exploration_) { storeLeafNodes(nodes); solution = space_->exploreLeafStates(leaves_); } } else if (exploration_) { std::vector<Node> nodes; nn.list(nodes); storeLeafNodes(nodes); solution = space_->exploreLeafStates(leaves_); } // Construct the solution path std::vector<RRT::Node> path; // path for a weird bug if (approxDist > 1000.0 && !exploration_) { printf("\nSimpleRRTStar. Error calculating the path!!!!\n\n"); // freeTreeMemory(); return path; } if (!exploration_) solution.getState()->setYaw(goal_->getYaw()); Node* current = &solution; path_cost_ = current->getAccCost(); if (path_cost_ == 0) printf("\n----------SimpleRRTStar. path_cost = 0!!!!-------------\n"); else printf("Path cost: %.4f\n", path_cost_); while (current != nullptr) { Node node = *current; // copyNode(&node, current); path.push_back(node); current = current->getParent(); path_nodes++; } stats_.planning_time = time; stats_.first_sol_time = first_sol_time; stats_.total_samples = total_samples; stats_.valid_samples = valid_samples; stats_.goal_samples = goal_samples; stats_.tree_nodes = tree_nodes; stats_.leaf_nodes = leaves_.size(); stats_.path_nodes = path_nodes; delete current; // delete ini; if (!exploration_) delete goalNode; // delete solution; // delete approxSolution; // freeTreeMemory(); // first_path_.clear(); return path; } void RRT::SimpleQuickRRTstar::getAncestors(std::vector<Node>& nbrs, int depth) { // printf("Neighbors size: %u\n", (unsigned int)nbrs.size()); std::vector<Node*> aux; for (unsigned int i = 0; i < nbrs.size(); i++) { std::vector<Node*> parents; Node* n = &nbrs[i]; // Store the parents of nbrs[i] to depth for (int j = 0; j < depth; j++) { //if (n->getParent() != nullptr) { parents.push_back(n->getParent()); n = n->getParent(); } } for (unsigned int h = 0; h < parents.size(); h++) { if (aux.empty()) { // aux.insert(std::end(aux), std::begin(parents), std::end(parents)); aux.insert(aux.end(), parents.begin(), parents.end()); } else { bool insert = true; for (unsigned int k = 0; k < aux.size(); k++) { if (parents[h] == aux[k]) { insert = false; break; } } if (insert) aux.push_back(parents[h]); } } } // Add the parents to nbrs // nbrs.insert(nbrs.end(), aux.begin(), aux.end()); for (unsigned int i = 0; i < aux.size(); i++) nbrs.push_back(*aux[i]); // printf("New Neighbors size: %u\n", (unsigned int)nbrs.size()); } void RRT::SimpleQuickRRTstar::getNearestNeighbors(KDTree<RRT::Node>& nn, const Node& node, std::vector<Node>& nbrs) { double size = static_cast<double>(nn.size() + 1u); if (useKnearest_) { // k-nearest RRT* unsigned int k = std::ceil(k_rrt_ * log(size)); // printf("k: %u\n", k); // nn_->nearestK(node, k, nbrs); nbrs = nn.knearest(node, k); } else { // Nearest in radius RRT* double r = std::min((double)maxRange_, r_rrt_ * std::pow(log(size) / size, 1 / static_cast<double>(space_->getDimensions()))); // printf("Neighbors in Radius: %.3f\n", r); // nn_->nearestR(node, r, nbrs); nbrs = nn.radiusSearch(node, r * r); } } void RRT::SimpleQuickRRTstar::calculateParamsNearest() { double dim = (double)space_->getDimensions(); // K-nearest if (useKnearest_) { // k_rrt_ = 1.1 * (boost::math::constants::e<double>() + // (boost::math::constants::e<double>() / dim)); k_rrt_ = rewire_factor_ * (exp(1) + (exp(1) / dim)); } else { // Radius float free_volume = space_->getSpaceMeasure() / 2.0; float unitBall = space_->getUnitBallMeasure(); r_rrt_ = rewire_factor_ * 2 * pow((1 + 1 / dim) * (free_volume / unitBall), 1 / dim); } } /*float RRT::SimpleQuickRRTstar::motionCost(Node* n1, Node* n2) { float dist = sqrt(distanceFunction(n1, n2)); //Normalize //float max_d = sqrt((space_->getSizeX()*2*space_->getSizeX()*2)+(space_->getSizeY()*2*space_->getSizeY()*2)); //dist = dist / max_d; //printf("Dist: %.3f, sqrt(dist): %.3f, avg cost: %.3f\n", dist, sqrt(dist), (n1->getCost() + n2->getCost())/2.0 ); return ((n1->getCost() + n2->getCost()) / 2.0) * dist; //return ((n1->getCost() + n2->getCost()) / 2.0) + dist; }*/ <|start_filename|>rrt_planners/include/rrt_planners/ros/capture.h<|end_filename|> #include <math.h> #include <iostream> #include <string> #include <stdio.h> #include <time.h> //ROS #include <ros/ros.h> #include <ros/package.h> #include <geometry_msgs/PointStamped.h> #include <geometry_msgs/Pose2D.h> #include <tf/transform_datatypes.h> #include <tf/transform_listener.h> #include <nav_msgs/OccupancyGrid.h> #include <upo_msgs/PersonPoseUPO.h> #include <upo_msgs/PersonPoseArrayUPO.h> #include <geometry_msgs/PoseStamped.h> #include <sensor_msgs/PointCloud.h> #include <sensor_msgs/PointCloud2.h> #include <sensor_msgs/point_cloud_conversion.h> #include <laser_geometry/laser_geometry.h> #include <nav_msgs/GetMap.h> //PCL #include <pcl/common/transforms.h> #include <pcl/point_types.h> #include <pcl_ros/point_cloud.h> #include "pcl_ros/transforms.h" #include <pcl/register_point_struct.h> //Boost //#include <boost/thread.hpp> // Mutex #include <mutex> // std::mutex //OpenCV #include <opencv2/opencv.hpp> #include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" using namespace std; class Capture { public: Capture(sensor_msgs::PointCloud* obs, vector<upo_msgs::PersonPoseUPO>* people, geometry_msgs::PoseStamped* goal); Capture(); ~Capture(); void setup(); void setScenario(sensor_msgs::PointCloud* obs, vector<upo_msgs::PersonPoseUPO>* people, geometry_msgs::PoseStamped* goal); //void TransformToLocal(sensor_msgs::PointCloud* obs, vector<upo_msgs::PersonPoseUPO>* people, geometry_msgs::PoseStamped* goal, vector<geometry_msgs::PoseStamped>* agent); bool addObstacles(cv::Mat* img); bool addPeople(cv::Mat* img); bool addGoal(cv::Mat* img); bool addPath(cv::Mat* img); vector<int> generateImg(sensor_msgs::PointCloud* obs, vector<upo_msgs::PersonPoseUPO>* people, geometry_msgs::PoseStamped* goal); cv::Mat generateImg(); float normalizeAngle(float val, float min, float max); bool draw_triangle(cv::Mat* img, geometry_msgs::Point32 center, float orientation, float radius); // retorna "a - b" en segundos double timeval_diff(struct timeval *a, struct timeval *b) { return (double)(a->tv_sec + (double)a->tv_usec/1000000) - (double)(b->tv_sec + (double)b->tv_usec/1000000); } private: pair<int,int> worldToImg(geometry_msgs::Point32* world_point); const string currentDateTime(); bool save_img_; unsigned int save_count_; string save_path_; // Global parameters and object bool use_static_map_; bool add_demo_path_; bool only_path_label_; std::string store_dir_; bool goal_ok_; bool greyscale_; bool people_orientation_; // Image map data float resolution_; // m/px int px_height_; //200px * 0.05m/px = 10m int px_width_; //px pair<int,int> px_origin_; //px pair<float,float> w_origin_; //m // Point cloud (obstacles) sensor_msgs::PointCloud* obs_; // people array vector<upo_msgs::PersonPoseUPO>* people_; // Goal geometry_msgs::PoseStamped* goal_; // Robot Path vector<geometry_msgs::PoseStamped>* agent_; }; <|start_filename|>rrt_planners/src/planners/simple/SimpleRRT.cpp<|end_filename|> #include <rrt_planners/planners/simple/SimpleRRT.h> //#define PRINT_STATISTICS false RRT::SimpleRRT::SimpleRRT() : Planner() { // maxRange_ = 0.5; // steering_ = new Steering(space_, maxRange_); } RRT::SimpleRRT::~SimpleRRT() { } RRT::State* RRT::SimpleRRT::steer(State* fromState, State* toState, std::vector<State>& istates) { return steering_->simple3dSteer(fromState, toState, istates); } std::vector<RRT::Node> RRT::SimpleRRT::solve(float secs) { /************************************************** GENERATE_RRT(Xinit, K, t) V<-{Xinit}, E<-0; for k=1 to K do Xrand <- SampleFree; Xnearest <- Nearest(G=(V,E), Xrand); Unew <- SelectInput(Xrand, Xnearest, Xrand); Xnew <- Steer(Xnearest, Unew, t); V <- V U {Xnew}; E <- E U {(Xnearest, Xnew, Unew)}; return G = (V,E); ***************************************************/ // Clear datastructure and initilize it // nn_->clear(); KDTree<RRT::Node> nn(dimensions_); Node ini(*start_); nn.add(ini); tree_.clear(); // Statistics unsigned int total_samples = 0; unsigned int valid_samples = 0; unsigned int goal_samples = 0; unsigned int tree_nodes = 1; unsigned int path_nodes = 0; float time = 0.0; bool solved = false; bool end = false; Node solution; Node approxSolution; float approxDist = std::numeric_limits<float>::max(); double t1, t2; struct timeval stop, start; gettimeofday(&start, NULL); t1 = start.tv_sec + (start.tv_usec / 1000000.0); while (!end) { State randState; // sample goal according to the bias parameter if (space_->sampleUniform() < goalBias_ && !exploration_) { randState = *goal_; // State* randState = goal_; // randNode = new Node(*randState); goal_samples++; valid_samples++; total_samples++; // delete randState; } else { // Sample a random valid state unsigned int cont = 0; do { randState = *space_->sampleState(); cont++; if (cont > 1) total_samples++; else { valid_samples++; total_samples++; } //} while(!space_->isStateValid(&randState)); } while (!space_->getValid3dState(&randState)); } Node randNode(randState); // Find nearest node in the tree std::shared_ptr<Node> nearNode = std::make_shared<Node>(nn.nearest(randNode)); //Node& nearNode = nn.nearest(randNode); std::vector<State> inter_states; State* newState = steer(nearNode->getState(), randNode.getState(), inter_states); // delete randNode; // Add the new node to the tree if (newState != nullptr) { Node newNode(*newState); // delete newState; newNode.setIntermediateStates(inter_states); newNode.setParent(nearNode.get()); // setChildren(newNode); nearNode->setChildren(); nn.add(newNode); tree_nodes++; if (!exploration_) { // Check if we reach the goal float dist = 0.0; solved = space_->isSimpleGoalToleranceSatisfied(newState, dist); if (solved) { approxDist = dist; solution = newNode; } else if (dist < approxDist) { approxDist = dist; approxSolution = newNode; } } } gettimeofday(&stop, NULL); t2 = stop.tv_sec + (stop.tv_usec / 1000000.0); time = t2 - t1; if (time >= secs || solved) { end = true; } } if (!solved && !exploration_) { printf("\nRRT. Approximate solution found. dist to goal: %.3f\n", approxDist); solution = approxSolution; } else { printf("\nRRT. Planning performed during %.6f secs\n", time); } if (storeTree_) { std::vector<Node> nodes; nn.list(nodes); storeTree(nodes); if (exploration_) { storeLeafNodes(nodes); solution = space_->exploreLeafStates(leaves_); } } else if (exploration_) { std::vector<Node> nodes; nn.list(nodes); storeLeafNodes(nodes); solution = space_->exploreLeafStates(leaves_); } // Construct the solution path std::vector<RRT::Node> path; solution.getState()->setYaw(goal_->getYaw()); Node* current = &solution; path_cost_ = current->getAccCost(); while (current != nullptr) { Node node = *current; // copyNode(&node, current); path.push_back(node); current = current->getParent(); path_nodes++; } stats_.planning_time = time; stats_.first_sol_time = time; stats_.total_samples = total_samples; stats_.valid_samples = valid_samples; stats_.goal_samples = goal_samples; stats_.tree_nodes = tree_nodes; stats_.leaf_nodes = leaves_.size(); stats_.path_nodes = path_nodes; /*if(PRINT_STATISTICS) { printf("Planning time: %.4f secs\n", time); printf("Total samples: %u \n", total_samples); printf("Valid samples: %u \n", valid_samples); printf("Goal samples: %u \n", goal_samples); printf("Tree nodes: %u \n", tree_nodes); printf("Path nodes: %u \n\n", path_nodes); }*/ delete current; // delete ini; // delete solution; // delete approxSolution; // freeTreeMemory(); return path; } /*void RRT::RRT::getTree(std::vector<RRT::Node*> &tree) const { //nn_->list(tree); nn_->getTree(tree); printf("Getting tree. Size: %u\n", (unsigned int)tree.size()); for(unsigned int i=0; i<tree.size(); i++) { if(tree[i]->getState() == NULL) printf("State node %u equals to NULL\n", i); else printf("Node %u. x:%.2f, y:%.2f\n", i+1, tree[i]->getState()->getX(), tree[i]->getState()->getY()); } //mytree = tree; }*/ <|start_filename|>local_3d_planner/src/local_3d_planner.cpp<|end_filename|> /********************************************************************* * * Author: <NAME> *********************************************************************/ #include <local_3d_planner/local_3d_planner.h> //#include <costmap_2d/footprint.h> #include <string> #include <sstream> #include <math.h> #include <angles/angles.h> #include <boost/algorithm/string.hpp> #include <ros/console.h> // for computing path distance #include <queue> using namespace std; // using namespace costmap_2d; namespace local_3d_planner { /*void UpoPlanner::reconfigure(SimpleLocalPlannerConfig &cfg) { SimpleLocalPlannerConfig config(cfg); boost::mutex::scoped_lock l(configuration_mutex_); acc_lim_trans_ = config.max_trans_acc; acc_lim_rot_ = config.max_rot_acc; max_vel_x_ = config.max_trans_vel; min_vel_x_ = config.min_trans_vel; max_vel_th_ = config.max_rot_vel; min_vel_th_ = config.min_rot_vel; min_in_place_vel_th_ = config.min_in_place_rot_vel; goal_lin_tolerance_ = config.xy_goal_tolerance; goal_ang_tolerance_ = config.yaw_goal_tolerance; wp_tolerance_ = config.wp_tolerance; sim_time_ = config.sim_time; sim_granularity_ = config.sim_granularity; angular_sim_granularity_ = config.angular_sim_granularity; dwa_ = config.sample_angular_vels; //printf("\nPure Planner Reconfigure. new wp_tolerance: %.2f\n", wp_tolerance_); }*/ Local3DPlanner::Local3DPlanner( std::string name, tf2_ros::Buffer* tf, local_3d_planner::OdometryHelperRos* oh, // std::vector<geometry_msgs::Point> footprint_spec, double robot_radius, double local_area_radius, double controller_freq, double max_trans_vel, double min_trans_vel, double max_rot_vel, double min_rot_vel, double min_in_place_rot_vel, double max_trans_acc, double max_rot_acc, double yaw_goal_tolerance, double xy_goal_tolerance, double wp_tolerance, double sim_time, double sim_granularity, double angular_sim_granularity, bool dwa) { // costmap_2d::calculateMinAndMaxDistances(footprint_spec_, inscribed_radius_, // circumscribed_radius_); // printf("\n\n\n---FOOTPRINT----\n"); // printf("inscribed_radius: %.3f, circumscribed_radius: %.3f\n", inscribed_radius_, // circumscribed_radius_); // printf("Footprint_specs:\n"); // for(unsigned int i = 0; i<footprint_spec_.size(); i++) //{ // printf("point %u: x=%.3f, y=%.3f\n", (i+1), footprint_spec_[i].x, //footprint_spec_[i].y); //} // printf("\n\n"); controller_freq_ = controller_freq; goal_reached_ = false; // For pure-pursuit running_ = false; new_plan_ = false; wp_index_ = -1; acc_lim_trans_ = max_trans_acc; acc_lim_rot_ = max_rot_acc; max_vel_x_ = max_trans_vel; min_vel_x_ = min_trans_vel; max_vel_th_ = max_rot_vel; min_vel_th_ = min_rot_vel; min_in_place_vel_th_ = min_in_place_rot_vel; goal_lin_tolerance_ = xy_goal_tolerance; goal_ang_tolerance_ = yaw_goal_tolerance; wp_tolerance_ = wp_tolerance; sim_time_ = sim_time; sim_granularity_ = sim_granularity; angular_sim_granularity_ = angular_sim_granularity; dwa_ = dwa; robot_radius_ = robot_radius; local_area_radius_ = local_area_radius; collision_detector_ = new CollisionDetection( name, tf, oh, max_vel_x_, max_vel_th_, acc_lim_trans_, acc_lim_rot_, sim_time_, robot_radius_, local_area_radius_, sim_granularity_); } Local3DPlanner::~Local3DPlanner() { delete collision_detector_; } bool Local3DPlanner::updatePlan(const vector<geometry_msgs::PoseStamped>& new_plan) { goal_reached_ = false; // Copy new plan global_plan_.clear(); global_plan_.resize(new_plan.size()); for (unsigned int i = 0; i < new_plan.size(); ++i) { global_plan_[i] = new_plan[i]; } // Check plan size if (global_plan_.size() == 0) { running_ = false; wp_index_ = -1; ROS_WARN("New local plan size = 0!"); return true; } // Set the way-point index to the first point of the path wp_index_ = 0; running_ = true; new_plan_ = true; // Set plan goal point geometry_msgs::PoseStamped& goal_pose = global_plan_[global_plan_.size() - 1]; goal_x_ = goal_pose.pose.position.x; goal_y_ = goal_pose.pose.position.y; goal_z_ = goal_pose.pose.position.z; goal_t_ = tf::getYaw(goal_pose.pose.orientation); // Set the plan starting point geometry_msgs::PoseStamped& start_pose = global_plan_[0]; start_x_ = start_pose.pose.position.x; start_y_ = start_pose.pose.position.y; start_z_ = start_pose.pose.position.z; start_t_ = tf::getYaw(start_pose.pose.orientation); return true; } bool Local3DPlanner::isGoalReached() { if (goal_reached_) { goal_reached_ = false; // we reset the flag return true; } return goal_reached_; } void Local3DPlanner::resetGoal() { goal_reached_ = false; } // given the current state of the robot, find a good control command bool Local3DPlanner::findBestAction(geometry_msgs::PoseStamped global_pose, geometry_msgs::PoseStamped global_vel, geometry_msgs::Twist& cmd_vel) { // ros::WallTime t1 = ros::WallTime::now(); // boost::mutex::scoped_lock l(configuration_mutex_); goal_reached_ = false; double vx, vy = 0.0, vt; // Check we have a path and we are running if (!running_) { vx = 0.0; vt = 0.0; cmd_vel.linear.x = vx; cmd_vel.linear.y = 0.0; cmd_vel.linear.z = 0.0; cmd_vel.angular.x = 0.0; cmd_vel.angular.y = 0.0; cmd_vel.angular.z = vt; printf("FindBestAction. PurePursuit waiting for a path\n"); return true; } // Get current robot position and velocity in X, Y and Theta (odom) float rx, ry, rz, rt, rvx, rvy, rvt; rx = global_pose.pose.position.x; ry = global_pose.pose.position.y; rz = global_pose.pose.position.z; rt = tf::getYaw(global_pose.pose.orientation); rvx = global_vel.pose.position.x; rvy = global_vel.pose.position.y; rvt = tf::getYaw(global_vel.pose.orientation); // Check if we are close enough to the goal double dist_goal = sqrt((rx - goal_x_) * (rx - goal_x_) + (ry - goal_y_) * (ry - goal_y_)); //+(rz-goal_z_)*(rz-goal_z_)); double dist_start = sqrt((rx - start_x_) * (rx - start_x_) + (ry - start_y_) * (ry - start_y_)); //+(rz-start_z_)*(rz-start_z_)); if (dist_goal < goal_lin_tolerance_) { printf("FindBestAction. dist_goal: %.2f. rx:%.2f, ry:%.2f, rz:%.2f, goalx:%.2f, goaly:%.2f, goalz: %.2f\n", dist_goal, rx, ry, rz, goal_x_, goal_y_, goal_z_); // Stop the robot vx = 0.0; vy = 0.0; // Rotate at minumin velocity until reaching the goal angle if (fabs(goal_t_ - rt) < goal_ang_tolerance_) { vt = 0.0; running_ = false; goal_reached_ = true; } /*else if(goal_t_ > rt) vt = min_in_place_vel_th_; else vt = -min_in_place_vel_th_; */ // Modified by Noé else { float ang_diff = goal_t_ - rt; ang_diff = normalizeAngle(ang_diff, -M_PI, M_PI); if (ang_diff > 0.0) vt = min_in_place_vel_th_; else vt = -min_in_place_vel_th_; } // Added by Noé cmd_vel.linear.x = vx; cmd_vel.linear.y = vy; cmd_vel.linear.z = 0.0; cmd_vel.angular.x = 0.0; cmd_vel.angular.y = 0.0; cmd_vel.angular.z = vt; // ros::WallTime t2 = ros::WallTime::now(); // double secs = (t2-t1).toSec(); // printf("\n\nFindBestPathTime: %f seconds\n\n", secs); printf("FindBestAction. goal reached, sending zero velocity\n"); return true; } // Do we have a new plan? get the closest point into the plan if (new_plan_) { new_plan_ = false; double dist; wp_index_ = 0; for (int i = global_plan_.size() - 1; i >= 0; i--) { double wpx = global_plan_[i].pose.position.x; double wpy = global_plan_[i].pose.position.y; double wpz = global_plan_[i].pose.position.z; dist = sqrt((rx - wpx) * (rx - wpx) + (ry - wpy) * (ry - wpy)); //+(rz-wpz)*(rz-wpz)); if (dist < wp_tolerance_) { wp_index_ = i; break; } } } // Get current way-point in the path double wpx = global_plan_[wp_index_].pose.position.x; double wpy = global_plan_[wp_index_].pose.position.y; double wpz = global_plan_[wp_index_].pose.position.z; // Is this way-point still valid? double dist_swp = sqrt((rx - wpx) * (rx - wpx) + (ry - wpy) * (ry - wpy)); //+(rz-wpz)*(rz-wpz)); while (dist_swp < wp_tolerance_ && wp_index_ < (int)global_plan_.size() - 1) { wp_index_++; wpx = global_plan_[wp_index_].pose.position.x; wpy = global_plan_[wp_index_].pose.position.y; // wpz = global_plan_[wp_index_].pose.position.z; dist_swp = sqrt((rx - wpx) * (rx - wpx) + (ry - wpy) * (ry - wpy)); //+(rz-wpz)*(rz-wpz)); } // Transform way-point into local robot frame and get desired x,y,theta double dx = (wpx - rx) * cos(rt) + (wpy - ry) * sin(rt); double dy = -(wpx - rx) * sin(rt) + (wpy - ry) * cos(rt); double dt = atan2(dy, dx); // double dz = (wpz - rz); //??? // features_->transformPoseTo(geometry_msgs::PoseStamped pose_in, std::string frame_out, // bool usetime); double incr = 1 / controller_freq_; // Check if we need rotation in place before moving the robot to reach the way-point if (fabs(dt) > 1.3) // 0.87 0.7~41º 0.79~45º { // vx = rvx-incr; // if(vx < 0.0) // vx = 0.0; vx = 0; vy = 0.0; vt = min_in_place_vel_th_; if (dt < 0.0) vt = -min_in_place_vel_th_; // printf("place_vt: %.2f\n", vt); } else // Select the linear and angular velocities to reach the way-point { // Compute actions depending to the distance to the goal and the starting points double dist_th = 1.5; if (dist_goal < dist_th) { vx = min_vel_x_ + (max_vel_x_ - min_vel_x_) * dist_goal / dist_th; vy = 0.0; vt = min_vel_th_ + (max_vel_th_ - min_vel_th_) * dist_goal / dist_th; //--added by noe if (dt < 0.0) vt *= -1; } /*else if(dist_start < dist_th) { vx = min_vel_x_ + (max_vel_x_ - min_vel_x_)*dist_start/dist_th; vy = 0.0; vt = min_vel_th_ + (max_vel_th_ - min_vel_th_)*dist_start/dist_th; }*/ else { vx = max_vel_x_ * (0.1 + exp(-fabs(dt))); // * tanh(4*dist_swp); //max_vel_x_; if (vx > max_vel_x_) vx = max_vel_x_; vy = 0.0; vt = max_vel_th_ * dt; // max_vel_th_; } // if(vx > rvx+incr) // vx = rvx+incr; // Set the sign of the commanded angular velocity and reset in case of small // variations // if(dt < 0.0) //commented by Noé // vt *= -1; if (fabs(dt) < 0.1) vt = 0.0; } // Check if the action collide with an obstacle double px = 0.0, py = 0.0, pz = 0.0, pth = 0.0; bool valid = true; if (vx != 0.0) { // valid = checkTrajectory(rx, ry, rt, rvx, rvy, rvt, vx, vy, vt, px, py, pth); ros::WallTime t_check1 = ros::WallTime::now(); valid = collision_detector_->checkTraj(rvx, rvy, rvt, vx, vy, vt, px, py, pz, pth); ros::WallTime t_check2 = ros::WallTime::now(); double secs = (t_check2 - t_check1).toSec(); // printf("\n\nCheckTraj time: %f seconds\n\n", secs); } if (valid /*|| fabs(vx) < 0.0001*/) { cmd_vel.linear.x = vx; cmd_vel.linear.y = vy; cmd_vel.linear.z = 0.0; cmd_vel.angular.x = 0.0; cmd_vel.angular.y = 0.0; cmd_vel.angular.z = vt; // ros::WallTime t2 = ros::WallTime::now(); // double secs = (t2-t1).toSec(); // printf("\n\nFindBestPathTime: %f seconds\n\n", secs); // printf("FindBestAction. validTraj found, vx:%.2f, vy:%.2f, vth:%.2f\n", vx, vy, // vt); return true; } // Try to find a valid command by sampling vels else if (dwa_) { // printf("Dentro de DWA!!!!!!!\n"); float vt_orig = vt; float vx_orig = vx; float ang_vel_inc = 0.1; float lin_vel_dec = 0.1; vels_ best_vels; best_vels.vel_x = -1.0; best_vels.vel_y = vy; // Linear vel for (unsigned int l = 0; l <= 3; l++) { vx = vx_orig - (lin_vel_dec * l); if (vx < 0.1) continue; best_vels.vel_x = vx; // Angular vel for (unsigned int v = 1; v <= 4; v++) { // To the right vt = vt_orig + (ang_vel_inc * v); if (fabs(vt) > max_vel_th_) vt = max_vel_th_; bool valid1 = collision_detector_->checkTraj(rvx, rvy, rvt, vx, vy, vt, px, py, pz, pth); double d1 = 0.0; if (valid1) { d1 = sqrt((dx - px) * (dx - px) + (dy - py) * (dy - py)); // + (dz-pz)*(dz-pz)); best_vels.vel_th = vt; } // to the left vt = vt_orig - (ang_vel_inc * v); if (fabs(vt) > max_vel_th_) vt = -max_vel_th_; bool valid2 = collision_detector_->checkTraj(rvx, rvy, rvt, vx, vy, vt, px, py, pz, pth); if (valid2) { // If both commands are valid, // chose the closest to the path. if (valid1) { double d2 = sqrt((dx - px) * (dx - px) + (dy - py) * (dy - py)); // + (dz-pz)*(dz-pz)); if (d2 < d1) { best_vels.vel_th = vt; } } } if (valid1 || valid2) { cmd_vel.linear.x = best_vels.vel_x; cmd_vel.linear.y = best_vels.vel_y; cmd_vel.linear.z = 0.0; cmd_vel.angular.x = 0.0; cmd_vel.angular.y = 0.0; cmd_vel.angular.z = best_vels.vel_th; // printf("\nValid cmd found! vx:%.2f, vth:%.2f\n", vx, vt); // ros::WallTime t2 = ros::WallTime::now(); // double secs = (t2-t1).toSec(); // printf("\n\nFindBestPathTime: %f seconds\n\n", secs); // printf("FindBestAction. Valid Traj found with DWA. vx:%.2f, vy:%.2f, // vth:%.2f\n", cmd_vel.linear.x, cmd_vel.linear.y, cmd_vel.angular.z); return true; } } } } // If still a valid command is not found, try to rotate in the spot if (dt > 0.09 || dt < -0.09) // 0.09rad~5º { // printf("The robot should rotate on the spot\n"); vx = 0.0; vy = 0.0; vt = min_in_place_vel_th_; if (dt < 0.0) vt = -min_in_place_vel_th_; cmd_vel.linear.x = vx; cmd_vel.linear.y = vy; cmd_vel.linear.z = 0.0; cmd_vel.angular.x = 0.0; cmd_vel.angular.y = 0.0; cmd_vel.angular.z = vt; // ros::WallTime t2 = ros::WallTime::now(); // double secs = (t2-t1).toSec(); // printf("\n\nFindBestPathTime: %f seconds\n\n", secs); printf("FindBestAction. Rotating in the spot vx:%.2f, vy:%.2f, vth:%.2f\n", vx, vy, vt); return true; } else { // Stop the robot // printf("The robot should stop\n"); cmd_vel.linear.x = 0.0; cmd_vel.linear.y = 0.0; cmd_vel.linear.z = 0.0; cmd_vel.angular.x = 0.0; cmd_vel.angular.y = 0.0; cmd_vel.angular.z = 0.0; // ros::WallTime t2 = ros::WallTime::now(); // double secs = (t2-t1).toSec(); // printf("\n\nFindBestPathTime: %f seconds\n\n", secs); printf("FindBestAction. No valid command was found\n"); return false; // return true; } } // we need to take the footprint of the robot into account when we calculate cost to // obstacles /*double UpoPlanner::footprintCost(double x_i, double y_i, double theta_i){ //check if the footprint is legal return world_model_.footprintCost(x_i, y_i, theta_i, footprint_spec_, inscribed_radius_, circumscribed_radius_); }*/ }; <|start_filename|>indires_macro_actions/src/Indires_macro_actions.cpp<|end_filename|> #include <indires_macro_actions/Indires_macro_actions.h> /* Status can take this values: uint8 PENDING = 0 # The goal has yet to be processed by the action server uint8 ACTIVE = 1 # The goal is currently being processed by the action server uint8 PREEMPTED = 2 # The goal received a cancel request after it started executing # and has since completed its execution (Terminal State) uint8 SUCCEEDED = 3 # The goal was achieved successfully by the action server (Terminal State) uint8 ABORTED = 4 # The goal was aborted during execution by the action server due # to some failure (Terminal State) uint8 REJECTED = 5 # The goal was rejected by the action server without being processed, # because the goal was unattainable or invalid (Terminal State) uint8 PREEMPTING = 6 # The goal received a cancel request after it started executing # and has not yet completed execution uint8 RECALLING = 7 # The goal received a cancel request before it started executing, # but the action server has not yet confirmed that the goal is canceled uint8 RECALLED = 8 # The goal received a cancel request before it started executing # and was successfully cancelled (Terminal State) uint8 LOST = 9 # An action client can determine that a goal is LOST. This should not be # sent over the wire by an action server */ // namespace macroactions { Indires_macro_actions::Indires_macro_actions(tf2_ros::Buffer* tf) { tf_ = tf; // UpoNav_ = nav; ros::NodeHandle n("~"); // Dynamic reconfigure // dsrv_ = new // dynamic_reconfigure::Server<upo_navigation_macro_actions::NavigationMacroActionsConfig>(n); // dynamic_reconfigure::Server<upo_navigation_macro_actions::NavigationMacroActionsConfig>::CallbackType // cb = boost::bind(&Upo_navigation_macro_actions::reconfigureCB, this, _1, _2); // dsrv_->setCallback(cb); n.param<double>("secs_to_check_block", secs_to_check_block_, 5.0); // seconds n.param<double>("block_dist", block_dist_, 0.4); // meters // n.param<double>("secs_to_wait", secs_to_wait_, 8.0); //seconds n.param<double>("control_frequency", control_frequency_, 15.0); std::string odom_topic = ""; n.param<std::string>("odom_topic", odom_topic, "odom"); manual_control_ = false; // Dynamic reconfigure // dsrv_ = new // dynamic_reconfigure::Server<upo_navigation_macro_actions::NavigationMacroActionsConfig>(n); // dynamic_reconfigure::Server<upo_navigation_macro_actions::NavigationMacroActionsConfig>::CallbackType // cb = boost::bind(&Upo_navigation_macro_actions::reconfigureCB, this, _1, _2); // dsrv_->setCallback(cb); ros::NodeHandle nh; rrtgoal_sub_ = nh.subscribe<geometry_msgs::PoseStamped>( "/rrt_goal", 1, &Indires_macro_actions::rrtGoalCallback, this); pose_sub_ = nh.subscribe<nav_msgs::Odometry>( odom_topic.c_str(), 1, &Indires_macro_actions::robotPoseCallback, this); // Services for walking side by side // start_client_ = nh.serviceClient<teresa_wsbs::start>("/wsbs/start"); // stop_client_ = nh.serviceClient<teresa_wsbs::stop>("/wsbs/stop"); // wsbs_status_sub_ = nh.subscribe<std_msgs::UInt8>("/wsbs/status", 1, // &Upo_navigation_macro_actions::wsbsCallback, this); moveBaseClient_ = new moveBaseClient("move_base", true); // true-> do not need ros::spin() ROS_INFO("Waiting for action server to start..."); moveBaseClient_->waitForServer(); ROS_INFO("Action server connected!"); // Initialize action servers NWActionServer_ = new NWActionServer( nh1_, "NavigateWaypoint", boost::bind(&Indires_macro_actions::navigateWaypointCB, this, _1), false); NHActionServer_ = new NHActionServer( nh2_, "NavigateHome", boost::bind(&Indires_macro_actions::navigateHomeCB, this, _1), false); ExActionServer_ = new ExActionServer( nh3_, "Exploration", boost::bind(&Indires_macro_actions::explorationCB, this, _1), false); TOActionServer_ = new TOActionServer(nh4_, "Teleoperation", boost::bind(&Indires_macro_actions::teleoperationCB, this, _1), false); NWActionServer_->start(); NHActionServer_->start(); ExActionServer_->start(); TOActionServer_->start(); // ros::NodeHandle nodeh("~/RRT_ros_wrapper"); // nodeh.getParam("full_path_stddev", initial_stddev_); } Indires_macro_actions::~Indires_macro_actions() { if (NWActionServer_) delete NWActionServer_; if (NHActionServer_) delete NHActionServer_; if (ExActionServer_) delete ExActionServer_; if (TOActionServer_) delete TOActionServer_; // if(UpoNav_) // delete UpoNav_; // if(dsrv_) // delete dsrv_; } /* void Upo_navigation_macro_actions::reconfigureCB(upo_navigation_macro_actions::NavigationMacroActionsConfig &config, uint32_t level){ boost::recursive_mutex::scoped_lock l(configuration_mutex_); control_frequency_ = config.control_frequency; secs_to_check_block_ = config.secs_to_check_block; block_dist_ = config.block_dist; secs_to_wait_ = config.secs_to_wait; social_approaching_type_ = config.social_approaching_type; secs_to_yield_ = config.secs_to_yield; //use_leds_ = config.use_leds; //leds_number_ = config.leds_number; }*/ /* //Receive feedback messages from upo_navigation void Upo_navigation_macro_actions::feedbackReceived(const move_base_msgs::MoveBaseActionFeedback::ConstPtr& msg) { pose_mutex_.lock(); robot_pose_ = msg->feedback.base_position; pose_mutex_.unlock(); if((unsigned int)(std::string(robot_pose_.header.frame_id).size()) < 3) robot_pose_.header.frame_id = "map"; } //Receive status messages from upo_navigation void Upo_navigation_macro_actions::statusReceived(const actionlib_msgs::GoalStatusArray::ConstPtr& msg) { unsigned int actions = msg->status_list.size(); if(actions != 0) { status_mutex_.lock(); nav_status_ = msg->status_list.at(0).status; nav_text_ = msg->status_list.at(0).text; goal_id_ = msg->status_list.at(0).goal_id.id; status_mutex_.unlock(); } else { status_mutex_.lock(); nav_status_ = -1; nav_text_ = " "; goal_id_ = " "; status_mutex_.unlock(); } } //This topic publishes only when the action finishes (because of reaching the goal or cancelation) void Upo_navigation_macro_actions::resultReceived(const move_base_msgs::MoveBaseActionResult::ConstPtr& msg) { action_end_ = true; }*/ /* MoveBase server: ----------------- Action Subscribed topics: move_base/goal [move_base_msgs::MoveBaseActionGoal] move_base/cancel [actionlib_msgs::GoalID] Action Published topcis: move_base/feedback [move_base_msgs::MoveBaseActionFeedback] move_base/status [actionlib_msgs::GoalStatusArray] move_base/result [move_base_msgs::MoveBaseAcionResult] */ void Indires_macro_actions::navigateWaypointCB( const indires_macro_actions::NavigateWaypointGoal::ConstPtr& goal) { printf("¡¡¡¡¡¡¡MacroAction navigatetoWaypoint --> started!!!!!!\n"); // printf("Goal x: %.2f, y: %.2f frame: %s\n", goal->target_pose.pose.position.x, // goal->target_pose.pose.position.y, goal->target_pose.header.frame_id.c_str()); // UpoNav_->stopRRTPlanning(); move_base_msgs::MoveBaseGoal g; g.target_pose = goal->target_pose; moveBaseClient_->sendGoal(g); // moveBaseClient_->waitForResult(); actionlib::SimpleClientGoalState state = moveBaseClient_->getState(); // moveBaseClient_->cancelAllGoals() // moveBaseClient_->cancelGoal() // moveBaseClient_->getResult() if (moveBaseClient_->getState() == actionlib::SimpleClientGoalState::SUCCEEDED) { ROS_INFO("Success!!!"); } /*else { ROS_INFO("Failed!"); }*/ /*bool ok = UpoNav_->executeNavigation(goal->target_pose); if(!ok) { ROS_INFO("Setting ABORTED state 1"); nwresult_.result = "Aborted. Navigation error"; nwresult_.value = 2; NWActionServer_->setAborted(nwresult_, "Navigation aborted"); //UpoNav_->stopRRTPlanning(); return; }*/ ros::Rate r(control_frequency_); // int pursue_status = 0; bool exit = false; ros::Time time_init = ros::Time::now(); bool first = true; nav_msgs::Odometry pose_init; // ros::WallTime startt; while (nh1_.ok()) { // startt = ros::WallTime::now(); if (NWActionServer_->isPreemptRequested()) { if (NWActionServer_->isNewGoalAvailable()) { indires_macro_actions::NavigateWaypointGoal new_goal = *NWActionServer_->acceptNewGoal(); g.target_pose = new_goal.target_pose; moveBaseClient_->sendGoal(g); /*bool ok = UpoNav_->executeNavigation(new_goal.target_pose); if(!ok) { ROS_INFO("Setting ABORTED state 1"); nwresult_.result = "Aborted. Navigation error"; nwresult_.value = 2; NWActionServer_->setAborted(nwresult_, "Navigation aborted"); UpoNav_->stopRRTPlanning(); if(use_leds_) setLedColor(WHITE); return; }*/ first = true; } else { // if we've been preempted explicitly we need to shut things down // UpoNav_->resetState(); // Cancel????? // notify the ActionServer that we've successfully preempted nwresult_.result = "Preempted"; nwresult_.value = 1; ROS_DEBUG_NAMED("indires_macro_actions", "indires_navigation preempting the current goal"); NWActionServer_->setPreempted(nwresult_, "Navigation preempted"); // we'll actually return from execute after preempting return; } } pose_mutex_.lock(); nav_msgs::Odometry new_pose = odom_pose_; pose_mutex_.unlock(); // pursue_status = UpoNav_->pathFollow(new_pose); // Posible states: // PENDING, ACTIVE, RECALLED, REJECTED, PREEMPTED, ABORTED, SUCCEEDED, LOST actionlib::SimpleClientGoalState state = moveBaseClient_->getState(); if (first) { pose_init = new_pose; time_init = ros::Time::now(); first = false; } if (state == actionlib::SimpleClientGoalState::SUCCEEDED) { // Goal reached ROS_INFO("Setting SUCCEEDED state"); nwresult_.result = "Navigation succeeded"; nwresult_.value = 0; NWActionServer_->setSucceeded(nwresult_, "Goal Reached"); nwfeedback_.text = "Succeeded"; exit = true; } else if (state == actionlib::SimpleClientGoalState::ACTIVE) { // Goal not reached, continue navigating nwfeedback_.text = "Navigating"; } else if (state == actionlib::SimpleClientGoalState::ABORTED) { // Aborted nwfeedback_.text = "Aborted"; ROS_INFO("Setting ABORTED state"); nwresult_.result = "Aborted"; nwresult_.value = 3; NWActionServer_->setAborted(nwresult_, "Navigation aborted"); exit = true; } else if (state == actionlib::SimpleClientGoalState::PENDING) { nwfeedback_.text = "Pending"; // ROS_INFO("Setting ABORTED state"); // nwresult_.result = ""; // nwresult_.value = 3; // NWActionServer_->setAborted(nwresult_, "Navigation aborted"); // exit = true; } else if (state == actionlib::SimpleClientGoalState::RECALLED) { nwfeedback_.text = "Recalled"; } else if (state == actionlib::SimpleClientGoalState::REJECTED) { // Rejected nwfeedback_.text = "Rejected"; ROS_INFO("Setting ABORTED (rejected) state"); nwresult_.result = "Rejected"; nwresult_.value = 3; NWActionServer_->setAborted(nwresult_, "Navigation aborted(rejected)"); exit = true; } else if (state == actionlib::SimpleClientGoalState::LOST) { // Rejected nwfeedback_.text = "Lost"; ROS_INFO("Setting ABORTED (lost) state"); nwresult_.result = "Lost"; nwresult_.value = 3; NWActionServer_->setAborted(nwresult_, "Navigation aborted(lost)"); exit = true; } else if (state == actionlib::SimpleClientGoalState::PREEMPTED) { nwfeedback_.text = "Preempted"; } // push the feedback out geometry_msgs::PoseStamped aux; aux.header = new_pose.header; aux.pose.position = new_pose.pose.pose.position; aux.pose.orientation = new_pose.pose.pose.orientation; nwfeedback_.base_position = aux; NWActionServer_->publishFeedback(nwfeedback_); if (exit) { // UpoNav_->stopRRTPlanning(); return; } // check the blocked situation. double time = (ros::Time::now() - time_init).toSec(); // printf("now: %.2f, init: %.2f, time: %.2f secs\n", ros::Time::now().toSec(), // time_init.toSec(), time); if (time > secs_to_check_block_) { double xinit = pose_init.pose.pose.position.x; double yinit = pose_init.pose.pose.position.y; double hinit = tf::getYaw(pose_init.pose.pose.orientation); double xnow = new_pose.pose.pose.position.x; double ynow = new_pose.pose.pose.position.y; double hnow = tf::getYaw(new_pose.pose.pose.orientation); double dist = sqrt(pow((xinit - xnow), 2) + pow((yinit - ynow), 2)); double yaw_diff = fabs(angles::shortest_angular_distance(hnow, hinit)); // printf("dist: %.2f, yaw_diff: %.2f\n", dist, yaw_diff); if (dist <= block_dist_ && yaw_diff < 0.79) { // 0.79 = 45º ROS_INFO("Setting ABORTED state because of blocked situation"); nwresult_.result = "Aborted. Blocked situation"; nwresult_.value = 5; NWActionServer_->setAborted(nwresult_, "Navigation aborted. blocked"); nwfeedback_.text = "Blocked"; NWActionServer_->publishFeedback(nwfeedback_); // UpoNav_->stopRRTPlanning(); return; } else { pose_init = new_pose; time_init = ros::Time::now(); } } // ros::WallDuration dur = ros::WallTime::now() - startt; // printf("Loop time: %.4f secs\n", dur.toSec()); r.sleep(); } ROS_INFO("Setting ABORTED state"); nwresult_.result = "Aborted. System is shuting down"; nwresult_.value = 6; NWActionServer_->setAborted(nwresult_, "Navigation aborted because the node has been killed"); } void Indires_macro_actions::navigateHomeCB(const indires_macro_actions::NavigateHomeGoal::ConstPtr& goal) { printf("¡¡¡¡¡¡¡MacroAction NavigateHome --> started!!!!!!\n"); // printf("Goal x: %.2f, y: %.2f frame: %s\n", goal->home_pose.pose.position.x, // goal->home_pose.pose.position.y, goal->home_pose.header.frame_id.c_str()); // UpoNav_->stopRRTPlanning(); // boost::recursive_mutex::scoped_lock l(configuration_mutex_); // Put the goal to map origin??? move_base_msgs::MoveBaseGoal g; g.target_pose = goal->home_pose; moveBaseClient_->sendGoal(g); ros::Rate r(control_frequency_); // int pursue_status = 0; bool exit = false; ros::Time time_init = ros::Time::now(); bool first = true; nav_msgs::Odometry pose_init; while (nh2_.ok()) { // startt = ros::WallTime::now(); if (NHActionServer_->isPreemptRequested()) { if (NHActionServer_->isNewGoalAvailable()) { indires_macro_actions::NavigateHomeGoal new_goal = *NHActionServer_->acceptNewGoal(); g.target_pose = new_goal.home_pose; moveBaseClient_->sendGoal(g); first = true; } else { // if we've been preempted explicitly we need to shut things down // UpoNav_->resetState(); // notify the ActionServer that we've successfully preempted ROS_DEBUG_NAMED("indires_macro_actions", "indires_navigation preempting the current goal"); nhresult_.result = "Preempted"; nhresult_.value = 1; NHActionServer_->setPreempted(nhresult_, "Navigation preempted"); // we'll actually return from execute after preempting return; } } pose_mutex_.lock(); nav_msgs::Odometry new_pose = odom_pose_; pose_mutex_.unlock(); // pursue_status = UpoNav_->pathFollow(new_pose); // Posible states: // PENDING, ACTIVE, RECALLED, REJECTED, PREEMPTED, ABORTED, SUCCEEDED, LOST actionlib::SimpleClientGoalState state = moveBaseClient_->getState(); if (first) { pose_init = new_pose; time_init = ros::Time::now(); first = false; } if (state == actionlib::SimpleClientGoalState::SUCCEEDED) { // Goal reached ROS_INFO("Setting SUCCEEDED state"); nhresult_.result = "Navigation succeeded"; nhresult_.value = 0; NHActionServer_->setSucceeded(nhresult_, "Goal Reached"); nhfeedback_.text = "Succeeded"; exit = true; } else if (state == actionlib::SimpleClientGoalState::ACTIVE) { // Goal not reached, continue navigating nhfeedback_.text = "Navigating"; } else if (state == actionlib::SimpleClientGoalState::ABORTED) { // Aborted nhfeedback_.text = "Aborted"; ROS_INFO("Setting ABORTED state"); nhresult_.result = "Aborted"; nhresult_.value = 3; NHActionServer_->setAborted(nhresult_, "Navigation aborted"); exit = true; } else if (state == actionlib::SimpleClientGoalState::PENDING) { nhfeedback_.text = "Pending"; // ROS_INFO("Setting ABORTED state"); // nwresult_.result = ""; // nwresult_.value = 3; // NWActionServer_->setAborted(nwresult_, "Navigation aborted"); // exit = true; } else if (state == actionlib::SimpleClientGoalState::RECALLED) { nhfeedback_.text = "Recalled"; } else if (state == actionlib::SimpleClientGoalState::REJECTED) { // Rejected nhfeedback_.text = "Rejected"; ROS_INFO("Setting ABORTED (rejected) state"); nhresult_.result = "Rejected"; nhresult_.value = 3; NHActionServer_->setAborted(nhresult_, "Navigation aborted(rejected)"); exit = true; } else if (state == actionlib::SimpleClientGoalState::LOST) { // Rejected nhfeedback_.text = "Lost"; ROS_INFO("Setting ABORTED (lost) state"); nhresult_.result = "Lost"; nhresult_.value = 3; NHActionServer_->setAborted(nhresult_, "Navigation aborted(lost)"); exit = true; } else if (state == actionlib::SimpleClientGoalState::PREEMPTED) { nhfeedback_.text = "Preempted"; } // push the feedback out geometry_msgs::PoseStamped aux; aux.header = new_pose.header; aux.pose.position = new_pose.pose.pose.position; aux.pose.orientation = new_pose.pose.pose.orientation; nhfeedback_.base_position = aux; NHActionServer_->publishFeedback(nhfeedback_); if (exit) { // UpoNav_->stopRRTPlanning(); return; } // check the blocked situation. double time = (ros::Time::now() - time_init).toSec(); // printf("now: %.2f, init: %.2f, time: %.2f secs\n", ros::Time::now().toSec(), // time_init.toSec(), time); if (time > secs_to_check_block_) { double xinit = pose_init.pose.pose.position.x; double yinit = pose_init.pose.pose.position.y; double hinit = tf::getYaw(pose_init.pose.pose.orientation); double xnow = new_pose.pose.pose.position.x; double ynow = new_pose.pose.pose.position.y; double hnow = tf::getYaw(new_pose.pose.pose.orientation); double dist = sqrt(pow((xinit - xnow), 2) + pow((yinit - ynow), 2)); double yaw_diff = fabs(angles::shortest_angular_distance(hnow, hinit)); // printf("dist: %.2f, yaw_diff: %.2f\n", dist, yaw_diff); if (dist <= block_dist_ && yaw_diff < 0.79) { // 0.79 = 45º ROS_INFO("Setting ABORTED state because of blocked situation"); nhresult_.result = "Aborted. Blocked situation"; nhresult_.value = 5; NHActionServer_->setAborted(nhresult_, "Navigation aborted. blocked"); nhfeedback_.text = "Blocked"; NHActionServer_->publishFeedback(nhfeedback_); // UpoNav_->stopRRTPlanning(); return; } else { pose_init = new_pose; time_init = ros::Time::now(); } } // ros::WallDuration dur = ros::WallTime::now() - startt; // printf("Loop time: %.4f secs\n", dur.toSec()); r.sleep(); } ROS_INFO("Setting ABORTED state"); nhresult_.result = "Aborted. system is shuting down"; nhresult_.value = 6; NHActionServer_->setAborted(nhresult_, "Navigation aborted because the node has been killed"); } void Indires_macro_actions::explorationCB(const indires_macro_actions::ExplorationGoal::ConstPtr& goal) { printf("¡¡¡¡¡¡¡MacroAction Exploration --> started!!!!!!\n"); // printf("Goal x: %.2f, y: %.2f frame: %s\n", goal->target_pose.pose.position.x, // goal->target_pose.pose.position.y, goal->target_pose.header.frame_id.c_str()); // UpoNav_->stopRRTPlanning(); move_base_msgs::MoveBaseGoal g; g.target_pose = goal->empty; g.target_pose.header.frame_id = ""; g.target_pose.pose.orientation.x = 0.0; g.target_pose.pose.orientation.y = 0.0; g.target_pose.pose.orientation.z = 0.0; g.target_pose.pose.orientation.w = 1.0; moveBaseClient_->sendGoal(g); // moveBaseClient_->waitForResult(); actionlib::SimpleClientGoalState state = moveBaseClient_->getState(); // moveBaseClient_->cancelAllGoals() // moveBaseClient_->cancelGoal() // moveBaseClient_->getResult() if (moveBaseClient_->getState() == actionlib::SimpleClientGoalState::SUCCEEDED) { ROS_INFO("Success!!!"); } /*else { ROS_INFO("Failed!"); }*/ /*bool ok = UpoNav_->executeNavigation(goal->target_pose); if(!ok) { ROS_INFO("Setting ABORTED state 1"); nwresult_.result = "Aborted. Navigation error"; nwresult_.value = 2; NWActionServer_->setAborted(nwresult_, "Navigation aborted"); //UpoNav_->stopRRTPlanning(); return; }*/ ros::Rate r(control_frequency_); // int pursue_status = 0; bool exit = false; ros::Time time_init = ros::Time::now(); bool first = true; nav_msgs::Odometry pose_init; // ros::WallTime startt; while (nh3_.ok()) { // startt = ros::WallTime::now(); if (ExActionServer_->isPreemptRequested()) { if (ExActionServer_->isNewGoalAvailable()) { indires_macro_actions::ExplorationGoal new_goal = *ExActionServer_->acceptNewGoal(); g.target_pose = new_goal.empty; moveBaseClient_->sendGoal(g); /*bool ok = UpoNav_->executeNavigation(new_goal.target_pose); if(!ok) { ROS_INFO("Setting ABORTED state 1"); nwresult_.result = "Aborted. Navigation error"; nwresult_.value = 2; NWActionServer_->setAborted(nwresult_, "Navigation aborted"); UpoNav_->stopRRTPlanning(); if(use_leds_) setLedColor(WHITE); return; }*/ first = true; } else { // if we've been preempted explicitly we need to shut things down // UpoNav_->resetState(); // Cancel????? // notify the ActionServer that we've successfully preempted exresult_.result = "Preempted"; exresult_.value = 1; ROS_DEBUG_NAMED("indires_macro_actions", "indires_exploration preempting the current goal"); ExActionServer_->setPreempted(exresult_, "Exploration preempted"); // we'll actually return from execute after preempting return; } } pose_mutex_.lock(); nav_msgs::Odometry new_pose = odom_pose_; pose_mutex_.unlock(); // pursue_status = UpoNav_->pathFollow(new_pose); // Posible states: // PENDING, ACTIVE, RECALLED, REJECTED, PREEMPTED, ABORTED, SUCCEEDED, LOST state = moveBaseClient_->getState(); if (first) { pose_init = new_pose; time_init = ros::Time::now(); first = false; } if (state == actionlib::SimpleClientGoalState::SUCCEEDED) { // Goal reached // WE MUST TO CONTINUE THE EXPLORATION ROS_INFO("Goal reached. Exploration continues..."); // exresult_.result = "Exploration succeeded"; // exresult_.value = 0; // ExActionServer_->setSucceeded(exresult_, "Goal Reached"); // exfeedback_.text = "Succeeded"; // exit = true; exfeedback_.text = "goal reached. Exploration continues"; moveBaseClient_->sendGoal(g); } else if (state == actionlib::SimpleClientGoalState::ACTIVE) { // Goal not reached, continue navigating exfeedback_.text = "Navigating"; } else if (state == actionlib::SimpleClientGoalState::ABORTED) { // Aborted exfeedback_.text = "Aborted"; ROS_INFO("Setting ABORTED state"); exresult_.result = "Aborted"; exresult_.value = 3; ExActionServer_->setAborted(exresult_, "Exploration aborted"); exit = true; } else if (state == actionlib::SimpleClientGoalState::PENDING) { exfeedback_.text = "Pending"; // ROS_INFO("Setting ABORTED state"); // nwresult_.result = ""; // nwresult_.value = 3; // NWActionServer_->setAborted(nwresult_, "Navigation aborted"); // exit = true; } else if (state == actionlib::SimpleClientGoalState::RECALLED) { exfeedback_.text = "Recalled"; } else if (state == actionlib::SimpleClientGoalState::REJECTED) { // Rejected exfeedback_.text = "Rejected"; ROS_INFO("Setting ABORTED (rejected) state"); exresult_.result = "Rejected"; exresult_.value = 3; ExActionServer_->setAborted(exresult_, "Exploration aborted(rejected)"); exit = true; } else if (state == actionlib::SimpleClientGoalState::LOST) { // Rejected exfeedback_.text = "Lost"; ROS_INFO("Setting ABORTED (lost) state"); exresult_.result = "Lost"; exresult_.value = 3; ExActionServer_->setAborted(exresult_, "Exploration aborted(lost)"); exit = true; } else if (state == actionlib::SimpleClientGoalState::PREEMPTED) { nwfeedback_.text = "Preempted"; } // push the feedback out geometry_msgs::PoseStamped aux; aux.header = new_pose.header; aux.pose.position = new_pose.pose.pose.position; aux.pose.orientation = new_pose.pose.pose.orientation; exfeedback_.base_position = aux; ExActionServer_->publishFeedback(exfeedback_); if (exit) { // UpoNav_->stopRRTPlanning(); return; } // check the blocked situation. double time = (ros::Time::now() - time_init).toSec(); // printf("now: %.2f, init: %.2f, time: %.2f secs\n", ros::Time::now().toSec(), // time_init.toSec(), time); if (time > secs_to_check_block_) { double xinit = pose_init.pose.pose.position.x; double yinit = pose_init.pose.pose.position.y; double hinit = tf::getYaw(pose_init.pose.pose.orientation); double xnow = new_pose.pose.pose.position.x; double ynow = new_pose.pose.pose.position.y; double hnow = tf::getYaw(new_pose.pose.pose.orientation); double dist = sqrt(pow((xinit - xnow), 2) + pow((yinit - ynow), 2)); double yaw_diff = fabs(angles::shortest_angular_distance(hnow, hinit)); // printf("dist: %.2f, yaw_diff: %.2f\n", dist, yaw_diff); if (dist <= block_dist_ && yaw_diff < 0.79) { // 0.79 = 45º ROS_INFO("Setting ABORTED state because of blocked situation"); exresult_.result = "Aborted. Blocked situation"; exresult_.value = 5; ExActionServer_->setAborted(exresult_, "Exploration aborted. blocked"); exfeedback_.text = "Blocked"; ExActionServer_->publishFeedback(exfeedback_); // UpoNav_->stopRRTPlanning(); return; } else { pose_init = new_pose; time_init = ros::Time::now(); } } // ros::WallDuration dur = ros::WallTime::now() - startt; // printf("Loop time: %.4f secs\n", dur.toSec()); r.sleep(); } ROS_INFO("Setting ABORTED state"); exresult_.result = "Aborted. System is shuting down"; exresult_.value = 6; ExActionServer_->setAborted(exresult_, "Exploration aborted because the node has been killed"); } /* bool Indires_macro_actions::reconfigureParameters(std::string node, std::string param_name, std::string value, const datatype type) { //printf("RECONFIGURE PARAMETERS METHOD\n"); dynamic_reconfigure::ReconfigureRequest srv_req; dynamic_reconfigure::ReconfigureResponse srv_resp; dynamic_reconfigure::IntParameter param1; dynamic_reconfigure::BoolParameter param2; dynamic_reconfigure::DoubleParameter param3; dynamic_reconfigure::StrParameter param4; dynamic_reconfigure::Config conf; switch(type) { case INT_TYPE: param1.name = param_name.c_str(); param1.value = stoi(value); conf.ints.push_back(param1); break; case DOUBLE_TYPE: param3.name = param_name.c_str(); //printf("type double. Value: %s\n", param3.name.c_str()); param3.value = stod(value); //printf("conversion to double: %.3f\n", param3.value); conf.doubles.push_back(param3); break; case BOOL_TYPE: param2.name = param_name.c_str(); param2.value = stoi(value); conf.bools.push_back(param2); break; case STRING_TYPE: param4.name = param_name.c_str(); param4.value = value; conf.strs.push_back(param4); break; default: ROS_ERROR("indires_macro_actions. ReconfigureParameters. datatype not valid!"); } srv_req.config = conf; std::string service = node + "/set_parameters"; if (!ros::service::call(service, srv_req, srv_resp)) { ROS_ERROR("Could not call the service %s reconfigure the param %s to %s", service.c_str(), param_name.c_str(), value.c_str()); return false; } return true; } */ void Indires_macro_actions::teleoperationCB(const indires_macro_actions::TeleoperationGoal::ConstPtr& goal) { if (!manual_control_) { printf("¡¡¡¡¡¡¡MacroAction AssistedSteering --> started!!!!!!\n"); manual_control_ = true; moveBaseClient_->cancelAllGoals(); // UpoNav_->stopRRTPlanning(); // stop the current wsbs if it is running // teresa_wsbs::stop stop_srv; // stop_client_.call(stop_srv); } ros::Time time_init; time_init = ros::Time::now(); bool exit = false; // boost::recursive_mutex::scoped_lock l(configuration_mutex_); ros::Rate r(30.0); while (nh4_.ok()) { if (TOActionServer_->isPreemptRequested()) { if (TOActionServer_->isNewGoalAvailable()) { // if we're active and a new goal is available, we'll accept it, but we won't shut // anything down // ROS_INFO("Accepting new goal"); indires_macro_actions::TeleoperationGoal new_goal = *TOActionServer_->acceptNewGoal(); time_init = ros::Time::now(); } else { TOActionServer_->setPreempted(toresult_, "Teleoperation preempted"); return; } } tofeedback_.text = "Robot manually controlled"; // Check the time without receiving commands from the interface double time = (ros::Time::now() - time_init).toSec(); if (time > 5.0) { tofeedback_.text = "Teleoperation finished"; toresult_.result = "Teleoperation Succeeded"; toresult_.value = 0; TOActionServer_->setSucceeded(toresult_, "Teleoperation succeeded"); exit = true; } TOActionServer_->publishFeedback(tofeedback_); if (exit) { manual_control_ = false; return; } r.sleep(); } manual_control_ = false; ROS_INFO("Setting ABORTED state"); TOActionServer_->setAborted(toresult_, "Teleoperation aborted because the node has been killed"); } // void Upo_navigation_macro_actions::poseCallback(const // geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msg) void Indires_macro_actions::robotPoseCallback(const nav_msgs::Odometry::ConstPtr& msg) { pose_mutex_.lock(); odom_pose_ = *msg; // robot_global_pose_.y = msg->pose.pose.position.y; // robot_global_pose_.theta = tf::getYaw(msg->pose.pose.orientation); pose_mutex_.unlock(); } void Indires_macro_actions::rrtGoalCallback(const geometry_msgs::PoseStamped::ConstPtr& msg) { /*geometry_msgs::PoseStamped out; out = transformPoseTo(*msg, "map"); geometry_msgs::Pose2D p; p.x = out.pose.position.x; p.y = out.pose.position.y; p.theta = 0.0; */ goal_mutex_.lock(); rrtgoal_ = *msg; goal_mutex_.unlock(); } geometry_msgs::PoseStamped Indires_macro_actions::transformPoseTo(geometry_msgs::PoseStamped pose_in, std::string frame_out) { geometry_msgs::PoseStamped in = pose_in; in.header.stamp = ros::Time(); geometry_msgs::PoseStamped pose_out; try { pose_out = tf_->transform(in, frame_out.c_str()); } catch (tf2::TransformException ex) { ROS_WARN("Macro-Action class. TransformException in method transformPoseTo: %s", ex.what()); pose_out.header = in.header; pose_out.header.stamp = ros::Time::now(); pose_out.pose.position.x = 0.0; pose_out.pose.position.y = 0.0; pose_out.pose.position.z = 0.0; pose_out.pose.orientation = tf::createQuaternionMsgFromYaw(0.0); } return pose_out; } // This method removes the initial slash from the frame names // in order to compare the string names easily void Indires_macro_actions::fixFrame(std::string& cad) { if (cad[0] == '/') { cad.erase(0, 1); } } float Indires_macro_actions::normalizeAngle(float val, float min, float max) { float norm = 0.0; if (val >= min) norm = min + fmod((val - min), (max - min)); else norm = max - fmod((min - val), (max - min)); return norm; } <|start_filename|>local_3d_planner/src/odometry_helper_ros.cpp<|end_filename|> /********************************************************************* * * Based on the odometry_helper_ros.cpp of the base_local_planner of ROS. * Modified by: <NAME> *********************************************************************/ #include <local_3d_planner/odometry_helper_ros.h> namespace local_3d_planner { OdometryHelperRos::OdometryHelperRos(std::string odom_topic) { setOdomTopic(odom_topic); } void OdometryHelperRos::odomCallback(const nav_msgs::Odometry::ConstPtr& msg) { ROS_INFO_ONCE("odom received!"); // we assume that the odometry is published in the frame of the base // boost::mutex::scoped_lock lock(odom_mutex_); // std::mutex::scoped_lock lock(odom_mutex_); odom_mutex_.lock(); base_odom_.header = msg->header; base_odom_.child_frame_id = msg->child_frame_id; base_odom_.pose = msg->pose; base_odom_.twist.twist.linear.x = msg->twist.twist.linear.x; base_odom_.twist.twist.linear.y = msg->twist.twist.linear.y; base_odom_.twist.twist.angular.z = msg->twist.twist.angular.z; base_odom_.child_frame_id = msg->child_frame_id; // ROS_DEBUG_NAMED("dwa_local_planner", "In the odometry callback with velocity values: // (%.2f, %.2f, %.2f)", // base_odom_.twist.twist.linear.x, base_odom_.twist.twist.linear.y, // base_odom_.twist.twist.angular.z); odom_mutex_.unlock(); } // copy over the odometry information void OdometryHelperRos::getOdom(nav_msgs::Odometry& base_odom) { // boost::mutex::scoped_lock lock(odom_mutex_); // std::mutex::scoped_lock lock(odom_mutex_); odom_mutex_.lock(); base_odom = base_odom_; odom_mutex_.unlock(); } void OdometryHelperRos::getRobotVel(geometry_msgs::PoseStamped& robot_vel) { // Set current velocities from odometry geometry_msgs::Twist global_vel; { // boost::mutex::scoped_lock lock(odom_mutex_); // std::mutex::scoped_lock lock(odom_mutex_); odom_mutex_.lock(); global_vel.linear.x = base_odom_.twist.twist.linear.x; global_vel.linear.y = base_odom_.twist.twist.linear.y; global_vel.angular.z = base_odom_.twist.twist.angular.z; robot_vel.header.frame_id = base_odom_.child_frame_id; odom_mutex_.unlock(); } robot_vel.pose.position.x = global_vel.linear.x; robot_vel.pose.position.y = global_vel.linear.y; robot_vel.pose.position.z = 0; robot_vel.pose.orientation = tf::createQuaternionMsgFromYaw(global_vel.angular.z); robot_vel.header.stamp = ros::Time(); //robot_vel.stamp_ = ros::Time(); } void OdometryHelperRos::setOdomTopic(std::string odom_topic) { if (odom_topic != odom_topic_) { odom_topic_ = odom_topic; if (odom_topic_ != "") { ros::NodeHandle gn; odom_sub_ = gn.subscribe<nav_msgs::Odometry>( odom_topic_, 1, boost::bind(&OdometryHelperRos::odomCallback, this, _1)); } else { odom_sub_.shutdown(); } } } } /* namespace local_3d_planner */ <|start_filename|>local_3d_planner/src/collision_detection.cpp<|end_filename|> #include <local_3d_planner/collision_detection.h> namespace local_3d_planner { CollisionDetection::CollisionDetection(std::string name, tf2_ros::Buffer* tf, local_3d_planner::OdometryHelperRos* oh, double max_lv, double max_av, double lin_acc, double ang_acc, double sim_t, double r_radius, double local_radius, double granularity) { tf_ = tf; odom_helper_ = NULL; if (oh) odom_helper_ = oh; max_lin_vel_ = max_lv; max_ang_vel_ = max_av; max_lin_acc_ = lin_acc; max_ang_acc_ = ang_acc; sim_time_ = sim_t; robot_radius_ = r_radius; robot_radius_aug_ = robot_radius_; local_radius_ = local_radius; granularity_ = granularity; use_laser_ = false; use_range_ = false; num_ranges_ = 0; ranges_ready_ = false; setup(name); } CollisionDetection::~CollisionDetection() { // delete odom_helper_; } void CollisionDetection::setup(std::string name) { // ros::NodeHandle n("~"); ros::NodeHandle n("~/" + name); n.param<std::string>("odometry_topic", odom_topic_, std::string("odom")); n.param<std::string>("base_frame", base_frame_, std::string("base_link")); std::string features_name; n.param<std::string>("features_name", features_name, std::string("nav_features_3d")); // printf("CollisionDetection. Features_name: %s\n", features_name.c_str()); double uncertainty = 0.0; n.getParam("sensor_uncertainty", uncertainty); robot_radius_aug_ = robot_radius_ + uncertainty; n.getParam("use_laser", use_laser_); std::string laser_topic; ros::NodeHandle nh; if (use_laser_) { n.param<std::string>("laser_topic", laser_topic, std::string("scan")); laser_sub_ = nh.subscribe<sensor_msgs::LaserScan>( laser_topic.c_str(), 1, &CollisionDetection::laserCallback, this); } unsigned int i = 0; n.param<bool>("use_range", use_range_, false); if (use_range_) { bool ok = true; while (ok) { char buf[25]; sprintf(buf, "range_topic_%u", i); string st = string(buf); if (n.hasParam(st.c_str())) { std::string rt; n.getParam(st.c_str(), rt); range_topics_.push_back(rt); // ros::Subscriber sub = nh.subscribe<sensor_msgs::Range>(rt.c_str(), 10, // &CollisionDetection::rangeCallback, this); ros::Subscriber sub = nh.subscribe<sensor_msgs::Range>( rt.c_str(), 1, boost::bind(&CollisionDetection::rangeCallback, this, _1)); range_subscribers_.push_back(sub); printf("%s. subscribed to topic: %s\n", name.c_str(), rt.c_str()); i++; } else ok = false; } num_ranges_ = (int)i; ranges_initiated_.assign(num_ranges_, false); // range_frames_.assign(num_ranges_, ""); } max_lv_var_ = max_lin_acc_ * sim_time_; max_av_var_ = max_ang_acc_ * sim_time_; features_ = new nav3d::Features3D(features_name, tf_, local_radius_, local_radius_, local_radius_); if (odom_helper_ == NULL) odom_helper_ = new OdometryHelperRos(odom_topic_); // Dynamic reconfigure // dsrv_ = new // dynamic_reconfigure::Server<assisted_steering::AssistedSteeringConfig>(n); // //ros::NodeHandle("~") // dynamic_reconfigure::Server<assisted_steering::AssistedSteeringConfig>::CallbackType // cb = boost::bind(&AssistedSteering::reconfigureCB, this, _1, _2); // dsrv_->setCallback(cb); } /*void CollisionDetection::reconfigureCB(assisted_steering::AssistedSteeringConfig &config, uint32_t level){ boost::recursive_mutex::scoped_lock l(configuration_mutex_); max_lin_vel_ = config.max_lin_vel; max_ang_vel_ = config.max_ang_vel; max_lin_acc_ = config.max_lin_acc; max_ang_acc_ = config.max_ang_acc; time_step_ = config.time_step; robot_radius_ = config.robot_radius; granularity_ = config.granularity; isActive_ = config.is_active; ang_vel_inc_ = config.ang_vel_inc; lin_vel_inc_ = config.lin_vel_inc; max_lv_var_ = max_lin_acc_ * time_step_; max_av_var_ = max_ang_acc_ * time_step_; }*/ void CollisionDetection::laserCallback(const sensor_msgs::LaserScan::ConstPtr& msg) { ROS_INFO_ONCE("Collision detector: Laser received!"); // IMPORTANT: the frame of the laser should be the center of the robot (base_link) // Otherwise we should include a shift to the center in the calculations. laser_mutex_.lock(); laser_scan_ = *msg; // scan1_time_ = ros::Time::now(); laser_mutex_.unlock(); } void CollisionDetection::rangeCallback(const sensor_msgs::Range::ConstPtr& msg) { ROS_INFO_ONCE("Collision detector: range received! Detecting configuration..."); if (!ranges_ready_) { if (range_frames_.size() != (unsigned int)num_ranges_) { bool found = false; for (unsigned int i = 0; i < range_frames_.size(); i++) { if (range_frames_[i].compare(msg->header.frame_id) == 0) { found = true; break; } } if (!found) { range_frames_.push_back(msg->header.frame_id); range r; r.range = msg->range; r.id = msg->header.frame_id; r.min_dist = msg->min_range; r.max_dist = msg->max_range; r.fov = msg->field_of_view; // listen to the TF to know the position of the sonar range // tf::StampedTransform transform; geometry_msgs::TransformStamped ts; try { // tf_->waitForTransform(base_frame_.c_str(), r.id.c_str(), ros::Time(0), // ros::Duration(3.0)); // tf_->lookupTransform(base_frame_.c_str(), r.id.c_str(), ros::Time(0), // transform); ts = tf_->lookupTransform(base_frame_.c_str(), r.id.c_str(), ros::Time(0)); } catch (tf2::TransformException& ex) { ROS_ERROR("%s", ex.what()); } float x = ts.transform.translation.x; float y = ts.transform.translation.y; r.polar_dist = sqrt(x * x + y * y); // tf::Matrix3x3 m(ts.transform.rotation); // double roll, pitch, yaw; // m.getRPY(roll, pitch, yaw); r.polar_angle = tf::getYaw(ts.transform.rotation); range_mutex_.lock(); ranges_.push_back(r); range_mutex_.unlock(); printf("Collision detector: Range %s configured.\n", msg->header.frame_id.c_str()); } } else { ranges_ready_ = true; printf("Collision detector: all the range sensors configured!!!\n\n"); } } else { range_mutex_.lock(); for (int i = 0; i < (int)ranges_.size(); i++) { if (ranges_[i].id.compare(msg->header.frame_id) == 0) { ranges_[i].range = msg->range; break; } } range_mutex_.unlock(); } } void CollisionDetection::saturateVelocities(geometry_msgs::Twist* twist) { float lv = twist->linear.x; float av = twist->angular.z; float rvx = robot_vel_.getOrigin().getX(); float rvy = robot_vel_.getOrigin().getY(); float rvt = tf::getYaw(robot_vel_.getRotation()); // acc linear if (fabs(rvx - lv) > max_lv_var_) { lv = (lv < rvx) ? (rvx - max_lv_var_) : (rvx + max_lv_var_); } // acc angular if (fabs(rvt - av) > max_av_var_) { av = (av < rvt) ? (rvt - max_av_var_) : (rvt + max_av_var_); } // Check maximum velocities if (lv > max_lin_vel_) lv = max_lin_vel_; else if (lv < (-max_lin_vel_)) lv = max_lin_vel_ * (-1); if (av > max_ang_vel_) av = max_ang_vel_; else if (av < (-max_ang_vel_)) av = max_ang_vel_ * (-1); twist->linear.x = lv; twist->angular.z = av; } bool CollisionDetection::inCollision(float x, float y, std::vector<geometry_msgs::Point>* scanpoints) { if (use_range_ && inRangeCollision(x, y)) { printf("Possible collision detected!"); return true; } if (use_laser_ && inLaserCollision(x, y, scanpoints)) { return true; } return false; } bool CollisionDetection::inRangeCollision(float x, float y) { range_mutex_.lock(); for (unsigned int i = 0; i < ranges_.size(); i++) { // Main point float rx = (ranges_[i].polar_dist + ranges_[i].range) * cos(ranges_[i].polar_angle); float ry = (ranges_[i].polar_dist + ranges_[i].range) * sin(ranges_[i].polar_angle); float dx = (x - rx); float dy = (y - ry); float dist = dx * dx + dy * dy; if (dist <= (robot_radius_aug_ * robot_radius_aug_)) { ROS_INFO("POSSIBLE COLLISION DETECTED IN FRAME: %s", ranges_[i].id.c_str()); range_mutex_.unlock(); return true; } if (ranges_[i].fov > 0.2) { // second point rx = (ranges_[i].polar_dist + ranges_[i].range) * cos(ranges_[i].polar_angle + (ranges_[i].fov / 2.0)); ry = (ranges_[i].polar_dist + ranges_[i].range) * sin(ranges_[i].polar_angle + (ranges_[i].fov / 2.0)); dx = (x - rx); dy = (y - ry); dist = dx * dx + dy * dy; if (dist <= (robot_radius_aug_ * robot_radius_aug_)) { ROS_INFO("POSSIBLE COLLISION DETECTED (p2) IN FRAME: %s", ranges_[i].id.c_str()); range_mutex_.unlock(); return true; } // third point rx = (ranges_[i].polar_dist + ranges_[i].range) * cos(ranges_[i].polar_angle - (ranges_[i].fov / 2.0)); ry = (ranges_[i].polar_dist + ranges_[i].range) * sin(ranges_[i].polar_angle - (ranges_[i].fov / 2.0)); dx = (x - rx); dy = (y - ry); dist = dx * dx + dy * dy; if (dist <= (robot_radius_aug_ * robot_radius_aug_)) { ROS_INFO("POSSIBLE COLLISION DETECTED (p3) IN FRAME: %s", ranges_[i].id.c_str()); range_mutex_.unlock(); return true; } } } range_mutex_.unlock(); return false; } std::vector<geometry_msgs::Point> CollisionDetection::laser_polar2euclidean(sensor_msgs::LaserScan* scan) { std::vector<geometry_msgs::Point> points; points.reserve(scan->ranges.size()); geometry_msgs::Point p; p.z = 0.0; for (unsigned int i = 0; i < scan->ranges.size(); i++) { // laser measure polar coordinates float laser_d = scan->ranges[i]; float laser_th = scan->angle_min + scan->angle_increment * i; // transform to x,y p.x = laser_d * cos(laser_th); p.y = laser_d * sin(laser_th); points.push_back(p); } return points; } bool CollisionDetection::inLaserCollision(float x, float y, std::vector<geometry_msgs::Point>* scanpoints) { for (unsigned int i = 0; i < scanpoints->size(); i++) { float dx = (x - scanpoints->at(i).x); float dy = (y - scanpoints->at(i).y); // float dist = sqrt(dx*dx + dy*dy); // if(dist <= robot_radius_) float dist = dx * dx + dy * dy; if (dist <= (robot_radius_aug_ * robot_radius_aug_)) return true; } return false; } /** * @brief Generate and check a single trajectory * @param cvx The current x velocity of the robot * @param cvy The current y velocity of the robot * @param cvth The current angular velocity of the robot * @param tvx The x velocity used to seed the trajectory * @param tvy The y velocity used to seed the trajectory * @param tvth The theta velocity used to seed the trajectory * @param px will be filled with the final x point of the trajectory (robot frame) * @param py will be filled with the final y point of the trajectory (robot frame) * @param pz will be filled with the final z point of the trajectory (robot frame) * @param pth will be filled with the final th point of the trajectory (robot frame) * @return True if the trajectory is legal, false otherwise */ bool CollisionDetection::checkTraj(double cvx, double cvy, double cvth, double tvx, double tvy, double tvth, double& px, double& py, double& pz, double& pth) { // boost::recursive_mutex::scoped_lock l(configuration_mutex_); px = 0.0; py = 0.0; pz = 0.0; pth = 0.0; // printf("\nCollisionDetection. CheckTraj with vels vx:%.2f, vy:%.2f th:%.2f\n", tvx, // tvy, tvth); double max_lv = computeNewVelocity(tvx, cvx, max_lin_acc_, sim_time_); float vel_mag = sqrt(max_lv * max_lv); float steps = (vel_mag * sim_time_) / granularity_; float dt = sim_time_ / steps; float x = 0.0, y = 0.0, z = 0.0, th = 0.0; double lv = cvx; double av = cvth; geometry_msgs::PoseStamped pose; pose.header.stamp = ros::Time(); // ros::Time::now(); pose.header.frame_id = features_->getRobotBaseFrame(); // base_frame_; std::vector<geometry_msgs::Point> laser_points; if (use_laser_) { laser_mutex_.lock(); sensor_msgs::LaserScan l = laser_scan_; laser_mutex_.unlock(); laser_points = laser_polar2euclidean(&l); } // int ini = floor(steps/2.0 + 0.5); for (unsigned int i = 0; i < steps; i++) { lv = computeNewVelocity(tvx, lv, max_lin_acc_, dt); av = computeNewVelocity(tvth, av, max_ang_acc_, dt); float lin_dist = lv * dt; th = th + (av * dt); // normalization just in case th = normalizeAngle(th, -M_PI, M_PI); x = x + lin_dist * cos(th); // cos(th+av*dt/2.0) y = y + lin_dist * sin(th); if (inCollision(x, y, &laser_points)) return false; pose.pose.position.x = x; pose.pose.position.y = y; pose.pose.position.z = z; pose.pose.orientation = tf::createQuaternionMsgFromYaw(th); // printf("CollisionDetection. CheckTraj. step %u - x:%.2f, y:%.2f, z:%.2f frame: %s // -", i, x, y, z, pose.header.frame_id.c_str()); // tomar el punto x,y,z=0 (inicialmente) y coger los vecinos en el radio. // Coger el valor de z del mean bool valid = features_->pose3dValid(&pose); // pose3dValid transforma el pose a odom frame, pero después lo vuelve a base_link // para coger el z correcto z = pose.pose.position.z; if (!valid) { // printf("NOT VALID\n"); return false; } // printf("VALID\n"); } px = x; py = y; pz = z; pth = th; return true; } } /* namespace collision detection */ <|start_filename|>rrt_planners/include/rrt_planners/StateChecker.h<|end_filename|> #ifndef RRT_STATE_CHECKER_ #define RRT_STATE_CHECKER_ #include <rrt_planners/State.h> #include <rrt_planners/Node.h> #include <math.h> namespace RRT { class StateChecker { public: StateChecker(){}; virtual ~StateChecker() { } virtual bool isValid(State* s) const = 0; virtual bool getValid3dState(State* s) const = 0; virtual float distance(State* s1, State* s2) const { float dx = s1->getX() - s2->getX(); float dy = s1->getY() - s2->getY(); float dz = s1->getZ() - s2->getZ(); return dx * dx + dy * dy + dz * dz; } virtual float getCost(State* s) = 0; // virtual void preplanning_computations() = 0; // This two methods are for exploration purposes virtual std::vector<Node> clusterize_leaves(std::vector<Node>& leaves) const { return leaves; } virtual Node evaluate_exploration(std::vector<Node>& leaves) const { return leaves.at(0); } }; } #endif <|start_filename|>rrt_planners/src/State.cpp<|end_filename|> #include <rrt_planners/State.h> // Constructor RRT::State::State() { x_ = 0.0; y_ = 0.0; z_ = 0.0; yaw_ = 0.0; roll_ = 0.0; pitch_ = 0.0; lin_vel_ = 0.0; ang_vel_ = 0.0; } // Constructor RRT::State::State(float x, float y, float z, float yaw, float roll, float pitch, float lv, float av) { x_ = x; y_ = y; z_ = z; yaw_ = yaw; roll_ = roll; pitch_ = pitch; lin_vel_ = lv; ang_vel_ = av; } // Destructor RRT::State::~State() { } void RRT::State::getState(float &x, float &y, float &z, float &yaw, float &roll, float &pitch, float &lv, float &av) { x = x_; y = y_; z = z_; yaw = yaw_; roll = roll_; pitch = pitch_; lv = lin_vel_; av = ang_vel_; } float RRT::State::getX() const { return x_; } float RRT::State::getY() const { return y_; } float RRT::State::getZ() const { return z_; } float RRT::State::getYaw() const { return yaw_; } float RRT::State::getRoll() const { return roll_; } float RRT::State::getPitch() const { return pitch_; } float RRT::State::getLinVel() const { return lin_vel_; } float RRT::State::getAngVel() const { return ang_vel_; } void RRT::State::setX(float x) { x_ = x; } void RRT::State::setY(float y) { y_ = y; } void RRT::State::setZ(float z) { z_ = z; } void RRT::State::setYaw(float yaw) { yaw_ = yaw; } void RRT::State::setRoll(float roll) { roll_ = roll; } void RRT::State::setPitch(float pitch) { pitch_ = pitch; } void RRT::State::setLv(float lv) { lin_vel_ = lv; } void RRT::State::setAv(float av) { ang_vel_ = av; } <|start_filename|>global_rrt_planner/src/global_rrt_planner_ros.cpp<|end_filename|> #include <global_rrt_planner/global_rrt_planner_ros.h> #include <pluginlib/class_list_macros.h> // register this planner as a BaseGlobalPlanner plugin PLUGINLIB_EXPORT_CLASS(global_rrt_planner::GlobalRRTPlanner, nav_core::BaseGlobalPlanner) namespace global_rrt_planner { GlobalRRTPlanner::GlobalRRTPlanner() { initialize(std::string("GlobalRRTPlanner"), std::string("")); } GlobalRRTPlanner::GlobalRRTPlanner(std::string name, std::string frame_id, tf2_ros::Buffer* tf) { tf_ = tf; // initialize the planner initialize(name, frame_id); } GlobalRRTPlanner::~GlobalRRTPlanner() { if (rrt_wrapper_) delete rrt_wrapper_; if (tf_) delete tf_; } void GlobalRRTPlanner::initialize(std::string name, costmap_2d::Costmap2DROS* costmap_ros) { initialize(name, std::string("")); } void GlobalRRTPlanner::initialize(std::string name, std::string frame_id) { if (!initialized_) { if(tf_ == nullptr) { tf_ = new tf2_ros::Buffer(); tf_listener_ = new tf2_ros::TransformListener(*tf_); } sleep(5.0); ros::NodeHandle private_nh("~/" + name); if (frame_id.empty()) { ros::NodeHandle nh("~/"); nh.param(std::string("global_costmap/global_frame"), frame_id_, std::string("odom")); } else frame_id_ = frame_id; rrt_wrapper_ = new RRT_ros::RRT_ros_wrapper(tf_); // private_nh.param("old_navfn_behavior", old_navfn_behavior_, false); plan_pub_ = private_nh.advertise<nav_msgs::Path>("global_plan", 1); // potential_pub_ = private_nh.advertise<nav_msgs::OccupancyGrid>("potential", 1); make_plan_srv_ = private_nh.advertiseService("make_plan", &GlobalRRTPlanner::makePlanService, this); // dsrv_ = new // dynamic_reconfigure::Server<global_rrt_planner::GlobalRRTPlannerConfig>(ros::NodeHandle("~/" // + name)); // dynamic_reconfigure::Server<global_rrt_planner::GlobalRRTPlannerConfig>::CallbackType // cb = boost::bind( // &GlobalRRTPlanner::reconfigureCB, this, _1, _2); // dsrv_->setCallback(cb); initialized_ = true; } else ROS_WARN("This planner has already been initialized, you can't call it twice, doing nothing"); } bool GlobalRRTPlanner::makePlan(const geometry_msgs::PoseStamped& start, const geometry_msgs::PoseStamped& goal, std::vector<geometry_msgs::PoseStamped>& plan) { double cost = 0.0; return makePlan(start, goal, plan, cost); } bool GlobalRRTPlanner::makePlan(const geometry_msgs::PoseStamped& start, const geometry_msgs::PoseStamped& goal, std::vector<geometry_msgs::PoseStamped>& plan, double& cost) { // bool GlobalRRTPlanner::makePlan(const geometry_msgs::PoseStamped& start, const // geometry_msgs::PoseStamped& goal, double tolerance, // std::vector<geometry_msgs::PoseStamped>& plan) { plan.clear(); bool explore = false; if (goal.header.frame_id.empty()) { printf("Global rrt planner. Goal empty! Passing to EXPLORATION MODE!!! \n"); explore = true; } // geometry_msgs::PoseStamped start; // start.header.stamp = ros::Time::now(); // start.header.frame_id = "base_link"; // start.pose.position.x = 0.0; // start.pose.position.y = 0.0; // start.pose.position.z = 0.0; // start.pose.orientation = tf::createQuaternionMsgFromYaw(0.0); // Inside RRT_plan method, start and goal are transformed to the local frame plan = rrt_wrapper_->RRT_plan(explore, start, goal, 0.0, 0.0); cost = (double)rrt_wrapper_->get_path_cost(); // Visualize the tree nodes of the resulting path if (plan.empty()) return false; // Transform plan to the given frame_id // in case that it is different if (plan[0].header.frame_id != frame_id_) { for (unsigned int i = 0; i < plan.size(); i++) { // geometry_msgs::PoseStamped p = plan[i]; geometry_msgs::PoseStamped pt; try { //tf_->transformPose(frame_id_, plan[i], pt); tf_->transform(pt, plan[i], frame_id_); } catch (tf2::TransformException ex) { ROS_ERROR("global_rrt_planner_ros. MakePlan. TransformException: %s", ex.what()); continue; } plan[i] = pt; } } publishPlan(plan); return true; } void GlobalRRTPlanner::publishPlan(const std::vector<geometry_msgs::PoseStamped>& path) { if (!initialized_) { ROS_ERROR("This planner has not been initialized yet, but it is being used, please call initialize() before use"); return; } // create a message for the plan nav_msgs::Path gui_path; gui_path.poses.resize(path.size()); gui_path.header.frame_id = frame_id_; gui_path.header.stamp = ros::Time::now(); // Extract the plan in world co-ordinates, we assume the path is all in the same frame for (unsigned int i = 0; i < path.size(); i++) { gui_path.poses[i] = path[i]; } plan_pub_.publish(gui_path); } bool GlobalRRTPlanner::makePlanService(nav_msgs::GetPlan::Request& req, nav_msgs::GetPlan::Response& resp) { makePlan(req.start, req.goal, resp.plan.poses); resp.plan.header.stamp = ros::Time::now(); resp.plan.header.frame_id = frame_id_; return true; } } // end namespace global_rrt_planner <|start_filename|>rrt_planners/include/rrt_planners/StateSpace.h<|end_filename|> #ifndef RRT_STATE_SPACE_ #define RRT_STATE_SPACE_ #include <rrt_planners/State.h> #include <rrt_planners/Node.h> #include <rrt_planners/StateChecker.h> #include <rrt_planners/RandomNumbers.h> // For pre C++ 11 gamma function #include <boost/math/special_functions/gamma.hpp> #include <vector> #include <cmath> #include <stdio.h> #include <mutex> namespace RRT { class StateSpace { public: StateSpace(); StateSpace(StateChecker* stateChecker, unsigned int dim, unsigned int dim_type, float sx, float sy, float sz = 0.0, float xyzres = 0.1, float yawres = 0.02, float min_lv = 0.1, float max_lv = 0.5, float lvres = 0.05, float max_av = 0.5, float avres = 0.1); ~StateSpace(); State* sampleState(); State* sampleStateFree(); State* sampleStateNear(State* st); // State* sampleStateNearFree(State* st); State* sampleStateExternal(); State* sampleStateExternal(std::vector<State>* space); void setExternalSamples(std::vector<State>* space); // State* samplePathBiasing(std::vector<State>* path, float stddev, float yawdev = 0.2); float sampleUniform(); // value between [0, 1] float distance(State* s1, State* s2); float euclideanDistance(State* s1, State* s2); bool isStateValid(State* s); float getCost(State* s); bool getValid3dState(State* s); Node exploreLeafStates(std::vector<Node>& leaves); bool isSimpleGoalToleranceSatisfied(State* st, float& dist); bool isGoalToleranceSatisfied(State* st, float& dist); float getSpaceMeasure(); float calculeUnitBallMeasure(unsigned int d, double r); float getUnitBallMeasure(); float normalizeAngle(float val, float min, float max); unsigned int getDimensions(); unsigned int getType(); std::vector<unsigned int> getWeights(); float getSizeX(); float getSizeY(); float getSizeZ(); float getXYZresolution(); float getRPYResolution(); float getMinLinVel(); float getMaxLinVel(); float getLinVelResolution(); float getMaxAngVel(); float getAngVelResolution(); float getGoalXYZTolerance(); float getGoalTHTolerance(); State* getStart(); State* getGoal(); void setDimensions(unsigned int d); void setWeights(std::vector<unsigned int> w); void setSizeX(float sx); void setSizeY(float sy); void setSizeZ(float sz); void setXYZresolution(float res); void setRPYResolution(float res); void setMinLinVel(float v); void setMaxLinVel(float v); void setLinVelResolution(float res); void setMaxAngVel(float v); void setAngVelResolution(float res); void setGoalTolerance(float xyz_tol, float th_tol); bool setStart(State* s); bool setGoal(State* g); bool setStartAndGoal(State* s, State* g); StateChecker* stateChecker_; private: std::vector<State> external_samples_; std::mutex ext_mutex_; std::vector<int> used_indices_; bool use_external_samples_; RNG random_; unsigned int dimensions_; // if dimensions is 3, type 1-> X,Y,th type 2->X,Y,Z unsigned int type_; std::vector<unsigned int> weights_; float size_x_; float size_y_; float size_z_; float xyz_resolution_; float rpy_resolution_; float space_volume_; float unit_ball_measure_; float min_lin_vel_; float max_lin_vel_; float lin_vel_res_; std::vector<float> lin_vels_; float max_ang_vel_; float ang_vel_res_; std::vector<float> ang_vels_; float goal_xyz_tolerance_; float goal_th_tolerance_; State* start_; State* goal_; }; } #endif <|start_filename|>rrt_planners/include/rrt_planners/kdtree.h<|end_filename|> #ifndef __KDTREE_H__ #define __KDTREE_H__ #include <algorithm> #include <array> #include <cmath> #include <iostream> #include <random> #include <vector> #include <numeric> #include <functional> #include <map> // namespace kdt //{ template <typename T> class KDTree { public: /** @brief constructors */ KDTree() : root_(nullptr), dims_(2), size_(0){}; KDTree(size_t d) : root_(nullptr), dims_(d), size_(0){}; KDTree(const KDTree&) = delete; KDTree& operator=(const KDTree&) = delete; KDTree(const std::vector<T>& points, size_t d) : root_(nullptr), dims_(d) { buildTree(points); } /** @brief destructor */ ~KDTree() { delete root_; } /** @brief clear the kdtree structure */ void clear() { delete root_; size_ = 0; } int size() { return size_; } /** @brief fill the vector with the elements of the structure. */ void list(std::vector<T>& data) const { list(root_, data); } /** @brief add a new element */ void add(const T& point) { root_ = addRecursive(root_, point, 0); }; /** @brief Build the kdtree structure */ void buildTree(const std::vector<T>& points) { buildRecursive(points); }; /** @brief Searches the nearest neighbor. */ T nearest(const T& point) const { if (root_ == nullptr) throw std::logic_error("No nearest! KDTree is empty!"); // T* closer = nullptr; T closer; float min_dist = std::numeric_limits<double>::max(); nearestNeighbor(root_, point, closer, min_dist, 0); return closer; } /** @brief Searches k-nearest neighbors. */ std::vector<T> knearest(const T& point, int k) const { std::map<float, T> queue; knnSearchRecursive(root_, point, queue, k, 0); std::vector<T> indices; typename std::map<float, T>::iterator it = queue.begin(); for (; it != queue.end(); it++) { indices.push_back(it->second); } return indices; } /** @brief Searches neighbors within radius. */ std::vector<T> radiusSearch(const T& point, double radius) const { std::vector<T> indices; radiusSearchRecursive(root_, point, indices, radius, 0); return indices; } private: struct KdTreeNode { KdTreeNode() : tpoint_(), left_(nullptr), right_(nullptr) { } KdTreeNode(const T& point) : tpoint_(point), left_(nullptr), right_(nullptr) { } ~KdTreeNode() { delete left_; delete right_; } double distance(const T& pt) const { return tpoint_.distance(pt); } T tpoint_; KdTreeNode* left_; KdTreeNode* right_; }; // KD-Tree KdTreeNode* root_; size_t dims_; int size_; void list(KdTreeNode* n, std::vector<T>& data) const { if (n == nullptr) return; data.push_back(n->tpoint_); list(n->left_, data); list(n->right_, data); } void buildRecursive(const std::vector<T>& points) { for (unsigned int i = 0; i < points.size(); i++) { root_ = addRecursive(root_, points[i], 0); } } KdTreeNode* addRecursive(KdTreeNode* root, const T& point, int depth) { if (root == nullptr) { size_++; return new KdTreeNode(point); } // Calculate current dimension (cd) of comparison int cd = depth % dims_; if (point[cd] < root->tpoint_[cd]) { root->left_ = addRecursive(root->left_, point, depth + 1); } else { root->right_ = addRecursive(root->right_, point, depth + 1); } return root; } void nearestNeighbor(KdTreeNode* root, const T& point, T& closest, float& mindist, int depth = 0) const { if (root == nullptr) return; float current_distance = point.distance(root->tpoint_); if (current_distance < mindist) { mindist = current_distance; closest = root->tpoint_; } if (mindist == 0) return; int cd = depth % dims_; float plane_dist = (root->tpoint_[cd] - point[cd]); if (plane_dist > 0) nearestNeighbor(root->left_, point, closest, mindist, depth + 1); else nearestNeighbor(root->right_, point, closest, mindist, depth + 1); if ((plane_dist * plane_dist) >= mindist) return; if (plane_dist > 0) nearestNeighbor(root->right_, point, closest, mindist, depth + 1); else nearestNeighbor(root->left_, point, closest, mindist, depth + 1); } /** @brief Searches k-nearest neighbors recursively. */ void knnSearchRecursive(KdTreeNode* root, const T& point, std::map<float, T>& queue, int k, int depth) const { if (root == nullptr) return; float current_distance = point.distance(root->tpoint_); queue.insert(std::make_pair(current_distance, root->tpoint_)); if ((int)queue.size() > k) { queue.erase(--queue.end()); } int cd = depth % dims_; float plane_dist = (root->tpoint_[cd] - point[cd]); if (plane_dist > 0) knnSearchRecursive(root->left_, point, queue, k, depth + 1); else knnSearchRecursive(root->right_, point, queue, k, depth + 1); typename std::map<float, T>::iterator it = queue.end(); if ((int)queue.size() < k || (plane_dist * plane_dist) < ((--it)->first)) { if (plane_dist > 0) knnSearchRecursive(root->right_, point, queue, k, depth + 1); else knnSearchRecursive(root->left_, point, queue, k, depth + 1); } } /** @brief Searches all the neighbors in a radius recursively. */ void radiusSearchRecursive(KdTreeNode* root, const T& point, std::vector<T>& vec, float radius, int depth) const { if (root == nullptr) return; float distance = point.distance(root->tpoint_); if (distance < radius) vec.push_back(root->tpoint_); int cd = depth % dims_; float plane_dist = (root->tpoint_[cd] - point[cd]); if (plane_dist > 0) radiusSearchRecursive(root->left_, point, vec, radius, depth + 1); else radiusSearchRecursive(root->right_, point, vec, radius, depth + 1); if ((plane_dist * plane_dist) < radius) { if (plane_dist > 0) radiusSearchRecursive(root->right_, point, vec, radius, depth + 1); else radiusSearchRecursive(root->left_, point, vec, radius, depth + 1); } } }; //} // kdt #endif // !__KDTREE_H_ <|start_filename|>rrt_planners/src/steering/Steering.cpp<|end_filename|> #include <rrt_planners/steering/Steering.h> RRT::Steering::Steering() { space_ = NULL; maxRange_ = 0.25; timeStep_ = 0.1; minControlSteps_ = 5; //minTime = timeStep*minControlSteps maxControlSteps_ = 10; maxLinearAcc_ = 1.0; // m/s² maxAngularAcc_ = 2.0; // rad/s² max_lv_var_ = maxLinearAcc_ * timeStep_; max_av_var_ = maxAngularAcc_ * timeStep_; steeringType_ = 2; motionCostType_ = 2; } RRT::Steering::Steering(StateSpace* sp) { space_ = sp; maxRange_ = 0.25; //setMaxRange is called later timeStep_ = 0.1; minControlSteps_ = 5; //minTime = timeStep*minControlSteps maxControlSteps_ = 10; maxLinearAcc_ = 1.0; // m/s² maxAngularAcc_ = 2.0; // rad/s² max_lv_var_ = maxLinearAcc_ * timeStep_; max_av_var_ = maxAngularAcc_ * timeStep_; steeringType_ = 2; motionCostType_ = 2; kp_ = space_->getMaxLinVel(); kv_ = 3.0; ka_ = space_->getMaxAngVel()*4.0; ko_ = ka_/8.0; } RRT::Steering::Steering(StateSpace* sp, float max_range) : maxRange_(max_range) { space_ = sp; timeStep_ = 0.1; minControlSteps_ = 5; //minTime = timeStep*minControlSteps maxControlSteps_ = 10; maxLinearAcc_ = 1.0; // m/s² maxAngularAcc_ = 2.0; // rad/s² max_lv_var_ = maxLinearAcc_ * timeStep_; max_av_var_ = maxAngularAcc_ * timeStep_; steeringType_ = 2; motionCostType_ = 2; } RRT::Steering::Steering(StateSpace* sp, float tstep, int minSteps, int maxSteps, float lAccMax, float aAccMax) : timeStep_(tstep), minControlSteps_(minSteps), maxControlSteps_(maxSteps), maxLinearAcc_(lAccMax), maxAngularAcc_(aAccMax) { space_ = sp; maxRange_ = 0.0; max_lv_var_ = maxLinearAcc_ * timeStep_; max_av_var_ = maxAngularAcc_ * timeStep_; steeringType_ = 2; motionCostType_ = 2; } RRT::Steering::Steering(StateSpace* sp, float max_range, float tstep, int minSteps, int maxSteps, float lAccMax, float aAccMax) : space_(sp), maxRange_(max_range), timeStep_(tstep), minControlSteps_(minSteps), maxControlSteps_(maxSteps), maxLinearAcc_(lAccMax), maxAngularAcc_(aAccMax) { max_lv_var_ = maxLinearAcc_ * timeStep_; max_av_var_ = maxAngularAcc_ * timeStep_; steeringType_ = 2; motionCostType_ = 2; kp_ = space_->getMaxLinVel(); kv_ = 3.0; ka_ = space_->getMaxAngVel()*4.0; ko_ = ka_/8.0; } RRT::Steering::~Steering() { //delete space_; } void RRT::Steering::setSteeringParams(float kp, float kv, float ka, float ko) { kp_ = kp; kv_ = kv; ka_ = ka; ko_ = ko; } RRT::State* RRT::Steering::simpleSteer(State* fromState, State* toState, std::vector<State>& istates) { //State* newState = NULL; //Distance between points float dx = (toState->getX()-fromState->getX()); float dy = (toState->getY()-fromState->getY()); float dt = atan2(dy, dx); float dist = sqrt(dx*dx+dy*dy); float res = space_->getXYZresolution(); unsigned int steps; if(dist >= maxRange_) steps = (int) floor(maxRange_/res + 0.5); else steps = (int) floor(dist/res + 0.5); //printf("Double distance: %.2f, steps: %u, res: %.2f\n", dist, steps, res); State* aux = new State(fromState->getX(), fromState->getY()); for(unsigned int i=0; i<steps; i++) { float newx = aux->getX() + res*cos(dt); float newy = aux->getY() + res*sin(dt); delete aux; aux = new State(newx, newy); if(space_->isStateValid(aux)) { //if(newState) // delete newState; //newState = new State(newx, newy); //istates.push_back(*newState); istates.push_back(*aux); } else { delete aux; aux = NULL; break; } } if(aux) delete aux; State* newState = NULL; if(istates.size() > 0) newState = &(istates.at(istates.size()-1)); return newState; } RRT::State* RRT::Steering::simple3dSteer(State* fromState, State* toState, std::vector<State>& istates) { //State* newState = NULL; //printf("simple3dSteer. fromState z:%.2f, toState z:%.2f\n", fromState->getZ(), toState->getZ()); //Distance between points float dx = (toState->getX()-fromState->getX()); float dy = (toState->getY()-fromState->getY()); float dz = (toState->getZ()-fromState->getZ()); float dt = atan2(dy, dx); float dist = sqrt(dx*dx+dy*dy+dz*dz); float res = space_->getXYZresolution(); unsigned int steps; if(dist >= maxRange_) steps = (int) floor(maxRange_/res + 0.5); else steps = (int) floor(dist/res + 0.5); //printf("Double distance: %.2f, steps: %u, res: %.2f\n", dist, steps, res); State* aux = new State(fromState->getX(), fromState->getY(), fromState->getZ()); for(unsigned int i=0; i<steps; i++) { float newx = aux->getX() + res*cos(dt); float newy = aux->getY() + res*sin(dt); float newz = aux->getZ(); delete aux; aux = new State(newx, newy, newz); if(space_->getValid3dState(aux)) { //printf("Steering. simple3dSteer. state step [%u] valid!!!\n", i); //if(newState) // delete newState; //newState = new State(newx, newy); //istates.push_back(*newState); istates.push_back(*aux); } else { //printf("Steering. simple3dSteer. state step [%u] NOT valid!!!\n", i); delete aux; aux = NULL; break; } } if(aux) delete aux; State* newState = NULL; if(istates.size() > 0) { newState = &(istates.at(istates.size()-1)); } else //printf("Steering. simple3dSteer. istates is empty!!!\n"); return newState; } bool RRT::Steering::simple3dCollisionFree(State* fromState, State* toState, std::vector<State>& istates) { //Distance between points float dx = (toState->getX()-fromState->getX()); float dy = (toState->getY()-fromState->getY()); float dz = (toState->getZ()-fromState->getZ()); float dt = atan2(dy, dx); float dist = sqrt(dx*dx+dy*dy+dz*dz); float res = space_->getXYZresolution(); unsigned int steps = (int) floor(dist/res + 0.5); //Check the validity of the steps of the line from the initial state //to the max_range distance State* aux = new State(fromState->getX(), fromState->getY(), fromState->getZ()); for(unsigned int i=0; i<steps; i++) { float newx = aux->getX() + cos(dt)*res; float newy = aux->getY() + sin(dt)*res; float newz = aux->getZ(); delete aux; aux = new State(newx, newy, newz); if(!space_->getValid3dState(aux)) { delete aux; return false; } istates.push_back(*aux); } if(aux) delete aux; return true; } bool RRT::Steering::simpleCollisionFree(State* fromState, State* toState, std::vector<State>& istates) { //Distance between points float dx = (toState->getX()-fromState->getX()); float dy = (toState->getY()-fromState->getY()); //float dz = (toState->getZ()-fromState->getZ()); float dt = atan2(dy, dx); float dist = sqrt(dx*dx+dy*dy); float res = space_->getXYZresolution(); unsigned int steps = (int) floor(dist/res + 0.5); //Check the validity of the steps of the line from the initial state //to the max_range distance State* aux = new State(fromState->getX(), fromState->getY()); for(unsigned int i=0; i<steps; i++) { float newx = aux->getX() + cos(dt)*res; float newy = aux->getY() + sin(dt)*res; delete aux; aux = new State(newx, newy); if(!space_->isStateValid(aux)) { delete aux; return false; } istates.push_back(*aux); } if(aux) delete aux; return true; } //Steering used in KinoRRT (only 2 dimensions, and one action between states) bool RRT::Steering::rrt_steer(Node* fromNode, Node* toNode, Node* newNode) { std::vector<State> istates; if(fromNode == NULL) { printf("Steering. Nodo inicial igual a NULL\n"); return false; } if(toNode == NULL) { printf("Steering. Nodo final igual a NULL\n"); return false; } max_lv_var_ = maxLinearAcc_ * timeStep_; max_av_var_ = maxAngularAcc_ * timeStep_; //Robot position float rx = fromNode->getState()->getX(); float ry = fromNode->getState()->getY(); float rth = fromNode->getState()->getYaw(); //waypoint to reach float wx = toNode->getState()->getX(); float wy = toNode->getState()->getY(); float wth = toNode->getState()->getYaw(); //printf("xr:%.2f, yr:%.2f, xw:%.2f, yw:%.2f\n", rx, ry, wx, wy); // Transform way-point into local robot frame and get desired x,y,theta float dx = (wx-rx)*cos(rth) + (wy-ry)*sin(rth); float dy =-(wx-rx)*sin(rth) + (wy-ry)*cos(rth); float dist = sqrt(dx*dx + dy*dy); float dt = atan2(dy, dx); //Velocities to command float lv = kp_ * exp(-fabs(dt))* tanh(3*dist); float av = space_->getMaxAngVel() * dt; float prev_lv = fromNode->getState()->getLinVel(); float prev_av = fromNode->getState()->getAngVel(); //std::vector<Action*> act = fromNode->getAction(); //float prev_lv = act->at(act.size()-1)->getVx(); //float prev_av = act->at(act.size()-1)->getVth(); // linear vel if(fabs(prev_lv - lv) > max_lv_var_) { if(lv < prev_lv) lv = prev_lv - max_lv_var_; else lv = prev_lv + max_lv_var_; } // angular vel if(fabs(prev_av - av) > max_av_var_) { if(av < prev_av) av = prev_av - max_av_var_; else av = prev_av + max_av_var_; } if(lv > space_->getMaxLinVel()) lv = space_->getMaxLinVel(); else if(lv < space_->getMinLinVel()) lv = space_->getMinLinVel(); if(av > space_->getMaxAngVel()) av = space_->getMaxAngVel(); else if(av < (-space_->getMaxAngVel())) av = space_->getMaxAngVel()*(-1); //Dead areas /*if(fabs(lv) < 0.08) lv = 0.0; if(fabs(av) < 0.05) av = 0.0; */ State currentState = *fromNode->getState(); int numSteps = 0; while(numSteps <= maxControlSteps_ && dist > space_->getGoalXYZTolerance()) { State* newState = propagateStep(&currentState, lv, av); if(!space_->isStateValid(newState)) { delete newState; break; } currentState = *newState; delete newState; istates.push_back(currentState); numSteps++; dist = sqrt((wx-currentState.getX())*(wx-currentState.getX()) + (wy-currentState.getY())*(wy-currentState.getY())); } if(numSteps == 0) { return false; } Action action(lv, 0.0, av, numSteps); //Node* newNode = new Node(currentState, action); newNode->setState(currentState); newNode->addAction(action); newNode->setIntermediateStates(istates); return true; } //Steering used in KinoRRT (only 2 dimensions, and one action between states) bool RRT::Steering::rrt_3d_steer(Node* fromNode, Node* toNode, Node* newNode) { std::vector<State> istates; if(fromNode == NULL) { printf("Steering. Start node is NULL\n"); return false; } if(toNode == NULL) { printf("Steering. Final node is NULL\n"); return false; } max_lv_var_ = maxLinearAcc_ * timeStep_; max_av_var_ = maxAngularAcc_ * timeStep_; //Robot position float rx = fromNode->getState()->getX(); float ry = fromNode->getState()->getY(); float rz = fromNode->getState()->getZ(); float rth = fromNode->getState()->getYaw(); //waypoint to reach float wx = toNode->getState()->getX(); float wy = toNode->getState()->getY(); float wz = toNode->getState()->getZ(); float wth = toNode->getState()->getYaw(); //printf("xr:%.2f, yr:%.2f, xw:%.2f, yw:%.2f\n", rx, ry, wx, wy); // Transform way-point into local robot frame and get desired x,y,theta float dx = (wx-rx)*cos(rth) + (wy-ry)*sin(rth); float dy =-(wx-rx)*sin(rth) + (wy-ry)*cos(rth); float dz = (wz-rz); float dist = sqrt(dx*dx + dy*dy + dz*dz); float dt = atan2(dy, dx); //Velocities to command float lv = kp_ * exp(-fabs(dt))* tanh(3*dist); float av = space_->getMaxAngVel() * dt; float prev_lv = fromNode->getState()->getLinVel(); float prev_av = fromNode->getState()->getAngVel(); //std::vector<Action*> act = fromNode->getAction(); //float prev_lv = act->at(act.size()-1)->getVx(); //float prev_av = act->at(act.size()-1)->getVth(); // linear vel if(fabs(prev_lv - lv) > max_lv_var_) { if(lv < prev_lv) lv = prev_lv - max_lv_var_; else lv = prev_lv + max_lv_var_; } // angular vel if(fabs(prev_av - av) > max_av_var_) { if(av < prev_av) av = prev_av - max_av_var_; else av = prev_av + max_av_var_; } if(lv > space_->getMaxLinVel()) lv = space_->getMaxLinVel(); else if(lv < space_->getMinLinVel()) lv = space_->getMinLinVel(); if(av > space_->getMaxAngVel()) av = space_->getMaxAngVel(); else if(av < (-space_->getMaxAngVel())) av = space_->getMaxAngVel()*(-1); //Dead areas /*if(fabs(lv) < 0.08) lv = 0.0; if(fabs(av) < 0.05) av = 0.0; */ State currentState = *fromNode->getState(); int numSteps = 0; while(numSteps <= maxControlSteps_ && dist > space_->getGoalXYZTolerance()) { State* newState = propagateStep(&currentState, lv, av); //if(!space_->isStateValid(newState)) { if(!space_->getValid3dState(newState)) { delete newState; break; } currentState = *newState; delete newState; istates.push_back(currentState); numSteps++; dist = sqrt((wx-currentState.getX())*(wx-currentState.getX()) + (wy-currentState.getY())*(wy-currentState.getY()) + (wz-currentState.getZ())*(wz-currentState.getZ()) ); } if(numSteps == 0) { return false; } Action action(lv, 0.0, av, numSteps); //Node* newNode = new Node(currentState, action); newNode->setState(currentState); newNode->addAction(action); newNode->setIntermediateStates(istates); return true; } /* //Steering used in KinoRRT (only 2 dimensions, and one action between states) bool RRT::Steering::accompany_steer(Node* fromNode, Node* toNode, Node* newNode) { std::vector<State> istates; if(fromNode == NULL) { printf("Steering. Nodo inicial igual a NULL\n"); return false; } if(toNode == NULL) { printf("Steering. Nodo final igual a NULL\n"); return false; } max_lv_var_ = maxLinearAcc_ * timeStep_; max_av_var_ = maxAngularAcc_ * timeStep_; //Robot position float rx = fromNode->getState()->getX(); float ry = fromNode->getState()->getY(); float rth = fromNode->getState()->getYaw(); //waypoint to reach float wx = toNode->getState()->getX(); float wy = toNode->getState()->getY(); float wth = toNode->getState()->getYaw(); //printf("xr:%.2f, yr:%.2f, xw:%.2f, yw:%.2f\n", rx, ry, wx, wy); // Transform way-point into local robot frame and get desired x,y,theta float dx = (wx-rx)*cos(rth) + (wy-ry)*sin(rth); float dy =-(wx-rx)*sin(rth) + (wy-ry)*cos(rth); float dist = sqrt(dx*dx + dy*dy); float dt = atan2(dy, dx); //We need to know the target position at the same //time that the robot is in 'fromNode' //double x,y; //xxxx_->getTargetPosition(double t, x, y); //Calculate the distance between the robot and the target //float dist = sqrt((x-rx)*(x-rx) + (y-ry)*(y-ry)); //Velocities to command float lv = space_->getMaxLinVel() * (dist/1.5); // *exp(-fabs(dt)) float av = space_->getMaxAngVel() * dt; float prev_lv = fromNode->getState()->getLinVel(); float prev_av = fromNode->getState()->getAngVel(); //std::vector<Action*> act = fromNode->getAction(); //float prev_lv = act->at(act.size()-1)->getVx(); //float prev_av = act->at(act.size()-1)->getVth(); // linear vel if(fabs(prev_lv - lv) > max_lv_var_) { if(lv < prev_lv) lv = prev_lv - max_lv_var_; else lv = prev_lv + max_lv_var_; } // angular vel if(fabs(prev_av - av) > max_av_var_) { if(av < prev_av) av = prev_av - max_av_var_; else av = prev_av + max_av_var_; } if(lv > space_->getMaxLinVel()) lv = space_->getMaxLinVel(); else if(lv < space_->getMinLinVel()) lv = space_->getMinLinVel(); if(av > space_->getMaxAngVel()) av = space_->getMaxAngVel(); else if(av < (-space_->getMaxAngVel())) av = space_->getMaxAngVel()*(-1); //Dead areas //if(fabs(lv) < 0.08) // lv = 0.0; //if(fabs(av) < 0.05) // av = 0.0; State currentState = *fromNode->getState(); int numSteps = 0; while(numSteps <= maxControlSteps_ && dist > space_->getGoalXYZTolerance()) { State* newState = propagateStep(&currentState, lv, av); if(!space_->isStateValid(newState)) { delete newState; break; } currentState = *newState; delete newState; istates.push_back(currentState); numSteps++; dist = sqrt((wx-currentState.getX())*(wx-currentState.getX()) + (wy-currentState.getY())*(wy-currentState.getY())); } if(numSteps == 0) { return false; } Action action(lv, 0.0, av, numSteps); //Node* newNode = new Node(currentState, action); newNode->setState(currentState); newNode->addAction(action); newNode->setIntermediateStates(istates); return true; }*/ bool RRT::Steering::rrt_collisionFree(Node* fromNode, Node* toNode, Node& out) { std::vector<State> istates; if(fromNode == NULL) { printf("Steering. Nodo inicial igual a NULL\n"); return false; } if(toNode == NULL) { printf("Steering. Nodo final igual a NULL\n"); return false; } max_lv_var_ = maxLinearAcc_ * timeStep_; max_av_var_ = maxAngularAcc_ * timeStep_; //Robot position float rx = fromNode->getState()->getX(); float ry = fromNode->getState()->getY(); float rth = fromNode->getState()->getYaw(); //waypoint to reach float wx = toNode->getState()->getX(); float wy = toNode->getState()->getY(); float wth = toNode->getState()->getYaw(); //printf("xr:%.2f, yr:%.2f, xw:%.2f, yw:%.2f\n", rx, ry, wx, wy); // Transform way-point into local robot frame and get desired x,y,theta float dx = (wx-rx)*cos(rth) + (wy-ry)*sin(rth); float dy =-(wx-rx)*sin(rth) + (wy-ry)*cos(rth); float dist = sqrt(dx*dx + dy*dy); float dt = atan2(dy, dx); //Velocities to command float lv = kp_ * exp(-fabs(dt))* tanh(3*dist); float av = space_->getMaxAngVel() * dt; float prev_lv = fromNode->getState()->getLinVel(); float prev_av = fromNode->getState()->getAngVel(); //std::vector<Action*> act = fromNode->getAction(); //float prev_lv = act->at(act.size()-1)->getVx(); //float prev_av = act->at(act.size()-1)->getVth(); // linear vel if(fabs(prev_lv - lv) > max_lv_var_) { if(lv < prev_lv) lv = prev_lv - max_lv_var_; else lv = prev_lv + max_lv_var_; } // angular vel if(fabs(prev_av - av) > max_av_var_) { if(av < prev_av) av = prev_av - max_av_var_; else av = prev_av + max_av_var_; } if(lv > space_->getMaxLinVel()) lv = space_->getMaxLinVel(); else if(lv < space_->getMinLinVel()) lv = space_->getMinLinVel(); if(av > space_->getMaxAngVel()) av = space_->getMaxAngVel(); else if(av < (-space_->getMaxAngVel())) av = space_->getMaxAngVel()*(-1); //Dead areas /*if(fabs(lv) < 0.08) lv = 0.0; if(fabs(av) < 0.05) av = 0.0; */ //printf("printf: dt: %.2f, dist:%.2f, lv: %.2f, av: %.2f \n\n", dt, dist, lv, av); float max_dist_step = space_->getMaxLinVel() * timeStep_; float approx_steps = dist/max_dist_step; State newState = *fromNode->getState(); int numSteps = 0; while (dist >= space_->getGoalXYZTolerance()) { //Check that the path to waypoint is not too long if(numSteps > ceil(approx_steps*2)) { return false; } //newState = *propagateStep(&newState, lv, av); State* st = propagateStep(&newState, lv, av); //Check if the state is valid if(!space_->isStateValid(st)) { delete st; return false; } newState = *st; delete st; //printf("Step: %i. NewState x:%.2f, y:%.2f, th:%.2f\n", numSteps, newState->getX(), newState->getY(), newState->getYaw()); istates.push_back(newState); numSteps++; dist = sqrt((wx-newState.getX())*(wx-newState.getX()) + (wy-newState.getY())*(wy-newState.getY())); } if(numSteps == 0) { return false; } Action newAction(lv, 0.0, av, numSteps); out.setState(newState); std::vector<Action> act; act.push_back(newAction); out.setAction(act); out.setIntermediateStates(istates); return true; } // Steering method in 2 dimensions (x, y) - Interpolation of the motion cost bool RRT::Steering::steer2(Node* fromNode, Node* toNode, Node* newNode) { //Node * newNode = NULL; //Node * prevNode = NULL; std::vector<Action> actions; std::vector<State> istates; if(fromNode == NULL) { printf("Steering. Nodo inicial igual a NULL\n"); return false; } if(toNode == NULL) { printf("Steering. Nodo final igual a NULL\n"); return false; } //Max velocities variations in one time step max_lv_var_ = maxLinearAcc_ * timeStep_; max_av_var_ = maxAngularAcc_ * timeStep_; float incCost = 0.0; float AccCost = fromNode->getAccCost(); //std::vector<Action*> act = fromNode->getAction(); //float prev_lv = act->at(act.size()-1)->getVx(); //float prev_av = act->at(act.size()-1)->getVth(); float prev_lv = fromNode->getState()->getLinVel(); float prev_av = fromNode->getState()->getAngVel(); //waypoint to reach float wx = toNode->getState()->getX(); float wy = toNode->getState()->getY(); float wth = toNode->getState()->getYaw(); float lv = 0.0, av=0.0; float phi = 0.0; float dist = 100.0; int numSteps = 0; //Node currentNode = *fromNode; State currentState = *fromNode->getState(); Node currentNode(currentState); currentNode.setCost(space_->getCost(currentNode.getState())); while(numSteps <= maxControlSteps_ && dist > space_->getGoalXYZTolerance()) { // Transform way-point into local robot frame and get desired x,y,theta float dx = (wx-currentState.getX())*cos(currentState.getYaw()) + (wy-currentState.getY())*sin(currentState.getYaw()); float dy =-(wx-currentState.getX())*sin(currentState.getYaw()) + (wy-currentState.getY())*cos(currentState.getYaw()); if(numSteps == 0) dist = sqrt(dx*dx + dy*dy); float alpha = atan2(dy, dx); //Astolfi //float lv = kp * dist; //float av = ka * alpha; // + ko * phi; if(steeringType_ == 1) { //POSQ lv = kp_ * tanh(kv_*dist); av = ka_ * alpha; } else { //Improved-POSQ lv = kp_ * tanh(kv_*dist) * exp(-fabs(alpha)); av = ka_ * alpha; } //Check velocities reacheability // linear vel if(fabs(prev_lv - lv) > max_lv_var_) { if(lv < prev_lv) lv = prev_lv - max_lv_var_; else lv = prev_lv + max_lv_var_; } // angular vel if(fabs(prev_av - av) > max_av_var_) { if(av < prev_av) av = prev_av - max_av_var_; else av = prev_av + max_av_var_; } //Check max and min velocities if(lv > space_->getMaxLinVel()) lv = space_->getMaxLinVel(); else if(lv < space_->getMinLinVel()) lv = space_->getMinLinVel(); if(av > space_->getMaxAngVel()) av = space_->getMaxAngVel(); else if(av < (-space_->getMaxAngVel())) av = space_->getMaxAngVel()*(-1); //Dead velocity ranges //if(fabs(lv) < 0.08) // lv = 0.0; //if(fabs(av) < 0.05) // av = 0.0; //Propagate the movement State* st = propagateStep(&currentState, lv, av); //Break the loop is the state is not valid if(!space_->isStateValid(st)) { delete st; break; } Node nextNode(*st); nextNode.setCost(space_->getCost(st)); float mc = motionCost(&currentNode, &nextNode); incCost += mc; currentState = *st; delete st; currentNode = nextNode; currentNode.setIncCost(incCost); dist = sqrt((wx-currentState.getX())*(wx-currentState.getX()) + (wy-currentState.getY())*(wy-currentState.getY())); istates.push_back(currentState); Action a(lv, 0.0, av, 1); actions.push_back(a); prev_lv = lv; prev_av = av; numSteps++; } if(numSteps == 0){ return false; } //currentNode.setAction(actions); //currentNode.setIntermediateStates(istates); //currentNode.setAccCost(AccCost + incCost); //newNode = new Node(currentState); newNode->setState(currentState); newNode->setAction(actions); newNode->setIntermediateStates(istates); newNode->setCost(currentNode.getCost()); newNode->setIncCost(incCost); newNode->setAccCost(AccCost + incCost); return true; } //Steering for collision checking in two dimensions (x, y) - Interpolation of the motion cost bool RRT::Steering::collisionFree2(Node* fromNode, Node* toNode, std::vector<Action>& acts, std::vector<State>& istates, float& motCost) { std::vector<Action> actions; std::vector<State> inter_states; if(fromNode == NULL) { printf("Steering. Nodo inicial igual a NULL\n"); motCost = 0.0; return false; } if(toNode == NULL) { printf("Steering. Nodo final igual a NULL\n"); motCost = 0.0; return false; } float incCost = 0.0; //float AccCost = fromNode->getAccCost(); //Max velocities variations in one time step max_lv_var_ = maxLinearAcc_ * timeStep_; max_av_var_ = maxAngularAcc_ * timeStep_; //std::vector<Action*> act = fromNode->getAction(); //float prev_lv = act->at(act.size()-1)->getVx(); //float prev_av = act->at(act.size()-1)->getVth(); float prev_lv = fromNode->getState()->getLinVel(); float prev_av = fromNode->getState()->getAngVel(); //waypoint to reach float wx = toNode->getState()->getX(); float wy = toNode->getState()->getY(); float wth = toNode->getState()->getYaw(); float lv = 0.0, av=0.0; float phi = 0.0; float xs = wx - fromNode->getState()->getX(); float ys = wy - fromNode->getState()->getY(); float init_dist = sqrt(xs*xs + ys*ys); //10.0; float dist = init_dist; float max_dist_step = space_->getMaxLinVel() * timeStep_; float approx_steps = init_dist/max_dist_step; //Initial robot position State currentState = *fromNode->getState(); //Node currentNode(currentState); Node currentNode(*fromNode); int numSteps = 0; while (dist >= space_->getGoalXYZTolerance()) { //Check that the path to waypoint is not too long if(numSteps > ceil(approx_steps*3)) { //printf("Step number > %.1f\n", ceil(approx_steps*5)); motCost = 0.0; return false; } // Transform way-point into local robot frame and get desired x,y,theta float dx = (wx-currentState.getX())*cos(currentState.getYaw()) + (wy-currentState.getY())*sin(currentState.getYaw()); float dy =-(wx-currentState.getX())*sin(currentState.getYaw()) + (wy-currentState.getY())*cos(currentState.getYaw()); if(numSteps == 0) dist = sqrt(dx*dx + dy*dy); float alpha = atan2(dy, dx); //Velocities to command if(steeringType_ == 1) { //POSQ lv = kp_ * tanh(kv_*dist); av = ka_ * alpha; // + ko * phi; } else { //Improved-POSQ lv = kp_ * tanh(kv_*dist) * exp(-fabs(alpha)); av = ka_ * alpha; // + ko * phi; } //Check velocities reacheability // linear vel if(fabs(prev_lv - lv) > max_lv_var_) { if(lv < prev_lv) lv = prev_lv - max_lv_var_; else lv = prev_lv + max_lv_var_; } // angular vel if(fabs(prev_av - av) > max_av_var_) { if(av < prev_av) av = prev_av - max_av_var_; else av = prev_av + max_av_var_; } if(lv > space_->getMaxLinVel()) lv = space_->getMaxLinVel(); else if(lv < space_->getMinLinVel()) lv = space_->getMinLinVel(); if(av > space_->getMaxAngVel()) av = space_->getMaxAngVel(); else if(av < (-space_->getMaxAngVel())) av = space_->getMaxAngVel()*(-1); //Dead areas /*if(fabs(lv) < 0.08) lv = 0.0; if(fabs(av) < 0.05) av = 0.0; */ State* st = propagateStep(&currentState, lv, av); //Check if the state is valid if(!space_->isStateValid(st)) { motCost = 0.0; delete st; return false; } Node nextNode(*st); nextNode.setCost(space_->getCost(st)); float mc = motionCost(&currentNode, &nextNode); incCost += mc; currentState = *st; delete st; currentNode = nextNode; numSteps++; dist = sqrt((wx-currentState.getX())*(wx-currentState.getX()) + (wy-currentState.getY())*(wy-currentState.getY())); inter_states.push_back(currentState); Action a(lv, 0.0, av, 1); actions.push_back(a); prev_lv = lv; prev_av = av; } if(numSteps == 0){ return false; } acts = actions; motCost = incCost; istates = inter_states; return true; } float RRT::Steering::motionCost(Node* n1, Node* n2) { switch(motionCostType_) { case 1: // avg_cost return ((n1->getCost() + n2->getCost()) / 2.0); case 2: // avg_cost * ecuclidean_dist return (((n1->getCost() + n2->getCost()) / 2.0) * distance(n1->getState(), n2->getState(), 2)); case 3: // avg_cost * exp(dist) return (((n1->getCost() + n2->getCost()) / 2.0) * exp(distance(n1->getState(), n2->getState(), 2))); case 4: // cost sum return (n1->getCost() + n2->getCost()); case 5: //avg_cost * (dist + orientation) return ((n1->getCost() + n2->getCost()) / 2.0) * distance(n1->getState(), n2->getState(), 4); case 6: // avg_cost * (dist + angles_accu_diff) (angles of the point orientation regarding the intersection line) return ((n1->getCost() + n2->getCost()) / 2.0) * distance(n1->getState(), n2->getState(), 5); case 7: // avg_cost * distance function of paper IROS2015 "Feedback motion planning via non-holonomic RRT* for mobile robots" return ((n1->getCost() + n2->getCost()) / 2.0) * distance(n1->getState(), n2->getState(), 6); default: // avg * ecuclidean_dist return (((n1->getCost() + n2->getCost()) / 2.0) * distance(n1->getState(), n2->getState(), 2)); } } float RRT::Steering::distance(State* s1, State* s2, int type) { float dx = s1->getX() - s2->getX(); float dy = s1->getY() - s2->getY(); float dz = s1->getZ() - s2->getZ(); //float dist = sqrt(dx*dx + dy*dy); float dist = dx*dx + dy*dy + dz*dz; switch(type) { case 1: return dist; case 2: return sqrt(dist); /*case 3: if(space_->getDimensions() == 2) return sqrt(dist); else { // w1*|| Pi+1 - Pi|| + w2*(1-|Qi+1 * Qi|)² float euc_dist = sqrt(dist); tf::Quaternion q1 = tf::createQuaternionFromYaw(s1->getYaw()); tf::Quaternion q2 = tf::createQuaternionFromYaw(s2->getYaw()); float dot_prod = q1.dot(q2); float angle_dist = (1 - fabs(dot_prod))*(1 - fabs(dot_prod)); //printf("eu_dist: %.2f, angle_dist: %.3f, dist: %.3f\n", euc_dist, angle_dist, 0.8*euc_dist + 0.2*angle_dist); return 0.7*euc_dist + 0.3*angle_dist; }*/ case 4: if(space_->getDimensions() == 2) return dist; else { // Another option /* First, transform the robot location into person location frame: |cos(th) sin(th) 0| Rotation matrix R(th)= |-sin(th) cos(th) 0| | 0 0 1| x' = (xr-xp)*cos(th_p)+(yr-yp)*sin(th_p) y' = (xr-xp)*(-sin(th_p))+(yr-yp)*cos(th_p) */ float x = (s2->getX()-s1->getX())*cos(s1->getYaw()) + (s2->getY()-s1->getY())*sin(s1->getYaw()); float y =-(s2->getX()-s1->getX())*sin(s1->getYaw()) + (s2->getY()-s1->getY())*cos(s1->getYaw()); float alpha = atan2(y, x); return (0.8*sqrt(dist)+0.2*fabs(alpha)); } case 5: if(space_->getDimensions() == 2) return dist; else { //UPO. Dist + sum of the angles of both points regarding the intersection line float x = (s2->getX()-s1->getX())*cos(s1->getYaw()) + (s2->getY()-s1->getY())*sin(s1->getYaw()); float y =-(s2->getX()-s1->getX())*sin(s1->getYaw()) + (s2->getY()-s1->getY())*cos(s1->getYaw()); float alpha = atan2(y, x); float beta = s2->getYaw() - alpha; beta = normalizeAngle(beta, -M_PI, M_PI); return (0.6*sqrt(dist)+0.4*(fabs(alpha)+fabs(beta))); } case 6: if(space_->getDimensions() == 2) return dist; else { //Paper IROS2015 "Feedback motion planning via non-holonomic RRT* for mobile robots" float x = (s2->getX()-s1->getX())*cos(s1->getYaw()) + (s2->getY()-s1->getY())*sin(s1->getYaw()); float y =-(s2->getX()-s1->getX())*sin(s1->getYaw()) + (s2->getY()-s1->getY())*cos(s1->getYaw()); float alpha = atan2(y, x); float phi = s2->getYaw() - alpha; phi = normalizeAngle(phi, -M_PI, M_PI); float ka = 0.5; float ko = ka/8.0; dist = sqrt(dist); // two options float alpha_prime = atan(-ko*phi); //float alpha_prime = atan(-ko*ko * phi/(dist*dist)); float r = normalizeAngle((alpha-alpha_prime), -M_PI, M_PI); return (sqrt(dist*dist + ko*ko + phi*phi) + ka*fabs(r)); } default: return dist; } } // Steering method in 3 dimensions (x, y, yaw) - Interpolation of the motion cost bool RRT::Steering::steer3(Node* fromNode, Node* toNode, Node* newNode) { //Node * newNode = NULL; //Node * prevNode = NULL; std::vector<Action> actions; std::vector<State> istates; if(fromNode == NULL) { printf("Steering. ERROR. Initial node is NULL\n"); return false; } if(toNode == NULL) { printf("Steering. ERROR. Final node is NULL\n"); return false; } //Max velocities variations in one time step max_lv_var_ = maxLinearAcc_ * timeStep_; max_av_var_ = maxAngularAcc_ * timeStep_; float incCost = 0.0; float AccCost = fromNode->getAccCost(); std::vector<Action>* ac = fromNode->getAction(); float prev_lv = ac->at(ac->size()-1).getVx(); float prev_av = ac->at(ac->size()-1).getVth(); //float prev_lv = fromNode->getState()->getLinVel(); //float prev_av = fromNode->getState()->getAngVel(); float prev_x = fromNode->getState()->getX(); float prev_y = fromNode->getState()->getY(); /*if(prev_x == 0.0 && prev_y ==0.0){ printf("a_lv: %.2f, st_lv:%.2f\n", prev_lvA, prev_lv); }*/ //waypoint to reach float wx = toNode->getState()->getX(); float wy = toNode->getState()->getY(); float wth = toNode->getState()->getYaw(); float lv = 0.0, av=0.0; float phi = 0.0; float dist = 100.0; int numSteps = 0; Node currentNode(*fromNode); State currentState = *currentNode.getState(); //Node currentNode(currentState); currentNode.setCost(space_->getCost(currentNode.getState())); bool first = true; while(numSteps <= maxControlSteps_ && (dist > space_->getGoalXYZTolerance() || fabs(phi) > space_->getGoalTHTolerance())) { // Transform way-point into local robot frame and get desired x,y,theta float dx = (wx-currentState.getX())*cos(currentState.getYaw()) + (wy-currentState.getY())*sin(currentState.getYaw()); float dy =-(wx-currentState.getX())*sin(currentState.getYaw()) + (wy-currentState.getY())*cos(currentState.getYaw()); if(numSteps == 0) { dist = sqrt(dx*dx + dy*dy); phi = currentState.getYaw() - wth; //Normalize phi phi = space_->normalizeAngle(phi, -M_PI, M_PI); } float alpha = atan2(dy, dx); if(fabs(alpha) > 1.0) // 1.5r~86º 0.7~41º 0.79~45º { lv = 0.0; av = 0.3; if(alpha < 0.0) av = -0.3; } else { //Astolfi //float lv = kp * dist; //float av = ka * alpha; // + ko * phi; if(steeringType_ == 1) { //POSQ lv = kp_ * tanh(kv_*dist); av = ka_ * alpha + ko_ * phi; } else { //Improved-POSQ lv = kp_ * tanh(kv_*dist) * exp(-fabs(alpha)); av = ka_ * alpha + ko_ * phi; } float ant_lv = lv; //Check velocities reacheability // linear vel if(fabs(prev_lv - lv) > max_lv_var_) { if(lv < prev_lv) lv = prev_lv - max_lv_var_; else lv = prev_lv + max_lv_var_; } // angular vel if(fabs(prev_av - av) > max_av_var_) { if(av < prev_av) av = prev_av - max_av_var_; else av = prev_av + max_av_var_; } //Check max and min velocities if(lv > space_->getMaxLinVel()) lv = space_->getMaxLinVel(); else if(lv < space_->getMinLinVel()) lv = space_->getMinLinVel(); if(av > space_->getMaxAngVel()) av = space_->getMaxAngVel(); else if(av < (-space_->getMaxAngVel())) av = space_->getMaxAngVel()*(-1); /*if(first && prev_x == 0.0 && prev_y == 0.0) { first = false; printf("prev_lv: %.2f n_lv:%.2f, n_lv2:%.2f\n", prev_lv, ant_lv, lv); }*/ //Dead velocity ranges /*if(fabs(lv) < 0.08) lv = 0.0; if(fabs(av) < 0.05) av = 0.0; */ } //Propagate the movement State* st = propagateStep(&currentState, lv, av); //Break the loop is the state is not valid if(!space_->isStateValid(st)) { delete st; break; } Node nextNode(*st); nextNode.setCost(space_->getCost(st)); float mc = motionCost(&currentNode, &nextNode); incCost += mc; currentState = *st; delete st; currentNode = nextNode; currentNode.setIncCost(incCost); dist = sqrt((wx-currentState.getX())*(wx-currentState.getX()) + (wy-currentState.getY())*(wy-currentState.getY())); phi = currentState.getYaw() - wth; //Normalize phi phi = space_->normalizeAngle(phi, -M_PI, M_PI); istates.push_back(currentState); Action a(lv, 0.0, av, 1); actions.push_back(a); prev_lv = lv; prev_av = av; numSteps++; } if(numSteps == 0){ return false; } newNode->setState(currentState); newNode->setAction(actions); newNode->setIntermediateStates(istates); newNode->setCost(currentNode.getCost()); newNode->setIncCost(incCost); newNode->setAccCost(AccCost + incCost); return true; } //Steering for collision checking in 3 dimensions (x, y, yaw) - Interpolation of the motion cost bool RRT::Steering::collisionFree3(Node* fromNode, Node* toNode, std::vector<Action>& acts, std::vector<State>& istates, float& motCost) { std::vector<Action> actions; std::vector<State> inter_states; if(fromNode == NULL) { printf("Steering. Nodo inicial igual a NULL\n"); motCost = 0.0; return false; } if(toNode == NULL) { printf("Steering. Nodo final igual a NULL\n"); motCost = 0.0; return false; } float incCost = 0.0; //float AccCost = fromNode->getAccCost(); //Max velocities variations in one time step max_lv_var_ = maxLinearAcc_ * timeStep_; max_av_var_ = maxAngularAcc_ * timeStep_; //std::vector<Action*> act = fromNode->getAction(); //float prev_lv = act.at(act.size()-1)->getVx(); //float prev_av = act.at(act.size()-1)->getVth(); float prev_lv = fromNode->getState()->getLinVel(); float prev_av = fromNode->getState()->getAngVel(); //waypoint to reach float wx = toNode->getState()->getX(); float wy = toNode->getState()->getY(); float wth = toNode->getState()->getYaw(); float lv = 0.0, av=0.0; float phi = 0.0; float xs = wx - fromNode->getState()->getX(); float ys = wy - fromNode->getState()->getY(); float init_dist = sqrt(xs*xs + ys*ys); //10.0; float dist = init_dist; float max_dist_step = space_->getMaxLinVel() * timeStep_; float approx_steps = init_dist/max_dist_step; //Initial robot position Node currentNode(*fromNode); State currentState = *currentNode.getState(); int numSteps = 0; while (dist >= space_->getGoalXYZTolerance() || fabs(phi) > space_->getGoalTHTolerance()) { //Check that the path to waypoint is not too long if(numSteps > ceil(approx_steps*3)) { //printf("Step number > %.1f\n", ceil(approx_steps*5)); motCost = 0.0; return false; } // Transform way-point into local robot frame and get desired x,y,theta float dx = (wx-currentState.getX())*cos(currentState.getYaw()) + (wy-currentState.getY())*sin(currentState.getYaw()); float dy =-(wx-currentState.getX())*sin(currentState.getYaw()) + (wy-currentState.getY())*cos(currentState.getYaw()); if(numSteps == 0) { dist = sqrt(dx*dx + dy*dy); phi = currentState.getYaw() - wth; //Normalize phi phi = space_->normalizeAngle(phi, -M_PI, M_PI); } float alpha = atan2(dy, dx); //Velocities to command if(steeringType_ == 1) { //POSQ lv = kp_ * tanh(kv_*dist); av = ka_ * alpha + ko_ * phi; } else { //Improved-POSQ lv = kp_ * tanh(kv_*dist) * exp(-fabs(alpha)); av = ka_ * alpha + ko_ * phi; } //Check velocities reacheability // linear vel if(fabs(prev_lv - lv) > max_lv_var_) { if(lv < prev_lv) lv = prev_lv - max_lv_var_; else lv = prev_lv + max_lv_var_; } // angular vel if(fabs(prev_av - av) > max_av_var_) { if(av < prev_av) av = prev_av - max_av_var_; else av = prev_av + max_av_var_; } if(lv > space_->getMaxLinVel()) lv = space_->getMaxLinVel(); else if(lv < space_->getMinLinVel()) lv = space_->getMinLinVel(); if(av > space_->getMaxAngVel()) av = space_->getMaxAngVel(); else if(av < (-space_->getMaxAngVel())) av = space_->getMaxAngVel()*(-1); //Dead areas /*if(fabs(lv) < 0.08) lv = 0.0; if(fabs(av) < 0.05) av = 0.0; */ //--------------------------------- State* st = propagateStep(&currentState, lv, av); //Check if the state is valid if(!space_->isStateValid(st)) { motCost = 0.0; delete st; return false; } Node nextNode(*st); nextNode.setCost(space_->getCost(st)); float mc = motionCost(&currentNode, &nextNode); incCost += mc; currentState = *st; delete st; currentNode = nextNode; numSteps++; dist = sqrt((wx-currentState.getX())*(wx-currentState.getX()) + (wy-currentState.getY())*(wy-currentState.getY())); phi = currentState.getYaw() - wth; //Normalize phi phi = space_->normalizeAngle(phi, -M_PI, M_PI); inter_states.push_back(currentState); Action a(lv, 0.0, av, 1); actions.push_back(a); prev_lv = lv; prev_av = av; } if(numSteps == 0){ return false; } acts = actions; motCost = incCost; istates = inter_states; return true; } //Propagate one step RRT::State* RRT::Steering::propagateStep(State* st, float lv, float av) { float lin_dist = lv * timeStep_; float ang_dist = av * timeStep_; float th = st->getYaw() + ang_dist; //Normalize th th = space_->normalizeAngle(th, -M_PI, M_PI); float x = st->getX() + lin_dist*cos(th); float y = st->getY() + lin_dist*sin(th); float z = st->getZ(); State* result = new State(x, y, z, th, lv, av); return result; } float RRT::Steering::normalizeAngle(float val, float min, float max) { float norm = 0.0; if (val >= min) norm = min + fmod((val - min), (max-min)); else norm = max - fmod((min - val), (max-min)); return norm; } <|start_filename|>rrt_planners/src/planners/control/Rrt.cpp<|end_filename|> #include <rrt_planners/planners/control/Rrt.h> //#define PRINT_STATISTICS false RRT::Rrt::Rrt() : Planner() { // accompany_steer_ = false; } RRT::Rrt::~Rrt() { } bool RRT::Rrt::steer(Node* fromNode, Node* toNode, Node* newNode) { // if(accompany_steer_) // return steering_->accompany_steer(fromNode, toNode, newNode); return steering_->rrt_3d_steer(fromNode, toNode, newNode); } std::vector<RRT::Node> RRT::Rrt::solve(float secs) { /************************************************** GENERATE_RRT(Xinit, K, t) V<-{Xinit}, E<-0; for k=1 to K do Xrand <- SampleFree; Xnearest <- Nearest(G=(V,E), Xrand); Unew <- SelectInput(Xrand, Xnearest, Xrand); Xnew <- Steer(Xnearest, Unew, t); V <- V U {Xnew}; E <- E U {(Xnearest, Xnew, Unew)}; return G = (V,E); ***************************************************/ // Clear datastructure and initilize it // nn_->clear(); KDTree<RRT::Node> nn(dimensions_); // Action* act = new Action(0.0, 0.0, 0.0, 5); // Node* ini = new Node(*start_, *init_action_state_); Node ini(*start_, *init_action_state_); nn.add(ini); tree_.clear(); // Statistics unsigned int total_samples = 0; unsigned int valid_samples = 0; unsigned int goal_samples = 0; unsigned int tree_nodes = 1; unsigned int path_nodes = 0; float time = 0.0; // unsigned int fathers = 0; bool solved = false; bool end = false; Node solution; Node approxSolution; float approxDist = std::numeric_limits<float>::max(); double t1, t2; struct timeval stop, start; gettimeofday(&start, NULL); t1 = start.tv_sec + (start.tv_usec / 1000000.0); while (!end) { // Node* randNode; State randState; if (space_->sampleUniform() < goalBias_ && !exploration_) // sample goal according to the bias parameter { randState = *goal_; // State* randState = goal_; // randNode = new Node(*randState); goal_samples++; valid_samples++; total_samples++; // delete randState; } else { // Sample a random valid state unsigned int cont = 0; do { randState = *space_->sampleState(); cont++; if (cont > 1) total_samples++; else { valid_samples++; total_samples++; } // delete randState; } while (!space_->getValid3dState(&randState)); } Node randNode(randState); // Find nearest node in the tree // Node* nearNode = nn_->nearest(&randNode); std::shared_ptr<Node> nearNode = std::make_shared<Node>(nn.nearest(randNode)); /*if(!nearNode->hasChildren()){ fathers++; nearNode->setChildren(); }*/ Node newNode; // Add the new node to the tree if (steer(nearNode.get(), &randNode, &newNode)) { newNode.setParent(nearNode.get()); nearNode->setChildren(); nn.add(newNode); tree_nodes++; if (!exploration_) { float dist = 0.0; solved = space_->isSimpleGoalToleranceSatisfied(newNode.getState(), dist); // isGoalToleranceSatisfied if (solved) { approxDist = dist; solution = newNode; // break; } else if (dist < approxDist) { approxDist = dist; approxSolution = newNode; } } } else { // printf("Node NULL!!!!\n"); } gettimeofday(&stop, NULL); t2 = stop.tv_sec + (stop.tv_usec / 1000000.0); time = t2 - t1; if (time >= secs || solved) { end = true; } } if (!solved && !exploration_) { printf("\nRRT. Approximate solution found. dist to goal: %.3f\n", approxDist); solution = approxSolution; } else { printf("\nRRT. Exlporation performed during %.6f secs\n", time); } unsigned int tree_total_nodes = 0; if (storeTree_) { std::vector<Node> nodes; nn.list(nodes); tree_total_nodes = (unsigned int)nodes.size(); storeTree(nodes); if (exploration_) { storeLeafNodes(nodes); solution = space_->exploreLeafStates(leaves_); } } else if (exploration_) { std::vector<Node> nodes; nn.list(nodes); storeLeafNodes(nodes); solution = space_->exploreLeafStates(leaves_); } // Construct the solution path std::vector<RRT::Node> path; // solution->getState()->setYaw(goal_->getYaw()); Node* current = &solution; path_cost_ = current->getAccCost(); while (current != nullptr) { Node node = *current; // copyNode(&node, current); path.push_back(node); current = current->getParent(); path_nodes++; } /*for(unsigned int k=0; k<path.size(); k++) { printf("Solution. Action.size(): %u, lv:%.2f, av:%.2f\n", (unsigned int)path[k].getAction().size(), path[k].getAction().at(0)->getVx(), path[k].getAction().at(0)->getVth()); }*/ stats_.planning_time = time; stats_.first_sol_time = time; stats_.total_samples = total_samples; stats_.valid_samples = valid_samples; stats_.goal_samples = goal_samples; stats_.tree_nodes = tree_nodes; stats_.leaf_nodes = leaves_.size(); stats_.path_nodes = path_nodes; // printf("Rrt.cpp. fathers: %u\n", fathers); // printf("Rrt.cpp. Total tree nodes: %u\n", tree_total_nodes); /*if(PRINT_STATISTICS) { printf("Planning time: %.4f secs\n", time); printf("Total samples: %u \n", total_samples); printf("Valid samples: %u \n", valid_samples); printf("Goal samples: %u \n", goal_samples); printf("Tree nodes: %u \n", tree_nodes); printf("Path nodes: %u \n\n", path_nodes); }*/ delete current; // delete ini; // delete solution; // delete approxSolution; // freeTreeMemory(); return path; } <|start_filename|>rrt_planners/src/planners/control/HalfRRTstar.cpp<|end_filename|> #include <rrt_planners/planners/control/HalfRRTstar.h> RRT::HalfRRTstar::HalfRRTstar() : Planner() { maxRange_ = 0.5; useKnearest_ = true; k_rrt_ = 0.0; r_rrt_ = 0.0; rewire_factor_ = 1.1; // useFirstPathBiasing_ = false; // pathBias_ = 0.0; // pathBias_stddev_ = 0.0; } RRT::HalfRRTstar::~HalfRRTstar() { } bool RRT::HalfRRTstar::steer(Node* fromNode, Node* toNode, Node* newNode) { if (space_->getDimensions() == 2) return steering_->steer2(fromNode, toNode, newNode); else return steering_->steer3(fromNode, toNode, newNode); } bool RRT::HalfRRTstar::collisionFree(Node* fromNode, Node* toNode, std::vector<Action>& acts, std::vector<State>& istates, float& motCost) { if (space_->getDimensions() == 2) { return steering_->collisionFree2(fromNode, toNode, acts, istates, motCost); } else { return steering_->collisionFree3(fromNode, toNode, acts, istates, motCost); } } std::vector<RRT::Node> RRT::HalfRRTstar::solve(float secs) { /****************************************************************************************** V<-{Xinit}, E<-0; for int i=0,...,n do Xrand <- SampleFree; Xnearest <- Nearest(G=(V,E), Xrand); {(Xnew, Unew, Tnew)} <- Steer(Xnearest, Xrand); if(ObstacleFree(Xnearest, Xnew)) then Xs_near <- Near(G=(V,E), Xnew, min{gamma(log(Card(V)/Card(V))^(1/d), eta}); V <- V U {Xnew} Xmin <- Xnearest; Cmin <- Cost(Xnearest) + C(Line(Xnearest, Xnew)); for each Xnear in Xs_near do //Connect along a minimum-cost path if CollisionFree(Xnear, Xnew) && Cost(Xnear)+C(Line(Xnear, Xnew)) < Cmin then Xmin <- Xnear; Cmin <- Cost(Xnear) + C(Line(Xnear, Xnear)); E <- E U {(Xmin, Xnew)}; for each Xnear in Xs_near do //Rewire the tree if CollisionFree(Xnew, Xnear) && Cost(Xnew) + C(Line(Xnew, Xnear)) < Cost(Xnear) then Xparent <- Parent(Xnear); E <- (E\{(Xparent, Xnear)}) U {(Xnew, Xnear)}; return G=(V,E); ***********************************************************************************************/ // Clear datastructure and initilize it // nn_->clear(); KDTree<RRT::Node> nn(dimensions_); Node ini(*start_, *init_action_state_); std::vector<Action>* actss = ini.getAction(); float vxx = 100.0, vyy = 100.0, vtt = 100.0; unsigned int vs; actss->at(actss->size() - 1).getAction(vxx, vyy, vtt, vs); printf("halfRRTstar solve. Ini x:%.2f, y:%.2f, vx:%.2f, vth:%.2f\n", ini.getState()->getX(), ini.getState()->getY(), vxx, vtt); float singleCost = space_->getCost(start_); ini.setCost(singleCost); ini.setIncCost(singleCost); ini.setAccCost(singleCost); nn.add(ini); calculateParamsNearest(); tree_.clear(); // Statistics unsigned int total_samples = 0; unsigned int valid_samples = 0; unsigned int goal_samples = 0; unsigned int tree_nodes = 1; unsigned int path_nodes = 0; float time = 0.0; float first_sol_time = 0.0; unsigned int total_rewirings = 0; unsigned int posible_rewirings = 0; bool solved = false; bool end = false; bool first_sol = true; Node solution; Node approxSolution; float approxDist = std::numeric_limits<float>::max(); // Goal node Node* goalNode = new Node(*goal_); goalNode->setCost(space_->getCost(goal_)); // unsigned int cont_null = 0; double t1, t2; struct timeval stop, start, first_stop; gettimeofday(&start, NULL); t1 = start.tv_sec + (start.tv_usec / 1000000.0); while (!end) { State randState; // sample goal according to the bias parameter if (first_sol && space_->sampleUniform() < goalBias_) { randState = *goal_; goal_samples++; valid_samples++; total_samples++; } else { // Sample a random valid state unsigned int cont = 0; do { randState = *space_->sampleState(); cont++; if (cont > 1) total_samples++; else { valid_samples++; total_samples++; } } while (!space_->isStateValid(&randState)); } Node randNode(randState); // Find nearest node in the tree // Node* nearNode = nn_->nearest(&randNode); std::shared_ptr<Node> nearNode = std::make_shared<Node>(nn.nearest(randNode)); if (nearNode == nullptr) printf("\n\nNo nearest node!!!!!\n\n"); Node newNode; if (steer(nearNode.get(), &randNode, &newNode)) { // Use the neighbors of the new node to find the best parent std::vector<RRT::Node> nbrs; getNearestNeighbors(nn, newNode, nbrs); // printf("Neighbors of newnode obtained: %u\n", (unsigned int)nbrs.size()); Node* node_min = nearNode.get(); float inc_cost = newNode.getIncCost(); float cost_min = nearNode->getAccCost() + inc_cost; // Check the nodes costs to chose the parent with // a lower cost connection std::vector<Action> acts; std::vector<Action> acts_aux; State st; float aux_inc_cost = 0.0; std::vector<State> i_aux; std::vector<State> istates; for (unsigned int i = 0; i < nbrs.size(); i++) { if (&nbrs[i] != nearNode.get() && collisionFree(&nbrs[i], &newNode, acts_aux, i_aux, aux_inc_cost)) { float total_cost = nbrs[i].getAccCost() + aux_inc_cost; if (total_cost < cost_min) { // printf("Changing parent\n"); node_min = &nbrs[i]; cost_min = total_cost; inc_cost = aux_inc_cost; acts = acts_aux; st = i_aux.at(i_aux.size() - 1); istates = i_aux; } } } // node_min->setChildren(newNode); newNode.setParent(node_min); if (node_min != nearNode.get()) { // printf("Connecting parent!!\n"); newNode.setIncCost(inc_cost); newNode.setAccCost(cost_min); newNode.setAction(acts); if (space_->getDimensions() == 2) newNode.getState()->setYaw(st.getYaw()); newNode.getState()->setLv(st.getLinVel()); newNode.getState()->setAv(st.getAngVel()); newNode.setIntermediateStates(istates); // if we have a cost based on the // yaw, lv or av, we will have to recalculate it again later!!! // newNode->setCost(space_->getCost(newNode->getState())); } nn.add(newNode); tree_nodes++; // Rewire the tree /*std::vector<Action> acts2; State st2; for(unsigned int i=0; i<nbrs.size(); i++) { if(nbrs[i]!=node_min && collisionFree(newNode, nbrs[i], acts2, istates, aux_inc_cost)) { posible_rewirings++; //Node* node_aux = new Node(&st_aux2); //node_aux->setAction(acts2); //aux_inc_cost = motionCost(newNode, node_aux); float total_cost = newNode->getAccCost() + aux_inc_cost; if(total_cost < nbrs[i]->getAccCost()) { total_rewirings++; //newNode->setChildren(nbrs[i]); nbrs[i]->setParent(newNode); nbrs[i]->setIncCost(aux_inc_cost); nbrs[i]->setAccCost(total_cost); nbrs[i]->setAction(acts2); st2 = istates.at(istates.size()-1); if(space_->getDimensions() == 2) { nbrs[i]->getState()->setYaw(st2.getYaw()); } nbrs[i]->getState()->setLv(st2.getLinVel()); nbrs[i]->getState()->setAv(st2.getAngVel()); nbrs[i]->setIntermediateStates(istates); //if we have a cost based on the //yaw, lv or av, we will have to recalculate it again later!!! //nbrs[i]->setCost(space_->getCost(nbrs[i]->getState())); } } }*/ float dist = 0.0; solved = space_->isGoalToleranceSatisfied(newNode.getState(), dist); if (solved) { // We re-establish the correct orientation of the goal. // Probably we changed it if we were planning in 2 dimensions. if (space_->getDimensions() == 2) newNode.getState()->setYaw(goalNode->getState()->getYaw()); approxDist = dist; solution = newNode; if (first_sol) { gettimeofday(&first_stop, NULL); double t3 = first_stop.tv_sec + (first_stop.tv_usec / 1000000.0); first_sol_time = (t3 - t1); // Store the first solution to draw samples from it. /*if(useFirstPathBiasing_) { Node* current = solution; while (current != NULL) { State state; copyState(&state, current->getState()); first_path_.push_back(state); current = current->getParent(); } }*/ first_sol = false; } } else if (dist < approxDist) { approxDist = dist; approxSolution = newNode; } } else { // cont_null++; } gettimeofday(&stop, NULL); t2 = stop.tv_sec + (stop.tv_usec / 1000000.0); time = t2 - t1; // printf("Time: %.3f, fin: %.3f\n", time, secs); if (time >= secs) { end = true; } } if (!solved) { printf("\nRRT. Approximate solution found. dist to goal: %.3f\n", approxDist); solution = approxSolution; } else { printf("\nRRT. Solution found in %.6f secs\n", time); } // printf("Number of null states: %u\n", cont_null); // printf("Possible rewirings: %u. Total rewirings peformed: %u\n", posible_rewirings, // total_rewirings); if (storeTree_) { std::vector<Node> nodes; nn.list(nodes); storeTree(nodes); } // Construct the solution path std::vector<RRT::Node> path; Node* current = &solution; path_cost_ = current->getAccCost(); while (current != NULL) { Node node = *current; // copyNode(&node, current); path.push_back(node); current = current->getParent(); path_nodes++; } // Fill statistics stats_.planning_time = time; stats_.first_sol_time = first_sol_time; stats_.total_samples = total_samples; stats_.valid_samples = valid_samples; stats_.goal_samples = goal_samples; stats_.tree_nodes = tree_nodes; stats_.path_nodes = path_nodes; delete current; // delete ini; delete goalNode; // delete solution; // delete approxSolution; // freeTreeMemory(); return path; } void RRT::HalfRRTstar::getNearestNeighbors(KDTree<RRT::Node>& nn, const Node& node, std::vector<Node>& nbrs) { double size = static_cast<double>(nn.size() + 1u); if (useKnearest_) { // k-nearest RRT* unsigned int k = std::ceil(k_rrt_ * log(size)); // printf("k: %u\n", k); nbrs = nn.knearest(node, k); } else { // Nearest in radius RRT* double r = std::min((double)maxRange_, r_rrt_ * std::pow(log(size) / size, 1 / static_cast<double>(space_->getDimensions()))); // printf("Neighbors in Radius: %.3f\n", r); nbrs = nn.radiusSearch(node, r * r); } } void RRT::HalfRRTstar::calculateParamsNearest() { double dim = (double)space_->getDimensions(); // K-nearest if (useKnearest_) { // k_rrt_ = 1.1 * (boost::math::constants::e<double>() + // (boost::math::constants::e<double>() / dim)); k_rrt_ = rewire_factor_ * (exp(1) + (exp(1) / dim)); } else { // Radius float free_volume = space_->getSpaceMeasure() / 2.0; float unitBall = space_->getUnitBallMeasure(); r_rrt_ = rewire_factor_ * 2 * pow((1 + 1 / dim) * (free_volume / unitBall), 1 / dim); // printf("CalculateParamNearest. Dim: %.0f, free_volume: %.3f, unitBall: %.3f, // r_rrt_: %.3f\n", dim, free_volume, unitBall, r_rrt_); } } /*float RRT::RRTstar::motionCost(Node* n1, Node* n2) { if(space_->getDimensions() == 2) { //if(useKnearest_) { float dist = sqrt(distanceFunction(n1, n2)); return ((n1->getCost() + n2->getCost()) / 2.0) * exp(dist); //} else { // return ((n1->getCost() + n2->getCost()) / 2.0); //} } else { return ((n1->getCost() + n2->getCost()) / 2.0) * exp(distanceFunction(n1, n2)); } }*/ <|start_filename|>local_3d_planner/include/local_3d_planner/local_3d_planner.h<|end_filename|> /********************************************************************* * * Author: <NAME> *********************************************************************/ #ifndef __LOCAL_3D_PLANNER_H__ #define __LOCAL_3D_PLANNER_H__ #include <vector> #include <cmath> //#include <upo_local_planner/SimpleLocalPlannerConfig.h> #include <local_3d_planner/odometry_helper_ros.h> // New collision detector based on laser #include <local_3d_planner/collision_detection.h> // we'll take in a path as a vector of poses #include <geometry_msgs/PoseStamped.h> #include <geometry_msgs/Point.h> #include <geometry_msgs/Twist.h> // for some datatypes #include <tf/transform_datatypes.h> //#include <tf/transform_listener.h> #include <tf2_ros/transform_listener.h> #include <tf2_ros/buffer.h> namespace local_3d_planner { /** * @class UpoPlanner * @brief Computes control velocities for a robot given a costmap, a plan, and the robot's * position in the world. */ class Local3DPlanner { public: /** * @brief Constructs a trajectory controller * @param tf A pointer to TransformListener for frame transformations * @param oh A pointer to the odometryhelper functions * @param robot_radius Radius in meters of the sphere that wraps the robot. * @param local_area_radius Radius in meters of the local area considered for the planner * @param footprint_spec A polygon representing the footprint of the robot. (Must be * convex) * @param controller_freq Frequency of the controller * @param max_trans_vel Maximum velocity of translation * @param min_trans_vel Minimun velocity of translation * @param max_rot_vel Maximum velocity of rotation * @param min_rot_vel Minimum velocity of rotation * @param min_in_place_rot_vel minimum rotational velocity for a rotation in place * @param max_trans_acc Maximum acceleration of translation * @param max_rot_acc Maximum acceleration of rotation * @param yaw_goal_tolerance Tolerance in angle distance (rad) to consider that the goal * has been reached * @param xy_goal_tolerance Tolerance in distance (m) to consider that the goal has been * reached * @param wp_tolerance Distance from the robot to the point of the path to to calculate * the velocities to apply * @param sim_time The maximum number of seconds to expand the movement * @param sim_granularity The distance between simulation points should be small enough * that the robot doesn't hit things * @param angular_sim_granularity The distance between simulation points for angular * velocity should be small enough that the robot doesn't hit things * @param dwa try to find a valid command similar to invalid command calculated by the * pure pursuit. */ Local3DPlanner(std::string name, tf2_ros::Buffer* tf, local_3d_planner::OdometryHelperRos* oh, // std::vector<geometry_msgs::Point> footprint_spec, double robot_radius = 0.20, double local_area_radius = 1.0, double controller_freq = 15.0, double max_trans_vel = 0.6, double min_trans_vel = 0.1, double max_rot_vel = 0.5, double min_rot_vel = 0.1, double min_in_place_rot_vel = 0.3, double max_trans_acc = 1.0, double max_rot_acc = 1.0, double yaw_goal_tolerance = 0.1, double xy_goal_tolerance = 0.2, double wp_tolerance = 0.5, double sim_time = 1.0, double sim_granularity = 0.025, double angular_sim_granularity = 0.025, bool dwa = true); /** * @brief Destructs a trajectory controller */ ~Local3DPlanner(); /** * @brief Reconfigures the trajectory planner */ // void reconfigure(SimpleLocalPlannerConfig &cfg); struct vels_ { float vel_x; float vel_y; float vel_th; }; /** * @brief Given the current position, orientation, and velocity of the robot, return a * trajectory to follow * @param global_pose The current pose of the robot in world space * @param global_vel The current velocity of the robot in world space * @param drive_velocities Will be set to velocities to send to the robot base * @return True if a valid command was found, false otherwise */ bool findBestAction(geometry_msgs::PoseStamped global_pose, geometry_msgs::PoseStamped global_vel, geometry_msgs::Twist& cmd_vel); /** * @brief Update the plan that the controller is following * @param new_plan A new plan for the controller to follow * @param compute_dists Wheter or not to compute path/goal distances when a plan is * updated */ bool updatePlan(const std::vector<geometry_msgs::PoseStamped>& new_plan); bool isGoalReached(); void resetGoal(); /** @brief Set the footprint specification of the robot. */ // void setFootprint( std::vector<geometry_msgs::Point> footprint ) { footprint_spec_ = // footprint; } /** @brief Return the footprint specification of the robot. */ // geometry_msgs::Polygon getFootprintPolygon() const { return // costmap_2d::toPolygon(footprint_spec_); } // std::vector<geometry_msgs::Point> getFootprint() const { return footprint_spec_; } private: // std::vector<geometry_msgs::Point> footprint_spec_; ///< @brief The footprint // specification of the robot std::vector<geometry_msgs::PoseStamped> global_plan_; ///< @brief The global path for /// the robot to follow double sim_time_; ///< @brief The number of seconds each trajectory is "rolled-out" double sim_granularity_; ///< @brief The distance between simulation points double angular_sim_granularity_; ///< @brief The distance between angular simulation /// points double acc_lim_trans_, acc_lim_rot_; ///< @brief The acceleration limits of the robot double max_vel_x_, min_vel_x_, max_vel_th_, min_vel_th_, min_in_place_vel_th_; ///< @brief Velocity limits for the controller bool dwa_; double robot_radius_; double local_area_radius_; CollisionDetection* collision_detector_; // Pure pursuit params int wp_index_; bool running_; double start_x_; double start_y_; double start_z_; double start_t_; double goal_x_; double goal_y_; double goal_z_; double goal_t_; double goal_lin_tolerance_; double goal_ang_tolerance_; double wp_tolerance_; bool new_plan_; double controller_freq_; bool goal_reached_; float inline normalizeAngle(float val, float min, float max) { float norm = 0.0; if (val >= min) norm = min + fmod((val - min), (max - min)); else norm = max - fmod((min - val), (max - min)); return norm; } /** * @brief Compute x position based on velocity * @param xi The current x position * @param vx The current x velocity * @param vy The current y velocity * @param theta The current orientation * @param dt The timestep to take * @return The new x position */ inline double computeNewXPosition(double xi, double vx, double vy, double theta, double dt) { return xi + (vx * cos(theta) + vy * cos(M_PI_2 + theta)) * dt; } /** * @brief Compute y position based on velocity * @param yi The current y position * @param vx The current x velocity * @param vy The current y velocity * @param theta The current orientation * @param dt The timestep to take * @return The new y position */ inline double computeNewYPosition(double yi, double vx, double vy, double theta, double dt) { return yi + (vx * sin(theta) + vy * sin(M_PI_2 + theta)) * dt; } /** * @brief Compute orientation based on velocity * @param thetai The current orientation * @param vth The current theta velocity * @param dt The timestep to take * @return The new orientation */ inline double computeNewThetaPosition(double thetai, double vth, double dt) { return thetai + vth * dt; } // compute velocity based on acceleration /** * @brief Compute velocity based on acceleration * @param vg The desired velocity, what we're accelerating up to * @param vi The current velocity * @param a_max An acceleration limit * @param dt The timestep to take * @return The new velocity */ inline double computeNewVelocity(double vg, double vi, double a_max, double dt) { if ((vg - vi) >= 0) { return std::min(vg, vi + a_max * dt); } return std::max(vg, vi - a_max * dt); } void getMaxSpeedToStopInTime(double time, double& vx, double& vy, double& vth) { vx = acc_lim_trans_ * std::max(time, 0.0); vy = 0.0 * std::max(time, 0.0); vth = acc_lim_rot_ * std::max(time, 0.0); } }; }; #endif <|start_filename|>rrt_planners/include/rrt_planners/ros/ValidityChecker3D.h<|end_filename|> #ifndef RRT_CHECKER_ #define RRT_CHECKER_ // RRT library #include <rrt_planners/StateChecker.h> // C++ #include <vector> #include <list> #include <cmath> #include <math.h> #include <iostream> #include <stdio.h> /* printf, fgets */ #include <stdlib.h> /* atof, srand, rand */ #include <exception> // std::exception #include <time.h> /* time */ #include <random> // ROS #include <ros/ros.h> #include <visualization_msgs/Marker.h> #include <geometry_msgs/PointStamped.h> #include <geometry_msgs/Pose2D.h> #include <tf/transform_datatypes.h> #include <tf2_ros/transform_listener.h> #include <tf2_ros/buffer.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <nav_msgs/OccupancyGrid.h> //#include <upo_msgs/PersonPoseUPO.h> //#include <upo_msgs/PersonPoseArrayUPO.h> #include <geometry_msgs/PoseStamped.h> // Features for navigation cost functions //#include <navigation_features/nav_features.h> #include <navigation_features_3d/nav_features3d.h> // Mutex #include <mutex> namespace RRT_ros { class ValidityChecker3D : public RRT::StateChecker { public: ValidityChecker3D(tf2_ros::Buffer* tf, std::vector<geometry_msgs::Point>* footprint, float insc_radius, float size_x, float size_y, float size_z, float res, unsigned int dimensions, int distType, std::string planning_frame); virtual ~ValidityChecker3D(); bool isValid(RRT::State* s) const; bool getValid3dState(RRT::State* s) const; // Distance function between two states float distance(RRT::State* s1, RRT::State* s2) const; float getCost(RRT::State* s); std::vector<float> getFeatures(RRT::State* s); // This two methods are for exploring purposes std::vector<RRT::Node> clusterize_leaves(std::vector<RRT::Node>& leaves) const; RRT::Node evaluate_exploration(std::vector<RRT::Node>& leaves) const; inline std::string getPlanningFrame() { return planning_frame_; } void setGoal(RRT::State* g) { geometry_msgs::PoseStamped goal; // For exploration if (g == NULL) { features_->setGoal(goal); return; } goal.header.frame_id = planning_frame_; goal.header.stamp = ros::Time(); goal.pose.position.x = g->getX(); goal.pose.position.y = g->getY(); goal.pose.position.z = g->getZ(); goal.pose.orientation = tf::createQuaternionMsgFromYaw(g->getYaw()); features_->setGoal(goal); } // Implemented for learning purposes // void setPeople(upo_msgs::PersonPoseArrayUPO p); geometry_msgs::PoseStamped transformPoseTo(geometry_msgs::PoseStamped pose_in, std::string frame_out, bool usetime); bool isQuaternionValid(const geometry_msgs::Quaternion q); void setWeights(std::vector<float> we); /*void setUseLossFunc(bool l, std::vector<geometry_msgs::PoseStamped> path) { navfeatures_->set_use_loss_func(l); navfeatures_->set_demo_path(path); }*/ // Pre-computations needed just before starting planning // void preplanning_computations(); void setInitialTime(ros::Time t) { time_ = t; } private: // features::NavFeatures* navfeatures_; nav3d::Features3D* features_; // const costmap_2d::Costmap2D* loc_costmap_; // const costmap_2d::Costmap2D* glo_costmap_; // bool use_global_costmap_; //tf2_ros::Buffer* tf_; unsigned int dimensions_; int distanceType_; ros::Time time_; std::string planning_frame_; // std::string robot_odom_frame_; ros::Publisher explore_pub_; int rrt_planner_type_; // bool nfe_exploration_; }; } #endif <|start_filename|>local_3d_planner/include/local_3d_planner/local_3d_planner_ros.h<|end_filename|> /********************************************************************* * * Software License Agreement (BSD License) * * Author: <NAME> *********************************************************************/ #ifndef UPO_PLANNER_ROS_H_ #define UPO_PLANNER_ROS_H_ #include <ros/ros.h> #include <costmap_2d/costmap_2d.h> #include <costmap_2d/costmap_2d_ros.h> #include <local_3d_planner/local_3d_planner.h> #include <nav_msgs/Odometry.h> #include <geometry_msgs/PoseStamped.h> #include <geometry_msgs/Twist.h> #include <geometry_msgs/Point.h> #include <tf/transform_datatypes.h> //#include <tf/transform_listener.h> #include <tf2_ros/transform_listener.h> #include <tf2_ros/buffer.h> #include <thread> #include <string> #include <angles/angles.h> #include <nav_core/base_local_planner.h> // Dynamic reconfigure //#include <dynamic_reconfigure/server.h> //#include <simple_local_planner/SimpleLocalPlannerConfig.h> #include <local_3d_planner/odometry_helper_ros.h> namespace local_3d_planner { /** * @class UpoPlannerROS * @brief A ROS wrapper for the trajectory controller that queries the param server to * construct a controller */ class Local3DPlannerROS : public nav_core::BaseLocalPlanner { public: /** * @brief Default constructor for the ros wrapper */ Local3DPlannerROS(); /** * @brief Constructs the ros wrapper * @param name The name to give this instance of the trajectory planner * @param tf A pointer to a transform listener * @param costmap The cost map to use for assigning costs to trajectories */ Local3DPlannerROS(std::string name, tf2_ros::Buffer* tf, costmap_2d::Costmap2DROS* costmap_ros); /** * @brief Constructs the ros wrapper * @param name The name to give this instance of the trajectory planner * @param tf A pointer to a transform listener * @param costmap The cost map to use for assigning costs to trajectories */ void initialize(std::string name, tf2_ros::Buffer* tf, costmap_2d::Costmap2DROS* costmap_ros); /** * @brief Destructor for the wrapper */ ~Local3DPlannerROS(); /** * @brief Given the current position, orientation, and velocity of the robot, * compute velocity commands to send to the base * @param cmd_vel Will be filled with the velocity command to be passed to the robot * base * @return True if a valid trajectory was found, false otherwise */ bool computeVelocityCommands(geometry_msgs::Twist& cmd_vel); /** * @brief Set the plan that the controller is following * @param orig_global_plan The plan to pass to the controller * @return True if the plan was updated successfully, false otherwise */ bool setPlan(const std::vector<geometry_msgs::PoseStamped>& orig_global_plan); /** * @brief Check if the goal pose has been achieved * @return True if achieved, false otherwise */ bool isGoalReached(); bool isInitialized() { return initialized_; } /** @brief Return the inner TrajectoryPlanner object. Only valid after initialize(). */ Local3DPlanner* getPlanner() const { return tc_; } private: /** * @brief Callback to update the local planner's parameters based on dynamic reconfigure */ // void reconfigureCB(SimpleLocalPlannerConfig &config, uint32_t level); Local3DPlanner* tc_; ///< @brief The trajectory controller // tf::TransformListener* tf_; ///< @brief Used for transforming point clouds tf2_ros::Buffer* tf_; std::string global_frame_; ///< @brief The frame in which the controller will run std::string robot_base_frame_; ///< @brief Used as the base frame id of the robot std::vector<geometry_msgs::PoseStamped> global_plan_; // Controller freq double controller_freq_; // Robot Configuration Parameters double max_vel_x_, min_vel_x_; double max_vel_th_, min_vel_th_; double max_trans_acc_; double max_rot_acc_; double min_in_place_vel_th_; double robot_radius_; double local_area_radius_; // Goal tolerance parameters double yaw_goal_tolerance_; double xyz_goal_tolerance_; double wp_tolerance_; double sim_time_; double sim_granularity_; double angular_sim_granularity_; double sim_period_; bool rotating_to_goal_; bool reached_goal_; ros::Publisher g_plan_pub_, l_plan_pub_; // dynamic_reconfigure::Server<SimpleLocalPlannerConfig> *dsrv_; // simple_local_planner::SimpleLocalPlannerConfig default_config_; bool setup_; bool initialized_; local_3d_planner::OdometryHelperRos odom_helper_; // std::vector<geometry_msgs::Point> footprint_spec_; }; }; #endif <|start_filename|>indires_macro_actions/src/Indires_macro_actions_node.cpp<|end_filename|> #include <ros/ros.h> #include <indires_macro_actions/Indires_macro_actions.h> int main(int argc, char** argv) { ros::init(argc, argv, "indires_macro_actions"); ROS_INFO("Starting indires_macro_actions..."); //tf::TransformListener tf(ros::Duration(10)); tf2_ros::Buffer tfBuffer; tf2_ros::TransformListener tfListener(tfBuffer); //upo_nav::UpoNavigation UpoNav(tf, true); Indires_macro_actions macro(&tfBuffer); //(tf, &UpoNav); ros::spin(); return 0; } <|start_filename|>rrt_planners/src/RandomNumbers.cpp<|end_filename|> #include <stdio.h> #include <rrt_planners/RandomNumbers.h> #include <boost/random/lagged_fibonacci.hpp> #include <boost/random/uniform_int.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/once.hpp> #include <boost/scoped_ptr.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/math/constants/constants.hpp> /// @cond IGNORE namespace { /// We use a different random number generator for the seeds of the /// other random generators. The root seed is from the number of /// nano-seconds in the current time, or given by the user. class RNGSeedGenerator { public: RNGSeedGenerator() : someSeedsGenerated_(false) , firstSeed_((boost::uint32_t)(boost::posix_time::microsec_clock::universal_time() - boost::posix_time::ptime(boost::date_time::min_date_time)) .total_microseconds()) , sGen_(firstSeed_) , sDist_(1, 1000000000) , s_(sGen_, sDist_) { } boost::uint32_t firstSeed() { boost::mutex::scoped_lock slock(rngMutex_); return firstSeed_; } void setSeed(boost::uint32_t seed) { boost::mutex::scoped_lock slock(rngMutex_); if (seed > 0) { if (someSeedsGenerated_) { printf("ERROR. Random number generation already started. Changing seed now will not lead to deterministic sampling."); } else { // In this case, since no seeds have been generated yet, so we remember this seed // as the first one. firstSeed_ = seed; } } else { if (someSeedsGenerated_) { printf("WARN. Random generator seed cannot be 0. Ignoring seed."); return; } else { printf("WARN. Random generator seed cannot be 0. Using 1 instead."); seed = 1; } } sGen_.seed(seed); } boost::uint32_t nextSeed() { boost::mutex::scoped_lock slock(rngMutex_); someSeedsGenerated_ = true; return s_(); } private: bool someSeedsGenerated_; boost::uint32_t firstSeed_; boost::mutex rngMutex_; boost::lagged_fibonacci607 sGen_; boost::uniform_int<> sDist_; boost::variate_generator<boost::lagged_fibonacci607&, boost::uniform_int<> > s_; }; static boost::once_flag g_once = BOOST_ONCE_INIT; static boost::scoped_ptr<RNGSeedGenerator> g_RNGSeedGenerator; void initRNGSeedGenerator() { g_RNGSeedGenerator.reset(new RNGSeedGenerator()); } RNGSeedGenerator& getRNGSeedGenerator() { boost::call_once(&initRNGSeedGenerator, g_once); return *g_RNGSeedGenerator; } } // namespace /// @endcond boost::uint32_t RNG::getSeed() { return getRNGSeedGenerator().firstSeed(); } void RNG::setSeed(boost::uint32_t seed) { getRNGSeedGenerator().setSeed(seed); } RNG::RNG() : generator_(getRNGSeedGenerator().nextSeed()) , uniDist_(0, 1) , normalDist_(0, 1) , uni_(generator_, uniDist_) , normal_(generator_, normalDist_) { } double RNG::halfNormalReal(double r_min, double r_max, double focus) { assert(r_min <= r_max); const double mean = r_max - r_min; double v = gaussian(mean, mean / focus); if (v > mean) v = 2.0 * mean - v; double r = v >= 0.0 ? v + r_min : r_min; return r > r_max ? r_max : r; } int RNG::halfNormalInt(int r_min, int r_max, double focus) { int r = (int)floor(halfNormalReal((double)r_min, (double)(r_max) + 1.0, focus)); return (r > r_max) ? r_max : r; } // From: "Uniform Random Rotations", <NAME>, Graphics Gems III, // pg. 124-132 void RNG::quaternion(double value[4]) { double x0 = uni_(); double r1 = sqrt(1.0 - x0), r2 = sqrt(x0); double t1 = 2.0 * boost::math::constants::pi<double>() * uni_(), t2 = 2.0 * boost::math::constants::pi<double>() * uni_(); double c1 = cos(t1), s1 = sin(t1); double c2 = cos(t2), s2 = sin(t2); value[0] = s1 * r1; value[1] = c1 * r1; value[2] = s2 * r2; value[3] = c2 * r2; } // From Effective Sampling and Distance Metrics for 3D Rigid Body Path Planning, by James // Kuffner, ICRA 2004 void RNG::eulerRPY(double value[3]) { value[0] = boost::math::constants::pi<double>() * (-2.0 * uni_() + 1.0); value[1] = acos(1.0 - 2.0 * uni_()) - boost::math::constants::pi<double>() / 2.0; value[2] = boost::math::constants::pi<double>() * (-2.0 * uni_() + 1.0); } <|start_filename|>rrt_planners/include/rrt_planners/ros/ValidityChecker2.h<|end_filename|> #ifndef UPO_RRT_CHECKER2_ #define UPO_RRT_CHECKER2_ //upo RRT library #include <upo_rrt_planners/StateChecker.h> //C++ #include <vector> #include <list> #include <cmath> #include <math.h> #include <iostream> #include <stdio.h> /* printf, fgets */ #include <stdlib.h> /* atof */ #include <exception> // std::exception #include <time.h> /* time */ //ROS #include <ros/ros.h> #include <visualization_msgs/Marker.h> #include <geometry_msgs/PointStamped.h> #include <geometry_msgs/Pose2D.h> #include <tf/transform_datatypes.h> #include <tf/transform_listener.h> #include <nav_msgs/OccupancyGrid.h> //#include <upo_msgs/PersonPoseUPO.h> //#include <upo_msgs/PersonPoseArrayUPO.h> #include <geometry_msgs/PoseStamped.h> //Features for navigation cost functions //#include <navigation_features/nav_features.h> //Mutex #include <mutex> //using namespace std; namespace upo_RRT_ros { class ValidityChecker2 : public upo_RRT::StateChecker { public: //ValidityChecker(bool use_fc_costmap, tf::TransformListener* tf, const costmap_2d::Costmap2D* loc_costmap, const costmap_2d::Costmap2D* glob_costmap, std::vector<geometry_msgs::Point>* footprint, float insc_radius, float size_x, float size_y, unsigned int dimensions, int distType); ValidityChecker2(nav_msgs::OccupancyGrid* costmap, tf::TransformListener* tf, unsigned int dimensions, int distType); ValidityChecker2(tf::TransformListener* tf, unsigned int dimensions, int distType); virtual ~ValidityChecker2(); void updateCostmap(nav_msgs::OccupancyGrid* costmap); bool isValid(upo_RRT::State* s) const; //Distance function between two states float distance(upo_RRT::State* s1, upo_RRT::State* s2) const; float getCost(upo_RRT::State* s); //std::vector<float> getFeatures(upo_RRT::State* s); /*void setGoal(upo_RRT::State* g) { geometry_msgs::PoseStamped goal; goal.header.frame_id = "base_link"; goal.header.stamp = ros::Time(); goal.pose.position.x = g->getX(); goal.pose.position.y = g->getY(); goal.pose.position.z = 0.0; goal.pose.orientation = tf::createQuaternionMsgFromYaw(g->getYaw()); navfeatures_->setGoal(goal); }*/ //Implemented for learning purposes //void setPeople(upo_msgs::PersonPoseArrayUPO p); geometry_msgs::PoseStamped transformPoseTo(geometry_msgs::PoseStamped pose_in, std::string frame_out, bool usetime); bool isQuaternionValid(const geometry_msgs::Quaternion q); std::vector<int> poseToCell(std::vector<float> pose) const; std::vector<float> cellToPose(std::vector<int> cell) const; //void setWeights(std::vector<float> we); /*void setUseLossFunc(bool l, std::vector<geometry_msgs::PoseStamped> path) { navfeatures_->set_use_loss_func(l); navfeatures_->set_demo_path(path); }*/ //Pre-computations needed just before starting planning void preplanning_computations(); void setInitialTime(ros::Time t) { time_ = t; } inline float normalizeAngle(float val, float min, float max) const { float norm = 0.0; if (val >= min) norm = min + fmod((val - min), (max-min)); else norm = max - fmod((min - val), (max-min)); return norm; } private: //features::NavFeatures* navfeatures_; //const costmap_2d::Costmap2D* loc_costmap_; //const costmap_2d::Costmap2D* glo_costmap_; //bool use_global_costmap_; tf::TransformListener* tf_; std::vector<int> costmap_; std::mutex costmap_mutex_; float resolution_; float width_; float height_; std::vector<float> origin_; //The origin of the map [m, m, rad]. This is the real-world pose of the cell (0,0) in the map unsigned int dimensions_; int distanceType_; //bool get_cost_from_costmap_; ros::Time time_; }; } #endif <|start_filename|>rrt_planners/src/ros/ValidityChecker3.cpp<|end_filename|> #include <upo_rrt_planners/ros/ValidityChecker3.h> #include <nav_msgs/Odometry.h> #include <Eigen/Core> #include <ros/console.h> using namespace std; upo_RRT_ros::ValidityChecker3::ValidityChecker3(tf::TransformListener* tf, float resol, int width, int height, unsigned int dimensions, int distType) : StateChecker() { capture_ = new Capture(); cm_resolution_ = resol; //m/cell cm_width_ = width * 2.0; //m cm_height_ = height * 2.0; //m cm_width_pixs_ = cm_width_/cm_resolution_; cm_height_pixs_ = cm_height_/cm_resolution_; //The robot position (center) from the upper-right corner cm_origin_.clear(); cm_origin_.push_back(cm_width_/2.0); //x cm_origin_.push_back(cm_height_/2.0); //y //negative earlier costmap_.clear(); costmap_.assign((cm_width_pixs_*cm_height_pixs_), 1.0); tf_ = tf; dimensions_ = dimensions; distanceType_ = distType; time_ = ros::Time::now(); setup(); } /*upo_RRT_ros::ValidityChecker3::ValidityChecker3(tf::TransformListener* tf, unsigned int dimensions, int distType) : StateChecker() { capture_ = new Capture(); tf_ = tf; dimensions_ = dimensions; distanceType_ = distType; time_ = ros::Time::now(); //Build a default costmap resolution_ = 0.05; //m/cell width_ = 100; //cells height_ = 100; //cells origin_.clear(); origin_.push_back(2.5); //m origin_.push_back(2.5); //m origin_.push_back(0.0); //rad costmap_mutex_.lock(); costmap_.clear(); for(unsigned int i=0; i<(width_*height_); i++) costmap_.push_back((int)0); costmap_mutex_.unlock(); setup(); }*/ upo_RRT_ros::ValidityChecker3::~ValidityChecker3() { delete capture_; } void upo_RRT_ros::ValidityChecker3::setup() { ros::NodeHandle nh; ros::NodeHandle n("~/Validity_checker"); string pc_topic; n.param<string>("pc_topic", pc_topic, std::string("/scan360/point_cloud3")); printf("ValidityChecker3. pc_topic: %s\n", pc_topic.c_str()); int pc_type; n.param<int>("pc_type", pc_type, 2); //1->PointCloud, 2->PointCloud2 printf("ValidityChecker3. pc_type: %i\n", pc_type); n.param<bool>("project_onto_map", project_onto_map_, false); double thres; n.param<double>("path_threshold", thres, 0.0); path_threshold_ = (float)thres; n.param<double>("robot_radius", insc_radius_robot_, 0.30); printf("ValidityChecker3. Robot Radius: %.2f\n", insc_radius_robot_); goal_sub_ = n.subscribe("/rrt_goal", 1, &ValidityChecker3::goalCallback, this); sub_people_ = n.subscribe("/people/navigation", 1, &ValidityChecker3::peopleCallback, this); if(pc_type == 1) //pointCloud sub_pc_ = n.subscribe(pc_topic, 1, &ValidityChecker3::pcCallback, this); else //pointCloud2 sub_pc_ = n.subscribe(pc_topic, 1, &ValidityChecker3::pc2Callback, this); //Network prediction service cnn_client_ = nh.serviceClient<path_prediction::PathPrediction>("path_prediction"); costmap_pub_ = nh.advertise<nav_msgs::OccupancyGrid>("prediction_rewardmap", 1); if(project_onto_map_) setupStaticMap(nh); else setupNoMapProjection(); } void upo_RRT_ros::ValidityChecker3::setupStaticMap(ros::NodeHandle nh) { people_paint_area_ = 25; ros::ServiceClient map_client = nh.serviceClient<nav_msgs::GetMap>("/static_map"); while (! ros::service::waitForService("/static_map",1)){ ROS_INFO("Waiting for map service"); } nav_msgs::GetMap srv; map_client.call(srv); ROS_INFO_STREAM(srv.response.map.info); map_image_ = cv::Mat(srv.response.map.info.height, srv.response.map.info.width,CV_8UC1, cv::Scalar(0)); map_metadata_ =srv.response.map.info; map_resolution_ = (double) map_metadata_.resolution; map_origin_.push_back(map_metadata_.origin.position.x); map_origin_.push_back(map_metadata_.origin.position.y); map_origin_.push_back(tf::getYaw(map_metadata_.origin.orientation)); uint8_t *myData = map_image_.data; for (int i=0;i<srv.response.map.data.size();i++){ if (srv.response.map.data.at(i)==100 || srv.response.map.data.at(i)==-1 ){ } else { map_image_.data[i] = 255; } } dt_mutex_.lock(); distance_transform_ = cv::Mat(map_image_.rows,map_image_.cols,CV_32FC1); cv::distanceTransform(map_image_,distance_transform_,CV_DIST_L1,3); dt_mutex_.unlock(); } void upo_RRT_ros::ValidityChecker3::setupNoMapProjection() { people_paint_area_ = 25; map_image_ = cv::Mat(cm_width_pixs_, cm_height_pixs_, CV_8UC1, cv::Scalar(255)); map_metadata_.resolution = cm_resolution_; map_metadata_.width = cm_width_pixs_; //Cells map_metadata_.height = cm_height_pixs_; //Cells geometry_msgs::Pose orig; orig.position.x = cm_origin_[0]; orig.position.y = cm_origin_[1]; orig.position.z = 0.0; orig.orientation = tf::createQuaternionMsgFromYaw(cm_origin_[2]); map_metadata_.origin = orig; //m dt_mutex_.lock(); distance_transform_ = cv::Mat(map_image_.rows,map_image_.cols,CV_32FC1); //cv::distanceTransform(map_image_,distance_transform_,CV_DIST_L1,3); dt_mutex_.unlock(); } //Update map with point cloud data void upo_RRT_ros::ValidityChecker3::updateDistTransform(){ sensor_msgs::PointCloud temp_pt_cloud; pc_mutex_.lock(); sensor_msgs::PointCloud2 lcloud = laser_cloud_; pc_mutex_.unlock(); if(lcloud.data.size() <= 0) { ROS_WARN("No cloud updated"); return; } bool done = sensor_msgs::convertPointCloud2ToPointCloud(lcloud, temp_pt_cloud); if(!done) ROS_ERROR("\n\nUpdateDistTransform. convertPointCloud2toPoingCloud!!!!!\n"); //Add the laser readings (pointcloud) to the map dt_mutex_.lock(); cv::Mat map_copy = map_image_.clone(); dt_mutex_.unlock(); for (int i =0;i<temp_pt_cloud.points.size();i++){ vector<int> pix; if(project_onto_map_) pix = worldToMap(&(temp_pt_cloud.points[i]),&map_metadata_); else pix = BaseLinkWorldToImg(&(temp_pt_cloud.points[i])); if(pix[0] >= 0.0 && pix[0] < map_metadata_.width && pix[1] >= 0.0 && pix[1] < map_metadata_.height) map_copy.at<unsigned char>(pix[1],pix[0]) = 0; //else //ROS_WARN("\n\nNAV FEATURES. UPDATEDT. pixel out of range!\n"); } //Remove the people detected from the map /*people_mutex_.lock(); std::vector<upo_msgs::PersonPoseUPO> per = people_; people_mutex_.unlock(); for (int i=0; i<per.size(); i++){ geometry_msgs::Point32 temp_point; temp_point.x = per[i].position.x; temp_point.y = per[i].position.y; vector<int> pix; if(project_onto_map_) pix = worldToMap(&temp_point,&map_metadata_); else pix = BaseLinkWorldToImg(&temp_point); if (pix[0] >= 0.0 && pix[0] < map_metadata_.width && pix[1] >= 0.0 && pix[1] < map_metadata_.height) { for (int j = -floor(people_paint_area_/2);j<ceil(people_paint_area_/2);j++){ for (int k = -floor(people_paint_area_/2);k<ceil(people_paint_area_/2);k++){ if (pix[1]+k>=0 && pix[0]+j>=0){ map_copy.at<unsigned char>(pix[1]+k,pix[0]+j) =255; } } } } }*/ cv::Mat dt; try{ cv::distanceTransform(map_copy, dt, CV_DIST_L1, 3); } catch(...){ ROS_ERROR("\n\nValidityChecker3. UpdateDistTrans. cv::distanceTransform!!!!!\n"); } dt_mutex_.lock(); distance_transform_ = dt.clone(); dt_mutex_.unlock(); //gettimeofday(&stop, NULL); //printf("took %lu\n", stop.tv_usec - start.tv_usec); imwrite(ros::package::getPath("upo_rrt_planners").append("/test_write.jpg"), map_copy); } //People callback void upo_RRT_ros::ValidityChecker3::peopleCallback(const upo_msgs::PersonPoseArrayUPO::ConstPtr& msg) { ROS_INFO_ONCE("People received!!"); people_mutex_.lock(); people_ = msg->personPoses; /*if(people_.size() > 0) { people_frame_id_ = msg->header.frame_id; }*/ people_mutex_.unlock(); } //Point_cloud2 callback void upo_RRT_ros::ValidityChecker3::pc2Callback(const sensor_msgs::PointCloud2::ConstPtr& pc_in){ setObstacles(*pc_in); } //Point_cloud callback void upo_RRT_ros::ValidityChecker3::pcCallback(const sensor_msgs::PointCloud::ConstPtr& pc_in){ sensor_msgs::PointCloud2 pc2; bool ok = sensor_msgs::convertPointCloudToPointCloud2(*pc_in, pc2); if(!ok) { ROS_WARN("NavFeatures. Error transforming pointCloud to pointCloud2"); } setObstacles(pc2); } //Goal callback void upo_RRT_ros::ValidityChecker3::goalCallback(const geometry_msgs::PoseStamped::ConstPtr& msg) { ROS_INFO_ONCE("Goal received!!"); setGoal(*msg); } void upo_RRT_ros::ValidityChecker3::setObstacles(sensor_msgs::PointCloud2 obs) { ROS_INFO_ONCE("Obstacles received!\n"); sensor_msgs::PointCloud2 lcloud; obs.header.stamp = ros::Time(); try{ if(project_onto_map_) { if(!pcl_ros::transformPointCloud("/map", obs, lcloud, *tf_)) ROS_WARN("TransformPointCloud failed!!!!!"); } else { if(!pcl_ros::transformPointCloud("/base_link", obs, lcloud, *tf_)) ROS_WARN("TransformPointCloud failed!!!!!"); } } catch (tf::TransformException ex){ ROS_WARN("NAV FEATURES. pcCallback. TransformException: %s", ex.what()); } pc_mutex_.lock(); laser_cloud_ = lcloud; pc_mutex_.unlock(); } //Publish the path planning prediction into a ros costmap for visualization void upo_RRT_ros::ValidityChecker3::publish_costmap_ros(ros::Time t) { //Get the robot coordinates in odom frame tf::StampedTransform transform; try{ tf_->waitForTransform("/odom", "/base_link", ros::Time(0), ros::Duration(1.0)); tf_->lookupTransform("/odom", "/base_link", ros::Time(0), transform); //t } catch (tf::TransformException ex){ ROS_ERROR("Publish_feature_costmap. TF exception: %s",ex.what()); } nav_msgs::OccupancyGrid cmap; cmap.header.frame_id = "odom"; //"base_link"; cmap.header.stamp = ros::Time::now(); //t; //time map_load_time. The time at which the map was loaded cmap.info.map_load_time = cmap.header.stamp; //t; //float32 resolution. The map resolution [m/cell] cmap.info.resolution = cm_resolution_; //0.25 m/cell //uint32 width. Map width [cells] cmap.info.width = cm_height_pixs_; //x //uint32 height. Map height [cells] cmap.info.height = cm_width_pixs_; //y //geometry_msgs/Pose origin. The origin of the map [m, m, rad]. This is the real-world pose of the // cell (0,0) in the map. geometry_msgs::Pose p; p.position.x = transform.getOrigin().x()-(cm_height_/2.0); //x p.position.y = transform.getOrigin().y()-(cm_width_/2.0); //y (substraction initially) p.position.z = 0.0; p.orientation = tf::createQuaternionMsgFromYaw(0.0); //robot_odom_h cmap.info.origin = p; //int8[] cmap.data. The map data, in row-major order, starting with (0,0). Occupancy // probabilities are in the range [0,100]. Unknown is -1. std::vector<signed char> data; // size =(cmap.info.width*cmap.info.height) double cost = 0.0; //for(int i=0; i<cmap.info.height; i++) for(int i=(cmap.info.height-1); i>0; i--) { for(unsigned int j=0; j<cmap.info.width; j++) { float reward = costmap_[i*cm_width_pixs_ + j]>1.0?1.0:costmap_[i*cm_width_pixs_ + j]; //cost = (1 - reward); //Transform cost into the scale[0,100] data.push_back((int)round(reward*100.0)); } } cmap.data = data; costmap_pub_.publish(cmap); } bool upo_RRT_ros::ValidityChecker3::predictionService(vector<int> input, int rows, int cols) { path_prediction::PathPrediction srv; srv.request.input = input; srv.request.input_rows = rows; srv.request.input_cols = cols; if (cnn_client_.call(srv)) { ROS_INFO("Service path prediction called!"); costmap_mutex_.lock(); costmap_.clear(); costmap_ = srv.response.prediction; cm_width_pixs_ = srv.response.pred_cols; cm_height_pixs_ = srv.response.pred_rows; cm_width_ = cm_width_pixs_ * cm_resolution_; cm_height_ = cm_height_pixs_ * cm_resolution_; costmap_mutex_.unlock(); /*printf("Prediction received:\n"); printf("Vector size: %u\n", (unsigned int)costmap_.size()); for(unsigned int i=0; i<cm_height_pixs_; i++) { for(unsigned int j=0; j<cm_width_pixs_; j++) printf("%.2f ", costmap_[i*cm_width_pixs_ + j]); printf("\n"); }*/ return true; } else { ROS_ERROR("Failed to call service path_prediction"); return false; } } //Update the navigation scene and get the path planning prediction void upo_RRT_ros::ValidityChecker3::preplanning_computations() { struct timeval t_ini1, t_fin1; gettimeofday(&t_ini1, NULL); //if(project_onto_map_) updateDistTransform(); //Take point cloud pc_mutex_.lock(); sensor_msgs::PointCloud2 pc2 = laser_cloud_; //base_link pc_mutex_.unlock(); sensor_msgs::PointCloud pc; bool done = sensor_msgs::convertPointCloud2ToPointCloud(pc2, pc); if(!done) ROS_ERROR("\n\nPreplanning computations. convertPointCloud2toPointCloud!!!!!\n"); //Take people people_mutex_.lock(); vector<upo_msgs::PersonPoseUPO> p = people_; //odom people_mutex_.unlock(); //Take goal goal_mutex_.lock(); geometry_msgs::PoseStamped g = goal_; //base_link goal_mutex_.unlock(); //Form current navigation scene vector<int> input = capture_->generateImg(&pc, &p, &g); gettimeofday(&t_fin1, NULL); double secs1 = capture_->timeval_diff(&t_fin1, &t_ini1); /*printf("Nav scene vector generated: \n"); for(unsigned int i=0; i<200; i++) { for(unsigned int j=0; j<200; j++) printf("%i", input[((i*200)+j)]); printf("\n"); }*/ struct timeval t_ini2, t_fin2; gettimeofday(&t_ini2, NULL); //Update the path prediction (costmap) predictionService(input, cm_height_pixs_, cm_width_pixs_); gettimeofday(&t_fin2, NULL); double secs2 = capture_->timeval_diff(&t_fin2, &t_ini2); printf("Preplanning times:\n \tGenerate input: %.3f msecs\n \tGeneratePrediction: %.3f msecs\n", (secs1*1000.0), (secs2*1000.0) ); } vector<upo_RRT::State> upo_RRT_ros::ValidityChecker3::getPredictedPointList() { vector<upo_RRT::State> points; costmap_mutex_.lock(); for(unsigned int i=0; i<cm_height_pixs_; i++) { for(unsigned int j=0; j<cm_width_pixs_; j++) { if(costmap_[i*cm_width_pixs_+j] > path_threshold_) { vector<int> cell; cell.push_back(j); //x cell.push_back(i); //y vector<float> pos = costmapCellToPose(cell); upo_RRT::State state(pos[0], pos[1], 0.0); //x, y, yaw points.push_back(state); } } } costmap_mutex_.unlock(); return points; } // Transform a point in the world to the pixels in the static map vector<int> upo_RRT_ros::ValidityChecker3::worldToMap(geometry_msgs::Point32* world_point,nav_msgs::MapMetaData* map_metadata) const { vector<int> pixels; float x_map = world_point->x - map_metadata->origin.position.x; float y_map = world_point->y - map_metadata->origin.position.y; pixels.push_back((int)floor(x_map/map_metadata->resolution )); pixels.push_back((int)floor(y_map/map_metadata->resolution)); return pixels; } /** * transform point in base link frame (m) to pixel */ vector<int> upo_RRT_ros::ValidityChecker3::BaseLinkWorldToImg(geometry_msgs::Point32* point) const { vector<int> pix; float wx = cm_origin_[0] + point->x; float wy = cm_origin_[1] + point->y; pix.push_back((int)floor(wx/cm_resolution_)); pix.push_back((int)floor(wy/cm_resolution_)); return pix; } vector<int> upo_RRT_ros::ValidityChecker3::poseToCostmapCell(vector<float> pose) const { //Be careful, I'm not taking into account the rotation because is zero usually. //Pose is in robot frame coordinates, and the robot is centered in the costmap int x = floor(fabs((pose[0] + cm_origin_[0])/cm_resolution_)); //x int y = floor(fabs((pose[1] - cm_origin_[1])/cm_resolution_)); //y vector<int> cell; cell.push_back(x); cell.push_back(y); return cell; } vector<float> upo_RRT_ros::ValidityChecker3::costmapCellToPose(vector<int> cell) const { //Be careful, I'm not taking into account the rotation because is zero usually. float x = (cell[0]*cm_resolution_) - cm_origin_[0] + (cm_resolution_/2.0); //- float y = (-1)*((cell[1]*cm_resolution_) - cm_origin_[1] + (cm_resolution_/2.0)); //+ vector<float> pose; pose.push_back(x); pose.push_back(y); return pose; } //This checking is done over the static map (updated with the point cloud or not) bool upo_RRT_ros::ValidityChecker3::isValid(upo_RRT::State* s) const { geometry_msgs::PoseStamped p_in; p_in.header.frame_id = "base_link"; //p_in.header.stamp = ros::Time(0); //this is a problem when the planning time is long. the time stamp should be the time when the rrt started to plan. if((ros::Time::now()-time_).toSec() > 2.0) { //time_ = ros::Time::now(); p_in.header.stamp = ros::Time(0); } else p_in.header.stamp = time_; p_in.pose.position.x = s->getX(); p_in.pose.position.y = s->getY(); p_in.pose.orientation = tf::createQuaternionMsgFromYaw(s->getYaw()); //Transform the coordinates float res; vector<int> pix; geometry_msgs::PoseStamped sm; if(project_onto_map_) { res = map_metadata_.resolution; sm = transformPoseTo(&p_in, string("/map"), false); geometry_msgs::Point32 point; point.x = sm.pose.position.x; point.y = sm.pose.position.y; point.z = 0.0; //pix = worldToMap(&point, &map_metadata_); float x_map = point.x - map_metadata_.origin.position.x; float y_map = point.y - map_metadata_.origin.position.y; pix.push_back((int)floor(x_map/map_metadata_.resolution)); pix.push_back((int)floor(y_map/map_metadata_.resolution)); }else { res = cm_resolution_; //sm = transformPoseTo(&p_in, string("/base_link"), false); geometry_msgs::Point32 point; point.x = s->getX(); //sm.pose.position.x; point.y = s->getY(); //sm.pose.position.y; point.z = 0.0; pix = BaseLinkWorldToImg(&point); } float px = pix[0]; float py = pix[1]; float distance = 0.0; //dt_mutex_.lock(); if (py<0 || px<0 || px > map_image_.cols || py > map_image_.rows) { distance = 0.0; } else{ try{ distance = distance_transform_.at<float>(py,px)*res; } catch(...) { ROS_ERROR("ERROR. IS_VALID. px:%.2f, py:%.2f, distance:%.2f", px, py, distance); distance = 0.0; } } //dt_mutex_.unlock(); // Take into account the robot radius if(distance <= insc_radius_robot_) { return false; }else { return true; } } float upo_RRT_ros::ValidityChecker3::distance(upo_RRT::State* s1, upo_RRT::State* s2) const { float dx = s1->getX() - s2->getX(); float dy = s1->getY() - s2->getY(); //float dist = sqrt(dx*dx + dy*dy); float dist = dx*dx + dy*dy; switch(distanceType_) { case 1: return dist; case 2: return sqrt(dist); case 3: if(dimensions_ == 2) return sqrt(dist); else { //SUM w1*|| Pi+1 - Pi|| + w2*(1-|Qi+1 * Qi|)² float euc_dist = sqrt(dist); tf::Quaternion q1 = tf::createQuaternionFromYaw(s1->getYaw()); tf::Quaternion q2 = tf::createQuaternionFromYaw(s2->getYaw()); float dot_prod = q1.dot(q2); float angle_dist = (1 - fabs(dot_prod))*(1 - fabs(dot_prod)); return 0.7*euc_dist + 0.3*angle_dist; } case 4: if(dimensions_ == 2) return sqrt(dist); else { // Another option /* First, transform the robot location into person location frame: |cos(th) sin(th) 0| Rotation matrix R(th)= |-sin(th) cos(th) 0| | 0 0 1| x' = (xr-xp)*cos(th_p)+(yr-yp)*sin(th_p) y' = (xr-xp)*(-sin(th_p))+(yr-yp)*cos(th_p) */ float x = (s2->getX()-s1->getX())*cos(s1->getYaw()) + (s2->getY()-s1->getY())*sin(s1->getYaw()); float y =-(s2->getX()-s1->getX())*sin(s1->getYaw()) + (s2->getY()-s1->getY())*cos(s1->getYaw()); float alpha = atan2(y, x); return (0.8*sqrt(dist)+0.2*fabs(alpha)); } case 5: if(dimensions_ == 2) return sqrt(dist); else { //UPO. Dist + sum of the angles of both points regarding the intersection line float x = (s2->getX()-s1->getX())*cos(s1->getYaw()) + (s2->getY()-s1->getY())*sin(s1->getYaw()); float y =-(s2->getX()-s1->getX())*sin(s1->getYaw()) + (s2->getY()-s1->getY())*cos(s1->getYaw()); float alpha = atan2(y, x); float beta = s2->getYaw() - alpha; beta = normalizeAngle(beta, -M_PI, M_PI); return (0.6*sqrt(dist)+0.4*(fabs(alpha)+fabs(beta))); } case 6: if(dimensions_ == 2) return sqrt(dist); else { //Paper IROS2015 "Feedback motion planning via non-holonomic RRT* for mobile robots" float x = (s2->getX()-s1->getX())*cos(s1->getYaw()) + (s2->getY()-s1->getY())*sin(s1->getYaw()); float y =-(s2->getX()-s1->getX())*sin(s1->getYaw()) + (s2->getY()-s1->getY())*cos(s1->getYaw()); float alpha = atan2(y, x); float phi = s2->getYaw() - alpha; phi = normalizeAngle(phi, -M_PI, M_PI); float ka = 0.5; float ko = ka/8.0; dist = sqrt(dist); // two options float alpha_prime = atan(-ko*phi); //float alpha_prime = atan(-ko*ko * phi/(dist*dist)); float r = normalizeAngle((alpha-alpha_prime), -M_PI, M_PI); return (sqrt(dist*dist + ko*ko + phi*phi) + ka*fabs(r)); } default: return sqrt(dist); } } float upo_RRT_ros::ValidityChecker3::getCost(upo_RRT::State* s) { //cell.first = x = column, cell.second = y = row vector<float> pose; pose.push_back((float)s->getX()); pose.push_back((float)s->getY()); costmap_mutex_.lock(); vector<int> cell = poseToCostmapCell(pose); //vector<int> cell = BaseLinkWorldToImg(&p); int ind = (cell[1]*cm_width_pixs_) + cell[0]; //if(ind < 0 || ind >= (200*200)) // printf("GetCost. Ind out of range: %i\n", ind); float reward = costmap_[ind]>1.0?1.0:costmap_[ind]; //if(reward == 0.0) // return 10.0; //printf("r: %.2f\t", reward); costmap_mutex_.unlock(); return (1-reward); //*1000.0 //Value between [0,1] } geometry_msgs::PoseStamped upo_RRT_ros::ValidityChecker3::transformPoseTo(geometry_msgs::PoseStamped* pose_in, std::string frame_out, bool usetime) const { geometry_msgs::PoseStamped in = *pose_in; if(!usetime) in.header.stamp = ros::Time(); geometry_msgs::PoseStamped pose_out; try { tf_->transformPose(frame_out.c_str(), in, pose_out); }catch (tf::TransformException ex){ ROS_WARN("ValidityChecker3. TransformException in method transformPoseTo. TargetFrame: %s : %s", frame_out.c_str(), ex.what()); } return pose_out; } bool upo_RRT_ros::ValidityChecker3::isQuaternionValid(const geometry_msgs::Quaternion q) { //first we need to check if the quaternion has nan's or infs if(!std::isfinite(q.x) || !std::isfinite(q.y) || !std::isfinite(q.z) || !std::isfinite(q.w)){ ROS_ERROR("Quaternion has infs!!!!"); return false; } if(std::isnan(q.x) || std::isnan(q.y) || std::isnan(q.z) || std::isnan(q.w)) { ROS_ERROR("Quaternion has nans !!!"); return false; } if(std::fabs(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w - 1) > 0.01) { ROS_ERROR("Quaternion malformed, magnitude: %.3f should be 1.0", (q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w)); return false; } tf::Quaternion tf_q(q.x, q.y, q.z, q.w); //next, we need to check if the length of the quaternion is close to zero if(tf_q.length2() < 1e-6){ ROS_ERROR("Quaternion has length close to zero... discarding."); return false; } //next, we'll normalize the quaternion and check that it transforms the vertical vector correctly tf_q.normalize(); tf::Vector3 up(0, 0, 1); double dot = up.dot(up.rotate(tf_q.getAxis(), tf_q.getAngle())); if(fabs(dot - 1) > 1e-3){ ROS_ERROR("Quaternion is invalid... for navigation the z-axis of the quaternion must be close to vertical."); return false; } return true; } <|start_filename|>indires_macro_actions/include/indires_macro_actions/Indires_macro_actions.h<|end_filename|> //#ifndef MACRO_ACTION_H_ //#define MACRO_ACTION_H_ #include <vector> #include <string> #include <stdlib.h> #include <stdio.h> #include <ros/ros.h> #include <tf/transform_datatypes.h> #include <tf2_ros/transform_listener.h> #include <tf2_ros/buffer.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <angles/angles.h> #include <geometry_msgs/PoseStamped.h> #include <geometry_msgs/PoseWithCovarianceStamped.h> #include <nav_msgs/Odometry.h> #include <geometry_msgs/Twist.h> #include <geometry_msgs/Pose2D.h> #include <move_base_msgs/MoveBaseAction.h> #include <nav_msgs/GetPlan.h> #include <actionlib_msgs/GoalStatusArray.h> #include <actionlib_msgs/GoalStatus.h> #include <actionlib_msgs/GoalID.h> #include <actionlib/server/simple_action_server.h> #include <actionlib/client/simple_action_client.h> #include <indires_macro_actions/NavigateWaypointAction.h> #include <indires_macro_actions/NavigateHomeAction.h> #include <indires_macro_actions/ExplorationAction.h> #include <indires_macro_actions/TeleoperationAction.h> // Probably it is not required //#include <adapted_move_base/move_base.h> //#include <upo_navigation_macro_actions/Yield.h> #include <mutex> //Mutex // Dynamic reconfigure /*#include <dynamic_reconfigure/server.h> #include <dynamic_reconfigure/IntParameter.h> #include <dynamic_reconfigure/StrParameter.h> #include <dynamic_reconfigure/BoolParameter.h> #include <dynamic_reconfigure/DoubleParameter.h> #include <dynamic_reconfigure/Reconfigure.h> #include <dynamic_reconfigure/Config.h> #include <indires_macro_actions/NavigationMacroActionsConfig.h> */ // namespace macroactions { class Indires_macro_actions { public: // enum datatype{INT_TYPE=1, DOUBLE_TYPE=2, BOOL_TYPE=3, STRING_TYPE=4, GROUP_TYPE=5}; Indires_macro_actions(tf2_ros::Buffer* tf); ~Indires_macro_actions(); void navigateWaypointCB(const indires_macro_actions::NavigateWaypointGoal::ConstPtr& goal); void navigateHomeCB(const indires_macro_actions::NavigateHomeGoal::ConstPtr& goal); void explorationCB(const indires_macro_actions::ExplorationGoal::ConstPtr& goal); void teleoperationCB(const indires_macro_actions::TeleoperationGoal::ConstPtr& goal); // void robotPoseCallback(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& // msg); void robotPoseCallback(const nav_msgs::Odometry::ConstPtr& msg); void rrtGoalCallback(const geometry_msgs::PoseStamped::ConstPtr& msg); // void changeParametersNarrowPlaces(); // void changeParametersNarrowPlaces2(); // bool reconfigureParameters(std::string node, std::string param_name, std::string // value, const datatype type); private: // upo_nav::UpoNavigation* UpoNav_; // Dynamic reconfigure // boost::recursive_mutex configuration_mutex_; // dynamic_reconfigure::Server<upo_navigation_macro_actions::NavigationMacroActionsConfig> // *dsrv_; // void reconfigureCB(upo_navigation_macro_actions::NavigationMacroActionsConfig // &config, uint32_t level); void fixFrame(std::string& cad); float normalizeAngle(float val, float min, float max); geometry_msgs::PoseStamped transformPoseTo(geometry_msgs::PoseStamped pose_in, std::string frame_out); // geometry_msgs::PoseStamped approachIT(upo_msgs::PersonPoseUPO* person); // geometry_msgs::PoseStamped approachIT(int id); // ADD CLIENT FOR THE MOVE_BASE SERVER typedef actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> moveBaseClient; moveBaseClient* moveBaseClient_; //tf::TransformListener* tf_listener_; tf2_ros::Buffer* tf_; ros::NodeHandle nh_; ros::NodeHandle nh1_; ros::NodeHandle nh2_; ros::NodeHandle nh3_; ros::NodeHandle nh4_; typedef actionlib::SimpleActionServer<indires_macro_actions::NavigateWaypointAction> NWActionServer; NWActionServer* NWActionServer_; typedef actionlib::SimpleActionServer<indires_macro_actions::NavigateHomeAction> NHActionServer; NHActionServer* NHActionServer_; typedef actionlib::SimpleActionServer<indires_macro_actions::ExplorationAction> ExActionServer; ExActionServer* ExActionServer_; typedef actionlib::SimpleActionServer<indires_macro_actions::TeleoperationAction> TOActionServer; TOActionServer* TOActionServer_; indires_macro_actions::NavigateWaypointFeedback nwfeedback_; indires_macro_actions::NavigateWaypointResult nwresult_; indires_macro_actions::NavigateHomeFeedback nhfeedback_; indires_macro_actions::NavigateHomeResult nhresult_; indires_macro_actions::ExplorationFeedback exfeedback_; indires_macro_actions::ExplorationResult exresult_; indires_macro_actions::TeleoperationFeedback tofeedback_; indires_macro_actions::TeleoperationResult toresult_; // Parameters to be read double control_frequency_; // Wait double secs_to_check_block_; double block_dist_; double secs_to_wait_; /* // Yield Yield* yield_; double secs_to_yield_; std::string yieldmap_; bool robot_inzone_; bool robot_inzone2_; bool person_inzone_; //bool person_inzone2_; boost::mutex rinzone_mutex_; boost::mutex pinzone_mutex_; geometry_msgs::Pose2D rrtgoal_; boost::mutex goal_mutex_; geometry_msgs::Pose2D robot_global_pose_; boost::mutex global_pose_mutex_; bool isYieldDirectionCorrect(); int people_counter_; */ // Assisted steering bool manual_control_; ros::Subscriber pose_sub_; nav_msgs::Odometry odom_pose_; std::mutex pose_mutex_; ros::Subscriber rrtgoal_sub_; geometry_msgs::PoseStamped rrtgoal_; std::mutex goal_mutex_; }; //}; //#endif <|start_filename|>rrt_planners/src/ros/RRT_ros_wrapper3.cpp<|end_filename|> /******************************************************************* * * Software License Agreement (BSD License) * * Author: <NAME> *********************************************************************/ #include <upo_rrt_planners/ros/RRT_ros_wrapper3.h> upo_RRT_ros::RRT_ros_wrapper3::RRT_ros_wrapper3() : tf_(NULL) {} upo_RRT_ros::RRT_ros_wrapper3::RRT_ros_wrapper3(tf::TransformListener* tf) { tf_ = tf; rrt_planner_ = NULL; setup(); } upo_RRT_ros::RRT_ros_wrapper3::~RRT_ros_wrapper3() { delete checker_; delete rrt_planner_; } void upo_RRT_ros::RRT_ros_wrapper3::setup() { //boost::recursive_mutex::scoped_lock ecl(configuration_mutex_); ros::NodeHandle private_nh("~/RRT_ros_wrapper3"); private_nh.param<int>("rrt_planner_type", rrt_planner_type_, 1); printf("RRT_ros_wrapper3. rrt_planner_type = %i\n", rrt_planner_type_); //RRT double aux; private_nh.param<double>("rrt_solve_time", aux, 0.5); solve_time_ = (float)aux; printf("RRT_ros_wrapper3. rrt_solve_time = %.2f\n", solve_time_); private_nh.param<double>("rrt_goal_bias", aux, 0.1); goal_bias_ = (float)aux; printf("RRT_ros_wrapper3. goal_bias = %.2f\n", goal_bias_); private_nh.param<double>("rrt_max_insertion_dist", aux, 0.2); max_range_ = (float) aux; printf("RRT_ros_wrapper3. max_range_ = %.2f\n", max_range_); double robot_radius; private_nh.param<double>("robot_radius", robot_radius, 0.4); printf("RRT_ros_wrapper3. robot_radius = %.2f\n", robot_radius); //RRT* if(rrt_planner_type_ == 2 || rrt_planner_type_ >= 4) { private_nh.param<bool>("rrtstar_use_k_nearest", rrtstar_use_k_nearest_, true); printf("RRT_ros_wrapper3. rrtstar_use_k_nearest = %i\n", rrtstar_use_k_nearest_); private_nh.param<bool>("rrtstar_first_path_biasing", rrtstar_first_path_biasing_, false); printf("RRT_ros_wrapper3. rrtstar_first_path_biasing_ = %i\n", rrtstar_first_path_biasing_); private_nh.param<double>("rrtstar_first_path_bias", aux, 0.5); rrtstar_first_path_bias_ = (float)aux; printf("RRT_ros_wrapper3. rrtstar_first_path_bias_ = %.2f\n", rrtstar_first_path_bias_); private_nh.param<double>("rrtstar_first_path_stddev", aux, 0.8); rrtstar_first_path_stddev_bias_ = (float)aux; printf("RRT_ros_wrapper3. rrtstar_first_path_stddev_bias_ = %.2f\n", rrtstar_first_path_stddev_bias_); private_nh.param<double>("rrtstar_rewire_factor", aux, 1.1); rrtstar_rewire_factor_ = (float)aux; printf("RRT_ros_wrapper3. rrtstar_rewire_factor_ = %.2f\n", rrtstar_rewire_factor_); } //All private_nh.param<bool>("full_path_biasing", full_path_biasing_, false); printf("RRT_ros_wrapper3. full_path_biasing_ = %i\n", full_path_biasing_); private_nh.param<double>("full_path_stddev", aux, 1.2); full_path_stddev_ = (float)aux; printf("RRT_ros_wrapper3. full_path_stddev_ = %.2f\n", full_path_stddev_); private_nh.param<double>("full_path_bias", aux, 0.8); full_path_bias_ = (float)aux; printf("RRT_ros_wrapper3. full_path_bias_ = %.2f\n", full_path_bias_); //GMM biasing //private_nh.param<bool>("gmm_biasing", gmm_biasing_, false); //private_nh.param<double>("gmm_bias", aux, 0.95); //gmm_bias_ = (float)aux; //CNN path prediction biasing private_nh.param<bool>("prediction_biasing", prediction_biasing_, false); private_nh.param<double>("prediction_bias", aux, 0.8); prediction_bias_ = (float)aux; private_nh.param<double>("prediction_stddev", aux, 0.3); prediction_stddev_ = (float)aux; //if RRT or RRT* are kinodynamics //float kino_linAcc, kino_angAcc; //int kino_minControlSteps, kino_maxControlSteps; //int kino_steeringType; if(rrt_planner_type_ > 2) { private_nh.param<double>("kino_time_step", aux, 0.067); kino_timeStep_ = (float)aux; private_nh.param<int>("kino_min_control_steps", kino_minControlSteps_, 5); private_nh.param<int>("kino_max_control_steps", kino_maxControlSteps_, 30); //Robot accelerations private_nh.param<double>("kino_linear_acc", aux, 0.6); kino_linAcc_ = (float)aux; private_nh.param<double>("kino_angular_acc", aux, 1.57); kino_angAcc_ = (float)aux; private_nh.param<int>("kino_steering_type", kino_steeringType_, 1); } //Steering parameters for kinodynamic planning private_nh.param<double>("kino_steer_kp", aux, 0.5); float kino_steer_kp = (float)aux; printf("RRT_ros_wrapper3. kino_steer_kp = %.2f\n", kino_steer_kp); private_nh.param<double>("kino_steer_kv", aux, 3.0); float kino_steer_kv = (float)aux; printf("RRT_ros_wrapper3. kino_steer_kv = %.2f\n", kino_steer_kv); private_nh.param<double>("kino_steer_ka", aux, 2.0); float kino_steer_ka = (float)aux; printf("RRT_ros_wrapper3. kino_steer_ka = %.2f\n", kino_steer_ka); private_nh.param<double>("kino_steer_ko", aux, 0.25); float kino_steer_ko = (float)aux; printf("RRT_ros_wrapper3. kino_steer_ko = %.2f\n", kino_steer_ko); //RRT State Space private_nh.param<int>("rrt_dimensions", dimensions_, 2); printf("RRT_ros_wrapper3. rrt_dimensions = %i\n", dimensions_); private_nh.param<double>("rrt_size_x", aux, 5.0); size_x_ = (float)aux; printf("RRT_ros_wrapper3. size_x_ = %.2f\n", size_x_); private_nh.param<double>("rrt_size_y", aux, 5.0); size_y_ = (float)aux; printf("RRT_ros_wrapper3. size_y_ = %.2f\n", size_y_); private_nh.param<double>("rrt_xy_resolution", aux, 0.05); xy_res_ = (float)aux; private_nh.param<double>("rrt_yaw_resolution", aux, 0.02); yaw_res_ = (float)aux; private_nh.param<double>("rrt_min_linear_vel", aux, 0.0); min_lin_vel_ = (float)aux; private_nh.param<double>("rrt_max_linear_vel", aux, 0.5); max_lin_vel_ = (float)aux; private_nh.param<double>("rrt_lin_vel_resolution", aux, 0.05); lin_vel_res_ = (float)aux; private_nh.param<double>("rrt_max_angular_vel", aux, 0.5); max_ang_vel_ = (float)aux; private_nh.param<double>("rrt_min_angular_vel", aux, 0.3); min_ang_vel_ = (float)aux; private_nh.param<double>("rrt_ang_vel_resolution", aux, 0.1); ang_vel_res_ = (float)aux; private_nh.param<double>("rrt_goal_xy_tol", aux, 0.15); goal_xy_tol_ = (float)aux; private_nh.param<double>("rrt_goal_th_tol", aux, 0.15); goal_th_tol_ = (float)aux; private_nh.param<int>("rrt_nn_type", nn_params_, 1); //int distanceType; private_nh.param<int>("distance_type", distanceType_, 1); private_nh.param<int>("motion_cost_type", motionCostType_, 1); //Visualization private_nh.param<bool>("visualize_rrt_tree", visualize_tree_, false); private_nh.param<bool>("visualize_nav_costmap", visualize_costmap_, false); private_nh.param<bool>("show_rrt_statistics", show_statistics_, false); //private_nh.param<double>("equal_path_percentage", aux, 0.5); //equal_path_percentage_ = (float)aux; private_nh.param<double>("rrt_interpolate_path_dist", aux, 0.05); interpolate_path_distance_ = (float)aux; private_nh.param<bool>("show_intermediate_states", show_intermediate_states_, false); //path_smoothing private_nh.param<bool>("path_smoothing", path_smoothing_, true); private_nh.param<int>("smoothing_samples", smoothing_samples_, 15); //if the planner is an RRT, the nav costmap can not be visualized if(rrt_planner_type_ == 1 || rrt_planner_type_ == 3) visualize_costmap_ = false; ros::NodeHandle n; /*if(visualize_costmap_) { printf("Visualize_costmap = true, initializing costmap_pub\n"); costmap_pub_ = n.advertise<nav_msgs::OccupancyGrid>("rrt_costmap", 5); }*/ //gmm_costmap_pub_ = n.advertise<nav_msgs::OccupancyGrid>("gmm_costmap", 5); if(visualize_tree_) { printf("Visualize_tree = true, initializing tree_pub\n"); tree_pub_ = n.advertise<visualization_msgs::Marker>("rrt_tree", 5); } rrt_goal_pub_ = n.advertise<geometry_msgs::PoseStamped>("rrt_goal", 5); local_goal_pub_ = n.advertise<visualization_msgs::Marker>("rrt_goal_marker", 5); path_points_pub_ = n.advertise<visualization_msgs::Marker>("rrt_path_points", 5); path_interpol_points_pub_ = n.advertise<visualization_msgs::Marker>("rrt_path_interpol_points", 5); if(size_x_ != size_y_) { ROS_ERROR("X size and Y size of the State Space has to be equal!!!"); return; } //costmap_sub_ = n.subscribe<nav_msgs::OccupancyGrid>("cnn_costmap", 1, &RRT_ros_wrapper2::costmapCallback, this); inscribed_radius_ = (float)robot_radius; circumscribed_radius_ = (float)robot_radius; checker_ = new ValidityChecker3(tf_, xy_res_, size_x_, size_y_, dimensions_, distanceType_); //GMM sampling service client //gmm_samples_client_ = n.serviceClient<gmm_sampling::GetApproachGMMSamples>("/gmm_sampling/GetApproachGMMSamples"); //GMM probs service client //gmm_probs_client_ = n.serviceClient<gmm_sampling::GetApproachGMMProbs>("/gmm_sampling/GetApproachGMMProbs"); switch(rrt_planner_type_) { // ----- simple RRT -------------------- case 1: printf("\n-------- Using simple RRT planner ----------\n"); rrt_planner_ = new upo_RRT::SimpleRRT(); rrt_planner_->as<upo_RRT::SimpleRRT>()->setMaxRange(max_range_); break; // ----- simple RRT* -------------------- case 2: printf("\n-------- Using simple RRT* planner ----------\n"); rrt_planner_ = new upo_RRT::SimpleRRTstar(); rrt_planner_->as<upo_RRT::SimpleRRTstar>()->setMaxRange(max_range_); rrt_planner_->as<upo_RRT::SimpleRRTstar>()->set_useKnearest(rrtstar_use_k_nearest_); rrt_planner_->as<upo_RRT::SimpleRRTstar>()->set_useFirstPathBiasing(rrtstar_first_path_biasing_); rrt_planner_->as<upo_RRT::SimpleRRTstar>()->setRewireFactor(rrtstar_rewire_factor_); if(rrtstar_first_path_biasing_ && !full_path_biasing_) { rrt_planner_->as<upo_RRT::SimpleRRTstar>()->setPathBias(rrtstar_first_path_bias_); rrt_planner_->as<upo_RRT::SimpleRRTstar>()->setPathBias_stddev(rrtstar_first_path_stddev_bias_); } break; // ----- kinodynamic RRT -------------------- case 3: printf("\n-------- Using Kinodynamic RRT planner ----------\n"); rrt_planner_ = new upo_RRT::RRT(); rrt_planner_->as<upo_RRT::RRT>()->setTimeStep(kino_timeStep_); rrt_planner_->as<upo_RRT::RRT>()->setControlSteps(kino_minControlSteps_, kino_maxControlSteps_); rrt_planner_->as<upo_RRT::RRT>()->setRobotAcc(kino_linAcc_, kino_angAcc_); break; // ----- kinodynamic RRT* -------------------- case 4: printf("\n-------- Using Kinodynamic RRT* planner ----------\n"); rrt_planner_ = new upo_RRT::RRTstar(); rrt_planner_->as<upo_RRT::RRTstar>()->setMaxRange(max_range_); rrt_planner_->as<upo_RRT::RRTstar>()->setTimeStep(kino_timeStep_); rrt_planner_->as<upo_RRT::RRTstar>()->setControlSteps(kino_minControlSteps_, kino_maxControlSteps_); rrt_planner_->as<upo_RRT::RRTstar>()->setRobotAcc(kino_linAcc_, kino_angAcc_); rrt_planner_->as<upo_RRT::RRTstar>()->set_useKnearest(rrtstar_use_k_nearest_); rrt_planner_->as<upo_RRT::RRTstar>()->set_useFirstPathBiasing(rrtstar_first_path_biasing_); rrt_planner_->as<upo_RRT::RRTstar>()->setRewireFactor(rrtstar_rewire_factor_); rrt_planner_->as<upo_RRT::RRTstar>()->setSteeringType(kino_steeringType_); rrt_planner_->as<upo_RRT::RRTstar>()->setMotionCostType(motionCostType_); if(rrtstar_first_path_biasing_ && !full_path_biasing_) { rrt_planner_->as<upo_RRT::RRTstar>()->setPathBias(rrtstar_first_path_bias_); rrt_planner_->as<upo_RRT::RRTstar>()->setPathBias_stddev(rrtstar_first_path_stddev_bias_); } break; // ----- kinodynamic simplified RRT* -------------------- case 5: printf("\n-------- Using Kinodynamic simplified RRT* planner ----------\n"); rrt_planner_ = new upo_RRT::HalfRRTstar(); rrt_planner_->as<upo_RRT::HalfRRTstar>()->setMaxRange(max_range_); rrt_planner_->as<upo_RRT::HalfRRTstar>()->setTimeStep(kino_timeStep_); rrt_planner_->as<upo_RRT::HalfRRTstar>()->setControlSteps(kino_minControlSteps_, kino_maxControlSteps_); rrt_planner_->as<upo_RRT::HalfRRTstar>()->setRobotAcc(kino_linAcc_, kino_angAcc_); rrt_planner_->as<upo_RRT::HalfRRTstar>()->set_useKnearest(rrtstar_use_k_nearest_); rrt_planner_->as<upo_RRT::HalfRRTstar>()->set_useFirstPathBiasing(rrtstar_first_path_biasing_); rrt_planner_->as<upo_RRT::HalfRRTstar>()->setRewireFactor(rrtstar_rewire_factor_); rrt_planner_->as<upo_RRT::HalfRRTstar>()->setSteeringType(kino_steeringType_); rrt_planner_->as<upo_RRT::HalfRRTstar>()->setMotionCostType(motionCostType_); if(rrtstar_first_path_biasing_ && !full_path_biasing_) { rrt_planner_->as<upo_RRT::HalfRRTstar>()->setPathBias(rrtstar_first_path_bias_); rrt_planner_->as<upo_RRT::HalfRRTstar>()->setPathBias_stddev(rrtstar_first_path_stddev_bias_); } break; default: printf("\n-------- Using default simple RRT planner ----------\n"); rrt_planner_ = new upo_RRT::SimpleRRT(); rrt_planner_->as<upo_RRT::SimpleRRT>()->setMaxRange(max_range_); } rrt_planner_->setup(checker_, nn_params_, dimensions_, size_x_, size_y_, xy_res_, yaw_res_, min_lin_vel_, max_lin_vel_, lin_vel_res_, max_ang_vel_, ang_vel_res_, kino_steer_kp, kino_steer_kv, kino_steer_ka, kino_steer_ko); rrt_planner_->setGoalBias(goal_bias_); rrt_planner_->setGoalTolerance(goal_xy_tol_, goal_th_tol_); rrt_planner_->setStoreTree(visualize_tree_); if(full_path_biasing_) { rrt_planner_->setFullBiasing(full_path_biasing_); rrt_planner_->setPathBias(full_path_bias_); rrt_planner_->setPathBias_stddev(full_path_stddev_); //rrt_planner_->setGoalBias(0.0); } if(prediction_biasing_) { rrt_planner_->setFullBiasing(prediction_biasing_); rrt_planner_->setPathBias(prediction_bias_); rrt_planner_->setPathBias_stddev(prediction_stddev_); } //Planning server ros::NodeHandle nhandle("RRT_ros_wrapper3"); plan_srv_ = nhandle.advertiseService("makeRRTPlan", &upo_RRT_ros::RRT_ros_wrapper3::makePlanService, this); //Planning with costmap //planCostmap_srv_ = nhandle.advertiseService("makeRRTPlanCostmap", &upo_RRT_ros::RRT_ros_wrapper2::makePlanCostmapService, this); } /*void upo_RRT_ros::RRT_ros_wrapper2::costmapCallback(const nav_msgs::OccupancyGrid::ConstPtr& msg) { nav_msgs::OccupancyGrid og; og.header = msg->header; og.info = msg->info; og.data = msg->data; checker_->updateCostmap(&og); size_x_ = (msg->info.width * msg->info.resolution); //m size_y_ = (msg->info.height * msg->info.resolution); //m }*/ std::vector<geometry_msgs::PoseStamped> upo_RRT_ros::RRT_ros_wrapper3::RRT_plan(geometry_msgs::Pose2D start, geometry_msgs::Pose2D goal, float start_lin_vel, float start_ang_vel) { if(!rrt_planner_->setStartAndGoal(start.x, start.y, start.theta, goal.x, goal.y, goal.theta)){ ROS_ERROR("RRT_plan. Goal state is not valid!!!"); rrt_plan_.clear(); geometry_msgs::PoseStamped p; p.pose.position.x = -100.0; p.pose.position.y = -100.0; p.pose.position.z = -100.0; rrt_plan_.push_back(p); return rrt_plan_; } upo_RRT::State* g = NULL; //if we use costs /*if(rrt_planner_type_ == 2 || rrt_planner_type_ >= 4) { //if(!use_fc_costmap_) { //Set the goal in the state checker g = new upo_RRT::State(goal.x, goal.y, goal.theta); checker_->setGoal(g); //} }*/ g = new upo_RRT::State(goal.x, goal.y, goal.theta); checker_->setGoal2(g); geometry_msgs::PoseStamped rg; rg.header.frame_id = "base_link"; rg.header.stamp = ros::Time(); rg.pose.position.x = goal.x; rg.pose.position.y = goal.y; rg.pose.position.z = 0.0; rg.pose.orientation = tf::createQuaternionMsgFromYaw(goal.theta); rrt_goal_pub_.publish(rg); //visualize rrt goal visualization_msgs::Marker marker; marker.header.frame_id = "base_link"; //robot_base_frame_ = "/base_link" marker.header.stamp = ros::Time::now(); marker.ns = "basic_shapes"; marker.id = 0; marker.type = visualization_msgs::Marker::ARROW; marker.action = visualization_msgs::Marker::ADD; marker.pose.position.x = goal.x; marker.pose.position.y = goal.y; marker.pose.position.z = 0.5; marker.pose.orientation = tf::createQuaternionMsgFromYaw(goal.theta); // Set the scale of the marker marker.scale.x = 0.7; marker.scale.y = 0.15; marker.scale.z = 0.15; // Set the color -- be sure to set alpha to something non-zero! marker.color.r = 1.0f; marker.color.g = 0.5f; marker.color.b = 0.0f; marker.color.a = 1.0; marker.lifetime = ros::Duration(); // Publish the marker local_goal_pub_.publish(marker); ros::Time time = ros::Time::now(); rrt_planner_->setInitialActionState(start_lin_vel, 0.0, start_ang_vel, 1); //-------- GET THE RRT PATH ------------------------------ //boost::recursive_mutex::scoped_lock ecl(configuration_mutex_); //computations needed before starting planning //In this case, we calculate the gaussian functions over the current people checker_->setInitialTime(time); checker_->preplanning_computations(); //sleep(2); if(visualize_costmap_) checker_->publish_costmap_ros(time); if(prediction_biasing_) setPathPredictionBiasing(); std::vector<upo_RRT::Node> path; switch(rrt_planner_type_) { case 1: path = rrt_planner_->as<upo_RRT::SimpleRRT>()->solve(solve_time_); break; case 2: path = rrt_planner_->as<upo_RRT::SimpleRRTstar>()->solve(solve_time_); break; case 3: path = rrt_planner_->as<upo_RRT::RRT>()->solve(solve_time_); break; case 4: path = rrt_planner_->as<upo_RRT::RRTstar>()->solve(solve_time_); break; case 5: path = rrt_planner_->as<upo_RRT::HalfRRTstar>()->solve(solve_time_); break; default: path = rrt_planner_->as<upo_RRT::SimpleRRT>()->solve(solve_time_); } if(path.empty()) { printf("Wrapper3. Path planned is empty!!!\n"); return rrt_plan_; } if(show_statistics_) { upo_RRT::Planner::statistics stats = rrt_planner_->getStatistics(); printf("Planning time: %.4f secs\n", stats.planning_time); printf("First sol time: %.4f secs\n", stats.first_sol_time); printf("Total samples: %u \n", stats.total_samples); printf("Valid samples: %u \n", stats.valid_samples); printf("Goal samples: %u \n", stats.goal_samples); printf("Tree nodes: %u \n", stats.tree_nodes); printf("Path nodes: %u \n\n", stats.path_nodes); } // Build the path in ROS format rrt_plan_.clear(); geometry_msgs::PoseStamped pose; pose.header.frame_id = "base_link"; pose.header.stamp = time; int cont = 0; for(int i=path.size()-1; i>=0; --i) { pose.pose.position.z = 0.1; pose.pose.position.x = (double)path[i].getState()->getX(); pose.pose.position.y = (double)path[i].getState()->getY(); try { pose.pose.orientation = tf::createQuaternionMsgFromYaw((double)path[i].getState()->getYaw()); } catch (tf::TransformException ex) { printf("TransformException in getting sol path: %s",ex.what()); } rrt_plan_.push_back(pose); if(show_intermediate_states_ && path[i].hasIntermediateStates()) { std::vector<upo_RRT::State>* inter = path[i].getIntermediateStates(); for(unsigned int j=0; j<inter->size(); j++) { //if(i != 0 || j != (inter.size()-1)) { pose.pose.position.x = (double)inter->at(j).getX(); pose.pose.position.y = (double)inter->at(j).getY(); try { pose.pose.orientation = tf::createQuaternionMsgFromYaw((double)inter->at(j).getYaw()); } catch (tf::TransformException ex) { printf("TransformException in getting sol path: %s",ex.what()); } pose.pose.position.z = 0.0; rrt_plan_.push_back(pose); //} } } cont++; } // Build the command list in ROS format std::vector<geometry_msgs::Twist> vels; if(rrt_planner_type_ > 2) { unsigned int cont = 0; unsigned int c = 0; for(unsigned int i=path.size()-1; i>0; i--) { std::vector<upo_RRT::Action>* acts = path[i].getAction(); float vx, vy, vth; unsigned int steps; for(unsigned int j=0; j<acts->size(); j++) { acts->at(j).getAction(vx, vy, vth, steps); geometry_msgs::Twist v; v.linear.x = vx; v.linear.y = vy; v.angular.z = vth; vels.push_back(v); cont+=steps; //printf("Action %u. lv: %.2f, av: %.2f, Steps: %u\n", c, vx, vth, steps); } c++; } printf("Approximated Total Path Time: %.3f secs\n", kino_timeStep_*cont); } //Visualize the tree nodes of the resulting path /*visualization_msgs::Marker points; points.header.frame_id = "base_link"; //robot_base_frame_; points.header.stamp = time; points.ns = "basic_shapes"; points.id = 0; points.type = visualization_msgs::Marker::SPHERE_LIST; points.action = visualization_msgs::Marker::ADD; points.pose.position.x = 0.0; points.pose.position.y = 0.0; points.pose.position.z = 0.1; points.scale.x = 0.12; points.scale.y = 0.12; points.color.r = 0.0f; points.color.g = 1.0f; points.color.b = 0.0f; points.color.a = 1.0; points.lifetime = ros::Duration(); for(unsigned int i=0; i<rrt_plan_.size(); i++) { geometry_msgs::Point p = rrt_plan_[i].pose.position; points.points.push_back(p); } path_points_pub_.publish(points); */ if(visualize_tree_) visualizeTree(time); //if(visualize_costmap_) // checker_->publish_costmap_ros(time); //reconf_mutex_.unlock(); if(interpolate_path_distance_ > 0.0) { rrt_plan_ = path_interpolation(rrt_plan_, interpolate_path_distance_); //Visualize the interpolated path nodes /*visualization_msgs::Marker mar; mar.header.frame_id = "base_link"; //robot_base_frame_; mar.header.stamp = time; mar.ns = "basic_shapes"; mar.id = 2; mar.type = visualization_msgs::Marker::SPHERE_LIST; mar.action = visualization_msgs::Marker::ADD; mar.pose.position.x = 0.0; mar.pose.position.y = 0.0; mar.pose.position.z = 0.05; mar.scale.x = 0.08; mar.scale.y = 0.08; mar.color.r = 0.0f; mar.color.g = 1.0f; mar.color.b = 1.0f; mar.color.a = 1.0; mar.lifetime = ros::Duration(); for(unsigned int i=0; i<rrt_plan_.size(); i++) { geometry_msgs::Point p = rrt_plan_[i].pose.position; mar.points.push_back(p); } path_interpol_points_pub_.publish(mar); */ } if(path_smoothing_) { rrt_plan_ = simple_path_smoothing(&rrt_plan_); } if(g) delete g; //rrt_planner_->freeTreeMemory(); //delete rrt_planner_; return rrt_plan_; } bool upo_RRT_ros::RRT_ros_wrapper3::makePlanService(upo_rrt_planners::MakePlan::Request &req, upo_rrt_planners::MakePlan::Response &res) { //printf("Wrapper. MakePlanService called!\n"); geometry_msgs::PoseStamped p = req.goal; p = checker_->transformPoseTo(&p, string("base_link"), false); checker_->setGoal(p); geometry_msgs::Pose2D start; start.x = 0.0; start.y = 0.0; start.theta = 0.0; geometry_msgs::Pose2D goal; goal.x = p.pose.position.x; goal.y = p.pose.position.y; goal.theta = tf::getYaw(p.pose.orientation); std::vector<geometry_msgs::PoseStamped> path = RRT_plan(start, goal, 0.0, 0.0); //Visualize the tree nodes of the resulting path if(!path.empty()) { visualization_msgs::Marker points; points.header.frame_id = "base_link"; //robot_base_frame_; points.header.stamp = ros::Time::now(); points.ns = "basic_shapes"; points.id = 0; points.type = visualization_msgs::Marker::SPHERE_LIST; points.action = visualization_msgs::Marker::ADD; points.pose.position.x = 0.0; points.pose.position.y = 0.0; points.pose.position.z = 0.1; points.scale.x = 0.12; points.scale.y = 0.12; points.color.r = 0.0f; points.color.g = 1.0f; points.color.b = 0.0f; points.color.a = 1.0; points.lifetime = ros::Duration(); for(unsigned int i=0; i<path.size(); i++) { geometry_msgs::Point p = path[i].pose.position; points.points.push_back(p); } path_points_pub_.publish(points); } else return false; res.ok = true; res.path = path; return true; } /*bool upo_RRT_ros::RRT_ros_wrapper2::makePlanCostmapService(upo_rrt_planners::MakePlanCostmap::Request &req, upo_rrt_planners::MakePlanCostmap::Response &res) { checker_->updateCostmap(&req.costmap); printf("MakePlanCostmap called!!!!!\n"); geometry_msgs::PoseStamped p = req.goal; //printf("makePlanService. x:%.2f, y:%.2f, z:%.2f, w:%.2f\n", p.pose.orientation.x, p.pose.orientation.y, p.pose.orientation.z, p.pose.orientation.w); p = checker_->transformPoseTo(p, "base_link", false); geometry_msgs::Pose2D start; start.x = 0.0; start.y = 0.0; start.theta = 0.0; geometry_msgs::Pose2D goal; goal.x = p.pose.position.x; goal.y = p.pose.position.y; goal.theta = tf::getYaw(p.pose.orientation); std::vector<geometry_msgs::PoseStamped> path = RRT_plan(start, goal, 0.0, 0.0); //Visualize the tree nodes of the resulting path if(!path.empty()) { visualization_msgs::Marker points; points.header.frame_id = "base_link"; //robot_base_frame_; points.header.stamp = ros::Time::now(); points.ns = "basic_shapes"; points.id = 0; points.type = visualization_msgs::Marker::SPHERE_LIST; points.action = visualization_msgs::Marker::ADD; points.pose.position.x = 0.0; points.pose.position.y = 0.0; points.pose.position.z = 0.1; points.scale.x = 0.12; points.scale.y = 0.12; points.color.r = 0.0f; points.color.g = 1.0f; points.color.b = 0.0f; points.color.a = 1.0; points.lifetime = ros::Duration(); for(unsigned int i=0; i<path.size(); i++) { geometry_msgs::Point p = path[i].pose.position; points.points.push_back(p); } path_points_pub_.publish(points); } res.ok = true; res.path = path; return true; }*/ std::vector<geometry_msgs::PoseStamped> upo_RRT_ros::RRT_ros_wrapper3::simple_path_smoothing(std::vector<geometry_msgs::PoseStamped>* path) { int s = smoothing_samples_; if(path->size() < (s+1)) return *path; std::vector<geometry_msgs::PoseStamped> newpath; //Add first point newpath.push_back(path->at(0)); //Smoothing for(unsigned int i=1; i<path->size()-1; i++) { newpath.push_back(path->at(i)); geometry_msgs::Pose2D p; p.x = 0.0; p.y = 0.0; p.theta = 0.0; int cont = 0; int half = (int)floor(s/2 + 0.5); if(i < half) half = i; else if((i+half) > path->size()) half = path->size()-i; for(unsigned int j=i-half; j<(i+half); j++) { p.x += path->at(j).pose.position.x; p.y += path->at(j).pose.position.y; p.theta += tf::getYaw(path->at(j).pose.orientation); cont++; } //printf("i:%i, Half:%i, Cont: %i\n", i, half, cont); p.x = p.x/cont; p.y = p.y/cont; p.theta = normalizeAngle((p.theta/cont), -M_PI, M_PI); newpath[i].pose.position.x = p.x; newpath[i].pose.position.y = p.y; newpath[i].pose.orientation = tf::createQuaternionMsgFromYaw(p.theta); } //Add last point newpath.push_back(path->at(path->size()-1)); return newpath; } std::vector<geometry_msgs::PoseStamped> upo_RRT_ros::RRT_ros_wrapper3::path_interpolation(std::vector<geometry_msgs::PoseStamped> path, float step_distance) { std::vector<geometry_msgs::PoseStamped> pathnew; for(unsigned int i=0; i<path.size()-1; i++) { geometry_msgs::PoseStamped p1 = path[i]; geometry_msgs::PoseStamped p2 = path[i+1]; float dx = p2.pose.position.x - p1.pose.position.x; float dy = p2.pose.position.y - p1.pose.position.y; float dis = sqrt(dx*dx + dy*dy); geometry_msgs::PoseStamped intermediate = p1; pathnew.push_back(p1); float steps = dis/step_distance; //printf("Steps: %.2f\n", steps); if(steps > 1.0) { intermediate.header = path[0].header; intermediate.pose.position.z = p1.pose.position.z; for(unsigned int i=1; i<steps; i++) { float xr = (dx)*cos(0.0) + (dy)*sin(0.0); float yr =-(dx)*sin(0.0) + (dy)*cos(0.0); float tr = atan2(yr, xr); float newx = intermediate.pose.position.x + step_distance*cos(tr); float newy = intermediate.pose.position.y + step_distance*sin(tr); intermediate.pose.position.x = newx; intermediate.pose.position.y = newy; intermediate.pose.orientation = tf::createQuaternionMsgFromYaw(tr); pathnew.push_back(intermediate); dx = p2.pose.position.x - intermediate.pose.position.x; dy = p2.pose.position.y - intermediate.pose.position.y; } } } pathnew.push_back(path[path.size()-1]); //printf("Path interpolation. Original size: %u, new size: %u\n", (unsigned int)path.size(), (unsigned int)pathnew.size()); return pathnew; } void upo_RRT_ros::RRT_ros_wrapper3::setBiasingPath(std::vector<geometry_msgs::PoseStamped>* path_to_follow) { if(full_path_biasing_) { //Transform path_to_be_followed into a vector of RRT states std::vector<upo_RRT::State> state_path; for(unsigned int i=0; i<path_to_follow->size(); i++) { geometry_msgs::PoseStamped p = path_to_follow->at(i); float x = p.pose.position.x; float y = p.pose.position.y; float yaw = tf::getYaw(p.pose.orientation); upo_RRT::State state(x, y, yaw); state_path.push_back(state); } rrt_planner_->setBiasingPath(&state_path); } } void upo_RRT_ros::RRT_ros_wrapper3::setPathPredictionBiasing() { vector<upo_RRT::State> points = checker_->getPredictedPointList(); //printf("\nRRT_rosWrapper3. SetPathPredictionBiasing. path size: %u\n\n", (unsigned int)points.size()); rrt_planner_->setBiasingPath(&points); } float upo_RRT_ros::RRT_ros_wrapper3::get_rrt_planning_radius() { return size_x_; } void upo_RRT_ros::RRT_ros_wrapper3::visualizeTree(ros::Time t) { std::vector<upo_RRT::State> tree_states = rrt_planner_->getTree(); visualization_msgs::Marker edges; edges.header.frame_id = "base_link"; edges.header.stamp = t; edges.ns = "rrt_tree"; edges.id = 0; edges.type = visualization_msgs::Marker::LINE_LIST; edges.action = visualization_msgs::Marker::ADD; edges.pose.position.x = 0.0; edges.pose.position.y = 0.0; edges.pose.position.z = 0.05; edges.scale.x = 0.03; edges.scale.y = 0.03; edges.color.r = 1.0f; edges.color.g = 1.0f; edges.color.b = 1.0f; edges.color.a = 0.3; edges.lifetime = ros::Duration(); //printf("VisualizeTree. tree nodes: %u\n", (unsigned int)tree_states.size()); for(unsigned int i=0; i<tree_states.size()-1; i=i+2) { geometry_msgs::Point p1; p1.x = tree_states[i].getX(); p1.y = tree_states[i].getY(); p1.z = 0.05; geometry_msgs::Point p2; p2.x = tree_states[i+1].getX(); p2.y = tree_states[i+1].getY(); p2.z = 0.05; edges.points.push_back(p1); edges.points.push_back(p2); } tree_pub_.publish(edges); } /* void upo_RRT_ros::RRT_ros_wrapper3::publish_feature_costmap(ros::Time t) { //Get the robot coordinates in odom frame tf::StampedTransform transform; try{ tf_->waitForTransform("/odom", "/base_link", ros::Time(0), ros::Duration(1.0)); tf_->lookupTransform("/odom", "/base_link", t, transform); } catch (tf::TransformException ex){ ROS_ERROR("Publish_feature_costmap. TF exception: %s",ex.what()); } nav_msgs::OccupancyGrid cmap; cmap.header.frame_id = "odom"; //"base_link"; cmap.header.stamp = t; //time map_load_time. The time at which the map was loaded cmap.info.map_load_time = t; double cell_size = 0.25; // m/cell //float32 resolution. The map resolution [m/cell] cmap.info.resolution = cell_size; //0.25 m/cell //uint32 width. Map width [cells] cmap.info.width = (size_x_*2.0)/cell_size; //uint32 height. Map height [cells] cmap.info.height = (size_y_*2.0)/cell_size; //geometry_msgs/Pose origin. The origin of the map [m, m, rad]. This is the real-world pose of the // cell (0,0) in the map. geometry_msgs::Pose p; p.position.x = transform.getOrigin().x()-size_x_; p.position.y = transform.getOrigin().y()-size_y_; p.position.z = 0.0; p.orientation = tf::createQuaternionMsgFromYaw(0.0); //robot_odom_h cmap.info.origin = p; //int8[] cmap.data. The map data, in row-major order, starting with (0,0). Occupancy // probabilities are in the range [0,100]. Unknown is -1. std::vector<signed char> data; // size =(cmap.info.width*cmap.info.height) double cost = 0.0; for(int i=0; i<cmap.info.height; i++) { for(unsigned int j=0; j<cmap.info.width; j++) { geometry_msgs::PoseStamped robotp; robotp.header.stamp = ros::Time(); robotp.header.frame_id = "odom"; robotp.pose.position.x = (transform.getOrigin().x()-size_x_ + cell_size*j) + (cell_size/2.0); //i robotp.pose.position.y = (transform.getOrigin().y()-size_y_ + cell_size*i) + (cell_size/2.0); //j robotp.pose.position.z = 0.0; tf::quaternionTFToMsg(transform.getRotation(), robotp.pose.orientation); geometry_msgs::PoseStamped robot_frame_pose = checker_->transformPoseTo(robotp, "base_link", true); upo_RRT::State* s = new upo_RRT::State(robot_frame_pose.pose.position.x, robot_frame_pose.pose.position.y, tf::getYaw(robot_frame_pose.pose.orientation)); cost = checker_->getCost(s); //printf("publish_feature_map. x:%.2f, y:%.2f, cost:%.2f\n", robotp.pose.position.x, robotp.pose.position.y, cost); //Transform cost into the scale[0,100] data.push_back((int)round(cost*100.0)); } } cmap.data = data; costmap_pub_.publish(cmap); }*/ float upo_RRT_ros::RRT_ros_wrapper3::get_path_cost() { return rrt_planner_->getCost(); } <|start_filename|>local_3d_planner/include/local_3d_planner/collision_detection.h<|end_filename|> #ifndef COLLISION_DETECTION_H_ #define COLLISION_DETECTION_H_ #include <vector> #include <string> #include <stdlib.h> #include <stdio.h> #include <ros/ros.h> //#include <tf/transform_listener.h> #include <tf2_ros/transform_listener.h> #include <tf2_ros/buffer.h> #include <sensor_msgs/LaserScan.h> #include <sensor_msgs/Range.h> #include <geometry_msgs/Twist.h> #include <geometry_msgs/Point.h> #include <geometry_msgs/TransformStamped.h> #include <local_3d_planner/odometry_helper_ros.h> // Dynamic reconfigure //#include <dynamic_reconfigure/server.h> //#include <upo_local_planner/AssistedSteeringConfig.h> //#include <boost/thread/mutex.hpp> //Mutex #include <mutex> #include <sys/time.h> #include <navigation_features_3d/nav_features3d.h> namespace local_3d_planner { class CollisionDetection { public: struct range { std::string id; float range; float polar_angle; float polar_dist; float fov; float min_dist; float max_dist; }; // CollisionDetection(); CollisionDetection(std::string name, tf2_ros::Buffer* tf, local_3d_planner::OdometryHelperRos* oh, double max_lv, double max_av, double lin_acc, double ang_acc, double sim_t, double r_radius, double local_radius, double granularity); ~CollisionDetection(); void setup(std::string name); /** * @brief Generate and check a single trajectory * @param cvx The current x velocity of the robot * @param cvy The current y velocity of the robot * @param cvth The current angular velocity of the robot * @param tvx The x velocity used to seed the trajectory * @param tvy The y velocity used to seed the trajectory * @param tvth The theta velocity used to seed the trajectory * @param px will be filled with the final x point of the trajectory (robot frame) * @param py will be filled with the final y point of the trajectory (robot frame) * @param pz will be filled with the final z point of the trajectory (robot frame) * @param pth will be filled with the final th point of the trajectory (robot frame) * @return True if the trajectory is legal, false otherwise */ bool checkTraj(double cvx, double cvy, double cvth, double tvx, double tvy, double tvth, double& px, double& py, double& pz, double& pth); void saturateVelocities(geometry_msgs::Twist* twist); void laserCallback(const sensor_msgs::LaserScan::ConstPtr& msg); std::vector<geometry_msgs::Point> laser_polar2euclidean(sensor_msgs::LaserScan* scan); void rangeCallback(const sensor_msgs::Range::ConstPtr& msg); void initiateRanges(); bool inRangeCollision(float x, float y); bool inLaserCollision(float x, float y, std::vector<geometry_msgs::Point>* scanpoints); bool inCollision(float x, float y, std::vector<geometry_msgs::Point>* scanpoints); private: float inline normalizeAngle(float val, float min, float max) { float norm = 0.0; if (val >= min) norm = min + fmod((val - min), (max - min)); else norm = max - fmod((min - val), (max - min)); return norm; } /** * @brief Compute x position based on velocity * @param xi The current x position * @param vx The current x velocity * @param vy The current y velocity * @param theta The current orientation * @param dt The timestep to take * @return The new x position */ inline double computeNewXPosition(double xi, double vx, double vy, double theta, double dt) { return xi + (vx * cos(theta) + vy * cos(M_PI_2 + theta)) * dt; } /** * @brief Compute y position based on velocity * @param yi The current y position * @param vx The current x velocity * @param vy The current y velocity * @param theta The current orientation * @param dt The timestep to take * @return The new y position */ inline double computeNewYPosition(double yi, double vx, double vy, double theta, double dt) { return yi + (vx * sin(theta) + vy * sin(M_PI_2 + theta)) * dt; } /** * @brief Compute orientation based on velocity * @param thetai The current orientation * @param vth The current theta velocity * @param dt The timestep to take * @return The new orientation */ inline double computeNewThetaPosition(double thetai, double vth, double dt) { return thetai + vth * dt; } // compute velocity based on acceleration /** * @brief Compute velocity based on acceleration * @param vg The desired velocity, what we're accelerating up to * @param vi The current velocity * @param a_max An acceleration limit * @param dt The timestep to take * @return The new velocity */ inline double computeNewVelocity(double vg, double vi, double a_max, double dt) { if ((vg - vi) >= 0) { return std::min(vg, vi + a_max * dt); } return std::max(vg, vi - a_max * dt); } nav3d::Features3D* features_; //tf::TransformListener* tf_; tf2_ros::Buffer* tf_; std::string odom_topic_; std::string base_frame_; OdometryHelperRos* odom_helper_; double max_lin_vel_; double max_ang_vel_; double max_lin_acc_; double max_ang_acc_; double sim_time_; double robot_radius_; double robot_radius_aug_; double local_radius_; double granularity_; float max_lv_var_; float max_av_var_; tf::Stamped<tf::Pose> robot_vel_; // in case a laser range finder is also used bool use_laser_; ros::Subscriber laser_sub_; sensor_msgs::LaserScan laser_scan_; std::mutex laser_mutex_; // Sonar ranges employed bool use_range_; int num_ranges_; std::vector<std::string> range_topics_; std::vector<std::string> range_frames_; std::vector<ros::Subscriber> range_subscribers_; // ros::Subscriber range_sub_; std::vector<range> ranges_; std::mutex range_mutex_; std::vector<bool> ranges_initiated_; bool ranges_ready_; // Dynamic reconfigure // boost::recursive_mutex configuration_mutex_; // dynamic_reconfigure::Server<assisted_steering::AssistedSteeringConfig> *dsrv_; // void reconfigureCB(assisted_steering::AssistedSteeringConfig &config, uint32_t // level); }; } #endif <|start_filename|>navigation_features_3d/include/navigation_features_3d/nav_features3d.h<|end_filename|> //#ifndef NAV_FEATURES_ //#define NAV_FEATURES_ #include <math.h> #include <vector> #include <ctime> // ROS #include <ros/ros.h> #include <ros/package.h> #include <visualization_msgs/Marker.h> #include <visualization_msgs/MarkerArray.h> #include <geometry_msgs/PointStamped.h> #include <geometry_msgs/Pose2D.h> //#include <tf/transform_datatypes.h> #include <tf2_ros/transform_listener.h> #include <tf/transform_listener.h> #include <tf2_ros/buffer.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <std_msgs/Float32.h> #include <geometry_msgs/PoseStamped.h> //#include <sensor_msgs/PointCloud.h> #include <sensor_msgs/PointCloud2.h> #include <sensor_msgs/point_cloud_conversion.h> //#include <laser_geometry/laser_geometry.h> #include <nav_msgs/Odometry.h> #include <pcl_ros/transforms.h> // Eigen #include <Eigen/Geometry> #include <Eigen/Dense> // PCL /* //This solves the problem of compiling pcl search with C++11 #include <pcl/search/impl/search.hpp> #ifndef PCL_NO_PRECOMPILE #include <pcl/impl/instantiate.hpp> #include <pcl/point_types.h> PCL_INSTANTIATE(Search, PCL_POINT_TYPES) #endif // PCL_NO_PRECOMPILE */ #include <pcl/common/transforms.h> #include <pcl/common/pca.h> #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <pcl_ros/point_cloud.h> #include "pcl_ros/transforms.h" #include <pcl/register_point_struct.h> #include <pcl/io/pcd_io.h> #include <pcl/conversions.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/kdtree/kdtree.h> #include <pcl/search/kdtree.h> #include <pcl/search/pcl_search.h> #include <pcl/features/normal_3d.h> #include <pcl/segmentation/extract_clusters.h> #include <pcl/ModelCoefficients.h> #include <pcl/sample_consensus/method_types.h> #include <pcl/sample_consensus/model_types.h> #include <pcl/sample_consensus/sac.h> #include <pcl/sample_consensus/ransac.h> #include <pcl/sample_consensus/sac_model_perpendicular_plane.h> #include <pcl/segmentation/sac_segmentation.h> #include <pcl/filters/voxel_grid_covariance.h> //#include <pcl/octree/octree.h> //#include <pcl/octree/octree_search.h> //#include <pcl/search/octree.h> //#include <pcl/search/search.h> // Mutex #include <mutex> // OpenCV //#include <opencv2/opencv.hpp> //#include "opencv2/core/core.hpp" //#include "opencv2/highgui/highgui.hpp" //#include "opencv2/imgproc/imgproc.hpp" // Service msg #include "pcl_filters/GetFilteredPC.h" #include "pcl_filters/ChangeCropboxSize.h" // Dynamic reconfigure //#include <dynamic_reconfigure/server.h> //#include <3D_navigation_features/nav_featuresConfig.h> using namespace std; namespace nav3d { class Features3D { public: struct exp_goal { geometry_msgs::Point p; float num_points; int visits; }; Features3D(); Features3D(string name, tf2_ros::Buffer* tf, float size_x, float size_y, float size_z); Features3D(string name, tf2_ros::Buffer* tf, vector<geometry_msgs::Point>* footprint, float size_x, float size_y, float size_z); ~Features3D(); void setParams(string name); bool poseValid(geometry_msgs::PoseStamped* s); // bool poseValid2(geometry_msgs::PoseStamped* s); // bool poseValid3(geometry_msgs::PoseStamped* s); bool pose3dValid(geometry_msgs::PoseStamped* s); float getCost(geometry_msgs::PoseStamped* s); vector<float> getFeatures(geometry_msgs::PoseStamped* s); vector<vector<int> > clusterize_leaves(vector<geometry_msgs::Point>* points, float radius); int evaluate_leaves(vector<geometry_msgs::Point>* points, vector<float>* pcosts, string frame, float radius); float evaluate_leaf(geometry_msgs::Point* p, float rrt_cost, string frame, float radius, float& npoints); // float evaluate_leaf_nfe_bfe(geometry_msgs::Point* p, float rrt_cost, std::string // frame, float radius, float &npoints); float no_return_cost(geometry_msgs::PoseStamped* p); // std::vector<float> getPathFeatureCount(vector<geometry_msgs::PoseStamped>* path); // void goalCallback(const geometry_msgs::PoseStamped::ConstPtr& msg); void cloudCallback(const sensor_msgs::PointCloud2::ConstPtr& msg); void poseCallback(const nav_msgs::OdometryConstPtr& msg); // Feature: Distance to the goal float goalDistFeature(geometry_msgs::PoseStamped* s); // Feature: inclination in pitch and roll // float inclinationFeature(geometry_msgs::PoseStamped* s); // Feature: roughness of the terrain // float roughnessFeature(geometry_msgs::PoseStamped* s); // Feature: Distance to the closest obstacle (based on costmaps or map image) // float obstacleDistFeature(geometry_msgs::PoseStamped* s); geometry_msgs::PoseStamped transformPoseTo(geometry_msgs::PoseStamped pose_in, string frame_out, bool usetime); bool isQuaternionValid(const geometry_msgs::Quaternion q); // pcl::normAngle(float alpha) //norm angle [-PI, PI] float normalizeAngle(float val, float min, float max); void setWeights(vector<float> we); void setGoal(geometry_msgs::PoseStamped g); inline string getRobotBaseFrame() { return robot_base_frame_; }; inline string getRobotOdomFrame() { return robot_odom_frame_; }; // void setObstacles(sensor_msgs::PointCloud2 obs); // void setScenario(sensor_msgs::PointCloud2 obs, geometry_msgs::PoseStamped goal); // Services // bool setWeightsService(navigation_features::SetWeights::Request &req, // navigation_features::SetWeights::Response &res); // bool initializeWeightsService(navigation_features::InitWeights::Request &req, // navigation_features::InitWeights::Response &res); // bool setLossService(navigation_features::SetLossCost::Request &req, // navigation_features::SetLossCost::Response &res); // bool setScenarioService(navigation_features::SetScenario::Request &req, // navigation_features::SetScenario::Response &res); // bool isPoseValidService(navigation_features::PoseValid::Request &req, // navigation_features::PoseValid::Response &res); // bool getFeatureCountService(navigation_features::GetFeatureCount::Request &req, // navigation_features::GetFeatureCount::Response &res); private: //tf::TransformListener* tf1_listener_; tf2_ros::TransformListener* tf_listener_; tf2_ros::Buffer* tf_; string name_; ros::Subscriber cloud_sub_; ros::ServiceClient exp_client_; string exp_pc_service_name_; // pcl::KdTreeFLANN<pcl::PointXYZ>* kdtree_exp_; pcl::PointCloud<pcl::PointXYZ>::Ptr exp_cloud_; pcl::VoxelGridCovariance<pcl::PointXYZ>* vgc_; float cell_size_; vector<pcl::PointXYZ> wall_points_; ros::Publisher wall_pub_; vector<geometry_msgs::Point> frontier_points_; ros::Publisher frontier_pub_; ros::Publisher visited_pub_; sensor_msgs::PointCloud2 cloud_; pcl::PointCloud<pcl::PointXYZ> pcl_cloud_; pcl::PointCloud<pcl::PointXYZ> wall_cloud_; ros::Publisher pc_wall_pub_; vector<float> num_points_; float num_points_saturation_; // mutex cloudMutex_; pcl::KdTreeFLANN<pcl::PointXYZ>* kdtree_; mutex tree_mutex_; // boost::mutex tree_mutex_; float robot_radius_; // const double octree_resolution_ = 128.0; // float octree_resolution_; // pcl::octree::OctreePointCloudSearch<pcl::PointXYZ> octree_(); // pcl::search::Octree<pcl::PointXYZ>* octree_; // pcl::octree::OctreePointCloudSearch<pcl::PointXYZ>::Ptr octree_; // pcl::octree::OctreePointCloudSearch<pcl::PointXYZ> octree_; //esto da error // pcl::PCA<pcl::PointXYZ>* pca_; double pitch_high_; // double pitch_high2_; double pitch_low_; // double pitch_low2_; double roll_high_; // double roll_high2_; double roll_low_; // double roll_low2_; double roughness_; int min_points_allowed_; double pitch_high2_; double pitch_low2_; double roll_high2_; double roll_low2_; int feature_set_; vector<geometry_msgs::Point>* myfootprint_; string robot_base_frame_; string robot_odom_frame_; string robot_odom_topic_; ros::Subscriber pose_sub_; geometry_msgs::PoseStamped robot_pose_; vector<geometry_msgs::PoseStamped> robot_traj_; mutex pose_mutex_; // boost::mutex pose_mutex_; geometry_msgs::PoseStamped goal_; float max_planning_dist_; float size_x_; float size_y_; float size_z_; float current_size_; float max_size_; float min_size_; ros::NodeHandle nh_; // ros::Subscriber goal_sub_; vector<float> w_; vector<float> wexp_; ros::Publisher explore_pub_; bool nfe_; // Neirest Frontier Exploration bool bfe_; // Biggest Frontier Exploration float threshold_frontier_; bool adaptative_threshold_; vector<exp_goal> exp_regions_; float exp_min_dist_goals_; float numpoint_cost_limit_; float percentage_limit_; bool first_rrt_time_; float rrt_time_; ros::Publisher rrt_time_pub_; bool visited_region_enabled_; bool remove_wall_frontier_enabled_; bool variable_size_enabled_; bool visualize_visited_reg_; bool visualize_frontiers_; bool visualize_wall_leaves_; // Dynamic reconfigure // boost::recursive_mutex configuration_mutex_; // mutex configuration_mutex_; // dynamic_reconfigure::Server<3D_navigation_features::nav_featuresConfig> *dsrv_; // void reconfigureCB(3D_navigation_features::nav_featuresConfig &config, uint32_t // level); }; } //#endif <|start_filename|>rrt_planners/src/ros/ValidityChecker.cpp<|end_filename|> #include <upo_rrt_planners/ros/ValidityChecker.h> #include <nav_msgs/Odometry.h> #include <Eigen/Core> #include <ros/console.h> upo_RRT_ros::ValidityChecker::ValidityChecker(bool use_fc_costmap, tf::TransformListener* tf, std::vector<geometry_msgs::Point>* footprint, float insc_radius, float size_x, float size_y, float res, unsigned int dimensions, int distType) : StateChecker() { get_cost_from_costmap_ = use_fc_costmap; //if(!get_cost_from_costmap_) { //printf("Initialization of nav_features\n"); navfeatures_ = new features::NavFeatures(tf, footprint, insc_radius, size_x, size_y, res); /*}else { printf("----Using cost function to build a costmap-----\n"); loc_costmap_ = loc_costmap; glo_costmap_ = glob_costmap; tf_ = tf; }*/ dimensions_ = dimensions; distanceType_ = distType; time_ = ros::Time::now(); } upo_RRT_ros::ValidityChecker::~ValidityChecker() { delete navfeatures_; } bool upo_RRT_ros::ValidityChecker::isValid(upo_RRT::State* s) const { geometry_msgs::PoseStamped p_in; p_in.header.frame_id = "base_link"; //p_in.header.stamp = ros::Time(0); //this is a problem when the planning time is long. the time stamp should be the time when the rrt started to plan. if((ros::Time::now()-time_).toSec() > 2.0) { //time_ = ros::Time::now(); p_in.header.stamp = ros::Time(0); } else p_in.header.stamp = time_; p_in.pose.position.x = s->getX(); p_in.pose.position.y = s->getY(); p_in.pose.orientation = tf::createQuaternionMsgFromYaw(s->getYaw()); if(!get_cost_from_costmap_) { //If we calculate the validity in a normal way return navfeatures_->poseValid(&p_in); } else { //we check the validity checking the value of the costmap built by using the RRT* cost function printf("\nERROR!! Validity checking by using costmap is not available!!!!\n"); return false; } } void upo_RRT_ros::ValidityChecker::preplanning_computations() { if(!get_cost_from_costmap_) navfeatures_->update(); } float upo_RRT_ros::ValidityChecker::distance(upo_RRT::State* s1, upo_RRT::State* s2) const { float dx = s1->getX() - s2->getX(); float dy = s1->getY() - s2->getY(); //float dist = sqrt(dx*dx + dy*dy); float dist = dx*dx + dy*dy; switch(distanceType_) { case 1: return dist; case 2: return sqrt(dist); case 3: if(dimensions_ == 2) return sqrt(dist); else { //SUM w1*|| Pi+1 - Pi|| + w2*(1-|Qi+1 * Qi|)² float euc_dist = sqrt(dist); tf::Quaternion q1 = tf::createQuaternionFromYaw(s1->getYaw()); tf::Quaternion q2 = tf::createQuaternionFromYaw(s2->getYaw()); float dot_prod = q1.dot(q2); float angle_dist = (1 - fabs(dot_prod))*(1 - fabs(dot_prod)); //printf("eu_dist: %.2f, angle_dist: %.3f, dist: %.3f\n", euc_dist, angle_dist, 0.8*euc_dist + 0.2*angle_dist); return 0.7*euc_dist + 0.3*angle_dist; } case 4: if(dimensions_ == 2) return sqrt(dist); else { // Another option /* First, transform the robot location into person location frame: |cos(th) sin(th) 0| Rotation matrix R(th)= |-sin(th) cos(th) 0| | 0 0 1| x' = (xr-xp)*cos(th_p)+(yr-yp)*sin(th_p) y' = (xr-xp)*(-sin(th_p))+(yr-yp)*cos(th_p) */ float x = (s2->getX()-s1->getX())*cos(s1->getYaw()) + (s2->getY()-s1->getY())*sin(s1->getYaw()); float y =-(s2->getX()-s1->getX())*sin(s1->getYaw()) + (s2->getY()-s1->getY())*cos(s1->getYaw()); float alpha = atan2(y, x); return (0.8*sqrt(dist)+0.2*fabs(alpha)); } case 5: if(dimensions_ == 2) return sqrt(dist); else { //UPO. Dist + sum of the angles of both points regarding the intersection line float x = (s2->getX()-s1->getX())*cos(s1->getYaw()) + (s2->getY()-s1->getY())*sin(s1->getYaw()); float y =-(s2->getX()-s1->getX())*sin(s1->getYaw()) + (s2->getY()-s1->getY())*cos(s1->getYaw()); float alpha = atan2(y, x); float beta = s2->getYaw() - alpha; beta = navfeatures_->normalizeAngle(beta, -M_PI, M_PI); return (0.6*sqrt(dist)+0.4*(fabs(alpha)+fabs(beta))); } case 6: if(dimensions_ == 2) return sqrt(dist); else { //Paper IROS2015 "Feedback motion planning via non-holonomic RRT* for mobile robots" float x = (s2->getX()-s1->getX())*cos(s1->getYaw()) + (s2->getY()-s1->getY())*sin(s1->getYaw()); float y =-(s2->getX()-s1->getX())*sin(s1->getYaw()) + (s2->getY()-s1->getY())*cos(s1->getYaw()); float alpha = atan2(y, x); float phi = s2->getYaw() - alpha; phi = navfeatures_->normalizeAngle(phi, -M_PI, M_PI); float ka = 0.5; float ko = ka/8.0; dist = sqrt(dist); // two options float alpha_prime = atan(-ko*phi); //float alpha_prime = atan(-ko*ko * phi/(dist*dist)); float r = navfeatures_->normalizeAngle((alpha-alpha_prime), -M_PI, M_PI); return (sqrt(dist*dist + ko*ko + phi*phi) + ka*fabs(r)); } default: return sqrt(dist); } } float upo_RRT_ros::ValidityChecker::getCost(upo_RRT::State* s) { if(get_cost_from_costmap_) { printf("\nERROR!! ValidityChecker. getCost from costmap is not available!!!!\n"); } geometry_msgs::PoseStamped pose; pose.header.frame_id = "base_link"; if((ros::Time::now()-time_).toSec() > 2.0) time_ = ros::Time::now(); pose.header.stamp = time_; //pose.header.stamp = ros::Time(0); pose.pose.position.x = s->getX(); pose.pose.position.y = s->getY(); pose.pose.orientation = tf::createQuaternionMsgFromYaw(s->getYaw()); //printf("ValidityChecker. x: %.2f, y:%.2f, th: %.2f\n", pose.pose.position.x, pose.pose.position.y, s->getYaw()); float cost = navfeatures_->getCost(&pose); return cost; } std::vector<float> upo_RRT_ros::ValidityChecker::getFeatures(upo_RRT::State* s) { geometry_msgs::PoseStamped pose; pose.header.frame_id = "base_link"; pose.header.stamp = ros::Time(0); pose.pose.position.x = s->getX(); pose.pose.position.y = s->getY(); pose.pose.orientation = tf::createQuaternionMsgFromYaw(s->getYaw()); std::vector<float> features = navfeatures_->getFeatures(&pose); return features; } void upo_RRT_ros::ValidityChecker::setPeople(upo_msgs::PersonPoseArrayUPO p) { navfeatures_->setPeople(p); } void upo_RRT_ros::ValidityChecker::setWeights(std::vector<float> we) { navfeatures_->setWeights(we); } geometry_msgs::PoseStamped upo_RRT_ros::ValidityChecker::transformPoseTo(geometry_msgs::PoseStamped pose_in, std::string frame_out, bool usetime) { return navfeatures_->transformPoseTo(pose_in, frame_out, usetime); } bool upo_RRT_ros::ValidityChecker::isQuaternionValid(const geometry_msgs::Quaternion q) { return navfeatures_->isQuaternionValid(q); } <|start_filename|>rrt_planners/src/ros/ros_wrapper2_node.cpp<|end_filename|> #include <upo_rrt_planners/ros/RRT_ros_wrapper2.h> int main(int argc, char** argv){ ros::init(argc, argv, "ros_wrapper2_node"); tf::TransformListener tf(ros::Duration(10)); upo_RRT_ros::RRT_ros_wrapper2 rrt_wrapper(&tf); //ros::MultiThreadedSpinner s; ros::spin(); return(0); } <|start_filename|>pcl_filters/src/alternate_pc.cpp<|end_filename|> #include <iostream> #include <math.h> #include <mutex> #include <time.h> #include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include <pcl_ros/transforms.h> std::string sensor_frame; bool publishFirst = true; ros::Publisher pc_pub; tf::TransformListener *listener; sensor_msgs::PointCloud2 pc2; std::mutex mutex2; sensor_msgs::PointCloud2 pc1; std::mutex mutex1; void pc1Callback(const sensor_msgs::PointCloud2ConstPtr &msg) { mutex1.lock(); sensor_frame = msg->header.frame_id; pc1 = *msg; mutex1.unlock(); } void pc2Callback(const sensor_msgs::PointCloud2ConstPtr &msg) { mutex2.lock(); pc2 = *msg; if(!sensor_frame.empty() && msg->header.frame_id != sensor_frame) { //Transform the coordinates of the pointcloud pcl_ros::transformPointCloud(sensor_frame, *msg, pc2, *listener); } mutex2.unlock(); } void publish_pc() { if(!sensor_frame.empty()) { sensor_msgs::PointCloud2 pc; if(publishFirst) { mutex1.lock(); pc = pc1; mutex1.unlock(); publishFirst = false; pc_pub.publish(pc); } else { mutex2.lock(); pc = pc2; mutex2.unlock(); publishFirst = true; pc_pub.publish(pc); } } } int main(int argc, char **argv) { ros::init(argc, argv, "alternate"); ROS_INFO("---ALTERNATE POINTCLOUDS---"); ros::NodeHandle n; ros::NodeHandle nh("~"); listener = new tf::TransformListener(ros::Duration(10)); std::string pc_topic1 = "indires_rover/front_rgbd_camera/depth/points"; std::string pc_topic2 = "indires_rover/above_rgbd_camera/depth/points"; //camera_tf = "indires_rover/front_rgbd_camera/depth_frame"; nh.getParam("in_pc_topic_1", pc_topic1); nh.getParam("in_pc_topic_2", pc_topic2); std::string output_topic = "PointCloud_filtered"; nh.getParam("output_topic", output_topic); ros::Subscriber sub1; sub1 = n.subscribe(pc_topic1, 1, pc1Callback); ros::Subscriber sub2; sub2 = n.subscribe(pc_topic2, 1, pc2Callback); pc_pub = nh.advertise<sensor_msgs::PointCloud2>( output_topic, 0); ros::Rate r(20); while(ros::ok()) { ros::spinOnce(); publish_pc(); r.sleep(); } } <|start_filename|>rrt_planners/include/rrt_planners/ros/RRT_ros_wrapper.h<|end_filename|> /******************************************************************** * * Software License Agreement (BSD License) * * Author: <NAME> *********************************************************************/ #ifndef RRT_ROS_WRAPPER_ #define RRT_ROS_WRAPPER_ // C++ #include <vector> #include <queue> #include <cmath> #include <stdio.h> #include <iostream> // Mutex #include <mutex> // ROS #include <ros/ros.h> #include <costmap_2d/costmap_2d.h> #include <costmap_2d/VoxelGrid.h> #include <costmap_2d/costmap_2d_ros.h> #include <visualization_msgs/Marker.h> #include <geometry_msgs/PointStamped.h> #include <geometry_msgs/Pose.h> #include <tf/transform_datatypes.h> //#include <tf/transform_listener.h> #include <tf2_ros/transform_listener.h> #include <tf2_ros/buffer.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <nav_msgs/OccupancyGrid.h> #include <sensor_msgs/PointCloud2.h> #include <sensor_msgs/PointCloud.h> #include <sensor_msgs/point_cloud_conversion.h> #include <pcl_ros/transforms.h> // PCL //#include <pcl/io/pcd_io.h> //#include <pcl/conversions.h> //#include <pcl_conversions/pcl_conversions.h> //#include <pcl/point_types.h> // GMM sampling services //#include <gmm_sampling/GetApproachGMMSamples.h> //#include <gmm_sampling/GetApproachGMMProbs.h> // RRT library #include <rrt_planners/planners/Planner.h> #include <rrt_planners/planners/simple/SimpleRRT.h> #include <rrt_planners/planners/simple/SimpleRRTstar.h> #include <rrt_planners/planners/simple/SimpleQuickRRTstar.h> #include <rrt_planners/planners/control/Rrt.h> #include <rrt_planners/planners/control/RRTstar.h> #include <rrt_planners/planners/control/HalfRRTstar.h> // Planning service #include <rrt_planners/MakePlan.h> #include <rrt_planners/ChangeSolveTime.h> //#include <rrt_planners/ros/ValidityChecker.h> #include <rrt_planners/ros/ValidityChecker3D.h> // Dynamic reconfigure //#include <dynamic_reconfigure/server.h> //#include <rrt_planners/RRTRosWrapperConfig.h> namespace RRT_ros { class RRT_ros_wrapper { public: RRT_ros_wrapper(); RRT_ros_wrapper(tf2_ros::Buffer* tf); // Only for RRT as a local controller RRT_ros_wrapper(tf2_ros::Buffer* tf, float controller_freq, float path_stddev, int planner_type); ~RRT_ros_wrapper(); void setup(); ////Only for RRT as a local controller // void setup_controller(float controller_freq, float path_stddev, int planner_type); std::vector<geometry_msgs::PoseStamped> RRT_plan(bool exploration, geometry_msgs::PoseStamped start, geometry_msgs::PoseStamped goal, float start_lin_vel, float start_ang_vel); float get_rrt_planning_radius(); void visualizeTree(ros::Time t); void visualizeLeaves(ros::Time t); void publish_feature_costmap(ros::Time t); // void publish_gmm_costmap(geometry_msgs::PoseStamped person); void setWeights(std::vector<float> w) { checker_->setWeights(w); } /*void setUseLossFunc(bool l, std::vector<geometry_msgs::PoseStamped> path) { checker_->setUseLossFunc(l, path); }*/ // For full path biasing using the kinodynamic RRT local controller // int RRT_local_plan(std::vector<geometry_msgs::PoseStamped> path_to_follow, float // start_lin_vel, float start_ang_vel, geometry_msgs::Twist& cmd_vel); // subscribe to the filtered pointcloud topic for the RRT // Get array of points ( std::vector<pcl::PointXYZ> data = cloud.points; ) // Transform the pointXYZ to RRT::State and // call rrt_planner_->updateSamplingSpace(std::vector<RRT::State>* space) void setSamplingSpace(); void pcCallback(const sensor_msgs::PointCloud2ConstPtr& msg); // void setBiasingPath(std::vector<geometry_msgs::PoseStamped>* path_to_follow); std::vector<geometry_msgs::PoseStamped> simple_path_smoothing( std::vector<geometry_msgs::PoseStamped>* path); // Planning service bool makePlanService(rrt_planners::MakePlan::Request& req, rrt_planners::MakePlan::Response& res); // Change the RRT solve time service // bool changeTimeService(rrt_planners::ChangeSolveTime::Request &req, // rrt_planners::ChangeSolveTime::Response &res); void rrttimeCallback(const std_msgs::Float32ConstPtr& msg); bool change_rrt_time(float time); // std::vector<float> get_features_count(geometry_msgs::PoseStamped* goal, // std::vector<geometry_msgs::PoseStamped>* path, upo_msgs::PersonPoseArrayUPO* people); // std::vector<float> get_feature_counts(geometry_msgs::PoseStamped* goal, // std::vector<geometry_msgs::PoseStamped>* path); // std::vector<float> get_feature_counts(geometry_msgs::PoseStamped* goal, // std::vector<geometry_msgs::PoseStamped>* path, // std::vector<upo_msgs::PersonPoseArrayUPO>* people); float get_path_cost(geometry_msgs::PoseStamped* goal, std::vector<geometry_msgs::PoseStamped>* path); float get_path_cost(); std::vector<geometry_msgs::PoseStamped> path_interpolation( std::vector<geometry_msgs::PoseStamped> path, float step_distance); float get_xyz_tol() { return goal_xyz_tol_; }; float get_th_tol() { return goal_th_tol_; }; void get_vel_ranges(float& max_lin_vel, float& min_lin_vel, float& max_ang_vel, float& min_ang_vel) { max_lin_vel = max_lin_vel_; min_lin_vel = min_lin_vel_; max_ang_vel = max_ang_vel_; min_ang_vel = min_ang_vel_; }; // bool set_approaching_gmm_sampling(float orientation, int num_samp, // geometry_msgs::PoseStamped person); inline float normalizeAngle(float val, float min, float max) { float norm = 0.0; if (val >= min) norm = min + fmod((val - min), (max - min)); else norm = max - fmod((min - val), (max - min)); return norm; } inline std::string get_robot_base_frame() { return robot_base_frame_; }; inline std::string get_robot_odom_frame() { return robot_odom_frame_; }; private: // boost::recursive_mutex configuration_mutex_; ////boost::mutex reconf_mutex_; // dynamic_reconfigure::Server<rrt_planners::RRTRosWrapperConfig> *dsrv_; // void reconfigureCB(rrt_planners::RRTRosWrapperConfig &config, uint32_t level); // ROS // costmap_2d::Costmap2DROS* global_costmap_ros_; // costmap_2d::Costmap2DROS* local_costmap_ros_; //The ROS wrapper for the costmap // the controller will use // costmap_2d::Costmap2D* global_costmap_; // costmap_2d::Costmap2D* local_costmap_; //The costmap the controller will use //tf::TransformListener* tf_; tf2_ros::Buffer* tf_; // Robot float inscribed_radius_; float circumscribed_radius_; std::vector<geometry_msgs::Point> footprint_; std::string robot_base_frame_; std::string robot_odom_frame_; std::string robot_pc_sensor_frame_; std::string planning_frame_; // RRT RRT::Planner* rrt_planner_; float solve_time_; mutex solvetime_mutex_; // ros::ServiceServer solvetime_srv_; ros::Subscriber solvetime_sub_; std::vector<geometry_msgs::PoseStamped> rrt_plan_; RRT_ros::ValidityChecker3D* checker_; int rrt_planner_type_; ros::ServiceServer plan_srv_; bool use_external_pc_samples_; ros::Subscriber pc_sub_; sensor_msgs::PointCloud2 pc_; mutex pc_mutex_; int motionCostType_; float kino_timeStep_; // float equal_path_percentage_; float path_cost_; // StateSpace int dimensions_; int dim_type_; float size_x_; float size_y_; float size_z_; // Visualization bool visualize_tree_; bool visualize_leaves_; bool visualize_costmap_; bool show_statistics_; bool show_intermediate_states_; float interpolate_path_distance_; ros::Publisher local_goal_pub_; ros::Publisher rrt_goal_pub_; ros::Publisher costmap_pub_; ros::Publisher tree_pub_; ros::Publisher leaves_pub_; ros::Publisher path_points_pub_; ros::Publisher path_interpol_points_pub_; // Path smoothing bool path_smoothing_; int smoothing_samples_; // GMM biasing // bool gmm_biasing_; // float gmm_bias_; // ros::ServiceClient gmm_samples_client_; // ros::ServiceClient gmm_probs_client_; // std::vector< std::pair<float,float> > gmm_samples_; // geometry_msgs::PoseStamped gmm_person_; // float gmm_person_ori_; // std::mutex gmm_mutex_; // ros::Publisher gmm_costmap_pub_; //------------------------------------------- // bool use_uva_lib_; // bool use_fc_costmap_; float goal_bias_; float max_range_; bool rrtstar_use_k_nearest_; bool rrtstar_first_path_biasing_; float rrtstar_first_path_bias_; float rrtstar_first_path_stddev_bias_; float rrtstar_rewire_factor_; bool full_path_biasing_; float full_path_stddev_; float full_path_bias_; int kino_minControlSteps_; int kino_maxControlSteps_; float kino_linAcc_; float kino_angAcc_; int kino_steeringType_; float xyz_res_; float yaw_res_; float min_lin_vel_; float max_lin_vel_; float lin_vel_res_; float max_ang_vel_; float min_ang_vel_; float ang_vel_res_; float goal_xyz_tol_; float goal_th_tol_; int nn_params_; int distanceType_; // Only for Quick-RRTstar int depth_; }; } #endif <|start_filename|>rrt_planners/include/rrt_planners/ros/ValidityChecker.h<|end_filename|> #ifndef RRT_CHECKER_ #define RRT_CHECKER_ // RRT library #include <rrt_planners/StateChecker.h> // C++ #include <vector> #include <list> #include <cmath> #include <math.h> #include <iostream> #include <stdio.h> /* printf, fgets */ #include <stdlib.h> /* atof */ #include <exception> // std::exception #include <time.h> /* time */ // ROS #include <ros/ros.h> #include <visualization_msgs/Marker.h> #include <geometry_msgs/PointStamped.h> #include <geometry_msgs/Pose2D.h> #include <tf/transform_datatypes.h> #include <tf/transform_listener.h> #include <nav_msgs/OccupancyGrid.h> //#include <upo_msgs/PersonPoseUPO.h> //#include <upo_msgs/PersonPoseArrayUPO.h> #include <geometry_msgs/PoseStamped.h> // Features for navigation cost functions #include <navigation_features/nav_features.h> // Mutex #include <mutex> namespace RRT_ros { class ValidityChecker : public RRT::StateChecker { public: ValidityChecker(bool use_fc_costmap, tf::TransformListener* tf, std::vector<geometry_msgs::Point>* footprint, float insc_radius, float size_x, float size_y, float size_z, float res, unsigned int dimensions, int distType); virtual ~ValidityChecker(); bool isValid(RRT::State* s) const; // Distance function between two states float distance(RRT::State* s1, RRT::State* s2) const; float getCost(RRT::State* s); std::vector<float> getFeatures(RRT::State* s); void setGoal(RRT::State* g) { geometry_msgs::PoseStamped goal; goal.header.frame_id = "base_link"; goal.header.stamp = ros::Time(); goal.pose.position.x = g->getX(); goal.pose.position.y = g->getY(); goal.pose.position.z = g->getZ(); goal.pose.orientation = tf::createQuaternionMsgFromYaw(g->getYaw()); navfeatures_->setGoal(goal); } // Implemented for learning purposes //void setPeople(upo_msgs::PersonPoseArrayUPO p); geometry_msgs::PoseStamped transformPoseTo(geometry_msgs::PoseStamped pose_in, std::string frame_out, bool usetime); bool isQuaternionValid(const geometry_msgs::Quaternion q); void setWeights(std::vector<float> we); void setUseLossFunc(bool l, std::vector<geometry_msgs::PoseStamped> path) { navfeatures_->set_use_loss_func(l); navfeatures_->set_demo_path(path); } // Pre-computations needed just before starting planning void preplanning_computations(); void setInitialTime(ros::Time t) { time_ = t; } private: features::NavFeatures* navfeatures_; // const costmap_2d::Costmap2D* loc_costmap_; // const costmap_2d::Costmap2D* glo_costmap_; // bool use_global_costmap_; tf::TransformListener* tf_; unsigned int dimensions_; int distanceType_; bool get_cost_from_costmap_; ros::Time time_; }; } #endif <|start_filename|>pcl_filters/src/pcl_costmap.cpp<|end_filename|> #include <iostream> #include <math.h> #include <mutex> #include <time.h> //PCL /* //This solves the problem of compiling pcl search with C++11 #include <pcl/search/impl/search.hpp> #ifndef PCL_NO_PRECOMPILE #include <pcl/impl/instantiate.hpp> #include <pcl/point_types.h> PCL_INSTANTIATE(Search, PCL_POINT_TYPES) #endif // PCL_NO_PRECOMPILE */ #include <pcl/io/pcd_io.h> #include <pcl/conversions.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/point_types.h> #include <pcl/features/normal_3d.h> #include <pcl/PCLPointCloud2.h> #include <pcl_ros/transforms.h> //PCL filters #include <pcl/filters/filter_indices.h> #include <pcl/filters/extract_indices.h> #include <pcl/filters/voxel_grid.h> #include <pcl/filters/voxel_grid_covariance.h> #include <pcl/filters/statistical_outlier_removal.h> #include <pcl/filters/crop_box.h> #include <pcl/filters/passthrough.h> #include <pcl/filters/conditional_removal.h> //#include <pcl/filters/radius_outlier_removal.h> //the shadow filter requires to compute the normals previously #include <pcl/filters/shadowpoints.h> //ROS #include <ros/ros.h> #include <visualization_msgs/Marker.h> #include <visualization_msgs/MarkerArray.h> #include <sensor_msgs/PointCloud2.h> #include <nav_msgs/Odometry.h> #include <geometry_msgs/PoseStamped.h> #include <tf/transform_listener.h> #include <pcl_ros/transforms.h> //Eigen #include <Eigen/Geometry> #include <Eigen/Dense> //Filters pcl::VoxelGridCovariance<pcl::PointXYZ>* vgc; bool voxelgridcov = false; pcl::VoxelGrid<pcl::PointXYZ>* vg; bool voxelgrid = false; pcl::StatisticalOutlierRemoval<pcl::PointXYZ>* sor; bool statistical = false; pcl::PassThrough<pcl::PointXYZ>* pass; bool passthrough = false; float pass_cx = 0.0; float pass_cy = 0.0; float pass_cz = 0.0; float pass_rx = 100.0; float pass_ry = 100.0; float pass_rz = 100.0; pcl::CropBox<pcl::PointXYZ>* box; bool cropbox = false; std::string pc_frame; bool use_robot_pose = false; bool filter_ceiling = false; float local_grid_radius = 3.0; float max_height_allowed = 2.0; std::string robot_pose_topic; std::string odom_frame; std::string sensor_frame; geometry_msgs::PoseStamped robot_pose; std::mutex mutex; bool print_arrows = false; double pitch_max = M_PI/2.0; double roll_max = M_PI/2.0; double roughness = 0.03; double pitch_low; double pitch_high; double roll_low; double roll_high; bool assign_costs = true; ros::Publisher pc_pub; ros::Publisher arrow_pub; tf::TransformListener *listener; bool isQuaternionValid(const geometry_msgs::Quaternion q){ //first we need to check if the quaternion has nan's or infs if(!std::isfinite(q.x) || !std::isfinite(q.y) || !std::isfinite(q.z) || !std::isfinite(q.w)){ ROS_ERROR("Quaternion has infs!!!!"); return false; } if(std::isnan(q.x) || std::isnan(q.y) || std::isnan(q.z) || std::isnan(q.w)) { ROS_ERROR("Quaternion has nans !!!"); return false; } if(std::fabs(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w - 1) > 0.01) { ROS_ERROR("Quaternion malformed, magnitude: %.3f should be 1.0", (q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w)); return false; } tf::Quaternion tf_q(q.x, q.y, q.z, q.w); //next, we need to check if the length of the quaternion is close to zero if(tf_q.length2() < 1e-6){ ROS_ERROR("Quaternion has length close to zero... discarding."); return false; } //next, we'll normalize the quaternion and check that it transforms the vertical vector correctly /*tf_q.normalize(); tf::Vector3 up(0, 0, 1); double dot = up.dot(up.rotate(tf_q.getAxis(), tf_q.getAngle())); if(fabs(dot - 1) > 1e-3){ ROS_ERROR("Quaternion is invalid... for navigation the z-axis of the quaternion must be close to vertical."); return false; }*/ return true; } geometry_msgs::PoseStamped transformPoseTo(geometry_msgs::PoseStamped pose_in, std::string frame_out, bool usetime) { geometry_msgs::PoseStamped in = pose_in; if(!usetime) in.header.stamp = ros::Time(); //ros::Time::now(); //ros::Time(); geometry_msgs::PoseStamped pose_out; geometry_msgs::Quaternion q = in.pose.orientation; if(!isQuaternionValid(q)) { ROS_WARN("pcl_filters. transformPoseTo. Quaternion no valid. Creating new quaternion with yaw=0.0"); in.pose.orientation = tf::createQuaternionMsgFromYaw(0.0); } try { listener->transformPose(frame_out.c_str(), in, pose_out); }catch (tf::TransformException ex){ ROS_WARN("pcl_filters. TransformException in method transformPoseTo. TargetFrame: %s : %s", frame_out.c_str(), ex.what()); } //printf("Tranform pose. frame_in: %s, x:%.2f, y:%.2f, frame_out: %s, x:%.2f, y:%.2f\n", in.header.frame_id.c_str(), in.pose.position.x, in.pose.position.y, frame_out.c_str(), pose_out.pose.position.x, pose_out.pose.position.y); return pose_out; } pcl::PointCloud<pcl::PointXYZ> removeWallsAndCeiling(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud) { visualization_msgs::MarkerArray marray; pcl::PointCloud<pcl::PointXYZ> filtered; filtered.header = cloud->header; filtered.is_dense = cloud->is_dense; filtered.height = cloud->height; filtered.sensor_origin_ = cloud->sensor_origin_; filtered.sensor_orientation_ = cloud->sensor_orientation_; const std::map< size_t, pcl::VoxelGridCovariance<pcl::PointXYZ>::Leaf >* leaves = &(vgc->getLeaves()); if(!cloud->isOrganized()) //The height value must be different than 1 for a dataset to be organized { //the index of the width should match with the leaf index??? pcl::IndicesPtr indices(new std::vector<int>); //typedef boost::shared_ptr<std::vector<int> > pcl::IndicesPtr //std::vector<int> indices2; int ind=0; for(const auto& it : *leaves) //const { const pcl::VoxelGridCovariance<pcl::PointXYZ>::Leaf *l = &(it.second); Eigen::Vector3d mean = l->getMean(); Eigen::Matrix3d evecs = l->getEvecs(); Eigen::Vector3d evals = l->getEvals(); pcl::PointXYZ p; p.x = mean[0]; p.y = mean[1]; p.z = mean[2]; Eigen::Quaternion<double> q(evecs); auto euler = q.toRotationMatrix().eulerAngles(0, 1, 2); //0->yaw, 1->pitch, 2->roll double yaw = euler[0]; double pitch = euler[1]; double roll = euler[2]; //Identify the lowest eigenvalue //TODO: the eigen values are ordered. //The smallest is the last one. CHECK THIS! int i=0; if(evals(0) < evals(1) && evals(0) < evals(2)) i = 0; else if(evals(1) < evals(0) && evals(1) < evals(2)) i = 1; else i = 2; float nx = (float)evecs(0,i); float ny = (float)evecs(1,i); float nz = (float)evecs(2,i); //create a pose //geometry_msgs::PoseStamped pose; //pose.header.frame_id = odom_frame; //pose.header.stamp = ros::Time::now(); tf::Quaternion aux(q.x(), q.y(), q.z(), q.w()); aux.normalize(); //pose.pose.position.x = mean[0]; //pose.pose.position.y = mean[1]; //pose.pose.position.z = mean[2]; //pose.pose.orientation.x = aux.x(); //pose.pose.orientation.y = aux.y(); //pose.pose.orientation.z = aux.z(); //pose.pose.orientation.w = aux.w(); //Transform pose to odom frame //geometry_msgs::PoseStamped meanpose = transformPoseTo(pose, sensor_frame, false); mutex.lock(); geometry_msgs::PoseStamped rpose = robot_pose; mutex.unlock(); //WATCH OUT!!! //This is a very poor filter of the ceiling //I compare the height of the point with the height of the robot if(fabs(rpose.pose.position.z - p.z) > max_height_allowed) continue; /* //geometry_msgs::PoseStamped rpose = transformPoseTo(aux_pose, odom_frame, false); // correct if n . (pv - Pi) > 0 // n -> evec with the lowest eigenvalue (= normal vector) // pv -> (0,0,0) // pi -> mean // See if we need to flip any plane normals // Dot product between the (viewpoint - point) and the plane normal float cos_theta = ((rpose.pose.position.x-mean[0]) * nx + (rpose.pose.position.y-mean[1]) * ny + (rpose.pose.position.z-mean[2]) * nz); // Flip the plane normal if (cos_theta < 0) { pcl::flipNormalTowardsViewpoint(p, rpose.pose.position.x, rpose.pose.position.y, rpose.pose.position.z, nx, ny, nz); Eigen::Vector3d norm(nx, ny, nz); norm = norm.normalized(); //evecs(0,i) = nx; //evecs(1,i) = ny; //evecs(2,i) = nz; evecs.col(i) = norm; //evecs = -1.0*evecs; Eigen::Vector3d norm2; Eigen::Vector3d norm3; if ((fabs((double)norm(0)) > 0.001) || (fabs((double)norm(1)) > 0.001)) { norm2 << -norm(1), norm(0), 0; } else { norm2 << 0, norm(2), -norm(1); } norm2.normalize(); norm3 = norm.cross(norm2); Eigen::Matrix3d R; // Rotation matrix defining orientation R.col(0) = norm; R.col(1) = norm2; R.col(2) = norm3; //Eigen::Quaternion<double> q2(evecs); //evecs_trans Eigen::Quaternion<double> q2(R); tf::Quaternion aux2(q2.x(), q2.y(), q2.z(), q2.w()); aux2.normalize(); aux = aux2; tf::Matrix3x3 m(aux2); //double roll2, pitch2, yaw2; m.getRPY(roll, pitch, yaw); //pose.pose.orientation.x = aux2.x(); //pose.pose.orientation.y = aux2.y(); //pose.pose.orientation.z = aux2.z(); //pose.pose.orientation.w = aux2.w(); }*/ //if(fabs(pitch) < pitch_low || fabs(pitch) > pitch_high && fabs(yaw) < roll_low || fabs(yaw) > roll_high) //if(pitch < pitch_high && pitch > pitch_low && yaw < roll_high && yaw > roll_low) // && fabs(evals(i)) < roughness)) if(fabs(pitch) < pitch_high && fabs(pitch) > pitch_low && fabs(roll) < roll_high && fabs(roll) > roll_low) //ok //if(-pitch < pitch_high && -pitch > pitch_low && -roll < roll_high && -roll > roll_low) { //printf("pose3d VALID. pitch:%.2f, roll:%.2f, upper:%.2f, lower:%.2f\n", fabs(pitch), fabs(roll), pitch_high, pitch_low); indices->push_back(ind); //indices2.push_back(ind); filtered.push_back(p); if(print_arrows) { visualization_msgs::Marker marker; marker.header.frame_id = odom_frame; //frame_out; marker.header.stamp = ros::Time(); marker.ns = "normal_arrows"; marker.id = ind; //key; marker.type = visualization_msgs::Marker::ARROW; marker.action = visualization_msgs::Marker::ADD; marker.pose.position.x = mean[0]; //m[0] marker.pose.position.y = mean[1]; //m[1] marker.pose.position.z = mean[2]; //m[2] //marker.pose.position = meanpose.pose.position; //tf::Quaternion aux(q.x(), q.y(), q.z(), q.w()); //aux.normalize(); marker.pose.orientation.x = aux.x(); marker.pose.orientation.y = aux.y(); marker.pose.orientation.z = aux.z(); marker.pose.orientation.w = aux.w(); //marker.pose.orientation = meanpose.pose.orientation; marker.scale.x = 9.0*evals(i); marker.scale.y = 0.03; //2.0*evals(1); marker.scale.z = 0.03; //2.0*evals(2); marker.color.a = 1.0; marker.color.r = 0.0; marker.color.g = 0.0; marker.color.b = 1.0; marker.lifetime = ros::Duration(2.0); marray.markers.push_back(marker); } } else { //printf("pose3d INVALID. pitch:%.2f, roll:%.2f, upper:%.2f, lower:%.2f\n", fabs(pitch), fabs(roll), pitch_high, pitch_low); } ind++; } pcl::ExtractIndices<pcl::PointXYZ> eifilter(false); // Initializing with true will allow us to extract the removed indices eifilter.setInputCloud(cloud); eifilter.setIndices(indices); //eifilter.filter (*cloud_out); eifilter.filterDirectly(cloud); //eifilter.filter(indices2); arrow_pub.publish(marray); return filtered; } else { printf("pcl_filters. The point cloud is ordered!!!\n"); } /* En setIndices, indices_in es un pcl::IndicesPtr, que es un puntero a vector: typedef boost::shared_ptr<std::vector<int> > pcl::ExtractIndices<PointType> eifilter (true); // Initializing with true will allow us to extract the removed indices eifilter.setInputCloud (cloud_in); eifilter.setIndices (indices_in); eifilter.filter (*cloud_out); Alternativamente a filter, podemos usar: eifilter.filterDirectly (cloud_in); This will directly modify cloud_in instead of creating a copy of the cloud */ } pcl::PointCloud<pcl::PointXYZRGB> assignCosts(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud) { visualization_msgs::MarkerArray marray; pcl::PointCloud<pcl::PointXYZRGB> coloured; coloured.header = cloud->header; coloured.is_dense = cloud->is_dense; coloured.height = cloud->height; coloured.sensor_origin_ = cloud->sensor_origin_; coloured.sensor_orientation_ = cloud->sensor_orientation_; std::vector<float> weights; const std::map< size_t, pcl::VoxelGridCovariance<pcl::PointXYZ>::Leaf >* leaves = &(vgc->getLeaves()); if(!cloud->isOrganized()) //The height value must be different than 1 for a dataset to be organized { //the index of the width should match with the leaf index??? //pcl::IndicesPtr indices(new std::vector<int>); //typedef boost::shared_ptr<std::vector<int> > pcl::IndicesPtr int ind=0; for(const auto& it : *leaves) //const { const pcl::VoxelGridCovariance<pcl::PointXYZ>::Leaf *l = &(it.second); Eigen::Vector3d mean = l->getMean(); Eigen::Matrix3d evecs = l->getEvecs(); Eigen::Vector3d evals = l->getEvals(); float num_points = (float)l->getPointCount(); int points = l->getPointCount(); pcl::PointXYZRGB p; p.x = mean[0]; p.y = mean[1]; p.z = mean[2]; Eigen::Quaternion<double> q(evecs); auto euler = q.toRotationMatrix().eulerAngles(0, 1, 2); //0->yaw, 1->pitch, 2->roll double yaw = euler[0]; double pitch = euler[1]; double roll = euler[2]; //Identify the lowest eigenvalue //TODO: the eigen values are ordered. //The smallest is the last one. CHECK THIS! int i=0; if(evals(0) < evals(1) && evals(0) < evals(2)) i = 0; else if(evals(1) < evals(0) && evals(1) < evals(2)) i = 1; else i = 2; float nx = (float)evecs(0,i); float ny = (float)evecs(1,i); float nz = (float)evecs(2,i); //create a pose //geometry_msgs::PoseStamped pose; //pose.header.frame_id = odom_frame; //pose.header.stamp = ros::Time::now(); tf::Quaternion aux(q.x(), q.y(), q.z(), q.w()); aux.normalize(); //pose.pose.position.x = mean[0]; //pose.pose.position.y = mean[1]; //pose.pose.position.z = mean[2]; //pose.pose.orientation.x = aux.x(); //pose.pose.orientation.y = aux.y(); //pose.pose.orientation.z = aux.z(); //pose.pose.orientation.w = aux.w(); //Transform pose to odom frame //geometry_msgs::PoseStamped meanpose = transformPoseTo(pose, sensor_frame, false); mutex.lock(); geometry_msgs::PoseStamped rpose = robot_pose; mutex.unlock(); if(filter_ceiling) { //WATCH OUT!!! //This is a very poor filter of the ceiling //I compare the height of the point with the height of the robot if(fabs(rpose.pose.position.z - p.z) > max_height_allowed) continue; if(!(fabs(pitch) < pitch_high && fabs(pitch) > pitch_low && fabs(roll) < roll_high && fabs(roll) > roll_low)) //!ok continue; } std::vector<float> features; //Normalize pitch and yaw float zero = M_PI/2.0; pitch = fabs(zero - fabs(pitch)); pitch = pitch/zero; roll = fabs(zero - fabs(roll)); roll = roll/zero; if (pitch > 0.55) pitch = 1.0; if(roll > 0.55) roll = 1.0; features.push_back(pitch); features.push_back(roll); //Normalize roughness //Maximum value of roughness????? float rough = fabs(evals(2)); if (rough > roughness) rough = roughness; rough = rough/roughness; features.push_back(rough); //normalize point dist. max dist = robot_radius_ //point_dist = point_dist / robot_radius_; //Normalize stddev //stddev = 1.0 - (stddev / max_stddev); //Normalize num_points float max_points = 50.0; if(num_points > max_points) num_points = max_points; num_points = 1.0 - (num_points/max_points); features.push_back(num_points); std::vector<float> weights; weights.assign(4, 0.25); float cost = 0.0; for(unsigned int i=0; i<features.size(); i++) cost += features[i] * weights[i]; //Filter walls, high ceiling and high roughness //if(pitch > 0.6 || roll > 0.6 || rough > 0.6 || (fabs(rpose.pose.position.z - p.z) > max_height_allowed) ) { if(!filter_ceiling && fabs(rpose.pose.position.z - p.z) > max_height_allowed) { cost = 1.0; } if(pitch == 1.0 || roll == 1.0 || rough > 0.75) cost = cost>0.8? 0.8 : cost; //Convert scale [0-1] of the cost to scale [0-255]; int c = (int)round(cost * 255); //printf("cost:%.3f, color:%i, p:%.2f, r:%.2f, roug:%.2f, np:%i, pc:%.2f\n", cost, c, pitch, roll, rough, points, num_points); p.r = c; p.g = 255 - c; p.b = 0; coloured.push_back(p); ind++; /* //geometry_msgs::PoseStamped rpose = transformPoseTo(aux_pose, odom_frame, false); // correct if n . (pv - Pi) > 0 // n -> evec with the lowest eigenvalue (= normal vector) // pv -> (0,0,0) // pi -> mean // See if we need to flip any plane normals // Dot product between the (viewpoint - point) and the plane normal float cos_theta = ((rpose.pose.position.x-mean[0]) * nx + (rpose.pose.position.y-mean[1]) * ny + (rpose.pose.position.z-mean[2]) * nz); // Flip the plane normal if (cos_theta < 0) { pcl::flipNormalTowardsViewpoint(p, rpose.pose.position.x, rpose.pose.position.y, rpose.pose.position.z, nx, ny, nz); Eigen::Vector3d norm(nx, ny, nz); norm = norm.normalized(); //evecs(0,i) = nx; //evecs(1,i) = ny; //evecs(2,i) = nz; evecs.col(i) = norm; //evecs = -1.0*evecs; Eigen::Vector3d norm2; Eigen::Vector3d norm3; if ((fabs((double)norm(0)) > 0.001) || (fabs((double)norm(1)) > 0.001)) { norm2 << -norm(1), norm(0), 0; } else { norm2 << 0, norm(2), -norm(1); } norm2.normalize(); norm3 = norm.cross(norm2); Eigen::Matrix3d R; // Rotation matrix defining orientation R.col(0) = norm; R.col(1) = norm2; R.col(2) = norm3; //Eigen::Quaternion<double> q2(evecs); //evecs_trans Eigen::Quaternion<double> q2(R); tf::Quaternion aux2(q2.x(), q2.y(), q2.z(), q2.w()); aux2.normalize(); aux = aux2; tf::Matrix3x3 m(aux2); //double roll2, pitch2, yaw2; m.getRPY(roll, pitch, yaw); //pose.pose.orientation.x = aux2.x(); //pose.pose.orientation.y = aux2.y(); //pose.pose.orientation.z = aux2.z(); //pose.pose.orientation.w = aux2.w(); }*/ } coloured.width = ind; return coloured; } else { ROS_ERROR("pcl_filters. The point cloud is ordered!!!\n"); return coloured; } } void pcCallback(const sensor_msgs::PointCloud2ConstPtr &msg) { //Transform the coordinates of the pointcloud sensor_msgs::PointCloud2 local; pcl_ros::transformPointCloud(odom_frame, *msg, local, *listener); //pc_frame = msg->header.frame_id; pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>); //pcl::fromROSMsg(*msg, *cloud); pcl::fromROSMsg(local, *cloud); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_fil(new pcl::PointCloud<pcl::PointXYZ>); //pcl::PointCloud<pcl::PointXYZ> cloud_out = *cloud; sensor_msgs::PointCloud2 pc_out; if(passthrough) { //TODO: this is not the most efficient way to do it. Try to use indices //TODO: Try conditional removal /* pcl::ConditionOr<PointT>::Ptr range_cond (new pcl::ConditionOr<PointT> ()); range_cond->addComparison (pcl::FieldComparison<PointT>::Ptr (new pcl::FieldComparison<PointT>("x", pcl::ComparisonOps::GT, minX))); range_cond->addComparison (pcl::FieldComparison<PointT>::Ptr (new pcl::FieldComparison<PointT>("x", pcl::ComparisonOps::LT, maxX))); range_cond->addComparison (pcl::FieldComparison<PointT>::Ptr (new pcl::FieldComparison<PointT>("y", pcl::ComparisonOps::GT, minY))); range_cond->addComparison (pcl::FieldComparison<PointT>::Ptr (new pcl::FieldComparison<PointT>("y", pcl::ComparisonOps::LT, maxY))); range_cond->addComparison (pcl::FieldComparison<PointT>::Ptr (new pcl::FieldComparison<PointT>("z", pcl::ComparisonOps::GT, minZ))); range_cond->addComparison (pcl::FieldComparison<PointT>::Ptr (new pcl::FieldComparison<PointT>("z", pcl::ComparisonOps::LT, maxZ))); pcl::ConditionalRemoval<PointT> range_filt; range_filt.setInputCloud(body); range_filt.setCondition (range_cond); range_filt.filter(*bodyFiltered); */ pass->setInputCloud(cloud); //filter X axis pass->setFilterFieldName ("x"); pass->setFilterLimits((pass_cx - pass_rx), (pass_cx + pass_rx)); //std::vector<int> indices_x; //pcl::IndicesPtr indices_x; //ROS_INFO("before filter X"); //pass->filter(*indices_x); pass->filter(*cloud_fil); *cloud = *cloud_fil; //filter Y axis //pass->setIndices(indices_x); pass->setInputCloud(cloud); pass->setFilterFieldName ("y"); pass->setFilterLimits ((pass_cy - pass_ry), (pass_cy + pass_ry)); //pass->setNegative(true); //std::vector<int>* indices_xy; //pcl::IndicesPtr indices_xy; pass->filter(*cloud_fil); *cloud = *cloud_fil; //filter Z axis //pass->setIndices(indices_xy); pass->setInputCloud(cloud); pass->setFilterFieldName ("z"); pass->setFilterLimits ((pass_cz - pass_rz), (pass_cz + pass_rz)); //pass->setNegative(true); pass->filter(*cloud_fil); *cloud = *cloud_fil; } if(cropbox) { box->setInputCloud(cloud); if(use_robot_pose) { mutex.lock(); geometry_msgs::PoseStamped p = robot_pose; mutex.unlock(); //geometry_msgs::PoseStamped p; //p = transformPoseTo(pose, odom_frame, true); float min_x = p.pose.position.x - local_grid_radius; float max_x = p.pose.position.x + local_grid_radius; float min_y = p.pose.position.y - local_grid_radius; float max_y = p.pose.position.y + local_grid_radius; float min_z = p.pose.position.z - local_grid_radius; float max_z = p.pose.position.z + local_grid_radius; box->setMin(Eigen::Vector4f(min_x, min_y, min_z, 1.0)); box->setMax(Eigen::Vector4f(max_x, max_y, max_z, 1.0)); } box->filter(*cloud_fil); *cloud = *cloud_fil; } if(statistical) { sor->setInputCloud(cloud); sor->filter(*cloud_fil); *cloud = *cloud_fil; } if(voxelgrid) { vg->setInputCloud(cloud); vg->filter(*cloud_fil); *cloud = *cloud_fil; } pcl::PointCloud<pcl::PointXYZRGB> coloured; if(voxelgridcov && !voxelgrid) { vgc->setInputCloud(cloud); vgc->filter(*cloud_fil, true); *cloud = *cloud_fil; //if(filter_ceiling) //{ // filtered = removeWallsAndCeiling(cloud); // *cloud = filtered; //} if(assign_costs) { coloured = assignCosts(cloud); pcl::toROSMsg(coloured, pc_out); pc_pub.publish(pc_out); return; } } pcl::toROSMsg(*cloud, pc_out); //Transform the coordinates of the pointcloud //sensor_msgs::PointCloud2 local; //pcl_ros::transformPointCloud("/indires_rover/base_link", pc_out, local, *listener); pc_pub.publish(pc_out); //pc_pub.publish(local); } void poseCallback(const nav_msgs::OdometryConstPtr &msg) { geometry_msgs::PoseStamped pose; pose.header = msg->header; pose.pose = msg->pose.pose; geometry_msgs::PoseStamped pose_out; //if(!pc_frame.empty()) pose_out = transformPoseTo(pose, odom_frame, false); mutex.lock(); robot_pose = pose_out; mutex.unlock(); } int main(int argc, char **argv) { ros::init(argc, argv, "pcl_costmap"); ROS_INFO("---PCL COSTMAP---"); ros::NodeHandle n; ros::NodeHandle nh("~"); listener = new tf::TransformListener(ros::Duration(10)); std::string pointcloud_topic = "indires_rover/front_rgbd_camera/front_rgbd_camera/depth/points"; //camera_tf = "indires_rover/front_rgbd_camera/depth_frame"; nh.getParam("pointcloud_topic", pointcloud_topic); std::string output_topic = "PointCloud_filtered"; nh.getParam("output_topic", output_topic); nh.getParam("use_robot_pose", use_robot_pose); nh.getParam("robot_pose_topic", robot_pose_topic); nh.getParam("local_grid_radius", local_grid_radius); nh.getParam("max_height_allowed", max_height_allowed); nh.getParam("odom_frame", odom_frame); nh.getParam("sensor_frame", sensor_frame); //nh.getParam("show_normal_arrows", print_arrows); nh.getParam("filter_ceiling_and_walls", filter_ceiling); nh.getParam("pitch_max_inclination", pitch_max); nh.getParam("roll_max_inclination", roll_max); nh.getParam("max_roughness", roughness); //pitch_low = -M_PI/2.0 - pitch_max; //pitch_high = -M_PI/2.0 + pitch_max; //roll_low = -M_PI/2.0 - roll_max; //roll_high = -M_PI/2.0 + roll_max; //pitch_low = pitch_max; //pitch_high = M_PI - pitch_max; //roll_low = roll_max; //roll_high = M_PI - roll_max; pitch_low = M_PI/2.0 - pitch_max; pitch_high = M_PI/2.0 + pitch_max; roll_low = M_PI/2.0 - roll_max; roll_high = M_PI/2.0 + roll_max; //sleep a bit in order to fill the TF buffer sleep(6.0); if(nh.hasParam("PassThroughFilter")) { ros::NodeHandle n("~PassThroughFilter"); n.getParam("enable", passthrough); if(passthrough) { ROS_INFO("Using PassThrough filter:"); n.getParam("center_x", pass_cx); n.getParam("center_y", pass_cy); n.getParam("center_z", pass_cz); ROS_INFO("\tcx: %.2f, cy: %.2f, cz: %.2f", pass_cx, pass_cy, pass_cz); n.getParam("rad_x", pass_rx); n.getParam("rad_y", pass_ry); n.getParam("rad_z", pass_rz); ROS_INFO("\trx: %.2f, ry: %.2f, rz: %.2f", pass_rx, pass_ry, pass_rz); pass = new pcl::PassThrough<pcl::PointXYZ>(false); } } if(nh.hasParam("CropBoxFilter")) { ros::NodeHandle n("~CropBoxFilter"); n.getParam("enable", cropbox); if(cropbox) { ROS_INFO("Using CropBox filter:"); float min_x = -10.0; float min_y = -10.0; float min_z = -10.0; float max_x = 10.0; float max_y = 10.0; float max_z = 10.0; n.getParam("cb_min_x", min_x); n.getParam("cb_min_y", min_y); n.getParam("cb_min_z", min_z); n.getParam("cb_max_x", max_x); n.getParam("cb_max_y", max_y); n.getParam("cb_max_z", max_z); ROS_INFO("\tminx: %.2f, miny: %.2f, minz: %.2f", min_x, min_y, min_z); ROS_INFO("\tmaxx: %.2f, maxy: %.2f, maxz: %.2f", max_x, max_y, max_z); box = new pcl::CropBox<pcl::PointXYZ>(); box->setMin(Eigen::Vector4f(min_x, min_y, min_z, 1.0)); box->setMax(Eigen::Vector4f(max_x, max_y, max_z, 1.0)); } } if(nh.hasParam("StatisticalOutlierFilter")) { ros::NodeHandle n("~StatisticalOutlierFilter"); n.getParam("enable", statistical); if(statistical) { ROS_INFO("Using StatisticalOutlierRemoval filter:"); int kneighbors = 80; n.getParam("mean_k_neighbors", kneighbors); ROS_INFO("\tMean_k_neighbors: %i", kneighbors); float stddev = 2.0; n.getParam("std_dev", stddev); ROS_INFO("\tStd_dev: %.2f", stddev); sor = new pcl::StatisticalOutlierRemoval<pcl::PointXYZ>(); sor->setMeanK (kneighbors); sor->setStddevMulThresh (stddev); } } if(nh.hasParam("VoxelGridFilter")) { ros::NodeHandle n("~VoxelGridFilter"); n.getParam("enable", voxelgrid); if(voxelgrid) { ROS_INFO("Using VoxelGrid filter:"); float leaf_size = 0.20; n.getParam("leaf_size", leaf_size); ROS_INFO("\tLeaf_size: %.2f", leaf_size); int min_point_per_voxel = 10; n.getParam("leaf_size", leaf_size); n.getParam("min_point_per_voxel", min_point_per_voxel); ROS_INFO("\tmin_point_per_voxel: %i", min_point_per_voxel); vg = new pcl::VoxelGrid<pcl::PointXYZ>(); vg->setLeafSize(leaf_size, leaf_size, leaf_size); //vg->setMinPointPerVoxel(min_point_per_voxel); vg->setMinimumPointsNumberPerVoxel(min_point_per_voxel); } } if(nh.hasParam("VoxelGridCovarianceFilter") && !voxelgrid) { ros::NodeHandle n("~VoxelGridCovarianceFilter"); n.getParam("enable", voxelgridcov); if(voxelgridcov) { ROS_INFO("Using VoxelGridCovariance filter:"); float leaf_size = 0.20; n.getParam("leaf_size", leaf_size); ROS_INFO("\tLeaf_size: %.2f", leaf_size); int min_point_per_voxel = 10; n.getParam("leaf_size", leaf_size); n.getParam("min_point_per_voxel", min_point_per_voxel); vgc = new pcl::VoxelGridCovariance<pcl::PointXYZ>(); vgc->setLeafSize(leaf_size, leaf_size, leaf_size); //0.01f, 0.01f, 0.01f //inherited from pcl::VoxelGrid vgc->setMinPointPerVoxel(min_point_per_voxel); } } arrow_pub = nh.advertise<visualization_msgs::MarkerArray>( "pcl_filter_arrows", 0); //filter_pub = nh.advertise<visualization_msgs::MarkerArray>( "NDTMAP_TRANS", 0); pc_pub = nh.advertise<sensor_msgs::PointCloud2>( output_topic, 0); ros::Subscriber sub; sub = n.subscribe(pointcloud_topic, 1, pcCallback); ros::Subscriber sub2; if(use_robot_pose) sub2 = n.subscribe(robot_pose_topic, 1, poseCallback); ros::spin(); } <|start_filename|>pcl_filters/src/pc2_to_ply.cpp<|end_filename|> #include <iostream> #include <math.h> #include <mutex> #include <time.h> //PCL /* //This solves the problem of compiling pcl search with C++11 #include <pcl/search/impl/search.hpp> #ifndef PCL_NO_PRECOMPILE #include <pcl/impl/instantiate.hpp> #include <pcl/point_types.h> PCL_INSTANTIATE(Search, PCL_POINT_TYPES) #endif // PCL_NO_PRECOMPILE */ #include <pcl/io/pcd_io.h> #include <pcl/io/ply_io.h> #include <pcl/conversions.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/point_types.h> #include <pcl/features/normal_3d.h> #include <pcl/PCLPointCloud2.h> #include <pcl_ros/transforms.h> //ROS #include <ros/ros.h> #include <visualization_msgs/Marker.h> #include <visualization_msgs/MarkerArray.h> #include <sensor_msgs/PointCloud2.h> #include <nav_msgs/Odometry.h> #include <geometry_msgs/PoseStamped.h> #include <tf/transform_listener.h> #include <pcl_ros/transforms.h> #include <std_msgs/Bool.h> //Eigen #include <Eigen/Geometry> #include <Eigen/Dense> std::mutex mutex; bool store = false; std::string output_file; tf::TransformListener *listener; void pcCallback(const sensor_msgs::PointCloud2ConstPtr &msg) { //Transform the coordinates of the pointcloud sensor_msgs::PointCloud2 local; pcl_ros::transformPointCloud("indires_rover/odom", *msg, local, *listener); //pc_frame = msg->header.frame_id; pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>); //pcl::fromROSMsg(*msg, *cloud); pcl::fromROSMsg(local, *cloud); mutex.lock(); if(store) { printf("\nSTORING FILE TO PLY IN:\n %s \n", output_file.c_str()); pcl::io::savePLYFileBinary(output_file, *cloud); pcl::io::savePLYFileASCII(output_file+"_ascci.ply", *cloud); //pcl::PCLPointCloud2 cloud //pcl::PLYWriter writer; //writer.write (filename, cloud, Eigen::Vector4f::Zero (), //Eigen::Quaternionf::Identity (), binary, use_camera); } store = false; mutex.unlock(); } /*void poseCallback(const nav_msgs::OdometryConstPtr &msg) { geometry_msgs::PoseStamped pose; pose.header = msg->header; pose.pose = msg->pose.pose; geometry_msgs::PoseStamped pose_out; //if(!pc_frame.empty()) pose_out = transformPoseTo(pose, odom_frame, false); mutex.lock(); robot_pose = pose_out; mutex.unlock(); }*/ void storeCallback(const std_msgs::BoolConstPtr &msg) { mutex.lock(); store = true; mutex.unlock(); } int main(int argc, char **argv) { ros::init(argc, argv, "pcl_filters"); ROS_INFO("---PCL to PLY---"); ros::NodeHandle n; ros::NodeHandle nh("~"); listener = new tf::TransformListener(ros::Duration(10)); ros::Publisher store_pub = n.advertise<std_msgs::Bool>("store_ply", 1); std::string pointcloud_topic = "indires_rover/front_rgbd_camera/front_rgbd_camera/depth/points"; //camera_tf = "indires_rover/front_rgbd_camera/depth_frame"; nh.getParam("pointcloud_topic", pointcloud_topic); output_file = "PointCloud_filtered"; nh.getParam("output_file", output_file); ros::Subscriber sub; sub = n.subscribe(pointcloud_topic, 1, pcCallback); //ros::Subscriber sub2; //if(use_robot_pose) // sub2 = n.subscribe(robot_pose_topic, 1, poseCallback); ros::Subscriber action; action = n.subscribe("store_ply", 1, storeCallback); ros::spin(); } <|start_filename|>rrt_planners/src/ros/capture.cpp<|end_filename|> #include <upo_rrt_planners/ros/capture.h> using namespace std; Capture::Capture(sensor_msgs::PointCloud* obs, vector<upo_msgs::PersonPoseUPO>* people, geometry_msgs::PoseStamped* goal) { setScenario(obs, people, goal); setup(); } Capture::Capture() { //tf_listener_ = new tf::TransformListener(ros::Duration(10)); setup(); } Capture::~Capture() { } void Capture::setScenario(sensor_msgs::PointCloud* obs, vector<upo_msgs::PersonPoseUPO>* people, geometry_msgs::PoseStamped* goal) { //Take all the trajectory data obs_ = obs; people_ = people; goal_ = goal; //agent_ = agent; //TransformToLocal(pc_, people_, goal_, agent_); } void Capture::setup() { goal_ok_ = false; ros::NodeHandle n("~/Capture"); n.param("use_static_map", use_static_map_, false); n.param("save_img", save_img_, false); save_count_ = 1; save_path_ = ros::package::getPath("upo_rrt_planners"); //Add the demo path n.param("add_demo_path", add_demo_path_, false); //if add_demo_path is true // we can chose whether to draw only the path or path+scenario n.param("only_path_label", only_path_label_, false); //With and height in pixels n.param("img_pixels", px_height_, 400); //Image resolution m/pix n.param("img_resolution", resolution_, (float)0.025); n.param("use_greyscale", greyscale_, false); n.param("add_people_orientation", people_orientation_, false); px_width_ = px_height_; //400; //400px*0.025m/px = 10m px_origin_ = make_pair((int)px_width_/2, (int)px_height_/2); w_origin_ = make_pair(px_origin_.first*resolution_, px_origin_.second*resolution_); cout << "---- Capture navigation images ----" << endl; cout << "px_width: " << px_width_ << " px" << endl; cout << "px_height: " << px_height_ << " px" << endl; cout << "px_origin x: " << px_origin_.first << " px" << endl; cout << "px_origin y: " << px_origin_.second << " px" << endl; cout << "resolution: " << resolution_ << " m/px" << endl; cout << "w_origin x: " << w_origin_.first << " m" << endl; cout << "w_origin y: " << w_origin_.second << " m" << endl; cout << "-----------------------------------" << endl; } /** * Get current date/time, format is YYYY-MM-DD.HH:mm:ss */ const string Capture::currentDateTime() { time_t now = std::time(0); struct tm tstruct; char buf[80]; tstruct = *localtime(&now); strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct); return buf; } /** * transform world point (m) to pixel */ pair<int,int> Capture::worldToImg(geometry_msgs::Point32* world_point) { float wx = w_origin_.first + world_point->x; float wy = w_origin_.second - world_point->y; pair<int,int> pix = make_pair((int)floor(wx/resolution_),(int)floor(wy/resolution_)); return pix; } /** * Add the laser readings (obstacles) to the image */ bool Capture::addObstacles(cv::Mat* img) { /*sensor_msgs::PointCloud temp_pc; //Transform pointCloud2 to pointCloud bool done = sensor_msgs::convertPointCloud2ToPointCloud(*pc_, temp_pc); if(!done) { ROS_ERROR("\n\nGenerateImg. ERROR in convertPointCloud2toPoingCloud!!!!!\n"); return false; }*/ cv::Vec3b intensity; intensity.val[0] = 0; //blue intensity.val[1] = 255; //green intensity.val[2] = 0; //red uchar intensity_grey = 204; //printf("\naddObstacles!!! points.size: %u\n\n", (unsigned int)obs_->points.size()); for(int i =0;i<obs_->points.size();i++){ pair<int,int> pix = worldToImg(&obs_->points[i]); //printf("pix x: %i, y: %i\n", pix.first, pix.second); if(pix.first >= 0 && pix.first < px_width_ && pix.second >= 0 && pix.second < px_height_) { if(greyscale_) { img->at<uchar>(pix.second, pix.first) = intensity_grey; } else img->at<cv::Vec3b>(pix.second, pix.first) = intensity; } } return true; } /*bool Capture::draw_half_circle(cv::Mat* img, radius, start_angle): height, width = img.shape[0:2] // Ellipse parameters radius = 100 center = (width / 2, height - 25) axes = (radius, radius) angle = 0 startAngle = 180 endAngle = 360 thickness = 10 # http://docs.opencv.org/modules/core/doc/drawing_functions.html#ellipse cv2.ellipse(image, center, axes, angle, startAngle, endAngle, BLACK, thickness) */ float Capture::normalizeAngle(float val, float min, float max) { float norm = 0.0; if (val >= min) norm = min + fmod((val - min), (max-min)); else norm = max - fmod((min - val), (max-min)); return norm; } bool Capture::draw_triangle(cv::Mat* img, geometry_msgs::Point32 center, float orientation, float radius) { int lineType = 8; cv::Point points[1][3]; //Point 1 float ori1 = orientation+(M_PI/2.0); geometry_msgs::Point32 p1; p1.x = center.x + radius*cos(normalizeAngle(ori1,-M_PI, M_PI)); p1.y = center.y + radius*sin(normalizeAngle(ori1, -M_PI, M_PI)); pair<int,int> pix1 = worldToImg(&p1); points[0][0] = cv::Point(pix1.first, pix1.second); //Point 2 float ori2 = orientation-(M_PI/2.0); geometry_msgs::Point32 p2; p2.x = center.x + radius*cos(normalizeAngle(ori2,-M_PI, M_PI)); p2.y = center.y + radius*sin(normalizeAngle(ori2, -M_PI, M_PI)); pair<int,int> pix2 = worldToImg(&p2); points[0][1] = cv::Point(pix2.first, pix2.second); //Point 3 geometry_msgs::Point32 p3; p3.x = center.x + (radius+0.15)*cos(orientation); p3.y = center.y + (radius+0.15)*sin(orientation); pair<int,int> pix3 = worldToImg(&p3); points[0][2] = cv::Point(pix3.first, pix3.second); const cv::Point* ppt[1] = { points[0] }; int npt[] = { 3 }; if(greyscale_) cv::fillPoly(*img, ppt, npt, 1, cv::Scalar(153), lineType ); else cv::fillPoly(*img, ppt, npt, 1, cv::Scalar( 255, 255, 0), lineType ); return true; } /** * Add the people to the image */ bool Capture::addPeople(cv::Mat* img) { float radius = 0.3; //m //0.3m/0.025m/px = 12 px int thickness = -1; int lineType = 8; for (int i=0; i<people_->size(); i++){ //Transform people to base_link //geometry_msgs::PoseStamped p; //p.header = people_->at(i).header; //p.pose.position = people_->at(i).position; //p.pose.orientation = people_->at(i).orientation; //p = transformPoseTo(p, "base_link", true); geometry_msgs::Point32 center; center.x = people_->at(i).position.x; //p.pose.position.x; center.y = people_->at(i).position.y; //p.pose.position.y; pair<int,int> pix = worldToImg(&center); if(pix.first >= 0 && pix.first < px_width_ && pix.second >= 0 && pix.second < px_height_) { if(greyscale_) cv::circle(*img, cv::Point(pix.first, pix.second), radius/resolution_, cv::Scalar(102), thickness, lineType); else cv::circle(*img, cv::Point(pix.first, pix.second), radius/resolution_, cv::Scalar(0,0,255), thickness, lineType); //Red if(people_orientation_) { //Add a line with the orientation //geometry_msgs::Point32 p2; //p2.x = center.x + radius*cos(tf::getYaw(people_->at(i).orientation)); //p2.y = center.y + radius*sin(tf::getYaw(people_->at(i).orientation)); //pair<int,int> pix2 = worldToImg(&p2); //if(greyscale_) { //cv::line(*img, cv::Point(pix.first, pix.second), cv::Point(pix2.first, pix2.second), cv::Scalar(0), 2); //black greyscale //} else { //cv::line(*img, cv::Point(pix.first, pix.second), cv::Point(pix2.first, pix2.second), cv::Scalar(255,255,0), 2); //cyan //} draw_triangle(img, center, tf::getYaw(people_->at(i).orientation), radius); } } } return true; } /** * Add the goal to the image */ bool Capture::addGoal(cv::Mat* img) { goal_ok_ = false; float radius = 0.20; //m int thickness = -1; int lineType = 8; //geometry_msgs::PoseStamped p = transformPoseTo(*goal_, "base_link", true); geometry_msgs::Point32 center; center.x = goal_->pose.position.x; //p.pose.position.x; center.y = goal_->pose.position.y; //p.pose.position.y; pair<int,int> pix = worldToImg(&center); if(pix.first >= 0 && pix.first < px_width_ && pix.second >= 0 && pix.second < px_height_) { if(greyscale_) cv::circle(*img, cv::Point(pix.first, pix.second), radius/resolution_, cv::Scalar(63), thickness, lineType); //greyscale else cv::circle(*img, cv::Point(pix.first, pix.second), radius/resolution_, cv::Scalar(255,0,0), thickness, lineType); //Blue goal_ok_ = true; } return true; } /** * Add the demo path to the image */ bool Capture::addPath(cv::Mat* img) { unsigned int lastPoint=0; for (unsigned int i=0; i<(agent_->size()-1); i++){ //geometry_msgs::PoseStamped p = transformPoseTo(path_->at(i), "base_link", true); geometry_msgs::Point32 p1; p1.x = agent_->at(i).pose.position.x; //p.pose.position.x; p1.y = agent_->at(i).pose.position.y; //p.pose.position.y; pair<int,int> pix1 = worldToImg(&p1); //p = transformPoseTo(path_->at(i+1), "base_link", true); geometry_msgs::Point32 p2; p2.x = agent_->at(i+1).pose.position.x; //p.pose.position.x; p2.y = agent_->at(i+1).pose.position.y; //p.pose.position.y; pair<int,int> pix2 = worldToImg(&p2); if(pix2.first >= 0 && pix2.first < px_width_ && pix2.second >= 0 && pix2.second < px_height_) { if(greyscale_) cv::line(*img, cv::Point(pix1.first, pix1.second), cv::Point(pix2.first, pix2.second), cv::Scalar(255), 3); //greyscale else cv::line(*img, cv::Point(pix1.first, pix1.second), cv::Point(pix2.first, pix2.second), cv::Scalar(255,255,255), 3); //white lastPoint = i+1; } } // We check if the path is outside the boundaries of the image. // In that case, we cut the path and take the last point as the goal if(lastPoint < (agent_->size()-1) && !goal_ok_){ goal_->header = agent_->at(lastPoint).header; goal_->pose = agent_->at(lastPoint).pose; } return true; } /** * Generate the image */ std::vector<int> Capture::generateImg(sensor_msgs::PointCloud* pc, vector<upo_msgs::PersonPoseUPO>* people, geometry_msgs::PoseStamped* goal) { setScenario(pc, people, goal); cv::Mat imgmat = generateImg(); if(save_img_){ char buf[10]; sprintf(buf, "input_%u", save_count_); string name = string(buf); string filename = save_path_ + "/saved_input/" + name + ".jpg"; imwrite(filename.c_str(), imgmat); save_count_++; } //cv::namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display. //cv::imshow( "Display window", imgmat ); //cv::waitKey(0); /*printf("Capture. Generating navigation image:\n"); //std::vector<int> img_array; //Transform mat to 1D array for(int i=0; i < imgmat.rows; i++) { for (int j =0; j < imgmat.cols; j++){ //img_array.push_back((int)imgmat.at<uchar>(i,j)); printf("%u", imgmat.at<uchar>(i,j)); } printf("\n"); }*/ std::vector<int> img_array; if (imgmat.isContinuous()) { img_array.assign(imgmat.datastart, imgmat.dataend); } else { for (int i = 0; i < imgmat.rows; ++i) { img_array.insert(img_array.end(), imgmat.ptr<uchar>(i), imgmat.ptr<uchar>(i)+imgmat.cols); } } return img_array; } /** * Generate and store the image */ cv::Mat Capture::generateImg() { cv::Mat img; //if(use_static_map) //{ // img = map_image_.clone(); //} else { // Create OpenCV mat image if(greyscale_) img = cv::Mat(px_width_, px_height_, CV_8UC1, cv::Scalar(0)); //greyscale (black) else img = cv::Mat(px_width_, px_height_, CV_8UC3, cv::Scalar::all(0)); //black //0. Draw robot axes in the center /*float longitude = 0.5; //m pair<int,int> p2; p2.first = px_origin_.first + (longitude/resolution_); p2.second = px_origin_.second; cv::line(img, cv::Point(px_origin_.first, px_origin_.second), cv::Point(p2.first, p2.second), cv::Scalar(0,0,255), 3); pair<int,int> p3; p3.first = px_origin_.first; p3.second = px_origin_.second-(longitude/resolution_); cv::line(img, cv::Point(px_origin_.first, px_origin_.second), cv::Point(p3.first, p3.second), cv::Scalar(0,255,0), 3); */ //Draw the robot position //float radius = 0.1; //m //int thickness = -1; //int lineType = 8; //cv::circle(img, cv::Point(px_origin_.first, px_origin_.second), radius/resolution_, cv::Scalar(255,255,255), thickness, lineType); //white //1. Add the laser readings (pointcloud) to the image addObstacles(&img); //2. Add the people detected to the image addPeople(&img); //3. Add the goal to the image addGoal(&img); return img; //5. Write file image //string time = currentDateTime(); //string filename = store_dir_ + name + ".jpg"; //imwrite(filename.c_str(), img); //cout << "Capture " << filename << " stored!!!" << endl; //6. If the demonstration path too /*if(add_demo_path_) { filename = store_dir_ + "labels/" + name + ".jpg"; if(only_path_label_) { cv::Mat img2; if(greyscale_) img2 = cv::Mat(px_width_, px_height_, CV_8UC1, cv::Scalar(0)); //greyscale else img2= cv::Mat(px_width_, px_height_, CV_8UC3, cv::Scalar::all(0)); //black addPath(&img2); imwrite(filename.c_str(), img2); } else { addPath(&img); imwrite(filename.c_str(), img); } cout << "Capture " << filename << " stored!!!" << endl; }*/ } <|start_filename|>rrt_planners/src/Action.cpp<|end_filename|> #include <rrt_planners/Action.h> // Constructor RRT::Action::Action() { vx_ = 0.0; vy_ = 0.0; vth_ = 0.0; steps_ = 1; } // Constructor RRT::Action::Action(float vx, float vy, float vth, unsigned int steps) { vx_ = vx; vy_ = vy; vth_ = vth; steps_ = steps; } // Destructor RRT::Action::~Action() { } void RRT::Action::getAction(float &vx, float &vy, float &vth, unsigned int &steps) { vx = vx_; vy = vy_; vth = vth_; steps = steps_; } float RRT::Action::getVx() { return vx_; } float RRT::Action::getVy() { return vy_; } float RRT::Action::getVth() { return vth_; } unsigned int RRT::Action::getSteps() { return steps_; } <|start_filename|>rrt_planners/src/ros/ValidityChecker2.cpp<|end_filename|> #include <upo_rrt_planners/ros/ValidityChecker2.h> #include <nav_msgs/Odometry.h> #include <Eigen/Core> #include <ros/console.h> upo_RRT_ros::ValidityChecker2::ValidityChecker2(nav_msgs::OccupancyGrid* costmap, tf::TransformListener* tf, unsigned int dimensions, int distType) : StateChecker() { costmap_mutex_.lock(); costmap_.clear(); for(unsigned int i=0; i<costmap->data.size(); i++) costmap_.push_back((int)costmap->data[i]); resolution_ = (float)costmap->info.resolution; //m/cell width_ = costmap->info.width; //cells height_ = costmap->info.height; //cells origin_.clear(); origin_.push_back(costmap->info.origin.position.x); //m origin_.push_back(costmap->info.origin.position.y); //m origin_.push_back(tf::getYaw(costmap->info.origin.orientation)); //rad costmap_mutex_.unlock(); tf_ = tf; dimensions_ = dimensions; distanceType_ = distType; time_ = ros::Time::now(); } upo_RRT_ros::ValidityChecker2::ValidityChecker2(tf::TransformListener* tf, unsigned int dimensions, int distType) : StateChecker() { tf_ = tf; dimensions_ = dimensions; distanceType_ = distType; time_ = ros::Time::now(); //Build a default costmap resolution_ = 0.05; //m/cell width_ = 100; //cells height_ = 100; //cells origin_.clear(); origin_.push_back(2.5); //m origin_.push_back(2.5); //m origin_.push_back(0.0); //rad costmap_mutex_.lock(); costmap_.clear(); for(unsigned int i=0; i<(width_*height_); i++) costmap_.push_back((int)0); costmap_mutex_.unlock(); } upo_RRT_ros::ValidityChecker2::~ValidityChecker2() { //delete navfeatures_; } void upo_RRT_ros::ValidityChecker2::updateCostmap(nav_msgs::OccupancyGrid* costmap) { costmap_mutex_.lock(); costmap_.clear(); for(unsigned int i=0; i<costmap->data.size(); i++) costmap_.push_back((int)costmap->data[i]); resolution_ = (float)costmap->info.resolution; width_ = costmap->info.width; height_ = costmap->info.height; origin_.clear(); origin_.push_back(costmap->info.origin.position.x); origin_.push_back(costmap->info.origin.position.y); origin_.push_back(tf::getYaw(costmap->info.origin.orientation)); costmap_mutex_.unlock(); } std::vector<int> upo_RRT_ros::ValidityChecker2::poseToCell(std::vector<float> pose) const { //Be careful, I'm not taking into account the rotation because is zero usually. //Pose is in robot frame coordinates, and the robot is centered in the costmap int x = fabs(origin_[0])/resolution_ + pose[0]/resolution_; int y = fabs(origin_[1])/resolution_ + pose[1]/resolution_; std::vector<int> cell; cell.push_back(x); cell.push_back(y); return cell; } std::vector<float> upo_RRT_ros::ValidityChecker2::cellToPose(std::vector<int> cell) const { //Be careful, I'm not taking into account the rotation because is zero usually. float x = (resolution_*cell[1] - origin_[0]); // + (resolution_/2.0); float y = (resolution_*cell[0] - origin_[1]); // + (resolution_/2.0); std::vector<float> pose; pose.push_back(x); pose.push_back(y); return pose; } bool upo_RRT_ros::ValidityChecker2::isValid(upo_RRT::State* s) const { std::vector<float> pose; pose.push_back((float)s->getX()); pose.push_back((float)s->getY()); //costmap_mutex_.lock(); std::vector<int> cell = poseToCell(pose); //printf("IsValid cell[%i][%i]\n", cell[0],cell[1]); int ind = cell[0]*200 + cell[1]; //printf("Indice: %i\n", ind); float cost = costmap_[ind]; //costmap_mutex_.unlock(); if(cost == -1 || cost > 100) //cost == 100 return false; else return true; } void upo_RRT_ros::ValidityChecker2::preplanning_computations() { } float upo_RRT_ros::ValidityChecker2::distance(upo_RRT::State* s1, upo_RRT::State* s2) const { float dx = s1->getX() - s2->getX(); float dy = s1->getY() - s2->getY(); //float dist = sqrt(dx*dx + dy*dy); float dist = dx*dx + dy*dy; switch(distanceType_) { case 1: return dist; case 2: return sqrt(dist); case 3: if(dimensions_ == 2) return sqrt(dist); else { //SUM w1*|| Pi+1 - Pi|| + w2*(1-|Qi+1 * Qi|)² float euc_dist = sqrt(dist); tf::Quaternion q1 = tf::createQuaternionFromYaw(s1->getYaw()); tf::Quaternion q2 = tf::createQuaternionFromYaw(s2->getYaw()); float dot_prod = q1.dot(q2); float angle_dist = (1 - fabs(dot_prod))*(1 - fabs(dot_prod)); //printf("eu_dist: %.2f, angle_dist: %.3f, dist: %.3f\n", euc_dist, angle_dist, 0.8*euc_dist + 0.2*angle_dist); return 0.7*euc_dist + 0.3*angle_dist; } case 4: if(dimensions_ == 2) return sqrt(dist); else { // Another option /* First, transform the robot location into person location frame: |cos(th) sin(th) 0| Rotation matrix R(th)= |-sin(th) cos(th) 0| | 0 0 1| x' = (xr-xp)*cos(th_p)+(yr-yp)*sin(th_p) y' = (xr-xp)*(-sin(th_p))+(yr-yp)*cos(th_p) */ float x = (s2->getX()-s1->getX())*cos(s1->getYaw()) + (s2->getY()-s1->getY())*sin(s1->getYaw()); float y =-(s2->getX()-s1->getX())*sin(s1->getYaw()) + (s2->getY()-s1->getY())*cos(s1->getYaw()); float alpha = atan2(y, x); return (0.8*sqrt(dist)+0.2*fabs(alpha)); } case 5: if(dimensions_ == 2) return sqrt(dist); else { //UPO. Dist + sum of the angles of both points regarding the intersection line float x = (s2->getX()-s1->getX())*cos(s1->getYaw()) + (s2->getY()-s1->getY())*sin(s1->getYaw()); float y =-(s2->getX()-s1->getX())*sin(s1->getYaw()) + (s2->getY()-s1->getY())*cos(s1->getYaw()); float alpha = atan2(y, x); float beta = s2->getYaw() - alpha; beta = normalizeAngle(beta, -M_PI, M_PI); return (0.6*sqrt(dist)+0.4*(fabs(alpha)+fabs(beta))); } case 6: if(dimensions_ == 2) return sqrt(dist); else { //Paper IROS2015 "Feedback motion planning via non-holonomic RRT* for mobile robots" float x = (s2->getX()-s1->getX())*cos(s1->getYaw()) + (s2->getY()-s1->getY())*sin(s1->getYaw()); float y =-(s2->getX()-s1->getX())*sin(s1->getYaw()) + (s2->getY()-s1->getY())*cos(s1->getYaw()); float alpha = atan2(y, x); float phi = s2->getYaw() - alpha; phi = normalizeAngle(phi, -M_PI, M_PI); float ka = 0.5; float ko = ka/8.0; dist = sqrt(dist); // two options float alpha_prime = atan(-ko*phi); //float alpha_prime = atan(-ko*ko * phi/(dist*dist)); float r = normalizeAngle((alpha-alpha_prime), -M_PI, M_PI); return (sqrt(dist*dist + ko*ko + phi*phi) + ka*fabs(r)); } default: return sqrt(dist); } } float upo_RRT_ros::ValidityChecker2::getCost(upo_RRT::State* s) { //cell.first = x = column, cell.second = y = row std::vector<float> pose; pose.push_back((float)s->getX()); pose.push_back((float)s->getY()); costmap_mutex_.lock(); std::vector<int> cell = poseToCell(pose); int ind = (cell[1]+1) * cell[0]; //row*column float cost = costmap_[ind]; costmap_mutex_.unlock(); return cost; } /*void upo_RRT_ros::ValidityChecker::setPeople(upo_msgs::PersonPoseArrayUPO p) { navfeatures_->setPeople(p); } void upo_RRT_ros::ValidityChecker::setWeights(std::vector<float> we) { navfeatures_->setWeights(we); }*/ geometry_msgs::PoseStamped upo_RRT_ros::ValidityChecker2::transformPoseTo(geometry_msgs::PoseStamped pose_in, std::string frame_out, bool usetime) { geometry_msgs::PoseStamped in = pose_in; if(!usetime) in.header.stamp = ros::Time(); geometry_msgs::PoseStamped pose_out; try { tf_->transformPose(frame_out.c_str(), in, pose_out); }catch (tf::TransformException ex){ ROS_WARN("ValidityChecker2. TransformException in method transformPoseTo. TargetFrame: %s : %s", frame_out.c_str(), ex.what()); } return pose_out; } bool upo_RRT_ros::ValidityChecker2::isQuaternionValid(const geometry_msgs::Quaternion q) { //first we need to check if the quaternion has nan's or infs if(!std::isfinite(q.x) || !std::isfinite(q.y) || !std::isfinite(q.z) || !std::isfinite(q.w)){ ROS_ERROR("Quaternion has infs!!!!"); return false; } if(std::isnan(q.x) || std::isnan(q.y) || std::isnan(q.z) || std::isnan(q.w)) { ROS_ERROR("Quaternion has nans !!!"); return false; } if(std::fabs(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w - 1) > 0.01) { ROS_ERROR("Quaternion malformed, magnitude: %.3f should be 1.0", (q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w)); return false; } tf::Quaternion tf_q(q.x, q.y, q.z, q.w); //next, we need to check if the length of the quaternion is close to zero if(tf_q.length2() < 1e-6){ ROS_ERROR("Quaternion has length close to zero... discarding."); return false; } //next, we'll normalize the quaternion and check that it transforms the vertical vector correctly tf_q.normalize(); tf::Vector3 up(0, 0, 1); double dot = up.dot(up.rotate(tf_q.getAxis(), tf_q.getAngle())); if(fabs(dot - 1) > 1e-3){ ROS_ERROR("Quaternion is invalid... for navigation the z-axis of the quaternion must be close to vertical."); return false; } return true; } <|start_filename|>local_3d_planner/src/local_3d_planner_ros.cpp<|end_filename|> /********************************************************************* * * Software License Agreement (BSD License) * * * Author: <NAME> *********************************************************************/ #include <local_3d_planner/local_3d_planner_ros.h> #include <sys/time.h> #include <boost/tokenizer.hpp> #include <Eigen/Core> #include <cmath> #include <ros/console.h> #include <pluginlib/class_list_macros.h> #include <local_3d_planner/goal_functions.h> #include <nav_msgs/Path.h> // register this planner as a BaseLocalPlanner plugin PLUGINLIB_EXPORT_CLASS(local_3d_planner::Local3DPlannerROS, nav_core::BaseLocalPlanner) namespace local_3d_planner { // void PurePlannerROS::reconfigureCB(SimpleLocalPlannerConfig &config, uint32_t level) { /*if (setup_ && config.restore_defaults) { config = default_config_; //Avoid looping config.restore_defaults = false; } if ( ! setup_) { default_config_ = config; setup_ = true; }*/ // tc_->reconfigure(config); // reached_goal_ = false; //} Local3DPlannerROS::Local3DPlannerROS() : tc_(NULL), tf_(NULL), setup_(false), initialized_(false), odom_helper_("odom") { } Local3DPlannerROS::Local3DPlannerROS(std::string name, tf2_ros::Buffer* tf, costmap_2d::Costmap2DROS* costmap_ros) : tc_(NULL), tf_(NULL), setup_(false), initialized_(false), odom_helper_("odom") { // initialize the planner initialize(name, tf, NULL); } void Local3DPlannerROS::initialize(std::string name, tf2_ros::Buffer* tf, costmap_2d::Costmap2DROS* costmap_ros) { if (!isInitialized()) { ros::NodeHandle private_nh("/" + name); g_plan_pub_ = private_nh.advertise<nav_msgs::Path>("global_plan", 1); l_plan_pub_ = private_nh.advertise<nav_msgs::Path>("local_plan", 1); tf_ = tf; ros::NodeHandle nh("~/" + name); std::string odom_topic; nh.param("odometry_topic", odom_topic, std::string("odom")); odom_helper_.setOdomTopic(odom_topic); nh.param("global_frame", global_frame_, std::string("odom")); // printf("local_3d_planner_ros.cpp. global_frame: %s\n", global_frame_.c_str()); nh.param("base_frame", robot_base_frame_, std::string("base_link")); // Robot Configuration Parameters nh.param("max_trans_vel", max_vel_x_, 0.6); nh.param("min_trans_vel", min_vel_x_, 0.1); nh.param("max_rot_vel", max_vel_th_, 0.8); nh.param("min_rot_vel", min_vel_th_, 0.1); nh.param("max_trans_acc", max_trans_acc_, 1.0); nh.param("max_rot_acc", max_rot_acc_, 1.0); nh.param("min_in_place_rot_vel", min_in_place_vel_th_, 0.5); // Goal tolerance parameters nh.param("yaw_goal_tolerance", yaw_goal_tolerance_, 0.12); nh.param("xyz_goal_tolerance", xyz_goal_tolerance_, 0.20); nh.param("wp_tolerance", wp_tolerance_, 0.5); nh.param("sim_time", sim_time_, 1.0); nh.param("sim_granularity", sim_granularity_, 0.025); nh.param("angular_sim_granularity", angular_sim_granularity_, sim_granularity_); // Assuming this planner is being run within the navigation stack, we can // just do an upward search for the frequency at which its being run. This // also allows the frequency to be overwritten locally. nh.param("controller_freq", controller_freq_, 15.0); bool dwa; nh.param("dwa", dwa, true); nh.param("robot_radius", robot_radius_, 0.345); nh.param("local_area_radius", local_area_radius_, 1.0); // footprint_spec_ = costmap_ros_->getRobotFootprint(); tc_ = new Local3DPlanner(name, tf_, &odom_helper_, robot_radius_, local_area_radius_, controller_freq_, max_vel_x_, min_vel_x_, max_vel_th_, min_vel_th_, min_in_place_vel_th_, max_trans_acc_, max_rot_acc_, yaw_goal_tolerance_, xyz_goal_tolerance_, wp_tolerance_, sim_time_, sim_granularity_, angular_sim_granularity_, dwa); initialized_ = true; // BE CAREFUL, this will load the values of cfg params overwritting the read ones from // the yaml file. // dsrv_ = new dynamic_reconfigure::Server<SimpleLocalPlannerConfig>(private_nh); // dynamic_reconfigure::Server<SimpleLocalPlannerConfig>::CallbackType cb = // boost::bind(&PurePlannerROS::reconfigureCB, this, _1, _2); // dsrv_->setCallback(cb); } else { ROS_WARN("This planner has already been initialized, doing nothing"); } } Local3DPlannerROS::~Local3DPlannerROS() { // make sure to clean things up // delete dsrv_; if (tc_ != NULL) delete tc_; } bool Local3DPlannerROS::setPlan(const std::vector<geometry_msgs::PoseStamped>& orig_global_plan) { if (!isInitialized()) { ROS_ERROR("This planner has not been initialized, please call initialize() before using this planner"); return false; } // reset the global plan global_plan_.clear(); global_plan_ = orig_global_plan; // reset the goal flag reached_goal_ = false; return true; } bool Local3DPlannerROS::computeVelocityCommands(geometry_msgs::Twist& cmd_vel) { if (!isInitialized()) { ROS_ERROR("This planner has not been initialized, please call initialize() before using this planner"); return false; } std::vector<geometry_msgs::PoseStamped> local_plan; /* tf::Stamped<tf::Pose> global_pose; tf::Stamped<tf::Pose> robot_orig; geometry_msgs::PoseStamped ro; ro.header.frame_id = robot_base_frame_; ro.header.stamp = ros::Time(); ro.pose.position.x = 0.0; ro.pose.position.y = 0.0; ro.pose.position.z = 0.0; ro.pose.orientation = tf::createQuaternionMsgFromYaw(0.0); tf::poseStampedMsgToTF(ro, robot_orig); tf_->transformPose(global_frame_, robot_orig, global_pose); */ // tf::Stamped<tf::Pose> global_pose; geometry_msgs::PoseStamped global_pose; nav_msgs::Odometry odom; odom_helper_.getOdom(odom); // tf::Stamped<tf::Pose> rg; geometry_msgs::PoseStamped ro; ro.header = odom.header; ro.pose.position = odom.pose.pose.position; ro.pose.orientation = odom.pose.pose.orientation; // tf::poseStampedMsgToTF(ro, rg); if (odom.header.frame_id != global_frame_) { global_pose = tf_->transform(ro, global_frame_); } else global_pose = ro; // TODO: Check here if we have already reached the goal // In case that the global plan is in map frame, we tranform it to local frame (odom) // and we cut the part that lies on the local area std::vector<geometry_msgs::PoseStamped> transformed_plan; if (!transformGlobalPlan(*tf_, global_plan_, global_pose, global_frame_, local_area_radius_, transformed_plan)) { // TransformGlobalPlan belongs to goal_functions.cpp ROS_WARN("Could not transform the global plan to the frame of the controller"); return false; } // now we'll prune the plan based on the position of the robot // if(prune_plan_) prunePlan(global_pose, transformed_plan, global_plan_); // PrunePlan belongs to goal_functions.cpp geometry_msgs::PoseStamped robot_vel; odom_helper_.getRobotVel(robot_vel); /* For timing uncomment struct timeval start, end; double start_t, end_t, t_diff; gettimeofday(&start, NULL); */ // if the global plan passed in is empty... we won't do anything if (transformed_plan.empty()) return false; tc_->updatePlan(transformed_plan); geometry_msgs::Twist drive_cmds; bool ok = tc_->findBestAction(global_pose, robot_vel, drive_cmds); /* For timing uncomment gettimeofday(&end, NULL); start_t = start.tv_sec + double(start.tv_usec) / 1e6; end_t = end.tv_sec + double(end.tv_usec) / 1e6; t_diff = end_t - start_t; ROS_INFO("Cycle time: %.9f", t_diff); */ // pass along drive commands cmd_vel = drive_cmds; if (!ok) { ROS_DEBUG_NAMED("local_3d_planner_ros", "The local_3d_planner failed to find a valid plan. This means that the footprint of the robot was in collision for all simulated trajectories."); ROS_WARN("ComputeVelocityCommands. The local_3d_planner failed to find a valid plan. This means that the footprint of the robot was in collision for all simulated trajectories."); publishPlan(transformed_plan, g_plan_pub_); return false; } // publish information to the visualizer publishPlan(transformed_plan, g_plan_pub_); // publishPlan(local_plan, l_plan_pub_); return true; } bool Local3DPlannerROS::isGoalReached() { if (!isInitialized()) { ROS_ERROR("This planner has not been initialized, please call initialize() before using this planner"); return false; } // return flag set in controller // return reached_goal_; return tc_->isGoalReached(); } }; <|start_filename|>rrt_planners/include/rrt_planners/planners/control/RRT_not_used.h<|end_filename|> #ifndef RRT_RRT_ #define RRT_RRT_ #include <rrt_planners/StateSpace.h> #include <rrt_planners/State.h> #include <rrt_planners/Action.h> #include <rrt_planners/Node.h> #include <rrt_planners/StateChecker.h> #include <rrt_planners/NearestNeighborsFLANN.h> #include <rrt_planners/NearestNeighbors.h> #include <rrt_planners/planners/Planner.h> #include <vector> #include <cmath> #include <stdio.h> #include <iostream> #include <sys/time.h> namespace RRT { class RRT : public RRT::Planner { public: RRT(); ~RRT(); bool steer(Node* fromNode, Node* toNode, Node* newNode); std::vector<RRT::Node> solve(float secs); /*void setMaxRange(float range) { maxRange_ = range; }*/ void setTimeStep(float step) { steering_->setTimeStep(step); } void setControlSteps(int min_steps, int max_steps) { steering_->setMinMaxSteps(min_steps, max_steps); } void setRobotAcc(float linear_acc, float angular_acc) { steering_->setAccelerations(linear_acc, angular_acc); } void setAccompanySteer(bool s){ accompany_steer_ = s; } private: bool accompany_steer_; //float maxRange_; //max distance to insert a new node //float timeStep_; //should be 1/freq with freq = freq of the controller(15~20Hz) //int minControlSteps_; //minTime = timeStep*minControlDuration //int maxControlSteps_; }; } #endif <|start_filename|>rrt_planners/include/rrt_planners/State.h<|end_filename|> #ifndef RRT_STATE_ #define RRT_STATE_ namespace RRT { /** * \brief Class representing a state in 6DoF * */ class State { public: State(); State(float x, float y, float z = 0.0, float yaw = 0.0, float roll = 0.0, float pitch = 0.0, float lv = 0.0, float av = 0.0); ~State(); void getState(float &x, float &y, float &z, float &yaw, float &roll, float &pitch, float &lv, float &av); float getX() const; float getY() const; float getZ() const; float getYaw() const; float getRoll() const; float getPitch() const; float getLinVel() const; float getAngVel() const; void setX(float x); void setY(float y); void setZ(float z); void setYaw(float yaw); void setRoll(float roll); void setPitch(float pitch); void setLv(float lv); void setAv(float av); float operator()(int index) const { switch (index) { case 0: return x_; case 1: return y_; case 2: return z_; case 3: return yaw_; case 4: return roll_; case 5: return pitch_; case 6: return lin_vel_; case 7: return ang_vel_; default: return x_; } } float operator[](int index) const { switch (index) { case 0: return x_; case 1: return y_; case 2: return z_; case 3: return yaw_; case 4: return roll_; case 5: return pitch_; case 6: return lin_vel_; case 7: return ang_vel_; default: return x_; } } bool operator==(const State &other) const { return (x_ == other.x_ && y_ == other.y_ && z_ == other.z_); } private: float x_; float y_; float z_; float yaw_; float roll_; float pitch_; float lin_vel_; float ang_vel_; }; } #endif
Tutorgaming/indires_navigation
<|start_filename|>src/web/ui/CurrentPrice.css<|end_filename|> .sparkswap h1.current-price { margin: 0 auto; text-align: left; margin-bottom: 0.2em; } .sparkswap h1.current-price .subtitle { display: block; margin-left: 0; line-height: 12px; margin-bottom: 0.5em; } .sparkswap h6.current-price .subtitle { padding-right: 0.5em; } <|start_filename|>src/web/ui/components/TxCard.css<|end_filename|> .sparkswap .bp3-card.transaction { display: flex; } .sparkswap .transaction>* { flex: 1; } .sparkswap .transaction>.bp3-icon, .sparkswap .transaction>.bp3-spinner { max-width: 18px; margin-right: 12px; } .sparkswap .transaction>.bp3-icon { margin-top: 9px; } .sparkswap .transaction .bp3-heading { /* align all elements of the card */ line-height: 18px; margin-bottom: 0; } .sparkswap .transaction .bp3-heading .subtitle { margin-left: 0; } .sparkswap .transaction .extra-info .subtitle { margin-right: 0.5em; } .sparkswap .transaction .extra-info .tx-link { color: rgba(245,248,250, 0.4); font-size: 13px; } .sparkswap .transaction .amounts { text-align: right; } <|start_filename|>package.json<|end_filename|> { "name": "sparkswap-desktop", "author": "Sparkswap <<EMAIL>> (https://github.com/sparkswap)", "description": "Sparkswap Desktop: the only way to buy Bitcoin instantly", "productName": "Sparkswap", "version": "0.4.2", "license": "MIT", "private": true, "main": "./build/electron.js", "repository": { "type": "git", "url": "https://github.com/sparkswap/sparkswap-desktop.git" }, "devDependencies": { "@types/better-sqlite3": "5.4.0", "@types/fs-extra": "8.0.0", "@types/js-yaml": "3.12.1", "@types/node": "12.12.11", "@types/node-fetch": "2.5.0", "@typescript-eslint/eslint-plugin": "2.7.0", "@typescript-eslint/parser": "2.7.0", "electron": "6.0.7", "electron-builder": "21.2.0", "electron-notarize": "0.1.1", "eslint": "6.6.0", "eslint-config-standard": "13.0.1", "eslint-plugin-import": "2.18.0", "eslint-plugin-node": "9.1.0", "eslint-plugin-promise": "4.2.1", "eslint-plugin-react": "7.14.3", "eslint-plugin-standard": "4.0.0", "foreman": "3.0.1", "please-update-dependencies": "2.0.0", "react-app-rewired": "2.1.3", "yarn": "1.22.0" }, "dependencies": { "@blueprintjs/core": "3.15.1", "@blueprintjs/select": "3.10.0", "@types/react": "16.8.23", "@types/react-dom": "16.8.4", "@types/uuid": "3.4.5", "berbix-react": "0.0.8", "better-sqlite3": "5.4.3", "btcnodejs": "0.1.3", "chart.js": "2.8.0", "electron-updater": "4.1.2", "js-yaml": "3.13.1", "lnd-engine": "github:sparkswap/lnd-engine#v0.10.0-beta", "node-fetch": "2.6.0", "react": "16.8.6", "react-chartjs-2": "2.7.6", "react-dom": "16.8.6", "react-scripts": "3.2.0", "ts-node": "8.3.0", "typescript": "3.7.2", "uuid": "3.3.2" }, "scripts": { "start-electron": "NODE_PRESERVE_SYMLINKS=1 electron", "start": "nf start --raw", "react-start": "BROWSER=none react-app-rewired start --scripts-version react-scripts", "build": "react-app-rewired build --scripts-version react-scripts", "build-test": "REACT_APP_ENV=test npm run build", "test": "npm run typecheck", "test-web": "react-app-rewired test --scripts-version react-scripts", "ci-test": "npm run typecheck && npm run lint", "typecheck": "npm run typecheck-web && npm run typecheck-node", "typecheck-web": "tsc --noEmit", "typecheck-node": "tsc -p tsconfig.node.json --noEmit", "userdata": "npm run start-electron -- ./scripts/get-user-data-path.js", "db": "sqlite3 \"$(npm run --silent userdata)/sparkswap-data.sqlite\"", "drop": "rm \"$(npm run --silent userdata)/sparkswap-data.sqlite\"", "dev": "NODE_ENV=development npm start | sed '/^$/d'", "eject": "react-scripts eject", "lint": "npm run lint-web && npm run lint-node", "lint-web": "eslint -c .eslintrc.web.js --max-warnings=0 --ext .ts,.tsx,.js,.jsx ./src/global-shared ./src/web ./src/common", "lint-node": "eslint -c .eslintrc.node.js --max-warnings=0 --ext .ts,.js ./src/global-shared ./src/node ./src/common", "electron": "npm run start-electron -- ./src/node/ts-node.js", "build-prod": "npm run build && npm run build-node", "build-node": "tsc -p tsconfig.node.json && rsync -av --exclude '**/*.ts' --exclude '**/*.js' src/node build/src", "package": "electron-builder", "prepackage": "npm run build-prod", "package-mac": "npm run package -- --mac", "package-mac-notarize": "NOTARIZE=true npm run package -- --mac", "package-linux": "npm run package -- --linux", "package-win": "npm run package -- --win", "package-all": "NOTARIZE=true npm run package -- -mwl", "publish": "npm run package -- --publish always", "publish-win": "npm run package-win -- --publish always", "publish-mac": "NOTARIZE=true npm run package-mac -- --publish always", "publish-linux": "npm run package-linux -- --publish always", "publish-all": "NOTARIZE=true npm run package -- -mwl --publish always", "publish-client-code": "bash ./scripts/publish-client-code.sh" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "homepage": "./" } <|start_filename|>src/web/ui/components/InlineTooltip.css<|end_filename|> .InlineTooltip { display: inline-block; } .InlineTooltip .bp3-popover-wrapper, label.bp3-label .InlineTooltip .bp3-popover-wrapper { margin-left: 0.5em; display: inline-block; } .InlineIcon { color: #5C7080; margin-bottom: 2px; } <|start_filename|>src/web/ui/components/EmptyableList.css<|end_filename|> .EmptyableList { overflow-y: scroll; } .EmptyableList .bp3-non-ideal-state { height: 100%; } <|start_filename|>src/web/ui/account/ChannelCard.css<|end_filename|> .Channel { display: flex; } .Channel > *, .Channel .bp3-heading { margin-bottom: 0; line-height: 24px; } .Channel > *:last-child { margin-left: 0.5em; } .Channel.collapsed .details { display: none; } .Channel > .channel-balance { text-align: right; width: 215px; flex-shrink: 1; } .Channel .channel-balance .subtitle { margin-right: 0.75em; margin-left: 0; } .Channel .channel-balance .balance-units .subtitle { margin-right: 0; } .Channel .channel-status { font-weight: 400; text-align: right; flex: 1; } .Channel .channel-status .StatusBadge { margin-bottom: 1px; } .Channel .channel-actions { min-width: 105px; flex: 1; } .Channel .channel-actions .channel-close { margin-top: 0.9em; float: right; } .Channel .channel-actions .channel-status > .bp3-icon { color: #a7b6c2; vertical-align: middle; margin-left: 0.75em; } .Channel > .channel-peer { min-width: 150px; flex: 1; } .Channel h5.channel-peer .channel-id { margin-left: 0.5em; text-align: right; } .Channel.expanded h5.channel-peer .pubkey, .Channel.expanded h5.channel-peer .channel-tx { display: block; font-size: 13px; margin-left: 0; width: 150px; line-height: 1.3em; margin-top: 0.25em; margin-bottom: 0.5em; } .Channel .channel-peer .pubkey a, .Channel .channel-peer .channel-tx a { color: rgba(245,248,250, 0.4); } <|start_filename|>src/web/ui/MainContent.css<|end_filename|> .main-content-tabs { height: 100%; width: 100%; position: relative; padding-top: 50px; } .main-content-tabs > .bp3-tab-list { position: absolute; top: 0; left: 0; } .main-content-tabs > .bp3-tab-list .bp3-tab { margin-right: 29px; } .main-content-tabs > .bp3-tab-list .bp3-tab.history-tab.new-history { margin-right: 8px; } .main-content-tabs > .bp3-tab-panel { margin-top: 0; height: calc(100%); width: 100%; } .main-content-tabs .main-content-spinner .bp3-spinner { position: relative; top: 50%; margin-top: -72px; } .bp3-menu.account-select { min-width: 82px; } <|start_filename|>src/web/ui/account/Account.css<|end_filename|> .Account, .Account .bp3-tabs, .Account .bp3-tab-panel { height: 100%; } .Account .balance-details { width: 100%; } .Account .balance-details tr td:first-child, .Account .balance-details tr th:first-child { padding-left: 0; } .Account .balance-details tr td:last-child, .Account .balance-details tr th:last-child { padding-right: 0; } .Account .balance-details .subtitle { display: block; min-height: 16px; } .Account .account-actions { float: right; padding-right: 2px; } .Account .account-actions .request-channel { margin-right: 1em; } .Account .switch-asset { display: inline-block; margin-left: 1em; } .Account .TabContent { height: calc(100% - 175px); } <|start_filename|>src/web/ui/App.css<|end_filename|> @import url("https://fonts.googleapis.com/css?family=Encode+Sans&text=₿"); html { height: 100%; } ::-webkit-scrollbar { width: 0px; /* Remove scrollbar space */ background: transparent; /* make scrollbar invisible */ } body { height: 100%; width: 100%; } #root { height: 100%; } body.sparkswap { background-color: #293742; background-image: linear-gradient( to top right, rgba(27, 34, 42, 1), rgba(41, 52, 59, 1) ); background-attachment: fixed; font-family: -apple-system, "BlinkMacSystemFont", "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Open Sans", "Helvetica Neue", "Icons16", sans-serif, "Encode Sans"; } .App { padding: 60px 30px; height: 100%; } .App .chrome-title { height: 40px; width: 100%; -webkit-app-region: drag; text-align: right; position: fixed; left: 0; top: 0; z-index: 21; } .App .logo { position: fixed; width: 20px; height: 20px; top: 40px; right: 30px; z-index: 21; } .App .chrome-title button { -webkit-app-region: no-drag; cursor: pointer; } .App .chrome-title + .current-price { position: fixed; top: 38px; /* based on .App .logo's and positioning + 40px*/ right: 260px; z-index: 1; line-height: 1.7em; } .App .help-link { position: fixed; bottom: 20px; right: 30px; z-index: 22; padding-right: 0; } .bp3-dark.sparkswap .error { color: #DB3737; } .bp3-dark.sparkswap .error.text-muted { color: rgba(255, 115, 115, 0.5) } .app-content { display: flex; flex-direction: row; align-items: stretch; height: 100%; overflow: hidden; } .main-content { flex: auto; min-width: 460px; } .tools-content { flex: initial; display: flex; flex-direction: column; min-width: 325px; max-width: 325px; height: 100%; } .tools-content > * { flex-shrink: 0; } .tools-content .DCA { flex-grow: 1; flex-shrink: 1; margin-bottom: 20px; } .vertical-line { margin: 0 30px; margin-top: 10px; max-width: 1px; min-width: 1px; background-color: rgba(90, 103, 112, 0.50); } /* Spinners */ .bp3-spinner.invisible { visibility: hidden; } /* Fonts */ .sparkswap h1.bp3-heading { font-size: 38px; } .sparkswap .subtitle { color: rgba(245,248,250, 0.4); font-size: 0.9em; } .sparkswap .bp3-heading .subtitle { font-size: 0.35em; font-weight: bold; margin-left: 1.5em; } .sparkswap h5.bp3-heading .subtitle { font-size: 0.95em; font-weight: 400; } .sparkswap h6.bp3-heading .subtitle { font-size: 1em; font-weight: 400; } /* Links */ .sparkswap.bp3-dark a, .sparkswap.bp3-dark a:hover, .sparkswap.bp3-dark a:active { text-decoration: underline; color: #f5f8fa; } .sparkswap.bp3-dark a:hover, .sparkswap.bp3-dark a:active { opacity: 0.8; } .sparkswap.bp3-dark a .bp3-icon, .sparkswap.bp3-dark a:hover .bp3-icon, .sparkswap.bp3-dark a:active .bp3-icon { text-decoration: none; } .sparkswap.bp3-dark a.bp3-button, .sparkswap.bp3-dark a.bp3-button:hover, .sparkswap.bp3-dark a.bp3-button:active { text-decoration: none; opacity: inherit; } a .bp3-icon { margin: 0 0.5em; } /* Animations */ @keyframes red-color-change { 0% { color: #f0413b; } 100% { color: #f5f8fa; } } @keyframes green-color-change { 0% { color: #3DCC91; } 100% { color: #f5f8fa; } } @keyframes gray-color-change { 0% { color: #aaaaaa; } 100% { color: #f5f8fa; } } .PulseGray, .PulseGray input { animation: gray-color-change 1s 1; } .PulseRed, .PulseRed input { animation: red-color-change 1s 1; } .PulseGreen, .PulseGreen input { animation: green-color-change 1s 1; } .sparkswap .placeholder, .sparkswap table.bp3-html-table .placeholder td { color: rgba(191,204,214,.5); } /* Inputs */ .bp3-dark.sparkswap .bp3-input { background-color: #1b2129; box-shadow: none; } /* Buttons */ .bp3-dark.sparkswap .bp3-button:not([class*="bp3-intent-"], [class="bp3-disabled"]) { box-shadow: 0 0 10px 0 rgba(16, 22, 26, 0.1); background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0.03), rgba(255, 255, 255, 0)); } .bp3-dark.sparkswap .bp3-button:not([class*="bp3-intent-"], [class="bp3-disabled"]):hover { box-shadow: 0 0 10px 0 rgba(16, 22, 26, 0.1); background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0.03), rgba(255, 255, 255, 0)); background-color: #546879; } .bp3-dark.sparkswap .bp3-button:not([class*="bp3-intent-"], [class="bp3-disabled"]):active { background-color: #374754; box-shadow: none; } .bp3-dark.sparkswap .bp3-button.bp3-minimal { box-shadow: none; background: none; color: rgba(245,248,250, 0.4); } .bp3-dark.sparkswap .bp3-button.bp3-minimal .bp3-icon { color: rgba(245,248,250, 0.4); } .bp3-dark.sparkswap .bp3-button.bp3-minimal:hover, .bp3-dark.sparkswap .bp3-button.bp3-minimal:active { background: none; color: rgba(245,248,250, 0.7); } .bp3-dark.sparkswap .bp3-button.bp3-minimal:hover .bp3-icon, .bp3-dark.sparkswap .bp3-button.bp3-minimal:active .bp3-icon { color: rgba(245,248,250, 0.7); } .bp3-dark.sparkswap .bp3-button.bp3-minimal.link-button { padding: 0px; padding-bottom: 2px; min-height: 0px; } /* Dialogs */ .bp3-dark.sparkswap .bp3-overlay-backdrop { backdrop-filter: blur(2px); } .bp3-portal { z-index: 22; } .bp3-portal.portal-behind { z-index: 21; } .bp3-dark.sparkswap .bp3-dialog { width: 360px; background-color: rgba(16, 22, 26, 0.85); box-shadow: none; padding-bottom: 15px; } .bp3-dark.sparkswap .bp3-dialog.bp3-alert { width: 500px; } .bp3-dark.sparkswap .bp3-dialog .bp3-dialog-header { background: none; box-shadow: none; padding-left: 15px; } .sparkswap .bp3-dialog .bp3-dialog-body { min-height: 419px; margin: 15px; margin-top: 5px; } .sparkswap .bp3-dialog .bp3-dialog-body .bp3-heading { margin-bottom: 20px; } .sparkswap .bp3-dialog .bp3-dialog-body .bp3-callout .bp3-heading { margin-bottom: 5px; } .sparkswap .bp3-dialog .bp3-dialog-body p { margin-top: 10px; } .sparkswap .bp3-dialog .bp3-dialog-footer { margin: 0 15px; } .sparkswap .bp3-dialog .bp3-dialog-footer>.bp3-button.bp3-minimal { padding-left: 1px; padding-right: 1px; } .sparkswap .bp3-dialog .bp3-dialog-footer>.bp3-button.bp3-minimal:last-of-type { float: right; } .sparkswap .bp3-dialog .bp3-dialog-footer>.bp3-button.bp3-minimal:first-child { float: none; } .sparkswap .bp3-dialog .bp3-dialog-footer-actions .bp3-button { padding: 13px 20px; } .sparkswap .bp3-dialog .bp3-dialog-footer-actions .bp3-button.bp3-fill:only-child { margin-left: 0; } /* Skeleton */ /* Make the beginning of the loading 0 opacity to reduce flicker */ .bp3-dark.sparkswap .bp3-skeleton { border-color: rgba(0, 0, 0, 0); background: rgba(0, 0, 0, 0); animation: 1000ms linear infinite alternate gentle-glow; animation-delay: 500ms; } @keyframes gentle-glow { 0% { border-color: rgba(92, 112, 128, 0.0); background: rgba(92, 112, 128, 0.0); } 100% { border-color: rgba(206, 217, 224, 0.2); background: rgba(206, 217, 224, 0.2); } } /* Asset Switcher */ .sparkswap.bp3-dark .switch-asset.bp3-control.bp3-switch input ~ .bp3-control-indicator, .sparkswap.bp3-dark .switch-asset.bp3-control.bp3-switch input:checked ~ .bp3-control-indicator { background: rgba(16, 22, 26, 0.5); } .sparkswap.bp3-dark .switch-asset.bp3-control.bp3-switch input:checked ~ .bp3-control-indicator::before { box-shadow: 0 0 0 1px rgba(16, 22, 26, 0.4); } .sparkswap.bp3-dark .switch-asset.bp3-control.bp3-switch:hover input ~ .bp3-control-indicator, .sparkswap.bp3-dark .switch-asset.bp3-control.bp3-switch:hover input:checked ~ .bp3-control-indicator { background: rgba(16, 22, 26, 0.7); } /* Shared table */ /* monospace amounts to make things line up */ .trade-table tbody .trade-amount { font-family: 'B612 Mono', monospace; font-size: 0.95em; text-align: right; } table.bp3-html-table.bp3-html-table-condensed.trade-table tbody td.trade-amount.usd { position: relative; padding-left: 20px; } .trade-table tbody .trade-amount.usd::before { display: inline; content: '$'; color: #828f99; text-align: left; position: absolute; left: 10px } /* Cards */ .sparkswap.bp3-dark .bp3-card{ padding: 15px 20px 15px 18px; background-color: rgba(48, 64, 77, 0.4); margin-right: 1px; margin-left: 1px; } .sparkswap .bp3-card:first-child { margin-top: 1px; } .sparkswap .bp3-card:not(:first-child) { border-top-right-radius: 0; border-top-left-radius: 0; } .sparkswap .bp3-card:last-of-type { margin-bottom: 2px; } .sparkswap .bp3-card:not(:last-of-type) { border-bottom-left-radius: 0; border-bottom-right-radius: 0; } /* Tabs */ .sparkswap.bp3-dark .bp3-tab { color: rgba(245,248,250, 0.6) } .sparkswap.bp3-dark .bp3-tab-indicator { background-color: #f5f8fa; } .sparkswap.bp3-dark .bp3-tab:not([aria-disabled="true"]):hover, .sparkswap.bp3-dark .bp3-tab[aria-selected="true"] { color: #f5f8fa; } <|start_filename|>src/web/ui/Prices.css<|end_filename|> .PriceChart { height: 100%; padding-top: 10px; } .PriceChart .price-change { text-align: left; margin-bottom: 1.5em; } .PriceChart .chart-wrapper { height: calc(100% - 8.5em); } <|start_filename|>src/web/ui/Trade.css<|end_filename|> .Trade { margin-top: 10px; margin-bottom: 0px; } .Trade form { padding: 0; padding-top: 35px; padding-bottom: 25px; border-radius: 0.25em; } .Trade .bp3-button-group { margin-left: 1px; margin-right: 1px; } .Trade .bp3-overlay-backdrop { z-index: 23; position: absolute; animation: backdropfadein 0.1s ease 1; } @keyframes backdropfadein { from { background-color: rgba(16, 22, 26, 0); } to { background-color: rgba(16, 22, 26, 0.7); } } .Trade .quoted .seconds-remaining { display: block; text-align: center; opacity: 0.5; height: 20px; padding-top: 5px; padding-bottom: 20px; } .Trade .quoted { position: relative; z-index: 100; background: rgba(57, 75, 89, 0.5); padding-bottom: 10px; margin-bottom: 27px; padding-top: 10px; } .Trade .conversion { text-align: center; padding: 12px 18px; margin: 0; } .Trade .button-container { width: 75%; margin: 0 auto; margin-top: 10px; } .Trade .button-container .bp3-button.bp3-fill { padding: 12px 18px; } .Trade .quoted .button-container .bp3-button.bp3-minimal { padding-left: 2px; } .Trade .TradeForm { margin-bottom: 0; position: relative; } .Trade .TradeForm .bp3-input { background: none; font-size: 2.5em; text-align: right; height: 1.5em; } .Trade .TradeForm .bp3-input:disabled { background: none; color: inherit; } .Trade .TradeForm .bp3-input:focus { box-shadow: none } .Trade .TradeForm .bp3-input-action { top: 50%; } .Trade .TradeForm .bp3-input-action .bp3-heading { padding-left: 1em; } .TradeForm .quantity { position: relative; } .TradeForm .quantity-label { position: absolute; right: 0; top: 8px; font-size: 1.5em; font-weight: 300; color: rgba(245,248,250,0.4); } .Trade .TradeForm .switch-asset { margin-left: 10px; margin-top: -0.5em; } <|start_filename|>src/web/ui/LNDStatus.css<|end_filename|> .bp3-button.settings-button.bp3-minimal { position: fixed; top: 38px; /* based on .App .logo's and positioning + 40px*/ right: 70px; z-index: 21; text-align: right; line-height: 1em; } .bp3-dark.sparkswap .bp3-button.settings-button.bp3-minimal:not([class*="bp3-intent-"]):hover { box-shadow: none; } .bp3-button.settings-button.bp3-minimal .bp3-button-text { /* the spinner is a flex display, so we need the parent to be one too */ display: flex; } .bp3-button.settings-button.bp3-minimal .bp3-spinner { margin-right: 0.7em; } .bp3-button.settings-button.bp3-minimal .StatusBadge { margin-left: 0.2em; } .bp3-button.settings-button.bp3-minimal { font-size: 0.85em; } .bp3-button.settings-button.bp3-minimal .bp3-icon:last-child { margin-left: 0.75em; } .bp3-dark.sparkswap .bp3-button.bp3-intent-warning.settings-button.bp3-minimal, .bp3-dark.sparkswap .bp3-button.bp3-intent-warning.settings-button.bp3-minimal .bp3-icon { color: rgba(255,179,102, 0.7) } .bp3-dark.sparkswap .bp3-button.bp3-intent-warning.settings-button:hover, .bp3-dark.sparkswap .bp3-button.bp3-intent-warning.settings-button:hover .bp3-icon { color: rgba(255,179,102, 0.9) } <|start_filename|>src/web/ui/Balances.css<|end_filename|> .Balances .single-balance { display: block; margin: 0; padding: 0; } .Balances .single-balance .bp3-heading { vertical-align: middle; font-weight: 500; display: flex; height: 70px; padding: 1em 0; margin: 0; border-bottom: 1px solid rgba(90, 103, 112, 0.50); } .Balances .single-balance:last-child .bp3-heading { border-bottom: none; height: calc(70px - 1em); padding-bottom: 0; } .sparkswap .Balances .bp3-heading a { display: inherit; } .sparkswap .Balances .bp3-heading > a, .sparkswap .Balances .bp3-heading > a:hover, .sparkswap .Balances .bp3-heading > a:active { text-decoration: none; opacity: 1; } .Balances .single-balance .asset { width: 50px; } .Balances .single-balance .bp3-heading .actions { width: 100px; text-align: right; } .Balances .single-balance .actions .bp3-button { line-height: 25px; margin-left: 1em; width: 75px; float: right; } .Balances .single-balance .bp3-heading a { flex: 1; } .Balances .single-balance .subtitle { margin-left: 0; display: block; height: 1.65em; } <|start_filename|>src/web/ui/trade-history/TradeHistory.css<|end_filename|> .History { /** 36px is to account for the export-row **/ height: calc(100% - 36px); } .export-row { width: 100%; text-align: right; } .export-row .export-button { padding-bottom: 15px; padding-right: 2px; } <|start_filename|>src/node/main.js<|end_filename|> require('./app').default() <|start_filename|>src/web/ui/onboarding/onboarding.css<|end_filename|> .RegisterPanel { text-align: center; margin-top: 2em; } .RegisterPanel .RegisterButton { margin-top: 2em; } .webview-loading #AnchorDepositIFrame { opacity: 0; } .DepositDialog.done #AnchorDepositIFrame { display: none; } .bp3-overlay-backdrop.plaid { background-color: rgba(16, 22, 26, 0); transition: background-color ease 350ms; } #AnchorDepositIFrame { width: 360px; height: 300px; position: absolute; left: 0; top: 250px; } .plaid #AnchorDepositIFrame { height: 100%; width: 100%; left: 0; top: 0; position: fixed; } .DepositDialog { position: relative; min-height: 536px; } .bp3-dialog-body > .AnchorSpinner { width: 100px; height: 100px; position: absolute; top: 50%; left: 50%; margin-top: -50px; margin-left: -50px; } .select-jurisdiction { margin-top: 20px; } .select-jurisdiction span.state-label { display: inline-block; margin-bottom: 5px; } .bp3-button.select-button { width: 330px; padding: 10px; margin-bottom: 1em; } .bp3-popover.select-jurisdiction .bp3-menu { height: 350px; width: 330px; overflow-y: scroll; } .SubscribeForm { margin-top: 40px; }
buffaloo/sparkswap-desktop
<|start_filename|>index.js<|end_filename|> 'use strict' var Standard = require('standard') var format = require('util').format var loaderUtils = require('loader-utils') var snazzy = require('snazzy') var assign = require('object-assign') module.exports = function standardLoader (input, map) { var webpack = this var callback = webpack.async() webpack.cacheable() var config = assign({}, loaderUtils.getOptions(webpack)) config.filename = webpack.resourcePath let standard = Standard // allow configurable 'standard' e.g. standardx if (config.standard) { if (typeof config.standard === 'string') { standard = require(config.standard) } else { standard = config.standard } } delete config.standard standard.lintText(input, config, function (err, result) { if (err) return callback(err, input, map) if (result.errorCount === 0) return callback(null, input, map) var warnings = result.results.reduce(function (items, result) { return items.concat(result.messages.map(function (message) { return format( '%s:%d:%d: %s%s', result.filePath, message.line || 0, message.column || 0, message.message, !config.verbose ? ' (' + message.ruleId + ')' : '' ) })) }, []) if (config.snazzy !== false) { snazzy({ encoding: 'utf8' }) .on('data', function (data) { emit(new StandardJSError(data)) }) .end(warnings.join('\n')) } else { warnings.forEach(function (warning) { emit(new StandardJSError(warning)) }) } callback(null, input, map) }) function emit (data) { if (config.error) return webpack.emitError(data) webpack.emitWarning(data) } } class StandardJSError extends Error { constructor (messages) { super() this.name = 'StandardJSError' this.message = messages this.stack = '' } inspect () { return this.message } }
tagliala/standard-loader
<|start_filename|>Hack No Internet Dino Game/Source_code.js<|end_filename|> ''' Hack Google chrome No Internet Dino Game! Author: <NAME> ''' #Open console tab of devloper menu and use this command. #Yes, literally just one-line of code! Runner.instance_.gameOver = function(){};
chaitanyashimpi/Youtube-Projects
<|start_filename|>playbilling/src/test/java/com/google/androidbrowserhelper/playbilling/digitalgoods/GetDetailsCallTest.java<|end_filename|> // Copyright 2020 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.androidbrowserhelper.playbilling.digitalgoods; import android.os.Build; import android.os.Bundle; import android.os.Parcelable; import com.android.billingclient.api.BillingClient; import com.android.billingclient.api.SkuDetails; import com.google.androidbrowserhelper.playbilling.provider.BillingWrapperFactory; import com.google.androidbrowserhelper.playbilling.provider.MockBillingWrapper; import org.json.JSONException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.robolectric.annotation.internal.DoNotInstrument; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static com.google.androidbrowserhelper.playbilling.digitalgoods.GetDetailsCall.RESPONSE_GET_DETAILS; import static com.google.androidbrowserhelper.playbilling.digitalgoods.GetDetailsCall.RESPONSE_GET_DETAILS_DETAILS_LIST; import static com.google.androidbrowserhelper.playbilling.digitalgoods.GetDetailsCall.RESPONSE_GET_DETAILS_RESPONSE_CODE; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** Tests for {@link GetDetailsCall} and {@link DigitalGoodsRequestHandler}. */ @RunWith(RobolectricTestRunner.class) @DoNotInstrument @Config(sdk = {Build.VERSION_CODES.O_MR1}) public class GetDetailsCallTest { private final static DigitalGoodsCallback EMPTY_CALLBACK = (name, args) -> {}; private final static String SKU_DETAILS = ItemDetailsTest.createSkuDetailsJson("id1", "My item", "Some description.", "GBP", 123450000, null, null, null, null); private final MockBillingWrapper mBillingWrapper = new MockBillingWrapper(); private DigitalGoodsRequestHandler mHandler; @Before public void setUp() { BillingWrapperFactory.setBillingWrapperForTesting(mBillingWrapper); mHandler = new DigitalGoodsRequestHandler(null); } @Test public void unknownCommand() { assertFalse(mHandler.handle("unknown", new Bundle(), EMPTY_CALLBACK)); } @Test public void wrongArgs() { assertFalse(mHandler.handle(GetDetailsCall.COMMAND_NAME, new Bundle(), EMPTY_CALLBACK)); } @Test public void goodArgs() { Bundle args = GetDetailsCall.createBundleForTesting("id1"); assertTrue(mHandler.handle(GetDetailsCall.COMMAND_NAME, args, EMPTY_CALLBACK)); } @Test public void callsCallback() throws InterruptedException { Bundle args = GetDetailsCall.createBundleForTesting("id1"); CountDownLatch callbackTriggered = new CountDownLatch(1); DigitalGoodsCallback callback = (name, bundle) -> callbackTriggered.countDown(); assertTrue(mHandler.handle( GetDetailsCall.COMMAND_NAME, args, callback)); mBillingWrapper.triggerConnected(); assertTrue(mBillingWrapper.waitForQuerySkuDetails()); mBillingWrapper.triggerOnGotInAppSkuDetails(Collections.emptyList()); mBillingWrapper.triggerOnGotSubsSkuDetails(Collections.emptyList()); assertTrue(callbackTriggered.await(5, TimeUnit.SECONDS)); } @Test public void parsesResult_inApp() throws InterruptedException, JSONException { checkParsesResult( Collections.singletonList(new SkuDetails(SKU_DETAILS)), Collections.emptyList()); } @Test public void parsesResult_subs() throws InterruptedException, JSONException { checkParsesResult( Collections.emptyList(), Collections.singletonList(new SkuDetails(SKU_DETAILS))); } private void checkParsesResult(List<SkuDetails> inAppSkuDetails, List<SkuDetails> subsSkuDetails) throws InterruptedException { Bundle args = GetDetailsCall.createBundleForTesting("id1"); CountDownLatch callbackTriggered = new CountDownLatch(1); DigitalGoodsCallback callback = (name, bundle) -> { assertEquals(RESPONSE_GET_DETAILS, name); assertEquals(bundle.getInt(RESPONSE_GET_DETAILS_RESPONSE_CODE), BillingClient.BillingResponseCode.OK); Parcelable[] array = bundle.getParcelableArray(RESPONSE_GET_DETAILS_DETAILS_LIST); ItemDetails details = ItemDetails.create((Bundle) array[0]); ItemDetailsTest.assertItemDetails(details, "id1", "My item", "Some description.", "GBP", "123.450000", "", "", "", "GBP", "0.000000"); callbackTriggered.countDown(); }; assertTrue(mHandler.handle(GetDetailsCall.COMMAND_NAME, args, callback)); mBillingWrapper.triggerConnected(); assertTrue(mBillingWrapper.waitForQuerySkuDetails()); mBillingWrapper.triggerOnGotInAppSkuDetails(inAppSkuDetails); mBillingWrapper.triggerOnGotSubsSkuDetails(subsSkuDetails); assertTrue(callbackTriggered.await(5, TimeUnit.SECONDS)); } }
angie1148/android-browser-helper
<|start_filename|>src/global/action-names.js<|end_filename|> "use strict"; export const LOGIN_ATTEMPT = "LOGIN_ATTEMPT"; export const LOGIN_FAILED = "LOGGED_FAILED"; export const LOGIN_SUCCESSFULLY = "LOGGED_SUCCESSFULLY"; export const LOGIN_RESET_CONTROL_VARS = "LOGIN_RESET_CONTROL_VARS"; export const LOGIN_LOGOUT = "LOGIN_LOGOUT";
AkioUnity/Calendar-Widget-old
<|start_filename|>app/src/main/java/bupt/tiantian/callrecorder/model/DefaultAvatar.java<|end_filename|> package bupt.tiantian.callrecorder.model; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Build; import bupt.tiantian.callrecorder.R; /** * Created by tiantian on 3/4/17. */ public class DefaultAvatar { public static final int[] colorsId = new int[]{ R.color.red, R.color.pink, R.color.purple, R.color.deep_purple, R.color.indigo, R.color.blue, R.color.light_blue, R.color.cyan, R.color.teal, R.color.green, R.color.light_green, R.color.lime, R.color.yellow, R.color.amber, R.color.orange, R.color.deep_orange }; public static final int[] avatarsId = new int[]{ R.drawable.ic_account_circle_48dp, R.drawable.ic_account_circle_48dp_1, R.drawable.ic_account_circle_48dp_2, R.drawable.ic_account_circle_48dp_3, R.drawable.ic_account_circle_48dp_4, R.drawable.ic_account_circle_48dp_5, R.drawable.ic_account_circle_48dp_6, R.drawable.ic_account_circle_48dp_7 }; private static int calcHash(String phoneNum) { int tmp; if (phoneNum.length() > 5) { tmp = Integer.parseInt(phoneNum.substring(phoneNum.length() - 5)); }else{ tmp =Integer.parseInt(phoneNum)* 7; } return tmp % avatarsId.length; } public static Drawable getDefaultDrawable(String phoneNum, Context context) { Drawable drawable; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { drawable = context.getDrawable(avatarsId[calcHash(phoneNum)]); } else { drawable = context.getResources().getDrawable(avatarsId[calcHash(phoneNum)]); } return drawable; } } <|start_filename|>app/src/main/java/bupt/tiantian/callrecorder/model/PhoneCallRecord.java<|end_filename|> package bupt.tiantian.callrecorder.model; import android.Manifest; import android.content.ContentUris; import android.content.Context; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.provider.ContactsContract; import android.support.v4.app.ActivityCompat; import bupt.tiantian.callrecorder.database.CallLog; import java.io.InputStream; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Info about a phone call recording */ public class PhoneCallRecord { // Cache of Contact Pictures to minimize image memory use... private static Map<String, Drawable> synchronizedMap = Collections.synchronizedMap(new HashMap<String, Drawable>()); private String name; private String contactId; CallLog phoneCall; public PhoneCallRecord(CallLog phoneCall) { this.phoneCall = phoneCall; } public void setImage(Drawable photo) { synchronizedMap.put(phoneCall.getPhoneNumber(), photo); } /** * Get the Contact image from the cache... * * @return NULL if there isn't an Image in the cache */ public Drawable getImage() { Drawable drawable = synchronizedMap.get(phoneCall.getPhoneNumber()); return drawable; } public void setContactId(String contactId) { this.contactId = contactId; } public String getContactId() { return contactId; } public void setName(String name) { this.name = name; } public String getName() { if (null == name) { return phoneCall.getPhoneNumber(); } return name; } public CallLog getPhoneCall() { return phoneCall; } public void resolveContactInfo(Context context) { String name = null; String contactId = null; InputStream input = null; String phoneNumber = phoneCall.getPhoneNumber(); if (null == phoneNumber || phoneNumber.isEmpty()) return; if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) return; try { // define the columns the query should return String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID}; // encode the phone number and build the filter URI Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber)); // query time Cursor cursor = context.getContentResolver().query(contactUri, projection, null, null, null); if (cursor.moveToFirst()) { // Get values from contacts database: contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup._ID)); setContactId(contactId); name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)); setName(name); // Already in the cache? if (null == getImage()) { // no... // Get photo of contactId as input stream: Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(contactId)); input = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(), uri); if (null != input) { BitmapDrawable drawable = new BitmapDrawable(context.getResources(), input); setImage(drawable); } } } } catch (Exception e) { } } } <|start_filename|>app/src/main/java/bupt/tiantian/callrecorder/callrecorder/AppPreferences.java<|end_filename|> package bupt.tiantian.callrecorder.callrecorder; import android.content.Context; import android.content.SharedPreferences; import android.support.v4.content.ContextCompat; import java.io.File; /** * A Singleton * Wrapper around the default SharedPreferences so we can easily set and read our settings */ public class AppPreferences { private static AppPreferences instance = null; private SharedPreferences preferences; private String defaultStoragePath; /** * Must be called once on app startup * * @param context - application context * @return this */ public static AppPreferences getInstance(Context context) { if (instance == null) { if (context == null) { throw new IllegalStateException(AppPreferences.class.getSimpleName() + " is not initialized, call getInstance(Context) with a VALID Context first."); } instance = new AppPreferences(context.getApplicationContext()); } return instance; } private AppPreferences(Context context) { // From Android sources for getDefaultSharedPreferences preferences = context.getSharedPreferences( context.getPackageName() + "_preferences", Context.MODE_PRIVATE); defaultStoragePath = new ContextCompat().getExternalFilesDirs(context, null)[0].getAbsolutePath(); } /** * Is Recording Enabled * * @return true/false */ public boolean isRecordingEnabled() { return preferences.getBoolean("RecordingEnabled", true); } /** * Set Recording is Enabled * * @param enabled true/false */ public void setRecordingEnabled(boolean enabled) { preferences.edit().putBoolean("RecordingEnabled", enabled).commit(); } /** * Record incoming calls if {@link #isRecordingEnabled() isRecordingEnabled} * * @return true/false */ public boolean isRecordingIncomingEnabled() { return preferences.getBoolean("RecordingIncomingEnabled", true); } /** * Set Recording is Enabled for incoming calls * * @param enabled true/false */ public void setRecordingIncomingEnabled(boolean enabled) { preferences.edit().putBoolean("RecordingIncomingEnabled", enabled).commit(); } /** * Record outgoing calls if {@link #isRecordingEnabled() isRecordingEnabled} * * @return true/false */ public boolean isRecordingOutgoingEnabled() { return preferences.getBoolean("RecordingOutgoingEnabled", true); } /** * Set Recording is Enabled for outgoing calls * * @param enabled true/false */ public void setRecordingOutgoingEnabled(boolean enabled) { preferences.edit().putBoolean("RecordingOutgoingEnabled", enabled).commit(); } /** * Get the location to store the recordings too... * TODO: make configurable * * @return directory location */ public File getFilesDirectory() { // might make this configurable.... String filesDir = preferences.getString("FilesDirectoryNew", defaultStoragePath); File myDir = new File(filesDir); if (myDir.exists() || myDir.mkdirs()) { return myDir; } return new File(defaultStoragePath); } public enum OlderThan { NEVER, DAILY, THREE_DAYS, WEEKLY, MONTHLY, QUARTERLY, YEARLY } /** * get the Older Than Days for recording cleanup * * @return 0 if not set */ public OlderThan getOlderThan() { String name = preferences.getString("OlderThan", OlderThan.NEVER.name()); return OlderThan.valueOf(name); } /** * Set the Older Than date for recording cleanup * * @param olderThan NEVER default */ public void setOlderThan(OlderThan olderThan) { preferences.edit().putString("OlderThan", olderThan.name()).commit(); } } <|start_filename|>app/src/main/java/bupt/tiantian/callrecorder/receivers/MyLocalBroadcastReceiver.java<|end_filename|> package bupt.tiantian.callrecorder.receivers; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; /** * Internal BroadcastReceiver to handle * {@link LocalBroadcastActions} */ public class MyLocalBroadcastReceiver extends BroadcastReceiver { public interface OnNewRecordingListener{ void OnBroadcastReceived(Intent intent); } OnNewRecordingListener listener; public MyLocalBroadcastReceiver(OnNewRecordingListener listener) { this.listener = listener; } public MyLocalBroadcastReceiver() { } public void setListener( OnNewRecordingListener listener){ this.listener = listener; } @Override public void onReceive(Context context, Intent intent) { if(null!=listener) listener.OnBroadcastReceived(intent); } } <|start_filename|>app/src/main/java/bupt/tiantian/callrecorder/callrecorder/WhitelistFragment.java<|end_filename|> package bupt.tiantian.callrecorder.callrecorder; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.PopupMenu; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import bupt.tiantian.callrecorder.R; import bupt.tiantian.callrecorder.database.Database; import bupt.tiantian.callrecorder.database.Whitelist; import bupt.tiantian.callrecorder.model.WhitelistRecord; /** * A fragment representing a list of Items. * <p/> * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener} * interface. */ public class WhitelistFragment extends Fragment implements MyWhitelistItemRecyclerViewAdapter.OnListInteractionListener { private static final String ARG_COLUMN_COUNT = "ARG_COLUMN_COUNT"; private int mColumnCount = 1; private OnListFragmentInteractionListener mListener; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public WhitelistFragment() { } public static WhitelistFragment newInstance(int columnCount) { WhitelistFragment fragment = new WhitelistFragment(); Bundle args = new Bundle(); args.putInt(ARG_COLUMN_COUNT, columnCount); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT); } } MyWhitelistItemRecyclerViewAdapter adapter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_whitelist, container, false); // Set the adapter if (view instanceof RecyclerView) { Context context = view.getContext(); RecyclerView recyclerView = (RecyclerView) view; if (mColumnCount <= 1) { recyclerView.setLayoutManager(new LinearLayoutManager(context)); } else { recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount)); } recyclerView.setAdapter(adapter = new MyWhitelistItemRecyclerViewAdapter(getContext(), this)); } return view; } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnListFragmentInteractionListener) { mListener = (OnListFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnListFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnListFragmentInteractionListener { void onListFragmentInteraction(WhitelistRecord[] item); } @Override public void onListInteraction(WhitelistRecord[] item) { mListener.onListFragmentInteraction(item); } @Override public boolean onListLongClick(View v, final WhitelistRecord record) { PopupMenu popupMenu = new PopupMenu(getContext(), v); popupMenu.getMenuInflater().inflate(R.menu.menu_whitelist_popup, popupMenu.getMenu()); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { if (item.getItemId() == R.id.action_delete) { removeSelectedContacts(); return true; } return false; } }); popupMenu.show(); return true; // handled } public void removeSelectedContacts() { AlertDialog.Builder alert = new AlertDialog.Builder(getContext()); alert.setTitle(R.string.delete_whitelist_title); alert.setMessage(R.string.delete_whitelist_subject); alert.setPositiveButton(R.string.dialog_yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { Database whitelistDB = Database.getInstance(getContext()); WhitelistRecord[] records = adapter.getSelectedRecords(); for (WhitelistRecord record : records) { int id = record.whitelist.getId(); whitelistDB.removeWhiteList(id); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); // need to run this on main thread.... refresh(); if (mListener != null) { //选中的都删除了,删除后selectedItems应该为空 mListener.onListFragmentInteraction(new WhitelistRecord[]{}); } } }; asyncTask.execute(); dialog.dismiss(); } }); alert.setNegativeButton(R.string.dialog_no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alert.show(); } public void addContact() { ListView listView = new ListView(getContext()); final MyContactsAdapter adapter = new MyContactsAdapter(getContext()); listView.setAdapter(adapter); AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setTitle(R.string.add_contact); builder.setView(listView); builder.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Do nothing dialog.dismiss(); } }); final Dialog dialog = builder.create(); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { MyContactsAdapter.ContactRecord contactRecord = (MyContactsAdapter.ContactRecord) adapter.getItem(position); addContact(contactRecord.contactId); dialog.dismiss(); } }); dialog.show(); } public void addContact(String contactId) { Whitelist whitelist = new Whitelist(); whitelist.setContactId(contactId); if (Database.getInstance(getContext()).addWhitelist(whitelist)) { refresh(); } else { Toast.makeText(getContext(), R.string.white_list_duplicate, Toast.LENGTH_SHORT).show(); } } private void refresh() { adapter.refresh(); } } <|start_filename|>app/src/main/java/bupt/tiantian/callrecorder/callrecorder/RoundImageView.java<|end_filename|> package bupt.tiantian.callrecorder.callrecorder; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.widget.ImageView; /** * Created by tiantian on 17-2-17. */ public class RoundImageView extends ImageView { private int width; private int height; public RoundImageView(Context context) { super(context); } public RoundImageView(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); width = w; height = h; } @Override protected void onDraw(Canvas canvas) { Drawable drawable = getDrawable(); if (drawable == null) { return; } if (!(drawable instanceof BitmapDrawable)) { super.onDraw(canvas); return; } Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap(); if (null == bitmap) { return; } // int width = getWidth(); Bitmap roundBitmap = getCroppedBitmap(bitmap, width); canvas.drawBitmap(roundBitmap, 0, 0, null); } /** * 初始Bitmap对象的缩放裁剪过程 * * @param bmp 初始Bitmap对象 * @param dia 圆形图片直径大小 * @return 返回一个圆形的缩放裁剪过后的Bitmap对象 */ public static Bitmap getCroppedBitmap(Bitmap bmp, int dia) { Bitmap sbmp; //比较初始Bitmap宽高和给定的圆形直径,判断是否需要缩放裁剪Bitmap对象 if (bmp.getWidth() != dia || bmp.getHeight() != dia) { sbmp = Bitmap.createScaledBitmap(bmp, dia, dia, false); } else { sbmp = bmp; } Bitmap output = Bitmap.createBitmap(sbmp.getWidth(), sbmp.getHeight(), Bitmap.Config.ARGB_4444); Canvas canvas = new Canvas(output); final Paint paint = new Paint(); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); int radius = dia / 2; canvas.drawCircle(radius, radius, radius, paint); //核心部分,设置两张图片的相交模式,在这里就是上面绘制的Circle和下面绘制的Bitmap paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(sbmp, 0, 0, paint); return output; } } <|start_filename|>app/src/main/java/bupt/tiantian/callrecorder/receivers/LocalBroadcastActions.java<|end_filename|> package bupt.tiantian.callrecorder.receivers; /** * Defines our INTERNAL Broadcast Actions */ public final class LocalBroadcastActions { public static String NEW_RECORDING_BROADCAST = "bupt.tiantian.callrecorder.callrecorder.NEW_RECORDING_ACTION"; public static String RECORDING_DELETED_BROADCAST = "bupt.tiantian.callrecorder.callrecorder.RECORDING_DELETED_BROADCAST"; } <|start_filename|>app/src/main/java/bupt/tiantian/callrecorder/callrecorder/MyWhitelistItemRecyclerViewAdapter.java<|end_filename|> package bupt.tiantian.callrecorder.callrecorder; import android.content.ContentUris; import android.content.Context; import android.database.Cursor; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Handler; import android.os.Message; import android.provider.ContactsContract; import android.support.v7.widget.RecyclerView; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import bupt.tiantian.callrecorder.R; import bupt.tiantian.callrecorder.database.Database; import bupt.tiantian.callrecorder.database.Whitelist; import bupt.tiantian.callrecorder.model.DefaultAvatar; import bupt.tiantian.callrecorder.model.WhitelistRecord; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * {@link RecyclerView.Adapter} that can display a {@link WhitelistRecord} and makes a call to the * specified {@link WhitelistFragment.OnListFragmentInteractionListener}. */ public class MyWhitelistItemRecyclerViewAdapter extends RecyclerView.Adapter<MyWhitelistItemRecyclerViewAdapter.ViewHolder> implements Handler.Callback { public interface OnListInteractionListener { void onListInteraction(WhitelistRecord[] items); boolean onListLongClick(View v, WhitelistRecord item); } private static int WHAT_NOTIFY_CHANGES = 1; private List<WhitelistRecord> mValues; private final OnListInteractionListener mListener; private SparseBooleanArray selectedItems; public boolean isSelected(int pos) { return selectedItems.get(pos, false); } public void toggleSelection(int pos) { if (selectedItems.get(pos, false)) { selectedItems.delete(pos); } else { selectedItems.put(pos, true); } notifyItemChanged(pos); } public void clearSelections() { selectedItems.clear(); notifyDataSetChanged(); } public int getSelectedItemCount() { return selectedItems.size(); } public List<Integer> getSelectedItems() { List<Integer> items = new ArrayList<Integer>(selectedItems.size()); for (int i = 0; i < selectedItems.size(); i++) { items.add(selectedItems.keyAt(i)); } return items; } private Handler handler; @Override public boolean handleMessage(Message msg) { if (msg.what == WHAT_NOTIFY_CHANGES) { // Add to the values if (null != msg.obj) { mValues.add((WhitelistRecord) msg.obj); } notifyDataSetChanged(); } return false; } Context context; public MyWhitelistItemRecyclerViewAdapter(Context context, OnListInteractionListener listener) { handler = new Handler(this); selectedItems = new SparseBooleanArray(); mListener = listener; this.context = context; loadAdapter(context); } private void loadAdapter(final Context context) { mValues = new ArrayList<WhitelistRecord>(); // Using a Runnable and a separate Thread with Message on the UI thread // is a nice way to make the list display more interactive // no need for a progress indicator, since the user can see the list populating Runnable runnable = new Runnable() { @Override public void run() { final ArrayList<Whitelist> all = Database.getInstance(context).getAllWhitelist(); for (Whitelist whitelist : all) { WhitelistRecord record = new WhitelistRecord(whitelist); resolveContactInfo(context, record); // Send to the main thread... Message msg = Message.obtain(); msg.what = WHAT_NOTIFY_CHANGES; msg.obj = record; handler.sendMessage(msg); } if (all.size() == 0) { Message msg = Message.obtain(); msg.what = WHAT_NOTIFY_CHANGES; msg.obj = null; handler.sendMessage(msg); } } }; new Thread(runnable).start(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_whitelist, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, final int position) { holder.mItem = mValues.get(position); holder.mImageView.setImageDrawable(mValues.get(position).getImage()); holder.mNameView.setText(mValues.get(position).getName()); holder.mView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (null != mListener) { toggleSelection(position); holder.itemView.setSelected(selectedItems.get(position, false)); // Notify the active callbacks interface (the activity, if the // fragment is attached to one) that an item has been selected. mListener.onListInteraction(getSelectedRecords()); } } }); holder.mView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (null != mListener) { if (!isSelected(position)) toggleSelection(position); // Notify the active callbacks interface (the activity, if the // fragment is attached to one) that an item has been selected. return mListener.onListLongClick(v, holder.mItem); } return false; } }); // Selection State holder.itemView.setSelected(selectedItems.get(position, false)); } public WhitelistRecord[] getSelectedRecords() { ArrayList<WhitelistRecord> selected = new ArrayList<>(); List<Integer> items = getSelectedItems(); for (Integer pos : items) { selected.add(mValues.get(pos)); } return selected.toArray(new WhitelistRecord[selected.size()]); } @Override public int getItemCount() { return mValues.size(); } public class ViewHolder extends RecyclerView.ViewHolder { public final View mView; public final ImageView mImageView; public final TextView mNameView; public WhitelistRecord mItem; public ViewHolder(View view) { super(view); mView = view; mImageView = (ImageView) view.findViewById(R.id.ivProfile); mNameView = (TextView) view.findViewById(R.id.tvNumberOrName); } @Override public String toString() { return super.toString() + " '" + mNameView.getText() + "'"; } } /** * Get the contact info details from the Contacts Content Provider * * @param context * @param record */ private void resolveContactInfo(Context context, WhitelistRecord record) { String name = null; InputStream input = null; // define the columns the query should return String[] projection = new String[]{ContactsContract.Contacts.DISPLAY_NAME}; // encode the phone number and build the filter URI Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(record.getContactId())); // query time Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null); if (cursor.moveToFirst()) { // Get values from contacts database: name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); record.setName(name); // Get photo of contactId as input stream: uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(record.getContactId())); input = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(), uri); if (null != input) { BitmapDrawable drawable = new BitmapDrawable(context.getResources(), input); record.setImage(drawable); } else { record.setImage(DefaultAvatar.getDefaultDrawable(record.getContactId(), context)); } } } /** * Something changed, reload the adapter */ public void refresh() { clearSelections(); loadAdapter(context); } } <|start_filename|>app/src/main/java/bupt/tiantian/callrecorder/receivers/MyCallReceiver.java<|end_filename|> package bupt.tiantian.callrecorder.receivers; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; import bupt.tiantian.callrecorder.callrecorder.AppPreferences; import bupt.tiantian.callrecorder.listeners.PhoneListener; /** * Handle the Phone call related BroadcastActions * <action android:name="android.intent.action.PHONE_STATE" /> * <action android:name="android.intent.action.NEW_OUTGOING_CALL" /> */ public class MyCallReceiver extends BroadcastReceiver { public MyCallReceiver() { } static TelephonyManager manager; @Override public void onReceive(Context context, Intent intent) { Log.i("tiantianCallRecorder", "MyCallReceiver.onReceive "); if (!AppPreferences.getInstance(context).isRecordingEnabled()) { removeListener(); return; } if (Intent.ACTION_NEW_OUTGOING_CALL.equals(intent.getAction())) { if (!AppPreferences.getInstance(context).isRecordingOutgoingEnabled()) { removeListener(); return; } PhoneListener.getInstance(context).setOutgoing(intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER)); } else { if (!AppPreferences.getInstance(context).isRecordingIncomingEnabled()) { removeListener(); return; } } // Start Listening to the call.... if (null == manager) { manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); } if (null != manager) manager.listen(PhoneListener.getInstance(context), PhoneStateListener.LISTEN_CALL_STATE); } private void removeListener() { if (null != manager) { if (PhoneListener.hasInstance()) manager.listen(PhoneListener.getInstance(null), PhoneStateListener.LISTEN_NONE); } } } <|start_filename|>app/src/main/java/bupt/tiantian/callrecorder/callrecorder/SettingsActivity.java<|end_filename|> package bupt.tiantian.callrecorder.callrecorder; import android.os.Bundle; import android.os.StatFs; import android.support.v7.app.AppCompatActivity; import android.text.Html; import android.view.View; import android.widget.Button; import android.widget.TextView; import bupt.tiantian.callrecorder.R; import bupt.tiantian.callrecorder.database.CallLog; import bupt.tiantian.callrecorder.database.Database; import bupt.tiantian.callrecorder.receivers.MyAlarmReceiver; import bupt.tiantian.callrecorder.services.CleanupService; import java.io.File; import java.util.ArrayList; /** * Created by tiantian on 17-2-13. */ public class SettingsActivity extends AppCompatActivity implements SettingsFragment.OnFragmentInteractionListener { private TextView tvTotalFilesSize; private TextView tvTotalFiles; private TextView tvTotalFolderSize; private Button btnCleanNow; private String mStorgePath = null; boolean permissionWriteExternal; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); permissionWriteExternal = getIntent().getBooleanExtra("write_external", false); setContentView(R.layout.activity_settings); tvTotalFiles = (TextView) findViewById(R.id.tvTotalFiles); tvTotalFilesSize = (TextView) findViewById(R.id.tvTotalFilesSize); tvTotalFolderSize = (TextView) findViewById(R.id.tvTotalFolderSize); btnCleanNow = (Button) findViewById(R.id.btnCleanNow); // Now, count the recordings ArrayList<CallLog> allCalls = Database.getInstance(getApplicationContext()).getAllCalls(); String str = tvTotalFiles.getText().toString(); str = String.format(str, allCalls.size()); tvTotalFiles.setText(Html.fromHtml(str)); // Get the length of each file... long length = 0; for (CallLog call : allCalls) { File file = new File(call.getPathToRecording()); length += file.length(); } str = tvTotalFilesSize.getText().toString(); str = String.format(str, length / 1024); tvTotalFilesSize.setText(Html.fromHtml(str)); if (mStorgePath != null) { calcFreeSpace(mStorgePath); } btnCleanNow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CleanupService.startCleaning(SettingsActivity.this); } }); } @Override public void onStorgeLocationChanged(String path) { mStorgePath = path; calcFreeSpace(path); } @Override public void onStorgeLocationInit(String path) { mStorgePath = path; } private void calcFreeSpace(String path) { // http://stackoverflow.com/questions/3394765/how-to-check-available-space-on-android-device-on-mini-sd-card StatFs stat = new StatFs(path); long bytesTotal = 0; long bytesAvailable = 0; float megAvailable = 0; long megTotalAvailable = 0; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) { bytesTotal = stat.getBlockSizeLong() * stat.getBlockCountLong(); bytesAvailable = stat.getBlockSizeLong() * stat.getAvailableBlocksLong(); } else { bytesTotal = (long) stat.getBlockSize() * (long) stat.getBlockCount(); bytesAvailable = (long) stat.getBlockSize() * (long) stat.getAvailableBlocks(); } megAvailable = bytesAvailable / 1048576; megTotalAvailable = bytesTotal / 1048576; // Free Space String str = getString(R.string.pref_folder_total_folder_size); str = String.format(str, megAvailable); tvTotalFolderSize.setText(Html.fromHtml(str)); } @Override protected void onStop() { final AppPreferences.OlderThan olderThan = AppPreferences.getInstance(this).getOlderThan(); if (olderThan != AppPreferences.OlderThan.NEVER) { MyAlarmReceiver.setAlarm(SettingsActivity.this); } else { MyAlarmReceiver.cancleAlarm(SettingsActivity.this); } super.onStop(); } } <|start_filename|>app/src/main/java/bupt/tiantian/callrecorder/callrecorder/SettingsFragment.java<|end_filename|> package bupt.tiantian.callrecorder.callrecorder; import android.app.Activity; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceFragment; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.io.File; import java.util.ArrayList; import java.util.List; import bupt.tiantian.callrecorder.R; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link SettingsFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link SettingsFragment#newInstance} factory method to * create an instance of this fragment. */ public class SettingsFragment extends PreferenceFragment { private OnFragmentInteractionListener mListener; private ListPreference dirList; private ListPreference cleanList; public SettingsFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @return A new instance of fragment SettingsFragment. */ // TODO: Rename and change types and number of parameters public static SettingsFragment newInstance() { SettingsFragment fragment = new SettingsFragment(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); Context context = getActivity(); dirList = (ListPreference) findPreference("FilesDirectoryNew"); List<String> list = new ArrayList<String>(); String folderName = context.getString(R.string.folder_name); if (context instanceof SettingsActivity) { if (((SettingsActivity) context).permissionWriteExternal) { //加入扩展卡存储目录(卸载后不会删除,需要权限) String externalDirPath = new StringBuilder(Environment.getExternalStorageDirectory().getAbsolutePath()) .append("/").append(folderName).append("/").toString(); File externalDir = new File(externalDirPath); if(externalDir.exists() || externalDir.mkdir()){ list.add(externalDirPath); } } } //加入扩展卡存储目录(卸载后会删除,KITKAT后的版本不需要权限) File[] externalFilesDirs = new ContextCompat().getExternalFilesDirs(context, null); for (File file : externalFilesDirs) { list.add(file.getAbsolutePath()); } //加入手机内存存储目录(卸载后会删除,不需要权限) File filesDir = context.getFilesDir(); list.add(filesDir.getAbsolutePath()); String[] entriesArray = new String[list.size()]; list.toArray(entriesArray); dirList.setEntries(entriesArray); dirList.setEntryValues(entriesArray); dirList.setDefaultValue(entriesArray[0]); if (dirList.getEntry() == null) {//首次打开时value值为“1”不是合法路径,先用getEntry判断一下 dirList.setValue(entriesArray[0]);//value值不是entryValueArray中的值,将value重新设为默认值 } String dirString = dirList.getValue(); dirList.setSummary(dirString); if (mListener != null) { mListener.onStorgeLocationInit(dirString); } dirList.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { dirList.setSummary((String) newValue); if (mListener != null) { mListener.onStorgeLocationChanged((String) newValue); } return true; } }); cleanList = (ListPreference) findPreference("OlderThan"); cleanList.setSummary(cleanList.getEntry()); cleanList.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { cleanList.setValue((String) newValue); cleanList.setSummary(cleanList.getEntry()); return false;//因为已经setValue所以返回false } }); return view; } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } //SDK API<23时,onAttach(Context)不执行,需要使用onAttach(Activity)。 // Fragment自身的Bug,v4的Fragment没有此问题 @Override public void onAttach(Activity activity) { super.onAttach(activity); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { if (activity instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) activity; } else { throw new RuntimeException(activity.toString() + " must implement OnFragmentInteractionListener"); } } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onStorgeLocationChanged(String path); void onStorgeLocationInit(String path); } }
xietiantian/CallRecorder
<|start_filename|>regression/cbmc/String_Abstraction14/pass-in-implicit.c<|end_filename|> void *malloc(__CPROVER_size_t); void use_str(char *s) { assert(__CPROVER_is_zero_string(s)); } int main(int argc, char *argv[]) { unsigned short len; char *str; __CPROVER_assume(len > 0); str = malloc(len); __CPROVER_assume(__CPROVER_buffer_size(str) == len); str[len - 1] = '\0'; // string abstraction takes care of this // __CPROVER_is_zero_string(str) = 1; // __CPROVER_zero_string_length(str) = len - 1; use_str(str); return 0; } <|start_filename|>src/ansi-c/gcc_builtin_headers_omp.h<|end_filename|> // clang-format off void __builtin_GOACC_data_end(); void __builtin_GOACC_data_start(int, __CPROVER_size_t, void*, void*, void*); void __builtin_GOACC_declare(int, __CPROVER_size_t, void*, void*, void*); void __builtin_GOACC_enter_exit_data(int, __CPROVER_size_t, void*, void*, void*, int, int, ...); void __builtin_GOACC_parallel_keyed(int, void (*)(void *), __CPROVER_size_t, void*, void*, void*, ...); void __builtin_GOACC_update(int, __CPROVER_size_t, void*, void*, void*, int, int, ...); void __builtin_GOACC_wait(int, int, ...); void __builtin_GOMP_atomic_end(); void __builtin_GOMP_atomic_start(); void __builtin_GOMP_barrier(); _Bool __builtin_GOMP_barrier_cancel(); _Bool __builtin_GOMP_cancel(int, _Bool); _Bool __builtin_GOMP_cancellation_point(int); void __builtin_GOMP_critical_end(); void __builtin_GOMP_critical_name_end(void**); void __builtin_GOMP_critical_name_start(void**); void __builtin_GOMP_critical_start(); void __builtin_GOMP_doacross_post(void*); void __builtin_GOMP_doacross_ull_post(void*); void __builtin_GOMP_doacross_ull_wait(unsigned long long, ...); void __builtin_GOMP_doacross_wait(long, ...); _Bool __builtin_GOMP_loop_doacross_dynamic_start(unsigned, long*, long, long*, long*); _Bool __builtin_GOMP_loop_doacross_guided_start(unsigned, long*, long, long*, long*); _Bool __builtin_GOMP_loop_doacross_runtime_start(unsigned, long*, long*, long*); _Bool __builtin_GOMP_loop_doacross_start(unsigned, long*, long, long, long*, long*, void*, void*); _Bool __builtin_GOMP_loop_doacross_static_start(unsigned, long*, long, long*, long*); _Bool __builtin_GOMP_loop_dynamic_next(long*, long*); _Bool __builtin_GOMP_loop_dynamic_start(long, long, long, long, long*, long*); void __builtin_GOMP_loop_end(); _Bool __builtin_GOMP_loop_end_cancel(); void __builtin_GOMP_loop_end_nowait(); _Bool __builtin_GOMP_loop_guided_next(long*, long*); _Bool __builtin_GOMP_loop_guided_start(long, long, long, long, long*, long*); _Bool __builtin_GOMP_loop_maybe_nonmonotonic_runtime_next(long*, long*); _Bool __builtin_GOMP_loop_maybe_nonmonotonic_runtime_start(long, long, long, long*, long*); _Bool __builtin_GOMP_loop_nonmonotonic_dynamic_next(long*, long*); _Bool __builtin_GOMP_loop_nonmonotonic_dynamic_start(long, long, long, long, long*, long*); _Bool __builtin_GOMP_loop_nonmonotonic_guided_next(long*, long*); _Bool __builtin_GOMP_loop_nonmonotonic_guided_start(long, long, long, long, long*, long*); _Bool __builtin_GOMP_loop_nonmonotonic_runtime_next(long*, long*); _Bool __builtin_GOMP_loop_nonmonotonic_runtime_start(long, long, long, long*, long*); _Bool __builtin_GOMP_loop_ordered_dynamic_next(long*, long*); _Bool __builtin_GOMP_loop_ordered_dynamic_start(long, long, long, long, long*, long*); _Bool __builtin_GOMP_loop_ordered_guided_next(long*, long*); _Bool __builtin_GOMP_loop_ordered_guided_start(long, long, long, long, long*, long*); _Bool __builtin_GOMP_loop_ordered_runtime_next(long*, long*); _Bool __builtin_GOMP_loop_ordered_runtime_start(long, long, long, long*, long*); _Bool __builtin_GOMP_loop_ordered_start(long, long, long, long, long, long*, long*, void*, void*); _Bool __builtin_GOMP_loop_ordered_static_next(long*, long*); _Bool __builtin_GOMP_loop_ordered_static_start(long, long, long, long, long*, long*); _Bool __builtin_GOMP_loop_runtime_next(long*, long*); _Bool __builtin_GOMP_loop_runtime_start(long, long, long, long*, long*); _Bool __builtin_GOMP_loop_start(long, long, long, long, long, long*, long*, void*, void*); _Bool __builtin_GOMP_loop_static_next(long*, long*); _Bool __builtin_GOMP_loop_static_start(long, long, long, long, long*, long*); _Bool __builtin_GOMP_loop_ull_doacross_dynamic_start(unsigned, unsigned long long*, unsigned long long, unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_doacross_guided_start(unsigned, unsigned long long*, unsigned long long, unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_doacross_runtime_start(unsigned, unsigned long long*, unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_doacross_start(unsigned, unsigned long long*, long, unsigned long long, unsigned long long*, unsigned long long*, void*, void*); _Bool __builtin_GOMP_loop_ull_doacross_static_start(unsigned, unsigned long long*, unsigned long long, unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_dynamic_next(unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_dynamic_start(_Bool, unsigned long long, unsigned long long, unsigned long long, unsigned long long, unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_guided_next(unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_guided_start(_Bool, unsigned long long, unsigned long long, unsigned long long, unsigned long long, unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_maybe_nonmonotonic_runtime_next(unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_maybe_nonmonotonic_runtime_start(_Bool, unsigned long long, unsigned long long, unsigned long long, unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_nonmonotonic_dynamic_next(unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_nonmonotonic_dynamic_start(_Bool, unsigned long long, unsigned long long, unsigned long long, unsigned long long, unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_nonmonotonic_guided_next(unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_nonmonotonic_guided_start(_Bool, unsigned long long, unsigned long long, unsigned long long, unsigned long long, unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_nonmonotonic_runtime_next(unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_nonmonotonic_runtime_start(_Bool, unsigned long long, unsigned long long, unsigned long long, unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_ordered_dynamic_next(unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_ordered_dynamic_start(_Bool, unsigned long long, unsigned long long, unsigned long long, unsigned long long, unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_ordered_guided_next(unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_ordered_guided_start(_Bool, unsigned long long, unsigned long long, unsigned long long, unsigned long long, unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_ordered_runtime_next(unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_ordered_runtime_start(_Bool, unsigned long long, unsigned long long, unsigned long long, unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_ordered_start(_Bool, unsigned long long, unsigned long long, unsigned long long, long, unsigned long long, unsigned long long*, unsigned long long*, void*, void*); _Bool __builtin_GOMP_loop_ull_ordered_static_next(unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_ordered_static_start(_Bool, unsigned long long, unsigned long long, unsigned long long, unsigned long long, unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_runtime_next(unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_runtime_start(_Bool, unsigned long long, unsigned long long, unsigned long long, unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_start(_Bool, unsigned long long, unsigned long long, unsigned long long, long, unsigned long long, unsigned long long*, unsigned long long*, void*, void*); _Bool __builtin_GOMP_loop_ull_static_next(unsigned long long*, unsigned long long*); _Bool __builtin_GOMP_loop_ull_static_start(_Bool, unsigned long long, unsigned long long, unsigned long long, unsigned long long, unsigned long long*, unsigned long long*); void __builtin_GOMP_offload_register_ver(int, void*, int, void*); void __builtin_GOMP_offload_unregister_ver(int, void*, int, void*); void __builtin_GOMP_ordered_end(); void __builtin_GOMP_ordered_start(); void __builtin_GOMP_parallel(void (*)(void *), void*, unsigned, unsigned); void __builtin_GOMP_parallel_loop_dynamic(void (*)(void *), void*, unsigned, long, long, long, long, unsigned); void __builtin_GOMP_parallel_loop_guided(void (*)(void *), void*, unsigned, long, long, long, long, unsigned); void __builtin_GOMP_parallel_loop_maybe_nonmonotonic_runtime(void (*)(void *), void*, unsigned, long, long, long, unsigned); void __builtin_GOMP_parallel_loop_nonmonotonic_dynamic(void (*)(void *), void*, unsigned, long, long, long, long, unsigned); void __builtin_GOMP_parallel_loop_nonmonotonic_guided(void (*)(void *), void*, unsigned, long, long, long, long, unsigned); void __builtin_GOMP_parallel_loop_nonmonotonic_runtime(void (*)(void *), void*, unsigned, long, long, long, unsigned); void __builtin_GOMP_parallel_loop_runtime(void (*)(void *), void*, unsigned, long, long, long, unsigned); void __builtin_GOMP_parallel_loop_static(void (*)(void *), void*, unsigned, long, long, long, long, unsigned); unsigned __builtin_GOMP_parallel_reductions(void (*)(void *), void*, unsigned, unsigned); void __builtin_GOMP_parallel_sections(void (*)(void *), void*, unsigned, unsigned, unsigned); unsigned __builtin_GOMP_sections2_start(unsigned, void*, void*); void __builtin_GOMP_sections_end(); _Bool __builtin_GOMP_sections_end_cancel(); void __builtin_GOMP_sections_end_nowait(); unsigned __builtin_GOMP_sections_next(); unsigned __builtin_GOMP_sections_start(unsigned); void __builtin_GOMP_single_copy_end(void*); void* __builtin_GOMP_single_copy_start(); _Bool __builtin_GOMP_single_start(); void __builtin_GOMP_target_data_ext(int, __CPROVER_size_t, void*, void*, void*); void __builtin_GOMP_target_end_data(); void __builtin_GOMP_target_enter_exit_data(int, __CPROVER_size_t, void*, void*, void*, unsigned, void*); void __builtin_GOMP_target_ext(int, void (*)(void *), __CPROVER_size_t, void*, void*, void*, unsigned, void*, void*); void __builtin_GOMP_target_update_ext(int, __CPROVER_size_t, void*, void*, void*, unsigned, void*); void __builtin_GOMP_task(void (*)(void *), void*, void (*)(void *, void *), long, long, _Bool, unsigned, void*, int, void*); void __builtin_GOMP_task_reduction_remap(__CPROVER_size_t, __CPROVER_size_t, void*); void __builtin_GOMP_taskgroup_end(); void __builtin_GOMP_taskgroup_reduction_register(void*); void __builtin_GOMP_taskgroup_reduction_unregister(void*); void __builtin_GOMP_taskgroup_start(); void __builtin_GOMP_taskloop(void (*)(void *), void*, void (*)(void *, void *), long, long, unsigned, long, int, long, long, long); void __builtin_GOMP_taskloop_ull(void (*)(void *), void*, void (*)(void *, void *), long, long, unsigned, long, int, unsigned long long, unsigned long long, unsigned long long); void __builtin_GOMP_taskwait(); void __builtin_GOMP_taskwait_depend(void*); void __builtin_GOMP_taskyield(); void __builtin_GOMP_teams(unsigned, unsigned); void __builtin_GOMP_teams_reg(void (*)(void *), void*, unsigned, unsigned, unsigned); void __builtin_GOMP_workshare_task_reduction_unregister(_Bool); int __builtin_omp_get_num_teams(); int __builtin_omp_get_num_threads(); int __builtin_omp_get_team_num(); int __builtin_omp_get_thread_num(); int __builtin_acc_get_device_type(); int __builtin_acc_on_device(int); int __builtin_goacc_parlevel_id(int); int __builtin_goacc_parlevel_size(int); // clang-format on <|start_filename|>src/ansi-c/gcc_builtin_headers_ubsan.h<|end_filename|> // clang-format off void __builtin___asan_after_dynamic_init(); void __builtin___asan_before_dynamic_init(const void*); void __builtin___asan_handle_no_return(); void __builtin___asan_init(); void __builtin___asan_load1(void*); void __builtin___asan_load16(void*); void __builtin___asan_load16_noabort(void*); void __builtin___asan_load1_noabort(void*); void __builtin___asan_load2(void*); void __builtin___asan_load2_noabort(void*); void __builtin___asan_load4(void*); void __builtin___asan_load4_noabort(void*); void __builtin___asan_load8(void*); void __builtin___asan_load8_noabort(void*); void __builtin___asan_report_load1(void*); void __builtin___asan_report_load16(void*); void __builtin___asan_report_load16_noabort(void*); void __builtin___asan_report_load1_noabort(void*); void __builtin___asan_report_load2(void*); void __builtin___asan_report_load2_noabort(void*); void __builtin___asan_report_load4(void*); void __builtin___asan_report_load4_noabort(void*); void __builtin___asan_report_load8(void*); void __builtin___asan_report_load8_noabort(void*); void __builtin___asan_report_store1(void*); void __builtin___asan_report_store16(void*); void __builtin___asan_report_store16_noabort(void*); void __builtin___asan_report_store1_noabort(void*); void __builtin___asan_report_store2(void*); void __builtin___asan_report_store2_noabort(void*); void __builtin___asan_report_store4(void*); void __builtin___asan_report_store4_noabort(void*); void __builtin___asan_report_store8(void*); void __builtin___asan_report_store8_noabort(void*); void __builtin___asan_store1(void*); void __builtin___asan_store16(void*); void __builtin___asan_store16_noabort(void*); void __builtin___asan_store1_noabort(void*); void __builtin___asan_store2(void*); void __builtin___asan_store2_noabort(void*); void __builtin___asan_store4(void*); void __builtin___asan_store4_noabort(void*); void __builtin___asan_store8(void*); void __builtin___asan_store8_noabort(void*); void __builtin___asan_version_mismatch_check_v8(); void __builtin___hwasan_handle_longjmp(const void*); void __builtin___hwasan_init(); void __builtin___hwasan_load1(void*); void __builtin___hwasan_load16(void*); void __builtin___hwasan_load16_noabort(void*); void __builtin___hwasan_load1_noabort(void*); void __builtin___hwasan_load2(void*); void __builtin___hwasan_load2_noabort(void*); void __builtin___hwasan_load4(void*); void __builtin___hwasan_load4_noabort(void*); void __builtin___hwasan_load8(void*); void __builtin___hwasan_load8_noabort(void*); void __builtin___hwasan_store1(void*); void __builtin___hwasan_store16(void*); void __builtin___hwasan_store16_noabort(void*); void __builtin___hwasan_store1_noabort(void*); void __builtin___hwasan_store2(void*); void __builtin___hwasan_store2_noabort(void*); void __builtin___hwasan_store4(void*); void __builtin___hwasan_store4_noabort(void*); void __builtin___hwasan_store8(void*); void __builtin___hwasan_store8_noabort(void*); void __builtin___hwasan_tag_mismatch4(void*); void* __builtin___hwasan_tag_pointer(const void*, unsigned char); void __builtin___sanitizer_cov_trace_cmp1(unsigned char, unsigned char); void __builtin___sanitizer_cov_trace_cmp2(uint16_t, uint16_t); void __builtin___sanitizer_cov_trace_cmp4(uint32_t, uint32_t); void __builtin___sanitizer_cov_trace_cmp8(uint64_t, uint64_t); void __builtin___sanitizer_cov_trace_cmpd(double, double); void __builtin___sanitizer_cov_trace_cmpf(float, float); void __builtin___sanitizer_cov_trace_const_cmp1(unsigned char, unsigned char); void __builtin___sanitizer_cov_trace_const_cmp2(uint16_t, uint16_t); void __builtin___sanitizer_cov_trace_const_cmp4(uint32_t, uint32_t); void __builtin___sanitizer_cov_trace_const_cmp8(uint64_t, uint64_t); void __builtin___sanitizer_cov_trace_pc(); void __builtin___sanitizer_cov_trace_switch(uint64_t, void*); void __builtin___tsan_atomic_signal_fence(int); void __builtin___tsan_atomic_thread_fence(int); void __builtin___tsan_func_entry(void*); void __builtin___tsan_func_exit(void*); void __builtin___tsan_init(); void __builtin___tsan_read1(void*); void __builtin___tsan_read16(void*); void __builtin___tsan_read2(void*); void __builtin___tsan_read4(void*); void __builtin___tsan_read8(void*); void __builtin___tsan_volatile_read1(void*); void __builtin___tsan_volatile_read16(void*); void __builtin___tsan_volatile_read2(void*); void __builtin___tsan_volatile_read4(void*); void __builtin___tsan_volatile_read8(void*); void __builtin___tsan_volatile_write1(void*); void __builtin___tsan_volatile_write16(void*); void __builtin___tsan_volatile_write2(void*); void __builtin___tsan_volatile_write4(void*); void __builtin___tsan_volatile_write8(void*); void __builtin___tsan_vptr_update(void*, void*); void __builtin___tsan_write1(void*); void __builtin___tsan_write16(void*); void __builtin___tsan_write2(void*); void __builtin___tsan_write4(void*); void __builtin___tsan_write8(void*); void __builtin___ubsan_handle_add_overflow(void*, void*, void*); void __builtin___ubsan_handle_add_overflow_abort(void*, void*, void*); void __builtin___ubsan_handle_builtin_unreachable(void*); void __builtin___ubsan_handle_divrem_overflow(void*, void*, void*); void __builtin___ubsan_handle_divrem_overflow_abort(void*, void*, void*); void __builtin___ubsan_handle_dynamic_type_cache_miss(void*, void*, void*); void __builtin___ubsan_handle_dynamic_type_cache_miss_abort(void*, void*, void*); void __builtin___ubsan_handle_float_cast_overflow(void*, void*); void __builtin___ubsan_handle_float_cast_overflow_abort(void*, void*); void __builtin___ubsan_handle_invalid_builtin(void*); void __builtin___ubsan_handle_invalid_builtin_abort(void*); void __builtin___ubsan_handle_load_invalid_value(void*, void*); void __builtin___ubsan_handle_load_invalid_value_abort(void*, void*); void __builtin___ubsan_handle_missing_return(void*); void __builtin___ubsan_handle_mul_overflow(void*, void*, void*); void __builtin___ubsan_handle_mul_overflow_abort(void*, void*, void*); void __builtin___ubsan_handle_negate_overflow(void*, void*); void __builtin___ubsan_handle_negate_overflow_abort(void*, void*); void __builtin___ubsan_handle_nonnull_arg(void*); void __builtin___ubsan_handle_nonnull_arg_abort(void*); void __builtin___ubsan_handle_nonnull_return(void*); void __builtin___ubsan_handle_nonnull_return_abort(void*); void __builtin___ubsan_handle_nonnull_return_v1(void*, void*); void __builtin___ubsan_handle_nonnull_return_v1_abort(void*, void*); void __builtin___ubsan_handle_out_of_bounds(void*, void*); void __builtin___ubsan_handle_out_of_bounds_abort(void*, void*); void __builtin___ubsan_handle_pointer_overflow(void*, void*, void*); void __builtin___ubsan_handle_pointer_overflow_abort(void*, void*, void*); void __builtin___ubsan_handle_shift_out_of_bounds(void*, void*, void*); void __builtin___ubsan_handle_shift_out_of_bounds_abort(void*, void*, void*); void __builtin___ubsan_handle_sub_overflow(void*, void*, void*); void __builtin___ubsan_handle_sub_overflow_abort(void*, void*, void*); void __builtin___ubsan_handle_type_mismatch(void*, void*); void __builtin___ubsan_handle_type_mismatch_abort(void*, void*); void __builtin___ubsan_handle_type_mismatch_v1(void*, void*); void __builtin___ubsan_handle_type_mismatch_v1_abort(void*, void*); void __builtin___ubsan_handle_vla_bound_not_positive(void*, void*); void __builtin___ubsan_handle_vla_bound_not_positive_abort(void*, void*); // clang-format on <|start_filename|>regression/contracts/invar_havoc_static_array/main.c<|end_filename|> #include <assert.h> #include <stdlib.h> #define SIZE 8 void main() { char data[SIZE]; data[5] = 0; for(unsigned i = 0; i < SIZE; i++) // clang-format off __CPROVER_assigns(i, __CPROVER_POINTER_OBJECT(data)) __CPROVER_loop_invariant(i <= SIZE) // clang-format on { data[i] = 1; } assert(data[5] == 0); assert(data[5] == 1); } <|start_filename|>regression/cbmc/pragma_cprover_enable3/main.c<|end_filename|> int main() { char *p, *q; #pragma CPROVER check push #pragma CPROVER check enable "pointer-primitive" // generate checks for the following statements and fail if(__CPROVER_r_ok(p, 1)) { } #pragma CPROVER check pop // but do not generate checks on the following statements if(__CPROVER_r_ok(q, 1)) { } } <|start_filename|>src/solvers/smt2_incremental/construct_value_expr_from_smt.h<|end_filename|> // Author: Diffblue Ltd. #ifndef CPROVER_SOLVERS_SMT2_INCREMENTAL_CONSTRUCT_VALUE_EXPR_FROM_SMT_H #define CPROVER_SOLVERS_SMT2_INCREMENTAL_CONSTRUCT_VALUE_EXPR_FROM_SMT_H #include <util/expr.h> class smt_termt; class typet; /// \brief Given a \p value_term and a \p type_to_construct, this function /// constructs a value exprt with a value based on \p value_term and a type of /// \p type_to_construct. /// \param value_term /// This must be a "simple" term encoding a value. It must not be a term /// requiring any kind of further evaluation to get a value, such as would be /// the case for identifiers or function applications. /// \param type_to_construct /// The type which the constructed expr returned is expected to have. This /// type must be compatible with the sort of \p value_term. /// \note The type is required separately in order to carry out this conversion, /// because the smt value term does not contain all the required information. /// For example an 8 bit, bit vector with a value of 255 could be used to /// construct an `unsigned char` with the value 255 or alternatively a /// `signed char` with the value -1. So these alternatives are disambiguated /// using the type. exprt construct_value_expr_from_smt( const smt_termt &value_term, const typet &type_to_construct); #endif // CPROVER_SOLVERS_SMT2_INCREMENTAL_CONSTRUCT_VALUE_EXPR_FROM_SMT_H <|start_filename|>regression/cbmc/pointer-primitive-check-03/main.c<|end_filename|> #include <stdlib.h> void main() { // uninitialized pointer char *p1; __CPROVER_r_ok(p1, 1); // special value of invalid pointer char *p2 = (size_t)1 << (sizeof(char *) * 8 - 8); __CPROVER_r_ok(p2, 1); // pointer object 123, offset 123, not pointing to valid memory char *p3 = ((size_t)123 << (sizeof(char *) * 8 - 8)) | 123; __CPROVER_r_ok(p3, 1); // negative offset char *p4 = malloc(1); p4 -= 1; __CPROVER_r_ok(p4, 1); // offset out of bounds char *p5 = malloc(10); p5 += 10; __CPROVER_r_ok(p5, 1); // dead char *p6; { char c; p6 = &c; } __CPROVER_r_ok(p6, 1); *p6; // deallocated char *p7 = malloc(1); free(p7); __CPROVER_r_ok(p7, 1); } <|start_filename|>regression/cbmc-primitives/alternating_quantifiers_6231/exists_in_forall.c<|end_filename|> #include <stdlib.h> // clang-format off int main(int argc, char **argv) { int *i = malloc(sizeof(int)); *i = 1; __CPROVER_assert( __CPROVER_forall { int z; (0 < z && z < 10) ==> __CPROVER_exists { int y; ( 10 < y && y < 20) && y == z + 10 && y > *i } }, "for all z, there exists a y so that y = z + 10 and y > 1"); } // clang-format on <|start_filename|>regression/cbmc/pragma_cprover_enable2/main.c<|end_filename|> int foo(int x) { return x; } int main() { int m, n; #pragma CPROVER check push #pragma CPROVER check enable "signed-overflow" // generate assertions for the following statements int x = m = n + n; ++n; n++; n += 1; foo(x + n); #pragma CPROVER check pop // but do not generate assertions for these x = n + n; foo(x + n); return x; } <|start_filename|>src/ansi-c/windows_builtin_headers.h<|end_filename|> // clang-format off int __assume(int); unsigned short __lzcnt16(unsigned short value); unsigned int __lzcnt(unsigned int value); unsigned __int64 __lzcnt64(unsigned __int64 value); // clang-format on <|start_filename|>src/goto-instrument/uninitialized.h<|end_filename|> /*******************************************************************\ Module: Detection for Uninitialized Local Variables Author: <NAME> Date: January 2010 \*******************************************************************/ /// \file /// Detection for Uninitialized Local Variables #ifndef CPROVER_GOTO_INSTRUMENT_UNINITIALIZED_H #define CPROVER_GOTO_INSTRUMENT_UNINITIALIZED_H #include <iosfwd> class goto_modelt; void add_uninitialized_locals_assertions(goto_modelt &); void show_uninitialized( const goto_modelt &, std::ostream &out); #define OPT_UNINITIALIZED_CHECK "(uninitialized-check)" #define HELP_UNINITIALIZED_CHECK \ " --uninitialized-check add checks for uninitialized locals " \ "(experimental)\n" // NOLINT(whitespace/line_length) #endif // CPROVER_GOTO_INSTRUMENT_UNINITIALIZED_H <|start_filename|>src/goto-instrument/function_assigns.h<|end_filename|> /*******************************************************************\ Module: Compute objects assigned to in a function Author: <NAME>, <EMAIL> \*******************************************************************/ /// \file /// Compute objects assigned to in a function. #ifndef CPROVER_GOTO_INSTRUMENT_FUNCTION_ASSIGNS_H #define CPROVER_GOTO_INSTRUMENT_FUNCTION_ASSIGNS_H #include <goto-programs/goto_program.h> #include <map> class goto_functionst; class local_may_aliast; class function_assignst { public: explicit function_assignst(const goto_functionst &_goto_functions) : goto_functions(_goto_functions) { } typedef std::set<exprt> assignst; void get_assigns( const local_may_aliast &local_may_alias, const goto_programt::const_targett, assignst &); void get_assigns_function(const exprt &, assignst &); void operator()(const exprt &function, assignst &assigns) { get_assigns_function(function, assigns); } protected: const goto_functionst &goto_functions; typedef std::map<irep_idt, assignst> function_mapt; function_mapt function_map; }; #endif // CPROVER_GOTO_INSTRUMENT_FUNCTION_ASSIGNS_H <|start_filename|>src/ansi-c/gcc_builtin_headers_mem_string.h<|end_filename|> // clang-format off void __builtin___bnd_chk_ptr_bounds(const void*, __CPROVER_size_t); void __builtin___bnd_chk_ptr_lbounds(const void*); void __builtin___bnd_chk_ptr_ubounds(const void*); void* __builtin___bnd_copy_ptr_bounds(const void*, const void*); const void* __builtin___bnd_get_ptr_lbound(const void*); const void* __builtin___bnd_get_ptr_ubound(const void*); void* __builtin___bnd_init_ptr_bounds(const void*); void* __builtin___bnd_narrow_ptr_bounds(const void*, const void*, __CPROVER_size_t); void* __builtin___bnd_null_ptr_bounds(const void*); void* __builtin___bnd_set_ptr_bounds(const void*, __CPROVER_size_t); void __builtin___bnd_store_ptr_bounds(void**, const void*); const void* __builtin___chkp_bndldx(const void*, const void*); void __builtin___clear_cache(void*, void*); int __builtin___fprintf_chk(void*, int, const char*, ...); void* __builtin___memcpy_chk(void*, const void*, __CPROVER_size_t, __CPROVER_size_t); void* __builtin___memmove_chk(void*, const void*, __CPROVER_size_t, __CPROVER_size_t); void* __builtin___mempcpy_chk(void*, const void*, __CPROVER_size_t, __CPROVER_size_t); void* __builtin___memset_chk(void*, int, __CPROVER_size_t, __CPROVER_size_t); int __builtin___printf_chk(int, const char*, ...); int __builtin___snprintf_chk(char*, __CPROVER_size_t, int, __CPROVER_size_t, const char*, ...); int __builtin___sprintf_chk(char*, int, __CPROVER_size_t, const char*, ...); char* __builtin___stpcpy(char *s1, const char *s2); char* __builtin___stpcpy_chk(char*, const char*, __CPROVER_size_t); char* __builtin___stpncpy_chk(char*, const char*, __CPROVER_size_t, __CPROVER_size_t); char* __builtin___strcat_chk(char*, const char*, __CPROVER_size_t); char* __builtin___strcpy_chk(char*, const char*, __CPROVER_size_t); char* __builtin___strncat_chk(char*, const char*, __CPROVER_size_t, __CPROVER_size_t); char* __builtin___strncpy_chk(char*, const char*, __CPROVER_size_t, __CPROVER_size_t); int __builtin___vfprintf_chk(void*, int, const char*, __builtin_va_list); int __builtin___vprintf_chk(int, const char*, __builtin_va_list); int __builtin___vsnprintf_chk (char *s, __CPROVER_size_t maxlen, int flag, __CPROVER_size_t os, const char *fmt, __builtin_va_list ap); int __builtin___vsprintf_chk(char*, int, __CPROVER_size_t, const char*, __builtin_va_list); void* __builtin_aggregate_incoming_address(); void* __builtin_aligned_alloc(__CPROVER_size_t, __CPROVER_size_t); void* __builtin_alloca(__CPROVER_size_t); void* __builtin_assume_aligned(const void*, __CPROVER_size_t, ...); int __builtin_bcmp(const void*, const void*, __CPROVER_size_t); void __builtin_bcopy(const void*, void*, __CPROVER_size_t); short unsigned int __builtin_bswap16(short unsigned int); unsigned int __builtin_bswap32(unsigned int); long long unsigned int __builtin_bswap64(long long unsigned int); void __builtin_bzero(void*, __CPROVER_size_t); void* __builtin_calloc(__CPROVER_size_t, __CPROVER_size_t); void* __builtin_chkp_memcpy_nobnd(void*, const void*, __CPROVER_size_t); void* __builtin_chkp_memcpy_nobnd_nochk(void*, const void*, __CPROVER_size_t); void* __builtin_chkp_memcpy_nochk(void*, const void*, __CPROVER_size_t); void* __builtin_chkp_memmove_nobnd(void*, const void*, __CPROVER_size_t); void* __builtin_chkp_memmove_nobnd_nochk(void*, const void*, __CPROVER_size_t); void* __builtin_chkp_memmove_nochk(void*, const void*, __CPROVER_size_t); void* __builtin_chkp_mempcpy_nobnd(void*, const void*, __CPROVER_size_t); void* __builtin_chkp_mempcpy_nobnd_nochk(void*, const void*, __CPROVER_size_t); void* __builtin_chkp_mempcpy_nochk(void*, const void*, __CPROVER_size_t); void* __builtin_chkp_memset_nobnd(void*, int, __CPROVER_size_t); void* __builtin_chkp_memset_nobnd_nochk(void*, int, __CPROVER_size_t); void* __builtin_chkp_memset_nochk(void*, int, __CPROVER_size_t); int __builtin_clrsb(int); int __builtin_clrsbimax(intmax_t); int __builtin_clrsbl(long); int __builtin_clrsbll(long long); int __builtin_clz(unsigned); int __builtin_clzimax(uintmax_t); int __builtin_clzl(unsigned long); int __builtin_clzll(unsigned long long); int __builtin_ctz(unsigned); int __builtin_ctzimax(uintmax_t); int __builtin_ctzl(unsigned long); int __builtin_ctzll(unsigned long long); char* __builtin_dcgettext(const char*, const char*, int); char* __builtin_dgettext(const char*, const char*); void* __builtin_extract_return_addr(void*); int __builtin_ffs(int); int __builtin_ffsl(long); int __builtin_ffsll(long long); int __builtin_fprintf(void *stream, const char *fmt, ...); int __builtin_fprintf_unlocked(void*, const char*, ...); int __builtin_fputc(int, void*); int __builtin_fputc_unlocked(int, void*); int __builtin_fputs(const char *s, void *stream); int __builtin_fputs_unlocked(const char*, void*); void* __builtin_frame_address(unsigned); void __builtin_free(void*); void* __builtin_frob_return_addr(void*); int __builtin_fscanf(void *stream, const char *fmt, ...); __CPROVER_size_t __builtin_fwrite(const void*, __CPROVER_size_t, __CPROVER_size_t, void*); __CPROVER_size_t __builtin_fwrite_unlocked(const void*, __CPROVER_size_t, __CPROVER_size_t, void*); char* __builtin_gettext(const char*); char* __builtin_index(const char*, int); int __builtin_isalnum(int); int __builtin_isalpha(int); int __builtin_isascii(int); int __builtin_isblank(int); int __builtin_iscntrl(int); int __builtin_isdigit(int); int __builtin_isgraph(int); int __builtin_islower(int); int __builtin_isprint(int); int __builtin_ispunct(int); int __builtin_isspace(int); int __builtin_isupper(int); int __builtin_iswalnum(wint_t); int __builtin_iswalpha(wint_t); int __builtin_iswblank(wint_t); int __builtin_iswcntrl(wint_t); int __builtin_iswdigit(wint_t); int __builtin_iswgraph(wint_t); int __builtin_iswlower(wint_t); int __builtin_iswprint(wint_t); int __builtin_iswpunct(wint_t); int __builtin_iswspace(wint_t); int __builtin_iswupper(wint_t); int __builtin_iswxdigit(wint_t); int __builtin_isxdigit(int); void* __builtin_malloc(__CPROVER_size_t); void* __builtin_memchr(const void*, int, __CPROVER_size_t); int __builtin_memcmp(const void*, const void*, __CPROVER_size_t); void* __builtin_memcpy(void*, const void*, __CPROVER_size_t); void* __builtin_memmove(void*, const void*, __CPROVER_size_t); void* __builtin_mempcpy(void*, const void*, __CPROVER_size_t); void* __builtin_memset(void*, int, __CPROVER_size_t); __CPROVER_size_t __builtin_object_size(const void*, int); int __builtin_popcount(unsigned); int __builtin_popcountimax(uintmax_t); int __builtin_popcountll(unsigned long long int x); int __builtin_posix_memalign(void**, __CPROVER_size_t, __CPROVER_size_t); void __builtin_prefetch(const void*, ...); int __builtin_printf(const char*, ...); int __builtin_printf_unlocked(const char*, ...); int __builtin_putc(int, void*); int __builtin_putc_unlocked(int, void*); int __builtin_putchar(int); int __builtin_putchar_unlocked(int); int __builtin_puts(const char*); int __builtin_puts_unlocked(const char*); void* __builtin_realloc(void*, __CPROVER_size_t); void* __builtin_return_address(unsigned); char* __builtin_rindex(const char*, int); int __builtin_scanf(const char *str, const char *fmt, ...); int __builtin_scanf(const char*, ...); int __builtin_snprintf(char*, __CPROVER_size_t, const char*, ...); int __builtin_sprintf(char*, const char*, ...); int __builtin_sscanf(const char*, const char*, ...); char* __builtin_stpcpy(char*, const char*); char* __builtin_stpncpy(char*, const char*, __CPROVER_size_t); int __builtin_strcasecmp(const char*, const char*); char* __builtin_strcat(char*, const char*); char* __builtin_strchr(const char*, int); int __builtin_strcmp(const char*, const char*); char* __builtin_strcpy(char*, const char*); __CPROVER_size_t __builtin_strcspn(const char*, const char*); char* __builtin_strdup(const char*); ssize_t __builtin_strfmon(char*, __CPROVER_size_t, const char*, ...); __CPROVER_size_t __builtin_strftime(char*, __CPROVER_size_t, const char*, const struct tm*); __CPROVER_size_t __builtin_strlen(const char*); int __builtin_strncasecmp(const char*, const char*, __CPROVER_size_t); char* __builtin_strncat(char*, const char*, __CPROVER_size_t); int __builtin_strncmp(const char*, const char*, __CPROVER_size_t); char* __builtin_strncpy(char*, const char*, __CPROVER_size_t); char* __builtin_strndup(const char*, __CPROVER_size_t); __CPROVER_size_t __builtin_strnlen(const char*, __CPROVER_size_t); char* __builtin_strpbrk(const char*, const char*); char* __builtin_strrchr(const char*, int); __CPROVER_size_t __builtin_strspn(const char*, const char*); char* __builtin_strstr(const char*, const char*); int __builtin_toascii(int); int __builtin_tolower(int); int __builtin_toupper(int); wint_t __builtin_towlower(wint_t); wint_t __builtin_towupper(wint_t); int __builtin_vfprintf(void*, const char*, __builtin_va_list); int __builtin_vfscanf(void*, const char*, __builtin_va_list); int __builtin_vprintf(const char*, __builtin_va_list); int __builtin_vscanf(const char*, __builtin_va_list); int __builtin_vsnprintf(char*, __CPROVER_size_t, const char*, __builtin_va_list); int __builtin_vsprintf(char*, const char*, __builtin_va_list); int __builtin_vsscanf(const char*, const char*, __builtin_va_list); // clang-format on <|start_filename|>src/ansi-c/library/setjmp.c<|end_filename|> /* FUNCTION: longjmp */ #ifndef __CPROVER_SETJMP_H_INCLUDED #include <setjmp.h> #define __CPROVER_SETJMP_H_INCLUDED #endif inline void longjmp(jmp_buf env, int val) { // does not return (void)env; (void)val; __CPROVER_assert(0, "longjmp requires instrumentation"); __CPROVER_assume(0); #ifdef LIBRARY_CHECK __builtin_unreachable(); #endif } /* FUNCTION: _longjmp */ #ifndef __CPROVER_SETJMP_H_INCLUDED #include <setjmp.h> #define __CPROVER_SETJMP_H_INCLUDED #endif inline void _longjmp(jmp_buf env, int val) { // does not return (void)env; (void)val; __CPROVER_assert(0, "_longjmp requires instrumentation"); __CPROVER_assume(0); #ifdef LIBRARY_CHECK __builtin_unreachable(); #endif } /* FUNCTION: siglongjmp */ #ifndef _WIN32 #ifndef __CPROVER_SETJMP_H_INCLUDED #include <setjmp.h> #define __CPROVER_SETJMP_H_INCLUDED #endif inline void siglongjmp(sigjmp_buf env, int val) { // does not return (void)env; (void)val; __CPROVER_assert(0, "siglongjmp requires instrumentation"); __CPROVER_assume(0); #ifdef LIBRARY_CHECK __builtin_unreachable(); #endif } #endif /* FUNCTION: setjmp */ #ifndef __CPROVER_SETJMP_H_INCLUDED #include <setjmp.h> #define __CPROVER_SETJMP_H_INCLUDED #endif #undef setjmp inline int setjmp(jmp_buf env) { (void)env; // returns via longjmp require instrumentation; only such returns would // return a non-zero value return 0; } /* FUNCTION: _setjmp */ #ifndef __CPROVER_SETJMP_H_INCLUDED #include <setjmp.h> #define __CPROVER_SETJMP_H_INCLUDED #endif inline int _setjmp(jmp_buf env) { (void)env; // returns via longjmp require instrumentation; only such returns would // return a non-zero value return 0; } /* FUNCTION: sigsetjmp */ #ifndef _WIN32 #ifndef __CPROVER_SETJMP_H_INCLUDED # include <setjmp.h> # define __CPROVER_SETJMP_H_INCLUDED #endif #undef sigsetjmp inline int sigsetjmp(sigjmp_buf env, int savesigs) { (void)env; (void)savesigs; // returns via siglongjmp require instrumentation; only such returns would // return a non-zero value return 0; } #endif /* FUNCTION: __sigsetjmp */ #ifndef _WIN32 #ifndef __CPROVER_SETJMP_H_INCLUDED # include <setjmp.h> # define __CPROVER_SETJMP_H_INCLUDED #endif inline int __sigsetjmp(sigjmp_buf env, int savesigs) { (void)env; (void)savesigs; // returns via siglongjmp require instrumentation; only such returns would // return a non-zero value return 0; } #endif <|start_filename|>regression/cbmc-library/llabs-01/main.c<|end_filename|> #include <assert.h> #include <stdlib.h> #include <limits.h> int main() { assert(llabs(LLONG_MIN + 1) == LLONG_MAX); return 0; } <|start_filename|>regression/contracts/invar_check_large/main.c<|end_filename|> #include <assert.h> void swap(int *a, int *b) { *a ^= *b; *b ^= *a; *a ^= *b; } int main() { int arr0, arr1, arr2, arr3, arr4; arr0 = 1; arr1 = 2; arr2 = 0; arr3 = 4; arr4 = 3; int *arr[5] = {&arr0, &arr1, &arr2, &arr3, &arr4}; int pivot = 2; int h = 5 - 1; int l = 0; int r = 1; while(h > l) // clang-format off __CPROVER_assigns(arr0, arr1, arr2, arr3, arr4, h, l, r) __CPROVER_loop_invariant( // Turn off `clang-format` because it breaks the `==>` operator. h >= l && 0 <= l && l < 5 && 0 <= h && h < 5 && l <= r && r <= h && (r == 0 ==> arr0 == pivot) && (r == 1 ==> arr1 == pivot) && (r == 2 ==> arr2 == pivot) && (r == 3 ==> arr3 == pivot) && (r == 4 ==> arr4 == pivot) && (0 < l ==> arr0 <= pivot) && (1 < l ==> arr1 <= pivot) && (2 < l ==> arr2 <= pivot) && (3 < l ==> arr3 <= pivot) && (4 < l ==> arr4 <= pivot) && (0 > h ==> arr0 >= pivot) && (1 > h ==> arr1 >= pivot) && (2 > h ==> arr2 >= pivot) && (3 > h ==> arr3 >= pivot) && (4 > h ==> arr4 >= pivot) ) __CPROVER_decreases(h - l) // clang-format on { if(*(arr[h]) <= pivot && *(arr[l]) >= pivot) { swap(arr[h], arr[l]); if(r == h) { r = l; h--; } else if(r == l) { r = h; l++; } else { h--; l++; } } else if(*(arr[h]) <= pivot) { l++; } else { h--; } } // Turn off `clang-format` because it breaks the `==>` operator. /* clang-format off */ assert(0 <= r && r < 5); assert(*(arr[r]) == pivot); assert(0 < r ==> arr0 <= pivot); assert(1 < r ==> arr1 <= pivot); assert(2 < r ==> arr2 <= pivot); assert(3 < r ==> arr3 <= pivot); assert(4 < r ==> arr4 <= pivot); assert(0 > r ==> arr0 >= pivot); assert(1 > r ==> arr1 >= pivot); assert(2 > r ==> arr2 >= pivot); assert(3 > r ==> arr3 >= pivot); assert(4 > r ==> arr4 >= pivot); /* clang-format on */ return r; } <|start_filename|>regression/contracts/assigns_enforce_havoc_object/main.c<|end_filename|> #include <assert.h> #include <stdlib.h> int x = 0; typedef struct stc { int i; int j; } stc; typedef struct stb { stc *c; } stb; typedef struct sta { union { stb *b; int i; int j; } u; } sta; int nondet_int(); void bar(sta *a) { if(nondet_bool()) return; __CPROVER_havoc_object(a->u.b->c); return; } void foo(sta *a1, sta *a2) __CPROVER_assigns(__CPROVER_POINTER_OBJECT(a1->u.b->c)) { bar(a1); bar(a2); return; } sta *allocate_sta() { stc *c = malloc(sizeof(*c)); stb *b = malloc(sizeof(*b)); sta *a = malloc(sizeof(*a)); b->c = c; a->u.b = b; return a; } int main() { sta *a1 = allocate_sta(); sta *a2 = allocate_sta(); foo(a1, a2); return 0; } <|start_filename|>src/ansi-c/gcc_builtin_headers_ia32-4.h<|end_filename|> // clang-format off __gcc_v2di __builtin_ia32_broadcastmb128(unsigned char); __gcc_v4di __builtin_ia32_broadcastmb256(unsigned char); __gcc_v4si __builtin_ia32_broadcastmw128(unsigned short); __gcc_v8si __builtin_ia32_broadcastmw256(unsigned short); __gcc_v4df __builtin_ia32_compressdf256_mask(__gcc_v4df, __gcc_v4df, unsigned char); __gcc_v2df __builtin_ia32_compressdf128_mask(__gcc_v2df, __gcc_v2df, unsigned char); __gcc_v8sf __builtin_ia32_compresssf256_mask(__gcc_v8sf, __gcc_v8sf, unsigned char); __gcc_v4sf __builtin_ia32_compresssf128_mask(__gcc_v4sf, __gcc_v4sf, unsigned char); __gcc_v4di __builtin_ia32_compressdi256_mask(__gcc_v4di, __gcc_v4di, unsigned char); __gcc_v2di __builtin_ia32_compressdi128_mask(__gcc_v2di, __gcc_v2di, unsigned char); __gcc_v8si __builtin_ia32_compresssi256_mask(__gcc_v8si, __gcc_v8si, unsigned char); __gcc_v4si __builtin_ia32_compresssi128_mask(__gcc_v4si, __gcc_v4si, unsigned char); __gcc_v4df __builtin_ia32_expanddf256_mask(__gcc_v4df, __gcc_v4df, unsigned char); __gcc_v2df __builtin_ia32_expanddf128_mask(__gcc_v2df, __gcc_v2df, unsigned char); __gcc_v8sf __builtin_ia32_expandsf256_mask(__gcc_v8sf, __gcc_v8sf, unsigned char); __gcc_v4sf __builtin_ia32_expandsf128_mask(__gcc_v4sf, __gcc_v4sf, unsigned char); __gcc_v4di __builtin_ia32_expanddi256_mask(__gcc_v4di, __gcc_v4di, unsigned char); __gcc_v2di __builtin_ia32_expanddi128_mask(__gcc_v2di, __gcc_v2di, unsigned char); __gcc_v8si __builtin_ia32_expandsi256_mask(__gcc_v8si, __gcc_v8si, unsigned char); __gcc_v4si __builtin_ia32_expandsi128_mask(__gcc_v4si, __gcc_v4si, unsigned char); __gcc_v4df __builtin_ia32_expanddf256_maskz(__gcc_v4df, __gcc_v4df, unsigned char); __gcc_v2df __builtin_ia32_expanddf128_maskz(__gcc_v2df, __gcc_v2df, unsigned char); __gcc_v8sf __builtin_ia32_expandsf256_maskz(__gcc_v8sf, __gcc_v8sf, unsigned char); __gcc_v4sf __builtin_ia32_expandsf128_maskz(__gcc_v4sf, __gcc_v4sf, unsigned char); __gcc_v4di __builtin_ia32_expanddi256_maskz(__gcc_v4di, __gcc_v4di, unsigned char); __gcc_v2di __builtin_ia32_expanddi128_maskz(__gcc_v2di, __gcc_v2di, unsigned char); __gcc_v8si __builtin_ia32_expandsi256_maskz(__gcc_v8si, __gcc_v8si, unsigned char); __gcc_v4si __builtin_ia32_expandsi128_maskz(__gcc_v4si, __gcc_v4si, unsigned char); __gcc_v8si __builtin_ia32_pmaxsd256_mask(__gcc_v8si, __gcc_v8si, __gcc_v8si, unsigned char); __gcc_v8si __builtin_ia32_pminsd256_mask(__gcc_v8si, __gcc_v8si, __gcc_v8si, unsigned char); __gcc_v8si __builtin_ia32_pmaxud256_mask(__gcc_v8si, __gcc_v8si, __gcc_v8si, unsigned char); __gcc_v8si __builtin_ia32_pminud256_mask(__gcc_v8si, __gcc_v8si, __gcc_v8si, unsigned char); __gcc_v4si __builtin_ia32_pmaxsd128_mask(__gcc_v4si, __gcc_v4si, __gcc_v4si, unsigned char); __gcc_v4si __builtin_ia32_pminsd128_mask(__gcc_v4si, __gcc_v4si, __gcc_v4si, unsigned char); __gcc_v4si __builtin_ia32_pmaxud128_mask(__gcc_v4si, __gcc_v4si, __gcc_v4si, unsigned char); __gcc_v4si __builtin_ia32_pminud128_mask(__gcc_v4si, __gcc_v4si, __gcc_v4si, unsigned char); __gcc_v4di __builtin_ia32_pmaxsq256_mask(__gcc_v4di, __gcc_v4di, __gcc_v4di, unsigned char); __gcc_v4di __builtin_ia32_pminsq256_mask(__gcc_v4di, __gcc_v4di, __gcc_v4di, unsigned char); __gcc_v4di __builtin_ia32_pmaxuq256_mask(__gcc_v4di, __gcc_v4di, __gcc_v4di, unsigned char); __gcc_v4di __builtin_ia32_pminuq256_mask(__gcc_v4di, __gcc_v4di, __gcc_v4di, unsigned char); __gcc_v2di __builtin_ia32_pmaxsq128_mask(__gcc_v2di, __gcc_v2di, __gcc_v2di, unsigned char); __gcc_v2di __builtin_ia32_pminsq128_mask(__gcc_v2di, __gcc_v2di, __gcc_v2di, unsigned char); __gcc_v2di __builtin_ia32_pmaxuq128_mask(__gcc_v2di, __gcc_v2di, __gcc_v2di, unsigned char); __gcc_v2di __builtin_ia32_pminuq128_mask(__gcc_v2di, __gcc_v2di, __gcc_v2di, unsigned char); __gcc_v32qi __builtin_ia32_pminsb256_mask(__gcc_v32qi, __gcc_v32qi, __gcc_v32qi, unsigned); __gcc_v32qi __builtin_ia32_pminub256_mask(__gcc_v32qi, __gcc_v32qi, __gcc_v32qi, unsigned); __gcc_v32qi __builtin_ia32_pmaxsb256_mask(__gcc_v32qi, __gcc_v32qi, __gcc_v32qi, unsigned); __gcc_v32qi __builtin_ia32_pmaxub256_mask(__gcc_v32qi, __gcc_v32qi, __gcc_v32qi, unsigned); __gcc_v16qi __builtin_ia32_pminsb128_mask(__gcc_v16qi, __gcc_v16qi, __gcc_v16qi, unsigned short); __gcc_v16qi __builtin_ia32_pminub128_mask(__gcc_v16qi, __gcc_v16qi, __gcc_v16qi, unsigned short); __gcc_v16qi __builtin_ia32_pmaxsb128_mask(__gcc_v16qi, __gcc_v16qi, __gcc_v16qi, unsigned short); __gcc_v16qi __builtin_ia32_pmaxub128_mask(__gcc_v16qi, __gcc_v16qi, __gcc_v16qi, unsigned short); __gcc_v16hi __builtin_ia32_pminsw256_mask(__gcc_v16hi, __gcc_v16hi, __gcc_v16hi, unsigned short); __gcc_v16hi __builtin_ia32_pminuw256_mask(__gcc_v16hi, __gcc_v16hi, __gcc_v16hi, unsigned short); __gcc_v16hi __builtin_ia32_pmaxsw256_mask(__gcc_v16hi, __gcc_v16hi, __gcc_v16hi, unsigned short); __gcc_v16hi __builtin_ia32_pmaxuw256_mask(__gcc_v16hi, __gcc_v16hi, __gcc_v16hi, unsigned short); __gcc_v8hi __builtin_ia32_pminsw128_mask(__gcc_v8hi, __gcc_v8hi, __gcc_v8hi, unsigned char); __gcc_v8hi __builtin_ia32_pminuw128_mask(__gcc_v8hi, __gcc_v8hi, __gcc_v8hi, unsigned char); __gcc_v8hi __builtin_ia32_pmaxsw128_mask(__gcc_v8hi, __gcc_v8hi, __gcc_v8hi, unsigned char); __gcc_v8hi __builtin_ia32_pmaxuw128_mask(__gcc_v8hi, __gcc_v8hi, __gcc_v8hi, unsigned char); __gcc_v4di __builtin_ia32_vpconflictdi_256_mask(__gcc_v4di, __gcc_v4di, unsigned char); __gcc_v8si __builtin_ia32_vpconflictsi_256_mask(__gcc_v8si, __gcc_v8si, unsigned char); __gcc_v4di __builtin_ia32_vplzcntq_256_mask(__gcc_v4di, __gcc_v4di, unsigned char); __gcc_v8si __builtin_ia32_vplzcntd_256_mask(__gcc_v8si, __gcc_v8si, unsigned char); __gcc_v4df __builtin_ia32_unpckhpd256_mask(__gcc_v4df, __gcc_v4df, __gcc_v4df, unsigned char); __gcc_v2df __builtin_ia32_unpckhpd128_mask(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char); __gcc_v8sf __builtin_ia32_unpckhps256_mask(__gcc_v8sf, __gcc_v8sf, __gcc_v8sf, unsigned char); __gcc_v4sf __builtin_ia32_unpckhps128_mask(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char); __gcc_v4df __builtin_ia32_unpcklpd256_mask(__gcc_v4df, __gcc_v4df, __gcc_v4df, unsigned char); __gcc_v2df __builtin_ia32_unpcklpd128_mask(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char); __gcc_v8sf __builtin_ia32_unpcklps256_mask(__gcc_v8sf, __gcc_v8sf, __gcc_v8sf, unsigned char); __gcc_v2di __builtin_ia32_vpconflictdi_128_mask(__gcc_v2di, __gcc_v2di, unsigned char); __gcc_v4si __builtin_ia32_vpconflictsi_128_mask(__gcc_v4si, __gcc_v4si, unsigned char); __gcc_v2di __builtin_ia32_vplzcntq_128_mask(__gcc_v2di, __gcc_v2di, unsigned char); __gcc_v4si __builtin_ia32_vplzcntd_128_mask(__gcc_v4si, __gcc_v4si, unsigned char); __gcc_v4sf __builtin_ia32_unpcklps128_mask(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char); __gcc_v8si __builtin_ia32_alignd256_mask(__gcc_v8si, __gcc_v8si, int, __gcc_v8si, unsigned char); __gcc_v4di __builtin_ia32_alignq256_mask(__gcc_v4di, __gcc_v4di, int, __gcc_v4di, unsigned char); __gcc_v4si __builtin_ia32_alignd128_mask(__gcc_v4si, __gcc_v4si, int, __gcc_v4si, unsigned char); __gcc_v2di __builtin_ia32_alignq128_mask(__gcc_v2di, __gcc_v2di, int, __gcc_v2di, unsigned char); __gcc_v8hi __builtin_ia32_vcvtps2ph256_mask(__gcc_v8sf, int, __gcc_v8hi, unsigned char); __gcc_v8hi __builtin_ia32_vcvtps2ph_mask(__gcc_v4sf, int, __gcc_v8hi, unsigned char); __gcc_v4sf __builtin_ia32_vcvtph2ps_mask(__gcc_v8hi, __gcc_v4sf, unsigned char); __gcc_v8sf __builtin_ia32_vcvtph2ps256_mask(__gcc_v8hi, __gcc_v8sf, unsigned char); __gcc_v4si __builtin_ia32_punpckhdq128_mask(__gcc_v4si, __gcc_v4si, __gcc_v4si, unsigned char); __gcc_v8si __builtin_ia32_punpckhdq256_mask(__gcc_v8si, __gcc_v8si, __gcc_v8si, unsigned char); __gcc_v2di __builtin_ia32_punpckhqdq128_mask(__gcc_v2di, __gcc_v2di, __gcc_v2di, unsigned char); __gcc_v4di __builtin_ia32_punpckhqdq256_mask(__gcc_v4di, __gcc_v4di, __gcc_v4di, unsigned char); __gcc_v4si __builtin_ia32_punpckldq128_mask(__gcc_v4si, __gcc_v4si, __gcc_v4si, unsigned char); __gcc_v8si __builtin_ia32_punpckldq256_mask(__gcc_v8si, __gcc_v8si, __gcc_v8si, unsigned char); __gcc_v2di __builtin_ia32_punpcklqdq128_mask(__gcc_v2di, __gcc_v2di, __gcc_v2di, unsigned char); __gcc_v4di __builtin_ia32_punpcklqdq256_mask(__gcc_v4di, __gcc_v4di, __gcc_v4di, unsigned char); __gcc_v16qi __builtin_ia32_punpckhbw128_mask(__gcc_v16qi, __gcc_v16qi, __gcc_v16qi, unsigned short); __gcc_v32qi __builtin_ia32_punpckhbw256_mask(__gcc_v32qi, __gcc_v32qi, __gcc_v32qi, unsigned); __gcc_v8hi __builtin_ia32_punpckhwd128_mask(__gcc_v8hi, __gcc_v8hi, __gcc_v8hi, unsigned char); __gcc_v16hi __builtin_ia32_punpckhwd256_mask(__gcc_v16hi, __gcc_v16hi, __gcc_v16hi, unsigned short); __gcc_v16qi __builtin_ia32_punpcklbw128_mask(__gcc_v16qi, __gcc_v16qi, __gcc_v16qi, unsigned short); __gcc_v32qi __builtin_ia32_punpcklbw256_mask(__gcc_v32qi, __gcc_v32qi, __gcc_v32qi, unsigned); __gcc_v8hi __builtin_ia32_punpcklwd128_mask(__gcc_v8hi, __gcc_v8hi, __gcc_v8hi, unsigned char); __gcc_v16hi __builtin_ia32_punpcklwd256_mask(__gcc_v16hi, __gcc_v16hi, __gcc_v16hi, unsigned short); __gcc_v16hi __builtin_ia32_psllv16hi_mask(__gcc_v16hi, __gcc_v16hi, __gcc_v16hi, unsigned short); __gcc_v8hi __builtin_ia32_psllv8hi_mask(__gcc_v8hi, __gcc_v8hi, __gcc_v8hi, unsigned char); __gcc_v16hi __builtin_ia32_packssdw256_mask(__gcc_v8si, __gcc_v8si, __gcc_v16hi, unsigned short); __gcc_v8hi __builtin_ia32_packssdw128_mask(__gcc_v4si, __gcc_v4si, __gcc_v8hi, unsigned char); __gcc_v16hi __builtin_ia32_packusdw256_mask(__gcc_v8si, __gcc_v8si, __gcc_v16hi, unsigned short); __gcc_v8hi __builtin_ia32_packusdw128_mask(__gcc_v4si, __gcc_v4si, __gcc_v8hi, unsigned char); __gcc_v32qi __builtin_ia32_pavgb256_mask(__gcc_v32qi, __gcc_v32qi, __gcc_v32qi, unsigned); __gcc_v16hi __builtin_ia32_pavgw256_mask(__gcc_v16hi, __gcc_v16hi, __gcc_v16hi, unsigned short); __gcc_v16qi __builtin_ia32_pavgb128_mask(__gcc_v16qi, __gcc_v16qi, __gcc_v16qi, unsigned short); __gcc_v8hi __builtin_ia32_pavgw128_mask(__gcc_v8hi, __gcc_v8hi, __gcc_v8hi, unsigned char); __gcc_v8sf __builtin_ia32_permvarsf256_mask(__gcc_v8sf, __gcc_v8si, __gcc_v8sf, unsigned char); __gcc_v4df __builtin_ia32_permvardf256_mask(__gcc_v4df, __gcc_v4di, __gcc_v4df, unsigned char); __gcc_v4df __builtin_ia32_permdf256_mask(__gcc_v4df, int, __gcc_v4df, unsigned char); __gcc_v32qi __builtin_ia32_pabsb256_mask(__gcc_v32qi, __gcc_v32qi, unsigned); __gcc_v16qi __builtin_ia32_pabsb128_mask(__gcc_v16qi, __gcc_v16qi, unsigned short); __gcc_v16hi __builtin_ia32_pabsw256_mask(__gcc_v16hi, __gcc_v16hi, unsigned short); __gcc_v8hi __builtin_ia32_pabsw128_mask(__gcc_v8hi, __gcc_v8hi, unsigned char); __gcc_v2df __builtin_ia32_vpermilvarpd_mask(__gcc_v2df, __gcc_v2di, __gcc_v2df, unsigned char); __gcc_v4sf __builtin_ia32_vpermilvarps_mask(__gcc_v4sf, __gcc_v4si, __gcc_v4sf, unsigned char); __gcc_v4df __builtin_ia32_vpermilvarpd256_mask(__gcc_v4df, __gcc_v4di, __gcc_v4df, unsigned char); __gcc_v8sf __builtin_ia32_vpermilvarps256_mask(__gcc_v8sf, __gcc_v8si, __gcc_v8sf, unsigned char); __gcc_v2df __builtin_ia32_vpermilpd_mask(__gcc_v2df, int, __gcc_v2df, unsigned char); __gcc_v4sf __builtin_ia32_vpermilps_mask(__gcc_v4sf, int, __gcc_v4sf, unsigned char); __gcc_v4df __builtin_ia32_vpermilpd256_mask(__gcc_v4df, int, __gcc_v4df, unsigned char); __gcc_v8sf __builtin_ia32_vpermilps256_mask(__gcc_v8sf, int, __gcc_v8sf, unsigned char); __gcc_v4di __builtin_ia32_blendmq_256_mask(__gcc_v4di, __gcc_v4di, unsigned char); __gcc_v8si __builtin_ia32_blendmd_256_mask(__gcc_v8si, __gcc_v8si, unsigned char); __gcc_v4df __builtin_ia32_blendmpd_256_mask(__gcc_v4df, __gcc_v4df, unsigned char); __gcc_v8sf __builtin_ia32_blendmps_256_mask(__gcc_v8sf, __gcc_v8sf, unsigned char); __gcc_v2di __builtin_ia32_blendmq_128_mask(__gcc_v2di, __gcc_v2di, unsigned char); __gcc_v4si __builtin_ia32_blendmd_128_mask(__gcc_v4si, __gcc_v4si, unsigned char); __gcc_v2df __builtin_ia32_blendmpd_128_mask(__gcc_v2df, __gcc_v2df, unsigned char); __gcc_v4sf __builtin_ia32_blendmps_128_mask(__gcc_v4sf, __gcc_v4sf, unsigned char); __gcc_v16hi __builtin_ia32_blendmw_256_mask(__gcc_v16hi, __gcc_v16hi, unsigned short); __gcc_v32qi __builtin_ia32_blendmb_256_mask(__gcc_v32qi, __gcc_v32qi, unsigned); __gcc_v8hi __builtin_ia32_blendmw_128_mask(__gcc_v8hi, __gcc_v8hi, unsigned char); __gcc_v16qi __builtin_ia32_blendmb_128_mask(__gcc_v16qi, __gcc_v16qi, unsigned short); __gcc_v8si __builtin_ia32_pmulld256_mask(__gcc_v8si, __gcc_v8si, __gcc_v8si, unsigned char); __gcc_v4si __builtin_ia32_pmulld128_mask(__gcc_v4si, __gcc_v4si, __gcc_v4si, unsigned char); __gcc_v4di __builtin_ia32_pmuludq256_mask(__gcc_v8si, __gcc_v8si, __gcc_v4di, unsigned char); __gcc_v4di __builtin_ia32_pmuldq256_mask(__gcc_v8si, __gcc_v8si, __gcc_v4di, unsigned char); __gcc_v2di __builtin_ia32_pmuldq128_mask(__gcc_v4si, __gcc_v4si, __gcc_v2di, unsigned char); __gcc_v2di __builtin_ia32_pmuludq128_mask(__gcc_v4si, __gcc_v4si, __gcc_v2di, unsigned char); __gcc_v4sf __builtin_ia32_cvtpd2ps256_mask(__gcc_v4df, __gcc_v4sf, unsigned char); __gcc_v4sf __builtin_ia32_cvtpd2ps_mask(__gcc_v2df, __gcc_v4sf, unsigned char); __gcc_v8si __builtin_ia32_permvarsi256_mask(__gcc_v8si, __gcc_v8si, __gcc_v8si, unsigned char); __gcc_v4di __builtin_ia32_permvardi256_mask(__gcc_v4di, __gcc_v4di, __gcc_v4di, unsigned char); __gcc_v4di __builtin_ia32_permdi256_mask(__gcc_v4di, int, __gcc_v4di, unsigned char); unsigned char __builtin_ia32_cmpq256_mask(__gcc_v4di, __gcc_v4di, int, unsigned char); unsigned char __builtin_ia32_cmpd256_mask(__gcc_v8si, __gcc_v8si, int, unsigned char); unsigned char __builtin_ia32_ucmpq256_mask(__gcc_v4di, __gcc_v4di, int, unsigned char); unsigned char __builtin_ia32_ucmpd256_mask(__gcc_v8si, __gcc_v8si, int, unsigned char); unsigned __builtin_ia32_cmpb256_mask(__gcc_v32qi, __gcc_v32qi, int, unsigned); unsigned short __builtin_ia32_cmpw256_mask(__gcc_v16hi, __gcc_v16hi, int, unsigned short); unsigned __builtin_ia32_ucmpb256_mask(__gcc_v32qi, __gcc_v32qi, int, unsigned); unsigned short __builtin_ia32_ucmpw256_mask(__gcc_v16hi, __gcc_v16hi, int, unsigned short); char __builtin_ia32_cmppd256_mask(__gcc_v4df, __gcc_v4df, int, unsigned char); char __builtin_ia32_cmpps256_mask(__gcc_v8sf, __gcc_v8sf, int, unsigned char); unsigned char __builtin_ia32_cmpq128_mask(__gcc_v2di, __gcc_v2di, int, unsigned char); unsigned char __builtin_ia32_cmpd128_mask(__gcc_v4si, __gcc_v4si, int, unsigned char); unsigned char __builtin_ia32_ucmpq128_mask(__gcc_v2di, __gcc_v2di, int, unsigned char); unsigned char __builtin_ia32_ucmpd128_mask(__gcc_v4si, __gcc_v4si, int, unsigned char); unsigned short __builtin_ia32_cmpb128_mask(__gcc_v16qi, __gcc_v16qi, int, unsigned short); unsigned char __builtin_ia32_cmpw128_mask(__gcc_v8hi, __gcc_v8hi, int, unsigned char); unsigned short __builtin_ia32_ucmpb128_mask(__gcc_v16qi, __gcc_v16qi, int, unsigned short); unsigned char __builtin_ia32_ucmpw128_mask(__gcc_v8hi, __gcc_v8hi, int, unsigned char); unsigned char __builtin_ia32_cmppd128_mask(__gcc_v2df, __gcc_v2df, int, unsigned char); unsigned char __builtin_ia32_cmpps128_mask(__gcc_v4sf, __gcc_v4sf, int, unsigned char); __gcc_v16sf __builtin_ia32_broadcastf32x2_512_mask(__gcc_v4sf, __gcc_v16sf, unsigned short); __gcc_v16si __builtin_ia32_broadcasti32x2_512_mask(__gcc_v4si, __gcc_v16si, unsigned short); __gcc_v8df __builtin_ia32_broadcastf64x2_512_mask(__gcc_v2df, __gcc_v8df, unsigned char); __gcc_v8di __builtin_ia32_broadcasti64x2_512_mask(__gcc_v2di, __gcc_v8di, unsigned char); __gcc_v16sf __builtin_ia32_broadcastf32x8_512_mask(__gcc_v8sf, __gcc_v16sf, unsigned short); __gcc_v16si __builtin_ia32_broadcasti32x8_512_mask(__gcc_v8si, __gcc_v16si, unsigned short); __gcc_v2df __builtin_ia32_extractf64x2_512_mask(__gcc_v8df, int, __gcc_v2df, unsigned char); __gcc_v8sf __builtin_ia32_extractf32x8_mask(__gcc_v16sf, int, __gcc_v8sf, unsigned char); __gcc_v2di __builtin_ia32_extracti64x2_512_mask(__gcc_v8di, int, __gcc_v2di, unsigned char); __gcc_v8si __builtin_ia32_extracti32x8_mask(__gcc_v16si, int, __gcc_v8si, unsigned char); __gcc_v8df __builtin_ia32_reducepd512_mask(__gcc_v8df, int, __gcc_v8df, unsigned char); __gcc_v16sf __builtin_ia32_reduceps512_mask(__gcc_v16sf, int, __gcc_v16sf, unsigned short); __gcc_v8di __builtin_ia32_pmullq512_mask(__gcc_v8di, __gcc_v8di, __gcc_v8di, unsigned char); __gcc_v8df __builtin_ia32_xorpd512_mask(__gcc_v8df, __gcc_v8df, __gcc_v8df, unsigned char); __gcc_v16sf __builtin_ia32_xorps512_mask(__gcc_v16sf, __gcc_v16sf, __gcc_v16sf, unsigned short); __gcc_v8df __builtin_ia32_orpd512_mask(__gcc_v8df, __gcc_v8df, __gcc_v8df, unsigned char); __gcc_v16sf __builtin_ia32_orps512_mask(__gcc_v16sf, __gcc_v16sf, __gcc_v16sf, unsigned short); __gcc_v8df __builtin_ia32_andpd512_mask(__gcc_v8df, __gcc_v8df, __gcc_v8df, unsigned char); __gcc_v16sf __builtin_ia32_andps512_mask(__gcc_v16sf, __gcc_v16sf, __gcc_v16sf, unsigned short); __gcc_v8df __builtin_ia32_andnpd512_mask(__gcc_v8df, __gcc_v8df, __gcc_v8df, unsigned char); __gcc_v16sf __builtin_ia32_andnps512_mask(__gcc_v16sf, __gcc_v16sf, __gcc_v16sf, unsigned short); __gcc_v16sf __builtin_ia32_insertf32x8_mask(__gcc_v16sf, __gcc_v8sf, int, __gcc_v16sf, unsigned short); __gcc_v16si __builtin_ia32_inserti32x8_mask(__gcc_v16si, __gcc_v8si, int, __gcc_v16si, unsigned short); __gcc_v8df __builtin_ia32_insertf64x2_512_mask(__gcc_v8df, __gcc_v2df, int, __gcc_v8df, unsigned char); __gcc_v8di __builtin_ia32_inserti64x2_512_mask(__gcc_v8di, __gcc_v2di, int, __gcc_v8di, unsigned char); char __builtin_ia32_fpclasspd512_mask(__gcc_v8df, int, unsigned char); short __builtin_ia32_fpclassps512_mask(__gcc_v16sf, int, unsigned short); unsigned short __builtin_ia32_cvtd2mask512(__gcc_v16si); unsigned char __builtin_ia32_cvtq2mask512(__gcc_v8di); __gcc_v16si __builtin_ia32_cvtmask2d512(unsigned short); __gcc_v8di __builtin_ia32_cvtmask2q512(unsigned char); unsigned __builtin_ia32_kunpcksi(unsigned, unsigned); unsigned long long __builtin_ia32_kunpckdi(unsigned long long, unsigned long long); __gcc_v32hi __builtin_ia32_packusdw512_mask(__gcc_v16si, __gcc_v16si, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_packssdw512_mask(__gcc_v16si, __gcc_v16si, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_movdquhi512_mask(__gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v64qi __builtin_ia32_movdquqi512_mask(__gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v8di __builtin_ia32_psadbw512(__gcc_v64qi, __gcc_v64qi); __gcc_v32hi __builtin_ia32_dbpsadbw512_mask(__gcc_v64qi, __gcc_v64qi, int, __gcc_v32hi, unsigned); __gcc_v64qi __builtin_ia32_pbroadcastb512_mask(__gcc_v16qi, __gcc_v64qi, unsigned long long); __gcc_v64qi __builtin_ia32_pbroadcastb512_gpr_mask(char, __gcc_v64qi, unsigned long long); __gcc_v32hi __builtin_ia32_pbroadcastw512_mask(__gcc_v8hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_pbroadcastw512_gpr_mask(short, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_pmovsxbw512_mask(__gcc_v32qi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_pmovzxbw512_mask(__gcc_v32qi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_permvarhi512_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_vpermt2varhi512_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_vpermt2varhi512_maskz(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_vpermi2varhi512_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v64qi __builtin_ia32_pavgb512_mask(__gcc_v64qi, __gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v32hi __builtin_ia32_pavgw512_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v64qi __builtin_ia32_paddb512_mask(__gcc_v64qi, __gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v64qi __builtin_ia32_psubb512_mask(__gcc_v64qi, __gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v64qi __builtin_ia32_psubsb512_mask(__gcc_v64qi, __gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v64qi __builtin_ia32_paddsb512_mask(__gcc_v64qi, __gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v64qi __builtin_ia32_psubusb512_mask(__gcc_v64qi, __gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v64qi __builtin_ia32_paddusb512_mask(__gcc_v64qi, __gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v32hi __builtin_ia32_psubw512_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_paddw512_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_psubsw512_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_paddsw512_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_psubusw512_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_paddusw512_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_pmaxuw512_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_pmaxsw512_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_pminuw512_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_pminsw512_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v64qi __builtin_ia32_pmaxub512_mask(__gcc_v64qi, __gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v64qi __builtin_ia32_pmaxsb512_mask(__gcc_v64qi, __gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v64qi __builtin_ia32_pminub512_mask(__gcc_v64qi, __gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v64qi __builtin_ia32_pminsb512_mask(__gcc_v64qi, __gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v32qi __builtin_ia32_pmovwb512_mask(__gcc_v32hi, __gcc_v32qi, unsigned); __gcc_v32qi __builtin_ia32_pmovswb512_mask(__gcc_v32hi, __gcc_v32qi, unsigned); __gcc_v32qi __builtin_ia32_pmovuswb512_mask(__gcc_v32hi, __gcc_v32qi, unsigned); __gcc_v32hi __builtin_ia32_pmulhrsw512_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_pmulhuw512_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_pmulhw512_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_pmullw512_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v64qi __builtin_ia32_packsswb512_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v64qi, unsigned long long); __gcc_v64qi __builtin_ia32_packuswb512_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v64qi, unsigned long long); __gcc_v32hi __builtin_ia32_psrav32hi_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_pmaddubsw512_mask(__gcc_v64qi, __gcc_v64qi, __gcc_v32hi, unsigned); __gcc_v16si __builtin_ia32_pmaddwd512_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v16si, unsigned short); __gcc_v32hi __builtin_ia32_psrlv32hi_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v64qi __builtin_ia32_punpckhbw512_mask(__gcc_v64qi, __gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v32hi __builtin_ia32_punpckhwd512_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v64qi __builtin_ia32_punpcklbw512_mask(__gcc_v64qi, __gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v32hi __builtin_ia32_punpcklwd512_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v64qi __builtin_ia32_pshufb512_mask(__gcc_v64qi, __gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v32hi __builtin_ia32_pshufhw512_mask(__gcc_v32hi, int, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_pshuflw512_mask(__gcc_v32hi, int, __gcc_v32hi, unsigned); unsigned long long __builtin_ia32_cvtb2mask512(__gcc_v64qi); unsigned __builtin_ia32_cvtw2mask512(__gcc_v32hi); __gcc_v64qi __builtin_ia32_cvtmask2b512(unsigned long long); __gcc_v32hi __builtin_ia32_cvtmask2w512(unsigned); unsigned long long __builtin_ia32_pcmpeqb512_mask(__gcc_v64qi, __gcc_v64qi, unsigned long long); unsigned __builtin_ia32_pcmpeqw512_mask(__gcc_v32hi, __gcc_v32hi, unsigned); unsigned long long __builtin_ia32_pcmpgtb512_mask(__gcc_v64qi, __gcc_v64qi, unsigned long long); unsigned __builtin_ia32_pcmpgtw512_mask(__gcc_v32hi, __gcc_v32hi, unsigned); unsigned long long __builtin_ia32_ptestmb512(__gcc_v64qi, __gcc_v64qi, unsigned long long); unsigned __builtin_ia32_ptestmw512(__gcc_v32hi, __gcc_v32hi, unsigned); unsigned long long __builtin_ia32_ptestnmb512(__gcc_v64qi, __gcc_v64qi, unsigned long long); unsigned __builtin_ia32_ptestnmw512(__gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_psllv32hi_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v64qi __builtin_ia32_pabsb512_mask(__gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v32hi __builtin_ia32_pabsw512_mask(__gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_blendmw_512_mask(__gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v64qi __builtin_ia32_blendmb_512_mask(__gcc_v64qi, __gcc_v64qi, unsigned long long); unsigned long long __builtin_ia32_cmpb512_mask(__gcc_v64qi, __gcc_v64qi, int, unsigned long long); unsigned __builtin_ia32_cmpw512_mask(__gcc_v32hi, __gcc_v32hi, int, unsigned); unsigned long long __builtin_ia32_ucmpb512_mask(__gcc_v64qi, __gcc_v64qi, int, unsigned long long); unsigned __builtin_ia32_ucmpw512_mask(__gcc_v32hi, __gcc_v32hi, int, unsigned); __gcc_v8di __builtin_ia32_vpmadd52luq512_mask(__gcc_v8di, __gcc_v8di, __gcc_v8di, unsigned char); __gcc_v8di __builtin_ia32_vpmadd52luq512_maskz(__gcc_v8di, __gcc_v8di, __gcc_v8di, unsigned char); __gcc_v8di __builtin_ia32_vpmadd52huq512_mask(__gcc_v8di, __gcc_v8di, __gcc_v8di, unsigned char); __gcc_v8di __builtin_ia32_vpmadd52huq512_maskz(__gcc_v8di, __gcc_v8di, __gcc_v8di, unsigned char); __gcc_v4di __builtin_ia32_vpmadd52luq256_mask(__gcc_v4di, __gcc_v4di, __gcc_v4di, unsigned char); __gcc_v4di __builtin_ia32_vpmadd52luq256_maskz(__gcc_v4di, __gcc_v4di, __gcc_v4di, unsigned char); __gcc_v4di __builtin_ia32_vpmadd52huq256_mask(__gcc_v4di, __gcc_v4di, __gcc_v4di, unsigned char); __gcc_v4di __builtin_ia32_vpmadd52huq256_maskz(__gcc_v4di, __gcc_v4di, __gcc_v4di, unsigned char); __gcc_v2di __builtin_ia32_vpmadd52luq128_mask(__gcc_v2di, __gcc_v2di, __gcc_v2di, unsigned char); __gcc_v2di __builtin_ia32_vpmadd52luq128_maskz(__gcc_v2di, __gcc_v2di, __gcc_v2di, unsigned char); __gcc_v2di __builtin_ia32_vpmadd52huq128_mask(__gcc_v2di, __gcc_v2di, __gcc_v2di, unsigned char); __gcc_v2di __builtin_ia32_vpmadd52huq128_maskz(__gcc_v2di, __gcc_v2di, __gcc_v2di, unsigned char); __gcc_v64qi __builtin_ia32_vpmultishiftqb512_mask(__gcc_v64qi, __gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v32qi __builtin_ia32_vpmultishiftqb256_mask(__gcc_v32qi, __gcc_v32qi, __gcc_v32qi, unsigned); __gcc_v16qi __builtin_ia32_vpmultishiftqb128_mask(__gcc_v16qi, __gcc_v16qi, __gcc_v16qi, unsigned short); __gcc_v64qi __builtin_ia32_permvarqi512_mask(__gcc_v64qi, __gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v64qi __builtin_ia32_vpermt2varqi512_mask(__gcc_v64qi, __gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v64qi __builtin_ia32_vpermt2varqi512_maskz(__gcc_v64qi, __gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v64qi __builtin_ia32_vpermi2varqi512_mask(__gcc_v64qi, __gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v32qi __builtin_ia32_permvarqi256_mask(__gcc_v32qi, __gcc_v32qi, __gcc_v32qi, unsigned); __gcc_v16qi __builtin_ia32_permvarqi128_mask(__gcc_v16qi, __gcc_v16qi, __gcc_v16qi, unsigned short); __gcc_v32qi __builtin_ia32_vpermt2varqi256_mask(__gcc_v32qi, __gcc_v32qi, __gcc_v32qi, unsigned); __gcc_v32qi __builtin_ia32_vpermt2varqi256_maskz(__gcc_v32qi, __gcc_v32qi, __gcc_v32qi, unsigned); __gcc_v16qi __builtin_ia32_vpermt2varqi128_mask(__gcc_v16qi, __gcc_v16qi, __gcc_v16qi, unsigned short); __gcc_v16qi __builtin_ia32_vpermt2varqi128_maskz(__gcc_v16qi, __gcc_v16qi, __gcc_v16qi, unsigned short); __gcc_v32qi __builtin_ia32_vpermi2varqi256_mask(__gcc_v32qi, __gcc_v32qi, __gcc_v32qi, unsigned); __gcc_v16qi __builtin_ia32_vpermi2varqi128_mask(__gcc_v16qi, __gcc_v16qi, __gcc_v16qi, unsigned short); __gcc_v2df __builtin_ia32_rangesd128_round(__gcc_v2df, __gcc_v2df, int, int); __gcc_v4sf __builtin_ia32_rangess128_round(__gcc_v4sf, __gcc_v4sf, int, int); __gcc_v8di __builtin_ia32_cvtpd2qq512_mask(__gcc_v8df, __gcc_v8di, char, int); __gcc_v8di __builtin_ia32_cvtps2qq512_mask(__gcc_v8sf, __gcc_v8di, char, int); __gcc_v8di __builtin_ia32_cvtpd2uqq512_mask(__gcc_v8df, __gcc_v8di, char, int); __gcc_v8di __builtin_ia32_cvtps2uqq512_mask(__gcc_v8sf, __gcc_v8di, char, int); __gcc_v8sf __builtin_ia32_cvtqq2ps512_mask(__gcc_v8di, __gcc_v8sf, char, int); __gcc_v8sf __builtin_ia32_cvtuqq2ps512_mask(__gcc_v8di, __gcc_v8sf, char, int); __gcc_v8df __builtin_ia32_cvtqq2pd512_mask(__gcc_v8di, __gcc_v8df, char, int); __gcc_v8df __builtin_ia32_cvtuqq2pd512_mask(__gcc_v8di, __gcc_v8df, char, int); __gcc_v8di __builtin_ia32_cvttps2qq512_mask(__gcc_v8sf, __gcc_v8di, char, int); __gcc_v8di __builtin_ia32_cvttps2uqq512_mask(__gcc_v8sf, __gcc_v8di, char, int); __gcc_v8di __builtin_ia32_cvttpd2qq512_mask(__gcc_v8df, __gcc_v8di, char, int); __gcc_v8di __builtin_ia32_cvttpd2uqq512_mask(__gcc_v8df, __gcc_v8di, char, int); __gcc_v16sf __builtin_ia32_rangeps512_mask(__gcc_v16sf, __gcc_v16sf, int, __gcc_v16sf, short, int); __gcc_v8df __builtin_ia32_rangepd512_mask(__gcc_v8df, __gcc_v8df, int, __gcc_v8df, char, int); __gcc_v16sf __builtin_ia32_4fmaddps_mask(__gcc_v16sf, __gcc_v16sf, __gcc_v16sf, __gcc_v16sf, __gcc_v16sf, const __gcc_v4sf*, __gcc_v16sf, unsigned short); __gcc_v16sf __builtin_ia32_4fmaddps(__gcc_v16sf, __gcc_v16sf, __gcc_v16sf, __gcc_v16sf, __gcc_v16sf, const __gcc_v4sf*); __gcc_v4sf __builtin_ia32_4fmaddss(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, __gcc_v4sf, __gcc_v4sf, const __gcc_v4sf*); __gcc_v4sf __builtin_ia32_4fmaddss_mask(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, __gcc_v4sf, __gcc_v4sf, const __gcc_v4sf*, __gcc_v4sf, unsigned char); __gcc_v16sf __builtin_ia32_4fnmaddps_mask(__gcc_v16sf, __gcc_v16sf, __gcc_v16sf, __gcc_v16sf, __gcc_v16sf, const __gcc_v4sf*, __gcc_v16sf, unsigned short); __gcc_v16sf __builtin_ia32_4fnmaddps(__gcc_v16sf, __gcc_v16sf, __gcc_v16sf, __gcc_v16sf, __gcc_v16sf, const __gcc_v4sf*); __gcc_v4sf __builtin_ia32_4fnmaddss(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, __gcc_v4sf, __gcc_v4sf, const __gcc_v4sf*); __gcc_v4sf __builtin_ia32_4fnmaddss_mask(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, __gcc_v4sf, __gcc_v4sf, const __gcc_v4sf*, __gcc_v4sf, unsigned char); __gcc_v16si __builtin_ia32_vp4dpwssd(__gcc_v16si, __gcc_v16si, __gcc_v16si, __gcc_v16si, __gcc_v16si, const __gcc_v4si*); __gcc_v16si __builtin_ia32_vp4dpwssd_mask(__gcc_v16si, __gcc_v16si, __gcc_v16si, __gcc_v16si, __gcc_v16si, const __gcc_v4si*, __gcc_v16si, unsigned short); __gcc_v16si __builtin_ia32_vp4dpwssds(__gcc_v16si, __gcc_v16si, __gcc_v16si, __gcc_v16si, __gcc_v16si, const __gcc_v4si*); __gcc_v16si __builtin_ia32_vp4dpwssds_mask(__gcc_v16si, __gcc_v16si, __gcc_v16si, __gcc_v16si, __gcc_v16si, const __gcc_v4si*, __gcc_v16si, unsigned short); __gcc_v16si __builtin_ia32_vpopcountd_v16si(__gcc_v16si); __gcc_v16si __builtin_ia32_vpopcountd_v16si_mask(__gcc_v16si, __gcc_v16si, unsigned short); __gcc_v8di __builtin_ia32_vpopcountq_v8di(__gcc_v8di); __gcc_v8di __builtin_ia32_vpopcountq_v8di_mask(__gcc_v8di, __gcc_v8di, unsigned char); unsigned __builtin_ia32_rdpid(); unsigned long __builtin_ia32_sizeof(void); unsigned long long __builtin_ia32_xgetbv(int); void __builtin_ia32_xsetbv(int, long long); __gcc_v2df __builtin_ia32_loadsd_mask(const double*, __gcc_v2df, unsigned char); __gcc_v4sf __builtin_ia32_loadss_mask(const float*, __gcc_v4sf, unsigned char); void __builtin_ia32_storesd_mask(double*, __gcc_v2df, unsigned char); void __builtin_ia32_storess_mask(float*, __gcc_v4sf, unsigned char); void __builtin_ia32_2intersectd512(unsigned short*, unsigned short*, __gcc_v16si, __gcc_v16si); void __builtin_ia32_2intersectq512(unsigned char*, unsigned char*, __gcc_v8di, __gcc_v8di); void __builtin_ia32_2intersectd256(unsigned char*, unsigned char*, __gcc_v8si, __gcc_v8si); void __builtin_ia32_2intersectq256(unsigned char*, unsigned char*, __gcc_v4di, __gcc_v4di); void __builtin_ia32_2intersectd128(unsigned char*, unsigned char*, __gcc_v4si, __gcc_v4si); void __builtin_ia32_2intersectq128(unsigned char*, unsigned char*, __gcc_v2di, __gcc_v2di); void __builtin_ia32_pmovwb128mem_mask(unsigned long long*, __gcc_v8hi, unsigned char); void __builtin_ia32_pmovwb256mem_mask(__gcc_v16qi*, __gcc_v16hi, unsigned short); void __builtin_ia32_pmovswb128mem_mask(unsigned long long*, __gcc_v8hi, unsigned char); void __builtin_ia32_pmovswb256mem_mask(__gcc_v16qi*, __gcc_v16hi, unsigned short); void __builtin_ia32_pmovuswb128mem_mask(unsigned long long*, __gcc_v8hi, unsigned char); void __builtin_ia32_pmovuswb256mem_mask(__gcc_v16qi*, __gcc_v16hi, unsigned short); void __builtin_ia32_pmovuswb512mem_mask(__gcc_v32qi*, __gcc_v32hi, unsigned); void __builtin_ia32_pmovswb512mem_mask(__gcc_v32qi*, __gcc_v32hi, unsigned); void __builtin_ia32_pmovwb512mem_mask(__gcc_v32qi*, __gcc_v32hi, unsigned); void __builtin_ia32_compressstoreuqi512_mask(__gcc_v64qi*, __gcc_v64qi, unsigned long long); void __builtin_ia32_compressstoreuhi512_mask(__gcc_v32hi*, __gcc_v32hi, unsigned); void __builtin_ia32_compressstoreuqi256_mask(__gcc_v32qi*, __gcc_v32qi, unsigned); void __builtin_ia32_compressstoreuqi128_mask(__gcc_v16qi*, __gcc_v16qi, unsigned short); void __builtin_ia32_compressstoreuhi256_mask(__gcc_v16hi*, __gcc_v16hi, unsigned short); void __builtin_ia32_compressstoreuhi128_mask(__gcc_v8hi*, __gcc_v8hi, unsigned char); __gcc_v64qi __builtin_ia32_expandloadqi512_mask(const __gcc_v64qi*, __gcc_v64qi, unsigned long long); __gcc_v64qi __builtin_ia32_expandloadqi512_maskz(const __gcc_v64qi*, __gcc_v64qi, unsigned long long); __gcc_v32hi __builtin_ia32_expandloadhi512_mask(const __gcc_v32hi*, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_expandloadhi512_maskz(const __gcc_v32hi*, __gcc_v32hi, unsigned); __gcc_v32qi __builtin_ia32_expandloadqi256_mask(const __gcc_v32qi*, __gcc_v32qi, unsigned); __gcc_v32qi __builtin_ia32_expandloadqi256_maskz(const __gcc_v32qi*, __gcc_v32qi, unsigned); __gcc_v16hi __builtin_ia32_expandloadhi256_mask(const __gcc_v16hi*, __gcc_v16hi, unsigned short); __gcc_v16hi __builtin_ia32_expandloadhi256_maskz(const __gcc_v16hi*, __gcc_v16hi, unsigned short); __gcc_v16qi __builtin_ia32_expandloadqi128_mask(const __gcc_v16qi*, __gcc_v16qi, unsigned short); __gcc_v16qi __builtin_ia32_expandloadqi128_maskz(const __gcc_v16qi*, __gcc_v16qi, unsigned short); __gcc_v8hi __builtin_ia32_expandloadhi128_mask(const __gcc_v8hi*, __gcc_v8hi, unsigned char); __gcc_v8hi __builtin_ia32_expandloadhi128_maskz(const __gcc_v8hi*, __gcc_v8hi, unsigned char); void __builtin_ia32_wbinvd(); void __builtin_ia32_directstoreu_u32(unsigned*, unsigned); void __builtin_ia32_directstoreu_u64(unsigned long long*, unsigned long long); void __builtin_ia32_wbnoinvd(); void __builtin_ia32_movdir64b(void*, const void*); void __builtin_ia32_ptwrite32(unsigned); void __builtin_ia32_ptwrite64(unsigned long long); int __builtin_ia32_enqcmd(void*, const void*); int __builtin_ia32_enqcmds(void*, const void*); void __builtin_ia32_serialize(); void __builtin_ia32_xsusldtrk(); void __builtin_ia32_xresldtrk(); void __builtin_ia32_clui(); void __builtin_ia32_stui(); void __builtin_ia32_senduipi(unsigned long long); void __builtin_ia32_hreset(unsigned); void __builtin_ia32_loadiwkey(__gcc_v2di, __gcc_v2di, __gcc_v2di, unsigned); unsigned char __builtin_ia32_aesdec128kl_u8(__gcc_v2di*, __gcc_v2di, const void*); unsigned char __builtin_ia32_aesdec256kl_u8(__gcc_v2di*, __gcc_v2di, const void*); unsigned char __builtin_ia32_aesenc128kl_u8(__gcc_v2di*, __gcc_v2di, const void*); unsigned char __builtin_ia32_aesenc256kl_u8(__gcc_v2di*, __gcc_v2di, const void*); unsigned __builtin_ia32_encodekey128_u32(unsigned, __gcc_v2di, void*); unsigned __builtin_ia32_encodekey256_u32(unsigned, __gcc_v2di, __gcc_v2di, void*); unsigned char __builtin_ia32_aesdecwide128kl_u8(__gcc_v2di*, const __gcc_v2di*, const void*); unsigned char __builtin_ia32_aesdecwide256kl_u8(__gcc_v2di*, const __gcc_v2di*, const void*); unsigned char __builtin_ia32_aesencwide128kl_u8(__gcc_v2di*, const __gcc_v2di*, const void*); unsigned char __builtin_ia32_aesencwide256kl_u8(__gcc_v2di*, const __gcc_v2di*, const void*); __gcc_v2df __builtin_ia32_rcp14sd_mask(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char); __gcc_v4sf __builtin_ia32_rcp14ss_mask(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char); __gcc_v2df __builtin_ia32_rsqrt14sd_mask(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char); __gcc_v4sf __builtin_ia32_rsqrt14ss_mask(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char); __gcc_v2df __builtin_ia32_movesd_mask(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char); __gcc_v4sf __builtin_ia32_movess_mask(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char); __gcc_v16sf __builtin_ia32_floorps512(__gcc_v16sf); __gcc_v16sf __builtin_ia32_ceilps512(__gcc_v16sf); __gcc_v16sf __builtin_ia32_truncps512(__gcc_v16sf); __gcc_v8df __builtin_ia32_floorpd512(__gcc_v8df); __gcc_v8df __builtin_ia32_ceilpd512(__gcc_v8df); __gcc_v8df __builtin_ia32_truncpd512(__gcc_v8df); __gcc_v16si __builtin_ia32_floorps_sfix512(__gcc_v16sf); __gcc_v16si __builtin_ia32_ceilps_sfix512(__gcc_v16sf); unsigned char __builtin_ia32_kshiftliqi(unsigned char, unsigned char); unsigned char __builtin_ia32_kshiftriqi(unsigned char, unsigned char); __gcc_v4di __builtin_ia32_palignr256_mask(__gcc_v4di, __gcc_v4di, int, __gcc_v4di, unsigned); __gcc_v2di __builtin_ia32_palignr128_mask(__gcc_v2di, __gcc_v2di, int, __gcc_v2di, unsigned short); __gcc_v2df __builtin_ia32_reducesd_mask(__gcc_v2df, __gcc_v2df, int, __gcc_v2df, unsigned char); __gcc_v4sf __builtin_ia32_reducess_mask(__gcc_v4sf, __gcc_v4sf, int, __gcc_v4sf, unsigned char); __gcc_v8hi __builtin_ia32_psllwi128_mask(__gcc_v8hi, int, __gcc_v8hi, unsigned char); __gcc_v4si __builtin_ia32_pslldi128_mask(__gcc_v4si, int, __gcc_v4si, unsigned char); __gcc_v2di __builtin_ia32_psllqi128_mask(__gcc_v2di, int, __gcc_v2di, unsigned char); __gcc_v8hi __builtin_ia32_psllw128_mask(__gcc_v8hi, __gcc_v8hi, __gcc_v8hi, unsigned char); __gcc_v4si __builtin_ia32_pslld128_mask(__gcc_v4si, __gcc_v4si, __gcc_v4si, unsigned char); __gcc_v2di __builtin_ia32_psllq128_mask(__gcc_v2di, __gcc_v2di, __gcc_v2di, unsigned char); __gcc_v16hi __builtin_ia32_psllwi256_mask(__gcc_v16hi, int, __gcc_v16hi, unsigned short); __gcc_v16hi __builtin_ia32_psllw256_mask(__gcc_v16hi, __gcc_v8hi, __gcc_v16hi, unsigned short); __gcc_v8si __builtin_ia32_pslldi256_mask(__gcc_v8si, int, __gcc_v8si, unsigned char); __gcc_v8si __builtin_ia32_pslld256_mask(__gcc_v8si, __gcc_v4si, __gcc_v8si, unsigned char); __gcc_v4di __builtin_ia32_psllqi256_mask(__gcc_v4di, int, __gcc_v4di, unsigned char); __gcc_v4di __builtin_ia32_psllq256_mask(__gcc_v4di, __gcc_v2di, __gcc_v4di, unsigned char); __gcc_v4si __builtin_ia32_psradi128_mask(__gcc_v4si, int, __gcc_v4si, unsigned char); __gcc_v4si __builtin_ia32_psrad128_mask(__gcc_v4si, __gcc_v4si, __gcc_v4si, unsigned char); __gcc_v8si __builtin_ia32_psradi256_mask(__gcc_v8si, int, __gcc_v8si, unsigned char); __gcc_v8si __builtin_ia32_psrad256_mask(__gcc_v8si, __gcc_v4si, __gcc_v8si, unsigned char); __gcc_v2di __builtin_ia32_psraqi128_mask(__gcc_v2di, int, __gcc_v2di, unsigned char); __gcc_v2di __builtin_ia32_psraq128_mask(__gcc_v2di, __gcc_v2di, __gcc_v2di, unsigned char); __gcc_v4di __builtin_ia32_psraqi256_mask(__gcc_v4di, int, __gcc_v4di, unsigned char); __gcc_v4di __builtin_ia32_psraq256_mask(__gcc_v4di, __gcc_v2di, __gcc_v4di, unsigned char); __gcc_v4si __builtin_ia32_psrldi128_mask(__gcc_v4si, int, __gcc_v4si, unsigned char); __gcc_v4si __builtin_ia32_psrld128_mask(__gcc_v4si, __gcc_v4si, __gcc_v4si, unsigned char); __gcc_v8si __builtin_ia32_psrldi256_mask(__gcc_v8si, int, __gcc_v8si, unsigned char); __gcc_v8si __builtin_ia32_psrld256_mask(__gcc_v8si, __gcc_v4si, __gcc_v8si, unsigned char); __gcc_v2di __builtin_ia32_psrlqi128_mask(__gcc_v2di, int, __gcc_v2di, unsigned char); __gcc_v2di __builtin_ia32_psrlq128_mask(__gcc_v2di, __gcc_v2di, __gcc_v2di, unsigned char); __gcc_v4di __builtin_ia32_psrlqi256_mask(__gcc_v4di, int, __gcc_v4di, unsigned char); __gcc_v4di __builtin_ia32_psrlq256_mask(__gcc_v4di, __gcc_v2di, __gcc_v4di, unsigned char); __gcc_v4df __builtin_ia32_vfmsubpd256_mask(__gcc_v4df, __gcc_v4df, __gcc_v4df, unsigned char); __gcc_v4df __builtin_ia32_vfmsubpd256_maskz(__gcc_v4df, __gcc_v4df, __gcc_v4df, unsigned char); __gcc_v2df __builtin_ia32_vfmsubpd128_mask(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char); __gcc_v2df __builtin_ia32_vfmsubpd128_maskz(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char); __gcc_v8sf __builtin_ia32_vfmsubps256_mask(__gcc_v8sf, __gcc_v8sf, __gcc_v8sf, unsigned char); __gcc_v8sf __builtin_ia32_vfmsubps256_maskz(__gcc_v8sf, __gcc_v8sf, __gcc_v8sf, unsigned char); __gcc_v4sf __builtin_ia32_vfmsubps128_mask(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char); __gcc_v4sf __builtin_ia32_vfmsubps128_maskz(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char); __gcc_v4df __builtin_ia32_vfnmaddpd256_mask3(__gcc_v4df, __gcc_v4df, __gcc_v4df, unsigned char); __gcc_v4df __builtin_ia32_vfnmaddpd256_maskz(__gcc_v4df, __gcc_v4df, __gcc_v4df, unsigned char); __gcc_v2df __builtin_ia32_vfnmaddpd128_mask3(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char); __gcc_v2df __builtin_ia32_vfnmaddpd128_maskz(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char); __gcc_v8sf __builtin_ia32_vfnmaddps256_mask3(__gcc_v8sf, __gcc_v8sf, __gcc_v8sf, unsigned char); __gcc_v8sf __builtin_ia32_vfnmaddps256_maskz(__gcc_v8sf, __gcc_v8sf, __gcc_v8sf, unsigned char); __gcc_v4sf __builtin_ia32_vfnmaddps128_mask3(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char); __gcc_v4sf __builtin_ia32_vfnmaddps128_maskz(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char); __gcc_v4df __builtin_ia32_vfnmsubpd256_maskz(__gcc_v4df, __gcc_v4df, __gcc_v4df, unsigned char); __gcc_v2df __builtin_ia32_vfnmsubpd128_maskz(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char); __gcc_v8sf __builtin_ia32_vfnmsubps256_maskz(__gcc_v8sf, __gcc_v8sf, __gcc_v8sf, unsigned char); __gcc_v4sf __builtin_ia32_vfnmsubps128_maskz(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char); __gcc_v16hi __builtin_ia32_psrawi256_mask(__gcc_v16hi, int, __gcc_v16hi, unsigned short); __gcc_v16hi __builtin_ia32_psraw256_mask(__gcc_v16hi, __gcc_v8hi, __gcc_v16hi, unsigned short); __gcc_v8hi __builtin_ia32_psrawi128_mask(__gcc_v8hi, int, __gcc_v8hi, unsigned char); __gcc_v8hi __builtin_ia32_psraw128_mask(__gcc_v8hi, __gcc_v8hi, __gcc_v8hi, unsigned char); __gcc_v16hi __builtin_ia32_psrlwi256_mask(__gcc_v16hi, int, __gcc_v16hi, unsigned short); __gcc_v16hi __builtin_ia32_psrlw256_mask(__gcc_v16hi, __gcc_v8hi, __gcc_v16hi, unsigned short); __gcc_v8hi __builtin_ia32_psrlwi128_mask(__gcc_v8hi, int, __gcc_v8hi, unsigned char); __gcc_v8hi __builtin_ia32_psrlw128_mask(__gcc_v8hi, __gcc_v8hi, __gcc_v8hi, unsigned char); char __builtin_ia32_fpclasssd_mask(__gcc_v2df, int, unsigned char); char __builtin_ia32_fpclassss_mask(__gcc_v4sf, int, unsigned char); __gcc_v8di __builtin_ia32_pslldq512(__gcc_v8di, int); __gcc_v8di __builtin_ia32_psrldq512(__gcc_v8di, int); __gcc_v8di __builtin_ia32_palignr512(__gcc_v8di, __gcc_v8di, int); __gcc_v8di __builtin_ia32_palignr512_mask(__gcc_v8di, __gcc_v8di, int, __gcc_v8di, unsigned long long); __gcc_v32hi __builtin_ia32_psllwi512_mask(__gcc_v32hi, int, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_psllw512_mask(__gcc_v32hi, __gcc_v8hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_psrawi512_mask(__gcc_v32hi, int, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_psraw512_mask(__gcc_v32hi, __gcc_v8hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_psrlwi512_mask(__gcc_v32hi, int, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_psrlw512_mask(__gcc_v32hi, __gcc_v8hi, __gcc_v32hi, unsigned); __gcc_v64qi __builtin_ia32_compressqi512_mask(__gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v32hi __builtin_ia32_compresshi512_mask(__gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v32qi __builtin_ia32_compressqi256_mask(__gcc_v32qi, __gcc_v32qi, unsigned); __gcc_v16qi __builtin_ia32_compressqi128_mask(__gcc_v16qi, __gcc_v16qi, unsigned short); __gcc_v16hi __builtin_ia32_compresshi256_mask(__gcc_v16hi, __gcc_v16hi, unsigned short); __gcc_v8hi __builtin_ia32_compresshi128_mask(__gcc_v8hi, __gcc_v8hi, unsigned char); __gcc_v64qi __builtin_ia32_expandqi512_mask(__gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v64qi __builtin_ia32_expandqi512_maskz(__gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v32hi __builtin_ia32_expandhi512_mask(__gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_expandhi512_maskz(__gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v32qi __builtin_ia32_expandqi256_mask(__gcc_v32qi, __gcc_v32qi, unsigned); __gcc_v32qi __builtin_ia32_expandqi256_maskz(__gcc_v32qi, __gcc_v32qi, unsigned); __gcc_v16qi __builtin_ia32_expandqi128_mask(__gcc_v16qi, __gcc_v16qi, unsigned short); __gcc_v16qi __builtin_ia32_expandqi128_maskz(__gcc_v16qi, __gcc_v16qi, unsigned short); __gcc_v16hi __builtin_ia32_expandhi256_mask(__gcc_v16hi, __gcc_v16hi, unsigned short); __gcc_v16hi __builtin_ia32_expandhi256_maskz(__gcc_v16hi, __gcc_v16hi, unsigned short); __gcc_v8hi __builtin_ia32_expandhi128_mask(__gcc_v8hi, __gcc_v8hi, unsigned char); __gcc_v8hi __builtin_ia32_expandhi128_maskz(__gcc_v8hi, __gcc_v8hi, unsigned char); // clang-format on <|start_filename|>regression/cbmc/pragma_cprover_enable_all/main.c<|end_filename|> #include <stdbool.h> #include <stdlib.h> bool nondet_bool(); typedef enum ABC { A = 0, B = 1, C = 2 } ABC; int main() { #pragma CPROVER check push #pragma CPROVER check disable "bounds" #pragma CPROVER check disable "pointer" #pragma CPROVER check disable "div-by-zero" #pragma CPROVER check disable "enum-range" #pragma CPROVER check disable "signed-overflow" #pragma CPROVER check disable "unsigned-overflow" #pragma CPROVER check disable "pointer-overflow" #pragma CPROVER check disable "float-overflow" #pragma CPROVER check disable "conversion" #pragma CPROVER check disable "undefined-shift" #pragma CPROVER check disable "nan" #pragma CPROVER check disable "pointer-primitive" { int N = 10; char *p = malloc(N * sizeof(*p)); char *q; char *r; float den; float x; float y; ABC e; bool readable; char i; signed int j; readable = __CPROVER_r_ok(q, 1); q = p + 2000000000000; q = r; if(nondet_bool()) den = 0.0; else den = 1.0; y = x / den; e = 10; i += 1; j += 1; } #pragma CPROVER check push #pragma CPROVER check enable "bounds" #pragma CPROVER check enable "pointer" #pragma CPROVER check enable "div-by-zero" #pragma CPROVER check enable "enum-range" #pragma CPROVER check enable "signed-overflow" #pragma CPROVER check enable "unsigned-overflow" #pragma CPROVER check enable "pointer-overflow" #pragma CPROVER check enable "float-overflow" #pragma CPROVER check enable "conversion" #pragma CPROVER check enable "undefined-shift" #pragma CPROVER check enable "nan" #pragma CPROVER check enable "pointer-primitive" { int N = 10; char *p = malloc(N * sizeof(*p)); char *q; char *r; float den; float x; float y; ABC e; bool readable; char i; signed int j; readable = __CPROVER_r_ok(q, 1); q = p + 2000000000000; q = r; if(nondet_bool()) den = 0.0; else den = 1.0; y = x / den; e = 10; i += 1; j += 1; } #pragma CPROVER check pop #pragma CPROVER check pop return 0; } <|start_filename|>regression/cbmc-library/__builtin_llabs-01/main.c<|end_filename|> #include <assert.h> #include <limits.h> #ifndef __GNUC__ long long __builtin_llabs(long long); #endif int main() { assert(__builtin_llabs(LLONG_MIN + 1) == LLONG_MAX); return 0; } <|start_filename|>regression/cbmc/switch9/main.c<|end_filename|> #include <stdlib.h> int main() { int *p = malloc(sizeof(int)); if(!p) return 1; switch(*p) { case 1: case 2: case 3: return 0; case 4: default: return -1; } } <|start_filename|>regression/contracts/loop-freeness-check/main.c<|end_filename|> int foo(int *arr) // clang-format off __CPROVER_assigns(__CPROVER_POINTER_OBJECT(arr)) // clang-format off { for(int i = 0; i < 10; i++) arr[i] = i; return 0; } int main() { int arr[10]; foo(arr); } <|start_filename|>regression/cbmc-library/siglongjmp-01/main.c<|end_filename|> #include <setjmp.h> static sigjmp_buf env; int main() { siglongjmp(env, 1); __CPROVER_assert(0, "unreachable"); return 0; } <|start_filename|>regression/goto-analyzer/label/main.c<|end_filename|> int main() { goto ERROR; return 0; ERROR: return 1; } <|start_filename|>src/ansi-c/gcc_builtin_headers_ia32-5.h<|end_filename|> // clang-format off __gcc_v32hi __builtin_ia32_vpshrd_v32hi(__gcc_v32hi, __gcc_v32hi, int); __gcc_v32hi __builtin_ia32_vpshrd_v32hi_mask(__gcc_v32hi, __gcc_v32hi, int, __gcc_v32hi, int); __gcc_v16hi __builtin_ia32_vpshrd_v16hi(__gcc_v16hi, __gcc_v16hi, int); __gcc_v16hi __builtin_ia32_vpshrd_v16hi_mask(__gcc_v16hi, __gcc_v16hi, int, __gcc_v16hi, int); __gcc_v8hi __builtin_ia32_vpshrd_v8hi(__gcc_v8hi, __gcc_v8hi, int); __gcc_v8hi __builtin_ia32_vpshrd_v8hi_mask(__gcc_v8hi, __gcc_v8hi, int, __gcc_v8hi, int); __gcc_v16si __builtin_ia32_vpshrd_v16si(__gcc_v16si, __gcc_v16si, int); __gcc_v16si __builtin_ia32_vpshrd_v16si_mask(__gcc_v16si, __gcc_v16si, int, __gcc_v16si, int); __gcc_v8si __builtin_ia32_vpshrd_v8si(__gcc_v8si, __gcc_v8si, int); __gcc_v8si __builtin_ia32_vpshrd_v8si_mask(__gcc_v8si, __gcc_v8si, int, __gcc_v8si, int); __gcc_v4si __builtin_ia32_vpshrd_v4si(__gcc_v4si, __gcc_v4si, int); __gcc_v4si __builtin_ia32_vpshrd_v4si_mask(__gcc_v4si, __gcc_v4si, int, __gcc_v4si, int); __gcc_v8di __builtin_ia32_vpshrd_v8di(__gcc_v8di, __gcc_v8di, int); __gcc_v8di __builtin_ia32_vpshrd_v8di_mask(__gcc_v8di, __gcc_v8di, int, __gcc_v8di, int); __gcc_v4di __builtin_ia32_vpshrd_v4di(__gcc_v4di, __gcc_v4di, int); __gcc_v4di __builtin_ia32_vpshrd_v4di_mask(__gcc_v4di, __gcc_v4di, int, __gcc_v4di, int); __gcc_v2di __builtin_ia32_vpshrd_v2di(__gcc_v2di, __gcc_v2di, int); __gcc_v2di __builtin_ia32_vpshrd_v2di_mask(__gcc_v2di, __gcc_v2di, int, __gcc_v2di, int); __gcc_v32hi __builtin_ia32_vpshld_v32hi(__gcc_v32hi, __gcc_v32hi, int); __gcc_v32hi __builtin_ia32_vpshld_v32hi_mask(__gcc_v32hi, __gcc_v32hi, int, __gcc_v32hi, int); __gcc_v16hi __builtin_ia32_vpshld_v16hi(__gcc_v16hi, __gcc_v16hi, int); __gcc_v16hi __builtin_ia32_vpshld_v16hi_mask(__gcc_v16hi, __gcc_v16hi, int, __gcc_v16hi, int); __gcc_v8hi __builtin_ia32_vpshld_v8hi(__gcc_v8hi, __gcc_v8hi, int); __gcc_v8hi __builtin_ia32_vpshld_v8hi_mask(__gcc_v8hi, __gcc_v8hi, int, __gcc_v8hi, int); __gcc_v16si __builtin_ia32_vpshld_v16si(__gcc_v16si, __gcc_v16si, int); __gcc_v16si __builtin_ia32_vpshld_v16si_mask(__gcc_v16si, __gcc_v16si, int, __gcc_v16si, int); __gcc_v8si __builtin_ia32_vpshld_v8si(__gcc_v8si, __gcc_v8si, int); __gcc_v8si __builtin_ia32_vpshld_v8si_mask(__gcc_v8si, __gcc_v8si, int, __gcc_v8si, int); __gcc_v4si __builtin_ia32_vpshld_v4si(__gcc_v4si, __gcc_v4si, int); __gcc_v4si __builtin_ia32_vpshld_v4si_mask(__gcc_v4si, __gcc_v4si, int, __gcc_v4si, int); __gcc_v8di __builtin_ia32_vpshld_v8di(__gcc_v8di, __gcc_v8di, int); __gcc_v8di __builtin_ia32_vpshld_v8di_mask(__gcc_v8di, __gcc_v8di, int, __gcc_v8di, int); __gcc_v4di __builtin_ia32_vpshld_v4di(__gcc_v4di, __gcc_v4di, int); __gcc_v4di __builtin_ia32_vpshld_v4di_mask(__gcc_v4di, __gcc_v4di, int, __gcc_v4di, int); __gcc_v2di __builtin_ia32_vpshld_v2di(__gcc_v2di, __gcc_v2di, int); __gcc_v2di __builtin_ia32_vpshld_v2di_mask(__gcc_v2di, __gcc_v2di, int, __gcc_v2di, int); __gcc_v32hi __builtin_ia32_vpshrdv_v32hi(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi); __gcc_v32hi __builtin_ia32_vpshrdv_v32hi_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_vpshrdv_v32hi_maskz(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v16hi __builtin_ia32_vpshrdv_v16hi(__gcc_v16hi, __gcc_v16hi, __gcc_v16hi); __gcc_v16hi __builtin_ia32_vpshrdv_v16hi_mask(__gcc_v16hi, __gcc_v16hi, __gcc_v16hi, unsigned short); __gcc_v16hi __builtin_ia32_vpshrdv_v16hi_maskz(__gcc_v16hi, __gcc_v16hi, __gcc_v16hi, unsigned short); __gcc_v8hi __builtin_ia32_vpshrdv_v8hi(__gcc_v8hi, __gcc_v8hi, __gcc_v8hi); __gcc_v8hi __builtin_ia32_vpshrdv_v8hi_mask(__gcc_v8hi, __gcc_v8hi, __gcc_v8hi, unsigned char); __gcc_v8hi __builtin_ia32_vpshrdv_v8hi_maskz(__gcc_v8hi, __gcc_v8hi, __gcc_v8hi, unsigned char); __gcc_v16si __builtin_ia32_vpshrdv_v16si(__gcc_v16si, __gcc_v16si, __gcc_v16si); __gcc_v16si __builtin_ia32_vpshrdv_v16si_mask(__gcc_v16si, __gcc_v16si, __gcc_v16si, unsigned short); __gcc_v16si __builtin_ia32_vpshrdv_v16si_maskz(__gcc_v16si, __gcc_v16si, __gcc_v16si, unsigned short); __gcc_v8si __builtin_ia32_vpshrdv_v8si(__gcc_v8si, __gcc_v8si, __gcc_v8si); __gcc_v8si __builtin_ia32_vpshrdv_v8si_mask(__gcc_v8si, __gcc_v8si, __gcc_v8si, unsigned char); __gcc_v8si __builtin_ia32_vpshrdv_v8si_maskz(__gcc_v8si, __gcc_v8si, __gcc_v8si, unsigned char); __gcc_v4si __builtin_ia32_vpshrdv_v4si(__gcc_v4si, __gcc_v4si, __gcc_v4si); __gcc_v4si __builtin_ia32_vpshrdv_v4si_mask(__gcc_v4si, __gcc_v4si, __gcc_v4si, unsigned char); __gcc_v4si __builtin_ia32_vpshrdv_v4si_maskz(__gcc_v4si, __gcc_v4si, __gcc_v4si, unsigned char); __gcc_v8di __builtin_ia32_vpshrdv_v8di(__gcc_v8di, __gcc_v8di, __gcc_v8di); __gcc_v8di __builtin_ia32_vpshrdv_v8di_mask(__gcc_v8di, __gcc_v8di, __gcc_v8di, unsigned char); __gcc_v8di __builtin_ia32_vpshrdv_v8di_maskz(__gcc_v8di, __gcc_v8di, __gcc_v8di, unsigned char); __gcc_v4di __builtin_ia32_vpshrdv_v4di(__gcc_v4di, __gcc_v4di, __gcc_v4di); __gcc_v4di __builtin_ia32_vpshrdv_v4di_mask(__gcc_v4di, __gcc_v4di, __gcc_v4di, unsigned char); __gcc_v4di __builtin_ia32_vpshrdv_v4di_maskz(__gcc_v4di, __gcc_v4di, __gcc_v4di, unsigned char); __gcc_v2di __builtin_ia32_vpshrdv_v2di(__gcc_v2di, __gcc_v2di, __gcc_v2di); __gcc_v2di __builtin_ia32_vpshrdv_v2di_mask(__gcc_v2di, __gcc_v2di, __gcc_v2di, unsigned char); __gcc_v2di __builtin_ia32_vpshrdv_v2di_maskz(__gcc_v2di, __gcc_v2di, __gcc_v2di, unsigned char); __gcc_v32hi __builtin_ia32_vpshldv_v32hi(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi); __gcc_v32hi __builtin_ia32_vpshldv_v32hi_mask(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_vpshldv_v32hi_maskz(__gcc_v32hi, __gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v16hi __builtin_ia32_vpshldv_v16hi(__gcc_v16hi, __gcc_v16hi, __gcc_v16hi); __gcc_v16hi __builtin_ia32_vpshldv_v16hi_mask(__gcc_v16hi, __gcc_v16hi, __gcc_v16hi, unsigned short); __gcc_v16hi __builtin_ia32_vpshldv_v16hi_maskz(__gcc_v16hi, __gcc_v16hi, __gcc_v16hi, unsigned short); __gcc_v8hi __builtin_ia32_vpshldv_v8hi(__gcc_v8hi, __gcc_v8hi, __gcc_v8hi); __gcc_v8hi __builtin_ia32_vpshldv_v8hi_mask(__gcc_v8hi, __gcc_v8hi, __gcc_v8hi, unsigned char); __gcc_v8hi __builtin_ia32_vpshldv_v8hi_maskz(__gcc_v8hi, __gcc_v8hi, __gcc_v8hi, unsigned char); __gcc_v16si __builtin_ia32_vpshldv_v16si(__gcc_v16si, __gcc_v16si, __gcc_v16si); __gcc_v16si __builtin_ia32_vpshldv_v16si_mask(__gcc_v16si, __gcc_v16si, __gcc_v16si, unsigned short); __gcc_v16si __builtin_ia32_vpshldv_v16si_maskz(__gcc_v16si, __gcc_v16si, __gcc_v16si, unsigned short); __gcc_v8si __builtin_ia32_vpshldv_v8si(__gcc_v8si, __gcc_v8si, __gcc_v8si); __gcc_v8si __builtin_ia32_vpshldv_v8si_mask(__gcc_v8si, __gcc_v8si, __gcc_v8si, unsigned char); __gcc_v8si __builtin_ia32_vpshldv_v8si_maskz(__gcc_v8si, __gcc_v8si, __gcc_v8si, unsigned char); __gcc_v4si __builtin_ia32_vpshldv_v4si(__gcc_v4si, __gcc_v4si, __gcc_v4si); __gcc_v4si __builtin_ia32_vpshldv_v4si_mask(__gcc_v4si, __gcc_v4si, __gcc_v4si, unsigned char); __gcc_v4si __builtin_ia32_vpshldv_v4si_maskz(__gcc_v4si, __gcc_v4si, __gcc_v4si, unsigned char); __gcc_v8di __builtin_ia32_vpshldv_v8di(__gcc_v8di, __gcc_v8di, __gcc_v8di); __gcc_v8di __builtin_ia32_vpshldv_v8di_mask(__gcc_v8di, __gcc_v8di, __gcc_v8di, unsigned char); __gcc_v8di __builtin_ia32_vpshldv_v8di_maskz(__gcc_v8di, __gcc_v8di, __gcc_v8di, unsigned char); __gcc_v4di __builtin_ia32_vpshldv_v4di(__gcc_v4di, __gcc_v4di, __gcc_v4di); __gcc_v4di __builtin_ia32_vpshldv_v4di_mask(__gcc_v4di, __gcc_v4di, __gcc_v4di, unsigned char); __gcc_v4di __builtin_ia32_vpshldv_v4di_maskz(__gcc_v4di, __gcc_v4di, __gcc_v4di, unsigned char); __gcc_v2di __builtin_ia32_vpshldv_v2di(__gcc_v2di, __gcc_v2di, __gcc_v2di); __gcc_v2di __builtin_ia32_vpshldv_v2di_mask(__gcc_v2di, __gcc_v2di, __gcc_v2di, unsigned char); __gcc_v2di __builtin_ia32_vpshldv_v2di_maskz(__gcc_v2di, __gcc_v2di, __gcc_v2di, unsigned char); __gcc_v64qi __builtin_ia32_vgf2p8affineinvqb_v64qi(__gcc_v64qi, __gcc_v64qi, int); __gcc_v64qi __builtin_ia32_vgf2p8affineinvqb_v64qi_mask(__gcc_v64qi, __gcc_v64qi, int, __gcc_v64qi, unsigned long long); __gcc_v32qi __builtin_ia32_vgf2p8affineinvqb_v32qi(__gcc_v32qi, __gcc_v32qi, int); __gcc_v32qi __builtin_ia32_vgf2p8affineinvqb_v32qi_mask(__gcc_v32qi, __gcc_v32qi, int, __gcc_v32qi, unsigned); __gcc_v16qi __builtin_ia32_vgf2p8affineinvqb_v16qi(__gcc_v16qi, __gcc_v16qi, int); __gcc_v16qi __builtin_ia32_vgf2p8affineinvqb_v16qi_mask(__gcc_v16qi, __gcc_v16qi, int, __gcc_v16qi, unsigned short); __gcc_v64qi __builtin_ia32_vgf2p8affineqb_v64qi(__gcc_v64qi, __gcc_v64qi, int); __gcc_v64qi __builtin_ia32_vgf2p8affineqb_v64qi_mask(__gcc_v64qi, __gcc_v64qi, int, __gcc_v64qi, unsigned long long); __gcc_v32qi __builtin_ia32_vgf2p8affineqb_v32qi(__gcc_v32qi, __gcc_v32qi, int); __gcc_v32qi __builtin_ia32_vgf2p8affineqb_v32qi_mask(__gcc_v32qi, __gcc_v32qi, int, __gcc_v32qi, unsigned); __gcc_v16qi __builtin_ia32_vgf2p8affineqb_v16qi(__gcc_v16qi, __gcc_v16qi, int); __gcc_v16qi __builtin_ia32_vgf2p8affineqb_v16qi_mask(__gcc_v16qi, __gcc_v16qi, int, __gcc_v16qi, unsigned short); __gcc_v64qi __builtin_ia32_vgf2p8mulb_v64qi(__gcc_v64qi, __gcc_v64qi); __gcc_v64qi __builtin_ia32_vgf2p8mulb_v64qi_mask(__gcc_v64qi, __gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v32qi __builtin_ia32_vgf2p8mulb_v32qi(__gcc_v32qi, __gcc_v32qi); __gcc_v32qi __builtin_ia32_vgf2p8mulb_v32qi_mask(__gcc_v32qi, __gcc_v32qi, __gcc_v32qi, unsigned); __gcc_v16qi __builtin_ia32_vgf2p8mulb_v16qi(__gcc_v16qi, __gcc_v16qi); __gcc_v16qi __builtin_ia32_vgf2p8mulb_v16qi_mask(__gcc_v16qi, __gcc_v16qi, __gcc_v16qi, unsigned short); __gcc_v16si __builtin_ia32_vpdpbusd_v16si(__gcc_v16si, __gcc_v16si, __gcc_v16si); __gcc_v16si __builtin_ia32_vpdpbusd_v16si_mask(__gcc_v16si, __gcc_v16si, __gcc_v16si, unsigned short); __gcc_v16si __builtin_ia32_vpdpbusd_v16si_maskz(__gcc_v16si, __gcc_v16si, __gcc_v16si, unsigned short); __gcc_v8si __builtin_ia32_vpdpbusd_v8si(__gcc_v8si, __gcc_v8si, __gcc_v8si); __gcc_v8si __builtin_ia32_vpdpbusd_v8si_mask(__gcc_v8si, __gcc_v8si, __gcc_v8si, unsigned char); __gcc_v8si __builtin_ia32_vpdpbusd_v8si_maskz(__gcc_v8si, __gcc_v8si, __gcc_v8si, unsigned char); __gcc_v4si __builtin_ia32_vpdpbusd_v4si(__gcc_v4si, __gcc_v4si, __gcc_v4si); __gcc_v4si __builtin_ia32_vpdpbusd_v4si_mask(__gcc_v4si, __gcc_v4si, __gcc_v4si, unsigned char); __gcc_v4si __builtin_ia32_vpdpbusd_v4si_maskz(__gcc_v4si, __gcc_v4si, __gcc_v4si, unsigned char); __gcc_v16si __builtin_ia32_vpdpbusds_v16si(__gcc_v16si, __gcc_v16si, __gcc_v16si); __gcc_v16si __builtin_ia32_vpdpbusds_v16si_mask(__gcc_v16si, __gcc_v16si, __gcc_v16si, unsigned short); __gcc_v16si __builtin_ia32_vpdpbusds_v16si_maskz(__gcc_v16si, __gcc_v16si, __gcc_v16si, unsigned short); __gcc_v8si __builtin_ia32_vpdpbusds_v8si(__gcc_v8si, __gcc_v8si, __gcc_v8si); __gcc_v8si __builtin_ia32_vpdpbusds_v8si_mask(__gcc_v8si, __gcc_v8si, __gcc_v8si, unsigned char); __gcc_v8si __builtin_ia32_vpdpbusds_v8si_maskz(__gcc_v8si, __gcc_v8si, __gcc_v8si, unsigned char); __gcc_v4si __builtin_ia32_vpdpbusds_v4si(__gcc_v4si, __gcc_v4si, __gcc_v4si); __gcc_v4si __builtin_ia32_vpdpbusds_v4si_mask(__gcc_v4si, __gcc_v4si, __gcc_v4si, unsigned char); __gcc_v4si __builtin_ia32_vpdpbusds_v4si_maskz(__gcc_v4si, __gcc_v4si, __gcc_v4si, unsigned char); __gcc_v16si __builtin_ia32_vpdpwssd_v16si(__gcc_v16si, __gcc_v16si, __gcc_v16si); __gcc_v16si __builtin_ia32_vpdpwssd_v16si_mask(__gcc_v16si, __gcc_v16si, __gcc_v16si, unsigned short); __gcc_v16si __builtin_ia32_vpdpwssd_v16si_maskz(__gcc_v16si, __gcc_v16si, __gcc_v16si, unsigned short); __gcc_v8si __builtin_ia32_vpdpwssd_v8si(__gcc_v8si, __gcc_v8si, __gcc_v8si); __gcc_v8si __builtin_ia32_vpdpwssd_v8si_mask(__gcc_v8si, __gcc_v8si, __gcc_v8si, unsigned char); __gcc_v8si __builtin_ia32_vpdpwssd_v8si_maskz(__gcc_v8si, __gcc_v8si, __gcc_v8si, unsigned char); __gcc_v4si __builtin_ia32_vpdpwssd_v4si(__gcc_v4si, __gcc_v4si, __gcc_v4si); __gcc_v4si __builtin_ia32_vpdpwssd_v4si_mask(__gcc_v4si, __gcc_v4si, __gcc_v4si, unsigned char); __gcc_v4si __builtin_ia32_vpdpwssd_v4si_maskz(__gcc_v4si, __gcc_v4si, __gcc_v4si, unsigned char); __gcc_v16si __builtin_ia32_vpdpwssds_v16si(__gcc_v16si, __gcc_v16si, __gcc_v16si); __gcc_v16si __builtin_ia32_vpdpwssds_v16si_mask(__gcc_v16si, __gcc_v16si, __gcc_v16si, unsigned short); __gcc_v16si __builtin_ia32_vpdpwssds_v16si_maskz(__gcc_v16si, __gcc_v16si, __gcc_v16si, unsigned short); __gcc_v8si __builtin_ia32_vpdpwssds_v8si(__gcc_v8si, __gcc_v8si, __gcc_v8si); __gcc_v8si __builtin_ia32_vpdpwssds_v8si_mask(__gcc_v8si, __gcc_v8si, __gcc_v8si, unsigned char); __gcc_v8si __builtin_ia32_vpdpwssds_v8si_maskz(__gcc_v8si, __gcc_v8si, __gcc_v8si, unsigned char); __gcc_v4si __builtin_ia32_vpdpwssds_v4si(__gcc_v4si, __gcc_v4si, __gcc_v4si); __gcc_v4si __builtin_ia32_vpdpwssds_v4si_mask(__gcc_v4si, __gcc_v4si, __gcc_v4si, unsigned char); __gcc_v4si __builtin_ia32_vpdpwssds_v4si_maskz(__gcc_v4si, __gcc_v4si, __gcc_v4si, unsigned char); __gcc_v2di __builtin_ia32_vpclmulqdq_v2di(__gcc_v2di, __gcc_v2di, int); __gcc_v4di __builtin_ia32_vpclmulqdq_v4di(__gcc_v4di, __gcc_v4di, int); __gcc_v8di __builtin_ia32_vpclmulqdq_v8di(__gcc_v8di, __gcc_v8di, int); __gcc_v4di __builtin_ia32_vpopcountq_v4di(__gcc_v4di); __gcc_v4di __builtin_ia32_vpopcountq_v4di_mask(__gcc_v4di, __gcc_v4di, unsigned char); __gcc_v2di __builtin_ia32_vpopcountq_v2di(__gcc_v2di); __gcc_v2di __builtin_ia32_vpopcountq_v2di_mask(__gcc_v2di, __gcc_v2di, unsigned char); __gcc_v4si __builtin_ia32_vpopcountd_v4si(__gcc_v4si); __gcc_v4si __builtin_ia32_vpopcountd_v4si_mask(__gcc_v4si, __gcc_v4si, unsigned short); __gcc_v8si __builtin_ia32_vpopcountd_v8si(__gcc_v8si); __gcc_v8si __builtin_ia32_vpopcountd_v8si_mask(__gcc_v8si, __gcc_v8si, unsigned short); __gcc_v64qi __builtin_ia32_vpopcountb_v64qi(__gcc_v64qi); __gcc_v64qi __builtin_ia32_vpopcountb_v64qi_mask(__gcc_v64qi, __gcc_v64qi, unsigned long long); __gcc_v32qi __builtin_ia32_vpopcountb_v32qi(__gcc_v32qi); __gcc_v32qi __builtin_ia32_vpopcountb_v32qi_mask(__gcc_v32qi, __gcc_v32qi, unsigned); __gcc_v16qi __builtin_ia32_vpopcountb_v16qi(__gcc_v16qi); __gcc_v16qi __builtin_ia32_vpopcountb_v16qi_mask(__gcc_v16qi, __gcc_v16qi, unsigned short); __gcc_v32hi __builtin_ia32_vpopcountw_v32hi(__gcc_v32hi); __gcc_v32hi __builtin_ia32_vpopcountw_v32hi_mask(__gcc_v32hi, __gcc_v32hi, unsigned); __gcc_v16hi __builtin_ia32_vpopcountw_v16hi(__gcc_v16hi); __gcc_v16hi __builtin_ia32_vpopcountw_v16hi_mask(__gcc_v16hi, __gcc_v16hi, unsigned short); __gcc_v8hi __builtin_ia32_vpopcountw_v8hi(__gcc_v8hi); __gcc_v8hi __builtin_ia32_vpopcountw_v8hi_mask(__gcc_v8hi, __gcc_v8hi, unsigned char); unsigned long long __builtin_ia32_vpshufbitqmb512_mask(__gcc_v64qi, __gcc_v64qi, unsigned long long); unsigned __builtin_ia32_vpshufbitqmb256_mask(__gcc_v32qi, __gcc_v32qi, unsigned); unsigned short __builtin_ia32_vpshufbitqmb128_mask(__gcc_v16qi, __gcc_v16qi, unsigned short); __gcc_v16qi __builtin_ia32_vaesdec_v16qi(__gcc_v16qi, __gcc_v16qi); __gcc_v32qi __builtin_ia32_vaesdec_v32qi(__gcc_v32qi, __gcc_v32qi); __gcc_v64qi __builtin_ia32_vaesdec_v64qi(__gcc_v64qi, __gcc_v64qi); __gcc_v16qi __builtin_ia32_vaesdeclast_v16qi(__gcc_v16qi, __gcc_v16qi); __gcc_v32qi __builtin_ia32_vaesdeclast_v32qi(__gcc_v32qi, __gcc_v32qi); __gcc_v64qi __builtin_ia32_vaesdeclast_v64qi(__gcc_v64qi, __gcc_v64qi); __gcc_v16qi __builtin_ia32_vaesenc_v16qi(__gcc_v16qi, __gcc_v16qi); __gcc_v32qi __builtin_ia32_vaesenc_v32qi(__gcc_v32qi, __gcc_v32qi); __gcc_v64qi __builtin_ia32_vaesenc_v64qi(__gcc_v64qi, __gcc_v64qi); __gcc_v16qi __builtin_ia32_vaesenclast_v16qi(__gcc_v16qi, __gcc_v16qi); __gcc_v32qi __builtin_ia32_vaesenclast_v32qi(__gcc_v32qi, __gcc_v32qi); __gcc_v64qi __builtin_ia32_vaesenclast_v64qi(__gcc_v64qi, __gcc_v64qi); __gcc_v32hi __builtin_ia32_cvtne2ps2bf16_v32hi(__gcc_v16sf, __gcc_v16sf); __gcc_v32hi __builtin_ia32_cvtne2ps2bf16_v32hi_mask(__gcc_v16sf, __gcc_v16sf, __gcc_v32hi, unsigned); __gcc_v32hi __builtin_ia32_cvtne2ps2bf16_v32hi_maskz(__gcc_v16sf, __gcc_v16sf, unsigned); __gcc_v16hi __builtin_ia32_cvtne2ps2bf16_v16hi(__gcc_v8sf, __gcc_v8sf); __gcc_v16hi __builtin_ia32_cvtne2ps2bf16_v16hi_mask(__gcc_v8sf, __gcc_v8sf, __gcc_v16hi, unsigned short); __gcc_v16hi __builtin_ia32_cvtne2ps2bf16_v16hi_maskz(__gcc_v8sf, __gcc_v8sf, unsigned short); __gcc_v8hi __builtin_ia32_cvtne2ps2bf16_v8hi(__gcc_v4sf, __gcc_v4sf); __gcc_v8hi __builtin_ia32_cvtne2ps2bf16_v8hi_mask(__gcc_v4sf, __gcc_v4sf, __gcc_v8hi, unsigned char); __gcc_v8hi __builtin_ia32_cvtne2ps2bf16_v8hi_maskz(__gcc_v4sf, __gcc_v4sf, unsigned char); __gcc_v16hi __builtin_ia32_cvtneps2bf16_v16sf(__gcc_v16sf); __gcc_v16hi __builtin_ia32_cvtneps2bf16_v16sf_mask(__gcc_v16sf, __gcc_v16hi, unsigned short); __gcc_v16hi __builtin_ia32_cvtneps2bf16_v16sf_maskz(__gcc_v16sf, unsigned short); __gcc_v8hi __builtin_ia32_cvtneps2bf16_v8sf(__gcc_v8sf); __gcc_v8hi __builtin_ia32_cvtneps2bf16_v8sf_mask(__gcc_v8sf, __gcc_v8hi, unsigned char); __gcc_v8hi __builtin_ia32_cvtneps2bf16_v8sf_maskz(__gcc_v8sf, unsigned char); __gcc_v8hi __builtin_ia32_cvtneps2bf16_v4sf(__gcc_v4sf); __gcc_v8hi __builtin_ia32_cvtneps2bf16_v4sf_mask(__gcc_v4sf, __gcc_v8hi, unsigned char); __gcc_v8hi __builtin_ia32_cvtneps2bf16_v4sf_maskz(__gcc_v4sf, unsigned char); __gcc_v16sf __builtin_ia32_dpbf16ps_v16sf(__gcc_v16sf, __gcc_v32hi, __gcc_v32hi); __gcc_v16sf __builtin_ia32_dpbf16ps_v16sf_mask(__gcc_v16sf, __gcc_v32hi, __gcc_v32hi, unsigned short); __gcc_v16sf __builtin_ia32_dpbf16ps_v16sf_maskz(__gcc_v16sf, __gcc_v32hi, __gcc_v32hi, unsigned short); __gcc_v8sf __builtin_ia32_dpbf16ps_v8sf(__gcc_v8sf, __gcc_v16hi, __gcc_v16hi); __gcc_v8sf __builtin_ia32_dpbf16ps_v8sf_mask(__gcc_v8sf, __gcc_v16hi, __gcc_v16hi, unsigned char); __gcc_v8sf __builtin_ia32_dpbf16ps_v8sf_maskz(__gcc_v8sf, __gcc_v16hi, __gcc_v16hi, unsigned char); __gcc_v4sf __builtin_ia32_dpbf16ps_v4sf(__gcc_v4sf, __gcc_v8hi, __gcc_v8hi); __gcc_v4sf __builtin_ia32_dpbf16ps_v4sf_mask(__gcc_v4sf, __gcc_v8hi, __gcc_v8hi, unsigned char); __gcc_v4sf __builtin_ia32_dpbf16ps_v4sf_maskz(__gcc_v4sf, __gcc_v8hi, __gcc_v8hi, unsigned char); __gcc_v2df __builtin_ia32_addsd_mask_round(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char, int); __gcc_v4sf __builtin_ia32_addss_mask_round(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char, int); __gcc_v4sf __builtin_ia32_cvtsd2ss_mask_round(__gcc_v4sf, __gcc_v2df, __gcc_v4sf, unsigned char, int); __gcc_v2df __builtin_ia32_cvtss2sd_mask_round(__gcc_v2df, __gcc_v4sf, __gcc_v2df, unsigned char, int); __gcc_v2df __builtin_ia32_divsd_mask_round(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char, int); __gcc_v4sf __builtin_ia32_divss_mask_round(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char, int); __gcc_v2df __builtin_ia32_getexpsd_mask_round(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char, int); __gcc_v4sf __builtin_ia32_getexpss_mask_round(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char, int); __gcc_v2df __builtin_ia32_getmantsd_mask_round(__gcc_v2df, __gcc_v2df, int, __gcc_v2df, unsigned char, int); __gcc_v4sf __builtin_ia32_getmantss_mask_round(__gcc_v4sf, __gcc_v4sf, int, __gcc_v4sf, unsigned char, int); __gcc_v2df __builtin_ia32_maxsd_mask_round(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char, int); __gcc_v4sf __builtin_ia32_maxss_mask_round(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char, int); __gcc_v2df __builtin_ia32_minsd_mask_round(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char, int); __gcc_v4sf __builtin_ia32_minss_mask_round(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char, int); __gcc_v2df __builtin_ia32_mulsd_mask_round(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char, int); __gcc_v4sf __builtin_ia32_mulss_mask_round(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char, int); __gcc_v2df __builtin_ia32_rndscalesd_mask_round(__gcc_v2df, __gcc_v2df, int, __gcc_v2df, unsigned char, int); __gcc_v4sf __builtin_ia32_rndscaless_mask_round(__gcc_v4sf, __gcc_v4sf, int, __gcc_v4sf, unsigned char, int); __gcc_v2df __builtin_ia32_scalefsd_mask_round(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char, int); __gcc_v4sf __builtin_ia32_scalefss_mask_round(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char, int); __gcc_v2df __builtin_ia32_sqrtsd_mask_round(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char, int); __gcc_v4sf __builtin_ia32_sqrtss_mask_round(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char, int); __gcc_v2df __builtin_ia32_subsd_mask_round(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char, int); __gcc_v4sf __builtin_ia32_subss_mask_round(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char, int); __gcc_v2df __builtin_ia32_vfmaddsd3_mask(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char, int); __gcc_v2df __builtin_ia32_vfmaddsd3_mask3(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char, int); __gcc_v2df __builtin_ia32_vfmaddsd3_maskz(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char, int); __gcc_v2df __builtin_ia32_vfmsubsd3_mask3(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char, int); __gcc_v4sf __builtin_ia32_vfmaddss3_mask(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char, int); __gcc_v4sf __builtin_ia32_vfmaddss3_mask3(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char, int); __gcc_v4sf __builtin_ia32_vfmaddss3_maskz(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char, int); __gcc_v4sf __builtin_ia32_vfmsubss3_mask3(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char, int); __gcc_v8df __builtin_ia32_vfmsubpd512_mask(__gcc_v8df, __gcc_v8df, __gcc_v8df, unsigned char, int); __gcc_v8df __builtin_ia32_vfmsubpd512_maskz(__gcc_v8df, __gcc_v8df, __gcc_v8df, unsigned char, int); __gcc_v16sf __builtin_ia32_vfmsubps512_mask(__gcc_v16sf, __gcc_v16sf, __gcc_v16sf, short, int); __gcc_v16sf __builtin_ia32_vfmsubps512_maskz(__gcc_v16sf, __gcc_v16sf, __gcc_v16sf, short, int); __gcc_v8df __builtin_ia32_vfnmaddpd512_mask3(__gcc_v8df, __gcc_v8df, __gcc_v8df, unsigned char, int); __gcc_v8df __builtin_ia32_vfnmaddpd512_maskz(__gcc_v8df, __gcc_v8df, __gcc_v8df, unsigned char, int); __gcc_v16sf __builtin_ia32_vfnmaddps512_mask3(__gcc_v16sf, __gcc_v16sf, __gcc_v16sf, short, int); __gcc_v16sf __builtin_ia32_vfnmaddps512_maskz(__gcc_v16sf, __gcc_v16sf, __gcc_v16sf, short, int); __gcc_v8df __builtin_ia32_vfnmsubpd512_maskz(__gcc_v8df, __gcc_v8df, __gcc_v8df, unsigned char, int); __gcc_v16sf __builtin_ia32_vfnmsubps512_maskz(__gcc_v16sf, __gcc_v16sf, __gcc_v16sf, short, int); __gcc_v2df __builtin_ia32_rcp28sd_mask_round(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char, int); __gcc_v4sf __builtin_ia32_rcp28ss_mask_round(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char, int); __gcc_v2df __builtin_ia32_rsqrt28sd_mask_round(__gcc_v2df, __gcc_v2df, __gcc_v2df, unsigned char, int); __gcc_v4sf __builtin_ia32_rsqrt28ss_mask_round(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf, unsigned char, int); __gcc_v8df __builtin_ia32_reducepd512_mask_round(__gcc_v8df, int, __gcc_v8df, unsigned char, int); __gcc_v16sf __builtin_ia32_reduceps512_mask_round(__gcc_v16sf, int, __gcc_v16sf, unsigned short, int); __gcc_v2df __builtin_ia32_reducesd_mask_round(__gcc_v2df, __gcc_v2df, int, __gcc_v2df, unsigned char, int); __gcc_v4sf __builtin_ia32_reducess_mask_round(__gcc_v4sf, __gcc_v4sf, int, __gcc_v4sf, unsigned char, int); __gcc_v2df __builtin_ia32_rangesd128_mask_round(__gcc_v2df, __gcc_v2df, int, __gcc_v2df, unsigned char, int); __gcc_v4sf __builtin_ia32_rangess128_mask_round(__gcc_v4sf, __gcc_v4sf, int, __gcc_v4sf, unsigned char, int); unsigned __builtin_ia32_rdsspd(); unsigned long long __builtin_ia32_rdsspq(); void __builtin_ia32_incsspd(unsigned); void __builtin_ia32_incsspq(unsigned long long); void __builtin_ia32_saveprevssp(); void __builtin_ia32_rstorssp(void*); void __builtin_ia32_wrssd(unsigned, void*); void __builtin_ia32_wrssq(unsigned long long, void*); void __builtin_ia32_wrussd(unsigned, void*); void __builtin_ia32_wrussq(unsigned long long, void*); void __builtin_ia32_setssbsy(); void __builtin_ia32_clrssbsy(void*); // clang-format on <|start_filename|>regression/contracts/quantifiers-forall-requires-enforce/main.c<|end_filename|> #include <stdbool.h> // clang-format off bool f1(int *arr) __CPROVER_requires(__CPROVER_forall { int i; (0 <= i && i < 10) ==> arr[i] == i }) __CPROVER_ensures( __CPROVER_return_value == true ) // clang-format on { bool is_identity = true; is_identity &= (arr[0] == 0); is_identity &= (arr[1] == 1); is_identity &= (arr[2] == 2); is_identity &= (arr[3] == 3); is_identity &= (arr[4] == 4); is_identity &= (arr[5] == 5); is_identity &= (arr[6] == 6); is_identity &= (arr[7] == 7); is_identity &= (arr[8] == 8); is_identity &= (arr[9] == 9); return is_identity; } int main() { int arr[10]; f1(arr); } <|start_filename|>regression/contracts/assigns_enforce_statics/main.c<|end_filename|> static int x = 0; void foo() __CPROVER_assigns(x) { int *y = &x; static int x = 0; // should pass (assigns local x) x++; // should fail (assigns global x) (*y)++; } int main() { foo(); } <|start_filename|>regression/contracts/no_redudant_checks/main.c<|end_filename|> #include <stdlib.h> const int N = 100; int main() { int *buf = malloc(N * sizeof(*buf)); char *lb = (((char *)buf) - __CPROVER_POINTER_OFFSET(buf)); char *ub = (((char *)buf) - __CPROVER_POINTER_OFFSET(buf)) + __CPROVER_OBJECT_SIZE(buf) - 1; } <|start_filename|>regression/cbmc/Quantifiers-type2/main.c<|end_filename|> int main() { int b[2]; int c[2]; // clang-format off // clang-format would rewrite the "==>" as "== >" __CPROVER_assume( __CPROVER_forall { char i; (i>=0 && i<2) ==> b[i]>=10 && b[i]<=10 } ); __CPROVER_assume( __CPROVER_forall { unsigned i; (i>=0 && i<2) ==> c[i]>=10 && c[i]<=10 } ); // clang-format on assert(b[0] == 10 && b[1] == 10); assert(c[0] == 10 && c[1] == 10); return 0; } <|start_filename|>src/goto-instrument/function_assigns.cpp<|end_filename|> /*******************************************************************\ Module: Compute objects assigned to in a function Author: <NAME>, <EMAIL> \*******************************************************************/ /// \file /// Compute objects assigned to in a function. #include "function_assigns.h" #include <util/std_expr.h> #include <analyses/local_may_alias.h> #include "loop_utils.h" void function_assignst::get_assigns( const local_may_aliast &local_may_alias, const goto_programt::const_targett i_it, assignst &assigns) { const goto_programt::instructiont &instruction = *i_it; if(instruction.is_assign()) { get_assigns_lhs(local_may_alias, i_it, instruction.assign_lhs(), assigns); } else if(instruction.is_function_call()) { const exprt &lhs = instruction.call_lhs(); // return value assignment if(lhs.is_not_nil()) get_assigns_lhs(local_may_alias, i_it, lhs, assigns); get_assigns_function(instruction.call_function(), assigns); } } void function_assignst::get_assigns_function( const exprt &function, assignst &assigns) { if(function.id() == ID_symbol) { const irep_idt &identifier = to_symbol_expr(function).get_identifier(); function_mapt::const_iterator fm_it = function_map.find(identifier); if(fm_it != function_map.end()) { // already done assigns.insert(fm_it->second.begin(), fm_it->second.end()); return; } goto_functionst::function_mapt::const_iterator f_it = goto_functions.function_map.find(identifier); if(f_it == goto_functions.function_map.end()) return; local_may_aliast local_may_alias(f_it->second); const goto_programt &goto_program = f_it->second.body; forall_goto_program_instructions(i_it, goto_program) get_assigns(local_may_alias, i_it, assigns); } else if(function.id() == ID_if) { get_assigns_function(to_if_expr(function).true_case(), assigns); get_assigns_function(to_if_expr(function).false_case(), assigns); } } <|start_filename|>regression/ansi-c/duplicate_label1/main.c<|end_filename|> int main() { int x; label: x = 1; goto label; label: x = 2; } <|start_filename|>regression/cbmc-primitives/forall_6231_3/test.c<|end_filename|> #include <assert.h> #include <stdlib.h> // This is essentially the same file as in test `forall_6231_1`, with the difference // being that the forall statement contains a bigger bound, so that we are to have // more concrete instantiations of the bound variable. // clang-format off int main() { char *a = malloc(10); assert(*a == *a); // BUG: In https://github.com/diffblue/cbmc/issues/6231, it was reported that // no checks would be performed on the derefence inside the quantified statement, // even when explicitly requested via for instance `--pointer-check`, because // we would simply skip over these quantified statements in goto-check. assert( __CPROVER_forall { int i ; (0 <= i && i < 10) ==> *(a+i) == *(a+i) } ); } // clang-format on <|start_filename|>src/goto-instrument/dump_c.h<|end_filename|> /*******************************************************************\ Module: Dump C from Goto Program Author: <NAME>, <EMAIL> \*******************************************************************/ /// \file /// Dump C from Goto Program #ifndef CPROVER_GOTO_INSTRUMENT_DUMP_C_H #define CPROVER_GOTO_INSTRUMENT_DUMP_C_H #include <iosfwd> #include <string> class goto_functionst; class namespacet; void dump_c( const goto_functionst &src, const bool use_system_headers, const bool use_all_headers, const bool include_harness, const namespacet &ns, std::ostream &out); void dump_c_type_header( const goto_functionst &src, const bool use_system_headers, const bool use_all_headers, const bool include_harness, const namespacet &ns, const std::string module, std::ostream &out); void dump_cpp( const goto_functionst &src, const bool use_system_headers, const bool use_all_headers, const bool include_harness, const namespacet &ns, std::ostream &out); #define OPT_DUMP_C \ "(dump-c)(dump-cpp)" \ "(dump-c-type-header):" \ "(no-system-headers)(use-all-headers)(harness)" // clang-format off #define HELP_DUMP_C \ " --dump-c generate C source\n" \ " --dump-c-type-header m generate a C header for types local in m\n" \ " --dump-cpp generate C++ source\n" \ " --no-system-headers generate C source expanding libc includes\n"\ " --use-all-headers generate C source with all includes\n" \ " --harness include input generator in output\n" // clang-format on #endif // CPROVER_GOTO_INSTRUMENT_DUMP_C_H <|start_filename|>regression/cbmc-primitives/forall_6231_3/test_malloc_less_than_bound.c<|end_filename|> #include <assert.h> #include <stdlib.h> // Similar to our test in `test.c` of this folder, with the difference being // that the malloc size is less than the bound checked, which implies that the // check for the pointer being outside the object bounds is expected to fail. // clang-format off int main() { char *a = malloc(4); assert(*a == *a); // BUG: no errors even with `--pointer-check` enabled -- now fixed. assert( __CPROVER_forall { int i ; (0 <= i && i < 10) ==> *(a+i) == *(a+i) } ); } // clang-format on <|start_filename|>regression/contracts/quantifiers-forall-ensures-enforce/main.c<|end_filename|> #include <stdlib.h> #define MAX_LEN 10 // clang-format off int f1(int *arr, int len) __CPROVER_assigns(__CPROVER_POINTER_OBJECT(arr)) __CPROVER_ensures(__CPROVER_forall { int i; // test enforcement with symbolic bound (0 <= i && i < len) ==> arr[i] == 0 }) // clang-format on { if(0 < len) arr[0] = 0; if(1 < len) arr[1] = 0; if(2 < len) arr[2] = 0; if(3 < len) arr[3] = 0; if(4 < len) arr[4] = 0; if(5 < len) arr[5] = 0; if(6 < len) arr[6] = 0; if(7 < len) arr[7] = 0; if(8 < len) arr[8] = 0; if(9 < len) arr[9] = 0; return 0; } int main() { int len; __CPROVER_assume(0 < len && len <= MAX_LEN); int *arr = malloc(len * sizeof(int)); f1(arr, len); } <|start_filename|>src/goto-checker/symex_bmc.cpp<|end_filename|> /*******************************************************************\ Module: Bounded Model Checking for ANSI-C Author: <NAME>, <EMAIL> \*******************************************************************/ /// \file /// Bounded Model Checking for ANSI-C #include "symex_bmc.h" #include <limits> #include <util/simplify_expr.h> #include <util/source_location.h> #include <goto-instrument/unwindset.h> symex_bmct::symex_bmct( message_handlert &mh, const symbol_tablet &outer_symbol_table, symex_target_equationt &_target, const optionst &options, path_storaget &path_storage, guard_managert &guard_manager, unwindsett &unwindset) : goto_symext( mh, outer_symbol_table, _target, options, path_storage, guard_manager), record_coverage(!options.get_option("symex-coverage-report").empty()), havoc_bodyless_functions( options.get_bool_option("havoc-undefined-functions")), unwindset(unwindset), symex_coverage(ns) { } /// show progress void symex_bmct::symex_step( const get_goto_functiont &get_goto_function, statet &state) { const source_locationt &source_location = state.source.pc->source_location(); if(!source_location.is_nil() && last_source_location != source_location) { log.debug() << "BMC at " << source_location.as_string() << " (depth " << state.depth << ')' << log.eom; last_source_location = source_location; } const goto_programt::const_targett cur_pc = state.source.pc; const guardt cur_guard = state.guard; if( !state.guard.is_false() && state.source.pc->is_assume() && simplify_expr(state.source.pc->condition(), ns).is_false()) { log.statistics() << "aborting path on assume(false) at " << state.source.pc->source_location() << " thread " << state.source.thread_nr; const irep_idt &c = state.source.pc->source_location().get_comment(); if(!c.empty()) log.statistics() << ": " << c; log.statistics() << log.eom; } goto_symext::symex_step(get_goto_function, state); if( record_coverage && // avoid an invalid iterator in state.source.pc (!cur_pc->is_end_function() || state.source.function_id != goto_functionst::entry_point())) { // forward goto will effectively be covered via phi function, // which does not invoke symex_step; as symex_step is called // before merge_gotos, also state.guard will be false (we have // taken an impossible transition); thus we synthesize a // transition from the goto instruction to its target to make // sure the goto is considered covered if( cur_pc->is_goto() && cur_pc->get_target() != state.source.pc && cur_pc->condition().is_true()) symex_coverage.covered(cur_pc, cur_pc->get_target()); else if(!state.guard.is_false()) symex_coverage.covered(cur_pc, state.source.pc); } } void symex_bmct::merge_goto( const symex_targett::sourcet &prev_source, goto_statet &&goto_state, statet &state) { const goto_programt::const_targett prev_pc = prev_source.pc; const guardt prev_guard = goto_state.guard; goto_symext::merge_goto(prev_source, std::move(goto_state), state); PRECONDITION(prev_pc->is_goto()); if( record_coverage && // could the branch possibly be taken? !prev_guard.is_false() && !state.guard.is_false() && // branches only, no single-successor goto !prev_pc->condition().is_true()) symex_coverage.covered(prev_pc, state.source.pc); } bool symex_bmct::should_stop_unwind( const symex_targett::sourcet &source, const call_stackt &context, unsigned unwind) { const irep_idt id = goto_programt::loop_id(source.function_id, *source.pc); tvt abort_unwind_decision; unsigned this_loop_limit = std::numeric_limits<unsigned>::max(); for(auto handler : loop_unwind_handlers) { abort_unwind_decision = handler(context, source.pc->loop_number, unwind, this_loop_limit); if(abort_unwind_decision.is_known()) break; } // If no handler gave an opinion, use standard command-line --unwindset // / --unwind options to decide: if(abort_unwind_decision.is_unknown()) { auto limit = unwindset.get_limit(id, source.thread_nr); if(!limit.has_value()) abort_unwind_decision = tvt(false); else abort_unwind_decision = tvt(unwind >= *limit); } INVARIANT( abort_unwind_decision.is_known(), "unwind decision should be taken by now"); bool abort = abort_unwind_decision.is_true(); log.statistics() << (abort ? "Not unwinding" : "Unwinding") << " loop " << id << " iteration " << unwind; if(this_loop_limit != std::numeric_limits<unsigned>::max()) log.statistics() << " (" << this_loop_limit << " max)"; log.statistics() << " " << source.pc->source_location() << " thread " << source.thread_nr << log.eom; return abort; } bool symex_bmct::get_unwind_recursion( const irep_idt &id, unsigned thread_nr, unsigned unwind) { tvt abort_unwind_decision; unsigned this_loop_limit = std::numeric_limits<unsigned>::max(); for(auto handler : recursion_unwind_handlers) { abort_unwind_decision = handler(id, unwind, this_loop_limit); if(abort_unwind_decision.is_known()) break; } // If no handler gave an opinion, use standard command-line --unwindset // / --unwind options to decide: if(abort_unwind_decision.is_unknown()) { auto limit = unwindset.get_limit(id, thread_nr); if(!limit.has_value()) abort_unwind_decision = tvt(false); else abort_unwind_decision = tvt(unwind > *limit); } INVARIANT( abort_unwind_decision.is_known(), "unwind decision should be taken by now"); bool abort = abort_unwind_decision.is_true(); if(unwind > 0 || abort) { const symbolt &symbol = ns.lookup(id); log.statistics() << (abort ? "Not unwinding" : "Unwinding") << " recursion " << symbol.display_name() << " iteration " << unwind; if(this_loop_limit != std::numeric_limits<unsigned>::max()) log.statistics() << " (" << this_loop_limit << " max)"; log.statistics() << log.eom; } return abort; } void symex_bmct::no_body(const irep_idt &identifier) { if(body_warnings.insert(identifier).second) { log.warning() << "**** WARNING: no body for function " << identifier; if(havoc_bodyless_functions) { log.warning() << "; assigning non-deterministic values to any pointer arguments"; } log.warning() << log.eom; } } <|start_filename|>regression/cbmc-primitives/alternating_quantifiers_6231/forall_in_exists.c<|end_filename|> #include <stdlib.h> // clang-format off int main(int argc, char **argv) { int *i = malloc(sizeof(int)); *i = 1; __CPROVER_assert( __CPROVER_exists { int z; (0 < z && z < 2) && __CPROVER_forall { int o; (10 < o && o < 20) ==> o > z && z == * i }}, "there exists a z between 0 and 2 so that for all o between 10 and 20, o > z and z = 1"); } // clang-format on <|start_filename|>regression/cbmc-primitives/exists_assume_6231/test2.c<|end_filename|> #include <stdlib.h> // clang-format off int main(int argc, char **argv) { int *i = malloc(sizeof(int)); *i = 1; // The exists inside the assume will evaluate to true, // and as such, the assertion below will fail as expected. __CPROVER_assume( __CPROVER_exists{int z; (z > 1 && z < 10) && z > *i} ); __CPROVER_assert(0, "this should come out as failure"); } // clang-format on <|start_filename|>regression/cbmc-primitives/forall_6231_2/test.c<|end_filename|> #include <assert.h> #include <stdlib.h> // clang-format off int main() { char *a = malloc(128); // BUG: In https://github.com/diffblue/cbmc/issues/6231, it was reported that // no checks would be performed on the derefence inside the quantified statement, // even when explicitly requested via for instance `--pointer-check`, because // we would simply skip over these quantified statements in goto-check. assert( __CPROVER_forall { int i ; (0 <= i && i < 1) ==> *(a+i) == *(a+i) } ); assert( __CPROVER_forall { int j; !(0 <= j && j < 1) || (j == 0 && *(a+j) == *(a+j)) }); } // clang-format on <|start_filename|>regression/cbmc/unwindset1/main.c<|end_filename|> int main() { int x; for_loop: for(int i = 0; i < x; ++i) --x; for(int j = 0; j < 5; ++j) ++x; __CPROVER_assert(0, "can be reached"); } <|start_filename|>regression/contracts/assigns_enforce_detect_local_statics/main.c<|end_filename|> #include <assert.h> #include <stdlib.h> static int x; static int xx; void foo() { int *y = &x; int *yy = &xx; static int x; // must pass (modifies local static) x++; // must pass (modifies assignable global static ) (*y)++; // must fail (modifies non-assignable global static) (*yy)++; } void bar() __CPROVER_assigns(x) { foo(); } int main() { bar(); } <|start_filename|>src/ansi-c/gcc_builtin_headers_ia32.h<|end_filename|> // clang-format off // from // http://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/X86-Built_002din-Functions.html __CPROVER_Float128 __builtin_fabsq(__CPROVER_Float128); __CPROVER_Float128 __builtin_copysignq(__CPROVER_Float128, __CPROVER_Float128); void __builtin_ia32_pause(); __CPROVER_Float128 __builtin_infq(void); __CPROVER_Float128 __builtin_huge_valq(void); __gcc_v8qi __builtin_ia32_paddb(__gcc_v8qi, __gcc_v8qi); __gcc_v4hi __builtin_ia32_paddw(__gcc_v4hi, __gcc_v4hi); __gcc_v2si __builtin_ia32_paddd(__gcc_v2si, __gcc_v2si); __gcc_v8qi __builtin_ia32_psubb(__gcc_v8qi, __gcc_v8qi); __gcc_v4hi __builtin_ia32_psubw(__gcc_v4hi, __gcc_v4hi); __gcc_v2si __builtin_ia32_psubd(__gcc_v2si, __gcc_v2si); __gcc_v8qi __builtin_ia32_paddsb(__gcc_v8qi, __gcc_v8qi); __gcc_v4hi __builtin_ia32_paddsw(__gcc_v4hi, __gcc_v4hi); __gcc_v8qi __builtin_ia32_psubsb(__gcc_v8qi, __gcc_v8qi); __gcc_v4hi __builtin_ia32_psubsw(__gcc_v4hi, __gcc_v4hi); __gcc_v8qi __builtin_ia32_paddusb(__gcc_v8qi, __gcc_v8qi); __gcc_v4hi __builtin_ia32_paddusw(__gcc_v4hi, __gcc_v4hi); __gcc_v8qi __builtin_ia32_psubusb(__gcc_v8qi, __gcc_v8qi); __gcc_v4hi __builtin_ia32_psubusw(__gcc_v4hi, __gcc_v4hi); __gcc_v4hi __builtin_ia32_pmullw(__gcc_v4hi, __gcc_v4hi); __gcc_v4hi __builtin_ia32_pmulhw(__gcc_v4hi, __gcc_v4hi); __gcc_v1di __builtin_ia32_pand(__gcc_v1di, __gcc_v1di); __gcc_v1di __builtin_ia32_pandn(__gcc_v1di, __gcc_v1di); __gcc_v1di __builtin_ia32_por(__gcc_v1di, __gcc_v1di); __gcc_v1di __builtin_ia32_pxor(__gcc_v1di, __gcc_v1di); __gcc_v8qi __builtin_ia32_pcmpeqb(__gcc_v8qi, __gcc_v8qi); __gcc_v4hi __builtin_ia32_pcmpeqw(__gcc_v4hi, __gcc_v4hi); __gcc_v2si __builtin_ia32_pcmpeqd(__gcc_v2si, __gcc_v2si); __gcc_v8qi __builtin_ia32_pcmpgtb(__gcc_v8qi, __gcc_v8qi); __gcc_v4hi __builtin_ia32_pcmpgtw(__gcc_v4hi, __gcc_v4hi); __gcc_v2si __builtin_ia32_pcmpgtd(__gcc_v2si, __gcc_v2si); __gcc_v8qi __builtin_ia32_punpckhbw(__gcc_v8qi, __gcc_v8qi); __gcc_v4hi __builtin_ia32_punpckhwd(__gcc_v4hi, __gcc_v4hi); __gcc_v2si __builtin_ia32_punpckhdq(__gcc_v2si, __gcc_v2si); __gcc_v8qi __builtin_ia32_punpcklbw(__gcc_v8qi, __gcc_v8qi); __gcc_v4hi __builtin_ia32_punpcklwd(__gcc_v4hi, __gcc_v4hi); __gcc_v2si __builtin_ia32_punpckldq(__gcc_v2si, __gcc_v2si); __gcc_v8qi __builtin_ia32_packsswb(__gcc_v4hi, __gcc_v4hi); __gcc_v4hi __builtin_ia32_packssdw(__gcc_v2si, __gcc_v2si); __gcc_v8qi __builtin_ia32_packuswb(__gcc_v4hi, __gcc_v4hi); __gcc_v4hi __builtin_ia32_psllw(__gcc_v4hi, __gcc_v4hi); __gcc_v2si __builtin_ia32_pslld(__gcc_v2si, __gcc_v2si); __gcc_v1di __builtin_ia32_psllq(__gcc_v1di, __gcc_v1di); __gcc_v4hi __builtin_ia32_psrlw(__gcc_v4hi, __gcc_v4hi); __gcc_v2si __builtin_ia32_psrld(__gcc_v2si, __gcc_v2si); __gcc_v1di __builtin_ia32_psrlq(__gcc_v1di, __gcc_v1di); __gcc_v4hi __builtin_ia32_psraw(__gcc_v4hi, __gcc_v4hi); __gcc_v2si __builtin_ia32_psrad(__gcc_v2si, __gcc_v2si); __gcc_v4hi __builtin_ia32_psllwi(__gcc_v4hi, int); __gcc_v2si __builtin_ia32_pslldi(__gcc_v2si, int); __gcc_v1di __builtin_ia32_psllqi(__gcc_v1di, int); __gcc_v4hi __builtin_ia32_psrlwi(__gcc_v4hi, int); __gcc_v2si __builtin_ia32_psrldi(__gcc_v2si, int); __gcc_v1di __builtin_ia32_psrlqi(__gcc_v1di, int); __gcc_v4hi __builtin_ia32_psrawi(__gcc_v4hi, int); __gcc_v2si __builtin_ia32_psradi(__gcc_v2si, int); __gcc_v4hi __builtin_ia32_pmulhuw(__gcc_v4hi, __gcc_v4hi); __gcc_v8qi __builtin_ia32_pavgb(__gcc_v8qi, __gcc_v8qi); __gcc_v4hi __builtin_ia32_pavgw(__gcc_v4hi, __gcc_v4hi); __gcc_v1di __builtin_ia32_psadbw(__gcc_v8qi, __gcc_v8qi); __gcc_v8qi __builtin_ia32_pmaxub(__gcc_v8qi, __gcc_v8qi); __gcc_v4hi __builtin_ia32_pmaxsw(__gcc_v4hi, __gcc_v4hi); __gcc_v8qi __builtin_ia32_pminub(__gcc_v8qi, __gcc_v8qi); __gcc_v4hi __builtin_ia32_pminsw(__gcc_v4hi, __gcc_v4hi); int __builtin_ia32_pextrw(__gcc_v4hi, int); __gcc_v4hi __builtin_ia32_pinsrw(__gcc_v4hi, int, int); int __builtin_ia32_pmovmskb(__gcc_v8qi); void __builtin_ia32_maskmovq(__gcc_v8qi, __gcc_v8qi, char*); // clang uses the following: // void __builtin_ia32_movntq(__gcc_v1di*, __gcc_v1di); // // GCC uses this: // void __builtin_ia32_movntq(__gcc_di*, __gcc_di); // // So, we use: void __builtin_ia32_movntq(void*, ...); void __builtin_ia32_sfence(); int __builtin_ia32_comieq(__gcc_v4sf, __gcc_v4sf); int __builtin_ia32_comineq(__gcc_v4sf, __gcc_v4sf); int __builtin_ia32_comilt(__gcc_v4sf, __gcc_v4sf); int __builtin_ia32_comile(__gcc_v4sf, __gcc_v4sf); int __builtin_ia32_comigt(__gcc_v4sf, __gcc_v4sf); int __builtin_ia32_comige(__gcc_v4sf, __gcc_v4sf); int __builtin_ia32_ucomieq(__gcc_v4sf, __gcc_v4sf); int __builtin_ia32_ucomineq(__gcc_v4sf, __gcc_v4sf); int __builtin_ia32_ucomilt(__gcc_v4sf, __gcc_v4sf); int __builtin_ia32_ucomile(__gcc_v4sf, __gcc_v4sf); int __builtin_ia32_ucomigt(__gcc_v4sf, __gcc_v4sf); int __builtin_ia32_ucomige(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_addps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_subps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_mulps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_divps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_addss(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_subss(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_mulss(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_divss(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_cmpeqps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_cmpltps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_cmpleps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_cmpgtps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_cmpgeps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_cmpunordps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_cmpneqps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_cmpnltps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_cmpnleps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_cmpngtps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_cmpngeps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_cmpordps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_cmpeqss(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_cmpltss(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_cmpless(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_cmpunordss(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_cmpneqss(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_cmpnlts(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_cmpnless(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_cmpordss(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_maxps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_maxss(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_minps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_minss(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_andps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_andnps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_orps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_xorps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_movss(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_movhlps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_movlhps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_unpckhps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_unpcklps(__gcc_v4sf, __gcc_v4sf); __gcc_v4sf __builtin_ia32_cvtpi2ps(__gcc_v4sf, __gcc_v2si); __gcc_v4sf __builtin_ia32_cvtsi2ss(__gcc_v4sf, int); __gcc_v2si __builtin_ia32_cvtps2pi(__gcc_v4sf); int __builtin_ia32_cvtss2si(__gcc_v4sf); __gcc_v2si __builtin_ia32_cvttps2pi(__gcc_v4sf); int __builtin_ia32_cvttss2si(__gcc_v4sf); __gcc_v4sf __builtin_ia32_rcpps(__gcc_v4sf); __gcc_v4sf __builtin_ia32_rsqrtps(__gcc_v4sf); __gcc_v4sf __builtin_ia32_sqrtps(__gcc_v4sf); __gcc_v4sf __builtin_ia32_rcpss(__gcc_v4sf); __gcc_v4sf __builtin_ia32_rsqrtss(__gcc_v4sf); __gcc_v4sf __builtin_ia32_sqrtss(__gcc_v4sf); __gcc_v4sf __builtin_ia32_shufps(__gcc_v4sf, __gcc_v4sf, int); void __builtin_ia32_movntps(float*, __gcc_v4sf); int __builtin_ia32_movmskps(__gcc_v4sf); __gcc_v4sf __builtin_ia32_loadaps(float*); void __builtin_ia32_storeaps(float*, __gcc_v4sf); __gcc_v4sf __builtin_ia32_loadups(const float*); void __builtin_ia32_storeups(float*, __gcc_v4sf); __gcc_v4sf __builtin_ia32_loadsss(float*); void __builtin_ia32_storess(float*, __gcc_v4sf); // clang uses these: // __gcc_v4sf __builtin_ia32_loadhps(__gcc_v4sf, const __gcc_v2si*); // __gcc_v4sf __builtin_ia32_loadlps(__gcc_v4sf, const __gcc_v2si*); // void __builtin_ia32_storehps(__gcc_v2si*, __gcc_v4sf); // void __builtin_ia32_storelps(__gcc_v2si*, __gcc_v4sf); // // but GCC uses: // __gcc_v4sf __builtin_ia32_loadhps(__gcc_v4sf, const __gcc_v2sf*); // __gcc_v4sf __builtin_ia32_loadlps(__gcc_v4sf, const __gcc_v2sf*); // void __builtin_ia32_storehps(__gcc_v2sf*, __gcc_v4sf); // void __builtin_ia32_storelps(__gcc_v2sf*, __gcc_v4sf); // // So we use: __gcc_v4sf __builtin_ia32_loadhps(__gcc_v4sf, const void*); __gcc_v4sf __builtin_ia32_loadlps(__gcc_v4sf, const void*); void __builtin_ia32_storehps(void*, __gcc_v4sf); void __builtin_ia32_storelps(void*, __gcc_v4sf); __gcc_v4si __builtin_ia32_loadlv4si(const __gcc_v2si*); void __builtin_ia32_storelv4si(__gcc_v2si*, __gcc_v4si); __gcc_v4si __builtin_ia32_movqv4si(__gcc_v4si); int __builtin_ia32_comisdeq(__gcc_v2df, __gcc_v2df); int __builtin_ia32_comisdlt(__gcc_v2df, __gcc_v2df); int __builtin_ia32_comisdle(__gcc_v2df, __gcc_v2df); int __builtin_ia32_comisdgt(__gcc_v2df, __gcc_v2df); int __builtin_ia32_comisdge(__gcc_v2df, __gcc_v2df); int __builtin_ia32_comisdneq(__gcc_v2df, __gcc_v2df); int __builtin_ia32_ucomisdeq(__gcc_v2df, __gcc_v2df); int __builtin_ia32_ucomisdlt(__gcc_v2df, __gcc_v2df); int __builtin_ia32_ucomisdle(__gcc_v2df, __gcc_v2df); int __builtin_ia32_ucomisdgt(__gcc_v2df, __gcc_v2df); int __builtin_ia32_ucomisdge(__gcc_v2df, __gcc_v2df); int __builtin_ia32_ucomisdneq(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_cmpeqpd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_cmpltpd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_cmplepd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_cmpgtpd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_cmpgepd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_cmpunordpd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_cmpneqpd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_cmpnltpd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_cmpnlepd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_cmpngtpd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_cmpngepd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_cmpordpd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_cmpeqsd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_cmpltsd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_cmplesd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_cmpunordsd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_cmpneqsd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_cmpnltsd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_cmpnlesd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_cmpordsd(__gcc_v2df, __gcc_v2df); __gcc_v1di __builtin_ia32_paddq(__gcc_v1di, __gcc_v1di); __gcc_v1di __builtin_ia32_psubq(__gcc_v1di, __gcc_v1di); __gcc_v2df __builtin_ia32_addpd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_subpd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_mulpd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_divpd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_addsd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_subsd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_mulsd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_divsd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_minpd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_maxpd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_minsd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_maxsd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_andpd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_andnpd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_orpd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_xorpd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_movsd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_unpckhpd(__gcc_v2df, __gcc_v2df); __gcc_v2df __builtin_ia32_unpcklpd(__gcc_v2df, __gcc_v2df); __gcc_v16qi __builtin_ia32_paddb128(__gcc_v16qi, __gcc_v16qi); __gcc_v8hi __builtin_ia32_paddw128(__gcc_v8hi, __gcc_v8hi); __gcc_v4si __builtin_ia32_paddd128(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_paddq128(__gcc_v2di, __gcc_v2di); __gcc_v16qi __builtin_ia32_psubb128(__gcc_v16qi, __gcc_v16qi); __gcc_v8hi __builtin_ia32_psubw128(__gcc_v8hi, __gcc_v8hi); __gcc_v4si __builtin_ia32_psubd128(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_psubq128(__gcc_v2di, __gcc_v2di); __gcc_v8hi __builtin_ia32_pmullw128(__gcc_v8hi, __gcc_v8hi); __gcc_v8hi __builtin_ia32_pmulhw128(__gcc_v8hi, __gcc_v8hi); __gcc_v2di __builtin_ia32_pand128(__gcc_v2di, __gcc_v2di); __gcc_v2di __builtin_ia32_pandn128(__gcc_v2di, __gcc_v2di); __gcc_v2di __builtin_ia32_por128(__gcc_v2di, __gcc_v2di); __gcc_v2di __builtin_ia32_pxor128(__gcc_v2di, __gcc_v2di); __gcc_v16qi __builtin_ia32_pavgb128(__gcc_v16qi, __gcc_v16qi); __gcc_v8hi __builtin_ia32_pavgw128(__gcc_v8hi, __gcc_v8hi); __gcc_v16qi __builtin_ia32_pcmpeqb128(__gcc_v16qi, __gcc_v16qi); __gcc_v8hi __builtin_ia32_pcmpeqw128(__gcc_v8hi, __gcc_v8hi); __gcc_v4si __builtin_ia32_pcmpeqd128(__gcc_v4si, __gcc_v4si); __gcc_v16qi __builtin_ia32_pcmpgtb128(__gcc_v16qi, __gcc_v16qi); __gcc_v8hi __builtin_ia32_pcmpgtw128(__gcc_v8hi, __gcc_v8hi); __gcc_v4si __builtin_ia32_pcmpgtd128(__gcc_v4si, __gcc_v4si); __gcc_v16qi __builtin_ia32_pmaxub128(__gcc_v16qi, __gcc_v16qi); __gcc_v8hi __builtin_ia32_pmaxsw128(__gcc_v8hi, __gcc_v8hi); __gcc_v16qi __builtin_ia32_pminub128(__gcc_v16qi, __gcc_v16qi); __gcc_v8hi __builtin_ia32_pminsw128(__gcc_v8hi, __gcc_v8hi); __gcc_v16qi __builtin_ia32_punpckhbw128(__gcc_v16qi, __gcc_v16qi); __gcc_v8hi __builtin_ia32_punpckhwd128(__gcc_v8hi, __gcc_v8hi); __gcc_v4si __builtin_ia32_punpckhdq128(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_punpckhqdq128(__gcc_v2di, __gcc_v2di); __gcc_v16qi __builtin_ia32_punpcklbw128(__gcc_v16qi, __gcc_v16qi); __gcc_v8hi __builtin_ia32_punpcklwd128(__gcc_v8hi, __gcc_v8hi); __gcc_v4si __builtin_ia32_punpckldq128(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_punpcklqdq128(__gcc_v2di, __gcc_v2di); __gcc_v16qi __builtin_ia32_packsswb128(__gcc_v8hi, __gcc_v8hi); __gcc_v8hi __builtin_ia32_packssdw128(__gcc_v4si, __gcc_v4si); __gcc_v16qi __builtin_ia32_packuswb128(__gcc_v8hi, __gcc_v8hi); __gcc_v8hi __builtin_ia32_pmulhuw128(__gcc_v8hi, __gcc_v8hi); void __builtin_ia32_maskmovdqu(__gcc_v16qi, __gcc_v16qi, char*); __gcc_v2df __builtin_ia32_loadupd(const double*); void __builtin_ia32_storeupd(double*, __gcc_v2df); __gcc_v2df __builtin_ia32_loadhpd(__gcc_v2df, const double*); __gcc_v2df __builtin_ia32_loadlpd(__gcc_v2df, const double*); int __builtin_ia32_movmskpd(__gcc_v2df); int __builtin_ia32_pmovmskb128(__gcc_v16qi); void __builtin_ia32_movnti(int*, int); void __builtin_ia32_movnti64(long long*, long long); void __builtin_ia32_movntpd(double*, __gcc_v2df); void __builtin_ia32_movntdq(__gcc_v2di*, __gcc_v2di); __gcc_v4si __builtin_ia32_pshufd(__gcc_v4si, int); __gcc_v8hi __builtin_ia32_pshuflw(__gcc_v8hi, int); __gcc_v8hi __builtin_ia32_pshufhw(__gcc_v8hi, int); __gcc_v2di __builtin_ia32_psadbw128(__gcc_v16qi, __gcc_v16qi); __gcc_v2df __builtin_ia32_sqrtpd(__gcc_v2df); __gcc_v2df __builtin_ia32_sqrtsd(__gcc_v2df); __gcc_v2df __builtin_ia32_shufpd(__gcc_v2df, __gcc_v2df, int); __gcc_v2df __builtin_ia32_cvtdq2pd(__gcc_v4si); __gcc_v4sf __builtin_ia32_cvtdq2ps(__gcc_v4si); __gcc_v4si __builtin_ia32_cvtpd2dq(__gcc_v2df); __gcc_v2si __builtin_ia32_cvtpd2pi(__gcc_v2df); __gcc_v4sf __builtin_ia32_cvtpd2ps(__gcc_v2df); __gcc_v4si __builtin_ia32_cvttpd2dq(__gcc_v2df); __gcc_v2si __builtin_ia32_cvttpd2pi(__gcc_v2df); __gcc_v2df __builtin_ia32_cvtpi2pd(__gcc_v2si); int __builtin_ia32_cvtsd2si(__gcc_v2df); int __builtin_ia32_cvttsd2si(__gcc_v2df); long long __builtin_ia32_cvtsd2si64(__gcc_v2df); long long __builtin_ia32_cvttsd2si64(__gcc_v2df); __gcc_v4si __builtin_ia32_cvtps2dq(__gcc_v4sf); __gcc_v2df __builtin_ia32_cvtps2pd(__gcc_v4sf); __gcc_v4si __builtin_ia32_cvttps2dq(__gcc_v4sf); __gcc_v2df __builtin_ia32_cvtsi2sd(__gcc_v2df, int); __gcc_v2df __builtin_ia32_cvtsi642sd(__gcc_v2df, long long); __gcc_v4sf __builtin_ia32_cvtsd2ss(__gcc_v4sf, __gcc_v2df); __gcc_v2df __builtin_ia32_cvtss2sd(__gcc_v2df, __gcc_v4sf); void __builtin_ia32_clflush(const void*); void __builtin_ia32_lfence(); void __builtin_ia32_mfence(void); __gcc_v16qi __builtin_ia32_loaddqu(const char*); void __builtin_ia32_storedqu(char*, __gcc_v16qi); __gcc_v1di __builtin_ia32_pmuludq(__gcc_v2si, __gcc_v2si); __gcc_v2di __builtin_ia32_pmuludq128(__gcc_v4si, __gcc_v4si); __gcc_v8hi __builtin_ia32_psllw128(__gcc_v8hi, __gcc_v8hi); __gcc_v4si __builtin_ia32_pslld128(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_psllq128(__gcc_v2di, __gcc_v2di); __gcc_v8hi __builtin_ia32_psrlw128(__gcc_v8hi, __gcc_v8hi); __gcc_v4si __builtin_ia32_psrld128(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_psrlq128(__gcc_v2di, __gcc_v2di); __gcc_v8hi __builtin_ia32_psraw128(__gcc_v8hi, __gcc_v8hi); __gcc_v4si __builtin_ia32_psrad128(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_pslldqi128(__gcc_v2di, int); __gcc_v8hi __builtin_ia32_psllwi128(__gcc_v8hi, int); __gcc_v4si __builtin_ia32_pslldi128(__gcc_v4si, int); __gcc_v2di __builtin_ia32_psllqi128(__gcc_v2di, int); __gcc_v2di __builtin_ia32_psrldqi128(__gcc_v2di, int); __gcc_v8hi __builtin_ia32_psrlwi128(__gcc_v8hi, int); __gcc_v4si __builtin_ia32_psrldi128(__gcc_v4si, int); __gcc_v2di __builtin_ia32_psrlqi128(__gcc_v2di, int); __gcc_v8hi __builtin_ia32_psrawi128(__gcc_v8hi, int); __gcc_v4si __builtin_ia32_psradi128(__gcc_v4si, int); __gcc_v4si __builtin_ia32_pmaddwd128(__gcc_v8hi, __gcc_v8hi); __gcc_v2di __builtin_ia32_movq128(__gcc_v2di); __gcc_v2df __builtin_ia32_addsubpd(__gcc_v2df, __gcc_v2df); __gcc_v4sf __builtin_ia32_addsubps(__gcc_v4sf, __gcc_v4sf); __gcc_v2df __builtin_ia32_haddpd(__gcc_v2df, __gcc_v2df); __gcc_v4sf __builtin_ia32_haddps(__gcc_v4sf, __gcc_v4sf); __gcc_v2df __builtin_ia32_hsubpd(__gcc_v2df, __gcc_v2df); __gcc_v4sf __builtin_ia32_hsubps(__gcc_v4sf, __gcc_v4sf); __gcc_v16qi __builtin_ia32_lddqu(const char*); void __builtin_ia32_monitor(void*, unsigned int, unsigned int); __gcc_v2df __builtin_ia32_movddup(__gcc_v2df); __gcc_v4sf __builtin_ia32_movshdup(__gcc_v4sf); __gcc_v4sf __builtin_ia32_movsldup(__gcc_v4sf); void __builtin_ia32_mwait(unsigned int, unsigned int); __gcc_v2df __builtin_ia32_loadddup(double const*); __gcc_v2si __builtin_ia32_phaddd(__gcc_v2si, __gcc_v2si); __gcc_v4hi __builtin_ia32_phaddw(__gcc_v4hi, __gcc_v4hi); __gcc_v4hi __builtin_ia32_phaddsw(__gcc_v4hi, __gcc_v4hi); __gcc_v2si __builtin_ia32_phsubd(__gcc_v2si, __gcc_v2si); __gcc_v4hi __builtin_ia32_phsubw(__gcc_v4hi, __gcc_v4hi); __gcc_v4hi __builtin_ia32_phsubsw(__gcc_v4hi, __gcc_v4hi); __gcc_v4hi __builtin_ia32_pmaddubsw(__gcc_v8qi, __gcc_v8qi); __gcc_v4hi __builtin_ia32_pmulhrsw(__gcc_v4hi, __gcc_v4hi); __gcc_v8qi __builtin_ia32_pshufb(__gcc_v8qi, __gcc_v8qi); __gcc_v8qi __builtin_ia32_psignb(__gcc_v8qi, __gcc_v8qi); __gcc_v2si __builtin_ia32_psignd(__gcc_v2si, __gcc_v2si); __gcc_v4hi __builtin_ia32_psignw(__gcc_v4hi, __gcc_v4hi); __gcc_v1di __builtin_ia32_palignr(__gcc_v1di, __gcc_v1di, int); __gcc_v8qi __builtin_ia32_pabsb(__gcc_v8qi); __gcc_v2si __builtin_ia32_pabsd(__gcc_v2si); __gcc_v4hi __builtin_ia32_pabsw(__gcc_v4hi); __gcc_v4si __builtin_ia32_phaddd128(__gcc_v4si, __gcc_v4si); __gcc_v8hi __builtin_ia32_phaddw128(__gcc_v8hi, __gcc_v8hi); __gcc_v8hi __builtin_ia32_phaddsw128(__gcc_v8hi, __gcc_v8hi); __gcc_v4si __builtin_ia32_phsubd128(__gcc_v4si, __gcc_v4si); __gcc_v8hi __builtin_ia32_phsubw128(__gcc_v8hi, __gcc_v8hi); __gcc_v8hi __builtin_ia32_phsubsw128(__gcc_v8hi, __gcc_v8hi); __gcc_v8hi __builtin_ia32_pmaddubsw128(__gcc_v16qi, __gcc_v16qi); __gcc_v8hi __builtin_ia32_pmulhrsw128(__gcc_v8hi, __gcc_v8hi); __gcc_v16qi __builtin_ia32_pshufb128(__gcc_v16qi, __gcc_v16qi); __gcc_v16qi __builtin_ia32_psignb128(__gcc_v16qi, __gcc_v16qi); __gcc_v4si __builtin_ia32_psignd128(__gcc_v4si, __gcc_v4si); __gcc_v8hi __builtin_ia32_psignw128(__gcc_v8hi, __gcc_v8hi); __gcc_v2di __builtin_ia32_palignr128(__gcc_v2di, __gcc_v2di, int); __gcc_v16qi __builtin_ia32_pabsb128(__gcc_v16qi); __gcc_v4si __builtin_ia32_pabsd128(__gcc_v4si); __gcc_v8hi __builtin_ia32_pabsw128(__gcc_v8hi); __gcc_v2df __builtin_ia32_blendpd(__gcc_v2df, __gcc_v2df, int); __gcc_v4sf __builtin_ia32_blendps(__gcc_v4sf, __gcc_v4sf, int); __gcc_v2df __builtin_ia32_blendvpd(__gcc_v2df, __gcc_v2df, __gcc_v2df); __gcc_v4sf __builtin_ia32_blendvps(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf); __gcc_v2df __builtin_ia32_dppd(__gcc_v2df, __gcc_v2df, int); __gcc_v4sf __builtin_ia32_dpps(__gcc_v4sf, __gcc_v4sf, int); __gcc_v4sf __builtin_ia32_insertps128(__gcc_v4sf, __gcc_v4sf, int); __gcc_v2di __builtin_ia32_movntdqa(__gcc_v2di*); __gcc_v16qi __builtin_ia32_mpsadbw128(__gcc_v16qi, __gcc_v16qi, int); __gcc_v8hi __builtin_ia32_packusdw128(__gcc_v4si, __gcc_v4si); __gcc_v16qi __builtin_ia32_pblendvb128(__gcc_v16qi, __gcc_v16qi, __gcc_v16qi); __gcc_v8hi __builtin_ia32_pblendw128(__gcc_v8hi, __gcc_v8hi, int); __gcc_v2di __builtin_ia32_pcmpeqq(__gcc_v2di, __gcc_v2di); __gcc_v8hi __builtin_ia32_phminposuw128(__gcc_v8hi); __gcc_v16qi __builtin_ia32_pmaxsb128(__gcc_v16qi, __gcc_v16qi); __gcc_v4si __builtin_ia32_pmaxsd128(__gcc_v4si, __gcc_v4si); __gcc_v4si __builtin_ia32_pmaxud128(__gcc_v4si, __gcc_v4si); __gcc_v8hi __builtin_ia32_pmaxuw128(__gcc_v8hi, __gcc_v8hi); __gcc_v16qi __builtin_ia32_pminsb128(__gcc_v16qi, __gcc_v16qi); __gcc_v4si __builtin_ia32_pminsd128(__gcc_v4si, __gcc_v4si); __gcc_v4si __builtin_ia32_pminud128(__gcc_v4si, __gcc_v4si); __gcc_v8hi __builtin_ia32_pminuw128(__gcc_v8hi, __gcc_v8hi); __gcc_v4si __builtin_ia32_pmovsxbd128(__gcc_v16qi); __gcc_v2di __builtin_ia32_pmovsxbq128(__gcc_v16qi); __gcc_v8hi __builtin_ia32_pmovsxbw128(__gcc_v16qi); __gcc_v2di __builtin_ia32_pmovsxdq128(__gcc_v4si); __gcc_v4si __builtin_ia32_pmovsxwd128(__gcc_v8hi); __gcc_v2di __builtin_ia32_pmovsxwq128(__gcc_v8hi); __gcc_v4si __builtin_ia32_pmovzxbd128(__gcc_v16qi); __gcc_v2di __builtin_ia32_pmovzxbq128(__gcc_v16qi); __gcc_v8hi __builtin_ia32_pmovzxbw128(__gcc_v16qi); __gcc_v2di __builtin_ia32_pmovzxdq128(__gcc_v4si); __gcc_v4si __builtin_ia32_pmovzxwd128(__gcc_v8hi); __gcc_v2di __builtin_ia32_pmovzxwq128(__gcc_v8hi); __gcc_v2di __builtin_ia32_pmuldq128(__gcc_v4si, __gcc_v4si); __gcc_v4si __builtin_ia32_pmulld128(__gcc_v4si, __gcc_v4si); int __builtin_ia32_ptestc128(__gcc_v2di, __gcc_v2di); int __builtin_ia32_ptestnzc128(__gcc_v2di, __gcc_v2di); int __builtin_ia32_ptestz128(__gcc_v2di, __gcc_v2di); __gcc_v2df __builtin_ia32_roundpd(__gcc_v2df, int); __gcc_v4sf __builtin_ia32_roundps(__gcc_v4sf, int); __gcc_v2df __builtin_ia32_roundsd(__gcc_v2df, __gcc_v2df, int); __gcc_v4sf __builtin_ia32_roundss(__gcc_v4sf, __gcc_v4sf, int); int __builtin_ia32_vec_ext___gcc_v16qi(__gcc_v16qi, const int); float __builtin_ia32_vec_ext___gcc_v4sf(__gcc_v4sf, const int); int __builtin_ia32_vec_ext___gcc_v4si(__gcc_v4si, const int); __gcc_di __builtin_ia32_vec_ext___gcc_v2di(__gcc_v2di, const int); __gcc_v16qi __builtin_ia32_pcmpestrm128(__gcc_v16qi, int, __gcc_v16qi, int, const int); int __builtin_ia32_pcmpestri128(__gcc_v16qi, int, __gcc_v16qi, int, const int); int __builtin_ia32_pcmpestria128(__gcc_v16qi, int, __gcc_v16qi, int, const int); int __builtin_ia32_pcmpestric128(__gcc_v16qi, int, __gcc_v16qi, int, const int); int __builtin_ia32_pcmpestrio128(__gcc_v16qi, int, __gcc_v16qi, int, const int); int __builtin_ia32_pcmpestris128(__gcc_v16qi, int, __gcc_v16qi, int, const int); int __builtin_ia32_pcmpestriz128(__gcc_v16qi, int, __gcc_v16qi, int, const int); __gcc_v16qi __builtin_ia32_pcmpistrm128(__gcc_v16qi, __gcc_v16qi, const int); int __builtin_ia32_pcmpistri128(__gcc_v16qi, __gcc_v16qi, const int); int __builtin_ia32_pcmpistria128(__gcc_v16qi, __gcc_v16qi, const int); int __builtin_ia32_pcmpistric128(__gcc_v16qi, __gcc_v16qi, const int); int __builtin_ia32_pcmpistrio128(__gcc_v16qi, __gcc_v16qi, const int); int __builtin_ia32_pcmpistris128(__gcc_v16qi, __gcc_v16qi, const int); int __builtin_ia32_pcmpistriz128(__gcc_v16qi, __gcc_v16qi, const int); __gcc_v2di __builtin_ia32_pcmpgtq(__gcc_v2di, __gcc_v2di); unsigned __builtin_ia32_crc32qi(unsigned, unsigned char); unsigned __builtin_ia32_crc32hi(unsigned, unsigned short); unsigned __builtin_ia32_crc32si(unsigned, unsigned); unsigned long long __builtin_ia32_crc32di(unsigned long long, unsigned long long); int __builtin_popcount(unsigned int); int __builtin_popcountl(unsigned long); int __builtin_popcountll(unsigned long long); __gcc_v4df __builtin_ia32_addpd256(__gcc_v4df, __gcc_v4df); __gcc_v8sf __builtin_ia32_addps256(__gcc_v8sf, __gcc_v8sf); __gcc_v4df __builtin_ia32_addsubpd256(__gcc_v4df, __gcc_v4df); __gcc_v8sf __builtin_ia32_addsubps256(__gcc_v8sf, __gcc_v8sf); __gcc_v4df __builtin_ia32_andnpd256(__gcc_v4df, __gcc_v4df); __gcc_v8sf __builtin_ia32_andnps256(__gcc_v8sf, __gcc_v8sf); __gcc_v4df __builtin_ia32_andpd256(__gcc_v4df, __gcc_v4df); __gcc_v8sf __builtin_ia32_andps256(__gcc_v8sf, __gcc_v8sf); __gcc_v4df __builtin_ia32_blendpd256(__gcc_v4df, __gcc_v4df, int); __gcc_v8sf __builtin_ia32_blendps256(__gcc_v8sf, __gcc_v8sf, int); __gcc_v4df __builtin_ia32_blendvpd256(__gcc_v4df, __gcc_v4df, __gcc_v4df); __gcc_v8sf __builtin_ia32_blendvps256(__gcc_v8sf, __gcc_v8sf, __gcc_v8sf); __gcc_v2df __builtin_ia32_cmppd(__gcc_v2df, __gcc_v2df, int); __gcc_v4df __builtin_ia32_cmppd256(__gcc_v4df, __gcc_v4df, int); __gcc_v4sf __builtin_ia32_cmpps(__gcc_v4sf, __gcc_v4sf, int); __gcc_v8sf __builtin_ia32_cmpps256(__gcc_v8sf, __gcc_v8sf, int); __gcc_v2df __builtin_ia32_cmpsd(__gcc_v2df, __gcc_v2df, int); __gcc_v4sf __builtin_ia32_cmpss(__gcc_v4sf, __gcc_v4sf, int); __gcc_v4df __builtin_ia32_cvtdq2pd256(__gcc_v4si); __gcc_v8sf __builtin_ia32_cvtdq2ps256(__gcc_v8si); __gcc_v4si __builtin_ia32_cvtpd2dq256(__gcc_v4df); __gcc_v4sf __builtin_ia32_cvtpd2ps256(__gcc_v4df); __gcc_v8si __builtin_ia32_cvtps2dq256(__gcc_v8sf); __gcc_v4df __builtin_ia32_cvtps2pd256(__gcc_v4sf); __gcc_v4si __builtin_ia32_cvttpd2dq256(__gcc_v4df); __gcc_v8si __builtin_ia32_cvttps2dq256(__gcc_v8sf); __gcc_v4df __builtin_ia32_divpd256(__gcc_v4df, __gcc_v4df); __gcc_v8sf __builtin_ia32_divps256(__gcc_v8sf, __gcc_v8sf); __gcc_v8sf __builtin_ia32_dpps256(__gcc_v8sf, __gcc_v8sf, int); __gcc_v4df __builtin_ia32_haddpd256(__gcc_v4df, __gcc_v4df); __gcc_v8sf __builtin_ia32_haddps256(__gcc_v8sf, __gcc_v8sf); __gcc_v4df __builtin_ia32_hsubpd256(__gcc_v4df, __gcc_v4df); __gcc_v8sf __builtin_ia32_hsubps256(__gcc_v8sf, __gcc_v8sf); __gcc_v32qi __builtin_ia32_lddqu256(const char*); __gcc_v32qi __builtin_ia32_loaddqu256(const char*); __gcc_v4df __builtin_ia32_loadupd256(const double*); __gcc_v8sf __builtin_ia32_loadups256(const float*); __gcc_v2df __builtin_ia32_maskloadpd(const __gcc_v2df*, __gcc_v2di); __gcc_v4df __builtin_ia32_maskloadpd256(const __gcc_v4df*, __gcc_v4di); __gcc_v4sf __builtin_ia32_maskloadps(const __gcc_v4sf*, __gcc_v4si); __gcc_v8sf __builtin_ia32_maskloadps256(const __gcc_v8sf*, __gcc_v8si); void __builtin_ia32_maskstorepd(__gcc_v2df*, __gcc_v2di, __gcc_v2df); void __builtin_ia32_maskstorepd256(__gcc_v4df*, __gcc_v4di, __gcc_v4df); void __builtin_ia32_maskstoreps(__gcc_v4sf*, __gcc_v4si, __gcc_v4sf); void __builtin_ia32_maskstoreps256(__gcc_v8sf*, __gcc_v8si, __gcc_v8sf); __gcc_v4df __builtin_ia32_maxpd256(__gcc_v4df, __gcc_v4df); __gcc_v8sf __builtin_ia32_maxps256(__gcc_v8sf, __gcc_v8sf); __gcc_v4df __builtin_ia32_minpd256(__gcc_v4df, __gcc_v4df); __gcc_v8sf __builtin_ia32_minps256(__gcc_v8sf, __gcc_v8sf); __gcc_v4df __builtin_ia32_movddup256(__gcc_v4df); int __builtin_ia32_movmskpd256(__gcc_v4df); int __builtin_ia32_movmskps256(__gcc_v8sf); __gcc_v8sf __builtin_ia32_movshdup256(__gcc_v8sf); __gcc_v8sf __builtin_ia32_movsldup256(__gcc_v8sf); __gcc_v4df __builtin_ia32_mulpd256(__gcc_v4df, __gcc_v4df); __gcc_v8sf __builtin_ia32_mulps256(__gcc_v8sf, __gcc_v8sf); __gcc_v4df __builtin_ia32_orpd256(__gcc_v4df, __gcc_v4df); __gcc_v8sf __builtin_ia32_orps256(__gcc_v8sf, __gcc_v8sf); __gcc_v2df __builtin_ia32_pd_pd256(__gcc_v4df); __gcc_v4df __builtin_ia32_pd256_pd(__gcc_v2df); __gcc_v4sf __builtin_ia32_ps_ps256(__gcc_v8sf); __gcc_v8sf __builtin_ia32_ps256_ps(__gcc_v4sf); int __builtin_ia32_ptestc256(__gcc_v4di, __gcc_v4di); int __builtin_ia32_ptestnzc256(__gcc_v4di, __gcc_v4di); int __builtin_ia32_ptestz256(__gcc_v4di, __gcc_v4di); __gcc_v8sf __builtin_ia32_rcpps256(__gcc_v8sf); __gcc_v4df __builtin_ia32_roundpd256(__gcc_v4df, int); __gcc_v8sf __builtin_ia32_roundps256(__gcc_v8sf, int); __gcc_v8sf __builtin_ia32_rsqrtps_nr256(__gcc_v8sf); __gcc_v8sf __builtin_ia32_rsqrtps256(__gcc_v8sf); __gcc_v4df __builtin_ia32_shufpd256(__gcc_v4df, __gcc_v4df, int); __gcc_v8sf __builtin_ia32_shufps256(__gcc_v8sf, __gcc_v8sf, int); __gcc_v4si __builtin_ia32_si_si256(__gcc_v8si); __gcc_v8si __builtin_ia32_si256_si(__gcc_v4si); __gcc_v4df __builtin_ia32_sqrtpd256(__gcc_v4df); __gcc_v8sf __builtin_ia32_sqrtps_nr256(__gcc_v8sf); __gcc_v8sf __builtin_ia32_sqrtps256(__gcc_v8sf); void __builtin_ia32_storedqu256(char*, __gcc_v32qi); void __builtin_ia32_storeupd256(double*, __gcc_v4df); void __builtin_ia32_storeups256(float*, __gcc_v8sf); __gcc_v4df __builtin_ia32_subpd256(__gcc_v4df, __gcc_v4df); __gcc_v8sf __builtin_ia32_subps256(__gcc_v8sf, __gcc_v8sf); __gcc_v4df __builtin_ia32_unpckhpd256(__gcc_v4df, __gcc_v4df); __gcc_v8sf __builtin_ia32_unpckhps256(__gcc_v8sf, __gcc_v8sf); __gcc_v4df __builtin_ia32_unpcklpd256(__gcc_v4df, __gcc_v4df); __gcc_v8sf __builtin_ia32_unpcklps256(__gcc_v8sf, __gcc_v8sf); __gcc_v4df __builtin_ia32_vbroadcastf128_pd256(const __gcc_v2df*); __gcc_v8sf __builtin_ia32_vbroadcastf128_ps256(const __gcc_v4sf*); __gcc_v4df __builtin_ia32_vbroadcastsd256(const double*); __gcc_v4sf __builtin_ia32_vbroadcastss(const float*); __gcc_v8sf __builtin_ia32_vbroadcastss256(const float*); __gcc_v2df __builtin_ia32_vextractf128_pd256(__gcc_v4df, int); __gcc_v4sf __builtin_ia32_vextractf128_ps256(__gcc_v8sf, int); __gcc_v4si __builtin_ia32_vextractf128_si256(__gcc_v8si, int); __gcc_v4df __builtin_ia32_vinsertf128_pd256(__gcc_v4df, __gcc_v2df, int); __gcc_v8sf __builtin_ia32_vinsertf128_ps256(__gcc_v8sf, __gcc_v4sf, int); __gcc_v8si __builtin_ia32_vinsertf128_si256(__gcc_v8si, __gcc_v4si, int); __gcc_v4df __builtin_ia32_vperm2f128_pd256(__gcc_v4df, __gcc_v4df, int); __gcc_v8sf __builtin_ia32_vperm2f128_ps256(__gcc_v8sf, __gcc_v8sf, int); __gcc_v8si __builtin_ia32_vperm2f128_si256(__gcc_v8si, __gcc_v8si, int); __gcc_v2df __builtin_ia32_vpermil2pd(__gcc_v2df,__gcc_v2df,__gcc_v2di,int); __gcc_v4df __builtin_ia32_vpermil2pd256(__gcc_v4df,__gcc_v4df,__gcc_v4di,int); __gcc_v4sf __builtin_ia32_vpermil2ps(__gcc_v4sf,__gcc_v4sf,__gcc_v4si,int); __gcc_v8sf __builtin_ia32_vpermil2ps256(__gcc_v8sf,__gcc_v8sf,__gcc_v8si,int); __gcc_v2df __builtin_ia32_vpermilpd(__gcc_v2df, int); __gcc_v4df __builtin_ia32_vpermilpd256(__gcc_v4df, int); __gcc_v4sf __builtin_ia32_vpermilps(__gcc_v4sf, int); __gcc_v8sf __builtin_ia32_vpermilps256(__gcc_v8sf, int); __gcc_v2df __builtin_ia32_vpermilvarpd(__gcc_v2df, __gcc_v2di); __gcc_v4df __builtin_ia32_vpermilvarpd256(__gcc_v4df, __gcc_v4di); __gcc_v4sf __builtin_ia32_vpermilvarps(__gcc_v4sf, __gcc_v4si); __gcc_v8sf __builtin_ia32_vpermilvarps256(__gcc_v8sf, __gcc_v8si); int __builtin_ia32_vtestcpd(__gcc_v2df, __gcc_v2df); int __builtin_ia32_vtestcpd256(__gcc_v4df, __gcc_v4df); int __builtin_ia32_vtestcps(__gcc_v4sf, __gcc_v4sf); int __builtin_ia32_vtestcps256(__gcc_v8sf, __gcc_v8sf); int __builtin_ia32_vtestnzcpd(__gcc_v2df, __gcc_v2df); int __builtin_ia32_vtestnzcpd256(__gcc_v4df, __gcc_v4df); int __builtin_ia32_vtestnzcps(__gcc_v4sf, __gcc_v4sf); int __builtin_ia32_vtestnzcps256(__gcc_v8sf, __gcc_v8sf); int __builtin_ia32_vtestzpd(__gcc_v2df, __gcc_v2df); int __builtin_ia32_vtestzpd256(__gcc_v4df, __gcc_v4df); int __builtin_ia32_vtestzps(__gcc_v4sf, __gcc_v4sf); int __builtin_ia32_vtestzps256(__gcc_v8sf, __gcc_v8sf); void __builtin_ia32_vzeroall(); void __builtin_ia32_vzeroupper(); __gcc_v4df __builtin_ia32_xorpd256(__gcc_v4df, __gcc_v4df); __gcc_v8sf __builtin_ia32_xorps256(__gcc_v8sf, __gcc_v8sf); __gcc_v32qi __builtin_ia32_mpsadbw256(__gcc_v32qi, __gcc_v32qi, int); __gcc_v32qi __builtin_ia32_pabsb256(__gcc_v32qi); __gcc_v16hi __builtin_ia32_pabsw256(__gcc_v16hi); __gcc_v8si __builtin_ia32_pabsd256(__gcc_v8si); __gcc_v16hi __builtin_ia32_packssdw256(__gcc_v8si, __gcc_v8si); __gcc_v32qi __builtin_ia32_packsswb256(__gcc_v16hi, __gcc_v16hi); __gcc_v16hi __builtin_ia32_packusdw256(__gcc_v8si, __gcc_v8si); __gcc_v32qi __builtin_ia32_packuswb256(__gcc_v16hi, __gcc_v16hi); __gcc_v32qi __builtin_ia32_paddb256(__gcc_v32qi, __gcc_v32qi); __gcc_v16hi __builtin_ia32_paddw256(__gcc_v16hi, __gcc_v16hi); __gcc_v8si __builtin_ia32_paddd256(__gcc_v8si, __gcc_v8si); __gcc_v4di __builtin_ia32_paddq256(__gcc_v4di, __gcc_v4di); __gcc_v32qi __builtin_ia32_paddsb256(__gcc_v32qi, __gcc_v32qi); __gcc_v16hi __builtin_ia32_paddsw256(__gcc_v16hi, __gcc_v16hi); __gcc_v32qi __builtin_ia32_paddusb256(__gcc_v32qi, __gcc_v32qi); __gcc_v16hi __builtin_ia32_paddusw256(__gcc_v16hi, __gcc_v16hi); __gcc_v4di __builtin_ia32_palignr256(__gcc_v4di, __gcc_v4di, int); __gcc_v4di __builtin_ia32_andsi256(__gcc_v4di, __gcc_v4di); __gcc_v4di __builtin_ia32_andnotsi256(__gcc_v4di, __gcc_v4di); __gcc_v32qi __builtin_ia32_pavgb256(__gcc_v32qi, __gcc_v32qi); __gcc_v16hi __builtin_ia32_pavgw256(__gcc_v16hi, __gcc_v16hi); __gcc_v32qi __builtin_ia32_pblendvb256(__gcc_v32qi, __gcc_v32qi, __gcc_v32qi); __gcc_v16hi __builtin_ia32_pblendw256(__gcc_v16hi, __gcc_v16hi, int); __gcc_v32qi __builtin_ia32_pcmpeqb256(__gcc_v32qi, __gcc_v32qi); __gcc_v16hi __builtin_ia32_pcmpeqw256(__gcc_v16hi, __gcc_v16hi); __gcc_v8si __builtin_ia32_pcmpeqd256(__gcc_v8si, __gcc_v8si); __gcc_v4di __builtin_ia32_pcmpeqq256(__gcc_v4di, __gcc_v4di); __gcc_v32qi __builtin_ia32_pcmpgtb256(__gcc_v32qi, __gcc_v32qi); __gcc_v16hi __builtin_ia32_pcmpgtw256(__gcc_v16hi, __gcc_v16hi); __gcc_v8si __builtin_ia32_pcmpgtd256(__gcc_v8si, __gcc_v8si); __gcc_v4di __builtin_ia32_pcmpgtq256(__gcc_v4di, __gcc_v4di); __gcc_v16hi __builtin_ia32_phaddw256(__gcc_v16hi, __gcc_v16hi); __gcc_v8si __builtin_ia32_phaddd256(__gcc_v8si, __gcc_v8si); __gcc_v16hi __builtin_ia32_phaddsw256(__gcc_v16hi, __gcc_v16hi); __gcc_v16hi __builtin_ia32_phsubw256(__gcc_v16hi, __gcc_v16hi); __gcc_v8si __builtin_ia32_phsubd256(__gcc_v8si, __gcc_v8si); __gcc_v16hi __builtin_ia32_phsubsw256(__gcc_v16hi, __gcc_v16hi); __gcc_v16hi __builtin_ia32_pmaddubsw256(__gcc_v32qi, __gcc_v32qi); __gcc_v8si __builtin_ia32_pmaddwd256(__gcc_v16hi, __gcc_v16hi); __gcc_v32qi __builtin_ia32_pmaxsb256(__gcc_v32qi, __gcc_v32qi); __gcc_v16hi __builtin_ia32_pmaxsw256(__gcc_v16hi, __gcc_v16hi); __gcc_v8si __builtin_ia32_pmaxsd256(__gcc_v8si, __gcc_v8si); __gcc_v32qi __builtin_ia32_pmaxub256(__gcc_v32qi, __gcc_v32qi); __gcc_v16hi __builtin_ia32_pmaxuw256(__gcc_v16hi, __gcc_v16hi); __gcc_v8si __builtin_ia32_pmaxud256(__gcc_v8si, __gcc_v8si); __gcc_v32qi __builtin_ia32_pminsb256(__gcc_v32qi, __gcc_v32qi); __gcc_v16hi __builtin_ia32_pminsw256(__gcc_v16hi, __gcc_v16hi); __gcc_v8si __builtin_ia32_pminsd256(__gcc_v8si, __gcc_v8si); __gcc_v32qi __builtin_ia32_pminub256(__gcc_v32qi, __gcc_v32qi); __gcc_v16hi __builtin_ia32_pminuw256(__gcc_v16hi, __gcc_v16hi); __gcc_v8si __builtin_ia32_pminud256(__gcc_v8si, __gcc_v8si); int __builtin_ia32_pmovmskb256(__gcc_v32qi); __gcc_v16hi __builtin_ia32_pmovsxbw256(__gcc_v16qi); __gcc_v8si __builtin_ia32_pmovsxbd256(__gcc_v16qi); __gcc_v4di __builtin_ia32_pmovsxbq256(__gcc_v16qi); __gcc_v8si __builtin_ia32_pmovsxwd256(__gcc_v8hi); __gcc_v4di __builtin_ia32_pmovsxwq256(__gcc_v8hi); __gcc_v4di __builtin_ia32_pmovsxdq256(__gcc_v4si); __gcc_v16hi __builtin_ia32_pmovzxbw256(__gcc_v16qi); __gcc_v8si __builtin_ia32_pmovzxbd256(__gcc_v16qi); __gcc_v4di __builtin_ia32_pmovzxbq256(__gcc_v16qi); __gcc_v8si __builtin_ia32_pmovzxwd256(__gcc_v8hi); __gcc_v4di __builtin_ia32_pmovzxwq256(__gcc_v8hi); __gcc_v4di __builtin_ia32_pmovzxdq256(__gcc_v4si); __gcc_v4di __builtin_ia32_pmuldq256(__gcc_v8si, __gcc_v8si); __gcc_v16hi __builtin_ia32_pmulhrsw256(__gcc_v16hi, __gcc_v16hi); __gcc_v16hi __builtin_ia32_pmulhuw256(__gcc_v16hi, __gcc_v16hi); __gcc_v16hi __builtin_ia32_pmulhw256(__gcc_v16hi, __gcc_v16hi); __gcc_v16hi __builtin_ia32_pmullw256(__gcc_v16hi, __gcc_v16hi); __gcc_v8si __builtin_ia32_pmulld256(__gcc_v8si, __gcc_v8si); __gcc_v4di __builtin_ia32_pmuludq256(__gcc_v8si, __gcc_v8si); __gcc_v4di __builtin_ia32_por256(__gcc_v4di, __gcc_v4di); __gcc_v16hi __builtin_ia32_psadbw256(__gcc_v32qi, __gcc_v32qi); __gcc_v32qi __builtin_ia32_pshufb256(__gcc_v32qi, __gcc_v32qi); __gcc_v8si __builtin_ia32_pshufd256(__gcc_v8si, int); __gcc_v16hi __builtin_ia32_pshufhw256(__gcc_v16hi, int); __gcc_v16hi __builtin_ia32_pshuflw256(__gcc_v16hi, int); __gcc_v32qi __builtin_ia32_psignb256(__gcc_v32qi, __gcc_v32qi); __gcc_v16hi __builtin_ia32_psignw256(__gcc_v16hi, __gcc_v16hi); __gcc_v8si __builtin_ia32_psignd256(__gcc_v8si, __gcc_v8si); __gcc_v4di __builtin_ia32_pslldqi256(__gcc_v4di, int); __gcc_v16hi __builtin_ia32_psllwi256(__gcc_v16hi, int); __gcc_v16hi __builtin_ia32_psllw256(__gcc_v16hi, __gcc_v8hi); __gcc_v8si __builtin_ia32_pslldi256(__gcc_v8si, int); __gcc_v8si __builtin_ia32_pslld256(__gcc_v8si, __gcc_v4si); __gcc_v4di __builtin_ia32_psllqi256(__gcc_v4di, int); __gcc_v4di __builtin_ia32_psllq256(__gcc_v4di, __gcc_v2di); __gcc_v16hi __builtin_ia32_psrawi256(__gcc_v16hi, int); __gcc_v16hi __builtin_ia32_psraw256(__gcc_v16hi, __gcc_v8hi); __gcc_v8si __builtin_ia32_psradi256(__gcc_v8si, int); __gcc_v8si __builtin_ia32_psrad256(__gcc_v8si, __gcc_v4si); __gcc_v4di __builtin_ia32_psrldqi256(__gcc_v4di, int); __gcc_v16hi __builtin_ia32_psrlwi256(__gcc_v16hi, int); __gcc_v16hi __builtin_ia32_psrlw256(__gcc_v16hi, __gcc_v8hi); __gcc_v8si __builtin_ia32_psrldi256(__gcc_v8si, int); __gcc_v8si __builtin_ia32_psrld256(__gcc_v8si, __gcc_v4si); __gcc_v4di __builtin_ia32_psrlqi256(__gcc_v4di, int); __gcc_v4di __builtin_ia32_psrlq256(__gcc_v4di, __gcc_v2di); __gcc_v32qi __builtin_ia32_psubb256(__gcc_v32qi, __gcc_v32qi); __gcc_v16hi __builtin_ia32_psubw256(__gcc_v16hi, __gcc_v16hi); __gcc_v8si __builtin_ia32_psubd256(__gcc_v8si, __gcc_v8si); __gcc_v4di __builtin_ia32_psubq256(__gcc_v4di, __gcc_v4di); __gcc_v32qi __builtin_ia32_psubsb256(__gcc_v32qi, __gcc_v32qi); __gcc_v16hi __builtin_ia32_psubsw256(__gcc_v16hi, __gcc_v16hi); __gcc_v32qi __builtin_ia32_psubusb256(__gcc_v32qi, __gcc_v32qi); __gcc_v16hi __builtin_ia32_psubusw256(__gcc_v16hi, __gcc_v16hi); __gcc_v32qi __builtin_ia32_punpckhbw256(__gcc_v32qi, __gcc_v32qi); __gcc_v16hi __builtin_ia32_punpckhwd256(__gcc_v16hi, __gcc_v16hi); __gcc_v8si __builtin_ia32_punpckhdq256(__gcc_v8si, __gcc_v8si); __gcc_v4di __builtin_ia32_punpckhqdq256(__gcc_v4di, __gcc_v4di); __gcc_v32qi __builtin_ia32_punpcklbw256(__gcc_v32qi, __gcc_v32qi); __gcc_v16hi __builtin_ia32_punpcklwd256(__gcc_v16hi, __gcc_v16hi); __gcc_v8si __builtin_ia32_punpckldq256(__gcc_v8si, __gcc_v8si); __gcc_v4di __builtin_ia32_punpcklqdq256(__gcc_v4di, __gcc_v4di); __gcc_v4di __builtin_ia32_pxor256(__gcc_v4di, __gcc_v4di); __gcc_v4di __builtin_ia32_movntdqa256(__gcc_v4di*); __gcc_v4sf __builtin_ia32_vbroadcastss_ps(__gcc_v4sf); __gcc_v8sf __builtin_ia32_vbroadcastss_ps256(__gcc_v4sf); __gcc_v4df __builtin_ia32_vbroadcastsd_pd256(__gcc_v2df); __gcc_v4di __builtin_ia32_vbroadcastsi256(__gcc_v2di); __gcc_v4si __builtin_ia32_pblendd128(__gcc_v4si, __gcc_v4si, int); __gcc_v8si __builtin_ia32_pblendd256(__gcc_v8si, __gcc_v8si, int); __gcc_v32qi __builtin_ia32_pbroadcastb256(__gcc_v16qi); __gcc_v16hi __builtin_ia32_pbroadcastw256(__gcc_v8hi); __gcc_v8si __builtin_ia32_pbroadcastd256(__gcc_v4si); __gcc_v4di __builtin_ia32_pbroadcastq256(__gcc_v2di); __gcc_v16qi __builtin_ia32_pbroadcastb128(__gcc_v16qi); __gcc_v8hi __builtin_ia32_pbroadcastw128(__gcc_v8hi); __gcc_v4si __builtin_ia32_pbroadcastd128(__gcc_v4si); __gcc_v2di __builtin_ia32_pbroadcastq128(__gcc_v2di); __gcc_v8si __builtin_ia32_permvarsi256(__gcc_v8si, __gcc_v8si); __gcc_v4df __builtin_ia32_permdf256(__gcc_v4df, int); __gcc_v8sf __builtin_ia32_permvarsf256(__gcc_v8sf, __gcc_v8si); __gcc_v4di __builtin_ia32_permdi256(__gcc_v4di, int); __gcc_v4di __builtin_ia32_permti256(__gcc_v4di, __gcc_v4di, int); __gcc_v2di __builtin_ia32_extract128i256(__gcc_v4di, int); __gcc_v4di __builtin_ia32_insert128i256(__gcc_v4di, __gcc_v2di, int); __gcc_v8si __builtin_ia32_maskloadd256(const __gcc_v8si*, __gcc_v8si); __gcc_v4di __builtin_ia32_maskloadq256(const __gcc_v4di*, __gcc_v4di); __gcc_v4si __builtin_ia32_maskloadd(const __gcc_v4si*, __gcc_v4si); __gcc_v2di __builtin_ia32_maskloadq(const __gcc_v2di*, __gcc_v2di); void __builtin_ia32_maskstored256(__gcc_v8si*, __gcc_v8si, __gcc_v8si); void __builtin_ia32_maskstoreq256(__gcc_v4di*, __gcc_v4di, __gcc_v4di); void __builtin_ia32_maskstored(__gcc_v4si*, __gcc_v4si, __gcc_v4si); void __builtin_ia32_maskstoreq(__gcc_v2di*, __gcc_v2di, __gcc_v2di); __gcc_v8si __builtin_ia32_psll__gcc_v8si(__gcc_v8si,__gcc_v8si); __gcc_v4si __builtin_ia32_psll__gcc_v4si(__gcc_v4si,__gcc_v4si); __gcc_v4di __builtin_ia32_psll__gcc_v4di(__gcc_v4di,__gcc_v4di); __gcc_v2di __builtin_ia32_psll__gcc_v2di(__gcc_v2di,__gcc_v2di); __gcc_v8si __builtin_ia32_psra__gcc_v8si(__gcc_v8si,__gcc_v8si); __gcc_v4si __builtin_ia32_psra__gcc_v4si(__gcc_v4si,__gcc_v4si); __gcc_v8si __builtin_ia32_psrl__gcc_v8si(__gcc_v8si,__gcc_v8si); __gcc_v4si __builtin_ia32_psrl__gcc_v4si(__gcc_v4si,__gcc_v4si); __gcc_v4di __builtin_ia32_psrl__gcc_v4di(__gcc_v4di,__gcc_v4di); __gcc_v2di __builtin_ia32_psrl__gcc_v2di(__gcc_v2di,__gcc_v2di); __gcc_v2df __builtin_ia32_gathersi__gcc_v2df(__gcc_v2df, const double*,__gcc_v4si,__gcc_v2df,int); __gcc_v4df __builtin_ia32_gathersi__gcc_v4df(__gcc_v4df, const double*,__gcc_v4si,__gcc_v4df,int); __gcc_v2df __builtin_ia32_gatherdi__gcc_v2df(__gcc_v2df, const double*,__gcc_v2di,__gcc_v2df,int); __gcc_v4df __builtin_ia32_gatherdi__gcc_v4df(__gcc_v4df, const double*,__gcc_v4di,__gcc_v4df,int); __gcc_v4sf __builtin_ia32_gathersi__gcc_v4sf(__gcc_v4sf, const float*,__gcc_v4si,__gcc_v4sf,int); __gcc_v8sf __builtin_ia32_gathersi__gcc_v8sf(__gcc_v8sf, const float*,__gcc_v8si,__gcc_v8sf,int); __gcc_v4sf __builtin_ia32_gatherdi__gcc_v4sf(__gcc_v4sf, const float*,__gcc_v2di,__gcc_v4sf,int); __gcc_v4sf __builtin_ia32_gatherdi__gcc_v4sf256(__gcc_v4sf, const float*,__gcc_v4di,__gcc_v4sf,int); __gcc_v2di __builtin_ia32_gathersi__gcc_v2di(__gcc_v2di, const long long int*,__gcc_v4si,__gcc_v2di,int); __gcc_v4di __builtin_ia32_gathersi__gcc_v4di(__gcc_v4di, const long long int*,__gcc_v4si,__gcc_v4di,int); __gcc_v2di __builtin_ia32_gatherdi__gcc_v2di(__gcc_v2di, const long long int*,__gcc_v2di,__gcc_v2di,int); __gcc_v4di __builtin_ia32_gatherdi__gcc_v4di(__gcc_v4di, const long long int*,__gcc_v4di,__gcc_v4di,int); __gcc_v4si __builtin_ia32_gathersi__gcc_v4si(__gcc_v4si, const int*,__gcc_v4si,__gcc_v4si,int); __gcc_v8si __builtin_ia32_gathersi__gcc_v8si(__gcc_v8si, const int*,__gcc_v8si,__gcc_v8si,int); __gcc_v4si __builtin_ia32_gatherdi__gcc_v4si(__gcc_v4si, const int*,__gcc_v2di,__gcc_v4si,int); __gcc_v4si __builtin_ia32_gatherdi__gcc_v4si256(__gcc_v4si, const int*,__gcc_v4di,__gcc_v4si,int); __gcc_v2di __builtin_ia32_aesenc128(__gcc_v2di, __gcc_v2di); __gcc_v2di __builtin_ia32_aesenclast128(__gcc_v2di, __gcc_v2di); __gcc_v2di __builtin_ia32_aesdec128(__gcc_v2di, __gcc_v2di); __gcc_v2di __builtin_ia32_aesdeclast128(__gcc_v2di, __gcc_v2di); __gcc_v2di __builtin_ia32_aeskeygenassist128(__gcc_v2di, const int); __gcc_v2di __builtin_ia32_aesimc128(__gcc_v2di); __gcc_v2di __builtin_ia32_pclmulqdq128(__gcc_v2di, __gcc_v2di, const int); unsigned __builtin_ia32_rdfsbase32(); unsigned long long __builtin_ia32_rdfsbase64(); unsigned __builtin_ia32_rdgsbase32(); unsigned long long __builtin_ia32_rdgsbase64(); void _writefsbase_u32(unsigned int); void _writefsbase_u64(unsigned long long); void _writegsbase_u32(unsigned int); void _writegsbase_u64(unsigned long long); unsigned int __builtin_ia32_rdrand16_step(unsigned short*); unsigned int __builtin_ia32_rdrand32_step(unsigned int*); unsigned int __builtin_ia32_rdrand64_step(unsigned long long*); void __builtin_ia32_movntsd(double*, __gcc_v2df); void __builtin_ia32_movntss(float*, __gcc_v4sf); __gcc_v2di __builtin_ia32_extrq (__gcc_v2di, __gcc_v16qi); __gcc_v2di __builtin_ia32_extrqi(__gcc_v2di, unsigned, unsigned); __gcc_v2di __builtin_ia32_insertq(__gcc_v2di, __gcc_v2di); __gcc_v2di __builtin_ia32_insertqi(__gcc_v2di, __gcc_v2di, unsigned, unsigned); __gcc_v2df __builtin_ia32_vfrczpd(__gcc_v2df); __gcc_v4sf __builtin_ia32_vfrczps(__gcc_v4sf); __gcc_v2df __builtin_ia32_vfrczsd(__gcc_v2df); __gcc_v4sf __builtin_ia32_vfrczss(__gcc_v4sf); __gcc_v4df __builtin_ia32_vfrczpd256(__gcc_v4df); __gcc_v8sf __builtin_ia32_vfrczps256(__gcc_v8sf); __gcc_v2di __builtin_ia32_vpcmov(__gcc_v2di, __gcc_v2di, __gcc_v2di); __gcc_v2di __builtin_ia32_vpcmov_v2di(__gcc_v2di, __gcc_v2di, __gcc_v2di); __gcc_v4si __builtin_ia32_vpcmov_v4si(__gcc_v4si, __gcc_v4si, __gcc_v4si); __gcc_v8hi __builtin_ia32_vpcmov_v8hi(__gcc_v8hi, __gcc_v8hi, __gcc_v8hi); __gcc_v16qi __builtin_ia32_vpcmov_v16qi(__gcc_v16qi, __gcc_v16qi, __gcc_v16qi); __gcc_v2df __builtin_ia32_vpcmov_v2df(__gcc_v2df, __gcc_v2df, __gcc_v2df); __gcc_v4sf __builtin_ia32_vpcmov_v4sf(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf); __gcc_v4di __builtin_ia32_vpcmov_v4di256(__gcc_v4di, __gcc_v4di, __gcc_v4di); __gcc_v8si __builtin_ia32_vpcmov_v8si256(__gcc_v8si, __gcc_v8si, __gcc_v8si); __gcc_v16hi __builtin_ia32_vpcmov_v16hi256(__gcc_v16hi, __gcc_v16hi, __gcc_v16hi); __gcc_v32qi __builtin_ia32_vpcmov_v32qi256(__gcc_v32qi, __gcc_v32qi, __gcc_v32qi); __gcc_v4df __builtin_ia32_vpcmov___gcc_v4df256(__gcc_v4df, __gcc_v4df, __gcc_v4df); __gcc_v8sf __builtin_ia32_vpcmov___gcc_v8sf256(__gcc_v8sf, __gcc_v8sf, __gcc_v8sf); __gcc_v16qi __builtin_ia32_vpcomeqb(__gcc_v16qi, __gcc_v16qi); __gcc_v8hi __builtin_ia32_vpcomeqw(__gcc_v8hi, __gcc_v8hi); __gcc_v4si __builtin_ia32_vpcomeqd(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_vpcomeqq(__gcc_v2di, __gcc_v2di); __gcc_v16qi __builtin_ia32_vpcomequb(__gcc_v16qi, __gcc_v16qi); __gcc_v4si __builtin_ia32_vpcomequd(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_vpcomequq(__gcc_v2di, __gcc_v2di); __gcc_v8hi __builtin_ia32_vpcomequw(__gcc_v8hi, __gcc_v8hi); __gcc_v8hi __builtin_ia32_vpcomeqw(__gcc_v8hi, __gcc_v8hi); __gcc_v16qi __builtin_ia32_vpcomfalseb(__gcc_v16qi, __gcc_v16qi); __gcc_v4si __builtin_ia32_vpcomfalsed(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_vpcomfalseq(__gcc_v2di, __gcc_v2di); __gcc_v16qi __builtin_ia32_vpcomfalseub(__gcc_v16qi, __gcc_v16qi); __gcc_v4si __builtin_ia32_vpcomfalseud(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_vpcomfalseuq(__gcc_v2di, __gcc_v2di); __gcc_v8hi __builtin_ia32_vpcomfalseuw(__gcc_v8hi, __gcc_v8hi); __gcc_v8hi __builtin_ia32_vpcomfalsew(__gcc_v8hi, __gcc_v8hi); __gcc_v16qi __builtin_ia32_vpcomgeb(__gcc_v16qi, __gcc_v16qi); __gcc_v4si __builtin_ia32_vpcomged(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_vpcomgeq(__gcc_v2di, __gcc_v2di); __gcc_v16qi __builtin_ia32_vpcomgeub(__gcc_v16qi, __gcc_v16qi); __gcc_v4si __builtin_ia32_vpcomgeud(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_vpcomgeuq(__gcc_v2di, __gcc_v2di); __gcc_v8hi __builtin_ia32_vpcomgeuw(__gcc_v8hi, __gcc_v8hi); __gcc_v8hi __builtin_ia32_vpcomgew(__gcc_v8hi, __gcc_v8hi); __gcc_v16qi __builtin_ia32_vpcomgtb(__gcc_v16qi, __gcc_v16qi); __gcc_v4si __builtin_ia32_vpcomgtd(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_vpcomgtq(__gcc_v2di, __gcc_v2di); __gcc_v16qi __builtin_ia32_vpcomgtub(__gcc_v16qi, __gcc_v16qi); __gcc_v4si __builtin_ia32_vpcomgtud(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_vpcomgtuq(__gcc_v2di, __gcc_v2di); __gcc_v8hi __builtin_ia32_vpcomgtuw(__gcc_v8hi, __gcc_v8hi); __gcc_v8hi __builtin_ia32_vpcomgtw(__gcc_v8hi, __gcc_v8hi); __gcc_v16qi __builtin_ia32_vpcomleb(__gcc_v16qi, __gcc_v16qi); __gcc_v4si __builtin_ia32_vpcomled(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_vpcomleq(__gcc_v2di, __gcc_v2di); __gcc_v16qi __builtin_ia32_vpcomleub(__gcc_v16qi, __gcc_v16qi); __gcc_v4si __builtin_ia32_vpcomleud(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_vpcomleuq(__gcc_v2di, __gcc_v2di); __gcc_v8hi __builtin_ia32_vpcomleuw(__gcc_v8hi, __gcc_v8hi); __gcc_v8hi __builtin_ia32_vpcomlew(__gcc_v8hi, __gcc_v8hi); __gcc_v16qi __builtin_ia32_vpcomltb(__gcc_v16qi, __gcc_v16qi); __gcc_v4si __builtin_ia32_vpcomltd(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_vpcomltq(__gcc_v2di, __gcc_v2di); __gcc_v16qi __builtin_ia32_vpcomltub(__gcc_v16qi, __gcc_v16qi); __gcc_v4si __builtin_ia32_vpcomltud(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_vpcomltuq(__gcc_v2di, __gcc_v2di); __gcc_v8hi __builtin_ia32_vpcomltuw(__gcc_v8hi, __gcc_v8hi); __gcc_v8hi __builtin_ia32_vpcomltw(__gcc_v8hi, __gcc_v8hi); __gcc_v16qi __builtin_ia32_vpcomneb(__gcc_v16qi, __gcc_v16qi); __gcc_v4si __builtin_ia32_vpcomned(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_vpcomneq(__gcc_v2di, __gcc_v2di); __gcc_v16qi __builtin_ia32_vpcomneub(__gcc_v16qi, __gcc_v16qi); __gcc_v4si __builtin_ia32_vpcomneud(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_vpcomneuq(__gcc_v2di, __gcc_v2di); __gcc_v8hi __builtin_ia32_vpcomneuw(__gcc_v8hi, __gcc_v8hi); __gcc_v8hi __builtin_ia32_vpcomnew(__gcc_v8hi, __gcc_v8hi); __gcc_v16qi __builtin_ia32_vpcomtrueb(__gcc_v16qi, __gcc_v16qi); __gcc_v4si __builtin_ia32_vpcomtrued(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_vpcomtrueq(__gcc_v2di, __gcc_v2di); __gcc_v16qi __builtin_ia32_vpcomtrueub(__gcc_v16qi, __gcc_v16qi); __gcc_v4si __builtin_ia32_vpcomtrueud(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_vpcomtrueuq(__gcc_v2di, __gcc_v2di); __gcc_v8hi __builtin_ia32_vpcomtrueuw(__gcc_v8hi, __gcc_v8hi); __gcc_v8hi __builtin_ia32_vpcomtruew(__gcc_v8hi, __gcc_v8hi); __gcc_v4si __builtin_ia32_vphaddbd(__gcc_v16qi); __gcc_v2di __builtin_ia32_vphaddbq(__gcc_v16qi); __gcc_v8hi __builtin_ia32_vphaddbw(__gcc_v16qi); __gcc_v2di __builtin_ia32_vphadddq(__gcc_v4si); __gcc_v4si __builtin_ia32_vphaddubd(__gcc_v16qi); __gcc_v2di __builtin_ia32_vphaddubq(__gcc_v16qi); __gcc_v8hi __builtin_ia32_vphaddubw(__gcc_v16qi); __gcc_v2di __builtin_ia32_vphaddudq(__gcc_v4si); __gcc_v4si __builtin_ia32_vphadduwd(__gcc_v8hi); __gcc_v2di __builtin_ia32_vphadduwq(__gcc_v8hi); __gcc_v4si __builtin_ia32_vphaddwd(__gcc_v8hi); __gcc_v2di __builtin_ia32_vphaddwq(__gcc_v8hi); __gcc_v8hi __builtin_ia32_vphsubbw(__gcc_v16qi); __gcc_v2di __builtin_ia32_vphsubdq(__gcc_v4si); __gcc_v4si __builtin_ia32_vphsubwd(__gcc_v8hi); __gcc_v4si __builtin_ia32_vpmacsdd(__gcc_v4si, __gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_vpmacsdqh(__gcc_v4si, __gcc_v4si, __gcc_v2di); __gcc_v2di __builtin_ia32_vpmacsdql(__gcc_v4si, __gcc_v4si, __gcc_v2di); __gcc_v4si __builtin_ia32_vpmacssdd(__gcc_v4si, __gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_vpmacssdqh(__gcc_v4si, __gcc_v4si, __gcc_v2di); __gcc_v2di __builtin_ia32_vpmacssdql(__gcc_v4si, __gcc_v4si, __gcc_v2di); __gcc_v4si __builtin_ia32_vpmacsswd(__gcc_v8hi, __gcc_v8hi, __gcc_v4si); __gcc_v8hi __builtin_ia32_vpmacssww(__gcc_v8hi, __gcc_v8hi, __gcc_v8hi); __gcc_v4si __builtin_ia32_vpmacswd(__gcc_v8hi, __gcc_v8hi, __gcc_v4si); __gcc_v8hi __builtin_ia32_vpmacsww(__gcc_v8hi, __gcc_v8hi, __gcc_v8hi); __gcc_v4si __builtin_ia32_vpmadcsswd(__gcc_v8hi, __gcc_v8hi, __gcc_v4si); __gcc_v4si __builtin_ia32_vpmadcswd(__gcc_v8hi, __gcc_v8hi, __gcc_v4si); __gcc_v16qi __builtin_ia32_vpperm(__gcc_v16qi, __gcc_v16qi, __gcc_v16qi); __gcc_v16qi __builtin_ia32_vprotb(__gcc_v16qi, __gcc_v16qi); __gcc_v4si __builtin_ia32_vprotd(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_vprotq(__gcc_v2di, __gcc_v2di); __gcc_v8hi __builtin_ia32_vprotw(__gcc_v8hi, __gcc_v8hi); __gcc_v16qi __builtin_ia32_vpshab(__gcc_v16qi, __gcc_v16qi); __gcc_v4si __builtin_ia32_vpshad(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_vpshaq(__gcc_v2di, __gcc_v2di); __gcc_v8hi __builtin_ia32_vpshaw(__gcc_v8hi, __gcc_v8hi); __gcc_v16qi __builtin_ia32_vpshlb(__gcc_v16qi, __gcc_v16qi); __gcc_v4si __builtin_ia32_vpshld(__gcc_v4si, __gcc_v4si); __gcc_v2di __builtin_ia32_vpshlq(__gcc_v2di, __gcc_v2di); __gcc_v8hi __builtin_ia32_vpshlw(__gcc_v8hi, __gcc_v8hi); __gcc_v2df __builtin_ia32_fmaddpd(__gcc_v2df, __gcc_v2df, __gcc_v2df); __gcc_v4sf __builtin_ia32_fmaddps(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf); __gcc_v2df __builtin_ia32_fmaddsd(__gcc_v2df, __gcc_v2df, __gcc_v2df); __gcc_v4sf __builtin_ia32_fmaddss(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf); __gcc_v2df __builtin_ia32_fmsubpd(__gcc_v2df, __gcc_v2df, __gcc_v2df); __gcc_v4sf __builtin_ia32_fmsubps(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf); __gcc_v2df __builtin_ia32_fmsubsd(__gcc_v2df, __gcc_v2df, __gcc_v2df); __gcc_v4sf __builtin_ia32_fmsubss(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf); __gcc_v2df __builtin_ia32_fnmaddpd(__gcc_v2df, __gcc_v2df, __gcc_v2df); __gcc_v4sf __builtin_ia32_fnmaddps(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf); __gcc_v2df __builtin_ia32_fnmaddsd(__gcc_v2df, __gcc_v2df, __gcc_v2df); __gcc_v4sf __builtin_ia32_fnmaddss(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf); __gcc_v2df __builtin_ia32_fnmsubpd(__gcc_v2df, __gcc_v2df, __gcc_v2df); __gcc_v4sf __builtin_ia32_fnmsubps(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf); __gcc_v2df __builtin_ia32_fnmsubsd(__gcc_v2df, __gcc_v2df, __gcc_v2df); __gcc_v4sf __builtin_ia32_fnmsubss(__gcc_v4sf, __gcc_v4sf, __gcc_v4sf); __gcc_v2df __builtin_ia32_fmaddsubpd (__gcc_v2df, __gcc_v2df, __gcc_v2df); __gcc_v4sf __builtin_ia32_fmaddsubps (__gcc_v4sf, __gcc_v4sf, __gcc_v4sf); __gcc_v2df __builtin_ia32_fmsubaddpd (__gcc_v2df, __gcc_v2df, __gcc_v2df); __gcc_v4sf __builtin_ia32_fmsubaddps (__gcc_v4sf, __gcc_v4sf, __gcc_v4sf); __gcc_v4df __builtin_ia32_fmaddpd256(__gcc_v4df, __gcc_v4df, __gcc_v4df); __gcc_v8sf __builtin_ia32_fmaddps256(__gcc_v8sf, __gcc_v8sf, __gcc_v8sf); __gcc_v4df __builtin_ia32_fmsubpd256(__gcc_v4df, __gcc_v4df, __gcc_v4df); __gcc_v8sf __builtin_ia32_fmsubps256(__gcc_v8sf, __gcc_v8sf, __gcc_v8sf); __gcc_v4df __builtin_ia32_fnmaddpd256(__gcc_v4df, __gcc_v4df, __gcc_v4df); __gcc_v8sf __builtin_ia32_fnmaddps256(__gcc_v8sf, __gcc_v8sf, __gcc_v8sf); __gcc_v4df __builtin_ia32_fnmsubpd256(__gcc_v4df, __gcc_v4df, __gcc_v4df); __gcc_v8sf __builtin_ia32_fnmsubps256(__gcc_v8sf, __gcc_v8sf, __gcc_v8sf); __gcc_v4df __builtin_ia32_fmaddsubpd256(__gcc_v4df, __gcc_v4df, __gcc_v4df); __gcc_v8sf __builtin_ia32_fmaddsubps256(__gcc_v8sf, __gcc_v8sf, __gcc_v8sf); __gcc_v4df __builtin_ia32_fmsubaddpd256(__gcc_v4df, __gcc_v4df, __gcc_v4df); __gcc_v8sf __builtin_ia32_fmsubaddps256(__gcc_v8sf, __gcc_v8sf, __gcc_v8sf); void __builtin_ia32_llwpcb16(void*); void __builtin_ia32_llwpcb32(void*); void __builtin_ia32_llwpcb64(void*); //void* __builtin_ia32_llwpcb16(void); //void* __builtin_ia32_llwpcb32(void); //void* __builtin_ia32_llwpcb64(void); void __builtin_ia32_lwpval16(unsigned short, unsigned int, unsigned short); void __builtin_ia32_lwpval32(unsigned, unsigned, unsigned); void __builtin_ia32_lwpval64(unsigned long long, unsigned, unsigned); unsigned char __builtin_ia32_lwpins16(unsigned short, unsigned int, unsigned short); unsigned char __builtin_ia32_lwpins32(unsigned, unsigned, unsigned); unsigned char __builtin_ia32_lwpins64(unsigned long long, unsigned, unsigned); unsigned __builtin_ia32_bextr_u32(unsigned, unsigned); unsigned long long __builtin_ia32_bextr_u64(unsigned long long, unsigned long long); unsigned int _bzhi_u32(unsigned int, unsigned int); unsigned int _pdep_u32(unsigned int, unsigned int); unsigned int _pext_u32(unsigned int, unsigned int); unsigned long long _bzhi_u64(unsigned long long, unsigned long long); unsigned long long _pdep_u64(unsigned long long, unsigned long long); unsigned long long _pext_u64(unsigned long long, unsigned long long); unsigned short __builtin_ia32_lzcnt_16(unsigned short); unsigned __builtin_ia32_lzcnt_u32(unsigned); unsigned long long __builtin_ia32_lzcnt_u64(unsigned long long); unsigned __builtin_ia32_bextri_u32(unsigned, unsigned); unsigned long long __builtin_ia32_bextri_u64(unsigned long long, unsigned long long); void __builtin_ia32_femms(); __gcc_v8qi __builtin_ia32_pavgusb(__gcc_v8qi, __gcc_v8qi); __gcc_v2si __builtin_ia32_pf2id(__gcc_v2sf); __gcc_v2sf __builtin_ia32_pfacc(__gcc_v2sf, __gcc_v2sf); __gcc_v2sf __builtin_ia32_pfadd(__gcc_v2sf, __gcc_v2sf); __gcc_v2si __builtin_ia32_pfcmpeq(__gcc_v2sf, __gcc_v2sf); __gcc_v2si __builtin_ia32_pfcmpge(__gcc_v2sf, __gcc_v2sf); __gcc_v2si __builtin_ia32_pfcmpgt(__gcc_v2sf, __gcc_v2sf); __gcc_v2sf __builtin_ia32_pfmax(__gcc_v2sf, __gcc_v2sf); __gcc_v2sf __builtin_ia32_pfmin(__gcc_v2sf, __gcc_v2sf); __gcc_v2sf __builtin_ia32_pfmul(__gcc_v2sf, __gcc_v2sf); __gcc_v2sf __builtin_ia32_pfrcp(__gcc_v2sf); __gcc_v2sf __builtin_ia32_pfrcpit1(__gcc_v2sf, __gcc_v2sf); __gcc_v2sf __builtin_ia32_pfrcpit2(__gcc_v2sf, __gcc_v2sf); __gcc_v2sf __builtin_ia32_pfrsqrt(__gcc_v2sf); __gcc_v2sf __builtin_ia32_pfrsqrtit1(__gcc_v2sf, __gcc_v2sf); __gcc_v2sf __builtin_ia32_pfsub(__gcc_v2sf, __gcc_v2sf); __gcc_v2sf __builtin_ia32_pfsubr(__gcc_v2sf, __gcc_v2sf); __gcc_v2sf __builtin_ia32_pi2fd(__gcc_v2si); __gcc_v4hi __builtin_ia32_pmulhrw(__gcc_v4hi, __gcc_v4hi); __gcc_v2si __builtin_ia32_pf2iw(__gcc_v2sf); __gcc_v2sf __builtin_ia32_pfnacc(__gcc_v2sf, __gcc_v2sf); __gcc_v2sf __builtin_ia32_pfpnacc(__gcc_v2sf, __gcc_v2sf); __gcc_v2sf __builtin_ia32_pi2fw(__gcc_v2si); __gcc_v2sf __builtin_ia32_pswapdsf(__gcc_v2sf); __gcc_v2si __builtin_ia32_pswapdsi(__gcc_v2si); // unknown! __gcc_v4sf __builtin_ia32_cmpnltss(__gcc_v4sf, __gcc_v4sf); int __builtin_ia32_comeqpd(); int __builtin_ia32_comeqps(); int __builtin_ia32_comeqsd(); int __builtin_ia32_comeqss(); int __builtin_ia32_comfalsepd(); int __builtin_ia32_comfalseps(); int __builtin_ia32_comfalsesd(); int __builtin_ia32_comfalsess(); int __builtin_ia32_comgepd(); int __builtin_ia32_comgeps(); int __builtin_ia32_comgesd(); int __builtin_ia32_comgess(); int __builtin_ia32_comgtpd(); int __builtin_ia32_comgtps(); int __builtin_ia32_comgtsd(); int __builtin_ia32_comgtss(); int __builtin_ia32_comlepd(); int __builtin_ia32_comleps(); int __builtin_ia32_comlesd(); int __builtin_ia32_comless(); int __builtin_ia32_comltpd(); int __builtin_ia32_comltps(); int __builtin_ia32_comltsd(); int __builtin_ia32_comltss(); int __builtin_ia32_comneqpd(); int __builtin_ia32_comneqps(); int __builtin_ia32_comneqsd(); int __builtin_ia32_comneqss(); int __builtin_ia32_comordpd(); int __builtin_ia32_comordps(); int __builtin_ia32_comordsd(); int __builtin_ia32_comordss(); int __builtin_ia32_comtruepd(); int __builtin_ia32_comtrueps(); int __builtin_ia32_comtruesd(); int __builtin_ia32_comtruess(); int __builtin_ia32_comueqpd(); int __builtin_ia32_comueqps(); int __builtin_ia32_comueqsd(); int __builtin_ia32_comueqss(); int __builtin_ia32_comuneqpd(); int __builtin_ia32_comuneqps(); int __builtin_ia32_comuneqsd(); int __builtin_ia32_comuneqss(); int __builtin_ia32_comungepd(); int __builtin_ia32_comungeps(); int __builtin_ia32_comungesd(); int __builtin_ia32_comungess(); int __builtin_ia32_comungtpd(); int __builtin_ia32_comungtps(); int __builtin_ia32_comungtsd(); int __builtin_ia32_comungtss(); int __builtin_ia32_comunlepd(); int __builtin_ia32_comunleps(); int __builtin_ia32_comunlesd(); int __builtin_ia32_comunless(); int __builtin_ia32_comunltpd(); int __builtin_ia32_comunltps(); int __builtin_ia32_comunltsd(); int __builtin_ia32_comunltss(); int __builtin_ia32_comunordpd(); int __builtin_ia32_comunordps(); int __builtin_ia32_comunordsd(); int __builtin_ia32_comunordss(); int __builtin_ia32_frczpd(); int __builtin_ia32_frczps(); int __builtin_ia32_frczsd(); int __builtin_ia32_frczss(); int __builtin_ia32_pcmov(); int __builtin_ia32_pcomeqb(); int __builtin_ia32_pcomeqd(); int __builtin_ia32_pcomeqq(); int __builtin_ia32_pcomequb(); int __builtin_ia32_pcomequd(); int __builtin_ia32_pcomequq(); int __builtin_ia32_pcomequw(); int __builtin_ia32_pcomeqw(); int __builtin_ia32_pcomfalseb(); int __builtin_ia32_pcomfalsed(); int __builtin_ia32_pcomfalseq(); int __builtin_ia32_pcomfalseub(); int __builtin_ia32_pcomfalseud(); int __builtin_ia32_pcomfalseuq(); int __builtin_ia32_pcomfalseuw(); int __builtin_ia32_pcomfalsew(); int __builtin_ia32_pcomgeb(); int __builtin_ia32_pcomged(); int __builtin_ia32_pcomgeq(); int __builtin_ia32_pcomgeub(); int __builtin_ia32_pcomgeud(); int __builtin_ia32_pcomgeuq(); int __builtin_ia32_pcomgeuw(); int __builtin_ia32_pcomgew(); int __builtin_ia32_pcomgtb(); int __builtin_ia32_pcomgtd(); int __builtin_ia32_pcomgtq(); int __builtin_ia32_pcomgtub(); int __builtin_ia32_pcomgtud(); int __builtin_ia32_pcomgtuq(); int __builtin_ia32_pcomgtuw(); int __builtin_ia32_pcomgtw(); int __builtin_ia32_pcomleb(); int __builtin_ia32_pcomled(); int __builtin_ia32_pcomleq(); int __builtin_ia32_pcomleub(); int __builtin_ia32_pcomleud(); int __builtin_ia32_pcomleuq(); int __builtin_ia32_pcomleuw(); int __builtin_ia32_pcomlew(); int __builtin_ia32_pcomltb(); int __builtin_ia32_pcomltd(); int __builtin_ia32_pcomltq(); int __builtin_ia32_pcomltub(); int __builtin_ia32_pcomltud(); int __builtin_ia32_pcomltuq(); int __builtin_ia32_pcomltuw(); int __builtin_ia32_pcomltw(); int __builtin_ia32_pcomneqb(); int __builtin_ia32_pcomneqd(); int __builtin_ia32_pcomneqq(); int __builtin_ia32_pcomnequb(); int __builtin_ia32_pcomnequd(); int __builtin_ia32_pcomnequq(); int __builtin_ia32_pcomnequw(); int __builtin_ia32_pcomneqw(); int __builtin_ia32_pcomtrueb(); int __builtin_ia32_pcomtrued(); int __builtin_ia32_pcomtrueq(); int __builtin_ia32_pcomtrueub(); int __builtin_ia32_pcomtrueud(); int __builtin_ia32_pcomtrueuq(); int __builtin_ia32_pcomtrueuw(); int __builtin_ia32_pcomtruew(); int __builtin_ia32_permpd(); int __builtin_ia32_permps(); int __builtin_ia32_phaddbd(); int __builtin_ia32_phaddbq(); int __builtin_ia32_phaddbw(); int __builtin_ia32_phadddq(); int __builtin_ia32_phaddubd(); int __builtin_ia32_phaddubq(); int __builtin_ia32_phaddubw(); int __builtin_ia32_phaddudq(); int __builtin_ia32_phadduwd(); int __builtin_ia32_phadduwq(); int __builtin_ia32_phaddwd(); int __builtin_ia32_phaddwq(); int __builtin_ia32_phsubbw(); int __builtin_ia32_phsubdq(); int __builtin_ia32_phsubwd(); int __builtin_ia32_pmacsdd(); int __builtin_ia32_pmacsdqh(); int __builtin_ia32_pmacsdql(); int __builtin_ia32_pmacssdd(); int __builtin_ia32_pmacssdqh(); int __builtin_ia32_pmacssdql(); int __builtin_ia32_pmacsswd(); int __builtin_ia32_pmacssww(); int __builtin_ia32_pmacswd(); int __builtin_ia32_pmacsww(); int __builtin_ia32_pmadcsswd(); int __builtin_ia32_pmadcswd(); int __builtin_ia32_pperm(); int __builtin_ia32_protb(); int __builtin_ia32_protd(); int __builtin_ia32_protq(); int __builtin_ia32_protw(); int __builtin_ia32_pshab(); int __builtin_ia32_pshad(); int __builtin_ia32_pshaq(); int __builtin_ia32_pshaw(); int __builtin_ia32_pshlb(); int __builtin_ia32_pshld(); int __builtin_ia32_pshlq(); int __builtin_ia32_pshlw(); double __builtin_ia32_vec_ext_v2df(__gcc_v2df, int); __gcc_di __builtin_ia32_vec_ext_v2di(__gcc_v2di, int); float __builtin_ia32_vec_ext_v4sf(__gcc_v4sf, int); int __builtin_ia32_vec_ext_v4si(__gcc_v4si, int); // clang-format on <|start_filename|>regression/cbmc-concurrency/svcomp13_read_write_lock_safe/main.c<|end_filename|> /* Testcase from Threader's distribution. For details see: http://www.model.in.tum.de/~popeea/research/threader This file is adapted from the example introduced in the paper: Thread-Modular Verification for Shared-Memory Programs by <NAME>, <NAME>, <NAME>. */ int w=0, r=0, x, y; void __VERIFIER_atomic_take_write_lock() { __VERIFIER_assume(w==0 && r==0); w = 1; } void __VERIFIER_atomic_take_read_lock() { __VERIFIER_assume(w==0); r = r+1; } void __VERIFIER_atomic_release_read_lock() { r = r-1; } void *writer() { //writer __VERIFIER_atomic_take_write_lock(); x = 3; w = 0; } void *reader() { //reader int l; __VERIFIER_atomic_take_read_lock(); l = x; y = l; assert(y == x); __VERIFIER_atomic_release_read_lock(); } int main() { __CPROVER_ASYNC_1: writer(); __CPROVER_ASYNC_2: reader(); __CPROVER_ASYNC_3: writer(); __CPROVER_ASYNC_4: reader(); return 0; } <|start_filename|>regression/contracts/assigns_enforce_malloc_01/main.c<|end_filename|> #include <stdlib.h> int f(int *a) __CPROVER_assigns() { a = (int *)malloc(sizeof(int)); *a = 5; } int main() { int m = 4; f(&m); return 0; } <|start_filename|>regression/cbmc/pragma_cprover_enable1/main.c<|end_filename|> int main() { int x; int y[1]; #pragma CPROVER check push #pragma CPROVER check enable "bounds" #pragma CPROVER check enable "signed-overflow" // generate assertions for the following statement x = x + y[1]; #pragma CPROVER check pop // but do not generate assertions for this one x = y[1]; return x; } <|start_filename|>regression/cbmc/pragma_cprover3/main.c<|end_filename|> #include <stdlib.h> int main() { char *p = malloc(sizeof(*p)); char *q; #pragma CPROVER check push #pragma CPROVER check disable "pointer-primitive" // do not generate checks for the following statements if(__CPROVER_r_ok(p, sizeof(*p) + 2)) { } #pragma CPROVER check pop // no checks are generated for the following statement as the behaviour is // always defined if(__CPROVER_same_object(p, q)) { } // generate check and fail on the following statements if(__CPROVER_r_ok(q, 1)) { } } <|start_filename|>regression/ansi-c/asm2/main.c<|end_filename|> // this is a GCC extension int main() { int x, y; #ifdef __GNUC__ asm goto ("jc %l[error];" : : "r"(x), "r"(&y) : "memory" : error); asm # 11 __inline volatile("jc %l[error];" : : "r"(x), "r"(&y) : "memory" : error); #endif error: return 0; } <|start_filename|>regression/cbmc-primitives/forall_6231_4/test.c<|end_filename|> #include <assert.h> #include <stdlib.h> // Similar to the previous tests in forall_6231_1 but this one aims to check // the antecedent of the forall expression to make sure that checks are being // generated correctly for it. // clang-format off int main() { char *a = malloc(10); int n; // BUG: In https://github.com/diffblue/cbmc/issues/6231, it was reported that // no checks would be performed on the derefence inside the quantified statement, // even when explicitly requested via for instance `--pointer-check`, because // we would simply skip over these quantified statements in goto-check. assert( __CPROVER_forall { int i ; (0 <= i && i < (n / 0)) /* (n / 0) should be caught by --div-by-zero-check */ ==> *(a+i) == *(a+i) } ); } // clang-format on <|start_filename|>regression/contracts/replace-nondet-return-value/main.c<|end_filename|> int cmp(int i1, int i2) // clang-format off __CPROVER_ensures((i1 == i2) ==> (__CPROVER_return_value == 0)) __CPROVER_ensures((i1 != i2) ==> (__CPROVER_return_value == -1)) // clang-format on { if(i1 == i2) return 0; else return -1; } int main() { int ret = -1; ret = cmp(0, 0); __CPROVER_assert(ret == 0, "expecting SUCCESS"); ret = cmp(0, 1); __CPROVER_assert(ret == 0, "expecting FAILURE"); __CPROVER_assert(ret == -1, "expecting SUCCESS"); __CPROVER_assert(0, "expecting FAILURE"); return 0; } <|start_filename|>src/goto-programs/link_goto_model.h<|end_filename|> /*******************************************************************\ Module: Read Goto Programs Author: <NAME>, <EMAIL> \*******************************************************************/ /// \file /// Read Goto Programs #ifndef CPROVER_GOTO_PROGRAMS_LINK_GOTO_MODEL_H #define CPROVER_GOTO_PROGRAMS_LINK_GOTO_MODEL_H #include <util/nodiscard.h> #include <util/replace_symbol.h> class goto_modelt; class message_handlert; /// Link goto model \p src into goto model \p dest, invalidating \p src in this /// process. Linking may require updates to object types contained in \p dest, /// which need to be applied using \ref finalize_linking. /// \return nullopt if linking fails, else a (possibly empty) collection of /// replacements to be applied. NODISCARD optionalt<replace_symbolt::expr_mapt> link_goto_model(goto_modelt &dest, goto_modelt &&src, message_handlert &); /// Apply \p type_updates to \p dest, where \p type_updates were constructed /// from one or more calls to \p link_goto_model. void finalize_linking( goto_modelt &dest, const replace_symbolt::expr_mapt &type_updates); #endif // CPROVER_GOTO_PROGRAMS_LINK_GOTO_MODEL_H <|start_filename|>src/linking/linking.h<|end_filename|> /*******************************************************************\ Module: ANSI-C Linking Author: <NAME>, <EMAIL> \*******************************************************************/ /// \file /// ANSI-C Linking #ifndef CPROVER_LINKING_LINKING_H #define CPROVER_LINKING_LINKING_H class message_handlert; class symbol_tablet; /// Merges the symbol table \p new_symbol_table into \p dest_symbol_table, /// renaming symbols from \p new_symbol_table when necessary. /// \return True, iff linking failed with unresolvable conflicts. bool linking( symbol_tablet &dest_symbol_table, const symbol_tablet &new_symbol_table, message_handlert &message_handler); #endif // CPROVER_LINKING_LINKING_H <|start_filename|>regression/contracts/quantifiers-loop-02/main.c<|end_filename|> #include <assert.h> #define MAX_ARRAY_SIZE 3 void main() { int N, a[MAX_ARRAY_SIZE]; __CPROVER_assume(0 <= N && N < MAX_ARRAY_SIZE); for(int i = 0; i < N; ++i) // clang-format off __CPROVER_assigns(i, __CPROVER_POINTER_OBJECT(a)) __CPROVER_loop_invariant( (0 <= i) && (i <= N) && __CPROVER_forall { int k; (0 <= k && k < i) ==> a[k] == 1 } ) // clang-format on { a[i] = 1; } // clang-format off assert(__CPROVER_forall { int k; (0 <= k && k < N) ==> a[k] == 1 }); // clang-format on int k; __CPROVER_assume(0 <= k && k < N); assert(a[k] == 1); } <|start_filename|>regression/contracts/assigns-replace-malloc-zero/main.c<|end_filename|> #include <stdlib.h> // returns the index at which the write was performed if any // -1 otherwise int foo(char *a, int size) // clang-format off __CPROVER_requires(0 <= size && size <= __CPROVER_max_malloc_size) __CPROVER_requires(a == NULL || __CPROVER_rw_ok(a, size)) __CPROVER_assigns(__CPROVER_POINTER_OBJECT(a)) __CPROVER_ensures( a && __CPROVER_return_value >= 0 ==> a[__CPROVER_return_value] == 0) // clang-format on { if(!a) return -1; int i; if(0 <= i && i < size) { a[i] = 0; return i; } return -1; } int main() { int size; if(size < 0) size = 0; if(size > __CPROVER_max_malloc_size) size = __CPROVER_max_malloc_size; char *a = malloc(size * sizeof(*a)); int res = foo(a, size); if(a && res >= 0) __CPROVER_assert(a[res] == 0, "expecting SUCCESS"); return 0; } <|start_filename|>regression/contracts/assigns_enforce_arrays_05/main.c<|end_filename|> void assigns_ptr(int *x) { *x = 200; } void uses_assigns(int a[], int i, int len) // clang-format off __CPROVER_requires(0 <= i && i < len) __CPROVER_assigns(*(&a[i])) // clang-format on { int *ptr = &(a[i]); assigns_ptr(ptr); } int main() { int arr[10]; int i; __CPROVER_assume(0 <= i && i < 10); uses_assigns(arr, i, 10); return 0; } <|start_filename|>regression/goto-instrument/document-properties-basic/main.c<|end_filename|> #include <assert.h> int main(int argc, char **argv) { assert(1 == 1); return 0; }
Kafva/cbmc
<|start_filename|>src/BuddyBoxThread.h<|end_filename|> // // BuddyBoxThread.h // BuddyBox-PPM // // Created by <NAME> on 1/10/13. // Copyright (c) 2013 <NAME>. All rights reserved. // #ifndef BuddyBox_PPM_BuddyBoxThread_h #define BuddyBox_PPM_BuddyBoxThread_h #include "PortAudioStream.h" #include "BuddyBox.h" #include <pthread.h> typedef struct { PortAudioStream pas; BuddyBox bb; pthread_t buddyBoxThread; unsigned int deviceChannel; unsigned int sampleRate; unsigned int running; unsigned int inputEnabled; unsigned int outputEnabled; } PASBuddyBox; void initializeBuddyBoxThread(PASBuddyBox *pasBB, int testmode); void startBuddyBoxThread(PASBuddyBox *pasBB); void stopBuddyBoxThread(PASBuddyBox *pasBB); void joinBuddyBoxThread(PASBuddyBox *pasBB); void cleanupBuddyBoxThread(PASBuddyBox *pasBB); void* runBuddyBoxThread(void *arguments); unsigned int isBuddyBoxThreadRunning(PASBuddyBox *pasBB); unsigned int isBuddyBoxThreadCalibrated(PASBuddyBox *pasBB); void setBuddyBoxThreadOutputChannelCount(PASBuddyBox *pasBB, unsigned int channelCount); void setBuddyBoxThreadOutputChannelValue(PASBuddyBox *pasBB, unsigned int channel, float channelValue); unsigned int getBuddyBoxThreadInputChannelCount(PASBuddyBox *pasBB); float getBuddyBoxThreadInputChannelValue(PASBuddyBox *pasBB, unsigned int channel); void disableBuddyBoxThreadInput(PASBuddyBox *pasBB); void enableBuddyBoxThreadInput(PASBuddyBox *pasBB); void disableBuddyBoxThreadOutput(PASBuddyBox *pasBB); void enableBuddyBoxThreadOutput(PASBuddyBox *pasBB); #endif <|start_filename|>Makefile<|end_filename|> CFLAGS:=-Wall CFILES:=$(wildcard src/*.c) OBJS:=$(patsubst src/%.c,objs/%.o,$(CFILES)) HEADERS:=$(wildcard src/*.h) INCLUDES:=/usr/local/include LIBS:=$(wildcard $(OS)/*.a) LINK_FLAGS:=src/libportaudio.a OS:=$(shell uname) ifeq ($(OS),Darwin) LINK_FLAGS:=$(LINK_FLAGS) -framework CoreAudio -framework AudioToolbox -framework AudioUnit -framework CoreServices -framework IOKit endif all: macPPM macPPM: $(HEADERS) $(OBJS) $(LIBS) $(CC) $(LINK_FLAGS) $(CFLAGS) -o $@ $(OBJS) $(LIBS) objs: -rm -rf objs mkdir objs objs/%.o: src/%.c $(HEADERS) objs $(CC) $(CFLAGS) -I $(INCLUDES) -c -o $@ $< clean: -rm -f macPPM -rm -rf objs <|start_filename|>src/BuddyBox.c<|end_filename|> // // BuddyBox.c // BuddyBox // // Created by <NAME> on 12/23/12. // Copyright (c) 2012 <NAME>. All rights reserved. // #include "BuddyBox.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> void initializeBuddyBox(BuddyBox *bb, unsigned int sampleRate) { int i; printf("BuddyBox:\tInitializing.\n"); bb->active = 1; bb->negativeShift = 0; bb->sampleRate = sampleRate; bb->input = SIGNAL_LOW; bb->lastInput = SIGNAL_LOW; bb->inputChannel = 0; bb->inputChannelCount = 0; bb->outputChannelCount = 0; bb->inputSampleCount = 0; bb->outputSampleCount = 0; bb->elapsedInputSampleCounts = 0; bb->maxElapsedInputSampleCount = 0; bb->lastInputEdgeSampleCount = 0; bb->inputSynchroFrameCount = 0; bb->badInputFrameCount = 0; bb->outputOverflowSampleCount = 0; for (i = 0; i < MAX_CHANNELS; i++) bb->inputChannelBuffer[i] = 0; for (i = 0; i < MAX_CHANNELS; i++) bb->outputChannelBuffer[i] = 0; bb->minInputSample = 0.0f; bb->maxInputSample = 0.0f; for (i = 0; i < MAX_CHANNELS; i++) bb->inputChannelValues[i] = 0.0f; allocateOutputOverflowBuffer(bb); } void allocateOutputOverflowBuffer(BuddyBox *bb) { bb->outputOverflowBufferSize = OVERFLOW_SAMPLES; bb->outputOverflowBuffer = (float *) malloc(bb->outputOverflowBufferSize * sizeof(float)); if(bb->outputOverflowBuffer == NULL) { printf("BuddyBox:\tCould Not Allocate Output Overflow Buffer.\n"); exit(1); } memset(bb->outputOverflowBuffer, 0, bb->outputOverflowBufferSize * sizeof(float)); } void readBufferIntoBuddyBoxInputChannelBuffer(BuddyBox *bb, float* buffer, unsigned int bufferSize) { float localMinSample, localMaxSample; unsigned int i, localMaxElapsedCount, localNegativeShift; detectBuddyBoxInputTimeout(bb, buffer, bufferSize); localMinSample = 0.0f; localMaxSample = 0.0f; localMaxElapsedCount = 0; localNegativeShift = 0; for (i = 0; bb->active && i < bufferSize; i++, bb->inputSampleCount++) { processBuddyBoxRawInput(bb, buffer[i]); localMinSample = getBuddyBoxLocalMinSample(buffer[i], localMinSample); localMaxSample = getBuddyBoxLocalMaxSample(buffer[i], localMaxSample); localMaxElapsedCount = getBuddyBoxLocalMaxElapsedInputSampleCount(bb, localMaxElapsedCount, bufferSize); localNegativeShift = getBuddyBoxLocalNegativeShift(bb, localMaxElapsedCount, buffer[i]); if (isBuddyBoxInputEdge(bb, buffer[i])) processBuddyBoxInputEdge(bb); } if (isBuddyBoxInputCalibrating(bb)) calibrateBuddyBoxInput(bb, localMinSample, localMaxSample, localMaxElapsedCount, localNegativeShift); } void detectBuddyBoxInputTimeout(BuddyBox *bb, float* buffer, unsigned int bufferSize) { unsigned int i; for (i = 0; i < bufferSize; i++) if (isBuddyBoxRawInputAboveNoiseThreshold(buffer[i])) return; if (!isBuddyBoxInputCalibrating(bb)) handleBuddyBoxInputTimeout(bb); } unsigned int isBuddyBoxRawInputAboveNoiseThreshold(float bufferSample) { return (getBuddyBoxSampleMagnitude(bufferSample) > SIGNAL_NOISE_THRESHOLD); } void handleBuddyBoxInputTimeout(BuddyBox *bb) { printf("BuddyBox:\tInput Timeout.\n"); disconnectBuddyBox(bb); } float getBuddyBoxSampleMagnitude(float sample) { return fabs(sample); } float getBuddyBoxLocalMinSample(float bufferSample, float localMinSample) { return (bufferSample < localMinSample) ? bufferSample : localMinSample; } float getBuddyBoxLocalMaxSample(float bufferSample, float localMaxSample) { return (bufferSample > localMaxSample) ? bufferSample : localMaxSample; } float getBuddyBoxLocalMaxElapsedInputSampleCount(BuddyBox *bb, unsigned int localMaxElapsedCount, unsigned int bufferSize) { return (bb->elapsedInputSampleCounts > localMaxElapsedCount && bb->elapsedInputSampleCounts < bufferSize) ? bb->elapsedInputSampleCounts : localMaxElapsedCount; } unsigned int getBuddyBoxLocalNegativeShift(BuddyBox *bb, unsigned int localMaxElapsedCount, float bufferSample) { return (localMaxElapsedCount > bb->maxElapsedInputSampleCount) ? (bufferSample > 0.0f) : bb->negativeShift; } void processBuddyBoxRawInput(BuddyBox *bb, float bufferSample) { bb->lastInput = bb->input; bb->input = isBuddyBoxRawInputHigh(bb, bufferSample) ? SIGNAL_HIGH : SIGNAL_LOW; } unsigned int isBuddyBoxInputEdge(BuddyBox *bb, float bufferSample) { return (bb->input != bb->lastInput); } unsigned int isBuddyBoxRawInputHigh(BuddyBox *bb, float bufferSample) { if (bb->negativeShift) return (isBuddyBoxRawInputAboveNoiseThreshold(bufferSample) && bufferSample < (bb->maxInputSample + bb->minInputSample) / 2); else return (isBuddyBoxRawInputAboveNoiseThreshold(bufferSample) && bufferSample > (bb->maxInputSample + bb->minInputSample) / 2); } void processBuddyBoxInputEdge(BuddyBox *bb) { updateBuddyBoxElapsedInputSampleCounts(bb); if (isBuddyBoxInputHigh(bb)) processHighBuddyBoxInput(bb); bb->lastInputEdgeSampleCount = bb->inputSampleCount; } void updateBuddyBoxElapsedInputSampleCounts(BuddyBox *bb) { if (bb->lastInputEdgeSampleCount > bb->inputSampleCount) bb->elapsedInputSampleCounts = bb->inputSampleCount + (MAXUINT - bb->lastInputEdgeSampleCount); else bb->elapsedInputSampleCounts = bb->inputSampleCount - bb->lastInputEdgeSampleCount; } unsigned int isBuddyBoxInputHigh(BuddyBox *bb) { return (bb->input == SIGNAL_HIGH); } void processHighBuddyBoxInput(BuddyBox *bb) { if (isBuddyBoxInputSynchroFrame(bb)) processBuddyBoxInputSynchroFrame(bb); else { if (isBuddyBoxInputChannelValid(bb)) storeBuddyBoxInputChannel(bb); else if (!isBuddyBoxInputCalibrating(bb)) handleInvalidBuddyBoxInputChannel(bb); targetNextBuddyBoxInputChannel(bb); } } unsigned int isBuddyBoxInputSynchroFrame(BuddyBox *bb) { return (bb->inputChannel >= MIN_CHANNELS && (bb->elapsedInputSampleCounts > bb->maxElapsedInputSampleCount / 2)); } void processBuddyBoxInputSynchroFrame(BuddyBox *bb) { bb->inputSynchroFrameCount++; if (!isBuddyBoxInputCalibrating(bb)) { if (!isBuddyBoxInputChannelCountValid(bb)) handleInvalidBuddyBoxInputChannelCount(bb); else processBuddyBoxInputFrame(bb); } else if (isBuddyBoxInputChannelValid(bb)) storeBuddyBoxInputChannelCount(bb); targetNextBuddyBoxInputFrame(bb); } unsigned int isBuddyBoxInputChannelCountValid(BuddyBox *bb) { return (bb->inputChannel == bb->inputChannelCount); } void storeBuddyBoxInputChannelCount(BuddyBox *bb) { bb->inputChannelCount = bb->inputChannel; } void handleInvalidBuddyBoxInputChannelCount(BuddyBox *bb) { bb->badInputFrameCount++; if (!isBuddyBoxInputViable(bb)) { printf("BuddyBox:\tInput Channel Count Changed from %d to %d.\n", bb->inputChannelCount, bb->inputChannel); disconnectBuddyBox(bb); } } unsigned int isBuddyBoxInputViable(BuddyBox *bb) { return (bb->badInputFrameCount < BAD_FRAME_THRESHOLD); } void targetNextBuddyBoxInputFrame(BuddyBox *bb) { bb->inputChannel = 0; } unsigned int isBuddyBoxInputChannelValid(BuddyBox *bb) { return (bb->inputChannel < MAX_CHANNELS); } void processBuddyBoxInputFrame(BuddyBox *bb) { unsigned int i, chanelDuration; for (i = 0; i < bb->inputChannelCount; i++) { chanelDuration = bb->inputChannelBuffer[i] * MICROSECONDS_PER_SECOND / bb->sampleRate; if (chanelDuration < CHANNEL_MIN_DURATION) bb->inputChannelValues[i] = 0.0f; else if (chanelDuration > CHANNEL_MAX_DURATION) bb->inputChannelValues[i] = 1.0f; else bb->inputChannelValues[i] = (float) (chanelDuration - CHANNEL_MIN_DURATION) / (CHANNEL_MAX_DURATION - CHANNEL_MIN_DURATION); } bb->badInputFrameCount = 0; } void storeBuddyBoxInputChannel(BuddyBox *bb) { bb->inputChannelBuffer[bb->inputChannel] = bb->elapsedInputSampleCounts; } void handleInvalidBuddyBoxInputChannel(BuddyBox *bb) { bb->badInputFrameCount++; if (!isBuddyBoxInputViable(bb)) { printf("BuddyBox:\tInvalid Input Channel Received.\n"); disconnectBuddyBox(bb); } targetNextBuddyBoxInputFrame(bb); } void targetNextBuddyBoxInputChannel(BuddyBox *bb) { bb->inputChannel++; } unsigned int isBuddyBoxInputCalibrating(BuddyBox *bb) { return (bb->inputSynchroFrameCount < CALIBRATION_FRAMES); } void calibrateBuddyBoxInput(BuddyBox *bb, float localMinSample, float localMaxSample, unsigned int localMaxElapsedCount, unsigned int localNegativeShift) { bb->minInputSample = localMinSample; bb->maxInputSample = localMaxSample; bb->maxElapsedInputSampleCount = localMaxElapsedCount; bb->negativeShift = localNegativeShift; } void setBuddyBoxOutputChannelValue(BuddyBox *bb, unsigned int channel, float channelValue) { unsigned int channelDuration; channelDuration = channelValue / 1.0f * (CHANNEL_MAX_DURATION - CHANNEL_MIN_DURATION) + CHANNEL_MIN_DURATION; setBuddyBoxOutputChannelDuration(bb, channel, channelDuration); } void setBuddyBoxOutputChannelDuration(BuddyBox *bb, unsigned int channel, unsigned int channelDuration) { if (channel < MAX_CHANNELS) { if (channelDuration > CHANNEL_MAX_DURATION) channelDuration = CHANNEL_MAX_DURATION; else if (channelDuration < CHANNEL_MIN_DURATION) channelDuration = CHANNEL_MIN_DURATION; bb->outputChannelBuffer[channel] = channelDuration * bb->sampleRate / MICROSECONDS_PER_SECOND; } } void writeBuddyBoxOutputChannelBufferIntoBuffer(BuddyBox *bb, float buffer[], unsigned int bufferSize) { unsigned int bufferSampleCount; bufferSampleCount = writeBuddyBoxOverflowBufferIntoBuffer(bb, buffer); while (bufferSampleCount < bufferSize) bufferSampleCount += writeBuddyBoxOutputChannelBufferIntoBufferFrame(bb, buffer, bufferSize, bufferSampleCount); } unsigned int writeBuddyBoxOverflowBufferIntoBuffer(BuddyBox *bb, float* buffer) { unsigned int i; for (i = 0; i < bb->outputOverflowSampleCount; i++) buffer[i] = bb->outputOverflowBuffer[i]; bb->outputOverflowSampleCount = 0; return i; } unsigned int writeBuddyBoxOutputChannelBufferIntoBufferFrame(BuddyBox *bb, float buffer[], unsigned int bufferSize, unsigned int bufferSampleCount) { unsigned int frameSampleCount; frameSampleCount = writeBuddyBoxOutputChannelBufferIntoBufferChannels(bb, buffer, bufferSize, bufferSampleCount); frameSampleCount += writeBuddyBoxOutputChannelBufferIntoBufferSynchro(bb, buffer, bufferSize, bufferSampleCount, frameSampleCount); return frameSampleCount; } unsigned int writeBuddyBoxOutputChannelBufferIntoBufferChannels(BuddyBox *bb, float buffer[], unsigned int bufferSize, unsigned int bufferSampleCount) { unsigned int channel, channelsSampleCount; channelsSampleCount = 0; for (channel = 0; channel < bb->outputChannelCount; channel++) channelsSampleCount += writeBuddyBoxOutputChannelBufferIntoBufferChannel(bb, buffer, bufferSize, bufferSampleCount, channelsSampleCount, channel); return channelsSampleCount; } unsigned int writeBuddyBoxOutputChannelBufferIntoBufferChannel(BuddyBox *bb, float buffer[], unsigned int bufferSize, unsigned int bufferSampleCount, unsigned int channelsSampleCount, unsigned int channel) { unsigned int channelSampleCount; channelSampleCount = writeBuddyBoxChannelSeperatorIntoBufferChannel(bb, buffer, bufferSize, bufferSampleCount + channelsSampleCount); channelSampleCount += writeBuddyBoxChannelDurationIntoBufferChannel(bb, buffer, bufferSize, bufferSampleCount + channelsSampleCount + channelSampleCount, bb->outputChannelBuffer[channel]); return channelSampleCount; } unsigned int writeBuddyBoxChannelSeperatorIntoBufferChannel(BuddyBox *bb, float buffer[], unsigned int bufferSize, unsigned int startBufferSample) { return writeBuddyBoxSignalsToBufferOrOverflowBuffer(bb, buffer, bufferSize, startBufferSample, 0, SEPARATOR_DURATION * bb->sampleRate / MICROSECONDS_PER_SECOND, SIGNAL_HIGH_FLOAT); } unsigned int writeBuddyBoxSignalsToBufferOrOverflowBuffer(BuddyBox *bb, float *buffer, unsigned int bufferSize, unsigned int startBufferSample, unsigned int comparatorOffset, unsigned int endBufferSampleOffset, float signal) { unsigned int i; for (i = 0; i + comparatorOffset < endBufferSampleOffset; i++) writeBuddyBoxSignalToBufferOrOverflowBuffer(bb, buffer, bufferSize, startBufferSample + i, signal); return i; } void writeBuddyBoxSignalToBufferOrOverflowBuffer(BuddyBox *bb, float buffer[], unsigned int bufferSize, unsigned int bufferSample, float signal) { if (bufferSample < bufferSize) writeBuddyBoxSignalToBuffer(bb, buffer, bufferSample, signal); else writeBuddyBoxSignalToOverflowBuffer(bb, bufferSample - bufferSize, signal); } void writeBuddyBoxSignalToBuffer(BuddyBox *bb, float buffer[], unsigned int bufferSample, float signal) { buffer[bufferSample] = signal; bb->outputSampleCount++; } void writeBuddyBoxSignalToOverflowBuffer(BuddyBox *bb, unsigned int bufferSample, float signal) { bb->outputOverflowBuffer[bufferSample] = signal; bb->outputOverflowSampleCount++; } unsigned int writeBuddyBoxChannelDurationIntoBufferChannel(BuddyBox *bb, float buffer[], unsigned int bufferSize, unsigned int startBufferSample, unsigned int endBufferSampleOffset) { return writeBuddyBoxSignalsToBufferOrOverflowBuffer(bb, buffer, bufferSize, startBufferSample, 0, endBufferSampleOffset, SIGNAL_LOW_FLOAT); } unsigned int writeBuddyBoxOutputChannelBufferIntoBufferSynchro(BuddyBox *bb, float buffer[], unsigned int bufferSize, unsigned int bufferSampleCount, unsigned int frameSampleCount) { unsigned int synchroSampleCount; synchroSampleCount = writeBuddyBoxChannelSeperatorIntoBufferChannel(bb, buffer, bufferSize, bufferSampleCount + frameSampleCount); synchroSampleCount += writeBuddyBoxSynchroIntoBufferSynchro(bb, buffer, bufferSize, bufferSampleCount + frameSampleCount + synchroSampleCount, frameSampleCount); return synchroSampleCount; } unsigned int writeBuddyBoxSynchroIntoBufferSynchro(BuddyBox *bb, float buffer[], unsigned int bufferSize, unsigned int startBufferSample, unsigned int comparatorOffset) { return writeBuddyBoxSignalsToBufferOrOverflowBuffer(bb, buffer, bufferSize, startBufferSample, comparatorOffset, bb->sampleRate * FRAME_DURATION / MICROSECONDS_PER_SECOND, SIGNAL_LOW_FLOAT); } void disconnectBuddyBox(BuddyBox *bb) { bb->active = 0; free(bb->outputOverflowBuffer); printf("BuddyBox:\tDisconnected.\n"); } <|start_filename|>src/PortAudioStream.c<|end_filename|> // // PortAudioStream.c // BuddyBox // // Created by <NAME> on 12/23/12. // Copyright (c) 2012 <NAME>. All rights reserved. // #include "PortAudioStream.h" #include "pa_mac_core.h" #include <stdio.h> #include <stdlib.h> #include <string.h> void initializePortAudioStream(PortAudioStream *pas, unsigned int sampleRate, unsigned int deviceChannel ) { PaStreamParameters inputParameters, outputParameters; pas->sampleRate = sampleRate; allocatePortAudioStreamBuffer(pas); initializePortAudio(pas); configurePortAudioInputParameters(&inputParameters); configurePortAudioOutputParameters(&outputParameters); openPortAudioStream(pas, outputParameters, inputParameters, deviceChannel); } void allocatePortAudioStreamBuffer(PortAudioStream *pas) { pas->bufferSize = FRAMES_PER_BUFFER * NUM_CHANNELS; pas->bufferedSamples = (float *) malloc(pas->bufferSize * sizeof(float)); if(pas->bufferedSamples == NULL) { printf("PortAudioStream:\tCould Not Allocate Sample Buffer.\n"); exit(1); } memset(pas->bufferedSamples, 0, pas->bufferSize * sizeof(float)); } void initializePortAudio(PortAudioStream *pas) { PaError err; err = Pa_Initialize(); if(err != paNoError) handlePortAudioStreamInitializationError(pas, err); } void handlePortAudioStreamInitializationError(PortAudioStream *pas, PaError err) { terminatePortAudioStream(pas); fprintf(stderr, "PortAudioStream:\tAn error occured.\n"); fprintf(stderr, "Error number:\t%d\n", err); fprintf(stderr, "Error message:\t%s\n", Pa_GetErrorText(err)); exit(-1); } void terminatePortAudioStream(PortAudioStream *pas) { if(pas->stream) { Pa_AbortStream(pas->stream); Pa_CloseStream(pas->stream); } free(pas->bufferedSamples); Pa_Terminate(); } void configurePortAudioInputParameters(PaStreamParameters *inputParameters) { inputParameters->device = Pa_GetDefaultInputDevice(); inputParameters->channelCount = NUM_CHANNELS; inputParameters->sampleFormat = PA_SAMPLE_TYPE; inputParameters->suggestedLatency = Pa_GetDeviceInfo(inputParameters->device)->defaultHighInputLatency ; inputParameters->hostApiSpecificStreamInfo = NULL; } void configurePortAudioOutputParameters(PaStreamParameters *outputParameters) { outputParameters->device = Pa_GetDefaultOutputDevice(); outputParameters->channelCount = NUM_CHANNELS; outputParameters->sampleFormat = PA_SAMPLE_TYPE; outputParameters->suggestedLatency = Pa_GetDeviceInfo(outputParameters->device)->defaultHighOutputLatency; outputParameters->hostApiSpecificStreamInfo = NULL; } void openPortAudioStream(PortAudioStream *pas, PaStreamParameters outputParameters, PaStreamParameters inputParameters, unsigned int deviceChannel) { PaError err; PaMacCoreStreamInfo data; if (deviceChannel){ const SInt32 map[] = { 1, -1 }; // swap input channel (i.e. left/right) PaMacCore_SetupStreamInfo( &data, 0 ); // mit flag PaMacCore_GetChannelName statt 0 nur 'reale' sample rates moelich. weniger cpu mit 0 PaMacCore_SetupChannelMap(&data, map, 2 ); inputParameters.hostApiSpecificStreamInfo = &data; outputParameters.hostApiSpecificStreamInfo = &data; //error if not set for output as well } err = Pa_OpenStream( &pas->stream, &inputParameters, &outputParameters, pas->sampleRate, FRAMES_PER_BUFFER, paClipOff, // we won't output out of range samples so don't bother clipping them NULL, // no callback, use blocking API NULL // no callback, so no callback userData ); // for(int i=0; i<2; ++i ) // printf( "channel %d name: %s\n", i, PaMacCore_GetChannelName( PaMacCore_GetStreamInputDevice(&pas), 0, true ) ); //not working.... if(err != paNoError) handlePortAudioStreamInitializationError(pas, err); err = Pa_StartStream(pas->stream); if(err != paNoError) handlePortAudioStreamInitializationError(pas, err); } unsigned int readPortAudioStream(PortAudioStream *pas) { PaError err; err = Pa_ReadStream(pas->stream, pas->bufferedSamples, FRAMES_PER_BUFFER); if(err && CHECK_OVERFLOW) return handlePortAudioStreamFlowError(pas, err); else return 1; } unsigned int handlePortAudioStreamFlowError(PortAudioStream *pas, PaError err) { terminatePortAudioStream(pas); if(err & paInputOverflow) fprintf(stderr, "PortAudioStream:\tInput Overflow.\n"); if(err & paOutputUnderflow) fprintf(stderr, "PortAudioStream:\tOutput Underflow.\n"); return 0; } unsigned int writePortAudioStream(PortAudioStream *pas) { PaError err; err = Pa_WriteStream(pas->stream, pas->bufferedSamples, FRAMES_PER_BUFFER); if(err && CHECK_UNDERFLOW) return handlePortAudioStreamFlowError(pas, err); else return 1; } void closePortAudioStream(PortAudioStream *pas) { PaError err; err = Pa_StopStream(pas->stream); if(err != paNoError) handlePortAudioStreamInitializationError(pas, err); terminatePortAudioStream(pas); } <|start_filename|>src/main.c<|end_filename|> // // main.c // BuddyBox // // Created by <NAME> on 12/23/12. // Copyright (c) 2012 <NAME>. All rights reserved. // /* Modifications to integrate with foohid (c) 2016 by albhm */ #include "BuddyBoxThread.h" #include <signal.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <IOKit/IOKitLib.h> static const unsigned int DEFAULT_SAMPLE_RATE = 96000; static unsigned int running = 1; /* alternative joystick report descriptor: 0x05, 0x01, // USAGE_PAGE (Generic Desktop) 0x09, 0x04, // USAGE (Joystick) 0xa1, 0x01, // COLLECTION (Application) 0x15, 0x81, // LOGICAL_MINIMUM (-127) 0x25, 0x7f, // LOGICAL_MAXIMUM (127) 0x05, 0x01, // USAGE_PAGE (Generic Desktop) 0x09, 0x01, // USAGE (Pointer) 0xa1, 0x00, // COLLECTION (Physical) 0x09, 0x30, // USAGE (X) 0x09, 0x31, // USAGE (Y) 0x09, 0x32, // USAGE (Ry) for throttle 1 0x09, 0x33, // USAGE (Rz) for throttle 2 0x75, 0x08, // REPORT_SIZE (8) 0x95, 0x04, // REPORT_COUNT (2) 0x81, 0x02, // INPUT (Data,Var,Abs) 0xc0, // END_COLLECTION 0x05, 0x09, // USAGE_PAGE (Button) 0x19, 0x01, // USAGE_MINIMUM (Button 1) 0x29, 0x08, // USAGE_MAXIMUM (Button 8) 0x15, 0x00, // LOGICAL_MINIMUM (0) 0x25, 0x01, // LOGICAL_MAXIMUM (1) 0x75, 0x01, // REPORT_SIZE (1) 0x95, 0x08, // REPORT_COUNT (8) 0x55, 0x00, // UNIT_EXPONENT (0) 0x65, 0x00, // UNIT (None) 0x81, 0x02, // INPUT (Data,Var,Abs) 0xc0 // END_COLLECTION */ unsigned char joy_reportdesc[] = { 0x05, 0x01, // USAGE_PAGE (Generic Desktop) 0x09, 0x04, // USAGE (Joystick) 0xa1, 0x01, // COLLECTION (Application) 0xa1, 0x00, // COLLECTION (Physical) 0x05, 0x01, // USAGE_PAGE (Generic Desktop) 0x09, 0x30, // USAGE (X) 0x09, 0x31, // USAGE (Y) 0x09, 0x32, // USAGE 0x09, 0x33, // USAGE 0x15, 0x81, // LOGICAL_MINIMUM (-127) 0x25, 0x7f, // LOGICAL_MAXIMUM (127) 0x75, 0x08, // REPORT_SIZE (8) 0x95, 0x04, // REPORT_COUNT (4) 0x81, 0x02, // INPUT (Data,Var,Abs) 0x05, 0x09, // USAGE_PAGE (Button) 0x19, 0x01, // USAGE_MINIMUM (Button 1) 0x29, 0x08, // USAGE_MAXIMUM (Button 8) 0x15, 0x00, // LOGICAL_MINIMUM (0) 0x25, 0x01, // LOGICAL_MAXIMUM (1) 0x75, 0x01, // REPORT_SIZE (1) 0x95, 0x08, // REPORT_COUNT (8) 0x55, 0x00, // UNIT_EXPONENT (0) 0x65, 0x00, // UNIT (None) 0x81, 0x02, // INPUT (Data,Var,Abs) 0xc0, // END_COLLECTION 0xc0 // END_COLLECTION }; struct joystick_report_t { int8_t x; int8_t y; int8_t ry; int8_t rz; uint8_t buttons; }; #define SERVICE_NAME "it_unbit_foohid" #define FOOHID_CREATE 0 // create selector #define FOOHID_DESTROY 1 #define FOOHID_SEND 2 // send selector #define DEVICE_NAME "Foohid Virtual Joystick" #define DEVICE_SN "SN 123456" void intHandler(int sig) { running = 0; } void generateOutput(PASBuddyBox *pasBB) { unsigned int i, outputChannelCount; outputChannelCount = getBuddyBoxThreadInputChannelCount(pasBB); setBuddyBoxThreadOutputChannelCount(pasBB, outputChannelCount); for (i = 0; i < outputChannelCount; i++) setBuddyBoxThreadOutputChannelValue(pasBB, i, getBuddyBoxThreadInputChannelValue(pasBB, i)); } void displayInput(PASBuddyBox *pasBB) { unsigned int i, inputChannelCount; inputChannelCount = getBuddyBoxThreadInputChannelCount(pasBB); for (i = 0; i < inputChannelCount; i++) printf("%f\t", getBuddyBoxThreadInputChannelValue(pasBB, i)); printf("\n"); } void initVirtualJoystick () { } int main(int argc, const char * argv[]) { int testmode = 0; signal(SIGKILL, intHandler); signal(SIGINT, intHandler); PASBuddyBox pasBB; pasBB.sampleRate = DEFAULT_SAMPLE_RATE; pasBB.deviceChannel = 1; int opt=0; while ((opt = getopt(argc, (char * const *) argv, "tc")) != -1) { switch (opt) { case 't': testmode = 1; break; case 'c': pasBB.deviceChannel = 0; break; default: fprintf(stderr, "Usage: %s [-tc] [sample rate]\n", argv[0]); exit(1); } } if (optind < argc) pasBB.sampleRate = (unsigned int) strtol(argv[optind], NULL, 0); printf ("Usage: macPPM [-t(est) -c(hannel)] [sample rate] \n current sample rate: %d \n\n", pasBB.sampleRate); initializeBuddyBoxThread(&pasBB, testmode); printf ("\n"); // to set output apart from the deprecation warning of libportaudio //////// init joystick ////// io_iterator_t iterator; io_service_t service; io_connect_t connect; // Get a reference to the IOService kern_return_t ret = IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching(SERVICE_NAME), &iterator); if (ret != KERN_SUCCESS) { printf("Unable to access IOService.\n"); exit(1); } // Iterate till success int found = 0; while ((service = IOIteratorNext(iterator)) != IO_OBJECT_NULL) { ret = IOServiceOpen(service, mach_task_self(), 0, &connect); if (ret == KERN_SUCCESS) { found = 1; break; } IOObjectRelease(service); } IOObjectRelease(iterator); if (!found) { printf("Unable to open IOService.\n"); exit(1); } //printf("size rep desc: %d .\n", sizeof(joy_reportdesc)); // Fill up the input arguments. uint32_t input_count = 8; uint64_t input[input_count]; input[0] = (uint64_t) strdup(DEVICE_NAME); // device name input[1] = strlen((char *)input[0]); // name length input[2] = (uint64_t) joy_reportdesc; // report descriptor input[3] = sizeof(joy_reportdesc); // report descriptor len input[4] = (uint64_t) strdup(DEVICE_SN); // serial number input[5] = strlen((char *)input[4]); // serial number len input[6] = (uint64_t) 2; // vendor ID input[7] = (uint64_t) 3; // device ID ret = IOConnectCallScalarMethod(connect, FOOHID_CREATE, input, input_count, NULL, 0); if (ret != KERN_SUCCESS) { printf("Unable to create HID device - hope that it exists already. \n"); // exit(1); } // Arguments to be passed through the HID message. struct joystick_report_t joy; uint32_t send_count = 4; uint64_t send[send_count]; send[0] = (uint64_t)input[0]; // device name send[1] = strlen((char *)input[0]); // name length send[2] = (uint64_t) &joy; // mouse struct send[3] = sizeof(struct joystick_report_t); // mouse struct len /////////////end init joystick//////////// while(running) { startBuddyBoxThread(&pasBB); while(running && isBuddyBoxThreadRunning(&pasBB)) { if (testmode) generateOutput(&pasBB); if (isBuddyBoxThreadCalibrated(&pasBB)) { if (testmode) { displayInput(&pasBB); unsigned int i, inputChannelCount; inputChannelCount = getBuddyBoxThreadInputChannelCount(&pasBB); for (i = 0; i < inputChannelCount; i++) printf("%f\t", getBuddyBoxThreadInputChannelValue(&pasBB, i)); printf("\n"); } // This is for a NineEagles J6 Pro Transmitter (6 channels); may need to adjust for other models joy.buttons = (getBuddyBoxThreadInputChannelValue(&pasBB, 4)>0.5) ? 1:0; joy.x = (getBuddyBoxThreadInputChannelValue(&pasBB, 0)-0.5) * 255; joy.y = (getBuddyBoxThreadInputChannelValue(&pasBB, 1)-0.5) * 255; joy.ry = (getBuddyBoxThreadInputChannelValue(&pasBB, 3)-0.5) * 255; joy.rz = (getBuddyBoxThreadInputChannelValue(&pasBB, 2)-0.5) * 255; ret = IOConnectCallScalarMethod(connect, FOOHID_SEND, send, send_count, NULL, 0); if (ret != KERN_SUCCESS) { printf("Unable to send message to HID device.\n"); } } usleep(20000); } stopBuddyBoxThread(&pasBB); joinBuddyBoxThread(&pasBB); } cleanupBuddyBoxThread(&pasBB); ret = IOConnectCallScalarMethod(connect, FOOHID_DESTROY, input,2,NULL,0); if (ret != KERN_SUCCESS) { printf("Unable to destroy HID device. \n"); } printf("Program Halted...\n"); } <|start_filename|>src/PortAudioStream.h<|end_filename|> // // PortAudio.h // BuddyBox // // Created by <NAME> on 12/23/12. // Copyright (c) 2012 <NAME>. All rights reserved. // // Sample Rate Notes: // (glitchy) Line In @ 192kHz -> resolution of ~154 per channel // (glitchy) Line In @ 176.4kHz -> resolution of ~143 per channel // (glitchy) Line In @ 176.4kHz -> resolution of ~128 per channel // Line In @ 132.3kHz -> resolution of ~107 per channel // Line In @ 124.0kHz -> resolution of ~100 per channel // Line In @ 88.2kHz -> resolution of ~72 per channel // Line In @ 44.1kHz -> resolution of ~36 per channel #ifndef BuddyBox_PortAudio_h #define BuddyBox_PortAudio_h #include "portaudio.h" #define CHECK_OVERFLOW (0) // Not checking for overflow #define CHECK_UNDERFLOW (0) // Not checking for underflow #define PA_SAMPLE_TYPE paFloat32 static const unsigned int FRAMES_PER_BUFFER = 4096; static const unsigned int NUM_CHANNELS = 1; typedef struct { unsigned int sampleRate; float* bufferedSamples; unsigned int bufferSize; PaStream* stream; } PortAudioStream; void initializePortAudioStream(PortAudioStream *pas, unsigned int sampleRate, unsigned int deviceChannel); void allocatePortAudioStreamBuffer(PortAudioStream *pas); void initializePortAudio(PortAudioStream *pas); void handlePortAudioStreamInitializationError(PortAudioStream *pas, PaError err); void terminatePortAudioStream(PortAudioStream *pas); void configurePortAudioInputParameters(PaStreamParameters *inputParameters); void configurePortAudioOutputParameters(PaStreamParameters *outputParameters); void openPortAudioStream(PortAudioStream *pas, PaStreamParameters outputParameters, PaStreamParameters inputParameters, unsigned int deviceChannel); unsigned int readPortAudioStream(PortAudioStream *pas); unsigned int handlePortAudioStreamFlowError(PortAudioStream *pas, PaError err); unsigned int writePortAudioStream(PortAudioStream *pas); void closePortAudioStream(PortAudioStream *pas); #endif
sinan454/Sinan-opan
<|start_filename|>test/convert_test.dart<|end_filename|> // Copyright (c) 2021, Google LLC. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:osc/src/convert.dart'; import 'package:osc/src/message.dart'; import 'package:test/test.dart'; void main() { group('codecs', () { group('forType', () { test('unknown', () { expect(() => DataCodec.forType('x'), throwsA(const TypeMatcher<ArgumentError>())); }); }); group('messages', () { group('encode', () { test('empty', () { final message = OSCMessage('/empty', arguments: []); expect(oscMessageCodec.encode(message), [47, 101, 109, 112, 116, 121, 0, 0, 44, 0, 0, 0]); }); test('int', () { final message = OSCMessage('/int', arguments: [99]); expect(oscMessageCodec.encode(message), [47, 105, 110, 116, 0, 0, 0, 0, 44, 105, 0, 0, 0, 0, 0, 99]); }); }); group('decode', () { test('empty', () { final message = oscMessageCodec .decode([47, 101, 109, 112, 116, 121, 0, 0, 44, 0, 0, 0]); expect(message.address, '/empty'); expect(message.arguments, isEmpty); }); test('int', () { final message = oscMessageCodec.decode( [47, 105, 110, 116, 0, 0, 0, 0, 44, 105, 0, 0, 0, 0, 0, 99]); expect(message.address, '/int'); expect(message.arguments, <Object>[99]); }); }); }); group('equality', () { test('==', () { final message1 = OSCMessage('/baz', arguments: ['foo', 'bar', 1, 2, 3]); final message2 = OSCMessage('/baz', arguments: ['foo', 'bar', 1, 2, 3]); expect(message1, message2); }); test('hash', () { final message1 = OSCMessage('/baz', arguments: ['foo', 'bar', 1, 2, 3]); final message2 = OSCMessage('/baz', arguments: ['foo', 'bar', 1, 2, 3, 4]); expect(message1.hashCode, isNot(equals(message2.hashCode))); }); }); group('ints', () { test('decode', () { expect(intCodec.decoder.convert([0, 0, 0, 13]), 13); }); test('encode', () { expect(intCodec.encoder.convert(13), [0, 0, 0, 13]); }); }); group('floats', () { test('decode', () { expect(floatCodec.decoder.convert([66, 246, 230, 102]), closeTo(123.45, 1e-5)); }); test('encode', () { expect(floatCodec.encoder.convert(123.45), [66, 246, 230, 102]); }); }); group('strings', () { test('decode', () { expect(stringCodec.decoder.convert([102, 111, 111]), 'foo'); }); test('encode', () { expect(stringCodec.encoder.convert('foo'), [102, 111, 111, 0]); }); }); }); } <|start_filename|>example/sendosc.dart<|end_filename|> import 'dart:io'; import 'package:ansicolor/ansicolor.dart'; import 'package:osc/src/convert.dart'; import 'package:osc/src/message.dart'; void main(List<String> args) { if (args.length < 5 && (args.length & 1 == 0)) { printUsage(); exit(15); } final destination = InternetAddress(args[0]); final port = int.parse(args[1]); final address = args[2]; final arguments = <Object>[]; for (var i = 3; i < args.length; i += 2) { arguments.add(DataCodec.forType(args[i]).toValue(args[i + 1])); } final message = OSCMessage(address, arguments: arguments); RawDatagramSocket.bind(InternetAddress.anyIPv4, 0).then((socket) { final greenPen = AnsiPen()..green(bold: true); final yellowPen = AnsiPen()..yellow(); print( yellowPen('Sending from ${socket.address.address}:${socket.port}...')); final bytes = message.toBytes(); socket.send(bytes, destination, port); print(greenPen('$bytes')); }); } void printUsage() { print('Usage : sendosc host port path [[type] [param]] ...'); }
Nean0901/osc
<|start_filename|>users.go<|end_filename|> // Copyright 2018 <NAME> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "bufio" "errors" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "strconv" "strings" ) type user struct { Uid int Gid int Username string Name string HomeDir string Shell string Groups []group } type group struct { Gid int Name string } func lookupUser(name string) (*user, error) { f, err := os.Open("/etc/passwd") if err != nil { return nil, err } defer f.Close() var u *user s := bufio.NewScanner(f) for s.Scan() { l := s.Text() if !strings.HasPrefix(l, name+":") || strings.HasPrefix(l, "#") { continue } u, err = parsePasswd(l) if err == nil { break } } if err := s.Err(); err != nil { return nil, err } if u == nil { return nil, fmt.Errorf("user %q not found", name) } f, err = os.Open("/etc/group") if err != nil { return u, nil } defer f.Close() s = bufio.NewScanner(f) for s.Scan() { l := s.Text() // wireshark:x:974:mero sp := strings.SplitN(l, ":", 5) if len(sp) != 4 || strings.HasPrefix(l, "#") { continue } members := strings.Split(sp[3], ",") for _, uname := range members { if uname != name { continue } gid, err := strconv.Atoi(sp[2]) if err != nil { continue } u.Groups = append(u.Groups, group{ Gid: gid, Name: sp[0], }) break } } return u, nil } func parsePasswd(line string) (*user, error) { // mero:x:1000:1000:<NAME>:/home/mero:/usr/bin/zsh sp := strings.SplitN(line, ":", 8) if len(sp) != 7 { return nil, errors.New("wrong number of fields") } uid, err := strconv.Atoi(sp[2]) if err != nil { return nil, fmt.Errorf("invalid uid: %v", err) } gid, err := strconv.Atoi(sp[3]) if err != nil { return nil, fmt.Errorf("invalid gid: %v", err) } i := strings.IndexByte(sp[4], ',') if i >= 0 { sp[4] = sp[4][:i] } return &user{ Uid: uid, Gid: gid, Username: sp[0], Name: sp[4], HomeDir: sp[5], Shell: sp[6], }, nil } func createUser(name string, pubkey []byte) (u *user, err error) { args := []string{"-m", name} if *newGroup != "" { args = append(args, "-g", *newGroup) } if err = exec.Command("useradd", args...).Run(); err != nil { return nil, err } defer func() { if err != nil { exec.Command("userdel", "-r", "-Z", "-f", name) } }() if u, err = lookupUser(name); err != nil { return nil, err } if err = os.MkdirAll(filepath.Join(u.HomeDir, ".ssh"), 0700); err != nil { return nil, err } if err = os.Chown(filepath.Join(u.HomeDir, ".ssh"), u.Uid, u.Gid); err != nil { return nil, err } if err = ioutil.WriteFile(filepath.Join(u.HomeDir, ".ssh", "authorized_keys"), pubkey, 0600); err != nil { return nil, err } if err = os.Chown(filepath.Join(u.HomeDir, ".ssh", "authorized_keys"), u.Uid, u.Gid); err != nil { return nil, err } return u, nil } <|start_filename|>simsim.go<|end_filename|> // Copyright 2018 <NAME> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "bufio" "bytes" "crypto/rand" "encoding/pem" "errors" "flag" "fmt" "io" "io/ioutil" "log" "net" "os" "os/exec" "path/filepath" "strings" "syscall" "github.com/kr/pty" "golang.org/x/crypto/ed25519" "golang.org/x/crypto/ssh" ) func main() { log.SetFlags(log.LstdFlags | log.Lshortfile) if err := run(); err != nil { log.Fatal(err) } } var newGroup = flag.String("group", "", "Primary group of newly created users") func run() error { listen := flag.String("listen", "0.0.0.0:22", "Port to listen on") flag.Parse() cfg := ssh.ServerConfig{ PublicKeyCallback: checkPublicKey, AuthLogCallback: logAuth, } if err := ed25519key(&cfg); err != nil { return err } l, err := net.Listen("tcp", *listen) if err != nil { return err } for { c, err := l.Accept() if err != nil { return err } go serveConn(c, cfg) } } func ed25519key(cfg *ssh.ServerConfig) error { buf, err := ioutil.ReadFile("ed25519.key") if err == nil { return pemKey(cfg, buf) } pub, priv, err := ed25519.GenerateKey(rand.Reader) if err != nil { return err } sig, err := ssh.NewSignerFromSigner(priv) if err != nil { return err } w := new(bytes.Buffer) w.WriteString("openssh-key-v1\x00") key := struct { Pub []byte Priv []byte Comment string Pad []byte `ssh:"rest"` }{pub, priv, "", nil} pk1 := struct { Check1 uint32 Check2 uint32 Keytype string Rest []byte `ssh:"rest"` }{0, 0, ssh.KeyAlgoED25519, ssh.Marshal(key)} k := struct { CipherName string KdfName string KdfOpts string NumKeys uint32 PubKey []byte PrivKeyBlock []byte }{"none", "none", "", 1, nil, ssh.Marshal(&pk1)} w.Write(ssh.Marshal(k)) buf = pem.EncodeToMemory(&pem.Block{Type: "OPENSSH PRIVATE KEY", Bytes: w.Bytes()}) if err := ioutil.WriteFile("ed25519.key", buf, 0600); err != nil { return err } cfg.AddHostKey(sig) return nil } func pemKey(cfg *ssh.ServerConfig, b []byte) error { k, err := ssh.ParsePrivateKey(b) if err != nil { return err } cfg.AddHostKey(k) return nil } func logAuth(md ssh.ConnMetadata, method string, err error) { if err == nil { log.Printf("Successful %q login for %q from %v", method, md.User(), md.RemoteAddr()) return } log.Printf("Failed %q login for %q from %v: %v", method, md.User(), md.RemoteAddr(), err) } func checkPublicKey(md ssh.ConnMetadata, pub ssh.PublicKey) (*ssh.Permissions, error) { username := strings.ToLower(md.User()) for _, r := range username { if r < 'a' || r > 'z' { return nil, errors.New("invalid user name") } } u, err := lookupUser(username) if err != nil { if _, err = createUser(username, ssh.MarshalAuthorizedKey(pub)); err != nil { return nil, err } return permissions, nil } f, err := os.Open(filepath.Join(u.HomeDir, ".ssh", "authorized_keys")) if err != nil { return nil, err } defer f.Close() s := bufio.NewScanner(f) for s.Scan() { k, _, _, _, err := ssh.ParseAuthorizedKey(s.Bytes()) if err != nil { return nil, err } if k.Type() != pub.Type() { continue } if bytes.Compare(k.Marshal(), pub.Marshal()) == 0 { return permissions, nil } } if err := s.Err(); err != nil { return nil, err } return nil, errors.New("unauthorized") } var permissions = &ssh.Permissions{} func serveConn(c net.Conn, cfg ssh.ServerConfig) { defer c.Close() sc, ch, reqs, err := ssh.NewServerConn(c, &cfg) if err != nil { log.Println(err) return } defer sc.Close() u, err := lookupUser(strings.ToLower(sc.User())) if err != nil { log.Println(err) return } for { select { case nch, ok := <-ch: if !ok { log.Println("conn closed") return } log.Printf("NewChannel(%q): %q", nch.ChannelType(), nch.ExtraData()) switch nch.ChannelType() { case "session": ch, reqs, err := nch.Accept() go serveSession(u, ch, reqs, err) default: nch.Reject(ssh.UnknownChannelType, fmt.Sprintf("channel type %q not supported", nch.ChannelType())) } case req, ok := <-reqs: if !ok { log.Println("conn closed") return } log.Printf("Request(%q, %v): %q", req.Type, req.WantReply, req.Payload) if err := req.Reply(false, []byte(fmt.Sprintf("request type %q not supported", req.Type))); err != nil { log.Println(err) return } } } } func serveSession(u *user, ch ssh.Channel, reqs <-chan *ssh.Request, err error) { defer func() { ch.Close() for range reqs { } }() if err != nil { log.Println(err) return } var ( env []string allocPty *requestPTY ) done := make(chan struct{}) for { var req *ssh.Request select { case r, ok := <-reqs: if !ok { return } req = r case <-done: return } r, err := parseRequest(req.Type, req.Payload) if err != nil { log.Println(err) req.Reply(false, []byte(err.Error())) continue } switch r := r.(type) { case *requestEnv: env = append(env, fmt.Sprintf("%s=%s", r.Name, r.Value)) case *requestPTY: if allocPty != nil { err = errors.New("duplicate pty-req") } allocPty = r env = append(env, "TERM="+r.Term) case *requestExec: cmd := exec.Command("/bin/sh", "-c", r.Command) err = runCommand(ch, cmd, env, u, allocPty, done) if err == nil { defer cmd.Process.Kill() } case *requestShell: shell := u.Shell if shell == "" { shell = "/bin/bash" } cmd := exec.Command(shell, "-l") err = runCommand(ch, cmd, env, u, allocPty, done) if err == nil { defer cmd.Process.Kill() } default: err = fmt.Errorf("request type %T not handled") } if err != nil { req.Reply(false, []byte(err.Error())) } else if req.WantReply { req.Reply(true, nil) } } } func runCommand(ch ssh.Channel, cmd *exec.Cmd, env []string, u *user, allocPty *requestPTY, done chan struct{}) error { cmd.Dir = u.HomeDir cmd.Env = env cmd.SysProcAttr = &syscall.SysProcAttr{ Credential: &syscall.Credential{ Uid: uint32(u.Uid), Gid: uint32(u.Gid), }, Setsid: true, } for _, g := range u.Groups { cmd.SysProcAttr.Credential.Groups = append(cmd.SysProcAttr.Credential.Groups, uint32(g.Gid)) } var ( err error closer func() error ) if allocPty != nil { var f *os.File f, err = pty.StartWithSize(cmd, &pty.Winsize{Rows: uint16(allocPty.Rows), Cols: uint16(allocPty.Columns), X: uint16(allocPty.Height), Y: uint16(allocPty.Width)}) closer = f.Close go io.Copy(ch, f) go io.Copy(f, ch) } else { stdin, e := cmd.StdinPipe() if e != nil { return err } stdout, e := cmd.StdoutPipe() if e != nil { return err } stderr, e := cmd.StderrPipe() if e != nil { return err } closer = func() error { stdin.Close() stdout.Close() stderr.Close() return nil } err = cmd.Start() go io.Copy(stdin, ch) go io.Copy(ch, stdout) go io.Copy(ch, stderr) } if err == nil { go func() { if err := cmd.Wait(); err != nil { log.Println(err) } if ws, ok := cmd.ProcessState.Sys().(syscall.WaitStatus); ok { st := &struct{ Status uint32 }{uint32(ws.ExitStatus())} ch.SendRequest("exit-status", false, ssh.Marshal(st)) } if closer != nil { closer() } close(done) }() } return err } type requestPTY struct { Term string Columns uint32 Rows uint32 Width uint32 Height uint32 Modes string } type requestEnv struct { Name string Value string } type requestShell struct { } type requestExec struct { Command string } func parseRequest(t string, b []byte) (interface{}, error) { var r interface{} switch t { case "pty-req": r = new(requestPTY) case "env": r = new(requestEnv) case "exec": r = new(requestExec) case "shell": return new(requestShell), nil default: return nil, fmt.Errorf("request %q not supported", t) } return r, ssh.Unmarshal(b, r) }
Merovius/simsim
<|start_filename|>src/ini-parse.c<|end_filename|> #include <stdio.h> #include <stdlib.h> #include <regex.h> #include <string.h> #include <io500-util.h> uint32_t u_ini_gen_hash(ini_section_t ** sections){ uint32_t value = 0; for( ini_section_t ** ps = sections ; *ps != NULL; ps++){ ini_section_t * s = *ps; for( ini_option_t * o = s->option ; o->name != NULL; o++){ if(o->default_val){ // compute a hash for each option individually to make it invariant to reordered options u_hash_update_key_val(& value, o->name, o->default_val); } } } return value; } void u_ini_parse_file(char const * file, ini_section_t** cfg, ini_call_back_f func, char ** out_data){ struct stat statbuf; int ret = stat(file, & statbuf); if(ret != 0){ FATAL("Cannot open config file %s\n", file); } char * buff = ""; if(statbuf.st_size > 0){ buff = malloc(statbuf.st_size + 1); if(! buff){ FATAL("Cannot malloc();") } FILE * f = fopen(file, "r"); if(ret != 0){ FATAL("Cannot open config file %s\n", file); } ret = fread(buff, statbuf.st_size, 1, f); fclose(f); if( ret != 1 ){ FATAL("Couldn't read config file %s\n", file); } buff[statbuf.st_size] = '\0'; } ret = u_parse_ini(buff, cfg, func); if (ret != 0){ FATAL("Couldn't parse config file %s\n", file); } if (out_data){ *out_data = strdup(buff); } free(buff); } int u_parse_ini(char const * data, ini_section_t ** sections, ini_call_back_f cb_func){ int reti; // prepare regexes regex_t r_section, r_int, r_uint, r_str, r_empty; reti = regcomp(& r_section, "^[[:space:]]*\\[[[:space:]]*([0-9a-zA-Z_-]+)[[:space:]]*\\][[:space:]]*([[:space:]][#;].*)?$", REG_EXTENDED); if (reti){ FATAL("Could not compile regex\n"); } reti = regcomp(& r_str, "^[[:space:]]*([0-9a-zA-Z_.-]+)[[:space:]]*=[[:space:]]*([^#;]*)[[:space:]]*([[:space:]][#;].*)?$", REG_EXTENDED); if (reti){ FATAL("Could not compile regex\n"); } reti = regcomp(& r_int, "^[-]?[0-9]+$", REG_EXTENDED); if (reti){ FATAL("Could not compile regex\n"); } reti = regcomp(& r_uint, "^[0-9]+$", REG_EXTENDED); if (reti){ FATAL("Could not compile regex\n"); } reti = regcomp(& r_empty, "^[[:space:]]*([#;].*)?$", REG_EXTENDED); if (reti){ FATAL("Could not compile regex\n"); } char * copy = strdup(data); char * token; char * saveptr; token = strtok_r(copy, "\n", &saveptr); ini_section_t * section = NULL; int line = 0; char * lastsaveptr = saveptr; // parse each line while(token){ line += 1 + ((token - lastsaveptr) > 0 ? (token - lastsaveptr) : 0); // strtok skips whole lines lastsaveptr = saveptr; regmatch_t match[3]; DEBUG_INFO("Parsing: \"%s\"\n", token); reti = regexec(&r_section, token, 2, match, 0); if (reti == 0) { char * sname = token + match[1].rm_so; token[match[1].rm_eo] = '\0'; DEBUG_INFO("Section: \"%s\"\n", sname); if(cb_func){ // callback handler for sections cb_func(1, sname, NULL); } if( sections ){ section = NULL; for( ini_section_t ** ps = sections ; *ps != NULL; ps++){ if(strcasecmp((*ps)->name, sname) == 0){ section = *ps; break; } } if(section == NULL){ ERROR("Parsing error in line %d, unknown section %s\n", line, sname); return 1; } } token = strtok_r(NULL, "\n", &saveptr); continue; } reti = regexec(&r_str, token, 3, match, 0); if (reti == 0) { char * var = token + match[1].rm_so; char * val = token + match[2].rm_so; token[match[1].rm_eo] = '\0'; // trim whitespace from the right of the string value for(int p = match[2].rm_eo; p >= match[2].rm_so; p--){ switch(token[p]){ case ' ': case '\t': case '\r': case '\0': token[p] = '\0'; break; default: goto end_loop; } } end_loop: DEBUG_INFO("Var: \"%s\"=\"%s\"\n", var, val); if(*val == '\0'){ // no argument token = strtok_r(NULL, "\n", &saveptr); continue; } if(cb_func){ // callback handler for variables cb_func(0, var, val); } if( ! sections ) continue; if(section == NULL){ ERROR("Parsing error in line %d, variable assigned outside section\n", line); return 1; } ini_option_t * option = section->option; for( ; option->name != NULL; option++){ if(strcasecmp(option->name, var) == 0){ break; } } if(option->name == NULL){ ERROR("Parsing error in section %s line %d, unknown option \"%s\" with value \"%s\"\n", section->name, line, var, val); return 1; } if(option->type == INI_INT){ reti = regexec(& r_int, val, 0, NULL, 0); if(reti != 0){ ERROR("Parsing error in section %s line %d, option %s expects integer, received \"%s\"\n", section->name, line, var, val); return 1; } }else if(option->type == INI_UINT || option->type == INI_UINT64){ reti = regexec(& r_uint, val, 0, NULL, 0); if(reti != 0){ ERROR("Parsing error in section %s line %d, option %s expects integer >= 0, received \"%s\"\n", section->name, line, var, val); return 1; } }else if(option->type == INI_BOOL){ if(strcasecmp(val, "true") == 0 || strcmp(val, "1") == 0){ val = "TRUE"; }else if(strcasecmp(val, "false") == 0 || strcmp(val, "0") == 0){ val = "FALSE"; }else{ ERROR("Parsing error in section %s line %d, option %s expects bool (true|false), received \"%s\"\n", section->name, line, var, val); return 1; } } // assign new value option->default_val = strdup(val); token = strtok_r(NULL, "\n", &saveptr); continue; } if(sections){ // must be the empty line reti = regexec(&r_empty, token, 0, NULL, 0); if (reti != 0) { ERROR("Parsing error in section %s line %d, unexpected content: \"%s\"\n", section ? section->name : "no_section", line, token); return 1; } } token = strtok_r(NULL, "\n", &saveptr); } // check for mandatory options and assign values int error = 0; if(sections){ for( ini_section_t ** ps = sections ; *ps != NULL; ps++){ ini_section_t * s = *ps; for( ini_option_t * o = s->option ; o->name != NULL; o++){ if( o->mandatory && o->default_val == NULL ){ ERROR("[%s]: The mandatory option \"%s\" is not set\n", s->name, o->name); error = 1; } if(! o->var) continue; // assing a value to the configuration if(o->default_val){ switch(o->type){ case(INI_INT):{ *(int*) o->var = atoi(o->default_val); break; }case(INI_UINT):{ *(unsigned*) o->var = atoi(o->default_val); break; }case(INI_UINT64):{ *(uint64_t*) o->var = (uint64_t) atoll(o->default_val); break; }case(INI_BOOL):{ *(int*) o->var = o->default_val[0] == 'T'; break; }case(INI_STRING):{ *(char**) o->var = o->default_val; break; } } }else{ switch(o->type){ case(INI_INT):{ *(int*) o->var = INI_UNSET_INT; break; }case(INI_UINT):{ *(unsigned*) o->var = INI_UNSET_UINT; break; }case(INI_UINT64):{ *(uint64_t*) o->var = INI_UNSET_UINT64; break; }case(INI_BOOL):{ *(int*) o->var = INI_UNSET_BOOL; break; }case(INI_STRING):{ *(char**) o->var = INI_UNSET_STRING; break; } } } } } } // cleanup regfree(&r_section); regfree(&r_int); regfree(&r_uint); regfree(&r_str); free(copy); return error; } void u_ini_print_values(FILE * fd, ini_section_t ** sections, bool show_help){ for( ini_section_t ** ps = sections ; *ps != NULL; ps++){ ini_section_t * s = *ps; fprintf(fd, "[%s]\n", s->name); for( ini_option_t * o = s->option ; o->name != NULL; o++){ if (o->help && show_help){ fprintf(fd, "# %s\n", o->help); } fprintf(fd, "%s = %s\n", o->name, o->default_val ? o->default_val : ""); } fprintf(fd, "\n"); } } <|start_filename|>src/test/CMakeFiles/metatest.dir/DependInfo.cmake<|end_filename|> # The set of languages for which implicit dependencies are needed: set(CMAKE_DEPENDS_LANGUAGES "C" ) # The set of files for implicit dependencies of each language: set(CMAKE_DEPENDS_CHECK_C "/home/kunkel/ur-git/esiwace/ESD-Middleware/src/backends-metadata/posix/test/metatest.c" "/home/kunkel/ur-git/esiwace/ESD-Middleware/src/backends-metadata/posix/test/CMakeFiles/metatest.dir/metatest.c.o" ) set(CMAKE_C_COMPILER_ID "GNU") # The include file search paths: set(CMAKE_C_TARGET_INCLUDE_PATH "src" "." "src/include" "/usr/include/glib-2.0" "/usr/lib/x86_64-linux-gnu/glib-2.0/include" "deps/smd/include" "/usr/lib/x86_64-linux-gnu/openmpi/include/openmpi" "/usr/lib/x86_64-linux-gnu/openmpi/include" ) # Targets to which this target links. set(CMAKE_TARGET_LINKED_INFO_FILES "/home/kunkel/ur-git/esiwace/ESD-Middleware/src/CMakeFiles/esdm.dir/DependInfo.cmake" "/home/kunkel/ur-git/esiwace/ESD-Middleware/src/backends-data/posix/CMakeFiles/esdmposix.dir/DependInfo.cmake" "/home/kunkel/ur-git/esiwace/ESD-Middleware/src/backends-data/dummy/CMakeFiles/esdmdummy.dir/DependInfo.cmake" "/home/kunkel/ur-git/esiwace/ESD-Middleware/src/backends-metadata/posix/CMakeFiles/esdm-mdposix.dir/DependInfo.cmake" "/home/kunkel/ur-git/esiwace/ESD-Middleware/src/backends-data/pmem/CMakeFiles/esdmpmem.dir/DependInfo.cmake" "/home/kunkel/ur-git/esiwace/ESD-Middleware/src/CMakeFiles/esdmutils.dir/DependInfo.cmake" "/home/kunkel/ur-git/esiwace/ESD-Middleware/deps/smd/src/CMakeFiles/smd.dir/DependInfo.cmake" ) # Fortran module output directory. set(CMAKE_Fortran_TARGET_MODULE_DIR "") <|start_filename|>src/test/CMakeFiles/metatest.dir/cmake_clean.cmake<|end_filename|> file(REMOVE_RECURSE "CMakeFiles/metatest.dir/metatest.c.o" "metatest" "metatest.pdb" ) # Per-language clean rules from dependency scanning. foreach(lang C) include(CMakeFiles/metatest.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <|start_filename|>src/phase_mdtest_hard_delete.c<|end_filename|> #include <sys/stat.h> #include <unistd.h> #include <io500-phase.h> #include <phase_mdtest.h> typedef struct{ opt_mdtest_generic g; mdtest_generic_res res; } opt_mdtest_hard_delete; static opt_mdtest_hard_delete o; static ini_option_t option[] = { {"API", "The API to be used", 0, INI_STRING, NULL, & o.g.api}, {"posix.odirect", "Use ODirect", 0, INI_BOOL, NULL, & o.g.odirect}, {"noRun", "Disable running of this phase", 0, INI_BOOL, NULL, & o.g.no_run}, {NULL} }; static void validate(void){ } static double run(void){ u_argv_t * argv = u_argv_create(); mdtest_hard_add_params(argv); u_argv_push(argv, "-r"); opt_mdtest_hard d = mdtest_hard_o; mdtest_add_generic_params(argv, & d.g, & o.g); if(opt.dry_run || o.g.no_run == 1 || mdtest_hard_o.g.no_run == 1){ u_argv_free(argv); return 0; } FILE * out = u_res_file_prep(p_mdtest_hard_delete.name); p_mdtest_run(argv, out, & o.res, MDTEST_FILE_REMOVE_NUM); return o.res.rate; } u_phase_t p_mdtest_hard_delete = { "mdtest-hard-delete", IO500_PHASE_REMOVE, option, validate, run, 0, .group = IO500_SCORE_MD }; <|start_filename|>src/phase_dbg.c<|end_filename|> #include <io500-phase.h> #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) static ini_option_t option[] = { {"stonewall-time", "Stonewall timer must be "TOSTRING(IO500_MINWRITE)" for a valid result, can be smaller for testing", 0, INI_UINT, TOSTRING(IO500_MINWRITE), & opt.stonewall}, {NULL} }; static void validate(void){ if(opt.stonewall != IO500_MINWRITE && opt.rank == 0){ INVALID("stonewall-time != %us\n", IO500_MINWRITE); } } u_phase_t p_debug = { "debug", IO500_PHASE_DUMMY, option, validate, NULL }; <|start_filename|>src/phase-definitions.h<|end_filename|> static u_phase_t * phases[IO500_PHASES] = { & p_opt, & p_debug, & p_ior_easy, & p_ior_easy_write, & p_mdtest_easy, & p_mdtest_easy_write, & p_timestamp, & p_ior_hard, & p_ior_hard_write, & p_mdtest_hard, & p_mdtest_hard_write, & p_find, & p_ior_easy_read, & p_mdtest_easy_stat, & p_ior_hard_read, & p_mdtest_hard_stat, & p_mdtest_easy_delete, & p_mdtest_hard_read, & p_mdtest_hard_delete }; static ini_section_t ** u_options(void){ ini_section_t ** ini_section = u_malloc(sizeof(ini_section_t*) * (IO500_PHASES + 1)); for(int i=0; i < IO500_PHASES; i++){ ini_section[i] = u_malloc(sizeof(ini_section_t)); ini_section[i]->name = phases[i]->name; ini_section[i]->option = phases[i]->options; } ini_section[IO500_PHASES] = NULL; return ini_section; } <|start_filename|>src/test/metatest.c<|end_filename|> /** * This test uses the generic patterns to verify the high-level interface works as intended */ #include <backends-metadata/posix/md-posix.h> extern esdm_instance_t esdm; int main() { esdm_status ret; char const * cfg = "{\"esdm\": {\"backends\": [" "{" "\"type\": \"DUMMY\"," "\"id\": \"p1\"," "\"target\": \"x\"" "}" "]," "\"metadata\": {" "\"type\": \"metadummy\"," "\"id\": \"md\"," "\"target\": \"./_metadummy\"}}" "}"; esdm_load_config_str(cfg); esdm_init(); //esdm_md_backend_t *b = esdm.modules->metadata_backend; ret = esdm_mkfs(ESDM_FORMAT_PURGE_RECREATE, ESDM_ACCESSIBILITY_GLOBAL); eassert(ret == ESDM_SUCCESS); ret = esdm_mkfs(ESDM_FORMAT_PURGE_RECREATE, ESDM_ACCESSIBILITY_NODELOCAL); eassert(ret == ESDM_SUCCESS); esdm_simple_dspace_t dataspace = esdm_dataspace_2d(50, 100, SMD_DTYPE_UINT64); eassert(dataspace.ptr); esdm_container_t *container; ret = esdm_container_create("testContainer", 1, &container); eassert(ret == ESDM_SUCCESS); esdm_dataset_t *dataset; ret = esdm_dataset_create(container, "testDataset", dataspace.ptr, &dataset); eassert(ret == ESDM_SUCCESS); esdm_fragment_t *f1, *f2, *f3, *f4; { esdm_dataspace_t* space; ret = esdm_dataspace_create_full(2, (int64_t [2]){25, 50}, (int64_t [2]){0, 0}, SMD_DTYPE_UINT64, &space); eassert(ret == ESDM_SUCCESS); ret = esdmI_fragment_create(dataset, space, ea_checked_malloc(esdm_dataspace_total_bytes(space)), &f1); eassert(ret == ESDM_SUCCESS); } { esdm_dataspace_t* space; ret = esdm_dataspace_create_full(2, (int64_t [2]){25, 50}, (int64_t [2]){25, 0}, SMD_DTYPE_UINT64, &space); eassert(ret == ESDM_SUCCESS); ret = esdmI_fragment_create(dataset, space, ea_checked_malloc(esdm_dataspace_total_bytes(space)), &f2); eassert(ret == ESDM_SUCCESS); } { esdm_dataspace_t* space; ret = esdm_dataspace_create_full(2, (int64_t [2]){25, 50}, (int64_t [2]){25, 50}, SMD_DTYPE_UINT64, &space); eassert(ret == ESDM_SUCCESS); ret = esdmI_fragment_create(dataset, space, ea_checked_malloc(esdm_dataspace_total_bytes(space)), &f3); eassert(ret == ESDM_SUCCESS); } { esdm_dataspace_t* space; ret = esdm_dataspace_create_full(2, (int64_t [2]){25, 50}, (int64_t [2]){0, 50}, SMD_DTYPE_UINT64, &space); eassert(ret == ESDM_SUCCESS); ret = esdmI_fragment_create(dataset, space, ea_checked_malloc(esdm_dataspace_total_bytes(space)), &f4); eassert(ret == ESDM_SUCCESS); } //ret = b->callbacks.fragment_update(b, f1); //eassert(ret == ESDM_SUCCESS); //ret = b->callbacks.fragment_update(b, f2); //eassert(ret == ESDM_SUCCESS); //ret = b->callbacks.fragment_update(b, f3); //eassert(ret == ESDM_SUCCESS); //ret = b->callbacks.fragment_update(b, f4); //eassert(ret == ESDM_SUCCESS); //{ // int64_t size[] = {30, 30}; // int64_t offset[] = {10, 10}; // esdm_dataspace_subspace(dataspace, 2, size, offset, &res); //} esdmI_container_destroy(container); esdm_finalize(); return 0; } <|start_filename|>src/phase_mdtest.h<|end_filename|> #ifndef IO500_PHASE_MDTEST_H #define IO500_PHASE_MDTEST_H #include <mdtest.h> #include <io500-util.h> typedef struct{ int no_run; char * api; int odirect; uint64_t files_per_proc; char * command; } opt_mdtest_generic; typedef struct{ double rate; double rate_stonewall; uint64_t items; double time; } mdtest_generic_res; typedef struct{ opt_mdtest_generic g; mdtest_generic_res res; } opt_mdtest_easy; extern opt_mdtest_easy mdtest_easy_o; typedef struct{ opt_mdtest_generic g; mdtest_generic_res res; } opt_mdtest_hard; extern opt_mdtest_hard mdtest_hard_o; void mdtest_add_generic_params(u_argv_t * argv, opt_mdtest_generic * dflt, opt_mdtest_generic * generic); void mdtest_easy_add_params(u_argv_t * argv); void mdtest_hard_add_params(u_argv_t * argv); void p_mdtest_run(u_argv_t * argv, FILE * out, mdtest_generic_res * d, mdtest_test_num_t test); #endif
jyvet/io500
<|start_filename|>leobot_hardware/firmware/STM32F767_Firmware/Core/Src/main.cpp<|end_filename|> /* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "cmsis_os.h" //#include "tim.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "rtos.h" #include <stdio.h> /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); //void MX_FREERTOS_Init(void); /* USER CODE BEGIN PFP */ void LL_Init(void); /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /** * @brief The application entry point. * @retval int */ int main(void) { /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* Enable I-Cache---------------------------------------------------------*/ SCB_EnableICache(); /* Enable D-Cache---------------------------------------------------------*/ SCB_EnableDCache(); /* MCU Configuration--------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface */ LL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); // ToDo: increase speed of MCU to 216 Mhz /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ //MX_TIM2_Init(); /* USER CODE BEGIN 2 */ printf("start\r\n"); /* USER CODE END 2 */ /* Call init function for freertos objects (in freertos.c) */ MX_FREERTOS_Init(); /* Start scheduler */ osKernelStart(); /* We should never get here as control is now taken by the scheduler */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { LL_FLASH_SetLatency(LL_FLASH_LATENCY_7); if(LL_FLASH_GetLatency() != LL_FLASH_LATENCY_7) { Error_Handler(); } LL_PWR_SetRegulVoltageScaling(LL_PWR_REGU_VOLTAGE_SCALE1); LL_PWR_EnableOverDriveMode(); LL_RCC_HSE_EnableBypass(); LL_RCC_HSE_Enable(); /* Wait till HSE is ready */ while(LL_RCC_HSE_IsReady() != 1) { } LL_RCC_PLL_ConfigDomain_SYS(LL_RCC_PLLSOURCE_HSE, LL_RCC_PLLM_DIV_4, 216, LL_RCC_PLLP_DIV_2); LL_RCC_PLL_Enable(); /* Wait till PLL is ready */ while(LL_RCC_PLL_IsReady() != 1) { } LL_RCC_SetAHBPrescaler(LL_RCC_SYSCLK_DIV_1); LL_RCC_SetAPB1Prescaler(LL_RCC_APB1_DIV_4); LL_RCC_SetAPB2Prescaler(LL_RCC_APB2_DIV_2); LL_RCC_SetSysClkSource(LL_RCC_SYS_CLKSOURCE_PLL); /* Wait till System clock is ready */ while(LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_PLL) { } LL_Init1msTick(216000000); LL_SYSTICK_SetClkSource(LL_SYSTICK_CLKSOURCE_HCLK); LL_SetSystemCoreClock(216000000); LL_RCC_SetUSARTClockSource(LL_RCC_USART3_CLKSOURCE_PCLK1); } /* USER CODE BEGIN 4 */ //int __io_putchar(int ch) //{ // return 1; //} void LL_Init(void) { /* This code is moved from HAL_Init */ // ToDo: check if this code can be removed or simplified /* Configure Instruction cache through ART accelerator */ /* Enable the FLASH Adaptive Real-Time memory accelerator. */ /* The ART accelerator is available only for flash access on ITCM interface. */ SET_BIT(FLASH->ACR, FLASH_ACR_ARTEN); /* Enable the FLASH prefetch buffer. */ FLASH->ACR |= FLASH_ACR_PRFTEN; /* HAL_MspInit part of code */ //__HAL_RCC_PWR_CLK_ENABLE(); //APB1 Peripheral Clock Enable //Enable the Low Speed APB (APB1) peripheral clock. //@note After reset, the peripheral clock (used for registers read/write access) // * is disabled and the application software has to enable this clock before // * using it. __IO uint32_t tmpreg; SET_BIT(RCC->APB1ENR, RCC_APB1ENR_WWDGEN); /* Delay after an RCC peripheral clock enabling */ tmpreg = READ_BIT(RCC->APB1ENR, RCC_APB1ENR_WWDGEN); tmpreg = tmpreg; //__HAL_RCC_SYSCFG_CLK_ENABLE(); /** @defgroup RCC_APB2_Clock_Enable_Disable APB2 Peripheral Clock Enable Disable * @brief Enable or disable the High Speed APB (APB2) peripheral clock. * @note After reset, the peripheral clock (used for registers read/write access) * is disabled and the application software has to enable this clock before * using it. * @{ */ SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SYSCFGEN); /* Delay after an RCC peripheral clock enabling */ tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_SYSCFGEN); tmpreg = tmpreg; /* looks line this part of code is configured in FreeRTOS: Make PendSV and SysTick the lowest priority interrupts. */ /* System interrupt init*/ /* PendSV_IRQn interrupt configuration */ //HAL_NVIC_SetPriority(PendSV_IRQn, 15, 0); uint32_t prioritygroup = 0x00; prioritygroup = NVIC_GetPriorityGrouping(); //NVIC_SetPriority(IRQn, NVIC_EncodePriority(prioritygroup, PreemptPriority, SubPriority)); NVIC_SetPriority(PendSV_IRQn, NVIC_EncodePriority(prioritygroup, 15, 0)); } /* USER CODE END 4 */ /** * @brief This function is executed in case of error occurrence. * @retval None */ void Error_Handler(void) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ <|start_filename|>docker/ide/web/Dockerfile<|end_filename|> FROM rosukraine/leobot:latest MAINTAINER "ROS Ukraine Community" LABEL Description="This ROS Kinetic image for LeoBot development with Cloud 9 Web IDE" Vendor="ROS Ukraine" Version="1.0" ARG leobot_aurora_branch ENV leobot_aurora_branch ${leobot_aurora_branch:-"master"} ENV leobot_aurora_script "https://raw.githubusercontent.com/ros-ukraine/aurora/$leobot_aurora_branch/bin/run-ansible.sh" ENV LOCAL_USER_ID 1000 ENV MY_USERNAME user ENV DISPLAY :1.0 ENV QT_X11_NO_MITSHM 1 USER user COPY startup.sh /home/user/ RUN set -x && \ \ echo "Downloading one-liner" && \ wget -O /tmp/oneliner "$( echo "$leobot_aurora_script" | sed 's/#/%23/g' )" && \ chmod 755 /tmp/oneliner && \ \ echo "Installing IDEs and AWS CLI" && \ /tmp/oneliner install_software --debug-branch $leobot_aurora_branch software=[cloud9,gzweb] && \ \ echo "Link models to gzweb folders" && \ pushd /home/user/gzweb/http/client/assets && \ ln -s /home/user/workspace/leobot/base/src/leobot/leobot_description ./leobot_description && \ ln -s /home/user/workspace/leobot/base/src/leobot/leobot_gazebo ./leobot_gazebo && \ popd && \ \ echo "Generating models for visualization" && \ pushd /home/user/gzweb && \ GAZEBO_MODEL_PATH=/home/user/workspace/leobot/base/src/leobot/leobot_gazebo/models npm run deploy --- -m local && \ popd && \ \ echo "Clean up" && \ sudo apt-get clean && \ sudo rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /root/.ansible /root/.gitconfig /root/.cache USER root ENTRYPOINT ["/usr/local/bin/entrypoint.sh"] EXPOSE 8080 8181 8282 8090 9090 CMD ["/home/user/startup.sh"] <|start_filename|>leobot_hardware/include/leobot_hardware/robot_hardware.h<|end_filename|> /** * Copyright 2019 ROS Ukraine * * 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. * */ #ifndef LEOBOT_HARDWARE_ROBOT_HARDWARE_H #define LEOBOT_HARDWARE_ROBOT_HARDWARE_H #include <memory> #include <boost/thread/recursive_mutex.hpp> #include <ros/ros.h> #include <dynamic_reconfigure/server.h> #include <hardware_interface/joint_command_interface.h> #include <hardware_interface/joint_state_interface.h> #include <hardware_interface/robot_hw.h> #include "leobot_msgs/FirmwareStateRead.h" #include "leobot_msgs/FirmwareCommandWrite.h" #include "leobot_hardware/LeobotRobotHardwareConfig.h" namespace leobot_hardware { class LeobotRobotHW : public hardware_interface::RobotHW { public: LeobotRobotHW(); virtual ~LeobotRobotHW(); virtual bool init(ros::NodeHandle &root_nh, ros::NodeHandle &robot_hw_nh); virtual void read(const ros::Time &time, const ros::Duration &period); virtual void write(const ros::Time &time, const ros::Duration &period); private: void firmwareStateCallback(const leobot_msgs::FirmwareStateRead::ConstPtr &message); void dynamicReconfigureCallback(leobot_hardware::LeobotRobotHardwareConfig &config, uint32_t level); void setupDynamicReconfigure(ros::NodeHandle& node_handle); void setupHardwareInterfaces(); void fillFirmwareCommandMessageFromConfig(leobot_hardware::LeobotRobotHardwareConfig &config); hardware_interface::JointStateInterface joint_state_interface; hardware_interface::VelocityJointInterface joint_velocity_interface; ros::Subscriber state_subscriber_; ros::Publisher command_publisher_; static const int JOINTS_COUNT = 4; double command[JOINTS_COUNT]; double position[JOINTS_COUNT]; double velocity[JOINTS_COUNT]; double effort[JOINTS_COUNT]; double hardware_motor_position[JOINTS_COUNT]; double hardware_motor_velocity[JOINTS_COUNT]; double hardware_motor_effort[JOINTS_COUNT]; leobot_msgs::FirmwareCommandWrite firmware_command_message_; std::unique_ptr<dynamic_reconfigure::Server<leobot_hardware::LeobotRobotHardwareConfig>> dynamic_reconfigure_server_; dynamic_reconfigure::Server<leobot_hardware::LeobotRobotHardwareConfig>::CallbackType reconfigure_callback_; leobot_hardware::LeobotRobotHardwareConfig default_dynamic_server_config_; boost::recursive_mutex dynamic_reconfigure_mutex_; }; } // namespace leobot_hardware #endif // LEOBOT_HARDWARE_ROBOT_HARDWARE_H <|start_filename|>docker/ide/intel/Dockerfile<|end_filename|> FROM rosukraine/leobot:latest MAINTAINER "ROS Ukraine Community" LABEL Description="This ROS Kinetic image for LeoBot development with IDEs for Intel Graphic Card" Vendor="ROS Ukraine" Version="1.0" RUN set -x && \ echo "Installing video drivers for user" && \ apt-get update && \ apt-get -y install libgl1-mesa-glx libgl1-mesa-dri && \ usermod -a -G video user && \ echo "Removing cache" && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /home/$MY_USERNAME/.ansible /home/$MY_USERNAME/.gitconfig ENTRYPOINT ["/usr/local/bin/entrypoint.sh"] CMD ["/usr/bin/terminator"] <|start_filename|>docker/ide/nvidia/Dockerfile<|end_filename|> FROM rosukraine/leobot:latest MAINTAINER "ROS Ukraine Community" LABEL Description="This ROS Kinetic image for LeoBot development with IDEs for NVidia Graphic Card" Vendor="ROS Ukraine" Version="1.0" LABEL com.nvidia.volumes.needed="nvidia_driver" ENV PATH /usr/local/nvidia/bin:${PATH} ENV LD_LIBRARY_PATH /usr/local/nvidia/lib:/usr/local/nvidia/lib64:${LD_LIBRARY_PATH} ENTRYPOINT ["/usr/local/bin/entrypoint.sh"] CMD ["/usr/bin/terminator"] <|start_filename|>leobot_web_server/web_content/js/vr.js<|end_filename|> var docelem = document.documentElement; function fs_status() { if (document.fullscreenElement) { return 1; } else if (document.webkitFullscreenElement) { return 1; } else if (document.mozFullScreenElement) { return 1; } else return -1; } function setFullScreen() { if (docelem.requestFullscreen) { docelem.requestFullscreen(); } else if (docelem.mozRequestFullScreen) { docelem.mozRequestFullScreen(); } else if (docelem.webkitRequestFullScreen) { docelem.webkitRequestFullScreen(); } else if (docelem.msRequestFullscreen) { docelem.msRequestFullscreen(); } } document.onclick = function () { if(fs_status() == (-1)){ var conf = confirm("Fullscreen ON?"); if (conf == true) { setFullScreen(); screen.orientation.lock('landscape'); var frameHeight = window.screen.height; var frameWidth = window.screen.width; var frameWidthHalf = Math.round(frameWidth/2); var siteRoot = location.protocol + '//' + location.hostname + ':8090' + '/'; document.getElementById('right_iframe').src = siteRoot + "stream?topic=/stereocamera/right/image_raw&width="+frameWidthHalf+"&height="+frameHeight; document.getElementById('left_iframe').src = siteRoot + "stream?topic=/stereocamera/left/image_raw&width="+frameWidthHalf+"&height="+frameHeight; } }else{ var conf = confirm("Fullscreen OFF?"); if(conf == true){ setFullScreen(); window.screen.unlockOrientation(); } } } var alpha, beta, gamma; // setup event handler to capture the orientation event and store the most recent data in a variable if (window.DeviceOrientationEvent) { // Listen for the deviceorientation event and handle the raw data window.addEventListener('deviceorientation', function(eventData) { gamma = eventData.gamma; alpha = eventData.alpha }, false); }; // Connection to ROS var ros = new ROSLIB.Ros({ url : 'ws://' + window.location.hostname + ':9090' }); ros.on('connection', function() { console.log('Connected to websocket server.'); }); ros.on('error', function(error) { console.log('Error connecting to websocket server: ', error); }); ros.on('close', function() { console.log('Connection to websocket server closed.'); }); var headControl = new ROSLIB.Topic({ ros : ros, name : '/head_position_controller/command', messageType : 'std_msgs/Float64' }); function imusetorientation() { if(((alpha > 0 && alpha < 90) && (gamma >= (-90) && gamma <= 0)) || ((alpha > 270 && alpha < 360) && (gamma >= (-90) && gamma <= 0)) || ((gamma > 0 && gamma <= 90) && (alpha > 180 && alpha < 270)) || ((gamma > 0 && gamma <= 90) && (alpha > 90 && alpha < 180))) { if ((alpha > 0 && alpha < 90) && (gamma >= (-90) && gamma <= 0 )) { alpha = alpha; }else if ((alpha > 270 && alpha < 360) && (gamma >= (-90) && gamma <= 0)){ alpha = alpha - 360; }else if ((gamma > 0 && gamma <= 90) && (alpha > 180 && alpha < 270)){ alpha = alpha - 180; }else if ((gamma > 0 && gamma <= 90) && (alpha > 90 && alpha < 180)){ alpha = alpha + 180 - 360; } var alpha_radian = alpha / 180.0 * Math.PI; var imuMessage = new ROSLIB.Message({ data : alpha_radian }); headControl.publish(imuMessage); } } setInterval(function(){ imusetorientation(); }, 500); <|start_filename|>leobot_hardware/firmware/STM32F767_Firmware/Core/Src/tim.c<|end_filename|> /** ****************************************************************************** * File Name : TIM.c * Description : This file provides code for the configuration * of the TIM instances. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "tim.h" /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /* TIM1 init function */ void MX_TIM1_Init(void) { LL_TIM_InitTypeDef TIM_InitStruct = {0}; LL_GPIO_InitTypeDef GPIO_InitStruct = {0}; /* Peripheral clock enable */ LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_TIM1); LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_GPIOE); /**TIM1 GPIO Configuration PE9 ------> TIM1_CH1 PE11 ------> TIM1_CH2 */ GPIO_InitStruct.Pin = LL_GPIO_PIN_9; GPIO_InitStruct.Mode = LL_GPIO_MODE_ALTERNATE; GPIO_InitStruct.Speed = LL_GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.OutputType = LL_GPIO_OUTPUT_PUSHPULL; GPIO_InitStruct.Pull = LL_GPIO_PULL_UP; GPIO_InitStruct.Alternate = LL_GPIO_AF_1; LL_GPIO_Init(GPIOE, &GPIO_InitStruct); GPIO_InitStruct.Pin = LL_GPIO_PIN_11; GPIO_InitStruct.Mode = LL_GPIO_MODE_ALTERNATE; GPIO_InitStruct.Speed = LL_GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.OutputType = LL_GPIO_OUTPUT_PUSHPULL; GPIO_InitStruct.Pull = LL_GPIO_PULL_UP; GPIO_InitStruct.Alternate = LL_GPIO_AF_1; LL_GPIO_Init(GPIOE, &GPIO_InitStruct); TIM_InitStruct.Prescaler = 0; TIM_InitStruct.CounterMode = LL_TIM_COUNTERMODE_UP; TIM_InitStruct.Autoreload = 65535; TIM_InitStruct.ClockDivision = LL_TIM_CLOCKDIVISION_DIV1; TIM_InitStruct.RepetitionCounter = 0; LL_TIM_Init(TIM1, &TIM_InitStruct); LL_TIM_DisableARRPreload(TIM1); LL_TIM_SetEncoderMode(TIM1, LL_TIM_ENCODERMODE_X4_TI12); LL_TIM_IC_SetActiveInput(TIM1, LL_TIM_CHANNEL_CH1, LL_TIM_ACTIVEINPUT_DIRECTTI); LL_TIM_IC_SetPrescaler(TIM1, LL_TIM_CHANNEL_CH1, LL_TIM_ICPSC_DIV1); LL_TIM_IC_SetFilter(TIM1, LL_TIM_CHANNEL_CH1, LL_TIM_IC_FILTER_FDIV1); LL_TIM_IC_SetPolarity(TIM1, LL_TIM_CHANNEL_CH1, LL_TIM_IC_POLARITY_RISING); LL_TIM_IC_SetActiveInput(TIM1, LL_TIM_CHANNEL_CH2, LL_TIM_ACTIVEINPUT_DIRECTTI); LL_TIM_IC_SetPrescaler(TIM1, LL_TIM_CHANNEL_CH2, LL_TIM_ICPSC_DIV1); LL_TIM_IC_SetFilter(TIM1, LL_TIM_CHANNEL_CH2, LL_TIM_IC_FILTER_FDIV1); LL_TIM_IC_SetPolarity(TIM1, LL_TIM_CHANNEL_CH2, LL_TIM_IC_POLARITY_RISING); LL_TIM_SetTriggerOutput(TIM1, LL_TIM_TRGO_RESET); LL_TIM_SetTriggerOutput2(TIM1, LL_TIM_TRGO2_RESET); LL_TIM_DisableMasterSlaveMode(TIM1); } /* TIM2 init function */ void MX_TIM2_Init(void) { LL_TIM_InitTypeDef TIM_InitStruct = {0}; LL_TIM_OC_InitTypeDef TIM_OC_InitStruct = {0}; LL_GPIO_InitTypeDef GPIO_InitStruct = {0}; /* Peripheral clock enable */ LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_TIM2); TIM_InitStruct.Prescaler = 960; TIM_InitStruct.CounterMode = LL_TIM_COUNTERMODE_UP; TIM_InitStruct.Autoreload = 1000; TIM_InitStruct.ClockDivision = LL_TIM_CLOCKDIVISION_DIV1; LL_TIM_Init(TIM2, &TIM_InitStruct); LL_TIM_DisableARRPreload(TIM2); LL_TIM_OC_EnablePreload(TIM2, LL_TIM_CHANNEL_CH1); TIM_OC_InitStruct.OCMode = LL_TIM_OCMODE_PWM1; TIM_OC_InitStruct.OCState = LL_TIM_OCSTATE_DISABLE; TIM_OC_InitStruct.OCNState = LL_TIM_OCSTATE_DISABLE; TIM_OC_InitStruct.CompareValue = 0; TIM_OC_InitStruct.OCPolarity = LL_TIM_OCPOLARITY_HIGH; LL_TIM_OC_Init(TIM2, LL_TIM_CHANNEL_CH1, &TIM_OC_InitStruct); LL_TIM_OC_DisableFast(TIM2, LL_TIM_CHANNEL_CH1); LL_TIM_OC_EnablePreload(TIM2, LL_TIM_CHANNEL_CH2); TIM_OC_InitStruct.OCState = LL_TIM_OCSTATE_DISABLE; TIM_OC_InitStruct.OCNState = LL_TIM_OCSTATE_DISABLE; LL_TIM_OC_Init(TIM2, LL_TIM_CHANNEL_CH2, &TIM_OC_InitStruct); LL_TIM_OC_DisableFast(TIM2, LL_TIM_CHANNEL_CH2); LL_TIM_OC_EnablePreload(TIM2, LL_TIM_CHANNEL_CH3); TIM_OC_InitStruct.OCState = LL_TIM_OCSTATE_DISABLE; TIM_OC_InitStruct.OCNState = LL_TIM_OCSTATE_DISABLE; LL_TIM_OC_Init(TIM2, LL_TIM_CHANNEL_CH3, &TIM_OC_InitStruct); LL_TIM_OC_DisableFast(TIM2, LL_TIM_CHANNEL_CH3); LL_TIM_OC_EnablePreload(TIM2, LL_TIM_CHANNEL_CH4); TIM_OC_InitStruct.OCState = LL_TIM_OCSTATE_DISABLE; TIM_OC_InitStruct.OCNState = LL_TIM_OCSTATE_DISABLE; LL_TIM_OC_Init(TIM2, LL_TIM_CHANNEL_CH4, &TIM_OC_InitStruct); LL_TIM_OC_DisableFast(TIM2, LL_TIM_CHANNEL_CH4); LL_TIM_SetTriggerOutput(TIM2, LL_TIM_TRGO_RESET); LL_TIM_DisableMasterSlaveMode(TIM2); LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_GPIOA); LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_GPIOB); /**TIM2 GPIO Configuration PA0/WKUP ------> TIM2_CH1 PA1 ------> TIM2_CH2 PB10 ------> TIM2_CH3 PB11 ------> TIM2_CH4 */ GPIO_InitStruct.Pin = LL_GPIO_PIN_0; GPIO_InitStruct.Mode = LL_GPIO_MODE_ALTERNATE; GPIO_InitStruct.Speed = LL_GPIO_SPEED_FREQ_HIGH; GPIO_InitStruct.OutputType = LL_GPIO_OUTPUT_PUSHPULL; GPIO_InitStruct.Pull = LL_GPIO_PULL_NO; GPIO_InitStruct.Alternate = LL_GPIO_AF_1; LL_GPIO_Init(GPIOA, &GPIO_InitStruct); GPIO_InitStruct.Pin = LL_GPIO_PIN_1; GPIO_InitStruct.Mode = LL_GPIO_MODE_ALTERNATE; GPIO_InitStruct.Speed = LL_GPIO_SPEED_FREQ_HIGH; GPIO_InitStruct.OutputType = LL_GPIO_OUTPUT_PUSHPULL; GPIO_InitStruct.Pull = LL_GPIO_PULL_NO; GPIO_InitStruct.Alternate = LL_GPIO_AF_1; LL_GPIO_Init(GPIOA, &GPIO_InitStruct); GPIO_InitStruct.Pin = LL_GPIO_PIN_10; GPIO_InitStruct.Mode = LL_GPIO_MODE_ALTERNATE; GPIO_InitStruct.Speed = LL_GPIO_SPEED_FREQ_HIGH; GPIO_InitStruct.OutputType = LL_GPIO_OUTPUT_PUSHPULL; GPIO_InitStruct.Pull = LL_GPIO_PULL_NO; GPIO_InitStruct.Alternate = LL_GPIO_AF_1; LL_GPIO_Init(GPIOB, &GPIO_InitStruct); GPIO_InitStruct.Pin = LL_GPIO_PIN_11; GPIO_InitStruct.Mode = LL_GPIO_MODE_ALTERNATE; GPIO_InitStruct.Speed = LL_GPIO_SPEED_FREQ_HIGH; GPIO_InitStruct.OutputType = LL_GPIO_OUTPUT_PUSHPULL; GPIO_InitStruct.Pull = LL_GPIO_PULL_NO; GPIO_InitStruct.Alternate = LL_GPIO_AF_1; LL_GPIO_Init(GPIOB, &GPIO_InitStruct); } /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ <|start_filename|>leobot_hardware/src/robot_hardware.cpp<|end_filename|> /** * Copyright 2019 ROS Ukraine * * 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 "leobot_hardware/robot_hardware.h" #include <std_msgs/Float32.h> #include <hardware_interface/robot_hw.h> #include <string> #include <vector> namespace leobot_hardware { LeobotRobotHW::LeobotRobotHW() { } LeobotRobotHW::~LeobotRobotHW() { } void LeobotRobotHW::firmwareStateCallback(const leobot_msgs::FirmwareStateRead::ConstPtr &message) { hardware_motor_position[0] = message->motor_1_position; hardware_motor_velocity[0] = message->motor_1_velocity; hardware_motor_effort[0] = message->motor_1_effort; hardware_motor_position[1] = message->motor_2_position; hardware_motor_velocity[1] = message->motor_2_velocity; hardware_motor_effort[1] = message->motor_2_effort; hardware_motor_position[2] = message->motor_3_position; hardware_motor_velocity[2] = message->motor_3_velocity; hardware_motor_effort[2] = message->motor_3_effort; hardware_motor_position[3] = message->motor_4_position; hardware_motor_velocity[3] = message->motor_4_velocity; hardware_motor_effort[3] = message->motor_4_effort; } void LeobotRobotHW::fillFirmwareCommandMessageFromConfig(leobot_hardware::LeobotRobotHardwareConfig &config) { firmware_command_message_.motor_1_p = config.motor_1_p; firmware_command_message_.motor_1_i = config.motor_1_i; firmware_command_message_.motor_1_d = config.motor_1_d; firmware_command_message_.motor_2_p = config.motor_2_p; firmware_command_message_.motor_2_i = config.motor_2_i; firmware_command_message_.motor_2_d = config.motor_2_d; firmware_command_message_.motor_3_p = config.motor_3_p; firmware_command_message_.motor_3_i = config.motor_3_i; firmware_command_message_.motor_3_d = config.motor_3_d; firmware_command_message_.motor_4_p = config.motor_4_p; firmware_command_message_.motor_4_i = config.motor_4_i; firmware_command_message_.motor_4_d = config.motor_4_d; } void LeobotRobotHW::dynamicReconfigureCallback(leobot_hardware::LeobotRobotHardwareConfig &config, uint32_t level) { fillFirmwareCommandMessageFromConfig(config); } void LeobotRobotHW::setupHardwareInterfaces() { hardware_interface::JointStateHandle front_right_wheel_joint_state_handle("front_right_wheel_motor_joint", &position[0], &velocity[0], &effort[0]); joint_state_interface.registerHandle(front_right_wheel_joint_state_handle); hardware_interface::JointStateHandle front_left_wheel_joint_state_handle("front_left_wheel_motor_joint", &position[1], &velocity[1], &effort[1]); joint_state_interface.registerHandle(front_left_wheel_joint_state_handle); hardware_interface::JointStateHandle rear_right_wheel_joint_state_handle("rear_right_wheel_motor_joint", &position[2], &velocity[2], &effort[2]); joint_state_interface.registerHandle(rear_right_wheel_joint_state_handle); hardware_interface::JointStateHandle rear_left_wheel_joint_state_handle("rear_left_wheel_motor_joint", &position[3], &velocity[3], &effort[3]); joint_state_interface.registerHandle(rear_left_wheel_joint_state_handle); registerInterface(&joint_state_interface); hardware_interface::JointHandle front_right_wheel_joint_velocity_handler( joint_state_interface.getHandle("front_right_wheel_motor_joint"), &command[0]); joint_velocity_interface.registerHandle(front_right_wheel_joint_velocity_handler); hardware_interface::JointHandle front_left_wheel_joint_velocity_handler( joint_state_interface.getHandle("front_left_wheel_motor_joint"), &command[1]); joint_velocity_interface.registerHandle(front_left_wheel_joint_velocity_handler); hardware_interface::JointHandle rear_right_wheel_joint_velocity_handler( joint_state_interface.getHandle("rear_right_wheel_motor_joint"), &command[2]); joint_velocity_interface.registerHandle(rear_right_wheel_joint_velocity_handler); hardware_interface::JointHandle rear_left_wheel_joint_velocity_handler( joint_state_interface.getHandle("rear_left_wheel_motor_joint"), &command[3]); joint_velocity_interface.registerHandle(rear_left_wheel_joint_velocity_handler); registerInterface(&joint_velocity_interface); } void LeobotRobotHW::setupDynamicReconfigure(ros::NodeHandle &node_handle) { dynamic_reconfigure_server_.reset(new dynamic_reconfigure::Server<leobot_hardware::LeobotRobotHardwareConfig>( dynamic_reconfigure_mutex_, node_handle)); reconfigure_callback_ = boost::bind(&LeobotRobotHW::dynamicReconfigureCallback, this, _1, _2); default_dynamic_server_config_.__fromServer__(node_handle); dynamic_reconfigure_server_->setCallback(reconfigure_callback_); fillFirmwareCommandMessageFromConfig(default_dynamic_server_config_); } bool LeobotRobotHW::init(ros::NodeHandle &root_nh, ros::NodeHandle &robot_hw_nh) { command_publisher_ = robot_hw_nh.advertise<leobot_msgs::FirmwareCommandWrite>("firmware_command_write", 10); state_subscriber_ = robot_hw_nh.subscribe("firmware_state_read", 1, &LeobotRobotHW::firmwareStateCallback, this); setupHardwareInterfaces(); setupDynamicReconfigure(root_nh); } void LeobotRobotHW::read(const ros::Time &time, const ros::Duration &period) { } void LeobotRobotHW::write(const ros::Time &time, const ros::Duration &period) { boost::recursive_mutex::scoped_lock lock(dynamic_reconfigure_mutex_); firmware_command_message_.motor_1_velocity_command = command[0]; firmware_command_message_.motor_2_velocity_command = command[1]; firmware_command_message_.motor_3_velocity_command = command[2]; firmware_command_message_.motor_4_velocity_command = command[3]; command_publisher_.publish(firmware_command_message_); } } // namespace leobot_hardware <|start_filename|>leobot_hardware/firmware/STM32F767_Firmware/Libs/rosserial/leobot_msgs/FirmwareStateRead.h<|end_filename|> #ifndef _ROS_leobot_msgs_FirmwareStateRead_h #define _ROS_leobot_msgs_FirmwareStateRead_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" namespace leobot_msgs { class FirmwareStateRead : public ros::Msg { public: typedef float _imu_alpha_type; _imu_alpha_type imu_alpha; typedef float _imu_beta_type; _imu_beta_type imu_beta; typedef float _imu_gamma_type; _imu_gamma_type imu_gamma; typedef float _imu_alpha_velocity_type; _imu_alpha_velocity_type imu_alpha_velocity; typedef float _imu_beta_velocity_type; _imu_beta_velocity_type imu_beta_velocity; typedef float _imu_gamma_velocity_type; _imu_gamma_velocity_type imu_gamma_velocity; typedef float _imu_x_acceleration_type; _imu_x_acceleration_type imu_x_acceleration; typedef float _imu_y_acceleration_type; _imu_y_acceleration_type imu_y_acceleration; typedef float _imu_z_acceleration_type; _imu_z_acceleration_type imu_z_acceleration; typedef float _motor_1_position_type; _motor_1_position_type motor_1_position; typedef float _motor_1_velocity_type; _motor_1_velocity_type motor_1_velocity; typedef float _motor_1_effort_type; _motor_1_effort_type motor_1_effort; typedef float _motor_2_position_type; _motor_2_position_type motor_2_position; typedef float _motor_2_velocity_type; _motor_2_velocity_type motor_2_velocity; typedef float _motor_2_effort_type; _motor_2_effort_type motor_2_effort; typedef float _motor_3_position_type; _motor_3_position_type motor_3_position; typedef float _motor_3_velocity_type; _motor_3_velocity_type motor_3_velocity; typedef float _motor_3_effort_type; _motor_3_effort_type motor_3_effort; typedef float _motor_4_position_type; _motor_4_position_type motor_4_position; typedef float _motor_4_velocity_type; _motor_4_velocity_type motor_4_velocity; typedef float _motor_4_effort_type; _motor_4_effort_type motor_4_effort; FirmwareStateRead(): imu_alpha(0), imu_beta(0), imu_gamma(0), imu_alpha_velocity(0), imu_beta_velocity(0), imu_gamma_velocity(0), imu_x_acceleration(0), imu_y_acceleration(0), imu_z_acceleration(0), motor_1_position(0), motor_1_velocity(0), motor_1_effort(0), motor_2_position(0), motor_2_velocity(0), motor_2_effort(0), motor_3_position(0), motor_3_velocity(0), motor_3_effort(0), motor_4_position(0), motor_4_velocity(0), motor_4_effort(0) { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; union { float real; uint32_t base; } u_imu_alpha; u_imu_alpha.real = this->imu_alpha; *(outbuffer + offset + 0) = (u_imu_alpha.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_imu_alpha.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_imu_alpha.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_imu_alpha.base >> (8 * 3)) & 0xFF; offset += sizeof(this->imu_alpha); union { float real; uint32_t base; } u_imu_beta; u_imu_beta.real = this->imu_beta; *(outbuffer + offset + 0) = (u_imu_beta.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_imu_beta.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_imu_beta.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_imu_beta.base >> (8 * 3)) & 0xFF; offset += sizeof(this->imu_beta); union { float real; uint32_t base; } u_imu_gamma; u_imu_gamma.real = this->imu_gamma; *(outbuffer + offset + 0) = (u_imu_gamma.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_imu_gamma.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_imu_gamma.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_imu_gamma.base >> (8 * 3)) & 0xFF; offset += sizeof(this->imu_gamma); union { float real; uint32_t base; } u_imu_alpha_velocity; u_imu_alpha_velocity.real = this->imu_alpha_velocity; *(outbuffer + offset + 0) = (u_imu_alpha_velocity.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_imu_alpha_velocity.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_imu_alpha_velocity.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_imu_alpha_velocity.base >> (8 * 3)) & 0xFF; offset += sizeof(this->imu_alpha_velocity); union { float real; uint32_t base; } u_imu_beta_velocity; u_imu_beta_velocity.real = this->imu_beta_velocity; *(outbuffer + offset + 0) = (u_imu_beta_velocity.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_imu_beta_velocity.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_imu_beta_velocity.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_imu_beta_velocity.base >> (8 * 3)) & 0xFF; offset += sizeof(this->imu_beta_velocity); union { float real; uint32_t base; } u_imu_gamma_velocity; u_imu_gamma_velocity.real = this->imu_gamma_velocity; *(outbuffer + offset + 0) = (u_imu_gamma_velocity.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_imu_gamma_velocity.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_imu_gamma_velocity.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_imu_gamma_velocity.base >> (8 * 3)) & 0xFF; offset += sizeof(this->imu_gamma_velocity); union { float real; uint32_t base; } u_imu_x_acceleration; u_imu_x_acceleration.real = this->imu_x_acceleration; *(outbuffer + offset + 0) = (u_imu_x_acceleration.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_imu_x_acceleration.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_imu_x_acceleration.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_imu_x_acceleration.base >> (8 * 3)) & 0xFF; offset += sizeof(this->imu_x_acceleration); union { float real; uint32_t base; } u_imu_y_acceleration; u_imu_y_acceleration.real = this->imu_y_acceleration; *(outbuffer + offset + 0) = (u_imu_y_acceleration.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_imu_y_acceleration.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_imu_y_acceleration.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_imu_y_acceleration.base >> (8 * 3)) & 0xFF; offset += sizeof(this->imu_y_acceleration); union { float real; uint32_t base; } u_imu_z_acceleration; u_imu_z_acceleration.real = this->imu_z_acceleration; *(outbuffer + offset + 0) = (u_imu_z_acceleration.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_imu_z_acceleration.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_imu_z_acceleration.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_imu_z_acceleration.base >> (8 * 3)) & 0xFF; offset += sizeof(this->imu_z_acceleration); union { float real; uint32_t base; } u_motor_1_position; u_motor_1_position.real = this->motor_1_position; *(outbuffer + offset + 0) = (u_motor_1_position.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_1_position.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_1_position.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_1_position.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_1_position); union { float real; uint32_t base; } u_motor_1_velocity; u_motor_1_velocity.real = this->motor_1_velocity; *(outbuffer + offset + 0) = (u_motor_1_velocity.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_1_velocity.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_1_velocity.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_1_velocity.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_1_velocity); union { float real; uint32_t base; } u_motor_1_effort; u_motor_1_effort.real = this->motor_1_effort; *(outbuffer + offset + 0) = (u_motor_1_effort.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_1_effort.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_1_effort.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_1_effort.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_1_effort); union { float real; uint32_t base; } u_motor_2_position; u_motor_2_position.real = this->motor_2_position; *(outbuffer + offset + 0) = (u_motor_2_position.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_2_position.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_2_position.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_2_position.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_2_position); union { float real; uint32_t base; } u_motor_2_velocity; u_motor_2_velocity.real = this->motor_2_velocity; *(outbuffer + offset + 0) = (u_motor_2_velocity.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_2_velocity.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_2_velocity.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_2_velocity.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_2_velocity); union { float real; uint32_t base; } u_motor_2_effort; u_motor_2_effort.real = this->motor_2_effort; *(outbuffer + offset + 0) = (u_motor_2_effort.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_2_effort.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_2_effort.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_2_effort.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_2_effort); union { float real; uint32_t base; } u_motor_3_position; u_motor_3_position.real = this->motor_3_position; *(outbuffer + offset + 0) = (u_motor_3_position.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_3_position.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_3_position.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_3_position.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_3_position); union { float real; uint32_t base; } u_motor_3_velocity; u_motor_3_velocity.real = this->motor_3_velocity; *(outbuffer + offset + 0) = (u_motor_3_velocity.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_3_velocity.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_3_velocity.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_3_velocity.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_3_velocity); union { float real; uint32_t base; } u_motor_3_effort; u_motor_3_effort.real = this->motor_3_effort; *(outbuffer + offset + 0) = (u_motor_3_effort.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_3_effort.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_3_effort.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_3_effort.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_3_effort); union { float real; uint32_t base; } u_motor_4_position; u_motor_4_position.real = this->motor_4_position; *(outbuffer + offset + 0) = (u_motor_4_position.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_4_position.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_4_position.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_4_position.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_4_position); union { float real; uint32_t base; } u_motor_4_velocity; u_motor_4_velocity.real = this->motor_4_velocity; *(outbuffer + offset + 0) = (u_motor_4_velocity.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_4_velocity.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_4_velocity.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_4_velocity.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_4_velocity); union { float real; uint32_t base; } u_motor_4_effort; u_motor_4_effort.real = this->motor_4_effort; *(outbuffer + offset + 0) = (u_motor_4_effort.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_4_effort.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_4_effort.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_4_effort.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_4_effort); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; union { float real; uint32_t base; } u_imu_alpha; u_imu_alpha.base = 0; u_imu_alpha.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_imu_alpha.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_imu_alpha.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_imu_alpha.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->imu_alpha = u_imu_alpha.real; offset += sizeof(this->imu_alpha); union { float real; uint32_t base; } u_imu_beta; u_imu_beta.base = 0; u_imu_beta.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_imu_beta.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_imu_beta.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_imu_beta.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->imu_beta = u_imu_beta.real; offset += sizeof(this->imu_beta); union { float real; uint32_t base; } u_imu_gamma; u_imu_gamma.base = 0; u_imu_gamma.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_imu_gamma.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_imu_gamma.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_imu_gamma.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->imu_gamma = u_imu_gamma.real; offset += sizeof(this->imu_gamma); union { float real; uint32_t base; } u_imu_alpha_velocity; u_imu_alpha_velocity.base = 0; u_imu_alpha_velocity.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_imu_alpha_velocity.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_imu_alpha_velocity.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_imu_alpha_velocity.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->imu_alpha_velocity = u_imu_alpha_velocity.real; offset += sizeof(this->imu_alpha_velocity); union { float real; uint32_t base; } u_imu_beta_velocity; u_imu_beta_velocity.base = 0; u_imu_beta_velocity.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_imu_beta_velocity.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_imu_beta_velocity.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_imu_beta_velocity.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->imu_beta_velocity = u_imu_beta_velocity.real; offset += sizeof(this->imu_beta_velocity); union { float real; uint32_t base; } u_imu_gamma_velocity; u_imu_gamma_velocity.base = 0; u_imu_gamma_velocity.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_imu_gamma_velocity.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_imu_gamma_velocity.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_imu_gamma_velocity.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->imu_gamma_velocity = u_imu_gamma_velocity.real; offset += sizeof(this->imu_gamma_velocity); union { float real; uint32_t base; } u_imu_x_acceleration; u_imu_x_acceleration.base = 0; u_imu_x_acceleration.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_imu_x_acceleration.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_imu_x_acceleration.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_imu_x_acceleration.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->imu_x_acceleration = u_imu_x_acceleration.real; offset += sizeof(this->imu_x_acceleration); union { float real; uint32_t base; } u_imu_y_acceleration; u_imu_y_acceleration.base = 0; u_imu_y_acceleration.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_imu_y_acceleration.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_imu_y_acceleration.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_imu_y_acceleration.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->imu_y_acceleration = u_imu_y_acceleration.real; offset += sizeof(this->imu_y_acceleration); union { float real; uint32_t base; } u_imu_z_acceleration; u_imu_z_acceleration.base = 0; u_imu_z_acceleration.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_imu_z_acceleration.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_imu_z_acceleration.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_imu_z_acceleration.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->imu_z_acceleration = u_imu_z_acceleration.real; offset += sizeof(this->imu_z_acceleration); union { float real; uint32_t base; } u_motor_1_position; u_motor_1_position.base = 0; u_motor_1_position.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_1_position.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_1_position.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_1_position.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_1_position = u_motor_1_position.real; offset += sizeof(this->motor_1_position); union { float real; uint32_t base; } u_motor_1_velocity; u_motor_1_velocity.base = 0; u_motor_1_velocity.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_1_velocity.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_1_velocity.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_1_velocity.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_1_velocity = u_motor_1_velocity.real; offset += sizeof(this->motor_1_velocity); union { float real; uint32_t base; } u_motor_1_effort; u_motor_1_effort.base = 0; u_motor_1_effort.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_1_effort.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_1_effort.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_1_effort.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_1_effort = u_motor_1_effort.real; offset += sizeof(this->motor_1_effort); union { float real; uint32_t base; } u_motor_2_position; u_motor_2_position.base = 0; u_motor_2_position.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_2_position.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_2_position.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_2_position.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_2_position = u_motor_2_position.real; offset += sizeof(this->motor_2_position); union { float real; uint32_t base; } u_motor_2_velocity; u_motor_2_velocity.base = 0; u_motor_2_velocity.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_2_velocity.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_2_velocity.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_2_velocity.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_2_velocity = u_motor_2_velocity.real; offset += sizeof(this->motor_2_velocity); union { float real; uint32_t base; } u_motor_2_effort; u_motor_2_effort.base = 0; u_motor_2_effort.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_2_effort.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_2_effort.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_2_effort.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_2_effort = u_motor_2_effort.real; offset += sizeof(this->motor_2_effort); union { float real; uint32_t base; } u_motor_3_position; u_motor_3_position.base = 0; u_motor_3_position.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_3_position.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_3_position.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_3_position.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_3_position = u_motor_3_position.real; offset += sizeof(this->motor_3_position); union { float real; uint32_t base; } u_motor_3_velocity; u_motor_3_velocity.base = 0; u_motor_3_velocity.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_3_velocity.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_3_velocity.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_3_velocity.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_3_velocity = u_motor_3_velocity.real; offset += sizeof(this->motor_3_velocity); union { float real; uint32_t base; } u_motor_3_effort; u_motor_3_effort.base = 0; u_motor_3_effort.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_3_effort.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_3_effort.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_3_effort.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_3_effort = u_motor_3_effort.real; offset += sizeof(this->motor_3_effort); union { float real; uint32_t base; } u_motor_4_position; u_motor_4_position.base = 0; u_motor_4_position.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_4_position.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_4_position.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_4_position.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_4_position = u_motor_4_position.real; offset += sizeof(this->motor_4_position); union { float real; uint32_t base; } u_motor_4_velocity; u_motor_4_velocity.base = 0; u_motor_4_velocity.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_4_velocity.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_4_velocity.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_4_velocity.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_4_velocity = u_motor_4_velocity.real; offset += sizeof(this->motor_4_velocity); union { float real; uint32_t base; } u_motor_4_effort; u_motor_4_effort.base = 0; u_motor_4_effort.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_4_effort.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_4_effort.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_4_effort.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_4_effort = u_motor_4_effort.real; offset += sizeof(this->motor_4_effort); return offset; } const char * getType(){ return "leobot_msgs/FirmwareStateRead"; }; const char * getMD5(){ return "954be1c8ed8f4fc3286a7c7902b4d9ae"; }; }; } #endif <|start_filename|>leobot_web_server/web_content/css/styles.css<|end_filename|> @font-face { font-family: "GlacialIndifference-Bold"; src: url(../fonts/GlacialIndifference-Bold.otf); } body { margin: 0; } header { margin: 0; width: 100%; height: 110px; background-color: #595959; display: flex; align-items: center; } .header-wrapper { width: 1200px; display: flex; align-items: center; justify-content: space-between; margin-left: auto; margin-right: auto; } .header-image { width: 242px; height: 52px; margin-left: 15px; background-image: url(../images/site-logo-large.png); background-size: contain; background-repeat: no-repeat; } h1 { font-family: "GlacialIndifference-Bold", sans-serif; font-style: normal; font-weight: normal; font-size: 22px; line-height: 1.13; letter-spacing: normal; text-align: left; color: #fdfdfd; margin-right: 40px; } main { width: 100%; background-color: #fff; display: flex; flex-direction: column; align-items: center; } .wrapper { display: flex; justify-content: space-around; margin-top: 0; width: 1200px; margin-left: auto; margin-right: auto; } .video { margin-right: 24px; margin-top: 0; } .map { margin-top: 0; } .video-header, .map-header, .map .map-counter-item label, .map .map-counter-item input { font-family: "GlacialIndifference-Bold", sans-serif; font-size: 18px; font-weight: bold; font-style: normal; font-stretch: normal; line-height: 1.5; letter-spacing: normal; text-align: left; color: #595959; } .video-header, .map-header { font-size: 20px; margin-top: 10px; margin-bottom: 5px; } .video-streaming { width: 671px; height: 504px; } button { cursor: pointer; } .head-control-buttons { text-align:center; } .head-control-header { font-family: "GlacialIndifference-Bold", sans-serif; font-size: 22px; font-weight: bold; font-style: normal; font-stretch: normal; line-height: 1.13; letter-spacing: normal; text-align: center; color: #595959; } #head-control-button-left { width: 120px; height: 30px; border: none; border-radius: 10px; background-color: rgba(89,89,89,.4); box-shadow: 2.5px 4.3px 5px 0 rgba(0, 0, 0, 0.75); font-family: "GlacialIndifference-Bold", sans-serif; font-size: 18px; font-weight: bold; font-style: normal; font-stretch: normal; line-height: 1.13; letter-spacing: normal; text-align: center; color: #ffffff; margin-bottom: 2px; padding-left: 0; padding-right: 0; } #head-control-button-left:active { background-color: #dcdcdc; } #head-control-button-left:focus { outline: 0; } #head-control-button-center { width: 120px; height: 30px; border: none; border-radius: 10px; background-color: rgba(89,89,89,.4); box-shadow: 2.5px 4.3px 5px 0 rgba(0, 0, 0, 0.75); font-family: "GlacialIndifference-Bold", sans-serif; font-size: 18px; font-weight: bold; font-style: normal; font-stretch: normal; line-height: 1.13; letter-spacing: normal; text-align: center; color: #ffffff; margin-bottom: 2px; padding-left: 0; padding-right: 0; } #head-control-button-center:active { background-color: #dcdcdc; } #head-control-button-center:focus { outline: 0; } #head-control-button-right { width: 120px; height: 30px; border: none; border-radius: 10px; background-color: rgba(89,89,89,.4); box-shadow: 2.5px 4.3px 5px 0 rgba(0, 0, 0, 0.75); font-family: "GlacialIndifference-Bold", sans-serif; font-size: 18px; font-weight: bold; font-style: normal; font-stretch: normal; line-height: 1.13; letter-spacing: normal; text-align: center; color: #ffffff; margin-bottom: 2px; padding-left: 0; padding-right: 0; } #head-control-button-right:active { background-color: #dcdcdc; } #head-control-button-right:focus { outline: 0; } .map-tracking { width: 458px; height: 342px; } .map-counter { margin-top: 16px; } .map .map-counter-item input { border: none; margin-left: 5px; } .no-spinners::-webkit-outer-spin-button, .no-spinners::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } .no-spinners { -moz-appearance:textfield; } .control-panel { display: flex; flex-direction: column; align-items: center; margin-top: 0; margin-bottom: 0; } .control-panel-header { font-family: "GlacialIndifference-Bold", sans-serif; font-size: 22px; font-weight: bold; font-style: normal; font-stretch: normal; line-height: 1.13; letter-spacing: normal; text-align: left; color: #595959; margin-bottom: 10px; margin-top: 20px; } .control-panel-button { width: 180px; height: 44px; border: none; border-radius: 10px; background-color: rgba(89,89,89,.4); box-shadow: 2.5px 4.3px 5px 0 rgba(0, 0, 0, 0.75); font-family: "GlacialIndifference-Bold", sans-serif; font-size: 22px; font-weight: bold; font-style: normal; font-stretch: normal; line-height: 1.13; letter-spacing: normal; text-align: center; color: #ffffff; margin-bottom: 2px; padding-left: 0; padding-right: 0; } .control-panel-button:active { background-color: #dcdcdc; } .control-panel-button:focus { outline: 0; } .left-right { width: 700px; display: flex; justify-content: space-between; } footer p { font-family: "GlacialIndifference-Bold", sans-serif; font-size: 12px; font-weight: bold; font-style: normal; font-stretch: normal; line-height: 1.93; letter-spacing: normal; text-align: right; color: #595959; position: fixed; right: 10px; bottom: 0; } footer { width: 100%; margin-bottom: 0; margin-top: 0; position: relative; } @media all and (max-width: 1279px) and (min-width: 900px), (min-height: 700px) and (max-height: 800px) { .header-wrapper { width: 870px; } .wrapper { width: 870px; justify-content: center; } .video { margin-right: 14px; } .video-header, .map-header, .map .map-counter-item input { font-size: 12px; line-height: 1.1; } .map .map-counter-item label { font-size: 12px; } .video-header, .map-header { font-size: 14px; } .video-streaming { width: 540px; height: 405px; } .map-tracking { width: 320px; height: 238px; } .control-panel-header { font-size: 16px; margin-top: 10px; margin-bottom: 10px; } .control-panel-button { width: 160px; height: 32px; font-size: 16px; } .left-right { width: 540px; } } @media (max-height: 730px) { footer p { display: none; } } @media all and (max-width: 899px) and (min-width: 670px){ header { height: 90px; } h1 { font-size: 18px; } .header-image { width: 200px; height: 55px; margin-left: 10px; background-size: cover; } .header-wrapper { width: 650px; } .wrapper { width: 650px; justify-content: center; } .video { margin-right: 8px; } .video-header, .map-header, .map .map-counter-item input { font-size: 11px; line-height: 1.3; } .map .map-counter-item label { font-size: 10px; } .video-header, .map-header { font-size: 12px; } .video-streaming { width: 420px; height: 315px; } .map-tracking { width: 210px; height: 156px; } .control-panel-header { font-size: 14px; margin-top: 15px; margin-bottom: 15px; } .control-panel-button { width: 125px; height: 25px; font-size: 10px; } .left-right { width: 450px; } footer p { font-size: 9px; } } @media (min-width: 670px){ .button-forward:before { content: 'FORWARD'; } .button-left:before { content: 'LEFT'; } .button-right:before { content: 'RIGHT'; } .button-backward:before { content: 'BACKWARD'; } } @media all and (max-width: 669px) and (min-width: 320px){ header { height: 65px; } .header-wrapper { width: 320px; justify-content: center; } .header-image { width: 43px; height: 43px; margin-left: 5px; background-image: url(../images/site-logo-small.png); background-size: cover; } h1 { font-size: 14px; line-height: 1.13; text-align: center; margin-right: 0; } .wrapper { width: 320px; flex-direction: column; align-items: center; } .video { margin-right: 10px; } .video-header, .map-header { font-size: 16px; line-height: 1.3; text-align: center; } .map .map-counter-item input { width: 35px; font-size: 9px; } .smallscreen-wraper { display: flex; } .map-counter { margin-left: 7px; } .map .map-counter-item label { font-size: 9px; } .video-header, .map-header { font-size: 12px; } .video-streaming { width: 315px; height: 236px; } .map-tracking { width: 220px; height: 163px; } .control-panel { display: flex; flex-direction: column; align-items: center; } .control-panel-header { font-size: 12px; } .button-forward { border: none; background-color: transparent; width: 30px; height: 30px; background-image: url(../images/arrow-dark-up.png); } .left-right { display: flex; justify-content: center; } .button-left { border: none; background-color: transparent; width: 30px; height: 30px; margin-right: 40px; background-image: url(../images/arrow-dark-left.png); } .button-right { border: none; background-color: transparent; width: 30px; height: 30px; margin-left: 40px; background-image: url(../images/arrow-dark-right.png); } .button-backward { border: none; background-color: transparent; width: 30px; height: 30px; background-image: url(../images/arrow-dark-down.png); } .button-forward:active { background-image: url(../images/arrow-light-up.png); outline: none; } .button-left:active { background-image: url(../images/arrow-light-left.png); outline: none; } .button-right:active { background-image: url(../images/arrow-light-right.png); outline: none; } .button-backward:active { background-image: url(../images/arrow-light-bottom.png); outline: none; } .button-forward:focus { outline: 0; } .button-left:focus { outline: 0; } .button-right:focus { outline: 0; } .button-backward:focus { outline: 0; } footer p { font-size: 8px; } } <|start_filename|>leobot_web_server/package.json<|end_filename|> { "name": "leobot_web_server", "version": "1.0.0", "description": "LeoBot Telepresence Web Server", "repository": { "type": "git", "url": "git+https://github.com/ros-ukraine/leobot.git" }, "author": "<NAME>", "license": "MIT", "bugs": { "url": "https://github.com/ros-ukraine/leobot/issues" }, "homepage": "https://github.com/ros-ukraine/leobot#readme", "dependencies": { "rosnodejs": "2.1.1", "node-static": "0.7.10", "roslib": "0.20.0", "jquery": "3.3.1" } } <|start_filename|>leobot_web_server/web_content/js/main.js<|end_filename|> var headDelta = 0; function createTopic(name, type) { return new ROSLIB.Topic({ ros: ros, name: name, messageType: type }); } function publishMessage(message, topic) { topic.publish(new ROSLIB.Message(message)); } function publishMessageOnClick(selector, message, topic) { $(selector).click(function() { publishMessage(message, topic); }); } function publishHeadPosition() { var delta_radians = headDelta / 180.0 * Math.PI; console.debug('degrees = ' + headDelta + ' radians = ' + delta_radians); publishMessage({data: delta_radians}, headControlTopic); } function initVideoStreaming(){ var siteRoot = location.protocol + '//' + location.hostname + ':8090' + '/'; document.getElementsByClassName('video-streaming')[0].src = siteRoot + 'stream?topic=/stereocamera/left/image_raw&width=640&height=470'; } function initWheelsOperation() { var forwardMessage = { linear: { x: 1, y: 0, z: 0 } }; var leftMessage = { angular: { x: 0, y: 0, z: 0.1 } }; var rightMessage = { angular: { x: 0, y: 0, z: -0.1 } }; var backwardMessage = { linear: { x: -1, y: 0, z: 0 } }; publishMessageOnClick('.button-forward', forwardMessage, wheelsTopic); publishMessageOnClick('.button-left', leftMessage, wheelsTopic); publishMessageOnClick('.button-right', rightMessage, wheelsTopic); publishMessageOnClick('.button-backward', backwardMessage, wheelsTopic); window.addEventListener('keydown', function(e) { switch(e.key){ case 'ArrowUp': publishMessage(forwardMessage, wheelsTopic); e.preventDefault(); break; case 'ArrowLeft': publishMessage(leftMessage, wheelsTopic); e.preventDefault(); break; case 'ArrowRight': publishMessage(rightMessage, wheelsTopic); e.preventDefault(); break; case 'ArrowDown': publishMessage(backwardMessage, wheelsTopic); e.preventDefault(); break; } }); } function initHeadOperation() { document.getElementById('head-control-button-left').onclick = function() { headDelta = (headDelta > 85) ? 90 : headDelta + 5; publishHeadPosition() }; document.getElementById('head-control-button-center').onclick = function() { headDelta = 0; publishHeadPosition() }; document.getElementById('head-control-button-right').onclick = function() { headDelta = (headDelta < -85) ? -90 : headDelta - 5; publishHeadPosition() }; } // Connection to ROS var ros = new ROSLIB.Ros({ url : 'ws://' + location.hostname + ':9090' }); ros.on('connection', function() { console.log('Connected to websocket server.'); }); ros.on('error', function(error) { console.error('Error connecting to websocket server: ', error); }); ros.on('close', function() { console.log('Connection to websocket server closed.'); }); var wheelsTopic = createTopic('/cmd_vel', 'geometry_msgs/Twist'); var headControlTopic = createTopic('/head_position_controller/command', 'std_msgs/Float64'); var headListenerTopic = createTopic('/head_position_controller/state', 'control_msgs/JointControllerState'); wheelsTopic.subscribe(function(message) { console.debug('Received message on ' + wheelsTopic.name + ': ', message); }); headListenerTopic.subscribe(function(message) { headDelta = message.process_value * 180 / Math.PI; }); $(function(event) { initVideoStreaming(); initWheelsOperation(); initHeadOperation(); }); <|start_filename|>leobot_hardware/firmware/STM32F767_Firmware/Core/Src/freertos.cpp<|end_filename|> /* USER CODE BEGIN Header */ /** ****************************************************************************** * File Name : freertos.c * Description : Code for freertos applications ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ /* USER CODE END Header */ // ToDo: rename this file to app /* Includes ------------------------------------------------------------------*/ #include "FreeRTOS.h" #include "task.h" #include "main.h" #include "cmsis_os.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "gpio.h" #include "tim.h" #include "rtos.h" #include "arm_math.h" #include "ros.h" #include "std_msgs/UInt16.h" //#include "std_msgs/String.h" #include <stdio.h> /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* Choose PID parameters */ #define PID_PARAM_KP 100 /* Proporcional */ #define PID_PARAM_KI 0.025 /* Integral */ #define PID_PARAM_KD 20 /* Derivative */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN Variables */ static ros::NodeHandle nh; /* USER CODE END Variables */ osThreadId defaultTaskHandle; osThreadId LedBlinkTaskHandle; osThreadId EncoderTaskHandle; osThreadId RosSpinTaskHandle; osThreadId RosSubscriberTaHandle; osThreadId RosPublisherTasHandle; osMessageQId RosSubsriberQueueHandle; osMutexId rosPublishMutexHandle; /* Private function prototypes -----------------------------------------------*/ /* USER CODE BEGIN FunctionPrototypes */ void motor_cb(const std_msgs::UInt16& cmd_msg); void pid_cb(const std_msgs::UInt16& cmd_msg); /* USER CODE END FunctionPrototypes */ void StartDefaultTask(void const * argument); void LedBlinkTaskHandler(void const * argument); void EncoderTaskHandler(void const * argument); void RosSpinTaskHandler(void const * argument); void RosSubscriberTaskHandler(void const * argument); void RosPublisherTaskHandler(void const * argument); //void MX_FREERTOS_Init(void); /* (MISRA C 2004 rule 8.1) */ /** * @brief FreeRTOS initialization * @param None * @retval None */ void MX_FREERTOS_Init(void) { /* USER CODE BEGIN Init */ nh.initNode(); /* USER CODE END Init */ /* Create the mutex(es) */ /* definition and creation of rosPublishMutex */ osMutexDef(rosPublishMutex); rosPublishMutexHandle = osMutexCreate(osMutex(rosPublishMutex)); /* USER CODE BEGIN RTOS_MUTEX */ /* add mutexes, ... */ /* USER CODE END RTOS_MUTEX */ /* USER CODE BEGIN RTOS_SEMAPHORES */ /* add semaphores, ... */ /* USER CODE END RTOS_SEMAPHORES */ /* USER CODE BEGIN RTOS_TIMERS */ /* start timers, add new ones, ... */ /* USER CODE END RTOS_TIMERS */ /* Create the queue(s) */ /* definition and creation of RosSubsriberQueue */ osMessageQDef(RosSubsriberQueue, 16, uint16_t); RosSubsriberQueueHandle = osMessageCreate(osMessageQ(RosSubsriberQueue), NULL); /* USER CODE BEGIN RTOS_QUEUES */ /* add queues, ... */ /* USER CODE END RTOS_QUEUES */ /* Create the thread(s) */ /* definition and creation of defaultTask */ osThreadDef(defaultTask, StartDefaultTask, osPriorityIdle, 0, 128); defaultTaskHandle = osThreadCreate(osThread(defaultTask), NULL); /* definition and creation of LedBlinkTask */ osThreadDef(LedBlinkTask, LedBlinkTaskHandler, osPriorityLow, 0, 128); LedBlinkTaskHandle = osThreadCreate(osThread(LedBlinkTask), NULL); /* definition and creation of EncoderTask */ osThreadDef(EncoderTask, EncoderTaskHandler, osPriorityNormal, 0, 128); EncoderTaskHandle = osThreadCreate(osThread(EncoderTask), NULL); /* definition and creation of RosSpinTask */ osThreadDef(RosSpinTask, RosSpinTaskHandler, osPriorityIdle, 0, 128); RosSpinTaskHandle = osThreadCreate(osThread(RosSpinTask), NULL); /* definition and creation of RosSubscriberTa */ osThreadDef(RosSubscriberTa, RosSubscriberTaskHandler, osPriorityNormal, 0, 128); RosSubscriberTaHandle = osThreadCreate(osThread(RosSubscriberTa), NULL); /* definition and creation of RosPublisherTas */ osThreadDef(RosPublisherTas, RosPublisherTaskHandler, osPriorityNormal, 0, 128); RosPublisherTasHandle = osThreadCreate(osThread(RosPublisherTas), NULL); /* USER CODE BEGIN RTOS_THREADS */ /* add threads, ... */ /* USER CODE END RTOS_THREADS */ } /* USER CODE BEGIN Header_StartDefaultTask */ /** * @brief Function implementing the defaultTask thread. * @param argument: Not used * @retval None */ /* USER CODE END Header_StartDefaultTask */ void StartDefaultTask(void const * argument) { /* USER CODE BEGIN StartDefaultTask */ //ros::Subscriber<std_msgs::UInt16> sub("motor", motor_cb); //nh.subscribe(sub); //char hello[15] = "hello world!\r\n"; //str_msg.data = hello; //nh.advertise(chatter); /* Infinite loop */ for(;;) { osDelay(100); } /* USER CODE END StartDefaultTask */ } /* USER CODE BEGIN Header_LedBlinkTaskHandler */ /** * @brief Function implementing the LedBlinkTask thread. * @param argument: Not used * @retval None */ /* USER CODE END Header_LedBlinkTaskHandler */ void LedBlinkTaskHandler(void const * argument) { /* USER CODE BEGIN LedBlinkTaskHandler */ MX_GPIO_Init(); /* Infinite loop */ for(;;) { LL_GPIO_SetOutputPin(LD3_GPIO_Port, LD3_Pin); LL_GPIO_ResetOutputPin(LD2_GPIO_Port, LD2_Pin); osDelay(300); LL_GPIO_ResetOutputPin(LD3_GPIO_Port, LD3_Pin); LL_GPIO_SetOutputPin(LD2_GPIO_Port, LD2_Pin); osDelay(100); } /* USER CODE END LedBlinkTaskHandler */ } /* USER CODE BEGIN Header_EncoderTaskHandler */ /** * @brief Function implementing the EncoderTask thread. * @param argument: Not used * @retval None */ /* USER CODE END Header_EncoderTaskHandler */ void EncoderTaskHandler(void const * argument) { /* USER CODE BEGIN EncoderTaskHandler */ // https://www.vexforum.com/t/calculating-rpms/31506/4 uint32_t EncoderCurr = 0; uint32_t EncoderLast = 0; uint32_t RPM; uint32_t pmw; MX_TIM1_Init(); LL_TIM_CC_EnableChannel(TIM1, LL_TIM_CHANNEL_CH1); LL_TIM_CC_EnableChannel(TIM1, LL_TIM_CHANNEL_CH2); LL_TIM_EnableCounter(TIM1); /* ARM PID Instance, float_32 format */ arm_pid_instance_f32 PID; float32_t pid_error; /* Set PID parameters */ /* Set this for your needs */ PID.Kp = PID_PARAM_KP; /* Proporcional */ PID.Ki = PID_PARAM_KI; /* Integral */ PID.Kd = PID_PARAM_KD; /* Derivative */ /* Initialize PID system, float32_t format */ arm_pid_init_f32(&PID, 1); /* Infinite loop */ for(;;) { EncoderCurr = LL_TIM_GetCounter(TIM1); uint32_t dir = LL_TIM_GetDirection(TIM1); RPM = (EncoderCurr - EncoderLast) / 360 * 480 * 30; EncoderLast = EncoderCurr; //ITM_SendChar('0' + RPM); //ITM_SendChar('0' + EncoderCurr); //printf("EncoderCurr: %d \r\n", (int)EncoderCurr); printf("dir: %d \r\n", (int)dir); /* Calculate error */ //pid_error = TEMP_CURRENT - TEMP_WANT; pid_error = 1.0; /* Calculate PID here, argument is error */ /* Output data will be returned, we will use it as duty cycle parameter */ //pmw = (uint32_t)arm_pid_f32(&PID, pid_error); osDelay(500); } /* USER CODE END EncoderTaskHandler */ } /* USER CODE BEGIN Header_RosSpinTaskHandler */ /** * @brief Function implementing the RosSpinTask thread. * @param argument: Not used * @retval None */ /* USER CODE END Header_RosSpinTaskHandler */ void RosSpinTaskHandler(void const * argument) { /* USER CODE BEGIN RosSpinTaskHandler */ /* Infinite loop */ for(;;) { nh.spinOnce(); } /* USER CODE END RosSpinTaskHandler */ } /* USER CODE BEGIN Header_RosSubscriberTaskHandler */ /** * @brief Function implementing the RosSubscriberTa thread. * @param argument: Not used * @retval None */ /* USER CODE END Header_RosSubscriberTaskHandler */ void RosSubscriberTaskHandler(void const * argument) { /* USER CODE BEGIN RosSubscriberTaskHandler */ ros::Subscriber<std_msgs::UInt16> sub_motor("motor", motor_cb); ros::Subscriber<std_msgs::UInt16> sub_pid("pid", pid_cb); nh.subscribe(sub_motor); nh.subscribe(sub_pid); /* Infinite loop */ for(;;) { osDelay(200); //osStatus evt = osMessageGet (RosSubsriberQueue, 0); } /* USER CODE END RosSubscriberTaskHandler */ } /* USER CODE BEGIN Header_RosPublisherTaskHandler */ /** * @brief Function implementing the RosPublisherTas thread. * @param argument: Not used * @retval None */ /* USER CODE END Header_RosPublisherTaskHandler */ void RosPublisherTaskHandler(void const * argument) { /* USER CODE BEGIN RosPublisherTaskHandler */ /* Infinite loop */ for(;;) { osDelay(1); } /* USER CODE END RosPublisherTaskHandler */ } /* Private application code --------------------------------------------------*/ /* USER CODE BEGIN Application */ void motor_cb(const std_msgs::UInt16& cmd_msg) { //cmd_msg.data should be in range 0 - 100 //nh.logdebug("motor_cb\r\n"); //osMessagePut(RosSubsriberQueue, cmd_msg, 0); /* debug code: */ switch(cmd_msg.data) { case 0: LL_GPIO_ResetOutputPin(LD2_GPIO_Port, LD2_Pin); break; case 1: LL_GPIO_SetOutputPin(LD2_GPIO_Port, LD2_Pin); break; } //ITM_SendChar('B'); } void pid_cb(const std_msgs::UInt16& cmd_msg) { } /* USER CODE END Application */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ <|start_filename|>leobot_hardware/firmware/STM32F767_Firmware/Core/Src/usart.c<|end_filename|> /** ****************************************************************************** * File Name : USART.c * Description : This file provides code for the configuration * of the USART instances. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "usart.h" /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /* USART3 init function */ void MX_USART3_UART_Init(void) { LL_USART_InitTypeDef USART_InitStruct = {0}; LL_GPIO_InitTypeDef GPIO_InitStruct = {0}; /* Peripheral clock enable */ LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_USART3); LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_GPIOD); /**USART3 GPIO Configuration PD8 ------> USART3_TX PD9 ------> USART3_RX */ GPIO_InitStruct.Pin = LL_GPIO_PIN_8; GPIO_InitStruct.Mode = LL_GPIO_MODE_ALTERNATE; GPIO_InitStruct.Speed = LL_GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.OutputType = LL_GPIO_OUTPUT_PUSHPULL; GPIO_InitStruct.Pull = LL_GPIO_PULL_NO; GPIO_InitStruct.Alternate = LL_GPIO_AF_7; LL_GPIO_Init(GPIOD, &GPIO_InitStruct); GPIO_InitStruct.Pin = LL_GPIO_PIN_9; GPIO_InitStruct.Mode = LL_GPIO_MODE_ALTERNATE; GPIO_InitStruct.Speed = LL_GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.OutputType = LL_GPIO_OUTPUT_PUSHPULL; GPIO_InitStruct.Pull = LL_GPIO_PULL_NO; GPIO_InitStruct.Alternate = LL_GPIO_AF_7; LL_GPIO_Init(GPIOD, &GPIO_InitStruct); /* USART3 interrupt Init */ NVIC_SetPriority(USART3_IRQn, NVIC_EncodePriority(NVIC_GetPriorityGrouping(),5, 0)); NVIC_EnableIRQ(USART3_IRQn); USART_InitStruct.BaudRate = 115200; USART_InitStruct.DataWidth = LL_USART_DATAWIDTH_8B; USART_InitStruct.StopBits = LL_USART_STOPBITS_1; USART_InitStruct.Parity = LL_USART_PARITY_NONE; USART_InitStruct.TransferDirection = LL_USART_DIRECTION_TX_RX; USART_InitStruct.HardwareFlowControl = LL_USART_HWCONTROL_NONE; USART_InitStruct.OverSampling = LL_USART_OVERSAMPLING_16; LL_USART_Init(USART3, &USART_InitStruct); LL_USART_ConfigAsyncMode(USART3); LL_USART_Enable(USART3); } /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ <|start_filename|>leobot_hardware/src/hardware_node.cpp<|end_filename|> /** * Copyright 2019 ROS Ukraine * * 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 "leobot_hardware/robot_hardware.h" #include <string> #include <controller_manager/controller_manager.h> #include <hardware_interface/actuator_state_interface.h> #include <ros/callback_queue.h> using leobot_hardware::LeobotRobotHW; int main(int argc, char **argv) { const double ACTUAL_CYCLE = 0.75; std::string node_name = "leobot_hardware_node"; ros::init(argc, argv, node_name); ros::NodeHandle top_level_node_handle; ros::NodeHandle root_node_handle("~"); ros::NodeHandle private_node("~"); ros::CallbackQueue generic_queue; top_level_node_handle.setCallbackQueue(&generic_queue); root_node_handle.setCallbackQueue(&generic_queue); ros::AsyncSpinner spinner(2, &generic_queue); spinner.start(); ros::CallbackQueue read_state_queue; private_node.setCallbackQueue(&read_state_queue); LeobotRobotHW robot_hardware; robot_hardware.init(root_node_handle, private_node); controller_manager::ControllerManager controller_manager(&robot_hardware, top_level_node_handle); struct timespec last_time; struct timespec current_time; clock_gettime(CLOCK_MONOTONIC, &last_time); double loop_rate; private_node.param<double>("loop_rate", loop_rate, 10.0); ros::Duration desired_update_duration = ros::Duration(1.0 / loop_rate); ros::Duration communicaton_wait_duration = ros::Duration(ACTUAL_CYCLE / loop_rate); ros::Rate rate(loop_rate / ACTUAL_CYCLE); while (ros::ok()) { clock_gettime(CLOCK_MONOTONIC, &current_time); ros::Duration elapsed_time = ros::Duration(current_time.tv_sec - last_time.tv_sec + (current_time.tv_nsec - last_time.tv_nsec) / 1e+9); last_time = current_time; if (elapsed_time > desired_update_duration) { ROS_WARN_STREAM_THROTTLE(2.0, "Cycle time exceeded error threshold by: " << (elapsed_time - desired_update_duration) << ", cycle time: " << elapsed_time << ", desired_update_duration: " << desired_update_duration); } ros::Time timestamp = ros::Time::now(); read_state_queue.clear(); read_state_queue.callOne(ros::WallDuration(communicaton_wait_duration.toSec())); robot_hardware.read(timestamp, elapsed_time); controller_manager.update(ros::Time::now(), elapsed_time); robot_hardware.write(timestamp, elapsed_time); rate.sleep(); } spinner.stop(); return 0; } <|start_filename|>leobot_web_server/scripts/web_server.js<|end_filename|> #!/usr/bin/env nodejs 'use strict'; const fs = require('fs'); const path = require('path'); const rosnodejs = require('rosnodejs'); const nodeStatic = require('node-static'); function startWebServer(){ rosnodejs.initNode('leobot_web_server').then(() => { const nh = rosnodejs.nh; console.log('rosnodejs handle: ' + nh); nh.getParam('~port').then((port) => { const webContentFolderPath = '../web_content'; const webContentFolderAbsolutePath = path.join(__dirname, webContentFolderPath); console.log('Starting the web server in folder ' + webContentFolderAbsolutePath); // This command will fail if path is incorrect const webContentFolderRealPath = fs.realpathSync(webContentFolderAbsolutePath); const file = new(nodeStatic.Server)(webContentFolderRealPath); require('http').createServer(function (request, response) { file.serve(request, response); }).listen(port); console.log('Web server started at port ' + port); }); }); }; // If this module is executed directly rather than included as a library if (require.main === module) { startWebServer(); }; <|start_filename|>leobot_hardware/firmware/STM32F767_Firmware/Libs/rosserial/leobot_msgs/FirmwareCommandWrite.h<|end_filename|> #ifndef _ROS_leobot_msgs_FirmwareCommandWrite_h #define _ROS_leobot_msgs_FirmwareCommandWrite_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" namespace leobot_msgs { class FirmwareCommandWrite : public ros::Msg { public: typedef float _motor_1_p_type; _motor_1_p_type motor_1_p; typedef float _motor_1_i_type; _motor_1_i_type motor_1_i; typedef float _motor_1_d_type; _motor_1_d_type motor_1_d; typedef float _motor_2_p_type; _motor_2_p_type motor_2_p; typedef float _motor_2_i_type; _motor_2_i_type motor_2_i; typedef float _motor_2_d_type; _motor_2_d_type motor_2_d; typedef float _motor_3_p_type; _motor_3_p_type motor_3_p; typedef float _motor_3_i_type; _motor_3_i_type motor_3_i; typedef float _motor_3_d_type; _motor_3_d_type motor_3_d; typedef float _motor_4_p_type; _motor_4_p_type motor_4_p; typedef float _motor_4_i_type; _motor_4_i_type motor_4_i; typedef float _motor_4_d_type; _motor_4_d_type motor_4_d; typedef float _motor_1_velocity_command_type; _motor_1_velocity_command_type motor_1_velocity_command; typedef float _motor_2_velocity_command_type; _motor_2_velocity_command_type motor_2_velocity_command; typedef float _motor_3_velocity_command_type; _motor_3_velocity_command_type motor_3_velocity_command; typedef float _motor_4_velocity_command_type; _motor_4_velocity_command_type motor_4_velocity_command; FirmwareCommandWrite(): motor_1_p(0), motor_1_i(0), motor_1_d(0), motor_2_p(0), motor_2_i(0), motor_2_d(0), motor_3_p(0), motor_3_i(0), motor_3_d(0), motor_4_p(0), motor_4_i(0), motor_4_d(0), motor_1_velocity_command(0), motor_2_velocity_command(0), motor_3_velocity_command(0), motor_4_velocity_command(0) { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; union { float real; uint32_t base; } u_motor_1_p; u_motor_1_p.real = this->motor_1_p; *(outbuffer + offset + 0) = (u_motor_1_p.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_1_p.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_1_p.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_1_p.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_1_p); union { float real; uint32_t base; } u_motor_1_i; u_motor_1_i.real = this->motor_1_i; *(outbuffer + offset + 0) = (u_motor_1_i.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_1_i.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_1_i.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_1_i.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_1_i); union { float real; uint32_t base; } u_motor_1_d; u_motor_1_d.real = this->motor_1_d; *(outbuffer + offset + 0) = (u_motor_1_d.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_1_d.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_1_d.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_1_d.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_1_d); union { float real; uint32_t base; } u_motor_2_p; u_motor_2_p.real = this->motor_2_p; *(outbuffer + offset + 0) = (u_motor_2_p.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_2_p.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_2_p.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_2_p.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_2_p); union { float real; uint32_t base; } u_motor_2_i; u_motor_2_i.real = this->motor_2_i; *(outbuffer + offset + 0) = (u_motor_2_i.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_2_i.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_2_i.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_2_i.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_2_i); union { float real; uint32_t base; } u_motor_2_d; u_motor_2_d.real = this->motor_2_d; *(outbuffer + offset + 0) = (u_motor_2_d.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_2_d.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_2_d.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_2_d.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_2_d); union { float real; uint32_t base; } u_motor_3_p; u_motor_3_p.real = this->motor_3_p; *(outbuffer + offset + 0) = (u_motor_3_p.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_3_p.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_3_p.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_3_p.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_3_p); union { float real; uint32_t base; } u_motor_3_i; u_motor_3_i.real = this->motor_3_i; *(outbuffer + offset + 0) = (u_motor_3_i.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_3_i.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_3_i.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_3_i.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_3_i); union { float real; uint32_t base; } u_motor_3_d; u_motor_3_d.real = this->motor_3_d; *(outbuffer + offset + 0) = (u_motor_3_d.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_3_d.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_3_d.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_3_d.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_3_d); union { float real; uint32_t base; } u_motor_4_p; u_motor_4_p.real = this->motor_4_p; *(outbuffer + offset + 0) = (u_motor_4_p.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_4_p.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_4_p.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_4_p.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_4_p); union { float real; uint32_t base; } u_motor_4_i; u_motor_4_i.real = this->motor_4_i; *(outbuffer + offset + 0) = (u_motor_4_i.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_4_i.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_4_i.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_4_i.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_4_i); union { float real; uint32_t base; } u_motor_4_d; u_motor_4_d.real = this->motor_4_d; *(outbuffer + offset + 0) = (u_motor_4_d.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_4_d.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_4_d.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_4_d.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_4_d); union { float real; uint32_t base; } u_motor_1_velocity_command; u_motor_1_velocity_command.real = this->motor_1_velocity_command; *(outbuffer + offset + 0) = (u_motor_1_velocity_command.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_1_velocity_command.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_1_velocity_command.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_1_velocity_command.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_1_velocity_command); union { float real; uint32_t base; } u_motor_2_velocity_command; u_motor_2_velocity_command.real = this->motor_2_velocity_command; *(outbuffer + offset + 0) = (u_motor_2_velocity_command.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_2_velocity_command.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_2_velocity_command.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_2_velocity_command.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_2_velocity_command); union { float real; uint32_t base; } u_motor_3_velocity_command; u_motor_3_velocity_command.real = this->motor_3_velocity_command; *(outbuffer + offset + 0) = (u_motor_3_velocity_command.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_3_velocity_command.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_3_velocity_command.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_3_velocity_command.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_3_velocity_command); union { float real; uint32_t base; } u_motor_4_velocity_command; u_motor_4_velocity_command.real = this->motor_4_velocity_command; *(outbuffer + offset + 0) = (u_motor_4_velocity_command.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_motor_4_velocity_command.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_motor_4_velocity_command.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_motor_4_velocity_command.base >> (8 * 3)) & 0xFF; offset += sizeof(this->motor_4_velocity_command); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; union { float real; uint32_t base; } u_motor_1_p; u_motor_1_p.base = 0; u_motor_1_p.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_1_p.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_1_p.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_1_p.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_1_p = u_motor_1_p.real; offset += sizeof(this->motor_1_p); union { float real; uint32_t base; } u_motor_1_i; u_motor_1_i.base = 0; u_motor_1_i.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_1_i.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_1_i.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_1_i.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_1_i = u_motor_1_i.real; offset += sizeof(this->motor_1_i); union { float real; uint32_t base; } u_motor_1_d; u_motor_1_d.base = 0; u_motor_1_d.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_1_d.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_1_d.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_1_d.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_1_d = u_motor_1_d.real; offset += sizeof(this->motor_1_d); union { float real; uint32_t base; } u_motor_2_p; u_motor_2_p.base = 0; u_motor_2_p.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_2_p.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_2_p.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_2_p.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_2_p = u_motor_2_p.real; offset += sizeof(this->motor_2_p); union { float real; uint32_t base; } u_motor_2_i; u_motor_2_i.base = 0; u_motor_2_i.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_2_i.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_2_i.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_2_i.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_2_i = u_motor_2_i.real; offset += sizeof(this->motor_2_i); union { float real; uint32_t base; } u_motor_2_d; u_motor_2_d.base = 0; u_motor_2_d.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_2_d.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_2_d.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_2_d.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_2_d = u_motor_2_d.real; offset += sizeof(this->motor_2_d); union { float real; uint32_t base; } u_motor_3_p; u_motor_3_p.base = 0; u_motor_3_p.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_3_p.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_3_p.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_3_p.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_3_p = u_motor_3_p.real; offset += sizeof(this->motor_3_p); union { float real; uint32_t base; } u_motor_3_i; u_motor_3_i.base = 0; u_motor_3_i.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_3_i.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_3_i.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_3_i.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_3_i = u_motor_3_i.real; offset += sizeof(this->motor_3_i); union { float real; uint32_t base; } u_motor_3_d; u_motor_3_d.base = 0; u_motor_3_d.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_3_d.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_3_d.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_3_d.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_3_d = u_motor_3_d.real; offset += sizeof(this->motor_3_d); union { float real; uint32_t base; } u_motor_4_p; u_motor_4_p.base = 0; u_motor_4_p.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_4_p.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_4_p.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_4_p.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_4_p = u_motor_4_p.real; offset += sizeof(this->motor_4_p); union { float real; uint32_t base; } u_motor_4_i; u_motor_4_i.base = 0; u_motor_4_i.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_4_i.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_4_i.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_4_i.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_4_i = u_motor_4_i.real; offset += sizeof(this->motor_4_i); union { float real; uint32_t base; } u_motor_4_d; u_motor_4_d.base = 0; u_motor_4_d.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_4_d.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_4_d.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_4_d.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_4_d = u_motor_4_d.real; offset += sizeof(this->motor_4_d); union { float real; uint32_t base; } u_motor_1_velocity_command; u_motor_1_velocity_command.base = 0; u_motor_1_velocity_command.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_1_velocity_command.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_1_velocity_command.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_1_velocity_command.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_1_velocity_command = u_motor_1_velocity_command.real; offset += sizeof(this->motor_1_velocity_command); union { float real; uint32_t base; } u_motor_2_velocity_command; u_motor_2_velocity_command.base = 0; u_motor_2_velocity_command.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_2_velocity_command.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_2_velocity_command.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_2_velocity_command.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_2_velocity_command = u_motor_2_velocity_command.real; offset += sizeof(this->motor_2_velocity_command); union { float real; uint32_t base; } u_motor_3_velocity_command; u_motor_3_velocity_command.base = 0; u_motor_3_velocity_command.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_3_velocity_command.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_3_velocity_command.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_3_velocity_command.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_3_velocity_command = u_motor_3_velocity_command.real; offset += sizeof(this->motor_3_velocity_command); union { float real; uint32_t base; } u_motor_4_velocity_command; u_motor_4_velocity_command.base = 0; u_motor_4_velocity_command.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_motor_4_velocity_command.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_motor_4_velocity_command.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_motor_4_velocity_command.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->motor_4_velocity_command = u_motor_4_velocity_command.real; offset += sizeof(this->motor_4_velocity_command); return offset; } const char * getType(){ return "leobot_msgs/FirmwareCommandWrite"; }; const char * getMD5(){ return "3fc1e386055fce07b1eb02500bb1ca44"; }; }; } #endif
ros-ukraine/leobot
<|start_filename|>src/utils/index.js<|end_filename|> export function kebabify(prop) { const upperToHyphen = (match, offset, string) => { const addDash = offset && string.charAt(offset - 1) !== '-'; return (addDash ? '-' : '') + match.toLowerCase(); }; return prop.replace(/[A-Z]/g, upperToHyphen); } export const isPlainObject = arg => Object.prototype.toString.call(arg) === '[object Object]'; <|start_filename|>test/fixture/control/input.css<|end_filename|> :root { --should-be-removed: { content: 'gone'; } } .control { content: 'control'; } .should-pass { @apply not-a-prop-set; } .should-warn--not-root { --toolbar-title-theme: { color: green; } } .should-warn--not-declared { @apply --this-should-warn; } --should-warn-about-root-scope-and-be-removed: { color: green; } @apply --should-warn-about-root-scope-and-be-removed; <|start_filename|>src/visitor.js<|end_filename|> /* eslint-disable no-param-reassign */ import balanced from 'balanced-match'; import postcss from 'postcss'; import { kebabify, isPlainObject } from './utils'; const RE_PROP_SET = /^(--)([\w-]+)(\s*)([:]?)$/; export default class Visitor { cache = {}; result = {}; options = {}; defaults = { preserve: false, sets: {}, }; constructor(options) { this.options = { ...this.defaults, ...options, }; } /** * Prepend JS defined sets into the cache before parsing. * This means CSS defined sets will overrides them if they share the same name. */ prepend = () => { const { sets } = this.options; Object.keys(sets).forEach(setName => { const newRule = postcss.rule({ selector: `--${setName}` }); const set = sets[setName]; if (typeof set === 'string') { newRule.prepend(set); } else if (isPlainObject(set)) { Object.entries(set).forEach(([prop, value]) => { newRule.prepend(postcss.decl({ prop: kebabify(prop), value })); }); } else { throw new Error( `Unrecognized set type \`${typeof set}\`, must be an object or string.` ); } this.cache[setName] = newRule; }); }; /** * Collect all `:root` declared property sets and save them. */ collect = rule => { const matches = RE_PROP_SET.exec(rule.selector); if (!matches) { return; } const setName = matches[2]; const { parent } = rule; if (parent.selector !== ':root') { rule.warn( this.result, 'Custom property set ignored: not scoped to top-level `:root` ' + `(--${setName}` + `${parent.type === 'rule' ? ` declared in ${parent.selector}` : ''})` ); if (parent.type === 'root') { rule.remove(); } return; } // Custom property sets override each other wholly, // rather than cascading together like colliding style rules do. // @see: https://tabatkins.github.io/specs/css-apply-rule/#defining const newRule = rule.clone(); this.cache[setName] = newRule; if (!this.options.preserve) { removeCommentBefore(rule); safeRemoveRule(rule); } if (!parent.nodes.length) { parent.remove(); } }; /** * Replace nested `@apply` at-rules declarations. */ resolveNested = () => { Object.keys(this.cache).forEach(rule => { this.cache[rule].walkAtRules('apply', atRule => { this.resolve(atRule); // @TODO honor `preserve` option. atRule.remove(); }); }); }; /** * Replace `@apply` at-rules declarations with provided custom property set. */ resolve = atRule => { let ancestor = atRule.parent; while (ancestor && ancestor.type !== 'rule') { ancestor = ancestor.parent; } if (!ancestor) { atRule.warn( this.result, 'The @apply rule can only be declared inside Rule type nodes.' ); atRule.remove(); return; } if (isDefinition(atRule.parent)) { return; } const param = getParamValue(atRule.params); const matches = RE_PROP_SET.exec(param); if (!matches) { return; } const setName = matches[2]; const { parent } = atRule; if (!(setName in this.cache)) { atRule.warn( this.result, `No custom property set declared for \`${setName}\`.` ); return; } const newRule = this.cache[setName].clone(); cleanIndent(newRule); if (this.options.preserve) { parent.insertBefore(atRule, newRule.nodes); return; } atRule.replaceWith(newRule.nodes); }; } /** * Helper: return whether the rule is a custom property set definition. */ function isDefinition(rule) { return ( !!rule.selector && !!RE_PROP_SET.exec(rule.selector) && rule.parent && !!rule.parent.selector && rule.parent.selector === ':root' ); } /** * Helper: allow parens usage in `@apply` AtRule declaration. * This is for Polymer integration. */ function getParamValue(param) { return /^\(/.test(param) ? balanced('(', ')', param).body : param; } /** * Helper: remove excessive declarations indentation. */ function cleanIndent(rule) { rule.walkDecls(decl => { if (typeof decl.raws.before === 'string') { decl.raws.before = decl.raws.before.replace(/[^\S\n\r]{2,}/, ' '); } }); } /** * Helper: correctly handle property sets removal and semi-colons. * @See: postcss/postcss#1014 */ function safeRemoveRule(rule) { if (rule === rule.parent.last && rule.raws.ownSemicolon) { rule.parent.raws.semicolon = true; } rule.remove(); } /** * Helper: remove immediate preceding comments. */ function removeCommentBefore(node) { const previousNode = node.prev(); if (previousNode && previousNode.type === 'comment') { previousNode.remove(); } } <|start_filename|>test/integration.spec.js<|end_filename|> import postcss from 'postcss'; import { stripIndent } from 'common-tags'; import customProperties from 'postcss-custom-properties'; import plugin from '../src'; describe('integration', () => { test('custom properties declaration without plugin', async () => { const input = stripIndent` :root { --should-stay: 'test'; --should-be-removed: { content: 'gone'; }; }`; const expected = stripIndent` :root { --should-stay: 'test'; }`; const result = await postcss() .use(plugin) .process(input, { from: undefined }); expect(result.css).toBe(expected); }); test('custom properties declaration with plugin first', async () => { const input = stripIndent` :root { --should-be-pruned: 'pruned'; --should-be-removed: { content: 'gone'; }; }`; const expected = input; const result = await postcss() .use(customProperties) .process(input, { from: undefined }); expect(result.css).toBe(expected); }); test('custom properties declaration with plugin last', async () => { const input = stripIndent` :root { --should-be-pruned: 'pruned'; --should-be-removed: { content: 'gone'; }; }`; const expected = stripIndent` :root { --should-be-pruned: 'pruned'; }`; const result = await postcss() .use(plugin) .use(customProperties) .process(input, { from: undefined }); expect(result.css).toBe(expected); }); test('custom properties without plugin', async () => { const input = stripIndent` :root { --should-stay: 'test'; --should-be-removed: { content: 'gone'; }; } .test { @apply --should-be-removed; content: var(--should-stay); }`; const expected = stripIndent` :root { --should-stay: 'test'; } .test { content: 'gone'; content: var(--should-stay); }`; const result = await postcss() .use(plugin) .process(input, { from: undefined }); expect(result.css).toBe(expected); }); test('custom properties with plugin', async () => { const input = stripIndent` :root { --custom-prop: 'prop'; --custom-prop-set: { content: 'set'; }; } .test { @apply --custom-prop-set; content: var(--custom-prop); }`; const expected = stripIndent` :root { --custom-prop: 'prop'; } .test { content: 'set'; content: 'prop'; content: var(--custom-prop); }`; const result = await postcss() .use(customProperties) .use(plugin) .process(input, { from: undefined }); expect(result.css).toBe(expected); }); test('custom properties nested without plugin', async () => { const input = stripIndent` :root { --custom-prop: 'prop'; --custom-prop-set: { content: var(--custom-prop); }; } .test { @apply --custom-prop-set; content: var(--custom-prop); }`; const expected = stripIndent` :root { --custom-prop: 'prop'; } .test { content: var(--custom-prop); content: var(--custom-prop); }`; const result = await postcss() .use(plugin) .process(input, { from: undefined }); expect(result.css).toBe(expected); }); test('custom properties nested with plugin first', async () => { const input = stripIndent` :root { --custom-prop: 'prop'; --custom-prop-set: { content: var(--custom-prop); }; } .test { @apply --custom-prop-set; content: var(--custom-prop); }`; const expected = stripIndent` :root { --custom-prop: 'prop'; } .test { content: 'prop'; content: var(--custom-prop); content: 'prop'; content: var(--custom-prop); }`; const result = await postcss() .use(customProperties) .use(plugin) .process(input, { from: undefined }); expect(result.css).toBe(expected); }); test('custom properties nested with plugin last', async () => { const input = stripIndent` :root { --custom-prop: 'prop'; --custom-prop-set: { content: var(--custom-prop); }; } .test { @apply --custom-prop-set; content: var(--custom-prop); }`; const expected = stripIndent` :root { --custom-prop: 'prop'; } .test { content: 'prop'; content: var(--custom-prop); content: 'prop'; content: var(--custom-prop); }`; const result = await postcss() .use(plugin) .use(customProperties) .process(input, { from: undefined }); expect(result.css).toBe(expected); }); test('custom properties nested with plugin first [preserve: false]', async () => { const input = stripIndent` :root { --custom-prop: 'prop'; --custom-prop-set: { content: var(--custom-prop); }; } .test { @apply --custom-prop-set; content: var(--custom-prop); }`; const expected = stripIndent` .test { content: 'prop'; content: 'prop'; }`; const result = await postcss() .use(customProperties({ preserve: false })) .use(plugin) .process(input, { from: undefined }); expect(result.css).toBe(expected); }); test('custom properties nested with plugin last [preserve: false]', async () => { const input = stripIndent` :root { --custom-prop: 'prop'; --custom-prop-set: { content: var(--custom-prop); }; } .test { @apply --custom-prop-set; content: var(--custom-prop); }`; const expected = stripIndent` .test { content: 'prop'; content: 'prop'; }`; const result = await postcss() .use(plugin) .use(customProperties({ preserve: false })) .process(input, { from: undefined }); expect(result.css).toBe(expected); }); }); <|start_filename|>test/utils.spec.js<|end_filename|> import { kebabify, isPlainObject } from '../src/utils'; describe('kekabify', () => { it('should convert camelCase properties to kebab-case', () => { const input = [ 'borderRadius', 'backgroundColor', 'background-color', 'fontSize', 'font-size', 'borderTopLeftRadius', '-moz-Whatever', '-webkit-whoCares', '--customProp', '--CustomProp', '--custom-prop', ]; const result = input.map(kebabify); expect(result).toMatchSnapshot(); }); }); describe('isPlainObject', () => { it('should assert for plain object types', () => { expect(isPlainObject({})).toBe(true); expect(isPlainObject([])).toBe(false); expect(isPlainObject(null)).toBe(false); expect(isPlainObject('')).toBe(false); }); }); <|start_filename|>src/index.js<|end_filename|> import { plugin } from 'postcss'; import Visitor from './visitor'; import { name } from '../package.json'; export default plugin(name, options => (css, result) => { const visitor = new Visitor(options); visitor.result = result; visitor.prepend(); css.walkRules(visitor.collect); visitor.resolveNested(); css.walkAtRules('apply', visitor.resolve); }); <|start_filename|>test/preserve.spec.js<|end_filename|> import fs from 'fs'; import path from 'path'; import postcss from 'postcss'; import plugin from '../src'; const read = name => fs.readFileSync(path.join(__dirname, 'fixture', name), 'utf8'); describe('the `preserve` option', () => { it('should properly apply and preserve custom property sets', async () => { const input = read('preserve/input.css'); const expected = read('preserve/expected.css'); const result = await postcss() .use(plugin({ preserve: true })) .process(input, { from: undefined }); expect(result.css).toBe(expected); }); }); <|start_filename|>develop/index.js<|end_filename|> /* eslint-disable no-console */ import fs from 'fs'; import path from 'path'; import postcss from 'postcss'; import reporter from 'postcss-reporter'; import plugin from '../src'; let from, to; let read = name => fs.readFileSync(path.join(process.cwd(), 'test', 'fixture', name), 'utf8'); let input = read('apply/input.css'); postcss() .use(plugin) .use(reporter) .process(input, { from, to }) .then(result => { console.log(result.css); }) .catch(console.error); <|start_filename|>test/comments.spec.js<|end_filename|> import postcss from 'postcss'; import plugin from '../src'; const input = ` :root { /* This should be pruned */ --toolbar-theme: { color: orangeRed; } } .toolbar { @apply --toolbar-theme; } `; let from; describe('comments', () => { it('should remove immediate preceding comments in declarations', async () => { const result = await postcss().use(plugin).process(input, { from }); expect(result.css).toMatchSnapshot(); }); it('should not remove immediate preceding comments in declarations with the preserve option', async () => { const result = await postcss() .use(plugin({ preserve: true })) .process(input, { from }); expect(result.css).toMatchSnapshot(); }); }); <|start_filename|>test/prepend.spec.js<|end_filename|> import postcss from 'postcss'; import { stripIndent } from 'common-tags'; import plugin from '../src'; describe('prepend', () => { describe('should prepend sets from options', () => { it('from an object set', async () => { const input = stripIndent` .dummy { @apply --justatest; } `; const sets = { justatest: { padding: '0 1rem', fontSize: '1.4rem', color: 'tomato', }, }; const result = await postcss() .use(plugin({ sets })) .process(input, { from: undefined }); expect(result.css).toMatchSnapshot(); }); it('from a string set', async () => { const input = stripIndent` .dummy { @apply --justatest; } `; const sets = { justatest: ` fontSize: 1.4rem; @media (width >= 500px) { fontSize: 2.4rem; } `, }; const result = await postcss() .use(plugin({ sets })) .process(input, { from: undefined }); expect(result.css).toMatchSnapshot(); }); it('throws if the set is not an object or a string', async () => { const input = stripIndent` .dummy { @apply --justatest; } `; const sets = { justatest: () => {}, }; expect(() => { postcss() // eslint-disable-line no-unused-expressions .use(plugin({ sets })) .process(input, { from: undefined }).css; }).toThrow( 'Unrecognized set type `function`, must be an object or string.' ); }); }); it('should override sets from options with CSS declared ones', async () => { const input = stripIndent` :root { --justatest: { padding: none; color: orangeRed; } } .dummy { @apply --justatest; } `; const sets = { justatest: { padding: '0 1rem', fontSize: '1.4rem', color: 'tomato', }, }; const result = await postcss() .use(plugin({ sets })) .process(input, { from: undefined }); expect(result.css).toMatchSnapshot(); }); it('should be able to be nested inside a CSS declared set', async () => { const input = stripIndent` :root { --from-css: { @apply --from-js; } } .dummy { @apply --from-css; } `; const sets = { 'from-js': { color: 'tomato', }, }; const result = await postcss() .use(plugin({ sets })) .process(input, { from: undefined }); expect(result.css).toMatchSnapshot(); }); });
pascalduez/postcss-apply
<|start_filename|>commands/fetchnvd.go<|end_filename|> package commands import ( "time" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/vulsio/go-cve-dictionary/db" log "github.com/vulsio/go-cve-dictionary/log" "github.com/vulsio/go-cve-dictionary/models" "golang.org/x/xerrors" ) var fetchNvdCmd = &cobra.Command{ Use: "nvd", Short: "Fetch Vulnerability dictionary from NVD", Long: "Fetch Vulnerability dictionary from NVD", RunE: fetchNvd, } func init() { fetchCmd.AddCommand(fetchNvdCmd) fetchNvdCmd.PersistentFlags().Bool("full", false, "Collect large amounts of CPE relate data") _ = viper.BindPFlag("full", fetchNvdCmd.PersistentFlags().Lookup("full")) } func fetchNvd(_ *cobra.Command, args []string) (err error) { if err := log.SetLogger(viper.GetBool("log-to-file"), viper.GetString("log-dir"), viper.GetBool("debug"), viper.GetBool("log-json")); err != nil { return xerrors.Errorf("Failed to SetLogger. err: %w", err) } driver, locked, err := db.NewDB(viper.GetString("dbtype"), viper.GetString("dbpath"), viper.GetBool("debug-sql"), db.Option{}) if err != nil { if locked { return xerrors.Errorf("Failed to initialize DB. Close DB connection before fetching. err: %w", err) } return xerrors.Errorf("Failed to open DB. err: %w", err) } fetchMeta, err := driver.GetFetchMeta() if err != nil { return xerrors.Errorf("Failed to get FetchMeta from DB. err: %w", err) } if fetchMeta.OutDated() { return xerrors.Errorf("Failed to Insert CVEs into DB. err: SchemaVersion is old. SchemaVersion: %+v", map[string]uint{"latest": models.LatestSchemaVersion, "DB": fetchMeta.SchemaVersion}) } // If the fetch fails the first time (without SchemaVersion), the DB needs to be cleaned every time, so insert SchemaVersion. if err := driver.UpsertFetchMeta(fetchMeta); err != nil { return xerrors.Errorf("Failed to upsert FetchMeta to DB. dbpath: %s, err: %w", viper.GetString("dbpath"), err) } log.Infof("Inserting NVD into DB (%s).", driver.Name()) if err := driver.InsertNvd(args); err != nil { return xerrors.Errorf("Failed to insert. dbpath: %s, err: %w", viper.GetString("dbpath"), err) } fetchMeta.LastFetchedAt = time.Now() if err := driver.UpsertFetchMeta(fetchMeta); err != nil { return xerrors.Errorf("Failed to upsert FetchMeta to DB. dbpath: %s, err: %w", viper.GetString("dbpath"), err) } log.Infof("Finished fetching NVD.") return nil } <|start_filename|>fetcher/jvn/jvn.go<|end_filename|> package jvn import ( "encoding/xml" "fmt" "net/http" "net/url" "regexp" "runtime" "strings" "time" "github.com/PuerkitoBio/goquery" "github.com/spf13/viper" "github.com/vulsio/go-cve-dictionary/fetcher" "github.com/vulsio/go-cve-dictionary/log" "github.com/vulsio/go-cve-dictionary/models" "github.com/vulsio/go-cve-dictionary/util" "golang.org/x/xerrors" ) // Meta ... https://jvndb.jvn.jp/ja/feed/checksum.txt type Meta struct { URL string `json:"url"` Hash string `json:"sha256"` LastModified string `json:"lastModified"` } type rdf struct { Items []Item `xml:"item"` } // Item ... http://jvndb.jvn.jp/apis/getVulnOverviewList_api.html type Item struct { About string `xml:"about,attr"` Title string `xml:"title"` Link string `xml:"link"` Description string `xml:"description"` Publisher string `xml:"publisher"` Identifier string `xml:"identifier"` References []references `xml:"references"` Cpes []cpe `xml:"cpe"` Cvsses []Cvss `xml:"cvss"` Date string `xml:"date"` Issued string `xml:"issued"` Modified string `xml:"modified"` } type cpe struct { Version string `xml:"version,attr"` // cpe:/a:mysql:mysql Vendor string `xml:"vendor,attr"` Product string `xml:"product,attr"` Value string `xml:",chardata"` } type references struct { ID string `xml:"id,attr"` Source string `xml:"source,attr"` Title string `xml:"title,attr"` URL string `xml:",chardata"` } // Cvss ... CVSS type Cvss struct { Score string `xml:"score,attr"` Severity string `xml:"severity,attr"` Vector string `xml:"vector,attr"` Version string `xml:"version,attr"` } // FetchConvert Fetch CVE vulnerability information from JVN func FetchConvert(uniqCve map[string]map[string]models.Jvn, years []string) error { for _, y := range years { items, err := fetch(y) if err != nil { return xerrors.Errorf("Failed to fetch. err: %w", err) } cves, err := convert(items) if err != nil { return xerrors.Errorf("Failed to convert. err: %w", err) } distributeCvesByYear(uniqCve, cves) } return nil } func fetch(year string) ([]Item, error) { url, err := models.GetURLByYear(models.JvnType, year) if err != nil { return nil, xerrors.Errorf("Failed to GetURLByYear. err: %w", err) } body, err := fetcher.FetchFeedFile(url, false) if err != nil { return nil, xerrors.Errorf("Failed to FetchFeedFiles. err: %w", err) } var rdf rdf items := []Item{} if err := xml.Unmarshal([]byte(body), &rdf); err != nil { return nil, xerrors.Errorf("Failed to unmarshal. url: %s, err: %w", url, err) } for i, item := range rdf.Items { if !(strings.Contains(item.Description, "** 未確定 **") || strings.Contains(item.Description, "** サポート外 **") || strings.Contains(item.Description, "** 削除 **")) { items = append(items, rdf.Items[i]) } } return items, nil } func convert(items []Item) (map[string]models.Jvn, error) { reqChan := make(chan Item, len(items)) resChan := make(chan []models.Jvn, len(items)) errChan := make(chan error) defer close(reqChan) defer close(resChan) defer close(errChan) go func() { for _, item := range items { reqChan <- item } }() concurrency := runtime.NumCPU() + 2 tasks := util.GenWorkers(concurrency) for range items { tasks <- func() { req := <-reqChan cves, err := convertToModel(&req) if err != nil { errChan <- err return } resChan <- cves } } cves := map[string]models.Jvn{} errs := []error{} timeout := time.After(10 * 60 * time.Second) for range items { select { case res := <-resChan: for _, cve := range res { uniqJVNID := fmt.Sprintf("%s#%s", cve.JvnID, cve.CveID) cves[uniqJVNID] = cve } case err := <-errChan: errs = append(errs, err) case <-timeout: return nil, fmt.Errorf("Timeout Fetching") } } if 0 < len(errs) { return nil, xerrors.Errorf("%w", errs) } return cves, nil } // convertJvn converts Jvn structure(got from JVN) to model structure. func convertToModel(item *Item) (cves []models.Jvn, err error) { var cvss2, cvss3 Cvss for _, cvss := range item.Cvsses { if strings.HasPrefix(cvss.Version, "2") { cvss2 = cvss } else if strings.HasPrefix(cvss.Version, "3") { cvss3 = cvss } else { log.Warnf("Unknown CVSS version format: %s", cvss.Version) } } // References refs, links := []models.JvnReference{}, []string{} for _, r := range item.References { ref := models.JvnReference{ Reference: models.Reference{ Link: r.URL, Name: r.Title, Source: r.Source, }, } refs = append(refs, ref) if ref.Source == "JPCERT-AT" { links = append(links, r.URL) } } certs, err := collectCertLinks(links) if err != nil { return nil, xerrors.Errorf("Failed to collect links. err: %w", err) } // Cpes cpes := []models.JvnCpe{} for _, c := range item.Cpes { cpeBase, err := fetcher.ParseCpeURI(c.Value) if err != nil { // logging only log.Warnf("Failed to parse CPE URI: %s, %s", c.Value, err) continue } cpes = append(cpes, models.JvnCpe{ CpeBase: *cpeBase, }) } publish, err := parseJvnTime(item.Issued) if err != nil { return nil, err } modified, err := parseJvnTime(item.Modified) if err != nil { return nil, err } cveIDs := getCveIDs(*item) if len(cveIDs) == 0 { log.Debugf("No CveIDs in references. JvnID: %s, Link: %s", item.Identifier, item.Link) // ignore this item return nil, nil } for _, cveID := range cveIDs { v2elems := parseCvss2VectorStr(cvss2.Vector) v3elems := parseCvss3VectorStr(cvss3.Vector) cve := models.Jvn{ CveID: cveID, Title: strings.Replace(item.Title, "\r", "", -1), Summary: strings.Replace(item.Description, "\r", "", -1), JvnLink: item.Link, JvnID: item.Identifier, Cvss2: models.JvnCvss2{ Cvss2: models.Cvss2{ BaseScore: fetcher.StringToFloat(cvss2.Score), Severity: cvss2.Severity, VectorString: cvss2.Vector, AccessVector: v2elems[0], AccessComplexity: v2elems[1], Authentication: v2elems[2], ConfidentialityImpact: v2elems[3], IntegrityImpact: v2elems[4], AvailabilityImpact: v2elems[5], }, }, Cvss3: models.JvnCvss3{ Cvss3: models.Cvss3{ BaseScore: fetcher.StringToFloat(cvss3.Score), BaseSeverity: cvss3.Severity, VectorString: cvss3.Vector, AttackVector: v3elems[0], AttackComplexity: v3elems[1], PrivilegesRequired: v3elems[2], UserInteraction: v3elems[3], Scope: v3elems[4], ConfidentialityImpact: v3elems[5], IntegrityImpact: v3elems[6], AvailabilityImpact: v3elems[7], }, }, References: append([]models.JvnReference{}, refs...), Cpes: append([]models.JvnCpe{}, cpes...), Certs: append([]models.JvnCert{}, certs...), PublishedDate: publish, LastModifiedDate: modified, } cves = append(cves, cve) } return } func collectCertLinks(links []string) (certs []models.JvnCert, err error) { var proxyURL *url.URL httpClient := &http.Client{} if viper.GetString("http-proxy") != "" { if proxyURL, err = url.Parse(viper.GetString("http-proxy")); err != nil { return nil, xerrors.Errorf("failed to parse proxy url: %w", err) } httpClient = &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)}} } certs = []models.JvnCert{} for _, link := range links { title := "" if strings.HasSuffix(link, ".html") { res, err := httpClient.Get(link) if err != nil { return nil, xerrors.Errorf("Failed to get %s: err: %w", link, err) } defer res.Body.Close() doc, err := goquery.NewDocumentFromReader(res.Body) if err != nil { return nil, xerrors.Errorf("Failed to NewDocumentFromReader. err: %w", err) } title = doc.Find("title").Text() } certs = append(certs, models.JvnCert{ Cert: models.Cert{ Title: title, Link: link, }, }) } return certs, nil } var cvss2VectorMap = map[string]string{ "AV:L": "LOCAL", "AV:A": "ADJACENT_NETWORK", "AV:N": "NETWORK", "AC:L": "LOW", "AC:M": "MEDIUM", "AC:H": "HIGH", "Au:M": "MULTIPLE", "Au:S": "SINGLE", "Au:N": "NONE", "C:N": "NONE", "C:P": "PARTIAL", "C:C": "COMPLETE", "I:N": "NONE", "I:P": "PARTIAL", "I:C": "COMPLETE", "A:N": "NONE", "A:P": "PARTIAL", "A:C": "COMPLETE", } func parseCvss2VectorStr(str string) (elems []string) { if len(str) == 0 { return []string{"", "", "", "", "", ""} } for _, s := range strings.Split(str, "/") { elems = append(elems, cvss2VectorMap[s]) } return } var cvss3VectorMap = map[string]string{ "AV:N": "NETWORK", "AV:A": "ADJACENT_NETWORK", "AV:L": "LOCAL", "AV:P": "PHYSICAL", "AC:L": "LOW", "AC:H": "HIGH", "PR:N": "NONE", "PR:L": "LOW", "PR:H": "HIGH", "UI:N": "NONE", "UI:R": "REQUIRED", "S:U": "UNCHANGED", "S:C": "CHANGED", "C:N": "NONE", "C:L": "LOW", "C:H": "HIGH", "I:N": "NONE", "I:L": "LOW", "I:H": "HIGH", "A:N": "NONE", "A:L": "LOW", "A:H": "HIGH", } func parseCvss3VectorStr(str string) (elems []string) { if len(str) == 0 { return []string{"", "", "", "", "", "", "", ""} } str = strings.TrimPrefix(str, "CVSS:3.0/") for _, s := range strings.Split(str, "/") { elems = append(elems, cvss3VectorMap[s]) } return } // convert string time to time.Time // JVN : "2016-01-26T13:36:23+09:00", // NVD : "2016-01-20T21:59:01.313-05:00", func parseJvnTime(strtime string) (t time.Time, err error) { layout := "2006-01-02T15:04-07:00" t, err = time.Parse(layout, strtime) if err != nil { return t, xerrors.Errorf("Failed to parse time, time: %s, err: %w", strtime, err) } return } var cveIDPattern = regexp.MustCompile(`^CVE-[0-9]{4}-[0-9]{4,}$`) func getCveIDs(item Item) []string { cveIDsMap := map[string]bool{} for _, ref := range item.References { switch ref.Source { case "NVD", "CVE": if cveIDPattern.MatchString(ref.ID) { cveIDsMap[ref.ID] = true } else { id := strings.TrimSpace(ref.ID) if cveIDPattern.MatchString(id) { log.Warnf("CVE-ID with extra space. Please email JVNDB (<EMAIL>) to fix the rdf file with the following information. RDF data(Identifier: %s, Reference Source: %s, ID: %s)", item.Identifier, ref.Source, ref.ID) cveIDsMap[id] = true } else { log.Warnf("Failed to get CVE-ID. Invalid CVE-ID. Please email JVNDB (<EMAIL>) to fix the rdf file with the following information. RDF data(Identifier: %s, Reference Source: %s, ID: %s)", item.Identifier, ref.Source, ref.ID) } } } } cveIDs := []string{} for cveID := range cveIDsMap { cveIDs = append(cveIDs, cveID) } return cveIDs } func distributeCvesByYear(uniqCves map[string]map[string]models.Jvn, cves map[string]models.Jvn) { for uniqJVNID, cve := range cves { y := strings.Split(cve.JvnID, "-")[1] if _, ok := uniqCves[y]; !ok { uniqCves[y] = map[string]models.Jvn{} } if destCve, ok := uniqCves[y][uniqJVNID]; !ok { uniqCves[y][uniqJVNID] = cve } else { if cve.LastModifiedDate.After(destCve.LastModifiedDate) { uniqCves[y][uniqJVNID] = cve } } } }
vulsio/go-cve-dictionary
<|start_filename|>Demo/Pods/OHHTTPStubs/OHHTTPStubs/Sources/OHPathHelpers.h<|end_filename|> // // OHPathHelpers.h // Pods // // Created by <NAME> on 18/04/2015. // // #import <Foundation/Foundation.h> #ifdef NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_BEGIN #define _nullable_ __nullable #else #define _nullable_ #endif /** * Useful function to build a path given a file name and a class. * * @param fileName The name of the file to get the path to, including file extension * @param inBundleForClass The class of the caller, used to determine the current bundle * in which the file is supposed to be located. * You should typically pass `self.class` (ObjC) or * `self.dynamicType` (Swift) when calling this function. * * @return The path of the given file in the same bundle as the inBundleForClass class */ NSString* _nullable_ OHPathForFile(NSString* fileName, Class inBundleForClass); /** * Useful function to build a path given a file name and a bundle. * * @param fileName The name of the file to get the path to, including file extension * @param bundle The bundle in which the file is supposed to be located. * This parameter can't be null. * * @return The path of the given file in given bundle * * @note You should avoid using `[NSBundle mainBundle]` for the `bundle` parameter, * as in the context of Unit Tests, this points to the Simulator's bundle, * not the bundle of the app under test. That's why `nil` is not an acceptable * value (so you won't expect it to default to the `mainBundle`). * You should use `[NSBundle bundleForClass:]` instead. */ NSString* _nullable_ OHPathForFileInBundle(NSString* fileName, NSBundle* bundle); /** * Useful function to build a path to a file in the Documents's directory in the * app sandbox, used by iTunes File Sharing for example. * * @param fileName The name of the file to get the path to, including file extension * * @return The path of the file in the Documents directory in your App Sandbox */ NSString* _nullable_ OHPathForFileInDocumentsDir(NSString* fileName); /** * Useful function to build an NSBundle located in the application's resources simply from its name * * @param bundleBasename The base name, without extension (extension is assumed to be ".bundle"). * @param inBundleForClass The class of the caller, used to determine the current bundle * in which the file is supposed to be located. * You should typically pass `self.class` (ObjC) or * `self.dynamicType` (Swift) when calling this function. * * @return The NSBundle object representing the bundle with the given basename located in your application's resources. */ NSBundle* _nullable_ OHResourceBundle(NSString* bundleBasename, Class inBundleForClass); #ifdef NS_ASSUME_NONNULL_END NS_ASSUME_NONNULL_END #endif <|start_filename|>Demo/Pods/Headers/Public/Nimble/NMBExceptionCapture.h<|end_filename|> #import <Foundation/Foundation.h> @interface NMBExceptionCapture : NSObject - (id)initWithHandler:(void(^)(NSException *))handler finally:(void(^)())finally; - (void)tryBlock:(void(^)())unsafeBlock; @end
neonichu/Moya
<|start_filename|>private-bundle-plugin.js<|end_filename|> // numtel:privatesources // MIT License, <EMAIL> var path = Npm.require('path'); var fs = Npm.require('fs'); var BASE_DIR = 'assets/app'; Iron.Router.plugins.privateSources = function (router, options) { options = options || {}; var route = '/' + (options.route || '_loadSource'); router.route(route, function(){ var query = this.params.query; var filename = path.join(BASE_DIR, query.f); if(filename.substr(0, BASE_DIR.length) !== BASE_DIR){ // Security breach trying to access file outside of BASE_DIR this.response.end(); }else if(options.allow && !options.allow.call(this, query.f)){ this.response.end(); }else{ fs.readFile(filename, function(err, data){ if(err){ options.debug && console.log(err); this.response.end(); }else{ this.response.end(data); } }.bind(this)); } }, { where: 'server' }); }; <|start_filename|>plugin/compile-private-sources.js<|end_filename|> var fs = Npm.require('fs'); var path = Npm.require('path'); var compiler = Npm.require('./compiler'); var projectContextModule = Npm.require('./project-context'); var PackageSource = Npm.require('./package-source'); var projectContext; if(process.privatesourcesProjectContext){ projectContext = process.privatesourcesProjectContext; }else{ projectContext = new projectContextModule.ProjectContext({ projectDir: process.cwd() }); process.privatesourcesProjectContext = projectContext; projectContext.prepareProjectForBuild(); } // Begin code borrowed from mquandalle:bower/plugin/handler.js var loadJSONContent = function (compileStep, content) { try { return JSON.parse(content); } catch (e) { compileStep.error({ message: "Syntax error in " + compileStep.inputPath, line: e.line, column: e.column }); } }; // End code from mquandalle:bower var isHtmlExt = function(n){ return n.substr(-5).toLowerCase() === '.html' }; // Use with Array.prototype.sort() in array of filenames to put '.html' first var sortHTMLFirst = function(a, b){ var aHtml = isHtmlExt(a); var bHtml = isHtmlExt(b); if(aHtml && bHtml) return 0; else if(aHtml) return -1; else if(bHtml) return 1; return 0; }; Plugin.registerSourceHandler('privatesources.json', { archMatching: 'os' }, function (compileStep) { var bundles = loadJSONContent(compileStep, compileStep.read().toString('utf8')); processBundles(compileStep, bundles); }); // Separate function for testing purposes var processBundles = function(compileStep, bundles){ var bundle; for(var name in bundles){ bundle = bundles[name]; var processed = bundlePrivateSources(bundle.sort(sortHTMLFirst)); processed.scripts.forEach(function(script){ compileStep.addAsset({ path: name + '.js', data: script.source }); compileStep.addAsset({ path: name + '.js.map', data: script.sourceMap.replace(script.servePath, name + '.js') }); }); processed.stylesheets.forEach(function(stylesheet){ compileStep.addAsset({ path: name + '.css', data: stylesheet.data }); if(stylesheet.sourceMap){ compileStep.addAsset({ path: name + '.css.map', data: stylesheet.sourceMap.replace( stylesheet.servePath, name + '.css') }); } }); } }; // @param {[string]} sources - Relative filenames from private directory var bundlePrivateSources = function(sources){ if(projectContext.isopackCache !== null){ var packages = []; for(var packageName in projectContext.isopackCache._isopacks){ packages.push(packageName); } var packageSource = new PackageSource; packageSource.initFromOptions('resources', { kind: 'plugin', sourceRoot: path.join(process.cwd(), 'private'), serveRoot: process.cwd(), use: packages, npmDependencies: [], npmDir: path.join(process.cwd(), 'node_modules'), sources: sources }); // initFromOptions() defaults to 'os' architecture packageSource.architectures[0].arch = 'web.browser'; var app = compiler.compile(packageSource, { packageMap: projectContext.packageMap, isopackCache: projectContext.isopackCache, includeCordovaUnibuild: false }); var buildData = app.unibuilds[0]; return { scripts: buildData.prelinkFiles, packageVariables: buildData.packageVariables.map(function(variable){ return variable.name; }), stylesheets: buildData.resources.filter(function(resource){ return resource.type === 'css'; }) }; } } <|start_filename|>package.js<|end_filename|> Package.describe({ name: 'numtel:privatesources', summary: 'DEPRECATED: Switch to the new numtel:lazy-bundles package for latest release', version: '1.0.2', git: 'https://github.com/numtel/meteor-privatesources.git' }); Package.registerBuildPlugin({ name: 'privateSources', use: [ ], sources: [ 'plugin/compile-private-sources.js' ], npmDependencies: {} }); Package.onUse(function(api){ api.versionsFrom('1.0.2.1'); api.addFiles('private-bundle-plugin.js', 'server'); });
numtel/meteor-privatesources
<|start_filename|>MFaaP.MFWSClient/Searching/PropertyValues/DatePropertyValueSearchCondition.cs<|end_filename|> using System; namespace MFaaP.MFWSClient { /// <summary> /// Represents a search condition that restricts by a Date property value. /// </summary> public class DatePropertyValueSearchCondition : PropertyValueSearchConditionBase<DateTime> { /// <summary> /// Creates a <see cref="DatePropertyValueSearchCondition"/>, searching for the value supplied. /// </summary> /// <param name="propertyDefId">The Id of the property def to search by.</param> /// <param name="value">The value to search by.</param> /// <param name="searchConditionOperator">The operator to use (defaults to Equals if not provided).</param> /// <param name="invertOperator">Whether to invert the search operator (defaults to false if not provided).</param> public DatePropertyValueSearchCondition( int propertyDefId, DateTime value, SearchConditionOperators searchConditionOperator = SearchConditionOperators.Equals, bool invertOperator = false) : base(propertyDefId, value, searchConditionOperator, invertOperator) { } /// <inheritdoc /> public override string EncodedValue => this.Value.ToString("yyyy-MM-dd"); } } <|start_filename|>MFaaP.MFWSClient/OAuth2/OAuth2Configuration.cs<|end_filename|> using MFaaP.MFWSClient.ExtensionMethods; using System; using System.Collections.Generic; namespace MFaaP.MFWSClient.OAuth2 { /// <summary> /// Represents the OAuth 2.0 configuration data within an OAuth 2.0 authentication plugin. /// </summary> public class OAuth2Configuration { /// <summary> /// The fallback redirect uri, if no others are specified. /// </summary> public const string FallbackRedirectUri = "http://localhost"; /// <summary> /// The authorisation endpoint. /// </summary> /// <remarks>Should not be used directly, but instead through <see cref="GenerateAuthorizationUri"/>.</remarks> public string AuthorizationEndpoint { get; set; } /// <summary> /// The client ID used for OAuth. /// </summary> public string ClientID { get; set; } /// <summary> /// The current M-Files server version. /// </summary> public Version MFServerVersion { get; set; } /// <summary> /// The protocol this configuration is for. Should be "OAuth 2.0". /// </summary> public string Protocol { get; set; } = "OAuth 2.0"; /// <summary> /// The redirect URI if this configuration is used on the web. /// </summary> /// <remarks>May not be set.</remarks> public string RedirectURIForWeb { get; set; } /// <summary> /// The redirect URI if this configuration is used in native apps. /// </summary> /// <remarks>May not be set.</remarks> public string RedirectURIForNative { get; set; } /// <summary> /// The redirect URI if this configuration is used in mobile apps. /// </summary> /// <remarks>May not be set.</remarks> public string RedirectURIForMobile { get; set; } /// <summary> /// The redirect URI if this configuration is used via a WOPI client. /// </summary> /// <remarks>May not be set.</remarks> public string RedirectURIForWOPI { get; set; } /// <summary> /// The redirect URI. /// </summary> /// <remarks>May not be set.</remarks> public string RedirectURI { get; set; } = OAuth2Configuration.FallbackRedirectUri; /// <summary> /// The resource this configuration is for. /// </summary> public string Resource { get; set; } /// <summary> /// The token endpoint, used for swapping an authorisation code for access (and possibly refresh) tokens. /// </summary> public string TokenEndpoint { get; set; } /// <summary> /// The grant type that should be provided. /// </summary> /// <remarks>May not be set.</remarks> public string GrantType { get; set; } = "authorization_code"; /// <summary> /// The scope that should be provided. /// </summary> /// <remarks>May not be set.</remarks> public string Scope { get; set; } /// <summary> /// The client secret that should be provided. /// </summary> /// <remarks>May not be set.</remarks> public string ClientSecret { get; set; } /// <summary> /// If true then users will be forced to log in, even if they've already logged into this resource. /// </summary> public bool ForceLogin { get; set; } = false; /// <summary> /// The prompt type to provide. /// </summary> public string PromptType => this.ForceLogin ? "login" : null; /// <summary> /// Whether to use the "Id token" as the access token. /// </summary> public bool UseIdTokenAsAccessToken { get; set; } = false; /// <summary> /// The site realm to provide. /// </summary> public string SiteRealm { get; set; } /// <summary> /// The OAuth state to provide and verify. Defaults to a new GUID. /// If set to null or an empty string then will not be provided. /// </summary> public string State { get; set; } = Guid.NewGuid().ToString("B"); /// <summary> /// The vault guid this relates to. /// </summary> public string VaultGuid { get; set; } /// <summary> /// Instantiates the configuration class. /// </summary> /// <param name="forceLogin">If true, the user will be prompted to log in even if they have done so already (<see cref="ForceLogin"/>).</param> public OAuth2Configuration(bool forceLogin = false) : base() { this.ForceLogin = forceLogin; } /// <summary> /// Instantiates the configuration class, retrieving configuration values from the /// provided plugin configuration. /// </summary> /// <param name="pluginConfiguration">The dictionary containing plugin configuration settings.</param> /// <param name="vaultGuid">The GUID of the vault.</param> /// <param name="forceLogin">If true, the user will be prompted to log in even if they have done so already (<see cref="ForceLogin"/>).</param> public OAuth2Configuration(Dictionary<string, string> pluginConfiguration, string vaultGuid, bool forceLogin = false) : this(forceLogin) { // Sanity. if (null == pluginConfiguration) throw new ArgumentNullException(nameof(pluginConfiguration)); // Extract data. this.AuthorizationEndpoint = pluginConfiguration.GetValueOrDefault("AuthorizationEndpoint"); this.ClientID = pluginConfiguration.GetValueOrDefault("ClientID"); this.Protocol = pluginConfiguration.GetValueOrDefault("Protocol"); this.RedirectURIForWeb = pluginConfiguration.GetValueOrDefault("RedirectURIForWeb"); this.RedirectURIForNative = pluginConfiguration.GetValueOrDefault("RedirectURIForNative"); this.RedirectURIForWOPI = pluginConfiguration.GetValueOrDefault("RedirectURIForWOPI"); this.RedirectURIForMobile = pluginConfiguration.GetValueOrDefault("RedirectURIForMobile"); this.RedirectURI = pluginConfiguration.GetValueOrDefault("RedirectURI", OAuth2Configuration.FallbackRedirectUri); this.Resource = pluginConfiguration.GetValueOrDefault("Resource"); this.TokenEndpoint = pluginConfiguration.GetValueOrDefault("TokenEndpoint"); this.Scope = pluginConfiguration.GetValueOrDefault("Scope"); this.ClientSecret = pluginConfiguration.GetValueOrDefault("ClientSecret"); this.SiteRealm = pluginConfiguration.GetValueOrDefault("SiteRealm"); this.VaultGuid = vaultGuid; try { this.MFServerVersion = Version.Parse(pluginConfiguration.GetValueOrDefault("MFServerVersion")); } catch { } // If the configuration tells us to use the id token instead of the access token then we should. this.UseIdTokenAsAccessToken = string.Equals( pluginConfiguration.GetValueOrDefault("UseIdTokenAsAccessToken"), "true", StringComparison.InvariantCultureIgnoreCase); // If the configuration asks us to force the login then do so. if (pluginConfiguration.GetValueOrDefault("PromptLoginParameter") == "login") { this.ForceLogin = true; } } /// <summary> /// Creates an <see cref="OAuth2Configuration"/> by parsing the provided plugin configuration. /// </summary> /// <param name="pluginConfiguration">The dictionary containing plugin configuration settings.</param> /// <param name="vaultGuid">The GUID of the vault.</param> /// <returns>A configuration class representing the provided details.</returns> public static OAuth2Configuration ParseFrom(Dictionary<string, string> pluginConfiguration, string vaultGuid) { return new OAuth2Configuration(pluginConfiguration, vaultGuid); } /// <summary> /// Retrieves the appropriate redirect uri from the various ones provided in this configuration. /// This method ensures that the logic for which redirect URI is used remains constant. /// </summary> /// <returns>The redirect uri to use.</returns> /// <remarks>The standard implementation will check the following values in this order, using the first one that has a value: /// <see cref="RedirectURIForNative"/>, <see cref="RedirectURI"/>, <see cref="FallbackRedirectUri"/>. /// </remarks> public virtual string GetAppropriateRedirectUri() { if (false == string.IsNullOrWhiteSpace(this.RedirectURIForNative)) { // Use the native redirect URI. return this.RedirectURIForNative; } else if(false == string.IsNullOrWhiteSpace(this.RedirectURI)) { // Use the redirect URI. return this.RedirectURI; } return OAuth2Configuration.FallbackRedirectUri; } /// <summary> /// Generates a <see cref="Uri"/> that can be displayed in a web browser for authorisation. /// Includes both the <see cref="AuthorizationEndpoint"/> and also other required information such as /// <see cref="ClientID"/> and <see cref="Resource"/>. /// </summary> /// <param name="redirectUri"> /// The redirect Uri to use. /// If null or a blank string then this method will attempt to retrieve a valid redirect uri from the current configuration. /// If that also cannot be found, will use <see cref="OAuth2Configuration.FallbackRedirectUri"/>.</param> /// <returns></returns> public Uri GenerateAuthorizationUri(string redirectUri = null) { // If we do not have a redirect uri then try and make one. if (string.IsNullOrWhiteSpace(redirectUri)) { redirectUri = this.GetAppropriateRedirectUri(); } // Build up the URI with mandatory data. var uriBuilder = new UriBuilder(this.AuthorizationEndpoint); uriBuilder.SetQueryParam("client_id", this.ClientID); uriBuilder.SetQueryParam("redirect_uri", redirectUri); uriBuilder.SetQueryParam("response_type", "code"); // Add the optional items, if set. uriBuilder.SetQueryParamIfNotNullOrWhitespace("scope", this.Scope); uriBuilder.SetQueryParamIfNotNullOrWhitespace("state", this.State); uriBuilder.SetQueryParamIfNotNullOrWhitespace("prompt", this.PromptType); uriBuilder.SetQueryParamIfNotNullOrWhitespace("resource", this.Resource); // Return the generated URI. return uriBuilder.Uri; } } } <|start_filename|>MFaaP.MFWSClient/MFWSVaultValueListItemOperations.cs<|end_filename|> using System; using System.Net; using System.Threading; using System.Threading.Tasks; using RestSharp; using RestSharp.Extensions; namespace MFaaP.MFWSClient { /// <summary> /// Value list item operations. /// </summary> public class MFWSVaultValueListItemOperations : MFWSVaultOperationsBase { /// <inheritdoc /> public MFWSVaultValueListItemOperations(MFWSClientBase client) : base(client) { } /// <summary> /// Gets the contents of the value list with Id <see paramref="valueListId"/>. /// </summary> /// <param name="valueListId">The Id of the value list to return the items from.</param> /// <param name="nameFilter">If has a value, is used to filter the items by name.</param> /// <param name="token">A cancellation token for the request.</param> /// <param name="limit">If 0, uses Mfiles default at server (default 500 items returned)</param> /// <returns>The contents of the value list.</returns> /// <remarks>Note that this may be limited.</remarks> public async Task<Results<ValueListItem>> GetValueListItemsAsync(int valueListId, string nameFilter = null, CancellationToken token = default(CancellationToken), int limit = 0) { // Create the request. var request = new RestRequest($"/REST/valuelists/{valueListId}/items"); // Filter by name? var querySeperator = "?"; if (false == string.IsNullOrWhiteSpace(nameFilter)) { request.Resource += "?filter=" + WebUtility.UrlEncode(nameFilter); querySeperator = "&"; } if (limit > 0) { request.Resource += $"{querySeperator}limit={limit.ToString()}"; } // Make the request and get the response. var response = await this.MFWSClient.Get<Results<ValueListItem>>(request, token) .ConfigureAwait(false); // Return the data. return response.Data; } /// <summary> /// Gets the contents of the value list with Id <see paramref="valueListId"/>. /// </summary> /// <param name="valueListId">The Id of the value list to return the items from.</param> /// <param name="nameFilter">If has a value, is used to filter the items by name.</param> /// <param name="token">A cancellation token for the request.</param> /// <param name="limit">If 0, uses Mfiles default at server (default 500 items returned)</param> /// <returns>The contents of the value list.</returns> /// <remarks>Note that this may be limited.</remarks> public Results<ValueListItem> GetValueListItems(int valueListId, string nameFilter = null, CancellationToken token = default(CancellationToken), int limit = 0) { // Execute the async method. return this.GetValueListItemsAsync(valueListId, nameFilter, token, limit) .ConfigureAwait(false) .GetAwaiter() .GetResult(); } /// <summary> /// Creates a new item with the <see cref="newItemName"/> in the value list with id <see cref="valueListId"/>. /// </summary> /// <param name="valueListId">The Id of the value list to create the new item in.</param> /// <param name="newItemName">Name of the new value list item to create.</param> /// <param name="token">A cancellation token for the request.</param> /// <returns>The newly created value list item</returns> public Task<ValueListItem> AddValueListItemAsync(int valueListId, string newItemName, CancellationToken token = default(CancellationToken)) { // Sanity. if (string.IsNullOrWhiteSpace(newItemName)) throw new ArgumentException("The value list item must have a name.", nameof(newItemName)); // Create the value list item instance. var newValueListItem = new ValueListItem { Name = newItemName, ValueListID = valueListId }; // Use the other overload. return this.AddValueListItemAsync(valueListId, newValueListItem, token); } /// Creates a new item with the <see cref="newItemName"/> in the value list with id <see cref="valueListId"/>. /// </summary> /// <param name="valueListId">The Id of the value list to create the new item in.</param> /// <param name="newItemName">Name of the new value list item to create.</param> /// <param name="token">A cancellation token for the request.</param> /// <returns>The newly created value list item</returns> public ValueListItem AddValueListItem(int valueListId, string newItemName, CancellationToken token = default(CancellationToken)) { // Execute the async method. return this.AddValueListItemAsync(valueListId, newItemName, token) .ConfigureAwait(false) .GetAwaiter() .GetResult(); } /// <summary> /// Creates a new <see cref="valueListItem"/> in the value list with id <see cref="valueListId"/>. /// </summary> /// <param name="valueListId">The Id of the value list to create the new item in.</param> /// <param name="valueListItem">The value list item to create.</param> /// <param name="token">A cancellation token for the request.</param> /// <returns>The newly created value list item</returns> public async Task<ValueListItem> AddValueListItemAsync(int valueListId, ValueListItem valueListItem, CancellationToken token = default(CancellationToken)) { // Sanity. if (null == valueListItem) throw new ArgumentNullException(nameof(valueListItem)); if (valueListItem.ValueListID != valueListId) valueListItem.ValueListID = valueListId; if (string.IsNullOrWhiteSpace(valueListItem.Name)) throw new ArgumentException("The value list item must have a name.", nameof(valueListItem)); // Create the request. var request = new RestRequest($"/REST/valuelists/{valueListId}/items"); request.AddJsonBody(valueListItem); // Make the request and get the response. var response = await this.MFWSClient.Post<ValueListItem>(request, token) .ConfigureAwait(false); return response.Data; } /// <summary> /// Creates a new <see cref="valueListItem"/> in the value list with id <see cref="valueListId"/>. /// </summary> /// <param name="valueListId">The Id of the value list to create the new item in.</param> /// <param name="valueListItem">The value list item to create.</param> /// <param name="token">A cancellation token for the request.</param> /// <returns>The newly created value list item</returns> public ValueListItem AddValueListItem(int valueListId, ValueListItem valueListItem, CancellationToken token = default(CancellationToken)) { // Execute the async method. return this.AddValueListItemAsync(valueListId, valueListItem, token) .ConfigureAwait(false) .GetAwaiter() .GetResult(); } } } <|start_filename|>MFaaP.MFWSClient.Tests/MFWSVaultWorkflowOperations.cs<|end_filename|> using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using RestSharp; namespace MFaaP.MFWSClient.Tests { [TestClass] public class MFWSVaultWorkflowOperations { #region Get workflow states /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultWorkflowOperations.GetWorkflowStatesAsync"/> /// requests the correct resource address with the correct method. /// </summary> [TestMethod] public async Task GetWorkflowStatesAsync() { // Create our test runner. var runner = new RestApiTestRunner<List<WorkflowState>>(Method.GET, "/REST/structure/workflows/1234/states.aspx"); // Execute. await runner.MFWSClient.WorkflowOperations.GetWorkflowStatesAsync(1234); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultWorkflowOperations.GetWorkflowStates"/> /// requests the correct resource address with the correct method. /// </summary> [TestMethod] public void GetWorkflowStates() { // Create our test runner. var runner = new RestApiTestRunner<List<WorkflowState>>(Method.GET, "/REST/structure/workflows/12345/states.aspx"); // Execute. runner.MFWSClient.WorkflowOperations.GetWorkflowStates(12345); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultWorkflowOperations.GetWorkflowStateByName"/> /// returns the correct state. /// </summary> [TestMethod] public void GetWorkflowStateByName_IncludesWorkflow() { // Create our test runner. var runner = new RestApiTestRunner<List<WorkflowState>>(Method.GET, "/REST/structure/workflows/12345/states.aspx"); // Set up the response to include runner.ResponseData = new List<WorkflowState> { new WorkflowState() { ID = 1, Name = "abc" }, new WorkflowState() { ID = 2, Name = "hello" } }; // Execute. var result = runner.MFWSClient.WorkflowOperations.GetWorkflowStateByName(12345, "hello"); // Verify. runner.Verify(); // Ensure we got the right result back. Assert.IsNotNull(result); Assert.AreEqual(2, result.ID); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultWorkflowOperations.GetWorkflowStateByName"/> /// returns null if no state with that name is found. /// </summary> [TestMethod] public void GetWorkflowStateByName_DoesNotIncludeWorkflow() { // Create our test runner. var runner = new RestApiTestRunner<List<WorkflowState>>(Method.GET, "/REST/structure/workflows/123/states.aspx"); // Set up the response to include runner.ResponseData = new List<WorkflowState> { new WorkflowState() { ID = 1, Name = "abc" }, new WorkflowState() { ID = 2, Name = "hello" } }; // Execute. var result = runner.MFWSClient.WorkflowOperations.GetWorkflowStateByName(123, "hello world"); // Verify. runner.Verify(); // Ensure we got nothing back. Assert.IsNull(result); } #endregion #region Workflow alias to ID resolution /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultWorkflowOperations.GetWorkflowIDByAliasAsync"/> /// requests the correct resource address with the correct method. /// </summary> [TestMethod] public async Task GetWorkflowIDByAliasAsync() { // Create our test runner. var runner = new RestApiTestRunner<Dictionary<string, int>>(Method.POST, "/REST/structure/workflows/itemidbyalias.aspx"); // Set up the expected body. var body = new JsonArray { "hello world" }; runner.SetExpectedRequestBody(body); // Execute. await runner.MFWSClient.WorkflowOperations.GetWorkflowIDByAliasAsync("hello world"); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultWorkflowOperations.GetWorkflowIDsByAliasesAsync"/> /// requests the correct resource address with the correct method. /// </summary> [TestMethod] public async Task GetWorkflowIDsByAliasesAsync() { // Create our test runner. var runner = new RestApiTestRunner<Dictionary<string, int>>(Method.POST, "/REST/structure/workflows/itemidbyalias.aspx"); // Set up the expected body. var body = new JsonArray { "hello", "world", "third option" }; runner.SetExpectedRequestBody(body); // Execute. await runner.MFWSClient.WorkflowOperations.GetWorkflowIDsByAliasesAsync(aliases: new string[] { "hello", "world", "third option" }); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultWorkflowOperations.GetWorkflowIDsByAliases"/> /// requests the correct resource address with the correct method. /// </summary> [TestMethod] public void GetWorkflowIDsByAliases() { // Create our test runner. var runner = new RestApiTestRunner<Dictionary<string, int>>(Method.POST, "/REST/structure/workflows/itemidbyalias.aspx"); // Set up the expected body. var body = new JsonArray { "hello", "world", "third option" }; runner.SetExpectedRequestBody(body); // Execute. runner.MFWSClient.WorkflowOperations.GetWorkflowIDsByAliases(aliases: new string[] { "hello", "world", "third option" }); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultWorkflowOperations.GetWorkflowIDByAlias"/> /// requests the correct resource address with the correct method. /// </summary> [TestMethod] public void GetWorkflowIDByAlias() { // Create our test runner. var runner = new RestApiTestRunner<Dictionary<string, int>>(Method.POST, "/REST/structure/workflows/itemidbyalias.aspx"); // Set up the expected body. var body = new JsonArray { "hello world" }; runner.SetExpectedRequestBody(body); // Execute. runner.MFWSClient.WorkflowOperations.GetWorkflowIDByAlias("hello world"); // Verify. runner.Verify(); } #endregion #region Workflow state alias to ID resolution /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultWorkflowOperations.GetWorkflowStateIDByAliasAsync"/> /// requests the correct resource address with the correct method. /// </summary> [TestMethod] public async Task GetWorkflowStateIDByAliasAsync() { // Create our test runner. var runner = new RestApiTestRunner<Dictionary<string, int>>(Method.POST, "/REST/structure/workflowstates/itemidbyalias.aspx"); // Set up the expected body. var body = new JsonArray { "hello world" }; runner.SetExpectedRequestBody(body); // Execute. await runner.MFWSClient.WorkflowOperations.GetWorkflowStateIDByAliasAsync("hello world"); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultWorkflowOperations.GetWorkflowStateIDsByAliasesAsync"/> /// requests the correct resource address with the correct method. /// </summary> [TestMethod] public async Task GetWorkflowStateIDsByAliasesAsync() { // Create our test runner. var runner = new RestApiTestRunner<Dictionary<string, int>>(Method.POST, "/REST/structure/workflowstates/itemidbyalias.aspx"); // Set up the expected body. var body = new JsonArray { "hello", "world", "third option" }; runner.SetExpectedRequestBody(body); // Execute. await runner.MFWSClient.WorkflowOperations.GetWorkflowStateIDsByAliasesAsync(aliases: new string[] { "hello", "world", "third option" }); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultWorkflowOperations.GetWorkflowStateIDsByAliases"/> /// requests the correct resource address with the correct method. /// </summary> [TestMethod] public void GetWorkflowStateIDsByAliases() { // Create our test runner. var runner = new RestApiTestRunner<Dictionary<string, int>>(Method.POST, "/REST/structure/workflowstates/itemidbyalias.aspx"); // Set up the expected body. var body = new JsonArray { "hello", "world", "third option" }; runner.SetExpectedRequestBody(body); // Execute. runner.MFWSClient.WorkflowOperations.GetWorkflowStateIDsByAliases(aliases: new string[] { "hello", "world", "third option" }); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultWorkflowOperations.GetWorkflowStateIDByAlias"/> /// requests the correct resource address with the correct method. /// </summary> [TestMethod] public void GetWorkflowStateIDByAlias() { // Create our test runner. var runner = new RestApiTestRunner<Dictionary<string, int>>(Method.POST, "/REST/structure/workflowstates/itemidbyalias.aspx"); // Set up the expected body. var body = new JsonArray { "hello world" }; runner.SetExpectedRequestBody(body); // Execute. runner.MFWSClient.WorkflowOperations.GetWorkflowStateIDByAlias("hello world"); // Verify. runner.Verify(); } #endregion #region Workflow state transition alias to ID resolution /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultWorkflowOperations.GetWorkflowStateTransitionIDByAliasAsync"/> /// requests the correct resource address with the correct method. /// </summary> [TestMethod] public async Task GetWorkflowStateTransitionIDByAliasAsync() { // Create our test runner. var runner = new RestApiTestRunner<Dictionary<string, int>>(Method.POST, "/REST/structure/statetransitions/itemidbyalias.aspx"); // Set up the expected body. var body = new JsonArray { "hello world" }; runner.SetExpectedRequestBody(body); // Execute. await runner.MFWSClient.WorkflowOperations.GetWorkflowStateTransitionIDByAliasAsync("hello world"); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultWorkflowOperations.GetWorkflowStateTransitionIDsByAliasesAsync"/> /// requests the correct resource address with the correct method. /// </summary> [TestMethod] public async Task GetWorkflowStateTransitionIDsByAliasesAsync() { // Create our test runner. var runner = new RestApiTestRunner<Dictionary<string, int>>(Method.POST, "/REST/structure/statetransitions/itemidbyalias.aspx"); // Set up the expected body. var body = new JsonArray { "hello", "world", "third option" }; runner.SetExpectedRequestBody(body); // Execute. await runner.MFWSClient.WorkflowOperations.GetWorkflowStateTransitionIDsByAliasesAsync(aliases: new string[] { "hello", "world", "third option" }); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultWorkflowOperations.GetWorkflowStateTransitionIDsByAliases"/> /// requests the correct resource address with the correct method. /// </summary> [TestMethod] public void GetWorkflowStateTransitionIDsByAliases() { // Create our test runner. var runner = new RestApiTestRunner<Dictionary<string, int>>(Method.POST, "/REST/structure/statetransitions/itemidbyalias.aspx"); // Set up the expected body. var body = new JsonArray { "hello", "world", "third option" }; runner.SetExpectedRequestBody(body); // Execute. runner.MFWSClient.WorkflowOperations.GetWorkflowStateTransitionIDsByAliases(aliases: new string[] { "hello", "world", "third option" }); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultWorkflowOperations.GetWorkflowStateTransitionIDByAlias"/> /// requests the correct resource address with the correct method. /// </summary> [TestMethod] public void GetWorkflowStateTransitionIDByAlias() { // Create our test runner. var runner = new RestApiTestRunner<Dictionary<string, int>>(Method.POST, "/REST/structure/statetransitions/itemidbyalias.aspx"); // Set up the expected body. var body = new JsonArray { "hello world" }; runner.SetExpectedRequestBody(body); // Execute. runner.MFWSClient.WorkflowOperations.GetWorkflowStateTransitionIDByAlias("hello world"); // Verify. runner.Verify(); } #endregion } } <|start_filename|>MFaaP.MFWSClient.Tests/MFWSVaultObjectOperations.cs<|end_filename|> using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using MFaaP.MFilesAPI.Tests.ExtensionMethods; using MFaaP.MFWSClient.Tests.ExtensionMethods; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Newtonsoft.Json; using RestSharp; namespace MFaaP.MFWSClient.Tests { [TestClass] public class MFWSVaultObjectOperations { #region RenameObject /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.RenameObjectAsync(MFaaP.MFWSClient.ObjVer,string,System.Threading.CancellationToken)()"/> /// requests the correct resource address and HTTP method. /// </summary> [TestMethod] public async Task RenameObjectAsync() { // Create our test runner. var runner = new RestApiTestRunner<ObjectVersion>(Method.PUT, $"/REST/objects/1/2/latest/title"); // Set the expected body. var newObjectName = new PrimitiveType<string>() { Value = "renamed object" }; runner.SetExpectedRequestBody(newObjectName); // Execute. await runner.MFWSClient.ObjectOperations.RenameObjectAsync(new ObjID() { Type = 1, ID = 2 }, newObjectName.Value); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.RenameObjectAsync(MFaaP.MFWSClient.ObjVer,string,System.Threading.CancellationToken)()"/> /// when using unmanaged object information /// requests the correct resource address and HTTP method. /// </summary> [TestMethod] public async Task RenameObjectAsync_Unmanaged() { // Create our test runner. var runner = new RestApiTestRunner<ObjectVersion>(Method.PUT, $"/REST/objects/0/uhello%3Aworld/uagain/title"); // Set the expected body. var newObjectName = new PrimitiveType<string>() { Value = "renamed object" }; runner.SetExpectedRequestBody(newObjectName); // Execute. await runner.MFWSClient.ObjectOperations.RenameObjectAsync(new ObjVer() { Type = 0, ExternalRepositoryName = "hello", ExternalRepositoryObjectID = "world", ExternalRepositoryObjectVersionID = "again" }, newObjectName.Value); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.RenameObjectAsync(MFaaP.MFWSClient.ObjVer,string,System.Threading.CancellationToken)()"/> /// when using unmanaged object information /// requests the correct resource address and HTTP method. /// </summary> [TestMethod] public async Task RenameObjectAsync_Unmanaged_Latest() { // Create our test runner. var runner = new RestApiTestRunner<ObjectVersion>(Method.PUT, $"/REST/objects/0/uhello%3Aworld/latest/title"); // Set the expected body. var newObjectName = new PrimitiveType<string>() { Value = "renamed object" }; runner.SetExpectedRequestBody(newObjectName); // Execute. await runner.MFWSClient.ObjectOperations.RenameObjectAsync(new ObjID() { Type = 0, ExternalRepositoryName = "hello", ExternalRepositoryObjectID = "world" }, newObjectName.Value); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.RenameObject(MFaaP.MFWSClient.ObjVer,string,System.Threading.CancellationToken)()"/> /// requests the correct resource address and HTTP method. /// </summary> [TestMethod] public void RenameObject() { // Create our test runner. var runner = new RestApiTestRunner<ObjectVersion>(Method.PUT, $"/REST/objects/1/2/latest/title"); // Set the expected body. var newObjectName = new PrimitiveType<string>() { Value = "renamed object" }; runner.SetExpectedRequestBody(newObjectName); // Execute. runner.MFWSClient.ObjectOperations.RenameObject(new ObjID() { Type = 1, ID = 2 }, newObjectName.Value); // Verify. runner.Verify(); } #endregion #region GetLatestObjectVersionAndProperties /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.GetLatestObjectVersionAndPropertiesAsync(MFaaP.MFWSClient.ObjID,System.Threading.CancellationToken)"/> /// requests the correct resource address with the correct method. /// </summary> [TestMethod] public async Task GetLatestObjectVersionAndPropertiesAsync() { // Create our test runner. var runner = new RestApiTestRunner<ExtendedObjectVersion>(Method.GET, "/REST/objects/0/123/latest.aspx?include=properties"); // Execute. await runner.MFWSClient.ObjectOperations.GetLatestObjectVersionAndPropertiesAsync(0, 123); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.GetLatestObjectVersionAndProperties(MFaaP.MFWSClient.ObjID,System.Threading.CancellationToken)"/> /// requests the correct resource address with the correct method. /// </summary> [TestMethod] public void GetLatestObjectVersionAndProperties() { // Create our test runner. var runner = new RestApiTestRunner<ExtendedObjectVersion>(Method.GET, "/REST/objects/0/123/latest.aspx?include=properties"); // Execute. runner.MFWSClient.ObjectOperations.GetLatestObjectVersionAndProperties(0, 123); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.GetLatestObjectVersionAndPropertiesAsync(MFaaP.MFWSClient.ObjID,System.Threading.CancellationToken)"/> /// using an external object's details /// requests the correct resource address with the correct method. /// </summary> [TestMethod] public async Task GetLatestObjectVersionAndPropertiesAsync_External() { // Create our test runner. var runner = new RestApiTestRunner<ExtendedObjectVersion>(Method.GET, "/REST/objects/0/uhello%2Bworld%3A123%2525123/latest.aspx?include=properties"); // Execute. await runner.MFWSClient.ObjectOperations.GetLatestObjectVersionAndPropertiesAsync(new ObjID() { Type = 0, ExternalRepositoryName = "hello world", // This will be double-encoded. ExternalRepositoryObjectID = "123%123" // This will be double-encoded. }); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.GetLatestObjectVersionAndProperties(MFaaP.MFWSClient.ObjID,System.Threading.CancellationToken)"/> /// using an external object's details /// requests the correct resource address with the correct method. /// </summary> [TestMethod] public void GetLatestObjectVersionAndProperties_External() { // Create our test runner. var runner = new RestApiTestRunner<ExtendedObjectVersion>(Method.GET, "/REST/objects/0/uhello%2Bworld%3A123%2525123/latest.aspx?include=properties"); // Execute. runner.MFWSClient.ObjectOperations.GetLatestObjectVersionAndProperties(new ObjID() { Type = 0, ExternalRepositoryName = "hello world", // This will be double-encoded. ExternalRepositoryObjectID = "123%123" // This will be double-encoded. }); // Verify. runner.Verify(); } #endregion #region Creating new objects /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.CreateNewObject"/> /// requests the correct resource address. /// </summary> [TestMethod] public async Task CreateNewObjectAsync() { // Create our test runner. var runner = new RestApiTestRunner<ObjectVersion>(Method.POST, $"/REST/objects/0"); // Execute. await runner.MFWSClient.ObjectOperations.CreateNewObjectAsync(0, new ObjectCreationInfo()); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.CreateNewObject"/> /// requests the correct resource address. /// </summary> [TestMethod] public void CreateNewObject() { // Create our test runner. var runner = new RestApiTestRunner<ObjectVersion>(Method.POST, $"/REST/objects/0"); // Execute. runner.MFWSClient.ObjectOperations.CreateNewObject(0, new ObjectCreationInfo()); // Verify. runner.Verify(); } #endregion #region GetCheckoutStatus /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.GetCheckoutStatusAsync(ObjVer,System.Threading.CancellationToken)"/> /// requests the correct resource address using the correct HTTP method. /// </summary> [TestMethod] public async Task GetCheckoutStatusAsync() { // Create our test runner. var runner = new RestApiTestRunner<PrimitiveType<MFCheckOutStatus>>(Method.GET, $"/REST/objects/0/1/2/checkedout"); // Execute. await runner.MFWSClient.ObjectOperations.GetCheckoutStatusAsync(new ObjVer() { Type = 0, ID = 1, Version = 2 }); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.GetCheckoutStatus(ObjVer,System.Threading.CancellationToken)"/> /// requests the correct resource address using the correct HTTP method. /// </summary> [TestMethod] public void GetCheckoutStatus() { // Create our test runner. var runner = new RestApiTestRunner<PrimitiveType<MFCheckOutStatus>>(Method.GET, $"/REST/objects/0/1/2/checkedout"); // Execute. runner.MFWSClient.ObjectOperations.GetCheckoutStatus(new ObjVer() { Type = 0, ID = 1, Version = 2 }); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.GetCheckoutStatusAsync(ObjVer,System.Threading.CancellationToken)"/> /// when using unmanaged object details /// requests the correct resource address using the correct HTTP method. /// </summary> [TestMethod] public async Task GetCheckoutStatusAsync_External() { // Create our test runner. var runner = new RestApiTestRunner<PrimitiveType<MFCheckOutStatus>>(Method.GET, $"/REST/objects/0/umy+repository:hello+world/latest/checkedout"); // Execute. await runner.MFWSClient.ObjectOperations.GetCheckoutStatusAsync(new ObjVer() { Type = 0, ExternalRepositoryObjectID = "hello world", ExternalRepositoryName = "my repository" }); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.GetCheckoutStatus(ObjVer,System.Threading.CancellationToken)"/> /// when using unmanaged object details /// requests the correct resource address using the correct HTTP method. /// </summary> [TestMethod] public void GetCheckoutStatus_External() { // Create our test runner. var runner = new RestApiTestRunner<PrimitiveType<MFCheckOutStatus>>(Method.GET, $"/REST/objects/0/umy+repository:hello+world/latest/checkedout"); // Execute. runner.MFWSClient.ObjectOperations.GetCheckoutStatus(new ObjVer() { Type = 0, ExternalRepositoryObjectID = "hello world", ExternalRepositoryName = "my repository" }); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.GetCheckoutStatusAsync(ObjVer,System.Threading.CancellationToken)"/> /// when using unmanaged object details /// requests the correct resource address using the correct HTTP method. /// </summary> [TestMethod] public async Task GetCheckoutStatusAsync_External_WithVersion() { // Create our test runner. var runner = new RestApiTestRunner<PrimitiveType<MFCheckOutStatus>>(Method.GET, $"/REST/objects/0/umy+repository:hello+world/myversionid/checkedout"); // Execute. await runner.MFWSClient.ObjectOperations.GetCheckoutStatusAsync(new ObjVer() { Type = 0, ExternalRepositoryObjectID = "hello world", ExternalRepositoryName = "my repository", ExternalRepositoryObjectVersionID = "myversionid" }); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.GetCheckoutStatus(ObjVer,System.Threading.CancellationToken)"/> /// when using unmanaged object details /// requests the correct resource address using the correct HTTP method. /// </summary> [TestMethod] public void GetCheckoutStatus_External_WithVersion() { // Create our test runner. var runner = new RestApiTestRunner<PrimitiveType<MFCheckOutStatus>>(Method.GET, $"/REST/objects/0/umy+repository:hello+world/myversionid/checkedout"); // Execute. runner.MFWSClient.ObjectOperations.GetCheckoutStatus(new ObjVer() { Type = 0, ExternalRepositoryObjectID = "hello world", ExternalRepositoryName = "my repository", ExternalRepositoryObjectVersionID = "myversionid" }); // Verify. runner.Verify(); } #endregion #region Undo checkout /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.UndoCheckout"/> /// requests the correct resource address. /// </summary> [TestMethod] public void UndoCheckout() { // Create our test runner. var runner = new RestApiTestRunner<ObjectVersion>(Method.DELETE, $"/REST/objects/0/1/2?force=false"); // Execute. runner.MFWSClient.ObjectOperations.UndoCheckout(0, 1, 2); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.ForceUndoCheckout"/> /// requests the correct resource address. /// </summary> [TestMethod] public void ForceUndoCheckout() { // Create our test runner. var runner = new RestApiTestRunner<ObjectVersion>(Method.DELETE, $"/REST/objects/0/1/2?force=true"); // Execute. runner.MFWSClient.ObjectOperations.ForceUndoCheckout(0, 1, 2); // Verify. runner.Verify(); } #endregion #region Undelete object /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.UndeleteObject(MFaaP.MFWSClient.ObjID,System.Threading.CancellationToken)"/> /// requests the correct resource address. /// </summary> [TestMethod] public void UndeleteObject() { // Create our test runner. var runner = new RestApiTestRunner<ObjectVersion>(Method.PUT, $"/REST/objects/0/1/deleted"); // Set the expected request body. runner.SetExpectedRequestBody(new PrimitiveType<bool>() { Value = false }); // Execute. runner.MFWSClient.ObjectOperations.UndeleteObject(0, 1); // Verify. runner.Verify(); } #endregion #region Delete object /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.DeleteObject(MFaaP.MFWSClient.ObjID,System.Threading.CancellationToken)"/> /// requests the correct resource address. /// </summary> [TestMethod] public void DeleteObject() { // Create our test runner. var runner = new RestApiTestRunner<ObjectVersion>(Method.PUT, $"/REST/objects/0/1/deleted"); // Set the expected request body. runner.SetExpectedRequestBody(new PrimitiveType<bool>() { Value = true }); // Execute. runner.MFWSClient.ObjectOperations.DeleteObject(0, 1); // Verify. runner.Verify(); } #endregion #region Destroy object /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.DestroyObject(MFaaP.MFWSClient.ObjID,bool,int,System.Threading.CancellationToken)"/> /// requests the correct resource address. /// </summary> [TestMethod] public void DestroyObject() { // Create our test runner. var runner = new RestApiTestRunner<ObjectVersion>(Method.DELETE, $"/REST/objects/0/1/latest?allVersions=true"); // Execute. runner.MFWSClient.ObjectOperations.DestroyObject(0, 1, true, -1); // Verify. runner.Verify(); } #endregion #region SetCheckoutStatus /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.SetCheckoutStatusAsync(ObjVer,MFaaP.MFWSClient.MFCheckOutStatus,System.Threading.CancellationToken)"/> /// requests the correct resource address using the correct HTTP method. /// </summary> [TestMethod] public async Task SetCheckoutStatusAsync() { // Create our test runner. var runner = new RestApiTestRunner<ObjectVersion>(Method.PUT, $"/REST/objects/0/1/2/checkedout"); // Set the expected body. runner.SetExpectedRequestBody(new PrimitiveType<MFCheckOutStatus>() { Value = MFCheckOutStatus.CheckedOutToMe }); // Execute. await runner.MFWSClient.ObjectOperations.SetCheckoutStatusAsync(new ObjVer() { Type = 0, ID = 1, Version = 2 }, MFCheckOutStatus.CheckedOutToMe); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.SetCheckoutStatus(ObjVer,MFaaP.MFWSClient.MFCheckOutStatus,System.Threading.CancellationToken)"/> /// requests the correct resource address using the correct HTTP method. /// </summary> [TestMethod] public void SetCheckoutStatus() { // Create our test runner. var runner = new RestApiTestRunner<ObjectVersion>(Method.PUT, $"/REST/objects/0/1/2/checkedout"); // Set the expected body. runner.SetExpectedRequestBody(new PrimitiveType<MFCheckOutStatus>() { Value = MFCheckOutStatus.CheckedOutToMe }); // Execute. runner.MFWSClient.ObjectOperations.SetCheckoutStatus(new ObjVer() { Type = 0, ID = 1, Version = 2 }, MFCheckOutStatus.CheckedOutToMe); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.SetCheckoutStatusAsync(ObjVer,MFaaP.MFWSClient.MFCheckOutStatus,System.Threading.CancellationToken)"/> /// when using an unmanaged object /// requests the correct resource address using the correct HTTP method. /// </summary> [TestMethod] public async Task SetCheckoutStatusAsync_External() { // Create our test runner. var runner = new RestApiTestRunner<ObjectVersion>(Method.PUT, $"/REST/objects/0/urepository%2Bname%3Amy%2Bobject/uversion%2B1/checkedout"); // Set the expected body. runner.SetExpectedRequestBody(new PrimitiveType<MFCheckOutStatus>() { Value = MFCheckOutStatus.CheckedOutToMe }); // Execute. await runner.MFWSClient.ObjectOperations.SetCheckoutStatusAsync(new ObjVer() { Type = 0, ExternalRepositoryName = "repository name", ExternalRepositoryObjectID = "my object", ExternalRepositoryObjectVersionID = "version 1" }, MFCheckOutStatus.CheckedOutToMe); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.SetCheckoutStatus(ObjVer,MFaaP.MFWSClient.MFCheckOutStatus,System.Threading.CancellationToken)"/> /// when using an unmanaged object /// requests the correct resource address using the correct HTTP method. /// </summary> [TestMethod] public void SetCheckoutStatus_External() { // Create our test runner. var runner = new RestApiTestRunner<ObjectVersion>(Method.PUT, $"/REST/objects/0/urepository%2Bname%3Amy%2Bobject/uversion%2B1/checkedout"); // Set the expected body. runner.SetExpectedRequestBody(new PrimitiveType<MFCheckOutStatus>() { Value = MFCheckOutStatus.CheckedOutToMe }); // Execute. runner.MFWSClient.ObjectOperations.SetCheckoutStatus(new ObjVer() { Type = 0, ExternalRepositoryName = "repository name", ExternalRepositoryObjectID = "my object", ExternalRepositoryObjectVersionID = "version 1" }, MFCheckOutStatus.CheckedOutToMe); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.SetCheckoutStatus(ObjVer,MFaaP.MFWSClient.MFCheckOutStatus,System.Threading.CancellationToken)"/> /// when using an unmanaged object /// requests the correct resource address using the correct HTTP method. /// </summary> [TestMethod] public void SetCheckoutStatus_External_Latest() { // Create our test runner. var runner = new RestApiTestRunner<ObjectVersion>(Method.PUT, $"/REST/objects/0/urepository%2Bname%3Amy%2Bobject/latest/checkedout"); // Set the expected body. runner.SetExpectedRequestBody(new PrimitiveType<MFCheckOutStatus>() { Value = MFCheckOutStatus.CheckedOutToMe }); // Execute. runner.MFWSClient.ObjectOperations.SetCheckoutStatus(new ObjVer() { Type = 0, ExternalRepositoryName = "repository name", ExternalRepositoryObjectID = "my object" }, MFCheckOutStatus.CheckedOutToMe); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.SetCheckoutStatusAsync(ObjID,MFaaP.MFWSClient.MFCheckOutStatus,System.Nullable{int},System.Threading.CancellationToken)"/> /// when providing the latest version /// requests the correct resource address using the correct HTTP method. /// </summary> [TestMethod] public async Task SetCheckoutStatusAsync_LatestVersion() { // Create our test runner. var runner = new RestApiTestRunner<ObjectVersion>(Method.PUT, $"/REST/objects/0/1/latest/checkedout"); // Set the expected body. runner.SetExpectedRequestBody(new PrimitiveType<MFCheckOutStatus>() { Value = MFCheckOutStatus.CheckedOutToMe }); // Execute. await runner.MFWSClient.ObjectOperations.SetCheckoutStatusAsync(new ObjID() { Type = 0, ID = 1 }, MFCheckOutStatus.CheckedOutToMe); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.SetCheckoutStatus(ObjID,MFaaP.MFWSClient.MFCheckOutStatus,System.Nullable{int},System.Threading.CancellationToken)"/> /// when providing the latest version /// requests the correct resource address using the correct HTTP method. /// </summary> [TestMethod] public void SetCheckoutStatus_LatestVersion() { // Create our test runner. var runner = new RestApiTestRunner<ObjectVersion>(Method.PUT, $"/REST/objects/0/1/latest/checkedout"); // Set the expected body. runner.SetExpectedRequestBody(new PrimitiveType<MFCheckOutStatus>() { Value = MFCheckOutStatus.CheckedOutToMe }); // Execute. runner.MFWSClient.ObjectOperations.SetCheckoutStatus(new ObjID() { Type = 0, ID = 1 }, MFCheckOutStatus.CheckedOutToMe); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.SetCheckoutStatus(ObjID,MFaaP.MFWSClient.MFCheckOutStatus,System.Nullable{int},System.Threading.CancellationToken)"/> /// when providing the latest version /// requests the correct resource address using the correct HTTP method. /// </summary> [TestMethod] public void SetCheckoutStatus_CheckIn() { // Create our test runner. var runner = new RestApiTestRunner<ObjectVersion>(Method.PUT, $"/REST/objects/0/1/latest/checkedout"); // Set the expected body. runner.SetExpectedRequestBody(new PrimitiveType<MFCheckOutStatus>() { Value = MFCheckOutStatus.CheckedIn }); // Execute. runner.MFWSClient.ObjectOperations.SetCheckoutStatus(new ObjID() { Type = 0, ID = 1 }, MFCheckOutStatus.CheckedIn); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.SetCheckoutStatus(ObjID,MFaaP.MFWSClient.MFCheckOutStatus,System.Nullable{int},System.Threading.CancellationToken)"/> /// when providing the latest version /// requests the correct resource address using the correct HTTP method. /// </summary> [TestMethod] public void SetCheckoutStatus_CheckedOutToMe() { // Create our test runner. var runner = new RestApiTestRunner<ObjectVersion>(Method.PUT, $"/REST/objects/0/1/latest/checkedout"); // Set the expected body. runner.SetExpectedRequestBody(new PrimitiveType<MFCheckOutStatus>() { Value = MFCheckOutStatus.CheckedOutToMe }); // Execute. runner.MFWSClient.ObjectOperations.SetCheckoutStatus(new ObjID() { Type = 0, ID = 1 }, MFCheckOutStatus.CheckedOutToMe); // Verify. runner.Verify(); } #endregion #region GetHistory /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.GetHistory(int,int,System.Threading.CancellationToken)"/> /// requests the correct resource address and HTTP method. /// </summary> [TestMethod] public async Task GetHistoryAsync() { // Create our test runner. var runner = new RestApiTestRunner<List<ObjectVersion>>(Method.GET, $"/REST/objects/0/1/history"); // Execute. await runner.MFWSClient.ObjectOperations.GetHistoryAsync(new ObjID() { Type = 0, ID = 1 }); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.GetHistory(int,int,System.Threading.CancellationToken)"/> /// requests the correct resource address and HTTP method. /// </summary> [TestMethod] public void GetHistory() { // Create our test runner. var runner = new RestApiTestRunner<List<ObjectVersion>>(Method.GET, $"/REST/objects/0/1/history"); // Execute. runner.MFWSClient.ObjectOperations.GetHistory(new ObjID() { Type = 0, ID = 1 }); // Verify. runner.Verify(); } #endregion #region RemoveFromFavorites /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.RemoveFromFavoritesAsync(MFaaP.MFWSClient.ObjID,System.Threading.CancellationToken)"/> /// requests the correct resource address and HTTP method. /// </summary> [TestMethod] public async Task RemoveFromFavoritesAsync() { // Create our test runner. var runner = new RestApiTestRunner<ExtendedObjectVersion>(Method.DELETE, $"/REST/favorites/1/2"); // Execute. await runner.MFWSClient.ObjectOperations.RemoveFromFavoritesAsync(new ObjID() { Type = 1, ID = 2 }); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.RemoveFromFavorites(MFaaP.MFWSClient.ObjID,System.Threading.CancellationToken)"/> /// requests the correct resource address and HTTP method. /// </summary> [TestMethod] public void RemoveFromFavorites() { // Create our test runner. var runner = new RestApiTestRunner<ExtendedObjectVersion>(Method.DELETE, $"/REST/favorites/1/2"); // Execute. runner.MFWSClient.ObjectOperations.RemoveFromFavorites(new ObjID() { Type = 1, ID = 2 }); // Verify. runner.Verify(); } #endregion #region AddToFavorites /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.AddToFavoritesAsync(MFaaP.MFWSClient.ObjID,System.Threading.CancellationToken)"/> /// requests the correct resource address and HTTP method. /// </summary> [TestMethod] public async Task AddToFavoritesAsync() { // Create our test runner. var runner = new RestApiTestRunner<ExtendedObjectVersion>(Method.POST, $"/REST/favorites"); // Set the expected body. var objId = new ObjID() { Type = 0, ID = 1 }; runner.SetExpectedRequestBody(objId); // Execute. await runner.MFWSClient.ObjectOperations.AddToFavoritesAsync(objId); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultObjectOperations.AddToFavorites(MFaaP.MFWSClient.ObjID,System.Threading.CancellationToken)"/> /// requests the correct resource address and HTTP method. /// </summary> [TestMethod] public void AddToFavorites() { // Create our test runner. var runner = new RestApiTestRunner<ExtendedObjectVersion>(Method.POST, $"/REST/favorites"); // Set the expected body. var objId = new ObjID() { Type = 0, ID = 1 }; runner.SetExpectedRequestBody(objId); // Execute. runner.MFWSClient.ObjectOperations.AddToFavorites(objId); // Verify. runner.Verify(); } #endregion } } <|start_filename|>MFaaP.MFWSClient.Tests/MFWSVaultClassGroupOperations.cs<|end_filename|> using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using RestSharp; namespace MFaaP.MFWSClient.Tests { [TestClass] public class MFWSVaultClassGroupOperations { #region GetClassGroups /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultClassGroupOperations.GetClassGroupsAsync"/> /// requests the correct resource address with the correct method. /// </summary> [TestMethod] public async Task GetClassGroupsAsync() { // Create our test runner. var runner = new RestApiTestRunner<List<ClassGroup>>(Method.GET, "/REST/structure/classes.aspx?objtype=0&bygroup=true"); // Execute. await runner.MFWSClient.ClassGroupOperations.GetClassGroupsAsync(0); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultClassGroupOperations.GetClassGroups"/> /// requests the correct resource address with the correct method. /// </summary> [TestMethod] public void GetClassGroups() { // Create our test runner. var runner = new RestApiTestRunner<List<ClassGroup>>(Method.GET, "/REST/structure/classes.aspx?objtype=0&bygroup=true"); // Execute. runner.MFWSClient.ClassGroupOperations.GetClassGroups(0); // Verify. runner.Verify(); } #endregion } } <|start_filename|>MFaaP.MFWSClient.Tests/MFWSVaultValueListItemOperations.cs<|end_filename|> using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using RestSharp; namespace MFaaP.MFWSClient.Tests { [TestClass] public class MFWSVaultValueListItemOperations { #region GetValueListItems /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultValueListItemOperations.GetValueListItemsAsync"/> /// requests the correct resource using the correct method. /// </summary> [TestMethod] public async Task GetValueListItemsAsync() { // Create our test runner. var runner = new RestApiTestRunner<Results<ValueListItem>>(Method.GET, "/REST/valuelists/1/items"); // Execute. await runner.MFWSClient.ValueListItemOperations.GetValueListItemsAsync(1); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultValueListItemOperations.GetValueListItems"/> /// requests the correct resource using the correct method. /// </summary> [TestMethod] public void GetValueListItems() { // Create our test runner. var runner = new RestApiTestRunner<Results<ValueListItem>>(Method.GET, "/REST/valuelists/1/items"); // Execute. runner.MFWSClient.ValueListItemOperations.GetValueListItems(1); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultValueListItemOperations.GetValueListItemsAsync"/> /// requests the correct resource using the correct method (when using a name filter). /// </summary> [TestMethod] public async Task GetValueListItemsAsync_WithNameFilter() { // Create our test runner. var runner = new RestApiTestRunner<Results<ValueListItem>>(Method.GET, "/REST/valuelists/1/items?filter=hello"); // Execute. await runner.MFWSClient.ValueListItemOperations.GetValueListItemsAsync(1, "hello"); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultValueListItemOperations.GetValueListItems"/> /// requests the correct resource using the correct method (when using a name filter). /// </summary> [TestMethod] public void GetValueListItems_WithNameFilter() { // Create our test runner. var runner = new RestApiTestRunner<Results<ValueListItem>>(Method.GET, "/REST/valuelists/1/items?filter=hello"); // Execute. runner.MFWSClient.ValueListItemOperations.GetValueListItems(1, "hello"); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultValueListItemOperations.GetValueListItemsAsync"/> /// requests the correct resource using the correct method (when using a limit). /// </summary> [TestMethod] public async Task GetValueListItemsAsync_WithLimit() { // Create our test runner. var runner = new RestApiTestRunner<Results<ValueListItem>>(Method.GET, "/REST/valuelists/1/items?limit=501"); // Execute. await runner.MFWSClient.ValueListItemOperations.GetValueListItemsAsync(1, limit: 501); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultValueListItemOperations.GetValueListItems"/> /// requests the correct resource using the correct method (when using a limit). /// </summary> [TestMethod] public void GetValueListItems_WithLimit() { // Create our test runner. var runner = new RestApiTestRunner<Results<ValueListItem>>(Method.GET, "/REST/valuelists/1/items?limit=501"); // Execute. runner.MFWSClient.ValueListItemOperations.GetValueListItems(1, limit: 501); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultValueListItemOperations.GetValueListItemsAsync"/> /// requests the correct resource using the correct method (when using a name filter and limit). /// </summary> [TestMethod] public async Task GetValueListItemsAsync_WithLimitAndNameFilter() { // Create our test runner. var runner = new RestApiTestRunner<Results<ValueListItem>>(Method.GET, "/REST/valuelists/1/items?filter=hello&limit=501"); // Execute. await runner.MFWSClient.ValueListItemOperations.GetValueListItemsAsync(1, "hello", limit: 501); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultValueListItemOperations.GetValueListItems"/> /// requests the correct resource using the correct method (when using a name filter and limit). /// </summary> [TestMethod] public void GetValueListItems_WithLimitAndNameFilter() { // Create our test runner. var runner = new RestApiTestRunner<Results<ValueListItem>>(Method.GET, "/REST/valuelists/1/items?filter=hello&limit=501"); // Execute. runner.MFWSClient.ValueListItemOperations.GetValueListItems(1, "hello", limit: 501); // Verify. runner.Verify(); } #endregion #region AddValueListItem /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultValueListItemOperations.CreateValueListItemAsync"/> /// requests the correct resource using the correct method. /// </summary> [TestMethod] public async Task AddValueListItemByNameAsync() { // Create our test runner. var runner = new RestApiTestRunner<ValueListItem>(Method.POST, "/REST/valuelists/1/items"); // Set the expected body. var newVLitem = new ValueListItem { ValueListID = 1, Name = "new valuelistItem name" }; runner.SetExpectedRequestBody(newVLitem); // Execute. await runner.MFWSClient.ValueListItemOperations.AddValueListItemAsync(1, "new valuelistItem name"); // Verify. runner.Verify(); } /// <summary> /// Ensures that <see cref="MFaaP.MFWSClient.MFWSVaultValueListItemOperations.AddValueListItemAsync"/> /// excepts with a null name. /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentException))] public async Task AddValueListItemByNameAsyncThrowsWithNullName() { // Create our test runner. var runner = new RestApiTestRunner<ValueListItem>(Method.POST, "/REST/valuelists/1/items"); // Execute. await runner.MFWSClient.ValueListItemOperations.AddValueListItemAsync(1, newItemName: null); } /// <summary> /// Ensures that <see cref="MFaaP.MFWSClient.MFWSVaultValueListItemOperations.AddValueListItemAsync"/> /// excepts with a blank name. /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentException))] public async Task AddValueListItemByNameAsyncThrowsWithBlankName() { // Create our test runner. var runner = new RestApiTestRunner<ValueListItem>(Method.POST, "/REST/valuelists/1/items"); // Execute. await runner.MFWSClient.ValueListItemOperations.AddValueListItemAsync(1, newItemName: ""); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultValueListItemOperations.AddValueListItem"/> /// requests the correct resource using the correct method. /// </summary> [TestMethod] public void AddValueListItemByName() { // Create our test runner. var runner = new RestApiTestRunner<ValueListItem>(Method.POST, "/REST/valuelists/1/items"); // Set the expected body. var newVLitem = new ValueListItem { ValueListID = 1, Name = "new valuelistItem name" }; runner.SetExpectedRequestBody(newVLitem); // Execute. runner.MFWSClient.ValueListItemOperations.AddValueListItem(1, "new valuelistItem name"); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultValueListItemOperations.AddValueListItemAsync"/> /// requests the correct resource using the correct method. /// </summary> [TestMethod] public async Task AddValueListItemAsync() { // Create our test runner. var runner = new RestApiTestRunner<ValueListItem>(Method.POST, "/REST/valuelists/1/items"); // Set the expected body. var newVLitem = new ValueListItem { ValueListID = 1, Name = "new valuelistItem name" }; runner.SetExpectedRequestBody(newVLitem); // Execute. await runner.MFWSClient.ValueListItemOperations.AddValueListItemAsync ( 1, newVLitem ); // Verify. runner.Verify(); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultValueListItemOperations.AddValueListItemAsync"/> /// requests the correct resource using the correct method. /// </summary> [TestMethod] public async Task AddValueListItemValueListIDPopulatedAsync() { // Create our test runner. var runner = new RestApiTestRunner<ValueListItem>(Method.POST, "/REST/valuelists/23/items"); // Set the expected body. var newVLitem = new ValueListItem { ValueListID = 23, Name = "new valuelistItem name" }; runner.SetExpectedRequestBody(newVLitem); // Execute. await runner.MFWSClient.ValueListItemOperations.AddValueListItemAsync ( 23, new ValueListItem { Name = "new valuelistItem name" } ); // Verify. runner.Verify(); } /// <summary> /// Ensures that <see cref="MFaaP.MFWSClient.MFWSVaultValueListItemOperations.AddValueListItemAsync"/> /// excepts with a null value. /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public async Task AddValueListItemAsyncThrowsWithNull() { // Create our test runner. var runner = new RestApiTestRunner<ValueListItem>(Method.POST, "/REST/valuelists/1/items"); // Execute. await runner.MFWSClient.ValueListItemOperations.AddValueListItemAsync(1, valueListItem: null); } /// <summary> /// Ensures that a call to <see cref="MFaaP.MFWSClient.MFWSVaultValueListItemOperations.CreateValueListItem"/> /// requests the correct resource using the correct method. /// </summary> [TestMethod] public void AddValueListItem() { // Create our test runner. var runner = new RestApiTestRunner<ValueListItem>(Method.POST, "/REST/valuelists/1/items"); // Set the expected body. var newVLitem = new ValueListItem { ValueListID = 1, Name = "new valuelistItem name" }; runner.SetExpectedRequestBody(newVLitem); // Execute. runner.MFWSClient.ValueListItemOperations.AddValueListItem ( 1, newVLitem ); // Verify. runner.Verify(); } #endregion } } <|start_filename|>MFaaP.MFWSClient/MFWSVaultClassGroupOperations.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using RestSharp; namespace MFaaP.MFWSClient { /// <summary> /// Methods to create and modify objects. /// </summary> public class MFWSVaultClassGroupOperations : MFWSVaultOperationsBase { /// <summary> /// Creates a new <see cref="MFWSVaultClassGroupOperations"/> object. /// </summary> /// <param name="client">The client to interact with the server.</param> internal MFWSVaultClassGroupOperations(MFWSClientBase client) : base(client) { } /// <summary> /// Gets a list of all class groups with classes in the vault for a given object type. /// </summary> /// <param name="objectTypeId">The type of the object.</param> /// <param name="token">A cancellation token for the request.</param> /// <returns>All classes in the vault for the supplied object type.</returns> /// <remarks>This may be filtered by the user's permissions.</remarks> public async Task<List<ClassGroup>> GetClassGroupsAsync(int objectTypeId, CancellationToken token = default(CancellationToken)) { // Create the request. var request = new RestRequest($"/REST/structure/classes.aspx?objtype={objectTypeId}&bygroup=true"); // Make the request and get the response. var response = await this.MFWSClient.Get<List<ClassGroup>>(request, token) .ConfigureAwait(false); // Return the data. return response.Data; } /// <summary> /// Gets a list of all classes in the vault for a given object type. /// </summary> /// <param name="objectTypeId">The type of the object.</param> /// <param name="token">A cancellation token for the request.</param> /// <returns>All classes in the vault for the supplied object type.</returns> /// <remarks>This may be filtered by the user's permissions.</remarks> public List<ClassGroup> GetClassGroups(int objectTypeId, CancellationToken token = default(CancellationToken)) { // Execute the async method. return this.GetClassGroupsAsync(objectTypeId, token) .ConfigureAwait(false) .GetAwaiter() .GetResult(); } } }
MatthewFocus/Libraries.MFWSClient
<|start_filename|>repository/src/main/java/org/apache/atlas/repository/store/graph/v1/SoftDeleteHandlerV1.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.store.graph.v1; import org.apache.atlas.RequestContextV1; import org.apache.atlas.annotation.ConditionalOnAtlasProperty; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.instance.AtlasEntity; import org.apache.atlas.repository.graph.GraphHelper; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.type.AtlasTypeRegistry; import org.springframework.stereotype.Component; import javax.inject.Inject; import static org.apache.atlas.repository.Constants.MODIFICATION_TIMESTAMP_PROPERTY_KEY; import static org.apache.atlas.repository.Constants.MODIFIED_BY_KEY; import static org.apache.atlas.repository.Constants.STATE_PROPERTY_KEY; @Component @ConditionalOnAtlasProperty(property = "atlas.DeleteHandlerV1.impl", isDefault = true) public class SoftDeleteHandlerV1 extends DeleteHandlerV1 { @Inject public SoftDeleteHandlerV1(AtlasTypeRegistry typeRegistry) { super(typeRegistry, false, true); } @Override protected void _deleteVertex(AtlasVertex instanceVertex, boolean force) { if (force) { graphHelper.removeVertex(instanceVertex); } else { AtlasEntity.Status state = AtlasGraphUtilsV1.getState(instanceVertex); if (state != AtlasEntity.Status.DELETED) { GraphHelper.setProperty(instanceVertex, STATE_PROPERTY_KEY, AtlasEntity.Status.DELETED.name()); GraphHelper.setProperty(instanceVertex, MODIFICATION_TIMESTAMP_PROPERTY_KEY, RequestContextV1.get().getRequestTime()); GraphHelper.setProperty(instanceVertex, MODIFIED_BY_KEY, RequestContextV1.get().getUser()); } } } @Override protected void deleteEdge(AtlasEdge edge, boolean force) throws AtlasBaseException { if (force) { graphHelper.removeEdge(edge); } else { AtlasEntity.Status state = AtlasGraphUtilsV1.getState(edge); if (state != AtlasEntity.Status.DELETED) { GraphHelper.setProperty(edge, STATE_PROPERTY_KEY, AtlasEntity.Status.DELETED.name()); GraphHelper .setProperty(edge, MODIFICATION_TIMESTAMP_PROPERTY_KEY, RequestContextV1.get().getRequestTime()); GraphHelper.setProperty(edge, MODIFIED_BY_KEY, RequestContextV1.get().getUser()); } } } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/store/graph/v1/AtlasRelationshipStoreV1.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.store.graph.v1; import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.annotation.GraphTransaction; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.TypeCategory; import org.apache.atlas.model.instance.AtlasObjectId; import org.apache.atlas.model.instance.AtlasRelationship; import org.apache.atlas.model.typedef.AtlasRelationshipEndDef; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.RepositoryException; import org.apache.atlas.repository.graph.GraphHelper; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.repository.graphdb.GremlinVersion; import org.apache.atlas.repository.store.graph.AtlasRelationshipStore; import org.apache.atlas.type.AtlasEntityType; import org.apache.atlas.type.AtlasRelationshipType; import org.apache.atlas.type.AtlasStructType; import org.apache.atlas.type.AtlasStructType.AtlasAttribute; import org.apache.atlas.type.AtlasType; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.type.AtlasTypeUtil; import org.apache.atlas.typesystem.exception.EntityNotFoundException; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.inject.Inject; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; @Component public class AtlasRelationshipStoreV1 implements AtlasRelationshipStore { private static final Logger LOG = LoggerFactory.getLogger(AtlasRelationshipStoreV1.class); private static final int DEFAULT_RELATIONSHIP_VERSION = 0; private final AtlasTypeRegistry typeRegistry; private final EntityGraphRetriever entityRetriever; private final GraphHelper graphHelper = GraphHelper.getInstance(); @Inject public AtlasRelationshipStoreV1(AtlasTypeRegistry typeRegistry) { this.typeRegistry = typeRegistry; this.entityRetriever = new EntityGraphRetriever(typeRegistry); } @Override @GraphTransaction public AtlasRelationship create(AtlasRelationship relationship) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> create({})", relationship); } validateRelationship(relationship); AtlasVertex end1Vertex = getVertexFromEndPoint(relationship.getEnd1()); AtlasVertex end2Vertex = getVertexFromEndPoint(relationship.getEnd2()); AtlasRelationship ret = createRelationship(relationship, end1Vertex, end2Vertex); if (LOG.isDebugEnabled()) { LOG.debug("<== create({}): {}", relationship, ret); } return ret; } @Override @GraphTransaction public AtlasRelationship update(AtlasRelationship relationship) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> update({})", relationship); } AtlasRelationship ret = null; // TODO: update(relationship) implementation if (LOG.isDebugEnabled()) { LOG.debug("<== update({}): {}", relationship, ret); } return ret; } @Override @GraphTransaction public AtlasRelationship getById(String guid) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> getById({})", guid); } AtlasRelationship ret; try { AtlasEdge edge = graphHelper.getEdgeForGUID(guid); ret = mapEdgeToAtlasRelationship(edge); } catch (EntityNotFoundException ex) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIP_GUID_NOT_FOUND, guid); } if (LOG.isDebugEnabled()) { LOG.debug("<== getById({}): {}", guid, ret); } return ret; } @Override @GraphTransaction public void deleteById(String guid) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> deleteById({})", guid); } // TODO: deleteById(guid) implementation if (LOG.isDebugEnabled()) { LOG.debug("<== deleteById({}): {}", guid); } } public AtlasRelationship getOrCreate(AtlasRelationship relationship) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> getOrCreate({})", relationship); } validateRelationship(relationship); AtlasVertex end1Vertex = getVertexFromEndPoint(relationship.getEnd1()); AtlasVertex end2Vertex = getVertexFromEndPoint(relationship.getEnd2()); AtlasRelationship ret; // check if relationship exists AtlasEdge relationshipEdge = getRelationshipEdge(end1Vertex, end2Vertex, relationship); if (relationshipEdge != null) { ret = mapEdgeToAtlasRelationship(relationshipEdge); } else { validateRelationship(relationship); ret = createRelationship(relationship, end1Vertex, end2Vertex); } if (LOG.isDebugEnabled()) { LOG.debug("<== getOrCreate({}): {}", relationship, ret); } return ret; } private AtlasRelationship createRelationship(AtlasRelationship relationship, AtlasVertex end1Vertex, AtlasVertex end2Vertex) throws AtlasBaseException { AtlasRelationship ret; try { AtlasEdge relationshipEdge = getRelationshipEdge(end1Vertex, end2Vertex, relationship); if (relationshipEdge == null) { relationshipEdge = createRelationshipEdge(end1Vertex, end2Vertex, relationship); AtlasRelationshipType relationType = typeRegistry.getRelationshipTypeByName(relationship.getTypeName()); if (MapUtils.isNotEmpty(relationType.getAllAttributes())) { for (AtlasAttribute attr : relationType.getAllAttributes().values()) { String attrName = attr.getName(); String attrVertexProperty = attr.getVertexPropertyName(); Object attrValue = relationship.getAttribute(attrName); AtlasGraphUtilsV1.setProperty(relationshipEdge, attrVertexProperty, attrValue); } } ret = mapEdgeToAtlasRelationship(relationshipEdge); } else { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIP_ALREADY_EXISTS, relationship.getTypeName(), relationship.getEnd1().getGuid(), relationship.getEnd2().getGuid()); } } catch (RepositoryException e) { throw new AtlasBaseException(AtlasErrorCode.INTERNAL_ERROR, e); } return ret; } private void validateRelationship(AtlasRelationship relationship) throws AtlasBaseException { if (relationship == null) { throw new AtlasBaseException(AtlasErrorCode.INVALID_PARAMETERS, "AtlasRelationship is null"); } String relationshipName = relationship.getTypeName(); String end1TypeName = getTypeNameFromObjectId(relationship.getEnd1()); String end2TypeName = getTypeNameFromObjectId(relationship.getEnd2()); AtlasRelationshipType relationshipType = typeRegistry.getRelationshipTypeByName(relationshipName); if (relationshipType == null) { throw new AtlasBaseException(AtlasErrorCode.INVALID_VALUE, "unknown relationship type'" + relationshipName + "'"); } if (relationship.getEnd1() == null || relationship.getEnd2() == null) { throw new AtlasBaseException(AtlasErrorCode.INVALID_PARAMETERS, "end1/end2 is null"); } if (!relationshipType.getEnd1Type().isTypeOrSuperTypeOf(end1TypeName) && !relationshipType.getEnd2Type().isTypeOrSuperTypeOf(end1TypeName)) { throw new AtlasBaseException(AtlasErrorCode.INVALID_RELATIONSHIP_END_TYPE, relationshipName, relationshipType.getEnd2Type().getTypeName(), end1TypeName); } if (!relationshipType.getEnd2Type().isTypeOrSuperTypeOf(end2TypeName) && !relationshipType.getEnd1Type().isTypeOrSuperTypeOf(end2TypeName)) { throw new AtlasBaseException(AtlasErrorCode.INVALID_RELATIONSHIP_END_TYPE, relationshipName, relationshipType.getEnd1Type().getTypeName(), end2TypeName); } validateEnd(relationship.getEnd1()); validateEnd(relationship.getEnd2()); validateAndNormalize(relationship); } private void validateEnd(AtlasObjectId end) throws AtlasBaseException { String guid = end.getGuid(); String typeName = end.getTypeName(); Map<String, Object> uniqueAttributes = end.getUniqueAttributes(); AtlasVertex endVertex = AtlasGraphUtilsV1.findByGuid(guid); if (!AtlasTypeUtil.isValidGuid(guid) || endVertex == null) { throw new AtlasBaseException(AtlasErrorCode.INSTANCE_GUID_NOT_FOUND, guid); } else if (MapUtils.isNotEmpty(uniqueAttributes)) { AtlasEntityType entityType = typeRegistry.getEntityTypeByName(typeName); if (AtlasGraphUtilsV1.findByUniqueAttributes(entityType, uniqueAttributes) == null) { throw new AtlasBaseException(AtlasErrorCode.INSTANCE_BY_UNIQUE_ATTRIBUTE_NOT_FOUND, typeName, uniqueAttributes.toString()); } } } private void validateAndNormalize(AtlasRelationship relationship) throws AtlasBaseException { List<String> messages = new ArrayList<>(); if (! AtlasTypeUtil.isValidGuid(relationship.getGuid())) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIP_GUID_NOT_FOUND, relationship.getGuid()); } AtlasRelationshipType type = typeRegistry.getRelationshipTypeByName(relationship.getTypeName()); if (type == null) { throw new AtlasBaseException(AtlasErrorCode.TYPE_NAME_INVALID, TypeCategory.RELATIONSHIP.name(), relationship.getTypeName()); } type.validateValue(relationship, relationship.getTypeName(), messages); if (!messages.isEmpty()) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIP_CRUD_INVALID_PARAMS, messages); } type.getNormalizedValue(relationship); } public AtlasEdge getRelationshipEdge(AtlasVertex fromVertex, AtlasVertex toVertex, AtlasRelationship relationship) { String relationshipLabel = getRelationshipEdgeLabel(fromVertex, toVertex, relationship); AtlasEdge ret = graphHelper.getEdgeForLabel(fromVertex, relationshipLabel); if (ret != null) { AtlasVertex inVertex = ret.getInVertex(); if (inVertex != null) { if (!StringUtils.equals(AtlasGraphUtilsV1.getIdFromVertex(inVertex), AtlasGraphUtilsV1.getIdFromVertex(toVertex))) { ret = null; } } } return ret; } private int getRelationshipVersion(AtlasRelationship relationship) { Long ret = relationship != null ? relationship.getVersion() : null; return (ret != null) ? ret.intValue() : DEFAULT_RELATIONSHIP_VERSION; } private AtlasVertex getVertexFromEndPoint(AtlasObjectId endPoint) { AtlasVertex ret = null; if (StringUtils.isNotEmpty(endPoint.getGuid())) { ret = AtlasGraphUtilsV1.findByGuid(endPoint.getGuid()); } else if (StringUtils.isNotEmpty(endPoint.getTypeName()) && MapUtils.isNotEmpty(endPoint.getUniqueAttributes())) { AtlasEntityType entityType = typeRegistry.getEntityTypeByName(endPoint.getTypeName()); ret = AtlasGraphUtilsV1.findByUniqueAttributes(entityType, endPoint.getUniqueAttributes()); } return ret; } private AtlasEdge createRelationshipEdge(AtlasVertex fromVertex, AtlasVertex toVertex, AtlasRelationship relationship) throws RepositoryException { String relationshipLabel = getRelationshipEdgeLabel(fromVertex, toVertex, relationship); AtlasEdge ret = graphHelper.getOrCreateEdge(fromVertex, toVertex, relationshipLabel); // map additional properties to relationship edge if (ret != null) { final String guid = UUID.randomUUID().toString(); AtlasGraphUtilsV1.setProperty(ret, Constants.ENTITY_TYPE_PROPERTY_KEY, relationship.getTypeName()); AtlasGraphUtilsV1.setProperty(ret, Constants.GUID_PROPERTY_KEY, guid); AtlasGraphUtilsV1.setProperty(ret, Constants.VERSION_PROPERTY_KEY, getRelationshipVersion(relationship)); } return ret; } private String getRelationshipEdgeLabel(AtlasVertex fromVertex, AtlasVertex toVertex, AtlasRelationship relationship) { AtlasRelationshipType relationshipType = typeRegistry.getRelationshipTypeByName(relationship.getTypeName()); String ret = relationshipType.getRelationshipDef().getRelationshipLabel(); AtlasRelationshipEndDef endDef1 = relationshipType.getRelationshipDef().getEndDef1(); AtlasRelationshipEndDef endDef2 = relationshipType.getRelationshipDef().getEndDef2(); Set<String> fromVertexTypes = getTypeAndAllSuperTypes(AtlasGraphUtilsV1.getTypeName(fromVertex)); Set<String> toVertexTypes = getTypeAndAllSuperTypes(AtlasGraphUtilsV1.getTypeName(toVertex)); AtlasAttribute attribute = null; // validate entity type and all its supertypes contains relationshipDefs end type // e.g. [hive_process -> hive_table] -> [Process -> DataSet] if (fromVertexTypes.contains(endDef1.getType()) && toVertexTypes.contains(endDef2.getType())) { String attributeName = endDef1.getName(); attribute = relationshipType.getEnd1Type().getRelationshipAttribute(attributeName); } else if (fromVertexTypes.contains(endDef2.getType()) && toVertexTypes.contains(endDef1.getType())) { String attributeName = endDef2.getName(); attribute = relationshipType.getEnd2Type().getRelationshipAttribute(attributeName); } if (attribute != null) { ret = attribute.getRelationshipEdgeLabel(); } return ret; } public Set<String> getTypeAndAllSuperTypes(String entityTypeName) { AtlasEntityType entityType = typeRegistry.getEntityTypeByName(entityTypeName); return (entityType != null) ? entityType.getTypeAndAllSuperTypes() : new HashSet<String>(); } private AtlasRelationship mapEdgeToAtlasRelationship(AtlasEdge edge) throws AtlasBaseException { AtlasRelationship ret = new AtlasRelationship(); mapSystemAttributes(edge, ret); mapAttributes(edge, ret); return ret; } private AtlasRelationship mapSystemAttributes(AtlasEdge edge, AtlasRelationship relationship) { if (LOG.isDebugEnabled()) { LOG.debug("Mapping system attributes for relationship"); } relationship.setGuid(GraphHelper.getGuid(edge)); relationship.setTypeName(GraphHelper.getTypeName(edge)); relationship.setCreatedBy(GraphHelper.getCreatedByAsString(edge)); relationship.setUpdatedBy(GraphHelper.getModifiedByAsString(edge)); relationship.setCreateTime(new Date(GraphHelper.getCreatedTime(edge))); relationship.setUpdateTime(new Date(GraphHelper.getModifiedTime(edge))); Integer version = GraphHelper.getVersion(edge); if (version == null) { version = Integer.valueOf(1); } relationship.setVersion(version.longValue()); relationship.setStatus(GraphHelper.getEdgeStatus(edge)); AtlasVertex end1Vertex = edge.getOutVertex(); AtlasVertex end2Vertex = edge.getInVertex(); relationship.setEnd1(new AtlasObjectId(GraphHelper.getGuid(end1Vertex), GraphHelper.getTypeName(end1Vertex))); relationship.setEnd2(new AtlasObjectId(GraphHelper.getGuid(end2Vertex), GraphHelper.getTypeName(end2Vertex))); relationship.setLabel(edge.getLabel()); return relationship; } private void mapAttributes(AtlasEdge edge, AtlasRelationship relationship) throws AtlasBaseException { AtlasType objType = typeRegistry.getType(relationship.getTypeName()); if (!(objType instanceof AtlasRelationshipType)) { throw new AtlasBaseException(AtlasErrorCode.TYPE_NAME_INVALID, relationship.getTypeName()); } AtlasRelationshipType relationshipType = (AtlasRelationshipType) objType; for (AtlasAttribute attribute : relationshipType.getAllAttributes().values()) { // mapping only primitive attributes Object attrValue = entityRetriever.mapVertexToPrimitive(edge, attribute.getQualifiedName(), attribute.getAttributeDef()); relationship.setAttribute(attribute.getName(), attrValue); } } private String getTypeNameFromObjectId(AtlasObjectId objectId) { String typeName = objectId.getTypeName(); if (StringUtils.isBlank(typeName)) { typeName = AtlasGraphUtilsV1.getTypeNameFromGuid(objectId.getGuid()); } return typeName; } } <|start_filename|>repository/src/main/java/org/apache/atlas/services/MetricsService.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.services; import com.google.common.annotations.VisibleForTesting; import org.apache.atlas.ApplicationProperties; import org.apache.atlas.AtlasException; import org.apache.atlas.annotation.AtlasService; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.metrics.AtlasMetrics; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.util.AtlasGremlinQueryProvider; import org.apache.atlas.util.AtlasGremlinQueryProvider.AtlasGremlinQuery; import org.apache.commons.configuration.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import java.util.List; import java.util.Map; @AtlasService public class MetricsService { private static final Logger LOG = LoggerFactory.getLogger(MetricsService.class); // Query Category constants public static final String TYPE = "type"; public static final String ENTITY = "entity"; public static final String TAG = "tag"; public static final String GENERAL = "general"; // Query names protected static final String METRIC_TYPE_COUNT = TYPE + "Count"; protected static final String METRIC_TYPE_UNUSED_COUNT = TYPE + "UnusedCount"; protected static final String METRIC_TYPE_ENTITIES = TYPE + "Entities"; protected static final String METRIC_ENTITY_COUNT = ENTITY + "Count"; protected static final String METRIC_ENTITY_DELETED = ENTITY + "Deleted"; protected static final String METRIC_TAGGED_ENTITIES = ENTITY + "Tagged"; protected static final String METRIC_TAGS_PER_ENTITY = ENTITY + "Tags"; protected static final String METRIC_TAG_COUNT = TAG + "Count"; protected static final String METRIC_ENTITIES_PER_TAG = TAG + "Entities"; public static final String METRIC_QUERY_PREFIX = "atlas.metric.query."; public static final String METRIC_QUERY_CACHE_TTL = "atlas.metric.query.cache.ttlInSecs"; public static final int DEFAULT_CACHE_TTL_IN_SECS = 900; public static final String METRIC_COLLECTION_TIME = "collectionTime"; private static Configuration configuration = null; private static AtlasGremlinQueryProvider gremlinQueryProvider = null; private final AtlasGraph atlasGraph; private final int cacheTTLInSecs; private AtlasMetrics cachedMetrics = null; private long cacheExpirationTime = 0; @Inject public MetricsService(AtlasGraph atlasGraph) throws AtlasException { this(ApplicationProperties.get(), atlasGraph); } @VisibleForTesting MetricsService(Configuration configuration, AtlasGraph graph) { MetricsService.configuration = configuration; atlasGraph = graph; cacheTTLInSecs = configuration != null ? configuration.getInt(METRIC_QUERY_CACHE_TTL, DEFAULT_CACHE_TTL_IN_SECS) : DEFAULT_CACHE_TTL_IN_SECS; gremlinQueryProvider = AtlasGremlinQueryProvider.INSTANCE; } @SuppressWarnings("unchecked") public AtlasMetrics getMetrics(boolean ignoreCache) { if (ignoreCache || !isCacheValid()) { AtlasMetrics metrics = new AtlasMetrics(); for (MetricQuery metricQuery : MetricQuery.values()) { try { if (LOG.isDebugEnabled()) { LOG.debug("Executing query: {}", metricQuery); } executeGremlinQuery(metrics, metricQuery.group, metricQuery.name, metricQuery.query); } catch (AtlasBaseException e) { if (LOG.isDebugEnabled()) { LOG.debug("Gremlin execution failed for metric {}", metricQuery, e); } else { LOG.warn("Gremlin execution failed for metric {}", metricQuery); } } } long collectionTime = System.currentTimeMillis(); metrics.addData(GENERAL, METRIC_COLLECTION_TIME, collectionTime); this.cachedMetrics = metrics; this.cacheExpirationTime = (collectionTime + cacheTTLInSecs * 1000); } return cachedMetrics; } private void executeGremlinQuery(AtlasMetrics metrics, String type, String name, String query) throws AtlasBaseException { Object result = atlasGraph.executeGremlinScript(query, false); if (result instanceof Number) { metrics.addData(type, name, ((Number) result).intValue()); } else if (result instanceof List) { for (Map<String, Number> resultMap : (List<Map<String, Number>>) result) { for (Map.Entry<String, Number> entry : resultMap.entrySet()) { metrics.addData(type, entry.getKey(), entry.getValue().intValue()); } } } else { String returnClassName = result != null ? result.getClass().getSimpleName() : "null"; LOG.warn("Unhandled return type {} for {}. Ignoring", returnClassName, query); } } private boolean isCacheValid() { boolean valid = cachedMetrics != null && System.currentTimeMillis() < cacheExpirationTime; if (LOG.isDebugEnabled()) { LOG.debug("cachedMetrics: {}", cachedMetrics != null); LOG.debug("cacheExpirationTime: {}", cacheExpirationTime); LOG.debug("valid: {}", valid); } return valid; } private static String getQuery(String type, String name, String defaultQuery) { String ret = configuration != null ? configuration.getString(METRIC_QUERY_PREFIX + type + "." + name, defaultQuery) : defaultQuery; if (LOG.isDebugEnabled()) { LOG.debug("query for {}.{}: {}", type, name, ret); } return ret; } /** * MetricQuery enum has the capability of reading the queries from the externalized config. * * The default behavior is to read from the properties and override the statically type query if the configured * query is not blank/empty. */ private enum MetricQuery { TYPE_COUNT(GENERAL, METRIC_TYPE_COUNT, AtlasGremlinQuery.TYPE_COUNT_METRIC), UNUSED_TYPE_COUNT(GENERAL, METRIC_TYPE_UNUSED_COUNT, AtlasGremlinQuery.TYPE_UNUSED_COUNT_METRIC), ENTITY_COUNT(GENERAL, METRIC_ENTITY_COUNT, AtlasGremlinQuery.ENTITY_COUNT_METRIC), TAGS_COUNT(GENERAL, METRIC_TAG_COUNT, AtlasGremlinQuery.TAG_COUNT_METRIC), DELETED_ENTITY_COUNT(GENERAL, METRIC_ENTITY_DELETED, AtlasGremlinQuery.ENTITY_DELETED_METRIC), ENTITIES_PER_TYPE(ENTITY, METRIC_TYPE_ENTITIES, AtlasGremlinQuery.ENTITIES_PER_TYPE_METRIC), TAGGED_ENTITIES(ENTITY, METRIC_TAGGED_ENTITIES, AtlasGremlinQuery.TAGGED_ENTITIES_METRIC), ENTITIES_WITH_SPECIFIC_TAG(TAG, METRIC_ENTITIES_PER_TAG, AtlasGremlinQuery.ENTITIES_FOR_TAG_METRIC), ; private final String group; private final String name; private final String query; MetricQuery(String group, String name, AtlasGremlinQuery gremlinQuery) { this.group = group; this.name = name; this.query = MetricsService.getQuery(group, name, gremlinQueryProvider.getQuery(gremlinQuery)); } @Override public String toString() { return "MetricQuery{" + "group='" + group + '\'' + ", name='" + name + '\'' + ", query='" + query + '\'' + '}'; } } } <|start_filename|>intg/src/main/java/org/apache/atlas/model/instance/AtlasEntityHeader.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.model.instance; import java.io.Serializable; import java.util.List; import java.util.Map; import java.util.Objects; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSeeAlso; import org.apache.atlas.model.PList; import org.apache.atlas.model.SearchFilter.SortType; import org.apache.atlas.model.typedef.AtlasEntityDef; import org.codehaus.jackson.annotate.JsonAutoDetect; import static org.codehaus.jackson.annotate.JsonAutoDetect.Visibility.PUBLIC_ONLY; import static org.codehaus.jackson.annotate.JsonAutoDetect.Visibility.NONE; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.map.annotate.JsonSerialize; /** * An instance of an entity - like hive_table, hive_database. */ @JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) @JsonIgnoreProperties(ignoreUnknown=true) @XmlRootElement @XmlAccessorType(XmlAccessType.PROPERTY) public class AtlasEntityHeader extends AtlasStruct implements Serializable { private static final long serialVersionUID = 1L; private String guid = null; private AtlasEntity.Status status = AtlasEntity.Status.ACTIVE; private String displayText = null; private List<String> classificationNames = null; public AtlasEntityHeader() { this(null, null); } public AtlasEntityHeader(String typeName) { this(typeName, null); } public AtlasEntityHeader(AtlasEntityDef entityDef) { this(entityDef != null ? entityDef.getName() : null, null); } public AtlasEntityHeader(String typeName, Map<String, Object> attributes) { super(typeName, attributes); setClassificationNames(null); } public AtlasEntityHeader(String typeName, String guid, Map<String, Object> attributes) { super(typeName, attributes); setGuid(guid); setClassificationNames(null); } public AtlasEntityHeader(AtlasEntityHeader other) { super(other); if (other != null) { setGuid(other.getGuid()); setStatus(other.getStatus()); setDisplayText(other.getDisplayText()); setClassificationNames(other.getClassificationNames()); } } public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } public AtlasEntity.Status getStatus() { return status; } public void setStatus(AtlasEntity.Status status) { this.status = status; } public String getDisplayText() { return displayText; } public void setDisplayText(final String displayText) { this.displayText = displayText; } public List<String> getClassificationNames(){ return classificationNames; } public void setClassificationNames(List<String> classificationNames) { this.classificationNames = classificationNames; } @Override public StringBuilder toString(StringBuilder sb) { if (sb == null) { sb = new StringBuilder(); } sb.append("AtlasEntityHeader{"); sb.append("guid='").append(guid).append('\''); sb.append(", status=").append(status); sb.append(", displayText=").append(displayText); sb.append(", classificationNames=["); dumpObjects(classificationNames, sb); sb.append("],"); sb.append(", "); super.toString(sb); sb.append('}'); return sb; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; AtlasEntityHeader that = (AtlasEntityHeader) o; return Objects.equals(guid, that.guid) && status == that.status && Objects.equals(displayText, that.displayText) && Objects.equals(classificationNames, that.classificationNames); } @Override public int hashCode() { return Objects.hash(super.hashCode(), guid, status, displayText, classificationNames); } @Override public String toString() { return toString(new StringBuilder()).toString(); } /** * REST serialization friendly list. */ @JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) @JsonIgnoreProperties(ignoreUnknown=true) @XmlRootElement @XmlAccessorType(XmlAccessType.PROPERTY) @XmlSeeAlso(AtlasEntity.class) public static class AtlasEntityHeaders extends PList<AtlasEntityHeader> { private static final long serialVersionUID = 1L; public AtlasEntityHeaders() { super(); } public AtlasEntityHeaders(List<AtlasEntityHeader> list) { super(list); } public AtlasEntityHeaders(List list, long startIndex, int pageSize, long totalCount, SortType sortType, String sortBy) { super(list, startIndex, pageSize, totalCount, sortType, sortBy); } } } <|start_filename|>graphdb/titan1/src/main/java/org/apache/atlas/repository/graphdb/titan1/serializer/StringListSerializer.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan1.serializer; import java.util.ArrayList; import java.util.List; import com.thinkaurelius.titan.core.attribute.AttributeSerializer; import com.thinkaurelius.titan.diskstorage.ScanBuffer; import com.thinkaurelius.titan.diskstorage.WriteBuffer; import com.thinkaurelius.titan.graphdb.database.idhandling.VariableLong; import com.thinkaurelius.titan.graphdb.database.serialize.attribute.StringSerializer; /** * Serializer for String lists. */ public class StringListSerializer implements AttributeSerializer<List<String>> { private final StringSerializer stringSerializer = new StringSerializer(); @Override public List<String> read(ScanBuffer buffer) { int length = (int)VariableLong.readPositive(buffer); List<String> result = new ArrayList<String>(length); for(int i = 0; i < length; i++) { result.add(stringSerializer.read(buffer)); } return result; } @Override public void write(WriteBuffer buffer, List<String> attributes) { VariableLong.writePositive(buffer, attributes.size()); for(String attr : attributes) { stringSerializer.write(buffer, attr); } } } <|start_filename|>repository/src/test/java/org/apache/atlas/repository/store/graph/v1/InverseReferenceUpdateSoftDeleteV1Test.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.store.graph.v1; import com.google.common.collect.ImmutableList; import org.apache.atlas.TestModules; import org.apache.atlas.model.instance.AtlasEntity; import org.apache.atlas.model.instance.AtlasObjectId; import org.apache.atlas.type.AtlasTypeUtil; import org.testng.annotations.Guice; import java.util.Map; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; /** * Inverse reference update test with {@link SoftDeleteHandlerV1} */ @Guice(modules = TestModules.SoftDeleteModule.class) public class InverseReferenceUpdateSoftDeleteV1Test extends InverseReferenceUpdateV1Test { @Override protected void verify_testInverseReferenceAutoUpdate_NonComposite_OneToMany(AtlasEntity jane) throws Exception { // Max is still in the subordinates list, as the edge still exists with state DELETED verifyReferenceList(jane, "subordinates", ImmutableList.of(nameIdMap.get("John"), nameIdMap.get("Max"))); } @Override protected void verify_testInverseReferenceAutoUpdate_NonCompositeManyToOne(AtlasEntity a1, AtlasEntity a2, AtlasEntity a3, AtlasEntity b) { verifyReferenceValue(a1, "oneB", b.getGuid()); verifyReferenceValue(a2, "oneB", b.getGuid()); verifyReferenceList(b, "manyA", ImmutableList.of(AtlasTypeUtil.getAtlasObjectId(a1), AtlasTypeUtil.getAtlasObjectId(a2), AtlasTypeUtil.getAtlasObjectId(a3))); } @Override protected void verify_testInverseReferenceAutoUpdate_NonComposite_OneToOne(AtlasEntity a1, AtlasEntity b) { verifyReferenceValue(a1, "b", b.getGuid()); } @Override protected void verify_testInverseReferenceAutoUpdate_Map(AtlasEntity a1, AtlasEntity b1, AtlasEntity b2, AtlasEntity b3) { Object value = a1.getAttribute("mapToB"); assertTrue(value instanceof Map); Map<String, AtlasObjectId> refMap = (Map<String, AtlasObjectId>) value; assertEquals(refMap.size(), 3); AtlasObjectId referencedEntityId = refMap.get("b3"); assertEquals(referencedEntityId, AtlasTypeUtil.getAtlasObjectId(b3)); verifyReferenceValue(b1, "mappedFromA", a1.getGuid()); verifyReferenceValue(b2, "mappedFromA", a1.getGuid()); } } <|start_filename|>webapp/src/test/java/org/apache/atlas/web/resources/TaxonomyServiceTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.web.resources; import static org.easymock.EasyMock.capture; import static org.easymock.EasyMock.createNiceMock; import static org.easymock.EasyMock.createStrictMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.newCapture; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.ws.rs.core.PathSegment; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.apache.atlas.AtlasException; import org.apache.atlas.catalog.AtlasTypeSystem; import org.apache.atlas.catalog.JsonSerializer; import org.apache.atlas.catalog.Request; import org.apache.atlas.catalog.ResourceProvider; import org.apache.atlas.catalog.Result; import org.apache.atlas.catalog.TaxonomyResourceProvider; import org.apache.atlas.catalog.TermPath; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.services.MetadataService; import org.apache.atlas.store.AtlasTypeDefStore; import org.easymock.Capture; import org.testng.annotations.Test; /** * Unit tests for TaxonomyService. */ public class TaxonomyServiceTest { @Test public void testGetTaxonomy() throws Exception { String taxonomyName = "testTaxonomy"; MetadataService metadataService = createStrictMock(MetadataService.class); AtlasTypeDefStore typeDefStore = createStrictMock(AtlasTypeDefStore.class); ResourceProvider taxonomyResourceProvider = createStrictMock(ResourceProvider.class); ResourceProvider termResourceProvider = createStrictMock(ResourceProvider.class); UriInfo uriInfo = createNiceMock(UriInfo.class); JsonSerializer serializer = createStrictMock(JsonSerializer.class); Capture<Request> requestCapture = newCapture(); Collection<Map<String, Object>> resultPropertyMaps = new ArrayList<>(); Map<String, Object> propertyMap = new HashMap<>(); propertyMap.put("name", "testTaxonomy"); resultPropertyMaps.add(propertyMap); Result result = new Result(resultPropertyMaps); expect(taxonomyResourceProvider.getResourceById(capture(requestCapture))).andReturn(result); expect(metadataService.getTypeDefinition(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE)).andReturn(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE + "-definition"); expect(serializer.serialize(result, uriInfo)).andReturn("Taxonomy Get Response"); replay(uriInfo, metadataService, taxonomyResourceProvider, termResourceProvider, serializer); TestTaxonomyService service = new TestTaxonomyService( metadataService, typeDefStore, taxonomyResourceProvider, termResourceProvider, serializer); Response response = service.getTaxonomy(null, uriInfo, taxonomyName); Request request = requestCapture.getValue(); Map<String, Object> requestProperties = request.getQueryProperties(); assertEquals(requestProperties.size(), 1); assertEquals(requestProperties.get("name"), taxonomyName); assertEquals(response.getStatus(), 200); assertEquals(response.getEntity(), "Taxonomy Get Response"); verify(uriInfo, taxonomyResourceProvider, termResourceProvider, serializer); } @Test public void testGetTaxonomies() throws Exception { MetadataService metadataService = createStrictMock(MetadataService.class); AtlasTypeDefStore typeDefStore = createStrictMock(AtlasTypeDefStore.class); ResourceProvider taxonomyResourceProvider = createStrictMock(ResourceProvider.class); ResourceProvider termResourceProvider = createStrictMock(ResourceProvider.class); UriInfo uriInfo = createNiceMock(UriInfo.class); URI uri = new URI("http://localhost:21000/api/atlas/v1/taxonomies?name:testTaxonomy"); JsonSerializer serializer = createStrictMock(JsonSerializer.class); Capture<Request> requestCapture = newCapture(); Collection<Map<String, Object>> resultPropertyMaps = new ArrayList<>(); Map<String, Object> propertyMap = new HashMap<>(); propertyMap.put("name", "testTaxonomy"); resultPropertyMaps.add(propertyMap); Result result = new Result(resultPropertyMaps); // set mock expectations expect(uriInfo.getRequestUri()).andReturn(uri); expect(taxonomyResourceProvider.getResources(capture(requestCapture))).andReturn(result); expect(serializer.serialize(result, uriInfo)).andReturn("Taxonomy Get Response"); expect(metadataService.getTypeDefinition(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE)).andReturn(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE + "-definition"); replay(uriInfo, metadataService, taxonomyResourceProvider, termResourceProvider, serializer); // instantiate service and invoke method being tested TestTaxonomyService service = new TestTaxonomyService( metadataService, typeDefStore, taxonomyResourceProvider, termResourceProvider, serializer); Response response = service.getTaxonomies(null, uriInfo); Request request = requestCapture.getValue(); assertTrue(request.getQueryProperties().isEmpty()); assertEquals(request.getQueryString(), "name:testTaxonomy"); assertEquals(response.getStatus(), 200); assertEquals(response.getEntity(), "Taxonomy Get Response"); verify(uriInfo, taxonomyResourceProvider, termResourceProvider, serializer); } @Test public void testCreateTaxonomy() throws Exception { MetadataService metadataService = createStrictMock(MetadataService.class); AtlasTypeDefStore typeDefStore = createStrictMock(AtlasTypeDefStore.class); ResourceProvider taxonomyResourceProvider = createStrictMock(ResourceProvider.class); ResourceProvider termResourceProvider = createStrictMock(ResourceProvider.class); UriInfo uriInfo = createNiceMock(UriInfo.class); URI uri = new URI("http://localhost:21000/api/atlas/v1/taxonomies/testTaxonomy"); Capture<Request> requestCapture = newCapture(); String body = "{ \"description\" : \"test description\" } "; // set mock expectations expect(uriInfo.getRequestUri()).andReturn(uri); expect(metadataService.getTypeDefinition(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE)).andReturn(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE + "-definition"); taxonomyResourceProvider.createResource(capture(requestCapture)); replay(uriInfo, metadataService, taxonomyResourceProvider, termResourceProvider); // instantiate service and invoke method being tested TestTaxonomyService service = new TestTaxonomyService( metadataService, typeDefStore, taxonomyResourceProvider, termResourceProvider, null); Response response = service.createTaxonomy(body, null, uriInfo, "testTaxonomy"); Request request = requestCapture.getValue(); assertEquals(request.getQueryProperties().size(), 2); assertEquals(request.getQueryProperties().get("name"), "testTaxonomy"); assertEquals(request.getQueryProperties().get("description"), "test description"); assertNull(request.getQueryString()); assertEquals(response.getStatus(), 201); BaseService.Results createResults = (BaseService.Results) response.getEntity(); assertEquals(createResults.href, "http://localhost:21000/api/atlas/v1/taxonomies/testTaxonomy"); assertEquals(createResults.status, 201); verify(uriInfo, taxonomyResourceProvider, termResourceProvider); } @Test public void testDeleteTaxonomy() throws Exception { MetadataService metadataService = createStrictMock(MetadataService.class); AtlasTypeDefStore typeDefStore = createStrictMock(AtlasTypeDefStore.class); ResourceProvider taxonomyResourceProvider = createStrictMock(ResourceProvider.class); ResourceProvider termResourceProvider = createStrictMock(ResourceProvider.class); UriInfo uriInfo = createNiceMock(UriInfo.class); URI uri = new URI("http://localhost:21000/api/atlas/v1/taxonomies/testTaxonomy"); Capture<Request> requestCapture = newCapture(); // set mock expectations expect(uriInfo.getRequestUri()).andReturn(uri); taxonomyResourceProvider.deleteResourceById(capture(requestCapture)); expect(metadataService.getTypeDefinition(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE)).andReturn(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE + "-definition"); replay(uriInfo, metadataService, taxonomyResourceProvider, termResourceProvider); // instantiate service and invoke method being tested TestTaxonomyService service = new TestTaxonomyService( metadataService, typeDefStore, taxonomyResourceProvider, termResourceProvider, null); Response response = service.deleteTaxonomy(null, uriInfo, "testTaxonomy"); Request request = requestCapture.getValue(); assertEquals(request.getQueryProperties().size(), 1); assertEquals(request.getQueryProperties().get("name"), "testTaxonomy"); assertNull(request.getQueryString()); assertEquals(response.getStatus(), 200); BaseService.Results createResults = (BaseService.Results) response.getEntity(); assertEquals(createResults.href, "http://localhost:21000/api/atlas/v1/taxonomies/testTaxonomy"); assertEquals(createResults.status, 200); verify(uriInfo, taxonomyResourceProvider, termResourceProvider); } @Test public void testGetTaxonomyTerm() throws Exception { String taxonomyName = "testTaxonomy"; String termName = "testTaxonomy.termName"; MetadataService metadataService = createStrictMock(MetadataService.class); AtlasTypeDefStore typeDefStore = createStrictMock(AtlasTypeDefStore.class); ResourceProvider taxonomyResourceProvider = createStrictMock(ResourceProvider.class); ResourceProvider termResourceProvider = createStrictMock(ResourceProvider.class); UriInfo uriInfo = createNiceMock(UriInfo.class); JsonSerializer serializer = createStrictMock(JsonSerializer.class); Capture<Request> requestCapture = newCapture(); Collection<Map<String, Object>> resultPropertyMaps = new ArrayList<>(); Map<String, Object> propertyMap = new HashMap<>(); propertyMap.put("name", "testTaxonomy.termName"); resultPropertyMaps.add(propertyMap); Result result = new Result(resultPropertyMaps); expect(termResourceProvider.getResourceById(capture(requestCapture))).andReturn(result); expect(serializer.serialize(result, uriInfo)).andReturn("Taxonomy Term Get Response"); expect(metadataService.getTypeDefinition(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE)).andReturn(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE + "-definition"); replay(uriInfo, metadataService, taxonomyResourceProvider, termResourceProvider, serializer); TestTaxonomyService service = new TestTaxonomyService( metadataService, typeDefStore, taxonomyResourceProvider, termResourceProvider, serializer); Response response = service.getTaxonomyTerm(null, uriInfo, taxonomyName, termName); Request request = requestCapture.getValue(); Map<String, Object> requestProperties = request.getQueryProperties(); assertEquals(requestProperties.size(), 1); TermPath termPath = (TermPath) request.getQueryProperties().get("termPath"); assertEquals(termPath.getFullyQualifiedName(), "testTaxonomy.testTaxonomy.termName"); assertEquals(response.getStatus(), 200); assertEquals(response.getEntity(), "Taxonomy Term Get Response"); verify(uriInfo, taxonomyResourceProvider, termResourceProvider, serializer); } @Test public void testGetTaxonomyTerms() throws Exception { MetadataService metadataService = createStrictMock(MetadataService.class); AtlasTypeDefStore typeDefStore = createStrictMock(AtlasTypeDefStore.class); ResourceProvider taxonomyResourceProvider = createStrictMock(ResourceProvider.class); ResourceProvider termResourceProvider = createStrictMock(ResourceProvider.class); UriInfo uriInfo = createNiceMock(UriInfo.class); URI uri = new URI("http://localhost:21000/api/atlas/v1/taxonomies/testTaxonomy/terms?name:testTaxonomy.testTerm"); JsonSerializer serializer = createStrictMock(JsonSerializer.class); Capture<Request> requestCapture = newCapture(); Collection<Map<String, Object>> resultPropertyMaps = new ArrayList<>(); Map<String, Object> propertyMap = new HashMap<>(); propertyMap.put("name", "testTaxonomy.testTerm"); resultPropertyMaps.add(propertyMap); Result result = new Result(resultPropertyMaps); // set mock expectations expect(uriInfo.getRequestUri()).andReturn(uri); expect(termResourceProvider.getResources(capture(requestCapture))).andReturn(result); expect(serializer.serialize(result, uriInfo)).andReturn("Taxonomy Term Get Response"); expect(metadataService.getTypeDefinition(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE)).andReturn(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE + "-definition"); replay(uriInfo, metadataService, taxonomyResourceProvider, termResourceProvider, serializer); // instantiate service and invoke method being tested TestTaxonomyService service = new TestTaxonomyService( metadataService, typeDefStore, taxonomyResourceProvider, termResourceProvider, serializer); Response response = service.getTaxonomyTerms(null, uriInfo, "testTaxonomy"); Request request = requestCapture.getValue(); assertEquals(request.getQueryProperties().size(), 1); TermPath termPath = (TermPath) request.getQueryProperties().get("termPath"); assertEquals(termPath.getFullyQualifiedName(), "testTaxonomy"); assertEquals(request.getQueryString(), "name:testTaxonomy.testTerm"); assertEquals(response.getStatus(), 200); assertEquals(response.getEntity(), "Taxonomy Term Get Response"); verify(uriInfo, taxonomyResourceProvider, termResourceProvider, serializer); } @Test public void testGetSubTerms_instance() throws Exception { MetadataService metadataService = createStrictMock(MetadataService.class); AtlasTypeDefStore typeDefStore = createStrictMock(AtlasTypeDefStore.class); ResourceProvider taxonomyResourceProvider = createStrictMock(ResourceProvider.class); ResourceProvider termResourceProvider = createStrictMock(ResourceProvider.class); UriInfo uriInfo = createNiceMock(UriInfo.class); URI uri = new URI("http://localhost:21000/api/atlas/v1/taxonomies/testTaxonomy/terms/testTerm/terms/testTerm2"); JsonSerializer serializer = createStrictMock(JsonSerializer.class); PathSegment segment1 = createNiceMock(PathSegment.class); PathSegment segment2 = createNiceMock(PathSegment.class); PathSegment segment3 = createNiceMock(PathSegment.class); Capture<Request> requestCapture = newCapture(); Collection<Map<String, Object>> resultPropertyMaps = new ArrayList<>(); Map<String, Object> propertyMap = new HashMap<>(); propertyMap.put("name", "testTaxonomy.testTerm.testTerm2"); resultPropertyMaps.add(propertyMap); Result result = new Result(resultPropertyMaps); // set mock expectations expect(uriInfo.getRequestUri()).andReturn(uri); expect(uriInfo.getPathSegments()).andReturn(Arrays.asList(segment1, segment2, segment3)); expect(segment3.getPath()).andReturn("testTerm2"); expect(termResourceProvider.getResourceById(capture(requestCapture))).andReturn(result); expect(serializer.serialize(result, uriInfo)).andReturn("Taxonomy Term Get Response"); expect(metadataService.getTypeDefinition(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE)).andReturn(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE + "-definition"); replay(uriInfo, metadataService, taxonomyResourceProvider, termResourceProvider, serializer, segment1, segment2, segment3); // instantiate service and invoke method being tested TestTaxonomyService service = new TestTaxonomyService( metadataService, typeDefStore, taxonomyResourceProvider, termResourceProvider, serializer); Response response = service.getSubTerms(null, uriInfo, "testTaxonomy", "testTerm", "/terms/testTerm2"); Request request = requestCapture.getValue(); assertEquals(request.getQueryProperties().size(), 1); TermPath termPath = (TermPath) request.getQueryProperties().get("termPath"); assertEquals(termPath.getFullyQualifiedName(), "testTaxonomy.testTerm.testTerm2"); assertNull(request.getQueryString()); assertEquals(response.getStatus(), 200); assertEquals(response.getEntity(), "Taxonomy Term Get Response"); verify(uriInfo, taxonomyResourceProvider, termResourceProvider, serializer, segment1, segment2, segment3); } @Test public void testGetSubTerms_collection() throws Exception { MetadataService metadataService = createStrictMock(MetadataService.class); AtlasTypeDefStore typeDefStore = createStrictMock(AtlasTypeDefStore.class); ResourceProvider taxonomyResourceProvider = createStrictMock(ResourceProvider.class); ResourceProvider termResourceProvider = createStrictMock(ResourceProvider.class); UriInfo uriInfo = createNiceMock(UriInfo.class); URI uri = new URI("http://localhost:21000/api/atlas/v1/taxonomies/testTaxonomy/terms/testTerm/terms/testTerm2/terms?name:testTaxonomy.testTerm.testTerm2.testTerm3"); JsonSerializer serializer = createStrictMock(JsonSerializer.class); // would actually be more segments but at this time only the last segment is used PathSegment segment1 = createNiceMock(PathSegment.class); PathSegment segment2 = createNiceMock(PathSegment.class); PathSegment segment3 = createNiceMock(PathSegment.class); Capture<Request> requestCapture = newCapture(); Collection<Map<String, Object>> resultPropertyMaps = new ArrayList<>(); Map<String, Object> propertyMap = new HashMap<>(); propertyMap.put("name", "testTaxonomy.testTerm.testTerm2.testTerm3"); resultPropertyMaps.add(propertyMap); Result result = new Result(resultPropertyMaps); // set mock expectations expect(uriInfo.getRequestUri()).andReturn(uri); expect(uriInfo.getPathSegments()).andReturn(Arrays.asList(segment1, segment2, segment3)); expect(segment3.getPath()).andReturn("terms"); expect(termResourceProvider.getResources(capture(requestCapture))).andReturn(result); expect(serializer.serialize(result, uriInfo)).andReturn("Taxonomy Term Get Response"); expect(metadataService.getTypeDefinition(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE)).andReturn(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE + "-definition"); replay(uriInfo, metadataService, taxonomyResourceProvider, termResourceProvider, serializer, segment1, segment2, segment3); // instantiate service and invoke method being tested TestTaxonomyService service = new TestTaxonomyService( metadataService, typeDefStore, taxonomyResourceProvider, termResourceProvider, serializer); Response response = service.getSubTerms(null, uriInfo, "testTaxonomy", "testTerm", "/terms/testTerm2/terms"); Request request = requestCapture.getValue(); assertEquals(request.getQueryProperties().size(), 1); TermPath termPath = (TermPath) request.getQueryProperties().get("termPath"); assertEquals(termPath.getFullyQualifiedName(), "testTaxonomy.testTerm.testTerm2."); assertEquals(request.getQueryString(), "name:testTaxonomy.testTerm.testTerm2.testTerm3"); assertEquals(response.getStatus(), 200); assertEquals(response.getEntity(), "Taxonomy Term Get Response"); verify(uriInfo, taxonomyResourceProvider, termResourceProvider, serializer, segment1, segment2, segment3); } @Test public void testCreateTerm() throws Exception { String taxonomyName = "testTaxonomy"; String termName = "testTerm"; MetadataService metadataService = createStrictMock(MetadataService.class); AtlasTypeDefStore typeDefStore = createStrictMock(AtlasTypeDefStore.class); ResourceProvider taxonomyResourceProvider = createStrictMock(ResourceProvider.class); ResourceProvider termResourceProvider = createStrictMock(ResourceProvider.class); UriInfo uriInfo = createNiceMock(UriInfo.class); URI uri = new URI("http://localhost:21000/api/atlas/v1/taxonomies/testTaxonomy/terms/testTerm"); Capture<Request> requestCapture = newCapture(); String body = "{ \"description\" : \"test description\" } "; // set mock expectations expect(uriInfo.getRequestUri()).andReturn(uri); expect(metadataService.getTypeDefinition(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE)).andReturn(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE + "-definition"); termResourceProvider.createResource(capture(requestCapture)); replay(uriInfo, metadataService, taxonomyResourceProvider, termResourceProvider); // instantiate service and invoke method being tested TestTaxonomyService service = new TestTaxonomyService( metadataService, typeDefStore, taxonomyResourceProvider, termResourceProvider, null); Response response = service.createTerm(body, null, uriInfo, taxonomyName, termName); Request request = requestCapture.getValue(); assertEquals(request.getQueryProperties().size(), 2); assertEquals(request.getQueryProperties().get("description"), "test description"); TermPath termPath = (TermPath) request.getQueryProperties().get("termPath"); assertEquals(termPath.getFullyQualifiedName(), "testTaxonomy.testTerm"); assertNull(request.getQueryString()); assertEquals(response.getStatus(), 201); BaseService.Results createResults = (BaseService.Results) response.getEntity(); assertEquals(createResults.href, "http://localhost:21000/api/atlas/v1/taxonomies/testTaxonomy/terms/testTerm"); assertEquals(createResults.status, 201); verify(uriInfo, taxonomyResourceProvider, termResourceProvider); } @Test public void testCreateSubTerm() throws Exception { String taxonomyName = "testTaxonomy"; String termName = "testTerm"; MetadataService metadataService = createStrictMock(MetadataService.class); AtlasTypeDefStore typeDefStore = createStrictMock(AtlasTypeDefStore.class); ResourceProvider taxonomyResourceProvider = createStrictMock(ResourceProvider.class); ResourceProvider termResourceProvider = createStrictMock(ResourceProvider.class); UriInfo uriInfo = createNiceMock(UriInfo.class); URI uri = new URI("http://localhost:21000/api/atlas/v1/taxonomies/testTaxonomy/terms/testTerm/terms/testTerm2"); Capture<Request> requestCapture = newCapture(); String body = "{ \"description\" : \"test description\" } "; // set mock expectations expect(uriInfo.getRequestUri()).andReturn(uri); expect(metadataService.getTypeDefinition(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE)).andReturn(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE + "-definition"); termResourceProvider.createResource(capture(requestCapture)); replay(uriInfo, metadataService, taxonomyResourceProvider, termResourceProvider); // instantiate service and invoke method being tested TestTaxonomyService service = new TestTaxonomyService( metadataService, typeDefStore, taxonomyResourceProvider, termResourceProvider, null); Response response = service.createSubTerm(body, null, uriInfo, taxonomyName, termName, "/terms/testTerm2"); Request request = requestCapture.getValue(); assertEquals(request.getQueryProperties().size(), 2); assertEquals(request.getQueryProperties().get("description"), "test description"); TermPath termPath = (TermPath) request.getQueryProperties().get("termPath"); assertEquals(termPath.getFullyQualifiedName(), "testTaxonomy.testTerm.testTerm2"); assertNull(request.getQueryString()); assertEquals(response.getStatus(), 201); BaseService.Results createResults = (BaseService.Results) response.getEntity(); assertEquals(createResults.href, "http://localhost:21000/api/atlas/v1/taxonomies/testTaxonomy/terms/testTerm/terms/testTerm2"); assertEquals(createResults.status, 201); verify(uriInfo, taxonomyResourceProvider, termResourceProvider); } @Test public void testDeleteTerm() throws Exception { MetadataService metadataService = createStrictMock(MetadataService.class); AtlasTypeDefStore typeDefStore = createStrictMock(AtlasTypeDefStore.class); ResourceProvider taxonomyResourceProvider = createStrictMock(ResourceProvider.class); ResourceProvider termResourceProvider = createStrictMock(ResourceProvider.class); UriInfo uriInfo = createNiceMock(UriInfo.class); URI uri = new URI("http://localhost:21000/api/atlas/v1/taxonomies/testTaxonomy/terms/testTerm"); Capture<Request> requestCapture = newCapture(); // set mock expectations expect(uriInfo.getRequestUri()).andReturn(uri); termResourceProvider.deleteResourceById(capture(requestCapture)); expect(metadataService.getTypeDefinition(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE)).andReturn(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE + "-definition"); replay(uriInfo, metadataService, taxonomyResourceProvider, termResourceProvider); // instantiate service and invoke method being tested TestTaxonomyService service = new TestTaxonomyService( metadataService, typeDefStore, taxonomyResourceProvider, termResourceProvider, null); Response response = service.deleteTerm(null, uriInfo, "testTaxonomy", "testTerm"); Request request = requestCapture.getValue(); assertEquals(request.getQueryProperties().size(), 1); TermPath termPath = (TermPath) request.getQueryProperties().get("termPath"); assertEquals(termPath.getFullyQualifiedName(), "testTaxonomy.testTerm"); assertNull(request.getQueryString()); assertEquals(response.getStatus(), 200); BaseService.Results createResults = (BaseService.Results) response.getEntity(); assertEquals(createResults.href, "http://localhost:21000/api/atlas/v1/taxonomies/testTaxonomy/terms/testTerm"); assertEquals(createResults.status, 200); verify(uriInfo, taxonomyResourceProvider, termResourceProvider); } @Test public void testDeleteSubTerm() throws Exception { MetadataService metadataService = createStrictMock(MetadataService.class); AtlasTypeDefStore typeDefStore = createStrictMock(AtlasTypeDefStore.class); ResourceProvider taxonomyResourceProvider = createStrictMock(ResourceProvider.class); ResourceProvider termResourceProvider = createStrictMock(ResourceProvider.class); UriInfo uriInfo = createNiceMock(UriInfo.class); URI uri = new URI("http://localhost:21000/api/atlas/v1/taxonomies/testTaxonomy/terms/testTerm/terms/testTerm2"); Capture<Request> requestCapture = newCapture(); // set mock expectations expect(uriInfo.getRequestUri()).andReturn(uri); termResourceProvider.deleteResourceById(capture(requestCapture)); expect(metadataService.getTypeDefinition(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE)).andReturn(TaxonomyResourceProvider.TAXONOMY_TERM_TYPE + "-definition"); replay(uriInfo, metadataService, taxonomyResourceProvider, termResourceProvider); // instantiate service and invoke method being tested TestTaxonomyService service = new TestTaxonomyService( metadataService, typeDefStore, taxonomyResourceProvider, termResourceProvider, null); Response response = service.deleteSubTerm(null, uriInfo, "testTaxonomy", "testTerm", "terms/testTerm2"); Request request = requestCapture.getValue(); assertEquals(request.getQueryProperties().size(), 1); TermPath termPath = (TermPath) request.getQueryProperties().get("termPath"); assertEquals(termPath.getFullyQualifiedName(), "testTaxonomy.testTerm.testTerm2"); assertNull(request.getQueryString()); assertEquals(response.getStatus(), 200); BaseService.Results createResults = (BaseService.Results) response.getEntity(); assertEquals(createResults.href, "http://localhost:21000/api/atlas/v1/taxonomies/testTaxonomy/terms/testTerm/terms/testTerm2"); assertEquals(createResults.status, 200); verify(uriInfo, taxonomyResourceProvider, termResourceProvider); } private static class TestTaxonomyService extends TaxonomyService { private final ResourceProvider testTaxonomyResourceProvider; private final ResourceProvider testTermResourceProvider; private final JsonSerializer testSerializer; private boolean transactionInitialized = false; public TestTaxonomyService(MetadataService metadataService, AtlasTypeDefStore typeDefStore, ResourceProvider taxonomyProvider, ResourceProvider termResourceProvider, JsonSerializer serializer) throws AtlasBaseException { testTaxonomyResourceProvider = taxonomyProvider; testTermResourceProvider = termResourceProvider; testSerializer = serializer; setMetadataService(metadataService, typeDefStore); } @Override protected ResourceProvider createTaxonomyResourceProvider(AtlasTypeSystem typeSystem) { return testTaxonomyResourceProvider; } @Override protected ResourceProvider createTermResourceProvider(AtlasTypeSystem typeSystem) { return testTermResourceProvider; } @Override protected JsonSerializer getSerializer() { return testSerializer; } } } <|start_filename|>repository/src/test/java/org/apache/atlas/repository/audit/AuditRepositoryTestBase.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.audit; import org.apache.atlas.EntityAuditEvent; import org.apache.atlas.TestUtils; import org.apache.atlas.typesystem.Referenceable; import org.apache.commons.lang.RandomStringUtils; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; public class AuditRepositoryTestBase { protected EntityAuditRepository eventRepository; private String rand() { return RandomStringUtils.randomAlphanumeric(10); } @BeforeTest public void setUp() throws Exception{ eventRepository = new InMemoryEntityAuditRepository(); } @Test public void testAddEvents() throws Exception { TestUtils.skipForGremlin3EnabledGraphDb(); EntityAuditEvent event = new EntityAuditEvent(rand(), System.currentTimeMillis(), "u1", EntityAuditEvent.EntityAuditAction.ENTITY_CREATE, "d1", new Referenceable(rand())); eventRepository.putEvents(event); List<EntityAuditEvent> events = eventRepository.listEvents(event.getEntityId(), null, (short) 10); assertEquals(events.size(), 1); assertEventEquals(events.get(0), event); } @Test public void testListPagination() throws Exception { TestUtils.skipForGremlin3EnabledGraphDb(); String id1 = "id1" + rand(); String id2 = "id2" + rand(); String id3 = "id3" + rand(); long ts = System.currentTimeMillis(); Referenceable entity = new Referenceable(rand()); List<EntityAuditEvent> expectedEvents = new ArrayList<>(3); for (int i = 0; i < 3; i++) { //Add events for both ids EntityAuditEvent event = new EntityAuditEvent(id2, ts - i, "user" + i, EntityAuditEvent.EntityAuditAction.ENTITY_UPDATE, "details" + i, entity); eventRepository.putEvents(event); expectedEvents.add(event); eventRepository.putEvents(new EntityAuditEvent(id1, ts - i, "user" + i, EntityAuditEvent.EntityAuditAction.TAG_DELETE, "details" + i, entity)); eventRepository.putEvents(new EntityAuditEvent(id3, ts - i, "user" + i, EntityAuditEvent.EntityAuditAction.TAG_ADD, "details" + i, entity)); } //Use ts for which there is no event - ts + 2 List<EntityAuditEvent> events = eventRepository.listEvents(id2, null, (short) 3); assertEquals(events.size(), 3); assertEventEquals(events.get(0), expectedEvents.get(0)); assertEventEquals(events.get(1), expectedEvents.get(1)); assertEventEquals(events.get(2), expectedEvents.get(2)); //Use last event's timestamp for next list(). Should give only 1 event and shouldn't include events from other id events = eventRepository.listEvents(id2, events.get(2).getEventKey(), (short) 3); assertEquals(events.size(), 1); assertEventEquals(events.get(0), expectedEvents.get(2)); } @Test public void testInvalidEntityId() throws Exception { TestUtils.skipForGremlin3EnabledGraphDb(); List<EntityAuditEvent> events = eventRepository.listEvents(rand(), null, (short) 3); assertEquals(events.size(), 0); } protected void assertEventEquals(EntityAuditEvent actual, EntityAuditEvent expected) { if (expected != null) { assertNotNull(actual); } assertEquals(actual.getEntityId(), expected.getEntityId()); assertEquals(actual.getAction(), expected.getAction()); assertEquals(actual.getTimestamp(), expected.getTimestamp()); assertEquals(actual.getDetails(), expected.getDetails()); } } <|start_filename|>repository/src/test/java/org/apache/atlas/repository/graph/GraphHelperTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graph; import org.apache.atlas.AtlasException; import org.apache.atlas.TestModules; import org.apache.atlas.TestUtils; import org.apache.atlas.repository.graph.GraphHelper.VertexInfo; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.services.MetadataService; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.TypesDef; import org.apache.atlas.typesystem.exception.TypeNotFoundException; import org.apache.atlas.typesystem.json.InstanceSerialization; import org.apache.atlas.typesystem.json.TypesSerialization; import org.apache.atlas.typesystem.types.ClassType; import org.apache.atlas.typesystem.types.Multiplicity; import org.apache.atlas.typesystem.types.TypeSystem; import org.codehaus.jettison.json.JSONArray; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Guice; import org.testng.annotations.Test; import javax.inject.Inject; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import static org.testng.Assert.*; @Guice(modules = TestModules.TestOnlyModule.class) public class GraphHelperTest { @DataProvider(name = "encodeDecodeTestData") private Object[][] createTestData() { return new Object[][]{ {"hivedb$", "hivedb_d"}, {"hivedb", "hivedb"}, {"{hivedb}", "_ohivedb_c"}, {"%hivedb}", "_phivedb_c"}, {"\"hivedb\"", "_qhivedb_q"}, {"\"$%{}", "_q_d_p_o_c"}, {"", ""}, {" ", " "}, {"\n\r", "\n\r"}, {null, null} }; } @Inject private MetadataService metadataService; @Inject private GraphBackedMetadataRepository repositoryService; private TypeSystem typeSystem; @Inject private AtlasTypeRegistry typeRegistry; @BeforeClass public void setUp() throws Exception { typeSystem = TypeSystem.getInstance(); typeSystem.reset(); new GraphBackedSearchIndexer(typeRegistry); TypesDef typesDef = TestUtils.defineHiveTypes(); try { metadataService.getTypeDefinition(TestUtils.TABLE_TYPE); } catch (TypeNotFoundException e) { metadataService.createType(TypesSerialization.toJson(typesDef)); } TestUtils.defineDeptEmployeeTypes(typeSystem); } @AfterClass public void tearDown() { // AtlasGraphProvider.cleanup(); } @Test public void testGetInstancesByUniqueAttributes() throws Exception { GraphHelper helper = GraphHelper.getInstance(); List<ITypedReferenceableInstance> instances = new ArrayList<>(); List<String> guids = new ArrayList<>(); TypeSystem ts = TypeSystem.getInstance(); ClassType dbType = ts.getDataType(ClassType.class, TestUtils.DATABASE_TYPE); for(int i = 0; i < 10; i++) { Referenceable db = TestUtils.createDBEntity(); String guid = createInstance(db); ITypedReferenceableInstance instance = convert(db, dbType); instances.add(instance); guids.add(guid); } //lookup vertices via getVertexForInstanceByUniqueAttributes List<AtlasVertex> vertices = helper.getVerticesForInstancesByUniqueAttribute(dbType, instances); assertEquals(instances.size(), vertices.size()); //assert vertex matches the vertex we get through getVertexForGUID for(int i = 0; i < instances.size(); i++) { String guid = guids.get(i); AtlasVertex foundVertex = vertices.get(i); AtlasVertex expectedVertex = helper.getVertexForGUID(guid); assertEquals(foundVertex, expectedVertex); } } @Test public void testGetVerticesForGUIDSWithDuplicates() throws Exception { ITypedReferenceableInstance hrDept = TestUtils.createDeptEg1(TypeSystem.getInstance()); List<String> result = repositoryService.createEntities(hrDept).getCreatedEntities(); String guid = result.get(0); Map<String, AtlasVertex> verticesForGUIDs = GraphHelper.getInstance().getVerticesForGUIDs(Arrays.asList(guid, guid)); Assert.assertEquals(verticesForGUIDs.size(), 1); Assert.assertTrue(verticesForGUIDs.containsKey(guid)); } @Test public void testGetCompositeGuidsAndVertices() throws Exception { ITypedReferenceableInstance hrDept = TestUtils.createDeptEg1(typeSystem); List<String> createdGuids = repositoryService.createEntities(hrDept).getCreatedEntities(); String deptGuid = null; Set<String> expectedGuids = new HashSet<>(); for (String guid : createdGuids) { ITypedReferenceableInstance entityDefinition = repositoryService.getEntityDefinition(guid); expectedGuids.add(guid); if (entityDefinition.getId().getTypeName().equals(TestUtils.DEPARTMENT_TYPE)) { deptGuid = guid; } } AtlasVertex deptVertex = GraphHelper.getInstance().getVertexForGUID(deptGuid); Set<VertexInfo> compositeVertices = GraphHelper.getInstance().getCompositeVertices(deptVertex); HashMap<String, VertexInfo> verticesByGuid = new HashMap<>(); for (VertexInfo vertexInfo: compositeVertices) { verticesByGuid.put(vertexInfo.getGuid(), vertexInfo); } // Verify compositeVertices has entries for all expected guids. Assert.assertEquals(compositeVertices.size(), expectedGuids.size()); for (String expectedGuid : expectedGuids) { Assert.assertTrue(verticesByGuid.containsKey(expectedGuid)); } } @Test(dataProvider = "encodeDecodeTestData") public void testEncodeDecode(String str, String expectedEncodedStr) throws Exception { String encodedStr = GraphHelper.encodePropertyKey(str); assertEquals(encodedStr, expectedEncodedStr); String decodedStr = GraphHelper.decodePropertyKey(encodedStr); assertEquals(decodedStr, str); } @Test public void testGetOutgoingEdgesByLabel() throws Exception { AtlasGraph graph = TestUtils.getGraph(); AtlasVertex v1 = graph.addVertex(); AtlasVertex v2 = graph.addVertex(); graph.addEdge(v1, v2, "l1"); graph.addEdge(v1, v2, "l2"); Iterator<AtlasEdge> iterator = GraphHelper.getInstance().getOutGoingEdgesByLabel(v1, "l1"); assertTrue(iterator.hasNext()); assertTrue(iterator.hasNext()); assertNotNull(iterator.next()); assertNull(iterator.next()); assertFalse(iterator.hasNext()); assertFalse(iterator.hasNext()); } private ITypedReferenceableInstance convert(Referenceable instance, ClassType type) throws AtlasException { return type.convert(instance, Multiplicity.REQUIRED); } private String createInstance(Referenceable entity) throws Exception { TestUtils.resetRequestContext(); String entityjson = InstanceSerialization.toJson(entity, true); JSONArray entitiesJson = new JSONArray(); entitiesJson.put(entityjson); List<String> guids = metadataService.createEntities(entitiesJson.toString()).getCreatedEntities(); if (guids != null && guids.size() > 0) { return guids.get(guids.size() - 1); } return null; } } <|start_filename|>repository/src/main/java/org/apache/atlas/discovery/ClassificationSearchProcessor.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.discovery; import org.apache.atlas.model.discovery.SearchParameters.FilterCriteria; import org.apache.atlas.model.instance.AtlasEntity; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.graphdb.*; import org.apache.atlas.repository.store.graph.v1.AtlasGraphUtilsV1; import org.apache.atlas.type.AtlasClassificationType; import org.apache.atlas.utils.AtlasPerfTracer; import org.apache.commons.collections.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; public class ClassificationSearchProcessor extends SearchProcessor { private static final Logger LOG = LoggerFactory.getLogger(ClassificationSearchProcessor.class); private static final Logger PERF_LOG = AtlasPerfTracer.getPerfLogger("ClassificationSearchProcessor"); private final AtlasIndexQuery indexQuery; private final AtlasGraphQuery allGraphQuery; private final AtlasGraphQuery filterGraphQuery; public ClassificationSearchProcessor(SearchContext context) { super(context); final AtlasClassificationType classificationType = context.getClassificationType(); final FilterCriteria filterCriteria = context.getSearchParameters().getTagFilters(); final Set<String> typeAndSubTypes = classificationType.getTypeAndAllSubTypes(); final String typeAndSubTypesQryStr = classificationType.getTypeAndAllSubTypesQryStr(); final Set<String> solrAttributes = new HashSet<>(); final Set<String> gremlinAttributes = new HashSet<>(); final Set<String> allAttributes = new HashSet<>(); processSearchAttributes(classificationType, filterCriteria, solrAttributes, gremlinAttributes, allAttributes); // for classification search, if any attribute can't be handled by Solr - switch to all Gremlin boolean useSolrSearch = typeAndSubTypesQryStr.length() <= MAX_QUERY_STR_LENGTH_TAGS && CollectionUtils.isEmpty(gremlinAttributes) && canApplySolrFilter(classificationType, filterCriteria, false); if (useSolrSearch) { StringBuilder solrQuery = new StringBuilder(); constructTypeTestQuery(solrQuery, typeAndSubTypesQryStr); constructFilterQuery(solrQuery, classificationType, filterCriteria, solrAttributes); String solrQueryString = STRAY_AND_PATTERN.matcher(solrQuery).replaceAll(")"); solrQueryString = STRAY_OR_PATTERN.matcher(solrQueryString).replaceAll(")"); solrQueryString = STRAY_ELIPSIS_PATTERN.matcher(solrQueryString).replaceAll(""); indexQuery = context.getGraph().indexQuery(Constants.VERTEX_INDEX, solrQueryString); } else { indexQuery = null; } AtlasGraphQuery query = context.getGraph().query().in(Constants.TYPE_NAME_PROPERTY_KEY, typeAndSubTypes); allGraphQuery = toGremlinFilterQuery(classificationType, filterCriteria, allAttributes, query); query = context.getGraph().query().in(Constants.TRAIT_NAMES_PROPERTY_KEY, typeAndSubTypes); filterGraphQuery = query; // TODO: filer based on tag attributes } @Override public List<AtlasVertex> execute() { if (LOG.isDebugEnabled()) { LOG.debug("==> ClassificationSearchProcessor.execute({})", context); } List<AtlasVertex> ret = new ArrayList<>(); AtlasPerfTracer perf = null; if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "ClassificationSearchProcessor.execute(" + context + ")"); } try { final int startIdx = context.getSearchParameters().getOffset(); final int limit = context.getSearchParameters().getLimit(); final boolean activeOnly = context.getSearchParameters().getExcludeDeletedEntities(); // query to start at 0, even though startIdx can be higher - because few results in earlier retrieval could // have been dropped: like non-active-entities or duplicate-entities (same entity pointed to by multiple // classifications in the result) // // first 'startIdx' number of entries will be ignored int qryOffset = 0; int resultIdx = qryOffset; final Set<String> processedGuids = new HashSet<>(); final List<AtlasVertex> entityVertices = new ArrayList<>(); final List<AtlasVertex> classificationVertices = new ArrayList<>(); for (; ret.size() < limit; qryOffset += limit) { entityVertices.clear(); classificationVertices.clear(); if (context.terminateSearch()) { LOG.warn("query terminated: {}", context.getSearchParameters()); break; } if (indexQuery != null) { Iterator<AtlasIndexQuery.Result> queryResult = indexQuery.vertices(qryOffset, limit); if (!queryResult.hasNext()) { // no more results from solr - end of search break; } getVerticesFromIndexQueryResult(queryResult, classificationVertices); } else { Iterator<AtlasVertex> queryResult = allGraphQuery.vertices(qryOffset, limit).iterator(); if (!queryResult.hasNext()) { // no more results - end of search break; } getVertices(queryResult, classificationVertices); } for (AtlasVertex classificationVertex : classificationVertices) { Iterable<AtlasEdge> edges = classificationVertex.getEdges(AtlasEdgeDirection.IN); for (AtlasEdge edge : edges) { AtlasVertex entityVertex = edge.getOutVertex(); if (activeOnly && AtlasGraphUtilsV1.getState(entityVertex) != AtlasEntity.Status.ACTIVE) { continue; } String guid = AtlasGraphUtilsV1.getIdFromVertex(entityVertex); if (processedGuids.contains(guid)) { continue; } entityVertices.add(entityVertex); processedGuids.add(guid); } } super.filter(entityVertices); for (AtlasVertex entityVertex : entityVertices) { resultIdx++; if (resultIdx <= startIdx) { continue; } ret.add(entityVertex); if (ret.size() == limit) { break; } } } } finally { AtlasPerfTracer.log(perf); } if (LOG.isDebugEnabled()) { LOG.debug("<== ClassificationSearchProcessor.execute({}): ret.size()={}", context, ret.size()); } return ret; } @Override public void filter(List<AtlasVertex> entityVertices) { if (LOG.isDebugEnabled()) { LOG.debug("==> ClassificationSearchProcessor.filter({})", entityVertices.size()); } AtlasGraphQuery query = context.getGraph().query().in(Constants.GUID_PROPERTY_KEY, getGuids(entityVertices)); query.addConditionsFrom(filterGraphQuery); entityVertices.clear(); getVertices(query.vertices().iterator(), entityVertices); super.filter(entityVertices); if (LOG.isDebugEnabled()) { LOG.debug("<== ClassificationSearchProcessor.filter(): ret.size()={}", entityVertices.size()); } } } <|start_filename|>repository/src/test/java/org/apache/atlas/repository/graph/ReverseReferenceUpdateHardDeleteTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graph; import org.apache.atlas.TestModules; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.testng.Assert; import org.testng.annotations.Guice; import java.util.List; /** * Run tests in {@link ReverseReferenceUpdateTestBase} with hard delete enabled. * */ @Guice(modules = TestModules.HardDeleteModule.class) public class ReverseReferenceUpdateHardDeleteTest extends ReverseReferenceUpdateTestBase { @Override void assertTestOneToOneReference(Object refValue, ITypedReferenceableInstance expectedValue, ITypedReferenceableInstance referencingInstance) throws Exception { // Verify reference was disconnected Assert.assertNull(refValue); } @Override void assertTestOneToManyReference(Object object, ITypedReferenceableInstance referencingInstance) { Assert.assertTrue(object instanceof List); List<ITypedReferenceableInstance> refValues = (List<ITypedReferenceableInstance>) object; Assert.assertEquals(refValues.size(), 1); } } <|start_filename|>webapp/src/main/java/org/apache/atlas/web/security/AtlasSecurityConfig.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.web.security; import org.apache.atlas.web.filters.ActiveServerFilter; import org.apache.atlas.web.filters.AtlasAuthenticationEntryPoint; import org.apache.atlas.web.filters.AtlasAuthenticationFilter; import org.apache.atlas.web.filters.AtlasAuthorizationFilter; import org.apache.atlas.web.filters.AtlasCSRFPreventionFilter; import org.apache.atlas.web.filters.AtlasKnoxSSOAuthenticationFilter; import org.apache.atlas.web.filters.StaleTransactionCleanupFilter; import org.apache.commons.configuration.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.access.intercept.FilterSecurityInterceptor; import org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint; import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter; import org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import javax.inject.Inject; import java.util.LinkedHashMap; @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class AtlasSecurityConfig extends WebSecurityConfigurerAdapter { private static final Logger LOG = LoggerFactory.getLogger(AtlasSecurityConfig.class); private final AtlasAuthenticationProvider authenticationProvider; private final AtlasAuthenticationSuccessHandler successHandler; private final AtlasAuthenticationFailureHandler failureHandler; private final AtlasAuthorizationFilter atlasAuthorizationFilter; private final AtlasKnoxSSOAuthenticationFilter ssoAuthenticationFilter; private final AtlasAuthenticationFilter atlasAuthenticationFilter; private final AtlasCSRFPreventionFilter csrfPreventionFilter; private final AtlasAuthenticationEntryPoint atlasAuthenticationEntryPoint; // Our own Atlas filters need to be registered as well private final Configuration configuration; private final StaleTransactionCleanupFilter staleTransactionCleanupFilter; private final ActiveServerFilter activeServerFilter; @Inject public AtlasSecurityConfig(AtlasKnoxSSOAuthenticationFilter ssoAuthenticationFilter, AtlasCSRFPreventionFilter atlasCSRFPreventionFilter, AtlasAuthenticationFilter atlasAuthenticationFilter, AtlasAuthenticationProvider authenticationProvider, AtlasAuthenticationSuccessHandler successHandler, AtlasAuthenticationFailureHandler failureHandler, AtlasAuthorizationFilter atlasAuthorizationFilter, AtlasAuthenticationEntryPoint atlasAuthenticationEntryPoint, Configuration configuration, StaleTransactionCleanupFilter staleTransactionCleanupFilter, ActiveServerFilter activeServerFilter) { this.ssoAuthenticationFilter = ssoAuthenticationFilter; this.csrfPreventionFilter = atlasCSRFPreventionFilter; this.atlasAuthenticationFilter = atlasAuthenticationFilter; this.authenticationProvider = authenticationProvider; this.successHandler = successHandler; this.failureHandler = failureHandler; this.atlasAuthorizationFilter = atlasAuthorizationFilter; this.atlasAuthenticationEntryPoint = atlasAuthenticationEntryPoint; this.configuration = configuration; this.staleTransactionCleanupFilter = staleTransactionCleanupFilter; this.activeServerFilter = activeServerFilter; } public BasicAuthenticationEntryPoint getAuthenticationEntryPoint() { BasicAuthenticationEntryPoint basicAuthenticationEntryPoint = new BasicAuthenticationEntryPoint(); basicAuthenticationEntryPoint.setRealmName("atlas.com"); return basicAuthenticationEntryPoint; } public DelegatingAuthenticationEntryPoint getDelegatingAuthenticationEntryPoint() { LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPointMap = new LinkedHashMap<>(); entryPointMap.put(new RequestHeaderRequestMatcher("User-Agent", "Mozilla"), atlasAuthenticationEntryPoint); DelegatingAuthenticationEntryPoint entryPoint = new DelegatingAuthenticationEntryPoint(entryPointMap); entryPoint.setDefaultEntryPoint(getAuthenticationEntryPoint()); return entryPoint; } @Inject protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) { authenticationManagerBuilder.authenticationProvider(authenticationProvider); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring() .antMatchers("/login.jsp", "/css/**", "/img/**", "/libs/**", "/js/**", "/ieerror.html", "/api/atlas/admin/status", "/api/atlas/admin/metrics"); } protected void configure(HttpSecurity httpSecurity) throws Exception { //@formatter:off httpSecurity .authorizeRequests().anyRequest().authenticated() .and() .headers().disable() .servletApi() .and() .csrf().disable() .sessionManagement() .enableSessionUrlRewriting(false) .sessionCreationPolicy(SessionCreationPolicy.ALWAYS) .sessionFixation() .newSession() .and() .formLogin() .loginPage("/login.jsp") .loginProcessingUrl("/j_spring_security_check") .successHandler(successHandler) .failureHandler(failureHandler) .usernameParameter("j_username") .passwordParameter("<PASSWORD>") .and() .logout() .logoutSuccessUrl("/login.jsp") .deleteCookies("ATLASSESSIONID") .logoutUrl("/logout.html") .and() .httpBasic() .authenticationEntryPoint(getDelegatingAuthenticationEntryPoint()); //@formatter:on if (configuration.getBoolean("atlas.server.ha.enabled", false)) { LOG.info("Atlas is in HA Mode, enabling ActiveServerFilter"); httpSecurity.addFilterAfter(activeServerFilter, BasicAuthenticationFilter.class); } httpSecurity .addFilterAfter(staleTransactionCleanupFilter, BasicAuthenticationFilter.class) .addFilterAfter(ssoAuthenticationFilter, BasicAuthenticationFilter.class) .addFilterAfter(atlasAuthenticationFilter, SecurityContextHolderAwareRequestFilter.class) .addFilterAfter(csrfPreventionFilter, AtlasAuthenticationFilter.class) .addFilterAfter(atlasAuthorizationFilter, FilterSecurityInterceptor.class); } } <|start_filename|>addons/sqoop-bridge/src/test/java/org/apache/atlas/sqoop/hook/SqoopHookIT.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.sqoop.hook; import org.apache.atlas.ApplicationProperties; import org.apache.atlas.AtlasClient; import org.apache.atlas.hive.bridge.HiveMetaStoreBridge; import org.apache.atlas.hive.model.HiveDataTypes; import org.apache.atlas.sqoop.model.SqoopDataTypes; import org.apache.atlas.utils.AuthenticationUtil; import org.apache.commons.configuration.Configuration; import org.apache.sqoop.SqoopJobDataPublisher; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONObject; import org.slf4j.Logger; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.Properties; public class SqoopHookIT { public static final Logger LOG = org.slf4j.LoggerFactory.getLogger(SqoopHookIT.class); private static final String CLUSTER_NAME = "primary"; public static final String DEFAULT_DB = "default"; private static final int MAX_WAIT_TIME = 2000; private AtlasClient atlasClient; @BeforeClass public void setUp() throws Exception { //Set-up sqoop session Configuration configuration = ApplicationProperties.get(); if (!AuthenticationUtil.isKerberosAuthenticationEnabled()) { atlasClient = new AtlasClient(configuration.getStringArray(HiveMetaStoreBridge.ATLAS_ENDPOINT), new String[]{"admin", "admin"}); } else { atlasClient = new AtlasClient(configuration.getStringArray(HiveMetaStoreBridge.ATLAS_ENDPOINT)); } } @Test public void testSqoopImport() throws Exception { SqoopJobDataPublisher.Data d = new SqoopJobDataPublisher.Data("import", "jdbc:mysql:///localhost/db", "mysqluser", "mysql", "myTable", null, "default", "hiveTable", new Properties(), System.currentTimeMillis() - 100, System.currentTimeMillis()); SqoopHook hook = new SqoopHook(); hook.publish(d); Thread.sleep(1000); String storeName = SqoopHook.getSqoopDBStoreName(d); assertDBStoreIsRegistered(storeName); String name = SqoopHook.getSqoopProcessName(d, CLUSTER_NAME); assertSqoopProcessIsRegistered(name); assertHiveTableIsRegistered(DEFAULT_DB, "hiveTable"); } @Test public void testSqoopExport() throws Exception { SqoopJobDataPublisher.Data d = new SqoopJobDataPublisher.Data("export", "jdbc:mysql:///localhost/db", "mysqluser", "mysql", "myTable", null, "default", "hiveTable", new Properties(), System.currentTimeMillis() - 100, System.currentTimeMillis()); SqoopHook hook = new SqoopHook(); hook.publish(d); Thread.sleep(1000); String storeName = SqoopHook.getSqoopDBStoreName(d); assertDBStoreIsRegistered(storeName); String name = SqoopHook.getSqoopProcessName(d, CLUSTER_NAME); assertSqoopProcessIsRegistered(name); assertHiveTableIsRegistered(DEFAULT_DB, "hiveTable"); } private String assertDBStoreIsRegistered(String storeName) throws Exception { LOG.debug("Searching for db store {}", storeName); String query = String.format( "%s as t where " + AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME + " = '%s'" + " select t", SqoopDataTypes.SQOOP_DBDATASTORE.getName(), storeName); return assertEntityIsRegistered(query); } private String assertHiveTableIsRegistered(String dbName, String tableName) throws Exception { LOG.debug("Searching for table {}.{}", dbName, tableName); String query = String.format( "%s as t where " + AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME + " = '%s', db where " + AtlasClient.NAME + " = '%s' and clusterName = '%s'" + " select t", HiveDataTypes.HIVE_TABLE.getName(), HiveMetaStoreBridge.getTableQualifiedName(CLUSTER_NAME, dbName, tableName), dbName.toLowerCase(), CLUSTER_NAME); return assertEntityIsRegistered(query); } private String assertSqoopProcessIsRegistered(String processName) throws Exception { LOG.debug("Searching for sqoop process {}", processName); String query = String.format( "%s as t where %s = '%s' select t", SqoopDataTypes.SQOOP_PROCESS.getName(), AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, processName); return assertEntityIsRegistered(query); } private String assertEntityIsRegistered(final String query) throws Exception { waitFor(MAX_WAIT_TIME, new Predicate() { @Override public boolean evaluate() throws Exception { JSONArray results = atlasClient.search(query, 10, 0); return results.length() > 0; } }); JSONArray results = atlasClient.search(query, 10, 0); JSONObject row = results.getJSONObject(0).getJSONObject("t"); return row.getString("id"); } protected void waitFor(int timeout, Predicate predicate) throws Exception { long mustEnd = System.currentTimeMillis() + timeout; boolean eval; while (!(eval = predicate.evaluate()) && System.currentTimeMillis() < mustEnd) { LOG.info("Waiting up to {} msec", mustEnd - System.currentTimeMillis()); Thread.sleep(1000); } if (!eval) { throw new Exception("Waiting timed out after " + timeout + " msec"); } } public interface Predicate { /** * Perform a predicate evaluation. * * @return the boolean result of the evaluation. * @throws Exception thrown if the predicate evaluation could not evaluate. */ boolean evaluate() throws Exception; } } <|start_filename|>repository/src/main/java/org/apache/atlas/gremlin/optimizer/AliasFinder.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.gremlin.optimizer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.atlas.groovy.AbstractFunctionExpression; import org.apache.atlas.groovy.FunctionCallExpression; import org.apache.atlas.groovy.GroovyExpression; import org.apache.atlas.groovy.LiteralExpression; import org.apache.atlas.groovy.TraversalStepType; /** * Finds all aliases in the expression. */ public class AliasFinder implements CallHierarchyVisitor { private List<LiteralExpression> foundAliases = new ArrayList<>(); //Whether a final alias is needed. A final alias is needed //if there are transformation steps after the last alias in //the expression. We initialize this to false since a final //alias is not needed if there are no aliases. private boolean finalAliasNeeded = false; @Override public boolean preVisitFunctionCaller(AbstractFunctionExpression expr) { return true; } @Override public void visitNonFunctionCaller(GroovyExpression expr) { } @Override public void visitNullCaller() { } private static final Set<TraversalStepType> TRANSFORMATION_STEP_TYPES = new HashSet<>(Arrays.asList( TraversalStepType.MAP_TO_ELEMENT, TraversalStepType.MAP_TO_VALUE, TraversalStepType.FLAT_MAP_TO_ELEMENTS, TraversalStepType.FLAT_MAP_TO_VALUES, TraversalStepType.BARRIER, TraversalStepType.NONE)); @Override public boolean postVisitFunctionCaller(AbstractFunctionExpression functionCall) { if (functionCall instanceof FunctionCallExpression) { FunctionCallExpression expr = (FunctionCallExpression)functionCall; if (expr.getType() == TraversalStepType.SIDE_EFFECT && expr.getFunctionName().equals("as")) { //We found an alias. This is currently the last expression we've seen //in our traversal back up the expression tree, so at this point a final //alias is not needed. LiteralExpression aliasNameExpr = (LiteralExpression)expr.getArguments().get(0); foundAliases.add(aliasNameExpr); finalAliasNeeded=false; } } if(TRANSFORMATION_STEP_TYPES.contains(functionCall.getType())) { //This step changes the value of the traverser. Now, a final alias //needs to be added. if(!foundAliases.isEmpty()) { finalAliasNeeded = true; } } return true; } public List<LiteralExpression> getAliases() { return foundAliases; } public boolean isFinalAliasNeeded() { return finalAliasNeeded; } } <|start_filename|>graphdb/titan1/src/main/java/org/apache/atlas/repository/graphdb/titan1/Titan1IndexQuery.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan1; import java.util.Iterator; import com.google.common.base.Preconditions; import org.apache.atlas.repository.graphdb.AtlasIndexQuery; import org.apache.atlas.repository.graphdb.AtlasVertex; import com.google.common.base.Function; import com.google.common.collect.Iterators; import com.thinkaurelius.titan.core.TitanIndexQuery; import com.thinkaurelius.titan.core.TitanVertex; /** * Titan 1.0.0 implementation of AtlasIndexQuery. */ public class Titan1IndexQuery implements AtlasIndexQuery<Titan1Vertex, Titan1Edge> { private Titan1Graph graph; private TitanIndexQuery query; public Titan1IndexQuery(Titan1Graph graph, TitanIndexQuery query) { this.query = query; this.graph = graph; } @Override public Iterator<Result<Titan1Vertex, Titan1Edge>> vertices() { Iterator<TitanIndexQuery.Result<TitanVertex>> results = query.vertices().iterator(); Function<TitanIndexQuery.Result<TitanVertex>, Result<Titan1Vertex, Titan1Edge>> function = new Function<TitanIndexQuery.Result<TitanVertex>, Result<Titan1Vertex, Titan1Edge>>() { @Override public Result<Titan1Vertex, Titan1Edge> apply(TitanIndexQuery.Result<TitanVertex> source) { return new ResultImpl(source); } }; return Iterators.transform(results, function); } @Override public Iterator<Result<Titan1Vertex, Titan1Edge>> vertices(int offset, int limit) { Preconditions.checkArgument(offset >=0, "Index offset should be greater than or equals to 0"); Preconditions.checkArgument(limit >=0, "Index limit should be greater than or equals to 0"); Iterator<TitanIndexQuery.Result<TitanVertex>> results = query .offset(offset) .limit(limit) .vertices().iterator(); Function<TitanIndexQuery.Result<TitanVertex>, Result<Titan1Vertex, Titan1Edge>> function = new Function<TitanIndexQuery.Result<TitanVertex>, Result<Titan1Vertex, Titan1Edge>>() { @Override public Result<Titan1Vertex, Titan1Edge> apply(TitanIndexQuery.Result<TitanVertex> source) { return new ResultImpl(source); } }; return Iterators.transform(results, function); } /** * Titan 1.0.0 implementation of AtlasIndexQuery.Result. */ public final class ResultImpl implements AtlasIndexQuery.Result<Titan1Vertex, Titan1Edge> { private TitanIndexQuery.Result<TitanVertex> source; public ResultImpl(TitanIndexQuery.Result<TitanVertex> source) { this.source = source; } @Override public AtlasVertex<Titan1Vertex, Titan1Edge> getVertex() { return GraphDbObjectFactory.createVertex(graph, source.getElement()); } @Override public double getScore() { return source.getScore(); } } } <|start_filename|>authorization/src/main/java/org/apache/atlas/authorize/simple/AtlasAuthorizationUtils.java<|end_filename|> /** /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.authorize.simple; import javax.servlet.http.HttpServletRequest; import org.apache.atlas.AtlasClient; import org.apache.atlas.authorize.AtlasActionTypes; import org.apache.atlas.authorize.AtlasResourceTypes; import org.apache.atlas.authorize.AtlasAuthorizationException; import org.apache.atlas.authorize.AtlasAuthorizer; import org.apache.atlas.authorize.AtlasAccessRequest; import org.apache.atlas.authorize.AtlasAuthorizerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.HashSet; import java.util.Set; import java.util.regex.Pattern; public class AtlasAuthorizationUtils { private static final Logger LOG = LoggerFactory.getLogger(AtlasAuthorizationUtils.class); private static boolean isDebugEnabled = LOG.isDebugEnabled(); private static final String BASE_URL = "/" + AtlasClient.BASE_URI; public static String getApi(String contextPath) { if (isDebugEnabled) { LOG.debug("==> getApi({})", contextPath); } if(contextPath == null){ contextPath = ""; } if (contextPath.startsWith(BASE_URL)) { contextPath = contextPath.substring(BASE_URL.length()); } else { // strip of leading '/' if (contextPath.startsWith("/")) { contextPath = contextPath.substring(1); } } String[] split = contextPath.split("/", 3); String api = split[0]; if (Pattern.matches("v\\d", api)) { api = split[1]; } if (isDebugEnabled) { LOG.debug("<== getApi({}): {}", contextPath, api); } return api; } public static AtlasActionTypes getAtlasAction(String method) { AtlasActionTypes action = null; switch (method.toUpperCase()) { case "POST": action = AtlasActionTypes.CREATE; break; case "GET": action = AtlasActionTypes.READ; break; case "PUT": action = AtlasActionTypes.UPDATE; break; case "DELETE": action = AtlasActionTypes.DELETE; break; default: if (isDebugEnabled) { LOG.debug("getAtlasAction(): Invalid HTTP method '{}", method); } break; } if (isDebugEnabled) { LOG.debug("<== AtlasAuthorizationFilter getAtlasAction HTTP Method {} mapped to AtlasAction : {}", method, action); } return action; } /** * @param contextPath * @return set of AtlasResourceTypes types api mapped with AtlasResourceTypes.TYPE eg :- /api/atlas/types/* * * gremlin discovery,admin,graph apis are mapped with AtlasResourceTypes.OPERATION eg :-/api/atlas/admin/* * /api/atlas/discovery/search/gremlin /api/atlas/graph/* * * entities,lineage and discovery apis are mapped with AtlasResourceTypes.ENTITY eg :- /api/atlas/lineage/hive/table/* * /api/atlas/entities/{guid}* /api/atlas/discovery/* * * taxonomy API are also mapped to AtlasResourceTypes.TAXONOMY & AtlasResourceTypes.ENTITY and its terms APIs have * added AtlasResourceTypes.TERM associations. * * unprotected types are mapped with AtlasResourceTypes.UNKNOWN, access to these are allowed. */ public static Set<AtlasResourceTypes> getAtlasResourceType(String contextPath) { Set<AtlasResourceTypes> resourceTypes = new HashSet<>(); if (isDebugEnabled) { LOG.debug("==> getAtlasResourceType for {}", contextPath); } String api = getApi(contextPath); if (api.startsWith("types")) { resourceTypes.add(AtlasResourceTypes.TYPE); } else if (api.startsWith("admin") && (contextPath.contains("/session") || contextPath.contains("/version"))) { resourceTypes.add(AtlasResourceTypes.UNKNOWN); } else if ((api.startsWith("discovery") && contextPath.contains("/gremlin")) || api.startsWith("admin") || api.startsWith("graph")) { resourceTypes.add(AtlasResourceTypes.OPERATION); } else if (api.startsWith("entities") || api.startsWith("lineage") || api.startsWith("discovery") || api.startsWith("entity") || api.startsWith("search")) { resourceTypes.add(AtlasResourceTypes.ENTITY); } else if (api.startsWith("taxonomies")) { resourceTypes.add(AtlasResourceTypes.TAXONOMY); // taxonomies are modeled as entities resourceTypes.add(AtlasResourceTypes.ENTITY); if (contextPath.contains("/terms")) { resourceTypes.add(AtlasResourceTypes.TERM); } } else if (api.startsWith("relationship")) { resourceTypes.add(AtlasResourceTypes.RELATIONSHIP); } else { LOG.error("Unable to find Atlas Resource corresponding to : {}\nSetting {}" , api, AtlasResourceTypes.UNKNOWN.name()); resourceTypes.add(AtlasResourceTypes.UNKNOWN); } if (isDebugEnabled) { LOG.debug("<== Returning AtlasResources {} for api {}", resourceTypes, api); } return resourceTypes; } public static boolean isAccessAllowed(AtlasResourceTypes resourcetype, AtlasActionTypes actionType, String userName, Set<String> groups, HttpServletRequest request) { AtlasAuthorizer authorizer = null; boolean isaccessAllowed = false; Set<AtlasResourceTypes> resourceTypes = new HashSet<>(); resourceTypes.add(resourcetype); AtlasAccessRequest atlasRequest = new AtlasAccessRequest(resourceTypes, "*", actionType, userName, groups, AtlasAuthorizationUtils.getRequestIpAddress(request)); try { authorizer = AtlasAuthorizerFactory.getAtlasAuthorizer(); if (authorizer != null) { isaccessAllowed = authorizer.isAccessAllowed(atlasRequest); } } catch (AtlasAuthorizationException e) { LOG.error("Unable to obtain AtlasAuthorizer. ", e); } return isaccessAllowed; } public static String getRequestIpAddress(HttpServletRequest httpServletRequest) { try { InetAddress inetAddr = InetAddress.getByName(httpServletRequest.getRemoteAddr()); String ip = inetAddr.getHostAddress(); return ip; } catch (UnknownHostException ex) { LOG.error("Error occured when retrieving IP address", ex); return ""; } } } <|start_filename|>graphdb/titan0/src/main/java/org/apache/atlas/repository/graphdb/titan0/GraphDbObjectFactory.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan0; import org.apache.atlas.repository.graphdb.AtlasCardinality; import org.apache.atlas.repository.graphdb.AtlasGraphIndex; import org.apache.atlas.repository.graphdb.titan0.query.Titan0GraphQuery; import com.thinkaurelius.titan.core.Cardinality; import com.thinkaurelius.titan.core.PropertyKey; import com.thinkaurelius.titan.core.schema.TitanGraphIndex; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Vertex; /** * Factory that serves up instances of graph database abstraction layer classes * that correspond to Titan/Tinkerpop classes. */ public final class GraphDbObjectFactory { private GraphDbObjectFactory() { } /** * Creates a Titan0Edge that corresponds to the given Gremlin Edge. * * @param graph The graph the edge should be created in * @param source The gremlin edge */ public static Titan0Edge createEdge(Titan0Graph graph, Edge source) { if (source == null) { return null; } return new Titan0Edge(graph, source); } /** * Creates a Titan0GraphQuery that corresponds to the given GraphQuery. * * @param graph the graph that is being quried */ public static Titan0GraphQuery createQuery(Titan0Graph graph) { return new Titan0GraphQuery(graph); } /** * Creates a Titan0Vertex that corresponds to the given Gremlin Vertex. * * @param graph The graph that contains the vertex * @param source the Gremlin vertex */ public static Titan0Vertex createVertex(Titan0Graph graph, Vertex source) { if (source == null) { return null; } return new Titan0Vertex(graph, source); } /** * @param propertyKey The Gremlin propertyKey. * */ public static Titan0PropertyKey createPropertyKey(PropertyKey propertyKey) { if (propertyKey == null) { return null; } return new Titan0PropertyKey(propertyKey); } /** * @param index The gremlin index. * @return */ public static AtlasGraphIndex createGraphIndex(TitanGraphIndex index) { if (index == null) { return null; } return new Titan0GraphIndex(index); } /** * Converts a Multiplicity to a Cardinality. * * @param cardinality * @return */ public static AtlasCardinality createCardinality(Cardinality cardinality) { if (cardinality == Cardinality.SINGLE) { return AtlasCardinality.SINGLE; } else if (cardinality == Cardinality.LIST) { return AtlasCardinality.LIST; } return AtlasCardinality.SET; } } <|start_filename|>catalog/src/test/java/org/apache/atlas/catalog/query/AtlasEntityQueryTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.catalog.query; import com.thinkaurelius.titan.core.TitanGraph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.gremlin.java.GremlinPipeline; import com.tinkerpop.pipes.Pipe; import org.apache.atlas.catalog.Request; import org.apache.atlas.catalog.VertexWrapper; import org.apache.atlas.catalog.definition.ResourceDefinition; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.easymock.Capture; import org.testng.annotations.Test; import java.util.*; import static org.easymock.EasyMock.*; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; /** * Unit tests for AtlasEntityQuery. */ @SuppressWarnings("unchecked") public class AtlasEntityQueryTest { //todo: add tests for instance query and getInitialPipeline() @Test public void testExecute_Collection() throws Exception { AtlasGraph graph = createStrictMock(AtlasGraph.class); QueryExpression expression = createStrictMock(QueryExpression.class); ResourceDefinition resourceDefinition = createStrictMock(ResourceDefinition.class); Request request = createStrictMock(Request.class); GremlinPipeline initialPipeline = createStrictMock(GremlinPipeline.class); Pipe queryPipe = createStrictMock(Pipe.class); Pipe expressionPipe = createStrictMock(Pipe.class); Pipe notDeletedPipe = createStrictMock(Pipe.class); GremlinPipeline rootPipeline = createStrictMock(GremlinPipeline.class); GremlinPipeline queryPipeline = createStrictMock(GremlinPipeline.class); GremlinPipeline expressionPipeline = createStrictMock(GremlinPipeline.class); GremlinPipeline notDeletedPipeline = createStrictMock(GremlinPipeline.class); Vertex vertex1 = createStrictMock(Vertex.class); VertexWrapper vertex1Wrapper = createStrictMock(VertexWrapper.class); List<Vertex> results = new ArrayList<>(); results.add(vertex1); Map<String, Object> vertex1PropertyMap = new HashMap<>(); vertex1PropertyMap.put("prop1", "prop1.value1"); vertex1PropertyMap.put("prop2", "prop2.value1"); Map<String, Object> filteredVertex1PropertyMap = new HashMap<>(); filteredVertex1PropertyMap.put("prop1", "prop1.value1"); // mock expectations expect(initialPipeline.add(queryPipe)).andReturn(queryPipeline); expect(initialPipeline.add(notDeletedPipe)).andReturn(notDeletedPipeline); expect(initialPipeline.as("root")).andReturn(rootPipeline); expect(expression.asPipe()).andReturn(expressionPipe); expect(rootPipeline.add(expressionPipe)).andReturn(expressionPipeline); expect(expressionPipeline.back("root")).andReturn(rootPipeline); expect(rootPipeline.toList()).andReturn(results); graph.commit(); expect(vertex1Wrapper.getPropertyMap()).andReturn(vertex1PropertyMap); expect(resourceDefinition.filterProperties(request, vertex1PropertyMap)).andReturn(filteredVertex1PropertyMap); expect(resourceDefinition.resolveHref(filteredVertex1PropertyMap)).andReturn("/foo/bar"); expect(request.getCardinality()).andReturn(Request.Cardinality.COLLECTION); replay(graph, expression, resourceDefinition, request, initialPipeline, queryPipe, expressionPipe, notDeletedPipe, rootPipeline, queryPipeline, expressionPipeline, notDeletedPipeline, vertex1, vertex1Wrapper); // end mock expectations AtlasEntityQuery query = new TestAtlasEntityQuery(expression, resourceDefinition, request, initialPipeline, queryPipe, notDeletedPipe, graph, vertex1Wrapper); // invoke method being tested Collection<Map<String, Object>> queryResults = query.execute(); assertEquals(queryResults.size(), 1); Map<String, Object> queryResultMap = queryResults.iterator().next(); assertEquals(queryResultMap.size(), 2); assertEquals(queryResultMap.get("prop1"), "prop1.value1"); assertEquals(queryResultMap.get("href"), "/foo/bar"); verify(graph, expression, resourceDefinition, request, initialPipeline, queryPipe, expressionPipe, notDeletedPipe, rootPipeline, queryPipeline, expressionPipeline, notDeletedPipeline, vertex1, vertex1Wrapper); } @Test public void testExecute_Collection_rollbackOnException() throws Exception { AtlasGraph graph = createStrictMock(AtlasGraph.class); QueryExpression expression = createStrictMock(QueryExpression.class); ResourceDefinition resourceDefinition = createStrictMock(ResourceDefinition.class); Request request = createStrictMock(Request.class); GremlinPipeline initialPipeline = createStrictMock(GremlinPipeline.class); Pipe queryPipe = createStrictMock(Pipe.class); Pipe expressionPipe = createStrictMock(Pipe.class); Pipe notDeletedPipe = createStrictMock(Pipe.class); GremlinPipeline rootPipeline = createStrictMock(GremlinPipeline.class); GremlinPipeline queryPipeline = createStrictMock(GremlinPipeline.class); GremlinPipeline expressionPipeline = createStrictMock(GremlinPipeline.class); GremlinPipeline notDeletedPipeline = createStrictMock(GremlinPipeline.class); // mock expectations expect(initialPipeline.add(queryPipe)).andReturn(queryPipeline); expect(initialPipeline.add(notDeletedPipe)).andReturn(notDeletedPipeline); expect(initialPipeline.as("root")).andReturn(rootPipeline); expect(expression.asPipe()).andReturn(expressionPipe); expect(rootPipeline.add(expressionPipe)).andReturn(expressionPipeline); expect(expressionPipeline.back("root")).andReturn(rootPipeline); expect(rootPipeline.toList()).andThrow(new RuntimeException("something bad happened")); graph.rollback(); replay(graph, expression, resourceDefinition, request, initialPipeline, queryPipe, expressionPipe, notDeletedPipe, rootPipeline, queryPipeline, expressionPipeline, notDeletedPipeline); // end mock expectations AtlasEntityQuery query = new TestAtlasEntityQuery(expression, resourceDefinition, request, initialPipeline, queryPipe, notDeletedPipe, graph, null); try { // invoke method being tested query.execute(); fail("expected exception"); } catch (RuntimeException e) { assertEquals(e.getMessage(), "something bad happened"); } verify(graph, expression, resourceDefinition, request, initialPipeline, queryPipe, expressionPipe, notDeletedPipe, rootPipeline, queryPipeline, expressionPipeline, notDeletedPipeline); } @Test public void testExecute_Collection_update() throws Exception { AtlasGraph graph = createStrictMock(AtlasGraph.class); QueryExpression expression = createStrictMock(QueryExpression.class); ResourceDefinition resourceDefinition = createStrictMock(ResourceDefinition.class); Request request = createStrictMock(Request.class); GremlinPipeline initialPipeline = createStrictMock(GremlinPipeline.class); Pipe queryPipe = createStrictMock(Pipe.class); Pipe expressionPipe = createStrictMock(Pipe.class); Pipe notDeletedPipe = createStrictMock(Pipe.class); GremlinPipeline rootPipeline = createStrictMock(GremlinPipeline.class); GremlinPipeline queryPipeline = createStrictMock(GremlinPipeline.class); GremlinPipeline expressionPipeline = createStrictMock(GremlinPipeline.class); GremlinPipeline notDeletedPipeline = createStrictMock(GremlinPipeline.class); Vertex vertex1 = createStrictMock(Vertex.class); VertexWrapper vertex1Wrapper = createStrictMock(VertexWrapper.class); Capture<Long> modifiedTimestampCapture = newCapture(); List<Vertex> results = new ArrayList<>(); results.add(vertex1); Map<String, Object> vertex1PropertyMap = new HashMap<>(); vertex1PropertyMap.put("prop1", "prop1.value1"); vertex1PropertyMap.put("prop2", "prop2.value1"); Map<String, Object> filteredVertex1PropertyMap = new HashMap<>(); filteredVertex1PropertyMap.put("prop1", "prop1.value1"); Map<String, Object> updateProperties = new HashMap<>(); updateProperties.put("prop3", "newValue"); // mock expectations expect(initialPipeline.add(queryPipe)).andReturn(queryPipeline); expect(initialPipeline.add(notDeletedPipe)).andReturn(notDeletedPipeline); expect(initialPipeline.as("root")).andReturn(rootPipeline); expect(expression.asPipe()).andReturn(expressionPipe); expect(rootPipeline.add(expressionPipe)).andReturn(expressionPipeline); expect(expressionPipeline.back("root")).andReturn(rootPipeline); expect(rootPipeline.toList()).andReturn(results); graph.commit(); vertex1Wrapper.setProperty("prop3", "newValue"); vertex1Wrapper.setProperty(eq(Constants.MODIFICATION_TIMESTAMP_PROPERTY_KEY), capture(modifiedTimestampCapture)); expect(vertex1Wrapper.getPropertyMap()).andReturn(vertex1PropertyMap); expect(resourceDefinition.filterProperties(request, vertex1PropertyMap)).andReturn(filteredVertex1PropertyMap); expect(resourceDefinition.resolveHref(filteredVertex1PropertyMap)).andReturn("/foo/bar"); expect(request.getCardinality()).andReturn(Request.Cardinality.COLLECTION); replay(graph, expression, resourceDefinition, request, initialPipeline, queryPipe, expressionPipe, notDeletedPipe, rootPipeline, queryPipeline, expressionPipeline, notDeletedPipeline, vertex1, vertex1Wrapper); // end mock expectations AtlasEntityQuery query = new TestAtlasEntityQuery(expression, resourceDefinition, request, initialPipeline, queryPipe, notDeletedPipe, graph, vertex1Wrapper); long startTime = System.currentTimeMillis(); // invoke method being tested Collection<Map<String, Object>> queryResults = query.execute(updateProperties); long endTime = System.currentTimeMillis(); assertEquals(queryResults.size(), 1); Map<String, Object> queryResultMap = queryResults.iterator().next(); assertEquals(queryResultMap.size(), 2); assertEquals(queryResultMap.get("prop1"), "prop1.value1"); assertEquals(queryResultMap.get("href"), "/foo/bar"); long modifiedTimestamp = modifiedTimestampCapture.getValue(); assertTrue(modifiedTimestamp >= startTime && modifiedTimestamp <= endTime); verify(graph, expression, resourceDefinition, request, initialPipeline, queryPipe, expressionPipe, notDeletedPipe, rootPipeline, queryPipeline, expressionPipeline, notDeletedPipeline, vertex1, vertex1Wrapper); } private class TestAtlasEntityQuery extends AtlasEntityQuery { private final GremlinPipeline initialPipeline; private final Pipe queryPipe; private final Pipe notDeletedPipe; private final AtlasGraph graph; private final VertexWrapper vWrapper; public TestAtlasEntityQuery(QueryExpression queryExpression, ResourceDefinition resourceDefinition, Request request, GremlinPipeline initialPipeline, Pipe queryPipe, Pipe notDeletedPipe, AtlasGraph graph, VertexWrapper vWrapper) { super(queryExpression, resourceDefinition, request); this.initialPipeline = initialPipeline; this.queryPipe = queryPipe; this.notDeletedPipe = notDeletedPipe; this.graph = graph; this.vWrapper = vWrapper; } @Override protected GremlinPipeline getRootVertexPipeline() { return initialPipeline; } @Override protected Pipe getQueryPipe() { return queryPipe; } @Override protected Pipe getNotDeletedPipe() { return notDeletedPipe; } @Override protected AtlasGraph getGraph() { return graph; } @Override protected VertexWrapper wrapVertex(Vertex v) { return vWrapper; } } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/graph/GraphToTypedInstanceMapper.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graph; import org.apache.atlas.AtlasException; import org.apache.atlas.RequestContext; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.RepositoryException; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasEdgeDirection; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.typesystem.ITypedInstance; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.ITypedStruct; import org.apache.atlas.typesystem.persistence.AtlasSystemAttributes; import org.apache.atlas.typesystem.persistence.Id; import org.apache.atlas.typesystem.types.AttributeInfo; import org.apache.atlas.typesystem.types.ClassType; import org.apache.atlas.typesystem.types.DataTypes; import org.apache.atlas.typesystem.types.IDataType; import org.apache.atlas.typesystem.types.Multiplicity; import org.apache.atlas.typesystem.types.StructType; import org.apache.atlas.typesystem.types.TraitType; import org.apache.atlas.typesystem.types.TypeSystem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.inject.Inject; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.apache.atlas.repository.graph.GraphHelper.string; @Component @Deprecated public final class GraphToTypedInstanceMapper { private static final Logger LOG = LoggerFactory.getLogger(GraphToTypedInstanceMapper.class); private static TypeSystem typeSystem = TypeSystem.getInstance(); private static final GraphHelper graphHelper = GraphHelper.getInstance(); private final AtlasGraph atlasGraph; @Inject public GraphToTypedInstanceMapper(AtlasGraph atlasGraph) { this.atlasGraph = atlasGraph; } public ITypedReferenceableInstance mapGraphToTypedInstance(String guid, AtlasVertex instanceVertex) throws AtlasException { if(LOG.isDebugEnabled()) { //We don't do a cache check here since we want that to be at a higher level //where the vertex lookup can also be avoided. However, this is a convenient //place to add a check to see if there are any places that were missed. if(RequestContext.get().getInstanceV1(guid) != null) { LOG.warn("Looking up previously cached guid at: ", new Exception()); } LOG.debug("Mapping graph root vertex {} to typed instance for guid {}", instanceVertex, guid); } String typeName = GraphHelper.getSingleValuedProperty(instanceVertex, Constants.ENTITY_TYPE_PROPERTY_KEY, String.class); List<String> traits = GraphHelper.getTraitNames(instanceVertex); String state = GraphHelper.getStateAsString(instanceVertex); String createdBy = GraphHelper.getCreatedByAsString(instanceVertex); String modifiedBy = GraphHelper.getModifiedByAsString(instanceVertex); Date createdTime = new Date(GraphHelper.getCreatedTime(instanceVertex)); Date modifiedTime = new Date(GraphHelper.getModifiedTime(instanceVertex)); AtlasSystemAttributes systemAttributes = new AtlasSystemAttributes(createdBy, modifiedBy, createdTime, modifiedTime); if (LOG.isDebugEnabled()) { LOG.debug("Found createdBy : {} modifiedBy : {} createdTime: {} modifedTime: {}", createdBy, modifiedBy, createdTime, modifiedTime); } Id id = new Id(guid, Integer.parseInt(String.valueOf(GraphHelper.getProperty(instanceVertex, Constants.VERSION_PROPERTY_KEY))), typeName, state); if (LOG.isDebugEnabled()) { LOG.debug("Created id {} for instance type {}", id, typeName); } ClassType classType = typeSystem.getDataType(ClassType.class, typeName); ITypedReferenceableInstance typedInstance = classType.createInstance(id, systemAttributes, traits.toArray(new String[traits.size()])); mapVertexToInstance(instanceVertex, typedInstance, classType.fieldMapping().fields); mapVertexToInstanceTraits(instanceVertex, typedInstance, traits); RequestContext.get().cache(typedInstance); return typedInstance; } private void mapVertexToInstanceTraits(AtlasVertex instanceVertex, ITypedReferenceableInstance typedInstance, List<String> traits) throws AtlasException { for (String traitName : traits) { if (LOG.isDebugEnabled()) { LOG.debug("mapping trait {} to instance", traitName); } TraitType traitType = typeSystem.getDataType(TraitType.class, traitName); mapVertexToTraitInstance(instanceVertex, typedInstance, traitName, traitType); } } public void mapVertexToInstance(AtlasVertex instanceVertex, ITypedInstance typedInstance, Map<String, AttributeInfo> fields) throws AtlasException { if (LOG.isDebugEnabled()) { LOG.debug("Mapping vertex {} to instance {} for fields", instanceVertex, typedInstance.getTypeName(), fields); } for (AttributeInfo attributeInfo : fields.values()) { mapVertexToAttribute(instanceVertex, typedInstance, attributeInfo); } } private void mapVertexToAttribute(AtlasVertex instanceVertex, ITypedInstance typedInstance, AttributeInfo attributeInfo) throws AtlasException { if (LOG.isDebugEnabled()) { LOG.debug("Mapping attributeInfo {}", attributeInfo.name); } final IDataType dataType = attributeInfo.dataType(); final String vertexPropertyName = GraphHelper.getQualifiedFieldName(typedInstance, attributeInfo); String relationshipLabel = GraphHelper.getEdgeLabel(typedInstance, attributeInfo); switch (dataType.getTypeCategory()) { case PRIMITIVE: mapVertexToPrimitive(instanceVertex, typedInstance, attributeInfo); break; // add only if vertex has this attribute case ENUM: Object propertyValue = GraphHelper.getProperty(instanceVertex, vertexPropertyName); if (propertyValue == null) { return; } typedInstance.set(attributeInfo.name, dataType.convert(propertyValue, Multiplicity.REQUIRED)); break; case ARRAY: mapVertexToArrayInstance(instanceVertex, typedInstance, attributeInfo, vertexPropertyName); break; case MAP: mapVertexToMapInstance(instanceVertex, typedInstance, attributeInfo, vertexPropertyName); break; case STRUCT: ITypedStruct structInstance = mapVertexToStructInstance(instanceVertex, (StructType) attributeInfo.dataType(), relationshipLabel, null); typedInstance.set(attributeInfo.name, structInstance); break; case TRAIT: // do NOTHING - handled in class break; case CLASS: AtlasEdge nullEdge = null; Object idOrInstance = mapVertexToClassReference(instanceVertex, attributeInfo, relationshipLabel, attributeInfo.dataType(), nullEdge); if (idOrInstance != null) { typedInstance.set(attributeInfo.name, idOrInstance); } break; default: break; } } private Object mapVertexToClassReference(AtlasVertex instanceVertex, AttributeInfo attributeInfo, String relationshipLabel, IDataType dataType, AtlasEdge optionalEdge) throws AtlasException { if (LOG.isDebugEnabled()) { LOG.debug("Finding edge for {} -> label {} ", instanceVertex, relationshipLabel); } AtlasEdge edge = null; if (optionalEdge == null) { edge = graphHelper.getEdgeForLabel(instanceVertex, relationshipLabel); } else { edge = optionalEdge; } if (GraphHelper.elementExists(edge)) { final AtlasVertex referenceVertex = edge.getInVertex(); final String guid = GraphHelper.getSingleValuedProperty(referenceVertex, Constants.GUID_PROPERTY_KEY, String.class); if (LOG.isDebugEnabled()) { LOG.debug("Found vertex {} for label {} with guid {}", referenceVertex, relationshipLabel, guid); } if (attributeInfo.isComposite) { //Also, when you retrieve a type's instance, you get the complete object graph of the composites LOG.debug("Found composite, mapping vertex to instance"); ITypedReferenceableInstance cached = RequestContext.get().getInstanceV1(guid); if(cached != null) { return cached; } return mapGraphToTypedInstance(guid, referenceVertex); } else { String state = GraphHelper.getStateAsString(referenceVertex); Id referenceId = new Id(guid, GraphHelper.getSingleValuedProperty(referenceVertex, Constants.VERSION_PROPERTY_KEY, Integer.class), dataType.getName(), state); if (LOG.isDebugEnabled()) { LOG.debug("Found non-composite, adding id {} ", referenceId); } return referenceId; } } return null; } @SuppressWarnings("unchecked") private void mapVertexToArrayInstance(AtlasVertex<?,?> instanceVertex, ITypedInstance typedInstance, AttributeInfo attributeInfo, String propertyName) throws AtlasException { if (LOG.isDebugEnabled()) { LOG.debug("mapping vertex {} to array {}", instanceVertex, attributeInfo.name); } final DataTypes.ArrayType arrayType = (DataTypes.ArrayType) attributeInfo.dataType(); final IDataType elementType = arrayType.getElemType(); List<Object> list = GraphHelper.getArrayElementsProperty(elementType, instanceVertex, propertyName); if (list == null || list.size() == 0) { return; } String edgeLabel = GraphHelper.EDGE_LABEL_PREFIX + propertyName; ArrayList values = new ArrayList(); for (Object aList : list) { values.add(mapVertexToCollectionEntry(instanceVertex, attributeInfo, elementType, aList, edgeLabel)); } if (values.size() > 0) { typedInstance.set(attributeInfo.name, values); } } private Object mapVertexToCollectionEntry(AtlasVertex instanceVertex, AttributeInfo attributeInfo, IDataType elementType, Object value, String edgeLabel) throws AtlasException { switch (elementType.getTypeCategory()) { case PRIMITIVE: case ENUM: return value; case ARRAY: case MAP: case TRAIT: // do nothing break; case STRUCT: return mapVertexToStructInstance(instanceVertex, (StructType) elementType, edgeLabel, (AtlasEdge) value); case CLASS: return mapVertexToClassReference(instanceVertex, attributeInfo, edgeLabel, elementType, (AtlasEdge) value); default: break; } throw new IllegalArgumentException(); } @SuppressWarnings("unchecked") private void mapVertexToMapInstance(AtlasVertex<?,?> instanceVertex, ITypedInstance typedInstance, AttributeInfo attributeInfo, final String propertyName) throws AtlasException { if (LOG.isDebugEnabled()) { LOG.debug("mapping vertex {} to array {}", instanceVertex, attributeInfo.name); } List<String> keys = GraphHelper.getListProperty(instanceVertex, propertyName); if (keys == null || keys.size() == 0) { return; } DataTypes.MapType mapType = (DataTypes.MapType) attributeInfo.dataType(); final IDataType valueType = mapType.getValueType(); HashMap<String,Object> values = new HashMap<>(); for (String key : keys) { final String keyPropertyName = propertyName + "." + key; final String edgeLabel = GraphHelper.EDGE_LABEL_PREFIX + keyPropertyName; final Object keyValue = GraphHelper.getMapValueProperty(valueType, instanceVertex, keyPropertyName); Object mapValue = mapVertexToCollectionEntry(instanceVertex, attributeInfo, valueType, keyValue, edgeLabel); if (mapValue != null) { values.put(key, mapValue); } } if (!values.isEmpty()) { typedInstance.set(attributeInfo.name, values); } } private ITypedStruct mapVertexToStructInstance(AtlasVertex instanceVertex, StructType structType, String relationshipLabel, AtlasEdge optionalEdge) throws AtlasException { if (LOG.isDebugEnabled()) { LOG.debug("mapping {} to struct {}", string(instanceVertex), relationshipLabel); } ITypedStruct structInstance = null; AtlasEdge edge; if (optionalEdge == null) { edge = graphHelper.getEdgeForLabel(instanceVertex, relationshipLabel); } else { edge = optionalEdge; } if (GraphHelper.elementExists(edge)) { structInstance = structType.createInstance(); AtlasVertex structInstanceVertex = edge.getInVertex(); if (LOG.isDebugEnabled()) { LOG.debug("Found struct instance {}, mapping to instance {} ", string(structInstanceVertex), structInstance.getTypeName()); } mapVertexToInstance(structInstanceVertex, structInstance, structType.fieldMapping().fields); } return structInstance; } private void mapVertexToTraitInstance(AtlasVertex instanceVertex, ITypedReferenceableInstance typedInstance, String traitName, TraitType traitType) throws AtlasException { ITypedStruct traitInstance = (ITypedStruct) typedInstance.getTrait(traitName); mapVertexToTraitInstance(instanceVertex, typedInstance.getTypeName(), traitName, traitType, traitInstance); } private void mapVertexToTraitInstance(AtlasVertex<?,?> instanceVertex, String typedInstanceTypeName, String traitName, TraitType traitType, ITypedStruct traitInstance) throws AtlasException { String relationshipLabel = GraphHelper.getTraitLabel(typedInstanceTypeName, traitName); if (LOG.isDebugEnabled()) { LOG.debug("Finding edge for {} -> label {} ", instanceVertex, relationshipLabel); } for (AtlasEdge<?,?> edge : instanceVertex.getEdges(AtlasEdgeDirection.OUT, relationshipLabel)) { final AtlasVertex<?,?> traitInstanceVertex = edge.getInVertex(); if (traitInstanceVertex != null) { if (LOG.isDebugEnabled()) { LOG.debug("Found trait instance vertex {}, mapping to instance {} ", traitInstanceVertex, traitInstance.getTypeName()); } mapVertexToInstance(traitInstanceVertex, traitInstance, traitType.fieldMapping().fields); break; } } } private void mapVertexToPrimitive(AtlasVertex<?,?> instanceVertex, ITypedInstance typedInstance, AttributeInfo attributeInfo) throws AtlasException { if (LOG.isDebugEnabled()) { LOG.debug("Adding primitive {} from vertex {}", attributeInfo, instanceVertex); } final String vertexPropertyName = GraphHelper.getQualifiedFieldName(typedInstance, attributeInfo); if (GraphHelper.getSingleValuedProperty(instanceVertex, vertexPropertyName, Object.class) == null) { return; } if (attributeInfo.dataType() == DataTypes.STRING_TYPE) { typedInstance.setString(attributeInfo.name, GraphHelper.getSingleValuedProperty(instanceVertex, vertexPropertyName, String.class)); } else if (attributeInfo.dataType() == DataTypes.SHORT_TYPE) { typedInstance.setShort(attributeInfo.name, GraphHelper.getSingleValuedProperty(instanceVertex, vertexPropertyName, Short.class)); } else if (attributeInfo.dataType() == DataTypes.INT_TYPE) { typedInstance.setInt(attributeInfo.name, GraphHelper.getSingleValuedProperty(instanceVertex, vertexPropertyName, Integer.class)); } else if (attributeInfo.dataType() == DataTypes.BIGINTEGER_TYPE) { typedInstance.setBigInt(attributeInfo.name, GraphHelper.getSingleValuedProperty(instanceVertex, vertexPropertyName, BigInteger.class)); } else if (attributeInfo.dataType() == DataTypes.BOOLEAN_TYPE) { typedInstance.setBoolean(attributeInfo.name, GraphHelper.getSingleValuedProperty(instanceVertex, vertexPropertyName, Boolean.class)); } else if (attributeInfo.dataType() == DataTypes.BYTE_TYPE) { typedInstance.setByte(attributeInfo.name, GraphHelper.getSingleValuedProperty(instanceVertex, vertexPropertyName, Byte.class)); } else if (attributeInfo.dataType() == DataTypes.LONG_TYPE) { typedInstance.setLong(attributeInfo.name, GraphHelper.getSingleValuedProperty(instanceVertex, vertexPropertyName, Long.class)); } else if (attributeInfo.dataType() == DataTypes.FLOAT_TYPE) { typedInstance.setFloat(attributeInfo.name, GraphHelper.getSingleValuedProperty(instanceVertex, vertexPropertyName, Float.class)); } else if (attributeInfo.dataType() == DataTypes.DOUBLE_TYPE) { typedInstance.setDouble(attributeInfo.name, GraphHelper.getSingleValuedProperty(instanceVertex, vertexPropertyName, Double.class)); } else if (attributeInfo.dataType() == DataTypes.BIGDECIMAL_TYPE) { typedInstance .setBigDecimal(attributeInfo.name, GraphHelper.getSingleValuedProperty(instanceVertex, vertexPropertyName, BigDecimal.class)); } else if (attributeInfo.dataType() == DataTypes.DATE_TYPE) { final Long dateVal = GraphHelper.getSingleValuedProperty(instanceVertex, vertexPropertyName, Long.class); typedInstance.setDate(attributeInfo.name, new Date(dateVal)); } } public ITypedInstance getReferredEntity(String edgeId, IDataType<?> referredType) throws AtlasException { final AtlasEdge edge = getGraph().getEdge(edgeId); if (edge != null) { final AtlasVertex referredVertex = edge.getInVertex(); if (referredVertex != null) { switch (referredType.getTypeCategory()) { case STRUCT: if (LOG.isDebugEnabled()) { LOG.debug("Found struct instance vertex {}, mapping to instance {} ", referredVertex, referredType.getName()); } StructType structType = (StructType) referredType; ITypedStruct instance = structType.createInstance(); Map<String, AttributeInfo> fields = structType.fieldMapping().fields; mapVertexToInstance(referredVertex, instance, fields); return instance; case CLASS: //TODO isComposite handling for class loads return GraphHelper.getIdFromVertex(referredType.getName(), referredVertex); default: throw new UnsupportedOperationException("Loading " + referredType.getTypeCategory() + " is not supported"); } } } return null; } private AtlasGraph getGraph() throws RepositoryException { return atlasGraph; } } <|start_filename|>dashboardv2/public/js/utils/Messages.js<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(['require'], function(require) { 'use strict'; var Messages = { defaultErrorMessage: "Something went wrong", addSuccessMessage: " has been created successfully", addErrorMessage: " could not be Created", addTermToEntitySuccessMessage: " has been added to entity", deleteTerm: "Delete Term", removeTag: "Remove Tag Assignment", removeTerm: "Remove Term Assignment", deleteSuccessMessage: " has been deleted successfully", deleteErrorMessage: " could not be deleted", removeSuccessMessage: " has been removed successfully", removeErrorMessage: " could not be removed", addAttributeSuccessMessage: "Tag attribute is added successfully", updateTagDescriptionMessage: "Tag description is updated successfully", updateTermDescriptionMessage: "Term description is updated successfully", editSuccessMessage: " has been updated successfully", assignDeletedEntity: " is deleted, tag cannot be assigned" }; return Messages; }); <|start_filename|>client/src/main/java/org/apache/atlas/AtlasClient.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; import com.sun.jersey.api.client.WebResource; import org.apache.atlas.model.legacy.EntityResult; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.Struct; import org.apache.atlas.typesystem.TypesDef; import org.apache.atlas.typesystem.json.InstanceSerialization; import org.apache.atlas.typesystem.json.TypesSerialization; import org.apache.atlas.typesystem.types.AttributeDefinition; import org.apache.atlas.typesystem.types.DataTypes; import org.apache.atlas.typesystem.types.HierarchicalTypeDefinition; import org.apache.atlas.typesystem.types.TraitType; import org.apache.atlas.typesystem.types.utils.TypesUtil; import org.apache.commons.configuration.Configuration; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.security.UserGroupInformation; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.HttpMethod; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; /** * Client for metadata. */ @Deprecated public class AtlasClient extends AtlasBaseClient { private static final Logger LOG = LoggerFactory.getLogger(AtlasClient.class); public static final String TYPE = "type"; public static final String TYPENAME = "typeName"; public static final String GUID = "GUID"; public static final String ENTITIES = "entities"; public static final String GUID_ASSIGNMENTS = "guidAssignments"; public static final String DEFINITION = "definition"; public static final String ERROR = "error"; public static final String STACKTRACE = "stackTrace"; public static final String REQUEST_ID = "requestId"; public static final String RESULTS = "results"; public static final String COUNT = "count"; public static final String ROWS = "rows"; public static final String DATATYPE = "dataType"; public static final String STATUS = "Status"; public static final String EVENTS = "events"; public static final String START_KEY = "startKey"; public static final String NUM_RESULTS = "count"; public static final String URI_ENTITY = "entities"; public static final String URI_ENTITY_AUDIT = "audit"; public static final String URI_SEARCH = "discovery/search"; public static final String URI_NAME_LINEAGE = "lineage/hive/table"; public static final String URI_LINEAGE = "lineage/"; public static final String URI_TRAITS = "traits"; public static final String TRAITS = "traits"; public static final String TRAIT_DEFINITIONS = "traitDefinitions"; public static final String QUERY = "query"; public static final String LIMIT = "limit"; public static final String OFFSET = "offset"; public static final String QUERY_TYPE = "queryType"; public static final String ATTRIBUTE_NAME = "property"; public static final String ATTRIBUTE_VALUE = "value"; public static final String SUPERTYPE = "supertype"; public static final String NOT_SUPERTYPE = "notsupertype"; public static final String ASSET_TYPE = "Asset"; public static final String NAME = "name"; public static final String DESCRIPTION = "description"; public static final String OWNER = "owner"; public static final String INFRASTRUCTURE_SUPER_TYPE = "Infrastructure"; public static final String DATA_SET_SUPER_TYPE = "DataSet"; public static final String PROCESS_SUPER_TYPE = "Process"; public static final String PROCESS_ATTRIBUTE_INPUTS = "inputs"; public static final String PROCESS_ATTRIBUTE_OUTPUTS = "outputs"; public static final String REFERENCEABLE_SUPER_TYPE = "Referenceable"; public static final String QUALIFIED_NAME = "qualifiedName"; public static final String REFERENCEABLE_ATTRIBUTE_NAME = QUALIFIED_NAME; public static final String UNKNOWN_STATUS = "Unknown status"; /** * Constructor for AtlasClient with cookie params as header * @param baseUrl * @param cookieName * @param value * @param path * @param domain */ public AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain) { super(baseUrl, new Cookie( cookieName, value, path, domain)); } /** * Constructor for AtlasClient with cookie as header * @param baseUrl * @param cookie */ public AtlasClient(String[] baseUrl, Cookie cookie) { super(baseUrl, cookie); } // New constructor for Basic auth public AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword) { super(baseUrl, basicAuthUserNamePassword); } /** * Create a new Atlas client. * @param baseUrls A list of URLs that point to an ensemble of Atlas servers working in * High Availability mode. The client will automatically determine the * active instance on startup and also when there is a scenario of * failover. */ public AtlasClient(String... baseUrls) throws AtlasException { this(getCurrentUGI(), baseUrls); } /** * Create a new Atlas client. * @param ugi UserGroupInformation * @param doAsUser * @param baseUrls A list of URLs that point to an ensemble of Atlas servers working in * High Availability mode. The client will automatically determine the * active instance on startup and also when there is a scenario of * failover. */ public AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls) { initializeState(baseUrls, ugi, doAsUser); } private AtlasClient(UserGroupInformation ugi, String[] baseUrls) { this(ugi, ugi.getShortUserName(), baseUrls); } //Used by LocalAtlasClient protected AtlasClient() { //Do nothing } @VisibleForTesting public AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword) { super(configuration, baseUrl, basicAuthUserNamePassword); } @VisibleForTesting public AtlasClient(Configuration configuration, String... baseUrls) throws AtlasException { initializeState(configuration, baseUrls, getCurrentUGI(), getCurrentUGI().getShortUserName()); } @VisibleForTesting AtlasClient(WebResource service, Configuration configuration) { super(service, configuration); } public WebResource getResource() { return service; } public enum API { //Admin operations VERSION(BASE_URI + ADMIN_VERSION, HttpMethod.GET, Response.Status.OK), STATUS(BASE_URI + ADMIN_STATUS, HttpMethod.GET, Response.Status.OK), //Type operations CREATE_TYPE(BASE_URI + TYPES, HttpMethod.POST, Response.Status.CREATED), UPDATE_TYPE(BASE_URI + TYPES, HttpMethod.PUT, Response.Status.OK), GET_TYPE(BASE_URI + TYPES, HttpMethod.GET, Response.Status.OK), LIST_TYPES(BASE_URI + TYPES, HttpMethod.GET, Response.Status.OK), LIST_TRAIT_TYPES(BASE_URI + TYPES + "?type=trait", HttpMethod.GET, Response.Status.OK), //Entity operations CREATE_ENTITY(BASE_URI + URI_ENTITY, HttpMethod.POST, Response.Status.CREATED), GET_ENTITY(BASE_URI + URI_ENTITY, HttpMethod.GET, Response.Status.OK), UPDATE_ENTITY(BASE_URI + URI_ENTITY, HttpMethod.PUT, Response.Status.OK), UPDATE_ENTITY_PARTIAL(BASE_URI + URI_ENTITY, HttpMethod.POST, Response.Status.OK), LIST_ENTITIES(BASE_URI + URI_ENTITY, HttpMethod.GET, Response.Status.OK), DELETE_ENTITIES(BASE_URI + URI_ENTITY, HttpMethod.DELETE, Response.Status.OK), DELETE_ENTITY(BASE_URI + URI_ENTITY, HttpMethod.DELETE, Response.Status.OK), //audit operation LIST_ENTITY_AUDIT(BASE_URI + URI_ENTITY, HttpMethod.GET, Response.Status.OK), //Trait operations ADD_TRAITS(BASE_URI + URI_ENTITY, HttpMethod.POST, Response.Status.CREATED), DELETE_TRAITS(BASE_URI + URI_ENTITY, HttpMethod.DELETE, Response.Status.OK), LIST_TRAITS(BASE_URI + URI_ENTITY, HttpMethod.GET, Response.Status.OK), GET_ALL_TRAIT_DEFINITIONS(BASE_URI + URI_ENTITY, HttpMethod.GET, Response.Status.OK), GET_TRAIT_DEFINITION(BASE_URI + URI_ENTITY, HttpMethod.GET, Response.Status.OK), //Search operations SEARCH(BASE_URI + URI_SEARCH, HttpMethod.GET, Response.Status.OK), SEARCH_DSL(BASE_URI + URI_SEARCH + "/dsl", HttpMethod.GET, Response.Status.OK), SEARCH_FULL_TEXT(BASE_URI + URI_SEARCH + "/fulltext", HttpMethod.GET, Response.Status.OK), GREMLIN_SEARCH(BASE_URI + URI_SEARCH + "/gremlin", HttpMethod.GET, Response.Status.OK), //Lineage operations based on dataset name NAME_LINEAGE_INPUTS_GRAPH(BASE_URI + URI_NAME_LINEAGE, HttpMethod.GET, Response.Status.OK), NAME_LINEAGE_OUTPUTS_GRAPH(BASE_URI + URI_NAME_LINEAGE, HttpMethod.GET, Response.Status.OK), NAME_LINEAGE_SCHEMA(BASE_URI + URI_NAME_LINEAGE, HttpMethod.GET, Response.Status.OK), //Lineage operations based on entity id of the dataset LINEAGE_INPUTS_GRAPH(BASE_URI + URI_LINEAGE, HttpMethod.GET, Response.Status.OK), LINEAGE_OUTPUTS_GRAPH(BASE_URI + URI_LINEAGE, HttpMethod.GET, Response.Status.OK), LINEAGE_SCHEMA(BASE_URI + URI_LINEAGE, HttpMethod.GET, Response.Status.OK); private final String method; private final String path; private final Response.Status status; API(String path, String method, Response.Status status) { this.path = path; this.method = method; this.status = status; } public String getMethod() { return method; } public String getPath() { return path; } public Response.Status getExpectedStatus() { return status; } } /** * Register the given type(meta model) * @param typeAsJson type definition a jaon * @return result json object * @throws AtlasServiceException */ public List<String> createType(String typeAsJson) throws AtlasServiceException { LOG.debug("Creating type definition: {}", typeAsJson); JSONObject response = callAPIWithBody(API.CREATE_TYPE, typeAsJson); List<String> results = extractResults(response, AtlasClient.TYPES, new ExtractOperation<String, JSONObject>() { @Override String extractElement(JSONObject element) throws JSONException { return element.getString(AtlasClient.NAME); } }); LOG.debug("Create type definition returned results: {}", results); return results; } /** * Register the given type(meta model) * @param typeDef type definition * @return result json object * @throws AtlasServiceException */ public List<String> createType(TypesDef typeDef) throws AtlasServiceException { return createType(TypesSerialization.toJson(typeDef)); } /** * Creates trait type with specifiedName, superTraits and attributes * @param traitName the name of the trait type * @param superTraits the list of super traits from which this trait type inherits attributes * @param attributeDefinitions the list of attributes of the trait type * @return the list of types created * @throws AtlasServiceException */ public List<String> createTraitType(String traitName, ImmutableSet<String> superTraits, AttributeDefinition... attributeDefinitions) throws AtlasServiceException { HierarchicalTypeDefinition<TraitType> piiTrait = TypesUtil.createTraitTypeDef(traitName, superTraits, attributeDefinitions); String traitDefinitionAsJSON = TypesSerialization.toJson(piiTrait, true); LOG.debug("Creating trait type {} {}" , traitName, traitDefinitionAsJSON); return createType(traitDefinitionAsJSON); } /** * Creates simple trait type with specifiedName with no superTraits or attributes * @param traitName the name of the trait type * @return the list of types created * @throws AtlasServiceException */ public List<String> createTraitType(String traitName) throws AtlasServiceException { return createTraitType(traitName, null); } /** * Register the given type(meta model) * @param typeAsJson type definition a jaon * @return result json object * @throws AtlasServiceException */ public List<String> updateType(String typeAsJson) throws AtlasServiceException { LOG.debug("Updating type definition: {}", typeAsJson); JSONObject response = callAPIWithBody(API.UPDATE_TYPE, typeAsJson); List<String> results = extractResults(response, AtlasClient.TYPES, new ExtractOperation<String, JSONObject>() { @Override String extractElement(JSONObject element) throws JSONException { return element.getString(AtlasClient.NAME); } }); LOG.debug("Update type definition returned results: {}", results); return results; } /** * Register the given type(meta model) * @param typeDef type definition * @return result json object * @throws AtlasServiceException */ public List<String> updateType(TypesDef typeDef) throws AtlasServiceException { return updateType(TypesSerialization.toJson(typeDef)); } /** * Returns all type names in the system * @return list of type names * @throws AtlasServiceException */ public List<String> listTypes() throws AtlasServiceException { final JSONObject jsonObject = callAPIWithQueryParams(API.LIST_TYPES, null); return extractResults(jsonObject, AtlasClient.RESULTS, new ExtractOperation<String, String>()); } /** * Returns all type names with the given category * @param category * @return list of type names * @throws AtlasServiceException */ public List<String> listTypes(final DataTypes.TypeCategory category) throws AtlasServiceException { JSONObject response = callAPIWithRetries(API.LIST_TYPES, null, new ResourceCreator() { @Override public WebResource createResource() { WebResource resource = getResource(API.LIST_TYPES.getPath()); resource = resource.queryParam(TYPE, category.name()); return resource; } }); return extractResults(response, AtlasClient.RESULTS, new ExtractOperation<String, String>()); } /** * Return the list of type names in the type system which match the specified filter. * * @param category returns types whose category is the given typeCategory * @param superType returns types which contain the given supertype * @param notSupertype returns types which do not contain the given supertype * * Its possible to specify combination of these filters in one request and the conditions are combined with AND * For example, typeCategory = TRAIT && supertype contains 'X' && supertype !contains 'Y' * If there is no filter, all the types are returned * @return list of type names */ public List<String> listTypes(final DataTypes.TypeCategory category, final String superType, final String notSupertype) throws AtlasServiceException { JSONObject response = callAPIWithRetries(API.LIST_TYPES, null, new ResourceCreator() { @Override public WebResource createResource() { WebResource resource = getResource(API.LIST_TYPES); resource = resource.queryParam(TYPE, category.name()); resource = resource.queryParam(SUPERTYPE, superType); resource = resource.queryParam(NOT_SUPERTYPE, notSupertype); return resource; } }); return extractResults(response, AtlasClient.RESULTS, new ExtractOperation<String, String>()); } public TypesDef getType(String typeName) throws AtlasServiceException { try { JSONObject response = callAPIWithBodyAndParams(API.GET_TYPE, null, typeName); String typeJson = response.getString(DEFINITION); return TypesSerialization.fromJson(typeJson); } catch (JSONException e) { throw new AtlasServiceException(e); } } /** * Create the given entity * @param entities entity(type instance) as json * @return json array of guids * @throws AtlasServiceException */ protected List<String> createEntity(JSONArray entities) throws AtlasServiceException { LOG.debug("Creating entities: {}", entities); JSONObject response = callAPIWithBody(API.CREATE_ENTITY, entities.toString()); List<String> results = extractEntityResult(response).getCreatedEntities(); LOG.debug("Create entities returned results: {}", results); return results; } protected EntityResult extractEntityResult(JSONObject response) throws AtlasServiceException { return EntityResult.fromString(response.toString()); } /** * Create the given entity * @param entitiesAsJson entity(type instance) as json * @return json array of guids * @throws AtlasServiceException */ public List<String> createEntity(String... entitiesAsJson) throws AtlasServiceException { return createEntity(new JSONArray(Arrays.asList(entitiesAsJson))); } public List<String> createEntity(Referenceable... entities) throws AtlasServiceException { return createEntity(Arrays.asList(entities)); } public List<String> createEntity(Collection<Referenceable> entities) throws AtlasServiceException { JSONArray entityArray = getEntitiesArray(entities); return createEntity(entityArray); } private JSONArray getEntitiesArray(Collection<Referenceable> entities) { JSONArray entityArray = new JSONArray(entities.size()); for (Referenceable entity : entities) { entityArray.put(InstanceSerialization.toJson(entity, true)); } return entityArray; } /** * Replaces entity definitions identified by their guid or unique attribute * Updates properties set in the definition for the entity corresponding to guid * @param entities entities to be updated * @return json array of guids which were updated/created * @throws AtlasServiceException */ public EntityResult updateEntities(Referenceable... entities) throws AtlasServiceException { return updateEntities(Arrays.asList(entities)); } protected EntityResult updateEntities(JSONArray entities) throws AtlasServiceException { LOG.debug("Updating entities: {}", entities); JSONObject response = callAPIWithBody(API.UPDATE_ENTITY, entities.toString()); EntityResult results = extractEntityResult(response); LOG.debug("Update entities returned results: {}", results); return results; } public EntityResult updateEntities(Collection<Referenceable> entities) throws AtlasServiceException { JSONArray entitiesArray = getEntitiesArray(entities); return updateEntities(entitiesArray); } /** * Supports Partial updates * Updates property for the entity corresponding to guid * @param guid guid * @param attribute property key * @param value property value */ public EntityResult updateEntityAttribute(final String guid, final String attribute, String value) throws AtlasServiceException { LOG.debug("Updating entity id: {}, attribute name: {}, attribute value: {}", guid, attribute, value); JSONObject response = callAPIWithRetries(API.UPDATE_ENTITY_PARTIAL, value, new ResourceCreator() { @Override public WebResource createResource() { API api = API.UPDATE_ENTITY_PARTIAL; WebResource resource = getResource(api, guid); resource = resource.queryParam(ATTRIBUTE_NAME, attribute); return resource; } }); return extractEntityResult(response); } /** * Supports Partial updates * Updates properties set in the definition for the entity corresponding to guid * @param guid guid * @param entity entity definition */ public EntityResult updateEntity(String guid, Referenceable entity) throws AtlasServiceException { String entityJson = InstanceSerialization.toJson(entity, true); LOG.debug("Updating entity id {} with {}", guid, entityJson); JSONObject response = callAPIWithBodyAndParams(API.UPDATE_ENTITY_PARTIAL, entityJson, guid); return extractEntityResult(response); } /** * Associate trait to an entity * * @param guid guid * @param traitDefinition trait definition */ public void addTrait(String guid, Struct traitDefinition) throws AtlasServiceException { String traitJson = InstanceSerialization.toJson(traitDefinition, true); LOG.debug("Adding trait to entity with id {} {}", guid, traitJson); callAPIWithBodyAndParams(API.ADD_TRAITS, traitJson, guid, URI_TRAITS); } /** * Delete a trait from the given entity * @param guid guid of the entity * @param traitName trait to be deleted * @throws AtlasServiceException */ public void deleteTrait(String guid, String traitName) throws AtlasServiceException { callAPIWithBodyAndParams(API.DELETE_TRAITS, null, guid, TRAITS, traitName); } /** * Supports Partial updates * Updates properties set in the definition for the entity corresponding to guid * @param entityType Type of the entity being updated * @param uniqueAttributeName Attribute Name that uniquely identifies the entity * @param uniqueAttributeValue Attribute Value that uniquely identifies the entity * @param entity entity definition */ public EntityResult updateEntity(final String entityType, final String uniqueAttributeName, final String uniqueAttributeValue, Referenceable entity) throws AtlasServiceException { final API api = API.UPDATE_ENTITY_PARTIAL; String entityJson = InstanceSerialization.toJson(entity, true); LOG.debug("Updating entity type: {}, attributeName: {}, attributeValue: {}, entity: {}", entityType, uniqueAttributeName, uniqueAttributeValue, entityJson); JSONObject response = callAPIWithRetries(api, entityJson, new ResourceCreator() { @Override public WebResource createResource() { WebResource resource = getResource(api, QUALIFIED_NAME); resource = resource.queryParam(TYPE, entityType); resource = resource.queryParam(ATTRIBUTE_NAME, uniqueAttributeName); resource = resource.queryParam(ATTRIBUTE_VALUE, uniqueAttributeValue); return resource; } }); EntityResult result = extractEntityResult(response); LOG.debug("Update entity returned result: {}", result); return result; } protected String getString(JSONObject jsonObject, String parameter) throws AtlasServiceException { try { return jsonObject.getString(parameter); } catch (JSONException e) { throw new AtlasServiceException(e); } } /** * Delete the specified entities from the repository * * @param guids guids of entities to delete * @return List of entity ids updated/deleted * @throws AtlasServiceException */ public EntityResult deleteEntities(final String ... guids) throws AtlasServiceException { LOG.debug("Deleting entities: {}", guids); JSONObject jsonResponse = callAPIWithRetries(API.DELETE_ENTITIES, null, new ResourceCreator() { @Override public WebResource createResource() { API api = API.DELETE_ENTITIES; WebResource resource = getResource(api); for (String guid : guids) { resource = resource.queryParam(GUID.toLowerCase(), guid); } return resource; } }); EntityResult results = extractEntityResult(jsonResponse); LOG.debug("Delete entities returned results: {}", results); return results; } /** * Supports Deletion of an entity identified by its unique attribute value * @param entityType Type of the entity being deleted * @param uniqueAttributeName Attribute Name that uniquely identifies the entity * @param uniqueAttributeValue Attribute Value that uniquely identifies the entity * @return List of entity ids updated/deleted(including composite references from that entity) */ public EntityResult deleteEntity(String entityType, String uniqueAttributeName, String uniqueAttributeValue) throws AtlasServiceException { LOG.debug("Deleting entity type: {}, attributeName: {}, attributeValue: {}", entityType, uniqueAttributeName, uniqueAttributeValue); API api = API.DELETE_ENTITY; WebResource resource = getResource(api); resource = resource.queryParam(TYPE, entityType); resource = resource.queryParam(ATTRIBUTE_NAME, uniqueAttributeName); resource = resource.queryParam(ATTRIBUTE_VALUE, uniqueAttributeValue); JSONObject jsonResponse = callAPIWithResource(API.DELETE_ENTITIES, resource); EntityResult results = extractEntityResult(jsonResponse); LOG.debug("Delete entities returned results: {}", results); return results; } /** * Get an entity given the entity id * @param guid entity id * @return result object * @throws AtlasServiceException */ public Referenceable getEntity(String guid) throws AtlasServiceException { JSONObject jsonResponse = callAPIWithBodyAndParams(API.GET_ENTITY, null, guid); try { String entityInstanceDefinition = jsonResponse.getString(AtlasClient.DEFINITION); return InstanceSerialization.fromJsonReferenceable(entityInstanceDefinition, true); } catch (JSONException e) { throw new AtlasServiceException(API.GET_ENTITY, e); } } public static String toString(JSONArray jsonArray) throws JSONException { ArrayList<String> resultsList = new ArrayList<>(); for (int index = 0; index < jsonArray.length(); index++) { resultsList.add(jsonArray.getString(index)); } return StringUtils.join(resultsList, ","); } /** * Get an entity given the entity id * @param entityType entity type name * @param attribute qualified name of the entity * @param value * @return result object * @throws AtlasServiceException */ public Referenceable getEntity(final String entityType, final String attribute, final String value) throws AtlasServiceException { JSONObject jsonResponse = callAPIWithRetries(API.GET_ENTITY, null, new ResourceCreator() { @Override public WebResource createResource() { WebResource resource = getResource(API.GET_ENTITY); resource = resource.queryParam(TYPE, entityType); resource = resource.queryParam(ATTRIBUTE_NAME, attribute); resource = resource.queryParam(ATTRIBUTE_VALUE, value); return resource; } }); try { String entityInstanceDefinition = jsonResponse.getString(AtlasClient.DEFINITION); return InstanceSerialization.fromJsonReferenceable(entityInstanceDefinition, true); } catch (JSONException e) { throw new AtlasServiceException(API.GET_ENTITY, e); } } /** * List entities for a given entity type * @param entityType * @return * @throws AtlasServiceException */ public List<String> listEntities(final String entityType) throws AtlasServiceException { JSONObject jsonResponse = callAPIWithRetries(API.LIST_ENTITIES, null, new ResourceCreator() { @Override public WebResource createResource() { WebResource resource = getResource(API.LIST_ENTITIES); resource = resource.queryParam(TYPE, entityType); return resource; } }); return extractResults(jsonResponse, AtlasClient.RESULTS, new ExtractOperation<String, String>()); } /** * List traits for a given entity identified by its GUID * @param guid GUID of the entity * @return List<String> - traitnames associated with entity * @throws AtlasServiceException */ public List<String> listTraits(final String guid) throws AtlasServiceException { JSONObject jsonResponse = callAPIWithBodyAndParams(API.LIST_TRAITS, null, guid, URI_TRAITS); return extractResults(jsonResponse, AtlasClient.RESULTS, new ExtractOperation<String, String>()); } /** * Get all trait definitions for an entity * @param guid GUID of the entity * @return List<String> trait definitions of the traits associated to the entity * @throws AtlasServiceException */ public List<Struct> listTraitDefinitions(final String guid) throws AtlasServiceException{ JSONObject jsonResponse = callAPIWithBodyAndParams(API.GET_ALL_TRAIT_DEFINITIONS, null, guid, TRAIT_DEFINITIONS); List<JSONObject> traitDefList = extractResults(jsonResponse, AtlasClient.RESULTS, new ExtractOperation<JSONObject, JSONObject>()); ArrayList<Struct> traitStructList = new ArrayList<>(); for(JSONObject traitDef:traitDefList){ Struct traitStruct = InstanceSerialization.fromJsonStruct(traitDef.toString(), true); traitStructList.add(traitStruct); } return traitStructList; } /** * Get trait definition for a given entity and traitname * @param guid GUID of the entity * @param traitName * @return trait definition * @throws AtlasServiceException */ public Struct getTraitDefinition(final String guid, final String traitName) throws AtlasServiceException{ JSONObject jsonResponse = callAPIWithBodyAndParams(API.GET_TRAIT_DEFINITION, null, guid, TRAIT_DEFINITIONS, traitName); try { return InstanceSerialization.fromJsonStruct(jsonResponse.getString(AtlasClient.RESULTS), false); }catch (JSONException e){ throw new AtlasServiceException(API.GET_TRAIT_DEFINITION, e); } } protected class ExtractOperation<T, U> { T extractElement(U element) throws JSONException { return (T) element; } } protected <T, U> List<T> extractResults(JSONObject jsonResponse, String key, ExtractOperation<T, U> extractInterafce) throws AtlasServiceException { try { JSONArray results = jsonResponse.getJSONArray(key); ArrayList<T> resultsList = new ArrayList<>(); for (int index = 0; index < results.length(); index++) { Object element = results.get(index); resultsList.add(extractInterafce.extractElement((U) element)); } return resultsList; } catch (JSONException e) { throw new AtlasServiceException(e); } } /** * Get the latest numResults entity audit events in decreasing order of timestamp for the given entity id * @param entityId entity id * @param numResults number of results to be returned * @return list of audit events for the entity id * @throws AtlasServiceException */ public List<EntityAuditEvent> getEntityAuditEvents(String entityId, short numResults) throws AtlasServiceException { return getEntityAuditEvents(entityId, null, numResults); } /** * Get the entity audit events in decreasing order of timestamp for the given entity id * @param entityId entity id * @param startKey key for the first event to be returned, used for pagination * @param numResults number of results to be returned * @return list of audit events for the entity id * @throws AtlasServiceException */ public List<EntityAuditEvent> getEntityAuditEvents(String entityId, String startKey, short numResults) throws AtlasServiceException { WebResource resource = getResource(API.LIST_ENTITY_AUDIT, entityId, URI_ENTITY_AUDIT); if (StringUtils.isNotEmpty(startKey)) { resource = resource.queryParam(START_KEY, startKey); } resource = resource.queryParam(NUM_RESULTS, String.valueOf(numResults)); JSONObject jsonResponse = callAPIWithResource(API.LIST_ENTITY_AUDIT, resource); return extractResults(jsonResponse, AtlasClient.EVENTS, new ExtractOperation<EntityAuditEvent, JSONObject>() { @Override EntityAuditEvent extractElement(JSONObject element) throws JSONException { return SerDe.GSON.fromJson(element.toString(), EntityAuditEvent.class); } }); } /** * Search using dsl/full text * @param searchQuery * @param limit number of rows to be returned in the result, used for pagination. maxlimit > limit > 0. -1 maps to atlas.search.defaultlimit property value * @param offset offset to the results returned, used for pagination. offset >= 0. -1 maps to offset 0 * @return Query results * @throws AtlasServiceException */ public JSONArray search(final String searchQuery, final int limit, final int offset) throws AtlasServiceException { JSONObject result = callAPIWithRetries(API.SEARCH, null, new ResourceCreator() { @Override public WebResource createResource() { WebResource resource = getResource(API.SEARCH); resource = resource.queryParam(QUERY, searchQuery); resource = resource.queryParam(LIMIT, String.valueOf(limit)); resource = resource.queryParam(OFFSET, String.valueOf(offset)); return resource; } }); try { return result.getJSONArray(RESULTS); } catch (JSONException e) { throw new AtlasServiceException(e); } } /** * Search given query DSL * @param query DSL query * @param limit number of rows to be returned in the result, used for pagination. maxlimit > limit > 0. -1 maps to atlas.search.defaultlimit property value * @param offset offset to the results returned, used for pagination. offset >= 0. -1 maps to offset 0 * @return result json object * @throws AtlasServiceException */ public JSONArray searchByDSL(final String query, final int limit, final int offset) throws AtlasServiceException { LOG.debug("DSL query: {}", query); JSONObject result = callAPIWithRetries(API.SEARCH_DSL, null, new ResourceCreator() { @Override public WebResource createResource() { WebResource resource = getResource(API.SEARCH_DSL); resource = resource.queryParam(QUERY, query); resource = resource.queryParam(LIMIT, String.valueOf(limit)); resource = resource.queryParam(OFFSET, String.valueOf(offset)); return resource; } }); try { return result.getJSONArray(RESULTS); } catch (JSONException e) { throw new AtlasServiceException(e); } } /** * Search given full text search * @param query Query * @param limit number of rows to be returned in the result, used for pagination. maxlimit > limit > 0. -1 maps to atlas.search.defaultlimit property value * @param offset offset to the results returned, used for pagination. offset >= 0. -1 maps to offset 0 * @return result json object * @throws AtlasServiceException */ public JSONObject searchByFullText(final String query, final int limit, final int offset) throws AtlasServiceException { return callAPIWithRetries(API.SEARCH_FULL_TEXT, null, new ResourceCreator() { @Override public WebResource createResource() { WebResource resource = getResource(API.SEARCH_FULL_TEXT); resource = resource.queryParam(QUERY, query); resource = resource.queryParam(LIMIT, String.valueOf(limit)); resource = resource.queryParam(OFFSET, String.valueOf(offset)); return resource; } }); } public JSONObject getInputGraph(String datasetName) throws AtlasServiceException { JSONObject response = callAPIWithBodyAndParams(API.NAME_LINEAGE_INPUTS_GRAPH, null, datasetName, "/inputs/graph"); try { return response.getJSONObject(AtlasClient.RESULTS); } catch (JSONException e) { throw new AtlasServiceException(e); } } public JSONObject getOutputGraph(String datasetName) throws AtlasServiceException { JSONObject response = callAPIWithBodyAndParams(API.NAME_LINEAGE_OUTPUTS_GRAPH, null, datasetName, "/outputs/graph"); try { return response.getJSONObject(AtlasClient.RESULTS); } catch (JSONException e) { throw new AtlasServiceException(e); } } public JSONObject getInputGraphForEntity(String entityId) throws AtlasServiceException { JSONObject response = callAPIWithBodyAndParams(API.LINEAGE_INPUTS_GRAPH, null, entityId, "/inputs/graph"); try { return response.getJSONObject(AtlasClient.RESULTS); } catch (JSONException e) { throw new AtlasServiceException(e); } } public JSONObject getOutputGraphForEntity(String datasetId) throws AtlasServiceException { JSONObject response = callAPIWithBodyAndParams(API.LINEAGE_OUTPUTS_GRAPH, null, datasetId, "/outputs/graph"); try { return response.getJSONObject(AtlasClient.RESULTS); } catch (JSONException e) { throw new AtlasServiceException(e); } } public JSONObject getSchemaForEntity(String datasetId) throws AtlasServiceException { JSONObject response = callAPIWithBodyAndParams(API.LINEAGE_OUTPUTS_GRAPH, null, datasetId, "/schema"); try { return response.getJSONObject(AtlasClient.RESULTS); } catch (JSONException e) { throw new AtlasServiceException(e); } } // Wrapper methods for compatibility @VisibleForTesting public JSONObject callAPIWithResource(API api, WebResource resource) throws AtlasServiceException { return callAPIWithResource(toAPIInfo(api), resource, null, JSONObject.class); } @VisibleForTesting public WebResource getResource(API api, String ... params) { return getResource(toAPIInfo(api), params); } @VisibleForTesting public JSONObject callAPIWithBody(API api, Object requestObject) throws AtlasServiceException { return callAPI(toAPIInfo(api), JSONObject.class, requestObject, (String[]) null); } @VisibleForTesting public JSONObject callAPIWithBodyAndParams(API api, Object requestObject, String ... params) throws AtlasServiceException { return callAPI(toAPIInfo(api), JSONObject.class, requestObject, params); } @VisibleForTesting public JSONObject callAPIWithQueryParams(API api, MultivaluedMap<String, String> queryParams) throws AtlasServiceException { return callAPI(toAPIInfo(api), JSONObject.class, queryParams); } @VisibleForTesting JSONObject callAPIWithRetries(API api, Object requestObject, ResourceCreator resourceCreator) throws AtlasServiceException { return super.callAPIWithRetries(toAPIInfo(api), requestObject, resourceCreator); } private APIInfo toAPIInfo(API api){ return new APIInfo(api.getPath(), api.getMethod(), api.getExpectedStatus()); } } <|start_filename|>typesystem/src/main/java/org/apache/atlas/typesystem/persistence/StructInstance.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.typesystem.persistence; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.apache.atlas.AtlasException; import org.apache.atlas.typesystem.ITypedStruct; import org.apache.atlas.typesystem.types.AttributeInfo; import org.apache.atlas.typesystem.types.ClassType; import org.apache.atlas.typesystem.types.DataTypes; import org.apache.atlas.typesystem.types.EnumType; import org.apache.atlas.typesystem.types.EnumValue; import org.apache.atlas.typesystem.types.FieldMapping; import org.apache.atlas.typesystem.types.StructType; import org.apache.atlas.typesystem.types.TypeSystem; import org.apache.atlas.typesystem.types.ValueConversionException; import org.apache.atlas.utils.SHA256Utils; import java.math.BigDecimal; import java.math.BigInteger; import java.security.MessageDigest; import java.util.Date; import java.util.HashMap; import java.util.Map; public class StructInstance implements ITypedStruct { public final String dataTypeName; public final FieldMapping fieldMapping; public final boolean nullFlags[]; public final boolean explicitSets[]; public final boolean[] bools; public final byte[] bytes; public final short[] shorts; public final int[] ints; public final long[] longs; public final float[] floats; public final double[] doubles; public final BigDecimal[] bigDecimals; public final BigInteger[] bigIntegers; public final Date[] dates; public final String[] strings; public final ImmutableList<Object>[] arrays; public final ImmutableMap<Object, Object>[] maps; public final StructInstance[] structs; public final ReferenceableInstance[] referenceables; public final Id[] ids; public StructInstance(String dataTypeName, FieldMapping fieldMapping, boolean[] nullFlags, boolean[] explicitSets, boolean[] bools, byte[] bytes, short[] shorts, int[] ints, long[] longs, float[] floats, double[] doubles, BigDecimal[] bigDecimals, BigInteger[] bigIntegers, Date[] dates, String[] strings, ImmutableList<Object>[] arrays, ImmutableMap<Object, Object>[] maps, StructInstance[] structs, ReferenceableInstance[] referenceables, Id[] ids) { assert dataTypeName != null; this.dataTypeName = dataTypeName; this.fieldMapping = fieldMapping; this.nullFlags = nullFlags; this.explicitSets = explicitSets; this.bools = bools; this.bytes = bytes; this.shorts = shorts; this.ints = ints; this.longs = longs; this.floats = floats; this.doubles = doubles; this.bigDecimals = bigDecimals; this.bigIntegers = bigIntegers; this.dates = dates; this.strings = strings; this.arrays = arrays; this.maps = maps; this.structs = structs; this.referenceables = referenceables; this.ids = ids; for (int i = 0; i < nullFlags.length; i++) { nullFlags[i] = true; } for (int i = 0; i < explicitSets.length; i++) { explicitSets[i] = false; } } @Override public String getTypeName() { return dataTypeName; } @Override public FieldMapping fieldMapping() { return fieldMapping; } public void set(String attrName, Object val) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new ValueConversionException(getTypeName(), val, "Unknown field " + attrName); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); Object cVal = null; explicitSets[nullPos] = true; if (val != null && val instanceof Id) { ClassType clsType = TypeSystem.getInstance().getDataType(ClassType.class, i.dataType().getName()); clsType.validateId((Id) val); cVal = val; } else { try { cVal = i.dataType().convert(val, i.multiplicity); } catch(ValueConversionException.NullConversionException e) { throw new ValueConversionException.NullConversionException("For field '" + attrName + "'", e); } } if (cVal == null) { nullFlags[nullPos] = true; return; } nullFlags[nullPos] = false; if (i.dataType() == DataTypes.BOOLEAN_TYPE) { bools[pos] = (Boolean) cVal; } else if (i.dataType() == DataTypes.BYTE_TYPE) { bytes[pos] = (Byte) cVal; } else if (i.dataType() == DataTypes.SHORT_TYPE) { shorts[pos] = (Short) cVal; } else if (i.dataType() == DataTypes.INT_TYPE) { ints[pos] = (Integer) cVal; } else if (i.dataType() == DataTypes.LONG_TYPE) { longs[pos] = (Long) cVal; } else if (i.dataType() == DataTypes.FLOAT_TYPE) { floats[pos] = (Float) cVal; } else if (i.dataType() == DataTypes.DOUBLE_TYPE) { doubles[pos] = (Double) cVal; } else if (i.dataType() == DataTypes.BIGINTEGER_TYPE) { bigIntegers[pos] = (BigInteger) cVal; } else if (i.dataType() == DataTypes.BIGDECIMAL_TYPE) { bigDecimals[pos] = (BigDecimal) cVal; } else if (i.dataType() == DataTypes.DATE_TYPE) { dates[pos] = (Date) cVal; } else if (i.dataType() == DataTypes.STRING_TYPE) { strings[pos] = (String) cVal; } else if (i.dataType().getTypeCategory() == DataTypes.TypeCategory.ENUM) { ints[pos] = ((EnumValue) cVal).ordinal; } else if (i.dataType().getTypeCategory() == DataTypes.TypeCategory.ARRAY) { arrays[pos] = (ImmutableList) cVal; } else if (i.dataType().getTypeCategory() == DataTypes.TypeCategory.MAP) { maps[pos] = (ImmutableMap) cVal; } else if (i.dataType().getTypeCategory() == DataTypes.TypeCategory.STRUCT || i.dataType().getTypeCategory() == DataTypes.TypeCategory.TRAIT) { structs[pos] = (StructInstance) cVal; } else if (i.dataType().getTypeCategory() == DataTypes.TypeCategory.CLASS) { if (cVal instanceof Id) { ids[pos] = (Id) cVal; } else { referenceables[pos] = (ReferenceableInstance) cVal; } } else { throw new AtlasException(String.format("Unknown datatype %s", i.dataType())); } } public Object get(String attrName) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); if (nullFlags[nullPos]) { if ( i.dataType().getTypeCategory() == DataTypes.TypeCategory.PRIMITIVE) { return ((DataTypes.PrimitiveType) i.dataType()).nullValue(); } else { return null; } } if (i.dataType() == DataTypes.BOOLEAN_TYPE) { return bools[pos]; } else if (i.dataType() == DataTypes.BYTE_TYPE) { return bytes[pos]; } else if (i.dataType() == DataTypes.SHORT_TYPE) { return shorts[pos]; } else if (i.dataType() == DataTypes.INT_TYPE) { return ints[pos]; } else if (i.dataType() == DataTypes.LONG_TYPE) { return longs[pos]; } else if (i.dataType() == DataTypes.FLOAT_TYPE) { return floats[pos]; } else if (i.dataType() == DataTypes.DOUBLE_TYPE) { return doubles[pos]; } else if (i.dataType() == DataTypes.BIGINTEGER_TYPE) { return bigIntegers[pos]; } else if (i.dataType() == DataTypes.BIGDECIMAL_TYPE) { return bigDecimals[pos]; } else if (i.dataType() == DataTypes.DATE_TYPE) { return dates[pos]; } else if (i.dataType() == DataTypes.STRING_TYPE) { return strings[pos]; } else if (i.dataType().getTypeCategory() == DataTypes.TypeCategory.ENUM) { return ((EnumType) i.dataType()).fromOrdinal(ints[pos]); } else if (i.dataType().getTypeCategory() == DataTypes.TypeCategory.ARRAY) { return arrays[pos]; } else if (i.dataType().getTypeCategory() == DataTypes.TypeCategory.MAP) { return maps[pos]; } else if (i.dataType().getTypeCategory() == DataTypes.TypeCategory.STRUCT || i.dataType().getTypeCategory() == DataTypes.TypeCategory.TRAIT) { return structs[pos]; } else if (i.dataType().getTypeCategory() == DataTypes.TypeCategory.CLASS) { if (ids[pos] != null) { return ids[pos]; } else { return referenceables[pos]; } } else { throw new AtlasException(String.format("Unknown datatype %s", i.dataType())); } } public void setNull(String attrName) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } int nullPos = fieldMapping.fieldNullPos.get(attrName); nullFlags[nullPos] = true; explicitSets[nullPos] = true; int pos = fieldMapping.fieldPos.get(attrName); if (i.dataType() == DataTypes.BIGINTEGER_TYPE) { bigIntegers[pos] = null; } else if (i.dataType() == DataTypes.BIGDECIMAL_TYPE) { bigDecimals[pos] = null; } else if (i.dataType() == DataTypes.DATE_TYPE) { dates[pos] = null; } else if (i.dataType() == DataTypes.INT_TYPE) { ints[pos] = 0; } else if (i.dataType() == DataTypes.BOOLEAN_TYPE) { bools[pos] = false; } else if (i.dataType() == DataTypes.STRING_TYPE) { strings[pos] = null; } else if (i.dataType().getTypeCategory() == DataTypes.TypeCategory.ARRAY) { arrays[pos] = null; } else if (i.dataType().getTypeCategory() == DataTypes.TypeCategory.MAP) { maps[pos] = null; } else if (i.dataType().getTypeCategory() == DataTypes.TypeCategory.STRUCT || i.dataType().getTypeCategory() == DataTypes.TypeCategory.TRAIT) { structs[pos] = null; } else if (i.dataType().getTypeCategory() == DataTypes.TypeCategory.CLASS) { ids[pos] = null; referenceables[pos] = null; } else { throw new AtlasException(String.format("Unknown datatype %s", i.dataType())); } } /* * Use only for json serialization * @nonpublic */ @Override public Map<String, Object> getValuesMap() throws AtlasException { Map<String, Object> m = new HashMap<>(); for (String attr : fieldMapping.fields.keySet()) { // int pos = fieldMapping.fieldNullPos.get(attr); // if ( explicitSets[pos] ) { m.put(attr, get(attr)); // } } return m; } public boolean getBoolean(String attrName) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } if (i.dataType() != DataTypes.BOOLEAN_TYPE) { throw new AtlasException( String.format("Field %s for Struct %s is not a %s, call generic get method", attrName, getTypeName(), DataTypes.BOOLEAN_TYPE.getName())); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); if (nullFlags[nullPos]) { return DataTypes.BOOLEAN_TYPE.nullValue(); } return bools[pos]; } public byte getByte(String attrName) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } if (i.dataType() != DataTypes.BYTE_TYPE) { throw new AtlasException( String.format("Field %s for Struct %s is not a %s, call generic get method", attrName, getTypeName(), DataTypes.BYTE_TYPE.getName())); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); if (nullFlags[nullPos]) { return DataTypes.BYTE_TYPE.nullValue(); } return bytes[pos]; } public short getShort(String attrName) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } if (i.dataType() != DataTypes.SHORT_TYPE) { throw new AtlasException( String.format("Field %s for Struct %s is not a %s, call generic get method", attrName, getTypeName(), DataTypes.SHORT_TYPE.getName())); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); if (nullFlags[nullPos]) { return DataTypes.SHORT_TYPE.nullValue(); } return shorts[pos]; } public int getInt(String attrName) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } if (i.dataType() != DataTypes.INT_TYPE && !(i.dataType() instanceof EnumType)) { throw new AtlasException( String.format("Field %s for Struct %s is not a %s, call generic get method", attrName, getTypeName(), DataTypes.INT_TYPE.getName())); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); if (nullFlags[nullPos]) { return DataTypes.INT_TYPE.nullValue(); } return ints[pos]; } public long getLong(String attrName) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } if (i.dataType() != DataTypes.LONG_TYPE) { throw new AtlasException( String.format("Field %s for Struct %s is not a %s, call generic get method", attrName, getTypeName(), DataTypes.LONG_TYPE.getName())); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); if (nullFlags[nullPos]) { return DataTypes.LONG_TYPE.nullValue(); } return longs[pos]; } public float getFloat(String attrName) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } if (i.dataType() != DataTypes.FLOAT_TYPE) { throw new AtlasException( String.format("Field %s for Struct %s is not a %s, call generic get method", attrName, getTypeName(), DataTypes.FLOAT_TYPE.getName())); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); if (nullFlags[nullPos]) { return DataTypes.FLOAT_TYPE.nullValue(); } return floats[pos]; } public double getDouble(String attrName) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } if (i.dataType() != DataTypes.DOUBLE_TYPE) { throw new AtlasException( String.format("Field %s for Struct %s is not a %s, call generic get method", attrName, getTypeName(), DataTypes.DOUBLE_TYPE.getName())); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); if (nullFlags[nullPos]) { return DataTypes.DOUBLE_TYPE.nullValue(); } return doubles[pos]; } public BigInteger getBigInt(String attrName) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } if (i.dataType() != DataTypes.BIGINTEGER_TYPE) { throw new AtlasException( String.format("Field %s for Struct %s is not a %s, call generic get method", attrName, getTypeName(), DataTypes.BIGINTEGER_TYPE.getName())); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); if (nullFlags[nullPos]) { return DataTypes.BIGINTEGER_TYPE.nullValue(); } return bigIntegers[pos]; } public BigDecimal getBigDecimal(String attrName) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } if (i.dataType() != DataTypes.BIGDECIMAL_TYPE) { throw new AtlasException( String.format("Field %s for Struct %s is not a %s, call generic get method", attrName, getTypeName(), DataTypes.BIGDECIMAL_TYPE.getName())); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); if (nullFlags[nullPos]) { return DataTypes.BIGDECIMAL_TYPE.nullValue(); } return bigDecimals[pos]; } public Date getDate(String attrName) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } if (i.dataType() != DataTypes.DATE_TYPE) { throw new AtlasException( String.format("Field %s for Struct %s is not a %s, call generic get method", attrName, getTypeName(), DataTypes.DATE_TYPE.getName())); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); if (nullFlags[nullPos]) { return DataTypes.DATE_TYPE.nullValue(); } return dates[pos]; } public String getString(String attrName) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } if (i.dataType() != DataTypes.STRING_TYPE) { throw new AtlasException( String.format("Field %s for Struct %s is not a %s, call generic get method", attrName, getTypeName(), DataTypes.STRING_TYPE.getName())); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); if (nullFlags[nullPos]) { return DataTypes.STRING_TYPE.nullValue(); } return strings[pos]; } public void setBoolean(String attrName, boolean val) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } if (i.dataType() != DataTypes.BOOLEAN_TYPE) { throw new AtlasException( String.format("Field %s for Struct %s is not a %s, call generic set method", attrName, getTypeName(), DataTypes.BOOLEAN_TYPE.getName())); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); nullFlags[nullPos] = false; bools[pos] = val; explicitSets[nullPos] = true; } public void setByte(String attrName, byte val) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } if (i.dataType() != DataTypes.BYTE_TYPE) { throw new AtlasException( String.format("Field %s for Struct %s is not a %s, call generic set method", attrName, getTypeName(), DataTypes.BYTE_TYPE.getName())); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); nullFlags[nullPos] = false; bytes[pos] = val; explicitSets[nullPos] = true; } public void setShort(String attrName, short val) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } if (i.dataType() != DataTypes.SHORT_TYPE) { throw new AtlasException( String.format("Field %s for Struct %s is not a %s, call generic set method", attrName, getTypeName(), DataTypes.SHORT_TYPE.getName())); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); nullFlags[nullPos] = false; shorts[pos] = val; explicitSets[nullPos] = true; } public void setInt(String attrName, int val) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } if (i.dataType() != DataTypes.INT_TYPE && !(i.dataType() instanceof EnumType)) { throw new AtlasException( String.format("Field %s for Struct %s is not a %s, call generic set method", attrName, getTypeName(), DataTypes.INT_TYPE.getName())); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); nullFlags[nullPos] = false; ints[pos] = val; explicitSets[nullPos] = true; } public void setLong(String attrName, long val) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } if (i.dataType() != DataTypes.LONG_TYPE) { throw new AtlasException( String.format("Field %s for Struct %s is not a %s, call generic set method", attrName, getTypeName(), DataTypes.LONG_TYPE.getName())); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); nullFlags[nullPos] = false; longs[pos] = val; explicitSets[nullPos] = true; } public void setFloat(String attrName, float val) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } if (i.dataType() != DataTypes.FLOAT_TYPE) { throw new AtlasException( String.format("Field %s for Struct %s is not a %s, call generic set method", attrName, getTypeName(), DataTypes.FLOAT_TYPE.getName())); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); nullFlags[nullPos] = false; floats[pos] = val; explicitSets[nullPos] = true; } public void setDouble(String attrName, double val) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } if (i.dataType() != DataTypes.DOUBLE_TYPE) { throw new AtlasException( String.format("Field %s for Struct %s is not a %s, call generic set method", attrName, getTypeName(), DataTypes.DOUBLE_TYPE.getName())); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); nullFlags[nullPos] = false; doubles[pos] = val; explicitSets[nullPos] = true; } public void setBigInt(String attrName, BigInteger val) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } if (i.dataType() != DataTypes.BIGINTEGER_TYPE) { throw new AtlasException( String.format("Field %s for Struct %s is not a %s, call generic set method", attrName, getTypeName(), DataTypes.BIGINTEGER_TYPE.getName())); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); nullFlags[nullPos] = val == null; bigIntegers[pos] = val; explicitSets[nullPos] = true; } public void setBigDecimal(String attrName, BigDecimal val) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } if (i.dataType() != DataTypes.BIGDECIMAL_TYPE) { throw new AtlasException( String.format("Field %s for Struct %s is not a %s, call generic set method", attrName, getTypeName(), DataTypes.BIGDECIMAL_TYPE.getName())); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); nullFlags[nullPos] = val == null; bigDecimals[pos] = val; explicitSets[nullPos] = true; } public void setDate(String attrName, Date val) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } if (i.dataType() != DataTypes.DATE_TYPE) { throw new AtlasException( String.format("Field %s for Struct %s is not a %s, call generic set method", attrName, getTypeName(), DataTypes.DATE_TYPE.getName())); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); nullFlags[nullPos] = val == null; dates[pos] = val; explicitSets[nullPos] = true; } public void setString(String attrName, String val) throws AtlasException { AttributeInfo i = fieldMapping.fields.get(attrName); if (i == null) { throw new AtlasException(String.format("Unknown field %s for Struct %s", attrName, getTypeName())); } if (i.dataType() != DataTypes.STRING_TYPE) { throw new AtlasException( String.format("Field %s for Struct %s is not a %s, call generic set method", attrName, getTypeName(), DataTypes.STRING_TYPE.getName())); } int pos = fieldMapping.fieldPos.get(attrName); int nullPos = fieldMapping.fieldNullPos.get(attrName); nullFlags[nullPos] = val == null; strings[pos] = val; explicitSets[nullPos] = true; } @Override public String toString() { try { StringBuilder buf = new StringBuilder(); String prefix = ""; fieldMapping.output(this, buf, prefix, null); return buf.toString(); } catch (AtlasException me) { throw new RuntimeException(me); } } @Override public String getSignatureHash(MessageDigest digester) throws AtlasException { StructType structType = TypeSystem.getInstance().getDataType(StructType.class, getTypeName()); structType.updateSignatureHash(digester, this); byte[] digest = digester.digest(); return SHA256Utils.toString(digest); } @Override public boolean isValueSet(final String attrName) throws AtlasException { int nullPos = fieldMapping.fieldNullPos.get(attrName); return explicitSets[nullPos]; } @Override public String toShortString() { return String.format("struct[type=%s]", dataTypeName); } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/graph/FullTextMapper.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graph; import org.apache.atlas.AtlasException; import org.apache.atlas.RequestContext; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.typesystem.ITypedInstance; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.persistence.Id; import org.apache.atlas.typesystem.types.AttributeInfo; import org.apache.atlas.typesystem.types.DataTypes; import org.apache.atlas.typesystem.types.EnumValue; import org.apache.atlas.typesystem.types.IDataType; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.Map; @Deprecated public class FullTextMapper { private static final Logger LOG = LoggerFactory.getLogger(FullTextMapper.class); private final GraphToTypedInstanceMapper graphToTypedInstanceMapper; private final TypedInstanceToGraphMapper typedInstanceToGraphMapper; private static final GraphHelper graphHelper = GraphHelper.getInstance(); private static final String FULL_TEXT_DELIMITER = " "; public FullTextMapper(TypedInstanceToGraphMapper typedInstanceToGraphMapper, GraphToTypedInstanceMapper graphToTypedInstanceMapper) { this.graphToTypedInstanceMapper = graphToTypedInstanceMapper; this.typedInstanceToGraphMapper = typedInstanceToGraphMapper; } public String mapRecursive(AtlasVertex instanceVertex, boolean followReferences) throws AtlasException { String guid = GraphHelper.getGuid(instanceVertex); ITypedReferenceableInstance typedReference; RequestContext context = RequestContext.get(); typedReference = context.getInstanceV1(guid); if (typedReference != null) { if (LOG.isDebugEnabled()) { LOG.debug("Cache hit: guid = {}, entityId = {}", guid, typedReference.getId()._getId()); } } else { typedReference = graphToTypedInstanceMapper.mapGraphToTypedInstance(guid, instanceVertex); context.cache(typedReference); if (LOG.isDebugEnabled()) { LOG.debug("Cache miss: guid = {}, entityId = {}", guid, typedReference.getId().getId()); } } String fullText = forInstance(typedReference, followReferences); StringBuilder fullTextBuilder = new StringBuilder(typedReference.getTypeName()).append(FULL_TEXT_DELIMITER).append(fullText); List<String> traits = typedReference.getTraits(); for (String traitName : traits) { String traitText = forInstance((ITypedInstance) typedReference.getTrait(traitName), false); fullTextBuilder.append(FULL_TEXT_DELIMITER).append(traitName).append(FULL_TEXT_DELIMITER) .append(traitText); } return fullTextBuilder.toString(); } private String forAttribute(IDataType type, Object value, boolean followReferences) throws AtlasException { if (value == null) { return null; } switch (type.getTypeCategory()) { case PRIMITIVE: return String.valueOf(value); case ENUM: return ((EnumValue) value).value; case ARRAY: StringBuilder fullText = new StringBuilder(); IDataType elemType = ((DataTypes.ArrayType) type).getElemType(); List list = (List) value; for (Object element : list) { String elemFullText = forAttribute(elemType, element, false); if (StringUtils.isNotEmpty(elemFullText)) { fullText = fullText.append(FULL_TEXT_DELIMITER).append(elemFullText); } } return fullText.toString(); case MAP: fullText = new StringBuilder(); IDataType keyType = ((DataTypes.MapType) type).getKeyType(); IDataType valueType = ((DataTypes.MapType) type).getValueType(); Map map = (Map) value; for (Object entryObj : map.entrySet()) { Map.Entry entry = (Map.Entry) entryObj; String keyFullText = forAttribute(keyType, entry.getKey(), false); if (StringUtils.isNotEmpty(keyFullText)) { fullText = fullText.append(FULL_TEXT_DELIMITER).append(keyFullText); } String valueFullText = forAttribute(valueType, entry.getValue(), false); if (StringUtils.isNotEmpty(valueFullText)) { fullText = fullText.append(FULL_TEXT_DELIMITER).append(valueFullText); } } return fullText.toString(); case CLASS: if (followReferences) { Id refId = ((ITypedReferenceableInstance) value).getId(); String refGuid = refId._getId(); AtlasVertex refVertex = typedInstanceToGraphMapper.lookupVertex(refId); if(refVertex == null) { refVertex = graphHelper.getVertexForGUID(refGuid); } return mapRecursive(refVertex, false); } break; case STRUCT: if (followReferences) { return forInstance((ITypedInstance) value, true); } break; default: throw new IllegalStateException("Unhandled type category " + type.getTypeCategory()); } return null; } private String forInstance(ITypedInstance typedInstance, boolean followReferences) throws AtlasException { StringBuilder fullText = new StringBuilder(); for (AttributeInfo attributeInfo : typedInstance.fieldMapping().fields.values()) { Object attrValue = typedInstance.get(attributeInfo.name); if (attrValue == null) { continue; } String attrFullText = forAttribute(attributeInfo.dataType(), attrValue, followReferences); if (StringUtils.isNotEmpty(attrFullText)) { fullText = fullText.append(FULL_TEXT_DELIMITER).append(attributeInfo.name).append(FULL_TEXT_DELIMITER) .append(attrFullText); } } return fullText.toString(); } } <|start_filename|>graphdb/titan1/src/main/java/org/apache/atlas/repository/graphdb/titan1/serializer/BigDecimalSerializer.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan1.serializer; import java.math.BigDecimal; import java.math.BigInteger; import com.thinkaurelius.titan.core.attribute.AttributeSerializer; import com.thinkaurelius.titan.diskstorage.ScanBuffer; import com.thinkaurelius.titan.diskstorage.WriteBuffer; /** * Serializer for BigDecimal values. */ public class BigDecimalSerializer implements AttributeSerializer<BigDecimal> { private final BigIntegerSerializer bigIntegerDelegate = new BigIntegerSerializer(); @Override public BigDecimal read(ScanBuffer buffer) { BigInteger unscaledVal = bigIntegerDelegate.read(buffer); int scale = buffer.getInt(); return new BigDecimal(unscaledVal, scale); } @Override public void write(WriteBuffer buffer, BigDecimal attribute) { BigInteger unscaledVal = attribute.unscaledValue(); int scale = attribute.scale(); bigIntegerDelegate.write(buffer, unscaledVal); buffer.putInt(scale); } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/converters/AtlasStructFormatConverter.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.converters; import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.AtlasException; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.TypeCategory; import org.apache.atlas.model.instance.AtlasStruct; import org.apache.atlas.type.AtlasStructType; import org.apache.atlas.type.AtlasStructType.AtlasAttribute; import org.apache.atlas.type.AtlasType; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.typesystem.IStruct; import org.apache.atlas.typesystem.Struct; import org.apache.commons.collections.MapUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; public class AtlasStructFormatConverter extends AtlasAbstractFormatConverter { private static final Logger LOG = LoggerFactory.getLogger(AtlasStructFormatConverter.class); public static final String ATTRIBUTES_PROPERTY_KEY = "attributes"; public AtlasStructFormatConverter(AtlasFormatConverters registry, AtlasTypeRegistry typeRegistry) { this(registry, typeRegistry, TypeCategory.STRUCT); } protected AtlasStructFormatConverter(AtlasFormatConverters registry, AtlasTypeRegistry typeRegistry, TypeCategory typeCategory) { super(registry, typeRegistry, typeCategory); } @Override public Object fromV1ToV2(Object v1Obj, AtlasType type, ConverterContext converterContext) throws AtlasBaseException { AtlasStruct ret = null; if (v1Obj != null) { AtlasStructType structType = (AtlasStructType)type; if (v1Obj instanceof Map) { final Map v1Map = (Map) v1Obj; final Map v1Attribs = (Map) v1Map.get(ATTRIBUTES_PROPERTY_KEY); if (MapUtils.isNotEmpty(v1Attribs)) { ret = new AtlasStruct(type.getTypeName(), fromV1ToV2(structType, v1Attribs, converterContext)); } else { ret = new AtlasStruct(type.getTypeName()); } } else if (v1Obj instanceof IStruct) { IStruct struct = (IStruct) v1Obj; Map<String, Object> v1Attribs = null; try { v1Attribs = struct.getValuesMap(); } catch (AtlasException excp) { LOG.error("IStruct.getValuesMap() failed", excp); } ret = new AtlasStruct(type.getTypeName(), fromV1ToV2(structType, v1Attribs, converterContext)); } else { throw new AtlasBaseException(AtlasErrorCode.UNEXPECTED_TYPE, "Map or IStruct", v1Obj.getClass().getCanonicalName()); } } return ret; } @Override public Object fromV2ToV1(Object v2Obj, AtlasType type, ConverterContext converterContext) throws AtlasBaseException { Struct ret = null; if (v2Obj != null) { AtlasStructType structType = (AtlasStructType)type; if (v2Obj instanceof Map) { final Map v2Map = (Map) v2Obj; final Map v2Attribs; if (v2Map.containsKey(ATTRIBUTES_PROPERTY_KEY)) { v2Attribs = (Map) v2Map.get(ATTRIBUTES_PROPERTY_KEY); } else { v2Attribs = v2Map; } if (MapUtils.isNotEmpty(v2Attribs)) { ret = new Struct(type.getTypeName(), fromV2ToV1(structType, v2Attribs, converterContext)); } else { ret = new Struct(type.getTypeName()); } } else if (v2Obj instanceof AtlasStruct) { AtlasStruct struct = (AtlasStruct) v2Obj; ret = new Struct(type.getTypeName(), fromV2ToV1(structType, struct.getAttributes(), converterContext)); } else { throw new AtlasBaseException(AtlasErrorCode.UNEXPECTED_TYPE, "Map or AtlasStruct", v2Obj.getClass().getCanonicalName()); } } return ret; } protected Map<String, Object> fromV2ToV1(AtlasStructType structType, Map<String, Object> attributes, ConverterContext context) throws AtlasBaseException { Map<String, Object> ret = null; if (MapUtils.isNotEmpty(attributes)) { ret = new HashMap<>(); // Only process the requested/set attributes for (String attrName : attributes.keySet()) { AtlasAttribute attr = structType.getAttribute(attrName); if (attr == null) { LOG.warn("ignored unknown attribute {}.{}", structType.getTypeName(), attrName); continue; } AtlasType attrType = attr.getAttributeType(); Object v2Value = attributes.get(attr.getName()); Object v1Value; AtlasFormatConverter attrConverter = converterRegistry.getConverter(attrType.getTypeCategory()); v1Value = attrConverter.fromV2ToV1(v2Value, attrType, context); ret.put(attr.getName(), v1Value); } } return ret; } protected Map<String, Object> fromV1ToV2(AtlasStructType structType, Map attributes, ConverterContext context) throws AtlasBaseException { Map<String, Object> ret = null; if (MapUtils.isNotEmpty(attributes)) { ret = new HashMap<>(); // Only process the requested/set attributes for (Object attribKey : attributes.keySet()) { String attrName = attribKey.toString(); AtlasAttribute attr = structType.getAttribute(attrName); if (attr == null) { LOG.warn("ignored unknown attribute {}.{}", structType.getTypeName(), attrName); continue; } AtlasType attrType = attr.getAttributeType(); AtlasFormatConverter attrConverter = converterRegistry.getConverter(attrType.getTypeCategory()); Object v1Value = attributes.get(attr.getName()); Object v2Value = attrConverter.fromV1ToV2(v1Value, attrType, context); ret.put(attr.getAttributeDef().getName(), v2Value); } } return ret; } } <|start_filename|>notification/src/test/java/org/apache/atlas/kafka/KafkaNotificationTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.kafka; import org.apache.atlas.ApplicationProperties; import org.apache.atlas.notification.NotificationConsumer; import org.apache.atlas.notification.NotificationInterface; import org.apache.atlas.notification.hook.HookNotification; import org.apache.atlas.typesystem.Referenceable; import org.apache.commons.configuration.Configuration; import org.apache.commons.lang.RandomStringUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.apache.atlas.notification.hook.HookNotification.HookNotificationMessage; import java.util.List; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class KafkaNotificationTest { private KafkaNotification kafkaNotification; @BeforeClass public void setup() throws Exception { Configuration properties = ApplicationProperties.get(); properties.setProperty("atlas.kafka.data", "target/" + RandomStringUtils.randomAlphanumeric(5)); kafkaNotification = new KafkaNotification(properties); kafkaNotification.start(); } @AfterClass public void shutdown() throws Exception { kafkaNotification.close(); kafkaNotification.stop(); } @Test public void testReceiveKafkaMessages() throws Exception { kafkaNotification.send(NotificationInterface.NotificationType.HOOK, new HookNotification.EntityCreateRequest("u1", new Referenceable("type"))); kafkaNotification.send(NotificationInterface.NotificationType.HOOK, new HookNotification.EntityCreateRequest("u2", new Referenceable("type"))); kafkaNotification.send(NotificationInterface.NotificationType.HOOK, new HookNotification.EntityCreateRequest("u3", new Referenceable("type"))); kafkaNotification.send(NotificationInterface.NotificationType.HOOK, new HookNotification.EntityCreateRequest("u4", new Referenceable("type"))); NotificationConsumer<Object> consumer = kafkaNotification.createConsumers(NotificationInterface.NotificationType.HOOK, 1).get(0); List<AtlasKafkaMessage<Object>> messages = null ; long startTime = System.currentTimeMillis(); //fetch starting time while ((System.currentTimeMillis() - startTime) < 10000) { messages = consumer.receive(); if (messages.size() > 0) { break; } } int i=1; for (AtlasKafkaMessage<Object> msg : messages){ HookNotification.HookNotificationMessage message = (HookNotificationMessage) msg.getMessage(); assertEquals(message.getUser(), "u"+i++); } consumer.close(); } } <|start_filename|>typesystem/src/test/java/org/apache/atlas/typesystem/types/StructTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.typesystem.types; import com.google.common.collect.ImmutableList; import org.apache.atlas.AtlasException; import org.apache.atlas.typesystem.ITypedStruct; import org.apache.atlas.typesystem.Struct; import org.apache.atlas.typesystem.TypesDef; import org.apache.atlas.typesystem.types.utils.TypesUtil; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.testng.Assert.assertTrue; public class StructTest extends TypeUpdateBaseTest { StructType structType; StructType recursiveStructType; StructType invalidStructType; @BeforeMethod public void setup() throws Exception { super.setup(); structType = getTypeSystem().getDataType(StructType.class, STRUCT_TYPE_1); recursiveStructType = getTypeSystem().getDataType(StructType.class, STRUCT_TYPE_2); invalidStructType = getTypeSystem().getDataType(StructType.class, STRUCT_TYPE_3); } @Test public void test1() throws AtlasException { Struct s = createStruct(); ITypedStruct ts = structType.convert(s, Multiplicity.REQUIRED); Assert.assertEquals(ts.toString(), "{\n" + "\ta : \t1\n" + "\tb : \ttrue\n" + "\tc : \t1\n" + "\td : \t2\n" + "\te : \t1\n" + "\tf : \t1\n" + "\tg : \t1\n" + "\th : \t1.0\n" + "\ti : \t1.0\n" + "\tj : \t1\n" + "\tk : \t1\n" + "\tl : \t" + TEST_DATE + "\n" + "\tm : \t[1, 1]\n" + "\tn : \t[1.1, 1.1]\n" + "\to : \t{a=1.0, b=2.0}\n" + "\tp : \t\n" + "\tq : \t<null>\n"+ "\tr : \t{a=}\n" + "}"); } @Test public void testStructWithEmptyString() throws AtlasException{ try { assertTrue(getTypeSystem().getTypeNames().contains("t3")); Struct s = new Struct(invalidStructType.getName()); s.set("a", ""); ITypedStruct ts = invalidStructType.convert(s, Multiplicity.REQUIRED); } catch (AtlasException e){ String err = "org.apache.atlas.typesystem.types.ValueConversionException: Cannot convert value 'org.apache.atlas.typesystem.Struct@1ba02' to datatype t3"; Assert.assertEquals(e.toString(), err); } } @Test public void testRecursive() throws AtlasException { Struct s1 = new Struct(recursiveStructType.getName()); s1.set("a", 1); Struct s2 = new Struct(recursiveStructType.getName()); s2.set("a", 1); s2.set("s", s1); ITypedStruct ts = recursiveStructType.convert(s2, Multiplicity.REQUIRED); Assert.assertEquals(ts.toString(), "{\n" + "\ta : \t1\n" + "\ts : \t{\n" + "\t\ta : \t\t1\n" + "\t\ts : <null>\n" + "\n" + "\t}\n" + "}"); } @Test public void testTypeUpdate() throws Exception { testTypeUpdateForAttributes(); } @Override protected int getNumberOfFields(TypeSystem ts, String typeName) throws Exception { return ts.getDataType(StructType.class, typeName).numFields; } @Override protected StructTypeDefinition getTypeDefinition(String name, AttributeDefinition... attributes) { return new StructTypeDefinition(name, attributes); } @Override protected TypesDef getTypesDef(StructTypeDefinition typeDefinition) { return TypesUtil.getTypesDef(ImmutableList.<EnumTypeDefinition>of(), ImmutableList.of(typeDefinition), ImmutableList.<HierarchicalTypeDefinition<TraitType>>of(), ImmutableList.<HierarchicalTypeDefinition<ClassType>>of()); } } <|start_filename|>graphdb/titan1/src/main/java/org/apache/atlas/repository/graphdb/titan1/Titan1PropertyKey.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan1; import org.apache.atlas.repository.graphdb.AtlasCardinality; import org.apache.atlas.repository.graphdb.AtlasPropertyKey; import com.thinkaurelius.titan.core.PropertyKey; /** * */ public class Titan1PropertyKey implements AtlasPropertyKey { private PropertyKey wrapped; public Titan1PropertyKey(PropertyKey toWrap) { wrapped = toWrap; } /* (non-Javadoc) * @see org.apache.atlas.repository.graphdb.AtlasPropertyKey#getName() */ @Override public String getName() { return wrapped.name(); } /** * @return */ public PropertyKey getWrappedPropertyKey() { return wrapped; } @Override public int hashCode() { int result = 17; result = 37*result + wrapped.hashCode(); return result; } @Override public boolean equals(Object other) { if (!(other instanceof Titan1PropertyKey)) { return false; } Titan1PropertyKey otherKey = (Titan1PropertyKey)other; return otherKey.getWrappedPropertyKey().equals(getWrappedPropertyKey()); } /* (non-Javadoc) * @see org.apache.atlas.repository.graphdb.AtlasPropertyKey#getCardinality() */ @Override public AtlasCardinality getCardinality() { return GraphDbObjectFactory.createCardinality(wrapped.cardinality()); } } <|start_filename|>dashboardv2/public/js/collection/VCatalogList.js<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(['require', 'utils/Globals', 'collection/BaseCollection', 'models/VCatalog', 'utils/UrlLinks' ], function(require, Globals, BaseCollection, VCatalog, UrlLinks) { 'use strict'; var VCatalogList = BaseCollection.extend( //Prototypal attributes { url: UrlLinks.taxonomiesApiUrl(), model: VCatalog, initialize: function() { this.modelName = 'VCatalog'; this.modelAttrName = ''; }, fetch: function(options) { //Call Backbone's fetch return Backbone.Collection.prototype.fetch.call(this, options); }, parseRecords: function(resp, options) { try { /* var arr = []; arr.push({ taxonomies: resp });*/ return resp; } catch (e) { console.log(e); } }, }, //Static Class Members { /** * Table Cols to be passed to Backgrid * UI has to use this as base and extend this. * */ tableCols: {} } ); return VCatalogList; }); <|start_filename|>graphdb/titan1/src/main/java/org/apache/atlas/repository/graphdb/titan1/Titan1VertexQuery.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan1; import com.google.common.base.Preconditions; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasEdgeDirection; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.repository.graphdb.AtlasVertexQuery; import com.thinkaurelius.titan.core.TitanVertexQuery; /** * Titan 1.0.0 implementation of AtlasVertexQuery. */ public class Titan1VertexQuery implements AtlasVertexQuery<Titan1Vertex, Titan1Edge> { private Titan1Graph graph; private TitanVertexQuery<?> query; public Titan1VertexQuery(Titan1Graph graph, TitanVertexQuery<?> query) { this.query = query; this.graph = graph; } @Override public AtlasVertexQuery<Titan1Vertex, Titan1Edge> direction(AtlasEdgeDirection queryDirection) { query.direction(TitanObjectFactory.createDirection(queryDirection)); return this; } @Override public Iterable<AtlasVertex<Titan1Vertex, Titan1Edge>> vertices() { Iterable vertices = query.vertices(); return graph.wrapVertices(vertices); } @Override public Iterable<AtlasVertex<Titan1Vertex, Titan1Edge>> vertices(int limit) { Preconditions.checkArgument(limit >=0, "Limit should be greater than or equals to 0"); Iterable vertices = query.limit(limit).vertices(); return graph.wrapVertices(vertices); } @Override public Iterable<AtlasEdge<Titan1Vertex, Titan1Edge>> edges() { Iterable edges = query.edges(); return graph.wrapEdges(edges); } @Override public Iterable<AtlasEdge<Titan1Vertex, Titan1Edge>> edges(int limit) { Preconditions.checkArgument(limit >=0, "Limit should be greater than or equals to 0"); Iterable edges = query.limit(limit).edges(); return graph.wrapEdges(edges); } @Override public long count() { return query.count(); } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/typestore/TypePersistenceVisitor.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.typestore; import static org.apache.atlas.repository.graph.GraphHelper.setProperty; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.atlas.AtlasException; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.RepositoryException; import org.apache.atlas.repository.graph.GraphHelper; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.typesystem.types.AttributeInfo; import org.apache.atlas.typesystem.types.DataTypes.TypeCategory; import org.apache.atlas.typesystem.types.EnumType; import org.apache.atlas.typesystem.types.EnumValue; import org.apache.atlas.typesystem.types.HierarchicalType; import org.apache.atlas.typesystem.types.IDataType; import org.apache.atlas.typesystem.types.TypeSystem; import org.codehaus.jettison.json.JSONException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * TypeVisitor implementation that completes the type storage process by * adding the required properties and edges to the type vertices * that were created. */ public class TypePersistenceVisitor implements TypeVisitor { private static final Logger LOG = LoggerFactory.getLogger(TypePersistenceVisitor.class); private static final GraphHelper graphHelper = GraphHelper.getInstance(); private final GraphBackedTypeStore typeStore_; private final Map<String,AtlasVertex> typeVertices; private final TypeSystem typeSystem; /** * @param graphBackedTypeStore */ public TypePersistenceVisitor(GraphBackedTypeStore graphBackedTypeStore, Map<String,AtlasVertex> typeVertices, TypeSystem typeSystem) { typeStore_ = graphBackedTypeStore; this.typeVertices = typeVertices; this.typeSystem = typeSystem; } @Override public void visitEnumeration(EnumType dataType) throws AtlasException { AtlasVertex vertex = typeVertices.get(dataType.getName()); List<String> values = new ArrayList<>(dataType.values().size()); for (EnumValue enumValue : dataType.values()) { String key = GraphBackedTypeStore.getPropertyKey(dataType.getName(), enumValue.value); setProperty(vertex, key, enumValue.ordinal); values.add(enumValue.value); } setProperty(vertex, GraphBackedTypeStore.getPropertyKey(dataType.getName()), values); } @Override public void visitAttributeDataType(String typeName, AttributeInfo attribute, IDataType attrType) throws AtlasException { AtlasVertex vertex = typeVertices.get(typeName); String vertexTypeName = GraphHelper.getSingleValuedProperty(vertex, Constants.TYPENAME_PROPERTY_KEY, String.class); AtlasVertex attrVertex = typeVertices.get(attrType.getName()); String label = GraphBackedTypeStore.getEdgeLabel(vertexTypeName, attribute.name); graphHelper.getOrCreateEdge(vertex, attrVertex, label); } @Override public void visitSuperType(String typeName, String superTypeName) throws AtlasException { AtlasVertex vertex = typeVertices.get(typeName); HierarchicalType superType = typeSystem.getDataType(HierarchicalType.class, superTypeName); AtlasVertex superVertex = typeVertices.get(superTypeName); graphHelper.getOrCreateEdge(vertex, superVertex, GraphBackedTypeStore.SUPERTYPE_EDGE_LABEL); } @Override public void visitAttributeNames(String typeName, List<String> attrNames) throws AtlasException { AtlasVertex vertex = typeVertices.get(typeName); setProperty(vertex, GraphBackedTypeStore.getPropertyKey(typeName), attrNames); } @Override public void visitAttribute(String typeName, AttributeInfo attribute) throws AtlasException { AtlasVertex vertex = typeVertices.get(typeName); String propertyKey = GraphBackedTypeStore.getPropertyKey(typeName, attribute.name); try { setProperty(vertex, propertyKey, attribute.toJson()); } catch (JSONException e) { throw new StorageException(typeName, e); } } @Override public void visitDataType(TypeCategory category, String typeName, String typeDescription) { //nothing to do } } <|start_filename|>webapp/src/test/java/org/apache/atlas/web/integration/EntityLineageJerseyResourceIT.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.web.integration; import com.google.common.collect.ImmutableList; import com.google.gson.Gson; import com.sun.jersey.core.util.MultivaluedMapImpl; import org.apache.atlas.AtlasClient; import org.apache.atlas.model.instance.AtlasEntityHeader; import org.apache.atlas.model.lineage.AtlasLineageInfo; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.persistence.Id; import org.codehaus.jettison.json.JSONObject; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import java.util.List; import java.util.Map; import java.util.Set; import static org.apache.atlas.AtlasBaseClient.APIInfo; /** * Entity Lineage v2 Integration Tests. */ public class EntityLineageJerseyResourceIT extends DataSetLineageJerseyResourceIT { private static final String BASE_URI = "api/atlas/v2/lineage"; private static final APIInfo LINEAGE_V2_API = new APIInfo(BASE_URI, "GET", Response.Status.OK); private static final String INPUT_DIRECTION = "INPUT"; private static final String OUTPUT_DIRECTION = "OUTPUT"; private static final String BOTH_DIRECTION = "BOTH"; private static final String DIRECTION_PARAM = "direction"; private static final String DEPTH_PARAM = "depth"; private String salesFactTable; private String salesMonthlyTable; private String salesDBName; Gson gson = new Gson(); @BeforeClass public void setUp() throws Exception { super.setUp(); createTypeDefinitionsV1(); setupInstances(); } @Test public void testInputLineageInfo() throws Exception { String tableId = atlasClientV1.getEntity(HIVE_TABLE_TYPE, AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, salesMonthlyTable).getId()._getId(); MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); queryParams.add(DIRECTION_PARAM, INPUT_DIRECTION); queryParams.add(DEPTH_PARAM, "5"); JSONObject response = atlasClientV1.callAPI(LINEAGE_V2_API, JSONObject.class, queryParams, tableId); Assert.assertNotNull(response); System.out.println("input lineage info = " + response ); AtlasLineageInfo inputLineageInfo = gson.fromJson(response.toString(), AtlasLineageInfo.class); Map<String, AtlasEntityHeader> entities = inputLineageInfo.getGuidEntityMap(); Assert.assertNotNull(entities); Set<AtlasLineageInfo.LineageRelation> relations = inputLineageInfo.getRelations(); Assert.assertNotNull(relations); Assert.assertEquals(entities.size(), 6); Assert.assertEquals(relations.size(), 5); Assert.assertEquals(inputLineageInfo.getLineageDirection(), AtlasLineageInfo.LineageDirection.INPUT); Assert.assertEquals(inputLineageInfo.getLineageDepth(), 5); Assert.assertEquals(inputLineageInfo.getBaseEntityGuid(), tableId); } @Test public void testOutputLineageInfo() throws Exception { String tableId = atlasClientV1.getEntity(HIVE_TABLE_TYPE, AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, salesFactTable).getId()._getId(); MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); queryParams.add(DIRECTION_PARAM, OUTPUT_DIRECTION); queryParams.add(DEPTH_PARAM, "5"); JSONObject response = atlasClientV1.callAPI(LINEAGE_V2_API, JSONObject.class, queryParams, tableId); Assert.assertNotNull(response); System.out.println("output lineage info = " + response); AtlasLineageInfo outputLineageInfo = gson.fromJson(response.toString(), AtlasLineageInfo.class); Map<String, AtlasEntityHeader> entities = outputLineageInfo.getGuidEntityMap(); Assert.assertNotNull(entities); Set<AtlasLineageInfo.LineageRelation> relations = outputLineageInfo.getRelations(); Assert.assertNotNull(relations); Assert.assertEquals(entities.size(), 5); Assert.assertEquals(relations.size(), 4); Assert.assertEquals(outputLineageInfo.getLineageDirection(), AtlasLineageInfo.LineageDirection.OUTPUT); Assert.assertEquals(outputLineageInfo.getLineageDepth(), 5); Assert.assertEquals(outputLineageInfo.getBaseEntityGuid(), tableId); } @Test public void testLineageInfo() throws Exception { String tableId = atlasClientV1.getEntity(HIVE_TABLE_TYPE, AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, salesMonthlyTable).getId()._getId(); MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); queryParams.add(DIRECTION_PARAM, BOTH_DIRECTION); queryParams.add(DEPTH_PARAM, "5"); JSONObject response = atlasClientV1.callAPI(LINEAGE_V2_API, JSONObject.class, queryParams, tableId); Assert.assertNotNull(response); System.out.println("both lineage info = " + response); AtlasLineageInfo bothLineageInfo = gson.fromJson(response.toString(), AtlasLineageInfo.class); Map<String, AtlasEntityHeader> entities = bothLineageInfo.getGuidEntityMap(); Assert.assertNotNull(entities); Set<AtlasLineageInfo.LineageRelation> relations = bothLineageInfo.getRelations(); Assert.assertNotNull(relations); Assert.assertEquals(entities.size(), 6); Assert.assertEquals(relations.size(), 5); Assert.assertEquals(bothLineageInfo.getLineageDirection(), AtlasLineageInfo.LineageDirection.BOTH); Assert.assertEquals(bothLineageInfo.getLineageDepth(), 5); Assert.assertEquals(bothLineageInfo.getBaseEntityGuid(), tableId); } private void setupInstances() throws Exception { salesDBName = "Sales" + randomString(); Id salesDB = database(salesDBName, "Sales Database", "<NAME>", "hdfs://host:8000/apps/warehouse/sales"); List<Referenceable> salesFactColumns = ImmutableList .of(column("time_id", "int", "time id"), column("product_id", "int", "product id"), column("customer_id", "int", "customer id"), column("sales", "double", "product id")); salesFactTable = "sales_fact" + randomString(); Id salesFact = table(salesFactTable, "sales fact table", salesDB, "Joe", "MANAGED", salesFactColumns); List<Referenceable> timeDimColumns = ImmutableList .of(column("time_id", "int", "time id"), column("dayOfYear", "int", "day Of Year"), column("weekDay", "int", "week Day")); Id timeDim = table("time_dim" + randomString(), "time dimension table", salesDB, "<NAME>", "EXTERNAL", timeDimColumns); Id reportingDB = database("Reporting" + randomString(), "reporting database", "Jane BI", "hdfs://host:8000/apps/warehouse/reporting"); Id salesFactDaily = table("sales_fact_daily_mv" + randomString(), "sales fact daily materialized view", reportingDB, "Joe BI", "MANAGED", salesFactColumns); loadProcess("loadSalesDaily" + randomString(), "John ETL", ImmutableList.of(salesFact, timeDim), ImmutableList.of(salesFactDaily), "create table as select ", "plan", "id", "graph"); salesMonthlyTable = "sales_fact_monthly_mv" + randomString(); Id salesFactMonthly = table(salesMonthlyTable, "sales fact monthly materialized view", reportingDB, "Jane BI", "MANAGED", salesFactColumns); loadProcess("loadSalesMonthly" + randomString(), "John ETL", ImmutableList.of(salesFactDaily), ImmutableList.of(salesFactMonthly), "create table as select ", "plan", "id", "graph"); } } <|start_filename|>repository/src/test/java/org/apache/atlas/discovery/DataSetLineageServiceTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.discovery; import com.google.common.collect.ImmutableList; import org.apache.atlas.AtlasException; import org.apache.atlas.BaseRepositoryTest; import org.apache.atlas.TestModules; import org.apache.atlas.model.legacy.EntityResult; import org.apache.atlas.query.QueryParams; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.Struct; import org.apache.atlas.typesystem.exception.EntityNotFoundException; import org.apache.atlas.typesystem.json.InstanceSerialization; import org.apache.atlas.typesystem.persistence.Id; import org.apache.commons.collections.ArrayStack; import org.apache.commons.lang.RandomStringUtils; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Guice; import org.testng.annotations.Test; import javax.inject.Inject; import java.util.Arrays; import java.util.List; import java.util.Map; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; /** * Unit tests for Hive LineageService. */ @Guice(modules = TestModules.TestOnlyModule.class) public class DataSetLineageServiceTest extends BaseRepositoryTest { @Inject private DiscoveryService discoveryService; @Inject private DataSetLineageService lineageService; @BeforeClass public void setUp() throws Exception { super.setUp(); } @AfterClass public void tearDown() throws Exception { super.tearDown(); } @DataProvider(name = "dslQueriesProvider") private Object[][] createDSLQueries() { return new String[][]{ // joins {"hive_table where name=\"sales_fact\", columns"}, {"hive_table where name=\"sales_fact\", columns select name, dataType, comment"}, {"hive_table where name=\"sales_fact\", columns as c select c.name, c.dataType, c.comment"}, // {"hive_db as db where (db.name=\"Reporting\"), hive_table as table select db.name, // table.name"}, {"from hive_db"}, {"hive_db"}, {"hive_db where hive_db.name=\"Reporting\""}, {"hive_db hive_db.name = \"Reporting\""}, {"hive_db where hive_db.name=\"Reporting\" select name, owner"}, {"hive_db has name"}, // {"hive_db, hive_table"}, // {"hive_db, hive_process has name"}, // {"hive_db as db1, hive_table where db1.name = \"Reporting\""}, // {"hive_db where hive_db.name=\"Reporting\" and hive_db.createTime < " + System // .currentTimeMillis()}, {"from hive_table"}, {"hive_table"}, {"hive_table is Dimension"}, {"hive_column where hive_column isa PII"}, // {"hive_column where hive_column isa PII select hive_column.name"}, {"hive_column select hive_column.name"}, {"hive_column select name"}, {"hive_column where hive_column.name=\"customer_id\""}, {"from hive_table select hive_table.name"}, {"hive_db where (name = \"Reporting\")"}, {"hive_db where (name = \"Reporting\") select name as _col_0, owner as _col_1"}, {"hive_db where hive_db has name"}, // {"hive_db hive_table"}, {"hive_db where hive_db has name"}, // {"hive_db as db1 hive_table where (db1.name = \"Reporting\")"}, {"hive_db where (name = \"Reporting\") select name as _col_0, (createTime + 1) as _col_1 "}, // {"hive_db where (name = \"Reporting\") and ((createTime + 1) > 0)"}, // {"hive_db as db1 hive_table as tab where ((db1.createTime + 1) > 0) and (db1.name = // \"Reporting\") select db1.name as dbName, tab.name as tabName"}, // {"hive_db as db1 hive_table as tab where ((db1.createTime + 1) > 0) or (db1.name = // \"Reporting\") select db1.name as dbName, tab.name as tabName"}, // {"hive_db as db1 hive_table as tab where ((db1.createTime + 1) > 0) and (db1.name = // \"Reporting\") or db1 has owner select db1.name as dbName, tab.name as tabName"}, // {"hive_db as db1 hive_table as tab where ((db1.createTime + 1) > 0) and (db1.name = // \"Reporting\") or db1 has owner select db1.name as dbName, tab.name as tabName"}, // trait searches {"Dimension"}, {"Fact"}, {"ETL"}, {"Metric"}, {"PII"},}; } @Test(enabled = false) public void testSearchByDSLQueries(String dslQuery) throws Exception { System.out.println("Executing dslQuery = " + dslQuery); String jsonResults = discoveryService.searchByDSL(dslQuery, new QueryParams(100, 0)); assertNotNull(jsonResults); JSONObject results = new JSONObject(jsonResults); Assert.assertEquals(results.length(), 3); System.out.println("results = " + results); Object query = results.get("query"); assertNotNull(query); JSONObject dataType = results.getJSONObject("dataType"); assertNotNull(dataType); String typeName = dataType.getString("typeName"); assertNotNull(typeName); JSONArray rows = results.getJSONArray("rows"); assertNotNull(rows); Assert.assertTrue(rows.length() >= 0); // some queries may not have any results System.out.println("query [" + dslQuery + "] returned [" + rows.length() + "] rows"); } @Test(enabled = false) public void testGetInputsGraphInvalidArguments(final String tableName, String expectedException) throws Exception { testInvalidArguments(expectedException, new Invoker() { @Override void run() throws AtlasException { lineageService.getInputsGraph(tableName); } }); } @Test(enabled = false) public void testGetInputsGraphForEntityInvalidArguments(final String tableName, String expectedException) throws Exception { testInvalidArguments(expectedException, new Invoker() { @Override void run() throws AtlasException { lineageService.getInputsGraph(tableName); } }); } @Test(enabled = false) public void testGetInputsGraph() throws Exception { JSONObject results = getInputsGraph("sales_fact_monthly_mv"); assertNotNull(results); System.out.println("inputs graph = " + results); JSONObject values = results.getJSONObject("values"); assertNotNull(values); final JSONObject vertices = values.getJSONObject("vertices"); Assert.assertEquals(vertices.length(), 4); final JSONObject edges = values.getJSONObject("edges"); Assert.assertEquals(edges.length(), 4); } @Test(enabled = false) public void testCircularLineage() throws Exception{ JSONObject results = getInputsGraph("table2"); assertNotNull(results); System.out.println("inputs graph = " + results); JSONObject values = results.getJSONObject("values"); assertNotNull(values); final JSONObject vertices = values.getJSONObject("vertices"); Assert.assertEquals(vertices.length(), 2); final JSONObject edges = values.getJSONObject("edges"); Assert.assertEquals(edges.length(), 4); } @Test(enabled = false) public void testGetInputsGraphForEntity() throws Exception { ITypedReferenceableInstance entity = repository.getEntityDefinition(HIVE_TABLE_TYPE, "name", "sales_fact_monthly_mv"); JSONObject results = new JSONObject(lineageService.getInputsGraphForEntity(entity.getId()._getId())); assertNotNull(results); System.out.println("inputs graph = " + results); JSONObject values = results.getJSONObject("values"); assertNotNull(values); final JSONObject vertices = values.getJSONObject("vertices"); Assert.assertEquals(vertices.length(), 4); final JSONObject edges = values.getJSONObject("edges"); Assert.assertEquals(edges.length(), 4); } @Test(enabled = false) public void testGetOutputsGraphInvalidArguments(final String tableName, String expectedException) throws Exception { testInvalidArguments(expectedException, new Invoker() { @Override void run() throws AtlasException { lineageService.getOutputsGraph(tableName); } }); } @Test(enabled = false) public void testGetOutputsGraphForEntityInvalidArguments(final String tableId, String expectedException) throws Exception { testInvalidArguments(expectedException, new Invoker() { @Override void run() throws AtlasException { lineageService.getOutputsGraphForEntity(tableId); } }); } @Test(enabled = false) public void testGetOutputsGraph() throws Exception { JSONObject results = getOutputsGraph("sales_fact"); assertNotNull(results); System.out.println("outputs graph = " + results); JSONObject values = results.getJSONObject("values"); assertNotNull(values); final JSONObject vertices = values.getJSONObject("vertices"); Assert.assertEquals(vertices.length(), 3); final JSONObject edges = values.getJSONObject("edges"); Assert.assertEquals(edges.length(), 4); } @Test(enabled = false) public void testGetOutputsGraphForEntity() throws Exception { ITypedReferenceableInstance entity = repository.getEntityDefinition(HIVE_TABLE_TYPE, "name", "sales_fact"); JSONObject results = new JSONObject(lineageService.getOutputsGraphForEntity(entity.getId()._getId())); assertNotNull(results); System.out.println("outputs graph = " + results); JSONObject values = results.getJSONObject("values"); assertNotNull(values); final JSONObject vertices = values.getJSONObject("vertices"); Assert.assertEquals(vertices.length(), 3); final JSONObject edges = values.getJSONObject("edges"); Assert.assertEquals(edges.length(), 4); } @DataProvider(name = "tableNamesProvider") private Object[][] tableNames() { return new String[][]{{"sales_fact", "4"}, {"time_dim", "3"}, {"sales_fact_daily_mv", "4"}, {"sales_fact_monthly_mv", "4"}}; } @Test(enabled = false) public void testGetSchema(String tableName, String expected) throws Exception { JSONObject results = getSchema(tableName); assertNotNull(results); System.out.println("columns = " + results); JSONArray rows = results.getJSONArray("rows"); Assert.assertEquals(rows.length(), Integer.parseInt(expected)); for (int index = 0; index < rows.length(); index++) { assertColumn(rows.getJSONObject(index)); } } @Test(enabled = false) public void testGetSchemaForEntity(String tableName, String expected) throws Exception { ITypedReferenceableInstance entity = repository.getEntityDefinition(HIVE_TABLE_TYPE, "name", tableName); JSONObject results = new JSONObject(lineageService.getSchemaForEntity(entity.getId()._getId())); assertNotNull(results); System.out.println("columns = " + results); JSONArray rows = results.getJSONArray("rows"); Assert.assertEquals(rows.length(), Integer.parseInt(expected)); for (int index = 0; index < rows.length(); index++) { assertColumn(rows.getJSONObject(index)); } } private void assertColumn(JSONObject jsonObject) throws JSONException { assertNotNull(jsonObject.getString("name")); assertNotNull(jsonObject.getString("comment")); assertNotNull(jsonObject.getString("dataType")); Assert.assertEquals(jsonObject.getString("$typeName$"), "hive_column"); } @Test(enabled = false) public void testGetSchemaForDBEntity() throws Exception { String dbId = getEntityId(DATASET_SUBTYPE, "name", "dataSetSubTypeInst1"); JSONObject results = new JSONObject(lineageService.getSchemaForEntity(dbId)); } @DataProvider(name = "invalidArgumentsProvider") private Object[][] arguments() { return new String[][]{{null, IllegalArgumentException.class.getName()}, {"", IllegalArgumentException.class.getName()}, {"blah", EntityNotFoundException.class.getName()}}; } abstract class Invoker { abstract void run() throws AtlasException; } public void testInvalidArguments(String expectedException, Invoker invoker) throws Exception { try { invoker.run(); fail("Expected " + expectedException); } catch(Exception e) { assertEquals(e.getClass().getName(), expectedException); } } @Test(enabled = false) public void testGetSchemaInvalidArguments(final String tableName, String expectedException) throws Exception { testInvalidArguments(expectedException, new Invoker() { @Override void run() throws AtlasException { lineageService.getSchema(tableName); } }); } @Test(enabled = false) public void testGetSchemaForEntityInvalidArguments(final String entityId, String expectedException) throws Exception { testInvalidArguments(expectedException, new Invoker() { @Override void run() throws AtlasException { lineageService.getSchemaForEntity(entityId); } }); } private JSONObject getSchema(String tableName) throws Exception { return new JSONObject(lineageService.getSchema("qualified:" + tableName)); } private JSONObject getInputsGraph(String tableName) throws Exception { return new JSONObject(lineageService.getInputsGraph("qualified:" + tableName)); } private JSONObject getOutputsGraph(String tableName) throws Exception { return new JSONObject(lineageService.getOutputsGraph("qualified:" + tableName)); } @Test(enabled = false) public void testLineageWithDelete() throws Exception { String tableName = "table" + random(); createTable(tableName, 3, true); String tableId = getEntityId(HIVE_TABLE_TYPE, "name", tableName); JSONObject results = getSchema(tableName); assertEquals(results.getJSONArray("rows").length(), 3); results = getInputsGraph(tableName); Struct resultInstance = InstanceSerialization.fromJsonStruct(results.toString(), true); Map<String, Struct> vertices = (Map) resultInstance.get("vertices"); assertEquals(vertices.size(), 2); Struct vertex = vertices.get(tableId); assertEquals(((Struct) vertex.get("vertexId")).get("state"), Id.EntityState.ACTIVE.name()); results = getOutputsGraph(tableName); assertEquals(results.getJSONObject("values").getJSONObject("vertices").length(), 2); results = new JSONObject(lineageService.getSchemaForEntity(tableId)); assertEquals(results.getJSONArray("rows").length(), 3); results = new JSONObject(lineageService.getInputsGraphForEntity(tableId)); assertEquals(results.getJSONObject("values").getJSONObject("vertices").length(), 2); results = new JSONObject(lineageService.getOutputsGraphForEntity(tableId)); assertEquals(results.getJSONObject("values").getJSONObject("vertices").length(), 2); //Delete the entity. Lineage for entity returns the same results as before. //Lineage for table name throws EntityNotFoundException EntityResult deleteResult = repository.deleteEntities(Arrays.asList(tableId)); assertTrue(deleteResult.getDeletedEntities().contains(tableId)); results = new JSONObject(lineageService.getSchemaForEntity(tableId)); assertEquals(results.getJSONArray("rows").length(), 3); results = new JSONObject(lineageService.getInputsGraphForEntity(tableId)); resultInstance = InstanceSerialization.fromJsonStruct(results.toString(), true); vertices = (Map) resultInstance.get("vertices"); assertEquals(vertices.size(), 2); vertex = vertices.get(tableId); assertEquals(((Struct) vertex.get("vertexId")).get("state"), Id.EntityState.DELETED.name()); assertEquals(results.getJSONObject("values").getJSONObject("vertices").length(), 2); results = new JSONObject(lineageService.getOutputsGraphForEntity(tableId)); assertEquals(results.getJSONObject("values").getJSONObject("vertices").length(), 2); try { getSchema(tableName); fail("Expected EntityNotFoundException"); } catch (EntityNotFoundException e) { //expected } try { getInputsGraph(tableName); fail("Expected EntityNotFoundException"); } catch (EntityNotFoundException e) { //expected } try { getOutputsGraph(tableName); fail("Expected EntityNotFoundException"); } catch (EntityNotFoundException e) { //expected } //Create table again should show new lineage createTable(tableName, 2, false); results = getSchema(tableName); assertEquals(results.getJSONArray("rows").length(), 2); results = getOutputsGraph(tableName); assertEquals(results.getJSONObject("values").getJSONObject("vertices").length(), 0); results = getInputsGraph(tableName); assertEquals(results.getJSONObject("values").getJSONObject("vertices").length(), 0); tableId = getEntityId(HIVE_TABLE_TYPE, "name", tableName); results = new JSONObject(lineageService.getSchemaForEntity(tableId)); assertEquals(results.getJSONArray("rows").length(), 2); results = new JSONObject(lineageService.getInputsGraphForEntity(tableId)); assertEquals(results.getJSONObject("values").getJSONObject("vertices").length(), 0); results = new JSONObject(lineageService.getOutputsGraphForEntity(tableId)); assertEquals(results.getJSONObject("values").getJSONObject("vertices").length(), 0); } private void createTable(String tableName, int numCols, boolean createLineage) throws Exception { String dbId = getEntityId(DATABASE_TYPE, "name", "Sales"); Id salesDB = new Id(dbId, 0, DATABASE_TYPE); //Create the entity again and schema should return the new schema List<Referenceable> columns = new ArrayStack(); for (int i = 0; i < numCols; i++) { columns.add(column("col" + random(), "int", "column descr")); } Referenceable sd = storageDescriptor("hdfs://host:8000/apps/warehouse/sales", "TextInputFormat", "TextOutputFormat", true, ImmutableList.of(column("time_id", "int", "time id"))); Id table = table(tableName, "test table", salesDB, sd, "fetl", "External", columns); if (createLineage) { Id inTable = table("table" + random(), "test table", salesDB, sd, "fetl", "External", columns); Id outTable = table("table" + random(), "test table", salesDB, sd, "fetl", "External", columns); loadProcess("process" + random(), "hive query for monthly summary", "<NAME>", ImmutableList.of(inTable), ImmutableList.of(table), "create table as select ", "plan", "id", "graph", "ETL"); loadProcess("process" + random(), "hive query for monthly summary", "<NAME>", ImmutableList.of(table), ImmutableList.of(outTable), "create table as select ", "plan", "id", "graph", "ETL"); } } private String random() { return RandomStringUtils.randomAlphanumeric(5); } private String getEntityId(String typeName, String attributeName, String attributeValue) throws Exception { return repository.getEntityDefinition(typeName, attributeName, attributeValue).getId()._getId(); } } <|start_filename|>graphdb/titan0/src/main/java/org/apache/atlas/repository/graphdb/titan0/query/Titan0GraphQuery.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan0.query; import org.apache.atlas.repository.graphdb.AtlasGraphQuery; import org.apache.atlas.repository.graphdb.titan.query.TitanGraphQuery; import org.apache.atlas.repository.graphdb.titan.query.NativeTitanGraphQuery; import org.apache.atlas.repository.graphdb.titan.query.NativeTitanQueryFactory; import org.apache.atlas.repository.graphdb.titan0.Titan0Edge; import org.apache.atlas.repository.graphdb.titan0.Titan0Graph; import org.apache.atlas.repository.graphdb.titan0.Titan0Vertex; /** * Titan 0.5.4 implementation of AtlasGraphQuery. */ public class Titan0GraphQuery extends TitanGraphQuery<Titan0Vertex, Titan0Edge> implements NativeTitanQueryFactory<Titan0Vertex, Titan0Edge> { public Titan0GraphQuery(Titan0Graph graph, boolean isChildQuery) { super(graph, isChildQuery); } public Titan0GraphQuery(Titan0Graph graph) { super(graph); } @Override public AtlasGraphQuery<Titan0Vertex, Titan0Edge> createChildQuery() { return new Titan0GraphQuery((Titan0Graph)graph, true); } @Override protected NativeTitanQueryFactory<Titan0Vertex, Titan0Edge> getQueryFactory() { return this; } @Override public NativeTitanGraphQuery<Titan0Vertex, Titan0Edge> createNativeTitanQuery() { return new NativeTitan0GraphQuery((Titan0Graph)graph); } } <|start_filename|>typesystem/src/main/java/org/apache/atlas/typesystem/persistence/AtlasSystemAttributes.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.typesystem.persistence; import org.apache.atlas.typesystem.types.TypeSystem; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class AtlasSystemAttributes { public String createdBy; public String modifiedBy; public Date createdTime; public Date modifiedTime; public SimpleDateFormat simpleDateFormat = TypeSystem.getInstance().getDateFormat(); public AtlasSystemAttributes(String createdBy, String modifiedBy, Date createdTime, Date modifiedTime){ this.createdBy = createdBy; this.modifiedBy = modifiedBy; this.createdTime = createdTime; this.modifiedTime = modifiedTime; } public AtlasSystemAttributes(){ super(); } public AtlasSystemAttributes(String createdBy, String modifiedBy, String createdTime, String modifiedTime){ this.createdBy = createdBy; this.modifiedBy = modifiedBy; try{ this.createdTime = simpleDateFormat.parse(createdTime); }catch (ParseException e){ //this.createdTime = new Date(0); } try{ this.modifiedTime = simpleDateFormat.parse(modifiedTime); }catch (ParseException e){ //this.modifiedTime = new Date(0); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AtlasSystemAttributes sys_attr = (AtlasSystemAttributes) o; if (!createdBy.equals(sys_attr.createdBy)) { return false; } if (!modifiedBy.equals(sys_attr.modifiedBy)) { return false; } if (!createdTime.equals(sys_attr.createdTime)) { return false; } if(!modifiedTime.equals(sys_attr.modifiedTime)){ return false; } return true; } @Override public int hashCode() { int result = createdBy.hashCode(); result = 31 * result + modifiedBy.hashCode(); result = 31 * result + createdTime.hashCode(); result = 31 * result + modifiedTime.hashCode(); return result; } public String getCreatedBy(){ return createdBy; } public String getModifiedBy(){ return modifiedBy; } public Date getCreatedTime(){ return createdTime; } public Date getModifiedTime(){ return modifiedTime; } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/graph/GraphBackedSearchIndexer.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graph; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import org.apache.atlas.ApplicationProperties; import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.AtlasException; import org.apache.atlas.discovery.SearchIndexer; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.ha.HAConfiguration; import org.apache.atlas.listener.ActiveStateChangeHandler; import org.apache.atlas.listener.ChangedTypeDefs; import org.apache.atlas.listener.TypeDefChangeListener; import org.apache.atlas.model.typedef.AtlasBaseTypeDef; import org.apache.atlas.model.typedef.AtlasEnumDef; import org.apache.atlas.model.typedef.AtlasStructDef; import org.apache.atlas.model.typedef.AtlasStructDef.AtlasAttributeDef; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.IndexCreationException; import org.apache.atlas.repository.IndexException; import org.apache.atlas.repository.RepositoryException; import org.apache.atlas.repository.graphdb.AtlasCardinality; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.AtlasGraphIndex; import org.apache.atlas.repository.graphdb.AtlasGraphManagement; import org.apache.atlas.repository.graphdb.AtlasPropertyKey; import org.apache.atlas.type.AtlasClassificationType; import org.apache.atlas.type.AtlasEntityType; import org.apache.atlas.type.AtlasEnumType; import org.apache.atlas.type.AtlasStructType; import org.apache.atlas.type.AtlasType; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.type.AtlasTypeUtil; import org.apache.atlas.typesystem.types.AttributeInfo; import org.apache.atlas.typesystem.types.ClassType; import org.apache.atlas.typesystem.types.DataTypes; import org.apache.atlas.typesystem.types.IDataType; import org.apache.atlas.typesystem.types.Multiplicity; import org.apache.atlas.typesystem.types.StructType; import org.apache.atlas.typesystem.types.TraitType; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.configuration.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.inject.Inject; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.*; /** * Adds index for properties of a given type when its added before any instances are added. */ @Component public class GraphBackedSearchIndexer implements SearchIndexer, ActiveStateChangeHandler, TypeDefChangeListener { private static final Logger LOG = LoggerFactory.getLogger(GraphBackedSearchIndexer.class); private static final List<Class> VERTEX_INDEX_EXCLUSIONS = new ArrayList() { { add(Boolean.class); add(BigDecimal.class); add(BigInteger.class); } }; // Added for type lookup when indexing the new typedefs private final AtlasTypeRegistry typeRegistry; //allows injection of a dummy graph for testing private IAtlasGraphProvider provider; private boolean recomputeIndexedKeys = true; private Set<String> vertexIndexKeys = new HashSet<>(); @Inject public GraphBackedSearchIndexer(AtlasTypeRegistry typeRegistry) throws AtlasException { this(new AtlasGraphProvider(), ApplicationProperties.get(), typeRegistry); } @VisibleForTesting GraphBackedSearchIndexer( IAtlasGraphProvider provider, Configuration configuration, AtlasTypeRegistry typeRegistry) throws IndexException, RepositoryException { this.provider = provider; this.typeRegistry = typeRegistry; if (!HAConfiguration.isHAEnabled(configuration)) { initialize(provider.get()); } } /** * Initializes the indices for the graph - create indices for Global AtlasVertex Keys */ private void initialize() throws RepositoryException, IndexException { initialize(provider.get()); } /** * Initializes the indices for the graph - create indices for Global AtlasVertex Keys */ private void initialize(AtlasGraph graph) throws RepositoryException, IndexException { AtlasGraphManagement management = graph.getManagementSystem(); try { if (management.containsPropertyKey(Constants.VERTEX_TYPE_PROPERTY_KEY)) { LOG.info("Global indexes already exist for graph"); management.commit(); return; } /* This is called only once, which is the first time Atlas types are made indexable .*/ LOG.info("Indexes do not exist, Creating indexes for graph."); management.createVertexIndex(Constants.VERTEX_INDEX, Constants.BACKING_INDEX, Collections.<AtlasPropertyKey>emptyList()); management.createEdgeIndex(Constants.EDGE_INDEX, Constants.BACKING_INDEX); // create a composite index for guid as its unique createIndexes(management, Constants.GUID_PROPERTY_KEY, String.class, true, AtlasCardinality.SINGLE, true, true); // Add creation_timestamp property to Vertex Index (mixed index) createIndexes(management, Constants.TIMESTAMP_PROPERTY_KEY, Long.class, false, AtlasCardinality.SINGLE, false, false); // Add modification_timestamp property to Vertex Index (mixed index) createIndexes(management, Constants.MODIFICATION_TIMESTAMP_PROPERTY_KEY, Long.class, false, AtlasCardinality.SINGLE, false, false); // create a mixed index for entity state. Set systemProperty flag deliberately to false // so that it doesnt create a composite index which has issues with // titan 0.5.4 - Refer https://groups.google.com/forum/#!searchin/aureliusgraphs/hemanth/aureliusgraphs/bx7T843mzXU/fjAsclx7GAAJ createIndexes(management, Constants.STATE_PROPERTY_KEY, String.class, false, AtlasCardinality.SINGLE, false, false); // Create a composite and mixed index for created by property createIndexes(management, Constants.CREATED_BY_KEY, String.class, false, AtlasCardinality.SINGLE, true, true); // Create a composite and mixed index for modified by property createIndexes(management, Constants.MODIFIED_BY_KEY, String.class, false, AtlasCardinality.SINGLE, true, true); // create a composite and mixed index for type since it can be combined with other keys createIndexes(management, Constants.ENTITY_TYPE_PROPERTY_KEY, String.class, false, AtlasCardinality.SINGLE, true, true); // create a composite and mixed index for type since it can be combined with other keys createIndexes(management, Constants.SUPER_TYPES_PROPERTY_KEY, String.class, false, AtlasCardinality.SET, true, true); // create a composite and mixed index for traitNames since it can be combined with other // keys. Traits must be a set and not a list. createIndexes(management, Constants.TRAIT_NAMES_PROPERTY_KEY, String.class, false, AtlasCardinality.SET, true, true); // Index for full text search createFullTextIndex(management); //Indexes for graph backed type system store createTypeStoreIndexes(management); commit(management); LOG.info("Index creation for global keys complete."); } catch (Throwable t) { rollback(management); throw new RepositoryException(t); } } private void createFullTextIndex(AtlasGraphManagement management) { AtlasPropertyKey fullText = management.makePropertyKey(Constants.ENTITY_TEXT_PROPERTY_KEY, String.class, AtlasCardinality.SINGLE); management.createFullTextIndex(Constants.FULLTEXT_INDEX, fullText, Constants.BACKING_INDEX); } private void createTypeStoreIndexes(AtlasGraphManagement management) { //Create unique index on typeName createIndexes(management, Constants.TYPENAME_PROPERTY_KEY, String.class, true, AtlasCardinality.SINGLE, true, true); //create index on vertex type createIndexes(management, Constants.VERTEX_TYPE_PROPERTY_KEY, String.class, false, AtlasCardinality.SINGLE, true, true); } /** * This is upon adding a new type to Store. * * @param dataTypes data type * @throws AtlasException */ @Override public void onAdd(Collection<? extends IDataType> dataTypes) throws AtlasException { AtlasGraphManagement management = provider.get().getManagementSystem(); for (IDataType dataType : dataTypes) { if (LOG.isDebugEnabled()) { LOG.debug("Creating indexes for type name={}, definition={}", dataType.getName(), dataType.getClass()); } try { addIndexForType(management, dataType); LOG.info("Index creation for type {} complete", dataType.getName()); } catch (Throwable throwable) { LOG.error("Error creating index for type {}", dataType, throwable); //Rollback indexes if any failure rollback(management); throw new IndexCreationException("Error while creating index for type " + dataType, throwable); } } //Commit indexes commit(management); } @Override public void onChange(Collection<? extends IDataType> dataTypes) throws AtlasException { onAdd(dataTypes); } public Set<String> getVertexIndexKeys() { if (recomputeIndexedKeys) { AtlasGraphManagement management = null; try { management = provider.get().getManagementSystem(); } catch (RepositoryException excp) { LOG.error("failed to get indexedKeys from graph", excp); } if (management != null) { recomputeIndexedKeys = false; AtlasGraphIndex vertexIndex = management.getGraphIndex(Constants.VERTEX_INDEX); Set<String> indexKeys = new HashSet<>(); for (AtlasPropertyKey fieldKey : vertexIndex.getFieldKeys()) { indexKeys.add(fieldKey.getName()); } vertexIndexKeys = indexKeys; } } return vertexIndexKeys; } private void addIndexForType(AtlasGraphManagement management, AtlasBaseTypeDef typeDef) { if (typeDef instanceof AtlasEnumDef) { // Only handle complex types like Struct, Classification and Entity return; } if (typeDef instanceof AtlasStructDef) { AtlasStructDef structDef = (AtlasStructDef) typeDef; List<AtlasAttributeDef> attributeDefs = structDef.getAttributeDefs(); if (CollectionUtils.isNotEmpty(attributeDefs)) { for (AtlasAttributeDef attributeDef : attributeDefs) { createIndexForAttribute(management, typeDef.getName(), attributeDef); } } } else if (!AtlasTypeUtil.isBuiltInType(typeDef.getName())){ throw new IllegalArgumentException("bad data type" + typeDef.getName()); } } private void createIndexForAttribute(AtlasGraphManagement management, String typeName, AtlasAttributeDef attributeDef) { final String propertyName = GraphHelper.encodePropertyKey(typeName + "." + attributeDef.getName()); AtlasCardinality cardinality = toAtlasCardinality(attributeDef.getCardinality()); boolean isUnique = attributeDef.getIsUnique(); boolean isIndexable = attributeDef.getIsIndexable(); String attribTypeName = attributeDef.getTypeName(); boolean isBuiltInType = AtlasTypeUtil.isBuiltInType(attribTypeName); boolean isArrayType = AtlasTypeUtil.isArrayType(attribTypeName); boolean isMapType = AtlasTypeUtil.isMapType(attribTypeName); try { AtlasType atlasType = typeRegistry.getType(attribTypeName); if (isMapType || isArrayType || isClassificationType(atlasType) || isEntityType(atlasType)) { LOG.warn("Ignoring non-indexable attribute {}", attribTypeName); } else if (isBuiltInType) { createIndexes(management, propertyName, getPrimitiveClass(attribTypeName), isUnique, cardinality, false, isIndexable); } else if (isEnumType(atlasType)) { createIndexes(management, propertyName, String.class, isUnique, cardinality, false, isIndexable); } else if (isStructType(atlasType)) { AtlasStructDef structDef = typeRegistry.getStructDefByName(attribTypeName); updateIndexForTypeDef(management, structDef); } } catch (AtlasBaseException e) { LOG.error("No type exists for {}", attribTypeName, e); } } private boolean isEntityType(AtlasType type) { return type instanceof AtlasEntityType; } private boolean isClassificationType(AtlasType type) { return type instanceof AtlasClassificationType; } private boolean isEnumType(AtlasType type) { return type instanceof AtlasEnumType; } private boolean isStructType(AtlasType type) { return type instanceof AtlasStructType; } private Class getPrimitiveClass(String attribTypeName) { switch (attribTypeName.toLowerCase()) { case ATLAS_TYPE_BOOLEAN: return Boolean.class; case ATLAS_TYPE_BYTE: return Byte.class; case ATLAS_TYPE_SHORT: return Short.class; case ATLAS_TYPE_INT: return Integer.class; case ATLAS_TYPE_LONG: case ATLAS_TYPE_DATE: return Long.class; case ATLAS_TYPE_FLOAT: return Float.class; case ATLAS_TYPE_DOUBLE: return Double.class; case ATLAS_TYPE_BIGINTEGER: return BigInteger.class; case ATLAS_TYPE_BIGDECIMAL: return BigDecimal.class; case ATLAS_TYPE_STRING: return String.class; } throw new IllegalArgumentException(String.format("Unknown primitive typename %s", attribTypeName)); } private AtlasCardinality toAtlasCardinality(AtlasAttributeDef.Cardinality cardinality) { switch (cardinality) { case SINGLE: return AtlasCardinality.SINGLE; case LIST: return AtlasCardinality.LIST; case SET: return AtlasCardinality.SET; } // Should never reach this point throw new IllegalArgumentException(String.format("Bad cardinality %s", cardinality)); } private void addIndexForType(AtlasGraphManagement management, IDataType dataType) { switch (dataType.getTypeCategory()) { case PRIMITIVE: case ENUM: case ARRAY: case MAP: // do nothing since these are only attributes // and not types like structs, traits or classes break; case STRUCT: StructType structType = (StructType) dataType; createIndexForFields(management, structType, structType.fieldMapping().fields); break; case TRAIT: TraitType traitType = (TraitType) dataType; createIndexForFields(management, traitType, traitType.fieldMapping().fields); break; case CLASS: ClassType classType = (ClassType) dataType; createIndexForFields(management, classType, classType.fieldMapping().fields); break; default: throw new IllegalArgumentException("bad data type" + dataType); } } private void createIndexForFields(AtlasGraphManagement management, IDataType dataType, Map<String, AttributeInfo> fields) { for (AttributeInfo field : fields.values()) { createIndexForAttribute(management, dataType.getName(), field); } } private void createIndexForAttribute(AtlasGraphManagement management, String typeName, AttributeInfo field) { final String propertyName = GraphHelper.encodePropertyKey(typeName + "." + field.name); switch (field.dataType().getTypeCategory()) { case PRIMITIVE: AtlasCardinality cardinality = getCardinality(field.multiplicity); createIndexes(management, propertyName, getPrimitiveClass(field.dataType()), field.isUnique, cardinality, false, field.isIndexable); break; case ENUM: cardinality = getCardinality(field.multiplicity); createIndexes(management, propertyName, String.class, field.isUnique, cardinality, false, field.isIndexable); break; case ARRAY: case MAP: // todo - how do we overcome this limitation? // IGNORE: Can only index single-valued property keys on vertices in Mixed Index break; case STRUCT: StructType structType = (StructType) field.dataType(); createIndexForFields(management, structType, structType.fieldMapping().fields); break; case TRAIT: // do nothing since this is NOT contained in other types break; case CLASS: // this is only A reference, index the attribute for edge // Commenting this out since we do not need an index for edge here //createEdgeMixedIndex(propertyName); break; default: throw new IllegalArgumentException("bad data type" + field.dataType().getName()); } } private Class getPrimitiveClass(IDataType dataType) { if (dataType == DataTypes.STRING_TYPE) { return String.class; } else if (dataType == DataTypes.SHORT_TYPE) { return Short.class; } else if (dataType == DataTypes.INT_TYPE) { return Integer.class; } else if (dataType == DataTypes.BIGINTEGER_TYPE) { return BigInteger.class; } else if (dataType == DataTypes.BOOLEAN_TYPE) { return Boolean.class; } else if (dataType == DataTypes.BYTE_TYPE) { return Byte.class; } else if (dataType == DataTypes.LONG_TYPE) { return Long.class; } else if (dataType == DataTypes.FLOAT_TYPE) { return Float.class; } else if (dataType == DataTypes.DOUBLE_TYPE) { return Double.class; } else if (dataType == DataTypes.BIGDECIMAL_TYPE) { return BigDecimal.class; } else if (dataType == DataTypes.DATE_TYPE) { //Indexing with date converted to long as of now since Titan is yet to add support for Date type with mixed indexes return Long.class; } throw new IllegalArgumentException("unknown data type " + dataType); } private AtlasCardinality getCardinality(Multiplicity multiplicity) { if (multiplicity == Multiplicity.OPTIONAL || multiplicity == Multiplicity.REQUIRED) { return AtlasCardinality.SINGLE; } else if (multiplicity == Multiplicity.COLLECTION) { return AtlasCardinality.LIST; } else if (multiplicity == Multiplicity.SET) { return AtlasCardinality.SET; } // todo - default to LIST as this is the most forgiving return AtlasCardinality.LIST; } private AtlasPropertyKey createIndexes(AtlasGraphManagement management, String propertyName, Class propertyClass, boolean isUnique, AtlasCardinality cardinality, boolean createCompositeForAttribute, boolean createCompositeWithTypeandSuperTypes) { AtlasPropertyKey propertyKey = management.getPropertyKey(propertyName); if (propertyKey == null) { propertyKey = management.makePropertyKey(propertyName, propertyClass, cardinality); updateVertexIndex(management, propertyName, propertyClass, cardinality, propertyKey); } if (createCompositeForAttribute) { createExactMatchIndex(management, propertyClass, propertyKey, isUnique); } else if (createCompositeWithTypeandSuperTypes) { // Index with typename since typename+property key queries need to // speed up createExactMatchIndexWithTypeName(management, propertyClass, propertyKey); createExactMatchIndexWithSuperTypeName(management, propertyClass, propertyKey); } return propertyKey; } private void createExactMatchIndex(AtlasGraphManagement management, Class propertyClass, AtlasPropertyKey propertyKey, boolean enforceUniqueness) { String propertyName = propertyKey.getName(); if (LOG.isDebugEnabled()) { LOG.debug("Creating composite index for property {} of type {}; isUnique={} ", propertyName, propertyClass.getName(), enforceUniqueness); } AtlasGraphIndex existingIndex = management.getGraphIndex(propertyName); if (existingIndex == null) { management.createExactMatchIndex(propertyName, enforceUniqueness, Collections.singletonList(propertyKey)); } LOG.info("Created composite index for property {} of type {}; isUnique={} ", propertyName, propertyClass.getName(), enforceUniqueness); } private void createExactMatchIndexWithTypeName(AtlasGraphManagement management, Class propertyClass, AtlasPropertyKey propertyKey) { createExactMatchIndexWithSystemProperty(management, propertyClass, propertyKey, Constants.ENTITY_TYPE_PROPERTY_KEY, AtlasCardinality.SINGLE); } private void createExactMatchIndexWithSuperTypeName(AtlasGraphManagement management, Class propertyClass, AtlasPropertyKey propertyKey) { createExactMatchIndexWithSystemProperty(management, propertyClass, propertyKey, Constants.SUPER_TYPES_PROPERTY_KEY, AtlasCardinality.SET); } private void createExactMatchIndexWithSystemProperty(AtlasGraphManagement management, Class propertyClass, AtlasPropertyKey propertyKey, final String systemPropertyKey, AtlasCardinality cardinality) { if (LOG.isDebugEnabled()) { LOG.debug("Creating composite index for property {} of type {} and {}", propertyKey.getName(), propertyClass.getName(), systemPropertyKey); } AtlasPropertyKey typePropertyKey = management.getPropertyKey(systemPropertyKey); if (typePropertyKey == null) { typePropertyKey = management.makePropertyKey(systemPropertyKey, String.class, cardinality); } final String indexName = propertyKey.getName() + systemPropertyKey; AtlasGraphIndex existingIndex = management.getGraphIndex(indexName); if (existingIndex == null) { List<AtlasPropertyKey> keys = new ArrayList<>(2); keys.add(propertyKey); keys.add(typePropertyKey); management.createExactMatchIndex(indexName, false, keys); LOG.info("Created composite index for property {} of type {} and {}", propertyKey.getName(), propertyClass.getName(), systemPropertyKey); } } private void updateVertexIndex(AtlasGraphManagement management, String propertyName, Class propertyClass, AtlasCardinality cardinality, AtlasPropertyKey propertyKey) { if (checkIfVertexIndexApplicable(propertyClass, cardinality)) { if (LOG.isDebugEnabled()) { LOG.debug("Creating backing index for property {} of type {} ", propertyName, propertyClass.getName()); } // Use backing index management.addVertexIndexKey(Constants.VERTEX_INDEX, propertyKey); LOG.info("Created backing index for property {} of type {} ", propertyName, propertyClass.getName()); } } private boolean checkIfVertexIndexApplicable(Class propertyClass, AtlasCardinality cardinality) { return !(VERTEX_INDEX_EXCLUSIONS.contains(propertyClass) || cardinality.isMany()); } private void commit(AtlasGraphManagement management) throws IndexException { try { management.commit(); recomputeIndexedKeys = true; } catch (Exception e) { LOG.error("Index commit failed", e); throw new IndexException("Index commit failed ", e); } } private void rollback(AtlasGraphManagement management) throws IndexException { try { management.rollback(); recomputeIndexedKeys = true; } catch (Exception e) { LOG.error("Index rollback failed ", e); throw new IndexException("Index rollback failed ", e); } } /** * Initialize global indices for Titan graph on server activation. * * Since the indices are shared state, we need to do this only from an active instance. */ @Override public void instanceIsActive() throws AtlasException { LOG.info("Reacting to active: initializing index"); try { initialize(); } catch (RepositoryException | IndexException e) { throw new AtlasException("Error in reacting to active on initialization", e); } } @Override public void instanceIsPassive() { LOG.info("Reacting to passive state: No action right now."); } @Override public void onChange(ChangedTypeDefs changedTypeDefs) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("Processing changed typedefs {}", changedTypeDefs); } AtlasGraphManagement management = null; try { management = provider.get().getManagementSystem(); // Update index for newly created types if (CollectionUtils.isNotEmpty(changedTypeDefs.getCreateTypeDefs())) { for (AtlasBaseTypeDef typeDef : changedTypeDefs.getCreateTypeDefs()) { updateIndexForTypeDef(management, typeDef); } } // Update index for updated types if (CollectionUtils.isNotEmpty(changedTypeDefs.getUpdatedTypeDefs())) { for (AtlasBaseTypeDef typeDef : changedTypeDefs.getUpdatedTypeDefs()) { updateIndexForTypeDef(management, typeDef); } } // Invalidate the property key for deleted types if (CollectionUtils.isNotEmpty(changedTypeDefs.getDeletedTypeDefs())) { for (AtlasBaseTypeDef typeDef : changedTypeDefs.getDeletedTypeDefs()) { cleanupIndices(management, typeDef); } } //Commit indexes commit(management); } catch (RepositoryException | IndexException e) { LOG.error("Failed to update indexes for changed typedefs", e); attemptRollback(changedTypeDefs, management); } } private void cleanupIndices(AtlasGraphManagement management, AtlasBaseTypeDef typeDef) { Preconditions.checkNotNull(typeDef, "Cannot process null typedef"); if (LOG.isDebugEnabled()) { LOG.debug("Cleaning up index for {}", typeDef); } if (typeDef instanceof AtlasEnumDef) { // Only handle complex types like Struct, Classification and Entity return; } if (typeDef instanceof AtlasStructDef) { AtlasStructDef structDef = (AtlasStructDef) typeDef; List<AtlasAttributeDef> attributeDefs = structDef.getAttributeDefs(); if (CollectionUtils.isNotEmpty(attributeDefs)) { for (AtlasAttributeDef attributeDef : attributeDefs) { cleanupIndexForAttribute(management, typeDef.getName(), attributeDef); } } } else if (!AtlasTypeUtil.isBuiltInType(typeDef.getName())){ throw new IllegalArgumentException("bad data type" + typeDef.getName()); } } private void cleanupIndexForAttribute(AtlasGraphManagement management, String typeName, AtlasAttributeDef attributeDef) { final String propertyName = GraphHelper.encodePropertyKey(typeName + "." + attributeDef.getName()); String attribTypeName = attributeDef.getTypeName(); boolean isBuiltInType = AtlasTypeUtil.isBuiltInType(attribTypeName); boolean isArrayType = AtlasTypeUtil.isArrayType(attribTypeName); boolean isMapType = AtlasTypeUtil.isMapType(attribTypeName); try { AtlasType atlasType = typeRegistry.getType(attribTypeName); if (isMapType || isArrayType || isClassificationType(atlasType) || isEntityType(atlasType)) { LOG.warn("Ignoring non-indexable attribute {}", attribTypeName); } else if (isBuiltInType || isEnumType(atlasType)) { cleanupIndex(management, propertyName); } else if (isStructType(atlasType)) { AtlasStructDef structDef = typeRegistry.getStructDefByName(attribTypeName); cleanupIndices(management, structDef); } } catch (AtlasBaseException e) { LOG.error("No type exists for {}", attribTypeName, e); } } private void cleanupIndex(AtlasGraphManagement management, String propertyKey) { if (LOG.isDebugEnabled()) { LOG.debug("Invalidating property key = {}", propertyKey); } management.deletePropertyKey(propertyKey); } private void attemptRollback(ChangedTypeDefs changedTypeDefs, AtlasGraphManagement management) throws AtlasBaseException { if (null != management) { try { rollback(management); } catch (IndexException e) { LOG.error("Index rollback has failed", e); throw new AtlasBaseException(AtlasErrorCode.INDEX_ROLLBACK_FAILED, e, changedTypeDefs.toString()); } } } private void updateIndexForTypeDef(AtlasGraphManagement management, AtlasBaseTypeDef typeDef) { Preconditions.checkNotNull(typeDef, "Cannot index on null typedefs"); if (LOG.isDebugEnabled()) { LOG.debug("Creating indexes for type name={}, definition={}", typeDef.getName(), typeDef.getClass()); } addIndexForType(management, typeDef); LOG.info("Index creation for type {} complete", typeDef.getName()); } /* Commenting this out since we do not need an index for edge label here private void createEdgeMixedIndex(String propertyName) { EdgeLabel edgeLabel = management.getEdgeLabel(propertyName); if (edgeLabel == null) { edgeLabel = management.makeEdgeLabel(propertyName).make(); management.buildEdgeIndex(edgeLabel, propertyName, Direction.BOTH, Order.DEFAULT); LOG.info("Created index for edge label {}", propertyName); } }*/ } <|start_filename|>repository/src/main/java/org/apache/atlas/gremlin/optimizer/IsOrParent.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.gremlin.optimizer; import com.google.common.base.Function; import org.apache.atlas.groovy.AbstractFunctionExpression; import org.apache.atlas.groovy.FunctionCallExpression; import org.apache.atlas.groovy.GroovyExpression; import org.apache.atlas.groovy.TraversalStepType; /** * Matches an expression that gets called after calling or(). For example, * in g.V().or(x,y).toList(), "toList()" is the "or parent", so calling * "apply()" on this expression would return true and calling it on all * the other ones would return false. */ public final class IsOrParent implements Function<GroovyExpression, Boolean> { public static final IsOrParent INSTANCE = new IsOrParent(); private IsOrParent() { } @Override public Boolean apply(GroovyExpression expr) { if (!(expr instanceof AbstractFunctionExpression)) { return false; } AbstractFunctionExpression functionCall = (AbstractFunctionExpression)expr; GroovyExpression target = functionCall.getCaller(); if (!(target instanceof FunctionCallExpression)) { return false; } if (target.getType() != TraversalStepType.FILTER) { return false; } FunctionCallExpression targetFunction = (FunctionCallExpression)target; return targetFunction.getFunctionName().equals("or"); } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/store/graph/AtlasRelationshipStore.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.store.graph; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.instance.AtlasRelationship; /** * Persistence/Retrieval API for AtlasRelationship */ public interface AtlasRelationshipStore { /** * Create a new relationship instance. * @param relationship relationship instance definition * @return AtlasRelationship d */ AtlasRelationship create(AtlasRelationship relationship) throws AtlasBaseException; /** * Update an existing relationship instance. * @param relationship relationship instance definition * @return AtlasRelationship d */ AtlasRelationship update(AtlasRelationship relationship) throws AtlasBaseException; /** * Retrieve a relationship instance using guid. * @param guid relationship instance guid * @return AtlasRelationship */ AtlasRelationship getById(String guid) throws AtlasBaseException; /** * Retrieve a relationship if it exists or creates a new relationship instance. * @param relationship relationship instance definition * @return AtlasRelationship */ AtlasRelationship getOrCreate(AtlasRelationship relationship) throws AtlasBaseException; /** * Delete a relationship instance using guid. * @param guid relationship instance guid */ void deleteById(String guid) throws AtlasBaseException; } <|start_filename|>repository/src/test/java/org/apache/atlas/repository/graph/AbstractGremlinQueryOptimizerTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graph; import org.apache.atlas.AtlasException; import org.apache.atlas.gremlin.GremlinExpressionFactory; import org.apache.atlas.gremlin.optimizer.GremlinQueryOptimizer; import org.apache.atlas.gremlin.optimizer.RangeFinder; import org.apache.atlas.groovy.AbstractFunctionExpression; import org.apache.atlas.groovy.FunctionCallExpression; import org.apache.atlas.groovy.GroovyExpression; import org.apache.atlas.groovy.IdentifierExpression; import org.apache.atlas.groovy.LiteralExpression; import org.apache.atlas.groovy.TraversalStepType; import org.apache.atlas.query.GraphPersistenceStrategies; import org.apache.atlas.query.TypeUtils.FieldInfo; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.MetadataRepository; import org.apache.atlas.repository.RepositoryException; import org.apache.atlas.repository.graphdb.AtlasEdgeDirection; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.GremlinVersion; import org.apache.atlas.typesystem.types.AttributeDefinition; import org.apache.atlas.typesystem.types.AttributeInfo; import org.apache.atlas.typesystem.types.DataTypes; import org.apache.atlas.typesystem.types.IDataType; import org.apache.atlas.typesystem.types.Multiplicity; import org.apache.atlas.typesystem.types.TypeSystem; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; public abstract class AbstractGremlinQueryOptimizerTest implements IAtlasGraphProvider { protected abstract GremlinExpressionFactory getFactory(); private MetadataRepository repo; private final GraphPersistenceStrategies STRATEGY = mock(GraphPersistenceStrategies.class); @BeforeClass public void setUp() throws RepositoryException { GremlinQueryOptimizer.reset(); GremlinQueryOptimizer.setExpressionFactory(getFactory()); when(STRATEGY.typeAttributeName()).thenReturn(Constants.ENTITY_TYPE_PROPERTY_KEY); when(STRATEGY.superTypeAttributeName()).thenReturn(Constants.SUPER_TYPES_PROPERTY_KEY); repo = new GraphBackedMetadataRepository(new HardDeleteHandler(TypeSystem.getInstance()), this.get()); } private FieldInfo getTestFieldInfo() throws AtlasException { AttributeDefinition def = new AttributeDefinition("foo", DataTypes.STRING_TYPE.getName(), Multiplicity.REQUIRED, false, null); AttributeInfo attrInfo = new AttributeInfo(TypeSystem.getInstance(), def, null); return new FieldInfo(DataTypes.STRING_TYPE, attrInfo, null, null); } private GroovyExpression getVerticesExpression() { IdentifierExpression g = new IdentifierExpression("g"); return new FunctionCallExpression(TraversalStepType.START, g, "V"); } @Test public void testPullHasExpressionsOutOfAnd() throws AtlasException { GroovyExpression expr1 = makeOutExpression(null, "out1"); GroovyExpression expr2 = makeOutExpression(null, "out2"); GroovyExpression expr3 = makeHasExpression("prop1","Fred"); GroovyExpression expr4 = makeHasExpression("prop2","George"); GroovyExpression toOptimize = getFactory().generateLogicalExpression(getVerticesExpression(), "and", Arrays.asList(expr1, expr2, expr3, expr4)); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestPullHasExpressionsOutOfHas()); } protected abstract String getExpectedGremlinForTestPullHasExpressionsOutOfHas(); @Test public void testOrGrouping() throws AtlasException { GroovyExpression expr1 = makeOutExpression(null, "out1"); GroovyExpression expr2 = makeOutExpression(null, "out2"); GroovyExpression expr3 = makeHasExpression("prop1","Fred"); GroovyExpression expr4 = makeHasExpression("prop2","George"); GroovyExpression toOptimize = getFactory().generateLogicalExpression(getVerticesExpression(), "or", Arrays.asList(expr1, expr2, expr3, expr4)); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestOrGrouping()); } protected abstract String getExpectedGremlinForTestOrGrouping(); @Test public void testAndOfOrs() throws AtlasException { GroovyExpression or1Cond1 = makeHasExpression("p1","e1"); GroovyExpression or1Cond2 = makeHasExpression("p2","e2"); GroovyExpression or2Cond1 = makeHasExpression("p3","e3"); GroovyExpression or2Cond2 = makeHasExpression("p4","e4"); GroovyExpression or1 = getFactory().generateLogicalExpression(null, "or", Arrays.asList(or1Cond1, or1Cond2)); GroovyExpression or2 = getFactory().generateLogicalExpression(null, "or", Arrays.asList(or2Cond1, or2Cond2)); GroovyExpression toOptimize = getFactory().generateLogicalExpression(getVerticesExpression(), "and", Arrays.asList(or1, or2)); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestAndOfOrs()); } protected abstract String getExpectedGremlinForTestAndOfOrs(); @Test public void testAndWithMultiCallArguments() throws AtlasException { GroovyExpression cond1 = makeHasExpression("p1","e1"); GroovyExpression cond2 = makeHasExpression(cond1, "p2","e2"); GroovyExpression cond3 = makeHasExpression("p3","e3"); GroovyExpression cond4 = makeHasExpression(cond3, "p4","e4"); GroovyExpression toOptimize = getFactory().generateLogicalExpression(getVerticesExpression(), "and", Arrays.asList(cond2, cond4)); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestAndWithMultiCallArguments()); } protected abstract String getExpectedGremlinForTestAndWithMultiCallArguments(); @Test public void testOrOfAnds() throws AtlasException { GroovyExpression or1Cond1 = makeHasExpression("p1","e1"); GroovyExpression or1Cond2 = makeHasExpression("p2","e2"); GroovyExpression or2Cond1 = makeHasExpression("p3","e3"); GroovyExpression or2Cond2 = makeHasExpression("p4","e4"); GroovyExpression or1 = getFactory().generateLogicalExpression(null, "and", Arrays.asList(or1Cond1, or1Cond2)); GroovyExpression or2 = getFactory().generateLogicalExpression(null, "and", Arrays.asList(or2Cond1, or2Cond2)); GroovyExpression toOptimize = getFactory().generateLogicalExpression(getVerticesExpression(), "or", Arrays.asList(or1, or2)); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestOrOfAnds()); } protected abstract String getExpectedGremlinForTestOrOfAnds(); @Test public void testHasNotMovedToResult() throws AtlasException { GroovyExpression toOptimize = getVerticesExpression(); GroovyExpression or1Cond1 = makeHasExpression("p1","e1"); GroovyExpression or1Cond2 = makeHasExpression("p2","e2"); toOptimize = getFactory().generateLogicalExpression(toOptimize, "or", Arrays.asList(or1Cond1, or1Cond2)); toOptimize = makeHasExpression(toOptimize, "p3","e3"); toOptimize = getFactory().generateAliasExpression(toOptimize, "_src"); toOptimize = getFactory().generateSelectExpression(toOptimize, Collections.singletonList(new LiteralExpression("src1")), Collections.<GroovyExpression>singletonList(new IdentifierExpression("it"))); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestHasNotMovedToResult()); } protected abstract String getExpectedGremlinForTestHasNotMovedToResult(); @Test public void testOptimizeLoopExpression() throws AtlasException { GroovyExpression input = getVerticesExpression(); input = getFactory().generateTypeTestExpression(STRATEGY, input, "DataSet", TestIntSequence.INSTANCE).get(0); input = makeHasExpression(input, "name","Fred"); input = getFactory().generateAliasExpression(input, "label"); GroovyExpression loopExpr = getFactory().getLoopExpressionParent(input); loopExpr = getFactory().generateAdjacentVerticesExpression(loopExpr, AtlasEdgeDirection.IN, "inputTables"); loopExpr = getFactory().generateAdjacentVerticesExpression(loopExpr, AtlasEdgeDirection.OUT, "outputTables"); GroovyExpression result = getFactory().generateLoopExpression(input, STRATEGY, DataTypes.STRING_TYPE, loopExpr, "label", null); result = getFactory().generateToListExpression(result); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(result); assertEquals(optimized.toString(), getExpectedGremlinForOptimizeLoopExpression()); } protected abstract String getExpectedGremlinForOptimizeLoopExpression(); @Test public void testLongStringEndingWithOr() throws AtlasException { GroovyExpression toOptimize = getVerticesExpression(); toOptimize = makeHasExpression(toOptimize, "name","Fred"); toOptimize = makeHasExpression(toOptimize, "age","13"); toOptimize = makeOutExpression(toOptimize, "livesIn"); toOptimize = makeHasExpression(toOptimize, "state","Massachusetts"); GroovyExpression or1cond1 = makeHasExpression("p1", "e1"); GroovyExpression or1cond2 = makeHasExpression("p2", "e2"); toOptimize = getFactory().generateLogicalExpression(toOptimize, "or", Arrays.asList(or1cond1, or1cond2)); GroovyExpression or2cond1 = makeHasExpression("p3", "e3"); GroovyExpression or2cond2 = makeHasExpression("p4", "e4"); toOptimize = getFactory().generateLogicalExpression(toOptimize, "or", Arrays.asList(or2cond1, or2cond2)); toOptimize = makeHasExpression(toOptimize, "p5","e5"); toOptimize = makeHasExpression(toOptimize, "p6","e6"); GroovyExpression or3cond1 = makeHasExpression("p7", "e7"); GroovyExpression or3cond2 = makeHasExpression("p8", "e8"); toOptimize = getFactory().generateLogicalExpression(toOptimize, "or", Arrays.asList(or3cond1, or3cond2)); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestLongStringEndingWithOr()); } protected abstract String getExpectedGremlinForTestLongStringEndingWithOr(); @Test public void testLongStringNotEndingWithOr() throws AtlasException { GroovyExpression toOptimize = getVerticesExpression(); toOptimize = makeHasExpression(toOptimize, "name","Fred"); toOptimize = makeHasExpression(toOptimize, "age","13"); toOptimize = makeOutExpression(toOptimize, "livesIn"); toOptimize = makeHasExpression(toOptimize, "state","Massachusetts"); GroovyExpression or1cond1 = makeHasExpression("p1", "e1"); GroovyExpression or1cond2 = makeHasExpression("p2", "e2"); toOptimize = getFactory().generateLogicalExpression(toOptimize, "or", Arrays.asList(or1cond1, or1cond2)); GroovyExpression or2cond1 = makeHasExpression("p3", "e3"); GroovyExpression or2cond2 = makeHasExpression("p4", "e4"); toOptimize = getFactory().generateLogicalExpression(toOptimize, "or", Arrays.asList(or2cond1, or2cond2)); toOptimize = makeHasExpression(toOptimize, "p5","e5"); toOptimize = makeHasExpression(toOptimize, "p6","e6"); GroovyExpression or3cond1 = makeHasExpression("p7", "e7"); GroovyExpression or3cond2 = makeHasExpression("p8", "e8"); toOptimize = getFactory().generateLogicalExpression(toOptimize, "or", Arrays.asList(or3cond1, or3cond2)); toOptimize = makeHasExpression(toOptimize, "p9","e9"); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestLongStringNotEndingWithOr()); } protected abstract String getExpectedGremlinForTestLongStringNotEndingWithOr(); @Test public void testToListConversion() throws AtlasException { GroovyExpression expr1 = makeHasExpression("prop1","Fred"); GroovyExpression expr2 = makeHasExpression("prop2","George"); GroovyExpression toOptimize = getFactory().generateLogicalExpression(getVerticesExpression(), "or", Arrays.asList(expr1, expr2)); toOptimize = new FunctionCallExpression(TraversalStepType.END, toOptimize,"toList"); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestToListConversion()); } protected abstract String getExpectedGremlinForTestToListConversion(); @Test public void testToListWithExtraStuff() throws AtlasException { GroovyExpression expr1 = makeHasExpression("prop1","Fred"); GroovyExpression expr2 = makeHasExpression("prop2","George"); GroovyExpression toOptimize = getFactory().generateLogicalExpression(getVerticesExpression(), "or", Arrays.asList(expr1, expr2)); toOptimize = new FunctionCallExpression(TraversalStepType.END, toOptimize,"toList"); toOptimize = new FunctionCallExpression(toOptimize,"size"); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestToListWithExtraStuff()); } protected abstract String getExpectedGremlinForTestToListWithExtraStuff(); public void testAddClosureWithExitExpressionDifferentFromExpr() throws AtlasException { GroovyExpression expr1 = makeHasExpression("prop1","Fred"); GroovyExpression expr2 = makeHasExpression("prop2","George"); GroovyExpression toOptimize = getFactory().generateLogicalExpression(getVerticesExpression(), "or", Arrays.asList(expr1, expr2)); toOptimize = makeOutExpression(toOptimize, "knows"); toOptimize = makeOutExpression(toOptimize, "livesIn"); toOptimize = new FunctionCallExpression(TraversalStepType.END, toOptimize,"toList"); toOptimize = new FunctionCallExpression(toOptimize,"size"); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestAddClosureWithExitExpressionDifferentFromExpr()); } protected abstract String getExpectedGremlinForTestAddClosureWithExitExpressionDifferentFromExpr(); @Test public void testAddClosureNoExitExpression() throws AtlasException { GroovyExpression expr1 = makeHasExpression("prop1","Fred"); GroovyExpression expr2 = makeHasExpression("prop2","George"); GroovyExpression toOptimize = getFactory().generateLogicalExpression(getVerticesExpression(), "or", Arrays.asList(expr1, expr2)); toOptimize = makeOutExpression(toOptimize, "knows"); toOptimize = makeOutExpression(toOptimize, "livesIn"); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestAddClosureNoExitExpression()); } protected abstract String getExpectedGremlinForTestAddClosureNoExitExpression(); private GroovyExpression makeOutExpression(GroovyExpression parent, String label) { return getFactory().generateAdjacentVerticesExpression(parent, AtlasEdgeDirection.OUT, label); } @Test public void testAddClosureWithExitExpressionEqualToExpr() throws AtlasException { GroovyExpression expr1 = makeHasExpression("prop1","Fred"); GroovyExpression expr2 = makeHasExpression("prop2","George"); GroovyExpression toOptimize = getFactory().generateLogicalExpression(getVerticesExpression(), "or", Arrays.asList(expr1, expr2)); toOptimize = makeOutExpression(toOptimize, "knows"); toOptimize = makeOutExpression(toOptimize, "livesIn"); toOptimize = new FunctionCallExpression(TraversalStepType.END, toOptimize,"toList"); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestAddClosureWithExitExpressionEqualToExpr()); } protected abstract String getExpectedGremlinForTestAddClosureWithExitExpressionEqualToExpr(); @Test public void testClosureNotCreatedWhenNoOrs() throws AtlasException { GroovyExpression expr1 = makeHasExpression("prop1","Fred"); GroovyExpression expr2 = makeHasExpression("prop2","George"); GroovyExpression toOptimize = getFactory().generateLogicalExpression(getVerticesExpression(), "and", Arrays.asList(expr1, expr2)); toOptimize = makeOutExpression(toOptimize, "knows"); toOptimize = makeOutExpression(toOptimize, "livesIn"); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestClosureNotCreatedWhenNoOrs()); } protected abstract String getExpectedGremlinForTestClosureNotCreatedWhenNoOrs(); private GroovyExpression makeHasExpression(String name, String value) throws AtlasException { return makeHasExpression(null, name, value); } private GroovyExpression makeHasExpression(GroovyExpression parent, String name, String value) throws AtlasException { return getFactory().generateHasExpression(STRATEGY, parent, name, "=", new LiteralExpression(value), getTestFieldInfo()); } private GroovyExpression makeFieldExpression(GroovyExpression parent, String fieldName) throws AtlasException { return getFactory().generateFieldExpression(parent, getTestFieldInfo(), fieldName, false); } @Test public void testOrFollowedByAnd() throws AtlasException { GroovyExpression expr1 = makeHasExpression("name","Fred"); GroovyExpression expr2 = makeHasExpression("name","George"); GroovyExpression expr3 = makeHasExpression("age","13"); GroovyExpression expr4 = makeHasExpression("age","14"); GroovyExpression toOptimize = getFactory().generateLogicalExpression(getVerticesExpression(), "or", Arrays.asList(expr1,expr2)); toOptimize = getFactory().generateLogicalExpression(toOptimize, "and", Arrays.asList(expr3, expr4)); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestOrFollowedByAnd()); } protected abstract String getExpectedGremlinForTestOrFollowedByAnd(); @Test public void testOrFollowedByOr() throws AtlasException { GroovyExpression expr1 = makeHasExpression("name","Fred"); GroovyExpression expr2 = makeHasExpression("name","George"); GroovyExpression expr3 = makeHasExpression("age","13"); GroovyExpression expr4 = makeHasExpression("age","14"); GroovyExpression toOptimize = getFactory().generateLogicalExpression(getVerticesExpression(), "or", Arrays.asList(expr1,expr2)); toOptimize = getFactory().generateLogicalExpression(toOptimize, "or", Arrays.asList(expr3, expr4)); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestOrFollowedByOr()); } protected abstract String getExpectedGremlinForTestOrFollowedByOr(); @Test public void testMassiveOrExpansion() throws AtlasException { GroovyExpression toOptimize = getVerticesExpression(); toOptimize = makeHasExpression(toOptimize, "h1","h2"); toOptimize = makeHasExpression(toOptimize, "h3","h4"); for(int i = 0; i < 5; i++) { GroovyExpression expr1 = makeHasExpression("p1" + i,"e1" + i); GroovyExpression expr2 = makeHasExpression("p2" + i,"e2" + i); toOptimize = getFactory().generateLogicalExpression(toOptimize, "or", Arrays.asList(expr1,expr2)); toOptimize = makeHasExpression(toOptimize, "ha" + i,"hb" + i); toOptimize = makeHasExpression(toOptimize, "hc" + i,"hd" + i); } toOptimize = makeHasExpression(toOptimize, "h5","h6"); toOptimize = makeHasExpression(toOptimize, "h7","h8"); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestMassiveOrExpansion()); } protected abstract String getExpectedGremlinForTestMassiveOrExpansion(); @Test public void testAndFollowedByAnd() throws AtlasException { GroovyExpression expr1 = makeHasExpression("name","Fred"); GroovyExpression expr2 = makeHasExpression("name","George"); GroovyExpression expr3 = makeHasExpression("age","13"); GroovyExpression expr4 = makeHasExpression("age","14"); GroovyExpression toOptimize = getFactory().generateLogicalExpression(getVerticesExpression(), "and", Arrays.asList(expr1,expr2)); toOptimize = getFactory().generateLogicalExpression(toOptimize, "and", Arrays.asList(expr3, expr4)); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestAndFollowedByAnd()); } protected abstract String getExpectedGremlinForTestAndFollowedByAnd(); @Test public void testAndFollowedByOr() throws AtlasException { GroovyExpression expr1 = makeHasExpression("name","Fred"); GroovyExpression expr2 = makeHasExpression("name","George"); GroovyExpression expr3 = makeHasExpression("age","13"); GroovyExpression expr4 = makeHasExpression("age","14"); GroovyExpression toOptimize = getFactory().generateLogicalExpression(getVerticesExpression(), "and", Arrays.asList(expr1,expr2)); toOptimize = getFactory().generateLogicalExpression(toOptimize, "or", Arrays.asList(expr3, expr4)); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestAndFollowedByOr()); } protected abstract String getExpectedGremlinForTestAndFollowedByOr(); @Test public void testInitialAlias() throws AtlasException { GroovyExpression expr1 = makeHasExpression("name","Fred"); GroovyExpression expr2 = makeHasExpression("name","George"); GroovyExpression toOptimize = getVerticesExpression(); toOptimize = getFactory().generateAliasExpression(toOptimize, "x"); toOptimize = getFactory().generateLogicalExpression(toOptimize, "or", Arrays.asList(expr1, expr2)); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestInitialAlias()); } protected abstract String getExpectedGremlinForTestInitialAlias(); @Test public void testFinalAlias() throws AtlasException { GroovyExpression expr1 = makeHasExpression("name","Fred"); GroovyExpression expr2 = makeHasExpression("name","George"); GroovyExpression toOptimize = getVerticesExpression(); toOptimize = getFactory().generateLogicalExpression(toOptimize, "or", Arrays.asList(expr1, expr2)); toOptimize = getFactory().generateAliasExpression(toOptimize, "x"); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestFinalAlias()); } protected abstract String getExpectedGremlinForTestFinalAlias(); @Test public void testAliasInMiddle() throws AtlasException { GroovyExpression expr1 = makeHasExpression("name","Fred"); GroovyExpression expr2 = makeHasExpression("name","George"); GroovyExpression expr3 = makeHasExpression("age","13"); GroovyExpression expr4 = makeHasExpression("age","14"); GroovyExpression toOptimize = getVerticesExpression(); toOptimize = getFactory().generateLogicalExpression(toOptimize, "or", Arrays.asList(expr1, expr2)); toOptimize = getFactory().generateAliasExpression(toOptimize, "x"); toOptimize = getFactory().generateLogicalExpression(toOptimize, "or", Arrays.asList(expr3, expr4)); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestAliasInMiddle()); } protected abstract String getExpectedGremlinForTestAliasInMiddle(); @Test public void testMultipleAliases() throws AtlasException { GroovyExpression expr1 = makeHasExpression("name","Fred"); GroovyExpression expr2 = makeHasExpression("name","George"); GroovyExpression expr3 = makeHasExpression("age","13"); GroovyExpression expr4 = makeHasExpression("age","14"); GroovyExpression toOptimize = getVerticesExpression(); toOptimize = getFactory().generateLogicalExpression(toOptimize, "or", Arrays.asList(expr1, expr2)); toOptimize = getFactory().generateAliasExpression(toOptimize, "x"); toOptimize = getFactory().generateLogicalExpression(toOptimize, "or", Arrays.asList(expr3, expr4)); toOptimize = getFactory().generateAliasExpression(toOptimize, "y"); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGreminForTestMultipleAliases()); } protected abstract String getExpectedGreminForTestMultipleAliases(); @Test public void testAliasInOrExpr() throws AtlasException { GroovyExpression expr1 = makeHasExpression("name","Fred"); GroovyExpression expr2 = getFactory().generateAliasExpression(makeHasExpression("name","George"), "george"); GroovyExpression toOptimize = getVerticesExpression(); toOptimize = getFactory().generateLogicalExpression(toOptimize, "or", Arrays.asList(expr1, expr2)); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestAliasInOrExpr()); } protected abstract String getExpectedGremlinForTestAliasInOrExpr(); @Test public void testAliasInAndExpr() throws AtlasException { GroovyExpression expr1 = makeHasExpression("name","Fred"); GroovyExpression expr2 = getFactory().generateAliasExpression(makeHasExpression("name","George"), "george"); GroovyExpression toOptimize = getVerticesExpression(); toOptimize = getFactory().generateLogicalExpression(toOptimize, "and", Arrays.asList(expr1, expr2)); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); //expression with alias cannot currently be pulled out of the and assertEquals(optimized.toString(), getExpectedGremlinForTestAliasInAndExpr()); } protected abstract String getExpectedGremlinForTestAliasInAndExpr(); @Test public void testFlatMapExprInAnd() throws AtlasException { GroovyExpression expr1 = makeHasExpression("name","Fred"); GroovyExpression expr2 = makeHasExpression(makeOutExpression(null,"knows"), "name","George"); GroovyExpression toOptimize = getVerticesExpression(); toOptimize = getFactory().generateLogicalExpression(toOptimize, "and", Arrays.asList(expr1, expr2)); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestFlatMapExprInAnd()); } protected abstract String getExpectedGremlinForTestFlatMapExprInAnd(); @Test public void testFlatMapExprInOr() throws AtlasException { GroovyExpression expr1 = makeHasExpression("name","Fred"); GroovyExpression expr2 = makeHasExpression(makeOutExpression(null,"knows"), "name","George"); GroovyExpression toOptimize = getVerticesExpression(); toOptimize = getFactory().generateLogicalExpression(toOptimize, "or", Arrays.asList(expr1, expr2)); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestFlatMapExprInOr()); } protected abstract String getExpectedGremlinForTestFlatMapExprInOr(); @Test public void testFieldExpressionPushedToResultExpression() throws AtlasException { GroovyExpression expr1 = makeHasExpression("name","Fred"); GroovyExpression expr2 = makeHasExpression(makeOutExpression(null,"knows"), "name","George"); GroovyExpression toOptimize = getVerticesExpression(); toOptimize = getFactory().generateLogicalExpression(toOptimize, "or", Arrays.asList(expr1, expr2)); toOptimize = makeFieldExpression(toOptimize, "name"); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestFieldExpressionPushedToResultExpression()); } protected abstract String getExpectedGremlinForTestFieldExpressionPushedToResultExpression(); @Test public void testOrWithNoChildren() throws AtlasException { GroovyExpression toOptimize = getVerticesExpression(); GroovyExpression expr1 = makeHasExpression(toOptimize, "name","Fred"); toOptimize = getFactory().generateLogicalExpression(expr1, "or", Collections.<GroovyExpression>emptyList()); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); //or with no children matches no vertices assertEquals(optimized.toString(), getExpectedGremlinFortestOrWithNoChildren()); } protected abstract String getExpectedGremlinFortestOrWithNoChildren(); @Test public void testFinalAliasNeeded() throws AtlasException { GroovyExpression toOptimize = getVerticesExpression(); toOptimize = makeHasExpression(toOptimize, "name", "Fred"); toOptimize = getFactory().generateAliasExpression(toOptimize, "person"); toOptimize = makeOutExpression(toOptimize, "livesIn"); GroovyExpression isChicago = makeHasExpression(null, "name", "Chicago"); GroovyExpression isBoston = makeHasExpression(null, "name", "Boston"); toOptimize = getFactory().generateLogicalExpression(toOptimize, "or", Arrays.asList(isChicago, isBoston)); toOptimize = getFactory().generateAliasExpression(toOptimize, "city"); toOptimize = makeOutExpression(toOptimize, "state"); toOptimize = makeHasExpression(toOptimize, "name", "Massachusetts"); toOptimize = getFactory().generatePathExpression(toOptimize); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestFinalAliasNeeded()); } protected abstract String getExpectedGremlinForTestFinalAliasNeeded(); @Test public void testSimpleRangeExpression() throws AtlasException { GroovyExpression expr1 = makeHasExpression(null, "name","Fred"); GroovyExpression expr2 = makeHasExpression(null, "name","George"); GroovyExpression expr3 = makeHasExpression(null, "age","34"); GroovyExpression expr4 = makeHasExpression(null, "size","small"); GroovyExpression toOptimize = getVerticesExpression(); toOptimize = getFactory().generateLogicalExpression(toOptimize, "or", Arrays.asList(expr1, expr2)); toOptimize = getFactory().generateLogicalExpression(toOptimize, "and", Collections.singletonList(expr3)); toOptimize = getFactory().generateAdjacentVerticesExpression(toOptimize, AtlasEdgeDirection.OUT, "eats"); toOptimize = getFactory().generateLogicalExpression(toOptimize, "and", Collections.singletonList(expr4)); toOptimize = makeHasExpression(toOptimize, "color","blue"); toOptimize = getFactory().generateRangeExpression(toOptimize, 0, 10); toOptimize = new FunctionCallExpression(TraversalStepType.END, toOptimize, "toList"); toOptimize = new FunctionCallExpression(toOptimize, "size"); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestSimpleRangeExpression()); } protected abstract String getExpectedGremlinForTestSimpleRangeExpression(); @Test public void testRangeWithNonZeroOffset() throws Exception { // g.V().or(has('__typeName','OMAS_OMRSAsset'),has('__superTypeNames','OMAS_OMRSAsset')).range(5,10).as('inst').select('inst') GroovyExpression toOptimize = getVerticesExpression(); GroovyExpression expr0 = makeHasExpression("__typeName", "OMAS_OMRSAsset"); GroovyExpression expr1 = makeHasExpression("__superTypeNames", "OMAS_OMRSAsset"); toOptimize = getFactory().generateLogicalExpression(toOptimize, "or", Arrays.asList(expr0, expr1)); toOptimize = getFactory().generateRangeExpression(toOptimize, 5, 10); toOptimize = getFactory().generateAliasExpression(toOptimize, "inst"); toOptimize = getFactory().generateSelectExpression(toOptimize, Collections.singletonList(new LiteralExpression("inst")), Collections.<GroovyExpression>emptyList()); RangeFinder visitor = new RangeFinder(getFactory()); GremlinQueryOptimizer.visitCallHierarchy(toOptimize, visitor); List<AbstractFunctionExpression> rangeExpressions = visitor.getRangeExpressions(); assertEquals(rangeExpressions.size(), 1); int[] rangeParameters = getFactory().getRangeParameters(rangeExpressions.get(0)); assertNotNull(rangeParameters); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); // The range optimization is not supported with a non-zero start index, so the optimizer should not add range expressions // to the expanded or's. assertEquals(optimized.toString(), getExpectedGremlinForTestRangeWithNonZeroOffset()); } protected abstract String getExpectedGremlinForTestRangeWithNonZeroOffset(); @Test public void testRangeWithOrderBy() throws Exception { // The range optimization is not supported with order, so the optimizer should not add range expressions // to the expanded or's. GroovyExpression toOptimize = getVerticesExpression(); GroovyExpression expr0 = makeHasExpression("__typeName", "OMAS_OMRSAsset"); GroovyExpression expr1 = makeHasExpression("__superTypeNames", "OMAS_OMRSAsset"); toOptimize = getFactory().generateLogicalExpression(toOptimize, "or", Arrays.asList(expr0, expr1)); toOptimize = getFactory().generateRangeExpression(toOptimize, 5, 10); toOptimize = getFactory().generateAliasExpression(toOptimize, "inst"); //toOptimize = getFactory().generateSelectExpression(toOptimize, Collections.singletonList(new LiteralExpression("inst")), Collections.<GroovyExpression>emptyList()); GroovyExpression orderFielda = makeFieldExpression(getFactory().getCurrentTraverserObject(getFactory().getClosureArgumentValue()), "name"); GroovyExpression orderFieldb = makeFieldExpression(getFactory().getCurrentTraverserObject(getFactory().getClosureArgumentValue()), "name"); toOptimize = getFactory().generateOrderByExpression(toOptimize,Arrays.asList(orderFielda, orderFieldb), true); RangeFinder visitor = new RangeFinder(getFactory()); GremlinQueryOptimizer.visitCallHierarchy(toOptimize, visitor); List<AbstractFunctionExpression> rangeExpressions = visitor.getRangeExpressions(); assertEquals(rangeExpressions.size(), 1); int[] rangeParameters = getFactory().getRangeParameters(rangeExpressions.get(0)); assertNotNull(rangeParameters); GroovyExpression optimized = GremlinQueryOptimizer.getInstance().optimize(toOptimize); assertEquals(optimized.toString(), getExpectedGremlinForTestRangeWithOrderBy()); } protected abstract String getExpectedGremlinForTestRangeWithOrderBy(); @Override public AtlasGraph get() throws RepositoryException { AtlasGraph graph = mock(AtlasGraph.class); when(graph.getSupportedGremlinVersion()).thenReturn(GremlinVersion.THREE); when(graph.isPropertyValueConversionNeeded(any(IDataType.class))).thenReturn(false); return graph; } } <|start_filename|>webapp/src/main/java/org/apache/atlas/notification/NotificationEntityChangeListener.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.notification; import com.google.common.annotations.VisibleForTesting; import org.apache.atlas.ApplicationProperties; import org.apache.atlas.AtlasException; import org.apache.atlas.listener.EntityChangeListener; import org.apache.atlas.notification.entity.EntityNotification; import org.apache.atlas.notification.entity.EntityNotificationImpl; import org.apache.atlas.typesystem.IReferenceableInstance; import org.apache.atlas.typesystem.IStruct; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.Struct; import org.apache.atlas.typesystem.types.FieldMapping; import org.apache.atlas.typesystem.types.TraitType; import org.apache.atlas.typesystem.types.TypeSystem; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.configuration.Configuration; import org.springframework.stereotype.Component; import javax.inject.Inject; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; /** * Listen to the repository for entity changes and produce entity change notifications. */ @Component public class NotificationEntityChangeListener implements EntityChangeListener { private final NotificationInterface notificationInterface; private final TypeSystem typeSystem; private Map<String, List<String>> notificationAttributesCache = new HashMap<>(); private static final String ATLAS_ENTITY_NOTIFICATION_PROPERTY = "atlas.notification.entity"; static Configuration APPLICATION_PROPERTIES = null; // ----- Constructors ------------------------------------------------------ /** * Construct a NotificationEntityChangeListener. * * @param notificationInterface the notification framework interface * @param typeSystem the Atlas type system */ @Inject public NotificationEntityChangeListener(NotificationInterface notificationInterface, TypeSystem typeSystem) { this.notificationInterface = notificationInterface; this.typeSystem = typeSystem; } // ----- EntityChangeListener ---------------------------------------------- @Override public void onEntitiesAdded(Collection<ITypedReferenceableInstance> entities, boolean isImport) throws AtlasException { notifyOfEntityEvent(entities, EntityNotification.OperationType.ENTITY_CREATE); } @Override public void onEntitiesUpdated(Collection<ITypedReferenceableInstance> entities, boolean isImport) throws AtlasException { notifyOfEntityEvent(entities, EntityNotification.OperationType.ENTITY_UPDATE); } @Override public void onTraitsAdded(ITypedReferenceableInstance entity, Collection<? extends IStruct> traits) throws AtlasException { notifyOfEntityEvent(Collections.singleton(entity), EntityNotification.OperationType.TRAIT_ADD); } @Override public void onTraitsDeleted(ITypedReferenceableInstance entity, Collection<String> traitNames) throws AtlasException { notifyOfEntityEvent(Collections.singleton(entity), EntityNotification.OperationType.TRAIT_DELETE); } @Override public void onTraitsUpdated(ITypedReferenceableInstance entity, Collection<? extends IStruct> traits) throws AtlasException { notifyOfEntityEvent(Collections.singleton(entity), EntityNotification.OperationType.TRAIT_UPDATE); } @Override public void onEntitiesDeleted(Collection<ITypedReferenceableInstance> entities, boolean isImport) throws AtlasException { notifyOfEntityEvent(entities, EntityNotification.OperationType.ENTITY_DELETE); } // ----- helper methods ------------------------------------------------- // ----- helper methods ---------------------------------------------------- @VisibleForTesting public static List<IStruct> getAllTraits(IReferenceableInstance entityDefinition, TypeSystem typeSystem) throws AtlasException { List<IStruct> traitInfo = new LinkedList<>(); for (String traitName : entityDefinition.getTraits()) { IStruct trait = entityDefinition.getTrait(traitName); String typeName = trait.getTypeName(); Map<String, Object> valuesMap = trait.getValuesMap(); traitInfo.add(new Struct(typeName, valuesMap)); traitInfo.addAll(getSuperTraits(typeName, valuesMap, typeSystem)); } return traitInfo; } private static List<IStruct> getSuperTraits( String typeName, Map<String, Object> values, TypeSystem typeSystem) throws AtlasException { List<IStruct> superTypes = new LinkedList<>(); TraitType traitDef = typeSystem.getDataType(TraitType.class, typeName); Set<String> superTypeNames = traitDef.getAllSuperTypeNames(); for (String superTypeName : superTypeNames) { TraitType superTraitDef = typeSystem.getDataType(TraitType.class, superTypeName); Map<String, Object> superTypeValues = new HashMap<>(); FieldMapping fieldMapping = superTraitDef.fieldMapping(); if (fieldMapping != null) { Set<String> superTypeAttributeNames = fieldMapping.fields.keySet(); for (String superTypeAttributeName : superTypeAttributeNames) { if (values.containsKey(superTypeAttributeName)) { superTypeValues.put(superTypeAttributeName, values.get(superTypeAttributeName)); } } } IStruct superTrait = new Struct(superTypeName, superTypeValues); superTypes.add(superTrait); superTypes.addAll(getSuperTraits(superTypeName, values, typeSystem)); } return superTypes; } // send notification of entity change private void notifyOfEntityEvent(Collection<ITypedReferenceableInstance> entityDefinitions, EntityNotification.OperationType operationType) throws AtlasException { List<EntityNotification> messages = new LinkedList<>(); for (IReferenceableInstance entityDefinition : entityDefinitions) { Referenceable entity = new Referenceable(entityDefinition); Map<String, Object> attributesMap = entity.getValuesMap(); List<String> entityNotificationAttrs = getNotificationAttributes(entity.getTypeName()); if (MapUtils.isNotEmpty(attributesMap) && CollectionUtils.isNotEmpty(entityNotificationAttrs)) { for (String entityAttr : attributesMap.keySet()) { if (!entityNotificationAttrs.contains(entityAttr)) { entity.setNull(entityAttr); } } } EntityNotificationImpl notification = new EntityNotificationImpl(entity, operationType, getAllTraits(entity, typeSystem)); messages.add(notification); } notificationInterface.send(NotificationInterface.NotificationType.ENTITIES, messages); } private List<String> getNotificationAttributes(String entityType) { List<String> ret = null; initApplicationProperties(); if (notificationAttributesCache.containsKey(entityType)) { ret = notificationAttributesCache.get(entityType); } else if (APPLICATION_PROPERTIES != null) { String[] notificationAttributes = APPLICATION_PROPERTIES.getStringArray(ATLAS_ENTITY_NOTIFICATION_PROPERTY + "." + entityType + "." + "attributes.include"); if (notificationAttributes != null) { ret = Arrays.asList(notificationAttributes); } notificationAttributesCache.put(entityType, ret); } return ret; } private void initApplicationProperties() { if (APPLICATION_PROPERTIES == null) { try { APPLICATION_PROPERTIES = ApplicationProperties.get(); } catch (AtlasException ex) { // ignore } } } } <|start_filename|>graphdb/titan1/src/main/java/org/apache/atlas/repository/graphdb/titan1/query/Titan1GraphQuery.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan1.query; import org.apache.atlas.repository.graphdb.AtlasGraphQuery; import org.apache.atlas.repository.graphdb.titan.query.TitanGraphQuery; import org.apache.atlas.repository.graphdb.titan.query.NativeTitanGraphQuery; import org.apache.atlas.repository.graphdb.titan.query.NativeTitanQueryFactory; import org.apache.atlas.repository.graphdb.titan1.Titan1Edge; import org.apache.atlas.repository.graphdb.titan1.Titan1Graph; import org.apache.atlas.repository.graphdb.titan1.Titan1Vertex; /** * Titan 1.0.0 implementation of TitanGraphQuery. */ public class Titan1GraphQuery extends TitanGraphQuery<Titan1Vertex, Titan1Edge> implements NativeTitanQueryFactory<Titan1Vertex, Titan1Edge> { public Titan1GraphQuery(Titan1Graph graph, boolean isChildQuery) { super(graph, isChildQuery); } public Titan1GraphQuery(Titan1Graph graph) { super(graph); } @Override public AtlasGraphQuery<Titan1Vertex, Titan1Edge> createChildQuery() { return new Titan1GraphQuery((Titan1Graph) graph, true); } @Override protected NativeTitanQueryFactory<Titan1Vertex, Titan1Edge> getQueryFactory() { return this; } @Override public NativeTitanGraphQuery<Titan1Vertex, Titan1Edge> createNativeTitanQuery() { return new NativeTitan1GraphQuery((Titan1Graph) graph); } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/graph/TypedInstanceToGraphMapper.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graph; import com.google.common.base.Function; import com.google.common.collect.Lists; import org.apache.atlas.AtlasException; import org.apache.atlas.RequestContext; import org.apache.atlas.model.instance.GuidMapping; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.RepositoryException; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasSchemaViolationException; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.typesystem.IReferenceableInstance; import org.apache.atlas.typesystem.ITypedInstance; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.ITypedStruct; import org.apache.atlas.typesystem.exception.EntityExistsException; import org.apache.atlas.typesystem.exception.EntityNotFoundException; import org.apache.atlas.typesystem.persistence.Id; import org.apache.atlas.typesystem.persistence.ReferenceableInstance; import org.apache.atlas.typesystem.types.*; import org.apache.atlas.typesystem.types.DataTypes.TypeCategory; import org.apache.atlas.typesystem.types.utils.TypesUtil; import org.apache.atlas.util.AtlasRepositoryConfiguration; import org.apache.atlas.utils.SHA256Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.inject.Inject; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static org.apache.atlas.repository.graph.GraphHelper.string; @Component @Deprecated public final class TypedInstanceToGraphMapper { private static final Logger LOG = LoggerFactory.getLogger(TypedInstanceToGraphMapper.class); private final Map<Id, AtlasVertex> idToVertexMap = new HashMap<>(); private final TypeSystem typeSystem = TypeSystem.getInstance(); private static final GraphHelper graphHelper = GraphHelper.getInstance(); private DeleteHandler deleteHandler; private GraphToTypedInstanceMapper graphToTypedInstanceMapper; @Inject public TypedInstanceToGraphMapper(GraphToTypedInstanceMapper graphToTypedInstanceMapper, DeleteHandler deleteHandler) { this.graphToTypedInstanceMapper = graphToTypedInstanceMapper; this.deleteHandler = deleteHandler; } private final String SIGNATURE_HASH_PROPERTY_KEY = Constants.INTERNAL_PROPERTY_KEY_PREFIX + "signature"; public enum Operation { CREATE, UPDATE_PARTIAL, UPDATE_FULL } void mapTypedInstanceToGraph(Operation operation, ITypedReferenceableInstance... typedInstances) throws AtlasException { RequestContext requestContext = RequestContext.get(); Collection<IReferenceableInstance> allNewInstances = new ArrayList<>(); for (ITypedReferenceableInstance typedInstance : typedInstances) { allNewInstances.addAll(walkClassInstances(typedInstance)); } TypeUtils.Pair<List<ITypedReferenceableInstance>, List<ITypedReferenceableInstance>> instancesPair = createVerticesAndDiscoverInstances(allNewInstances); List<ITypedReferenceableInstance> entitiesToCreate = instancesPair.left; List<ITypedReferenceableInstance> entitiesToUpdate = instancesPair.right; FullTextMapper fulltextMapper = new FullTextMapper(this, graphToTypedInstanceMapper); switch (operation) { case CREATE: List<String> ids = addOrUpdateAttributesAndTraits(operation, entitiesToCreate); addFullTextProperty(entitiesToCreate, fulltextMapper); requestContext.recordEntityCreate(ids); break; case UPDATE_FULL: case UPDATE_PARTIAL: ids = addOrUpdateAttributesAndTraits(Operation.CREATE, entitiesToCreate); requestContext.recordEntityCreate(ids); ids = addOrUpdateAttributesAndTraits(operation, entitiesToUpdate); requestContext.recordEntityUpdate(ids); addFullTextProperty(entitiesToCreate, fulltextMapper); addFullTextProperty(entitiesToUpdate, fulltextMapper); break; default: throw new UnsupportedOperationException("Not handled - " + operation); } for(ITypedReferenceableInstance instance : typedInstances) { addToEntityCache(requestContext, instance); } } private Collection<IReferenceableInstance> walkClassInstances(ITypedReferenceableInstance typedInstance) throws RepositoryException { EntityProcessor entityProcessor = new EntityProcessor(); try { if (LOG.isDebugEnabled()) { LOG.debug("Walking the object graph for instance {}", typedInstance.toShortString()); } new ObjectGraphWalker(typeSystem, entityProcessor, typedInstance).walk(); } catch (AtlasException me) { throw new RepositoryException("TypeSystem error when walking the ObjectGraph", me); } entityProcessor.addInstanceIfNotExists(typedInstance); return entityProcessor.getInstances(); } private List<String> addOrUpdateAttributesAndTraits(Operation operation, List<ITypedReferenceableInstance> instances) throws AtlasException { List<String> guids = new ArrayList<>(); for (ITypedReferenceableInstance instance : instances) { try { //new vertex, set all the properties String guid = addOrUpdateAttributesAndTraits(operation, instance); guids.add(guid); } catch (AtlasSchemaViolationException e) { throw new EntityExistsException(instance, e); } } return guids; } private String addOrUpdateAttributesAndTraits(Operation operation, ITypedReferenceableInstance typedInstance) throws AtlasException { if (LOG.isDebugEnabled()) { LOG.debug("Adding/Updating typed instance {}", typedInstance.toShortString()); } Id id = typedInstance.getId(); if (id == null) { // oops throw new RepositoryException("id cannot be null"); } AtlasVertex instanceVertex = idToVertexMap.get(id); // add the attributes for the instance ClassType classType = typeSystem.getDataType(ClassType.class, typedInstance.getTypeName()); final Map<String, AttributeInfo> fields = classType.fieldMapping().fields; mapInstanceToVertex(typedInstance, instanceVertex, fields, false, operation); if (Operation.CREATE.equals(operation)) { //TODO - Handle Trait updates addTraits(typedInstance, instanceVertex, classType); } return getId(typedInstance)._getId(); } void mapInstanceToVertex(ITypedInstance typedInstance, AtlasVertex instanceVertex, Map<String, AttributeInfo> fields, boolean mapOnlyUniqueAttributes, Operation operation) throws AtlasException { if (LOG.isDebugEnabled()) { LOG.debug("Mapping instance {} to vertex {}", typedInstance.toShortString(), string(instanceVertex)); } for (AttributeInfo attributeInfo : fields.values()) { if (mapOnlyUniqueAttributes && !attributeInfo.isUnique) { continue; } mapAttributeToVertex(typedInstance, instanceVertex, attributeInfo, operation); } GraphHelper.setProperty(instanceVertex, Constants.MODIFICATION_TIMESTAMP_PROPERTY_KEY, RequestContext.get().getRequestTime()); GraphHelper.setProperty(instanceVertex, Constants.MODIFIED_BY_KEY, RequestContext.get().getUser()); if (LOG.isDebugEnabled()) { LOG.debug("Setting modifiedBy: {} and modifiedTime: {}", RequestContext.get().getUser(), RequestContext.get().getRequestTime()); } } void mapAttributeToVertex(ITypedInstance typedInstance, AtlasVertex instanceVertex, AttributeInfo attributeInfo, Operation operation) throws AtlasException { if ( typedInstance.isValueSet(attributeInfo.name) || operation == Operation.CREATE ) { Object attrValue = typedInstance.get(attributeInfo.name); if (LOG.isDebugEnabled()) { LOG.debug("Mapping attribute {} = {}", attributeInfo.name, attrValue); } switch (attributeInfo.dataType().getTypeCategory()) { case PRIMITIVE: case ENUM: mapPrimitiveOrEnumToVertex(typedInstance, instanceVertex, attributeInfo); break; case ARRAY: mapArrayCollectionToVertex(typedInstance, instanceVertex, attributeInfo, operation); break; case MAP: mapMapCollectionToVertex(typedInstance, instanceVertex, attributeInfo, operation); break; case STRUCT: case CLASS: String edgeLabel = graphHelper.getEdgeLabel(typedInstance, attributeInfo); AtlasEdge currentEdge = graphHelper.getEdgeForLabel(instanceVertex, edgeLabel); AtlasEdge newEdge = addOrUpdateReference(instanceVertex, attributeInfo, attributeInfo.dataType(), attrValue, currentEdge, edgeLabel, operation); if (currentEdge != null && !currentEdge.equals(newEdge)) { deleteHandler.deleteEdgeReference(currentEdge, attributeInfo.dataType().getTypeCategory(), attributeInfo.isComposite, true); } if (attributeInfo.reverseAttributeName != null && newEdge != null) { addReverseReference(instanceVertex, attributeInfo.reverseAttributeName, newEdge); } break; case TRAIT: // do NOTHING - this is taken care of earlier break; default: throw new IllegalArgumentException("Unknown type category: " + attributeInfo.dataType().getTypeCategory()); } } } private TypeUtils.Pair<List<ITypedReferenceableInstance>, List<ITypedReferenceableInstance>> createVerticesAndDiscoverInstances( Collection<IReferenceableInstance> instances) throws AtlasException { List<ITypedReferenceableInstance> instancesToCreate = new ArrayList<>(); List<ITypedReferenceableInstance> instancesToUpdate = new ArrayList<>(); Map<Id,AtlasVertex> foundVertices = findExistingVertices(instances); //cache all the ids idToVertexMap.putAll(foundVertices); Set<Id> processedIds = new HashSet<>(); for(IReferenceableInstance instance : instances) { Id id = instance.getId(); if(processedIds.contains(id)) { continue; } AtlasVertex instanceVertex = foundVertices.get(id); ClassType classType = typeSystem.getDataType(ClassType.class, instance.getTypeName()); if(instanceVertex == null) { if(LOG.isDebugEnabled()) { LOG.debug("Creating new vertex for instance {}", instance.toShortString()); } ITypedReferenceableInstance newInstance = classType.convert(instance, Multiplicity.REQUIRED); instanceVertex = graphHelper.createVertexWithIdentity(newInstance, classType.getAllSuperTypeNames()); instancesToCreate.add(newInstance); //Map only unique attributes for cases of circular references mapInstanceToVertex(newInstance, instanceVertex, classType.fieldMapping().fields, true, Operation.CREATE); idToVertexMap.put(id, instanceVertex); } else { if(LOG.isDebugEnabled()) { LOG.debug("Re-using existing vertex {} for instance {}", string(instanceVertex), instance.toShortString()); } if (!(instance instanceof ITypedReferenceableInstance)) { throw new IllegalStateException( String.format("%s is not of type ITypedReferenceableInstance", instance.toShortString())); } ITypedReferenceableInstance existingInstance = (ITypedReferenceableInstance) instance; instancesToUpdate.add(existingInstance); } processedIds.add(id); } return TypeUtils.Pair.of(instancesToCreate, instancesToUpdate); } private Map<Id,AtlasVertex> findExistingVertices(Collection<IReferenceableInstance> instances) throws AtlasException { VertexLookupContext context = new VertexLookupContext(this); Map<Id,AtlasVertex> result = new HashMap<>(); for(IReferenceableInstance instance : instances) { context.addInstance(instance); } List<Id> instancesToLoad = new ArrayList<>(context.getInstancesToLoadByGuid()); List<String> guidsToLoad = Lists.transform(instancesToLoad, new Function<Id,String>() { @Override public String apply(Id instance) { Id id = getExistingId(instance); return id.id; } }); Map<String, AtlasVertex> instanceVertices = graphHelper.getVerticesForGUIDs(guidsToLoad); List<String> missingGuids = new ArrayList<>(); for(int i = 0 ; i < instancesToLoad.size(); i++) { String guid = guidsToLoad.get(i); AtlasVertex instanceVertex = instanceVertices.get(guid); if(instanceVertex == null) { missingGuids.add(guid); continue; } Id instance = instancesToLoad.get(i); if(LOG.isDebugEnabled()) { LOG.debug("Found vertex {} for instance {}", string(instanceVertex), instance); } result.put(instance, instanceVertex); } if(missingGuids.size() > 0) { throw new EntityNotFoundException("Could not find entities in the repository with the following GUIDs: " + missingGuids); } for(Map.Entry<ClassType,List<IReferenceableInstance>> entry : context.getInstancesToLoadByUniqueAttribute().entrySet()) { ClassType type = entry.getKey(); List<IReferenceableInstance> instancesForClass = entry.getValue(); List<AtlasVertex> correspondingVertices = graphHelper.getVerticesForInstancesByUniqueAttribute(type, instancesForClass); for(int i = 0; i < instancesForClass.size(); i++) { IReferenceableInstance inst = instancesForClass.get(i); AtlasVertex vertex = correspondingVertices.get(i); result.put(getExistingId(inst), vertex); } } return result; } private void addFullTextProperty(List<ITypedReferenceableInstance> instances, FullTextMapper fulltextMapper) throws AtlasException { if(! AtlasRepositoryConfiguration.isFullTextSearchEnabled()) { return; } for (ITypedReferenceableInstance typedInstance : instances) { // Traverse AtlasVertex instanceVertex = getClassVertex(typedInstance); String fullText = fulltextMapper.mapRecursive(instanceVertex, true); GraphHelper.setProperty(instanceVertex, Constants.ENTITY_TEXT_PROPERTY_KEY, fullText); } } private void addTraits(ITypedReferenceableInstance typedInstance, AtlasVertex instanceVertex, ClassType classType) throws AtlasException { for (String traitName : typedInstance.getTraits()) { if (LOG.isDebugEnabled()) { LOG.debug("mapping trait {}", traitName); } GraphHelper.addProperty(instanceVertex, Constants.TRAIT_NAMES_PROPERTY_KEY, traitName); ITypedStruct traitInstance = (ITypedStruct) typedInstance.getTrait(traitName); // add the attributes for the trait instance mapTraitInstanceToVertex(traitInstance, classType, instanceVertex); } } /******************************************** ARRAY **************************************************/ private void mapArrayCollectionToVertex(ITypedInstance typedInstance, AtlasVertex instanceVertex, AttributeInfo attributeInfo, Operation operation) throws AtlasException { if (LOG.isDebugEnabled()) { LOG.debug("Mapping instance {} for array attribute {} vertex {}", typedInstance.toShortString(), attributeInfo.name, string(instanceVertex)); } List newElements = (List) typedInstance.get(attributeInfo.name); boolean newAttributeEmpty = (newElements == null || newElements.isEmpty()); IDataType elementType = ((DataTypes.ArrayType) attributeInfo.dataType()).getElemType(); String propertyName = GraphHelper.getQualifiedFieldName(typedInstance, attributeInfo); List<Object> currentElements = GraphHelper.getArrayElementsProperty(elementType, instanceVertex, propertyName); List<Object> newElementsCreated = new ArrayList<>(); if (!newAttributeEmpty) { int index = 0; for (; index < newElements.size(); index++) { Object currentElement = (currentElements != null && index < currentElements.size()) ? currentElements.get(index) : null; if (LOG.isDebugEnabled()) { LOG.debug("Adding/updating element at position {}, current element {}, new element {}", index, currentElement, newElements.get(index)); } Object newEntry = addOrUpdateCollectionEntry(instanceVertex, attributeInfo, elementType, newElements.get(index), currentElement, propertyName, operation); newElementsCreated.add(newEntry); } } if(GraphHelper.isReference(elementType)) { if (attributeInfo.reverseAttributeName != null && newElementsCreated.size() > 0) { // Set/add the new reference value(s) on the reverse reference. for (Object newElement : newElementsCreated) { if ((newElement instanceof AtlasEdge)) { AtlasEdge newEdge = (AtlasEdge) newElement; addReverseReference(instanceVertex, attributeInfo.reverseAttributeName, newEdge); } else { throw new AtlasException("Invalid array element type " + newElement.getClass().getName() + " - expected " + AtlasEdge.class.getName() + " for reference " + GraphHelper.getQualifiedFieldName(typedInstance, attributeInfo) + " on vertex " + GraphHelper.getVertexDetails(instanceVertex)); } } } List<AtlasEdge> additionalEdges = removeUnusedEntries(instanceVertex, propertyName, (List)currentElements, (List)newElementsCreated, elementType, attributeInfo); newElementsCreated.addAll(additionalEdges); } // for dereference on way out GraphHelper.setArrayElementsProperty(elementType, instanceVertex, propertyName, newElementsCreated); } //Removes unused edges from the old collection, compared to the new collection private List<AtlasEdge> removeUnusedEntries(AtlasVertex instanceVertex, String edgeLabel, Collection<AtlasEdge> currentEntries, Collection<AtlasEdge> newEntries, IDataType entryType, AttributeInfo attributeInfo) throws AtlasException { if (currentEntries != null && !currentEntries.isEmpty()) { LOG.debug("Removing unused entries from the old collection"); if (entryType.getTypeCategory() == TypeCategory.STRUCT || entryType.getTypeCategory() == TypeCategory.CLASS) { //Remove the edges for (current edges - new edges) List<AtlasEdge> cloneElements = new ArrayList<>(currentEntries); cloneElements.removeAll(newEntries); List<AtlasEdge> additionalElements = new ArrayList<>(); if (LOG.isDebugEnabled()) { LOG.debug("Removing unused entries from the old collection - {}", cloneElements); } if (!cloneElements.isEmpty()) { for (AtlasEdge edge : cloneElements) { boolean deleted = deleteHandler.deleteEdgeReference(edge, entryType.getTypeCategory(), attributeInfo.isComposite, true); if (!deleted) { additionalElements.add(edge); } } } return additionalElements; } } return new ArrayList<>(); } /******************************************** MAP **************************************************/ private void mapMapCollectionToVertex(ITypedInstance typedInstance, AtlasVertex instanceVertex, AttributeInfo attributeInfo, Operation operation) throws AtlasException { if (LOG.isDebugEnabled()) { LOG.debug("Mapping instance {} to vertex {} for attribute {}", typedInstance.toShortString(), string(instanceVertex), attributeInfo.name); } @SuppressWarnings("unchecked") Map<Object, Object> newAttribute = (Map<Object, Object>) typedInstance.get(attributeInfo.name); boolean newAttributeEmpty = (newAttribute == null || newAttribute.isEmpty()); IDataType elementType = ((DataTypes.MapType) attributeInfo.dataType()).getValueType(); String propertyName = GraphHelper.getQualifiedFieldName(typedInstance, attributeInfo); Map<String, Object> currentMap = new HashMap<>(); Map<String, Object> newMap = new HashMap<>(); List<String> currentKeys = GraphHelper.getListProperty(instanceVertex, propertyName); if (currentKeys != null && !currentKeys.isEmpty()) { for (String key : currentKeys) { String propertyNameForKey = GraphHelper.getQualifiedNameForMapKey(propertyName, key); Object propertyValueForKey = GraphHelper.getMapValueProperty(elementType, instanceVertex, propertyNameForKey); currentMap.put(key, propertyValueForKey); } } if (!newAttributeEmpty) { for (Map.Entry<Object,Object> entry : newAttribute.entrySet()) { String keyStr = entry.getKey().toString(); String propertyNameForKey = GraphHelper.getQualifiedNameForMapKey(propertyName, keyStr); Object newEntry = addOrUpdateCollectionEntry(instanceVertex, attributeInfo, elementType, entry.getValue(), currentMap.get(keyStr), propertyNameForKey, operation); //Add/Update/Remove property value GraphHelper.setMapValueProperty(elementType, instanceVertex, propertyNameForKey, newEntry); newMap.put(keyStr, newEntry); } } Map<String, Object> additionalMap = removeUnusedMapEntries(instanceVertex, propertyName, currentMap, newMap, elementType, attributeInfo); Set<String> newKeys = new HashSet<>(newMap.keySet()); newKeys.addAll(additionalMap.keySet()); // for dereference on way out GraphHelper.setListProperty(instanceVertex, propertyName, new ArrayList<>(newKeys)); } //Remove unused entries from map private Map<String, Object> removeUnusedMapEntries( AtlasVertex instanceVertex, String propertyName, Map<String, Object> currentMap, Map<String, Object> newMap, IDataType elementType, AttributeInfo attributeInfo) throws AtlasException { Map<String, Object> additionalMap = new HashMap<>(); for (String currentKey : currentMap.keySet()) { boolean shouldDeleteKey = !newMap.containsKey(currentKey); if (GraphHelper.isReference(elementType)) { //Delete the edge reference if its not part of new edges created/updated AtlasEdge currentEdge = (AtlasEdge)currentMap.get(currentKey); if (!newMap.values().contains(currentEdge)) { boolean deleted = deleteHandler.deleteEdgeReference(currentEdge, elementType.getTypeCategory(), attributeInfo.isComposite, true); if (!deleted) { additionalMap.put(currentKey, currentEdge); shouldDeleteKey = false; } } } if (shouldDeleteKey) { String propertyNameForKey = GraphHelper.getQualifiedNameForMapKey(propertyName, currentKey); GraphHelper.setProperty(instanceVertex, propertyNameForKey, null); } } return additionalMap; } /******************************************** ARRAY & MAP **************************************************/ private Object addOrUpdateCollectionEntry(AtlasVertex instanceVertex, AttributeInfo attributeInfo, IDataType elementType, Object newAttributeValue, Object currentValue, String propertyName, Operation operation) throws AtlasException { switch (elementType.getTypeCategory()) { case PRIMITIVE: case ENUM: return newAttributeValue != null ? newAttributeValue : null; case ARRAY: case MAP: case TRAIT: // do nothing return null; case STRUCT: case CLASS: final String edgeLabel = GraphHelper.EDGE_LABEL_PREFIX + propertyName; return addOrUpdateReference(instanceVertex, attributeInfo, elementType, newAttributeValue, (AtlasEdge)currentValue, edgeLabel, operation); default: throw new IllegalArgumentException("Unknown type category: " + elementType.getTypeCategory()); } } private AtlasEdge addOrUpdateReference(AtlasVertex instanceVertex, AttributeInfo attributeInfo, IDataType attributeType, Object newAttributeValue, AtlasEdge currentEdge, String edgeLabel, Operation operation) throws AtlasException { switch (attributeType.getTypeCategory()) { case STRUCT: return addOrUpdateStruct(instanceVertex, attributeInfo, (ITypedStruct) newAttributeValue, currentEdge, edgeLabel, operation); case CLASS: return addOrUpdateClassVertex(instanceVertex, currentEdge, (ITypedReferenceableInstance) newAttributeValue, attributeInfo, edgeLabel); default: throw new IllegalArgumentException("Unknown type category: " + attributeType.getTypeCategory()); } } /******************************************** STRUCT **************************************************/ private AtlasEdge addOrUpdateStruct(AtlasVertex instanceVertex, AttributeInfo attributeInfo, ITypedStruct newAttributeValue, AtlasEdge currentEdge, String edgeLabel, Operation operation) throws AtlasException { AtlasEdge newEdge = null; if (GraphHelper.elementExists(currentEdge) && newAttributeValue != null) { //update updateStructVertex(newAttributeValue, currentEdge, operation); newEdge = currentEdge; } else if (! GraphHelper.elementExists(currentEdge) && newAttributeValue != null) { //add newEdge = addStructVertex(newAttributeValue, instanceVertex, attributeInfo, edgeLabel); } return newEdge; } private AtlasEdge addStructVertex(ITypedStruct structInstance, AtlasVertex instanceVertex, AttributeInfo attributeInfo, String edgeLabel) throws AtlasException { // add a new vertex for the struct or trait instance AtlasVertex structInstanceVertex = graphHelper.createVertexWithoutIdentity(structInstance.getTypeName(), null, Collections.<String>emptySet()); // no super types for struct type if (LOG.isDebugEnabled()) { LOG.debug("created vertex {} for struct {} value {}", string(structInstanceVertex), attributeInfo.name, structInstance.toShortString()); } // map all the attributes to this new vertex mapInstanceToVertex(structInstance, structInstanceVertex, structInstance.fieldMapping().fields, false, Operation.CREATE); // add an edge to the newly created vertex from the parent AtlasEdge newEdge = graphHelper.getOrCreateEdge(instanceVertex, structInstanceVertex, edgeLabel); return newEdge; } private void updateStructVertex(ITypedStruct newAttributeValue, AtlasEdge currentEdge, Operation operation) throws AtlasException { //Already existing vertex. Update AtlasVertex structInstanceVertex = currentEdge.getInVertex(); if (LOG.isDebugEnabled()) { LOG.debug("Updating struct vertex {} with struct {}", string(structInstanceVertex), newAttributeValue.toShortString()); } // Update attributes final MessageDigest digester = SHA256Utils.getDigester(); String newSignature = newAttributeValue.getSignatureHash(digester); String curSignature = GraphHelper.getSingleValuedProperty(structInstanceVertex, SIGNATURE_HASH_PROPERTY_KEY, String.class); if (!newSignature.equals(curSignature)) { //Update struct vertex instance only if there is a change if (LOG.isDebugEnabled()) { LOG.debug("Updating struct {} since signature has changed {} {} ", newAttributeValue, curSignature, newSignature); } mapInstanceToVertex(newAttributeValue, structInstanceVertex, newAttributeValue.fieldMapping().fields, false, operation); GraphHelper.setProperty(structInstanceVertex, SIGNATURE_HASH_PROPERTY_KEY, String.valueOf(newSignature)); } } /******************************************** CLASS **************************************************/ private AtlasEdge addOrUpdateClassVertex(AtlasVertex instanceVertex, AtlasEdge currentEdge, ITypedReferenceableInstance newAttributeValue, AttributeInfo attributeInfo, String edgeLabel) throws AtlasException { AtlasVertex newReferenceVertex = getClassVertex(newAttributeValue); if( ! GraphHelper.elementExists(newReferenceVertex) && newAttributeValue != null) { LOG.error("Could not find vertex for Class Reference {}", newAttributeValue); throw new EntityNotFoundException("Could not find vertex for Class Reference " + newAttributeValue); } AtlasEdge newEdge = null; if (GraphHelper.elementExists(currentEdge) && newAttributeValue != null) { newEdge = updateClassEdge(instanceVertex, currentEdge, newAttributeValue, newReferenceVertex, attributeInfo, edgeLabel); } else if (! GraphHelper.elementExists(currentEdge) && newAttributeValue != null){ newEdge = addClassEdge(instanceVertex, newReferenceVertex, edgeLabel); } return newEdge; } private AtlasEdge addClassEdge(AtlasVertex instanceVertex, AtlasVertex toVertex, String edgeLabel) throws AtlasException { // add an edge to the class vertex from the instance return graphHelper.getOrCreateEdge(instanceVertex, toVertex, edgeLabel); } private <V,E> AtlasVertex<V,E> getClassVertex(ITypedReferenceableInstance typedReference) throws EntityNotFoundException { AtlasVertex<V,E> referenceVertex = null; Id id = null; if (typedReference != null) { id = getExistingId(typedReference); referenceVertex = idToVertexMap.get(id); if(referenceVertex == null && id.isAssigned()) { referenceVertex = graphHelper.getVertexForGUID(id.id); } } return referenceVertex; } Id getExistingId(IReferenceableInstance instance) { return instance instanceof Id ? (Id) instance : instance.getId(); } private Id getId(ITypedReferenceableInstance typedReference) throws EntityNotFoundException { if (typedReference == null) { throw new IllegalArgumentException("typedReference must be non-null"); } Id id = typedReference instanceof Id ? (Id) typedReference : typedReference.getId(); if (id.isUnassigned()) { AtlasVertex classVertex = idToVertexMap.get(id); String guid = GraphHelper.getGuid(classVertex); id = new Id(guid, 0, typedReference.getTypeName()); } return id; } private AtlasEdge updateClassEdge(AtlasVertex instanceVertex, AtlasEdge currentEdge, ITypedReferenceableInstance newAttributeValue, AtlasVertex newVertex, AttributeInfo attributeInfo, String edgeLabel) throws AtlasException { if (LOG.isDebugEnabled()) { LOG.debug("Updating {} for reference attribute {}", string(currentEdge), attributeInfo.name); } // Update edge if it exists AtlasVertex currentVertex = currentEdge.getInVertex(); String currentEntityId = GraphHelper.getGuid(currentVertex); String newEntityId = getId(newAttributeValue).id; AtlasEdge newEdge = currentEdge; if (!currentEntityId.equals(newEntityId)) { // add an edge to the class vertex from the instance if (newVertex != null) { newEdge = graphHelper.getOrCreateEdge(instanceVertex, newVertex, edgeLabel); } } return newEdge; } /******************************************** TRAITS ****************************************************/ void mapTraitInstanceToVertex(ITypedStruct traitInstance, IDataType entityType, AtlasVertex parentInstanceVertex) throws AtlasException { // add a new AtlasVertex for the struct or trait instance final String traitName = traitInstance.getTypeName(); AtlasVertex traitInstanceVertex = graphHelper.createVertexWithoutIdentity(traitInstance.getTypeName(), null, typeSystem.getDataType(TraitType.class, traitName).getAllSuperTypeNames()); if (LOG.isDebugEnabled()) { LOG.debug("created vertex {} for trait {}", string(traitInstanceVertex), traitName); } // map all the attributes to this newly created AtlasVertex mapInstanceToVertex(traitInstance, traitInstanceVertex, traitInstance.fieldMapping().fields, false, Operation.CREATE); // add an edge to the newly created AtlasVertex from the parent String relationshipLabel = GraphHelper.getTraitLabel(entityType.getName(), traitName); graphHelper.getOrCreateEdge(parentInstanceVertex, traitInstanceVertex, relationshipLabel); } /******************************************** PRIMITIVES **************************************************/ private void mapPrimitiveOrEnumToVertex(ITypedInstance typedInstance, AtlasVertex instanceVertex, AttributeInfo attributeInfo) throws AtlasException { Object attrValue = typedInstance.get(attributeInfo.name); final String vertexPropertyName = GraphHelper.getQualifiedFieldName(typedInstance, attributeInfo); Object propertyValue = null; if (attrValue == null) { propertyValue = null; } else if (attributeInfo.dataType() == DataTypes.STRING_TYPE) { propertyValue = typedInstance.getString(attributeInfo.name); } else if (attributeInfo.dataType() == DataTypes.SHORT_TYPE) { propertyValue = typedInstance.getShort(attributeInfo.name); } else if (attributeInfo.dataType() == DataTypes.INT_TYPE) { propertyValue = typedInstance.getInt(attributeInfo.name); } else if (attributeInfo.dataType() == DataTypes.BIGINTEGER_TYPE) { propertyValue = typedInstance.getBigInt(attributeInfo.name); } else if (attributeInfo.dataType() == DataTypes.BOOLEAN_TYPE) { propertyValue = typedInstance.getBoolean(attributeInfo.name); } else if (attributeInfo.dataType() == DataTypes.BYTE_TYPE) { propertyValue = typedInstance.getByte(attributeInfo.name); } else if (attributeInfo.dataType() == DataTypes.LONG_TYPE) { propertyValue = typedInstance.getLong(attributeInfo.name); } else if (attributeInfo.dataType() == DataTypes.FLOAT_TYPE) { propertyValue = typedInstance.getFloat(attributeInfo.name); } else if (attributeInfo.dataType() == DataTypes.DOUBLE_TYPE) { propertyValue = typedInstance.getDouble(attributeInfo.name); } else if (attributeInfo.dataType() == DataTypes.BIGDECIMAL_TYPE) { propertyValue = typedInstance.getBigDecimal(attributeInfo.name); } else if (attributeInfo.dataType() == DataTypes.DATE_TYPE) { final Date dateVal = typedInstance.getDate(attributeInfo.name); //Convert Property value to Long while persisting if (dateVal != null) { propertyValue = dateVal.getTime(); } } else if (attributeInfo.dataType().getTypeCategory() == TypeCategory.ENUM) { if (attrValue != null) { propertyValue = ((EnumValue) attrValue).value; } } GraphHelper.setProperty(instanceVertex, vertexPropertyName, propertyValue); } public AtlasVertex lookupVertex(Id refId) { return idToVertexMap.get(refId); } private void addToEntityCache(RequestContext context, ITypedReferenceableInstance instance) throws EntityNotFoundException { Id instanceId = instance.getId(); if(instanceId.isUnassigned()) { if(instance instanceof ReferenceableInstance) { //When the id is unassigned, we can only cache the instance of it is //an instance of ReferenceableInstance, since replaceWithNewId is not //currently in the ITypedReferenceableInstance interface. Id id = getId(instance); ((ReferenceableInstance)instance).replaceWithNewId(id); context.cache(instance); } } else { context.cache(instance); } } public GuidMapping createGuidMapping() { Map<String,String> mapping = new HashMap<>(idToVertexMap.size()); for(Map.Entry<Id, AtlasVertex> entry : idToVertexMap.entrySet()) { Id id = entry.getKey(); if (id.isUnassigned()) { AtlasVertex classVertex = entry.getValue(); mapping.put(id._getId(), GraphHelper.getGuid(classVertex)); } } return new GuidMapping(mapping); } private <V,E> void addReverseReference(AtlasVertex<V,E> vertex, String reverseAttributeName, AtlasEdge<V,E> edge) throws AtlasException { String typeName = GraphHelper.getTypeName(vertex); Id id = GraphHelper.getIdFromVertex(typeName, vertex); AtlasVertex<V, E> reverseVertex = edge.getInVertex(); String reverseTypeName = GraphHelper.getTypeName(reverseVertex); Id reverseId = GraphHelper.getIdFromVertex(reverseTypeName, reverseVertex); IDataType reverseType = typeSystem.getDataType(IDataType.class, reverseTypeName); AttributeInfo reverseAttrInfo = TypesUtil.getFieldMapping(reverseType).fields.get(reverseAttributeName); if (reverseAttrInfo.dataType().getTypeCategory() == TypeCategory.MAP) { // If the reverse reference is a map, what would be used as the key? // Not supporting automatic update of reverse map references. LOG.debug("Automatic update of reverse map reference is not supported - reference = {}", GraphHelper.getQualifiedFieldName(reverseType, reverseAttributeName)); return; } String propertyName = GraphHelper.getQualifiedFieldName(reverseType, reverseAttributeName); String reverseEdgeLabel = GraphHelper.EDGE_LABEL_PREFIX + propertyName; AtlasEdge<V, E> reverseEdge = graphHelper.getEdgeForLabel(reverseVertex, reverseEdgeLabel); AtlasEdge<V, E> newEdge = null; if (reverseEdge != null) { newEdge = updateClassEdge(reverseVertex, reverseEdge, id, vertex, reverseAttrInfo, reverseEdgeLabel); } else { newEdge = addClassEdge(reverseVertex, vertex, reverseEdgeLabel); } switch (reverseAttrInfo.dataType().getTypeCategory()) { case CLASS: if (reverseEdge != null && !reverseEdge.getId().toString().equals(newEdge.getId().toString())) { // Disconnect old reference deleteHandler.deleteEdgeReference(reverseEdge, reverseAttrInfo.dataType().getTypeCategory(), reverseAttrInfo.isComposite, true); } break; case ARRAY: // Add edge ID to property value List<String> elements = reverseVertex.getProperty(propertyName, List.class); if (elements == null) { elements = new ArrayList<>(); elements.add(newEdge.getId().toString()); reverseVertex.setProperty(propertyName, elements); } else { if (!elements.contains(newEdge.getId().toString())) { elements.add(newEdge.getId().toString()); reverseVertex.setProperty(propertyName, elements); } } break; } RequestContext requestContext = RequestContext.get(); GraphHelper.setProperty(reverseVertex, Constants.MODIFICATION_TIMESTAMP_PROPERTY_KEY, requestContext.getRequestTime()); requestContext.recordEntityUpdate(reverseId._getId()); } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/graph/VertexLookupContext.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graph; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.atlas.AtlasException; import org.apache.atlas.typesystem.IReferenceableInstance; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.persistence.Id; import org.apache.atlas.typesystem.types.AttributeInfo; import org.apache.atlas.typesystem.types.ClassType; import org.apache.atlas.typesystem.types.DataTypes; import org.apache.atlas.typesystem.types.IDataType; import org.apache.atlas.typesystem.types.Multiplicity; import org.apache.atlas.typesystem.types.TypeSystem; import org.apache.atlas.typesystem.types.DataTypes.TypeCategory; /** * Helper class for TypedInstanceGraphMapper. Determines which instances * should be loaded by GUID and which ones should be loaded by unique attribute. * In addition, it sorts the instances that should be loaded by unique * attribute by class. * */ public class VertexLookupContext { private final TypedInstanceToGraphMapper mapper; private static final TypeSystem typeSystem = TypeSystem.getInstance(); private Map<ClassType,List<IReferenceableInstance>> instancesWithoutGuids = new HashMap<>(); private Set<Id> guidsToLookup = new HashSet<>(); /** * @param typedInstanceToGraphMapper */ VertexLookupContext(TypedInstanceToGraphMapper typedInstanceToGraphMapper) { mapper = typedInstanceToGraphMapper; } /** * Adds an instance to be loaded. * */ public void addInstance(IReferenceableInstance instance) throws AtlasException { ClassType classType = typeSystem.getDataType(ClassType.class, instance.getTypeName()); ITypedReferenceableInstance newInstance = classType.convert(instance, Multiplicity.REQUIRED); findReferencedInstancesToPreLoad(newInstance); Id id = instance.getId(); if(mapper.lookupVertex(id) == null) { if(id.isAssigned()) { guidsToLookup.add(id); } else { addToClassMap(classType, instance); } } } /** * Returns the instances that should be loaded by unique attribute, sorted by * class. * */ public Map<ClassType,List<IReferenceableInstance>> getInstancesToLoadByUniqueAttribute() { return instancesWithoutGuids; } /** * Returns the Ids of the instance that should be loaded by GUID * * @return */ public Set<Id> getInstancesToLoadByGuid() { return guidsToLookup; } private void addToClassMap(ClassType classType, IReferenceableInstance instance) throws AtlasException { List<IReferenceableInstance> toUpdate = instancesWithoutGuids.get(classType); if(toUpdate == null) { toUpdate = new ArrayList<>(); instancesWithoutGuids.put(classType, toUpdate); } toUpdate.add(instance); } private void findReferencedInstancesToPreLoad(ITypedReferenceableInstance newInstance) throws AtlasException { //pre-load vertices for reference fields for(AttributeInfo info : newInstance.fieldMapping().fields.values()) { if(info.dataType().getTypeCategory() == TypeCategory.CLASS) { ITypedReferenceableInstance newAttributeValue = (ITypedReferenceableInstance)newInstance.get(info.name); addAdditionalInstance(newAttributeValue); } if(info.dataType().getTypeCategory() == TypeCategory.ARRAY) { IDataType elementType = ((DataTypes.ArrayType) info.dataType()).getElemType(); if(elementType.getTypeCategory() == TypeCategory.CLASS) { List<ITypedReferenceableInstance> newElements = (List) newInstance.get(info.name); addAdditionalInstances(newElements); } } if(info.dataType().getTypeCategory() == TypeCategory.MAP) { IDataType elementType = ((DataTypes.MapType) info.dataType()).getValueType(); if(elementType.getTypeCategory() == TypeCategory.CLASS) { Map<Object, ITypedReferenceableInstance> newAttribute = (Map<Object, ITypedReferenceableInstance>) newInstance.get(info.name); if(newAttribute != null) { addAdditionalInstances(newAttribute.values()); } } } } } private void addAdditionalInstance(ITypedReferenceableInstance instance) { if(instance == null) { return; } Id id = mapper.getExistingId(instance); if(! id.isAssigned()) { return; } guidsToLookup.add(id); } private void addAdditionalInstances(Collection<ITypedReferenceableInstance> newElements) { if(newElements != null) { for(ITypedReferenceableInstance instance: newElements) { addAdditionalInstance(instance); } } } } <|start_filename|>repository/src/main/java/org/apache/atlas/gremlin/optimizer/ExpandOrsOptimization.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.gremlin.optimizer; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.apache.atlas.gremlin.GremlinExpressionFactory; import org.apache.atlas.groovy.AbstractFunctionExpression; import org.apache.atlas.groovy.ClosureExpression; import org.apache.atlas.groovy.FunctionCallExpression; import org.apache.atlas.groovy.GroovyExpression; import org.apache.atlas.groovy.LiteralExpression; import org.apache.atlas.groovy.StatementListExpression; import org.apache.atlas.groovy.TraversalStepType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; /** * Optimization that removes 'or' expressions from a graph traversal when possible * and replaces them with separate calls that are combined using a logical union operation. * Unfortunately, Titan does not use indices when executing the child graph traversals associated * with an 'or' call. In order to make the index be used, we split queries with * or expressions into multiple queries. These queries are executed individually, * using indices, and then the results are combined back together. Here is a * simple example to illustrate this: * * <h4>Original Query</h4> * * <pre> * g.V().or(has('name','Fred'),has('age','17')) * </pre> * *<h4>Optimized Query</h4> * * <pre> * def r = [] as Set; * g.V().has('name','Fred').fill(r); * g.V().has('age','17').fill(r); * r; * </pre> * * Here, we introduce an intermediate variable "r" which is declared as a Set. The Set is performing * the union for us. If there are vertices that happen to both have "Fred" as the name and "17" as the age, * the Set will prevent the second query execution from adding a duplicate vertex to the result. Recall that * in Groovy scripts, the last expression is the one that will be returned back to the caller. We refer to * that expression is the "result expression". For this example, the result expression is simply "r", which * contains the vertices that matched the query. * <p/> * If the query does any kind of transformation of the vertices to produce the query result, that needs * to be done in the result expression. To understand why that is, let's take a look at another example: * * <h4>Original Query</h4> * * <pre> * g.V().or(has('name','Fred'),has('age','17')).as('person').select('person').by('gender') * </pre> * * <h4>Incorrect Optimized Query</h4> * * <pre> * def r = [] as Set; * g.V().has('name','Fred').as('person').select('person').by('gender').fill(r) * g.V().has('age','17').as('person').select('person').by('gender').fill(r) * r; * </pre> * * The problem with this query is that now 'r' contains Strings (the gender of the person). Suppose * that there is one person named Fred and there are 3 people whose age is 17 (let's say Fred's age is 16). * The original query would have produced 4 rows, one corresponding to each of those people. The new * query would produce at most 2 rows - one for 'male' and one for 'female'. This is happening because * we are now performing the union on the Strings, not on the vertices. To fix this, we need to split * the original query and put the end portion into the result expression: * * <h4>Correct Optimized Query</h4> * * <pre> * def r = [] as Set; * g.V().has('name','Fred').fill(r) * g.V().has('age','17').fill(r) * __.inject(r as Object[]).as('person').select('person').by('gender') * </pre> * * The logic for doing this splitting is described in more detail in * {@link #moveTransformationsToResultExpression(GroovyExpression, OptimizationContext)}. * <p/> * There is one more problematic case that this optimizer is able to handle. Let's look at the following example: * * <h4>Original Query</h4> * * <pre> * g.V().or(has('type','Person'),has('superType','Person')).as('x').has('qualifiedName','Fred').as('y').select('x','y').by('name').by('name') * </pre> * * Queries of this form appear often when translating DSL queries. * * If we were to optimize this query using the logic described above, we would get something like this: * * <h4>Incorrect Optimized Query</h4> * * <pre> * def r = [] as Set; * g.V().has('type','Person').fill(r); * g.V().has('superType','Person').fill(r); * __.inject(r as Object[]).as('x').has('qualifiedName','Fred').as('y').select('x','y'); * </pre> * * While not strictly incorrect, this query will not perform well since the index on qualifiedName will * not be used. In order for that index to be used, the 'has' expression needs to be part of the original * query. However, if we do that alone, the query will be broken, since the select * will now refer to an undefined label: * * <h4>Incorrect Optimized Query</h4> * * <pre> * def r = [] as Set; * g.V().has('type','Person').as('x').has('qualifiedName','Fred').fill(r); * g.V().has('superType','Person').as('x').has('qualifiedName','Fred').fill(r); * __.inject(r as Object[]).as('y').select('x','y') * </pre> * * To fix this, we need to save the values of the aliased vertices in the original * query, and create labels in the result expression that refer to them. We do this * as follows: * * <h4>Correct Optimized Query</h4> * * <pre> * def r = [] as Set; * g.V().has('type','Person').as('x').has('qualifiedName','Fred').as('y').select('x','y').fill(r); * g.V().has('superType','Person').as('x').has('qualifiedName','Fred').select('x','y').fill(r); * __.inject(r as Object[]).as('__tmp').map({((Map)it.get()).get('x')}).as('x').select('__tmp').map({((Map)it.get()).get('x')}).as('y').select('x','y').by('name').by('name') * </pre> * * This is not pretty, but is the best solution we've found so far for supporting expressions that contain aliases in this optimization. * What ends up happening is that r gets populated with alias->Vertex maps. In the result expression, we make 'x' point * to a step where the value in the traverser is the vertex for 'x', and we do the same thing for y. The <code>select('_tmp')</code> step in the middle restores the value of * the traverser back to the map. * <p/> * The one known issue with the alias rearrangement is that it breaks loop expressions. As a result, expressions containing loops are currently excluded * from this optimization. * * ExpandOrsOptimization expands the entire expression tree recursively, so it is not invoked * recursively by GremlinQueryOptimizer. * */ public class ExpandOrsOptimization implements GremlinOptimization { private static final Logger logger_ = LoggerFactory.getLogger(ExpandOrsOptimization.class); private final GremlinExpressionFactory factory; public ExpandOrsOptimization(GremlinExpressionFactory factory) { this.factory = factory; } @Override public boolean appliesTo(GroovyExpression expr, OptimizationContext contxt) { ExpressionFinder finder = new ExpressionFinder(IsOr.INSTANCE); GremlinQueryOptimizer.visitCallHierarchy(expr, finder); return finder.isExpressionFound(); } @Override public GroovyExpression apply(GroovyExpression expr, OptimizationContext context) { setupRangeOptimization(expr, context); GroovyExpression traveralExpression = moveTransformationsToResultExpression(expr, context); FunctionGenerator functionGenerator = new FunctionGenerator(factory, context); GremlinQueryOptimizer.visitCallHierarchy(traveralExpression, functionGenerator); traveralExpression = functionGenerator.getNewRootExpression(); List<GroovyExpression> bodyExpressions = expandOrs(traveralExpression, context); //Adds a statement to define the result variable 'v' in the //groovy script. The variable is declared as a Set. The type //of the objects in the Set depend on the number of aliases in the Groovy // expression: // - 0 or 1 alias : Vertex // - multiple aliases: Map<String,Vertex> StatementListExpression result = new StatementListExpression(); context.prependStatement(context.getDefineResultVariableStmt()); for (GroovyExpression bodyExpression : bodyExpressions) { result.addStatement(bodyExpression); } result.addStatement(context.getResultExpression()); return result; } private void setupRangeOptimization(GroovyExpression expr, OptimizationContext context) { // Find any range expressions in the expression tree. RangeFinder rangeFinder = new RangeFinder(factory); GremlinQueryOptimizer.visitCallHierarchy(expr, rangeFinder); List<AbstractFunctionExpression> rangeExpressions = rangeFinder.getRangeExpressions(); if (rangeExpressions.size() == 1) { OrderFinder orderFinder = new OrderFinder(factory); GremlinQueryOptimizer.visitCallHierarchy(expr, orderFinder); if (!orderFinder.hasOrderExpression()) { // If there is one range expression and no order expression in the unoptimized gremlin, // save the range parameters to use for adding a range expression to // each expanded "or" expression result, such that it will only contain the specified range of vertices. // For now, apply this optimization only if the range start index is zero. AbstractFunctionExpression rangeExpression = rangeExpressions.get(0); int[] rangeParameters = factory.getRangeParameters(rangeExpression); if (rangeParameters[0] == 0) { context.setRangeExpression(rangeExpression); } } } } private GroovyExpression moveTransformationsToResultExpression(GroovyExpression expr, OptimizationContext context) { GroovyExpression traveralExpression = expr; // Determine the 'split point'. This is the expression that will become // the deepest function call in the result expression. If a split // point is found, its caller is changed. The new caller is // set to the graph traversal expression in the result expression. // The original caller becomes the new traversal expression that // will be carried through the rest of the 'or' expansion processing. // // Example: g.V().has('x').as('x').select('x') // Here, select('x') is the split expression // so : // 1) the result expression in OptimizationContext becomes [base result expression].select('x') // 2) we return g.V().has('x').as('x') SplitPointFinder finder = new SplitPointFinder(factory); GremlinQueryOptimizer.visitCallHierarchy(traveralExpression, finder); AbstractFunctionExpression splitPoint = finder.getSplitPoint(); List<LiteralExpression> aliases = new ArrayList<>(); //If we're not splitting the query, there is no need to save/restore //the aliases. if(splitPoint != null) { traveralExpression = splitPoint.getCaller(); AliasFinder aliasFinder = new AliasFinder(); GremlinQueryOptimizer.visitCallHierarchy(traveralExpression, aliasFinder); aliases.addAll(aliasFinder.getAliases()); if(aliasFinder.isFinalAliasNeeded()) { //The last alias in the expression does not capture the final vertex in the traverser, //so we need to create an alias to record that. traveralExpression = factory.generateAliasExpression(traveralExpression, context.getFinalAliasName()); aliases.add(new LiteralExpression(context.getFinalAliasName())); } GroovyExpression resultExpr = getBaseResultExpression(context, aliases); splitPoint.setCaller(resultExpr); expr = removeMapFromPathsIfNeeded(expr, aliases); context.setResultExpression(expr); } //Add expression(s) to the end of the traversal expression to add the vertices //that were found into the intermediate variable ('r') traveralExpression = addCallToUpdateResultVariable(traveralExpression, aliases, context); return traveralExpression; } private GroovyExpression removeMapFromPathsIfNeeded(GroovyExpression expr, List<LiteralExpression> aliases) { if(aliases.size() > 0 && factory.isSelectGeneratesMap(aliases.size())) { RepeatExpressionFinder repeatExprFinder = new RepeatExpressionFinder(factory); GremlinQueryOptimizer.visitCallHierarchy(expr, repeatExprFinder); boolean hasRepeat = repeatExprFinder.isRepeatExpressionFound(); PathExpressionFinder pathExprFinder = new PathExpressionFinder(); GremlinQueryOptimizer.visitCallHierarchy(expr, pathExprFinder); boolean hasPath = pathExprFinder.isPathExpressionFound(); if(! hasRepeat && hasPath) { //the path will now start with the map that we added. That is an artifact //of the optimization process and must be removed. if(expr.getType() != TraversalStepType.END && expr.getType() != TraversalStepType.NONE) { //we're still in the pipeline, need to execute the query before we can //modify the result expr = factory.generateToListExpression(expr); } expr = factory.removeExtraMapFromPathInResult(expr); } } return expr; } /** * This method adds steps to the end of the initial traversal to add the vertices * that were found into an intermediate variable (defined as a Set). If there is one alias, * this set will contain the vertices associated with that Alias. If there are multiple * aliases, the values in the set will be alias->vertex maps that have the vertex * associated with the alias for each result. * @param expr * @param aliasNames * @param context * @return */ private GroovyExpression addCallToUpdateResultVariable(GroovyExpression expr,List<LiteralExpression> aliasNames, OptimizationContext context) { GroovyExpression result = expr; // If there is one range expression in the unoptimized gremlin, // add a range expression here so that the intermediate variable will only contain // the specified range of vertices. AbstractFunctionExpression rangeExpression = context.getRangeExpression(); if (rangeExpression != null) { int[] rangeParameters = factory.getRangeParameters(rangeExpression); result = factory.generateRangeExpression(result, rangeParameters[0], rangeParameters[1]); } if( ! aliasNames.isEmpty()) { result = factory.generateSelectExpression(result, aliasNames, Collections.<GroovyExpression>emptyList()); } return factory.generateFillExpression(result, context.getResultVariable()); } /** * Recursively traverses the given expression, expanding or expressions * wherever they are found. * * @param expr * @param context * @return expressions that should be unioned together to get the query result */ private List<GroovyExpression> expandOrs(GroovyExpression expr, OptimizationContext context) { if (GremlinQueryOptimizer.isOrExpression(expr)) { return expandOrFunction(expr, context); } return processOtherExpression(expr, context); } /** * This method takes an 'or' expression and expands it into multiple expressions. * * For example: * * g.V().or(has('x'),has('y') * * is expanded to: * * g.V().has('x') * g.V().has('y') * * There are certain cases where it is not safe to move an expression out * of the 'or'. For example, in the expression * * g.V().or(has('x').out('y'),has('z')) * * has('x').out('y') cannot be moved out of the 'or', since it changes the value of the traverser. * * At this time, the ExpandOrsOptimizer is not able to handle this scenario, so we don't remove * that expression. In cases like this, a final expression is created that ors together * all of the expressions that could not be extracted. In this case that would be: * * g.V().has('z') * g.V().or(has('y').out('z')) * * This processing is done recursively. * * * @param expr * @param context * @return the expressions that should be unioned together to get the query result */ private List<GroovyExpression> expandOrFunction(GroovyExpression expr, OptimizationContext context) { FunctionCallExpression functionCall = (FunctionCallExpression) expr; GroovyExpression caller = functionCall.getCaller(); List<GroovyExpression> updatedCallers = null; if (caller != null) { updatedCallers = expandOrs(caller, context); } else { updatedCallers = Collections.singletonList(null); } UpdatedExpressions newArguments = getUpdatedChildren(functionCall.getArguments(), context); List<GroovyExpression> allUpdatedArguments = new ArrayList<>(); for (List<GroovyExpression> exprs : newArguments.getUpdatedChildren()) { allUpdatedArguments.addAll(exprs); } List<AbstractFunctionExpression> extractableArguments = new ArrayList<>(); List<GroovyExpression> nonExtractableArguments = new ArrayList<>(); for (GroovyExpression argument : allUpdatedArguments) { if (GremlinQueryOptimizer.isExtractable(argument)) { extractableArguments.add((AbstractFunctionExpression) argument); } else { logger_.warn("Found non-extractable argument '{}; in the 'or' expression '{}'",argument.toString(), expr.toString()); nonExtractableArguments.add(argument); } } List<GroovyExpression> result = new ArrayList<>(); for (GroovyExpression updatedCaller : updatedCallers) { for (AbstractFunctionExpression arg : extractableArguments) { GroovyExpression updated = GremlinQueryOptimizer.copyWithNewLeafNode(arg, updatedCaller); result.add(updated); } if (!nonExtractableArguments.isEmpty()) { result.add(factory.generateLogicalExpression(updatedCaller, "or", nonExtractableArguments)); } } return result; } private UpdatedExpressions getUpdatedChildren(List<GroovyExpression> children, OptimizationContext context) { List<List<GroovyExpression>> updatedChildren = new ArrayList<>(); boolean changed = false; for (GroovyExpression child : children) { List<GroovyExpression> childChoices = expandOrs(child, context); if (childChoices.size() != 1 || childChoices.iterator().next() != child) { changed = true; } updatedChildren.add(childChoices); } return new UpdatedExpressions(changed, updatedChildren); } private UpdatedExpressions getUpdatedChildren(GroovyExpression expr, OptimizationContext context) { return getUpdatedChildren(expr.getChildren(), context); } /** * This is called when we encounter an expression that is not an "or", for example an "and" expressio. For these * expressions, we process the children and create copies with the cartesian product of the updated * arguments. * * Example: * * g.V().and(or(has('x),has('y'), or(has('a'),has('b'))) * * Here, we have an "and" expression with two children: * * 1) or(has('x),has('y') * 2) or(has('a'),has('b')) * * We first process these children. They each yield 2 expressions: * * 1 -> [ has('x'), has('y') ] * 2 -> [ has('a'), has('b') ] * * The cartesian product of these gives this: * * [ has('x'), has('a') ] * [ has('x'), has('b') ] * [ has('y'), has('a') ] * [ has('y'), has('b') ] * * So the overall result is: * * g.V().and(has('x'), has('a')) * g.V().and(has('x'), has('b')) * g.V().and(has('y'), has('a')) * g.V().and(has('y'), has('b')) * * * @param source * @param context * @return expressions that should be unioned together to get the query result */ private List<GroovyExpression> processOtherExpression(GroovyExpression source, OptimizationContext context) { UpdatedExpressions updatedChildren = getUpdatedChildren(source, context); if (!updatedChildren.hasChanges()) { return Collections.singletonList(source); } List<GroovyExpression> result = new ArrayList<GroovyExpression>(); //The updated children list we get back has the possible values for each child //in the expression. We compute a cartesian product to get all possible //combinations of child values. List<List<GroovyExpression>> updateChildLists = Lists.cartesianProduct(updatedChildren.getUpdatedChildren()); for (List<GroovyExpression> updatedChildList : updateChildLists) { result.add(source.copy(updatedChildList)); } return result; } @Override public boolean isApplyRecursively() { return false; } /** * * This method creates a base result expression that recreates the state of the * graph traverser at start of the result expression to what it would have been * if we had been executing one Gremlin query (instead of many and doing a union). * * To do this, we start with an anonymous graph traversal that will iterate * through the values in the intermediate Set that was created. We then need * to set things up so that the aliases that were in the original gremlin query * refer to steps with the correct traverser value. * * The way we do this depends on the number of aliases. If there are 0 or 1 alias, * the intermediate variable already contains Vertices, so we just create the alias. * * If there are multiple aliases, the intermediate variable contains a String->Vertex * map. We first create a temporary alias that refers to that map. For each alias, * we use a MapStep to map the map to the Vertex for that alias. We then add back * the alias, making it refer to the MapStep. Between the alias restorations, we restore the * traverser object back to the map. * * @param context * @param aliases * @return */ private GroovyExpression getBaseResultExpression(OptimizationContext context, List<LiteralExpression> aliases) { //Start with an anonymous traversal that gets its objects from the intermediate result variable. GroovyExpression parent = factory.generateSeededTraversalExpresssion(aliases.size() > 1, context.getResultVariable()); if(aliases.isEmpty()) { return parent; } //The expression we will return. GroovyExpression result = parent; //We use a temporary alias to save/restore the original value of the traverser //at the start of the query. We do this so we can set the value of the traverser //back to being the map after we retrieve each alias. If there is only one //alias, the save/restore is not needed, so there is no need to create this alias. if(aliases.size() > 1) { result = factory.generateAliasExpression(result, context.getTempAliasName()); } Iterator<LiteralExpression> it = aliases.iterator(); while(it.hasNext()) { LiteralExpression curAlias = it.next(); //A map is only generated by Gremlin when there is more than one alias. When there is only one //alias, the intermediate variable will directly contain the vertices.` if(factory.isSelectGeneratesMap(aliases.size())) { //Since there is more than one alias, the current traverser object is an alias->vertex //map. We use a MapStep to map that map to the Vertex for the current alias. This sets //the current traverser object to that Vertex. We do this by defining the closure we //pass to the MapStep call [map].get(aliasName) where [map] is the expression //that refers to the map. GroovyExpression rowMapExpr = factory.getCurrentTraverserObject(factory.getClosureArgumentValue()); GroovyExpression getExpr = factory.generateGetSelectedValueExpression(curAlias, rowMapExpr); result = factory.generateMapExpression(result, new ClosureExpression(getExpr)); } //Create alias that points to the previous step. The traverser value at that step //is the Vertex associated with this alias. result = factory.generateAliasExpression(result, curAlias.getValue().toString()); if(it.hasNext()) { //Restore the current value of the traverser back to the current alias->vertex map result = factory.generateBackReferenceExpression(result, false, context.getTempAliasName()); } } return result; } } <|start_filename|>graphdb/titan1/src/main/java/org/apache/atlas/repository/graphdb/titan1/Titan1Vertex.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan1; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasEdgeDirection; import org.apache.atlas.repository.graphdb.AtlasSchemaViolationException; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.repository.graphdb.AtlasVertexQuery; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.structure.VertexProperty; import com.thinkaurelius.titan.core.SchemaViolationException; import com.thinkaurelius.titan.core.TitanVertex; /** * Titan 1.0.0 implementation of AtlasVertex. */ public class Titan1Vertex extends Titan1Element<Vertex> implements AtlasVertex<Titan1Vertex, Titan1Edge> { public Titan1Vertex(Titan1Graph graph, Vertex source) { super(graph, source); } @Override public <T> void addProperty(String propertyName, T value) { try { getWrappedElement().property(VertexProperty.Cardinality.set, propertyName, value); } catch(SchemaViolationException e) { throw new AtlasSchemaViolationException(e); } } @Override public Iterable<AtlasEdge<Titan1Vertex, Titan1Edge>> getEdges(AtlasEdgeDirection dir, String edgeLabel) { Direction d = TitanObjectFactory.createDirection(dir); Iterator<Edge> edges = getWrappedElement().edges(d, edgeLabel); return graph.wrapEdges(edges); } private TitanVertex getAsTitanVertex() { return (TitanVertex)getWrappedElement(); } @Override public Iterable<AtlasEdge<Titan1Vertex, Titan1Edge>> getEdges(AtlasEdgeDirection in) { Direction d = TitanObjectFactory.createDirection(in); Iterator<Edge> edges = getWrappedElement().edges(d); return graph.wrapEdges(edges); } @Override public <T> Collection<T> getPropertyValues(String propertyName, Class<T> clazz) { Collection<T> result = new ArrayList<T>(); Iterator<VertexProperty<T>> it = getWrappedElement().properties(propertyName); while(it.hasNext()) { result.add(it.next().value()); } return result; } @Override public AtlasVertexQuery<Titan1Vertex, Titan1Edge> query() { return new Titan1VertexQuery(graph, getAsTitanVertex().query()); } @Override public Titan1Vertex getV() { return this; } } <|start_filename|>graphdb/api/src/main/java/org/apache/atlas/repository/graphdb/AtlasGraphManagement.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb; import java.util.List; /** * Management interface for a graph. * */ public interface AtlasGraphManagement { /** * Checks whether a property with the given key has been defined in the graph schema. * * @param key * @return */ boolean containsPropertyKey(String key); /** * Creates a full text index for the given property. * * @param indexName the name of the index to create * @param propertyKey full text property to index * @param backingIndex the name of the backing index to use */ void createFullTextIndex(String indexName, AtlasPropertyKey propertyKey, String backingIndex); /** * Rolls back the changes that have been made to the management system. */ void rollback(); /** * Commits the changes that have been made to the management system. */ void commit(); /** * @param propertyName * @param propertyClass * @param cardinality * @return */ AtlasPropertyKey makePropertyKey(String propertyName, Class propertyClass, AtlasCardinality cardinality); /** * @param propertyKey * */ void deletePropertyKey(String propertyKey); /** * @param propertyName * @return */ AtlasPropertyKey getPropertyKey(String propertyName); /** * Creates a composite index for the graph. * * @param propertyName * @param isUnique * @param propertyKeys */ void createExactMatchIndex(String propertyName, boolean isUnique, List<AtlasPropertyKey> propertyKeys); /** * Looks up the index with the specified name in the graph. Returns null if * there is no index with the given name. * * @param indexName * @return */ AtlasGraphIndex getGraphIndex(String indexName); /** * Creates a mixed Vertex index for the graph. * * @param name the name of the index to create * @param backingIndex the name of the backing index to use */ void createVertexIndex(String name, String backingIndex, List<AtlasPropertyKey> propertyKeys); /** * Adds a property key to the given index in the graph. * * @param vertexIndex * @param propertyKey */ void addVertexIndexKey(String vertexIndex, AtlasPropertyKey propertyKey); /** * Creates a mixed Edge index for the graph. * * @param index the name of the index to create * @param backingIndex the name of the backing index to use */ void createEdgeIndex(String index, String backingIndex); } <|start_filename|>authorization/src/main/java/org/apache/atlas/authorize/simple/PolicyUtil.java<|end_filename|> /** Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.authorize.simple; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.atlas.authorize.AtlasActionTypes; import org.apache.atlas.authorize.AtlasResourceTypes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PolicyUtil { private static Logger LOG = LoggerFactory.getLogger(PolicyUtil.class); private static boolean isDebugEnabled = LOG.isDebugEnabled(); public static Map<String, Map<AtlasResourceTypes, List<String>>> createPermissionMap(List<PolicyDef> policyDefList, AtlasActionTypes permissionType, SimpleAtlasAuthorizer.AtlasAccessorTypes principalType) { if (isDebugEnabled) { LOG.debug("==> PolicyUtil createPermissionMap\nCreating Permission Map for :: {} & {}", permissionType, principalType); } Map<String, Map<AtlasResourceTypes, List<String>>> userReadMap = new HashMap<>(); // Iterate over the list of policies to create map for (PolicyDef policyDef : policyDefList) { if (LOG.isDebugEnabled()) { LOG.debug("Processing policy def : {}", policyDef); } Map<String, List<AtlasActionTypes>> principalMap = principalType.equals(SimpleAtlasAuthorizer.AtlasAccessorTypes.USER) ? policyDef.getUsers() : policyDef .getGroups(); // For every policy extract the resource list and populate the user map for (Entry<String, List<AtlasActionTypes>> e : principalMap.entrySet()) { // Check if the user has passed permission type like READ if (!e.getValue().contains(permissionType)) { continue; } // See if the current user is already added to map String username = e.getKey(); Map<AtlasResourceTypes, List<String>> userResourceList = userReadMap.get(username); // If its not added then create a new resource list if (userResourceList == null) { if (isDebugEnabled) { LOG.debug("Resource list not found for {}, creating it", username); } userResourceList = new HashMap<>(); } /* * Iterate over resources from the current policy def and update the resource list for the current user */ for (Entry<AtlasResourceTypes, List<String>> resourceTypeMap : policyDef.getResources().entrySet()) { // For the current resourceType in the policyDef, get the // current list of resources already added AtlasResourceTypes type = resourceTypeMap.getKey(); List<String> resourceList = userResourceList.get(type); if (resourceList == null) { // if the resource list was not added for this type then // create and add all the resources in this policy resourceList = new ArrayList<>(); resourceList.addAll(resourceTypeMap.getValue()); } else { // if the resource list is present then merge both the // list resourceList.removeAll(resourceTypeMap.getValue()); resourceList.addAll(resourceTypeMap.getValue()); } userResourceList.put(type, resourceList); } userReadMap.put(username, userResourceList); if (LOG.isDebugEnabled()) { LOG.debug("userReadMap {}", userReadMap); } } } if (isDebugEnabled) { LOG.debug("Returning Map for {} :: {}", principalType, userReadMap); LOG.debug("<== PolicyUtil createPermissionMap"); } return userReadMap; } } <|start_filename|>intg/src/main/java/org/apache/atlas/type/AtlasType.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.type; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.TypeCategory; import org.apache.atlas.model.typedef.AtlasBaseTypeDef; import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.ObjectMapper; import java.io.IOException; import java.util.List; /** * base class that declares interface for all Atlas types. */ public abstract class AtlasType { private static final ObjectMapper mapper = new ObjectMapper() .configure(DeserializationConfig.Feature.USE_BIG_DECIMAL_FOR_FLOATS, true); private final String typeName; private final TypeCategory typeCategory; protected AtlasType(AtlasBaseTypeDef typeDef) { this(typeDef.getName(), typeDef.getCategory()); } protected AtlasType(String typeName, TypeCategory typeCategory) { this.typeName = typeName; this.typeCategory = typeCategory; } public void resolveReferences(AtlasTypeRegistry typeRegistry) throws AtlasBaseException { } public void resolveReferencesPhase2(AtlasTypeRegistry typeRegistry) throws AtlasBaseException { } public void resolveReferencesPhase3(AtlasTypeRegistry typeRegistry) throws AtlasBaseException { } public String getTypeName() { return typeName; } public TypeCategory getTypeCategory() { return typeCategory; } public abstract Object createDefaultValue(); public Object createOptionalDefaultValue() { return createDefaultValue(); } public Object createDefaultValue(Object val){ return val == null ? createDefaultValue() : getNormalizedValue(val); } public abstract boolean isValidValue(Object obj); public abstract Object getNormalizedValue(Object obj); public boolean validateValue(Object obj, String objName, List<String> messages) { boolean ret = isValidValue(obj); if (!ret) { messages.add(objName + "=" + obj + ": invalid value for type " + getTypeName()); } return ret; } public boolean isValidValueForUpdate(Object obj) { return isValidValue(obj); } public Object getNormalizedValueForUpdate(Object obj) { return getNormalizedValue(obj); } public boolean validateValueForUpdate(Object obj, String objName, List<String> messages) { return validateValue(obj, objName, messages); } /* for attribute of entity-type, the value would be of AtlasObjectId * when an attribute instance is created i.e. AtlasAttribute, this method * will be called to get AtlasEntityType replaced with AtlasObjectType */ public AtlasType getTypeForAttribute() { return this; } public static String toJson(Object obj) { String ret; try { ret = mapper.writeValueAsString(obj); }catch (IOException e){ ret = null; } return ret; } public static <T> T fromJson(String jsonStr, Class<T> type) { T ret; try { ret = mapper.readValue(jsonStr, type); }catch (IOException e){ ret = null; } return ret; } } <|start_filename|>graphdb/titan0/src/main/java/org/apache/atlas/repository/graphdb/titan0/Titan0Vertex.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan0; import java.util.ArrayList; import java.util.Collection; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasEdgeDirection; import org.apache.atlas.repository.graphdb.AtlasSchemaViolationException; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.repository.graphdb.AtlasVertexQuery; import com.thinkaurelius.titan.core.SchemaViolationException; import com.thinkaurelius.titan.core.TitanProperty; import com.thinkaurelius.titan.core.TitanVertex; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Vertex; /** * Titan 0.5.4 implementation of AtlasVertex. */ public class Titan0Vertex extends Titan0Element<Vertex> implements AtlasVertex<Titan0Vertex, Titan0Edge> { public Titan0Vertex(Titan0Graph graph, Vertex source) { super(graph, source); } @Override public Iterable<AtlasEdge<Titan0Vertex, Titan0Edge>> getEdges(AtlasEdgeDirection dir, String edgeLabel) { Iterable<Edge> titanEdges = wrappedElement.getEdges(TitanObjectFactory.createDirection(dir), edgeLabel); return graph.wrapEdges(titanEdges); } private TitanVertex getAsTitanVertex() { return (TitanVertex) wrappedElement; } @Override public Iterable<AtlasEdge<Titan0Vertex, Titan0Edge>> getEdges(AtlasEdgeDirection in) { Iterable<Edge> titanResult = wrappedElement.getEdges(TitanObjectFactory.createDirection(in)); return graph.wrapEdges(titanResult); } @Override public <T> T getProperty(String propertyName, Class<T> clazz) { if (graph.isMultiProperty(propertyName)) { // throw exception in this case to be consistent with Titan 1.0.0 // behavior. throw new IllegalStateException(); } return super.getProperty(propertyName, clazz); } public <T> void setProperty(String propertyName, T value) { try { super.setProperty(propertyName, value); } catch (UnsupportedOperationException e) { // For consistency with Titan 1.0.0, treat sets of multiplicity many // properties as adds. Handle this here since this is an uncommon // occurrence. if (graph.isMultiProperty(propertyName)) { addProperty(propertyName, value); } else { throw e; } } } @Override public <T> void addProperty(String propertyName, T value) { try { getAsTitanVertex().addProperty(propertyName, value); } catch (SchemaViolationException e) { if (getPropertyValues(propertyName, value.getClass()).contains(value)) { // follow java set semantics, don't throw an exception if // value is already there. return; } throw new AtlasSchemaViolationException(e); } } @Override public <T> Collection<T> getPropertyValues(String key, Class<T> clazz) { TitanVertex tv = getAsTitanVertex(); Collection<T> result = new ArrayList<>(); for (TitanProperty property : tv.getProperties(key)) { result.add((T) property.getValue()); } return result; } @Override public AtlasVertexQuery<Titan0Vertex, Titan0Edge> query() { return new Titan0VertexQuery(graph, wrappedElement.query()); } @Override public Titan0Vertex getV() { return this; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "Titan0Vertex [id=" + getId() + "]"; } } <|start_filename|>repository/src/test/java/org/apache/atlas/repository/graph/GraphRepoMapperScaleTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graph; import org.apache.atlas.ApplicationProperties; import org.apache.atlas.CreateUpdateEntitiesResult; import org.apache.atlas.TestModules; import org.apache.atlas.TestUtils; import org.apache.atlas.annotation.GraphTransaction; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.RepositoryException; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.AtlasGraphQuery; import org.apache.atlas.repository.graphdb.AtlasGraphQuery.ComparisionOperator; import org.apache.atlas.repository.graphdb.AtlasIndexQuery; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.Struct; import org.apache.atlas.typesystem.exception.EntityExistsException; import org.apache.atlas.typesystem.persistence.Id; import org.apache.atlas.typesystem.types.ClassType; import org.apache.atlas.typesystem.types.IDataType; import org.apache.atlas.typesystem.types.Multiplicity; import org.apache.atlas.typesystem.types.TypeSystem; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Guice; import org.testng.annotations.Test; import javax.inject.Inject; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; @Test @Guice(modules = TestModules.TestOnlyModule.class) public class GraphRepoMapperScaleTest { private static final String DATABASE_NAME = "foo"; private static final String TABLE_NAME = "bar"; @Inject private GraphBackedMetadataRepository repositoryService; @Inject private GraphBackedSearchIndexer searchIndexer; private TypeSystem typeSystem = TypeSystem.getInstance(); private String dbGUID; @BeforeClass @GraphTransaction public void setUp() throws Exception { //force up front graph initialization TestUtils.getGraph(); searchIndexer = new GraphBackedSearchIndexer(new AtlasGraphProvider(), ApplicationProperties.get(), new AtlasTypeRegistry()); //Make sure we can cleanup the index directory Collection<IDataType> typesAdded = TestUtils.createHiveTypes(typeSystem); searchIndexer.onAdd(typesAdded); } @BeforeMethod public void setupContext() { TestUtils.resetRequestContext(); } @AfterClass public void tearDown() throws Exception { TypeSystem.getInstance().reset(); // AtlasGraphProvider.cleanup(); } @Test public void testSubmitEntity() throws Exception { Referenceable databaseInstance = new Referenceable(TestUtils.DATABASE_TYPE); databaseInstance.set("name", DATABASE_NAME); databaseInstance.set("description", "foo database"); // System.out.println("databaseInstance = " + databaseInstance); ClassType dbType = typeSystem.getDataType(ClassType.class, TestUtils.DATABASE_TYPE); ITypedReferenceableInstance db = dbType.convert(databaseInstance, Multiplicity.REQUIRED); dbGUID = result(db).getCreatedEntities().get(0); Referenceable dbInstance = new Referenceable(dbGUID, TestUtils.DATABASE_TYPE, databaseInstance.getValuesMap()); for (int index = 0; index < 1000; index++) { ITypedReferenceableInstance table = createHiveTableInstance(dbInstance, index); result(table); } } private CreateUpdateEntitiesResult result(ITypedReferenceableInstance db) throws RepositoryException, EntityExistsException { return repositoryService.createEntities(db); } @Test(dependsOnMethods = "testSubmitEntity") public void testSearchIndex() throws Exception { //Elasticsearch requires some time before index is updated Thread.sleep(5000); searchWithOutIndex(Constants.GUID_PROPERTY_KEY, dbGUID); searchWithOutIndex(Constants.ENTITY_TYPE_PROPERTY_KEY, "column_type"); searchWithOutIndex(Constants.ENTITY_TYPE_PROPERTY_KEY, TestUtils.TABLE_TYPE); searchWithOutIndex("hive_table.name", "bar-999"); searchWithIndex("hive_table.name", "bar-999"); searchWithIndex("hive_table.created", ComparisionOperator.GREATER_THAN_EQUAL, TestUtils.TEST_DATE_IN_LONG, 1000); for (int index = 500; index < 600; index++) { searchWithIndex("hive_table.name", "bar-" + index); } searchWithIndex(Constants.STATE_PROPERTY_KEY, Id.EntityState.ACTIVE.name()); } private void searchWithOutIndex(String key, String value) { AtlasGraph graph = TestUtils.getGraph(); long start = System.currentTimeMillis(); int count = 0; try { AtlasGraphQuery query = graph.query().has(key, ComparisionOperator.EQUAL, value); Iterable<AtlasVertex> result = query.vertices(); for (AtlasVertex ignored : result) { count++; } } finally { System.out.println("Search on [" + key + "=" + value + "] returned results: " + count + ", took " + ( System.currentTimeMillis() - start) + " ms"); } } private void searchWithIndex(String key, String value) { AtlasGraph graph = TestUtils.getGraph(); long start = System.currentTimeMillis(); int count = 0; try { String queryString = "v.\"" + key + "\":(" + value + ")"; AtlasIndexQuery query = graph.indexQuery(Constants.VERTEX_INDEX, queryString); Iterator<AtlasIndexQuery.Result> result = query.vertices(); while(result.hasNext()) { result.next(); count++; } } finally { System.out.println("Search on [" + key + "=" + value + "] returned results: " + count + ", took " + ( System.currentTimeMillis() - start) + " ms"); } } private void searchWithIndex(String key, ComparisionOperator op, Object value, int expectedResults) { AtlasGraph graph = TestUtils.getGraph(); long start = System.currentTimeMillis(); int count = 0; try { AtlasGraphQuery query = graph.query().has(key, op, value); Iterable<AtlasVertex> itrble = query.vertices(); for (AtlasVertex ignored : itrble) { count++; } } finally { System.out.println("Search on [" + key + "=" + value + "] returned results: " + count + ", took " + ( System.currentTimeMillis() - start) + " ms"); Assert.assertEquals(count, expectedResults); } } private ITypedReferenceableInstance createHiveTableInstance(Referenceable databaseInstance, int uberIndex) throws Exception { Referenceable tableInstance = new Referenceable(TestUtils.TABLE_TYPE); tableInstance.set("name", TABLE_NAME + "-" + uberIndex); tableInstance.set("description", "bar table" + "-" + uberIndex); tableInstance.set("type", "managed"); tableInstance.set("created", new Date(TestUtils.TEST_DATE_IN_LONG)); tableInstance.set("tableType", 1); // enum // refer to an existing class tableInstance.set("database", databaseInstance); ArrayList<String> columnNames = new ArrayList<>(); columnNames.add("first_name" + "-" + uberIndex); columnNames.add("last_name" + "-" + uberIndex); tableInstance.set("columnNames", columnNames); Struct serde1Instance = new Struct("serdeType"); serde1Instance.set("name", "serde1" + "-" + uberIndex); serde1Instance.set("serde", "serde1" + "-" + uberIndex); tableInstance.set("serde1", serde1Instance); Struct serde2Instance = new Struct("serdeType"); serde2Instance.set("name", "serde2" + "-" + uberIndex); serde2Instance.set("serde", "serde2" + "-" + uberIndex); tableInstance.set("serde2", serde2Instance); ArrayList<Referenceable> columns = new ArrayList<>(); for (int index = 0; index < 5; index++) { Referenceable columnInstance = new Referenceable("column_type"); columnInstance.set("name", "column_" + "-" + uberIndex + "-" + index); columnInstance.set("type", "string"); columns.add(columnInstance); } tableInstance.set("columns", columns); ArrayList<Struct> partitions = new ArrayList<>(); for (int index = 0; index < 5; index++) { Struct partitionInstance = new Struct(TestUtils.PARTITION_STRUCT_TYPE); partitionInstance.set("name", "partition_" + "-" + uberIndex + "-" + index); partitions.add(partitionInstance); } tableInstance.set("partitions", partitions); ClassType tableType = typeSystem.getDataType(ClassType.class, TestUtils.TABLE_TYPE); return tableType.convert(tableInstance, Multiplicity.REQUIRED); } } <|start_filename|>catalog/src/main/java/org/apache/atlas/catalog/query/BaseQuery.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.catalog.query; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import org.apache.atlas.catalog.Request; import org.apache.atlas.catalog.VertexWrapper; import org.apache.atlas.catalog.definition.ResourceDefinition; import org.apache.atlas.catalog.exception.ResourceNotFoundException; import org.apache.atlas.catalog.projection.Projection; import org.apache.atlas.catalog.projection.ProjectionResult; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.graph.AtlasGraphProvider; import org.apache.atlas.repository.graphdb.AtlasElement; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.typesystem.persistence.Id; import com.tinkerpop.blueprints.Compare; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.gremlin.java.GremlinPipeline; import com.tinkerpop.pipes.Pipe; import com.tinkerpop.pipes.filter.PropertyFilterPipe; /** * Base Query implementation. */ public abstract class BaseQuery implements AtlasQuery { protected final QueryExpression queryExpression; protected final ResourceDefinition resourceDefinition; protected final Request request; public BaseQuery(QueryExpression queryExpression, ResourceDefinition resourceDefinition, Request request) { this.queryExpression = queryExpression; this.resourceDefinition = resourceDefinition; this.request = request; } public Collection<Map<String, Object>> execute() throws ResourceNotFoundException { Collection<Map<String, Object>> resultMaps = new ArrayList<>(); try { for (Vertex vertex : executeQuery()) { resultMaps.add(processPropertyMap(wrapVertex(vertex))); } getGraph().commit(); } catch (Throwable t) { getGraph().rollback(); throw t; } return resultMaps; } @Override public Collection<Map<String, Object>> execute(Map<String, Object> updateProperties) throws ResourceNotFoundException { Collection<Map<String, Object>> resultMaps = new ArrayList<>(); try { for (Vertex vertex : executeQuery()) { VertexWrapper vWrapper = wrapVertex(vertex); for (Map.Entry<String, Object> property : updateProperties.entrySet()) { vWrapper.setProperty(property.getKey(), property.getValue()); vWrapper.setProperty(Constants.MODIFICATION_TIMESTAMP_PROPERTY_KEY, System.currentTimeMillis()); } resultMaps.add(processPropertyMap(vWrapper)); } getGraph().commit(); } catch (Throwable e) { getGraph().rollback(); throw e; } return resultMaps; } private List<Vertex> executeQuery() { GremlinPipeline pipeline = buildPipeline().as("root"); Pipe expressionPipe = queryExpression.asPipe(); // AlwaysQuery returns null for pipe return expressionPipe == null ? pipeline.toList() : pipeline.add(expressionPipe).back("root").toList(); } protected GremlinPipeline buildPipeline() { GremlinPipeline pipeline = getRootVertexPipeline(); Pipe queryPipe = getQueryPipe(); if (queryPipe != null) { pipeline.add(queryPipe); } pipeline.add(getNotDeletedPipe()); return pipeline; } protected abstract Pipe getQueryPipe(); protected GremlinPipeline getRootVertexPipeline() { return new GremlinPipeline(unWrapVertices()); } protected Iterable<Object> unWrapVertices() { final Iterable<AtlasVertex> vertices = getGraph().getVertices(); Iterable<Object> vertexIterable = new Iterable<Object>() { Iterator<Object> iterator = new Iterator<Object>() { Iterator<AtlasVertex> wrapperIterator = vertices.iterator(); @Override public boolean hasNext() { return wrapperIterator.hasNext(); } @Override public Object next() { if (hasNext()) { return ((AtlasElement) wrapperIterator.next().getV()).getWrappedElement(); } else { throw new NoSuchElementException(); } } @Override public void remove() { throw new UnsupportedOperationException("Remove not supported"); } }; @Override public Iterator<Object> iterator() { return iterator; } }; return vertexIterable; } protected Pipe getNotDeletedPipe() { return new PropertyFilterPipe(Constants.STATE_PROPERTY_KEY, Compare.EQUAL, Id.EntityState.ACTIVE.name()); } protected Map<String, Object> processPropertyMap(VertexWrapper vertex) { Map<String, Object> propertyMap = resourceDefinition.filterProperties( request, vertex.getPropertyMap()); addHref(vertex, propertyMap); return request.getCardinality() == Request.Cardinality.INSTANCE ? applyProjections(vertex, propertyMap) : propertyMap; } protected void addHref(VertexWrapper vWrapper, Map<String, Object> filteredPropertyMap) { String href = resourceDefinition.resolveHref(filteredPropertyMap); if (href != null) { filteredPropertyMap.put("href", href); } } protected Map<String, Object> applyProjections(VertexWrapper vertex, Map<String, Object> propertyMap) { for (Projection p : resourceDefinition.getProjections().values()) { for (ProjectionResult projectionResult : p.values(vertex)) { if (p.getCardinality() == Projection.Cardinality.MULTIPLE) { propertyMap.put(projectionResult.getName(), projectionResult.getPropertyMaps()); } else { for (Map<String, Object> projectionMap : projectionResult.getPropertyMaps()) { propertyMap.put(projectionResult.getName(), projectionMap); } } } } return propertyMap; } protected QueryExpression getQueryExpression() { return queryExpression; } protected ResourceDefinition getResourceDefinition() { return resourceDefinition; } protected Request getRequest() { return request; } // Underlying method is synchronized and caches the graph in a static field protected AtlasGraph getGraph() { return AtlasGraphProvider.getGraphInstance(); } protected VertexWrapper wrapVertex(Vertex v) { return new VertexWrapper(v, resourceDefinition); } } <|start_filename|>intg/src/main/java/org/apache/atlas/model/impexp/AtlasImportRequest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.model.impexp; import org.apache.atlas.model.typedef.AtlasBaseTypeDef; import org.codehaus.jackson.annotate.JsonAnySetter; import org.codehaus.jackson.annotate.JsonAutoDetect; import org.codehaus.jackson.annotate.JsonIgnore; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.map.annotate.JsonSerialize; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import static org.codehaus.jackson.annotate.JsonAutoDetect.Visibility.NONE; import static org.codehaus.jackson.annotate.JsonAutoDetect.Visibility.PUBLIC_ONLY; @JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) @JsonIgnoreProperties(ignoreUnknown=true) public class AtlasImportRequest implements Serializable { private static final long serialVersionUID = 1L; public static final String TRANSFORMS_KEY = "transforms"; private static final String START_POSITION_KEY = "startPosition"; private static final String START_GUID_KEY = "startGuid"; private static final String FILE_NAME_KEY = "fileName"; private static final String UPDATE_TYPE_DEFINITION_KEY = "updateTypeDefinition"; private Map<String, String> options; public AtlasImportRequest() { this.options = new HashMap<>(); } public Map<String, String> getOptions() { return options; } public void setOptions(Map<String, String> options) { this.options = options; } public StringBuilder toString(StringBuilder sb) { if (sb == null) { sb = new StringBuilder(); } sb.append("AtlasImportRequest{"); sb.append("options={"); AtlasBaseTypeDef.dumpObjects(options, sb); sb.append("}"); sb.append("}"); return sb; } @Override public String toString() { return toString(new StringBuilder()).toString(); } @JsonIgnore public String getStartGuid() { return getOptionForKey(START_GUID_KEY); } @JsonIgnore public String getFileName() { return getOptionForKey(FILE_NAME_KEY); } @JsonIgnore public void setFileName(String fileName) { setOption(FILE_NAME_KEY, fileName); } @JsonIgnore public String getStartPosition() { return getOptionForKey(START_POSITION_KEY); } @JsonIgnore public String getUpdateTypeDefs() { return getOptionForKey(UPDATE_TYPE_DEFINITION_KEY); } private String getOptionForKey(String key) { if (this.options == null || !this.options.containsKey(key)) { return null; } return (String) this.options.get(key); } @JsonAnySetter public void setOption(String key, String value) { if (null == options) { options = new HashMap<>(); } options.put(key, value); }} <|start_filename|>repository/src/test/java/org/apache/atlas/repository/graph/ReverseReferenceUpdateTestBase.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graph; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.inject.Inject; import org.apache.atlas.CreateUpdateEntitiesResult; import org.apache.atlas.TestUtils; import org.apache.atlas.repository.MetadataRepository; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.TypesDef; import org.apache.atlas.typesystem.types.AttributeDefinition; import org.apache.atlas.typesystem.types.ClassType; import org.apache.atlas.typesystem.types.DataTypes; import org.apache.atlas.typesystem.types.EnumTypeDefinition; import org.apache.atlas.typesystem.types.HierarchicalTypeDefinition; import org.apache.atlas.typesystem.types.Multiplicity; import org.apache.atlas.typesystem.types.StructTypeDefinition; import org.apache.atlas.typesystem.types.TraitType; import org.apache.atlas.typesystem.types.TypeSystem; import org.apache.atlas.typesystem.types.utils.TypesUtil; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; /** * Verifies automatic update of reverse references * */ public abstract class ReverseReferenceUpdateTestBase { @Inject MetadataRepository repositoryService; private TypeSystem typeSystem; protected ClassType typeA; protected ClassType typeB; abstract void assertTestOneToOneReference(Object actual, ITypedReferenceableInstance expectedValue, ITypedReferenceableInstance referencingInstance) throws Exception; abstract void assertTestOneToManyReference(Object refValue, ITypedReferenceableInstance referencingInstance) throws Exception; @BeforeClass public void setUp() throws Exception { typeSystem = TypeSystem.getInstance(); typeSystem.reset(); HierarchicalTypeDefinition<ClassType> aDef = TypesUtil.createClassTypeDef("A", ImmutableSet.<String>of(), TypesUtil.createRequiredAttrDef("name", DataTypes.STRING_TYPE), new AttributeDefinition("b", "B", Multiplicity.OPTIONAL, false, "a"), // 1-1 new AttributeDefinition("oneB", "B", Multiplicity.OPTIONAL, false, "manyA"), // 1-* new AttributeDefinition("manyB", DataTypes.arrayTypeName("B"), Multiplicity.OPTIONAL, false, "manyToManyA"), // *-* new AttributeDefinition("map", DataTypes.mapTypeName(DataTypes.STRING_TYPE.getName(), "B"), Multiplicity.OPTIONAL, false, "backToMap")); HierarchicalTypeDefinition<ClassType> bDef = TypesUtil.createClassTypeDef("B", ImmutableSet.<String>of(), TypesUtil.createRequiredAttrDef("name", DataTypes.STRING_TYPE), new AttributeDefinition("a", "A", Multiplicity.OPTIONAL, false, "b"), new AttributeDefinition("manyA", DataTypes.arrayTypeName("A"), Multiplicity.OPTIONAL, false, "oneB"), new AttributeDefinition("manyToManyA", DataTypes.arrayTypeName("A"), Multiplicity.OPTIONAL, false, "manyB"), new AttributeDefinition("backToMap", "A", Multiplicity.OPTIONAL, false, "map")); TypesDef typesDef = TypesUtil.getTypesDef(ImmutableList.<EnumTypeDefinition>of(), ImmutableList.<StructTypeDefinition>of(), ImmutableList.<HierarchicalTypeDefinition<TraitType>>of(), ImmutableList.of(aDef, bDef)); typeSystem.defineTypes(typesDef); typeA = typeSystem.getDataType(ClassType.class, "A"); typeB = typeSystem.getDataType(ClassType.class, "B"); repositoryService = TestUtils.addTransactionWrapper(repositoryService); } @BeforeMethod public void setupContext() { TestUtils.resetRequestContext(); } @Test public void testOneToOneReference() throws Exception { ITypedReferenceableInstance a = typeA.createInstance(); a.setString("name", TestUtils.randomString()); ITypedReferenceableInstance b1 = typeB.createInstance(); b1.setString("name", TestUtils.randomString()); a.set("b", b1); // Create a. This should also create b1 and set the reverse b1->a reference. repositoryService.createEntities(a); a = repositoryService.getEntityDefinition("A", "name", a.getString("name")); b1 = repositoryService.getEntityDefinition("B", "name", b1.getString("name")); Object object = a.get("b"); Assert.assertTrue(object instanceof ITypedReferenceableInstance); ITypedReferenceableInstance refValue = (ITypedReferenceableInstance) object; Assert.assertEquals(refValue.getId()._getId(), b1.getId()._getId()); object = b1.get("a"); Assert.assertTrue(object instanceof ITypedReferenceableInstance); refValue = (ITypedReferenceableInstance) object; Assert.assertEquals(refValue.getId()._getId(), a.getId()._getId()); ITypedReferenceableInstance b2 = typeB.createInstance(); b2.setString("name", TestUtils.randomString()); b2.set("a", a.getId()); // Create b2. This should set the reverse a->b2 reference // and disconnect b1->a. repositoryService.createEntities(b2); a = repositoryService.getEntityDefinition(a.getId()._getId()); b2 = repositoryService.getEntityDefinition("B", "name", b2.getString("name")); object = a.get("b"); Assert.assertTrue(object instanceof ITypedReferenceableInstance); refValue = (ITypedReferenceableInstance) object; Assert.assertEquals(refValue.getId()._getId(), b2.getId()._getId()); object = b2.get("a"); Assert.assertTrue(object instanceof ITypedReferenceableInstance); refValue = (ITypedReferenceableInstance) object; Assert.assertEquals(refValue.getId()._getId(), a.getId()._getId()); // Verify b1->a was disconnected. b1 = repositoryService.getEntityDefinition("B", "name", b1.getString("name")); object = b1.get("a"); assertTestOneToOneReference(object, a, b1); } @Test public void testOneToManyReference() throws Exception { ITypedReferenceableInstance a1 = typeA.createInstance(); a1.setString("name", TestUtils.randomString()); ITypedReferenceableInstance a2 = typeA.createInstance(); a2.setString("name", TestUtils.randomString()); ITypedReferenceableInstance b1 = typeB.createInstance(); b1.setString("name", TestUtils.randomString()); a1.set("oneB", b1); ITypedReferenceableInstance b2 = typeB.createInstance(); b2.setString("name", TestUtils.randomString()); repositoryService.createEntities(a1, a2, b2); a1 = repositoryService.getEntityDefinition("A", "name", a1.getString("name")); a2 = repositoryService.getEntityDefinition("A", "name", a2.getString("name")); b1 = repositoryService.getEntityDefinition("B", "name", b1.getString("name")); b2 = repositoryService.getEntityDefinition("B", "name", b2.getString("name")); Object object = b1.get("manyA"); Assert.assertTrue(object instanceof List); List<ITypedReferenceableInstance> refValues = (List<ITypedReferenceableInstance>) object; Assert.assertEquals(refValues.size(), 1); Assert.assertTrue(refValues.contains(a1.getId())); a2.set("oneB", b1.getId()); repositoryService.updateEntities(a2); b1 = repositoryService.getEntityDefinition(b1.getId()._getId()); object = b1.get("manyA"); Assert.assertTrue(object instanceof List); refValues = (List<ITypedReferenceableInstance>) object; Assert.assertEquals(refValues.size(), 2); Assert.assertTrue(refValues.containsAll(Arrays.asList(a1.getId(), a2.getId()))); b2.set("manyA", Collections.singletonList(a2)); repositoryService.updateEntities(b2); a2 = repositoryService.getEntityDefinition("A", "name", a2.getString("name")); // Verify reverse a2.oneB reference was set to b2. object = a2.get("oneB"); Assert.assertTrue(object instanceof ITypedReferenceableInstance); ITypedReferenceableInstance refValue = (ITypedReferenceableInstance) object; Assert.assertEquals(refValue.getId()._getId(), b2.getId()._getId()); // Verify a2 was removed from b1.manyA reference list. b1 = repositoryService.getEntityDefinition(b1.getId()._getId()); object = b1.get("manyA"); assertTestOneToManyReference(object, b1); } @Test public void testManyToManyReference() throws Exception { ITypedReferenceableInstance a1 = typeA.createInstance(); a1.setString("name", TestUtils.randomString()); ITypedReferenceableInstance a2 = typeA.createInstance(); a2.setString("name", TestUtils.randomString()); ITypedReferenceableInstance b1 = typeB.createInstance(); b1.setString("name", TestUtils.randomString()); ITypedReferenceableInstance b2 = typeB.createInstance(); b2.setString("name", TestUtils.randomString()); repositoryService.createEntities(a1, a2, b1, b2); a1 = repositoryService.getEntityDefinition("A", "name", a1.getString("name")); a2 = repositoryService.getEntityDefinition("A", "name", a2.getString("name")); b1 = repositoryService.getEntityDefinition("B", "name", b1.getString("name")); b2 = repositoryService.getEntityDefinition("B", "name", b2.getString("name")); // Update a1 to add b1 to its manyB reference. // This should update b1.manyToManyA. a1.set("manyB", Arrays.asList(b1.getId())); repositoryService.updateEntities(a1); // Verify reverse b1.manyToManyA reference was updated. b1 = repositoryService.getEntityDefinition(b1.getId()._getId()); Object object = b1.get("manyToManyA"); Assert.assertTrue(object instanceof List); List<ITypedReferenceableInstance> refValues = (List<ITypedReferenceableInstance>) object; Assert.assertEquals(refValues.size(), 1); Assert.assertTrue(refValues.contains(a1.getId())); } /** * Auto-update of bi-directional references where one end is a map reference is * not currently supported. Verify that the auto-update is not applied in this case. */ @Test public void testMapReference() throws Exception { ITypedReferenceableInstance a1 = typeA.createInstance(); a1.setString("name", TestUtils.randomString()); ITypedReferenceableInstance a2 = typeA.createInstance(); a2.setString("name", TestUtils.randomString()); ITypedReferenceableInstance b1 = typeB.createInstance(); b1.setString("name", TestUtils.randomString()); ITypedReferenceableInstance b2 = typeB.createInstance(); b2.setString("name", TestUtils.randomString()); repositoryService.createEntities(a1, a2, b1, b2); a1 = repositoryService.getEntityDefinition("A", "name", a1.getString("name")); a2 = repositoryService.getEntityDefinition("A", "name", a2.getString("name")); b1 = repositoryService.getEntityDefinition("B", "name", b1.getString("name")); b2 = repositoryService.getEntityDefinition("B", "name", b2.getString("name")); a1.set("map", Collections.singletonMap("b1", b1)); repositoryService.updateEntities(a1); // Verify reverse b1.manyToManyA reference was not updated. b1 = repositoryService.getEntityDefinition(b1.getId()._getId()); Object object = b1.get("backToMap"); Assert.assertNull(object); } /** * Verify that explicitly setting both ends of a reference * does not cause duplicate entries due to auto-update of * reverse reference. */ @Test public void testCallerHasSetBothEnds() throws Exception { ITypedReferenceableInstance a = typeA.createInstance(); a.setString("name", TestUtils.randomString()); ITypedReferenceableInstance b1 = typeB.createInstance(); b1.setString("name", TestUtils.randomString()); // Set both sides of the reference. a.set("oneB", b1); b1.set("manyA", Collections.singletonList(a)); CreateUpdateEntitiesResult result = repositoryService.createEntities(a); Map<String, String> guidAssignments = result.getGuidMapping().getGuidAssignments(); String aGuid = a.getId()._getId(); String b1Guid = guidAssignments.get(b1.getId()._getId()); a = repositoryService.getEntityDefinition(aGuid); Object object = a.get("oneB"); Assert.assertTrue(object instanceof ITypedReferenceableInstance); Assert.assertEquals(((ITypedReferenceableInstance)object).getId()._getId(), b1Guid); b1 = repositoryService.getEntityDefinition(b1Guid); object = b1.get("manyA"); Assert.assertTrue(object instanceof List); List<ITypedReferenceableInstance> refValues = (List<ITypedReferenceableInstance>)object; Assert.assertEquals(refValues.size(), 1); Assert.assertEquals(refValues.get(0).getId()._getId(), aGuid); } } <|start_filename|>repository/src/test/java/org/apache/atlas/query/QueryProcessorTest.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.query; import com.google.common.collect.ImmutableSet; import org.apache.atlas.AtlasException; import org.apache.atlas.typesystem.types.ClassType; import org.apache.atlas.typesystem.types.DataTypes; import org.apache.atlas.typesystem.types.DataTypes.TypeCategory; import org.apache.atlas.typesystem.types.HierarchicalTypeDefinition; import org.apache.atlas.typesystem.types.IDataType; import org.apache.atlas.typesystem.types.TypeSystem; import org.apache.atlas.typesystem.types.cache.DefaultTypeCache; import org.testng.annotations.Test; import scala.util.Either; import scala.util.parsing.combinator.Parsers; import java.util.HashSet; import java.util.Set; import static org.apache.atlas.typesystem.types.utils.TypesUtil.createClassTypeDef; import static org.apache.atlas.typesystem.types.utils.TypesUtil.createRequiredAttrDef; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; /** * Tests the logic for skipping type cache lookup for things that * cannot be types. * */ public class QueryProcessorTest { @Test public void testAliasesNotTreatedAsTypes() throws Exception { ValidatingTypeCache tc = findTypeLookupsDuringQueryParsing("hive_db as inst where inst.name=\"Reporting\" select inst as id, inst.name"); assertTrue(tc.wasTypeRequested("hive_db")); assertFalse(tc.wasTypeRequested("inst")); assertFalse(tc.wasTypeRequested("name")); } @Test public void testFieldInComparisionNotTreatedAsType() throws Exception { //test when the IdExpression is on the left, on the right, and on both sides of the ComparsionExpression ValidatingTypeCache tc = findTypeLookupsDuringQueryParsing("hive_db where name=\"Reporting\" or \"Reporting\" = name or name=name"); assertTrue(tc.wasTypeRequested("hive_db")); assertFalse(tc.wasTypeRequested("name")); } @Test public void testFieldInArithmeticExprNotTreatedAsType() throws Exception { //test when the IdExpression is on the left, on the right, and on both sides of the ArithmeticExpression ValidatingTypeCache tc = findTypeLookupsDuringQueryParsing("hive_db where (tableCount + 3) > (tableCount + tableCount) select (3 + tableCount) as updatedCount"); assertTrue(tc.wasTypeRequested("hive_db")); assertFalse(tc.wasTypeRequested("tableCount")); assertFalse(tc.wasTypeRequested("updatedCount")); } @Test public void testFieldInSelectListWithAlasNotTreatedAsType() throws Exception { ValidatingTypeCache tc = findTypeLookupsDuringQueryParsing("hive_db select name as theName"); assertTrue(tc.wasTypeRequested("hive_db")); assertFalse(tc.wasTypeRequested("theName")); assertFalse(tc.wasTypeRequested("name")); } @Test public void testFieldInSelectListNotTreatedAsType() throws Exception { ValidatingTypeCache tc = findTypeLookupsDuringQueryParsing("hive_db select name"); assertTrue(tc.wasTypeRequested("hive_db")); assertFalse(tc.wasTypeRequested("name")); } private ValidatingTypeCache findTypeLookupsDuringQueryParsing(String query) throws AtlasException { TypeSystem typeSystem = TypeSystem.getInstance(); ValidatingTypeCache result = new ValidatingTypeCache(); typeSystem.setTypeCache(result); typeSystem.reset(); HierarchicalTypeDefinition<ClassType> hiveTypeDef = createClassTypeDef("hive_db", "", ImmutableSet.<String>of(), createRequiredAttrDef("name", DataTypes.STRING_TYPE), createRequiredAttrDef("tableCount", DataTypes.INT_TYPE) ); typeSystem.defineClassType(hiveTypeDef); Either<Parsers.NoSuccess, Expressions.Expression> either = QueryParser.apply(query, null); Expressions.Expression expression = either.right().get(); QueryProcessor.validate(expression); return result; } private static class ValidatingTypeCache extends DefaultTypeCache { private Set<String> typesRequested = new HashSet<>(); @Override public boolean has(String typeName) throws AtlasException { typesRequested.add(typeName); return super.has(typeName); } @Override public boolean has(TypeCategory typeCategory, String typeName) throws AtlasException { typesRequested.add(typeName); return super.has(typeCategory, typeName); } @Override public IDataType get(String typeName) throws AtlasException { typesRequested.add(typeName); return super.get(typeName); } @Override public IDataType get(TypeCategory typeCategory, String typeName) throws AtlasException { typesRequested.add(typeName); return super.get(typeCategory, typeName); } public boolean wasTypeRequested(String name) { return typesRequested.contains(name); } } } <|start_filename|>typesystem/src/main/java/org/apache/atlas/typesystem/types/utils/TypesUtil.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.typesystem.types.utils; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import org.apache.atlas.AtlasException; import org.apache.atlas.typesystem.TypesDef; import org.apache.atlas.typesystem.types.AttributeDefinition; import org.apache.atlas.typesystem.types.AttributeInfo; import org.apache.atlas.typesystem.types.ClassType; import org.apache.atlas.typesystem.types.EnumTypeDefinition; import org.apache.atlas.typesystem.types.EnumValue; import org.apache.atlas.typesystem.types.FieldMapping; import org.apache.atlas.typesystem.types.HierarchicalType; import org.apache.atlas.typesystem.types.HierarchicalTypeDefinition; import org.apache.atlas.typesystem.types.IDataType; import org.apache.atlas.typesystem.types.Multiplicity; import org.apache.atlas.typesystem.types.StructType; import org.apache.atlas.typesystem.types.StructTypeDefinition; import org.apache.atlas.typesystem.types.TraitType; import org.apache.atlas.AtlasConstants; import org.apache.atlas.typesystem.types.TypeSystem; import scala.collection.JavaConversions; /** * Types utilities class. */ public class TypesUtil { private TypesUtil() { } public static AttributeDefinition createOptionalAttrDef(String name, IDataType dataType) { return new AttributeDefinition(name, dataType.getName(), Multiplicity.OPTIONAL, false, null); } public static AttributeDefinition createOptionalAttrDef(String name, String dataType) { return new AttributeDefinition(name, dataType, Multiplicity.OPTIONAL, false, null); } public static AttributeDefinition createRequiredAttrDef(String name, String dataType) { return new AttributeDefinition(name, dataType, Multiplicity.REQUIRED, false, null); } public static AttributeDefinition createUniqueRequiredAttrDef(String name, IDataType dataType) { return new AttributeDefinition(name, dataType.getName(), Multiplicity.REQUIRED, false, true, true, null); } public static AttributeDefinition createRequiredAttrDef(String name, IDataType dataType) { return new AttributeDefinition(name, dataType.getName(), Multiplicity.REQUIRED, false, null); } public static EnumTypeDefinition createEnumTypeDef(String name, EnumValue... enumValues) { return new EnumTypeDefinition(name, enumValues); } public static HierarchicalTypeDefinition<TraitType> createTraitTypeDef(String name, ImmutableSet<String> superTypes, AttributeDefinition... attrDefs) { return createTraitTypeDef(name, null, superTypes, attrDefs); } public static HierarchicalTypeDefinition<TraitType> createTraitTypeDef(String name, String description, ImmutableSet<String> superTypes, AttributeDefinition... attrDefs) { return createTraitTypeDef(name, description, AtlasConstants.DEFAULT_TYPE_VERSION, superTypes, attrDefs); } public static HierarchicalTypeDefinition<TraitType> createTraitTypeDef(String name, String description, String version, ImmutableSet<String> superTypes, AttributeDefinition... attrDefs) { return new HierarchicalTypeDefinition<>(TraitType.class, name, description, version, superTypes, attrDefs); } public static StructTypeDefinition createStructTypeDef(String name, AttributeDefinition... attrDefs) { return createStructTypeDef(name, null, attrDefs); } public static StructTypeDefinition createStructTypeDef(String name, String description, AttributeDefinition... attrDefs) { return new StructTypeDefinition(name, description, attrDefs); } public static StructTypeDefinition createStructTypeDef(String name, String description, String version, AttributeDefinition... attrDefs) { return new StructTypeDefinition(name, description, version, attrDefs); } public static HierarchicalTypeDefinition<ClassType> createClassTypeDef(String name, ImmutableSet<String> superTypes, AttributeDefinition... attrDefs) { return createClassTypeDef(name, null, superTypes, attrDefs); } public static HierarchicalTypeDefinition<ClassType> createClassTypeDef(String name, String description, ImmutableSet<String> superTypes, AttributeDefinition... attrDefs) { return createClassTypeDef(name, description, AtlasConstants.DEFAULT_TYPE_VERSION, superTypes, attrDefs); } public static HierarchicalTypeDefinition<ClassType> createClassTypeDef(String name, String description, String version, ImmutableSet<String> superTypes, AttributeDefinition... attrDefs) { return new HierarchicalTypeDefinition<>(ClassType.class, name, description, superTypes, attrDefs); } public static TypesDef getTypesDef(ImmutableList<EnumTypeDefinition> enums, ImmutableList<StructTypeDefinition> structs, ImmutableList<HierarchicalTypeDefinition<TraitType>> traits, ImmutableList<HierarchicalTypeDefinition<ClassType>> classes) { return new TypesDef(JavaConversions.asScalaBuffer(enums), JavaConversions.asScalaBuffer(structs), JavaConversions.asScalaBuffer(traits), JavaConversions.asScalaBuffer(classes)); } private static final TypeSystem ts = TypeSystem.getInstance(); public static AttributeInfo newAttributeInfo(String attribute, IDataType type) { try { return new AttributeInfo(ts, new AttributeDefinition(attribute, type.getName(), Multiplicity.REQUIRED, false, null), null); } catch (AtlasException e) { throw new RuntimeException(e); } } /** * Get the field mappings for the specified data type. * Field mappings are only relevant for CLASS, TRAIT, and STRUCT types. * * @param type * @return {@link FieldMapping} for the specified type * @throws IllegalArgumentException if type is not a CLASS, TRAIT, or STRUCT type. */ public static FieldMapping getFieldMapping(IDataType type) { switch (type.getTypeCategory()) { case CLASS: case TRAIT: return ((HierarchicalType)type).fieldMapping(); case STRUCT: return ((StructType)type).fieldMapping(); default: throw new IllegalArgumentException("Type " + type + " doesn't have any fields!"); } } } <|start_filename|>typesystem/src/main/java/org/apache/atlas/typesystem/types/TraitType.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.typesystem.types; import com.google.common.collect.ImmutableSet; import org.apache.atlas.AtlasConstants; import org.apache.atlas.AtlasException; import org.apache.atlas.typesystem.IStruct; import org.apache.atlas.typesystem.ITypedStruct; import java.nio.charset.Charset; import java.security.MessageDigest; import java.util.List; import java.util.Map; import java.util.Set; public class TraitType extends HierarchicalType<TraitType, IStruct> implements IConstructableType<IStruct, ITypedStruct> { public final Map<AttributeInfo, List<String>> infoToNameMap; private final TypedStructHandler handler; TraitType(TypeSystem typeSystem, String name, String description, ImmutableSet<String> superTraits, int numFields) { this(typeSystem, name, description, AtlasConstants.DEFAULT_TYPE_VERSION, superTraits, numFields); } TraitType(TypeSystem typeSystem, String name, String description, String version, ImmutableSet<String> superTraits, int numFields) { super(typeSystem, TraitType.class, name, description, version, superTraits, numFields); handler = null; infoToNameMap = null; } TraitType(TypeSystem typeSystem, String name, String description, ImmutableSet<String> superTraits, AttributeInfo... fields) throws AtlasException { this(typeSystem, name, description, AtlasConstants.DEFAULT_TYPE_VERSION, superTraits, fields); } TraitType(TypeSystem typeSystem, String name, String description, String version, ImmutableSet<String> superTraits, AttributeInfo... fields) throws AtlasException { super(typeSystem, TraitType.class, name, description, version, superTraits, fields); handler = new TypedStructHandler(this); infoToNameMap = TypeUtils.buildAttrInfoToNameMap(fieldMapping); } @Override public DataTypes.TypeCategory getTypeCategory() { return DataTypes.TypeCategory.TRAIT; } @Override public ITypedStruct convert(Object val, Multiplicity m) throws AtlasException { return handler.convert(val, m); } public ITypedStruct createInstance() { return handler.createInstance(); } @Override public void output(IStruct s, Appendable buf, String prefix, Set<IStruct> inProcess) throws AtlasException { handler.output(s, buf, prefix, inProcess); } @Override public void updateSignatureHash(MessageDigest digester, Object val) throws AtlasException { if( !(val instanceof ITypedStruct)) { throw new IllegalArgumentException("Unexpected value type " + val.getClass().getSimpleName() + ". Expected instance of ITypedStruct"); } digester.update(getName().getBytes(Charset.forName("UTF-8"))); if(fieldMapping.fields != null && val != null) { IStruct typedValue = (IStruct) val; for (AttributeInfo aInfo : fieldMapping.fields.values()) { Object attrVal = typedValue.get(aInfo.name); if(attrVal != null) { aInfo.dataType().updateSignatureHash(digester, attrVal); } } } } @Override public List<String> getNames(AttributeInfo info) { return infoToNameMap.get(info); } } <|start_filename|>repository/src/test/java/org/apache/atlas/repository/typestore/GraphBackedTypeStoreTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.typestore; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import org.apache.atlas.AtlasException; import org.apache.atlas.TestModules; import org.apache.atlas.TestUtils; import org.apache.atlas.repository.RepositoryException; import org.apache.atlas.repository.graph.GraphHelper; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasEdgeDirection; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.typesystem.TypesDef; import org.apache.atlas.typesystem.types.*; import org.apache.atlas.typesystem.types.utils.TypesUtil; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Guice; import org.testng.annotations.Test; import javax.inject.Inject; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import static org.apache.atlas.typesystem.types.utils.TypesUtil.createClassTypeDef; import static org.apache.atlas.typesystem.types.utils.TypesUtil.createOptionalAttrDef; import static org.apache.atlas.typesystem.types.utils.TypesUtil.createRequiredAttrDef; import static org.apache.atlas.typesystem.types.utils.TypesUtil.createStructTypeDef; @Guice(modules = TestModules.TestOnlyModule.class) public class GraphBackedTypeStoreTest { private static final String DESCRIPTION = "_description"; @Inject private ITypeStore typeStore; private TypeSystem ts; @BeforeClass public void setUp() throws Exception { ts = TypeSystem.getInstance(); ts.reset(); TestUtils.defineDeptEmployeeTypes(ts); } @AfterClass public void tearDown() throws Exception { ts.reset(); // AtlasGraphProvider.cleanup(); } @Test public void testStore() throws AtlasException { ImmutableList<String> typeNames = ts.getTypeNames(); typeStore.store(ts, typeNames); dumpGraph(); } @Test(dependsOnMethods = "testStore") public void testRestoreType() throws Exception { TypesDef typesDef = typeStore.restoreType("Manager"); verifyRestoredClassType(typesDef, "Manager"); } private void dumpGraph() { AtlasGraph<?, ?> graph = TestUtils.getGraph(); for (AtlasVertex<?,?> v : graph.getVertices()) { System.out.println("****v = " + GraphHelper.vertexString(v)); for (AtlasEdge<?,?> e : v.getEdges(AtlasEdgeDirection.OUT)) { System.out.println("****e = " + GraphHelper.edgeString(e)); } } } @Test(dependsOnMethods = "testStore") public void testRestore() throws Exception { TypesDef types = typeStore.restore(); //validate enum List<EnumTypeDefinition> enumTypes = types.enumTypesAsJavaList(); Assert.assertEquals(1, enumTypes.size()); EnumTypeDefinition orgLevel = enumTypes.get(0); Assert.assertEquals(orgLevel.name, "OrgLevel"); Assert.assertEquals(orgLevel.description, "OrgLevel"+DESCRIPTION); Assert.assertEquals(orgLevel.enumValues.length, 2); EnumValue enumValue = orgLevel.enumValues[0]; Assert.assertEquals(enumValue.value, "L1"); Assert.assertEquals(enumValue.ordinal, 1); //validate class List<StructTypeDefinition> structTypes = types.structTypesAsJavaList(); Assert.assertEquals(1, structTypes.size()); verifyRestoredClassType(types, "Manager"); //validate trait List<HierarchicalTypeDefinition<TraitType>> traitTypes = types.traitTypesAsJavaList(); Assert.assertEquals(1, traitTypes.size()); HierarchicalTypeDefinition<TraitType> trait = traitTypes.get(0); Assert.assertEquals("SecurityClearance", trait.typeName); Assert.assertEquals(trait.typeName+DESCRIPTION, trait.typeDescription); Assert.assertEquals(1, trait.attributeDefinitions.length); AttributeDefinition attribute = trait.attributeDefinitions[0]; Assert.assertEquals("level", attribute.name); Assert.assertEquals(DataTypes.INT_TYPE.getName(), attribute.dataTypeName); //validate the new types ts.reset(); ts.defineTypes(types); } @Test public void testTypeWithSpecialChars() throws AtlasException { HierarchicalTypeDefinition<ClassType> specialTypeDef1 = createClassTypeDef("SpecialTypeDef1", "Typedef with special character", ImmutableSet.<String>of(), createRequiredAttrDef("attribute$", DataTypes.STRING_TYPE)); HierarchicalTypeDefinition<ClassType> specialTypeDef2 = createClassTypeDef("SpecialTypeDef2", "Typedef with special character", ImmutableSet.<String>of(), createRequiredAttrDef("attribute%", DataTypes.STRING_TYPE)); HierarchicalTypeDefinition<ClassType> specialTypeDef3 = createClassTypeDef("SpecialTypeDef3", "Typedef with special character", ImmutableSet.<String>of(), createRequiredAttrDef("attribute{", DataTypes.STRING_TYPE)); HierarchicalTypeDefinition<ClassType> specialTypeDef4 = createClassTypeDef("SpecialTypeDef4", "Typedef with special character", ImmutableSet.<String>of(), createRequiredAttrDef("attribute}", DataTypes.STRING_TYPE)); HierarchicalTypeDefinition<ClassType> specialTypeDef5 = createClassTypeDef("SpecialTypeDef5", "Typedef with special character", ImmutableSet.<String>of(), createRequiredAttrDef("attribute$%{}", DataTypes.STRING_TYPE)); TypesDef typesDef = TypesUtil.getTypesDef(ImmutableList.<EnumTypeDefinition>of(), ImmutableList.<StructTypeDefinition>of(), ImmutableList.<HierarchicalTypeDefinition<TraitType>>of(), ImmutableList.of(specialTypeDef1, specialTypeDef2, specialTypeDef3, specialTypeDef4, specialTypeDef5)); Map<String, IDataType> createdTypes = ts.defineTypes(typesDef); typeStore.store(ts, ImmutableList.copyOf(createdTypes.keySet())); //Validate the updated types TypesDef types = typeStore.restore(); ts.reset(); ts.defineTypes(types); } @Test(dependsOnMethods = "testStore") public void testTypeUpdate() throws Exception { //Add enum value String _description = "_description_updated"; EnumTypeDefinition orgLevelEnum = new EnumTypeDefinition("OrgLevel", "OrgLevel"+_description, new EnumValue("L1", 1), new EnumValue("L2", 2), new EnumValue("L3", 3)); //Add attribute StructTypeDefinition addressDetails = createStructTypeDef("Address", createRequiredAttrDef("street", DataTypes.STRING_TYPE), createRequiredAttrDef("city", DataTypes.STRING_TYPE), createOptionalAttrDef("state", DataTypes.STRING_TYPE)); HierarchicalTypeDefinition<ClassType> deptTypeDef = createClassTypeDef("Department", "Department"+_description, ImmutableSet.<String>of(), createRequiredAttrDef("name", DataTypes.STRING_TYPE), new AttributeDefinition("employees", String.format("array<%s>", "Person"), Multiplicity.OPTIONAL, true, "department"), new AttributeDefinition("positions", String.format("map<%s,%s>", DataTypes.STRING_TYPE.getName(), "Person"), Multiplicity.OPTIONAL, false, null)); TypesDef typesDef = TypesUtil.getTypesDef(ImmutableList.of(orgLevelEnum), ImmutableList.of(addressDetails), ImmutableList.<HierarchicalTypeDefinition<TraitType>>of(), ImmutableList.of(deptTypeDef)); Map<String, IDataType> typesAdded = ts.updateTypes(typesDef); typeStore.store(ts, ImmutableList.copyOf(typesAdded.keySet())); verifyEdges(); //Validate the updated types TypesDef types = typeStore.restore(); ts.reset(); ts.defineTypes(types); //Assert new enum value EnumType orgLevel = ts.getDataType(EnumType.class, orgLevelEnum.name); Assert.assertEquals(orgLevel.name, orgLevelEnum.name); Assert.assertEquals(orgLevel.description, orgLevelEnum.description); Assert.assertEquals(orgLevel.values().size(), orgLevelEnum.enumValues.length); Assert.assertEquals(orgLevel.fromValue("L3").ordinal, 3); //Assert new attribute StructType addressType = ts.getDataType(StructType.class, addressDetails.typeName); Assert.assertEquals(addressType.numFields, 3); Assert.assertEquals(addressType.fieldMapping.fields.get("state").dataType(), DataTypes.STRING_TYPE); //Updating the definition again shouldn't add another edge typesDef = TypesUtil.getTypesDef(ImmutableList.<EnumTypeDefinition>of(), ImmutableList.<StructTypeDefinition>of(), ImmutableList.<HierarchicalTypeDefinition<TraitType>>of(), ImmutableList.of(deptTypeDef)); typesAdded = ts.updateTypes(typesDef); typeStore.store(ts, ImmutableList.copyOf(typesAdded.keySet())); verifyEdges(); } private void verifyEdges() throws RepositoryException { // ATLAS-474: verify that type update did not write duplicate edges to the type store. if (typeStore instanceof GraphBackedTypeStore) { GraphBackedTypeStore gbTypeStore = (GraphBackedTypeStore) typeStore; AtlasVertex typeVertex = gbTypeStore.findVertices(Collections.singletonList("Department")).get("Department"); int edgeCount = countOutgoingEdges(typeVertex, gbTypeStore.getEdgeLabel("Department", "employees")); Assert.assertEquals(edgeCount, 1, "Should only be 1 edge for employees attribute on Department type AtlasVertex"); } } private int countOutgoingEdges(AtlasVertex typeVertex, String edgeLabel) { Iterator<AtlasEdge> outGoingEdgesByLabel = GraphHelper.getInstance().getOutGoingEdgesByLabel(typeVertex, edgeLabel); int edgeCount = 0; for (; outGoingEdgesByLabel.hasNext();) { outGoingEdgesByLabel.next(); edgeCount++; } return edgeCount; } private void verifyRestoredClassType(TypesDef types, String typeName) throws AtlasException { boolean clsTypeFound = false; List<HierarchicalTypeDefinition<ClassType>> classTypes = types.classTypesAsJavaList(); for (HierarchicalTypeDefinition<ClassType> classType : classTypes) { if (classType.typeName.equals(typeName)) { ClassType expectedType = ts.getDataType(ClassType.class, classType.typeName); Assert.assertEquals(expectedType.immediateAttrs.size(), classType.attributeDefinitions.length); Assert.assertEquals(expectedType.superTypes.size(), classType.superTypes.size()); Assert.assertEquals(classType.typeDescription, classType.typeName+DESCRIPTION); clsTypeFound = true; } } Assert.assertTrue(clsTypeFound, typeName + " type not restored"); } } <|start_filename|>dashboardv2/public/js/views/business_catalog/AddTermToEntityLayoutView.js<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(['require', 'backbone', 'hbs!tmpl/business_catalog/AddTermToEntityLayoutView_tmpl', 'utils/Utils', 'modules/Modal', 'collection/VCatalogList', 'utils/CommonViewFunction', 'utils/Messages', 'utils/Enums' ], function(require, Backbone, AddTermToEntityLayoutViewTmpl, Utils, Modal, VCatalogList, CommonViewFunction, Messages, Enums) { 'use strict'; var AddTermToEntityLayoutView = Backbone.Marionette.LayoutView.extend( /** @lends AddTermToEntityLayoutView */ { _viewName: 'AddTermToEntityLayoutView', template: AddTermToEntityLayoutViewTmpl, /** Layout sub regions */ regions: { RTreeLayoutView: "#r_treeLayoutView" }, /** ui selector cache */ ui: {}, /** ui events hash */ events: function() { var events = {}; return events; }, /** * intialize a new AddTermToEntityLayoutView Layout * @constructs */ initialize: function(options) { _.extend(this, _.pick(options, 'guid', 'modalCollection', 'callback', 'multiple', 'showLoader', 'hideLoader')); this.vCatalogList = new VCatalogList(); var that = this; this.modal = new Modal({ title: 'Assign Term', content: this, okText: 'Assign', cancelText: "Cancel", allowCancel: true, }).open(); this.on('ok', function() { that.asyncFetchCounter = 0; var termName = this.modal.$el.find('.taxonomyTree li.active a').data('name').split("`").join(""); if (termName.trim) { termName = termName.trim(); } if (that.multiple) { for (var i = 0; i < that.multiple.length; i++) { if (i == 0) { if (that.showLoader) { that.showLoader(); } } var obj = { termName: termName, guid: that.multiple[i].id, deletedEntity: Enums.entityStateReadOnly[that.multiple[i].model.status], entityName: Utils.getName(that.multiple[i].model) }; if (obj.deletedEntity) { Utils.notifyError({ content: obj.entityName + Messages.assignDeletedEntity }); if (that.multiple.length === 1 || (that.multiple.length == (i + 1) && that.asyncFetchCounter == 0)) { that.hideLoader(); } } else { CommonViewFunction.saveTermToAsset(obj, that); } } } else { that.asyncFetchCounter = 0; if (that.showLoader) { that.showLoader(); } CommonViewFunction.saveTermToAsset({ termName: termName, guid: this.guid }, that); } }); this.on('closeModal', function() { this.modal.trigger('cancel'); }); }, onRender: function() { this.renderTreeLayoutView(); }, renderTreeLayoutView: function() { var that = this; require(['views/business_catalog/TreeLayoutView'], function(TreeLayoutView) { that.RTreeLayoutView.show(new TreeLayoutView({ url: that.url, viewBased: false })); }); } }); return AddTermToEntityLayoutView; }); <|start_filename|>repository/src/main/java/org/apache/atlas/repository/typestore/GraphBackedTypeStore.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.typestore; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import org.apache.atlas.AtlasException; import org.apache.atlas.annotation.GraphTransaction; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.RepositoryException; import org.apache.atlas.repository.graph.GraphHelper; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasEdgeDirection; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.typesystem.TypesDef; import org.apache.atlas.typesystem.types.*; import org.apache.atlas.typesystem.types.DataTypes.TypeCategory; import org.apache.atlas.typesystem.types.utils.TypesUtil; import org.codehaus.jettison.json.JSONException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.inject.Inject; import javax.inject.Singleton; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import static org.apache.atlas.repository.graph.GraphHelper.setProperty; @Singleton @Component @Deprecated public class GraphBackedTypeStore implements ITypeStore { public static final String VERTEX_TYPE = "typeSystem"; private static final String PROPERTY_PREFIX = Constants.INTERNAL_PROPERTY_KEY_PREFIX + "type."; public static final String SUPERTYPE_EDGE_LABEL = PROPERTY_PREFIX + ".supertype"; private static Logger LOG = LoggerFactory.getLogger(GraphBackedTypeStore.class); private final AtlasGraph graph; private GraphHelper graphHelper = GraphHelper.getInstance(); @Inject public GraphBackedTypeStore(AtlasGraph atlasGraph) { this.graph = atlasGraph; } @Override @GraphTransaction public void store(TypeSystem typeSystem, ImmutableList<String> typeNames) throws AtlasException { //Pre-create the vertices that are needed for the types. This allows us to execute //one query to determine all of the vertices that already exist. Map<String, AtlasVertex> typeVertices = getOrCreateTypeVertices(typeSystem, typeNames); //Complete the storage process by adding properties and edges to the vertices //that were created. TypePersistenceVisitor visitor = new TypePersistenceVisitor(this, typeVertices, typeSystem); processTypes(typeNames, typeSystem, visitor); } private void processTypes(ImmutableList<String> typeNames, TypeSystem typeSystem, TypeVisitor visitor) throws AtlasException { for (String typeName : typeNames) { IDataType dataType = typeSystem.getDataType(IDataType.class, typeName); LOG.debug("Processing {}.{}.{} in type store", dataType.getTypeCategory(), dataType.getName(), dataType.getDescription()); switch (dataType.getTypeCategory()) { case ENUM: visitor.visitEnumeration((EnumType)dataType); break; case STRUCT: StructType structType = (StructType) dataType; processType(typeSystem, dataType.getTypeCategory(), dataType.getName(), dataType.getDescription(), ImmutableList.copyOf(structType.infoToNameMap.keySet()), ImmutableSet.<String>of(), visitor); break; case TRAIT: case CLASS: HierarchicalType type = (HierarchicalType) dataType; processType(typeSystem, dataType.getTypeCategory(), dataType.getName(), type.getDescription(), type.immediateAttrs, type.superTypes, visitor); break; default: //Ignore primitive/collection types as they are covered under references break; } } } private Map<String, AtlasVertex> getOrCreateTypeVertices(TypeSystem typeSystem, ImmutableList<String> typeNames) throws AtlasException { //examine the types to determine what type vertices are needed TypeVertexFinder vertexFinder = new TypeVertexFinder(typeSystem); processTypes(typeNames, typeSystem, vertexFinder); List<TypeVertexInfo> typeVerticesNeeded = vertexFinder.getVerticesToCreate(); //find or create the type vertices List<AtlasVertex> vertices = createVertices(typeVerticesNeeded); //Create a type name->AtlasVertex map with the result Map<String, AtlasVertex> result = new HashMap<>(typeVerticesNeeded.size()); for(int i = 0 ; i < typeVerticesNeeded.size(); i++) { TypeVertexInfo createdVertexInfo = typeVerticesNeeded.get(i); AtlasVertex createdVertex = vertices.get(i); result.put(createdVertexInfo.getTypeName(), createdVertex); } return result; } static String getPropertyKey(String name) { return PROPERTY_PREFIX + name; } static String getPropertyKey(String parent, String child) { return PROPERTY_PREFIX + parent + "." + child; } static String getEdgeLabel(String parent, String child) { return PROPERTY_PREFIX + "edge." + parent + "." + child; } private void processType(TypeSystem typeSystem, DataTypes.TypeCategory category, String typeName, String typeDescription, ImmutableList<AttributeInfo> attributes, ImmutableSet<String> superTypes, TypeVisitor visitor) throws AtlasException { visitor.visitDataType(category, typeName, typeDescription); List<String> attrNames = new ArrayList<>(); if (attributes != null) { for (AttributeInfo attribute : attributes) { visitor.visitAttribute(typeName, attribute); attrNames.add(attribute.name); processsAttribute(typeSystem, typeName, attribute, visitor); } } visitor.visitAttributeNames(typeName, attrNames); //Add edges for hierarchy if (superTypes != null) { for (String superTypeName : superTypes) { visitor.visitSuperType(typeName, superTypeName); } } } private void processsAttribute(TypeSystem typeSystem, String typeName, AttributeInfo attribute, TypeVisitor visitor) throws AtlasException { ImmutableList<String> coreTypes = typeSystem.getCoreTypes(); List<IDataType> attrDataTypes = new ArrayList<>(); IDataType attrDataType = attribute.dataType(); switch (attrDataType.getTypeCategory()) { case ARRAY: String attrType = TypeUtils.parseAsArrayType(attrDataType.getName()); if(attrType != null) { IDataType elementType = typeSystem.getDataType(IDataType.class, attrType); attrDataTypes.add(elementType); } break; case MAP: String[] attrTypes = TypeUtils.parseAsMapType(attrDataType.getName()); if(attrTypes != null && attrTypes.length > 1) { IDataType keyType = typeSystem.getDataType(IDataType.class, attrTypes[0]); IDataType valueType = typeSystem.getDataType(IDataType.class, attrTypes[1]); attrDataTypes.add(keyType); attrDataTypes.add(valueType); } break; case ENUM: case STRUCT: case CLASS: attrDataTypes.add(attrDataType); break; case PRIMITIVE: //no vertex for primitive type, hence no edge required break; default: throw new IllegalArgumentException( "Attribute cannot reference instances of type : " + attrDataType.getTypeCategory()); } for (IDataType attrType : attrDataTypes) { if (!coreTypes.contains(attrType.getName())) { visitor.visitAttributeDataType(typeName, attribute, attrType); } } } @Override @GraphTransaction public TypesDef restore() throws AtlasException { //Get all vertices for type system Iterator vertices = graph.query().has(Constants.VERTEX_TYPE_PROPERTY_KEY, VERTEX_TYPE).vertices().iterator(); return getTypesFromVertices(vertices); } @Override @GraphTransaction public TypesDef restoreType(String typeName) throws AtlasException { // Get AtlasVertex for the specified type name. Iterator vertices = graph.query().has(Constants.VERTEX_TYPE_PROPERTY_KEY, VERTEX_TYPE).has(Constants.TYPENAME_PROPERTY_KEY, typeName).vertices().iterator(); return getTypesFromVertices(vertices); } private TypesDef getTypesFromVertices(Iterator<AtlasVertex> vertices) throws AtlasException { ImmutableList.Builder<EnumTypeDefinition> enums = ImmutableList.builder(); ImmutableList.Builder<StructTypeDefinition> structs = ImmutableList.builder(); ImmutableList.Builder<HierarchicalTypeDefinition<ClassType>> classTypes = ImmutableList.builder(); ImmutableList.Builder<HierarchicalTypeDefinition<TraitType>> traits = ImmutableList.builder(); while (vertices.hasNext()) { AtlasVertex vertex = vertices.next(); DataTypes.TypeCategory typeCategory = GraphHelper.getSingleValuedProperty(vertex, Constants.TYPE_CATEGORY_PROPERTY_KEY, TypeCategory.class); String typeName = GraphHelper.getSingleValuedProperty(vertex, Constants.TYPENAME_PROPERTY_KEY, String.class); String typeDescription = GraphHelper.getSingleValuedProperty(vertex, Constants.TYPEDESCRIPTION_PROPERTY_KEY, String.class); LOG.info("Restoring type {}.{}.{}", typeCategory, typeName, typeDescription); switch (typeCategory) { case ENUM: enums.add(getEnumType(vertex)); break; case STRUCT: AttributeDefinition[] attributes = getAttributes(vertex, typeName); structs.add(new StructTypeDefinition(typeName, typeDescription, attributes)); break; case CLASS: ImmutableSet<String> superTypes = getSuperTypes(vertex); attributes = getAttributes(vertex, typeName); classTypes.add(new HierarchicalTypeDefinition(ClassType.class, typeName, typeDescription, superTypes, attributes)); break; case TRAIT: superTypes = getSuperTypes(vertex); attributes = getAttributes(vertex, typeName); traits.add(new HierarchicalTypeDefinition(TraitType.class, typeName, typeDescription, superTypes, attributes)); break; case RELATIONSHIP: // v1 typesystem is not notified on new relation type break; default: throw new IllegalArgumentException("Unhandled type category " + typeCategory); } } return TypesUtil.getTypesDef(enums.build(), structs.build(), traits.build(), classTypes.build()); } private EnumTypeDefinition getEnumType(AtlasVertex vertex) throws AtlasException { String typeName = GraphHelper.getSingleValuedProperty(vertex, Constants.TYPENAME_PROPERTY_KEY, String.class); String typeDescription = GraphHelper.getSingleValuedProperty(vertex, Constants.TYPEDESCRIPTION_PROPERTY_KEY, String.class); List<EnumValue> enumValues = new ArrayList<>(); List<String> values = GraphHelper.getListProperty(vertex, getPropertyKey(typeName)); for (String value : values) { String valueProperty = getPropertyKey(typeName, value); enumValues.add(new EnumValue(value, GraphHelper.getSingleValuedProperty(vertex, valueProperty, Integer.class))); } return new EnumTypeDefinition(typeName, typeDescription, enumValues.toArray(new EnumValue[enumValues.size()])); } private ImmutableSet<String> getSuperTypes(AtlasVertex vertex) { Set<String> superTypes = new HashSet<>(); for (AtlasEdge edge : (Iterable<AtlasEdge>) vertex.getEdges(AtlasEdgeDirection.OUT, SUPERTYPE_EDGE_LABEL)) { superTypes.add(edge.getInVertex().getProperty(Constants.TYPENAME_PROPERTY_KEY, String.class)); } return ImmutableSet.copyOf(superTypes); } private AttributeDefinition[] getAttributes(AtlasVertex vertex, String typeName) throws AtlasException { List<AttributeDefinition> attributes = new ArrayList<>(); List<String> attrNames = GraphHelper.getListProperty(vertex, getPropertyKey(typeName)); if (attrNames != null) { for (String attrName : attrNames) { try { String encodedPropertyKey = GraphHelper.encodePropertyKey(getPropertyKey(typeName, attrName)); AttributeDefinition attrValue = AttributeInfo.fromJson((String) vertex.getJsonProperty(encodedPropertyKey)); if (attrValue != null) { attributes.add(attrValue); } } catch (JSONException e) { throw new AtlasException(e); } } } return attributes.toArray(new AttributeDefinition[attributes.size()]); } /** * Find vertex for the given type category and name, else create new vertex * @param category * @param typeName * @return vertex */ AtlasVertex findVertex(DataTypes.TypeCategory category, String typeName) { LOG.debug("Finding AtlasVertex for {}.{}", category, typeName); Iterator results = graph.query().has(Constants.TYPENAME_PROPERTY_KEY, typeName).vertices().iterator(); AtlasVertex vertex = null; if (results != null && results.hasNext()) { //There should be just one AtlasVertex with the given typeName vertex = (AtlasVertex) results.next(); } return vertex; } //package-private for testing Map<String, AtlasVertex> findVertices(List<String> typeNames) throws RepositoryException { LOG.debug("Finding vertices for {}", typeNames.toString()); Map<String, AtlasVertex> foundVertices = graphHelper.getVerticesForPropertyValues(Constants.TYPENAME_PROPERTY_KEY, typeNames); return foundVertices; } /** * Finds or creates type vertices with the information specified. * * @param infoList * @return list with the vertices corresponding to the types in the list. * @throws AtlasException */ private List<AtlasVertex> createVertices(List<TypeVertexInfo> infoList) throws AtlasException { List<AtlasVertex> result = new ArrayList<>(infoList.size()); List<String> typeNames = Lists.transform(infoList, new Function<TypeVertexInfo,String>() { @Override public String apply(TypeVertexInfo input) { return input.getTypeName(); } }); Map<String, AtlasVertex> vertices = findVertices(typeNames); for(TypeVertexInfo info : infoList) { AtlasVertex vertex = vertices.get(info.getTypeName()); if (! GraphHelper.elementExists(vertex)) { LOG.debug("Adding vertex {}{}", PROPERTY_PREFIX, info.getTypeName()); vertex = graph.addVertex(); setProperty(vertex, Constants.VERTEX_TYPE_PROPERTY_KEY, VERTEX_TYPE); // Mark as type AtlasVertex setProperty(vertex, Constants.TYPE_CATEGORY_PROPERTY_KEY, info.getCategory()); setProperty(vertex, Constants.TYPENAME_PROPERTY_KEY, info.getTypeName()); } String newDescription = info.getTypeDescription(); if (newDescription != null) { String oldDescription = getPropertyKey(Constants.TYPEDESCRIPTION_PROPERTY_KEY); if (!newDescription.equals(oldDescription)) { setProperty(vertex, Constants.TYPEDESCRIPTION_PROPERTY_KEY, newDescription); } } else { LOG.debug(" type description is null "); } result.add(vertex); } return result; } } <|start_filename|>typesystem/src/main/java/org/apache/atlas/typesystem/types/EnumTypeDefinition.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.typesystem.types; import org.apache.atlas.utils.ParamChecker; import org.apache.atlas.AtlasConstants; import java.util.Arrays; import java.util.Objects; public final class EnumTypeDefinition { public final String name; public final String description; public final String version; public final EnumValue[] enumValues; public EnumTypeDefinition(String name, EnumValue... enumValues) { this(name, null, AtlasConstants.DEFAULT_TYPE_VERSION, enumValues); } public EnumTypeDefinition(String name, String description, EnumValue... enumValues) { this(name, description, AtlasConstants.DEFAULT_TYPE_VERSION, enumValues); } public EnumTypeDefinition(String name, String description, String version, EnumValue... enumValues) { this.name = ParamChecker.notEmpty(name, "Enum type name"); this.description = description; this.enumValues = ParamChecker.notNullElements(enumValues, "Enum values"); this.version = version; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EnumTypeDefinition that = (EnumTypeDefinition) o; return Objects.equals(name, that.name) && Objects.equals(description, that.description) && Objects.equals(version, that.version) && Arrays.equals(enumValues, that.enumValues); } @Override public int hashCode() { return Objects.hash(name, description, version, enumValues); } } <|start_filename|>intg/src/test/java/org/apache/atlas/type/TestAtlasClassificationType.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.type; import java.util.*; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.ModelTestUtil; import org.apache.atlas.model.instance.AtlasClassification; import org.apache.atlas.model.typedef.AtlasBaseTypeDef; import org.apache.atlas.model.typedef.AtlasClassificationDef; import org.testng.annotations.Test; import static org.testng.Assert.*; public class TestAtlasClassificationType { private final AtlasClassificationType classificationType; private final List<Object> validValues = new ArrayList<>(); private final List<Object> invalidValues = new ArrayList<>(); { classificationType = getClassificationType(ModelTestUtil.getClassificationDefWithSuperTypes()); AtlasClassification invalidValue1 = classificationType.createDefaultValue(); AtlasClassification invalidValue2 = classificationType.createDefaultValue(); Map<String, Object> invalidValue3 = classificationType.createDefaultValue().getAttributes(); // invalid value for int invalidValue1.setAttribute(ModelTestUtil.getDefaultAttributeName(AtlasBaseTypeDef.ATLAS_TYPE_INT), "xyz"); // invalid value for date invalidValue2.setAttribute(ModelTestUtil.getDefaultAttributeName(AtlasBaseTypeDef.ATLAS_TYPE_DATE), "xyz"); // invalid value for bigint invalidValue3.put(ModelTestUtil.getDefaultAttributeName(AtlasBaseTypeDef.ATLAS_TYPE_BIGINTEGER), "xyz"); validValues.add(null); validValues.add(classificationType.createDefaultValue()); validValues.add(classificationType.createDefaultValue().getAttributes()); // Map<String, Object> invalidValues.add(invalidValue1); invalidValues.add(invalidValue2); invalidValues.add(invalidValue3); invalidValues.add(new AtlasClassification()); // no values for mandatory attributes invalidValues.add(new HashMap<>()); // no values for mandatory attributes invalidValues.add(1); // incorrect datatype invalidValues.add(new HashSet()); // incorrect datatype invalidValues.add(new ArrayList()); // incorrect datatype invalidValues.add(new String[] {}); // incorrect datatype } @Test public void testClassificationTypeDefaultValue() { AtlasClassification defValue = classificationType.createDefaultValue(); assertNotNull(defValue); assertEquals(defValue.getTypeName(), classificationType.getTypeName()); } @Test public void testClassificationTypeIsValidValue() { for (Object value : validValues) { assertTrue(classificationType.isValidValue(value), "value=" + value); } for (Object value : invalidValues) { assertFalse(classificationType.isValidValue(value), "value=" + value); } } @Test public void testClassificationTypeGetNormalizedValue() { assertNull(classificationType.getNormalizedValue(null), "value=" + null); for (Object value : validValues) { if (value == null) { continue; } Object normalizedValue = classificationType.getNormalizedValue(value); assertNotNull(normalizedValue, "value=" + value); } for (Object value : invalidValues) { assertNull(classificationType.getNormalizedValue(value), "value=" + value); } } @Test public void testClassificationTypeValidateValue() { List<String> messages = new ArrayList<>(); for (Object value : validValues) { assertTrue(classificationType.validateValue(value, "testObj", messages)); assertEquals(messages.size(), 0, "value=" + value); } for (Object value : invalidValues) { assertFalse(classificationType.validateValue(value, "testObj", messages)); assertTrue(messages.size() > 0, "value=" + value); messages.clear(); } } private static AtlasClassificationType getClassificationType(AtlasClassificationDef classificationDef) { try { return new AtlasClassificationType(classificationDef, ModelTestUtil.getTypesRegistry()); } catch (AtlasBaseException excp) { return null; } } } <|start_filename|>authorization/src/main/java/org/apache/atlas/authorize/AtlasAccessRequest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.authorize; import org.apache.atlas.authorize.simple.AtlasAuthorizationUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import java.util.Date; import java.util.Set; public class AtlasAccessRequest { private static Logger LOG = LoggerFactory.getLogger(AtlasAccessRequest.class); private static boolean isDebugEnabled = LOG.isDebugEnabled(); private Set<AtlasResourceTypes> resourceType = null; private String resource = null; private AtlasActionTypes action = null; private String user = null; private Set<String> userGroups = null; private Date accessTime = null; private String clientIPAddress = null; public AtlasAccessRequest(HttpServletRequest request, String user, Set<String> userGroups) { // Spring Security 4 Change => request.getServletPath() -> request.getPathInfo() this(AtlasAuthorizationUtils.getAtlasResourceType(request.getPathInfo()), "*", AtlasAuthorizationUtils .getAtlasAction(request.getMethod()), user, userGroups,AtlasAuthorizationUtils.getRequestIpAddress(request)); } public AtlasAccessRequest(Set<AtlasResourceTypes> resourceType, String resource, AtlasActionTypes action, String user, Set<String> userGroups, String clientIPAddress) { if (isDebugEnabled) { LOG.debug("==> AtlasAccessRequestImpl-- Initializing AtlasAccessRequest"); } setResource(resource); setAction(action); setUser(user); setUserGroups(userGroups); setResourceType(resourceType); // set remaining fields to default value setAccessTime(null); setClientIPAddress(clientIPAddress); } public Set<AtlasResourceTypes> getResourceTypes() { return resourceType; } public void setResourceType(Set<AtlasResourceTypes> resourceType) { this.resourceType = resourceType; } public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } public AtlasActionTypes getAction() { return action; } public void setAction(AtlasActionTypes action) { this.action = action; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public void setUserGroups(Set<String> userGroups) { this.userGroups = userGroups; } public Set<String> getUserGroups() { return userGroups; } public Date getAccessTime() { return accessTime; } public void setAccessTime(Date accessTime) { this.accessTime = accessTime; } public String getClientIPAddress() { return clientIPAddress; } public void setClientIPAddress(String clientIPAddress) { this.clientIPAddress = clientIPAddress; } @Override public String toString() { return "AtlasAccessRequest [resourceType=" + resourceType + ", resource=" + resource + ", action=" + action + ", user=" + user + ", userGroups=" + userGroups + ", accessTime=" + accessTime + ", clientIPAddress=" + clientIPAddress + "]"; } } <|start_filename|>dashboardv2/public/css/googlefonts.css<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* latin */ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 400; src: local('Source Sans Pro'), local('SourceSansPro-Regular'), url(../js/external_lib/fonts/ODelI1aHBYDBqgeIAH2zlNV_2ngZ8dMf8fLgjYEouxg.woff2) format('woff2'); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215; } /* latin */ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 600; src: local('Source Sans Pro Semibold'), local('SourceSansPro-Semibold'), url(../js/external_lib/fonts/toadOcfmlt9b38dHJxOBGCOFnW3Jk0f09zW_Yln67Ac.woff2) format('woff2'); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215; } @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 700; src: local('Source Sans Pro Bold'), local('SourceSansPro-Bold'), url(../js/external_lib/fonts/toadOcfmlt9b38dHJxOBGEo0As1BFRXtCDhS66znb_k.woff2) format('woff2'); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215; } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/converters/AtlasClassificationFormatConverter.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.converters; import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.AtlasException; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.TypeCategory; import org.apache.atlas.model.instance.AtlasClassification; import org.apache.atlas.type.AtlasClassificationType; import org.apache.atlas.type.AtlasType; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.typesystem.IStruct; import org.apache.commons.collections.MapUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; public class AtlasClassificationFormatConverter extends AtlasStructFormatConverter { private static final Logger LOG = LoggerFactory.getLogger(AtlasClassificationFormatConverter.class); public AtlasClassificationFormatConverter(AtlasFormatConverters registry, AtlasTypeRegistry typeRegistry) { super(registry, typeRegistry, TypeCategory.CLASSIFICATION); } @Override public AtlasClassification fromV1ToV2(Object v1Obj, AtlasType type, ConverterContext ctx) throws AtlasBaseException { AtlasClassification ret = null; if (v1Obj != null) { AtlasClassificationType classificationType = (AtlasClassificationType)type; if (v1Obj instanceof Map) { final Map v1Map = (Map) v1Obj; final Map v1Attribs = (Map) v1Map.get(ATTRIBUTES_PROPERTY_KEY); if (MapUtils.isNotEmpty(v1Attribs)) { ret = new AtlasClassification(type.getTypeName(), fromV1ToV2(classificationType, v1Attribs, ctx)); } else { ret = new AtlasClassification(type.getTypeName()); } } else if (v1Obj instanceof IStruct) { IStruct struct = (IStruct) v1Obj; Map<String, Object> v1Attribs = null; try { v1Attribs = struct.getValuesMap(); } catch (AtlasException excp) { LOG.error("IStruct.getValuesMap() failed", excp); } ret = new AtlasClassification(type.getTypeName(), fromV1ToV2(classificationType, v1Attribs, ctx)); } else { throw new AtlasBaseException(AtlasErrorCode.UNEXPECTED_TYPE, "Map or IStruct", v1Obj.getClass().getCanonicalName()); } } return ret; } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/typestore/TypeVertexFinder.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.typestore; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.atlas.AtlasException; import org.apache.atlas.typesystem.types.AttributeInfo; import org.apache.atlas.typesystem.types.DataTypes.TypeCategory; import org.apache.atlas.typesystem.types.EnumType; import org.apache.atlas.typesystem.types.HierarchicalType; import org.apache.atlas.typesystem.types.IDataType; import org.apache.atlas.typesystem.types.TypeSystem; /** * TypeVisitor implementation that builds up a list of type vertices * that need to be created for the types that are being stored. * */ public class TypeVertexFinder implements TypeVisitor { private final List<TypeVertexInfo> toCreate = new ArrayList<TypeVertexInfo>(); private final Set<String> typesIncluded = new HashSet<String>(); private final TypeSystem typeSystem; public TypeVertexFinder(TypeSystem ts) { typeSystem = ts; } @Override public void visitEnumeration(EnumType dataType) { visitDataType(dataType); } private void addTypeIfNeeded(TypeVertexInfo info) { if(! typesIncluded.contains(info.getTypeName())) { toCreate.add(info); typesIncluded.add(info.getTypeName()); } } @Override public void visitAttributeDataType(String typeName, AttributeInfo sourceAttr, IDataType attrType) throws AtlasException { visitDataType(attrType); } @Override public void visitSuperType(String typeName, String superTypeName) throws AtlasException { HierarchicalType superType = typeSystem.getDataType(HierarchicalType.class, superTypeName); visitDataType(superType); } @Override public void visitAttributeNames(String typeName, List<String> attrNames) throws AtlasException { //nothing to do } @Override public void visitAttribute(String typeName, AttributeInfo attribute) throws StorageException, AtlasException { //nothing to do } private void visitDataType(IDataType dataType) { TypeVertexInfo info = null; info = new TypeVertexInfo(dataType.getTypeCategory(), dataType.getName(), dataType.getDescription()); addTypeIfNeeded(info); } public List<TypeVertexInfo> getVerticesToCreate() { return toCreate; } @Override public void visitDataType(TypeCategory category, String typeName, String typeDescription) { TypeVertexInfo info = new TypeVertexInfo(category, typeName, typeDescription); addTypeIfNeeded(info); } } <|start_filename|>graphdb/titan0/src/main/java/org/apache/atlas/repository/graphdb/titan0/Titan0Element.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan0; import java.lang.Override; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasElement; import org.apache.atlas.repository.graphdb.AtlasSchemaViolationException; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.thinkaurelius.titan.core.SchemaViolationException; import com.thinkaurelius.titan.core.TitanElement; import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.util.io.graphson.GraphSONMode; import com.tinkerpop.blueprints.util.io.graphson.GraphSONUtility; /** * Titan 0.5.4 implementation of AtlasElement. */ public class Titan0Element<T extends Element> implements AtlasElement { protected Titan0Graph graph; protected T wrappedElement; public Titan0Element(Titan0Graph graph, T element) { wrappedElement = element; this.graph = graph; } @Override public Object getId() { return wrappedElement.getId(); } @Override public Set<String> getPropertyKeys() { return wrappedElement.getPropertyKeys(); } @Override public <U> void setProperty(String propertyName, U value) { try { wrappedElement.setProperty(propertyName, value); } catch (SchemaViolationException e) { throw new AtlasSchemaViolationException(e); } } @Override public <U> U getProperty(String propertyName, Class<U> clazz) { Object rawValue = wrappedElement.getProperty(propertyName); if (rawValue == null) { return null; } if (AtlasEdge.class == clazz) { return (U)graph.getEdge(rawValue.toString()); } if (AtlasVertex.class == clazz) { return (U)graph.getVertex(rawValue.toString()); } return (U)rawValue; } /** * Gets all of the values of the given property. * @param propertyName * @return */ @Override public <T> Collection<T> getPropertyValues(String propertyName, Class<T> type) { return Collections.singleton(getProperty(propertyName, type)); } @Override public void removeProperty(String propertyName) { wrappedElement.removeProperty(propertyName); } @Override public JSONObject toJson(Set<String> propertyKeys) throws JSONException { return GraphSONUtility.jsonFromElement(wrappedElement, propertyKeys, GraphSONMode.NORMAL); } /* * (non-Javadoc) * * @see * org.apache.atlas.repository.graphdb.AtlasElement#getListProperty(java. * lang.String) */ @Override public List<String> getListProperty(String propertyName) { return getProperty(propertyName, List.class); } /* * (non-Javadoc) * * @see * org.apache.atlas.repository.graphdb.AtlasElement#setListProperty(java. * lang.String, java.util.List) */ @Override public void setListProperty(String propertyName, List<String> values) { setProperty(propertyName, values); } @Override public T getWrappedElement() { return wrappedElement; } @Override public int hashCode() { int result = 37; result = 17 * result + getClass().hashCode(); result = 17 * result + getWrappedElement().hashCode(); return result; } @Override public boolean equals(Object other) { if (other == null) { return false; } if (other.getClass() != getClass()) { return false; } Titan0Element otherElement = (Titan0Element) other; return getWrappedElement().equals(otherElement.getWrappedElement()); } /* * (non-Javadoc) * * @see org.apache.atlas.repository.graphdb.AtlasElement#exists() */ @Override public boolean exists() { try { return !((TitanElement)wrappedElement).isRemoved(); } catch(IllegalStateException e) { return false; } } /* * (non-Javadoc) * * @see * org.apache.atlas.repository.graphdb.AtlasElement#setJsonProperty(java. * lang.String, java.lang.Object) */ @Override public <T> void setJsonProperty(String propertyName, T value) { setProperty(propertyName, value); } /* * (non-Javadoc) * * @see * org.apache.atlas.repository.graphdb.AtlasElement#getJsonProperty(java. * lang.String) */ @Override public <T> T getJsonProperty(String propertyName) { return (T) getProperty(propertyName, String.class); } @Override public String getIdForDisplay() { return getId().toString(); } @Override public <V> List<V> getListProperty(String propertyName, Class<V> elementType) { List<String> value = getListProperty(propertyName); if (value == null) { return null; } if (AtlasEdge.class == elementType) { return (List<V>)Lists.transform(value, new Function<String, AtlasEdge>(){ @Override public AtlasEdge apply(String input) { return graph.getEdge(input); } }); } if (AtlasVertex.class == elementType) { return (List<V>)Lists.transform(value, new Function<String, AtlasVertex>(){ @Override public AtlasVertex apply(String input) { return graph.getVertex(input); } }); } return (List<V>)value; } @Override public void setPropertyFromElementsIds(String propertyName, List<AtlasElement> values) { List<String> propertyValue = new ArrayList<>(values.size()); for(AtlasElement element: values) { propertyValue.add(element.getId().toString()); } setProperty(propertyName, propertyValue); } @Override public void setPropertyFromElementId(String propertyName, AtlasElement value) { setProperty(propertyName, value.getId().toString()); } @Override public boolean isIdAssigned() { return true; } } <|start_filename|>notification/src/main/java/org/apache/atlas/kafka/KafkaNotification.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.kafka; import com.google.common.annotations.VisibleForTesting; import kafka.server.KafkaConfig; import kafka.server.KafkaServer; import kafka.utils.Time; import org.apache.atlas.ApplicationProperties; import org.apache.atlas.AtlasException; import org.apache.atlas.notification.AbstractNotification; import org.apache.atlas.notification.NotificationConsumer; import org.apache.atlas.notification.NotificationException; import org.apache.atlas.service.Service; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationConverter; import org.apache.commons.lang.StringUtils; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; import org.apache.zookeeper.server.NIOServerCnxnFactory; import org.apache.zookeeper.server.ServerCnxnFactory; import org.apache.zookeeper.server.ZooKeeperServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import scala.Option; import javax.inject.Inject; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.ArrayList; import java.util.Properties; import java.util.concurrent.Future; /** * Kafka specific access point to the Atlas notification framework. */ @Component @Order(3) public class KafkaNotification extends AbstractNotification implements Service { public static final Logger LOG = LoggerFactory.getLogger(KafkaNotification.class); public static final String PROPERTY_PREFIX = "atlas.kafka"; private static final String ATLAS_KAFKA_DATA = "data"; public static final String ATLAS_HOOK_TOPIC = "ATLAS_HOOK"; public static final String ATLAS_ENTITIES_TOPIC = "ATLAS_ENTITIES"; protected static final String CONSUMER_GROUP_ID_PROPERTY = "group.id"; private KafkaServer kafkaServer; private ServerCnxnFactory factory; private Properties properties; private KafkaConsumer consumer = null; private KafkaProducer producer = null; private Long pollTimeOutMs = 1000L; private static final Map<NotificationType, String> TOPIC_MAP = new HashMap<NotificationType, String>() { { put(NotificationType.HOOK, ATLAS_HOOK_TOPIC); put(NotificationType.ENTITIES, ATLAS_ENTITIES_TOPIC); } }; @VisibleForTesting String getTopicName(NotificationType notificationType) { return TOPIC_MAP.get(notificationType); } // ----- Constructors ---------------------------------------------------- /** * Construct a KafkaNotification. * * @param applicationProperties the application properties used to configure Kafka * * @throws AtlasException if the notification interface can not be created */ @Inject public KafkaNotification(Configuration applicationProperties) throws AtlasException { super(applicationProperties); Configuration subsetConfiguration = ApplicationProperties.getSubsetConfiguration(applicationProperties, PROPERTY_PREFIX); properties = ConfigurationConverter.getProperties(subsetConfiguration); //override to store offset in kafka //todo do we need ability to replay? //Override default configs properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer"); properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); pollTimeOutMs = subsetConfiguration.getLong("poll.timeout.ms", 1000); boolean oldApiCommitEnbleFlag = subsetConfiguration.getBoolean("auto.commit.enable",false); //set old autocommit value if new autoCommit property is not set. properties.put("enable.auto.commit", subsetConfiguration.getBoolean("enable.auto.commit", oldApiCommitEnbleFlag)); properties.put("session.timeout.ms", subsetConfiguration.getString("session.timeout.ms", "30000")); } @VisibleForTesting protected KafkaNotification(Properties properties) { this.properties = properties; } // ----- Service --------------------------------------------------------- @Override public void start() throws AtlasException { if (isHAEnabled()) { LOG.info("Not starting embedded instances when HA is enabled."); return; } if (isEmbedded()) { try { startZk(); startKafka(); } catch (Exception e) { throw new AtlasException("Failed to start embedded kafka", e); } } } @Override public void stop() { if (kafkaServer != null) { kafkaServer.shutdown(); } if (factory != null) { factory.shutdown(); } } // ----- NotificationInterface ------------------------------------------- @Override public <T> List<NotificationConsumer<T>> createConsumers(NotificationType notificationType, int numConsumers) { return createConsumers(notificationType, numConsumers, Boolean.valueOf(properties.getProperty("enable.auto.commit", properties.getProperty("auto.commit.enable","false")))); } @VisibleForTesting public <T> List<NotificationConsumer<T>> createConsumers(NotificationType notificationType, int numConsumers, boolean autoCommitEnabled) { Properties consumerProperties = getConsumerProperties(notificationType); List<NotificationConsumer<T>> consumers = new ArrayList<>(); AtlasKafkaConsumer kafkaConsumer = new AtlasKafkaConsumer(notificationType.getDeserializer(), getKafkaConsumer(consumerProperties,notificationType, autoCommitEnabled), autoCommitEnabled, pollTimeOutMs ); consumers.add(kafkaConsumer); return consumers; } @Override public void close() { if (producer != null) { producer.close(); producer = null; } } // ----- AbstractNotification -------------------------------------------- @Override public void sendInternal(NotificationType type, String... messages) throws NotificationException { if (producer == null) { createProducer(); } sendInternalToProducer(producer, type, messages); } @VisibleForTesting void sendInternalToProducer(Producer p, NotificationType type, String[] messages) throws NotificationException { String topic = TOPIC_MAP.get(type); List<MessageContext> messageContexts = new ArrayList<>(); for (String message : messages) { ProducerRecord record = new ProducerRecord(topic, message); LOG.debug("Sending message for topic {}: {}", topic, message); Future future = p.send(record); messageContexts.add(new MessageContext(future, message)); } List<String> failedMessages = new ArrayList<>(); Exception lastFailureException = null; for (MessageContext context : messageContexts) { try { RecordMetadata response = context.getFuture().get(); LOG.debug("Sent message for topic - {}, partition - {}, offset - {}", response.topic(), response.partition(), response.offset()); } catch (Exception e) { lastFailureException = e; failedMessages.add(context.getMessage()); } } if (lastFailureException != null) { throw new NotificationException(lastFailureException, failedMessages); } } public KafkaConsumer getKafkaConsumer(Properties consumerProperties, NotificationType type, boolean autoCommitEnabled) { if(this.consumer == null) { try { String topic = TOPIC_MAP.get(type); consumerProperties.put("enable.auto.commit", autoCommitEnabled); this.consumer = new KafkaConsumer(consumerProperties); this.consumer.subscribe(Arrays.asList(topic)); }catch (Exception ee) { LOG.error("Exception in getKafkaConsumer ", ee); } } return this.consumer; } // Get properties for consumer request private Properties getConsumerProperties(NotificationType type) { // find the configured group id for the given notification type String groupId = properties.getProperty(type.toString().toLowerCase() + "." + CONSUMER_GROUP_ID_PROPERTY); if (StringUtils.isEmpty(groupId)) { throw new IllegalStateException("No configuration group id set for the notification type " + type); } Properties consumerProperties = new Properties(); consumerProperties.putAll(properties); consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, groupId); LOG.info("Consumer property: atlas.kafka.enable.auto.commit: {}", consumerProperties.getProperty("enable.auto.commit")); return consumerProperties; } private File constructDir(String dirPrefix) { File file = new File(properties.getProperty(ATLAS_KAFKA_DATA), dirPrefix); if (!file.exists() && !file.mkdirs()) { throw new RuntimeException("could not create temp directory: " + file.getAbsolutePath()); } return file; } private synchronized void createProducer() { if (producer == null) { producer = new KafkaProducer(properties); } } private URL getURL(String url) throws MalformedURLException { try { return new URL(url); } catch (MalformedURLException e) { return new URL("http://" + url); } } private String startZk() throws IOException, InterruptedException, URISyntaxException { String zkValue = properties.getProperty("zookeeper.connect"); LOG.debug("Starting zookeeper at {}", zkValue); URL zkAddress = getURL(zkValue); this.factory = NIOServerCnxnFactory.createFactory( new InetSocketAddress(zkAddress.getHost(), zkAddress.getPort()), 1024); File snapshotDir = constructDir("zk/txn"); File logDir = constructDir("zk/snap"); factory.startup(new ZooKeeperServer(snapshotDir, logDir, 500)); return factory.getLocalAddress().getAddress().toString(); } private void startKafka() throws IOException, URISyntaxException { String kafkaValue = properties.getProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG); LOG.debug("Starting kafka at {}", kafkaValue); URL kafkaAddress = getURL(kafkaValue); Properties brokerConfig = properties; brokerConfig.setProperty("broker.id", "1"); brokerConfig.setProperty("host.name", kafkaAddress.getHost()); brokerConfig.setProperty("port", String.valueOf(kafkaAddress.getPort())); brokerConfig.setProperty("log.dirs", constructDir("kafka").getAbsolutePath()); brokerConfig.setProperty("log.flush.interval.messages", String.valueOf(1)); kafkaServer = new KafkaServer(KafkaConfig.fromProps(brokerConfig), new SystemTime(), Option.apply(this.getClass().getName())); kafkaServer.startup(); LOG.debug("Embedded kafka server started with broker config {}", brokerConfig); } // ----- inner class : SystemTime ---------------------------------------- private static class SystemTime implements Time { @Override public long milliseconds() { return System.currentTimeMillis(); } @Override public long nanoseconds() { return System.nanoTime(); } @Override public void sleep(long arg0) { try { Thread.sleep(arg0); } catch (InterruptedException e) { throw new RuntimeException(e); } } } private class MessageContext { private final Future<RecordMetadata> future; private final String message; public MessageContext(Future<RecordMetadata> future, String message) { this.future = future; this.message = message; } public Future<RecordMetadata> getFuture() { return future; } public String getMessage() { return message; } } } <|start_filename|>intg/src/main/java/org/apache/atlas/model/instance/AtlasClassification.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.model.instance; import java.io.Serializable; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSeeAlso; import org.apache.atlas.model.PList; import org.apache.atlas.model.SearchFilter.SortType; import org.codehaus.jackson.annotate.JsonAutoDetect; import static org.codehaus.jackson.annotate.JsonAutoDetect.Visibility.PUBLIC_ONLY; import static org.codehaus.jackson.annotate.JsonAutoDetect.Visibility.NONE; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.map.annotate.JsonSerialize; /** * An instance of a classification; it doesn't have an identity, this object exists only when associated with an entity. */ @JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) @JsonIgnoreProperties(ignoreUnknown=true) @XmlRootElement @XmlAccessorType(XmlAccessType.PROPERTY) public class AtlasClassification extends AtlasStruct implements Serializable { private static final long serialVersionUID = 1L; public AtlasClassification() { this(null, null); } public AtlasClassification(String typeName) { this(typeName, null); } public AtlasClassification(String typeName, Map<String, Object> attributes) { super(typeName, attributes); } public AtlasClassification(String typeName, String attrName, Object attrValue) { super(typeName, attrName, attrValue); } public AtlasClassification(AtlasClassification other) { if (other != null) { setTypeName(other.getTypeName()); setAttributes(other.getAttributes()); } } /** * REST serialization friendly list. */ @JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) @JsonIgnoreProperties(ignoreUnknown=true) @XmlRootElement @XmlAccessorType(XmlAccessType.PROPERTY) @XmlSeeAlso(AtlasClassification.class) public static class AtlasClassifications extends PList<AtlasClassification> { private static final long serialVersionUID = 1L; public AtlasClassifications() { super(); } public AtlasClassifications(List<AtlasClassification> list) { super(list); } public AtlasClassifications(List list, long startIndex, int pageSize, long totalCount, SortType sortType, String sortBy) { super(list, startIndex, pageSize, totalCount, sortType, sortBy); } } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/typestore/TypeVertexInfo.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.typestore; import java.util.Objects; import org.apache.atlas.typesystem.types.DataTypes; import org.apache.atlas.typesystem.types.DataTypes.TypeCategory; /** * Records the information needed to create a particular type vertex. */ public class TypeVertexInfo { private DataTypes.TypeCategory category; private String typeName; private String typeDescription; public TypeVertexInfo(TypeCategory category, String typeName, String typeDescription) { super(); this.category = category; this.typeName = typeName; this.typeDescription = typeDescription; } public DataTypes.TypeCategory getCategory() { return category; } public void setCategory(DataTypes.TypeCategory category) { this.category = category; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } public String getTypeDescription() { return typeDescription; } public void setTypeDescription(String typeDescription) { this.typeDescription = typeDescription; } @Override public int hashCode() { return Objects.hash(category, typeName); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (getClass() != obj.getClass()) { return false; } TypeVertexInfo other = (TypeVertexInfo)obj; if(! Objects.equals(category, other.category)) { return false; } if(! Objects.equals(typeName, other.typeName)) { return false; } return true; } } <|start_filename|>catalog/src/test/java/org/apache/atlas/catalog/EntityTagResourceProviderTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.catalog; import org.apache.atlas.catalog.exception.CatalogException; import org.apache.atlas.catalog.exception.InvalidPayloadException; import org.apache.atlas.catalog.exception.ResourceAlreadyExistsException; import org.apache.atlas.catalog.exception.ResourceNotFoundException; import org.apache.atlas.catalog.query.AtlasQuery; import org.apache.atlas.catalog.query.QueryFactory; import org.easymock.Capture; import org.testng.annotations.Test; import java.util.*; import static org.easymock.EasyMock.*; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; /** * Unit tests for EntityTagResourceProvider. */ public class EntityTagResourceProviderTest { @Test public void testGetResource() throws Exception { AtlasTypeSystem typeSystem = createStrictMock(AtlasTypeSystem.class); QueryFactory queryFactory = createStrictMock(QueryFactory.class); AtlasQuery query = createStrictMock(AtlasQuery.class); Capture<Request> requestCapture = newCapture(); Collection<Map<String, Object>> queryResult = new ArrayList<>(); Map<String, Object> queryResultRow = new HashMap<>(); queryResult.add(queryResultRow); queryResultRow.put("name", "taxonomyName.termName"); queryResultRow.put("description", "test term description"); // mock expectations expect(queryFactory.createEntityTagQuery(capture(requestCapture))).andReturn(query); expect(query.execute()).andReturn(queryResult); replay(typeSystem, queryFactory, query); EntityTagResourceProvider provider = new EntityTagResourceProvider(typeSystem); provider.setQueryFactory(queryFactory); Map<String, Object> requestProperties = new HashMap<>(); requestProperties.put("name", "taxonomyName.termName"); requestProperties.put("id", "1"); Request userRequest = new InstanceRequest(requestProperties); Result result = provider.getResourceById(userRequest); assertEquals(1, result.getPropertyMaps().size()); assertEquals(queryResultRow, result.getPropertyMaps().iterator().next()); Request request = requestCapture.getValue(); assertNull(request.getQueryString()); assertEquals(0, request.getAdditionalSelectProperties().size()); assertEquals(2, request.getQueryProperties().size()); assertEquals("taxonomyName.termName", request.getQueryProperties().get("name")); assertEquals(Request.Cardinality.INSTANCE, request.getCardinality()); verify(typeSystem, queryFactory, query); } @Test(expectedExceptions = ResourceNotFoundException.class) public void testGetResource_404() throws Exception { AtlasTypeSystem typeSystem = createStrictMock(AtlasTypeSystem.class); QueryFactory queryFactory = createStrictMock(QueryFactory.class); AtlasQuery query = createStrictMock(AtlasQuery.class); Capture<Request> requestCapture = newCapture(); // empty response should result in a ResourceNotFoundException Collection<Map<String, Object>> emptyResponse = new ArrayList<>(); // mock expectations expect(queryFactory.createEntityTagQuery(capture(requestCapture))).andReturn(query); expect(query.execute()).andReturn(emptyResponse); replay(typeSystem, queryFactory, query); EntityTagResourceProvider provider = new EntityTagResourceProvider(typeSystem); provider.setQueryFactory(queryFactory); Map<String, Object> requestProperties = new HashMap<>(); requestProperties.put("name", "taxonomyName.termName"); requestProperties.put("id", "1"); Request request = new InstanceRequest(requestProperties); provider.getResourceById(request); } @Test public void testGetResources() throws Exception { AtlasTypeSystem typeSystem = createStrictMock(AtlasTypeSystem.class); QueryFactory queryFactory = createStrictMock(QueryFactory.class); AtlasQuery query = createStrictMock(AtlasQuery.class); Capture<Request> requestCapture = newCapture(); Collection<Map<String, Object>> queryResult = new ArrayList<>(); Map<String, Object> queryResultRow1 = new HashMap<>(); queryResult.add(queryResultRow1); queryResultRow1.put("name", "testTaxonomy.termName"); queryResultRow1.put("description", "test term description"); Map<String, Object> queryResultRow2 = new HashMap<>(); queryResult.add(queryResultRow2); queryResultRow2.put("name", "testTaxonomy.termName2"); queryResultRow2.put("description", "test term 2 description"); // mock expectations expect(queryFactory.createEntityTagQuery(capture(requestCapture))).andReturn(query); expect(query.execute()).andReturn(queryResult); replay(typeSystem, queryFactory, query); EntityTagResourceProvider provider = new EntityTagResourceProvider(typeSystem); provider.setQueryFactory(queryFactory); Map<String, Object> requestProperties = new HashMap<>(); requestProperties.put("id", "1"); Request userRequest = new CollectionRequest(requestProperties, "name:testTaxonomy.*"); // invoke test method Result result = provider.getResources(userRequest); assertEquals(2, result.getPropertyMaps().size()); assertTrue(result.getPropertyMaps().contains(queryResultRow1)); assertTrue(result.getPropertyMaps().contains(queryResultRow2)); Request request = requestCapture.getValue(); assertEquals("name:testTaxonomy.*", request.getQueryString()); assertEquals(0, request.getAdditionalSelectProperties().size()); verify(typeSystem, queryFactory, query); } @Test public void testGetResources_noResults() throws Exception { AtlasTypeSystem typeSystem = createStrictMock(AtlasTypeSystem.class); QueryFactory queryFactory = createStrictMock(QueryFactory.class); AtlasQuery query = createStrictMock(AtlasQuery.class); Capture<Request> requestCapture = newCapture(); Collection<Map<String, Object>> queryResult = new ArrayList<>(); // mock expectations expect(queryFactory.createEntityTagQuery(capture(requestCapture))).andReturn(query); expect(query.execute()).andReturn(queryResult); replay(typeSystem, queryFactory, query); EntityTagResourceProvider provider = new EntityTagResourceProvider(typeSystem); provider.setQueryFactory(queryFactory); Map<String, Object> requestProperties = new HashMap<>(); requestProperties.put("id", "1"); Request userRequest = new CollectionRequest(requestProperties, "name:testTaxonomy.*"); // invoke test method Result result = provider.getResources(userRequest); assertEquals(0, result.getPropertyMaps().size()); Request request = requestCapture.getValue(); assertEquals("name:testTaxonomy.*", request.getQueryString()); assertEquals(0, request.getAdditionalSelectProperties().size()); verify(typeSystem, queryFactory, query); } @Test(expectedExceptions = InvalidPayloadException.class) public void testCreateResource_invalidRequest__noName() throws Exception { AtlasTypeSystem typeSystem = createStrictMock(AtlasTypeSystem.class); QueryFactory queryFactory = createStrictMock(QueryFactory.class); AtlasQuery query = createStrictMock(AtlasQuery.class); replay(typeSystem, queryFactory, query); Map<String, Object> requestProperties = new HashMap<>(); // missing name name should result in InvalidPayloadException requestProperties.put("description", "description"); Request userRequest = new InstanceRequest(requestProperties); EntityTagResourceProvider provider = new EntityTagResourceProvider(typeSystem); provider.setQueryFactory(queryFactory); provider.createResource(userRequest); } @Test public void testCreateResource() throws Exception { AtlasTypeSystem typeSystem = createStrictMock(AtlasTypeSystem.class); QueryFactory queryFactory = createStrictMock(QueryFactory.class); AtlasQuery query = createStrictMock(AtlasQuery.class); ResourceProvider termResourceProvider = createStrictMock(TermResourceProvider.class); Capture<Request> termRequestCapture = newCapture(); Collection<Map<String, Object>> termQueryResult = new ArrayList<>(); Map<String, Object> termQueryResultRow = new HashMap<>(); termQueryResult.add(termQueryResultRow); termQueryResultRow.put("name", "testTaxonomy.termName"); termQueryResultRow.put("type", "testTaxonomy.termName"); termQueryResultRow.put("available_as_tag", true); termQueryResultRow.put("description", "term description"); Result termResult = new Result(termQueryResult); // mock expectations expect(termResourceProvider.getResourceById(capture(termRequestCapture))).andReturn(termResult); Map<String, Object> tagProperties = new HashMap<>(); tagProperties.put("name", "testTaxonomy.termName"); tagProperties.put("description", "term description"); typeSystem.createTraitInstance("11-22-33", "testTaxonomy.termName", tagProperties); replay(typeSystem, queryFactory, query, termResourceProvider); EntityTagResourceProvider provider = new TestEntityTagResourceProvider(typeSystem, termResourceProvider); provider.setQueryFactory(queryFactory); Map<String, Object> requestProperties = new HashMap<>(); requestProperties.put("name", "testTaxonomy.termName"); requestProperties.put("id", "11-22-33"); Request userRequest = new InstanceRequest(requestProperties); provider.createResource(userRequest); Request termRequest = termRequestCapture.getValue(); Map<String, Object> termRequestProps = termRequest.getQueryProperties(); assertEquals(1, termRequestProps.size()); TermPath termPath = (TermPath) termRequestProps.get("termPath"); assertEquals("testTaxonomy.termName", termPath.getFullyQualifiedName()); assertEquals(1, termRequest.getAdditionalSelectProperties().size()); assertEquals("type", termRequest.getAdditionalSelectProperties().iterator().next()); assertNull(termRequest.getQueryString()); verify(typeSystem, queryFactory, query, termResourceProvider); } @Test(expectedExceptions = CatalogException.class) public void testCreateResource_invalidRequest__termNotAvailableForTagging() throws Exception { AtlasTypeSystem typeSystem = createStrictMock(AtlasTypeSystem.class); QueryFactory queryFactory = createStrictMock(QueryFactory.class); AtlasQuery query = createStrictMock(AtlasQuery.class); ResourceProvider termResourceProvider = createStrictMock(TermResourceProvider.class); Capture<Request> termRequestCapture = newCapture(); Collection<Map<String, Object>> termQueryResult = new ArrayList<>(); Map<String, Object> termQueryResultRow = new HashMap<>(); termQueryResult.add(termQueryResultRow); termQueryResultRow.put("name", "testTaxonomy.termName"); termQueryResultRow.put("type", "testTaxonomy.termName"); // false value for 'available_as_tag' should result in an exception termQueryResultRow.put("available_as_tag", false); termQueryResultRow.put("description", "term description"); Result termResult = new Result(termQueryResult); // mock expectations expect(termResourceProvider.getResourceById(capture(termRequestCapture))).andReturn(termResult); replay(typeSystem, queryFactory, query, termResourceProvider); EntityTagResourceProvider provider = new TestEntityTagResourceProvider(typeSystem, termResourceProvider); provider.setQueryFactory(queryFactory); Map<String, Object> requestProperties = new HashMap<>(); requestProperties.put("name", "testTaxonomy.termName"); requestProperties.put("id", "11-22-33"); Request userRequest = new InstanceRequest(requestProperties); provider.createResource(userRequest); } @Test(expectedExceptions = ResourceAlreadyExistsException.class) public void testCreateResource_invalidRequest__alreadyExists() throws Exception { AtlasTypeSystem typeSystem = createStrictMock(AtlasTypeSystem.class); QueryFactory queryFactory = createStrictMock(QueryFactory.class); AtlasQuery query = createStrictMock(AtlasQuery.class); ResourceProvider termResourceProvider = createStrictMock(TermResourceProvider.class); Capture<Request> termRequestCapture = newCapture(); Collection<Map<String, Object>> termQueryResult = new ArrayList<>(); Map<String, Object> termQueryResultRow = new HashMap<>(); termQueryResult.add(termQueryResultRow); termQueryResultRow.put("name", "testTaxonomy.termName"); termQueryResultRow.put("type", "testTaxonomy.termName"); termQueryResultRow.put("available_as_tag", true); termQueryResultRow.put("description", "term description"); Result termResult = new Result(termQueryResult); // mock expectations expect(termResourceProvider.getResourceById(capture(termRequestCapture))).andReturn(termResult); Map<String, Object> tagProperties = new HashMap<>(); tagProperties.put("name", "testTaxonomy.termName"); tagProperties.put("description", "term description"); typeSystem.createTraitInstance("11-22-33", "testTaxonomy.termName", tagProperties); expectLastCall().andThrow(new ResourceAlreadyExistsException("")); replay(typeSystem, queryFactory, query, termResourceProvider); EntityTagResourceProvider provider = new TestEntityTagResourceProvider(typeSystem, termResourceProvider); provider.setQueryFactory(queryFactory); Map<String, Object> requestProperties = new HashMap<>(); requestProperties.put("name", "testTaxonomy.termName"); requestProperties.put("id", "11-22-33"); Request userRequest = new InstanceRequest(requestProperties); provider.createResource(userRequest); } @Test public void testCreateResources() throws Exception { AtlasTypeSystem typeSystem = createMock(AtlasTypeSystem.class); QueryFactory queryFactory = createStrictMock(QueryFactory.class); AtlasQuery entityQuery = createMock(AtlasQuery.class); ResourceProvider termResourceProvider = createMock(TermResourceProvider.class); Capture<Request> entityRequestCapture = newCapture(); Capture<Request> termRequestCapture1 = newCapture(); Capture<Request> termRequestCapture2 = newCapture(); Collection<Map<String, Object>> entityQueryResult = new ArrayList<>(); Map<String, Object> entityQueryResultRow = new HashMap<>(); entityQueryResultRow.put("id", "1"); entityQueryResult.add(entityQueryResultRow); Map<String, Object> entityQueryResultRow2 = new HashMap<>(); entityQueryResultRow2.put("id", "2"); entityQueryResult.add(entityQueryResultRow2); Collection<Map<String, Object>> termQueryResult1 = new ArrayList<>(); Map<String, Object> termQueryResultRow1 = new HashMap<>(); termQueryResult1.add(termQueryResultRow1); termQueryResultRow1.put("name", "testTaxonomy.termName1"); termQueryResultRow1.put("type", "testTaxonomy.termName1"); termQueryResultRow1.put("available_as_tag", true); termQueryResultRow1.put("description", "term description"); Result termResult1 = new Result(termQueryResult1); Collection<Map<String, Object>> termQueryResult2 = new ArrayList<>(); Map<String, Object> termQueryResultRow2 = new HashMap<>(); termQueryResult2.add(termQueryResultRow2); termQueryResultRow2.put("name", "testTaxonomy.termName2"); termQueryResultRow2.put("type", "testTaxonomy.termName2"); termQueryResultRow2.put("available_as_tag", true); termQueryResultRow2.put("description", "term 2 description"); Result termResult2 = new Result(termQueryResult2); // mock expectations expect(queryFactory.createEntityQuery(capture(entityRequestCapture))).andReturn(entityQuery); expect(entityQuery.execute()).andReturn(entityQueryResult); expect(termResourceProvider.getResourceById(capture(termRequestCapture1))).andReturn(termResult1); expect(termResourceProvider.getResourceById(capture(termRequestCapture2))).andReturn(termResult2); Map<String, Object> tagProperties1 = new HashMap<>(); tagProperties1.put("name", "testTaxonomy.termName1"); tagProperties1.put("description", "term description"); // each tag is associated with each entity typeSystem.createTraitInstance("1", "testTaxonomy.termName1", tagProperties1); typeSystem.createTraitInstance("2", "testTaxonomy.termName1", tagProperties1); Map<String, Object> tagProperties2 = new HashMap<>(); tagProperties2.put("name", "testTaxonomy.termName2"); tagProperties2.put("description", "term 2 description"); // each tag is associated with each entity typeSystem.createTraitInstance("1", "testTaxonomy.termName2", tagProperties2); typeSystem.createTraitInstance("2", "testTaxonomy.termName2", tagProperties2); replay(typeSystem, queryFactory, entityQuery, termResourceProvider); // end mock expectations EntityTagResourceProvider provider = new TestEntityTagResourceProvider(typeSystem, termResourceProvider); provider.setQueryFactory(queryFactory); Map<String, Object> requestProps = new HashMap<>(); Collection<Map<String, String>> tagMaps = new ArrayList<>(); requestProps.put("tags", tagMaps); Map<String, String> tagMap1 = new HashMap<>(); tagMap1.put("name", "testTaxonomy.termName1"); tagMaps.add(tagMap1); Map<String, String> tagMap2 = new HashMap<>(); tagMap2.put("name", "testTaxonomy.termName2"); tagMaps.add(tagMap2); Request userRequest = new CollectionRequest(requestProps, "name:foo*"); // invoke method being tested Collection<String> createResult = provider.createResources(userRequest); assertEquals(4, createResult.size()); assertTrue(createResult.contains("v1/entities/1/tags/testTaxonomy.termName1")); assertTrue(createResult.contains("v1/entities/1/tags/testTaxonomy.termName2")); assertTrue(createResult.contains("v1/entities/2/tags/testTaxonomy.termName1")); assertTrue(createResult.contains("v1/entities/2/tags/testTaxonomy.termName2")); Request entityRequest = entityRequestCapture.getValue(); assertEquals("name:foo*", entityRequest.getQueryString()); assertEquals(Request.Cardinality.COLLECTION, entityRequest.getCardinality()); Request termRequest1 = termRequestCapture1.getValue(); assertNull(termRequest1.getQueryString()); assertEquals(Request.Cardinality.INSTANCE, termRequest1.getCardinality()); Map<String, Object> termRequestProps = termRequest1.getQueryProperties(); assertEquals(1, termRequestProps.size()); TermPath termPath = (TermPath) termRequestProps.get("termPath"); assertEquals("testTaxonomy.termName1", termPath.getFullyQualifiedName()); Request termRequest2 = termRequestCapture2.getValue(); assertNull(termRequest2.getQueryString()); assertEquals(Request.Cardinality.INSTANCE, termRequest2.getCardinality()); Map<String, Object> termRequestProps2 = termRequest2.getQueryProperties(); assertEquals(1, termRequestProps2.size()); TermPath termPath2 = (TermPath) termRequestProps2.get("termPath"); assertEquals("testTaxonomy.termName2", termPath2.getFullyQualifiedName()); verify(typeSystem, queryFactory, entityQuery, termResourceProvider); } @Test public void testDeleteResourceById() throws Exception { AtlasTypeSystem typeSystem = createStrictMock(AtlasTypeSystem.class); // mock expectations typeSystem.deleteTag("1", "taxonomyName.termName"); replay(typeSystem); Map<String, Object> requestProperties = new HashMap<>(); requestProperties.put("name", "taxonomyName.termName"); requestProperties.put("id", "1"); Request userRequest = new InstanceRequest(requestProperties); // instantiate EntityTagResourceProvider and invoke method being tested EntityTagResourceProvider provider = new EntityTagResourceProvider(typeSystem); provider.setQueryFactory(null); provider.deleteResourceById(userRequest); verify(typeSystem); } //todo: test behavior of createResources in case of partial success after behavior is defined private static class TestEntityTagResourceProvider extends EntityTagResourceProvider { private ResourceProvider testTermResourceProvider; public TestEntityTagResourceProvider(AtlasTypeSystem typeSystem, ResourceProvider termResourceProvider) { super(typeSystem); testTermResourceProvider = termResourceProvider; } @Override protected synchronized ResourceProvider getTermResourceProvider() { return testTermResourceProvider; } } } <|start_filename|>server-api/src/main/java/org/apache/atlas/RequestContext.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.atlas.metrics.Metrics; import org.apache.atlas.model.instance.AtlasEntity.AtlasEntityWithExtInfo; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.persistence.Id; import org.apache.atlas.typesystem.types.ClassType; import org.apache.atlas.typesystem.types.TypeSystem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Deprecated public class RequestContext { private static final Logger LOG = LoggerFactory.getLogger(RequestContext.class); private static final ThreadLocal<RequestContext> CURRENT_CONTEXT = new ThreadLocal<>(); private Set<String> createdEntityIds = new LinkedHashSet<>(); private Set<String> updatedEntityIds = new LinkedHashSet<>(); private Set<String> deletedEntityIds = new LinkedHashSet<>(); private List<ITypedReferenceableInstance> deletedEntities = new ArrayList<>(); private Map<String,ITypedReferenceableInstance> entityCacheV1 = new HashMap<>(); private Map<String,AtlasEntityWithExtInfo> entityCacheV2 = new HashMap<>(); private String user; private long requestTime; private TypeSystem typeSystem = TypeSystem.getInstance(); private Metrics metrics = new Metrics(); private RequestContext() { } //To handle gets from background threads where createContext() is not called //createContext called for every request in the filter public static RequestContext get() { if (CURRENT_CONTEXT.get() == null) { synchronized (RequestContext.class) { if (CURRENT_CONTEXT.get() == null) { createContext(); } } } // ensure that RequestContextV1 is also initialized for this request RequestContextV1.get(); return CURRENT_CONTEXT.get(); } public static RequestContext createContext() { RequestContext context = new RequestContext(); context.requestTime = System.currentTimeMillis(); CURRENT_CONTEXT.set(context); return context; } /** * Adds the specified instance to the cache * */ public void cache(ITypedReferenceableInstance instance) { entityCacheV1.put(instance.getId()._getId(), instance); } /** * Adds the specified instance to the cache * */ public void cache(AtlasEntityWithExtInfo entity) { if (entity != null && entity.getEntity() != null && entity.getEntity().getGuid() != null) { entityCacheV2.put(entity.getEntity().getGuid(), entity); } } /** * Checks if an instance with the given guid is in the cache for this request. Either returns the instance * or null if it is not in the cache. * * @param guid the guid to find * @return Either the instance or null if it is not in the cache. */ public ITypedReferenceableInstance getInstanceV1(String guid) { return entityCacheV1.get(guid); } /** * Checks if an instance with the given guid is in the cache for this request. Either returns the instance * or null if it is not in the cache. * * @param guid the guid to find * @return Either the instance or null if it is not in the cache. */ public AtlasEntityWithExtInfo getInstanceV2(String guid) { return entityCacheV2.get(guid); } public static void clear() { RequestContext instance = CURRENT_CONTEXT.get(); if (instance != null) { if (instance.entityCacheV1 != null) { instance.entityCacheV1.clear(); } if (instance.entityCacheV2 != null) { instance.entityCacheV2.clear(); } } CURRENT_CONTEXT.remove(); } public String getUser() { return user; } public void setUser(String user) { this.user = user; RequestContextV1.get().setUser(user); } public void recordEntityCreate(Collection<String> createdEntityIds) { this.createdEntityIds.addAll(createdEntityIds); } public void recordEntityUpdate(Collection<String> updatedEntityIds) { this.updatedEntityIds.addAll(updatedEntityIds); } public void recordEntityUpdate(String entityId) { this.updatedEntityIds.add(entityId); } public void recordEntityDelete(String entityId, String typeName) throws AtlasException { ClassType type = typeSystem.getDataType(ClassType.class, typeName); ITypedReferenceableInstance entity = type.createInstance(new Id(entityId, 0, typeName)); if (deletedEntityIds.add(entityId)) { deletedEntities.add(entity); } } public List<String> getCreatedEntityIds() { return new ArrayList<>(createdEntityIds); } public List<String> getUpdatedEntityIds() { return new ArrayList<>(updatedEntityIds); } public List<String> getDeletedEntityIds() { return new ArrayList<>(deletedEntityIds); } public List<ITypedReferenceableInstance> getDeletedEntities() { return deletedEntities; } public long getRequestTime() { return requestTime; } public boolean isDeletedEntity(String entityGuid) { return deletedEntityIds.contains(entityGuid); } public static Metrics getMetrics() { return get().metrics; } } <|start_filename|>repository/src/main/java/org/apache/atlas/discovery/DataSetLineageService.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.discovery; import org.apache.atlas.ApplicationProperties; import org.apache.atlas.AtlasClient; import org.apache.atlas.AtlasConfiguration; import org.apache.atlas.AtlasException; import org.apache.atlas.annotation.GraphTransaction; import org.apache.atlas.discovery.graph.DefaultGraphPersistenceStrategy; import org.apache.atlas.discovery.graph.GraphBackedDiscoveryService; import org.apache.atlas.query.GremlinQueryResult; import org.apache.atlas.query.InputLineageClosureQuery; import org.apache.atlas.query.OutputLineageClosureQuery; import org.apache.atlas.query.QueryParams; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.MetadataRepository; import org.apache.atlas.repository.graph.GraphHelper; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.typesystem.exception.EntityNotFoundException; import org.apache.atlas.typesystem.exception.SchemaNotFoundException; import org.apache.atlas.typesystem.persistence.Id; import org.apache.atlas.typesystem.types.TypeUtils; import org.apache.atlas.utils.ParamChecker; import org.apache.commons.configuration.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import scala.Option; import scala.Some; import scala.collection.JavaConversions; import scala.collection.immutable.List; import javax.inject.Inject; import javax.inject.Singleton; import java.util.Arrays; import java.util.Iterator; /** * Hive implementation of Lineage service interface. */ @Singleton @Component public class DataSetLineageService implements LineageService { private static final Logger LOG = LoggerFactory.getLogger(DataSetLineageService.class); private static final Option<List<String>> SELECT_ATTRIBUTES = Some.apply(JavaConversions.asScalaBuffer(Arrays.asList(AtlasClient.NAME, AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME)).toList()); public static final String SELECT_INSTANCE_GUID = "__guid"; public static final String DATASET_SCHEMA_QUERY_PREFIX = "atlas.lineage.schema.query."; private static final String HIVE_PROCESS_TYPE_NAME = "Process"; private static final String HIVE_PROCESS_INPUT_ATTRIBUTE_NAME = "inputs"; private static final String HIVE_PROCESS_OUTPUT_ATTRIBUTE_NAME = "outputs"; private static final Configuration propertiesConf; static { try { propertiesConf = ApplicationProperties.get(); } catch (AtlasException e) { throw new RuntimeException(e); } } private final AtlasGraph graph; private final DefaultGraphPersistenceStrategy graphPersistenceStrategy; private final GraphBackedDiscoveryService discoveryService; @Inject DataSetLineageService(MetadataRepository metadataRepository, GraphBackedDiscoveryService discoveryService, AtlasGraph atlasGraph) throws DiscoveryException { this.graph = atlasGraph; this.graphPersistenceStrategy = new DefaultGraphPersistenceStrategy(metadataRepository); this.discoveryService = discoveryService; } /** * Return the lineage outputs graph for the given datasetName. * * @param datasetName datasetName * @return Outputs Graph as JSON */ @Override @GraphTransaction public String getOutputsGraph(String datasetName) throws AtlasException { LOG.info("Fetching lineage outputs graph for datasetName={}", datasetName); datasetName = ParamChecker.notEmpty(datasetName, "dataset name"); TypeUtils.Pair<String, String> typeIdPair = validateDatasetNameExists(datasetName); return getOutputsGraphForId(typeIdPair.right); } /** * Return the lineage inputs graph for the given tableName. * * @param tableName tableName * @return Inputs Graph as JSON */ @Override @GraphTransaction public String getInputsGraph(String tableName) throws AtlasException { LOG.info("Fetching lineage inputs graph for tableName={}", tableName); tableName = ParamChecker.notEmpty(tableName, "table name"); TypeUtils.Pair<String, String> typeIdPair = validateDatasetNameExists(tableName); return getInputsGraphForId(typeIdPair.right); } @Override @GraphTransaction public String getInputsGraphForEntity(String guid) throws AtlasException { LOG.info("Fetching lineage inputs graph for entity={}", guid); guid = ParamChecker.notEmpty(guid, "Entity id"); validateDatasetExists(guid); return getInputsGraphForId(guid); } private String getInputsGraphForId(String guid) { InputLineageClosureQuery inputsQuery = new InputLineageClosureQuery(AtlasClient.DATA_SET_SUPER_TYPE, SELECT_INSTANCE_GUID, guid, HIVE_PROCESS_TYPE_NAME, HIVE_PROCESS_INPUT_ATTRIBUTE_NAME, HIVE_PROCESS_OUTPUT_ATTRIBUTE_NAME, Option.empty(), SELECT_ATTRIBUTES, true, graphPersistenceStrategy, graph); GremlinQueryResult result = inputsQuery.evaluate(); return inputsQuery.graph(result).toInstanceJson(); } @Override @GraphTransaction public String getOutputsGraphForEntity(String guid) throws AtlasException { LOG.info("Fetching lineage outputs graph for entity guid={}", guid); guid = ParamChecker.notEmpty(guid, "Entity id"); validateDatasetExists(guid); return getOutputsGraphForId(guid); } private String getOutputsGraphForId(String guid) { OutputLineageClosureQuery outputsQuery = new OutputLineageClosureQuery(AtlasClient.DATA_SET_SUPER_TYPE, SELECT_INSTANCE_GUID, guid, HIVE_PROCESS_TYPE_NAME, HIVE_PROCESS_INPUT_ATTRIBUTE_NAME, HIVE_PROCESS_OUTPUT_ATTRIBUTE_NAME, Option.empty(), SELECT_ATTRIBUTES, true, graphPersistenceStrategy, graph); GremlinQueryResult result = outputsQuery.evaluate(); return outputsQuery.graph(result).toInstanceJson(); } /** * Return the schema for the given tableName. * * @param datasetName tableName * @return Schema as JSON */ @Override @GraphTransaction public String getSchema(String datasetName) throws AtlasException { datasetName = ParamChecker.notEmpty(datasetName, "table name"); LOG.info("Fetching schema for tableName={}", datasetName); TypeUtils.Pair<String, String> typeIdPair = validateDatasetNameExists(datasetName); return getSchemaForId(typeIdPair.left, typeIdPair.right); } private String getSchemaForId(String typeName, String guid) throws DiscoveryException, SchemaNotFoundException { String configName = DATASET_SCHEMA_QUERY_PREFIX + typeName; if (propertiesConf.getString(configName) != null) { final String schemaQuery = String.format(propertiesConf.getString(configName), guid); int limit = AtlasConfiguration.SEARCH_MAX_LIMIT.getInt(); return discoveryService.searchByDSL(schemaQuery, new QueryParams(limit, 0)); } throw new SchemaNotFoundException("Schema is not configured for type " + typeName + ". Configure " + configName); } @Override @GraphTransaction public String getSchemaForEntity(String guid) throws AtlasException { guid = ParamChecker.notEmpty(guid, "Entity id"); LOG.info("Fetching schema for entity guid={}", guid); String typeName = validateDatasetExists(guid); return getSchemaForId(typeName, guid); } /** * Validate if indeed this is a table type and exists. * * @param datasetName table name */ private TypeUtils.Pair<String, String> validateDatasetNameExists(String datasetName) throws AtlasException { Iterator<AtlasVertex> results = graph.query().has("Referenceable.qualifiedName", datasetName) .has(Constants.STATE_PROPERTY_KEY, Id.EntityState.ACTIVE.name()) .has(Constants.SUPER_TYPES_PROPERTY_KEY, AtlasClient.DATA_SET_SUPER_TYPE) .vertices().iterator(); while (results.hasNext()) { AtlasVertex vertex = results.next(); return TypeUtils.Pair.of(GraphHelper.getTypeName(vertex), GraphHelper.getGuid(vertex)); } throw new EntityNotFoundException("Dataset with name = " + datasetName + " does not exist"); } /** * Validate if indeed this is a table type and exists. * * @param guid entity id */ private String validateDatasetExists(String guid) throws AtlasException { for (AtlasVertex vertex : (Iterable<AtlasVertex>) graph.query().has(Constants.GUID_PROPERTY_KEY, guid) .has(Constants.SUPER_TYPES_PROPERTY_KEY, AtlasClient.DATA_SET_SUPER_TYPE) .vertices()) { return GraphHelper.getTypeName(vertex); } throw new EntityNotFoundException("Dataset with guid = " + guid + " does not exist"); } } <|start_filename|>graphdb/titan0/src/main/java/org/apache/atlas/repository/graphdb/titan0/Titan0GraphDatabase.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan0; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; import org.apache.atlas.ApplicationProperties; import org.apache.atlas.AtlasException; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.GraphDatabase; import org.apache.commons.configuration.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ImmutableMap; import com.thinkaurelius.titan.core.TitanFactory; import com.thinkaurelius.titan.core.TitanGraph; import com.thinkaurelius.titan.core.schema.TitanManagement; import com.thinkaurelius.titan.core.util.TitanCleanup; import com.thinkaurelius.titan.diskstorage.StandardIndexProvider; import com.thinkaurelius.titan.diskstorage.solr.Solr5Index; /** * Titan 0.5.4 implementation of GraphDatabase. */ public class Titan0GraphDatabase implements GraphDatabase<Titan0Vertex, Titan0Edge> { private static final Logger LOG = LoggerFactory.getLogger(Titan0GraphDatabase.class); /** * Constant for the configuration property that indicates the prefix. */ public static final String GRAPH_PREFIX = "atlas.graph"; public static final String INDEX_BACKEND_CONF = "index.search.backend"; public static final String INDEX_BACKEND_LUCENE = "lucene"; public static final String INDEX_BACKEND_ES = "elasticsearch"; private static volatile Titan0Graph atlasGraphInstance = null; private static volatile TitanGraph graphInstance = null; public static Configuration getConfiguration() throws AtlasException { Configuration configProperties = ApplicationProperties.get(); return ApplicationProperties.getSubsetConfiguration(configProperties, GRAPH_PREFIX); } static { addSolr5Index(); } /** * Titan loads index backend name to implementation using * StandardIndexProvider.ALL_MANAGER_CLASSES But * StandardIndexProvider.ALL_MANAGER_CLASSES is a private static final * ImmutableMap Only way to inject Solr5Index is to modify this field. So, * using hacky reflection to add Sol5Index */ private static void addSolr5Index() { try { Field field = StandardIndexProvider.class.getDeclaredField("ALL_MANAGER_CLASSES"); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); Map<String, String> customMap = new HashMap<>(StandardIndexProvider.getAllProviderClasses()); customMap.put("solr", Solr5Index.class.getName()); // for // consistency // with Titan // 1.0.0 customMap.put("solr5", Solr5Index.class.getName()); // for backward // compatibility ImmutableMap<String, String> immap = ImmutableMap.copyOf(customMap); field.set(null, immap); LOG.debug("Injected solr5 index - {}", Solr5Index.class.getName()); } catch (Exception e) { throw new RuntimeException(e); } } public static TitanGraph getGraphInstance() { if (graphInstance == null) { synchronized (Titan0GraphDatabase.class) { if (graphInstance == null) { Configuration config; try { config = getConfiguration(); } catch (AtlasException e) { throw new RuntimeException(e); } graphInstance = TitanFactory.open(config); atlasGraphInstance = new Titan0Graph(); validateIndexBackend(config); } } } return graphInstance; } public static void unload() { synchronized (Titan0GraphDatabase.class) { if (graphInstance == null) { return; } graphInstance.commit(); //shutdown invalidates the graph instance graphInstance.shutdown(); graphInstance = null; } } static void validateIndexBackend(Configuration config) { String configuredIndexBackend = config.getString(INDEX_BACKEND_CONF); TitanManagement managementSystem = null; try { managementSystem = getGraphInstance().getManagementSystem(); String currentIndexBackend = managementSystem.get(INDEX_BACKEND_CONF); if (!equals(configuredIndexBackend, currentIndexBackend)) { throw new RuntimeException("Configured Index Backend " + configuredIndexBackend + " differs from earlier configured Index Backend " + currentIndexBackend + ". Aborting!"); } } finally { if (managementSystem != null) { managementSystem.commit(); } } } private static boolean equals(Object o1, Object o2) { if (o1 == null) { return o2 == null; } return o1.equals(o2); } @Override public AtlasGraph<Titan0Vertex, Titan0Edge> getGraph() { // force graph loading up front to avoid bootstrapping // issues getGraphInstance(); return atlasGraphInstance; } @Override public boolean isGraphLoaded() { return graphInstance != null; } @Override public void initializeTestGraph() { //nothing to do } @Override public void cleanup() { try { getGraphInstance().shutdown(); } catch(Throwable t) { LOG.warn("Could not shutdown test TitanGraph", t); t.printStackTrace(); } try { TitanCleanup.clear(getGraphInstance()); } catch(Throwable t) { LOG.warn("Could not clear test TitanGraph", t); t.printStackTrace(); } } } <|start_filename|>webapp/src/main/java/org/apache/atlas/web/rest/EntityREST.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.web.rest; import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.TypeCategory; import org.apache.atlas.model.instance.AtlasClassification; import org.apache.atlas.model.instance.AtlasEntity.AtlasEntitiesWithExtInfo; import org.apache.atlas.model.instance.AtlasEntity.AtlasEntityWithExtInfo; import org.apache.atlas.model.instance.ClassificationAssociateRequest; import org.apache.atlas.model.instance.EntityMutationResponse; import org.apache.atlas.model.typedef.AtlasStructDef.AtlasAttributeDef; import org.apache.atlas.repository.store.graph.AtlasEntityStore; import org.apache.atlas.repository.store.graph.v1.AtlasEntityStream; import org.apache.atlas.repository.store.graph.v1.EntityStream; import org.apache.atlas.type.AtlasClassificationType; import org.apache.atlas.type.AtlasEntityType; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.utils.AtlasPerfTracer; import org.apache.atlas.web.util.Servlets; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.springframework.stereotype.Service; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * REST for a single entity */ @Path("v2/entity") @Singleton @Service public class EntityREST { private static final Logger PERF_LOG = AtlasPerfTracer.getPerfLogger("rest.EntityREST"); public static final String PREFIX_ATTR = "attr:"; private final AtlasTypeRegistry typeRegistry; private final AtlasEntityStore entitiesStore; @Inject public EntityREST(AtlasTypeRegistry typeRegistry, AtlasEntityStore entitiesStore) { this.typeRegistry = typeRegistry; this.entitiesStore = entitiesStore; } /** * Fetch complete definition of an entity given its GUID. * @param guid GUID for the entity * @return AtlasEntity * @throws AtlasBaseException */ @GET @Path("/guid/{guid}") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) public AtlasEntityWithExtInfo getById(@PathParam("guid") String guid) throws AtlasBaseException { AtlasPerfTracer perf = null; try { if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntityREST.getById(" + guid + ")"); } return entitiesStore.getById(guid); } finally { AtlasPerfTracer.log(perf); } } /** * Fetch complete definition of an entity given its type and unique attribute. * @param typeName * @return AtlasEntityWithExtInfo * @throws AtlasBaseException */ @GET @Path("/uniqueAttribute/type/{typeName}") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) public AtlasEntityWithExtInfo getByUniqueAttributes(@PathParam("typeName") String typeName, @Context HttpServletRequest servletRequest) throws AtlasBaseException { AtlasPerfTracer perf = null; try { Map<String, Object> attributes = getAttributes(servletRequest); if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntityREST.getByUniqueAttributes(" + typeName + "," + attributes + ")"); } AtlasEntityType entityType = ensureEntityType(typeName); validateUniqueAttribute(entityType, attributes); return entitiesStore.getByUniqueAttributes(entityType, attributes); } finally { AtlasPerfTracer.log(perf); } } /** * Create new entity or update existing entity in Atlas. * Existing entity is matched using its unique guid if supplied or by its unique attributes eg: qualifiedName * @param entity * @return EntityMutationResponse * @throws AtlasBaseException */ @POST @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) public EntityMutationResponse createOrUpdate(AtlasEntityWithExtInfo entity) throws AtlasBaseException { AtlasPerfTracer perf = null; try { if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntityREST.createOrUpdate()"); } return entitiesStore.createOrUpdate(new AtlasEntityStream(entity), false); } finally { AtlasPerfTracer.log(perf); } } /******* * Entity Partial Update - Allows a subset of attributes to be updated on * an entity which is identified by its type and unique attribute eg: Referenceable.qualifiedName. * Null updates are not possible *******/ @PUT @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) @Path("/uniqueAttribute/type/{typeName}") public EntityMutationResponse partialUpdateEntityByUniqueAttrs(@PathParam("typeName") String typeName, @Context HttpServletRequest servletRequest, AtlasEntityWithExtInfo entityInfo) throws Exception { AtlasPerfTracer perf = null; try { Map<String, Object> uniqueAttributes = getAttributes(servletRequest); if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntityREST.partialUpdateEntityByUniqueAttrs(" + typeName + "," + uniqueAttributes + ")"); } AtlasEntityType entityType = ensureEntityType(typeName); validateUniqueAttribute(entityType, uniqueAttributes); return entitiesStore.updateByUniqueAttributes(entityType, uniqueAttributes, entityInfo); } finally { AtlasPerfTracer.log(perf); } } /******* * Entity Partial Update - Add/Update entity attribute identified by its GUID. * Supports only uprimitive attribute type and entity references. * does not support updation of complex types like arrays, maps * Null updates are not possible *******/ @PUT @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) @Path("/guid/{guid}") public EntityMutationResponse partialUpdateEntityAttrByGuid(@PathParam("guid") String guid, @QueryParam("name") String attrName, Object attrValue) throws Exception { AtlasPerfTracer perf = null; try { if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntityREST.partialUpdateEntityAttrByGuid(" + guid + "," + attrName + ")"); } return entitiesStore.updateEntityAttributeByGuid(guid, attrName, attrValue); } finally { AtlasPerfTracer.log(perf); } } /** * Delete an entity identified by its GUID. * @param guid GUID for the entity * @return EntityMutationResponse */ @DELETE @Path("/guid/{guid}") @Consumes({Servlets.JSON_MEDIA_TYPE, MediaType.APPLICATION_JSON}) @Produces(Servlets.JSON_MEDIA_TYPE) public EntityMutationResponse deleteByGuid(@PathParam("guid") final String guid) throws AtlasBaseException { AtlasPerfTracer perf = null; try { if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntityREST.deleteByGuid(" + guid + ")"); } return entitiesStore.deleteById(guid); } finally { AtlasPerfTracer.log(perf); } } /** * Delete an entity identified by its type and unique attributes. * @param typeName - entity type to be deleted * @param servletRequest - request containing unique attributes/values * @return EntityMutationResponse */ @DELETE @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) @Path("/uniqueAttribute/type/{typeName}") public EntityMutationResponse deleteByUniqueAttribute(@PathParam("typeName") String typeName, @Context HttpServletRequest servletRequest) throws AtlasBaseException { AtlasPerfTracer perf = null; try { Map<String, Object> attributes = getAttributes(servletRequest); if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntityREST.deleteByUniqueAttribute(" + typeName + "," + attributes + ")"); } AtlasEntityType entityType = ensureEntityType(typeName); return entitiesStore.deleteByUniqueAttributes(entityType, attributes); } finally { AtlasPerfTracer.log(perf); } } /** * Gets the list of classifications for a given entity represented by a guid. * @param guid globally unique identifier for the entity * @return classification for the given entity guid */ @GET @Path("/guid/{guid}/classification/{classificationName}") @Produces(Servlets.JSON_MEDIA_TYPE) public AtlasClassification getClassification(@PathParam("guid") String guid, @PathParam("classificationName") final String classificationName) throws AtlasBaseException { AtlasPerfTracer perf = null; try { if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntityREST.getClassification(" + guid + "," + classificationName + ")"); } if (StringUtils.isEmpty(guid)) { throw new AtlasBaseException(AtlasErrorCode.INSTANCE_GUID_NOT_FOUND, guid); } ensureClassificationType(classificationName); return entitiesStore.getClassification(guid, classificationName); } finally { AtlasPerfTracer.log(perf); } } /** * Gets the list of classifications for a given entity represented by a guid. * @param guid globally unique identifier for the entity * @return a list of classifications for the given entity guid */ @GET @Path("/guid/{guid}/classifications") @Produces(Servlets.JSON_MEDIA_TYPE) public AtlasClassification.AtlasClassifications getClassifications(@PathParam("guid") String guid) throws AtlasBaseException { AtlasPerfTracer perf = null; try { if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntityREST.getClassifications(" + guid + ")"); } if (StringUtils.isEmpty(guid)) { throw new AtlasBaseException(AtlasErrorCode.INSTANCE_GUID_NOT_FOUND, guid); } return new AtlasClassification.AtlasClassifications(entitiesStore.getClassifications(guid)); } finally { AtlasPerfTracer.log(perf); } } /** * Adds classifications to an existing entity represented by a guid. * @param guid globally unique identifier for the entity */ @POST @Path("/guid/{guid}/classifications") @Consumes({Servlets.JSON_MEDIA_TYPE, MediaType.APPLICATION_JSON}) @Produces(Servlets.JSON_MEDIA_TYPE) public void addClassifications(@PathParam("guid") final String guid, List<AtlasClassification> classifications) throws AtlasBaseException { AtlasPerfTracer perf = null; try { if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntityREST.addClassifications(" + guid + ")"); } if (StringUtils.isEmpty(guid)) { throw new AtlasBaseException(AtlasErrorCode.INSTANCE_GUID_NOT_FOUND, guid); } entitiesStore.addClassifications(guid, classifications); } finally { AtlasPerfTracer.log(perf); } } /** * Updates classifications to an existing entity represented by a guid. * @param guid globally unique identifier for the entity * @return classification for the given entity guid */ @PUT @Path("/guid/{guid}/classifications") @Produces(Servlets.JSON_MEDIA_TYPE) public void updateClassification(@PathParam("guid") final String guid, List<AtlasClassification> classifications) throws AtlasBaseException { AtlasPerfTracer perf = null; try { if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntityREST.updateClassification(" + guid + ")"); } if (StringUtils.isEmpty(guid)) { throw new AtlasBaseException(AtlasErrorCode.INSTANCE_GUID_NOT_FOUND, guid); } entitiesStore.updateClassifications(guid, classifications); } finally { AtlasPerfTracer.log(perf); } } /** * Deletes a given classification from an existing entity represented by a guid. * @param guid globally unique identifier for the entity * @param classificationName name of the classifcation */ @DELETE @Path("/guid/{guid}/classification/{classificationName}") @Produces(Servlets.JSON_MEDIA_TYPE) public void deleteClassification(@PathParam("guid") String guid, @PathParam("classificationName") final String classificationName) throws AtlasBaseException { AtlasPerfTracer perf = null; try { if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntityREST.deleteClassification(" + guid + "," + classificationName + ")"); } if (StringUtils.isEmpty(guid)) { throw new AtlasBaseException(AtlasErrorCode.INSTANCE_GUID_NOT_FOUND, guid); } ensureClassificationType(classificationName); entitiesStore.deleteClassifications(guid, new ArrayList<String>() {{ add(classificationName);}} ); } finally { AtlasPerfTracer.log(perf); } } /******************************************************************/ /** Bulk API operations **/ /******************************************************************/ /** * Bulk API to retrieve list of entities identified by its GUIDs. */ @GET @Path("/bulk") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) public AtlasEntitiesWithExtInfo getByGuids(@QueryParam("guid") List<String> guids) throws AtlasBaseException { AtlasPerfTracer perf = null; try { if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntityREST.getByGuids(" + guids + ")"); } if (CollectionUtils.isEmpty(guids)) { throw new AtlasBaseException(AtlasErrorCode.INSTANCE_GUID_NOT_FOUND, guids); } return entitiesStore.getByIds(guids); } finally { AtlasPerfTracer.log(perf); } } /** * Bulk API to create new entities or update existing entities in Atlas. * Existing entity is matched using its unique guid if supplied or by its unique attributes eg: qualifiedName */ @POST @Path("/bulk") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) public EntityMutationResponse createOrUpdate(AtlasEntitiesWithExtInfo entities) throws AtlasBaseException { AtlasPerfTracer perf = null; try { if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntityREST.createOrUpdate(entityCount=" + (CollectionUtils.isEmpty(entities.getEntities()) ? 0 : entities.getEntities().size()) + ")"); } EntityStream entityStream = new AtlasEntityStream(entities); return entitiesStore.createOrUpdate(entityStream, false); } finally { AtlasPerfTracer.log(perf); } } /** * Bulk API to delete list of entities identified by its GUIDs */ @DELETE @Path("/bulk") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) public EntityMutationResponse deleteByGuids(@QueryParam("guid") final List<String> guids) throws AtlasBaseException { AtlasPerfTracer perf = null; try { if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntityREST.deleteByGuids(" + guids + ")"); } return entitiesStore.deleteByIds(guids); } finally { AtlasPerfTracer.log(perf); } } /** * Bulk API to associate a tag to multiple entities */ @POST @Path("/bulk/classification") @Consumes({Servlets.JSON_MEDIA_TYPE, MediaType.APPLICATION_JSON}) @Produces(Servlets.JSON_MEDIA_TYPE) public void addClassification(ClassificationAssociateRequest request) throws AtlasBaseException { AtlasPerfTracer perf = null; try { if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntityREST.addClassification(" + request + ")"); } AtlasClassification classification = request == null ? null : request.getClassification(); List<String> entityGuids = request == null ? null : request.getEntityGuids(); if (classification == null || StringUtils.isEmpty(classification.getTypeName())) { throw new AtlasBaseException(AtlasErrorCode.INVALID_PARAMETERS, "no classification"); } if (CollectionUtils.isEmpty(entityGuids)) { throw new AtlasBaseException(AtlasErrorCode.INVALID_PARAMETERS, "empty guid list"); } entitiesStore.addClassification(entityGuids, classification); } finally { AtlasPerfTracer.log(perf); } } private AtlasEntityType ensureEntityType(String typeName) throws AtlasBaseException { AtlasEntityType ret = typeRegistry.getEntityTypeByName(typeName); if (ret == null) { throw new AtlasBaseException(AtlasErrorCode.TYPE_NAME_INVALID, TypeCategory.ENTITY.name(), typeName); } return ret; } private AtlasClassificationType ensureClassificationType(String typeName) throws AtlasBaseException { AtlasClassificationType ret = typeRegistry.getClassificationTypeByName(typeName); if (ret == null) { throw new AtlasBaseException(AtlasErrorCode.TYPE_NAME_INVALID, TypeCategory.CLASSIFICATION.name(), typeName); } return ret; } private Map<String, Object> getAttributes(HttpServletRequest request) { Map<String, Object> attributes = new HashMap<>(); if (MapUtils.isNotEmpty(request.getParameterMap())) { for (Map.Entry<String, String[]> e : request.getParameterMap().entrySet()) { String key = e.getKey(); if (key != null && key.startsWith(PREFIX_ATTR)) { String[] values = e.getValue(); String value = values != null && values.length > 0 ? values[0] : null; attributes.put(key.substring(PREFIX_ATTR.length()), value); } } } return attributes; } /** * Validate that each attribute given is an unique attribute * @param entityType the entity type * @param attributes attributes */ private void validateUniqueAttribute(AtlasEntityType entityType, Map<String, Object> attributes) throws AtlasBaseException { if (MapUtils.isEmpty(attributes)) { throw new AtlasBaseException(AtlasErrorCode.ATTRIBUTE_UNIQUE_INVALID, entityType.getTypeName(), ""); } for (String attributeName : attributes.keySet()) { AtlasAttributeDef attribute = entityType.getAttributeDef(attributeName); if (attribute == null || !attribute.getIsUnique()) { throw new AtlasBaseException(AtlasErrorCode.ATTRIBUTE_UNIQUE_INVALID, entityType.getTypeName(), attributeName); } } } } <|start_filename|>graphdb/api/src/main/java/org/apache/atlas/repository/graphdb/AtlasElement.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb; import java.util.Collection; import java.util.List; import java.util.Set; import org.apache.atlas.AtlasException; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; /** * Represents a graph element. * */ public interface AtlasElement { /** * Gets the id of this element. If the object has not been physically created in the underlying graph, * calling this method will force the element to be created so that a valid Id can be returned. * * @return */ Object getId(); /** * Gets the names of the properties associated with this element. * @return */ Collection<? extends String> getPropertyKeys(); /** * Gets the value of the element property with the given name. The value * returned is guaranteed to be an instance of the specified class (or * an exception will be thrown). * * @param propertyName * @return * @throws IllegalStateException if the property is multi-valued in the graph schema. */ <T> T getProperty(String propertyName, Class<T> clazz); /** * Gets all of the values of the given property. * @param propertyName * @return */ <T> Collection<T> getPropertyValues(String propertyName, Class<T> type); /** * Gets the value of a multiplicity one property whose value is a String list. * The lists of super types and traits are stored this way. A separate method * is needed for this because special logic is required to handle this situation * in some implementations. */ List<String> getListProperty(String propertyName); /** * Gets the value of a multiplicity one property whose value is a list. It * attempts to convert the elements in the list to the specified type. Currently * conversion is only supported for subclasses of AtlasElement and String. */ <V> List<V> getListProperty(String propertyName, Class<V> elementType); /** * Sets a multiplicity one property whose value is a String list. * The lists of super types and traits are stored this way. A separate method * is needed for this because special logic is required to handle this situation * in some implementations. */ void setListProperty(String propertyName, List<String> values) throws AtlasException; /** * Sets a multiplicity one property whose effective value is a String list whose * values consist of the ids of the supplied elements. This is implemented efficiently * so that in many cases the property can be set without requiring new elements * to be immediately created in the graph database. It allows the actual underlying element * creation to be deferred until commit time. */ void setPropertyFromElementsIds(String propertyName, List<AtlasElement> values); /** * Sets a multiplicity one property whose effective value is a String whose value is the id of the supplied * element. This is implemented efficiently so that in many cases the property can be set without requiring * new elements to be immediately created in the graph database. It allows the actual underlying element * creation to be deferred until commit time. */ void setPropertyFromElementId(String propertyName, AtlasElement value); /** * Removes a property from the vertex. */ void removeProperty(String propertyName); /** * Sets a single-valued property to the given value. For * properties defined as multiplicty many in the graph schema, the value is added instead * (following set semantics) * * @param propertyName * @param value */ <T> void setProperty(String propertyName, T value); /** * Creates a Jettison JSONObject from this Element. * * @param propertyKeys The property keys at the root of the element to serialize. * If null, then all keys are serialized. */ JSONObject toJson(Set<String> propertyKeys) throws JSONException; /** * Determines if this element exists in the graph database. If the element has not * actually been loaded from the underlying graph, this will cause it to be loaded * so that the result is correct. * * @return */ boolean exists(); /** * @param propertyName * @param value */ <T> void setJsonProperty(String propertyName, T value); /** * @param propertyName * @return */ <T> T getJsonProperty(String propertyName); /** * Gets a human-readable id without forcing the element to * be created if it does not exist in the graph yet. * * @return */ String getIdForDisplay(); /** * Whether or not an id has been assigned yet for this Element. This can happen if the element has been created * in memory but has not been actually pushed into the underlying graph yet. * * @return */ boolean isIdAssigned(); <T> T getWrappedElement(); } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/converters/AtlasEnumFormatConverter.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.converters; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.TypeCategory; import org.apache.atlas.model.typedef.AtlasEnumDef.AtlasEnumElementDef; import org.apache.atlas.type.AtlasEnumType; import org.apache.atlas.type.AtlasType; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.typesystem.types.EnumValue; import java.util.Map; public class AtlasEnumFormatConverter extends AtlasAbstractFormatConverter { public AtlasEnumFormatConverter(AtlasFormatConverters registry, AtlasTypeRegistry typeRegistry) { super(registry, typeRegistry, TypeCategory.ENUM); } @Override public Object fromV1ToV2(Object v1Obj, AtlasType type, ConverterContext ctx) throws AtlasBaseException { String ret = null; if (v1Obj == null || !(type instanceof AtlasEnumType)) { return ret; } Object v1Value = null; if (v1Obj instanceof EnumValue) { EnumValue enumValue = (EnumValue)v1Obj; v1Value = enumValue.value; if (v1Value == null) { v1Value = enumValue.ordinal; } } else if (v1Obj instanceof Map) { Map mapValue = (Map)v1Obj; v1Value = mapValue.get("value"); if (v1Value == null) { v1Value = mapValue.get("ordinal"); } } if (v1Value == null) { // could be 'value' or 'ordinal' v1Value = v1Obj; } AtlasEnumElementDef elementDef; if (v1Value instanceof Number) { elementDef = ((AtlasEnumType)type).getEnumElementDef((Number) v1Value); } else { elementDef = ((AtlasEnumType)type).getEnumElementDef(v1Value.toString()); } if (elementDef != null) { ret = elementDef.getValue(); } return ret; } @Override public Object fromV2ToV1(Object v2Obj, AtlasType type, ConverterContext ctx) throws AtlasBaseException { EnumValue ret = null; if (v2Obj == null || !(type instanceof AtlasEnumType)) { return ret; } AtlasEnumType enumType = (AtlasEnumType) type; AtlasEnumElementDef elementDef = enumType.getEnumElementDef(v2Obj.toString()); if (elementDef != null) { ret = new EnumValue(elementDef.getValue(), elementDef.getOrdinal()); } return ret; } } <|start_filename|>intg/src/test/java/org/apache/atlas/type/TestAtlasTypeRegistry.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.type; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.typedef.*; import org.apache.atlas.model.typedef.AtlasStructDef.AtlasAttributeDef; import org.apache.atlas.type.AtlasTypeRegistry.AtlasTransientTypeRegistry; import org.testng.annotations.Test; import java.util.Arrays; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static org.testng.Assert.*; public class TestAtlasTypeRegistry { /* * L0 * / \ * / \ * L1_1---- L1_2 * / \ \ / \ * / \ \ / \ * L2_1 L2_2 L2_3 L2_4 */ @Test public void testClassificationDefValidHierarchy() { AtlasClassificationDef classifiL0 = new AtlasClassificationDef("L0"); AtlasClassificationDef classifiL1_1 = new AtlasClassificationDef("L1-1"); AtlasClassificationDef classifiL1_2 = new AtlasClassificationDef("L1-2"); AtlasClassificationDef classifiL2_1 = new AtlasClassificationDef("L2-1"); AtlasClassificationDef classifiL2_2 = new AtlasClassificationDef("L2-2"); AtlasClassificationDef classifiL2_3 = new AtlasClassificationDef("L2-3"); AtlasClassificationDef classifiL2_4 = new AtlasClassificationDef("L2-4"); classifiL1_1.addSuperType(classifiL0.getName()); classifiL1_2.addSuperType(classifiL0.getName()); classifiL2_1.addSuperType(classifiL1_1.getName()); classifiL2_2.addSuperType(classifiL1_1.getName()); classifiL2_3.addSuperType(classifiL1_1.getName()); classifiL2_3.addSuperType(classifiL1_2.getName()); classifiL2_4.addSuperType(classifiL1_2.getName()); classifiL0.addAttribute(new AtlasAttributeDef("L0_a1", AtlasBaseTypeDef.ATLAS_TYPE_INT)); classifiL1_1.addAttribute(new AtlasAttributeDef("L1-1_a1", AtlasBaseTypeDef.ATLAS_TYPE_INT)); classifiL1_2.addAttribute(new AtlasAttributeDef("L1-2_a1", AtlasBaseTypeDef.ATLAS_TYPE_INT)); classifiL2_1.addAttribute(new AtlasAttributeDef("L2-1_a1", AtlasBaseTypeDef.ATLAS_TYPE_INT)); classifiL2_2.addAttribute(new AtlasAttributeDef("L2-2_a1", AtlasBaseTypeDef.ATLAS_TYPE_INT)); classifiL2_3.addAttribute(new AtlasAttributeDef("L2-3_a1", AtlasBaseTypeDef.ATLAS_TYPE_INT)); classifiL2_4.addAttribute(new AtlasAttributeDef("L2-4_a1", AtlasBaseTypeDef.ATLAS_TYPE_INT)); AtlasTypesDef typesDef = new AtlasTypesDef(); typesDef.getClassificationDefs().add(classifiL0); typesDef.getClassificationDefs().add(classifiL1_1); typesDef.getClassificationDefs().add(classifiL1_2); typesDef.getClassificationDefs().add(classifiL2_1); typesDef.getClassificationDefs().add(classifiL2_2); typesDef.getClassificationDefs().add(classifiL2_3); typesDef.getClassificationDefs().add(classifiL2_4); AtlasTypeRegistry typeRegistry = new AtlasTypeRegistry(); AtlasTransientTypeRegistry ttr = null; boolean commit = false; String failureMsg = null; try { ttr = typeRegistry.lockTypeRegistryForUpdate(); ttr.addTypes(typesDef); commit = true; } catch (AtlasBaseException excp) { failureMsg = excp.getMessage(); } finally { typeRegistry.releaseTypeRegistryForUpdate(ttr, commit); } assertNull(failureMsg); validateSuperTypes(typeRegistry, "L0", new HashSet<String>()); validateSuperTypes(typeRegistry, "L1-1", new HashSet<>(Arrays.asList("L0"))); validateSuperTypes(typeRegistry, "L1-2", new HashSet<>(Arrays.asList("L0"))); validateSuperTypes(typeRegistry, "L2-1", new HashSet<>(Arrays.asList("L1-1", "L0"))); validateSuperTypes(typeRegistry, "L2-2", new HashSet<>(Arrays.asList("L1-1", "L0"))); validateSuperTypes(typeRegistry, "L2-3", new HashSet<>(Arrays.asList("L1-1", "L0", "L1-2"))); validateSuperTypes(typeRegistry, "L2-4", new HashSet<>(Arrays.asList("L1-2", "L0"))); validateSubTypes(typeRegistry, "L0", new HashSet<>(Arrays.asList("L1-1", "L1-2", "L2-1", "L2-2", "L2-3", "L2-4"))); validateSubTypes(typeRegistry, "L1-1", new HashSet<>(Arrays.asList("L2-1", "L2-2", "L2-3"))); validateSubTypes(typeRegistry, "L1-2", new HashSet<>(Arrays.asList("L2-3", "L2-4"))); validateSubTypes(typeRegistry, "L2-1", new HashSet<String>()); validateSubTypes(typeRegistry, "L2-2", new HashSet<String>()); validateSubTypes(typeRegistry, "L2-3", new HashSet<String>()); validateSubTypes(typeRegistry, "L2-4", new HashSet<String>()); validateAttributeNames(typeRegistry, "L0", new HashSet<>(Arrays.asList("L0_a1"))); validateAttributeNames(typeRegistry, "L1-1", new HashSet<>(Arrays.asList("L0_a1", "L1-1_a1"))); validateAttributeNames(typeRegistry, "L1-2", new HashSet<>(Arrays.asList("L0_a1", "L1-2_a1"))); validateAttributeNames(typeRegistry, "L2-1", new HashSet<>(Arrays.asList("L0_a1", "L1-1_a1", "L2-1_a1"))); validateAttributeNames(typeRegistry, "L2-2", new HashSet<>(Arrays.asList("L0_a1", "L1-1_a1", "L2-2_a1"))); validateAttributeNames(typeRegistry, "L2-3", new HashSet<>(Arrays.asList("L0_a1", "L1-1_a1", "L1-2_a1", "L2-3_a1"))); validateAttributeNames(typeRegistry, "L2-4", new HashSet<>(Arrays.asList("L0_a1", "L1-2_a1", "L2-4_a1"))); } @Test public void testClassificationDefInvalidHierarchy_Self() { AtlasClassificationDef classifiDef1 = new AtlasClassificationDef("classifiDef-1"); classifiDef1.addSuperType(classifiDef1.getName()); AtlasTypeRegistry typeRegistry = new AtlasTypeRegistry(); AtlasTransientTypeRegistry ttr = null; boolean commit = false; String failureMsg = null; try { ttr = typeRegistry.lockTypeRegistryForUpdate(); ttr.addType(classifiDef1); commit = true; } catch (AtlasBaseException excp) { failureMsg = excp.getMessage(); } finally { typeRegistry.releaseTypeRegistryForUpdate(ttr, commit); } assertNotNull(failureMsg, "expected invalid supertype failure"); } /* * L2_3 * \ * L0 * / \ * / \ * L1_1---- L1_2 * / \ \ / \ * / \ \ / \ * L2_1 L2_2 L2_3 L2_4 */ @Test public void testClassificationDefInvalidHierarchy_CircularRef() { AtlasClassificationDef classifiL0 = new AtlasClassificationDef("L0"); AtlasClassificationDef classifiL1_1 = new AtlasClassificationDef("L1-1"); AtlasClassificationDef classifiL1_2 = new AtlasClassificationDef("L1-2"); AtlasClassificationDef classifiL2_1 = new AtlasClassificationDef("L2-1"); AtlasClassificationDef classifiL2_2 = new AtlasClassificationDef("L2-2"); AtlasClassificationDef classifiL2_3 = new AtlasClassificationDef("L2-3"); AtlasClassificationDef classifiL2_4 = new AtlasClassificationDef("L2-4"); classifiL1_1.addSuperType(classifiL0.getName()); classifiL1_2.addSuperType(classifiL0.getName()); classifiL2_1.addSuperType(classifiL1_1.getName()); classifiL2_2.addSuperType(classifiL1_1.getName()); classifiL2_3.addSuperType(classifiL1_1.getName()); classifiL2_3.addSuperType(classifiL1_2.getName()); classifiL2_4.addSuperType(classifiL1_2.getName()); classifiL0.addSuperType(classifiL2_3.getName()); // circular-ref AtlasTypesDef typesDef = new AtlasTypesDef(); typesDef.getClassificationDefs().add(classifiL0); typesDef.getClassificationDefs().add(classifiL1_1); typesDef.getClassificationDefs().add(classifiL1_2); typesDef.getClassificationDefs().add(classifiL2_1); typesDef.getClassificationDefs().add(classifiL2_2); typesDef.getClassificationDefs().add(classifiL2_3); typesDef.getClassificationDefs().add(classifiL2_4); AtlasTypeRegistry typeRegistry = new AtlasTypeRegistry(); AtlasTransientTypeRegistry ttr = null; boolean commit = false; String failureMsg = null; try { ttr = typeRegistry.lockTypeRegistryForUpdate(); ttr.addTypes(typesDef); commit = true; } catch (AtlasBaseException excp) { failureMsg = excp.getMessage(); } finally { typeRegistry.releaseTypeRegistryForUpdate(ttr, commit); } assertNotNull(failureMsg, "expected invalid supertype failure"); } /* * L0 * / \ * / \ * L1_1---- L1_2 * / \ \ / \ * / \ \ / \ * L2_1 L2_2 L2_3 L2_4 */ @Test public void testEntityDefValidHierarchy() { AtlasEntityDef entL0 = new AtlasEntityDef("L0"); AtlasEntityDef entL1_1 = new AtlasEntityDef("L1-1"); AtlasEntityDef entL1_2 = new AtlasEntityDef("L1-2"); AtlasEntityDef entL2_1 = new AtlasEntityDef("L2-1"); AtlasEntityDef entL2_2 = new AtlasEntityDef("L2-2"); AtlasEntityDef entL2_3 = new AtlasEntityDef("L2-3"); AtlasEntityDef entL2_4 = new AtlasEntityDef("L2-4"); entL1_1.addSuperType(entL0.getName()); entL1_2.addSuperType(entL0.getName()); entL2_1.addSuperType(entL1_1.getName()); entL2_2.addSuperType(entL1_1.getName()); entL2_3.addSuperType(entL1_1.getName()); entL2_3.addSuperType(entL1_2.getName()); entL2_4.addSuperType(entL1_2.getName()); entL0.addAttribute(new AtlasAttributeDef("L0_a1", AtlasBaseTypeDef.ATLAS_TYPE_INT)); entL1_1.addAttribute(new AtlasAttributeDef("L1-1_a1", AtlasBaseTypeDef.ATLAS_TYPE_INT)); entL1_2.addAttribute(new AtlasAttributeDef("L1-2_a1", AtlasBaseTypeDef.ATLAS_TYPE_INT)); entL2_1.addAttribute(new AtlasAttributeDef("L2-1_a1", AtlasBaseTypeDef.ATLAS_TYPE_INT)); entL2_2.addAttribute(new AtlasAttributeDef("L2-2_a1", AtlasBaseTypeDef.ATLAS_TYPE_INT)); entL2_3.addAttribute(new AtlasAttributeDef("L2-3_a1", AtlasBaseTypeDef.ATLAS_TYPE_INT)); entL2_4.addAttribute(new AtlasAttributeDef("L2-4_a1", AtlasBaseTypeDef.ATLAS_TYPE_INT)); AtlasTypesDef typesDef = new AtlasTypesDef(); typesDef.getEntityDefs().add(entL0); typesDef.getEntityDefs().add(entL1_1); typesDef.getEntityDefs().add(entL1_2); typesDef.getEntityDefs().add(entL2_1); typesDef.getEntityDefs().add(entL2_2); typesDef.getEntityDefs().add(entL2_3); typesDef.getEntityDefs().add(entL2_4); AtlasTypeRegistry typeRegistry = new AtlasTypeRegistry(); AtlasTransientTypeRegistry ttr = null; boolean commit = false; String failureMsg = null; try { ttr = typeRegistry.lockTypeRegistryForUpdate(); ttr.addTypes(typesDef); commit = true; } catch (AtlasBaseException excp) { failureMsg = excp.getMessage(); } finally { typeRegistry.releaseTypeRegistryForUpdate(ttr, commit); } assertNull(failureMsg); validateSuperTypes(typeRegistry, "L0", new HashSet<String>()); validateSuperTypes(typeRegistry, "L1-1", new HashSet<>(Arrays.asList("L0"))); validateSuperTypes(typeRegistry, "L1-2", new HashSet<>(Arrays.asList("L0"))); validateSuperTypes(typeRegistry, "L2-1", new HashSet<>(Arrays.asList("L1-1", "L0"))); validateSuperTypes(typeRegistry, "L2-2", new HashSet<>(Arrays.asList("L1-1", "L0"))); validateSuperTypes(typeRegistry, "L2-3", new HashSet<>(Arrays.asList("L1-1", "L0", "L1-2"))); validateSuperTypes(typeRegistry, "L2-4", new HashSet<>(Arrays.asList("L1-2", "L0"))); validateSubTypes(typeRegistry, "L0", new HashSet<>(Arrays.asList("L1-1", "L1-2", "L2-1", "L2-2", "L2-3", "L2-4"))); validateSubTypes(typeRegistry, "L1-1", new HashSet<>(Arrays.asList("L2-1", "L2-2", "L2-3"))); validateSubTypes(typeRegistry, "L1-2", new HashSet<>(Arrays.asList("L2-3", "L2-4"))); validateSubTypes(typeRegistry, "L2-1", new HashSet<String>()); validateSubTypes(typeRegistry, "L2-2", new HashSet<String>()); validateSubTypes(typeRegistry, "L2-3", new HashSet<String>()); validateSubTypes(typeRegistry, "L2-4", new HashSet<String>()); validateAttributeNames(typeRegistry, "L0", new HashSet<>(Arrays.asList("L0_a1"))); validateAttributeNames(typeRegistry, "L1-1", new HashSet<>(Arrays.asList("L0_a1", "L1-1_a1"))); validateAttributeNames(typeRegistry, "L1-2", new HashSet<>(Arrays.asList("L0_a1", "L1-2_a1"))); validateAttributeNames(typeRegistry, "L2-1", new HashSet<>(Arrays.asList("L0_a1", "L1-1_a1", "L2-1_a1"))); validateAttributeNames(typeRegistry, "L2-2", new HashSet<>(Arrays.asList("L0_a1", "L1-1_a1", "L2-2_a1"))); validateAttributeNames(typeRegistry, "L2-3", new HashSet<>(Arrays.asList("L0_a1", "L1-1_a1", "L1-2_a1", "L2-3_a1"))); validateAttributeNames(typeRegistry, "L2-4", new HashSet<>(Arrays.asList("L0_a1", "L1-2_a1", "L2-4_a1"))); } @Test public void testEntityDefInvalidHierarchy_Self() { AtlasEntityDef entDef1 = new AtlasEntityDef("entDef-1"); entDef1.addSuperType(entDef1.getName()); AtlasTypeRegistry typeRegistry = new AtlasTypeRegistry(); AtlasTransientTypeRegistry ttr = null; boolean commit = false; String failureMsg = null; try { ttr = typeRegistry.lockTypeRegistryForUpdate(); ttr.addType(entDef1); commit = true; } catch (AtlasBaseException excp) { failureMsg = excp.getMessage(); } finally { typeRegistry.releaseTypeRegistryForUpdate(ttr, commit); } assertNotNull(failureMsg, "expected invalid supertype failure"); } /* * L2_3 * \ * L0 * / \ * / \ * L1_1---- L1_2 * / \ \ / \ * / \ \ / \ * L2_1 L2_2 L2_3 L2_4 */ @Test public void testEntityDefInvalidHierarchy_CircularRef() { AtlasEntityDef entL0 = new AtlasEntityDef("L0"); AtlasEntityDef entL1_1 = new AtlasEntityDef("L1-1"); AtlasEntityDef entL1_2 = new AtlasEntityDef("L1-2"); AtlasEntityDef entL2_1 = new AtlasEntityDef("L2-1"); AtlasEntityDef entL2_2 = new AtlasEntityDef("L2-2"); AtlasEntityDef entL2_3 = new AtlasEntityDef("L2-3"); AtlasEntityDef entL2_4 = new AtlasEntityDef("L2-4"); entL1_1.addSuperType(entL0.getName()); entL1_2.addSuperType(entL0.getName()); entL2_1.addSuperType(entL1_1.getName()); entL2_2.addSuperType(entL1_1.getName()); entL2_3.addSuperType(entL1_1.getName()); entL2_3.addSuperType(entL1_2.getName()); entL2_4.addSuperType(entL1_2.getName()); entL0.addSuperType(entL2_3.getName()); // circular-ref AtlasTypesDef typesDef = new AtlasTypesDef(); typesDef.getEntityDefs().add(entL0); typesDef.getEntityDefs().add(entL1_1); typesDef.getEntityDefs().add(entL1_2); typesDef.getEntityDefs().add(entL2_1); typesDef.getEntityDefs().add(entL2_2); typesDef.getEntityDefs().add(entL2_3); typesDef.getEntityDefs().add(entL2_4); AtlasTypeRegistry typeRegistry = new AtlasTypeRegistry(); AtlasTransientTypeRegistry ttr = null; boolean commit = false; String failureMsg = null; try { ttr = typeRegistry.lockTypeRegistryForUpdate(); ttr.addTypes(typesDef); commit = true; } catch (AtlasBaseException excp) { failureMsg = excp.getMessage(); } finally { typeRegistry.releaseTypeRegistryForUpdate(ttr, commit); } assertNotNull(failureMsg, "expected invalid supertype failure"); } @Test public void testNestedUpdates() { AtlasTypeRegistry typeRegistry = new AtlasTypeRegistry(); AtlasTransientTypeRegistry ttr = null; boolean commit = false; String failureMsg = null; AtlasClassificationDef testTag1 = new AtlasClassificationDef("testTag1"); AtlasClassificationDef testTag2 = new AtlasClassificationDef("testTag2"); try { ttr = typeRegistry.lockTypeRegistryForUpdate(); ttr.addType(testTag1); // changes should not be seen in typeRegistry until lock is released assertFalse(typeRegistry.isRegisteredType(testTag1.getName()), "type added should be seen in typeRegistry only after commit"); boolean isNestedUpdateSuccess = addType(typeRegistry, testTag2); assertTrue(isNestedUpdateSuccess); // changes made in nested commit, inside addType(), should not be seen in typeRegistry until lock is released here assertFalse(typeRegistry.isRegisteredType(testTag2.getName()), "type added within nested commit should be seen in typeRegistry only after outer commit"); commit = true; } catch (AtlasBaseException excp) { failureMsg = excp.getMessage(); } finally { typeRegistry.releaseTypeRegistryForUpdate(ttr, commit); } assertNull(failureMsg); assertTrue(typeRegistry.isRegisteredType(testTag1.getName())); assertTrue(typeRegistry.isRegisteredType(testTag2.getName())); } @Test public void testParallelUpdates() { final int numOfThreads = 3; final int numOfTypesPerKind = 30; final String enumTypePrefix = "testEnum-"; final String structTypePrefix = "testStruct-"; final String classificationPrefix = "testTag-"; final String entityTypePrefix = "testEntity-"; ExecutorService executor = Executors.newFixedThreadPool(numOfThreads); final AtlasTypeRegistry typeRegistry = new AtlasTypeRegistry(); // update typeRegistry simultaneously in multiple threads for (int threadIdx = 0; threadIdx < numOfThreads; threadIdx++) { executor.submit(new Callable<Object>() { @Override public Object call() throws Exception { for (int i = 0; i < numOfTypesPerKind; i++) { addType(typeRegistry, new AtlasEnumDef(enumTypePrefix + i)); } for (int i = 0; i < numOfTypesPerKind; i++) { addType(typeRegistry, new AtlasStructDef(structTypePrefix + i)); } for (int i = 0; i < numOfTypesPerKind; i++) { addType(typeRegistry, new AtlasClassificationDef(classificationPrefix + i)); } for (int i = 0; i < numOfTypesPerKind; i++) { addType(typeRegistry, new AtlasEntityDef(entityTypePrefix + i)); } return null; } }); } executor.shutdown(); try { boolean isCompleted = executor.awaitTermination(60, TimeUnit.SECONDS); assertTrue(isCompleted, "threads did not complete updating types"); } catch (InterruptedException excp) { // ignore? } // verify that all types added are present in the typeRegistry for (int i = 0; i < numOfTypesPerKind; i++) { String enumType = enumTypePrefix + i; String structType = structTypePrefix + i; String classificationType = classificationPrefix + i; String entityType = entityTypePrefix + i; assertNotNull(typeRegistry.getEnumDefByName(enumType), enumType + ": enum not found"); assertNotNull(typeRegistry.getStructDefByName(structType), structType + ": struct not found"); assertNotNull(typeRegistry.getClassificationDefByName(classificationType), classificationType + ": classification not found"); assertNotNull(typeRegistry.getEntityDefByName(entityType), entityType + ": entity not found"); } } /* create 2 entity types: L0 and L1, with L0 as superType of L1 * add entity type L2, with L0, L1 and L2 as super-types - this should fail due to L2 self-referencing itself in super-types * verify that after the update failure, the registry still has correct super-type/sub-type information for L0 and L1 */ @Test public void testRegistryValidityOnInvalidUpdate() { AtlasEntityDef entL0 = new AtlasEntityDef("L0"); AtlasEntityDef entL1 = new AtlasEntityDef("L1"); entL1.addSuperType(entL0.getName()); entL0.addAttribute(new AtlasAttributeDef("L0_a1", AtlasBaseTypeDef.ATLAS_TYPE_INT)); entL1.addAttribute(new AtlasAttributeDef("L1_a1", AtlasBaseTypeDef.ATLAS_TYPE_INT)); AtlasTypesDef typesDef = new AtlasTypesDef(); typesDef.getEntityDefs().add(entL0); typesDef.getEntityDefs().add(entL1); AtlasTypeRegistry typeRegistry = new AtlasTypeRegistry(); AtlasTransientTypeRegistry ttr = null; boolean commit = false; String failureMsg = null; try { ttr = typeRegistry.lockTypeRegistryForUpdate(); ttr.addTypes(typesDef); commit = true; } catch (AtlasBaseException excp) { failureMsg = excp.getMessage(); } finally { typeRegistry.releaseTypeRegistryForUpdate(ttr, commit); } assertNull(failureMsg); validateSuperTypes(typeRegistry, "L0", new HashSet<String>()); validateSubTypes(typeRegistry, "L0", new HashSet<>(Arrays.asList("L1"))); validateSuperTypes(typeRegistry, "L1", new HashSet<>(Arrays.asList("L0"))); validateSubTypes(typeRegistry, "L1", new HashSet<String>()); // create a circular reference AtlasEntityDef entL2 = new AtlasEntityDef("L2"); entL2.addSuperType(entL0.getName()); entL2.addSuperType(entL1.getName()); entL2.addSuperType(entL2.getName()); typesDef.clear(); typesDef.getEntityDefs().add(entL2); try { commit = false; ttr = typeRegistry.lockTypeRegistryForUpdate(); ttr.updateTypes(typesDef); commit = true; } catch (AtlasBaseException excp) { failureMsg = excp.getMessage(); } finally { typeRegistry.releaseTypeRegistryForUpdate(ttr, commit); } assertNotNull(failureMsg); assertNull(typeRegistry.getEntityTypeByName("L2")); validateSuperTypes(typeRegistry, "L0", new HashSet<String>()); validateSubTypes(typeRegistry, "L0", new HashSet<>(Arrays.asList("L1"))); validateSuperTypes(typeRegistry, "L1", new HashSet<>(Arrays.asList("L0"))); validateSubTypes(typeRegistry, "L1", new HashSet<String>()); } private boolean addType(AtlasTypeRegistry typeRegistry, AtlasBaseTypeDef typeDef) { boolean ret = false; AtlasTransientTypeRegistry ttr = null; try { ttr = typeRegistry.lockTypeRegistryForUpdate(); ttr.addType(typeDef); ret = true; } catch (AtlasBaseException excp) { // ignore } finally { typeRegistry.releaseTypeRegistryForUpdate(ttr, ret); } return ret; } private void validateSuperTypes(AtlasTypeRegistry typeRegistry, String typeName, Set<String> expectedSuperTypes) { AtlasType type = null; try { type = typeRegistry.getType(typeName); } catch (AtlasBaseException excp) { } Set<String> superTypes = null; if (type != null) { if (type instanceof AtlasEntityType) { superTypes = ((AtlasEntityType) type).getAllSuperTypes(); } else if (type instanceof AtlasClassificationType) { superTypes = ((AtlasClassificationType) type).getAllSuperTypes(); } } assertEquals(superTypes, expectedSuperTypes); } private void validateSubTypes(AtlasTypeRegistry typeRegistry, String typeName, Set<String> expectedSubTypes) { AtlasType type = null; try { type = typeRegistry.getType(typeName); } catch (AtlasBaseException excp) { } Set<String> subTypes = null; if (type != null) { if (type instanceof AtlasEntityType) { subTypes = ((AtlasEntityType) type).getAllSubTypes(); } else if (type instanceof AtlasClassificationType) { subTypes = ((AtlasClassificationType) type).getAllSubTypes(); } } assertEquals(subTypes, expectedSubTypes); } private void validateAttributeNames(AtlasTypeRegistry typeRegistry, String typeName, Set<String> attributeNames) { AtlasType type = null; try { type = typeRegistry.getType(typeName); } catch (AtlasBaseException excp) { } Map<String, AtlasStructType.AtlasAttribute> attributes = null; if (type != null) { if (type instanceof AtlasEntityType) { attributes = ((AtlasEntityType) type).getAllAttributes(); } else if (type instanceof AtlasClassificationType) { attributes = ((AtlasClassificationType) type).getAllAttributes(); } } assertNotNull(attributes); assertEquals(attributes.keySet(), attributeNames); } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/store/graph/AtlasStructDefStore.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.store.graph; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.SearchFilter; import org.apache.atlas.model.typedef.AtlasStructDef; import org.apache.atlas.model.typedef.AtlasStructDef.AtlasStructDefs; import java.util.List; /** * Interface for graph persistence store for AtlasStructDef */ public interface AtlasStructDefStore { Object preCreate(AtlasStructDef structDef) throws AtlasBaseException; AtlasStructDef create(AtlasStructDef structDef, Object preCreateResult) throws AtlasBaseException; List<AtlasStructDef> getAll() throws AtlasBaseException; AtlasStructDef getByName(String name) throws AtlasBaseException; AtlasStructDef getByGuid(String guid) throws AtlasBaseException; AtlasStructDef update(AtlasStructDef structDef) throws AtlasBaseException; AtlasStructDef updateByName(String name, AtlasStructDef structDef) throws AtlasBaseException; AtlasStructDef updateByGuid(String guid, AtlasStructDef structDef) throws AtlasBaseException; Object preDeleteByName(String name) throws AtlasBaseException; void deleteByName(String name, Object preDeleteResult) throws AtlasBaseException; Object preDeleteByGuid(String name) throws AtlasBaseException; void deleteByGuid(String guid, Object preDeleteResult) throws AtlasBaseException; } <|start_filename|>repository/src/main/java/org/apache/atlas/discovery/graph/DefaultGraphPersistenceStrategy.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.discovery.graph; import java.util.List; import javax.inject.Inject; import org.apache.atlas.AtlasException; import org.apache.atlas.RequestContext; import org.apache.atlas.groovy.GroovyExpression; import org.apache.atlas.query.GraphPersistenceStrategies; import org.apache.atlas.query.GraphPersistenceStrategies$class; import org.apache.atlas.query.TypeUtils; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.MetadataRepository; import org.apache.atlas.repository.RepositoryException; import org.apache.atlas.repository.graph.GraphBackedMetadataRepository; import org.apache.atlas.repository.graph.GraphHelper; import org.apache.atlas.repository.graphdb.AtlasEdgeDirection; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.repository.graphdb.GremlinVersion; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.ITypedStruct; import org.apache.atlas.typesystem.persistence.Id; import org.apache.atlas.typesystem.types.AttributeInfo; import org.apache.atlas.typesystem.types.ClassType; import org.apache.atlas.typesystem.types.DataTypes; import org.apache.atlas.typesystem.types.IDataType; import org.apache.atlas.typesystem.types.Multiplicity; import org.apache.atlas.typesystem.types.StructType; import org.apache.atlas.typesystem.types.TraitType; import org.apache.atlas.typesystem.types.TypeSystem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; /** * Default implementation of GraphPersistenceStrategy. */ public class DefaultGraphPersistenceStrategy implements GraphPersistenceStrategies { private static final Logger LOG = LoggerFactory.getLogger(DefaultGraphPersistenceStrategy.class); private final GraphBackedMetadataRepository metadataRepository; @Inject public DefaultGraphPersistenceStrategy(MetadataRepository metadataRepository) { this.metadataRepository = (GraphBackedMetadataRepository) metadataRepository; } @Override public String typeAttributeName() { return metadataRepository.getTypeAttributeName(); } @Override public String superTypeAttributeName() { return metadataRepository.getSuperTypeAttributeName(); } @Override public String edgeLabel(IDataType<?> dataType, AttributeInfo aInfo) { try { return metadataRepository.getEdgeLabel(dataType, aInfo); } catch (AtlasException e) { throw new RuntimeException(e); } } @Override public String traitLabel(IDataType<?> dataType, String traitName) { return metadataRepository.getTraitLabel(dataType, traitName); } @Override public String fieldNameInVertex(IDataType<?> dataType, AttributeInfo aInfo) { try { return metadataRepository.getFieldNameInVertex(dataType, aInfo); } catch (AtlasException e) { throw new RuntimeException(e); } } @Override public List<String> traitNames(AtlasVertex AtlasVertex) { return GraphHelper.getTraitNames(AtlasVertex); } @Override public Id getIdFromVertex(String dataTypeName, AtlasVertex vertex) { return GraphHelper.getIdFromVertex(dataTypeName, vertex); } @Override public ITypedReferenceableInstance constructClassInstanceId(ClassType classType, Object value) { try { AtlasVertex classVertex = (AtlasVertex) value; ITypedReferenceableInstance classInstance = classType.createInstance(GraphHelper.getIdFromVertex(classVertex), new String[0]); return classType.convert(classInstance, Multiplicity.OPTIONAL); } catch (AtlasException e) { LOG.error("error while constructing an instance", e); } return null; } @Override public <U> U constructInstance(IDataType<U> dataType, Object value) { try { switch (dataType.getTypeCategory()) { case PRIMITIVE: case ENUM: return dataType.convert(value, Multiplicity.OPTIONAL); case ARRAY: DataTypes.ArrayType arrType = (DataTypes.ArrayType) dataType; IDataType<?> elemType = arrType.getElemType(); ImmutableCollection.Builder result = ImmutableList.builder(); List list = (List) value; for(Object listElement : list) { Object collectionEntry = constructCollectionEntry(elemType, listElement); if(collectionEntry != null) { result.add(collectionEntry); } } return (U)result.build(); case MAP: // todo break; case STRUCT: AtlasVertex structVertex = (AtlasVertex) value; StructType structType = (StructType) dataType; ITypedStruct structInstance = structType.createInstance(); TypeSystem.IdType idType = TypeSystem.getInstance().getIdType(); if (dataType.getName().equals(idType.getName())) { structInstance.set(idType.typeNameAttrName(), GraphHelper.getSingleValuedProperty(structVertex, typeAttributeName(), String.class)); structInstance.set(idType.idAttrName(), GraphHelper.getSingleValuedProperty(structVertex, idAttributeName(), String.class)); String stateValue = GraphHelper.getSingleValuedProperty(structVertex, stateAttributeName(), String.class); if (stateValue != null) { structInstance.set(idType.stateAttrName(), stateValue); } structInstance.set(idType.versionAttrName(), structVertex.getProperty(versionAttributeName(), Integer.class)); } else { metadataRepository.getGraphToInstanceMapper() .mapVertexToInstance(structVertex, structInstance, structType.fieldMapping().fields); } return dataType.convert(structInstance, Multiplicity.OPTIONAL); case TRAIT: AtlasVertex traitVertex = (AtlasVertex) value; TraitType traitType = (TraitType) dataType; ITypedStruct traitInstance = traitType.createInstance(); // todo - this is not right, we should load the Instance associated with this // trait. for now just loading the trait struct. // metadataRepository.getGraphToInstanceMapper().mapVertexToTraitInstance( // traitVertex, dataType.getName(), , traitType, traitInstance); metadataRepository.getGraphToInstanceMapper() .mapVertexToInstance(traitVertex, traitInstance, traitType.fieldMapping().fields); break; case CLASS: AtlasVertex classVertex = (AtlasVertex) value; String guid = classVertex.getProperty(Constants.GUID_PROPERTY_KEY, String.class); // Check if the instance we need was previously loaded. ITypedReferenceableInstance classInstance = RequestContext.get().getInstanceV1(guid); if (classInstance == null) { classInstance = metadataRepository.getGraphToInstanceMapper().mapGraphToTypedInstance(guid, classVertex); } return dataType.convert(classInstance, Multiplicity.OPTIONAL); default: throw new UnsupportedOperationException("Load for type " + dataType + "is not supported"); } } catch (AtlasException e) { LOG.error("error while constructing an instance", e); } return null; } public <U> U constructCollectionEntry(IDataType<U> elementType, Object value) throws AtlasException { switch (elementType.getTypeCategory()) { case PRIMITIVE: case ENUM: return constructInstance(elementType, value); //The array values in case of STRUCT, CLASS contain the edgeId if the outgoing edge which links to the STRUCT, CLASS vertex referenced case STRUCT: case CLASS: String edgeId = (String) value; return (U) metadataRepository.getGraphToInstanceMapper().getReferredEntity(edgeId, elementType); case ARRAY: case MAP: case TRAIT: return null; default: throw new UnsupportedOperationException("Load for type " + elementType + " in collections is not supported"); } } @Override public String edgeLabel(TypeUtils.FieldInfo fInfo) { return fInfo.reverseDataType() == null ? edgeLabel(fInfo.dataType(), fInfo.attrInfo()) : edgeLabel(fInfo.reverseDataType(), fInfo.attrInfo()); } @Override public AtlasEdgeDirection instanceToTraitEdgeDirection() { return AtlasEdgeDirection.OUT; } @Override public AtlasEdgeDirection traitToInstanceEdgeDirection() { return AtlasEdgeDirection.IN; } @Override public String idAttributeName() { return metadataRepository.getIdAttributeName(); } @Override public String stateAttributeName() { return metadataRepository.getStateAttributeName(); } @Override public String versionAttributeName() { return metadataRepository.getVersionAttributeName(); } @Override public boolean collectTypeInstancesIntoVar() { return GraphPersistenceStrategies$class.collectTypeInstancesIntoVar(this); } @Override public boolean filterBySubTypes() { return GraphPersistenceStrategies$class.filterBySubTypes(this); } @Override public boolean addGraphVertexPrefix(scala.collection.Traversable<GroovyExpression> preStatements) { return GraphPersistenceStrategies$class.addGraphVertexPrefix(this, preStatements); } @Override public GremlinVersion getSupportedGremlinVersion() { return GraphPersistenceStrategies$class.getSupportedGremlinVersion(this); } @Override public GroovyExpression generatePersisentToLogicalConversionExpression(GroovyExpression expr, IDataType<?> t) { return GraphPersistenceStrategies$class.generatePersisentToLogicalConversionExpression(this,expr, t); } @Override public GroovyExpression addInitialQueryCondition(GroovyExpression expr) { return GraphPersistenceStrategies$class.addInitialQueryCondition(this, expr); } @Override public boolean isPropertyValueConversionNeeded(IDataType<?> t) { return GraphPersistenceStrategies$class.isPropertyValueConversionNeeded(this, t); } @Override public AtlasGraph getGraph() throws RepositoryException { return metadataRepository.getGraph(); } } <|start_filename|>dashboardv2/public/js/modules/atlasLogin.js<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //Define indexOf for IE if (!Array.indexOf) { Array.prototype.indexOf = function(obj, start) { for (var i = (start || 0); i < this.length; i++) { if (this[i] == obj) { return i; } } return -1; }; } function doLogin() { var userName = $('#username').val().trim(); var passwd = $('#password').val().trim(); if (userName === '' || passwd === '') { $('#errorBox').show(); $('#signInLoading').hide(); $('#signIn').removeAttr('disabled'); $('#errorBox .errorMsg').text("The username or password you entered is blank.."); return false; } var baseUrl = getBaseUrl(); if (baseUrl.lastIndexOf('/') != (baseUrl.length - 1)) { if (baseUrl) { baseUrl = baseUrl + '/'; } else { baseUrl = '/'; } } var url = baseUrl + 'j_spring_security_check'; $.ajax({ data: { j_username: userName, j_password: <PASSWORD> }, url: url, type: 'POST', headers: { "cache-control": "no-cache" }, success: function() { if (location.hash.length > 2) window.location.replace('index.html' + location.hash); else window.location.replace('index.html'); }, error: function(jqXHR, textStatus, err) { $('#signIn').removeAttr('disabled'); $('#signInLoading').css("visibility", "hidden"); if (jqXHR.status && jqXHR.status == 412) { $('#errorBox').hide(); $('#errorBoxUnsynced').show(); } else { try { var resp = JSON.parse(jqXHR.responseText); if (resp.msgDesc.startsWith("Username not found") || resp.msgDesc.startsWith("Wrong password")) { $('#errorBox .errorMsg').text("Invalid User credentials. Please try again."); } else if (resp.msgDesc.startsWith("User role credentials is not set properly")) { $('#errorBox .errorMsg').text("User role or credentials is not set properly"); } else { $('#errorBox .errorMsg').text("Error while authentication"); } } catch (err) { $('#errorBox .errorMsg').text("Something went wrong"); } $('#errorBox').show(); $('#errorBoxUnsynced').hide(); } } }); } function getBaseUrl() { if (!window.location.origin) { window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : ''); } return window.location.origin + window.location.pathname.substring(window.location.pathname .indexOf('/', 2) + 1, 0); } $(function() { // register handlers $('#signIn').on('click', function() { $('#signIn').attr('disabled', true); $('#signInLoading').css("visibility", "visible"); doLogin(); return false; }); $('#loginForm').each(function() { $('input').keypress(function(e) { // Enter pressed? if (e.which == 10 || e.which == 13) { doLogin(); } }); }); $('#loginForm li[class^=control-group] > input').on('change', function(e) { if (e.target.value === '') { $(e.target).parent().addClass('error'); } else { $(e.target).parent().removeClass('error'); } }); }); <|start_filename|>graphdb/titan0/src/test/java/org/apache/atlas/repository/graphdb/titan0/GraphQueryTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan0; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.apache.atlas.AtlasException; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.AtlasGraphQuery; import org.apache.atlas.repository.graphdb.AtlasGraphQuery.ComparisionOperator; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.testng.annotations.Test; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; /** * Tests for Titan0GraphQuery. */ @Test public class GraphQueryTest extends AbstractGraphDatabaseTest { @Test public <V, E> void testQueryThatCannotRunInMemory() throws AtlasException { AtlasGraph<V, E> graph = getGraph(); AtlasVertex<V, E> v1 = createVertex(graph); v1.setProperty("name", "Fred"); v1.setProperty("size15", "15"); AtlasVertex<V, E> v2 = createVertex(graph); v2.setProperty("name", "Fred"); AtlasVertex<V, E> v3 = createVertex(graph); v3.setProperty("size15", "15"); graph.commit(); AtlasVertex<V, E> v4 = createVertex(graph); v4.setProperty("name", "Fred"); v4.setProperty("size15", "15"); AtlasGraphQuery q = graph.query(); q.has("name", ComparisionOperator.NOT_EQUAL, "George"); q.has("size15", "15"); graph.commit(); pause(); //pause to let the index get updated assertQueryMatches(q, v1, v3, v4); } @Test public void testCombinationOfAndsAndOrs() throws AtlasException { Titan0Graph graph = getTitan0Graph(); AtlasVertex<Titan0Vertex, Titan0Edge> v1 = createVertex(graph); v1.setProperty("name", "Fred"); v1.setProperty("size15", "15"); v1.setProperty("typeName", "Person"); AtlasVertex<Titan0Vertex, Titan0Edge> v2 = createVertex(graph); v2.setProperty("name", "George"); v2.setProperty("size15", "16"); v2.setProperty("typeName", "Person"); AtlasVertex<Titan0Vertex, Titan0Edge> v3 = createVertex(graph); v3.setProperty("name", "Jane"); v3.setProperty("size15", "17"); v3.setProperty("typeName", "Person"); AtlasVertex<Titan0Vertex, Titan0Edge> v4 = createVertex(graph); v4.setProperty("name", "Bob"); v4.setProperty("size15", "18"); v4.setProperty("typeName", "Person"); AtlasVertex<Titan0Vertex, Titan0Edge> v5 = createVertex(graph); v5.setProperty("name", "Julia"); v5.setProperty("size15", "19"); v5.setProperty("typeName", "Manager"); AtlasGraphQuery q = getGraphQuery(); q.has("typeName", "Person"); //initially match AtlasGraphQuery inner1a = q.createChildQuery(); AtlasGraphQuery inner1b = q.createChildQuery(); inner1a.has("name", "Fred"); inner1b.has("name", "Jane"); q.or(toList(inner1a, inner1b)); AtlasGraphQuery inner2a = q.createChildQuery(); AtlasGraphQuery inner2b = q.createChildQuery(); AtlasGraphQuery inner2c = q.createChildQuery(); inner2a.has("size15", "18"); inner2b.has("size15", "15"); inner2c.has("size15", "16"); q.or(toList(inner2a, inner2b, inner2c)); assertQueryMatches(q, v1); graph.commit(); pause(); //let the index update assertQueryMatches(q, v1); } @Test public void testWithinStep() throws AtlasException { Titan0Graph graph = getTitan0Graph(); AtlasVertex<Titan0Vertex, Titan0Edge> v1 = createVertex(graph); v1.setProperty("name", "Fred"); v1.setProperty("size15", "15"); v1.setProperty("typeName", "Person"); AtlasVertex<Titan0Vertex, Titan0Edge> v2 = createVertex(graph); v2.setProperty("name", "George"); v2.setProperty("size15", "16"); v2.setProperty("typeName", "Person"); AtlasVertex<Titan0Vertex, Titan0Edge> v3 = createVertex(graph); v3.setProperty("name", "Jane"); v3.setProperty("size15", "17"); v3.setProperty("typeName", "Person"); AtlasVertex<Titan0Vertex, Titan0Edge> v4 = createVertex(graph); v4.setProperty("name", "Bob"); v4.setProperty("size15", "18"); v4.setProperty("typeName", "Person"); AtlasVertex<Titan0Vertex, Titan0Edge> v5 = createVertex(graph); v5.setProperty("name", "Julia"); v5.setProperty("size15", "19"); v5.setProperty("typeName", "Manager"); AtlasGraphQuery q = getGraphQuery(); q.has("typeName", "Person"); //initially match q.in("name", toList("Fred", "Jane")); q.in("size15", toList("18", "15", "16")); assertQueryMatches(q, v1); graph.commit(); pause(); //let the index update assertQueryMatches(q, v1); } @Test public void testWithinStepWhereGraphIsStale() throws AtlasException { Titan0Graph graph = getTitan0Graph(); AtlasVertex<Titan0Vertex, Titan0Edge> v1 = createVertex(graph); v1.setProperty("name", "Fred"); v1.setProperty("size15", "15"); v1.setProperty("typeName", "Person"); AtlasVertex<Titan0Vertex, Titan0Edge> v2 = createVertex(graph); v2.setProperty("name", "George"); v2.setProperty("size15", "16"); v2.setProperty("typeName", "Person"); AtlasVertex<Titan0Vertex, Titan0Edge> v3 = createVertex(graph); v3.setProperty("name", "Jane"); v3.setProperty("size15", "17"); v3.setProperty("typeName", "Person"); AtlasVertex<Titan0Vertex, Titan0Edge> v4 = createVertex(graph); v4.setProperty("name", "Bob"); v4.setProperty("size15", "18"); v4.setProperty("typeName", "Person"); AtlasVertex<Titan0Vertex, Titan0Edge> v5 = createVertex(graph); v5.setProperty("name", "Julia"); v5.setProperty("size15", "19"); v5.setProperty("typeName", "Manager"); AtlasGraphQuery q = getGraphQuery(); q.has("typeName", "Person"); //initially match q.in("name", toList("Fred", "Jane")); graph.commit(); pause(); //let the index update assertQueryMatches(q, v1, v3); //make v3 no longer match the query. Within step should filter out the vertex since it no longer matches. v3.setProperty("name", "Janet"); assertQueryMatches(q, v1); } @Test public void testSimpleOrQuery() throws AtlasException { Titan0Graph graph = getTitan0Graph(); AtlasVertex<Titan0Vertex, Titan0Edge> v1 = createVertex(graph); v1.setProperty("name", "Fred"); v1.setProperty("size15", "15"); AtlasVertex<Titan0Vertex, Titan0Edge> v2 = createVertex(graph); v2.setProperty("name", "Fred"); AtlasVertex<Titan0Vertex, Titan0Edge> v3 = createVertex(graph); v3.setProperty("size15", "15"); graph.commit(); AtlasVertex<Titan0Vertex, Titan0Edge> v4 = createVertex(graph); v4.setProperty("name", "Fred"); v4.setProperty("size15", "15"); AtlasVertex<Titan0Vertex, Titan0Edge> v5 = createVertex(graph); v5.setProperty("name", "George"); v5.setProperty("size15", "16"); AtlasGraphQuery q = graph.query(); AtlasGraphQuery inner1 = q.createChildQuery().has("name", "Fred"); AtlasGraphQuery inner2 = q.createChildQuery().has("size15", "15"); q.or(toList(inner1, inner2)); assertQueryMatches(q, v1, v2, v3, v4); graph.commit(); pause(); //pause to let the indexer get updated (this fails frequently without a pause) assertQueryMatches(q, v1, v2, v3, v4); } @Test public <V, E> void testQueryMatchesAddedVertices() throws AtlasException { AtlasGraph<V, E> graph = getGraph(); AtlasVertex<V, E> v1 = createVertex(graph); v1.setProperty("name", "Fred"); v1.setProperty("size15", "15"); AtlasVertex<V, E> v2 = createVertex(graph); v2.setProperty("name", "Fred"); AtlasVertex<V, E> v3 = createVertex(graph); v3.setProperty("size15", "15"); graph.commit(); AtlasVertex<V, E> v4 = createVertex(graph); v4.setProperty("name", "Fred"); v4.setProperty("size15", "15"); AtlasGraphQuery q = getGraphQuery(); q.has("name", "Fred"); q.has("size15", "15"); assertQueryMatches(q, v1, v4); graph.commit(); assertQueryMatches(q, v1, v4); } @Test public <V, E> void testQueryDoesNotMatchRemovedVertices() throws AtlasException { AtlasGraph<V, E> graph = getGraph(); AtlasVertex<V, E> v1 = createVertex(graph); v1.setProperty("name", "Fred"); v1.setProperty("size15", "15"); AtlasVertex<V, E> v2 = createVertex(graph); v2.setProperty("name", "Fred"); AtlasVertex<V, E> v3 = createVertex(graph); v3.setProperty("size15", "15"); AtlasVertex<V, E> v4 = createVertex(graph); v4.setProperty("name", "Fred"); v4.setProperty("size15", "15"); graph.commit(); graph.removeVertex(v1); AtlasGraphQuery q = getGraphQuery(); q.has("name", "Fred"); q.has("size15", "15"); assertQueryMatches(q, v4); graph.commit(); assertQueryMatches(q, v4); } @Test public <V, E> void testQueryDoesNotMatchUncommittedAddedAndRemovedVertices() throws AtlasException { AtlasGraph<V, E> graph = getGraph(); AtlasVertex<V, E> v1 = createVertex(graph); v1.setProperty("name", "Fred"); v1.setProperty("size15", "15"); AtlasVertex<V, E> v2 = createVertex(graph); v2.setProperty("name", "Fred"); AtlasVertex<V, E> v3 = createVertex(graph); v3.setProperty("size15", "15"); AtlasVertex<V, E> v4 = createVertex(graph); v4.setProperty("name", "Fred"); v4.setProperty("size15", "15"); AtlasGraphQuery q = getGraphQuery(); q.has("name", "Fred"); q.has("size15", "15"); assertQueryMatches(q, v1, v4); graph.removeVertex(v1); assertQueryMatches(q, v4); graph.commit(); assertQueryMatches(q, v4); } @Test public <V, E> void testQueryResultsReflectPropertyAdd() throws AtlasException { AtlasGraph<V, E> graph = getGraph(); AtlasVertex<V, E> v1 = createVertex(graph); v1.setProperty("name", "Fred"); v1.setProperty("size15", "15"); v1.addProperty(TRAIT_NAMES, "trait1"); v1.addProperty(TRAIT_NAMES, "trait2"); AtlasVertex<V, E> v2 = createVertex(graph); v2.setProperty("name", "Fred"); v2.addProperty(TRAIT_NAMES, "trait1"); AtlasVertex<V, E> v3 = createVertex(graph); v3.setProperty("size15", "15"); v3.addProperty(TRAIT_NAMES, "trait2"); AtlasGraphQuery query = getGraphQuery(); query.has("name", "Fred"); query.has(TRAIT_NAMES, "trait1"); query.has("size15", "15"); assertQueryMatches(query, v1); //make v3 match the query v3.setProperty("name", "Fred"); v3.addProperty(TRAIT_NAMES, "trait1"); assertQueryMatches(query, v1, v3); v3.removeProperty(TRAIT_NAMES); assertQueryMatches(query, v1); v3.addProperty(TRAIT_NAMES, "trait2"); assertQueryMatches(query, v1); v1.removeProperty(TRAIT_NAMES); assertQueryMatches(query); graph.commit(); assertQueryMatches(query); } private static <T> List<T> toList(Iterable<T> itr) { List<T> result = new ArrayList<>(); for(T object : itr) { result.add(object); } return result; } private <V, E> void assertQueryMatches(AtlasGraphQuery expr, AtlasVertex... expectedResults) throws AtlasException { //getGraph().commit(); Collection<AtlasVertex<Titan0Vertex, Titan0Edge>> temp = toList(expr.vertices()); //filter out vertices from previous test executions Collection<AtlasVertex<Titan0Vertex, Titan0Edge>> result = Collections2.filter(temp, new Predicate<AtlasVertex<Titan0Vertex, Titan0Edge>>() { @Override public boolean apply(AtlasVertex<Titan0Vertex, Titan0Edge> input) { return newVertices.contains(input); } }); String errorMessage = "Expected/found result sizes differ. Expected: " + Arrays.asList(expectedResults).toString() +", found: " + result; assertEquals(errorMessage, expectedResults.length, result.size()); for(AtlasVertex<V, E> v : expectedResults) { assertTrue(result.contains(v)); } } private static List<Object> toList(Object...objects) { return Arrays.asList(objects); } private AtlasGraphQuery<Titan0Vertex, Titan0Edge> getGraphQuery() { return getTitan0Graph().query(); } private void pause() { try { Thread.sleep(5000); } catch(InterruptedException e) { //ignore } } } <|start_filename|>graphdb/titan0/src/test/java/com/thinkaurelius/titan/diskstorage/hbase/HBaseKeyColumnValueStoreTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thinkaurelius.titan.diskstorage.hbase; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.fail; import java.util.concurrent.TimeUnit; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.thinkaurelius.titan.diskstorage.BackendException; import com.thinkaurelius.titan.diskstorage.EntryMetaData; import com.thinkaurelius.titan.diskstorage.StaticBuffer; import com.thinkaurelius.titan.diskstorage.configuration.Configuration; import com.thinkaurelius.titan.diskstorage.locking.LocalLockMediator; import com.thinkaurelius.titan.diskstorage.locking.PermanentLockingException; import com.thinkaurelius.titan.diskstorage.util.KeyColumn; import com.thinkaurelius.titan.diskstorage.util.time.StandardDuration; import com.thinkaurelius.titan.diskstorage.util.time.Timepoint; import com.thinkaurelius.titan.graphdb.configuration.GraphDatabaseConfiguration; public class HBaseKeyColumnValueStoreTest { @Mock HBaseStoreManager storeManager; @Mock ConnectionMask connectionMask; @Mock LocalLockMediator localLockMediator; @Mock StaticBuffer key; @Mock StaticBuffer column; @Mock StaticBuffer expectedValue; @Mock HBaseTransaction transaction; @Mock Configuration storageConfig; @BeforeMethod public void setup() { MockitoAnnotations.initMocks(this); } @Test public void shouldSucceedInLockingIfLockMediatorSucceeds() throws BackendException { when(storeManager.getMetaDataSchema("hbase")).thenReturn(new EntryMetaData[] {EntryMetaData.TIMESTAMP}); when(storeManager.getStorageConfig()).thenReturn(storageConfig); when(storageConfig.get(GraphDatabaseConfiguration.LOCK_EXPIRE)).thenReturn( new StandardDuration(300L, TimeUnit.MILLISECONDS)); when(storageConfig.get(GraphDatabaseConfiguration.LOCK_WAIT)).thenReturn( new StandardDuration(10L, TimeUnit.MILLISECONDS)); when(storageConfig.get(GraphDatabaseConfiguration.LOCK_RETRY)).thenReturn(3); KeyColumn lockID = new KeyColumn(key, column); when(localLockMediator.lock(eq(lockID), eq(transaction), any(Timepoint.class))). thenReturn(true); HBaseKeyColumnValueStore hBaseKeyColumnValueStore = new HBaseKeyColumnValueStore(storeManager, connectionMask, "titan", "e", "hbase", localLockMediator); hBaseKeyColumnValueStore.acquireLock(key, column, expectedValue, transaction); verify(transaction).updateLocks(lockID, expectedValue); verify(localLockMediator, times(1)).lock(eq(lockID), eq(transaction), any(Timepoint.class)); } @Test public void shouldRetryRightNumberOfTimesIfLockMediationFails() throws BackendException { when(storeManager.getMetaDataSchema("hbase")).thenReturn(new EntryMetaData[] {EntryMetaData.TIMESTAMP}); when(storeManager.getStorageConfig()).thenReturn(storageConfig); when(storageConfig.get(GraphDatabaseConfiguration.LOCK_EXPIRE)).thenReturn( new StandardDuration(300L, TimeUnit.MILLISECONDS)); when(storageConfig.get(GraphDatabaseConfiguration.LOCK_WAIT)).thenReturn( new StandardDuration(10L, TimeUnit.MILLISECONDS)); when(storageConfig.get(GraphDatabaseConfiguration.LOCK_RETRY)).thenReturn(3); KeyColumn lockID = new KeyColumn(key, column); when(localLockMediator.lock(eq(lockID), eq(transaction), any(Timepoint.class))). thenReturn(false).thenReturn(false).thenReturn(true); HBaseKeyColumnValueStore hBaseKeyColumnValueStore = new HBaseKeyColumnValueStore(storeManager, connectionMask, "titan", "e", "hbase", localLockMediator); hBaseKeyColumnValueStore.acquireLock(key, column, expectedValue, transaction); verify(transaction).updateLocks(lockID, expectedValue); verify(localLockMediator, times(3)).lock(eq(lockID), eq(transaction), any(Timepoint.class)); } @Test(expectedExceptions = PermanentLockingException.class) public void shouldThrowExceptionAfterConfiguredRetriesIfLockMediationFails() throws BackendException { when(storeManager.getMetaDataSchema("hbase")).thenReturn(new EntryMetaData[] {EntryMetaData.TIMESTAMP}); when(storeManager.getStorageConfig()).thenReturn(storageConfig); when(storageConfig.get(GraphDatabaseConfiguration.LOCK_EXPIRE)).thenReturn( new StandardDuration(300L, TimeUnit.MILLISECONDS)); when(storageConfig.get(GraphDatabaseConfiguration.LOCK_WAIT)).thenReturn( new StandardDuration(10L, TimeUnit.MILLISECONDS)); when(storageConfig.get(GraphDatabaseConfiguration.LOCK_RETRY)).thenReturn(3); KeyColumn lockID = new KeyColumn(key, column); when(localLockMediator.lock(eq(lockID), eq(transaction), any(Timepoint.class))). thenReturn(false).thenReturn(false).thenReturn(false); HBaseKeyColumnValueStore hBaseKeyColumnValueStore = new HBaseKeyColumnValueStore(storeManager, connectionMask, "titan", "e", "hbase", localLockMediator); hBaseKeyColumnValueStore.acquireLock(key, column, expectedValue, transaction); fail("Should fail as lock could not be acquired after 3 retries."); } } <|start_filename|>repository/src/test/java/org/apache/atlas/repository/graph/Gremlin3QueryOptimizerTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graph; import org.apache.atlas.gremlin.Gremlin3ExpressionFactory; import org.apache.atlas.gremlin.GremlinExpressionFactory; import org.testng.annotations.Test; @Test public class Gremlin3QueryOptimizerTest extends AbstractGremlinQueryOptimizerTest { public static GremlinExpressionFactory FACTORY = null; @Override protected GremlinExpressionFactory getFactory() { if (null == FACTORY) { FACTORY = new Gremlin3ExpressionFactory(); } return FACTORY; } @Override protected String getExpectedGremlinForTestPullHasExpressionsOutOfHas() { return "g.V().has('prop1',eq('Fred')).has('prop2',eq('George')).and(out('out1'),out('out2'))"; } @Override protected String getExpectedGremlinForTestOrGrouping() { return "def r=(([]) as Set);" + "g.V().has('prop1',eq('Fred')).fill(r);" + "g.V().has('prop2',eq('George')).fill(r);" + "g.V().or(out('out1'),out('out2')).fill(r);" + "r"; } @Override protected String getExpectedGremlinForTestAndOfOrs() { return "def r=(([]) as Set);" + "g.V().has('p1',eq('e1')).has('p3',eq('e3')).fill(r);" + "g.V().has('p1',eq('e1')).has('p4',eq('e4')).fill(r);" + "g.V().has('p2',eq('e2')).has('p3',eq('e3')).fill(r);" + "g.V().has('p2',eq('e2')).has('p4',eq('e4')).fill(r);" + "r"; } @Override protected String getExpectedGremlinForTestAndWithMultiCallArguments() { return "g.V().has('p1',eq('e1')).has('p2',eq('e2')).has('p3',eq('e3')).has('p4',eq('e4'))"; } @Override protected String getExpectedGremlinForTestOrOfAnds() { return "def r=(([]) as Set);" + "g.V().has('p1',eq('e1')).has('p2',eq('e2')).fill(r);" + "g.V().has('p3',eq('e3')).has('p4',eq('e4')).fill(r);" + "r"; } @Override protected String getExpectedGremlinForTestHasNotMovedToResult() { return "def r=(([]) as Set);" + "def f1={GraphTraversal x->x.has('p3',eq('e3')).as('_src').select('_src').fill(r)};" + "f1(g.V().has('p1',eq('e1')));f1(g.V().has('p2',eq('e2')));" + "g.V('').inject(((r) as Vertex[])).as('_src').select('src1').by((({it}) as Function))"; } @Override protected String getExpectedGremlinForTestLongStringEndingWithOr() { return "def r=(([]) as Set);" + "def f1={g.V().has('name',eq('Fred')).has('age',eq('13')).out('livesIn').has('state',eq('Massachusetts'))};" + "def f2={GraphTraversal x->x.has('p5',eq('e5')).has('p6',eq('e6'))};" + "f2(f1().has('p1',eq('e1')).has('p3',eq('e3'))).has('p7',eq('e7')).fill(r);" + "f2(f1().has('p1',eq('e1')).has('p3',eq('e3'))).has('p8',eq('e8')).fill(r);" + "f2(f1().has('p1',eq('e1')).has('p4',eq('e4'))).has('p7',eq('e7')).fill(r);" + "f2(f1().has('p1',eq('e1')).has('p4',eq('e4'))).has('p8',eq('e8')).fill(r);" + "f2(f1().has('p2',eq('e2')).has('p3',eq('e3'))).has('p7',eq('e7')).fill(r);" + "f2(f1().has('p2',eq('e2')).has('p3',eq('e3'))).has('p8',eq('e8')).fill(r);" + "f2(f1().has('p2',eq('e2')).has('p4',eq('e4'))).has('p7',eq('e7')).fill(r);" + "f2(f1().has('p2',eq('e2')).has('p4',eq('e4'))).has('p8',eq('e8')).fill(r);" + "r"; } @Override protected String getExpectedGremlinForTestLongStringNotEndingWithOr() { return "def r=(([]) as Set);" + "def f1={g.V().has('name',eq('Fred')).has('age',eq('13')).out('livesIn').has('state',eq('Massachusetts'))};" + "def f2={GraphTraversal x->x.has('p5',eq('e5')).has('p6',eq('e6'))};" + "def f3={GraphTraversal x->x.has('p9',eq('e9')).fill(r)};" + "f3(f2(f1().has('p1',eq('e1')).has('p3',eq('e3'))).has('p7',eq('e7')));" + "f3(f2(f1().has('p1',eq('e1')).has('p3',eq('e3'))).has('p8',eq('e8')));" + "f3(f2(f1().has('p1',eq('e1')).has('p4',eq('e4'))).has('p7',eq('e7')));" + "f3(f2(f1().has('p1',eq('e1')).has('p4',eq('e4'))).has('p8',eq('e8')));" + "f3(f2(f1().has('p2',eq('e2')).has('p3',eq('e3'))).has('p7',eq('e7')));" + "f3(f2(f1().has('p2',eq('e2')).has('p3',eq('e3'))).has('p8',eq('e8')));" + "f3(f2(f1().has('p2',eq('e2')).has('p4',eq('e4'))).has('p7',eq('e7')));" + "f3(f2(f1().has('p2',eq('e2')).has('p4',eq('e4'))).has('p8',eq('e8')));" + "r"; } @Override protected String getExpectedGremlinForTestToListConversion() { return "def r=(([]) as Set);" + "g.V().has('prop1',eq('Fred')).fill(r);" + "g.V().has('prop2',eq('George')).fill(r);" + "g.V('').inject(((r) as Vertex[])).toList()"; } @Override protected String getExpectedGremlinForTestToListWithExtraStuff() { return "def r=(([]) as Set);" + "g.V().has('prop1',eq('Fred')).fill(r);" + "g.V().has('prop2',eq('George')).fill(r);" + "g.V('').inject(((r) as Vertex[])).toList().size()"; } @Override protected String getExpectedGremlinForTestAddClosureWithExitExpressionDifferentFromExpr() { return "def r=(([]) as Set);" + "g.V().has('prop1',eq('Fred')).out('knows').out('livesIn').fill(r);" + "g.V().has('prop2',eq('George')).out('knows').out('livesIn').fill(r);" + "g.V('').inject(((r) as Vertex[])).toList().size()"; } @Override protected String getExpectedGremlinForTestAddClosureNoExitExpression() { return "def r=(([]) as Set);" + "g.V().has('prop1',eq('Fred')).out('knows').out('livesIn').fill(r);" + "g.V().has('prop2',eq('George')).out('knows').out('livesIn').fill(r);" + "r"; } @Override protected String getExpectedGremlinForTestAddClosureWithExitExpressionEqualToExpr() { return "def r=(([]) as Set);" + "g.V().has('prop1',eq('Fred')).out('knows').out('livesIn').fill(r);" + "g.V().has('prop2',eq('George')).out('knows').out('livesIn').fill(r);" + "g.V('').inject(((r) as Vertex[])).toList()"; } @Override protected String getExpectedGremlinForTestClosureNotCreatedWhenNoOrs() { return "g.V().has('prop1',eq('Fred')).has('prop2',eq('George')).out('knows').out('livesIn')"; } @Override protected String getExpectedGremlinForTestOrFollowedByAnd() { return "def r=(([]) as Set);" + "def f1={GraphTraversal x->x.has('age',eq('13')).has('age',eq('14')).fill(r)};" + "f1(g.V().has('name',eq('Fred')));" + "f1(g.V().has('name',eq('George')));" + "r"; } @Override protected String getExpectedGremlinForTestOrFollowedByOr() { return "def r=(([]) as Set);" + "g.V().has('name',eq('Fred')).has('age',eq('13')).fill(r);" + "g.V().has('name',eq('Fred')).has('age',eq('14')).fill(r);" + "g.V().has('name',eq('George')).has('age',eq('13')).fill(r);" + "g.V().has('name',eq('George')).has('age',eq('14')).fill(r);" + "r"; } @Override protected String getExpectedGremlinForTestMassiveOrExpansion() { return "def r=(([]) as Set);" + "def f1={g.V().has('h1',eq('h2')).has('h3',eq('h4'))};" + "def f2={GraphTraversal x->x.has('ha0',eq('hb0')).has('hc0',eq('hd0'))};" + "def f3={GraphTraversal x->x.has('ha1',eq('hb1')).has('hc1',eq('hd1'))};" + "def f4={GraphTraversal x->x.has('ha2',eq('hb2')).has('hc2',eq('hd2'))};" + "def f5={GraphTraversal x->x.has('ha3',eq('hb3')).has('hc3',eq('hd3'))};" + "def f6={GraphTraversal x->x.has('ha4',eq('hb4')).has('hc4',eq('hd4')).has('h5',eq('h6')).has('h7',eq('h8')).fill(r)};" + "f6(f5(f4(f3(f2(f1().has('p10',eq('e10'))).has('p11',eq('e11'))).has('p12',eq('e12'))).has('p13',eq('e13'))).has('p14',eq('e14')));" + "f6(f5(f4(f3(f2(f1().has('p10',eq('e10'))).has('p11',eq('e11'))).has('p12',eq('e12'))).has('p13',eq('e13'))).has('p24',eq('e24')));" + "f6(f5(f4(f3(f2(f1().has('p10',eq('e10'))).has('p11',eq('e11'))).has('p12',eq('e12'))).has('p23',eq('e23'))).has('p14',eq('e14')));" + "f6(f5(f4(f3(f2(f1().has('p10',eq('e10'))).has('p11',eq('e11'))).has('p12',eq('e12'))).has('p23',eq('e23'))).has('p24',eq('e24')));" + "f6(f5(f4(f3(f2(f1().has('p10',eq('e10'))).has('p11',eq('e11'))).has('p22',eq('e22'))).has('p13',eq('e13'))).has('p14',eq('e14')));" + "f6(f5(f4(f3(f2(f1().has('p10',eq('e10'))).has('p11',eq('e11'))).has('p22',eq('e22'))).has('p13',eq('e13'))).has('p24',eq('e24')));" + "f6(f5(f4(f3(f2(f1().has('p10',eq('e10'))).has('p11',eq('e11'))).has('p22',eq('e22'))).has('p23',eq('e23'))).has('p14',eq('e14')));" + "f6(f5(f4(f3(f2(f1().has('p10',eq('e10'))).has('p11',eq('e11'))).has('p22',eq('e22'))).has('p23',eq('e23'))).has('p24',eq('e24')));" + "f6(f5(f4(f3(f2(f1().has('p10',eq('e10'))).has('p21',eq('e21'))).has('p12',eq('e12'))).has('p13',eq('e13'))).has('p14',eq('e14')));" + "f6(f5(f4(f3(f2(f1().has('p10',eq('e10'))).has('p21',eq('e21'))).has('p12',eq('e12'))).has('p13',eq('e13'))).has('p24',eq('e24')));" + "f6(f5(f4(f3(f2(f1().has('p10',eq('e10'))).has('p21',eq('e21'))).has('p12',eq('e12'))).has('p23',eq('e23'))).has('p14',eq('e14')));" + "f6(f5(f4(f3(f2(f1().has('p10',eq('e10'))).has('p21',eq('e21'))).has('p12',eq('e12'))).has('p23',eq('e23'))).has('p24',eq('e24')));" + "f6(f5(f4(f3(f2(f1().has('p10',eq('e10'))).has('p21',eq('e21'))).has('p22',eq('e22'))).has('p13',eq('e13'))).has('p14',eq('e14')));" + "f6(f5(f4(f3(f2(f1().has('p10',eq('e10'))).has('p21',eq('e21'))).has('p22',eq('e22'))).has('p13',eq('e13'))).has('p24',eq('e24')));" + "f6(f5(f4(f3(f2(f1().has('p10',eq('e10'))).has('p21',eq('e21'))).has('p22',eq('e22'))).has('p23',eq('e23'))).has('p14',eq('e14')));" + "f6(f5(f4(f3(f2(f1().has('p10',eq('e10'))).has('p21',eq('e21'))).has('p22',eq('e22'))).has('p23',eq('e23'))).has('p24',eq('e24')));" + "f6(f5(f4(f3(f2(f1().has('p20',eq('e20'))).has('p11',eq('e11'))).has('p12',eq('e12'))).has('p13',eq('e13'))).has('p14',eq('e14')));" + "f6(f5(f4(f3(f2(f1().has('p20',eq('e20'))).has('p11',eq('e11'))).has('p12',eq('e12'))).has('p13',eq('e13'))).has('p24',eq('e24')));" + "f6(f5(f4(f3(f2(f1().has('p20',eq('e20'))).has('p11',eq('e11'))).has('p12',eq('e12'))).has('p23',eq('e23'))).has('p14',eq('e14')));" + "f6(f5(f4(f3(f2(f1().has('p20',eq('e20'))).has('p11',eq('e11'))).has('p12',eq('e12'))).has('p23',eq('e23'))).has('p24',eq('e24')));" + "f6(f5(f4(f3(f2(f1().has('p20',eq('e20'))).has('p11',eq('e11'))).has('p22',eq('e22'))).has('p13',eq('e13'))).has('p14',eq('e14')));" + "f6(f5(f4(f3(f2(f1().has('p20',eq('e20'))).has('p11',eq('e11'))).has('p22',eq('e22'))).has('p13',eq('e13'))).has('p24',eq('e24')));" + "f6(f5(f4(f3(f2(f1().has('p20',eq('e20'))).has('p11',eq('e11'))).has('p22',eq('e22'))).has('p23',eq('e23'))).has('p14',eq('e14')));" + "f6(f5(f4(f3(f2(f1().has('p20',eq('e20'))).has('p11',eq('e11'))).has('p22',eq('e22'))).has('p23',eq('e23'))).has('p24',eq('e24')));" + "f6(f5(f4(f3(f2(f1().has('p20',eq('e20'))).has('p21',eq('e21'))).has('p12',eq('e12'))).has('p13',eq('e13'))).has('p14',eq('e14')));" + "f6(f5(f4(f3(f2(f1().has('p20',eq('e20'))).has('p21',eq('e21'))).has('p12',eq('e12'))).has('p13',eq('e13'))).has('p24',eq('e24')));" + "f6(f5(f4(f3(f2(f1().has('p20',eq('e20'))).has('p21',eq('e21'))).has('p12',eq('e12'))).has('p23',eq('e23'))).has('p14',eq('e14')));" + "f6(f5(f4(f3(f2(f1().has('p20',eq('e20'))).has('p21',eq('e21'))).has('p12',eq('e12'))).has('p23',eq('e23'))).has('p24',eq('e24')));" + "f6(f5(f4(f3(f2(f1().has('p20',eq('e20'))).has('p21',eq('e21'))).has('p22',eq('e22'))).has('p13',eq('e13'))).has('p14',eq('e14')));" + "f6(f5(f4(f3(f2(f1().has('p20',eq('e20'))).has('p21',eq('e21'))).has('p22',eq('e22'))).has('p13',eq('e13'))).has('p24',eq('e24')));" + "f6(f5(f4(f3(f2(f1().has('p20',eq('e20'))).has('p21',eq('e21'))).has('p22',eq('e22'))).has('p23',eq('e23'))).has('p14',eq('e14')));" + "f6(f5(f4(f3(f2(f1().has('p20',eq('e20'))).has('p21',eq('e21'))).has('p22',eq('e22'))).has('p23',eq('e23'))).has('p24',eq('e24')));" + "r"; } @Override protected String getExpectedGremlinForTestAndFollowedByAnd() { return "g.V().has('name',eq('Fred')).has('name',eq('George')).has('age',eq('13')).has('age',eq('14'))"; } @Override protected String getExpectedGremlinForTestAndFollowedByOr() { return "def r=(([]) as Set);" + "def f1={g.V().has('name',eq('Fred')).has('name',eq('George'))};" + "f1().has('age',eq('13')).fill(r);" + "f1().has('age',eq('14')).fill(r);" + "r"; } @Override protected String getExpectedGremlinForTestInitialAlias() { return "def r=(([]) as Set);" + "g.V().as('x').has('name',eq('Fred')).fill(r);" + "g.V().as('x').has('name',eq('George')).fill(r);" + "r"; } @Override protected String getExpectedGremlinForTestFinalAlias() { return "def r=(([]) as Set);" + "g.V().has('name',eq('Fred')).as('x').fill(r);" + "g.V().has('name',eq('George')).as('x').fill(r);" + "r"; } @Override protected String getExpectedGremlinForTestAliasInMiddle() { return "def r=(([]) as Set);" + "g.V().has('name',eq('Fred')).as('x').has('age',eq('13')).fill(r);" + "g.V().has('name',eq('Fred')).as('x').has('age',eq('14')).fill(r);" + "g.V().has('name',eq('George')).as('x').has('age',eq('13')).fill(r);" + "g.V().has('name',eq('George')).as('x').has('age',eq('14')).fill(r);" + "r"; } @Override protected String getExpectedGreminForTestMultipleAliases() { return "def r=(([]) as Set);" + "def f1={GraphTraversal x->x.as('y').fill(r)};" + "f1(g.V().has('name',eq('Fred')).as('x').has('age',eq('13')));" + "f1(g.V().has('name',eq('Fred')).as('x').has('age',eq('14')));" + "f1(g.V().has('name',eq('George')).as('x').has('age',eq('13')));" + "f1(g.V().has('name',eq('George')).as('x').has('age',eq('14')));" + "r"; } @Override protected String getExpectedGremlinForTestAliasInOrExpr() { return "def r=(([]) as Set);" + "g.V().has('name',eq('Fred')).fill(r);" + "g.V().or(has('name',eq('George')).as('george')).fill(r);" + "r"; } @Override protected String getExpectedGremlinForTestAliasInAndExpr() { return "g.V().has('name',eq('Fred')).and(has('name',eq('George')).as('george'))"; } @Override protected String getExpectedGremlinForTestFlatMapExprInAnd() { return "g.V().has('name',eq('Fred')).and(out('knows').has('name',eq('George')))"; } @Override protected String getExpectedGremlinForTestFlatMapExprInOr() { return "def r=(([]) as Set);" + "g.V().has('name',eq('Fred')).fill(r);" + "g.V().or(out('knows').has('name',eq('George'))).fill(r);" + "r"; } @Override protected String getExpectedGremlinForTestFieldExpressionPushedToResultExpression() { return "def r=(([]) as Set);" + "g.V().has('name',eq('Fred')).fill(r);" + "g.V().or(out('knows').has('name',eq('George'))).fill(r);" + "g.V('').inject(((r) as Vertex[])).values('name')"; } @Override protected String getExpectedGremlinFortestOrWithNoChildren() { return "def r=(([]) as Set);" + "r"; } @Override protected String getExpectedGremlinForTestFinalAliasNeeded() { return "def r=(([]) as Set);" + "def f1={g.V().has('name',eq('Fred')).as('person').out('livesIn')};" + "def f2={GraphTraversal x->x.as('city').out('state').has('name',eq('Massachusetts')).as('__res').select('person','city','__res').fill(r)};" + "f2(f1().has('name',eq('Chicago')));f2(f1().has('name',eq('Boston')));" + "__(((r) as Map[])).as('__tmp').map({((Map)it.get()).get('person')}).as('person').select('__tmp').map({((Map)it.get()).get('city')}).as('city').select('__tmp').map({((Map)it.get()).get('__res')}).as('__res').path().toList().collect({it.tail()})"; } @Override protected String getExpectedGremlinForTestSimpleRangeExpression() { return "def r=(([]) as Set);" + "def f1={GraphTraversal x->x.has('age',eq('34')).out('eats').has('size',eq('small')).has('color',eq('blue')).range(0,10).fill(r)};" + "f1(g.V().has('name',eq('Fred')));" + "f1(g.V().has('name',eq('George')));" + "g.V('').inject(((r) as Vertex[])).range(0,10).toList().size()"; } @Override protected String getExpectedGremlinForOptimizeLoopExpression() { return "def r=(([]) as Set);def f1={GraphTraversal x->x.has('name',eq('Fred')).as('label').select('label').fill(r)};" + "f1(g.V().has('__typeName','DataSet'));" + "f1(g.V().has('__superTypeNames','DataSet'));" + "g.V('').inject(((r) as Vertex[])).as('label').repeat(__.in('inputTables').out('outputTables')).emit(has('__typeName',eq('string')).or().has('__superTypeNames',eq('string'))).toList()"; } @Override protected String getExpectedGremlinForTestRangeWithNonZeroOffset() { return "def r=(([]) as Set);" + "g.V().has('__typeName',eq('OMAS_OMRSAsset')).fill(r);" + "g.V().has('__superTypeNames',eq('OMAS_OMRSAsset')).fill(r);" + "g.V('').inject(((r) as Vertex[])).range(5,10).as('inst').select('inst')"; } @Override protected String getExpectedGremlinForTestRangeWithOrderBy() { return "def r=(([]) as Set);" + "g.V().has('__typeName',eq('OMAS_OMRSAsset')).fill(r);" + "g.V().has('__superTypeNames',eq('OMAS_OMRSAsset')).fill(r);" + "g.V('').inject(((r) as Vertex[])).range(5,10).as('inst').order().by((({it.get().values('name')}) as Function),{a, b->a.toString().toLowerCase() <=> b.toString().toLowerCase()})"; } } <|start_filename|>repository/src/main/java/org/apache/atlas/gremlin/Gremlin2ExpressionFactory.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.gremlin; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.atlas.AtlasException; import org.apache.atlas.groovy.AbstractFunctionExpression; import org.apache.atlas.groovy.CastExpression; import org.apache.atlas.groovy.ClosureExpression; import org.apache.atlas.groovy.ComparisonExpression; import org.apache.atlas.groovy.ComparisonExpression.ComparisonOperator; import org.apache.atlas.groovy.ComparisonOperatorExpression; import org.apache.atlas.groovy.FieldExpression; import org.apache.atlas.groovy.FunctionCallExpression; import org.apache.atlas.groovy.GroovyExpression; import org.apache.atlas.groovy.IdentifierExpression; import org.apache.atlas.groovy.ListExpression; import org.apache.atlas.groovy.LiteralExpression; import org.apache.atlas.groovy.LogicalExpression; import org.apache.atlas.groovy.LogicalExpression.LogicalOperator; import org.apache.atlas.groovy.RangeExpression; import org.apache.atlas.groovy.TernaryOperatorExpression; import org.apache.atlas.groovy.TraversalStepType; import org.apache.atlas.query.GraphPersistenceStrategies; import org.apache.atlas.query.TypeUtils.FieldInfo; import org.apache.atlas.typesystem.types.IDataType; /** * Generates gremlin query expressions using Gremlin 2 syntax. * */ public class Gremlin2ExpressionFactory extends GremlinExpressionFactory { private static final String LOOP_METHOD = "loop"; private static final String CONTAINS = "contains"; private static final String LOOP_COUNT_FIELD = "loops"; private static final String PATH_FIELD = "path"; private static final String ENABLE_PATH_METHOD = "enablePath"; private static final String BACK_METHOD = "back"; private static final String LAST_METHOD = "last"; @Override public GroovyExpression generateLogicalExpression(GroovyExpression parent, String operator, List<GroovyExpression> operands) { return new FunctionCallExpression(TraversalStepType.FILTER, parent, operator, operands); } @Override public GroovyExpression generateBackReferenceExpression(GroovyExpression parent, boolean inSelect, String alias) { if (inSelect && parent == null) { return getFieldInSelect(); } else if (inSelect && parent != null) { return parent; } else { return new FunctionCallExpression(TraversalStepType.MAP_TO_ELEMENT, parent, BACK_METHOD, new LiteralExpression(alias)); } } @Override public GroovyExpression getLoopExpressionParent(GroovyExpression inputQry) { return inputQry; } @Override public GroovyExpression generateLoopExpression(GroovyExpression parent,GraphPersistenceStrategies s, IDataType dataType, GroovyExpression loopExpr, String alias, Integer times) { GroovyExpression emitExpr = generateLoopEmitExpression(s, dataType); //note that in Gremlin 2 (unlike Gremlin 3), the parent is not explicitly used. It is incorporated //in the loopExpr. GroovyExpression whileFunction = null; if(times != null) { GroovyExpression loopsExpr = new FieldExpression(getItVariable(), LOOP_COUNT_FIELD); GroovyExpression timesExpr = new LiteralExpression(times); whileFunction = new ClosureExpression(new ComparisonExpression(loopsExpr, ComparisonOperator.LESS_THAN, timesExpr)); } else { GroovyExpression pathExpr = new FieldExpression(getItVariable(),PATH_FIELD); GroovyExpression itObjectExpr = getCurrentObjectExpression(); GroovyExpression pathContainsExpr = new FunctionCallExpression(pathExpr, CONTAINS, itObjectExpr); whileFunction = new ClosureExpression(new TernaryOperatorExpression(pathContainsExpr, LiteralExpression.FALSE, LiteralExpression.TRUE)); } GroovyExpression emitFunction = new ClosureExpression(emitExpr); GroovyExpression loopCall = new FunctionCallExpression(TraversalStepType.BRANCH, loopExpr, LOOP_METHOD, new LiteralExpression(alias), whileFunction, emitFunction); return new FunctionCallExpression(TraversalStepType.SIDE_EFFECT, loopCall, ENABLE_PATH_METHOD); } @Override public GroovyExpression typeTestExpression(GraphPersistenceStrategies s, String typeName, GroovyExpression itRef) { GroovyExpression superTypeAttrExpr = new FieldExpression(itRef, s.superTypeAttributeName()); GroovyExpression typeNameExpr = new LiteralExpression(typeName); GroovyExpression isSuperTypeExpr = new FunctionCallExpression(superTypeAttrExpr, CONTAINS, typeNameExpr); GroovyExpression superTypeMatchesExpr = new TernaryOperatorExpression(superTypeAttrExpr, isSuperTypeExpr, LiteralExpression.FALSE); GroovyExpression typeAttrExpr = new FieldExpression(itRef, s.typeAttributeName()); GroovyExpression typeMatchesExpr = new ComparisonExpression(typeAttrExpr, ComparisonOperator.EQUALS, typeNameExpr); return new LogicalExpression(typeMatchesExpr, LogicalOperator.OR, superTypeMatchesExpr); } @Override public GroovyExpression generateSelectExpression(GroovyExpression parent, List<LiteralExpression> sourceNames, List<GroovyExpression> srcExprs) { GroovyExpression srcNamesExpr = new ListExpression(sourceNames); List<GroovyExpression> selectArgs = new ArrayList<>(); selectArgs.add(srcNamesExpr); for(GroovyExpression expr : srcExprs) { selectArgs.add(new ClosureExpression(expr)); } return new FunctionCallExpression(TraversalStepType.MAP_TO_VALUE, parent, SELECT_METHOD, selectArgs); } @Override public GroovyExpression generateFieldExpression(GroovyExpression parent, FieldInfo fInfo, String propertyName, boolean inSelect) { return new FieldExpression(parent, propertyName); } @Override public GroovyExpression generateHasExpression(GraphPersistenceStrategies s, GroovyExpression parent, String propertyName, String symbol, GroovyExpression requiredValue, FieldInfo fInfo) throws AtlasException { GroovyExpression op = gremlin2CompOp(symbol); GroovyExpression propertyNameExpr = new LiteralExpression(propertyName); return new FunctionCallExpression(TraversalStepType.FILTER, parent, HAS_METHOD, propertyNameExpr, op, requiredValue); } @Override public GroovyExpression generateLikeExpressionUsingFilter(GroovyExpression parent, String propertyName, GroovyExpression propertyValue) throws AtlasException { GroovyExpression itExpr = getItVariable(); GroovyExpression nameExpr = new FieldExpression(itExpr, propertyName); GroovyExpression matchesExpr = new FunctionCallExpression(nameExpr, MATCHES, escapePropertyValue(propertyValue)); GroovyExpression closureExpr = new ClosureExpression(matchesExpr); return new FunctionCallExpression(TraversalStepType.FILTER, parent, FILTER_METHOD, closureExpr); } private GroovyExpression escapePropertyValue(GroovyExpression propertyValue) { GroovyExpression ret = propertyValue; if (propertyValue instanceof LiteralExpression) { LiteralExpression exp = (LiteralExpression) propertyValue; if (exp != null && exp.getValue() instanceof String) { String stringValue = (String) exp.getValue(); // replace '*' with ".*", replace '?' with '.' stringValue = stringValue.replaceAll("\\*", ".*") .replaceAll("\\?", "."); ret = new LiteralExpression(stringValue); } } return ret; } private GroovyExpression gremlin2CompOp(String op) throws AtlasException { GroovyExpression tExpr = new IdentifierExpression("T"); if(op.equals("=")) { return new FieldExpression(tExpr, "eq"); } if(op.equals("!=")) { return new FieldExpression(tExpr, "neq"); } if(op.equals(">")) { return new FieldExpression(tExpr, "gt"); } if(op.equals(">=")) { return new FieldExpression(tExpr, "gte"); } if(op.equals("<")) { return new FieldExpression(tExpr, "lt"); } if(op.equals("<=")) { return new FieldExpression(tExpr, "lte"); } if(op.equals("in")) { return new FieldExpression(tExpr, "in"); } throw new AtlasException("Comparison operator " + op + " not supported in Gremlin"); } @Override protected GroovyExpression initialExpression(GroovyExpression varExpr, GraphPersistenceStrategies s) { return generateSeededTraversalExpresssion(false, varExpr); } @Override public GroovyExpression generateSeededTraversalExpresssion(boolean isMap, GroovyExpression varExpr) { return new FunctionCallExpression(TraversalStepType.START, varExpr, "_"); } @Override public GroovyExpression generateRangeExpression(GroovyExpression parent, int startIndex, int endIndex) { //treat as barrier step, since limits need to be applied globally (even though it //is technically a filter step) return new RangeExpression(TraversalStepType.BARRIER, parent, startIndex, endIndex); } @Override public boolean isRangeExpression(GroovyExpression expr) { return (expr instanceof RangeExpression); } @Override public int[] getRangeParameters(AbstractFunctionExpression expr) { if (isRangeExpression(expr)) { RangeExpression rangeExpression = (RangeExpression) expr; return new int[] {rangeExpression.getStartIndex(), rangeExpression.getEndIndex()}; } else { return null; } } @Override public void setRangeParameters(GroovyExpression expr, int startIndex, int endIndex) { if (isRangeExpression(expr)) { RangeExpression rangeExpression = (RangeExpression) expr; rangeExpression.setStartIndex(startIndex); rangeExpression.setEndIndex(endIndex); } else { throw new IllegalArgumentException(expr.getClass().getName() + " is not a valid range expression - must be an instance of " + RangeExpression.class.getName()); } } @Override public List<GroovyExpression> getOrderFieldParents() { GroovyExpression itExpr = getItVariable(); List<GroovyExpression> result = new ArrayList<>(2); result.add(new FieldExpression(itExpr, "a")); result.add(new FieldExpression(itExpr, "b")); return result; } @Override public GroovyExpression generateOrderByExpression(GroovyExpression parent, List<GroovyExpression> translatedOrderBy, boolean isAscending) { GroovyExpression aPropertyExpr = translatedOrderBy.get(0); GroovyExpression bPropertyExpr = translatedOrderBy.get(1); GroovyExpression aPropertyNotNull = new ComparisonExpression(aPropertyExpr, ComparisonOperator.NOT_EQUALS, LiteralExpression.NULL); GroovyExpression bPropertyNotNull = new ComparisonExpression(bPropertyExpr, ComparisonOperator.NOT_EQUALS, LiteralExpression.NULL); GroovyExpression aCondition = new TernaryOperatorExpression(aPropertyNotNull, new FunctionCallExpression(aPropertyExpr,TO_LOWER_CASE_METHOD), aPropertyExpr); GroovyExpression bCondition = new TernaryOperatorExpression(bPropertyNotNull, new FunctionCallExpression(bPropertyExpr,TO_LOWER_CASE_METHOD), bPropertyExpr); GroovyExpression comparisonFunction = null; if(isAscending) { comparisonFunction = new ComparisonOperatorExpression(aCondition, bCondition); } else { comparisonFunction = new ComparisonOperatorExpression(bCondition, aCondition); } return new FunctionCallExpression(TraversalStepType.BARRIER, parent, ORDER_METHOD, new ClosureExpression(comparisonFunction)); } @Override public GroovyExpression getAnonymousTraversalExpression() { return new FunctionCallExpression(TraversalStepType.START, "_"); } @Override public GroovyExpression generateGroupByExpression(GroovyExpression parent, GroovyExpression groupByExpression, GroovyExpression aggregationFunction) { GroovyExpression groupByClosureExpr = new ClosureExpression(groupByExpression); GroovyExpression itClosure = new ClosureExpression(getItVariable()); GroovyExpression result = new FunctionCallExpression(TraversalStepType.BARRIER, parent, "groupBy", groupByClosureExpr, itClosure); result = new FunctionCallExpression(TraversalStepType.SIDE_EFFECT, result, "cap"); result = new FunctionCallExpression(TraversalStepType.END, result, "next"); result = new FunctionCallExpression(result, "values"); result = new FunctionCallExpression(result, "toList"); GroovyExpression aggregrationFunctionClosure = new ClosureExpression(aggregationFunction); result = new FunctionCallExpression(result, "collect", aggregrationFunctionClosure); return result; } @Override public GroovyExpression getFieldInSelect() { return getItVariable(); } @Override public GroovyExpression getGroupBySelectFieldParent() { GroovyExpression itExpr = getItVariable(); return new FunctionCallExpression(itExpr, LAST_METHOD); } //assumes cast already performed @Override public GroovyExpression generateCountExpression(GroovyExpression itExpr) { return new FunctionCallExpression(itExpr, "size"); } @Override public String getTraversalExpressionClass() { return "GremlinPipeline"; } @Override public boolean isSelectGeneratesMap(int aliasCount) { //in Gremlin 2 select always generates a map return true; } @Override public GroovyExpression generateMapExpression(GroovyExpression parent, ClosureExpression closureExpression) { return new FunctionCallExpression(TraversalStepType.MAP_TO_ELEMENT, parent, "transform", closureExpression); } @Override public GroovyExpression generateGetSelectedValueExpression(LiteralExpression key, GroovyExpression rowMap) { rowMap = new CastExpression(rowMap, "Row"); GroovyExpression getExpr = new FunctionCallExpression(rowMap, "getColumn", key); return getExpr; } @Override public GroovyExpression getCurrentTraverserObject(GroovyExpression traverser) { return traverser; } public List<String> getAliasesRequiredByExpression(GroovyExpression expr) { if(!(expr instanceof FunctionCallExpression)) { return Collections.emptyList(); } FunctionCallExpression fc = (FunctionCallExpression)expr; if(! fc.getFunctionName().equals(LOOP_METHOD)) { return Collections.emptyList(); } LiteralExpression aliasName = (LiteralExpression)fc.getArguments().get(0); return Collections.singletonList(aliasName.getValue().toString()); } @Override public boolean isRepeatExpression(GroovyExpression expr) { if(!(expr instanceof FunctionCallExpression)) { return false; } return ((FunctionCallExpression)expr).getFunctionName().equals(LOOP_METHOD); } } <|start_filename|>webapp/src/main/java/org/apache/atlas/web/resources/TypesResource.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.web.resources; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.core.ResourceContext; import org.apache.atlas.AtlasClient; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.typedef.AtlasTypesDef; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.typesystem.TypesDef; import org.apache.atlas.typesystem.json.TypesSerialization; import org.apache.atlas.repository.converters.TypeConverterUtil; import org.apache.atlas.utils.AtlasPerfTracer; import org.apache.atlas.web.rest.TypesREST; import org.apache.atlas.web.util.Servlets; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; /** * This class provides RESTful API for Types. * * A type is the description of any representable item; * e.g. a Hive table * * You could represent any meta model representing any domain using these types. */ @Path("types") @Singleton @Service @Deprecated public class TypesResource { private static final Logger LOG = LoggerFactory.getLogger(TypesResource.class); private static final Logger PERF_LOG = AtlasPerfTracer.getPerfLogger("rest.TypesResource"); private static AtlasTypeRegistry typeRegistry; private final TypesREST typesREST; @Inject public TypesResource(AtlasTypeRegistry typeRegistry, TypesREST typesREST) { this.typeRegistry = typeRegistry; this.typesREST = typesREST; } @Context private ResourceContext resourceContext; /** * Submits a type definition corresponding to a given type representing a meta model of a * domain. Could represent things like Hive Database, Hive Table, etc. */ @POST @Consumes({Servlets.JSON_MEDIA_TYPE, MediaType.APPLICATION_JSON}) @Produces(Servlets.JSON_MEDIA_TYPE) public Response submit(@Context HttpServletRequest request) { if (LOG.isDebugEnabled()) { LOG.debug("==> TypesResource.submit()"); } AtlasPerfTracer perf = null; if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "TypesResource.submit()"); } JSONArray typesResponse = new JSONArray(); try { final String typeDefinition = Servlets.getRequestPayload(request); if (LOG.isDebugEnabled()) { LOG.debug("Creating type with definition {} ", typeDefinition); } AtlasTypesDef createTypesDef = TypeConverterUtil.toAtlasTypesDef(typeDefinition, typeRegistry); AtlasTypesDef createdTypesDef = typesREST.createAtlasTypeDefs(createTypesDef); List<String> typeNames = TypeConverterUtil.getTypeNames(createdTypesDef); for (int i = 0; i < typeNames.size(); i++) { final String name = typeNames.get(i); typesResponse.put(new JSONObject() {{ put(AtlasClient.NAME, name); }}); } JSONObject response = new JSONObject(); response.put(AtlasClient.REQUEST_ID, Servlets.getRequestId()); response.put(AtlasClient.TYPES, typesResponse); return Response.status(ClientResponse.Status.CREATED).entity(response).build(); } catch (AtlasBaseException e) { LOG.error("Type creation failed", e); throw new WebApplicationException(Servlets.getErrorResponse(e)); } catch (IllegalArgumentException e) { LOG.error("Unable to persist types", e); throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.BAD_REQUEST)); } catch (WebApplicationException e) { LOG.error("Unable to persist types", e); throw e; } catch (Throwable e) { LOG.error("Unable to persist types", e); throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR)); } finally { AtlasPerfTracer.log(perf); if (LOG.isDebugEnabled()) { LOG.debug("<== TypesResource.submit()"); } } } /** * Update of existing types - if the given type doesn't exist, creates new type * Allowed updates are: * 1. Add optional attribute * 2. Change required to optional attribute * 3. Add super types - super types shouldn't contain any required attributes * @param request * @return */ @PUT @Consumes({Servlets.JSON_MEDIA_TYPE, MediaType.APPLICATION_JSON}) @Produces(Servlets.JSON_MEDIA_TYPE) public Response update(@Context HttpServletRequest request) { if (LOG.isDebugEnabled()) { LOG.debug("==> TypesResource.update()"); } AtlasPerfTracer perf = null; if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "TypesResource.update()"); } JSONArray typesResponse = new JSONArray(); try { final String typeDefinition = Servlets.getRequestPayload(request); if (LOG.isDebugEnabled()) { LOG.debug("Updating type with definition {} ", typeDefinition); } AtlasTypesDef updateTypesDef = TypeConverterUtil.toAtlasTypesDef(typeDefinition, typeRegistry); AtlasTypesDef updatedTypesDef = typesREST.updateAtlasTypeDefs(updateTypesDef); List<String> typeNames = TypeConverterUtil.getTypeNames(updatedTypesDef); for (int i = 0; i < typeNames.size(); i++) { final String name = typeNames.get(i); typesResponse.put(new JSONObject() {{ put(AtlasClient.NAME, name); }}); } JSONObject response = new JSONObject(); response.put(AtlasClient.REQUEST_ID, Servlets.getRequestId()); response.put(AtlasClient.TYPES, typesResponse); return Response.ok().entity(response).build(); } catch (AtlasBaseException e) { LOG.error("Unable to persist types", e); throw new WebApplicationException(Servlets.getErrorResponse(e)); } catch (IllegalArgumentException e) { LOG.error("Unable to persist types", e); throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.BAD_REQUEST)); } catch (WebApplicationException e) { LOG.error("Unable to persist types", e); throw e; } catch (Throwable e) { LOG.error("Unable to persist types", e); throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR)); } finally { AtlasPerfTracer.log(perf); if (LOG.isDebugEnabled()) { LOG.debug("<== TypesResource.update()"); } } } /** * Fetch the complete definition of a given type name which is unique. * * @param typeName name of a type which is unique. */ @GET @Path("{typeName}") @Produces(Servlets.JSON_MEDIA_TYPE) public Response getDefinition(@Context HttpServletRequest request, @PathParam("typeName") String typeName) { if (LOG.isDebugEnabled()) { LOG.debug("==> TypesResource.getDefinition({})", typeName); } AtlasPerfTracer perf = null; if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "TypesResource.getDefinition(" + typeName + ")"); } JSONObject response = new JSONObject(); try { TypesDef typesDef = TypeConverterUtil.toTypesDef(typeRegistry.getType(typeName), typeRegistry);; String typeDefinition = TypesSerialization.toJson(typesDef); response.put(AtlasClient.TYPENAME, typeName); response.put(AtlasClient.DEFINITION, new JSONObject(typeDefinition)); response.put(AtlasClient.REQUEST_ID, Servlets.getRequestId()); return Response.ok(response).build(); } catch (AtlasBaseException e) { LOG.error("Unable to get type definition for type {}", typeName, e); throw new WebApplicationException(Servlets.getErrorResponse(e)); } catch (JSONException | IllegalArgumentException e) { LOG.error("Unable to get type definition for type {}", typeName, e); throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.BAD_REQUEST)); } catch (WebApplicationException e) { LOG.error("Unable to get type definition for type {}", typeName, e); throw e; } catch (Throwable e) { LOG.error("Unable to get type definition for type {}", typeName, e); throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR)); } finally { AtlasPerfTracer.log(perf); if (LOG.isDebugEnabled()) { LOG.debug("<== TypesResource.getDefinition({})", typeName); } } } /** * Return the list of type names in the type system which match the specified filter. * * @return list of type names * @param typeCategory returns types whose relationshipCategory is the given typeCategory * @param supertype returns types which contain the given supertype * @param notsupertype returns types which do not contain the given supertype * * Its possible to specify combination of these filters in one request and the conditions are combined with AND * For example, typeCategory = TRAIT && supertype contains 'X' && supertype !contains 'Y' * If there is no filter, all the types are returned */ @GET @Produces(Servlets.JSON_MEDIA_TYPE) public Response getTypesByFilter(@Context HttpServletRequest request, @QueryParam("type") String typeCategory, @QueryParam("supertype") String supertype, @QueryParam("notsupertype") String notsupertype) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> TypesResource.getTypesByFilter({}, {}, {})", typeCategory, supertype, notsupertype); } AtlasPerfTracer perf = null; if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "TypesResource.getTypesByFilter(" + typeCategory + ", " + supertype + ", " + notsupertype + ")"); } JSONObject response = new JSONObject(); try { List<String> result = TypeConverterUtil.getTypeNames(typesREST.getTypeDefHeaders(request)); response.put(AtlasClient.RESULTS, new JSONArray(result)); response.put(AtlasClient.COUNT, result.size()); response.put(AtlasClient.REQUEST_ID, Servlets.getRequestId()); return Response.ok(response).build(); } catch (AtlasBaseException e) { LOG.warn("TypesREST exception: {} {}", e.getClass().getSimpleName(), e.getMessage()); throw new WebApplicationException(Servlets.getErrorResponse(e)); } catch (WebApplicationException e) { LOG.error("Unable to get types list", e); throw e; } catch (Throwable e) { LOG.error("Unable to get types list", e); throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR)); } finally { AtlasPerfTracer.log(perf); if (LOG.isDebugEnabled()) { LOG.debug("<== TypesResource.getTypesByFilter({}, {}, {})", typeCategory, supertype, notsupertype); } } } } <|start_filename|>graphdb/titan0/src/main/java/org/apache/atlas/repository/graphdb/titan0/Titan0Graph.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan0; import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.thinkaurelius.titan.core.Cardinality; import com.thinkaurelius.titan.core.PropertyKey; import com.thinkaurelius.titan.core.SchemaViolationException; import com.thinkaurelius.titan.core.TitanGraph; import com.thinkaurelius.titan.core.TitanIndexQuery; import com.thinkaurelius.titan.core.schema.TitanManagement; import com.thinkaurelius.titan.core.util.TitanCleanup; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.util.io.graphson.GraphSONWriter; import com.tinkerpop.pipes.util.structures.Row; import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.groovy.GroovyExpression; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.AtlasGraphManagement; import org.apache.atlas.repository.graphdb.AtlasGraphQuery; import org.apache.atlas.repository.graphdb.AtlasIndexQuery; import org.apache.atlas.repository.graphdb.AtlasSchemaViolationException; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.repository.graphdb.GremlinVersion; import org.apache.atlas.repository.graphdb.titan0.query.Titan0GraphQuery; import org.apache.atlas.repository.graphdb.utils.IteratorToIterableAdapter; import org.apache.atlas.typesystem.types.IDataType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.script.Bindings; import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * Titan 0.5.4 implementation of AtlasGraph. */ public class Titan0Graph implements AtlasGraph<Titan0Vertex, Titan0Edge> { private static final Logger LOG = LoggerFactory.getLogger(Titan0Graph.class); private final Set<String> multiProperties; public Titan0Graph() { //determine multi-properties once at startup TitanManagement mgmt = null; try { mgmt = Titan0GraphDatabase.getGraphInstance().getManagementSystem(); Iterable<PropertyKey> keys = mgmt.getRelationTypes(PropertyKey.class); multiProperties = Collections.synchronizedSet(new HashSet<String>()); for(PropertyKey key : keys) { if (key.getCardinality() != Cardinality.SINGLE) { multiProperties.add(key.getName()); } } } finally { if (mgmt != null) { mgmt.rollback(); } } } @Override public AtlasEdge<Titan0Vertex, Titan0Edge> addEdge(AtlasVertex<Titan0Vertex, Titan0Edge> outVertex, AtlasVertex<Titan0Vertex, Titan0Edge> inVertex, String edgeLabel) { try { Edge edge = getGraph().addEdge(null, outVertex.getV().getWrappedElement(), inVertex.getV().getWrappedElement(), edgeLabel); return GraphDbObjectFactory.createEdge(this, edge); } catch (SchemaViolationException e) { throw new AtlasSchemaViolationException(e); } } @Override public AtlasGraphQuery<Titan0Vertex, Titan0Edge> query() { return new Titan0GraphQuery(this); } @Override public AtlasEdge<Titan0Vertex, Titan0Edge> getEdge(String edgeId) { Edge edge = getGraph().getEdge(edgeId); return GraphDbObjectFactory.createEdge(this, edge); } @Override public void removeEdge(AtlasEdge<Titan0Vertex, Titan0Edge> edge) { getGraph().removeEdge(edge.getE().getWrappedElement()); } @Override public void removeVertex(AtlasVertex<Titan0Vertex, Titan0Edge> vertex) { getGraph().removeVertex(vertex.getV().getWrappedElement()); } @Override public Iterable<AtlasEdge<Titan0Vertex, Titan0Edge>> getEdges() { Iterable<Edge> edges = getGraph().getEdges(); return wrapEdges(edges); } @Override public Iterable<AtlasVertex<Titan0Vertex, Titan0Edge>> getVertices() { Iterable<Vertex> vertices = getGraph().getVertices(); return wrapVertices(vertices); } @Override public AtlasVertex<Titan0Vertex, Titan0Edge> addVertex() { Vertex result = getGraph().addVertex(null); return GraphDbObjectFactory.createVertex(this, result); } @Override public void commit() { getGraph().commit(); } @Override public void rollback() { getGraph().rollback(); } @Override public AtlasIndexQuery<Titan0Vertex, Titan0Edge> indexQuery(String fulltextIndex, String graphQuery) { return indexQuery(fulltextIndex, graphQuery, 0); } @Override public AtlasIndexQuery<Titan0Vertex, Titan0Edge> indexQuery(String fulltextIndex, String graphQuery, int offset) { TitanIndexQuery query = getGraph().indexQuery(fulltextIndex, graphQuery).offset(offset); return new Titan0IndexQuery(this, query); } @Override public AtlasGraphManagement getManagementSystem() { return new Titan0GraphManagement(this, getGraph().getManagementSystem()); } @Override public void shutdown() { getGraph().shutdown(); } @Override public Set<String> getVertexIndexKeys() { return getIndexKeys(Vertex.class); } @Override public Set<String> getEdgeIndexKeys() { return getIndexKeys(Edge.class); } private Set<String> getIndexKeys(Class<? extends Element> titanClass) { return getGraph().getIndexedKeys(titanClass); } @Override public AtlasVertex<Titan0Vertex, Titan0Edge> getVertex(String vertexId) { Vertex v = getGraph().getVertex(vertexId); return GraphDbObjectFactory.createVertex(this, v); } @Override public Iterable<AtlasVertex<Titan0Vertex, Titan0Edge>> getVertices(String key, Object value) { Iterable<Vertex> result = getGraph().getVertices(key, value); return wrapVertices(result); } private Object convertGremlinValue(Object rawValue) { if (rawValue instanceof Vertex) { return GraphDbObjectFactory.createVertex(this, (Vertex) rawValue); } else if (rawValue instanceof Edge) { return GraphDbObjectFactory.createEdge(this, (Edge) rawValue); } else if (rawValue instanceof Row) { Row rowValue = (Row)rawValue; Map<String, Object> result = new HashMap<>(rowValue.size()); List<String> columnNames = rowValue.getColumnNames(); for(int i = 0; i < rowValue.size(); i++) { String key = columnNames.get(i); Object value = convertGremlinValue(rowValue.get(i)); result.put(key, value); } return result; } else if (rawValue instanceof List) { return Lists.transform((List)rawValue, new Function<Object, Object>() { @Override public Object apply(Object input) { return convertGremlinValue(input); } }); } else if (rawValue instanceof Collection) { throw new UnsupportedOperationException("Unhandled collection type: " + rawValue.getClass()); } return rawValue; } @Override public GremlinVersion getSupportedGremlinVersion() { return GremlinVersion.TWO; } private List<Object> convertPathQueryResultToList(Object rawValue) { return (List<Object>) rawValue; } @Override public void clear() { TitanGraph graph = getGraph(); if (graph.isOpen()) { // only a shut down graph can be cleared graph.shutdown(); } TitanCleanup.clear(graph); } private TitanGraph getGraph() { // return the singleton instance of the graph in the plugin return Titan0GraphDatabase.getGraphInstance(); } @Override public void exportToGson(OutputStream os) throws IOException { GraphSONWriter.outputGraph(getGraph(), os); } @Override public Object executeGremlinScript(String query, boolean isPath) throws AtlasBaseException { Object result = executeGremlinScript(query); return convertGremlinScriptResult(isPath, result); } private Object convertGremlinScriptResult(boolean isPath, Object result) { if (isPath) { List<Object> path = convertPathQueryResultToList(result); List<Object> convertedResult = new ArrayList<>(path.size()); for(Object o : path) { convertedResult.add(convertGremlinValue(o)); } return convertedResult; } else { return convertGremlinValue(result); } } @Override public ScriptEngine getGremlinScriptEngine() throws AtlasBaseException { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("gremlin-groovy"); if (engine == null) { throw new AtlasBaseException(AtlasErrorCode.FAILED_TO_OBTAIN_GREMLIN_SCRIPT_ENGINE, "gremlin-groovy"); } //Do not cache script compilations due to memory implications engine.getContext().setAttribute("#jsr223.groovy.engine.keep.globals", "phantom", ScriptContext.ENGINE_SCOPE); return engine; } @Override public void releaseGremlinScriptEngine(ScriptEngine scriptEngine) { // no action needed } @Override public Object executeGremlinScript(ScriptEngine scriptEngine, Map<? extends String, ? extends Object> userBindings, String query, boolean isPath) throws ScriptException { if (LOG.isDebugEnabled()) { LOG.debug("executeGremlinScript(query={}, userBindings={})", query, userBindings); } Bindings bindings = scriptEngine.createBindings(); if (userBindings != null) { bindings.putAll(userBindings); } bindings.put("g", getGraph()); Object result = scriptEngine.eval(query, bindings); return convertGremlinScriptResult(isPath, result); } private Object executeGremlinScript(String gremlinQuery) throws AtlasBaseException { Object result = null; ScriptEngine engine = getGremlinScriptEngine(); try { Bindings bindings = engine.createBindings(); bindings.put("g", getGraph()); result = engine.eval(gremlinQuery, bindings); } catch (ScriptException e) { throw new AtlasBaseException(AtlasErrorCode.GREMLIN_SCRIPT_EXECUTION_FAILED, gremlinQuery); } finally { releaseGremlinScriptEngine(engine); } return result; } @Override public GroovyExpression generatePersisentToLogicalConversionExpression(GroovyExpression expr, IDataType<?> type) { //nothing special needed, value is stored in required type return expr; } @Override public boolean isPropertyValueConversionNeeded(IDataType<?> type) { return false; } @Override public boolean requiresInitialIndexedPredicate() { return false; } @Override public GroovyExpression getInitialIndexedPredicate(GroovyExpression expr) { return expr; } @Override public GroovyExpression addOutputTransformationPredicate(GroovyExpression expr, boolean inSelect, boolean isPath) { return expr; } public Iterable<AtlasEdge<Titan0Vertex, Titan0Edge>> wrapEdges(Iterator<Edge> it) { Iterable<Edge> iterable = new IteratorToIterableAdapter<>(it); return wrapEdges(iterable); } public Iterable<AtlasVertex<Titan0Vertex, Titan0Edge>> wrapVertices(Iterator<Vertex> it) { Iterable<Vertex> iterable = new IteratorToIterableAdapter<>(it); return wrapVertices(iterable); } public Iterable<AtlasVertex<Titan0Vertex, Titan0Edge>> wrapVertices(Iterable<Vertex> it) { return Iterables.transform(it, new Function<Vertex, AtlasVertex<Titan0Vertex, Titan0Edge>>(){ @Override public AtlasVertex<Titan0Vertex, Titan0Edge> apply(Vertex input) { return GraphDbObjectFactory.createVertex(Titan0Graph.this, input); } }); } public Iterable<AtlasEdge<Titan0Vertex, Titan0Edge>> wrapEdges(Iterable<Edge> it) { Iterable<Edge> result = it; return Iterables.transform(result, new Function<Edge, AtlasEdge<Titan0Vertex, Titan0Edge>>(){ @Override public AtlasEdge<Titan0Vertex, Titan0Edge> apply(Edge input) { return GraphDbObjectFactory.createEdge(Titan0Graph.this, input); } }); } @Override public boolean isMultiProperty(String propertyName) { return multiProperties.contains(propertyName); } public void addMultiProperties(Set<String> names) { multiProperties.addAll(names); } } <|start_filename|>repository/src/main/java/org/apache/atlas/gremlin/optimizer/SplitPointFinder.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.gremlin.optimizer; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.atlas.gremlin.GremlinExpressionFactory; import org.apache.atlas.groovy.AbstractFunctionExpression; import org.apache.atlas.groovy.FunctionCallExpression; import org.apache.atlas.groovy.GroovyExpression; import org.apache.atlas.groovy.TraversalStepType; /** * This class finds the first place in the expression where the value of the * traverser is changed from being a vertex to being something else. This is * important in the "or" optimization logic, since the union operation must be * done on *vertices* in order to preserve the semantics of the query. In addition, * expressions that have side effects must be moved as well, so that those * side effects will be available to the steps that need them. */ public class SplitPointFinder implements CallHierarchyVisitor { //Any steps that change the traverser value to something that is not a vertex or edge //must be included here, so that the union created by ExpandOrsOptimization //is done over vertices/edges. private static final Set<TraversalStepType> TYPES_REQUIRED_IN_RESULT_EXPRESSION = new HashSet<>( Arrays.asList( TraversalStepType.BARRIER, TraversalStepType.BRANCH, TraversalStepType.SIDE_EFFECT, TraversalStepType.MAP_TO_VALUE, TraversalStepType.FLAT_MAP_TO_VALUES, TraversalStepType.END, TraversalStepType.NONE)); private final Set<String> requiredAliases = new HashSet<>(); //Exceptions to the requirement that all expressions with a type //in the above list must be in the result expression. If the //function name is in this list, it is ok for that expression //to not be in the result expression. This mechanism allows //aliases to remain outside the result expression. Other //exceptions may be found in the future. private static final Map<TraversalStepType, WhiteList> WHITE_LISTS = new HashMap<>(); static { WHITE_LISTS.put(TraversalStepType.SIDE_EFFECT, new WhiteList("as")); } private final GremlinExpressionFactory factory; public SplitPointFinder(GremlinExpressionFactory factory) { this.factory = factory; } /** * Represents a set of function names. */ private static final class WhiteList { private Set<String> allowedFunctionNames = new HashSet<>(); public WhiteList(String... names) { for(String name : names) { allowedFunctionNames.add(name); } } public boolean contains(String name) { return allowedFunctionNames.contains(name); } } private AbstractFunctionExpression splitPoint; @Override public boolean preVisitFunctionCaller(AbstractFunctionExpression expr) { requiredAliases.addAll(factory.getAliasesRequiredByExpression(expr)); return true; } @Override public void visitNonFunctionCaller(GroovyExpression expr) { } @Override public void visitNullCaller() { } public AbstractFunctionExpression getSplitPoint() { return splitPoint; } @Override public boolean postVisitFunctionCaller(AbstractFunctionExpression functionCall) { String aliasName = factory.getAliasNameIfRelevant(functionCall); if (splitPoint == null) { boolean required = isRequiredAlias(aliasName) || isRequiredInResultExpression(functionCall); if (required) { splitPoint = functionCall; } } removeSeenAlias(aliasName); return true; } private void removeSeenAlias(String aliasName) { if(aliasName != null) { requiredAliases.remove(aliasName); } } private boolean isRequiredAlias(String aliasName) { if(aliasName != null) { return requiredAliases.contains(aliasName); } return false; } private boolean isRequiredInResultExpression(AbstractFunctionExpression expr) { TraversalStepType type = expr.getType(); if (!TYPES_REQUIRED_IN_RESULT_EXPRESSION.contains(type)) { return false; } if(expr instanceof FunctionCallExpression) { FunctionCallExpression functionCall = (FunctionCallExpression)expr; //check if the white list permits this function call. If there is //no white list, all expressions with the current step type must go in the //result expression. WhiteList whiteList = WHITE_LISTS.get(type); if(whiteList != null && whiteList.contains(functionCall.getFunctionName())) { return false; } } return true; } } <|start_filename|>graphdb/titan1/src/main/java/org/apache/atlas/repository/graphdb/titan1/Titan1GraphDatabase.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan1; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import org.apache.atlas.ApplicationProperties; import org.apache.atlas.AtlasException; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.GraphDatabase; import org.apache.atlas.repository.graphdb.titan1.serializer.BigDecimalSerializer; import org.apache.atlas.repository.graphdb.titan1.serializer.BigIntegerSerializer; import org.apache.atlas.repository.graphdb.titan1.serializer.StringListSerializer; import org.apache.atlas.repository.graphdb.titan1.serializer.TypeCategorySerializer; import org.apache.atlas.typesystem.types.DataTypes.TypeCategory; import org.apache.commons.configuration.Configuration; import org.apache.tinkerpop.gremlin.groovy.loaders.SugarLoader; import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.thinkaurelius.titan.core.TitanFactory; import com.thinkaurelius.titan.core.TitanGraph; import com.thinkaurelius.titan.core.schema.TitanManagement; import com.thinkaurelius.titan.core.util.TitanCleanup; import com.thinkaurelius.titan.graphdb.tinkerpop.TitanIoRegistry; /** * Default implementation for Graph Provider that doles out Titan Graph. */ public class Titan1GraphDatabase implements GraphDatabase<Titan1Vertex, Titan1Edge> { private static final Logger LOG = LoggerFactory.getLogger(Titan1GraphDatabase.class); /** * Constant for the configuration property that indicates the prefix. */ public static final String GRAPH_PREFIX = "atlas.graph"; public static final String INDEX_BACKEND_CONF = "index.search.backend"; public static final String INDEX_BACKEND_LUCENE = "lucene"; public static final String INDEX_BACKEND_ES = "elasticsearch"; private static volatile Titan1Graph atlasGraphInstance = null; private static volatile TitanGraph graphInstance; public Titan1GraphDatabase() { //update registry GraphSONMapper.build().addRegistry(TitanIoRegistry.INSTANCE).create(); } public static Configuration getConfiguration() throws AtlasException { Configuration configProperties = ApplicationProperties.get(); Configuration titanConfig = ApplicationProperties.getSubsetConfiguration(configProperties, GRAPH_PREFIX); //add serializers for non-standard property value types that Atlas uses titanConfig.addProperty("attributes.custom.attribute1.attribute-class", TypeCategory.class.getName()); titanConfig.addProperty("attributes.custom.attribute1.serializer-class", TypeCategorySerializer.class.getName()); //not ideal, but avoids making large changes to Atlas titanConfig.addProperty("attributes.custom.attribute2.attribute-class", ArrayList.class.getName()); titanConfig.addProperty("attributes.custom.attribute2.serializer-class", StringListSerializer.class.getName()); titanConfig.addProperty("attributes.custom.attribute3.attribute-class", BigInteger.class.getName()); titanConfig.addProperty("attributes.custom.attribute3.serializer-class", BigIntegerSerializer.class.getName()); titanConfig.addProperty("attributes.custom.attribute4.attribute-class", BigDecimal.class.getName()); titanConfig.addProperty("attributes.custom.attribute4.serializer-class", BigDecimalSerializer.class.getName()); return titanConfig; } public static TitanGraph getGraphInstance() { if (graphInstance == null) { synchronized (Titan1GraphDatabase.class) { if (graphInstance == null) { Configuration config; try { config = getConfiguration(); } catch (AtlasException e) { throw new RuntimeException(e); } graphInstance = TitanFactory.open(config); atlasGraphInstance = new Titan1Graph(); validateIndexBackend(config); } } } return graphInstance; } public static void unload() { synchronized (Titan1GraphDatabase.class) { if (graphInstance == null) { return; } graphInstance.tx().commit(); graphInstance.close(); graphInstance = null; } } static void validateIndexBackend(Configuration config) { String configuredIndexBackend = config.getString(INDEX_BACKEND_CONF); TitanManagement managementSystem = getGraphInstance().openManagement(); String currentIndexBackend = managementSystem.get(INDEX_BACKEND_CONF); managementSystem.commit(); if (!configuredIndexBackend.equals(currentIndexBackend)) { throw new RuntimeException("Configured Index Backend " + configuredIndexBackend + " differs from earlier configured Index Backend " + currentIndexBackend + ". Aborting!"); } } @Override public boolean isGraphLoaded() { return graphInstance != null; } @Override public void initializeTestGraph() { //nothing to do } @Override public void cleanup() { try { getGraphInstance().close(); } catch (Throwable t) { LOG.warn("Could not close test TitanGraph", t); t.printStackTrace(); } try { TitanCleanup.clear(getGraphInstance()); } catch (Throwable t) { LOG.warn("Could not clear test TitanGraph", t); t.printStackTrace(); } } @Override public AtlasGraph<Titan1Vertex, Titan1Edge> getGraph() { getGraphInstance(); return atlasGraphInstance; } } <|start_filename|>webapp/src/main/java/org/apache/atlas/web/resources/BaseService.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.web.resources; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import org.apache.atlas.catalog.JsonSerializer; import org.apache.atlas.catalog.Request; import org.apache.atlas.catalog.ResourceProvider; import org.apache.atlas.catalog.Result; import org.apache.atlas.catalog.exception.CatalogException; import org.apache.atlas.catalog.exception.CatalogRuntimeException; import org.apache.atlas.catalog.exception.InvalidPayloadException; import org.apache.atlas.catalog.exception.InvalidQueryException; import org.apache.atlas.catalog.exception.ResourceNotFoundException; import org.apache.atlas.repository.graph.AtlasGraphProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import javax.xml.bind.annotation.XmlRootElement; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Collection; import java.util.Map; /** * Base class for all v1 API services. */ public abstract class BaseService { private static final Gson gson = new Gson(); private final Logger LOG = LoggerFactory.getLogger(getClass()); private final static JsonSerializer serializer = new JsonSerializer(); protected Result getResource(ResourceProvider provider, Request request) throws ResourceNotFoundException { try { return provider.getResourceById(request); } catch (RuntimeException e) { throw wrapRuntimeException(e); } } protected Result getResources(ResourceProvider provider, Request request) throws ResourceNotFoundException, InvalidQueryException { try { return provider.getResources(request); } catch (RuntimeException e) { LOG.error("Error while retrieving taxonomy ", e); throw wrapRuntimeException(e); } } protected void createResource(ResourceProvider provider, Request request) throws CatalogException { try { provider.createResource(request); } catch (RuntimeException e) { throw wrapRuntimeException(e); } } protected void updateResource(ResourceProvider provider, Request request) throws CatalogException { try { provider.updateResourceById(request); } catch (RuntimeException e) { throw wrapRuntimeException(e); } } protected void deleteResource(ResourceProvider provider, Request request) throws CatalogException { try { provider.deleteResourceById(request); } catch (RuntimeException e) { throw wrapRuntimeException(e); } } protected Collection<String> createResources(ResourceProvider provider, Request request) throws CatalogException { try { return provider.createResources(request); } catch (RuntimeException e) { throw wrapRuntimeException(e); } } protected String getQueryString(@Context UriInfo ui) { String uri = ui.getRequestUri().toASCIIString(); int qsBegin = uri.indexOf("?"); return (qsBegin == -1) ? null : uri.substring(qsBegin + 1); } protected <T extends Map> T parsePayload(String body) throws InvalidPayloadException { T properties; try { properties = gson.<T>fromJson(body, Map.class); } catch (JsonSyntaxException e) { LOG.info("Unable to parse json in request body", e); throw new InvalidPayloadException("Request payload contains invalid JSON: " + e.getMessage()); } return properties; } protected String decode(String s) throws CatalogException { try { return s == null ? null : URLDecoder.decode(s, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new CatalogException("Unable to decode URL: " + e.getMessage(), 500); } } protected JsonSerializer getSerializer() { return serializer; } private RuntimeException wrapRuntimeException(RuntimeException e) { return e instanceof CatalogRuntimeException ? e : new CatalogRuntimeException(e); } @XmlRootElement // the name of this class is used as the collection name in the returned json when returning a collection public static class Results { public String href; public int status; public Results() { // required by JAXB } public Results(String href, int status) { this.href = href; this.status = status; } } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/typestore/StoreBackedTypeCache.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.typestore; import com.google.common.collect.ImmutableList; import org.apache.atlas.AtlasException; import org.apache.atlas.annotation.ConditionalOnAtlasProperty; import org.apache.atlas.typesystem.TypesDef; import org.apache.atlas.typesystem.types.AttributeDefinition; import org.apache.atlas.typesystem.types.ClassType; import org.apache.atlas.typesystem.types.EnumTypeDefinition; import org.apache.atlas.typesystem.types.HierarchicalTypeDefinition; import org.apache.atlas.typesystem.types.IDataType; import org.apache.atlas.typesystem.types.StructTypeDefinition; import org.apache.atlas.typesystem.types.TraitType; import org.apache.atlas.typesystem.types.TypeSystem; import org.apache.atlas.typesystem.types.TypeSystem.TransientTypeSystem; import org.apache.atlas.typesystem.types.TypeUtils; import org.apache.atlas.typesystem.types.cache.DefaultTypeCache; import org.apache.atlas.typesystem.types.utils.TypesUtil; import org.springframework.stereotype.Component; import javax.inject.Inject; import javax.inject.Singleton; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * An extension of {@link DefaultTypeCache} which loads * the requested type from the type store if it is not found in the cache, * and adds it to the cache if it's found in the store. * Any attribute and super types that are required by the requested type * are also loaded from the store if they are not already in the cache. */ @Singleton @Component @Deprecated @ConditionalOnAtlasProperty(property = "atlas.TypeCache.impl") public class StoreBackedTypeCache extends DefaultTypeCache { private ITypeStore typeStore; private ImmutableList<String> coreTypes; private TypeSystem typeSystem; @Inject public StoreBackedTypeCache(final ITypeStore typeStore) { this.typeStore = typeStore; typeSystem = TypeSystem.getInstance(); coreTypes = typeSystem.getCoreTypes(); } private static class Context { ImmutableList.Builder<EnumTypeDefinition> enums = ImmutableList.builder(); ImmutableList.Builder<StructTypeDefinition> structs = ImmutableList.builder(); ImmutableList.Builder<HierarchicalTypeDefinition<ClassType>> classTypes = ImmutableList.builder(); ImmutableList.Builder<HierarchicalTypeDefinition<TraitType>> traits = ImmutableList.builder(); Set<String> loadedFromStore = new HashSet<>(); public void addTypesDefToLists(TypesDef typesDef) { List<EnumTypeDefinition> enumTypesAsJavaList = typesDef.enumTypesAsJavaList(); enums.addAll(enumTypesAsJavaList); for (EnumTypeDefinition etd : enumTypesAsJavaList) { loadedFromStore.add(etd.name); } List<StructTypeDefinition> structTypesAsJavaList = typesDef.structTypesAsJavaList(); structs.addAll(structTypesAsJavaList); for (StructTypeDefinition std : structTypesAsJavaList) { loadedFromStore.add(std.typeName); } List<HierarchicalTypeDefinition<ClassType>> classTypesAsJavaList = typesDef.classTypesAsJavaList(); classTypes.addAll(classTypesAsJavaList); for (HierarchicalTypeDefinition<ClassType> classTypeDef : classTypesAsJavaList) { loadedFromStore.add(classTypeDef.typeName); } List<HierarchicalTypeDefinition<TraitType>> traitTypesAsJavaList = typesDef.traitTypesAsJavaList(); traits.addAll(traitTypesAsJavaList); for (HierarchicalTypeDefinition<TraitType> traitTypeDef : traitTypesAsJavaList) { loadedFromStore.add(traitTypeDef.typeName); } } public boolean isLoadedFromStore(String typeName) { return loadedFromStore.contains(typeName); } public TypesDef getTypesDef() { return TypesUtil.getTypesDef(enums.build(), structs.build(), traits.build(), classTypes.build()); } } /** * Checks whether the specified type is cached in memory and does *not* * access the type store. Used for testing. * * @param typeName * @return */ public boolean isCachedInMemory(String typeName) throws AtlasException { return super.has(typeName); } /** * Check the type store for the requested type. * If found in the type store, the type and any required super and attribute types * are loaded from the type store, and added to the cache. */ @Override public IDataType onTypeFault(String typeName) throws AtlasException { // Type is not cached - check the type store. // Any super and attribute types needed by the requested type // which are not cached will also be loaded from the store. Context context = new Context(); TypesDef typesDef = getTypeFromStore(typeName, context); if (typesDef.isEmpty()) { // Type not found in the type store. return null; } // Add all types that were loaded from the store to the cache. TransientTypeSystem transientTypeSystem = typeSystem.createTransientTypeSystem(context.getTypesDef(), false); Map<String, IDataType> typesAdded = transientTypeSystem.getTypesAdded(); putAll(typesAdded.values()); return typesAdded.get(typeName); } private void getTypeFromCacheOrStore(String typeName, Context context) throws AtlasException { if (coreTypes.contains(typeName) || super.has(typeName)) { return; } if (context.isLoadedFromStore(typeName)) { return; } // Type not cached and hasn't been loaded during this operation, so check the store. TypesDef typesDef = getTypeFromStore(typeName, context); if (typesDef.isEmpty()) { // Attribute type not found in cache or store. throw new AtlasException(typeName + " not found in type store"); } } private TypesDef getTypeFromStore(String typeName, Context context) throws AtlasException { TypesDef typesDef = typeStore.restoreType(typeName); if (!typesDef.isEmpty()) { // Type found in store, add it to lists. context.addTypesDefToLists(typesDef); // Check the attribute and super types that are // used by the requested type, and restore them // as needed. checkAttributeAndSuperTypes(typesDef, context); } return typesDef; } private void checkAttributeAndSuperTypes(TypesDef typesDef, Context context) throws AtlasException { // Check the cache and store for attribute types and super types. for (HierarchicalTypeDefinition<ClassType> classTypeDef : typesDef.classTypesAsJavaList()) { checkAttributeTypes(classTypeDef.attributeDefinitions, context); for (String superTypeName : classTypeDef.superTypes) { getTypeFromCacheOrStore(superTypeName, context); } } for (HierarchicalTypeDefinition<TraitType> traitTypeDef : typesDef.traitTypesAsJavaList()) { checkAttributeTypes(traitTypeDef.attributeDefinitions, context); for (String superTypeName : traitTypeDef.superTypes) { getTypeFromCacheOrStore(superTypeName, context); } } for (StructTypeDefinition structTypeDef : typesDef.structTypesAsJavaList()) { checkAttributeTypes(structTypeDef.attributeDefinitions, context); } } private void checkAttributeTypes(AttributeDefinition[] attributeDefinitions, Context context) throws AtlasException { for (AttributeDefinition attrDef : attributeDefinitions) { checkAttributeType(attrDef, context); } } private void checkAttributeType(AttributeDefinition attrDef, Context context) throws AtlasException { List<String> typeNamesToLookup = new ArrayList<>(2); // Get the attribute type(s). String elementTypeName = TypeUtils.parseAsArrayType(attrDef.dataTypeName); if (elementTypeName != null) { // Array attribute, lookup the element type. typeNamesToLookup.add(elementTypeName); } else { String[] mapTypeNames = TypeUtils.parseAsMapType(attrDef.dataTypeName); if (mapTypeNames != null) { // Map attribute, lookup the key and value types. typeNamesToLookup.addAll(Arrays.asList(mapTypeNames)); } else { // Not an array or map, lookup the attribute type. typeNamesToLookup.add(attrDef.dataTypeName); } } for (String typeName : typeNamesToLookup) { getTypeFromCacheOrStore(typeName, context); } } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/memory/StructStore.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.memory; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableMap; import org.apache.atlas.repository.RepositoryException; import org.apache.atlas.typesystem.persistence.StructInstance; import org.apache.atlas.typesystem.types.AttributeInfo; import org.apache.atlas.typesystem.types.StructType; import java.util.Collection; import java.util.Map; @Deprecated public class StructStore extends AttributeStores.AbstractAttributeStore implements IAttributeStore { final StructType structType; final ImmutableMap<AttributeInfo, IAttributeStore> attrStores; StructStore(AttributeInfo aInfo) throws RepositoryException { super(aInfo); this.structType = (StructType) aInfo.dataType(); ImmutableMap.Builder<AttributeInfo, IAttributeStore> b = new ImmutableBiMap.Builder<>(); Collection<AttributeInfo> l = structType.fieldMapping.fields.values(); for (AttributeInfo i : l) { b.put(i, AttributeStores.createStore(i)); } attrStores = b.build(); } @Override protected void store(StructInstance instance, int colPos, int pos) throws RepositoryException { StructInstance s = instance.structs[colPos]; for (Map.Entry<AttributeInfo, IAttributeStore> e : attrStores.entrySet()) { IAttributeStore attributeStore = e.getValue(); attributeStore.store(pos, structType, s); } } @Override protected void load(StructInstance instance, int colPos, int pos) throws RepositoryException { StructInstance s = (StructInstance) structType.createInstance(); instance.structs[colPos] = s; for (Map.Entry<AttributeInfo, IAttributeStore> e : attrStores.entrySet()) { IAttributeStore attributeStore = e.getValue(); attributeStore.load(pos, structType, s); } } @Override protected void store(StructInstance instance, int colPos, String attrName, Map<String, Object> m) { m.put(attrName, instance.structs[colPos]); } @Override protected void load(StructInstance instance, int colPos, Object val) { instance.structs[colPos] = (StructInstance) val; } @Override public void ensureCapacity(int pos) throws RepositoryException { for (Map.Entry<AttributeInfo, IAttributeStore> e : attrStores.entrySet()) { IAttributeStore attributeStore = e.getValue(); attributeStore.ensureCapacity(pos); } nullList.size(pos + 1); } } <|start_filename|>repository/src/main/java/org/apache/atlas/util/CompiledQueryCacheKey.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.util; import org.apache.atlas.query.QueryParams; /** * Represents a key for an entry in the compiled query cache. * */ public class CompiledQueryCacheKey { private final String dslQuery; private final QueryParams queryParams; public CompiledQueryCacheKey(String dslQuery, QueryParams queryParams) { super(); this.dslQuery = dslQuery; this.queryParams = queryParams; } public CompiledQueryCacheKey(String dslQuery) { super(); this.dslQuery = dslQuery; this.queryParams = null; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((dslQuery == null) ? 0 : dslQuery.hashCode()); result = prime * result + ((queryParams == null) ? 0 : queryParams.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof CompiledQueryCacheKey)) { return false; } CompiledQueryCacheKey other = (CompiledQueryCacheKey) obj; if (! equals(dslQuery, other.dslQuery)) { return false; } if (! equals(queryParams, other.queryParams)) { return false; } return true; } private static boolean equals(Object o1, Object o2) { if(o1 == o2) { return true; } if(o1 == null) { return o2 == null; } return o1.equals(o2); } } <|start_filename|>repository/src/test/java/org/apache/atlas/discovery/GraphBackedDiscoveryServiceTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.discovery; import com.google.common.collect.ImmutableSet; import org.apache.atlas.AtlasException; import org.apache.atlas.BaseRepositoryTest; import org.apache.atlas.RequestContext; import org.apache.atlas.TestModules; import org.apache.atlas.TestUtils; import org.apache.atlas.discovery.graph.GraphBackedDiscoveryService; import org.apache.atlas.query.QueryParams; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.MetadataRepository; import org.apache.atlas.repository.graph.AtlasGraphProvider; import org.apache.atlas.repository.graph.GraphBackedSearchIndexer; import org.apache.atlas.repository.graphdb.GremlinVersion; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.persistence.Id; import org.apache.atlas.typesystem.types.ClassType; import org.apache.atlas.typesystem.types.DataTypes; import org.apache.atlas.typesystem.types.HierarchicalTypeDefinition; import org.apache.atlas.typesystem.types.IDataType; import org.apache.atlas.typesystem.types.Multiplicity; import org.apache.atlas.typesystem.types.TypeSystem; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Guice; import org.testng.annotations.Test; import javax.inject.Inject; import java.text.SimpleDateFormat; import java.util.*; import static org.apache.atlas.typesystem.types.utils.TypesUtil.createClassTypeDef; import static org.apache.atlas.typesystem.types.utils.TypesUtil.createOptionalAttrDef; import static org.apache.atlas.typesystem.types.utils.TypesUtil.createRequiredAttrDef; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; @Guice(modules = TestModules.TestOnlyModule.class) public class GraphBackedDiscoveryServiceTest extends BaseRepositoryTest { @Inject private MetadataRepository repositoryService; @Inject private GraphBackedDiscoveryService discoveryService; private QueryParams queryParams = new QueryParams(40, 0); private static final String idType = "idType"; @Override @BeforeClass public void setUp() throws Exception { super.setUp(); repositoryService = TestUtils.addTransactionWrapper(repositoryService); final TypeSystem typeSystem = TypeSystem.getInstance(); Collection<String> oldTypeNames = new HashSet<>(); oldTypeNames.addAll(typeSystem.getTypeNames()); TestUtils.defineDeptEmployeeTypes(typeSystem); addIndexesForNewTypes(oldTypeNames, typeSystem); ITypedReferenceableInstance hrDept = TestUtils.createDeptEg1(typeSystem); repositoryService.createEntities(hrDept); ITypedReferenceableInstance jane = repositoryService.getEntityDefinition("Manager", "name", "Jane"); Id janeGuid = jane.getId(); ClassType personType = typeSystem.getDataType(ClassType.class, "Person"); ITypedReferenceableInstance instance = personType.createInstance(janeGuid); instance.set("orgLevel", "L1"); repositoryService.updatePartial(instance); } private void addIndexesForNewTypes(Collection<String> oldTypeNames, final TypeSystem typeSystem) throws AtlasException { Set<String> newTypeNames = new HashSet<>(); newTypeNames.addAll(typeSystem.getTypeNames()); newTypeNames.removeAll(oldTypeNames); Collection<IDataType> newTypes = new ArrayList<>(); for(String name : newTypeNames) { try { newTypes.add(typeSystem.getDataType(IDataType.class, name)); } catch (AtlasException e) { e.printStackTrace(); } } //We need to commit the transaction before creating the indices to release the locks held by the transaction. //otherwise, the index commit will fail while waiting for the those locks to be released. AtlasGraphProvider.getGraphInstance().commit(); GraphBackedSearchIndexer idx = new GraphBackedSearchIndexer(new AtlasTypeRegistry()); idx.onAdd(newTypes); } @BeforeMethod public void setupContext() { RequestContext.createContext(); } @AfterClass public void tearDown() throws Exception { super.tearDown(); } private String searchByDSL(String dslQuery) throws Exception { return discoveryService.searchByDSL(dslQuery, queryParams); } @Test public void testSearchBySystemProperties() throws Exception { //system property in select String dslQuery = "from Department select __guid"; String jsonResults = searchByDSL(dslQuery); assertNotNull(jsonResults); JSONObject results = new JSONObject(jsonResults); assertEquals(results.length(), 3); JSONArray rows = results.getJSONArray("rows"); assertNotNull(rows); assertEquals(rows.length(), 1); assertNotNull(rows.getJSONObject(0).getString("__guid")); //system property in where clause String guid = rows.getJSONObject(0).getString("__guid"); dslQuery = "Department where __guid = '" + guid + "' and __state = 'ACTIVE'"; jsonResults = searchByDSL(dslQuery); assertNotNull(jsonResults); results = new JSONObject(jsonResults); assertEquals(results.length(), 3); rows = results.getJSONArray("rows"); assertNotNull(rows); assertEquals(rows.length(), 1); //Assert system attributes are not null JSONObject sys_attributes = (JSONObject)rows.getJSONObject(0).get("$systemAttributes$"); assertNotNull(sys_attributes.get("createdBy")); assertNotNull(sys_attributes.get("modifiedBy")); assertNotNull(sys_attributes.get("createdTime")); assertNotNull(sys_attributes.get("modifiedTime")); //Assert that createdTime and modifiedTime are valid dates String createdTime = (String) sys_attributes.get("createdTime"); String modifiedTime = (String) sys_attributes.get("modifiedTime"); final String outputFormat = "EEE MMM dd HH:mm:ss z yyyy"; SimpleDateFormat df = new SimpleDateFormat(outputFormat); Date createdDate = df.parse(createdTime); Date modifiedDate = df.parse(modifiedTime); assertNotNull(createdDate); assertNotNull(modifiedDate); final String testTs = "\"2011-11-01T02:35:58.440Z\""; dslQuery = "Department where " + Constants.TIMESTAMP_PROPERTY_KEY + " > " + testTs; jsonResults = searchByDSL(dslQuery); assertNotNull(jsonResults); results = new JSONObject(jsonResults); assertEquals(results.length(), 3); rows = results.getJSONArray("rows"); assertNotNull(rows); assertEquals(rows.length(), 1); dslQuery = "Department where " + Constants.MODIFICATION_TIMESTAMP_PROPERTY_KEY + " > " + testTs; jsonResults = searchByDSL(dslQuery); assertNotNull(jsonResults); results = new JSONObject(jsonResults); assertEquals(results.length(), 3); rows = results.getJSONArray("rows"); assertNotNull(rows); assertEquals(rows.length(), 1); dslQuery = "from Department select " + Constants.CREATED_BY_KEY; jsonResults = searchByDSL(dslQuery); assertNotNull(jsonResults); results = new JSONObject(jsonResults); assertEquals(results.length(), 3); rows = results.getJSONArray("rows"); assertNotNull(rows); assertEquals(rows.length(), 1); dslQuery = "from Department select " + Constants.MODIFIED_BY_KEY; jsonResults = searchByDSL(dslQuery); assertNotNull(jsonResults); results = new JSONObject(jsonResults); assertEquals(results.length(), 3); rows = results.getJSONArray("rows"); assertNotNull(rows); assertEquals(rows.length(), 1); } /* * https://issues.apache.org/jira/browse/ATLAS-1875 */ @Test public void testGremlinSearchReturnVertexId() throws Exception { List<Map<String,String>> gremlinResults = discoveryService.searchByGremlin("g.V.range(0,0).collect()"); assertEquals(gremlinResults.size(), 1); Map<String, String> properties = gremlinResults.get(0); Assert.assertTrue(properties.containsKey(GraphBackedDiscoveryService.GREMLIN_ID_KEY)); } /* * https://issues.apache.org/jira/browse/ATLAS-1875 */ @Test public void testGremlinSearchReturnEdgeIds() throws Exception { List<Map<String,String>> gremlinResults = discoveryService.searchByGremlin("g.E.range(0,0).collect()"); assertEquals(gremlinResults.size(), 1); Map<String, String> properties = gremlinResults.get(0); Assert.assertTrue(properties.containsKey(GraphBackedDiscoveryService.GREMLIN_INVERTEX_KEY)); Assert.assertTrue(properties.containsKey(GraphBackedDiscoveryService.GREMLIN_OUTVERTEX_KEY)); Assert.assertTrue(properties.containsKey(GraphBackedDiscoveryService.GREMLIN_LABEL_KEY)); } @Test public void testSearchByDSLReturnsEntity() throws Exception { String dslQuery = "from Department"; String jsonResults = searchByDSL(dslQuery); assertNotNull(jsonResults); JSONObject results = new JSONObject(jsonResults); assertEquals(results.length(), 3); System.out.println("results = " + results); Object query = results.get("query"); assertNotNull(query); JSONObject dataType = results.getJSONObject("dataType"); assertNotNull(dataType); String typeName = dataType.getString("typeName"); assertNotNull(typeName); assertEquals(typeName, "Department"); JSONArray rows = results.getJSONArray("rows"); assertNotNull(rows); assertEquals(rows.length(), 1); //Assert that entity state is set in the result entities String entityState = rows.getJSONObject(0).getJSONObject("$id$").getString("state"); assertEquals(entityState, Id.EntityState.ACTIVE.name()); } @DataProvider(name = "dslLikeQueriesProvider") private Object[][] createDslLikeQueries() { return new Object[][]{ {"hive_table where name like \"sa?es*\"", 3}, {"hive_db where name like \"R*\"", 1}, {"hive_db where hive_db.name like \"R???rt?*\" or hive_db.name like \"S?l?s\" or hive_db.name like\"Log*\"", 3}, {"hive_db where hive_db.name like \"R???rt?*\" and hive_db.name like \"S?l?s\" and hive_db.name like\"Log*\"", 0}, {"hive_table where name like 'sales*', db where name like 'Sa?es'", 1}, {"hive_table where name like 'sales*' and db.name like 'Sa?es'", 1}, {"hive_table where db.name like \"Sa*\"", 4}, {"hive_table where db.name like \"Sa*\" and name like \"*dim\"", 3}, }; } @Test(dataProvider = "dslLikeQueriesProvider") public void testDslSearchUsingLikeOperator(String dslQuery, Integer expectedNumRows) throws Exception { runQuery(dslQuery, expectedNumRows, 50, 0); } @Test(expectedExceptions = Throwable.class) public void testSearchByDSLBadQuery() throws Exception { String dslQuery = "from blah"; searchByDSL(dslQuery); Assert.fail(); } @Test public void testRawSearch1() throws Exception { TestUtils.skipForGremlin3EnabledGraphDb(); // Query for all Vertices in Graph Object r = discoveryService.searchByGremlin("g.V.toList()"); Assert.assertTrue(r instanceof List); List<Map<String, Object>> resultList = (List<Map<String, Object>>) r; Assert.assertTrue(resultList.size() > 0); System.out.println("search result = " + r); // Query for all Vertices of a Type r = discoveryService.searchByGremlin("g.V.filter{it." + Constants.ENTITY_TYPE_PROPERTY_KEY + " == 'Department'}.toList()"); Assert.assertTrue(r instanceof List); resultList = (List<Map<String, Object>>) r; Assert.assertTrue(resultList.size() > 0); System.out.println("search result = " + r); // Property Query: list all Person names r = discoveryService.searchByGremlin("g.V.filter{it." + Constants.ENTITY_TYPE_PROPERTY_KEY + " == 'Person'}.'Person.name'.toList()"); Assert.assertTrue(r instanceof List); resultList = (List<Map<String, Object>>) r; Assert.assertTrue(resultList.size() > 0); System.out.println("search result = " + r); List<Object> names = new ArrayList<>(resultList.size()); for (Map<String, Object> vertexProps : resultList) { names.addAll(vertexProps.values()); } for (String name : Arrays.asList("John", "Max")) { Assert.assertTrue(names.contains(name)); } // Query for all Vertices modified after 01/01/2015 00:00:00 GMT r = discoveryService.searchByGremlin("g.V.filter{it." + Constants.MODIFICATION_TIMESTAMP_PROPERTY_KEY + " > 1420070400000}.toList()"); Assert.assertTrue(r instanceof List); resultList = (List<Map<String, Object>>) r; Assert.assertTrue(resultList.size() > 0); for (Map<String, Object> vertexProps : resultList) { Object object = vertexProps.get(Constants.MODIFICATION_TIMESTAMP_PROPERTY_KEY); assertNotNull(object); Long timestampAsLong = Long.valueOf((String)object); Assert.assertTrue(timestampAsLong > 1420070400000L); object = vertexProps.get(Constants.TIMESTAMP_PROPERTY_KEY); assertNotNull(object); } } @DataProvider(name = "comparisonQueriesProvider") private Object[][] createComparisonQueries() { //create queries the exercise the comparison logic for //all of the different supported data types return new Object[][] { {"Person where (birthday < \"1950-01-01T02:35:58.440Z\" )", 0}, {"Person where (birthday > \"1975-01-01T02:35:58.440Z\" )", 2}, {"Person where (birthday >= \"1975-01-01T02:35:58.440Z\" )", 2}, {"Person where (birthday <= \"1950-01-01T02:35:58.440Z\" )", 0}, {"Person where (birthday = \"1975-01-01T02:35:58.440Z\" )", 0}, {"Person where (birthday != \"1975-01-01T02:35:58.440Z\" )", 4}, {"Person where (hasPets = true)", 2}, {"Person where (hasPets = false)", 2}, {"Person where (hasPets != false)", 2}, {"Person where (hasPets != true)", 2}, {"Person where (numberOfCars > 0)", 2}, {"Person where (numberOfCars > 1)", 1}, {"Person where (numberOfCars >= 1)", 2}, {"Person where (numberOfCars < 2)", 3}, {"Person where (numberOfCars <= 2)", 4}, {"Person where (numberOfCars = 2)", 1}, {"Person where (numberOfCars != 2)", 3}, {"Person where (houseNumber > 0)", 2}, {"Person where (houseNumber > 17)", 1}, {"Person where (houseNumber >= 17)", 2}, {"Person where (houseNumber < 153)", 3}, {"Person where (houseNumber <= 153)", 4}, {"Person where (houseNumber = 17)", 1}, {"Person where (houseNumber != 17)", 3}, {"Person where (carMileage > 0)", 2}, {"Person where (carMileage > 13)", 1}, {"Person where (carMileage >= 13)", 2}, {"Person where (carMileage < 13364)", 3}, {"Person where (carMileage <= 13364)", 4}, {"Person where (carMileage = 13)", 1}, {"Person where (carMileage != 13)", 3}, {"Person where (shares > 0)", 2}, {"Person where (shares > 13)", 2}, {"Person where (shares >= 16000)", 1}, {"Person where (shares < 13364)", 2}, {"Person where (shares <= 15000)", 3}, {"Person where (shares = 15000)", 1}, {"Person where (shares != 1)", 4}, {"Person where (salary > 0)", 2}, {"Person where (salary > 100000)", 2}, {"Person where (salary >= 200000)", 1}, {"Person where (salary < 13364)", 2}, {"Person where (salary <= 150000)", 3}, {"Person where (salary = 12334)", 0}, {"Person where (salary != 12344)", 4}, {"Person where (age > 36)", 1}, {"Person where (age > 49)", 1}, {"Person where (age >= 49)", 1}, {"Person where (age < 50)", 3}, {"Person where (age <= 35)", 2}, {"Person where (age = 35)", 0}, {"Person where (age != 35)", 4} }; } @DataProvider(name = "dslQueriesProvider") private Object[][] createDSLQueries() { return new Object[][]{ {"hive_db as inst where inst.name=\"Reporting\" select inst as id, inst.name", 1}, {"from hive_db as h select h as id", 3}, {"from hive_db", 3}, {"hive_db", 3}, {"hive_db where hive_db.name=\"Reporting\"", 1}, {"hive_db hive_db.name = \"Reporting\"", 1}, {"hive_db where hive_db.name=\"Reporting\" select name, owner", 1}, {"hive_db has name", 3}, {"hive_db, hive_table", 10}, {"View is JdbcAccess", 2}, {"hive_db as db1, hive_table where db1.name = \"Reporting\"", isGremlin3() ? 4 : 0}, //Not working in with Titan 0 - ATLAS-145 // - Final working query -> discoveryService.searchByGremlin("L:{_var_0 = [] as Set;g.V().has(\"__typeName\", \"hive_db\").fill(_var_0);g.V().has(\"__superTypeNames\", \"hive_db\").fill(_var_0);_var_0._().as(\"db1\").in(\"__hive_table.db\").back(\"db1\").and(_().has(\"hive_db.name\", T.eq, \"Reporting\")).toList()}") /* {"hive_db, hive_process has name"}, //Invalid query {"hive_db where hive_db.name=\"Reporting\" and hive_db.createTime < " + System.currentTimeMillis()} */ {"from hive_table", 10}, {"hive_table", 10}, {"hive_table isa Dimension", 3}, {"hive_column where hive_column isa PII", 8}, {"View is Dimension" , 2}, // {"hive_column where hive_column isa PII select hive_column.name", 6}, //Not working - ATLAS-175 {"hive_column select hive_column.name", 37}, {"hive_column select name",37}, {"hive_column where hive_column.name=\"customer_id\"", 6}, {"from hive_table select hive_table.name", 10}, {"hive_db where (name = \"Reporting\")", 1}, {"hive_db where (name = \"Reporting\") select name as _col_0, owner as _col_1", 1}, {"hive_db where hive_db is JdbcAccess", 0}, //Not supposed to work {"hive_db hive_table", 10}, {"hive_db where hive_db has name", 3}, {"hive_db as db1 hive_table where (db1.name = \"Reporting\")", isGremlin3() ? 4 : 0}, //Not working in Titan 0 -> ATLAS-145 {"hive_db where (name = \"Reporting\") select name as _col_0, (createTime + 1) as _col_1 ", 1}, {"hive_table where (name = \"sales_fact\" and createTime > \"2014-01-01\" ) select name as _col_0, createTime as _col_1 ", 1}, {"hive_table where (name = \"sales_fact\" and createTime >= \"2014-12-11T02:35:58.440Z\" ) select name as _col_0, createTime as _col_1 ", 1}, /* todo: does not work - ATLAS-146 {"hive_db where (name = \"Reporting\") and ((createTime + 1) > 0)"}, {"hive_db as db1 hive_table as tab where ((db1.createTime + 1) > 0) and (db1.name = \"Reporting\") select db1.name as dbName, tab.name as tabName"}, {"hive_db as db1 hive_table as tab where ((db1.createTime + 1) > 0) or (db1.name = \"Reporting\") select db1.name as dbName, tab.name as tabName"}, {"hive_db as db1 hive_table as tab where ((db1.createTime + 1) > 0) and (db1.name = \"Reporting\") or db1 has owner select db1.name as dbName, tab.name as tabName"}, {"hive_db as db1 hive_table as tab where ((db1.createTime + 1) > 0) and (db1.name = \"Reporting\") or db1 has owner select db1.name as dbName, tab.name as tabName"}, */ // trait searches {"Dimension", 5}, {"JdbcAccess", 2}, {"ETL", 5}, {"Metric", 9}, {"PII", 8}, {"`Log Data`", 4}, // Not sure what the expected rows should be, but since we didn't assign or do anything with the created // I assume it'll be zero {"`isa`", 0}, /* Lineage queries are fired through ClosureQuery and are tested through HiveLineageJerseyResourceIt in webapp module. Commenting out the below queries since DSL to Gremlin parsing/translation fails with lineage queries when there are array types used within loop expressions which is the case with DataSet.inputs and outputs.` // Lineage {"Table LoadProcess outputTable"}, {"Table loop (LoadProcess outputTable)"}, {"Table as _loop0 loop (LoadProcess outputTable) withPath"}, {"Table as src loop (LoadProcess outputTable) as dest select src.name as srcTable, dest.name as " + "destTable withPath"}, */ // {"hive_table as t, sd, hive_column as c where t.name=\"sales_fact\" select c.name as colName, c.dataType as " // + "colType", 0}, //Not working - ATLAS-145 and ATLAS-166 {"hive_table where name='sales_fact', db where name='Sales'", 1}, {"hive_table where name='sales_fact', db where name='Reporting'", 0}, {"hive_partition as p where values = ['2015-01-01']", 1}, // {"StorageDesc select cols", 6} //Not working since loading of lists needs to be fixed yet //check supertypeNames {"DataSet where name='sales_fact'", 1}, {"Asset where name='sales_fact'", 1} }; } @DataProvider(name = "dslExplicitLimitQueriesProvider") private Object[][] createDSLQueriesWithExplicitLimit() { return new Object[][]{ {"hive_column", 37, 40, 0},//with higher limit all rows returned {"hive_column limit 10", 10, 50, 0},//lower limit in query {"hive_column select hive_column.name limit 10", 5, 5, 0},//lower limit in query param {"hive_column select hive_column.name withPath", 20, 20, 0},//limit only in params //with offset, only remaining rows returned {"hive_column select hive_column.name limit 40 withPath", 17, 40, 20}, //with higher offset, no rows returned {"hive_column select hive_column.name limit 40 withPath", 0, 40, 40}, //offset used from query {"hive_column select hive_column.name limit 40 offset 10", 27, 40, 0}, //offsets in query and parameter added up {"hive_column select hive_column.name limit 40 offset 10", 17, 40, 10}, //works with where clause {"hive_db where name = 'Reporting' limit 10 offset 0", 1, 40, 0}, //works with joins {"hive_db, hive_table where db.name = 'Reporting' limit 10", 1, 1, 0}, {"hive_column limit 25", 5, 10, 20}, //last page should return records limited by limit in query {"hive_column limit 25", 0, 10, 30}, //offset > limit returns 0 rows }; } @DataProvider(name = "dslLimitQueriesProvider") private Object[][] createDSLQueriesWithLimit() { return new Object[][]{ {"hive_column limit 10 ", 10}, {"hive_column select hive_column.name limit 10 ", 10}, {"hive_column select hive_column.name withPath", 37}, {"hive_column select hive_column.name limit 10 withPath", 10}, {"from hive_db", 3}, {"from hive_db limit 2", 2}, {"from hive_db limit 2 offset 0", 2}, {"from hive_db limit 2 offset 1", 2}, {"from hive_db limit 3 offset 1", 2}, {"hive_db", 3}, {"hive_db where hive_db.name=\"Reporting\"", 1}, {"hive_db where hive_db.name=\"Reporting\" or hive_db.name=\"Sales\" or hive_db.name=\"Logging\" limit 1 offset 1", 1}, {"hive_db where hive_db.name=\"Reporting\" or hive_db.name=\"Sales\" or hive_db.name=\"Logging\" limit 1 offset 2", 1}, {"hive_db where hive_db.name=\"Reporting\" or hive_db.name=\"Sales\" or hive_db.name=\"Logging\" limit 2 offset 1", 2}, {"hive_db where hive_db.name=\"Reporting\" limit 10 ", 1}, {"hive_db hive_db.name = \"Reporting\"", 1}, {"hive_db where hive_db.name=\"Reporting\" select name, owner", 1}, {"hive_db has name", 3}, {"hive_db has name limit 2 offset 0", 2}, {"hive_db has name limit 2 offset 1", 2}, {"hive_db has name limit 10 offset 1", 2}, {"hive_db has name limit 10 offset 0", 3}, {"hive_db, hive_table", 10}, {"hive_db, hive_table limit 5", 5}, {"hive_db, hive_table limit 5 offset 0", 5}, {"hive_db, hive_table limit 5 offset 5", 5}, {"View is JdbcAccess", 2}, {"View is JdbcAccess limit 1", 1}, {"View is JdbcAccess limit 2 offset 1", 1}, {"hive_db as db1, hive_table where db1.name = \"Reporting\"", isGremlin3() ? 4 : 0}, //Not working in Titan 0 - ATLAS-145 {"from hive_table", 10}, {"from hive_table limit 5", 5}, {"from hive_table limit 5 offset 5", 5}, {"hive_table", 10}, {"hive_table limit 5", 5}, {"hive_table limit 5 offset 5", 5}, {"hive_table isa Dimension", 3}, {"hive_table isa Dimension limit 2", 2}, {"hive_table isa Dimension limit 2 offset 0", 2}, {"hive_table isa Dimension limit 2 offset 1", 2}, {"hive_table isa Dimension limit 3 offset 1", 2}, {"hive_column where hive_column isa PII", 8}, {"hive_column where hive_column isa PII limit 5", 5}, {"hive_column where hive_column isa PII limit 5 offset 1", 5}, {"hive_column where hive_column isa PII limit 5 offset 5", 3}, {"View is Dimension" , 2}, {"View is Dimension limit 1" , 1}, {"View is Dimension limit 1 offset 1" , 1}, {"View is Dimension limit 10 offset 1" , 1}, {"hive_column select hive_column.name", 37}, {"hive_column select hive_column.name limit 5", 5}, {"hive_column select hive_column.name limit 5 offset 36", 1}, {"hive_column select name", 37}, {"hive_column select name limit 5", 5}, {"hive_column select name limit 5 offset 36 ", 1}, {"hive_column where hive_column.name=\"customer_id\"", 6}, {"hive_column where hive_column.name=\"customer_id\" limit 2", 2}, {"hive_column where hive_column.name=\"customer_id\" limit 2 offset 1", 2}, {"hive_column where hive_column.name=\"customer_id\" limit 10 offset 3", 3}, {"from hive_table select hive_table.name", 10}, {"from hive_table select hive_table.name limit 5", 5}, {"from hive_table select hive_table.name limit 5 offset 5", 5}, {"hive_db where (name = \"Reporting\")", 1}, {"hive_db where (name = \"Reporting\") limit 10", 1}, {"hive_db where (name = \"Reporting\") select name as _col_0, owner as _col_1", 1}, {"hive_db where (name = \"Reporting\") select name as _col_0, owner as _col_1 limit 10", 1}, {"hive_db where hive_db is JdbcAccess", 0}, //Not supposed to work {"hive_db hive_table", 10}, {"hive_db hive_table limit 5", 5}, {"hive_db hive_table limit 5 offset 5", 5}, {"hive_db where hive_db has name", 3}, {"hive_db where hive_db has name limit 5", 3}, {"hive_db where hive_db has name limit 2 offset 0", 2}, {"hive_db where hive_db has name limit 2 offset 1", 2}, {"hive_db as db1 hive_table where (db1.name = \"Reporting\")", isGremlin3() ? 4 : 0}, //Not working in Titan 0 -> ATLAS-145 {"hive_db where (name = \"Reporting\") select name as _col_0, (createTime + 1) as _col_1 ", 1}, {"hive_db where (name = \"Reporting\") select name as _col_0, (createTime + 1) as _col_1 limit 10", 1}, {"hive_db where (name = \"Reporting\") select name as _col_0, (createTime + 1) as _col_1 limit 10 offset 1", 0}, {"hive_db where (name = \"Reporting\") select name as _col_0, (createTime + 1) as _col_1 limit 10 offset 0", 1}, {"hive_table where (name = \"sales_fact\" and createTime > \"2014-01-01\" ) select name as _col_0, createTime as _col_1 ", 1}, {"hive_table where (name = \"sales_fact\" and createTime > \"2014-01-01\" ) select name as _col_0, createTime as _col_1 limit 10 ", 1}, {"hive_table where (name = \"sales_fact\" and createTime > \"2014-01-01\" ) select name as _col_0, createTime as _col_1 limit 10 offset 0", 1}, {"hive_table where (name = \"sales_fact\" and createTime > \"2014-01-01\" ) select name as _col_0, createTime as _col_1 limit 10 offset 5", 0}, {"hive_table where (name = \"sales_fact\" and createTime >= \"2014-12-11T02:35:58.440Z\" ) select name as _col_0, createTime as _col_1 ", 1}, {"hive_table where (name = \"sales_fact\" and createTime >= \"2014-12-11T02:35:58.440Z\" ) select name as _col_0, createTime as _col_1 limit 10 offset 0", 1}, {"hive_table where (name = \"sales_fact\" and createTime >= \"2014-12-11T02:35:58.440Z\" ) select name as _col_0, createTime as _col_1 limit 10 offset 1", 0}, {"hive_table where (name = \"sales_fact\" and createTime >= \"2014-12-11T02:35:58.440Z\" ) select name as _col_0, createTime as _col_1 limit 10", 1}, {"hive_table where (name = \"sales_fact\" and createTime >= \"2014-12-11T02:35:58.440Z\" ) select name as _col_0, createTime as _col_1 limit 0 offset 1", 0}, // trait searches {"Dimension", 5}, {"Dimension limit 2", 2}, {"Dimension limit 2 offset 1", 2}, {"Dimension limit 5 offset 4", 1}, {"JdbcAccess", 2}, {"JdbcAccess limit 5 offset 0", 2}, {"JdbcAccess limit 2 offset 1", 1}, {"JdbcAccess limit 1", 1}, {"ETL", 5}, {"ETL limit 2", 2}, {"ETL limit 1", 1}, {"ETL limit 1 offset 0", 1}, {"ETL limit 2 offset 1", 2}, {"Metric", 9}, {"Metric limit 10", 9}, {"Metric limit 2", 2}, {"Metric limit 10 offset 1", 8}, {"PII", 8}, {"PII limit 10", 8}, {"PII limit 2", 2}, {"PII limit 10 offset 1", 7}, {"`Log Data`", 4}, {"`Log Data` limit 3", 3}, {"`Log Data` limit 10 offset 2", 2}, {"hive_table where name='sales_fact', db where name='Sales'", 1}, {"hive_table where name='sales_fact', db where name='Sales' limit 10", 1}, {"hive_table where name='sales_fact', db where name='Sales' limit 10 offset 1", 0}, {"hive_table where name='sales_fact', db where name='Reporting'", 0}, {"hive_table where name='sales_fact', db where name='Reporting' limit 10", 0}, {"hive_table where name='sales_fact', db where name='Reporting' limit 10 offset 1", 0}, {"hive_partition as p where values = ['2015-01-01']", 1}, {"hive_partition as p where values = ['2015-01-01'] limit 10", 1}, {"hive_partition as p where values = ['2015-01-01'] limit 10 offset 1", 0}, }; } @DataProvider(name = "dslOrderByQueriesProvider") private Object[][] createDSLQueriesWithOrderBy() { Boolean isAscending = Boolean.TRUE; return new Object[][]{ //test with alias // {"from hive_db select hive_db.name as 'o' orderby o limit 3", 3, "name", isAscending}, {"from hive_db as h orderby h.owner limit 3", 3, "owner", isAscending}, {"hive_column as c select c.name orderby hive_column.name ", 37, "c.name", isAscending}, {"hive_column as c select c.name orderby hive_column.name limit 5", 5, "c.name", isAscending}, {"hive_column as c select c.name orderby hive_column.name desc limit 5", 5, "c.name", !isAscending}, {"from hive_db orderby hive_db.owner limit 3", 3, "owner", isAscending}, {"hive_column select hive_column.name orderby hive_column.name ", 37, "hive_column.name", isAscending}, {"hive_column select hive_column.name orderby hive_column.name limit 5", 5, "hive_column.name", isAscending}, {"hive_column select hive_column.name orderby hive_column.name desc limit 5", 5, "hive_column.name", !isAscending}, {"from hive_db orderby owner limit 3", 3, "owner", isAscending}, {"hive_column select hive_column.name orderby name ", 37, "hive_column.name", isAscending}, {"hive_column select hive_column.name orderby name limit 5", 5, "hive_column.name", isAscending}, {"hive_column select hive_column.name orderby name desc limit 5", 5, "hive_column.name", !isAscending}, //Not working, the problem is in server code not figuring out how to sort. not sure if it is valid use case. // {"hive_db hive_table orderby 'hive_db.owner'", 10, "owner", isAscending}, // {"hive_db hive_table orderby 'hive_db.owner' limit 5", 5, "owner", isAscending}, // {"hive_db hive_table orderby 'hive_db.owner' limit 5 offset 5", 3, "owner", isAscending}, {"hive_db select hive_db.description orderby hive_db.description limit 10 withPath", 3, "hive_db.description", isAscending}, {"hive_db select hive_db.description orderby hive_db.description desc limit 10 withPath", 3, "hive_db.description", !isAscending}, {"hive_column select hive_column.name orderby hive_column.name limit 10 withPath", 10, "hive_column.name", isAscending}, {"hive_column select hive_column.name orderby hive_column.name asc limit 10 withPath", 10, "hive_column.name", isAscending}, {"hive_column select hive_column.name orderby hive_column.name desc limit 10 withPath", 10, "hive_column.name", !isAscending}, {"from hive_db orderby hive_db.owner limit 3", 3, "owner", isAscending}, {"hive_db where hive_db.name=\"Reporting\" orderby 'owner'", 1, "owner", isAscending}, {"hive_db where hive_db.name=\"Reporting\" orderby hive_db.owner limit 10 ", 1, "owner", isAscending}, {"hive_db where hive_db.name=\"Reporting\" select name, owner orderby hive_db.name ", 1, "name", isAscending}, {"hive_db has name orderby hive_db.owner limit 10 offset 0", 3, "owner", isAscending}, {"from hive_table select hive_table.owner orderby hive_table.owner", 10, "hive_table.owner", isAscending}, {"from hive_table select hive_table.owner orderby hive_table.owner limit 8", 8, "hive_table.owner", isAscending}, {"hive_table orderby hive_table.name", 10, "name", isAscending}, {"hive_table orderby hive_table.owner", 10, "owner", isAscending}, {"hive_table orderby hive_table.owner limit 8", 8, "owner", isAscending}, {"hive_table orderby hive_table.owner limit 8 offset 0", 8, "owner", isAscending}, {"hive_table orderby hive_table.owner desc limit 8 offset 0", 8, "owner", !isAscending}, //Not working because of existing bug Atlas-175 // {"hive_table isa Dimension orderby hive_table.owner", 3, "hive_table.owner", isAscending},//order not working // {"hive_table isa Dimension orderby hive_table.owner limit 3", 3, "hive_table.owner", isAscending}, // {"hive_table isa Dimension orderby hive_table.owner limit 3 offset 0", 3, "hive_table.owner", isAscending}, // {"hive_table isa Dimension orderby hive_table.owner desc limit 3 offset 0", 3, "hive_table.owner", !isAscending}, // // {"hive_column where hive_column isa PII orderby hive_column.name", 6, "hive_column.name", isAscending}, // {"hive_column where hive_column isa PII orderby hive_column.name limit 5", 5, "hive_column.name", isAscending}, // {"hive_column where hive_column isa PII orderby hive_column.name limit 5 offset 1", 5, "hive_column.name", isAscending}, // {"hive_column where hive_column isa PII orderby hive_column.name desc limit 5 offset 1", 5, "hive_column.name", !isAscending}, {"hive_column select hive_column.name orderby hive_column.name ", 37, "hive_column.name", isAscending}, {"hive_column select hive_column.name orderby hive_column.name limit 5", 5, "hive_column.name", isAscending}, {"hive_column select hive_column.name orderby hive_column.name desc limit 5", 5, "hive_column.name", !isAscending}, {"hive_column select hive_column.name orderby hive_column.name limit 5 offset 28", 5, "hive_column.name", isAscending}, {"hive_column select name orderby hive_column.name", 37, "name", isAscending}, {"hive_column select name orderby hive_column.name limit 5", 5, "name", isAscending}, {"hive_column select name orderby hive_column.name desc", 37, "name", !isAscending}, {"hive_column where hive_column.name=\"customer_id\" orderby hive_column.name", 6, "name", isAscending}, {"hive_column where hive_column.name=\"customer_id\" orderby hive_column.name limit 2", 2, "name", isAscending}, {"hive_column where hive_column.name=\"customer_id\" orderby hive_column.name limit 2 offset 1", 2, "name", isAscending}, {"from hive_table select owner orderby hive_table.owner",10, "owner", isAscending}, {"from hive_table select owner orderby hive_table.owner limit 5", 5, "owner", isAscending}, {"from hive_table select owner orderby hive_table.owner desc limit 5", 5, "owner", !isAscending}, {"from hive_table select owner orderby hive_table.owner limit 5 offset 5", 5, "owner", isAscending}, {"hive_db where (name = \"Reporting\") orderby hive_db.name", 1, "name", isAscending}, {"hive_db where (name = \"Reporting\") orderby hive_db.name limit 10", 1, "name", isAscending}, {"hive_db where hive_db has name orderby hive_db.owner", 3, "owner", isAscending}, {"hive_db where hive_db has name orderby hive_db.owner limit 5", 3, "owner", isAscending}, {"hive_db where hive_db has name orderby hive_db.owner limit 2 offset 0", 2, "owner", isAscending}, {"hive_db where hive_db has name orderby hive_db.owner limit 2 offset 1", 2, "owner", isAscending}, {"hive_db where (name = \"Reporting\") select name as _col_0, (createTime + 1) as _col_1 orderby '_col_1'", 1, "_col_1", isAscending}, {"hive_db where (name = \"Reporting\") select name as _col_0, (createTime + 1) as _col_1 orderby '_col_1' limit 10", 1, "_col_1", isAscending}, {"hive_db where (name = \"Reporting\") select name as _col_0, (createTime + 1) as _col_1 orderby '_col_1' limit 10 offset 1", 0, "_col_1", isAscending}, {"hive_db where (name = \"Reporting\") select name as _col_0, (createTime + 1) as _col_1 orderby '_col_1' limit 10 offset 0", 1, "_col_1", isAscending}, {"hive_table where (name = \"sales_fact\" and createTime > \"2014-01-01\" ) select name as _col_0, createTime as _col_1 orderby '_col_1' ", 1, "_col_1", isAscending}, {"hive_table where (name = \"sales_fact\" and createTime > \"2014-01-01\" ) select name as _col_0, createTime as _col_1 orderby '_col_1' limit 10 ", 1, "_col_1", isAscending}, {"hive_table where (name = \"sales_fact\" and createTime > \"2014-01-01\" ) select name as _col_0, createTime as _col_1 orderby '_col_1' limit 10 offset 0", 1, "_col_1", isAscending}, {"hive_table where (name = \"sales_fact\" and createTime > \"2014-01-01\" ) select name as _col_0, createTime as _col_1 orderby '_col_1' limit 10 offset 5", 0, "_col_1", isAscending}, {"hive_table where (name = \"sales_fact\" and createTime >= \"2014-12-11T02:35:58.440Z\" ) select name as _col_0, createTime as _col_1 orderby '_col_0' ", 1, "_col_0", isAscending}, {"hive_table where (name = \"sales_fact\" and createTime >= \"2014-12-11T02:35:58.440Z\" ) select name as _col_0, createTime as _col_1 orderby '_col_0' limit 10 offset 0", 1, "_col_0", isAscending}, {"hive_table where (name = \"sales_fact\" and createTime >= \"2014-12-11T02:35:58.440Z\" ) select name as _col_0, createTime as _col_1 orderby '_col_0' limit 10 offset 1", 0, "_col_0", isAscending}, {"hive_table where (name = \"sales_fact\" and createTime >= \"2014-12-11T02:35:58.440Z\" ) select name as _col_0, createTime as _col_1 orderby '_col_0' limit 10", 1, "_col_0", isAscending}, {"hive_table where (name = \"sales_fact\" and createTime >= \"2014-12-11T02:35:58.440Z\" ) select name as _col_0, createTime as _col_1 orderby '_col_0' limit 0 offset 1", 0, "_col_0", isAscending}, {"hive_column select hive_column.name orderby hive_column.name limit 10 withPath", 10, "hive_column.name", isAscending}, {"hive_column select hive_column.name orderby hive_column.name limit 10 withPath", 10, "hive_column.name", isAscending}, {"hive_table orderby 'hive_table.owner_notdefined'", 10, null, isAscending}, }; } @DataProvider(name = "dslGroupByQueriesProvider") private Object[][] createDSLGroupByQueries() { return new Object[][]{ { "from Person as p, mentor as m groupby(m.name) select m.name, count()", new FieldValueValidator().withFieldNames("m.name", "count()").withExpectedValues("Max", 1) .withExpectedValues("Julius", 1) }, // This variant of this query is currently failing. See OMS-335 for details. { "from Person as p, mentor groupby(mentor.name) select mentor.name, count()", new FieldValueValidator().withFieldNames("mentor.name", "count()").withExpectedValues("Max", 1) .withExpectedValues("Julius", 1) }, { "from Person, mentor groupby(mentor.name) select mentor.name, count()", new FieldValueValidator().withFieldNames("mentor.name", "count()").withExpectedValues("Max", 1) .withExpectedValues("Julius", 1) }, { "from Person, mentor as m groupby(m.name) select m.name, count()", new FieldValueValidator().withFieldNames("m.name", "count()").withExpectedValues("Max", 1) .withExpectedValues("Julius", 1) }, { "from Person groupby (isOrganDonor) select count()", new FieldValueValidator().withFieldNames("count()").withExpectedValues(2) .withExpectedValues(2) }, { "from Person groupby (isOrganDonor) select Person.isOrganDonor, count()", new FieldValueValidator().withFieldNames("Person.isOrganDonor", "count()") .withExpectedValues(true, 2).withExpectedValues(false, 2) }, { "from Person groupby (isOrganDonor) select Person.isOrganDonor as 'organDonor', count() as 'count', max(Person.age) as 'max', min(Person.age) as 'min'", new FieldValueValidator().withFieldNames("organDonor", "max", "min", "count") .withExpectedValues(true, 50, 36, 2).withExpectedValues(false, 0, 0, 2) }, { "from hive_db groupby (owner, name) select count() ", new FieldValueValidator() .withFieldNames("count()").withExpectedValues(1).withExpectedValues(1).withExpectedValues(1) }, { "from hive_db groupby (owner, name) select hive_db.owner, hive_db.name, count() ", new FieldValueValidator().withFieldNames("hive_db.owner", "hive_db.name", "count()") .withExpectedValues("Jane BI", "Reporting", 1) .withExpectedValues("Tim ETL", "Logging", 1) .withExpectedValues("John ETL", "Sales", 1) }, { "from hive_db groupby (owner) select count() ", new FieldValueValidator().withFieldNames("count()").withExpectedValues(1).withExpectedValues(1) .withExpectedValues(1) }, { "from hive_db groupby (owner) select hive_db.owner, count() ", new FieldValueValidator().withFieldNames("hive_db.owner", "count()") .withExpectedValues("Jane BI", 1).withExpectedValues("Tim ETL", 1) .withExpectedValues("John ETL", 1) }, { "from hive_db groupby (owner) select hive_db.owner, max(hive_db.name) ", new FieldValueValidator().withFieldNames("hive_db.owner", "max(hive_db.name)") .withExpectedValues("Tim ETL", "Logging").withExpectedValues("Jane BI", "Reporting") .withExpectedValues("John ETL", "Sales") }, { "from hive_db groupby (owner) select max(hive_db.name) ", new FieldValueValidator().withFieldNames("max(hive_db.name)").withExpectedValues("Logging") .withExpectedValues("Reporting").withExpectedValues("Sales") }, { "from hive_db groupby (owner) select owner, hive_db.name, min(hive_db.name) ", new FieldValueValidator().withFieldNames("owner", "hive_db.name", "min(hive_db.name)") .withExpectedValues("Tim ETL", "Logging", "Logging") .withExpectedValues("Jane BI", "Reporting", "Reporting") .withExpectedValues("John ETL", "Sales", "Sales") }, { "from hive_db groupby (owner) select owner, min(hive_db.name) ", new FieldValueValidator().withFieldNames("owner", "min(hive_db.name)") .withExpectedValues("Tim ETL", "Logging").withExpectedValues("Jane BI", "Reporting") .withExpectedValues("John ETL", "Sales") }, { "from hive_db groupby (owner) select min(name) ", new FieldValueValidator().withFieldNames("min(name)") .withExpectedValues("Reporting").withExpectedValues("Logging") .withExpectedValues("Sales") }, { "from hive_db groupby (owner) select min('name') ", new FieldValueValidator().withFieldNames("min(\"name\")").withExpectedValues("name") .withExpectedValues("name").withExpectedValues("name") }, //finding the minimum of a constant literal expression... { "from hive_db groupby (owner) select name ", new FieldValueValidator().withFieldNames("name").withExpectedValues("Reporting") .withExpectedValues("Sales").withExpectedValues("Logging") }, //implied group by { "from hive_db select count() ", new FieldValueValidator().withFieldNames("count()").withExpectedValues(3) }, //implied group by { "from Person select count() as 'count', max(Person.age) as 'max', min(Person.age) as 'min'", new FieldValueValidator().withFieldNames("max", "min", "count").withExpectedValues(50, 0, 4) }, //Sum { "from Person groupby (isOrganDonor) select count() as 'count', sum(Person.age) as 'sum'", new FieldValueValidator().withFieldNames("count", "sum").withExpectedValues(2, 0) .withExpectedValues(2, 86) }, { "from Person groupby (isOrganDonor) select Person.isOrganDonor as 'organDonor', count() as 'count', sum(Person.age) as 'sum'", new FieldValueValidator().withFieldNames("organDonor", "count", "sum").withExpectedValues(false, 2, 0) .withExpectedValues(true, 2, 86) }, { "from Person select count() as 'count', sum(Person.age) as 'sum'", new FieldValueValidator().withFieldNames("count", "sum").withExpectedValues(4, 86) }, // tests to ensure that group by works with order by and limit { "from hive_db groupby (owner) select min(name) orderby name limit 2 ", new FieldValueValidator().withFieldNames("min(name)") .withExpectedValues("Logging").withExpectedValues("Reporting") }, { "from hive_db groupby (owner) select min(name) orderby name desc limit 2 ", new FieldValueValidator().withFieldNames("min(name)") .withExpectedValues("Reporting").withExpectedValues("Sales") }, }; } @DataProvider(name = "dslObjectQueriesReturnIdProvider") private Object[][] createDSLObjectIdQueries() { return new Object[][] { { "from hive_db as h select h as id", new FieldValueValidator().withFieldNames("id") .withExpectedValues(idType).withExpectedValues(idType) .withExpectedValues(idType) } }; } @Test(dataProvider = "dslOrderByQueriesProvider") public void testSearchByDSLQueriesWithOrderBy(String dslQuery, Integer expectedNumRows, String orderBy, boolean ascending) throws Exception { System.out.println("Executing dslQuery = " + dslQuery); String jsonResults = searchByDSL(dslQuery); assertNotNull(jsonResults); JSONObject results = new JSONObject(jsonResults); assertEquals(results.length(), 3); Object query = results.get("query"); assertNotNull(query); JSONObject dataType = results.getJSONObject("dataType"); assertNotNull(dataType); String typeName = dataType.getString("typeName"); assertNotNull(typeName); JSONArray rows = results.getJSONArray("rows"); assertNotNull(rows); assertEquals(rows.length(), expectedNumRows.intValue()); // some queries may not have any results List<String> returnedList = new ArrayList<>(); for (int i = 0; i < rows.length(); i++) { JSONObject row = rows.getJSONObject(i); try { returnedList.add(row.get(orderBy).toString()); } catch(Exception ex) { System.out.println( " Exception occured " + ex.getMessage() + " found row: "+row); } } Iterator<String> iter = returnedList.iterator(); String _current = null, _prev = null; if (orderBy != null) { // Following code compares the results in rows and makes sure data // is sorted as expected while (iter.hasNext()) { _prev = _current; _current = iter.next().toLowerCase(); if (_prev != null && _prev.compareTo(_current) != 0) { if(ascending) { Assert.assertTrue(_prev.compareTo(_current) < 0, _prev + " is greater than " + _current); } else { Assert.assertTrue(_prev.compareTo(_current) > 0, _prev + " is less than " + _current); } } } } System.out.println("query [" + dslQuery + "] returned [" + rows.length() + "] rows"); } @Test(dataProvider = "dslQueriesProvider") public void testSearchByDSLQueries(String dslQuery, Integer expectedNumRows) throws Exception { runQuery(dslQuery, expectedNumRows, 40, 0); } @Test(dataProvider = "comparisonQueriesProvider") public void testDataTypeComparisonQueries(String dslQuery, Integer expectedNumRows) throws Exception { runQuery(dslQuery, expectedNumRows, 40, 0); } @Test(dataProvider = "dslExplicitLimitQueriesProvider") public void testSearchByDSLQueriesWithExplicitLimit(String dslQuery, Integer expectedNumRows, int limit, int offset) throws Exception { runQuery(dslQuery, expectedNumRows, limit, offset); } public void runQuery(String dslQuery, Integer expectedNumRows, int limitParam, int offsetParam) throws Exception { System.out.println("Executing dslQuery = " + dslQuery); String jsonResults = discoveryService.searchByDSL(dslQuery, new QueryParams(limitParam, offsetParam)); assertNotNull(jsonResults); JSONObject results = new JSONObject(jsonResults); assertEquals(results.length(), 3); System.out.println("results = " + results); Object query = results.get("query"); assertNotNull(query); JSONObject dataType = results.getJSONObject("dataType"); assertNotNull(dataType); String typeName = dataType.getString("typeName"); assertNotNull(typeName); JSONArray rows = results.getJSONArray("rows"); assertNotNull(rows); assertEquals( rows.length(), expectedNumRows.intValue(), "query [" + dslQuery + "] returned [" + rows.length() + "] rows. Expected " + expectedNumRows + " rows."); // some queries may not have any results System.out.println("query [" + dslQuery + "] returned [" + rows.length() + "] rows"); } @Test(dataProvider = "dslLimitQueriesProvider") public void testSearchByDSLQueriesWithLimit(String dslQuery, Integer expectedNumRows) throws Exception { runQuery(dslQuery, expectedNumRows, 40, 0); } @DataProvider(name = "invalidDslQueriesProvider") private Object[][] createInvalidDSLQueries() { return new String[][]{{"from Unknown"}, {"Unknown"}, {"Unknown is Blah"},}; } @Test(dataProvider = "invalidDslQueriesProvider", expectedExceptions = DiscoveryException.class) public void testSearchByDSLInvalidQueries(String dslQuery) throws Exception { System.out.println("Executing dslQuery = " + dslQuery); searchByDSL(dslQuery); Assert.fail(); } @Test public void testSearchForTypeInheritance() throws Exception { createTypesWithMultiLevelInheritance(); createInstances(); String dslQuery = "from D where a = 1"; String jsonResults = searchByDSL(dslQuery); assertNotNull(jsonResults); JSONObject results = new JSONObject(jsonResults); System.out.println("results = " + results); } @Test public void testSearchForTypeWithReservedKeywordAttributes() throws Exception { createTypesWithReservedKeywordAttributes(); String dslQuery = "from OrderType where `order` = 1"; String jsonResults = searchByDSL(dslQuery); assertNotNull(jsonResults); JSONObject results = new JSONObject(jsonResults); System.out.println("results = " + results); } /* * Type Hierarchy is: * A(a) * B(b) extends A * C(c) extends B * D(d) extends C */ private void createTypesWithMultiLevelInheritance() throws Exception { HierarchicalTypeDefinition A = createClassTypeDef("A", null, createRequiredAttrDef("a", DataTypes.INT_TYPE)); HierarchicalTypeDefinition B = createClassTypeDef("B", ImmutableSet.of("A"), createOptionalAttrDef("b", DataTypes.BOOLEAN_TYPE)); HierarchicalTypeDefinition C = createClassTypeDef("C", ImmutableSet.of("B"), createOptionalAttrDef("c", DataTypes.BYTE_TYPE)); HierarchicalTypeDefinition D = createClassTypeDef("D", ImmutableSet.of("C"), createOptionalAttrDef("d", DataTypes.SHORT_TYPE)); TypeSystem.getInstance().defineClassTypes(A, B, C, D); } private void createTypesWithReservedKeywordAttributes() throws Exception { HierarchicalTypeDefinition orderType = createClassTypeDef("OrderType", null, createRequiredAttrDef("order", DataTypes.INT_TYPE)); HierarchicalTypeDefinition limitType = createClassTypeDef("LimitType", null, createOptionalAttrDef("limit", DataTypes.BOOLEAN_TYPE)); TypeSystem.getInstance().defineClassTypes(orderType, limitType); } private void createInstances() throws Exception { Referenceable instance = new Referenceable("D"); instance.set("d", 1); instance.set("c", 1); instance.set("b", true); instance.set("a", 1); ClassType deptType = TypeSystem.getInstance().getDataType(ClassType.class, "D"); ITypedReferenceableInstance typedInstance = deptType.convert(instance, Multiplicity.REQUIRED); repositoryService.createEntities(typedInstance); } private void runCountGroupByQuery(String dslQuery, ResultChecker checker) throws Exception { runAndValidateQuery(dslQuery, checker); } private void runAndValidateQuery(String dslQuery, ResultChecker checker) throws Exception { System.out.println("Executing dslQuery = " + dslQuery); String jsonResults = searchByDSL(dslQuery); assertNotNull(jsonResults); JSONObject results = new JSONObject(jsonResults); assertEquals(results.length(), 3); Object query = results.get("query"); assertNotNull(query); JSONArray rows = results.getJSONArray("rows"); assertNotNull(rows); if (checker != null) { checker.validateResult(dslQuery, rows); } System.out.println("query [" + dslQuery + "] returned [" + rows.length() + "] rows"); } @Test(dataProvider = "dslGroupByQueriesProvider") public void testSearchGroupByDSLQueries(String dslQuery, ResultChecker checker) throws Exception { runCountGroupByQuery(dslQuery, checker); } @Test(dataProvider = "dslObjectQueriesReturnIdProvider") public void testSearchObjectQueriesReturnId(String dslQuery, ResultChecker checker) throws Exception { runAndValidateQuery(dslQuery, checker); } private interface ResultChecker { void validateResult(String dslQuery, JSONArray foundRows) throws JSONException; } static class FieldValueValidator implements ResultChecker { static class ResultObject { private static String[] idTypeAttributes = { "id", "$typeName$", "state", "version" }; @Override public String toString() { return "ResultObject [fieldValues_=" + fieldValues_ + "]"; } Map<String, Object> fieldValues_ = new HashMap<>(); public void setFieldValue(String string, Object object) { fieldValues_.put(string, object); } public boolean matches(JSONObject object) throws JSONException { for (Map.Entry<String, Object> requiredFieldsEntry : fieldValues_.entrySet()) { String fieldName = requiredFieldsEntry.getKey(); Object expectedValue = requiredFieldsEntry.getValue(); Object foundValue = null; if (expectedValue.getClass() == Integer.class) { foundValue = object.getInt(fieldName); } else if (expectedValue == idType) { return validateObjectIdType(object, fieldName); } else { foundValue = object.get(fieldName); } if (foundValue == null || !expectedValue.equals(foundValue)) { return false; } } return true; } // validates that returned object id contains all the required attributes. private boolean validateObjectIdType(JSONObject object, String fieldName) throws JSONException { JSONObject foundJson = object.getJSONObject(fieldName); for (String idAttr : idTypeAttributes) { if (foundJson.get(idAttr) == null) { return false; } } return true; } } private String[] fieldNames_; private List<ResultObject> expectedObjects_ = new ArrayList<>(); public FieldValueValidator() { } public FieldValueValidator withFieldNames(String... fields) { fieldNames_ = fields; return this; } public FieldValueValidator withExpectedValues(Object... values) { ResultObject obj = new ResultObject(); for (int i = 0; i < fieldNames_.length; i++) { obj.setFieldValue(fieldNames_[i], values[i]); } expectedObjects_.add(obj); return this; } @Override public void validateResult(String dslQuery, JSONArray foundRows) throws JSONException { //make sure that all required rows are found Assert.assertEquals(foundRows.length(), expectedObjects_.size(), "The wrong number of objects was returned for query " + dslQuery + ". Expected " + expectedObjects_.size() + ", found " + foundRows.length()); for (ResultObject required : expectedObjects_) { //not exactly efficient, but this is test code boolean found = false; for (int i = 0; i < foundRows.length(); i++) { JSONObject row = foundRows.getJSONObject(i); System.out.println(" found row "+ row); if (required.matches(row)) { found = true; break; } } if (!found) { Assert.fail("The result for " + dslQuery + " is wrong. The required row " + required + " was not found in " + foundRows); } } } } static class CountOnlyValidator implements ResultChecker { private List<Integer> expectedCounts = new ArrayList<Integer>(); private int countColumn = 0; public CountOnlyValidator() { } public CountOnlyValidator withCountColumn(int col) { countColumn = col; return this; } public CountOnlyValidator withExpectedCounts(Integer... counts) { expectedCounts.addAll(Arrays.asList(counts)); return this; } @Override public void validateResult(String dslQuery, JSONArray foundRows) throws JSONException { assertEquals(foundRows.length(), expectedCounts.size()); for (int i = 0; i < foundRows.length(); i++) { JSONArray row = foundRows.getJSONArray(i); assertEquals(row.length(), 1); int foundCount = row.getInt(countColumn); // assertTrue(expectedCounts.contains(foundCount)); } } } @Test public void testSearchForTypeWithNoInstances() throws Exception { HierarchicalTypeDefinition EMPTY = createClassTypeDef("EmptyType", null, createRequiredAttrDef("a", DataTypes.INT_TYPE)); TypeSystem.getInstance().defineClassTypes(EMPTY); String dslQuery = "EmptyType"; String jsonResults = searchByDSL(dslQuery); assertNotNull(jsonResults); JSONObject results = new JSONObject(jsonResults); assertEquals(results.length(), 3); JSONArray rows = results.getJSONArray("rows"); assertNotNull(rows); // query should not return any rows assertEquals(rows.length(), 0); } @Test public void testTypePreservedWhenFilterTraversesEdges() throws DiscoveryException, JSONException { String dsl = "hive_table db.name=\"Reporting\" limit 10"; ImmutableSet<String> expectedTableNames = ImmutableSet.of("table1", "table2", "sales_fact_monthly_mv", "sales_fact_daily_mv"); String jsonResults = discoveryService.searchByDSL(dsl, null); assertNotNull(jsonResults); JSONObject results = new JSONObject(jsonResults); JSONArray rows = results.getJSONArray("rows"); assertEquals(rows.length(), expectedTableNames.size()); for(int i = 0; i < rows.length(); i++) { JSONObject row = rows.getJSONObject(i); Assert.assertTrue(expectedTableNames.contains(row.get("name"))); } } private FieldValueValidator makeCountValidator(int count) { return new FieldValueValidator().withFieldNames("count()").withExpectedValues(count); } private FieldValueValidator makeNoResultsValidator() { return new FieldValueValidator(); } private boolean isGremlin3() { return TestUtils.getGraph().getSupportedGremlinVersion() == GremlinVersion.THREE; } } <|start_filename|>dashboardv2/public/js/views/schema/SchemaLayoutView.js<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(['require', 'backbone', 'hbs!tmpl/schema/SchemaTableLayoutView_tmpl', 'collection/VSchemaList', 'utils/Utils', 'utils/CommonViewFunction', 'utils/Messages', 'utils/Globals', 'utils/Enums', 'utils/UrlLinks' ], function(require, Backbone, SchemaTableLayoutViewTmpl, VSchemaList, Utils, CommonViewFunction, Messages, Globals, Enums, UrlLinks) { 'use strict'; var SchemaTableLayoutView = Backbone.Marionette.LayoutView.extend( /** @lends SchemaTableLayoutView */ { _viewName: 'SchemaTableLayoutView', template: SchemaTableLayoutViewTmpl, /** Layout sub regions */ regions: { RSchemaTableLayoutView: "#r_schemaTableLayoutView", }, /** ui selector cache */ ui: { tagClick: '[data-id="tagClick"]', addTag: "[data-id='addTag']", addTerm: '[data-id="addTerm"]', showMoreLess: '[data-id="showMoreLess"]', showMoreLessTerm: '[data-id="showMoreLessTerm"]', addAssignTag: "[data-id='addAssignTag']", checkDeletedEntity: "[data-id='checkDeletedEntity']" }, /** ui events hash */ events: function() { var events = {}; events["click " + this.ui.addTag] = 'checkedValue'; events["click " + this.ui.addTerm] = 'checkedValue'; events["click " + this.ui.addAssignTag] = 'checkedValue'; events["click " + this.ui.tagClick] = function(e) { if (e.target.nodeName.toLocaleLowerCase() == "i") { this.onClickTagCross(e); } else { var value = e.currentTarget.text; Utils.setUrl({ url: '#!/tag/tagAttribute/' + value, mergeBrowserUrl: false, trigger: true }); } }; events["click " + this.ui.showMoreLess] = function(e) { this.$('.popover.popoverTag').hide(); $(e.currentTarget).parent().find("div.popover").show(); var positionContent = $(e.currentTarget).position(); positionContent.top = positionContent.top + 26; positionContent.left = positionContent.left - 41; $(e.currentTarget).parent().find("div.popover").css(positionContent); }; events["click " + this.ui.showMoreLessTerm] = function(e) { $(e.currentTarget).find('i').toggleClass('fa fa-angle-right fa fa-angle-up'); $(e.currentTarget).parents('.searchTerm').find('div.termTableBreadcrumb>div.showHideDiv').toggleClass('hide'); if ($(e.currentTarget).find('i').hasClass('fa-angle-right')) { $(e.currentTarget).find('span').text('Show More'); } else { $(e.currentTarget).find('span').text('Show less'); } }; events["click " + this.ui.checkDeletedEntity] = 'onCheckDeletedEntity'; return events; }, /** * intialize a new SchemaTableLayoutView Layout * @constructs */ initialize: function(options) { _.extend(this, _.pick(options, 'guid', 'entityDefCollection', 'attribute', 'referredEntities', 'fetchCollection', 'enumDefCollection')); this.schemaCollection = new VSchemaList([], {}); this.commonTableOptions = { collection: this.schemaCollection, includeFilter: false, includePagination: true, includePageSize: false, includeFooterRecords: true, includeOrderAbleColumns: false, gridOpts: { className: "table table-hover backgrid table-quickMenu", emptyText: 'No records found!' }, filterOpts: {}, paginatorOpts: {} }; this.bindEvents(); this.bradCrumbList = []; }, bindEvents: function() { this.listenTo(this.schemaCollection, 'backgrid:selected', function(model, checked) { if (checked === true) { model.set("isEnable", true); } else { model.set("isEnable", false); } this.arr = []; var that = this; this.schemaCollection.find(function(item) { var obj = item.toJSON(); if (item.get('isEnable')) { that.arr.push({ id: obj.guid, model: obj }); } }); if (this.arr.length > 0) { if (Globals.taxonomy) { this.$('.multiSelectTerm').show(); } this.$('.multiSelectTag').show(); } else { if (Globals.taxonomy) { this.$('.multiSelectTerm').hide(); } this.$('.multiSelectTag').hide(); } }); }, onRender: function() { this.generateTableData(); }, generateTableData: function(checkedDelete) { var that = this, newModel; this.activeObj = []; this.deleteObj = []; this.schemaTableAttribute = null; if (this.attribute && this.attribute[0]) { var firstColumn = this.attribute[0], defObj = that.entityDefCollection.fullCollection.find({ name: firstColumn.typeName }); if (defObj && defObj.get('options') && defObj.get('options').schemaAttributes) { if (firstColumn) { try { var mapObj = JSON.parse(defObj.get('options').schemaAttributes); that.schemaTableAttribute = _.pick(firstColumn.attributes, mapObj); } catch (e) {} } } } _.each(this.attribute, function(obj) { newModel = that.referredEntities[obj.guid]; if (newModel.attributes['position']) { newModel['position'] = newModel.attributes['position']; } if (!Enums.entityStateReadOnly[newModel.status]) { that.activeObj.push(newModel); that.schemaCollection.push(newModel); } else if (Enums.entityStateReadOnly[newModel.status]) { that.deleteObj.push(newModel); } }); $('body').click(function(e) { var iconEvnt = e.target.nodeName; if (that.$('.popoverContainer').length) { if ($(e.target).hasClass('tagDetailPopover') || iconEvnt == "I") { return; } that.$('.popover.popoverTag').hide(); } }); if (this.schemaCollection.length === 0 && this.deleteObj.length) { this.ui.checkDeletedEntity.find("input").prop('checked', true); this.schemaCollection.reset(this.deleteObj, { silent: true }); } if (this.activeObj.length === 0 && this.deleteObj.length === 0) { this.ui.checkDeletedEntity.hide(); } this.renderTableLayoutView(); }, showLoader: function() { this.$('.fontLoader').show(); this.$('.tableOverlay').show() }, hideLoader: function(argument) { this.$('.fontLoader').hide(); this.$('.tableOverlay').hide(); }, renderTableLayoutView: function() { var that = this; require(['utils/TableLayout'], function(TableLayout) { var columnCollection = Backgrid.Columns.extend({ // sortKey: "position", // comparator: function(item) { // return item.get(this.sortKey) || 999; // }, // setPositions: function() { // _.each(this.models, function(model, index) { // if (model.get('name') == "name") { // model.set("position", 2, { silent: true }); // model.set("label", "Name"); // } else if (model.get('name') == "description") { // model.set("position", 3, { silent: true }); // model.set("label", "Description"); // } else if (model.get('name') == "owner") { // model.set("position", 4, { silent: true }); // model.set("label", "Owner"); // } // }); // return this; // } }); var columns = new columnCollection(that.getSchemaTableColumns()); //columns.setPositions().sort(); that.RSchemaTableLayoutView.show(new TableLayout(_.extend({}, that.commonTableOptions, { columns: columns }))); that.$('.multiSelectTerm').hide(); that.$('.multiSelectTag').hide(); that.renderBreadcrumb(); }); }, renderBreadcrumb: function() { var that = this; _.each(this.bradCrumbList, function(object) { _.each(object.value, function(subObj) { var scopeObject = that.$('[dataterm-id="' + object.scopeId + '"]').find('[dataterm-name="' + subObj.name + '"] .liContent'); CommonViewFunction.breadcrumbMaker({ urlList: subObj.valueUrl, scope: scopeObject }); }); }); }, getSchemaTableColumns: function() { var that = this, col = { Check: { name: "selected", label: "", cell: "select-row", headerCell: "select-all" } } if (this.schemaTableAttribute) { _.each(_.keys(this.schemaTableAttribute), function(key) { if (key !== "position") { col[key] = { label: key, cell: "html", editable: false, sortable: false, className: "searchTableName", formatter: _.extend({}, Backgrid.CellFormatter.prototype, { fromRaw: function(rawValue, model) { var value = model.get('attributes')[key]; if (key === "name" && model.get('guid')) { var nameHtml = '<a href="#!/detailPage/' + model.get('guid') + '">' + value + '</a>'; if (model.get('status') && Enums.entityStateReadOnly[model.get('status')]) { nameHtml += '<button type="button" title="Deleted" class="btn btn-atlasAction btn-atlas deleteBtn"><i class="fa fa-trash"></i></button>'; return '<div class="readOnly readOnlyLink">' + nameHtml + '</div>'; } else { return nameHtml; } } else { return value } } }) }; } }); col['tag'] = { label: "Tags", cell: "Html", editable: false, sortable: false, className: 'searchTag', formatter: _.extend({}, Backgrid.CellFormatter.prototype, { fromRaw: function(rawValue, model) { var obj = model.toJSON(); if (obj.status && Enums.entityStateReadOnly[obj.status]) { return '<div class="readOnly">' + CommonViewFunction.tagForTable(obj); + '</div>'; } else { return CommonViewFunction.tagForTable(obj); } } }) }; if (Globals.taxonomy) { col['terms'] = { label: "Terms", cell: "Html", editable: false, sortable: false, orderable: true, className: 'searchTerm', formatter: _.extend({}, Backgrid.CellFormatter.prototype, { fromRaw: function(rawValue, model) { var obj = model.toJSON(); var returnObject = CommonViewFunction.termTableBreadcrumbMaker(obj); if (returnObject.object) { that.bradCrumbList.push(returnObject.object); } if (obj.status && Enums.entityStateReadOnly[obj.status]) { return '<div class="readOnly">' + returnObject.html + '</div>'; } else { return returnObject.html; } } }) }; } return this.schemaCollection.constructor.getTableCols(col, this.schemaCollection); } }, checkedValue: function(e) { if (e) { e.stopPropagation(); } var guid = "", that = this; var multiSelectTag = $(e.currentTarget).hasClass('assignTag'); if (multiSelectTag) { if (this.arr && this.arr.length && multiSelectTag) { that.addTagModalView(guid, this.arr); } else { guid = that.$(e.currentTarget).data("guid"); that.addTagModalView(guid); } } else { if (this.arr && this.arr.length) { that.addTermModalView(guid, this.arr); } else { guid = that.$(e.currentTarget).data("guid"); that.addTermModalView(guid); } } }, addTagModalView: function(guid, multiple) { var that = this; var tagList = that.schemaCollection.find({ 'guid': guid }); require(['views/tag/addTagModalView'], function(AddTagModalView) { var view = new AddTagModalView({ guid: guid, multiple: multiple, tagList: _.map((tagList ? tagList.get('classifications') : []), function(obj) { return obj.typeName; }), callback: function() { that.fetchCollection(); that.arr = []; }, hideLoader: that.hideLoader.bind(that), showLoader: that.showLoader.bind(that), enumDefCollection: that.enumDefCollection }); // view.saveTagData = function() { //override saveTagData function // } }); }, addTermModalView: function(guid, multiple) { var that = this; require([ 'views/business_catalog/AddTermToEntityLayoutView', ], function(AddTermToEntityLayoutView) { var view = new AddTermToEntityLayoutView({ guid: guid, multiple: multiple, callback: function(termName) { that.fetchCollection(); that.arr = []; }, hideLoader: that.hideLoader.bind(that), showLoader: that.showLoader.bind(that) }); }); }, onClickTagCross: function(e) { var tagName = $(e.target).data("name"), guid = $(e.target).data("guid"), assetName = $(e.target).data("assetname"), tagOrTerm = $(e.target).data("type"), that = this; if (tagOrTerm === "term") { var modal = CommonViewFunction.deleteTagModel({ msg: "<div class='ellipsis'>Remove: " + "<b>" + _.escape(tagName) + "</b> assignment from" + " " + "<b>" + assetName + " ?</b></div>", titleMessage: Messages.removeTerm, buttonText: "Remove" }); } else if (tagOrTerm === "tag") { var modal = CommonViewFunction.deleteTagModel({ msg: "<div class='ellipsis'>Remove: " + "<b>" + _.escape(tagName) + "</b> assignment from" + " " + "<b>" + assetName + " ?</b></div>", titleMessage: Messages.removeTag, buttonText: "Remove" }); } if (modal) { modal.on('ok', function() { that.deleteTagData(e, tagOrTerm); }); modal.on('closeModal', function() { modal.trigger('cancel'); }); } }, deleteTagData: function(e, tagOrTerm) { var that = this, tagName = $(e.target).data("name"), guid = $(e.target).data("guid"); CommonViewFunction.deleteTag({ 'tagName': tagName, 'guid': guid, 'tagOrTerm': tagOrTerm, showLoader: that.showLoader.bind(that), hideLoader: that.hideLoader.bind(that), callback: function() { that.fetchCollection(); } }); }, onCheckDeletedEntity: function(e) { if (e.target.checked) { if (this.deleteObj.length) { this.schemaCollection.reset(this.activeObj.concat(this.deleteObj)); } } else { this.schemaCollection.reset(this.activeObj); } } }); return SchemaTableLayoutView; }); <|start_filename|>repository/src/main/java/org/apache/atlas/repository/typestore/ITypeStore.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.typestore; import com.google.common.collect.ImmutableList; import org.apache.atlas.AtlasException; import org.apache.atlas.typesystem.TypesDef; import org.apache.atlas.typesystem.types.TypeSystem; @Deprecated public interface ITypeStore { /** * Add types to the underlying type storage layer * @param typeSystem {@link TypeSystem} object which contains existing types. To lookup newly added types, * an instance of {@link TypeSystem.TransientTypeSystem} can be passed. * @param types names of newly added types. * @throws AtlasException */ void store(TypeSystem typeSystem, ImmutableList<String> types) throws AtlasException; /** * Restore all type definitions * @return List of persisted type definitions * @throws AtlasException */ TypesDef restore() throws AtlasException; /** * Restore the specified type definition * * @param typeName name of requested type * @return persisted type definition * @throws AtlasException */ TypesDef restoreType(String typeName) throws AtlasException; } <|start_filename|>dashboardv2/public/js/views/tag/addTagModalView.js<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(['require', 'hbs!tmpl/tag/addTagModalView_tmpl', 'collection/VTagList', 'collection/VCommonList', 'modules/Modal', 'models/VEntity', 'utils/Utils', 'utils/UrlLinks', 'utils/Enums', 'utils/Messages', 'daterangepicker' ], function(require, AddTagModalViewTmpl, VTagList, VCommonList, Modal, VEntity, Utils, UrlLinks, Enums, Messages) { 'use strict'; var AddTagModel = Marionette.LayoutView.extend({ template: AddTagModalViewTmpl, templateHelpers: function() { return { tagModel: this.tagModel }; }, regions: {}, ui: { addTagOptions: "[data-id='addTagOptions']", tagAttribute: "[data-id='tagAttribute']" }, events: function() { var events = {}; events["change " + this.ui.addTagOptions] = 'onChangeTagDefination'; return events; }, /** * intialize a new AddTagModel Layout * @constructs */ initialize: function(options) { _.extend(this, _.pick(options, 'modalCollection', 'guid', 'callback', 'multiple', 'showLoader', 'hideLoader', 'tagList', 'tagModel', 'enumDefCollection')); this.collection = new VTagList(); this.commonCollection = new VTagList(); var that = this, modalObj = { title: 'Add Tag', content: this, okText: 'Add', cancelText: "Cancel", allowCancel: true, }; if (this.tagModel) { modalObj.title = 'Edit Tag'; modalObj.okText = 'Update'; } this.modal = new Modal(modalObj).open(); this.modal.$el.find('button.ok').attr("disabled", true); this.on('ok', function() { var tagName = this.tagModel ? this.tagModel.typeName : this.ui.addTagOptions.val(), tagAttributes = {}, tagAttributeNames = this.$(".attrName"), obj = { tagName: tagName, tagAttributes: tagAttributes, guid: [], skipEntity: [], deletedEntity: [] }; tagAttributeNames.each(function(i, item) { var selection = $(item).data("key"); var datatypeSelection = $(item).data("type"); if (datatypeSelection === "date") { tagAttributes[selection] = Date.parse($(item).val()) || null; } else { tagAttributes[selection] = $(item).val() || null; } }); if (that.multiple) { _.each(that.multiple, function(entity, i) { var name = Utils.getName(entity.model); if (Enums.entityStateReadOnly[entity.model.status]) { obj.deletedEntity.push(name); } else { if (_.indexOf((entity.model.classificationNames || _.pluck(entity.model.classifications, 'typeName')), tagName) === -1) { obj.guid.push(entity.model.guid) } else { obj.skipEntity.push(name); } } }); if (obj.deletedEntity.length) { Utils.notifyError({ html: true, content: "<b>" + obj.deletedEntity.join(', ') + "</b> " + (obj.deletedEntity.length === 1 ? "entity " : "entities ") + Messages.assignDeletedEntity }); } if (obj.skipEntity.length) { var text = "<b>" + obj.skipEntity.length + " of " + that.multiple.length + "</b> entities selected have already been associated with <b>" + tagName + "</b> tag, Do you want to associate the tag with other entities ?", removeCancelButton = false; if ((obj.skipEntity.length + obj.deletedEntity.length) === that.multiple.length) { text = (obj.skipEntity.length > 1 ? "All selected" : "Selected") + " entities have already been associated with <b>" + tagName + "</b> tag"; removeCancelButton = true; } var notifyObj = { text: text, modal: true, ok: function(argument) { if (obj.guid.length) { that.saveTagData(obj); } else { that.hideLoader(); } }, cancel: function(argument) { that.hideLoader(); obj = { tagName: tagName, tagAttributes: tagAttributes, guid: [], skipEntity: [], deletedEntity: [] } } } if (removeCancelButton) { notifyObj['confirm'] = { confirm: true, buttons: [{ text: 'Ok', addClass: 'btn-primary', click: function(notice) { notice.remove(); obj = { tagName: tagName, tagAttributes: tagAttributes, guid: [], skipEntity: [], deletedEntity: [] } } }, null ] } } Utils.notifyConfirm(notifyObj) } else { if (obj.guid.length) { that.saveTagData(obj); } else { that.hideLoader(); } } } else { obj.guid.push(that.guid); that.saveTagData(obj); } }); this.on('closeModal', function() { this.modal.trigger('cancel'); }); this.bindEvents(); }, onRender: function() { var that = this; $.extend(this.collection.queryParams, { type: 'classification' }); this.hideAttributeBox(); this.collection.fetch({ reset: true, complete: function() { if (that.tagModel) { that.fetchTagSubData(that.tagModel.typeName); } that.showAttributeBox(); }, }); }, bindEvents: function() { var that = this; this.enumArr = []; this.listenTo(this.collection, 'reset', function() { this.tagsCollection(); }, this); this.listenTo(this.commonCollection, 'reset', function() { this.subAttributeData(); }, this); }, tagsCollection: function() { var that = this; this.collection.fullCollection.comparator = function(model) { return Utils.getName(model.toJSON(), 'name').toLowerCase(); } var str = '<option selected="selected" disabled="disabled">-- Select a tag from the dropdown list --</option>'; this.collection.fullCollection.sort().each(function(obj, key) { var name = Utils.getName(obj.toJSON(), 'name'); if (name === "TaxonomyTerm") { return; } // using obj.get('name') insted of name variable because if html is presen in name then escaped name will not found in tagList. if (_.indexOf(that.tagList, obj.get('name')) === -1) { str += '<option ' + (that.tagModel && that.tagModel.typeName === name ? 'selected' : '') + '>' + name + '</option>'; } }); this.ui.addTagOptions.html(str); this.ui.addTagOptions.select2({ placeholder: "Select Tag", allowClear: false }); }, onChangeTagDefination: function() { this.ui.addTagOptions.select2("open").select2("close"); this.ui.tagAttribute.empty(); var saveBtn = this.modal.$el.find('button.ok'); saveBtn.prop("disabled", false); var tagname = this.ui.addTagOptions.val(); this.hideAttributeBox(); this.fetchTagSubData(tagname); }, fetchTagSubData: function(tagname) { var attributeDefs = Utils.getNestedSuperTypeObj({ data: this.collection.fullCollection.find({ name: tagname }).toJSON(), collection: this.collection, attrMerge: true }); this.subAttributeData(attributeDefs); }, showAttributeBox: function() { var that = this; this.$('.attrLoader').hide(); this.$('.form-group.hide').removeClass('hide'); if (this.ui.tagAttribute.children().length !== 0) { this.ui.tagAttribute.parent().show(); } this.ui.tagAttribute.find('input,select').on("keyup change", function(e) { if (e.keyCode != 32) { that.modal.$el.find('button.ok').attr("disabled", false); } }); }, hideAttributeBox: function() { this.ui.tagAttribute.children().empty(); this.ui.tagAttribute.parent().hide(); this.$('.attrLoader').show(); }, subAttributeData: function(attributeDefs) { var that = this; if (attributeDefs) { _.each(attributeDefs, function(obj) { var name = Utils.getName(obj, 'name'); var typeName = Utils.getName(obj, 'typeName'); var typeNameValue = that.enumDefCollection.fullCollection.findWhere({ 'name': typeName }); if (typeNameValue) { var str = '<option value=""' + (!that.tagModel ? 'selected' : '') + '>-- Select ' + typeName + " --</option>"; var enumValue = typeNameValue.get('elementDefs'); _.each(enumValue, function(key, value) { str += '<option ' + ((that.tagModel && key.value === that.tagModel.attributes[name]) ? 'selected' : '') + '>' + key.value + '</option>'; }) that.ui.tagAttribute.append('<div class="form-group"><label>' + name + '</label>' + ' (' + typeName + ')' + '<select class="form-control attributeInputVal attrName" data-key="' + name + '">' + str + '</select></div>'); } else { var textElement = that.getElement(name, typeName); that.ui.tagAttribute.append('<div class="form-group"><label>' + name + '</label>' + ' (' + typeName + ')' + textElement); } }); that.$('input[data-type="date"]').each(function() { if (!$(this).data('daterangepicker')) { var dateObj = { "singleDatePicker": true, "showDropdowns": true, "timePicker": true, locale: { format: 'MM/DD/YYYY h:mm A' } }; if (that.tagModel) { var formatDate = Number(this.value); dateObj["startDate"] = new Date(formatDate); } $(this).daterangepicker(dateObj); } }); that.$('select[data-type="boolean"]').each(function() { var labelName = $(this).data('key'); if (that.tagModel) { this.value = that.tagModel.attributes[labelName]; } }); this.showAttributeBox(); } }, getElement: function(labelName, typeName) { var value = this.tagModel && this.tagModel.attributes ? (this.tagModel.attributes[labelName] || "") : "", type = (typeName === "int" || typeName === "long" || typeName === "float" || typeName === "byte" || typeName === "double" || typeName === "short") ? "number" : "text"; if (typeName === "boolean") { return '<select class="form-control attributeInputVal attrName" data-key="' + labelName + '" data-type="' + typeName + '"> ' + '<option value="">--Select true or false--</option>' + '<option value="true">true</option>' + '<option value="false">false</option></select>'; } else { return '<input type="' + type + '" value="' + value + '" class="form-control attributeInputVal attrName" data-key="' + labelName + '" data-type="' + typeName + '"></input></div>'; } }, saveTagData: function(options) { var that = this; this.entityModel = new VEntity(); var tagName = options.tagName, tagAttributes = options.tagAttributes, json = { "classification": { "typeName": tagName, "attributes": tagAttributes }, "entityGuids": options.guid }; if (this.tagModel) { json = [{ "typeName": tagName, "attributes": tagAttributes }] } if (this.showLoader) { this.showLoader(); } this.entityModel.saveTraitsEntity(this.tagModel ? options.guid : null, { skipDefaultError: true, data: JSON.stringify(json), type: this.tagModel ? 'PUT' : 'POST', success: function(data) { var addupdatetext = that.tagModel ? 'updated successfully to ' : 'added to '; Utils.notifySuccess({ content: "Tag " + tagName + " has been " + addupdatetext + (that.multiple ? "entities" : "entity") }); if (options.modalCollection) { options.modalCollection.fetch({ reset: true }); } if (that.callback) { that.callback(); } }, cust_error: function(model, response) { var message = "Tag " + tagName + " could not be added"; if (response && response.responseJSON) { message = response.responseJSON.errorMessage; } Utils.notifyError({ content: message }); if (that.hideLoader) { that.hideLoader(); } } }); }, }); return AddTagModel; }); <|start_filename|>common/src/main/java/org/apache/atlas/repository/Constants.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository; /** * Repository Constants. * */ public final class Constants { /** * Globally Unique identifier property key. */ public static final String INTERNAL_PROPERTY_KEY_PREFIX = "__"; public static final String GUID_PROPERTY_KEY = INTERNAL_PROPERTY_KEY_PREFIX + "guid"; /** * Entity type name property key. */ public static final String ENTITY_TYPE_PROPERTY_KEY = INTERNAL_PROPERTY_KEY_PREFIX + "typeName"; /** * Entity type's super types property key. */ public static final String SUPER_TYPES_PROPERTY_KEY = INTERNAL_PROPERTY_KEY_PREFIX + "superTypeNames"; /** * Full-text for the entity for enabling full-text search. */ //weird issue in TitanDB if __ added to this property key. Not adding it for now public static final String ENTITY_TEXT_PROPERTY_KEY = "entityText"; /** * Properties for type store graph. */ public static final String TYPE_CATEGORY_PROPERTY_KEY = INTERNAL_PROPERTY_KEY_PREFIX + "type.category"; public static final String VERTEX_TYPE_PROPERTY_KEY = INTERNAL_PROPERTY_KEY_PREFIX + "type"; public static final String TYPENAME_PROPERTY_KEY = INTERNAL_PROPERTY_KEY_PREFIX + "type.name"; public static final String TYPEDESCRIPTION_PROPERTY_KEY = INTERNAL_PROPERTY_KEY_PREFIX + "type.description"; public static final String TYPEVERSION_PROPERTY_KEY = INTERNAL_PROPERTY_KEY_PREFIX + "type.version"; public static final String TYPEOPTIONS_PROPERTY_KEY = INTERNAL_PROPERTY_KEY_PREFIX + "type.options"; // relationship def constants public static final String RELATIONSHIPTYPE_END1_KEY = "endDef1"; public static final String RELATIONSHIPTYPE_END2_KEY = "endDef2"; public static final String RELATIONSHIPTYPE_CATEGORY_KEY = "relationshipCategory"; public static final String RELATIONSHIPTYPE_TAG_PROPAGATION_KEY = "tagPropagation"; /** * Trait names property key and index name. */ public static final String TRAIT_NAMES_PROPERTY_KEY = INTERNAL_PROPERTY_KEY_PREFIX + "traitNames"; public static final String VERSION_PROPERTY_KEY = INTERNAL_PROPERTY_KEY_PREFIX + "version"; public static final String STATE_PROPERTY_KEY = INTERNAL_PROPERTY_KEY_PREFIX + "state"; public static final String CREATED_BY_KEY = INTERNAL_PROPERTY_KEY_PREFIX + "createdBy"; public static final String MODIFIED_BY_KEY = INTERNAL_PROPERTY_KEY_PREFIX + "modifiedBy"; public static final String TIMESTAMP_PROPERTY_KEY = INTERNAL_PROPERTY_KEY_PREFIX + "timestamp"; public static final String MODIFICATION_TIMESTAMP_PROPERTY_KEY = INTERNAL_PROPERTY_KEY_PREFIX + "modificationTimestamp"; /** * search backing index name. */ public static final String BACKING_INDEX = "search"; /** * search backing index name for vertex keys. */ public static final String VERTEX_INDEX = "vertex_index"; /** * search backing index name for edge labels. */ public static final String EDGE_INDEX = "edge_index"; public static final String FULLTEXT_INDEX = "fulltext_index"; public static final String QUALIFIED_NAME = "Referenceable.qualifiedName"; public static final String TYPE_NAME_PROPERTY_KEY = INTERNAL_PROPERTY_KEY_PREFIX + "typeName"; public static final String INDEX_SEARCH_MAX_RESULT_SET_SIZE = "atlas.graph.index.search.max-result-set-size"; public static final String INDEX_SEARCH_TYPES_MAX_QUERY_STR_LENGTH = "atlas.graph.index.search.types.max-query-str-length"; public static final String INDEX_SEARCH_TAGS_MAX_QUERY_STR_LENGTH = "atlas.graph.index.search.tags.max-query-str-length"; private Constants() { } } <|start_filename|>authorization/src/main/java/org/apache/atlas/authorize/simple/FileReaderUtil.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.authorize.simple; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FileReaderUtil { private static Logger LOG = LoggerFactory.getLogger(FileReaderUtil.class); private static boolean isDebugEnabled = LOG.isDebugEnabled(); public static List<String> readFile(InputStream policyStoreStream) throws IOException { if (isDebugEnabled) { LOG.debug("==> FileReaderUtil readFile()"); } List<String> list = new ArrayList<>(); List<String> fileLines = IOUtils.readLines(policyStoreStream, StandardCharsets.UTF_8); if (fileLines != null) { for (String line : fileLines) { if ((!line.startsWith("#")) && Pattern.matches(".+;;.*;;.*;;.+", line)) list.add(line); } } if (isDebugEnabled) { LOG.debug("<== FileReaderUtil readFile()"); LOG.debug("Policies read :: " + list); } return list; } } <|start_filename|>repository/src/main/java/org/apache/atlas/discovery/AtlasDiscoveryService.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.discovery; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.discovery.AtlasSearchResult; import org.apache.atlas.model.discovery.SearchParameters; public interface AtlasDiscoveryService { /** * * @param query search query in DSL format. * @param limit number of resultant rows (for pagination). [ limit > 0 ] and [ limit < maxlimit ]. -1 maps to atlas.search.defaultlimit property. * @param offset offset to the results returned (for pagination). [ offset >= 0 ]. -1 maps to offset 0. * @return AtlasSearchResult */ AtlasSearchResult searchUsingDslQuery(String query, int limit, int offset) throws AtlasBaseException; /** * * @param query search query. * @param excludeDeletedEntities exclude deleted entities in search result. * @param limit number of resultant rows (for pagination). [ limit > 0 ] and [ limit < maxlimit ]. -1 maps to atlas.search.defaultlimit property. * @param offset offset to the results returned (for pagination). [ offset >= 0 ]. -1 maps to offset 0. * @return AtlasSearchResult */ AtlasSearchResult searchUsingFullTextQuery(String query, boolean excludeDeletedEntities, int limit, int offset) throws AtlasBaseException; /** * * @param query search query. * @param type entity type. * @param classification classification name. * @param attrName attribute name. * @param attrValuePrefix attribute value prefix. * @param excludeDeletedEntities exclude deleted entities in search result. * @param limit number of resultant rows (for pagination). [ limit > 0 ] and [ limit < maxlimit ]. -1 maps to atlas.search.defaultlimit property. * @param offset offset to the results returned (for pagination). [ offset >= 0 ]. -1 maps to offset 0. * @return AtlasSearchResult */ AtlasSearchResult searchUsingBasicQuery(String query, String type, String classification, String attrName, String attrValuePrefix, boolean excludeDeletedEntities, int limit, int offset) throws AtlasBaseException; /** * Search for entities matching the search criteria * @param searchParameters Search criteria * @return Matching entities * @throws AtlasBaseException */ AtlasSearchResult searchWithParameters(SearchParameters searchParameters) throws AtlasBaseException; } <|start_filename|>repository/src/main/java/org/apache/atlas/gremlin/optimizer/GremlinQueryOptimizer.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.gremlin.optimizer; import java.util.ArrayList; import java.util.List; import org.apache.atlas.gremlin.GremlinExpressionFactory; import org.apache.atlas.groovy.AbstractFunctionExpression; import org.apache.atlas.groovy.GroovyExpression; import org.apache.atlas.groovy.StatementListExpression; import org.apache.atlas.groovy.TraversalStepType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.VisibleForTesting; /** * Optimizer for gremlin queries. This class provides a framework for applying optimizations * to gremlin queries. Each optimization is implemented as a class that implements {@link GremlinOptimization}. * * The GremlinQueryOptimizer is the entry point for applying these optimizations. * * */ public final class GremlinQueryOptimizer { private static final Logger LOGGER = LoggerFactory.getLogger(GremlinQueryOptimizer.class); private final List<GremlinOptimization> optimizations = new ArrayList<>(); //Allows expression factory to be substituted in unit tests. private static volatile GremlinExpressionFactory FACTORY = GremlinExpressionFactory.INSTANCE; private static volatile GremlinQueryOptimizer INSTANCE = null; private GremlinQueryOptimizer() { } private void addOptimization(GremlinOptimization opt) { optimizations.add(opt); } public static GremlinQueryOptimizer getInstance() { if(INSTANCE == null) { synchronized(GremlinQueryOptimizer.class) { if(INSTANCE == null) { GremlinQueryOptimizer createdInstance = new GremlinQueryOptimizer(); //The order here is important. If there is an "or" nested within an "and", //that will not be found if ExpandOrsOptimization runs before ExpandAndsOptimization. createdInstance.addOptimization(new ExpandAndsOptimization(FACTORY)); createdInstance.addOptimization(new ExpandOrsOptimization(FACTORY)); INSTANCE = createdInstance; } } } return INSTANCE; } /** * For testing only */ @VisibleForTesting public static void setExpressionFactory(GremlinExpressionFactory factory) { GremlinQueryOptimizer.FACTORY = factory; } /** * For testing only */ @VisibleForTesting public static void reset() { INSTANCE = null; } /** * Optimizes the provided groovy expression. Note that the optimization * is a <i>destructive</i> process. The source GroovyExpression will be * modified as part of the optimization process. This is done to avoid * expensive copying operations where possible. * * @param source what to optimize * @return the optimized query */ public GroovyExpression optimize(GroovyExpression source) { LOGGER.debug("Optimizing gremlin query: " + source); OptimizationContext context = new OptimizationContext(); GroovyExpression updatedExpression = source; for (GremlinOptimization opt : optimizations) { updatedExpression = optimize(updatedExpression, opt, context); LOGGER.debug("After "+ opt.getClass().getSimpleName() + ", query = " + updatedExpression); } StatementListExpression result = new StatementListExpression(); result.addStatements(context.getInitialStatements()); result.addStatement(updatedExpression); LOGGER.debug("Final optimized query: " + result.toString()); return result; } /** * Optimizes the expression using the given optimization * @param source * @param optimization * @param context * @return */ private GroovyExpression optimize(GroovyExpression source, GremlinOptimization optimization, OptimizationContext context) { GroovyExpression result = source; if (optimization.appliesTo(source, context)) { //Apply the optimization to the expression. result = optimization.apply(source, context); } if (optimization.isApplyRecursively()) { //Visit the children, update result with the optimized //children. List<GroovyExpression> updatedChildren = new ArrayList<>(); boolean changed = false; for (GroovyExpression child : result.getChildren()) { //Recursively optimize this child. GroovyExpression updatedChild = optimize(child, optimization, context); changed |= updatedChild != child; updatedChildren.add(updatedChild); } if (changed) { //TBD - Can we update in place rather than making a copy? result = result.copy(updatedChildren); } } return result; } /** * Visits all expressions in the call hierarchy of an expression. For example, * in the expression g.V().has('x','y'), the order would be * <ol> * <li>pre-visit has('x','y')</li> * <li>pre-visit V()</li> * <li>visit g (non-function caller)</li> * <li>post-visit V()</li> * <li>post-visit has('x','y')</li> * </ol> * @param expr * @param visitor */ public static void visitCallHierarchy(GroovyExpression expr, CallHierarchyVisitor visitor) { if (expr == null) { visitor.visitNullCaller(); return; } if (expr instanceof AbstractFunctionExpression) { AbstractFunctionExpression functionCall = (AbstractFunctionExpression)expr; if (!visitor.preVisitFunctionCaller(functionCall)) { return; } GroovyExpression caller = functionCall.getCaller(); visitCallHierarchy(caller, visitor); if (!visitor.postVisitFunctionCaller(functionCall)) { return; } } else { visitor.visitNonFunctionCaller(expr); } } /** * Determines if the given expression is an "or" expression. * @param expr * @return */ public static boolean isOrExpression(GroovyExpression expr) { return IsOr.INSTANCE.apply(expr); } /** * Determines whether the given expression can safely * be pulled out of an and/or expression. * * @param expr an argument to an and or or function * @return */ public static boolean isExtractable(GroovyExpression expr) { HasForbiddenType hasForbiddenTypePredicate = new HasForbiddenType(FACTORY); //alias could conflict with alias in parent traversal hasForbiddenTypePredicate.addForbiddenType(TraversalStepType.SIDE_EFFECT); //inlining out(), in() steps will change the result of calls after the and/or() hasForbiddenTypePredicate.addForbiddenType(TraversalStepType.FLAT_MAP_TO_ELEMENTS); hasForbiddenTypePredicate.addForbiddenType(TraversalStepType.FLAT_MAP_TO_VALUES); hasForbiddenTypePredicate.addForbiddenType(TraversalStepType.BARRIER); hasForbiddenTypePredicate.addForbiddenType(TraversalStepType.MAP_TO_ELEMENT); hasForbiddenTypePredicate.addForbiddenType(TraversalStepType.MAP_TO_VALUE); //caller expects to be able to continue the traversal. We can't end it hasForbiddenTypePredicate.addForbiddenType(TraversalStepType.END); //we can't inline child traversals hasForbiddenTypePredicate.addForbiddenType(TraversalStepType.SOURCE); hasForbiddenTypePredicate.addForbiddenType(TraversalStepType.START); hasForbiddenTypePredicate.addForbiddenType(TraversalStepType.SIDE_EFFECT); hasForbiddenTypePredicate.addForbiddenType(TraversalStepType.NONE); hasForbiddenTypePredicate.addForbiddenType(TraversalStepType.BRANCH); ExpressionFinder forbiddenExpressionFinder = new ExpressionFinder(hasForbiddenTypePredicate); GremlinQueryOptimizer.visitCallHierarchy(expr, forbiddenExpressionFinder); return ! forbiddenExpressionFinder.isExpressionFound(); } /** * Recursively copies and follows the caller hierarchy of the expression until we come * to a function call with a null caller. The caller of that expression is set * to newLeaf. * * @param expr * @param newLeaf * @return the updated (/copied) expression */ public static GroovyExpression copyWithNewLeafNode(AbstractFunctionExpression expr, GroovyExpression newLeaf) { AbstractFunctionExpression result = (AbstractFunctionExpression)expr.copy(); //remove leading anonymous traversal expression, if there is one if(FACTORY.isLeafAnonymousTraversalExpression(expr)) { result = (AbstractFunctionExpression)newLeaf; } else { GroovyExpression newCaller = null; if (expr.getCaller() == null) { newCaller = newLeaf; } else { newCaller = copyWithNewLeafNode((AbstractFunctionExpression)result.getCaller(), newLeaf); } result.setCaller(newCaller); } return result; } } <|start_filename|>addons/hive-bridge/src/main/java/org/apache/atlas/hive/bridge/HiveMetaStoreBridge.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.hive.bridge; import com.google.common.annotations.VisibleForTesting; import com.sun.jersey.api.client.ClientResponse; import org.apache.atlas.ApplicationProperties; import org.apache.atlas.AtlasClient; import org.apache.atlas.AtlasConstants; import org.apache.atlas.AtlasServiceException; import org.apache.atlas.hive.hook.HiveHook; import org.apache.atlas.hive.model.HiveDataTypes; import org.apache.atlas.hook.AtlasHookException; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.Struct; import org.apache.atlas.typesystem.json.InstanceSerialization; import org.apache.atlas.typesystem.persistence.Id; import org.apache.atlas.utils.AuthenticationUtil; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Options; import org.apache.commons.configuration.Configuration; import org.apache.commons.lang.RandomStringUtils; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.metastore.TableType; import org.apache.hadoop.hive.metastore.api.Database; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.metastore.api.Order; import org.apache.hadoop.hive.metastore.api.SerDeInfo; import org.apache.hadoop.hive.metastore.api.StorageDescriptor; import org.apache.hadoop.hive.ql.metadata.Hive; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.metadata.Table; import org.apache.hadoop.hive.ql.session.SessionState; import org.apache.hadoop.security.UserGroupInformation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * A Bridge Utility that imports metadata from the Hive Meta Store * and registers them in Atlas. */ public class HiveMetaStoreBridge { private static final String DEFAULT_DGI_URL = "http://localhost:21000/"; public static final String HIVE_CLUSTER_NAME = "atlas.cluster.name"; public static final String DEFAULT_CLUSTER_NAME = "primary"; public static final String DESCRIPTION_ATTR = "description"; public static final String TEMP_TABLE_PREFIX = "_temp-"; private final String clusterName; public static final long MILLIS_CONVERT_FACTOR = 1000; public static final String ATLAS_ENDPOINT = "atlas.rest.address"; public static final String COMMENT = "comment"; public static final String PARAMETERS = "parameters"; public static final String COLUMNS = "columns"; public static final String POSITION = "position"; public static final String PART_COLS = "partitionKeys"; public static final String TABLE_ALIAS_LIST = "aliases"; public static final String STORAGE_NUM_BUCKETS = "numBuckets"; public static final String STORAGE_IS_STORED_AS_SUB_DIRS = "storedAsSubDirectories"; public static final String TABLE = "table"; public static final String DB = "db"; public static final String STORAGE_DESC = "sd"; public static final String STORAGE_DESC_INPUT_FMT = "inputFormat"; public static final String STORAGE_DESC_OUTPUT_FMT = "outputFormat"; public static final String LOCATION = "location"; public static final String TABLE_TYPE_ATTR = "tableType"; public static final String CREATE_TIME = "createTime"; public static final String LAST_ACCESS_TIME = "lastAccessTime"; public static final String HDFS_PATH = "hdfs_path"; private static final Logger LOG = LoggerFactory.getLogger(HiveMetaStoreBridge.class); public final Hive hiveClient; private AtlasClient atlasClient = null; HiveMetaStoreBridge(String clusterName, Hive hiveClient, AtlasClient atlasClient) { this.clusterName = clusterName; this.hiveClient = hiveClient; this.atlasClient = atlasClient; } public String getClusterName() { return clusterName; } /** * Construct a HiveMetaStoreBridge. * @param hiveConf {@link HiveConf} for Hive component in the cluster */ public HiveMetaStoreBridge(Configuration atlasProperties, HiveConf hiveConf) throws Exception { this(atlasProperties, hiveConf, null); } /** * Construct a HiveMetaStoreBridge. * @param hiveConf {@link HiveConf} for Hive component in the cluster */ public HiveMetaStoreBridge(Configuration atlasProperties, HiveConf hiveConf, AtlasClient atlasClient) throws Exception { this(atlasProperties.getString(HIVE_CLUSTER_NAME, DEFAULT_CLUSTER_NAME), Hive.get(hiveConf), atlasClient); } AtlasClient getAtlasClient() { return atlasClient; } void importHiveMetadata(boolean failOnError) throws Exception { LOG.info("Importing hive metadata"); importDatabases(failOnError); } private void importDatabases(boolean failOnError) throws Exception { List<String> databases = hiveClient.getAllDatabases(); for (String databaseName : databases) { Referenceable dbReference = registerDatabase(databaseName); if (dbReference != null) { importTables(dbReference, databaseName, failOnError); } } } /** * Create a Hive Database entity * @param hiveDB The Hive {@link Database} object from which to map properties * @return new Hive Database entity * @throws HiveException */ public Referenceable createDBInstance(Database hiveDB) throws HiveException { return createOrUpdateDBInstance(hiveDB, null); } /** * Checks if db is already registered, else creates and registers db entity * @param databaseName * @return * @throws Exception */ private Referenceable registerDatabase(String databaseName) throws Exception { Referenceable dbRef = getDatabaseReference(clusterName, databaseName); Database db = hiveClient.getDatabase(databaseName); if (db != null) { if (dbRef == null) { dbRef = createDBInstance(db); dbRef = registerInstance(dbRef); } else { LOG.info("Database {} is already registered with id {}. Updating it.", databaseName, dbRef.getId().id); dbRef = createOrUpdateDBInstance(db, dbRef); updateInstance(dbRef); } } return dbRef; } private Referenceable createOrUpdateDBInstance(Database hiveDB, Referenceable dbRef) { LOG.info("Importing objects from databaseName : {}", hiveDB.getName()); if (dbRef == null) { dbRef = new Referenceable(HiveDataTypes.HIVE_DB.getName()); } String dbName = hiveDB.getName().toLowerCase(); dbRef.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, getDBQualifiedName(clusterName, dbName)); dbRef.set(AtlasClient.NAME, dbName); dbRef.set(AtlasConstants.CLUSTER_NAME_ATTRIBUTE, clusterName); dbRef.set(DESCRIPTION_ATTR, hiveDB.getDescription()); dbRef.set(LOCATION, hiveDB.getLocationUri()); dbRef.set(PARAMETERS, hiveDB.getParameters()); dbRef.set(AtlasClient.OWNER, hiveDB.getOwnerName()); if (hiveDB.getOwnerType() != null) { dbRef.set("ownerType", hiveDB.getOwnerType().getValue()); } return dbRef; } /** * Registers an entity in atlas * @param referenceable * @return * @throws Exception */ private Referenceable registerInstance(Referenceable referenceable) throws Exception { String typeName = referenceable.getTypeName(); LOG.debug("creating instance of type {}", typeName); String entityJSON = InstanceSerialization.toJson(referenceable, true); LOG.debug("Submitting new entity {} = {}", referenceable.getTypeName(), entityJSON); List<String> guids = getAtlasClient().createEntity(entityJSON); LOG.debug("created instance for type {}, guid: {}", typeName, guids); return new Referenceable(guids.get(guids.size() - 1), referenceable.getTypeName(), null); } /** * Gets reference to the atlas entity for the database * @param databaseName database Name * @param clusterName cluster name * @return Reference for database if exists, else null * @throws Exception */ private Referenceable getDatabaseReference(String clusterName, String databaseName) throws Exception { LOG.debug("Getting reference for database {}", databaseName); String typeName = HiveDataTypes.HIVE_DB.getName(); return getEntityReference(typeName, getDBQualifiedName(clusterName, databaseName)); } /** * Construct the qualified name used to uniquely identify a Database instance in Atlas. * @param clusterName Name of the cluster to which the Hive component belongs * @param dbName Name of the Hive database * @return Unique qualified name to identify the Database instance in Atlas. */ public static String getDBQualifiedName(String clusterName, String dbName) { return String.format("%s@%s", dbName.toLowerCase(), clusterName); } private String getCreateTableString(Table table, String location){ String colString = ""; List<FieldSchema> colList = table.getAllCols(); if ( colList != null) { for (FieldSchema col : colList) { colString += col.getName() + " " + col.getType() + ","; } if (colList.size() > 0) { colString = colString.substring(0, colString.length() - 1); colString = "(" + colString + ")"; } } String query = "create external table " + table.getTableName() + colString + " location '" + location + "'"; return query; } /** * Imports all tables for the given db * @param databaseReferenceable * @param databaseName * @param failOnError * @throws Exception */ private int importTables(Referenceable databaseReferenceable, String databaseName, final boolean failOnError) throws Exception { int tablesImported = 0; List<String> hiveTables = hiveClient.getAllTables(databaseName); LOG.info("Importing tables {} for db {}", hiveTables.toString(), databaseName); for (String tableName : hiveTables) { int imported = importTable(databaseReferenceable, databaseName, tableName, failOnError); tablesImported += imported; } if (tablesImported == hiveTables.size()) { LOG.info("Successfully imported all {} tables from {} ", tablesImported, databaseName); } else { LOG.error("Able to import {} tables out of {} tables from {}. Please check logs for import errors", tablesImported, hiveTables.size(), databaseName); } return tablesImported; } @VisibleForTesting public int importTable(Referenceable databaseReferenceable, String databaseName, String tableName, final boolean failOnError) throws Exception { try { Table table = hiveClient.getTable(databaseName, tableName); Referenceable tableReferenceable = registerTable(databaseReferenceable, table); if (table.getTableType() == TableType.EXTERNAL_TABLE) { String tableQualifiedName = getTableProcessQualifiedName(clusterName, table); Referenceable process = getProcessReference(tableQualifiedName); if (process == null) { LOG.info("Attempting to register create table process for {}", tableQualifiedName); Referenceable lineageProcess = new Referenceable(HiveDataTypes.HIVE_PROCESS.getName()); ArrayList<Referenceable> sourceList = new ArrayList<>(); ArrayList<Referenceable> targetList = new ArrayList<>(); String tableLocation = table.getDataLocation().toString(); Referenceable path = fillHDFSDataSet(tableLocation); String query = getCreateTableString(table, tableLocation); sourceList.add(path); targetList.add(tableReferenceable); lineageProcess.set("inputs", sourceList); lineageProcess.set("outputs", targetList); lineageProcess.set("userName", table.getOwner()); lineageProcess.set("startTime", new Date(System.currentTimeMillis())); lineageProcess.set("endTime", new Date(System.currentTimeMillis())); lineageProcess.set("operationType", "CREATETABLE"); lineageProcess.set("queryText", query); lineageProcess.set("queryId", query); lineageProcess.set("queryPlan", "{}"); lineageProcess.set("clusterName", clusterName); List<String> recentQueries = new ArrayList<>(1); recentQueries.add(query); lineageProcess.set("recentQueries", recentQueries); String processQualifiedName = getTableProcessQualifiedName(clusterName, table); lineageProcess.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, processQualifiedName); lineageProcess.set(AtlasClient.NAME, query); registerInstance(lineageProcess); } else { LOG.info("Process {} is already registered", process.toString()); } } return 1; } catch (Exception e) { LOG.error("Import failed for hive_table {} ", tableName, e); if (failOnError) { throw e; } return 0; } } /** * Gets reference for the table * * @param hiveTable * @return table reference if exists, else null * @throws Exception */ private Referenceable getTableReference(Table hiveTable) throws Exception { LOG.debug("Getting reference for table {}.{}", hiveTable.getDbName(), hiveTable.getTableName()); String typeName = HiveDataTypes.HIVE_TABLE.getName(); String tblQualifiedName = getTableQualifiedName(getClusterName(), hiveTable.getDbName(), hiveTable.getTableName()); return getEntityReference(typeName, tblQualifiedName); } private Referenceable getEntityReference(final String typeName, final String tblQualifiedName) throws AtlasServiceException { AtlasClient dgiClient = getAtlasClient(); try { return dgiClient.getEntity(typeName, AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, tblQualifiedName); } catch (AtlasServiceException e) { if(e.getStatus() == ClientResponse.Status.NOT_FOUND) { return null; } throw e; } } private Referenceable getProcessReference(String qualifiedName) throws Exception{ LOG.debug("Getting reference for process {}", qualifiedName); String typeName = HiveDataTypes.HIVE_PROCESS.getName(); return getEntityReference(typeName, qualifiedName); } /** * Construct the qualified name used to uniquely identify a Table instance in Atlas. * @param clusterName Name of the cluster to which the Hive component belongs * @param dbName Name of the Hive database to which the Table belongs * @param tableName Name of the Hive table * @return Unique qualified name to identify the Table instance in Atlas. */ public static String getTableQualifiedName(String clusterName, String dbName, String tableName, boolean isTemporaryTable) { String tableTempName = tableName; if (isTemporaryTable) { if (SessionState.get() != null && SessionState.get().getSessionId() != null) { tableTempName = tableName + TEMP_TABLE_PREFIX + SessionState.get().getSessionId(); } else { tableTempName = tableName + TEMP_TABLE_PREFIX + RandomStringUtils.random(10); } } return String.format("%s.%s@%s", dbName.toLowerCase(), tableTempName.toLowerCase(), clusterName); } /** * Construct the qualified name used to uniquely identify a Table instance in Atlas. * @param clusterName Name of the cluster to which the Hive component belongs * @param table hive table for which the qualified name is needed * @return Unique qualified name to identify the Table instance in Atlas. */ public static String getTableQualifiedName(String clusterName, Table table) { return getTableQualifiedName(clusterName, table.getDbName(), table.getTableName(), table.isTemporary()); } public static String getTableProcessQualifiedName(String clusterName, Table table) { String tableQualifiedName = getTableQualifiedName(clusterName, table); Date createdTime = getTableCreatedTime(table); return tableQualifiedName + HiveHook.SEP + createdTime.getTime(); } /** * Construct the qualified name used to uniquely identify a Table instance in Atlas. * @param clusterName Name of the cluster to which the Hive component belongs * @param dbName Name of the Hive database to which the Table belongs * @param tableName Name of the Hive table * @return Unique qualified name to identify the Table instance in Atlas. */ public static String getTableQualifiedName(String clusterName, String dbName, String tableName) { return getTableQualifiedName(clusterName, dbName, tableName, false); } /** * Create a new table instance in Atlas * @param dbReference reference to a created Hive database {@link Referenceable} to which this table belongs * @param hiveTable reference to the Hive {@link Table} from which to map properties * @return Newly created Hive reference * @throws Exception */ public Referenceable createTableInstance(Referenceable dbReference, Table hiveTable) throws AtlasHookException { return createOrUpdateTableInstance(dbReference, null, hiveTable); } public static Date getTableCreatedTime(Table table) { return new Date(table.getTTable().getCreateTime() * MILLIS_CONVERT_FACTOR); } private Referenceable createOrUpdateTableInstance(Referenceable dbReference, Referenceable tableReference, final Table hiveTable) throws AtlasHookException { LOG.info("Importing objects from {}.{}", hiveTable.getDbName(), hiveTable.getTableName()); if (tableReference == null) { tableReference = new Referenceable(HiveDataTypes.HIVE_TABLE.getName()); } String tableQualifiedName = getTableQualifiedName(clusterName, hiveTable); tableReference.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, tableQualifiedName); tableReference.set(AtlasClient.NAME, hiveTable.getTableName().toLowerCase()); tableReference.set(AtlasClient.OWNER, hiveTable.getOwner()); Date createDate = new Date(); if (hiveTable.getTTable() != null){ try { createDate = getTableCreatedTime(hiveTable); LOG.debug("Setting create time to {} ", createDate); tableReference.set(CREATE_TIME, createDate); } catch(Exception ne) { LOG.error("Error while setting createTime for the table {} ", hiveTable.getCompleteName(), ne); } } Date lastAccessTime = createDate; if ( hiveTable.getLastAccessTime() > 0) { lastAccessTime = new Date(hiveTable.getLastAccessTime() * MILLIS_CONVERT_FACTOR); } tableReference.set(LAST_ACCESS_TIME, lastAccessTime); tableReference.set("retention", hiveTable.getRetention()); tableReference.set(COMMENT, hiveTable.getParameters().get(COMMENT)); // add reference to the database tableReference.set(DB, dbReference); // add reference to the StorageDescriptor Referenceable sdReferenceable = fillStorageDesc(hiveTable.getSd(), tableQualifiedName, getStorageDescQFName(tableQualifiedName), tableReference.getId()); tableReference.set(STORAGE_DESC, sdReferenceable); tableReference.set(PARAMETERS, hiveTable.getParameters()); if (hiveTable.getViewOriginalText() != null) { tableReference.set("viewOriginalText", hiveTable.getViewOriginalText()); } if (hiveTable.getViewExpandedText() != null) { tableReference.set("viewExpandedText", hiveTable.getViewExpandedText()); } tableReference.set(TABLE_TYPE_ATTR, hiveTable.getTableType().name()); tableReference.set("temporary", hiveTable.isTemporary()); // add reference to the Partition Keys List<Referenceable> partKeys = getColumns(hiveTable.getPartitionKeys(), tableReference); tableReference.set("partitionKeys", partKeys); tableReference.set(COLUMNS, getColumns(hiveTable.getCols(), tableReference)); return tableReference; } public static String getStorageDescQFName(String entityQualifiedName) { return entityQualifiedName + "_storage"; } private Referenceable registerTable(Referenceable dbReference, Table table) throws AtlasHookException { try { String dbName = table.getDbName(); String tableName = table.getTableName(); LOG.info("Attempting to register table [{}]", tableName); Referenceable tableReference = getTableReference(table); LOG.info("Found result {}", tableReference); if (tableReference == null) { tableReference = createTableInstance(dbReference, table); tableReference = registerInstance(tableReference); } else { LOG.info("Table {}.{} is already registered with id {}. Updating entity.", dbName, tableName, tableReference.getId().id); tableReference = createOrUpdateTableInstance(dbReference, tableReference, table); updateInstance(tableReference); } return tableReference; } catch (Exception e) { throw new AtlasHookException("HiveMetaStoreBridge.getStorageDescQFName() failed.", e); } } private void updateInstance(Referenceable referenceable) throws AtlasServiceException { String typeName = referenceable.getTypeName(); LOG.debug("updating instance of type {}", typeName); String entityJSON = InstanceSerialization.toJson(referenceable, true); LOG.debug("Updating entity {} = {}", referenceable.getTypeName(), entityJSON); atlasClient.updateEntity(referenceable.getId().id, referenceable); } public Referenceable fillStorageDesc(StorageDescriptor storageDesc, String tableQualifiedName, String sdQualifiedName, Id tableId) throws AtlasHookException { LOG.debug("Filling storage descriptor information for {}", storageDesc); Referenceable sdReferenceable = new Referenceable(HiveDataTypes.HIVE_STORAGEDESC.getName()); sdReferenceable.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, sdQualifiedName); SerDeInfo serdeInfo = storageDesc.getSerdeInfo(); LOG.debug("serdeInfo = {}", serdeInfo); // SkewedInfo skewedInfo = storageDesc.getSkewedInfo(); String serdeInfoName = HiveDataTypes.HIVE_SERDE.getName(); Struct serdeInfoStruct = new Struct(serdeInfoName); serdeInfoStruct.set(AtlasClient.NAME, serdeInfo.getName()); serdeInfoStruct.set("serializationLib", serdeInfo.getSerializationLib()); serdeInfoStruct.set(PARAMETERS, serdeInfo.getParameters()); sdReferenceable.set("serdeInfo", serdeInfoStruct); sdReferenceable.set(STORAGE_NUM_BUCKETS, storageDesc.getNumBuckets()); sdReferenceable .set(STORAGE_IS_STORED_AS_SUB_DIRS, storageDesc.isStoredAsSubDirectories()); List<Struct> sortColsStruct = new ArrayList<>(); for (Order sortcol : storageDesc.getSortCols()) { String hiveOrderName = HiveDataTypes.HIVE_ORDER.getName(); Struct colStruct = new Struct(hiveOrderName); colStruct.set("col", sortcol.getCol()); colStruct.set("order", sortcol.getOrder()); sortColsStruct.add(colStruct); } if (sortColsStruct.size() > 0) { sdReferenceable.set("sortCols", sortColsStruct); } sdReferenceable.set(LOCATION, storageDesc.getLocation()); sdReferenceable.set("inputFormat", storageDesc.getInputFormat()); sdReferenceable.set("outputFormat", storageDesc.getOutputFormat()); sdReferenceable.set("compressed", storageDesc.isCompressed()); if (storageDesc.getBucketCols().size() > 0) { sdReferenceable.set("bucketCols", storageDesc.getBucketCols()); } sdReferenceable.set(PARAMETERS, storageDesc.getParameters()); sdReferenceable.set("storedAsSubDirectories", storageDesc.isStoredAsSubDirectories()); sdReferenceable.set(TABLE, tableId); return sdReferenceable; } public Referenceable fillHDFSDataSet(String pathUri) { Referenceable ref = new Referenceable(HDFS_PATH); ref.set("path", pathUri); Path path = new Path(pathUri); ref.set(AtlasClient.NAME, Path.getPathWithoutSchemeAndAuthority(path).toString().toLowerCase()); ref.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, pathUri); ref.set(AtlasConstants.CLUSTER_NAME_ATTRIBUTE, clusterName); return ref; } public static String getColumnQualifiedName(final String tableQualifiedName, final String colName) { final String[] parts = tableQualifiedName.split("@"); final String tableName = parts[0]; final String clusterName = parts[1]; return String.format("%s.%s@%s", tableName, colName.toLowerCase(), clusterName); } public List<Referenceable> getColumns(List<FieldSchema> schemaList, Referenceable tableReference) throws AtlasHookException { List<Referenceable> colList = new ArrayList<>(); int columnPosition = 0; for (FieldSchema fs : schemaList) { LOG.debug("Processing field {}", fs); Referenceable colReferenceable = new Referenceable(HiveDataTypes.HIVE_COLUMN.getName()); colReferenceable.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, getColumnQualifiedName((String) tableReference.get(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME), fs.getName())); colReferenceable.set(AtlasClient.NAME, fs.getName()); colReferenceable.set(AtlasClient.OWNER, tableReference.get(AtlasClient.OWNER)); colReferenceable.set("type", fs.getType()); colReferenceable.set(POSITION, columnPosition++); colReferenceable.set(COMMENT, fs.getComment()); colReferenceable.set(TABLE, tableReference.getId()); colList.add(colReferenceable); } return colList; } public static void main(String[] args) throws AtlasHookException { try { Configuration atlasConf = ApplicationProperties.get(); String[] atlasEndpoint = atlasConf.getStringArray(ATLAS_ENDPOINT); if (atlasEndpoint == null || atlasEndpoint.length == 0){ atlasEndpoint = new String[] { DEFAULT_DGI_URL }; } AtlasClient atlasClient; if (!AuthenticationUtil.isKerberosAuthenticationEnabled()) { String[] basicAuthUsernamePassword = AuthenticationUtil.getBasicAuthenticationInput(); atlasClient = new AtlasClient(atlasEndpoint, basicAuthUsernamePassword); } else { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); atlasClient = new AtlasClient(ugi, ugi.getShortUserName(), atlasEndpoint); } Options options = new Options(); CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse( options, args); boolean failOnError = false; if (cmd.hasOption("failOnError")) { failOnError = true; } HiveMetaStoreBridge hiveMetaStoreBridge = new HiveMetaStoreBridge(atlasConf, new HiveConf(), atlasClient); hiveMetaStoreBridge.importHiveMetadata(failOnError); } catch(Exception e) { throw new AtlasHookException("HiveMetaStoreBridge.main() failed.", e); } } } <|start_filename|>webapp/src/test/java/org/apache/atlas/web/service/SecureEmbeddedServerTestBase.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.web.service; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.DefaultClientConfig; import org.apache.atlas.ApplicationProperties; import org.apache.atlas.Atlas; import org.apache.atlas.AtlasException; import org.apache.atlas.web.TestUtils; import org.apache.atlas.web.integration.AdminJerseyResourceIT; import org.apache.atlas.web.integration.EntityJerseyResourceIT; import org.apache.atlas.web.integration.MetadataDiscoveryJerseyResourceIT; import org.apache.atlas.web.integration.TypesJerseyResourceIT; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.security.alias.CredentialProvider; import org.apache.hadoop.security.alias.CredentialProviderFactory; import org.apache.hadoop.security.alias.JavaKeyStoreProvider; import org.testng.Assert; import org.testng.TestListenerAdapter; import org.testng.TestNG; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import javax.ws.rs.core.UriBuilder; import java.io.File; import java.io.IOException; import java.nio.file.Files; import static org.apache.atlas.security.SecurityProperties.CERT_STORES_CREDENTIAL_PROVIDER_PATH; import static org.apache.atlas.security.SecurityProperties.DEFAULT_KEYSTORE_FILE_LOCATION; import static org.apache.atlas.security.SecurityProperties.KEYSTORE_PASSWORD_KEY; import static org.apache.atlas.security.SecurityProperties.SERVER_CERT_PASSWORD_KEY; import static org.apache.atlas.security.SecurityProperties.TRUSTSTORE_PASSWORD_KEY; /** * Secure Test class for jersey resources. */ public class SecureEmbeddedServerTestBase { public static final int ATLAS_DEFAULT_HTTPS_PORT = 21443; private SecureEmbeddedServer secureEmbeddedServer; protected String providerUrl; private Path jksPath; protected WebResource service; private int securePort; static { //for localhost testing only javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() { public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) { return hostname.equals("localhost"); } }); System.setProperty("javax.net.ssl.trustStore", DEFAULT_KEYSTORE_FILE_LOCATION); System.setProperty("javax.net.ssl.trustStorePassword", "keypass"); System.setProperty("javax.net.ssl.trustStoreType", "JKS"); System.setProperty("https.protocols", "TLSv1.2"); } @BeforeClass public void setupSecurePort() throws AtlasException { org.apache.commons.configuration.Configuration configuration = ApplicationProperties.get(); securePort = configuration.getInt(Atlas.ATLAS_SERVER_HTTPS_PORT, ATLAS_DEFAULT_HTTPS_PORT); } @BeforeMethod public void setup() throws Exception { jksPath = new Path(Files.createTempDirectory("tempproviders").toString(), "test.jks"); providerUrl = JavaKeyStoreProvider.SCHEME_NAME + "://file/" + jksPath.toUri(); String baseUrl = String.format("https://localhost:%d/", securePort); DefaultClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); client.resource(UriBuilder.fromUri(baseUrl).build()); service = client.resource(UriBuilder.fromUri(baseUrl).build()); } @Test public void testNoConfiguredCredentialProvider() throws Exception { String originalConf = null; try { originalConf = System.getProperty("atlas.conf"); System.clearProperty("atlas.conf"); ApplicationProperties.forceReload(); secureEmbeddedServer = new SecureEmbeddedServer(securePort, TestUtils.getWarPath()); secureEmbeddedServer.server.start(); Assert.fail("Should have thrown an exception"); } catch (IOException e) { Assert.assertEquals(e.getMessage(), "No credential provider path configured for storage of certificate store passwords"); } finally { if (secureEmbeddedServer != null) { secureEmbeddedServer.server.stop(); } if (originalConf == null) { System.clearProperty("atlas.conf"); } else { System.setProperty("atlas.conf", originalConf); } } } @Test public void testMissingEntriesInCredentialProvider() throws Exception { // setup the configuration final PropertiesConfiguration configuration = new PropertiesConfiguration(); configuration.setProperty(CERT_STORES_CREDENTIAL_PROVIDER_PATH, providerUrl); try { secureEmbeddedServer = new SecureEmbeddedServer(securePort, TestUtils.getWarPath()) { @Override protected PropertiesConfiguration getConfiguration() { return configuration; } }; Assert.fail("No entries should generate an exception"); } catch (IOException e) { Assert.assertTrue(e.getMessage().startsWith("No credential entry found for")); } finally { secureEmbeddedServer.server.stop(); } } /** * Runs the existing webapp test cases, this time against the initiated secure server instance. * @throws Exception */ @Test public void runOtherSuitesAgainstSecureServer() throws Exception { final PropertiesConfiguration configuration = new PropertiesConfiguration(); configuration.setProperty(CERT_STORES_CREDENTIAL_PROVIDER_PATH, providerUrl); // setup the credential provider setupCredentials(); try { secureEmbeddedServer = new SecureEmbeddedServer(securePort, TestUtils.getWarPath()) { @Override protected PropertiesConfiguration getConfiguration() { return configuration; } }; secureEmbeddedServer.server.start(); TestListenerAdapter tla = new TestListenerAdapter(); TestNG testng = new TestNG(); testng.setTestClasses(new Class[]{AdminJerseyResourceIT.class, EntityJerseyResourceIT.class, MetadataDiscoveryJerseyResourceIT.class, TypesJerseyResourceIT.class}); testng.addListener(tla); testng.run(); } finally { secureEmbeddedServer.server.stop(); } } protected void setupCredentials() throws Exception { Configuration conf = new Configuration(false); File file = new File(jksPath.toUri().getPath()); file.delete(); conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, providerUrl); CredentialProvider provider = CredentialProviderFactory.getProviders(conf).get(0); // create new aliases try { char[] storepass = {'k', 'e', 'y', 'p', 'a', 's', 's'}; provider.createCredentialEntry(KEYSTORE_PASSWORD_KEY, storepass); char[] trustpass = {'k', 'e', 'y', 'p', 'a', 's', 's'}; provider.createCredentialEntry(TRUSTSTORE_PASSWORD_KEY, trustpass); char[] certpass = {'k', 'e', 'y', 'p', 'a', 's', 's'}; provider.createCredentialEntry(SERVER_CERT_PASSWORD_KEY, certpass); // write out so that it can be found in checks provider.flush(); } catch (Exception e) { e.printStackTrace(); throw e; } } } <|start_filename|>graphdb/titan1/src/main/java/org/apache/atlas/repository/graphdb/titan1/Titan1GraphManagement.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan1; import com.google.common.base.Preconditions; import com.thinkaurelius.titan.core.Cardinality; import com.thinkaurelius.titan.core.PropertyKey; import com.thinkaurelius.titan.core.schema.Mapping; import com.thinkaurelius.titan.core.schema.PropertyKeyMaker; import com.thinkaurelius.titan.core.schema.TitanGraphIndex; import com.thinkaurelius.titan.core.schema.TitanManagement; import com.thinkaurelius.titan.graphdb.internal.Token; import org.apache.atlas.repository.graphdb.AtlasCardinality; import org.apache.atlas.repository.graphdb.AtlasGraphIndex; import org.apache.atlas.repository.graphdb.AtlasGraphManagement; import org.apache.atlas.repository.graphdb.AtlasPropertyKey; import org.apache.commons.lang.StringUtils; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Element; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Titan 1.0.0 implementation of AtlasGraphManagement. */ public class Titan1GraphManagement implements AtlasGraphManagement { private static final Logger LOG = LoggerFactory.getLogger(Titan1GraphManagement.class); private static final char[] RESERVED_CHARS = { '{', '}', '"', '$', Token.SEPARATOR_CHAR }; private Titan1Graph graph; private TitanManagement management; private Set<String> newMultProperties = new HashSet<>(); public Titan1GraphManagement(Titan1Graph graph, TitanManagement managementSystem) { this.management = managementSystem; this.graph = graph; } @Override public void createVertexIndex(String propertyName, String backingIndex, List<AtlasPropertyKey> propertyKeys) { TitanManagement.IndexBuilder indexBuilder = management.buildIndex(propertyName, Vertex.class); for (AtlasPropertyKey key : propertyKeys) { PropertyKey titanKey = TitanObjectFactory.createPropertyKey(key); indexBuilder.addKey(titanKey); } indexBuilder.buildMixedIndex(backingIndex); } @Override public void createEdgeIndex(String index, String backingIndex) { buildMixedIndex(index, Edge.class, backingIndex); } private void buildMixedIndex(String index, Class<? extends Element> titanClass, String backingIndex) { management.buildIndex(index, titanClass).buildMixedIndex(backingIndex); } @Override public void createFullTextIndex(String indexName, AtlasPropertyKey propertyKey, String backingIndex) { PropertyKey fullText = TitanObjectFactory.createPropertyKey(propertyKey); management.buildIndex(indexName, Vertex.class) .addKey(fullText, com.thinkaurelius.titan.core.schema.Parameter.of("mapping", Mapping.TEXT)) .buildMixedIndex(backingIndex); } @Override public boolean containsPropertyKey(String propertyName) { return management.containsPropertyKey(propertyName); } @Override public void rollback() { management.rollback(); } @Override public void commit() { graph.addMultiProperties(newMultProperties); newMultProperties.clear(); management.commit(); } private static void checkName(String name) { //for some reason, name checking was removed from StandardPropertyKeyMaker.make() //in titan 1. For consistency, do the check here. Preconditions.checkArgument(StringUtils.isNotBlank(name), "Need to specify name"); for (char c : RESERVED_CHARS) { Preconditions.checkArgument(name.indexOf(c) < 0, "Name can not contains reserved character %s: %s", c, name); } } @Override public AtlasPropertyKey makePropertyKey(String propertyName, Class propertyClass, AtlasCardinality cardinality) { if (cardinality.isMany()) { newMultProperties.add(propertyName); } PropertyKeyMaker propertyKeyBuilder = management.makePropertyKey(propertyName).dataType(propertyClass); if (cardinality != null) { Cardinality titanCardinality = TitanObjectFactory.createCardinality(cardinality); propertyKeyBuilder.cardinality(titanCardinality); } PropertyKey propertyKey = propertyKeyBuilder.make(); return GraphDbObjectFactory.createPropertyKey(propertyKey); } @Override public void deletePropertyKey(String propertyKey) { PropertyKey titanPropertyKey = management.getPropertyKey(propertyKey); if (null == titanPropertyKey) return; for (int i = 0;; i++) { String deletedKeyName = titanPropertyKey + "_deleted_" + i; if (null == management.getPropertyKey(deletedKeyName)) { management.changeName(titanPropertyKey, deletedKeyName); break; } } } @Override public AtlasPropertyKey getPropertyKey(String propertyName) { checkName(propertyName); return GraphDbObjectFactory.createPropertyKey(management.getPropertyKey(propertyName)); } public void createExactMatchVertexIndex(String propertyName, boolean enforceUniqueness, List<AtlasPropertyKey> propertyKeys) { TitanManagement.IndexBuilder indexBuilder = management.buildIndex(propertyName, Vertex.class); for (AtlasPropertyKey key : propertyKeys) { PropertyKey titanKey = TitanObjectFactory.createPropertyKey(key); indexBuilder.addKey(titanKey); } if (enforceUniqueness) { indexBuilder.unique(); } indexBuilder.buildCompositeIndex(); } @Override public void addVertexIndexKey(String indexName, AtlasPropertyKey propertyKey) { PropertyKey titanKey = TitanObjectFactory.createPropertyKey(propertyKey); TitanGraphIndex vertexIndex = management.getGraphIndex(indexName); management.addIndexKey(vertexIndex, titanKey); } @Override public AtlasGraphIndex getGraphIndex(String indexName) { TitanGraphIndex index = management.getGraphIndex(indexName); return GraphDbObjectFactory.createGraphIndex(index); } @Override public void createExactMatchIndex(String propertyName, boolean isUnique, List<AtlasPropertyKey> propertyKeys) { createExactMatchVertexIndex(propertyName, isUnique, propertyKeys); } } <|start_filename|>notification/src/main/java/org/apache/atlas/notification/AbstractMessageDeserializer.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.notification; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.reflect.TypeToken; import org.apache.atlas.typesystem.IReferenceableInstance; import org.apache.atlas.typesystem.IStruct; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.Struct; import org.apache.atlas.typesystem.json.InstanceSerialization; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.slf4j.Logger; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Base notification message deserializer. */ public abstract class AbstractMessageDeserializer<T> extends VersionedMessageDeserializer<T> { private static final Map<Type, JsonDeserializer> DESERIALIZER_MAP = new HashMap<>(); static { DESERIALIZER_MAP.put(ImmutableList.class, new ImmutableListDeserializer()); DESERIALIZER_MAP.put(ImmutableMap.class, new ImmutableMapDeserializer()); DESERIALIZER_MAP.put(JSONArray.class, new JSONArrayDeserializer()); DESERIALIZER_MAP.put(IStruct.class, new StructDeserializer()); DESERIALIZER_MAP.put(IReferenceableInstance.class, new ReferenceableDeserializer()); DESERIALIZER_MAP.put(Referenceable.class, new ReferenceableDeserializer()); } // ----- Constructors ---------------------------------------------------- /** * Create a deserializer. * * @param versionedMessageType the type of the versioned message * @param expectedVersion the expected message version * @param deserializerMap map of individual deserializers used to define this message deserializer * @param notificationLogger logger for message version mismatch */ public AbstractMessageDeserializer(Type versionedMessageType, MessageVersion expectedVersion, Map<Type, JsonDeserializer> deserializerMap, Logger notificationLogger) { super(versionedMessageType, expectedVersion, getDeserializer(deserializerMap), notificationLogger); } // ----- helper methods -------------------------------------------------- private static Gson getDeserializer(Map<Type, JsonDeserializer> deserializerMap) { GsonBuilder builder = new GsonBuilder(); for (Map.Entry<Type, JsonDeserializer> entry : DESERIALIZER_MAP.entrySet()) { builder.registerTypeAdapter(entry.getKey(), entry.getValue()); } for (Map.Entry<Type, JsonDeserializer> entry : deserializerMap.entrySet()) { builder.registerTypeAdapter(entry.getKey(), entry.getValue()); } return builder.create(); } // ----- deserializer classes -------------------------------------------- /** * Deserializer for ImmutableList. */ protected static class ImmutableListDeserializer implements JsonDeserializer<ImmutableList<?>> { public static final Type LIST_TYPE = new TypeToken<List<?>>() { }.getType(); @Override public ImmutableList<?> deserialize(JsonElement json, Type type, JsonDeserializationContext context) { final List<?> list = context.deserialize(json, LIST_TYPE); return ImmutableList.copyOf(list); } } /** * Deserializer for ImmutableMap. */ protected static class ImmutableMapDeserializer implements JsonDeserializer<ImmutableMap<?, ?>> { public static final Type MAP_TYPE = new TypeToken<Map<?, ?>>() { }.getType(); @Override public ImmutableMap<?, ?> deserialize(JsonElement json, Type type, JsonDeserializationContext context) { final Map<?, ?> map = context.deserialize(json, MAP_TYPE); return ImmutableMap.copyOf(map); } } /** * Deserializer for JSONArray. */ public static final class JSONArrayDeserializer implements JsonDeserializer<JSONArray> { @Override public JSONArray deserialize(final JsonElement json, final Type type, final JsonDeserializationContext context) { try { return new JSONArray(json.toString()); } catch (JSONException e) { throw new JsonParseException(e.getMessage(), e); } } } /** * Deserializer for Struct. */ protected static final class StructDeserializer implements JsonDeserializer<IStruct> { @Override public IStruct deserialize(final JsonElement json, final Type type, final JsonDeserializationContext context) { return context.deserialize(json, Struct.class); } } /** * Deserializer for Referenceable. */ protected static final class ReferenceableDeserializer implements JsonDeserializer<IReferenceableInstance> { @Override public IReferenceableInstance deserialize(final JsonElement json, final Type type, final JsonDeserializationContext context) { return InstanceSerialization.fromJsonReferenceable(json.toString(), true); } } } <|start_filename|>webapp/src/test/java/org/apache/atlas/web/integration/MetadataDiscoveryJerseyResourceIT.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.web.integration; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.core.util.MultivaluedMapImpl; import org.apache.atlas.AtlasClient; import org.apache.atlas.AtlasServiceException; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.Struct; import org.apache.atlas.typesystem.TypesDef; import org.apache.atlas.typesystem.persistence.Id; import org.apache.atlas.typesystem.types.ClassType; import org.apache.atlas.typesystem.types.DataTypes; import org.apache.atlas.typesystem.types.EnumTypeDefinition; import org.apache.atlas.typesystem.types.HierarchicalTypeDefinition; import org.apache.atlas.typesystem.types.StructTypeDefinition; import org.apache.atlas.typesystem.types.TraitType; import org.apache.atlas.typesystem.types.utils.TypesUtil; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONObject; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import javax.ws.rs.core.MultivaluedMap; import java.util.List; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.fail; /** * Search Integration Tests. */ public class MetadataDiscoveryJerseyResourceIT extends BaseResourceIT { private String tagName; private String dbName; @BeforeClass public void setUp() throws Exception { super.setUp(); dbName = "db"+randomString(); createTypes(); createInstance( createHiveDBInstanceV1(dbName) ); } @Test public void testSearchByDSL() throws Exception { String dslQuery = "from "+ DATABASE_TYPE + " name=\"" + dbName + "\""; MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); queryParams.add("query", dslQuery); JSONObject response = atlasClientV1.callAPIWithQueryParams(AtlasClient.API.SEARCH_DSL, queryParams); Assert.assertNotNull(response); Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID)); assertEquals(response.getString("query"), dslQuery); assertEquals(response.getString("queryType"), "dsl"); JSONArray results = response.getJSONArray(AtlasClient.RESULTS); assertNotNull(results); assertEquals(results.length(), 1); int numRows = response.getInt(AtlasClient.COUNT); assertEquals(numRows, 1); } @Test public void testSearchDSLLimits() throws Exception { //search without new parameters of limit and offset should work String dslQuery = "from "+ DATABASE_TYPE + " name=\"" + dbName + "\""; MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); queryParams.add("query", dslQuery); JSONObject response = atlasClientV1.callAPIWithQueryParams(AtlasClient.API.SEARCH_DSL, queryParams); assertNotNull(response); //higher limit, all results returned JSONArray results = atlasClientV1.searchByDSL(dslQuery, 10, 0); assertEquals(results.length(), 1); //default limit and offset -1, all results returned results = atlasClientV1.searchByDSL(dslQuery, -1, -1); assertEquals(results.length(), 1); //uses the limit parameter passed results = atlasClientV1.searchByDSL(dslQuery, 1, 0); assertEquals(results.length(), 1); //uses the offset parameter passed results = atlasClientV1.searchByDSL(dslQuery, 10, 1); assertEquals(results.length(), 0); //limit > 0 try { atlasClientV1.searchByDSL(dslQuery, 0, 10); fail("Expected BAD_REQUEST"); } catch (AtlasServiceException e) { assertEquals(e.getStatus(), ClientResponse.Status.BAD_REQUEST, "Got " + e.getStatus()); } //limit > maxlimit try { atlasClientV1.searchByDSL(dslQuery, Integer.MAX_VALUE, 10); fail("Expected BAD_REQUEST"); } catch (AtlasServiceException e) { assertEquals(e.getStatus(), ClientResponse.Status.BAD_REQUEST, "Got " + e.getStatus()); } //offset >= 0 try { atlasClientV1.searchByDSL(dslQuery, 10, -2); fail("Expected BAD_REQUEST"); } catch (AtlasServiceException e) { assertEquals(e.getStatus(), ClientResponse.Status.BAD_REQUEST, "Got " + e.getStatus()); } } @Test(expectedExceptions = AtlasServiceException.class) public void testSearchByDSLForUnknownType() throws Exception { String dslQuery = "from blah"; MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); queryParams.add("query", dslQuery); atlasClientV1.callAPIWithQueryParams(AtlasClient.API.SEARCH_DSL, queryParams); } @Test public void testSearchUsingGremlin() throws Exception { String query = "g.V.has('type', '" + BaseResourceIT.HIVE_TABLE_TYPE + "').toList()"; MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); queryParams.add("query", query); JSONObject response = atlasClientV1.callAPIWithQueryParams(AtlasClient.API.GREMLIN_SEARCH, queryParams); assertNotNull(response); assertNotNull(response.get(AtlasClient.REQUEST_ID)); assertEquals(response.getString("query"), query); assertEquals(response.getString("queryType"), "gremlin"); } @Test public void testSearchUsingDSL() throws Exception { //String query = "from dsl_test_type"; String query = "from "+ DATABASE_TYPE + " name=\"" + dbName +"\""; MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); queryParams.add("query", query); JSONObject response = atlasClientV1.callAPIWithQueryParams(AtlasClient.API.SEARCH, queryParams); Assert.assertNotNull(response); Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID)); assertEquals(response.getString("query"), query); assertEquals(response.getString("queryType"), "dsl"); } @Test public void testSearchFullTextOnDSLFailure() throws Exception { String query = "*"; MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); queryParams.add("query", query); JSONObject response = atlasClientV1.callAPIWithQueryParams(AtlasClient.API.SEARCH, queryParams); Assert.assertNotNull(response); Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID)); assertEquals(response.getString("query"), query); assertEquals(response.getString("queryType"), "full-text"); } @Test(dependsOnMethods = "testSearchDSLLimits") public void testSearchUsingFullText() throws Exception { JSONObject response = atlasClientV1.searchByFullText(dbName, 10, 0); assertNotNull(response.get(AtlasClient.REQUEST_ID)); assertEquals(response.getString("query"), dbName); assertEquals(response.getString("queryType"), "full-text"); JSONArray results = response.getJSONArray(AtlasClient.RESULTS); assertEquals(results.length(), 1, "Results: " + results); JSONObject row = results.getJSONObject(0); assertNotNull(row.get("guid")); assertEquals(row.getString("typeName"), DATABASE_TYPE); assertNotNull(row.get("score")); int numRows = response.getInt(AtlasClient.COUNT); assertEquals(numRows, 1); //API works without limit and offset String query = dbName; MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); queryParams.add("query", query); response = atlasClientV1.callAPIWithQueryParams(AtlasClient.API.SEARCH_FULL_TEXT, queryParams); results = response.getJSONArray(AtlasClient.RESULTS); assertEquals(results.length(), 1); //verify passed in limits and offsets are used //higher limit and 0 offset returns all results results = atlasClientV1.searchByFullText(query, 10, 0).getJSONArray(AtlasClient.RESULTS); assertEquals(results.length(), 1); //offset is used results = atlasClientV1.searchByFullText(query, 10, 1).getJSONArray(AtlasClient.RESULTS); assertEquals(results.length(), 0); //limit is used results = atlasClientV1.searchByFullText(query, 1, 0).getJSONArray(AtlasClient.RESULTS); assertEquals(results.length(), 1); //higher offset returns 0 results results = atlasClientV1.searchByFullText(query, 1, 2).getJSONArray(AtlasClient.RESULTS); assertEquals(results.length(), 0); } private void createTypes() throws Exception { createTypeDefinitionsV1(); HierarchicalTypeDefinition<ClassType> dslTestTypeDefinition = TypesUtil .createClassTypeDef("dsl_test_type", ImmutableSet.<String>of(), TypesUtil.createUniqueRequiredAttrDef("name", DataTypes.STRING_TYPE), TypesUtil.createRequiredAttrDef("description", DataTypes.STRING_TYPE)); HierarchicalTypeDefinition<TraitType> classificationTraitDefinition = TypesUtil .createTraitTypeDef("Classification", ImmutableSet.<String>of(), TypesUtil.createRequiredAttrDef("tag", DataTypes.STRING_TYPE)); TypesDef typesDef = TypesUtil.getTypesDef(ImmutableList.<EnumTypeDefinition>of(), ImmutableList.<StructTypeDefinition>of(), ImmutableList.of(classificationTraitDefinition), ImmutableList.of(dslTestTypeDefinition)); createType(typesDef); } private Id createInstance() throws Exception { Referenceable entityInstance = new Referenceable("dsl_test_type", "Classification"); entityInstance.set("name", randomString()); entityInstance.set("description", randomString()); Struct traitInstance = (Struct) entityInstance.getTrait("Classification"); tagName = randomString(); traitInstance.set("tag", tagName); List<String> traits = entityInstance.getTraits(); assertEquals(traits.size(), 1); return createInstance(entityInstance); } } <|start_filename|>intg/src/main/java/org/apache/atlas/type/AtlasEntityType.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.type; import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.instance.AtlasEntity; import org.apache.atlas.model.instance.AtlasObjectId; import org.apache.atlas.model.typedef.AtlasEntityDef; import org.apache.atlas.model.typedef.AtlasStructDef.AtlasAttributeDef; import org.apache.atlas.type.AtlasBuiltInTypes.AtlasObjectIdType; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * class that implements behaviour of an entity-type. */ public class AtlasEntityType extends AtlasStructType { private static final Logger LOG = LoggerFactory.getLogger(AtlasEntityType.class); private final AtlasEntityDef entityDef; private List<AtlasEntityType> superTypes = Collections.emptyList(); private Set<String> allSuperTypes = Collections.emptySet(); private Set<String> allSubTypes = Collections.emptySet(); private Set<String> typeAndAllSubTypes = Collections.emptySet(); private Set<String> typeAndAllSuperTypes = Collections.emptySet(); private Map<String, AtlasAttribute> relationshipAttributes = Collections.emptyMap(); private Map<String, List<AtlasRelationshipType>> relationshipAttributesType = Collections.emptyMap(); private String typeAndAllSubTypesQryStr = ""; public AtlasEntityType(AtlasEntityDef entityDef) { super(entityDef); this.entityDef = entityDef; } public AtlasEntityType(AtlasEntityDef entityDef, AtlasTypeRegistry typeRegistry) throws AtlasBaseException { super(entityDef); this.entityDef = entityDef; resolveReferences(typeRegistry); } public AtlasEntityDef getEntityDef() { return entityDef; } @Override public void resolveReferences(AtlasTypeRegistry typeRegistry) throws AtlasBaseException { super.resolveReferences(typeRegistry); List<AtlasEntityType> s = new ArrayList<>(); Set<String> allS = new HashSet<>(); Map<String, AtlasAttribute> allA = new HashMap<>(); getTypeHierarchyInfo(typeRegistry, allS, allA); for (String superTypeName : entityDef.getSuperTypes()) { AtlasType superType = typeRegistry.getType(superTypeName); if (superType instanceof AtlasEntityType) { s.add((AtlasEntityType)superType); } else { throw new AtlasBaseException(AtlasErrorCode.INCOMPATIBLE_SUPERTYPE, superTypeName, entityDef.getName()); } } this.superTypes = Collections.unmodifiableList(s); this.allSuperTypes = Collections.unmodifiableSet(allS); this.allAttributes = Collections.unmodifiableMap(allA); this.uniqAttributes = getUniqueAttributes(this.allAttributes); this.allSubTypes = new HashSet<>(); // this will be populated in resolveReferencesPhase2() this.typeAndAllSubTypes = new HashSet<>(); // this will be populated in resolveReferencesPhase2() this.relationshipAttributes = new HashMap<>(); // this will be populated in resolveReferencesPhase3() this.relationshipAttributesType = new HashMap<>(); // this will be populated in resolveReferencesPhase3() this.typeAndAllSubTypes.add(this.getTypeName()); this.typeAndAllSuperTypes = new HashSet<>(this.allSuperTypes); this.typeAndAllSuperTypes.add(this.getTypeName()); this.typeAndAllSuperTypes = Collections.unmodifiableSet(this.typeAndAllSuperTypes); } @Override public void resolveReferencesPhase2(AtlasTypeRegistry typeRegistry) throws AtlasBaseException { super.resolveReferencesPhase2(typeRegistry); for (String superTypeName : allSuperTypes) { AtlasEntityType superType = typeRegistry.getEntityTypeByName(superTypeName); superType.addSubType(this); } } @Override public void resolveReferencesPhase3(AtlasTypeRegistry typeRegistry) throws AtlasBaseException { for (AtlasAttributeDef attributeDef : getStructDef().getAttributeDefs()) { String attributeName = attributeDef.getName(); AtlasType attributeType = typeRegistry.getType(attributeDef.getTypeName()); AtlasEntityType attributeEntityType = getReferencedEntityType(attributeType); // validate if RelationshipDefs is defined for all entityDefs if (attributeEntityType != null && !hasRelationshipAttribute(attributeName)) { LOG.warn("No RelationshipDef defined between {} and {} on attribute: {}.{}", getTypeName(), attributeEntityType.getTypeName(), getTypeName(), attributeName); } } for (String superTypeName : allSuperTypes) { AtlasEntityType superType = typeRegistry.getEntityTypeByName(superTypeName); Map<String, AtlasAttribute> superTypeRelationshipAttributes = superType.getRelationshipAttributes(); if (MapUtils.isNotEmpty(superTypeRelationshipAttributes)) { relationshipAttributes.putAll(superTypeRelationshipAttributes); } Map<String, List<AtlasRelationshipType>> superTypeRelationshipAttributesType = superType.getRelationshipAttributesType(); if (MapUtils.isNotEmpty(superTypeRelationshipAttributesType)) { relationshipAttributesType.putAll(superTypeRelationshipAttributesType); } } allSubTypes = Collections.unmodifiableSet(allSubTypes); typeAndAllSubTypes = Collections.unmodifiableSet(typeAndAllSubTypes); typeAndAllSubTypesQryStr = ""; // will be computed on next access relationshipAttributes = Collections.unmodifiableMap(relationshipAttributes); relationshipAttributesType = Collections.unmodifiableMap(relationshipAttributesType); } public Set<String> getSuperTypes() { return entityDef.getSuperTypes(); } public Set<String> getAllSuperTypes() { return allSuperTypes; } public Set<String> getAllSubTypes() { return allSubTypes; } public Set<String> getTypeAndAllSubTypes() { return typeAndAllSubTypes; } public Set<String> getTypeAndAllSuperTypes() { return typeAndAllSuperTypes; } public boolean isSuperTypeOf(AtlasEntityType entityType) { return entityType != null && allSubTypes.contains(entityType.getTypeName()); } public boolean isSuperTypeOf(String entityTypeName) { return StringUtils.isNotEmpty(entityTypeName) && allSubTypes.contains(entityTypeName); } public boolean isTypeOrSuperTypeOf(String entityTypeName) { return StringUtils.isNotEmpty(entityTypeName) && typeAndAllSubTypes.contains(entityTypeName); } public boolean isSubTypeOf(AtlasEntityType entityType) { return entityType != null && allSuperTypes.contains(entityType.getTypeName()); } public boolean isSubTypeOf(String entityTypeName) { return StringUtils.isNotEmpty(entityTypeName) && allSuperTypes.contains(entityTypeName); } public Map<String, AtlasAttribute> getRelationshipAttributes() { return relationshipAttributes; } public AtlasAttribute getRelationshipAttribute(String attributeName) { return relationshipAttributes.get(attributeName); } // this method should be called from AtlasRelationshipType.resolveReferencesPhase2() void addRelationshipAttribute(String attributeName, AtlasAttribute attribute) { relationshipAttributes.put(attributeName, attribute); } // this method should be called from AtlasRelationshipType.resolveReferencesPhase2() void addRelationshipAttributeType(String attributeName, AtlasRelationshipType relationshipType) { List<AtlasRelationshipType> relationshipTypes = relationshipAttributesType.get(attributeName); if (relationshipTypes == null) { relationshipTypes = new ArrayList<>(); relationshipAttributesType.put(attributeName, relationshipTypes); } relationshipTypes.add(relationshipType); } public List<AtlasRelationshipType> getRelationshipAttributeType(String attributeName) { return relationshipAttributesType.get(attributeName); } public Map<String, List<AtlasRelationshipType>> getRelationshipAttributesType() { return relationshipAttributesType; } public String getTypeAndAllSubTypesQryStr() { if (StringUtils.isEmpty(typeAndAllSubTypesQryStr)) { typeAndAllSubTypesQryStr = AtlasAttribute.escapeIndexQueryValue(typeAndAllSubTypes); } return typeAndAllSubTypesQryStr; } public boolean hasRelationshipAttribute(String attributeName) { return relationshipAttributes.containsKey(attributeName); } public String getQualifiedAttributeName(String attrName) throws AtlasBaseException { if (allAttributes.containsKey(attrName)) { return allAttributes.get(attrName).getQualifiedName(); } else if (relationshipAttributes.containsKey(attrName)) { return relationshipAttributes.get(attrName).getQualifiedName(); } throw new AtlasBaseException(AtlasErrorCode.UNKNOWN_ATTRIBUTE, attrName, entityDef.getName()); } @Override public AtlasEntity createDefaultValue() { AtlasEntity ret = new AtlasEntity(entityDef.getName()); populateDefaultValues(ret); return ret; } @Override public AtlasEntity createDefaultValue(Object defaultValue){ AtlasEntity ret = new AtlasEntity(entityDef.getName()); populateDefaultValues(ret); return ret; } @Override public boolean isValidValue(Object obj) { if (obj != null) { for (AtlasEntityType superType : superTypes) { if (!superType.isValidValue(obj)) { return false; } } return super.isValidValue(obj); } return true; } @Override public boolean isValidValueForUpdate(Object obj) { if (obj != null) { for (AtlasEntityType superType : superTypes) { if (!superType.isValidValueForUpdate(obj)) { return false; } } return super.isValidValueForUpdate(obj); } return true; } @Override public Object getNormalizedValue(Object obj) { Object ret = null; if (obj != null) { if (isValidValue(obj)) { if (obj instanceof AtlasEntity) { normalizeAttributeValues((AtlasEntity) obj); ret = obj; } else if (obj instanceof Map) { normalizeAttributeValues((Map) obj); ret = obj; } } } return ret; } @Override public Object getNormalizedValueForUpdate(Object obj) { Object ret = null; if (obj != null) { if (isValidValueForUpdate(obj)) { if (obj instanceof AtlasEntity) { normalizeAttributeValuesForUpdate((AtlasEntity) obj); ret = obj; } else if (obj instanceof Map) { normalizeAttributeValuesForUpdate((Map) obj); ret = obj; } } } return ret; } @Override public AtlasAttribute getAttribute(String attributeName) { return allAttributes.get(attributeName); } @Override public boolean validateValue(Object obj, String objName, List<String> messages) { boolean ret = true; if (obj != null) { if (obj instanceof AtlasEntity || obj instanceof Map) { for (AtlasEntityType superType : superTypes) { ret = superType.validateValue(obj, objName, messages) && ret; } ret = super.validateValue(obj, objName, messages) && ret; } else { ret = false; messages.add(objName + ": invalid value type '" + obj.getClass().getName()); } } return ret; } @Override public boolean validateValueForUpdate(Object obj, String objName, List<String> messages) { boolean ret = true; if (obj != null) { if (obj instanceof AtlasEntity || obj instanceof Map) { for (AtlasEntityType superType : superTypes) { ret = superType.validateValueForUpdate(obj, objName, messages) && ret; } ret = super.validateValueForUpdate(obj, objName, messages) && ret; } else { ret = false; messages.add(objName + ": invalid value type '" + obj.getClass().getName()); } } return ret; } @Override public AtlasType getTypeForAttribute() { AtlasType attributeType = new AtlasObjectIdType(getTypeName()); if (LOG.isDebugEnabled()) { LOG.debug("getTypeForAttribute(): {} ==> {}", getTypeName(), attributeType.getTypeName()); } return attributeType; } public void normalizeAttributeValues(AtlasEntity ent) { if (ent != null) { for (AtlasEntityType superType : superTypes) { superType.normalizeAttributeValues(ent); } super.normalizeAttributeValues(ent); } } public void normalizeAttributeValuesForUpdate(AtlasEntity ent) { if (ent != null) { for (AtlasEntityType superType : superTypes) { superType.normalizeAttributeValuesForUpdate(ent); } super.normalizeAttributeValuesForUpdate(ent); } } @Override public void normalizeAttributeValues(Map<String, Object> obj) { if (obj != null) { for (AtlasEntityType superType : superTypes) { superType.normalizeAttributeValues(obj); } super.normalizeAttributeValues(obj); } } public void normalizeAttributeValuesForUpdate(Map<String, Object> obj) { if (obj != null) { for (AtlasEntityType superType : superTypes) { superType.normalizeAttributeValuesForUpdate(obj); } super.normalizeAttributeValuesForUpdate(obj); } } public void populateDefaultValues(AtlasEntity ent) { if (ent != null) { for (AtlasEntityType superType : superTypes) { superType.populateDefaultValues(ent); } super.populateDefaultValues(ent); } } private void addSubType(AtlasEntityType subType) { allSubTypes.add(subType.getTypeName()); typeAndAllSubTypes.add(subType.getTypeName()); } private void getTypeHierarchyInfo(AtlasTypeRegistry typeRegistry, Set<String> allSuperTypeNames, Map<String, AtlasAttribute> allAttributes) throws AtlasBaseException { List<String> visitedTypes = new ArrayList<>(); collectTypeHierarchyInfo(typeRegistry, allSuperTypeNames, allAttributes, visitedTypes); } /* * This method should not assume that resolveReferences() has been called on all superTypes. * this.entityDef is the only safe member to reference here */ private void collectTypeHierarchyInfo(AtlasTypeRegistry typeRegistry, Set<String> allSuperTypeNames, Map<String, AtlasAttribute> allAttributes, List<String> visitedTypes) throws AtlasBaseException { if (visitedTypes.contains(entityDef.getName())) { throw new AtlasBaseException(AtlasErrorCode.CIRCULAR_REFERENCE, entityDef.getName(), visitedTypes.toString()); } if (CollectionUtils.isNotEmpty(entityDef.getSuperTypes())) { visitedTypes.add(entityDef.getName()); for (String superTypeName : entityDef.getSuperTypes()) { AtlasEntityType superType = typeRegistry.getEntityTypeByName(superTypeName); if (superType != null) { superType.collectTypeHierarchyInfo(typeRegistry, allSuperTypeNames, allAttributes, visitedTypes); } } visitedTypes.remove(entityDef.getName()); allSuperTypeNames.addAll(entityDef.getSuperTypes()); } if (CollectionUtils.isNotEmpty(entityDef.getAttributeDefs())) { for (AtlasAttributeDef attributeDef : entityDef.getAttributeDefs()) { AtlasType type = typeRegistry.getType(attributeDef.getTypeName()); allAttributes.put(attributeDef.getName(), new AtlasAttribute(this, attributeDef, type)); } } } boolean isAssignableFrom(AtlasObjectId objId) { boolean ret = AtlasTypeUtil.isValid(objId) && (StringUtils.equals(objId.getTypeName(), getTypeName()) || isSuperTypeOf(objId.getTypeName())); return ret; } } <|start_filename|>repository/src/test/java/org/apache/atlas/repository/store/graph/v1/SoftDeleteHandlerV1Test.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.store.graph.v1; import org.apache.atlas.AtlasClient; import org.apache.atlas.TestModules; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.instance.AtlasEntity; import org.apache.atlas.model.instance.AtlasEntityHeader; import org.apache.atlas.model.instance.AtlasObjectId; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.graph.GraphHelper; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.services.MetadataService; import org.apache.atlas.typesystem.IReferenceableInstance; import org.apache.atlas.typesystem.IStruct; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.ITypedStruct; import org.apache.atlas.typesystem.persistence.Id; import org.testng.Assert; import org.testng.annotations.Guice; import javax.inject.Inject; import java.util.List; import java.util.Map; import static org.apache.atlas.TestUtils.COLUMNS_ATTR_NAME; import static org.apache.atlas.TestUtils.NAME; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; @Guice(modules = TestModules.SoftDeleteModule.class) public class SoftDeleteHandlerV1Test extends AtlasDeleteHandlerV1Test { @Inject MetadataService metadataService; @Override protected void assertDeletedColumn(final AtlasEntity.AtlasEntityWithExtInfo tableInstance) throws AtlasBaseException { final List<AtlasObjectId> columns = (List<AtlasObjectId>) tableInstance.getEntity().getAttribute(COLUMNS_ATTR_NAME); Assert.assertEquals(columns.size(), 3); final AtlasEntity.AtlasEntityWithExtInfo colDeleted = entityStore.getById(columns.get(0).getGuid()); assertEquals(colDeleted.getEntity().getStatus(), AtlasEntity.Status.DELETED); } @Override protected void assertTestDeleteEntities(final AtlasEntity.AtlasEntityWithExtInfo tableInstance) throws Exception { //Assert that the deleted table can be fully constructed back List<IReferenceableInstance> columns = (List<IReferenceableInstance>) tableInstance.getEntity().getAttribute(COLUMNS_ATTR_NAME); assertEquals(columns.size(), 3); assertNotNull(tableInstance.getEntity().getAttribute("database")); } @Override protected void assertTableForTestDeleteReference(final String tableId) throws Exception { ITypedReferenceableInstance table = metadataService.getEntityDefinition(tableId); assertNotNull(table.get(NAME)); assertNotNull(table.get("description")); assertNotNull(table.get("type")); assertNotNull(table.get("tableType")); assertNotNull(table.get("created")); Id dbId = (Id) table.get("database"); assertNotNull(dbId); ITypedReferenceableInstance db = metadataService.getEntityDefinition(dbId.getId()._getId()); assertNotNull(db); assertEquals(db.getId().getState(), Id.EntityState.ACTIVE); } @Override protected void assertColumnForTestDeleteReference(final AtlasEntity.AtlasEntityWithExtInfo tableInstance) throws AtlasBaseException { List<AtlasObjectId> columns = (List<AtlasObjectId>) tableInstance.getEntity().getAttribute(COLUMNS_ATTR_NAME); assertEquals(columns.size(), 1); final AtlasEntity.AtlasEntityWithExtInfo byId = entityStore.getById(columns.get(0).getGuid()); assertEquals(byId.getEntity().getStatus(), AtlasEntity.Status.DELETED); } @Override protected void assertProcessForTestDeleteReference(final AtlasEntityHeader processInstance) throws Exception { // ITypedReferenceableInstance process = metadataService.getEntityDefinition(processInstance.getGuid()); List<ITypedReferenceableInstance> outputs = (List<ITypedReferenceableInstance>) process.get(AtlasClient.PROCESS_ATTRIBUTE_OUTPUTS); List<ITypedReferenceableInstance> expectedOutputs = (List<ITypedReferenceableInstance>) process.get(AtlasClient.PROCESS_ATTRIBUTE_OUTPUTS); assertEquals(outputs.size(), expectedOutputs.size()); } @Override protected void assertEntityDeleted(final String id) throws Exception { final AtlasEntity.AtlasEntityWithExtInfo byId = entityStore.getById(id); assertEquals(byId.getEntity().getStatus(), AtlasEntity.Status.DELETED); } @Override protected void assertTestUpdateEntity_MultiplicityOneNonCompositeReference(final String janeGuid) throws Exception { // Verify Jane's subordinates reference cardinality is still 2. ITypedReferenceableInstance jane = metadataService.getEntityDefinition(janeGuid); List<ITypedReferenceableInstance> subordinates = (List<ITypedReferenceableInstance>) jane.get("subordinates"); Assert.assertEquals(subordinates.size(), 2); } @Override protected void assertJohnForTestDisconnectBidirectionalReferences(final AtlasEntity.AtlasEntityWithExtInfo john, final String janeGuid) throws Exception { AtlasObjectId mgr = (AtlasObjectId) john.getEntity().getAttribute("manager"); assertNotNull(mgr); assertEquals(mgr.getGuid(), janeGuid); final AtlasEntity.AtlasEntityWithExtInfo mgrEntity = entityStore.getById(mgr.getGuid()); assertEquals(mgrEntity.getEntity().getStatus(), AtlasEntity.Status.DELETED); } @Override protected void assertMaxForTestDisconnectBidirectionalReferences(final Map<String, String> nameGuidMap) throws Exception { // Verify that the Department.employees reference to the deleted employee // was disconnected. ITypedReferenceableInstance hrDept = metadataService.getEntityDefinition(nameGuidMap.get("hr")); List<ITypedReferenceableInstance> employees = (List<ITypedReferenceableInstance>) hrDept.get("employees"); Assert.assertEquals(employees.size(), 4); String maxGuid = nameGuidMap.get("Max"); for (ITypedReferenceableInstance employee : employees) { if (employee.getId()._getId().equals(maxGuid)) { assertEquals(employee.getId().getState(), Id.EntityState.DELETED); } } // Verify that the Manager.subordinates still references deleted employee ITypedReferenceableInstance jane = metadataService.getEntityDefinition(nameGuidMap.get("Jane")); List<ITypedReferenceableInstance> subordinates = (List<ITypedReferenceableInstance>) jane.get("subordinates"); assertEquals(subordinates.size(), 2); for (ITypedReferenceableInstance subordinate : subordinates) { if (subordinate.getId()._getId().equals(maxGuid)) { assertEquals(subordinate.getId().getState(), Id.EntityState.DELETED); } } // Verify that max's Person.mentor unidirectional reference to john was disconnected. ITypedReferenceableInstance john = metadataService.getEntityDefinition(nameGuidMap.get("John")); Id mentor = (Id) john.get("mentor"); assertEquals(mentor._getId(), maxGuid); assertEquals(mentor.getState(), Id.EntityState.DELETED); } @Override protected void assertTestDisconnectUnidirectionalArrayReferenceFromClassType(final List<AtlasObjectId> columns, final String columnGuid) throws AtlasBaseException { Assert.assertEquals(columns.size(), 3); for (AtlasObjectId column : columns) { AtlasEntity.AtlasEntityWithExtInfo columnEntity = entityStore.getById(column.getGuid()); if (column.getGuid().equals(columnGuid)) { assertEquals(columnEntity.getEntity().getStatus(), AtlasEntity.Status.DELETED); } else { assertEquals(columnEntity.getEntity().getStatus(), AtlasEntity.Status.ACTIVE); } } } @Override protected void assertTestDisconnectMapReferenceFromClassType(final String mapOwnerGuid) throws Exception { AtlasEntity.AtlasEntityWithExtInfo mapOwnerInstance = entityStore.getById(mapOwnerGuid); Map<String, AtlasObjectId> map = (Map<String, AtlasObjectId>) mapOwnerInstance.getEntity().getAttribute("map"); assertNotNull(map); assertEquals(map.size(), 1); Map<String, AtlasObjectId> biMap = (Map<String, AtlasObjectId>) mapOwnerInstance.getEntity().getAttribute("biMap"); assertNotNull(biMap); assertEquals(biMap.size(), 1); } @Override protected void assertTestDisconnectUnidirectionalArrayReferenceFromStructAndTraitTypes(final String structContainerGuid) throws Exception { // Verify that the unidirectional references from the struct and trait instances // to the deleted entities were not disconnected. ITypedReferenceableInstance structContainerConvertedEntity = metadataService.getEntityDefinition(structContainerGuid); ITypedStruct struct = (ITypedStruct) structContainerConvertedEntity.get("struct"); assertNotNull(struct.get("target")); IStruct trait = structContainerConvertedEntity.getTrait("TestTrait"); assertNotNull(trait); assertNotNull(trait.get("target")); } @Override protected void assertVerticesDeleted(List<AtlasVertex> vertices) { for (AtlasVertex vertex : vertices) { assertEquals(GraphHelper.getSingleValuedProperty(vertex, Constants.STATE_PROPERTY_KEY, String.class), Id.EntityState.DELETED.name()); } } } <|start_filename|>graphdb/titan0/src/test/java/com/thinkaurelius/titan/diskstorage/locking/LocalLockMediatorTest.java<|end_filename|> /* * Copyright 2012-2013 Aurelius LLC * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thinkaurelius.titan.diskstorage.locking; import com.thinkaurelius.titan.diskstorage.hbase.HBaseTransaction; import com.thinkaurelius.titan.diskstorage.util.time.TimestampProvider; import com.thinkaurelius.titan.diskstorage.util.time.Timestamps; import com.thinkaurelius.titan.diskstorage.StaticBuffer; import com.thinkaurelius.titan.diskstorage.util.KeyColumn; import com.thinkaurelius.titan.diskstorage.util.StaticArrayBuffer; import org.mockito.Mockito; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; public class LocalLockMediatorTest { private static final String LOCK_NAMESPACE = "test"; private static final StaticBuffer LOCK_ROW = StaticArrayBuffer.of(new byte[]{1}); private static final StaticBuffer LOCK_COL = StaticArrayBuffer.of(new byte[]{1}); private static final KeyColumn kc = new KeyColumn(LOCK_ROW, LOCK_COL); private static final HBaseTransaction mockTx1 = Mockito.mock(HBaseTransaction.class); private static final HBaseTransaction mockTx2 = Mockito.mock(HBaseTransaction.class); @Test public void testLock() throws InterruptedException { TimestampProvider times = Timestamps.MICRO; LocalLockMediator<HBaseTransaction> llm = new LocalLockMediator<>(LOCK_NAMESPACE, times); //Expire immediately Assert.assertTrue(llm.lock(kc, mockTx1, times.getTime(0, TimeUnit.NANOSECONDS))); Assert.assertTrue(llm.lock(kc, mockTx2, times.getTime(Long.MAX_VALUE, TimeUnit.NANOSECONDS))); llm = new LocalLockMediator<>(LOCK_NAMESPACE, times); //Expire later Assert.assertTrue(llm.lock(kc, mockTx1, times.getTime(Long.MAX_VALUE, TimeUnit.NANOSECONDS))); //So second lock should fail on same keyCol Assert.assertFalse(llm.lock(kc, mockTx2, times.getTime(Long.MAX_VALUE, TimeUnit.NANOSECONDS))); //Unlock Assert.assertTrue(llm.unlock(kc, mockTx1)); //Now locking should succeed Assert.assertTrue(llm.lock(kc, mockTx2, times.getTime(Long.MAX_VALUE, TimeUnit.NANOSECONDS))); } } <|start_filename|>server-api/src/main/java/org/apache/atlas/services/MetadataService.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.services; import org.apache.atlas.AtlasException; import org.apache.atlas.CreateUpdateEntitiesResult; import org.apache.atlas.EntityAuditEvent; import org.apache.atlas.listener.EntityChangeListener; import org.apache.atlas.model.legacy.EntityResult; import org.apache.atlas.typesystem.IReferenceableInstance; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.ITypedStruct; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.Struct; import org.apache.atlas.typesystem.IStruct; import org.apache.atlas.typesystem.types.cache.TypeCache; import org.codehaus.jettison.json.JSONObject; import java.util.List; import java.util.Map; /** * Metadata service. */ @Deprecated public interface MetadataService { /** * Creates a new type based on the type system to enable adding * entities (instances for types). * * @param typeDefinition definition as json * @return a unique id for this type */ JSONObject createType(String typeDefinition) throws AtlasException; /**z * Updates the given types in the type definition * @param typeDefinition * @return * @throws AtlasException */ JSONObject updateType(String typeDefinition) throws AtlasException; /** * Return the definition for the given type. * * @param typeName name for this type, must be unique * @return type definition as JSON */ String getTypeDefinition(String typeName) throws AtlasException; /** * Return the list of type names in the type system which match the specified filter. * * @return list of type names * @param filterMap - Map of filter for type names. Valid keys are CATEGORY, SUPERTYPE, NOT_SUPERTYPE * For example, CATEGORY = TRAIT && SUPERTYPE contains 'X' && SUPERTYPE !contains 'Y' * If there is no filter, all the types are returned */ List<String> getTypeNames(Map<TypeCache.TYPE_FILTER, String> filterMap) throws AtlasException; /** * Creates an entity, instance of the type. * * @param entityDefinition definition * @return CreateUpdateEntitiesResult with the guids of the entities created */ CreateUpdateEntitiesResult createEntities(String entityDefinition) throws AtlasException; /** * Get a typed entity instance. * * @param entity entity * @return typed entity instance * * @throws AtlasException if any failure occurs */ ITypedReferenceableInstance getTypedReferenceableInstance(Referenceable entity) throws AtlasException; /** * Create entity instances. * * @param typedInstances instance to create * @return CreateUpdateEntitiesResult with the guids of the entities created * * @throws AtlasException if unable to create the entities */ CreateUpdateEntitiesResult createEntities(ITypedReferenceableInstance[] typedInstances) throws AtlasException; /** * Return the definition for the given guid. * * @param guid guid * @return entity definition as JSON */ String getEntityDefinitionJson(String guid) throws AtlasException; ITypedReferenceableInstance getEntityDefinition(String guid) throws AtlasException; /** * Return the definition given type and attribute. The attribute has to be unique attribute for the type * @param entityType - type name * @param attribute - attribute name * @param value - attribute value * @return * @throws AtlasException */ ITypedReferenceableInstance getEntityDefinitionReference(String entityType, String attribute, String value) throws AtlasException; /** * Return the definition given type and attribute. The attribute has to be unique attribute for the type * @param entityType - type name * @param attribute - attribute name * @param value - attribute value * @return * @throws AtlasException */ String getEntityDefinition(String entityType, String attribute, String value) throws AtlasException; /** * Return the list of entity names for the given type in the repository. * * @param entityType type * @return list of entity names for the given type in the repository */ List<String> getEntityList(String entityType) throws AtlasException; /** * Adds the property to the given entity id(guid). * Currently supports updates only on PRIMITIVE, CLASS attribute types * @param guid entity id * @param attribute property name * @param value property value * @return {@link CreateUpdateEntitiesResult} with the guids of the entities that were created/updated */ CreateUpdateEntitiesResult updateEntityAttributeByGuid(String guid, String attribute, String value) throws AtlasException; /** * Supports Partial updates of an entity. Users can update a subset of attributes for an entity identified by its guid * Note however that it cannot be used to set attribute values to null or delete attrbute values * @param guid entity id * @param entity * @return {@link CreateUpdateEntitiesResult} with the guids of the entities that were created/updated * @throws AtlasException */ CreateUpdateEntitiesResult updateEntityPartialByGuid(String guid, Referenceable entity) throws AtlasException; /** * Batch API - Adds/Updates the given entity id(guid). * * @param entityJson entity json * @return {@link CreateUpdateEntitiesResult} with the guids of the entities that were created/updated */ CreateUpdateEntitiesResult updateEntities(String entityJson) throws AtlasException; /** * Batch API - Adds/Updates the given entity id(guid). * * @param entityJson entity json * @return {@link CreateUpdateEntitiesResult} with the guids of the entities that were created/updated */ CreateUpdateEntitiesResult updateEntities(ITypedReferenceableInstance[] iTypedReferenceableInstances) throws AtlasException; // Trait management functions /** * Updates entity identified by a qualified name * * @param typeName * @param uniqueAttributeName * @param attrValue * @param updatedEntity * @return Guid of updated entity * @throws AtlasException */ CreateUpdateEntitiesResult updateEntityByUniqueAttribute(String typeName, String uniqueAttributeName, String attrValue, Referenceable updatedEntity) throws AtlasException; /** * Gets the list of trait names for a given entity represented by a guid. * * @param guid globally unique identifier for the entity * @return a list of trait names for the given entity guid * @throws AtlasException */ List<String> getTraitNames(String guid) throws AtlasException; /** * Adds a new trait to an existing entity represented by a guid. * * @param guid globally unique identifier for the entity * @param traitInstanceDefinition trait instance that needs to be added to entity * @throws AtlasException */ void addTrait(String guid, String traitInstanceDefinition) throws AtlasException; /** * Adds a new trait to an existing entity represented by a guid. * * @param guid globally unique identifier for the entity * @param traitInstance trait instance to add * * @throws AtlasException if unable to add the trait instance */ void addTrait(String guid, ITypedStruct traitInstance) throws AtlasException; /** * Adds a new trait to a list of existing entities represented by their respective guids * @param entityGuids list of guids of entities * @param traitInstance trait instance json that needs to be added to entities * @throws AtlasException */ void addTrait(List<String> entityGuids, ITypedStruct traitInstance) throws AtlasException; /** * Create a typed trait instance. * * @param traitInstance trait instance * @return a typed trait instance * @throws AtlasException if unable to create the typed trait instance */ ITypedStruct createTraitInstance(Struct traitInstance) throws AtlasException; /** * Return trait definition of a single trait for a given entity * @param guid - Guid of the entity to which the trait is tagged * @param traitName - Name of the trait * @return * @throws AtlasException */ IStruct getTraitDefinition(String guid, String traitName) throws AtlasException; /** * Deletes a given trait from an existing entity represented by a guid. * * @param guid globally unique identifier for the entity * @param traitNameToBeDeleted name of the trait * @throws AtlasException */ void deleteTrait(String guid, String traitNameToBeDeleted) throws AtlasException; /** * Delete the specified entities from the repository * * @param guids entity guids to be deleted * @return List of guids for deleted entities * @throws AtlasException */ EntityResult deleteEntities(List<String> guids) throws AtlasException; /** * Register a listener for entity change. * * @param listener the listener to register */ void registerListener(EntityChangeListener listener); /** * Unregister an entity change listener. * * @param listener the listener to unregister */ void unregisterListener(EntityChangeListener listener); /** * Delete the specified entity from the repository identified by its unique attribute (including its composite references) * * @param typeName The entity's type * @param uniqueAttributeName attribute name by which the entity could be identified uniquely * @param attrValue attribute value by which the entity could be identified uniquely * @return List of guids for deleted entities (including their composite references) * @throws AtlasException */ EntityResult deleteEntityByUniqueAttribute(String typeName, String uniqueAttributeName, String attrValue) throws AtlasException; /** * Returns entity audit events for entity id in the decreasing order of timestamp * @param guid entity id * @param startKey key for the first event, used for pagination * @param count number of events to be returned * @return */ List<EntityAuditEvent> getAuditEvents(String guid, String startKey, short count) throws AtlasException; /** * Deserializes entity instances into ITypedReferenceableInstance array. * @param entityInstanceDefinition * @return ITypedReferenceableInstance[] * @throws AtlasException */ ITypedReferenceableInstance[] deserializeClassInstances(String entityInstanceDefinition) throws AtlasException; ITypedReferenceableInstance validateAndConvertToTypedInstance(IReferenceableInstance updatedEntity, String typeName) throws AtlasException; } <|start_filename|>repository/src/main/java/org/apache/atlas/gremlin/optimizer/HasForbiddenType.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.gremlin.optimizer; import java.util.HashSet; import java.util.Set; import com.google.common.base.Function; import org.apache.atlas.gremlin.GremlinExpressionFactory; import org.apache.atlas.groovy.GroovyExpression; import org.apache.atlas.groovy.TraversalStepType; /** * Function that tests whether the expression is an 'or' * graph traversal function. */ public final class HasForbiddenType implements Function<GroovyExpression, Boolean> { private Set<TraversalStepType> forbiddenTypes = new HashSet<>(); private final GremlinExpressionFactory factory; public HasForbiddenType(GremlinExpressionFactory factory) { this.factory = factory; } public void addForbiddenType(TraversalStepType type) { forbiddenTypes.add(type); } @Override public Boolean apply(GroovyExpression expr) { if(factory.isLeafAnonymousTraversalExpression(expr)) { return false; } return forbiddenTypes.contains(expr.getType()); } } <|start_filename|>typesystem/src/main/java/org/apache/atlas/typesystem/types/HierarchicalType.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.typesystem.types; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.UnmodifiableIterator; import org.apache.atlas.AtlasConstants; import org.apache.atlas.AtlasException; import org.apache.atlas.typesystem.IStruct; import org.apache.atlas.typesystem.persistence.DownCastStructInstance; import org.apache.atlas.typesystem.types.TypeUtils.Pair; import java.io.IOException; import java.util.*; /** * Represents a Type that can have SuperTypes. An Instance of the HierarchicalType can be * downcast to a SuperType. * @param <ST> the Type of the SuperType. TraitTypes have TraitTypes as SuperTypes, ClassTypes * have ClassTypes * as SuperTypes. * @param <T> the class of the Instance of this DataType. */ public abstract class HierarchicalType<ST extends HierarchicalType, T> extends AbstractDataType<T> { public final TypeSystem typeSystem; public final Class<ST> superTypeClass; public final FieldMapping fieldMapping; public final int numFields; public final ImmutableSet<String> superTypes; public final ImmutableList<AttributeInfo> immediateAttrs; public final ImmutableMap<String, String> attributeNameToType; protected ImmutableMap<String, List<Path>> superTypePaths; protected ImmutableMap<String, Path> pathNameToPathMap; HierarchicalType(TypeSystem typeSystem, Class<ST> superTypeClass, String name, ImmutableSet<String> superTypes, int numFields) { this(typeSystem, superTypeClass, name, null, superTypes, numFields); } /** * Used when creating a Type, to support recursive Structs. */ HierarchicalType(TypeSystem typeSystem, Class<ST> superTypeClass, String name, String description, ImmutableSet<String> superTypes, int numFields) { this( typeSystem, superTypeClass, name, description, AtlasConstants.DEFAULT_TYPE_VERSION, superTypes, numFields); } HierarchicalType(TypeSystem typeSystem, Class<ST> superTypeClass, String name, String description, String version, ImmutableSet<String> superTypes, int numFields) { super(name, description, version); this.typeSystem = typeSystem; this.superTypeClass = superTypeClass; this.fieldMapping = null; this.numFields = numFields; this.superTypes = superTypes; this.immediateAttrs = ImmutableList.of(); this.attributeNameToType = null; } HierarchicalType(TypeSystem typeSystem, Class<ST> superTypeClass, String name, ImmutableSet<String> superTypes, AttributeInfo... fields) throws AtlasException { this(typeSystem, superTypeClass, name, null, superTypes, fields); } HierarchicalType(TypeSystem typeSystem, Class<ST> superTypeClass, String name, String description, ImmutableSet<String> superTypes, AttributeInfo... fields) throws AtlasException { this(typeSystem, superTypeClass, name, description, AtlasConstants.DEFAULT_TYPE_VERSION, superTypes, fields); } HierarchicalType(TypeSystem typeSystem, Class<ST> superTypeClass, String name, String description, String version, ImmutableSet<String> superTypes, AttributeInfo... fields) throws AtlasException { super(name, description, version); this.typeSystem = typeSystem; this.superTypeClass = superTypeClass; Pair<FieldMapping, ImmutableMap<String, String>> p = constructFieldMapping(superTypes, fields); this.fieldMapping = p.left; this.attributeNameToType = p.right; this.numFields = this.fieldMapping.fields.size(); this.superTypes = superTypes == null ? ImmutableSet.<String>of() : superTypes; this.immediateAttrs = ImmutableList.copyOf(fields); } public FieldMapping fieldMapping() { return fieldMapping; } /** * Given type must be a SubType of this type. * @param typeName * @throws AtlasException */ public boolean isSubType(String typeName) throws AtlasException { HierarchicalType cType = typeSystem.getDataType(HierarchicalType.class, typeName); return (cType == this || cType.superTypePaths.containsKey(getName())); } /** * Validate that current definition can be updated with the new definition * @param newType * @return true if the current definition can be updated with the new definition, else false */ @Override public void validateUpdate(IDataType newType) throws TypeUpdateException { super.validateUpdate(newType); HierarchicalType newHierarchicalType = (HierarchicalType) newType; //validate on supertypes if ((newHierarchicalType.superTypes.size() != superTypes.size()) || !newHierarchicalType.superTypes.containsAll(superTypes)) { throw new TypeUpdateException(newType, "New type cannot modify superTypes"); } //validate on fields try { TypeUtils.validateUpdate(fieldMapping, newHierarchicalType.fieldMapping); } catch (TypeUpdateException e) { throw new TypeUpdateException(newType, e); } } protected void setupSuperTypesGraph() throws AtlasException { setupSuperTypesGraph(superTypes); } private void setupSuperTypesGraph(ImmutableSet<String> superTypes) throws AtlasException { Map<String, List<Path>> superTypePaths = new HashMap<>(); Map<String, Path> pathNameToPathMap = new HashMap<>(); Queue<Path> queue = new LinkedList<>(); queue.add(new Node(getName())); while (!queue.isEmpty()) { Path currentPath = queue.poll(); ST superType = Objects.equals(currentPath.typeName, getName()) ? (ST) this : typeSystem.getDataType(superTypeClass, currentPath.typeName); pathNameToPathMap.put(currentPath.pathName, currentPath); if (superType != this) { List<Path> typePaths = superTypePaths.get(superType.getName()); if (typePaths == null) { typePaths = new ArrayList<>(); superTypePaths.put(superType.getName(), typePaths); } typePaths.add(currentPath); } ImmutableSet<String> sTs = superType == this ? superTypes : superType.superTypes; if (sTs != null) { for (String sT : sTs) { queue.add(new Path(sT, currentPath)); } } } this.superTypePaths = ImmutableMap.copyOf(superTypePaths); this.pathNameToPathMap = ImmutableMap.copyOf(pathNameToPathMap); } protected Pair<FieldMapping, ImmutableMap<String, String>> constructFieldMapping(ImmutableSet<String> superTypes, AttributeInfo... fields) throws AtlasException { Map<String, AttributeInfo> fieldsMap = new LinkedHashMap(); Map<String, Integer> fieldPos = new HashMap(); Map<String, Integer> fieldNullPos = new HashMap(); Map<String, String> attributeNameToType = new HashMap<>(); int numBools = 0; int numBytes = 0; int numShorts = 0; int numInts = 0; int numLongs = 0; int numFloats = 0; int numDoubles = 0; int numBigInts = 0; int numBigDecimals = 0; int numDates = 0; int numStrings = 0; int numArrays = 0; int numMaps = 0; int numStructs = 0; int numReferenceables = 0; setupSuperTypesGraph(superTypes); Iterator<Path> pathItr = pathIterator(); while (pathItr.hasNext()) { Path currentPath = pathItr.next(); ST superType = Objects.equals(currentPath.typeName, getName()) ? (ST) this : typeSystem.getDataType(superTypeClass, currentPath.typeName); ImmutableList<AttributeInfo> superTypeFields = superType == this ? ImmutableList.copyOf(fields) : superType.immediateAttrs; Set<String> immediateFields = new HashSet<>(); for (AttributeInfo i : superTypeFields) { if (superType == this) { if (immediateFields.contains(i.name)) { throw new AtlasException(String.format( "Struct defintion cannot contain multiple fields with the" + " same name %s", i.name)); } immediateFields.add(i.name); } String attrName = i.name; if (fieldsMap.containsKey(attrName)) { attrName = currentPath.addOverrideAttr(attrName); } attributeNameToType.put(attrName, superType.getName()); fieldsMap.put(attrName, i); fieldNullPos.put(attrName, fieldNullPos.size()); if (i.dataType() == DataTypes.BOOLEAN_TYPE) { fieldPos.put(attrName, numBools); numBools++; } else if (i.dataType() == DataTypes.BYTE_TYPE) { fieldPos.put(attrName, numBytes); numBytes++; } else if (i.dataType() == DataTypes.SHORT_TYPE) { fieldPos.put(attrName, numShorts); numShorts++; } else if (i.dataType() == DataTypes.INT_TYPE) { fieldPos.put(attrName, numInts); numInts++; } else if (i.dataType() == DataTypes.LONG_TYPE) { fieldPos.put(attrName, numLongs); numLongs++; } else if (i.dataType() == DataTypes.FLOAT_TYPE) { fieldPos.put(attrName, numFloats); numFloats++; } else if (i.dataType() == DataTypes.DOUBLE_TYPE) { fieldPos.put(attrName, numDoubles); numDoubles++; } else if (i.dataType() == DataTypes.BIGINTEGER_TYPE) { fieldPos.put(attrName, numBigInts); numBigInts++; } else if (i.dataType() == DataTypes.BIGDECIMAL_TYPE) { fieldPos.put(attrName, numBigDecimals); numBigDecimals++; } else if (i.dataType() == DataTypes.DATE_TYPE) { fieldPos.put(attrName, numDates); numDates++; } else if (i.dataType() == DataTypes.STRING_TYPE) { fieldPos.put(attrName, numStrings); numStrings++; } else if (i.dataType().getTypeCategory() == DataTypes.TypeCategory.ENUM) { fieldPos.put(i.name, numInts); numInts++; } else if (i.dataType().getTypeCategory() == DataTypes.TypeCategory.ARRAY) { fieldPos.put(attrName, numArrays); numArrays++; } else if (i.dataType().getTypeCategory() == DataTypes.TypeCategory.MAP) { fieldPos.put(attrName, numMaps); numMaps++; } else if (i.dataType().getTypeCategory() == DataTypes.TypeCategory.STRUCT || i.dataType().getTypeCategory() == DataTypes.TypeCategory.TRAIT) { fieldPos.put(attrName, numStructs); numStructs++; } else if (i.dataType().getTypeCategory() == DataTypes.TypeCategory.CLASS) { fieldPos.put(attrName, numReferenceables); numReferenceables++; } else { throw new AtlasException(String.format("Unknown datatype %s", i.dataType())); } } } this.superTypePaths = ImmutableMap.copyOf(superTypePaths); this.pathNameToPathMap = ImmutableMap.copyOf(pathNameToPathMap); FieldMapping fm = new FieldMapping(fieldsMap, fieldPos, fieldNullPos, numBools, numBytes, numShorts, numInts, numLongs, numFloats, numDoubles, numBigInts, numBigDecimals, numDates, numStrings, numArrays, numMaps, numStructs, numReferenceables); return new Pair(fm, ImmutableMap.copyOf(attributeNameToType)); } public IStruct castAs(IStruct s, String superTypeName) throws AtlasException { if (!superTypePaths.containsKey(superTypeName)) { throw new AtlasException(String.format("Cannot downcast to %s from type %s", superTypeName, getName())); } if (s != null) { if (!Objects.equals(s.getTypeName(), getName())) { throw new AtlasException( String.format("Downcast called on wrong type %s, instance type is %s", getName(), s.getTypeName())); } List<Path> pathToSuper = superTypePaths.get(superTypeName); if (pathToSuper.size() > 1) { throw new AtlasException(String.format( "Cannot downcast called to %s, from %s: there are multiple paths " + "to SuperType", superTypeName, getName())); } ST superType = typeSystem.getDataType(superTypeClass, superTypeName); Map<String, String> downCastMap = superType.constructDowncastFieldMap(this, pathToSuper.get(0)); return new DownCastStructInstance(superTypeName, new DownCastFieldMapping(ImmutableMap.copyOf(downCastMap)), s); } return null; } public ST getDefinedType(String attrName) throws AtlasException { if (!attributeNameToType.containsKey(attrName)) { throw new AtlasException(String.format("Unknown attribute %s in type %s", attrName, getName())); } return typeSystem.getDataType(superTypeClass, attributeNameToType.get(attrName)); } public String getDefinedTypeName(String attrName) throws AtlasException { return getDefinedType(attrName).getName(); } public String getQualifiedName(String attrName) throws AtlasException { String attrTypeName = getDefinedTypeName(attrName); return attrName.contains(".") ? attrName : String.format("%s.%s", attrTypeName, attrName); } protected Map<String, String> constructDowncastFieldMap(ST subType, Path pathToSubType) { String pathToSubTypeName = pathToSubType.pathAfterThis; /* * the downcastMap; */ Map<String, String> dCMap = new HashMap<>(); Iterator<Path> itr = pathIterator(); while (itr.hasNext()) { Path p = itr.next(); Path pInSubType = (Path) subType.pathNameToPathMap.get(p.pathName + "." + pathToSubTypeName); if (pInSubType.hiddenAttributeMap != null) { for (Map.Entry<String, String> e : pInSubType.hiddenAttributeMap.entrySet()) { String mappedInThisType = p.hiddenAttributeMap != null ? p.hiddenAttributeMap.get(e.getKey()) : null; if (mappedInThisType == null) { dCMap.put(e.getKey(), e.getValue()); } else { dCMap.put(mappedInThisType, e.getValue()); } } } } return dCMap; } @Override public String toString() { StringBuilder buf = new StringBuilder(); try { output(buf, new HashSet<String>()); } catch (AtlasException e) { throw new RuntimeException(e); } return buf.toString(); } @Override public void output(Appendable buf, Set<String> typesInProcess) throws AtlasException { if (typesInProcess == null) { typesInProcess = new HashSet<>(); } else if (typesInProcess.contains(name)) { // Avoid infinite recursion on bi-directional reference attributes. try { buf.append(name); } catch (IOException e) { throw new AtlasException(e); } return; } typesInProcess.add(name); try { buf.append(getClass().getSimpleName()).append('{'); buf.append("name=").append(name); buf.append(", description=").append(description); buf.append(", superTypes=").append(superTypes.toString()); buf.append(", immediateAttrs=["); UnmodifiableIterator<AttributeInfo> it = immediateAttrs.iterator(); while (it.hasNext()) { AttributeInfo attrInfo = it.next(); attrInfo.output(buf, typesInProcess); if (it.hasNext()) { buf.append(", "); } else { buf.append(']'); } } buf.append("}"); } catch(IOException e) { throw new AtlasException(e); } finally { typesInProcess.remove(name); } } public Set<String> getAllSuperTypeNames() { return superTypePaths.keySet(); } public Iterator<Path> pathIterator() { return new PathItr(); } static class Path { public final String typeName; public final String pathName; public final String pathAfterThis; private final Path subTypePath; /* * name mapping for attributes hidden by a SubType. */ Map<String, String> hiddenAttributeMap; Path(String typeName, Path childPath) throws AtlasException { this.typeName = typeName; this.subTypePath = childPath; if (childPath.contains(typeName)) { throw new CyclicTypeDefinition(this); } pathName = String.format("%s.%s", typeName, childPath.pathName); pathAfterThis = childPath.pathName; } Path(String typeName) { assert getClass() == Node.class; this.typeName = typeName; this.subTypePath = null; pathName = typeName; pathAfterThis = null; } public boolean contains(String typeName) { return this.typeName.equals(typeName) || (subTypePath != null && subTypePath.contains(typeName)); } public String pathString(String nodeSep) { StringBuilder b = new StringBuilder(); Path p = this; while (p != null) { b.append(p.typeName); p = p.subTypePath; if (p != null) { b.append(nodeSep); } } return b.toString(); } String addOverrideAttr(String name) { hiddenAttributeMap = hiddenAttributeMap == null ? new HashMap<String, String>() : hiddenAttributeMap; String oName = pathName + "." + name; hiddenAttributeMap.put(name, oName); return oName; } } static class Node extends Path { Node(String typeName) { super(typeName); } } static class CyclicTypeDefinition extends AtlasException { CyclicTypeDefinition(Path p) { super(String.format("Cycle in Type Definition %s", p.pathString(" -> "))); } } class PathItr implements Iterator<Path> { Queue<Path> pathQueue; PathItr() { pathQueue = new LinkedList<>(); pathQueue.add(pathNameToPathMap.get(getName())); } @Override public boolean hasNext() { return !pathQueue.isEmpty(); } @Override public Path next() { Path p = pathQueue.poll(); if(p != null) { ST t = null; try { t = typeSystem.getDataType(superTypeClass, p.typeName); } catch (AtlasException me) { throw new RuntimeException(me); } if (t.superTypes != null) { for (String sT : (ImmutableSet<String>) t.superTypes) { String nm = sT + "." + p.pathName; pathQueue.add(pathNameToPathMap.get(nm)); } } } return p; } @Override public void remove() { throw new UnsupportedOperationException(); } } } <|start_filename|>typesystem/src/main/java/org/apache/atlas/typesystem/types/HierarchicalTypeDefinition.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.typesystem.types; import com.google.common.collect.ImmutableSet; import org.apache.atlas.AtlasConstants; import java.util.Objects; public class HierarchicalTypeDefinition<T extends HierarchicalType> extends StructTypeDefinition { public final ImmutableSet<String> superTypes; public final String hierarchicalMetaTypeName; public HierarchicalTypeDefinition(Class<T> hierarchicalMetaType, String typeName, String typeDescription, ImmutableSet<String> superTypes, AttributeDefinition[] attributeDefinitions) { this(hierarchicalMetaType, typeName, typeDescription, AtlasConstants.DEFAULT_TYPE_VERSION, superTypes, attributeDefinitions); } // Used only for de-serializing JSON String to typedef. public HierarchicalTypeDefinition( String hierarchicalMetaTypeName, String typeName, String typeDescription, String typeVersion, String[] superTypes, AttributeDefinition[] attributeDefinitions) throws ClassNotFoundException { this((Class<T>) Class.forName(hierarchicalMetaTypeName), typeName, typeDescription, typeVersion, ImmutableSet.copyOf(superTypes), attributeDefinitions); } // Used only for de-serializing JSON String to typedef (no typeVersion). public HierarchicalTypeDefinition( String hierarchicalMetaTypeName, String typeName, String typeDescription, String[] superTypes, AttributeDefinition[] attributeDefinitions) throws ClassNotFoundException { this((Class<T>) Class.forName(hierarchicalMetaTypeName), typeName, typeDescription, AtlasConstants.DEFAULT_TYPE_VERSION, ImmutableSet.copyOf(superTypes), attributeDefinitions); } // Used only for serializing typedef to JSON String. public HierarchicalTypeDefinition( String hierarchicalMetaTypeName, String typeName, String typeDescription, String typeVersion, ImmutableSet<String> superTypes, AttributeDefinition[] attributeDefinitions, String typeDef) throws ClassNotFoundException { this((Class<T>) Class.forName(hierarchicalMetaTypeName), typeName, typeDescription, typeVersion, superTypes, attributeDefinitions); } // Used only for serializing typedef to JSON String (no typeVersion). public HierarchicalTypeDefinition( String hierarchicalMetaTypeName, String typeName, String typeDescription, ImmutableSet<String> superTypes, AttributeDefinition[] attributeDefinitions, String typeDef) throws ClassNotFoundException { this((Class<T>) Class.forName(hierarchicalMetaTypeName), typeName, typeDescription, AtlasConstants.DEFAULT_TYPE_VERSION, superTypes, attributeDefinitions); } public HierarchicalTypeDefinition(Class<T> hierarchicalMetaType, String typeName, String typeDescription, String typeVersion, ImmutableSet<String> superTypes, AttributeDefinition[] attributeDefinitions) { super(typeName, typeDescription, typeVersion, false, attributeDefinitions); this.hierarchicalMetaTypeName = hierarchicalMetaType.getName(); this.superTypes = superTypes == null ? ImmutableSet.<String>of() : superTypes; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; HierarchicalTypeDefinition<?> that = (HierarchicalTypeDefinition<?>) o; return Objects.equals(superTypes, that.superTypes) && Objects.equals(hierarchicalMetaTypeName, that.hierarchicalMetaTypeName); } @Override public int hashCode() { return Objects.hash(super.hashCode(), superTypes, hierarchicalMetaTypeName); } } <|start_filename|>webapp/src/main/java/org/apache/atlas/web/service/SecureEmbeddedServer.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.web.service; import org.apache.atlas.ApplicationProperties; import org.apache.atlas.AtlasConfiguration; import org.apache.atlas.AtlasException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.alias.CredentialProvider; import org.apache.hadoop.security.alias.CredentialProviderFactory; import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.SecureRequestCustomizer; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.SslConnectionFactory; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; import static org.apache.atlas.security.SecurityProperties.ATLAS_SSL_EXCLUDE_CIPHER_SUITES; import static org.apache.atlas.security.SecurityProperties.CERT_STORES_CREDENTIAL_PROVIDER_PATH; import static org.apache.atlas.security.SecurityProperties.CLIENT_AUTH_KEY; import static org.apache.atlas.security.SecurityProperties.DEFATULT_TRUSTORE_FILE_LOCATION; import static org.apache.atlas.security.SecurityProperties.DEFAULT_CIPHER_SUITES; import static org.apache.atlas.security.SecurityProperties.DEFAULT_KEYSTORE_FILE_LOCATION; import static org.apache.atlas.security.SecurityProperties.KEYSTORE_FILE_KEY; import static org.apache.atlas.security.SecurityProperties.KEYSTORE_PASSWORD_KEY; import static org.apache.atlas.security.SecurityProperties.SERVER_CERT_PASSWORD_KEY; import static org.apache.atlas.security.SecurityProperties.TRUSTSTORE_FILE_KEY; import static org.apache.atlas.security.SecurityProperties.TRUSTSTORE_PASSWORD_KEY; import static org.apache.atlas.security.SecurityProperties.ATLAS_SSL_EXCLUDE_PROTOCOLS; import static org.apache.atlas.security.SecurityProperties.DEFAULT_EXCLUDE_PROTOCOLS; /** * This is a jetty server which requires client auth via certificates. */ public class SecureEmbeddedServer extends EmbeddedServer { private static final Logger LOG = LoggerFactory.getLogger(SecureEmbeddedServer.class); public SecureEmbeddedServer(int port, String path) throws IOException { super(port, path); } protected Connector getConnector(int port) throws IOException { org.apache.commons.configuration.Configuration config = getConfiguration(); SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setKeyStorePath(config.getString(KEYSTORE_FILE_KEY, System.getProperty(KEYSTORE_FILE_KEY, DEFAULT_KEYSTORE_FILE_LOCATION))); sslContextFactory.setKeyStorePassword(getPassword(config, KEYSTORE_PASSWORD_KEY)); sslContextFactory.setKeyManagerPassword(getPassword(config, SERVER_CERT_PASSWORD_KEY)); sslContextFactory.setTrustStorePath(config.getString(TRUSTSTORE_FILE_KEY, System.getProperty(TRUSTSTORE_FILE_KEY, DEFATULT_TRUSTORE_FILE_LOCATION))); sslContextFactory.setTrustStorePassword(getPassword(config, TRUSTSTORE_PASSWORD_KEY)); sslContextFactory.setWantClientAuth(config.getBoolean(CLIENT_AUTH_KEY, Boolean.getBoolean(CLIENT_AUTH_KEY))); List<Object> cipherList = config.getList(ATLAS_SSL_EXCLUDE_CIPHER_SUITES, DEFAULT_CIPHER_SUITES); sslContextFactory.setExcludeCipherSuites(cipherList.toArray(new String[cipherList.size()])); sslContextFactory.setRenegotiationAllowed(false); String[] excludedProtocols = config.containsKey(ATLAS_SSL_EXCLUDE_PROTOCOLS) ? config.getStringArray(ATLAS_SSL_EXCLUDE_PROTOCOLS) : DEFAULT_EXCLUDE_PROTOCOLS; if (excludedProtocols != null && excludedProtocols.length > 0) { sslContextFactory.addExcludeProtocols(excludedProtocols); } // SSL HTTP Configuration // HTTP Configuration HttpConfiguration http_config = new HttpConfiguration(); http_config.setSecureScheme("https"); final int bufferSize = AtlasConfiguration.WEBSERVER_REQUEST_BUFFER_SIZE.getInt(); http_config.setSecurePort(port); http_config.setRequestHeaderSize(bufferSize); http_config.setResponseHeaderSize(bufferSize); http_config.setSendServerVersion(true); http_config.setSendDateHeader(false); HttpConfiguration https_config = new HttpConfiguration(http_config); https_config.addCustomizer(new SecureRequestCustomizer()); // SSL Connector ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(https_config)); sslConnector.setPort(port); server.addConnector(sslConnector); return sslConnector; } /** * Retrieves a password from a configured credential provider or prompts for the password and stores it in the * configured credential provider. * @param config application configuration * @param key the key/alias for the password. * @return the password. * @throws IOException */ private String getPassword(org.apache.commons.configuration.Configuration config, String key) throws IOException { String password; String provider = config.getString(CERT_STORES_CREDENTIAL_PROVIDER_PATH); if (provider != null) { LOG.info("Attempting to retrieve password from configured credential provider path"); Configuration c = new Configuration(); c.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, provider); CredentialProvider credentialProvider = CredentialProviderFactory.getProviders(c).get(0); CredentialProvider.CredentialEntry entry = credentialProvider.getCredentialEntry(key); if (entry == null) { throw new IOException(String.format("No credential entry found for %s. " + "Please create an entry in the configured credential provider", key)); } else { password = String.valueOf(entry.getCredential()); } } else { throw new IOException("No credential provider path configured for storage of certificate store passwords"); } return password; } /** * Returns the application configuration. * @return */ protected org.apache.commons.configuration.Configuration getConfiguration() { try { return ApplicationProperties.get(); } catch (AtlasException e) { throw new RuntimeException("Unable to load configuration: " + ApplicationProperties.APPLICATION_PROPERTIES); } } } <|start_filename|>intg/src/main/java/org/apache/atlas/type/AtlasTypeUtil.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.type; import com.google.common.collect.ImmutableSet; import org.apache.atlas.model.instance.AtlasEntity; import org.apache.atlas.model.instance.AtlasEntityHeader; import org.apache.atlas.model.instance.AtlasObjectId; import org.apache.atlas.model.typedef.*; import org.apache.atlas.model.typedef.AtlasEnumDef.AtlasEnumElementDef; import org.apache.atlas.model.typedef.AtlasRelationshipDef.PropagateTags; import org.apache.atlas.model.typedef.AtlasRelationshipDef.RelationshipCategory; import org.apache.atlas.model.typedef.AtlasStructDef.AtlasAttributeDef; import org.apache.atlas.model.typedef.AtlasStructDef.AtlasAttributeDef.Cardinality; import org.apache.atlas.model.typedef.AtlasStructDef.AtlasConstraintDef; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.*; /** * Utility methods for AtlasType/AtlasTypeDef. */ public class AtlasTypeUtil { private static final Set<String> ATLAS_BUILTIN_TYPENAMES = new HashSet<>(); private static final String NAME_REGEX = "[a-zA-Z][a-zA-Z0-9_ ]*"; private static final String TRAIT_NAME_REGEX = "[a-zA-Z][a-zA-Z0-9_ .]*"; private static final Pattern NAME_PATTERN = Pattern.compile(NAME_REGEX); private static final Pattern TRAIT_NAME_PATTERN = Pattern.compile(TRAIT_NAME_REGEX); private static final String InvalidTypeNameErrorMessage = "Name must consist of a letter followed by a sequence of [ letter, number, '_' ] characters."; private static final String InvalidTraitTypeNameErrorMessage = "Name must consist of a letter followed by a sequence of [ letter, number, '_', '.' ] characters."; static { Collections.addAll(ATLAS_BUILTIN_TYPENAMES, AtlasBaseTypeDef.ATLAS_BUILTIN_TYPES); } public static Set<String> getReferencedTypeNames(String typeName) { Set<String> ret = new HashSet<>(); getReferencedTypeNames(typeName, ret); return ret; } public static boolean isBuiltInType(String typeName) { return ATLAS_BUILTIN_TYPENAMES.contains(typeName); } public static boolean isArrayType(String typeName) { return StringUtils.startsWith(typeName, ATLAS_TYPE_ARRAY_PREFIX) && StringUtils.endsWith(typeName, ATLAS_TYPE_ARRAY_SUFFIX); } public static boolean isMapType(String typeName) { return StringUtils.startsWith(typeName, ATLAS_TYPE_MAP_PREFIX) && StringUtils.endsWith(typeName, ATLAS_TYPE_MAP_SUFFIX); } public static boolean isValidTypeName(String typeName) { Matcher m = NAME_PATTERN.matcher(typeName); return m.matches(); } public static String getInvalidTypeNameErrorMessage() { return InvalidTypeNameErrorMessage; } public static boolean isValidTraitTypeName(String typeName) { Matcher m = TRAIT_NAME_PATTERN.matcher(typeName); return m.matches(); } public static String getInvalidTraitTypeNameErrorMessage() { return InvalidTraitTypeNameErrorMessage; } public static String getStringValue(Map map, Object key) { Object ret = map != null ? map.get(key) : null; return ret != null ? ret.toString() : null; } private static void getReferencedTypeNames(String typeName, Set<String> referencedTypeNames) { if (StringUtils.isNotBlank(typeName) && !referencedTypeNames.contains(typeName)) { if (typeName.startsWith(ATLAS_TYPE_ARRAY_PREFIX) && typeName.endsWith(ATLAS_TYPE_ARRAY_SUFFIX)) { int startIdx = ATLAS_TYPE_ARRAY_PREFIX.length(); int endIdx = typeName.length() - ATLAS_TYPE_ARRAY_SUFFIX.length(); String elementTypeName = typeName.substring(startIdx, endIdx); getReferencedTypeNames(elementTypeName, referencedTypeNames); } else if (typeName.startsWith(ATLAS_TYPE_MAP_PREFIX) && typeName.endsWith(ATLAS_TYPE_MAP_SUFFIX)) { int startIdx = ATLAS_TYPE_MAP_PREFIX.length(); int endIdx = typeName.length() - ATLAS_TYPE_MAP_SUFFIX.length(); String[] keyValueTypes = typeName.substring(startIdx, endIdx).split(ATLAS_TYPE_MAP_KEY_VAL_SEP, 2); String keyTypeName = keyValueTypes.length > 0 ? keyValueTypes[0] : null; String valueTypeName = keyValueTypes.length > 1 ? keyValueTypes[1] : null; getReferencedTypeNames(keyTypeName, referencedTypeNames); getReferencedTypeNames(valueTypeName, referencedTypeNames); } else { referencedTypeNames.add(typeName); } } } public static AtlasAttributeDef createOptionalAttrDef(String name, AtlasType dataType) { return new AtlasAttributeDef(name, dataType.getTypeName(), true, Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList()); } public static AtlasAttributeDef createOptionalAttrDef(String name, String dataType) { return new AtlasAttributeDef(name, dataType, true, Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList()); } public static AtlasAttributeDef createRequiredAttrDef(String name, String dataType) { return new AtlasAttributeDef(name, dataType, false, Cardinality.SINGLE, 1, 1, false, true, Collections.<AtlasConstraintDef>emptyList()); } public static AtlasAttributeDef createListRequiredAttrDef(String name, String dataType) { return new AtlasAttributeDef(name, dataType, false, Cardinality.LIST, 1, Integer.MAX_VALUE, false, true, Collections.<AtlasConstraintDef>emptyList()); } public static AtlasAttributeDef createOptionalListAttrDef(String name, String dataType) { return new AtlasAttributeDef(name, dataType, true, Cardinality.LIST, 1, Integer.MAX_VALUE, false, true, Collections.<AtlasConstraintDef>emptyList()); } public static AtlasAttributeDef createRequiredListAttrDefWithConstraint(String name, String dataType, String type, Map param) { AtlasAttributeDef ret = AtlasTypeUtil.createListRequiredAttrDef(name, dataType); ret.addConstraint(new AtlasConstraintDef(type, param)); return ret; } public static AtlasAttributeDef createRequiredAttrDefWithConstraint(String name, String typeName, String type, Map param) { AtlasAttributeDef ret = AtlasTypeUtil.createRequiredAttrDef(name, typeName); ret.addConstraint(new AtlasConstraintDef(type, param)); return ret; } public static AtlasAttributeDef createOptionalAttrDefWithConstraint(String name, String typeName, String type, Map param) { AtlasAttributeDef ret = AtlasTypeUtil.createOptionalAttrDef(name, typeName); ret.addConstraint(new AtlasConstraintDef(type, param)); return ret; } public static AtlasAttributeDef createUniqueRequiredAttrDef(String name, AtlasType dataType) { return new AtlasAttributeDef(name, dataType.getTypeName(), false, Cardinality.SINGLE, 1, 1, true, true, Collections.<AtlasConstraintDef>emptyList()); } public static AtlasAttributeDef createUniqueRequiredAttrDef(String name, String typeName) { return new AtlasAttributeDef(name, typeName, false, Cardinality.SINGLE, 1, 1, true, true, Collections.<AtlasConstraintDef>emptyList()); } public static AtlasAttributeDef createRequiredAttrDef(String name, AtlasType dataType) { return new AtlasAttributeDef(name, dataType.getTypeName(), false, Cardinality.SINGLE, 1, 1, false, true, Collections.<AtlasConstraintDef>emptyList()); } public static AtlasEnumDef createEnumTypeDef(String name, String description, AtlasEnumElementDef... enumValues) { return new AtlasEnumDef(name, description, "1.0", Arrays.asList(enumValues)); } public static AtlasClassificationDef createTraitTypeDef(String name, ImmutableSet<String> superTypes, AtlasAttributeDef... attrDefs) { return createTraitTypeDef(name, null, superTypes, attrDefs); } public static AtlasClassificationDef createTraitTypeDef(String name, String description, ImmutableSet<String> superTypes, AtlasAttributeDef... attrDefs) { return createTraitTypeDef(name, description, "1.0", superTypes, attrDefs); } public static AtlasClassificationDef createTraitTypeDef(String name, String description, String version, ImmutableSet<String> superTypes, AtlasAttributeDef... attrDefs) { return new AtlasClassificationDef(name, description, version, Arrays.asList(attrDefs), superTypes); } public static AtlasStructDef createStructTypeDef(String name, AtlasAttributeDef... attrDefs) { return createStructTypeDef(name, null, attrDefs); } public static AtlasStructDef createStructTypeDef(String name, String description, AtlasAttributeDef... attrDefs) { return new AtlasStructDef(name, description, "1.0", Arrays.asList(attrDefs)); } public static AtlasEntityDef createClassTypeDef(String name, ImmutableSet<String> superTypes, AtlasAttributeDef... attrDefs) { return createClassTypeDef(name, null, "1.0", superTypes, attrDefs); } public static AtlasEntityDef createClassTypeDef(String name, String description, ImmutableSet<String> superTypes, AtlasAttributeDef... attrDefs) { return createClassTypeDef(name, description, "1.0", superTypes, attrDefs); } public static AtlasEntityDef createClassTypeDef(String name, String description, String version, ImmutableSet<String> superTypes, AtlasAttributeDef... attrDefs) { return new AtlasEntityDef(name, description, version, Arrays.asList(attrDefs), superTypes); } public static AtlasRelationshipDef createRelationshipTypeDef(String name, String description, String version, RelationshipCategory relationshipCategory, PropagateTags propagateTags, AtlasRelationshipEndDef endDef1, AtlasRelationshipEndDef endDef2, AtlasAttributeDef... attrDefs) { return new AtlasRelationshipDef(name, description, version, relationshipCategory, propagateTags, endDef1, endDef2, Arrays.asList(attrDefs)); } public static AtlasTypesDef getTypesDef(List<AtlasEnumDef> enums, List<AtlasStructDef> structs, List<AtlasClassificationDef> traits, List<AtlasEntityDef> classes) { return new AtlasTypesDef(enums, structs, traits, classes); } public static List<AtlasTypeDefHeader> toTypeDefHeader(AtlasTypesDef typesDef) { List<AtlasTypeDefHeader> headerList = new LinkedList<>(); if (CollectionUtils.isNotEmpty(typesDef.getEnumDefs())) { for (AtlasEnumDef enumDef : typesDef.getEnumDefs()) { headerList.add(new AtlasTypeDefHeader(enumDef)); } } if (CollectionUtils.isNotEmpty(typesDef.getStructDefs())) { for (AtlasStructDef structDef : typesDef.getStructDefs()) { headerList.add(new AtlasTypeDefHeader(structDef)); } } if (CollectionUtils.isNotEmpty(typesDef.getClassificationDefs())) { for (AtlasClassificationDef classificationDef : typesDef.getClassificationDefs()) { headerList.add(new AtlasTypeDefHeader(classificationDef)); } } if (CollectionUtils.isNotEmpty(typesDef.getEntityDefs())) { for (AtlasEntityDef entityDef : typesDef.getEntityDefs()) { headerList.add(new AtlasTypeDefHeader(entityDef)); } } if (CollectionUtils.isNotEmpty(typesDef.getRelationshipDefs())) { for (AtlasRelationshipDef relationshipDef : typesDef.getRelationshipDefs()) { headerList.add(new AtlasTypeDefHeader(relationshipDef)); } } return headerList; } public static Collection<AtlasObjectId> toObjectIds(Collection<AtlasEntity> entities) { List<AtlasObjectId> ret = new ArrayList<>(); if (CollectionUtils.isNotEmpty(entities)) { for (AtlasEntity entity : entities) { if (entity != null) { ret.add(AtlasTypeUtil.getAtlasObjectId(entity)); } } } return ret; } public static Map toStructAttributes(Map map) { if (map != null && map.containsKey("typeName") && map.containsKey("attributes") && map.get("attributes") instanceof Map) { return (Map)map.get("attributes"); } return map; } public static AtlasObjectId getAtlasObjectId(AtlasEntity entity) { return new AtlasObjectId(entity.getGuid(), entity.getTypeName()); } public static AtlasObjectId getAtlasObjectId(AtlasEntityHeader header) { return new AtlasObjectId(header.getGuid(), header.getTypeName()); } public static boolean isValidGuid(AtlasObjectId objId) { return isValidGuid(objId.getGuid()); } public static boolean isAssignedGuid(AtlasObjectId objId) { return isAssignedGuid(objId.getGuid()); } public static boolean isUnAssignedGuid(AtlasObjectId objId) { return isUnAssignedGuid(objId.getGuid()); } public static boolean isValidGuid(String guid) { return isAssignedGuid(guid) || isUnAssignedGuid(guid); } public static boolean isAssignedGuid(String guid) { if (guid != null) { try { UUID.fromString(guid); return true; } catch (IllegalArgumentException e) { // ignore } } return false; } public static boolean isUnAssignedGuid(String guid) { return guid != null && guid.length() > 0 && guid.charAt(0) == '-'; } public static boolean isValid(AtlasObjectId objId) { if (isAssignedGuid(objId) || isUnAssignedGuid(objId)) { return true; } else if (StringUtils.isNotEmpty(objId.getTypeName()) && MapUtils.isNotEmpty(objId.getUniqueAttributes())) { return true; } return false; } public static String toDebugString(AtlasTypesDef typesDef) { StringBuilder sb = new StringBuilder(); sb.append("typesDef={"); if (typesDef != null) { sb.append("enumDefs=["); dumpTypeNames(typesDef.getEnumDefs(), sb); sb.append("],"); sb.append("structDefs=["); dumpTypeNames(typesDef.getStructDefs(), sb); sb.append("],"); sb.append("classificationDefs=["); dumpTypeNames(typesDef.getClassificationDefs(), sb); sb.append("],"); sb.append("entityDefs=["); dumpTypeNames(typesDef.getEntityDefs(), sb); sb.append("]"); sb.append("relationshipDefs=["); dumpTypeNames(typesDef.getRelationshipDefs(), sb); sb.append("]"); } sb.append("}"); return sb.toString(); } private static void dumpTypeNames(List<? extends AtlasBaseTypeDef> typeDefs, StringBuilder sb) { if (CollectionUtils.isNotEmpty(typeDefs)) { for (int i = 0; i < typeDefs.size(); i++) { AtlasBaseTypeDef typeDef = typeDefs.get(i); if (i > 0) { sb.append(","); } sb.append(typeDef.getName()); } } } } <|start_filename|>authorization/src/test/java/org/apache/atlas/authorize/simple/SimpleAtlasAuthorizerTest.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.authorize.simple; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Map; import org.apache.atlas.authorize.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.AssertJUnit; import org.testng.annotations.Test; public class SimpleAtlasAuthorizerTest { private static Logger LOG = LoggerFactory .getLogger(SimpleAtlasAuthorizerTest.class); @Test public void testAccessAllowedForUserAndGroup() { Map<String, Map<AtlasResourceTypes, List<String>>> userReadMap = null; Map<String, Map<AtlasResourceTypes, List<String>>> groupReadMap = null; List<String> policies = new ArrayList<>(); policies.add("hivePolicy;;usr1:r,usr2:rw;;grp1:rwu,grp2:u;;type:*abc,type:PII"); List<PolicyDef> policyDefs = new PolicyParser().parsePolicies(policies); PolicyUtil policyUtil = new PolicyUtil(); // group read map groupReadMap = policyUtil.createPermissionMap(policyDefs, AtlasActionTypes.READ, SimpleAtlasAuthorizer.AtlasAccessorTypes.GROUP); // creating user readMap userReadMap = policyUtil.createPermissionMap(policyDefs, AtlasActionTypes.READ, SimpleAtlasAuthorizer.AtlasAccessorTypes.USER); Set<AtlasResourceTypes> resourceType = new HashSet<>(); resourceType.add(AtlasResourceTypes.TYPE); String resource = "xsdfhjabc"; AtlasActionTypes action = AtlasActionTypes.READ; String user = "usr1"; Set<String> userGroups = new HashSet<>(); userGroups.add("grp3"); try { AtlasAccessRequest request = new AtlasAccessRequest(resourceType, resource, action, user, userGroups,"127.0.0.1"); SimpleAtlasAuthorizer authorizer = (SimpleAtlasAuthorizer) AtlasAuthorizerFactory .getAtlasAuthorizer(); authorizer .setResourcesForTesting(userReadMap, groupReadMap, action); boolean isAccessAllowed = authorizer.isAccessAllowed(request); // getUserReadMap AssertJUnit.assertEquals(true, isAccessAllowed); } catch (AtlasAuthorizationException e) { if (LOG.isErrorEnabled()) { LOG.error("AtlasAuthorizationException in Unit Test", e); } } } @Test public void testAccessAllowedForGroup() { Map<String, Map<AtlasResourceTypes, List<String>>> userReadMap = null; Map<String, Map<AtlasResourceTypes, List<String>>> groupReadMap = null; List<String> policies = new ArrayList<>(); policies.add("hivePolicy;;usr1:r,usr2:rw;;grp1:rwu,grp2:u;;type:PII"); List<PolicyDef> policyDefs = new PolicyParser().parsePolicies(policies); PolicyUtil policyUtil = new PolicyUtil(); // creating group read map groupReadMap = policyUtil.createPermissionMap(policyDefs, AtlasActionTypes.READ, SimpleAtlasAuthorizer.AtlasAccessorTypes.GROUP); // creating user readMap userReadMap = policyUtil.createPermissionMap(policyDefs, AtlasActionTypes.READ, SimpleAtlasAuthorizer.AtlasAccessorTypes.USER); Set<AtlasResourceTypes> resourceType = new HashSet<>(); resourceType.add(AtlasResourceTypes.TYPE); String resource = "PII"; AtlasActionTypes action = AtlasActionTypes.READ; String user = "usr3"; Set<String> userGroups = new HashSet<>(); userGroups.add("grp1"); AtlasAccessRequest request = new AtlasAccessRequest(resourceType, resource, action, user, userGroups,"127.0.0.1"); try { SimpleAtlasAuthorizer authorizer = (SimpleAtlasAuthorizer) AtlasAuthorizerFactory .getAtlasAuthorizer(); authorizer .setResourcesForTesting(userReadMap, groupReadMap, action); boolean isAccessAllowed = authorizer.isAccessAllowed(request); AssertJUnit.assertEquals(true, isAccessAllowed); } catch (AtlasAuthorizationException e) { if (LOG.isErrorEnabled()) { LOG.error("AtlasAuthorizationException in Unit Test", e); } } } @Test public void testResourceNotAvailableInPolicy() { Map<String, Map<AtlasResourceTypes, List<String>>> userReadMap = null; Map<String, Map<AtlasResourceTypes, List<String>>> groupReadMap = null; List<String> policies = new ArrayList<>(); policies.add("hivePolicy;;usr1:r,usr2:rw;;grp1:rwu,grp2:u;;type:PII"); List<PolicyDef> policyDefs = new PolicyParser().parsePolicies(policies); PolicyUtil policyUtil = new PolicyUtil(); // group read map groupReadMap = policyUtil.createPermissionMap(policyDefs, AtlasActionTypes.READ, SimpleAtlasAuthorizer.AtlasAccessorTypes.GROUP); // creating user readMap userReadMap = policyUtil.createPermissionMap(policyDefs, AtlasActionTypes.READ, SimpleAtlasAuthorizer.AtlasAccessorTypes.USER); Set<AtlasResourceTypes> resourceType = new HashSet<>(); resourceType.add(AtlasResourceTypes.TYPE); String resource = "abc"; AtlasActionTypes action = AtlasActionTypes.READ; String user = "usr1"; Set<String> userGroups = new HashSet<>(); userGroups.add("grp1"); AtlasAccessRequest request = new AtlasAccessRequest(resourceType, resource, action, user, userGroups,"127.0.0.1"); try { SimpleAtlasAuthorizer authorizer = (SimpleAtlasAuthorizer) AtlasAuthorizerFactory .getAtlasAuthorizer(); authorizer .setResourcesForTesting(userReadMap, groupReadMap, action); boolean isAccessAllowed = authorizer.isAccessAllowed(request); AssertJUnit.assertEquals(false, isAccessAllowed); } catch (AtlasAuthorizationException e) { if (LOG.isErrorEnabled()) { LOG.error("AtlasAuthorizationException in Unit Test", e); } } } @Test public void testAccessNotAllowedForUserAndGroup() { Map<String, Map<AtlasResourceTypes, List<String>>> userReadMap = null; Map<String, Map<AtlasResourceTypes, List<String>>> groupReadMap = null; List<String> policies = new ArrayList<>(); policies.add("hivePolicy;;usr1:r,usr2:rw;;grp1:rwu,grp2:u;;type:PII"); List<PolicyDef> policyDefs = new PolicyParser().parsePolicies(policies); PolicyUtil policyUtil = new PolicyUtil(); // group read map groupReadMap = policyUtil.createPermissionMap(policyDefs, AtlasActionTypes.READ, SimpleAtlasAuthorizer.AtlasAccessorTypes.GROUP); // creating user readMap userReadMap = policyUtil.createPermissionMap(policyDefs, AtlasActionTypes.READ, SimpleAtlasAuthorizer.AtlasAccessorTypes.USER); Set<AtlasResourceTypes> resourceType = new HashSet<>(); resourceType.add(AtlasResourceTypes.TYPE); String resource = "PII"; AtlasActionTypes action = AtlasActionTypes.READ; String user = "usr3"; Set<String> userGroups = new HashSet<>(); userGroups.add("grp3"); AtlasAccessRequest request = new AtlasAccessRequest(resourceType, resource, action, user, userGroups,"127.0.0.1"); try { SimpleAtlasAuthorizer authorizer = (SimpleAtlasAuthorizer) AtlasAuthorizerFactory .getAtlasAuthorizer(); authorizer .setResourcesForTesting(userReadMap, groupReadMap, action); boolean isAccessAllowed = authorizer.isAccessAllowed(request); AssertJUnit.assertEquals(false, isAccessAllowed); } catch (AtlasAuthorizationException e) { if (LOG.isErrorEnabled()) { LOG.error("AtlasAuthorizationException in Unit Test", e); } } } } <|start_filename|>typesystem/src/main/java/org/apache/atlas/typesystem/types/TypeUtils.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.typesystem.types; import com.google.common.collect.ImmutableList; import org.apache.atlas.AtlasException; import java.io.IOException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TypeUtils { public static final String NAME_REGEX = "[a-zA-z][a-zA-Z0-9_]*"; public static final Pattern NAME_PATTERN = Pattern.compile(NAME_REGEX); public static final Pattern ARRAY_TYPE_NAME_PATTERN = Pattern.compile(String.format("array<(%s)>", NAME_REGEX)); public static final Pattern MAP_TYPE_NAME_PATTERN = Pattern.compile(String.format("map<(%s),(%s)>", NAME_REGEX, NAME_REGEX)); public static void outputVal(String val, Appendable buf, String prefix) throws AtlasException { try { buf.append(prefix).append(val); } catch (IOException ie) { throw new AtlasException(ie); } } public static String parseAsArrayType(String typeName) { Matcher m = ARRAY_TYPE_NAME_PATTERN.matcher(typeName); return m.matches() ? m.group(1) : null; } public static String[] parseAsMapType(String typeName) { Matcher m = MAP_TYPE_NAME_PATTERN.matcher(typeName); return m.matches() ? new String[]{m.group(1), m.group(2)} : null; } public static Map<AttributeInfo, List<String>> buildAttrInfoToNameMap(FieldMapping f) { Map<AttributeInfo, List<String>> b = new HashMap(); for (Map.Entry<String, AttributeInfo> e : f.fields.entrySet()) { List<String> names = b.get(e.getValue()); if (names == null) { names = new ArrayList<>(); b.put(e.getValue(), names); } names.add(e.getKey()); } return b; } public static class Pair<L, R> { public L left; public R right; public Pair(L left, R right) { this.left = left; this.right = right; } public static <L, R> Pair<L, R> of(L left, R right) { return new Pair<>(left, right); } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Pair p = (Pair)o; return Objects.equals(left, p.left) && Objects.equals(right, p.right); } public int hashCode() { return Objects.hash(left, right); } } /** * Validates that the old field mapping can be replaced with new field mapping * @param oldFieldMapping * @param newFieldMapping */ public static void validateUpdate(FieldMapping oldFieldMapping, FieldMapping newFieldMapping) throws TypeUpdateException { Map<String, AttributeInfo> newFields = newFieldMapping.fields; for (AttributeInfo attribute : oldFieldMapping.fields.values()) { if (newFields.containsKey(attribute.name)) { AttributeInfo newAttribute = newFields.get(attribute.name); //If old attribute is also in new definition, only allowed change is multiplicity change from REQUIRED to OPTIONAL if (!newAttribute.equals(attribute)) { if (attribute.multiplicity == Multiplicity.REQUIRED && newAttribute.multiplicity == Multiplicity.OPTIONAL) { continue; } else { throw new TypeUpdateException("Attribute " + attribute.name + " can't be updated"); } } } else { //If old attribute is missing in new definition, return false as attributes can't be deleted throw new TypeUpdateException("Old Attribute " + attribute.name + " is missing"); } } //Only new attributes Set<String> newAttributes = new HashSet<>(ImmutableList.copyOf(newFields.keySet())); newAttributes.removeAll(oldFieldMapping.fields.keySet()); for (String attributeName : newAttributes) { AttributeInfo newAttribute = newFields.get(attributeName); //New required attribute can't be added if (newAttribute.multiplicity == Multiplicity.REQUIRED) { throw new TypeUpdateException("Can't add required attribute " + attributeName); } } } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/typestore/TypeVisitor.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.typestore; import java.util.List; import org.apache.atlas.AtlasException; import org.apache.atlas.repository.RepositoryException; import org.apache.atlas.typesystem.types.AttributeInfo; import org.apache.atlas.typesystem.types.DataTypes.TypeCategory; import org.apache.atlas.typesystem.types.EnumType; import org.apache.atlas.typesystem.types.IDataType; /** * Callback mechanism used when storing types. As {@link GraphBackedTypeStore} traverses * through the types being persisted, these methods are called with the information that * it finds. */ public interface TypeVisitor { /** * Called when an enumeration type is found * @param type * @throws AtlasException */ void visitEnumeration(EnumType type) throws AtlasException; /** * Called with a data type that is associated with a given attribute. There can * be more than one. For example, map types have both a key and a value type. * This is called once for each type. This is called once for each datatype * associated with the given attribute. * * @param typeName The name of the type being processed. * @param sourceAttr The attribute in that type that we are processing. * @param attrType A dataType associated with that attribute. * @throws AtlasException */ void visitAttributeDataType(String typeName, AttributeInfo sourceAttr, IDataType attrType) throws AtlasException; /** * Called when a super type is found. It is called once for each superType. * * @param typeName The type being processed. * @param superType The name of the super type that was found. * @throws RepositoryException * @throws AtlasException */ void visitSuperType(String typeName, String superType) throws RepositoryException, AtlasException; /** * Called with the list of immediate attribute names that were found for the given type. It * is called once per type. * * @param typeName The name of the type that is being processed. * @param attrNames The names of all of the immediate attributes in the type. * @throws AtlasException */ void visitAttributeNames(String typeName, List<String> attrNames) throws AtlasException; /** * Called once for each immediate attribute in a type. * @param typeName The name of the type that is being procesed * @param attribute The immediate attribute that was found * * @throws StorageException * @throws AtlasException */ void visitAttribute(String typeName, AttributeInfo attribute) throws StorageException, AtlasException; /** * Called once for each struct, class, and trait type that was found. It is * called when we start processing that type. * * @param category The category of the type * @param typeName The name of the type * @param typeDescription The description of the type. */ void visitDataType(TypeCategory category, String typeName, String typeDescription); } <|start_filename|>repository/src/test/java/org/apache/atlas/services/EntityDiscoveryServiceTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.services; import org.apache.atlas.TestModules; import org.apache.atlas.discovery.EntityDiscoveryService; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.typedef.AtlasEntityDef; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.commons.lang.StringUtils; import org.powermock.reflect.Whitebox; import org.testng.annotations.BeforeClass; import org.testng.annotations.Guice; import org.testng.annotations.Test; import javax.inject.Inject; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; @Guice(modules = TestModules.TestOnlyModule.class) public class EntityDiscoveryServiceTest { private final String TEST_TYPE = "test"; private final String TEST_TYPE1 = "test1"; private final String TEST_TYPE2 = "test2"; private final String TEST_TYPE3 = "test3"; private final String TEST_TYPE_WITH_SUB_TYPES = "testTypeWithSubTypes"; private AtlasTypeRegistry typeRegistry = new AtlasTypeRegistry(); AtlasEntityDef typeTest = null; AtlasEntityDef typeTest1 = null; AtlasEntityDef typeTest2 = null; AtlasEntityDef typeTest3 = null; AtlasEntityDef typeWithSubTypes = null; private final int maxTypesCountInIdxQuery = 10; @Inject EntityDiscoveryService discoveryService; @BeforeClass public void init() throws AtlasBaseException { typeTest = new AtlasEntityDef(TEST_TYPE); typeTest1 = new AtlasEntityDef(TEST_TYPE1); typeTest2 = new AtlasEntityDef(TEST_TYPE2); typeTest3 = new AtlasEntityDef(TEST_TYPE3); typeWithSubTypes = new AtlasEntityDef(TEST_TYPE_WITH_SUB_TYPES); typeTest1.addSuperType(TEST_TYPE_WITH_SUB_TYPES); typeTest2.addSuperType(TEST_TYPE_WITH_SUB_TYPES); typeTest3.addSuperType(TEST_TYPE_WITH_SUB_TYPES); AtlasTypeRegistry.AtlasTransientTypeRegistry ttr = typeRegistry.lockTypeRegistryForUpdate(); ttr.addType(typeTest); ttr.addType(typeWithSubTypes); ttr.addType(typeTest1); ttr.addType(typeTest2); ttr.addType(typeTest3); typeRegistry.releaseTypeRegistryForUpdate(ttr, true); } @Test public void getSubTypesForType_NullStringReturnsEmptyString() throws Exception { invokeGetSubTypesForType(null, maxTypesCountInIdxQuery); } @Test public void getSubTypesForType_BlankStringReturnsEmptyString() throws Exception { invokeGetSubTypesForType(" ", maxTypesCountInIdxQuery); } @Test public void getSubTypesForType_EmptyStringReturnsEmptyString() throws Exception { invokeGetSubTypesForType("", maxTypesCountInIdxQuery); } @Test public void getSubTypeForTypeWithNoSubType_ReturnsTypeString() throws Exception { String s = invokeGetSubTypesForType(TEST_TYPE, 10); assertEquals(s, "(" + TEST_TYPE + ")"); } @Test public void getSubTypeForTypeWithSubTypes_ReturnsOrClause() throws Exception { String s = invokeGetSubTypesForType(TEST_TYPE_WITH_SUB_TYPES, maxTypesCountInIdxQuery); assertTrue(s.startsWith("(")); assertTrue(s.contains(TEST_TYPE_WITH_SUB_TYPES)); assertTrue(s.contains(TEST_TYPE1)); assertTrue(s.contains(TEST_TYPE2)); assertTrue(s.contains(TEST_TYPE3)); assertTrue(s.endsWith(")")); } @Test public void getSubTypeForTypeWithSubTypes_ReturnsEmptyString() throws Exception { String s = invokeGetSubTypesForType(TEST_TYPE_WITH_SUB_TYPES, 2); assertTrue(StringUtils.isBlank(s)); } private String invokeGetSubTypesForType(String inputString, int maxSubTypes) throws Exception { String s = Whitebox.invokeMethod(EntityDiscoveryService.class, "getTypeFilter", typeRegistry, inputString, maxSubTypes); assertNotNull(s); return s; } } <|start_filename|>repository/src/main/java/org/apache/atlas/util/IndexedInstance.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.util; import org.apache.atlas.repository.graph.GraphHelper; import org.apache.atlas.typesystem.IReferenceableInstance; /** * Data structure that stores an IReferenceableInstance and its location within * a list. * * @see GraphHelper#getVerticesForInstancesByUniqueAttributes */ public class IndexedInstance { private final IReferenceableInstance instance_; private final int index_; public IndexedInstance(IReferenceableInstance instance, int index) { super(); this.instance_ = instance; this.index_ = index; } public IReferenceableInstance getInstance() { return instance_; } public int getIndex() { return index_; } @Override public int hashCode() { return instance_.hashCode(); } @Override public boolean equals(Object other) { if(!(other instanceof IndexedInstance)) { return false; } IndexedInstance otherInstance = (IndexedInstance)other; return instance_.equals(otherInstance.getInstance()); } } <|start_filename|>repository/src/main/java/org/apache/atlas/discovery/SearchProcessor.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.discovery; import org.apache.atlas.ApplicationProperties; import org.apache.atlas.AtlasException; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.discovery.SearchParameters; import org.apache.atlas.model.discovery.SearchParameters.FilterCriteria; import org.apache.atlas.model.discovery.SearchParameters.FilterCriteria.Condition; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.graphdb.*; import org.apache.atlas.repository.store.graph.v1.AtlasGraphUtilsV1; import org.apache.atlas.type.AtlasEntityType; import org.apache.atlas.type.AtlasStructType; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.regex.Pattern; public abstract class SearchProcessor { private static final Logger LOG = LoggerFactory.getLogger(SearchProcessor.class); public static final Pattern STRAY_AND_PATTERN = Pattern.compile("(AND\\s+)+\\)"); public static final Pattern STRAY_OR_PATTERN = Pattern.compile("(OR\\s+)+\\)"); public static final Pattern STRAY_ELIPSIS_PATTERN = Pattern.compile("(\\(\\s*)\\)"); public static final int MAX_RESULT_SIZE = getApplicationProperty(Constants.INDEX_SEARCH_MAX_RESULT_SET_SIZE, 150); public static final int MAX_QUERY_STR_LENGTH_TYPES = getApplicationProperty(Constants.INDEX_SEARCH_TYPES_MAX_QUERY_STR_LENGTH, 512); public static final int MAX_QUERY_STR_LENGTH_TAGS = getApplicationProperty(Constants.INDEX_SEARCH_TAGS_MAX_QUERY_STR_LENGTH, 512); public static final String AND_STR = " AND "; public static final String EMPTY_STRING = ""; public static final String SPACE_STRING = " "; public static final String BRACE_OPEN_STR = "("; public static final String BRACE_CLOSE_STR = ")"; private static final Map<SearchParameters.Operator, String> OPERATOR_MAP = new HashMap<>(); static { OPERATOR_MAP.put(SearchParameters.Operator.LT,"v.\"%s\": [* TO %s}"); OPERATOR_MAP.put(SearchParameters.Operator.GT,"v.\"%s\": {%s TO *]"); OPERATOR_MAP.put(SearchParameters.Operator.LTE,"v.\"%s\": [* TO %s]"); OPERATOR_MAP.put(SearchParameters.Operator.GTE,"v.\"%s\": [%s TO *]"); OPERATOR_MAP.put(SearchParameters.Operator.EQ,"v.\"%s\": %s"); OPERATOR_MAP.put(SearchParameters.Operator.NEQ,"-" + "v.\"%s\": %s"); OPERATOR_MAP.put(SearchParameters.Operator.IN, "v.\"%s\": (%s)"); // this should be a list of quoted strings OPERATOR_MAP.put(SearchParameters.Operator.LIKE, "v.\"%s\": (%s)"); // this should be regex pattern OPERATOR_MAP.put(SearchParameters.Operator.STARTS_WITH, "v.\"%s\": (%s*)"); OPERATOR_MAP.put(SearchParameters.Operator.ENDS_WITH, "v.\"%s\": (*%s)"); OPERATOR_MAP.put(SearchParameters.Operator.CONTAINS, "v.\"%s\": (*%s*)"); } protected final SearchContext context; protected SearchProcessor nextProcessor; protected SearchProcessor(SearchContext context) { this.context = context; } public void addProcessor(SearchProcessor processor) { if (nextProcessor == null) { nextProcessor = processor; } else { nextProcessor.addProcessor(processor); } } public abstract List<AtlasVertex> execute(); public void filter(List<AtlasVertex> entityVertices) { if (nextProcessor != null && CollectionUtils.isNotEmpty(entityVertices)) { nextProcessor.filter(entityVertices); } } protected void processSearchAttributes(AtlasStructType structType, FilterCriteria filterCriteria, Set<String> solrFiltered, Set<String> gremlinFiltered, Set<String> allAttributes) { if (structType == null || filterCriteria == null) { return; } Condition filterCondition = filterCriteria.getCondition(); List<FilterCriteria> criterion = filterCriteria.getCriterion(); if (filterCondition != null && CollectionUtils.isNotEmpty(criterion)) { for (SearchParameters.FilterCriteria criteria : criterion) { processSearchAttributes(structType, criteria, solrFiltered, gremlinFiltered, allAttributes); } } else if (StringUtils.isNotEmpty(filterCriteria.getAttributeName())) { try { String attributeName = filterCriteria.getAttributeName(); String qualifiedName = structType.getQualifiedAttributeName(attributeName); Set<String> indexedKeys = context.getIndexedKeys(); if (indexedKeys != null && indexedKeys.contains(qualifiedName)) { solrFiltered.add(attributeName); } else { LOG.warn("search includes non-indexed attribute '{}'; might cause poor performance", qualifiedName); gremlinFiltered.add(attributeName); } if (structType instanceof AtlasEntityType) { // Capture the entity attributes context.getEntityAttributes().add(attributeName); } allAttributes.add(attributeName); } catch (AtlasBaseException e) { LOG.warn(e.getMessage()); } } } // // If filterCriteria contains any non-indexed attribute inside OR condition: // Solr+Grelin can't be used. Need to use only Gremlin filter for all attributes. Examples: // (OR idx-att1=x non-idx-attr=z) // (AND idx-att1=x (OR idx-attr2=y non-idx-attr=z)) // Else // Solr can be used for indexed-attribute filtering and Gremlin for non-indexed attributes. Examples: // (AND idx-att1=x idx-attr2=y non-idx-attr=z) // (AND (OR idx-att1=x idx-attr1=y) non-idx-attr=z) // (AND (OR idx-att1=x idx-attr1=y) non-idx-attr=z (AND idx-attr2=xyz idx-attr2=abc)) // protected boolean canApplySolrFilter(AtlasStructType structType, FilterCriteria filterCriteria, boolean insideOrCondition) { if (filterCriteria == null) { return true; } boolean ret = true; Condition filterCondition = filterCriteria.getCondition(); List<FilterCriteria> criterion = filterCriteria.getCriterion(); Set<String> indexedKeys = context.getIndexedKeys(); if (filterCondition != null && CollectionUtils.isNotEmpty(criterion)) { insideOrCondition = insideOrCondition || filterCondition == Condition.OR; // If we have nested criterion let's find any nested ORs with non-indexed attr for (FilterCriteria criteria : criterion) { ret = canApplySolrFilter(structType, criteria, insideOrCondition); if (!ret) { break; } } } else if (StringUtils.isNotEmpty(filterCriteria.getAttributeName())) { try { String qualifiedName = structType.getQualifiedAttributeName(filterCriteria.getAttributeName()); if (insideOrCondition && (indexedKeys == null || !indexedKeys.contains(qualifiedName))) { ret = false; } } catch (AtlasBaseException e) { LOG.warn(e.getMessage()); } } return ret; } protected void constructTypeTestQuery(StringBuilder solrQuery, String typeAndAllSubTypesQryStr) { if (StringUtils.isNotEmpty(typeAndAllSubTypesQryStr)) { if (solrQuery.length() > 0) { solrQuery.append(AND_STR); } solrQuery.append("v.\"").append(Constants.TYPE_NAME_PROPERTY_KEY).append("\":").append(typeAndAllSubTypesQryStr); } } protected void constructFilterQuery(StringBuilder solrQuery, AtlasStructType type, FilterCriteria filterCriteria, Set<String> solrAttributes) { if (filterCriteria != null) { LOG.debug("Processing Filters"); String filterQuery = toSolrQuery(type, filterCriteria, solrAttributes, 0); if (StringUtils.isNotEmpty(filterQuery)) { if (solrQuery.length() > 0) { solrQuery.append(AND_STR); } solrQuery.append(filterQuery); } } } protected void constructStateTestQuery(StringBuilder solrQuery) { if (solrQuery.length() > 0) { solrQuery.append(AND_STR); } solrQuery.append("v.\"").append(Constants.STATE_PROPERTY_KEY).append("\":ACTIVE"); } private String toSolrQuery(AtlasStructType type, FilterCriteria criteria, Set<String> solrAttributes, int level) { return toSolrQuery(type, criteria, solrAttributes, new StringBuilder(), level); } private String toSolrQuery(AtlasStructType type, FilterCriteria criteria, Set<String> solrAttributes, StringBuilder sb, int level) { if (criteria.getCondition() != null && CollectionUtils.isNotEmpty(criteria.getCriterion())) { StringBuilder nestedExpression = new StringBuilder(); for (FilterCriteria filterCriteria : criteria.getCriterion()) { String nestedQuery = toSolrQuery(type, filterCriteria, solrAttributes, level + 1); if (StringUtils.isNotEmpty(nestedQuery)) { if (nestedExpression.length() > 0) { nestedExpression.append(SPACE_STRING).append(criteria.getCondition()).append(SPACE_STRING); } // todo: when a neq operation is nested and occurs in the beginning of the query, solr has issues nestedExpression.append(nestedQuery); } } if (level == 0) { return nestedExpression.length() > 0 ? sb.append(nestedExpression).toString() : EMPTY_STRING; } else { return nestedExpression.length() > 0 ? sb.append(BRACE_OPEN_STR).append(nestedExpression).append(BRACE_CLOSE_STR).toString() : EMPTY_STRING; } } else if (solrAttributes.contains(criteria.getAttributeName())){ return toSolrExpression(type, criteria.getAttributeName(), criteria.getOperator(), criteria.getAttributeValue()); } else { return EMPTY_STRING; } } private String toSolrExpression(AtlasStructType type, String attrName, SearchParameters.Operator op, String attrVal) { String ret = EMPTY_STRING; try { if (OPERATOR_MAP.get(op) != null) { String qualifiedName = type.getQualifiedAttributeName(attrName); ret = String.format(OPERATOR_MAP.get(op), qualifiedName, AtlasStructType.AtlasAttribute.escapeIndexQueryValue(attrVal)); } } catch (AtlasBaseException ex) { LOG.warn(ex.getMessage()); } return ret; } protected AtlasGraphQuery toGremlinFilterQuery(AtlasStructType type, FilterCriteria criteria, Set<String> gremlinAttributes, AtlasGraphQuery query) { if (criteria != null) { if (criteria.getCondition() != null) { if (criteria.getCondition() == Condition.AND) { for (FilterCriteria filterCriteria : criteria.getCriterion()) { AtlasGraphQuery nestedQuery = toGremlinFilterQuery(type, filterCriteria, gremlinAttributes, context.getGraph().query()); query.addConditionsFrom(nestedQuery); } } else { List<AtlasGraphQuery> orConditions = new LinkedList<>(); for (FilterCriteria filterCriteria : criteria.getCriterion()) { AtlasGraphQuery nestedQuery = toGremlinFilterQuery(type, filterCriteria, gremlinAttributes, context.getGraph().query()); orConditions.add(context.getGraph().query().createChildQuery().addConditionsFrom(nestedQuery)); } if (!orConditions.isEmpty()) { query.or(orConditions); } } } else if (gremlinAttributes.contains(criteria.getAttributeName())) { String attrName = criteria.getAttributeName(); String attrValue = criteria.getAttributeValue(); SearchParameters.Operator operator = criteria.getOperator(); try { final String qualifiedName = type.getQualifiedAttributeName(attrName); switch (operator) { case LT: query.has(qualifiedName, AtlasGraphQuery.ComparisionOperator.LESS_THAN, attrValue); break; case LTE: query.has(qualifiedName, AtlasGraphQuery.ComparisionOperator.LESS_THAN_EQUAL, attrValue); break; case GT: query.has(qualifiedName, AtlasGraphQuery.ComparisionOperator.GREATER_THAN, attrValue); break; case GTE: query.has(qualifiedName, AtlasGraphQuery.ComparisionOperator.GREATER_THAN_EQUAL, attrValue); break; case EQ: query.has(qualifiedName, AtlasGraphQuery.ComparisionOperator.EQUAL, attrValue); break; case NEQ: query.has(qualifiedName, AtlasGraphQuery.ComparisionOperator.NOT_EQUAL, attrValue); break; case LIKE: // TODO: Maybe we need to validate pattern query.has(qualifiedName, AtlasGraphQuery.MatchingOperator.REGEX, getLikeRegex(attrValue)); break; case CONTAINS: query.has(qualifiedName, AtlasGraphQuery.MatchingOperator.REGEX, getContainsRegex(attrValue)); break; case STARTS_WITH: query.has(qualifiedName, AtlasGraphQuery.MatchingOperator.PREFIX, attrValue); break; case ENDS_WITH: query.has(qualifiedName, AtlasGraphQuery.MatchingOperator.REGEX, getSuffixRegex(attrValue)); break; case IN: LOG.warn("{}: unsupported operator. Ignored", operator); break; } } catch (AtlasBaseException e) { LOG.error("toGremlinFilterQuery(): failed for attrName=" + attrName + "; operator=" + operator + "; attrValue=" + attrValue, e); } } } return query; } private String getContainsRegex(String attributeValue) { return ".*" + attributeValue + ".*"; } private String getSuffixRegex(String attributeValue) { return ".*" + attributeValue; } private String getLikeRegex(String attributeValue) { return ".*" + attributeValue + ".*"; } protected List<AtlasVertex> getVerticesFromIndexQueryResult(Iterator<AtlasIndexQuery.Result> idxQueryResult, List<AtlasVertex> vertices) { if (idxQueryResult != null) { while (idxQueryResult.hasNext()) { AtlasVertex vertex = idxQueryResult.next().getVertex(); vertices.add(vertex); } } return vertices; } protected List<AtlasVertex> getVertices(Iterator<AtlasVertex> iterator, List<AtlasVertex> vertices) { if (iterator != null) { while (iterator.hasNext()) { AtlasVertex vertex = iterator.next(); vertices.add(vertex); } } return vertices; } protected Set<String> getGuids(List<AtlasVertex> vertices) { Set<String> ret = new HashSet<>(); if (vertices != null) { for(AtlasVertex vertex : vertices) { String guid = AtlasGraphUtilsV1.getIdFromVertex(vertex); if (StringUtils.isNotEmpty(guid)) { ret.add(guid); } } } return ret; } private static int getApplicationProperty(String propertyName, int defaultValue) { try { return ApplicationProperties.get().getInt(propertyName, defaultValue); } catch (AtlasException excp) { // ignore } return defaultValue; } } <|start_filename|>notification/src/main/java/org/apache/atlas/notification/entity/EntityNotificationImpl.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.notification.entity; import org.apache.atlas.AtlasException; import org.apache.atlas.typesystem.IReferenceableInstance; import org.apache.atlas.typesystem.IStruct; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.Struct; import org.apache.atlas.typesystem.types.FieldMapping; import org.apache.atlas.typesystem.types.TraitType; import org.apache.atlas.typesystem.types.TypeSystem; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; /** * Entity notification implementation. */ public class EntityNotificationImpl implements EntityNotification { private final Referenceable entity; private final OperationType operationType; private final List<IStruct> traits; // ----- Constructors ------------------------------------------------------ /** * No-arg constructor for serialization. */ @SuppressWarnings("unused") private EntityNotificationImpl() throws AtlasException { this(null, OperationType.ENTITY_CREATE, Collections.<IStruct>emptyList()); } /** * Construct an EntityNotification. * * @param entity the entity subject of the notification * @param operationType the type of operation that caused the notification * @param traits the traits for the given entity * * @throws AtlasException if the entity notification can not be created */ public EntityNotificationImpl(Referenceable entity, OperationType operationType, List<IStruct> traits) throws AtlasException { this.entity = entity; this.operationType = operationType; this.traits = traits; } /** * Construct an EntityNotification. * * @param entity the entity subject of the notification * @param operationType the type of operation that caused the notification * @param typeSystem the Atlas type system * * @throws AtlasException if the entity notification can not be created */ public EntityNotificationImpl(Referenceable entity, OperationType operationType, TypeSystem typeSystem) throws AtlasException { this(entity, operationType, getAllTraits(entity, typeSystem)); } // ----- EntityNotification ------------------------------------------------ @Override public IReferenceableInstance getEntity() { return entity; } @Override public List<IStruct> getAllTraits() { return traits; } @Override public OperationType getOperationType() { return operationType; } // ----- Object overrides -------------------------------------------------- @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EntityNotificationImpl that = (EntityNotificationImpl) o; return Objects.equals(entity, that.entity) && operationType == that.operationType && Objects.equals(traits, that.traits); } @Override public int hashCode() { return Objects.hash(entity, operationType, traits); } // ----- helper methods ---------------------------------------------------- private static List<IStruct> getAllTraits(IReferenceableInstance entityDefinition, TypeSystem typeSystem) throws AtlasException { List<IStruct> traitInfo = new LinkedList<>(); for (String traitName : entityDefinition.getTraits()) { IStruct trait = entityDefinition.getTrait(traitName); String typeName = trait.getTypeName(); Map<String, Object> valuesMap = trait.getValuesMap(); traitInfo.add(new Struct(typeName, valuesMap)); traitInfo.addAll(getSuperTraits(typeName, valuesMap, typeSystem)); } return traitInfo; } private static List<IStruct> getSuperTraits( String typeName, Map<String, Object> values, TypeSystem typeSystem) throws AtlasException { List<IStruct> superTypes = new LinkedList<>(); TraitType traitDef = typeSystem.getDataType(TraitType.class, typeName); Set<String> superTypeNames = traitDef.getAllSuperTypeNames(); for (String superTypeName : superTypeNames) { TraitType superTraitDef = typeSystem.getDataType(TraitType.class, superTypeName); Map<String, Object> superTypeValues = new HashMap<>(); FieldMapping fieldMapping = superTraitDef.fieldMapping(); if (fieldMapping != null) { Set<String> superTypeAttributeNames = fieldMapping.fields.keySet(); for (String superTypeAttributeName : superTypeAttributeNames) { if (values.containsKey(superTypeAttributeName)) { superTypeValues.put(superTypeAttributeName, values.get(superTypeAttributeName)); } } } IStruct superTrait = new Struct(superTypeName, superTypeValues); superTypes.add(superTrait); superTypes.addAll(getSuperTraits(superTypeName, values, typeSystem)); } return superTypes; } } <|start_filename|>repository/src/test/java/org/apache/atlas/repository/graph/GraphBackedMetadataRepositoryTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graph; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import org.apache.atlas.AtlasException; import org.apache.atlas.CreateUpdateEntitiesResult; import org.apache.atlas.TestModules; import org.apache.atlas.RequestContext; import org.apache.atlas.TestUtils; import org.apache.atlas.annotation.GraphTransaction; import org.apache.atlas.discovery.graph.GraphBackedDiscoveryService; import org.apache.atlas.query.QueryParams; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.MetadataRepository; import org.apache.atlas.repository.RepositoryException; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasEdgeDirection; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.AtlasGraphQuery; import org.apache.atlas.repository.graphdb.AtlasGraphQuery.ComparisionOperator; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.typesystem.IStruct; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.ITypedStruct; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.Struct; import org.apache.atlas.typesystem.exception.EntityNotFoundException; import org.apache.atlas.typesystem.exception.TraitNotFoundException; import org.apache.atlas.typesystem.persistence.AtlasSystemAttributes; import org.apache.atlas.typesystem.persistence.Id; import org.apache.atlas.typesystem.types.AttributeDefinition; import org.apache.atlas.typesystem.types.ClassType; import org.apache.atlas.typesystem.types.DataTypes; import org.apache.atlas.typesystem.types.HierarchicalTypeDefinition; import org.apache.atlas.typesystem.types.Multiplicity; import org.apache.atlas.typesystem.types.TraitType; import org.apache.atlas.typesystem.types.TypeSystem; import org.apache.atlas.typesystem.types.utils.TypesUtil; import org.apache.commons.lang.RandomStringUtils; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONObject; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Guice; import org.testng.annotations.Test; import javax.inject.Inject; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import static org.apache.atlas.typesystem.types.utils.TypesUtil.createClassTypeDef; import static org.apache.atlas.typesystem.types.utils.TypesUtil.createUniqueRequiredAttrDef; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; /** * GraphBackedMetadataRepository test * * Guice loads the dependencies and injects the necessary objects * */ @Guice(modules = TestModules.TestOnlyModule.class) public class GraphBackedMetadataRepositoryTest { @Inject private MetadataRepository repositoryService; @Inject private GraphBackedDiscoveryService discoveryService; private TypeSystem typeSystem; private String guid; private QueryParams queryParams = new QueryParams(100, 0); @BeforeClass public void setUp() throws Exception { typeSystem = TypeSystem.getInstance(); typeSystem.reset(); assertTrue(repositoryService instanceof GraphBackedMetadataRepository); repositoryService = TestUtils.addTransactionWrapper(repositoryService); new GraphBackedSearchIndexer(new AtlasTypeRegistry()); TestUtils.defineDeptEmployeeTypes(typeSystem); TestUtils.createHiveTypes(typeSystem); } @BeforeMethod public void setupContext() { TestUtils.resetRequestContext(); } @AfterClass public void tearDown() throws Exception { TypeSystem.getInstance().reset(); // AtlasGraphProvider.cleanup(); } @Test //In some cases of parallel APIs, the edge is added, but get edge by label doesn't return the edge. ATLAS-1104 public void testConcurrentCalls() throws Exception { final HierarchicalTypeDefinition<ClassType> refType = createClassTypeDef(randomString(), ImmutableSet.<String>of()); HierarchicalTypeDefinition<ClassType> type = createClassTypeDef(randomString(), ImmutableSet.<String>of(), new AttributeDefinition("ref", refType.typeName, Multiplicity.OPTIONAL, true, null)); typeSystem.defineClassType(refType); typeSystem.defineClassType(type); String refId1 = createEntity(new Referenceable(refType.typeName)).get(0); String refId2 = createEntity(new Referenceable(refType.typeName)).get(0); final Referenceable instance1 = new Referenceable(type.typeName); instance1.set("ref", new Referenceable(refId1, refType.typeName, null)); final Referenceable instance2 = new Referenceable(type.typeName); instance2.set("ref", new Referenceable(refId2, refType.typeName, null)); ExecutorService executor = Executors.newFixedThreadPool(3); List<Future<Object>> futures = new ArrayList<>(); futures.add(executor.submit(new Callable<Object>() { @Override public Object call() throws Exception { return createEntity(instance1).get(0); } })); futures.add(executor.submit(new Callable<Object>() { @Override public Object call() throws Exception { return createEntity(instance2).get(0); } })); futures.add(executor.submit(new Callable<Object>() { @Override public Object call() throws Exception { return discoveryService.searchByDSL(TestUtils.TABLE_TYPE, new QueryParams(10, 0)); } })); String id1 = (String) futures.get(0).get(); String id2 = (String) futures.get(1).get(); futures.get(2).get(); executor.shutdown(); boolean validated1 = assertEdge(id1, type.typeName); boolean validated2 = assertEdge(id2, type.typeName); assertTrue(validated1 | validated2); } private boolean assertEdge(String id, String typeName) throws Exception { AtlasGraph graph = TestUtils.getGraph(); Iterable<AtlasVertex> vertices = graph.query().has(Constants.GUID_PROPERTY_KEY, id).vertices(); AtlasVertex AtlasVertex = vertices.iterator().next(); Iterable<AtlasEdge> edges = AtlasVertex.getEdges(AtlasEdgeDirection.OUT, Constants.INTERNAL_PROPERTY_KEY_PREFIX + typeName + ".ref"); if (!edges.iterator().hasNext()) { ITypedReferenceableInstance entity = repositoryService.getEntityDefinition(id); assertNotNull(entity.get("ref")); return true; } return false; } @Test public void testSubmitEntity() throws Exception { ITypedReferenceableInstance hrDept = TestUtils.createDeptEg1(typeSystem); List<String> guids = repositoryService.createEntities(hrDept).getCreatedEntities(); Assert.assertNotNull(guids); Assert.assertEquals(guids.size(), 5); guid = guids.get(4); Assert.assertNotNull(guid); } @Test public void testCreateEntityWithOneNestingLevel() throws AtlasException { List<Referenceable> toValidate = new ArrayList<>(); Referenceable dept = new Referenceable(TestUtils.DEPARTMENT_TYPE); toValidate.add(dept); dept.set(TestUtils.NAME, "test1"); Referenceable mike = new Referenceable(TestUtils.PERSON_TYPE); toValidate.add(mike); mike.set(TestUtils.NAME, "Mike"); mike.set(TestUtils.DEPARTMENT_ATTR, dept); Referenceable mark = new Referenceable(TestUtils.PERSON_TYPE); toValidate.add(mark); mark.set(TestUtils.NAME, "Mark"); mark.set(TestUtils.DEPARTMENT_ATTR, dept); dept.set(TestUtils.EMPLOYEES_ATTR, ImmutableList.of(mike, mark)); Map<String,Referenceable> positions = new HashMap<>(); final String JANITOR = "janitor"; final String RECEPTIONIST = "receptionist"; positions.put(JANITOR, mike); positions.put(RECEPTIONIST, mark); dept.set(TestUtils.POSITIONS_ATTR, positions); ClassType deptType = TypeSystem.getInstance().getDataType(ClassType.class, TestUtils.DEPARTMENT_TYPE); ITypedReferenceableInstance deptInstance = deptType.convert(dept, Multiplicity.REQUIRED); CreateUpdateEntitiesResult result = repositoryService.createEntities(deptInstance); validateGuidMapping(toValidate, result); } @Test public void testCreateEntityWithTwoNestingLevels() throws AtlasException { List<Referenceable> toVerify = new ArrayList<>(); Referenceable dept = new Referenceable(TestUtils.DEPARTMENT_TYPE); toVerify.add(dept); dept.set(TestUtils.NAME, "test2"); Referenceable wallace = new Referenceable(TestUtils.PERSON_TYPE); toVerify.add(wallace); wallace.set(TestUtils.NAME, "Wallace"); wallace.set(TestUtils.DEPARTMENT_ATTR, dept); Referenceable wallaceComputer = new Referenceable(TestUtils.ASSET_TYPE); toVerify.add(wallaceComputer); wallaceComputer.set("name", "wallaceComputer"); wallace.set(TestUtils.ASSETS_ATTR, ImmutableList.of(wallaceComputer)); Referenceable jordan = new Referenceable(TestUtils.PERSON_TYPE); toVerify.add(jordan); jordan.set(TestUtils.NAME, "Jordan"); jordan.set(TestUtils.DEPARTMENT_ATTR, dept); Referenceable jordanComputer = new Referenceable(TestUtils.ASSET_TYPE); toVerify.add(jordanComputer); jordanComputer.set("name", "jordanComputer"); jordan.set(TestUtils.ASSETS_ATTR, ImmutableList.of(jordanComputer)); dept.set(TestUtils.EMPLOYEES_ATTR, ImmutableList.of(wallace, jordan)); Map<String,Referenceable> positions = new HashMap<>(); final String JANITOR = "janitor"; final String RECEPTIONIST = "receptionist"; positions.put(JANITOR, wallace); positions.put(RECEPTIONIST, jordan); dept.set(TestUtils.POSITIONS_ATTR, positions); ClassType deptType = TypeSystem.getInstance().getDataType(ClassType.class, TestUtils.DEPARTMENT_TYPE); ITypedReferenceableInstance deptInstance = deptType.convert(dept, Multiplicity.REQUIRED); CreateUpdateEntitiesResult result = repositoryService.createEntities(deptInstance); validateGuidMapping(toVerify, result); } @Test public void testCreateEntityWithThreeNestingLevels() throws AtlasException { List<Referenceable> toVerify = new ArrayList<>(); Referenceable dept = new Referenceable(TestUtils.DEPARTMENT_TYPE); toVerify.add(dept); dept.set(TestUtils.NAME, "test3"); Referenceable barry = new Referenceable(TestUtils.PERSON_TYPE); toVerify.add(barry); barry.set(TestUtils.NAME, "barry"); barry.set(TestUtils.DEPARTMENT_ATTR, dept); Referenceable barryComputer = new Referenceable(TestUtils.ASSET_TYPE); toVerify.add(barryComputer); barryComputer.set("name", "barryComputer"); barry.set(TestUtils.ASSETS_ATTR, ImmutableList.of(barryComputer)); Referenceable barryHardDrive = new Referenceable(TestUtils.ASSET_TYPE); toVerify.add(barryHardDrive); barryHardDrive.set("name", "barryHardDrive"); Referenceable barryCpuFan = new Referenceable(TestUtils.ASSET_TYPE); toVerify.add(barryCpuFan); barryCpuFan.set("name", "barryCpuFan"); Referenceable barryVideoCard = new Referenceable(TestUtils.ASSET_TYPE); toVerify.add(barryVideoCard); barryVideoCard.set("name", "barryVideoCard"); barryComputer.set("childAssets", ImmutableList.of(barryHardDrive, barryVideoCard, barryCpuFan)); Referenceable jacob = new Referenceable(TestUtils.PERSON_TYPE); toVerify.add(jacob); jacob.set(TestUtils.NAME, "jacob"); jacob.set(TestUtils.DEPARTMENT_ATTR, dept); Referenceable jacobComputer = new Referenceable(TestUtils.ASSET_TYPE); toVerify.add(jacobComputer); jacobComputer.set("name", "jacobComputer"); jacob.set(TestUtils.ASSETS_ATTR, ImmutableList.of(jacobComputer)); Referenceable jacobHardDrive = new Referenceable(TestUtils.ASSET_TYPE); toVerify.add(jacobHardDrive); jacobHardDrive.set("name", "jacobHardDrive"); Referenceable jacobCpuFan = new Referenceable(TestUtils.ASSET_TYPE); toVerify.add(jacobCpuFan); jacobCpuFan.set("name", "jacobCpuFan"); Referenceable jacobVideoCard = new Referenceable(TestUtils.ASSET_TYPE); toVerify.add(jacobVideoCard); jacobVideoCard.set("name", "jacobVideoCard"); jacobComputer.set("childAssets", ImmutableList.of(jacobHardDrive, jacobVideoCard, jacobCpuFan)); dept.set(TestUtils.EMPLOYEES_ATTR, ImmutableList.of(barry, jacob)); Map<String,Referenceable> positions = new HashMap<>(); final String JANITOR = "janitor"; final String RECEPTIONIST = "receptionist"; positions.put(JANITOR, barry); positions.put(RECEPTIONIST, jacob); dept.set(TestUtils.POSITIONS_ATTR, positions); ClassType deptType = TypeSystem.getInstance().getDataType(ClassType.class, TestUtils.DEPARTMENT_TYPE); ITypedReferenceableInstance deptInstance = deptType.convert(dept, Multiplicity.REQUIRED); CreateUpdateEntitiesResult result = repositoryService.createEntities(deptInstance); assertEquals(result.getCreatedEntities().size(), toVerify.size()); validateGuidMapping(toVerify, result); } private void validateGuidMapping(List<Referenceable> toVerify, CreateUpdateEntitiesResult result) throws AtlasException { Map<String,String> guids = result.getGuidMapping().getGuidAssignments(); TestUtils.assertContentsSame(result.getCreatedEntities(), guids.values()); assertEquals(guids.size(), toVerify.size()); for(Referenceable r : toVerify) { loadAndDoSimpleValidation(guids.get(r.getId()._getId()), r); } } private ITypedReferenceableInstance loadAndDoSimpleValidation(String guid, Referenceable inst) throws AtlasException { return TestUtils.loadAndDoSimpleValidation(guid, inst, repositoryService); } @Test(dependsOnMethods = "testSubmitEntity") public void testGetEntityDefinitionForDepartment() throws Exception { ITypedReferenceableInstance entity = repositoryService.getEntityDefinition(guid); Assert.assertNotNull(entity); //entity state should be active by default Assert.assertEquals(entity.getId().getState(), Id.EntityState.ACTIVE); //System attributes created time and modified time should not be null AtlasSystemAttributes systemAttributes = entity.getSystemAttributes(); Assert.assertNotNull(systemAttributes.createdTime); Assert.assertNotNull(systemAttributes.modifiedTime); } @Test(expectedExceptions = EntityNotFoundException.class) public void testGetEntityDefinitionNonExistent() throws Exception { repositoryService.getEntityDefinition("blah"); Assert.fail(); } @Test(dependsOnMethods = "testSubmitEntity") public void testGetEntityList() throws Exception { List<String> entityList = repositoryService.getEntityList(TestUtils.DEPARTMENT_TYPE); System.out.println("entityList = " + entityList); Assert.assertNotNull(entityList); Assert.assertTrue(entityList.contains(guid)); } @Test public void testGetTypeAttributeName() throws Exception { Assert.assertEquals(repositoryService.getTypeAttributeName(), Constants.ENTITY_TYPE_PROPERTY_KEY); } @Test(dependsOnMethods = "testSubmitEntity") public void testGetTraitLabel() throws Exception { Assert.assertEquals( repositoryService.getTraitLabel(typeSystem.getDataType(ClassType.class, TestUtils.TABLE_TYPE), TestUtils.CLASSIFICATION), TestUtils.CLASSIFICATION); } @Test public void testCreateEntity() throws Exception { Referenceable databaseInstance = new Referenceable(TestUtils.DATABASE_TYPE); databaseInstance.set("name", TestUtils.DATABASE_NAME); databaseInstance.set("description", "foo database"); databaseInstance.set("created", new Date(TestUtils.TEST_DATE_IN_LONG)); databaseInstance.set("namespace", "colo:cluster:hive:db"); databaseInstance.set("cluster", "cluster-1"); databaseInstance.set("colo", "colo-1"); System.out.println("databaseInstance = " + databaseInstance); ClassType dbType = typeSystem.getDataType(ClassType.class, TestUtils.DATABASE_TYPE); ITypedReferenceableInstance db = dbType.convert(databaseInstance, Multiplicity.REQUIRED); System.out.println("db = " + db); //Reuse the same database instance without id, with the same unique attribute ITypedReferenceableInstance table = createHiveTableInstance(databaseInstance); List<String> guids = createEntities(db, table); Assert.assertEquals(guids.size(), 7); //1 db + 5 columns + 1 table. Shouldn't create db again System.out.println("added db = " + guids.get(0)); System.out.println("added table = " + guids.get(6)); } @Test(dependsOnMethods = "testCreateEntity") public void testGetEntityDefinition() throws Exception { String guid = getGUID(); ITypedReferenceableInstance table = repositoryService.getEntityDefinition(guid); Assert.assertEquals(table.getDate("created"), new Date(TestUtils.TEST_DATE_IN_LONG)); System.out.println("*** table = " + table); } private List<String> createEntities(ITypedReferenceableInstance... instances) throws Exception { RequestContext.createContext(); return repositoryService.createEntities(instances).getCreatedEntities(); } private List<String> createEntity(Referenceable entity) throws Exception { ClassType type = typeSystem.getDataType(ClassType.class, entity.getTypeName()); ITypedReferenceableInstance instance = type.convert(entity, Multiplicity.REQUIRED); return createEntities(instance); } @GraphTransaction String getGUID() { AtlasVertex tableVertex = getTableEntityVertex(); String guid = GraphHelper.getSingleValuedProperty(tableVertex, Constants.GUID_PROPERTY_KEY, String.class); if (guid == null) { Assert.fail(); } return guid; } @GraphTransaction AtlasVertex getTableEntityVertex() { AtlasGraph graph = TestUtils.getGraph(); AtlasGraphQuery query = graph.query().has(Constants.ENTITY_TYPE_PROPERTY_KEY, ComparisionOperator.EQUAL, TestUtils.TABLE_TYPE); Iterator<AtlasVertex> results = query.vertices().iterator(); // returning one since guid should be unique AtlasVertex tableVertex = results.hasNext() ? results.next() : null; if (tableVertex == null) { Assert.fail(); } return tableVertex; } @Test(dependsOnMethods = "testCreateEntity") public void testGetTraitNames() throws Exception { final List<String> traitNames = repositoryService.getTraitNames(getGUID()); Assert.assertEquals(traitNames.size(), 1); Assert.assertEquals(traitNames, Arrays.asList(new String[]{TestUtils.CLASSIFICATION})); } @Test public void testGetTraitNamesForEmptyTraits() throws Exception { final List<String> traitNames = repositoryService.getTraitNames(guid); Assert.assertEquals(traitNames.size(), 0); } @Test(expectedExceptions = EntityNotFoundException.class) public void testGetTraitNamesForBadEntity() throws Exception { repositoryService.getTraitNames(UUID.randomUUID().toString()); Assert.fail(); } @Test public void testMultipleTypesWithSameUniqueAttribute() throws Exception { //Two entities of different types(with same supertype that has the unique attribute) with same qualified name should succeed HierarchicalTypeDefinition<ClassType> supertype = createClassTypeDef(randomString(), ImmutableSet.<String>of(), createUniqueRequiredAttrDef("name", DataTypes.STRING_TYPE)); HierarchicalTypeDefinition<ClassType> t1 = createClassTypeDef(randomString(), ImmutableSet.of(supertype.typeName)); HierarchicalTypeDefinition<ClassType> t2 = createClassTypeDef(randomString(), ImmutableSet.of(supertype.typeName)); typeSystem.defineClassTypes(supertype, t1, t2); final String name = randomString(); String id1 = createEntity(new Referenceable(t1.typeName) {{ set("name", name); }}).get(0); String id2 = createEntity(new Referenceable(t2.typeName) {{ set("name", name); }}).get(0); assertNotEquals(id1, id2); ITypedReferenceableInstance entity = repositoryService.getEntityDefinition(t1.typeName, "name", name); assertEquals(entity.getTypeName(), t1.typeName); assertEquals(entity.getId()._getId(), id1); entity = repositoryService.getEntityDefinition(t2.typeName, "name", name); assertEquals(entity.getTypeName(), t2.typeName); assertEquals(entity.getId()._getId(), id2); } @Test(dependsOnMethods = "testGetTraitNames") public void testAddTrait() throws Exception { final String aGUID = getGUID(); AtlasVertex AtlasVertex = GraphHelper.getInstance().getVertexForGUID(aGUID); Long modificationTimestampPreUpdate = GraphHelper.getSingleValuedProperty(AtlasVertex, Constants.MODIFICATION_TIMESTAMP_PROPERTY_KEY, Long.class); Assert.assertNotNull(modificationTimestampPreUpdate); List<String> traitNames = repositoryService.getTraitNames(aGUID); System.out.println("traitNames = " + traitNames); Assert.assertEquals(traitNames.size(), 1); Assert.assertTrue(traitNames.contains(TestUtils.CLASSIFICATION)); Assert.assertFalse(traitNames.contains(TestUtils.PII)); TraitType traitType = typeSystem.getDataType(TraitType.class, TestUtils.PII); ITypedStruct traitInstance = traitType.createInstance(); repositoryService.addTrait(aGUID, traitInstance); // refresh trait names traitNames = repositoryService.getTraitNames(aGUID); Assert.assertEquals(traitNames.size(), 2); Assert.assertTrue(traitNames.contains(TestUtils.PII)); Assert.assertTrue(traitNames.contains(TestUtils.CLASSIFICATION)); // Verify modification timestamp was updated. GraphHelper.getInstance().getVertexForGUID(aGUID); Long modificationTimestampPostUpdate = GraphHelper.getSingleValuedProperty(AtlasVertex, Constants.MODIFICATION_TIMESTAMP_PROPERTY_KEY, Long.class); Assert.assertNotNull(modificationTimestampPostUpdate); } @Test(dependsOnMethods = "testAddTrait") public void testAddTraitWithAttribute() throws Exception { final String aGUID = getGUID(); final String traitName = "P_I_I"; HierarchicalTypeDefinition<TraitType> piiTrait = TypesUtil .createTraitTypeDef(traitName, ImmutableSet.<String>of(), TypesUtil.createRequiredAttrDef("type", DataTypes.STRING_TYPE)); TraitType traitType = typeSystem.defineTraitType(piiTrait); ITypedStruct traitInstance = traitType.createInstance(); traitInstance.set("type", "SSN"); repositoryService.addTrait(aGUID, traitInstance); TestUtils.dumpGraph(TestUtils.getGraph()); // refresh trait names List<String> traitNames = repositoryService.getTraitNames(aGUID); Assert.assertEquals(traitNames.size(), 3); Assert.assertTrue(traitNames.contains(traitName)); ITypedReferenceableInstance instance = repositoryService.getEntityDefinition(aGUID); IStruct traitInstanceRef = instance.getTrait(traitName); String type = (String) traitInstanceRef.get("type"); Assert.assertEquals(type, "SSN"); } @Test(expectedExceptions = NullPointerException.class) public void testAddTraitWithNullInstance() throws Exception { repositoryService.addTrait(getGUID(), null); Assert.fail(); } @Test(dependsOnMethods = "testAddTrait", expectedExceptions = RepositoryException.class) public void testAddTraitForBadEntity() throws Exception { TraitType traitType = typeSystem.getDataType(TraitType.class, TestUtils.PII); ITypedStruct traitInstance = traitType.createInstance(); repositoryService.addTrait(UUID.randomUUID().toString(), traitInstance); Assert.fail(); } @Test(dependsOnMethods = "testAddTrait") public void testDeleteTrait() throws Exception { final String aGUID = getGUID(); AtlasVertex AtlasVertex = GraphHelper.getInstance().getVertexForGUID(aGUID); Long modificationTimestampPreUpdate = GraphHelper.getSingleValuedProperty(AtlasVertex, Constants.MODIFICATION_TIMESTAMP_PROPERTY_KEY, Long.class); Assert.assertNotNull(modificationTimestampPreUpdate); List<String> traitNames = repositoryService.getTraitNames(aGUID); Assert.assertEquals(traitNames.size(), 3); Assert.assertTrue(traitNames.contains(TestUtils.PII)); Assert.assertTrue(traitNames.contains(TestUtils.CLASSIFICATION)); Assert.assertTrue(traitNames.contains("P_I_I")); repositoryService.deleteTrait(aGUID, TestUtils.PII); // refresh trait names traitNames = repositoryService.getTraitNames(aGUID); Assert.assertEquals(traitNames.size(), 2); Assert.assertTrue(traitNames.contains(TestUtils.CLASSIFICATION)); Assert.assertFalse(traitNames.contains(TestUtils.PII)); // Verify modification timestamp was updated. GraphHelper.getInstance().getVertexForGUID(aGUID); Long modificationTimestampPostUpdate = GraphHelper.getSingleValuedProperty(AtlasVertex, Constants.MODIFICATION_TIMESTAMP_PROPERTY_KEY, Long.class); Assert.assertNotNull(modificationTimestampPostUpdate); Assert.assertTrue(modificationTimestampPostUpdate > modificationTimestampPreUpdate); } @Test(expectedExceptions = EntityNotFoundException.class) public void testDeleteTraitForNonExistentEntity() throws Exception { repositoryService.deleteTrait(UUID.randomUUID().toString(), TestUtils.PII); Assert.fail(); } @Test(expectedExceptions = TraitNotFoundException.class) public void testDeleteTraitForNonExistentTrait() throws Exception { final String aGUID = getGUID(); repositoryService.deleteTrait(aGUID, "PCI"); Assert.fail(); } @Test(dependsOnMethods = "testCreateEntity") public void testGetIdFromVertex() throws Exception { AtlasVertex tableVertex = getTableEntityVertex(); String guid = GraphHelper.getSingleValuedProperty(tableVertex, Constants.GUID_PROPERTY_KEY, String.class); if (guid == null) { Assert.fail(); } Id expected = new Id(guid, GraphHelper.getSingleValuedProperty(tableVertex, Constants.VERSION_PROPERTY_KEY, Integer.class), TestUtils.TABLE_TYPE); Assert.assertEquals(GraphHelper.getIdFromVertex(TestUtils.TABLE_TYPE, tableVertex), expected); } @Test(dependsOnMethods = "testCreateEntity") public void testGetTypeName() throws Exception { AtlasVertex tableVertex = getTableEntityVertex(); Assert.assertEquals(GraphHelper.getTypeName(tableVertex), TestUtils.TABLE_TYPE); } @Test(dependsOnMethods = "testCreateEntity") public void testSearchByDSLQuery() throws Exception { String dslQuery = "hive_database as PII"; System.out.println("Executing dslQuery = " + dslQuery); String jsonResults = discoveryService.searchByDSL(dslQuery, queryParams); Assert.assertNotNull(jsonResults); JSONObject results = new JSONObject(jsonResults); Assert.assertEquals(results.length(), 3); System.out.println("results = " + results); Object query = results.get("query"); Assert.assertNotNull(query); JSONObject dataType = results.getJSONObject("dataType"); Assert.assertNotNull(dataType); String typeName = dataType.getString("typeName"); Assert.assertNotNull(typeName); JSONArray rows = results.getJSONArray("rows"); Assert.assertNotNull(rows); Assert.assertTrue(rows.length() > 0); for (int index = 0; index < rows.length(); index++) { JSONObject row = rows.getJSONObject(index); String type = row.getString("$typeName$"); Assert.assertEquals(type, "hive_database"); String name = row.getString("name"); Assert.assertEquals(name, TestUtils.DATABASE_NAME); } } @Test(dependsOnMethods = "testSubmitEntity") public void testSearchByDSLWithInheritance() throws Exception { String dslQuery = "Person where name = 'Jane'"; System.out.println("Executing dslQuery = " + dslQuery); String jsonResults = discoveryService.searchByDSL(dslQuery, queryParams); Assert.assertNotNull(jsonResults); JSONObject results = new JSONObject(jsonResults); Assert.assertEquals(results.length(), 3); System.out.println("results = " + results); Object query = results.get("query"); Assert.assertNotNull(query); JSONObject dataType = results.getJSONObject("dataType"); Assert.assertNotNull(dataType); String typeName = dataType.getString("typeName"); Assert.assertEquals(typeName, "Person"); JSONArray rows = results.getJSONArray("rows"); Assert.assertEquals(rows.length(), 1); JSONObject row = rows.getJSONObject(0); Assert.assertEquals(row.getString("$typeName$"), "Manager"); Assert.assertEquals(row.getString("name"), "Jane"); } @Test(dependsOnMethods = "testCreateEntity") public void testBug37860() throws Exception { String dslQuery = "hive_table as t where name = 'bar' " + "database where name = 'foo' and description = 'foo database' select t"; TestUtils.dumpGraph(TestUtils.getGraph()); System.out.println("Executing dslQuery = " + dslQuery); String jsonResults = discoveryService.searchByDSL(dslQuery, queryParams); Assert.assertNotNull(jsonResults); JSONObject results = new JSONObject(jsonResults); Assert.assertEquals(results.length(), 3); System.out.println("results = " + results); Object query = results.get("query"); Assert.assertNotNull(query); JSONObject dataType = results.getJSONObject("dataType"); Assert.assertNotNull(dataType); JSONArray rows = results.getJSONArray("rows"); Assert.assertEquals(rows.length(), 1); } /** * Full text search requires GraphBackedSearchIndexer, and GraphBackedSearchIndexer can't be enabled in * GraphBackedDiscoveryServiceTest because of its test data. So, test for full text search is in * GraphBackedMetadataRepositoryTest:( */ @Test(dependsOnMethods = "testSubmitEntity") public void testFullTextSearch() throws Exception { //todo fix this //Weird: with lucene, the test passes without sleep //but with elasticsearch, doesn't work without sleep. why?? long sleepInterval = 1000; TestUtils.dumpGraph(TestUtils.getGraph()); //person in hr department whose name is john Thread.sleep(sleepInterval); String response = discoveryService.searchByFullText("john", queryParams); Assert.assertNotNull(response); JSONArray results = new JSONArray(response); Assert.assertEquals(results.length(), 1); JSONObject row = (JSONObject) results.get(0); Assert.assertEquals(row.get("typeName"), "Person"); //person in hr department who lives in santa clara response = discoveryService.searchByFullText("Jane AND santa AND clara", queryParams); Assert.assertNotNull(response); results = new JSONArray(response); Assert.assertEquals(results.length(), 1); row = (JSONObject) results.get(0); Assert.assertEquals(row.get("typeName"), "Manager"); //search for person in hr department whose name starts is john/jahn response = discoveryService.searchByFullText("hr AND (john OR jahn)", queryParams); Assert.assertNotNull(response); results = new JSONArray(response); Assert.assertEquals(results.length(), 1); row = (JSONObject) results.get(0); Assert.assertEquals(row.get("typeName"), "Person"); //verify limit and offset //higher limit should return all results results = new JSONArray(discoveryService.searchByFullText("Department", queryParams)); assertEquals(results.length(), 5); //smaller limit should return those many rows results = new JSONArray(discoveryService.searchByFullText("Department", new QueryParams(2, 0))); assertEquals(results.length(), 2); //offset should offset the results results = new JSONArray(discoveryService.searchByFullText("Department", new QueryParams(5, 2))); assertEquals(results.length(), 3); //higher offset shouldn't return any rows results = new JSONArray(discoveryService.searchByFullText("Department", new QueryParams(2, 6))); assertEquals(results.length(), 0); } private ITypedReferenceableInstance createHiveTableInstance(Referenceable databaseInstance) throws Exception { Referenceable tableInstance = new Referenceable(TestUtils.TABLE_TYPE, TestUtils.CLASSIFICATION); tableInstance.set("name", TestUtils.TABLE_NAME); tableInstance.set("description", "bar table"); tableInstance.set("type", "managed"); tableInstance.set("created", new Date(TestUtils.TEST_DATE_IN_LONG)); tableInstance.set("tableType", 1); // enum // super type tableInstance.set("namespace", "colo:cluster:hive:db:table"); tableInstance.set("cluster", "cluster-1"); tableInstance.set("colo", "colo-1"); // refer to an existing class tableInstance.set("database", databaseInstance); ArrayList<String> columnNames = new ArrayList<>(); columnNames.add("first_name"); columnNames.add("last_name"); tableInstance.set("columnNames", columnNames); Struct traitInstance = (Struct) tableInstance.getTrait(TestUtils.CLASSIFICATION); traitInstance.set("tag", "foundation_etl"); Struct serde1Instance = new Struct("serdeType"); serde1Instance.set("name", "serde1"); serde1Instance.set("serde", "serde1"); tableInstance.set("serde1", serde1Instance); Struct serde2Instance = new Struct("serdeType"); serde2Instance.set("name", "serde2"); serde2Instance.set("serde", "serde2"); tableInstance.set("serde2", serde2Instance); // HashMap<String, Referenceable> columnsMap = new HashMap<>(); ArrayList<Referenceable> columns = new ArrayList<>(); for (int index = 0; index < 5; index++) { Referenceable columnInstance = new Referenceable("column_type"); final String name = "column_" + index; columnInstance.set("name", name); columnInstance.set("type", "string"); columns.add(columnInstance); // columnsMap.put(name, columnInstance); } tableInstance.set("columns", columns); // tableInstance.set("columnsMap", columnsMap); // HashMap<String, Struct> partitionsMap = new HashMap<>(); ArrayList<Struct> partitions = new ArrayList<>(); for (int index = 0; index < 5; index++) { Struct partitionInstance = new Struct(TestUtils.PARTITION_STRUCT_TYPE); final String name = "partition_" + index; partitionInstance.set("name", name); partitions.add(partitionInstance); // partitionsMap.put(name, partitionInstance); } tableInstance.set("partitions", partitions); // tableInstance.set("partitionsMap", partitionsMap); HashMap<String, String> parametersMap = new HashMap<>(); parametersMap.put("foo", "bar"); parametersMap.put("bar", "baz"); parametersMap.put("some", "thing"); tableInstance.set("parametersMap", parametersMap); ClassType tableType = typeSystem.getDataType(ClassType.class, TestUtils.TABLE_TYPE); return tableType.convert(tableInstance, Multiplicity.REQUIRED); } private String randomUTF() { return RandomStringUtils.random(10); } private String randomString() { return RandomStringUtils.randomAlphanumeric(10); } @Test public void testUTFValues() throws Exception { Referenceable hrDept = new Referenceable("Department"); Referenceable john = new Referenceable("Person"); john.set("name", randomUTF()); john.set("department", hrDept); hrDept.set("name", randomUTF()); hrDept.set("employees", ImmutableList.of(john)); ClassType deptType = typeSystem.getDataType(ClassType.class, "Department"); ITypedReferenceableInstance hrDept2 = deptType.convert(hrDept, Multiplicity.REQUIRED); List<String> guids = repositoryService.createEntities(hrDept2).getCreatedEntities(); Assert.assertNotNull(guids); Assert.assertEquals(guids.size(), 2); Assert.assertNotNull(guids.get(0)); Assert.assertNotNull(guids.get(1)); } } <|start_filename|>typesystem/src/main/java/org/apache/atlas/typesystem/persistence/Id.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.typesystem.persistence; import com.google.common.collect.ImmutableList; import org.apache.atlas.AtlasException; import org.apache.atlas.utils.ParamChecker; import org.apache.atlas.typesystem.IStruct; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.types.FieldMapping; import org.apache.atlas.utils.SHA256Utils; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.Charset; import java.security.MessageDigest; import java.util.Date; import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; public class Id implements ITypedReferenceableInstance { public enum EntityState { ACTIVE, DELETED } public final String id; public final String typeName; public final int version; public EntityState state; private static AtomicLong s_nextId = new AtomicLong(System.nanoTime()); public final AtlasSystemAttributes systemAttributes; public Id(String id, int version, String typeName, String state) { id = ParamChecker.notEmpty(id, "id"); typeName = ParamChecker.notEmpty(typeName, "typeName"); state = ParamChecker.notEmptyIfNotNull(state, "state"); this.id = id; this.typeName = typeName; this.version = version; if (state == null) { this.state = EntityState.ACTIVE; } else { this.state = EntityState.valueOf(state.toUpperCase()); } this.systemAttributes = new AtlasSystemAttributes(); } public Id(String id, int version, String typeName) { this(id, version, typeName, null); } public Id(long id, int version, String typeName) { this("" + id, version, typeName); } public Id(long id, int version, String typeName, String state) { this("" + id, version, typeName, state); } public Id(String typeName) { this("" + Id.nextNegativeLong(), 0, typeName); } public boolean isUnassigned() { try { long l = Long.parseLong(id); return l < 0; } catch (NumberFormatException ne) { return false; } } public boolean isAssigned() { try { UUID.fromString(id); } catch (IllegalArgumentException e) { return false; } return true; } @Override public String toString() { return String.format("(type: %s, id: %s)", typeName, isUnassigned() ? "<unassigned>" : "" + id); } @Override public String toShortString() { return String.format("id[type=%s guid=%s state=%s]", typeName, id, state); } @Override public AtlasSystemAttributes getSystemAttributes(){ return systemAttributes; } public String getClassName() { return typeName; } public int getVersion() { return version; } public String _getId() { return id; } public EntityState getState() { return state; } public String getStateAsString() { return state == null ? null : state.name(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Id id1 = (Id) o; return version == id1.version && Objects.equals(id, id1.id) && Objects.equals(typeName, id1.typeName) && state == id1.state; } @Override public int hashCode() { return Objects.hash(id, typeName, version, state); } @Override public ImmutableList<String> getTraits() { return null; } @Override public Id getId() { return this; } @Override public IStruct getTrait(String typeName) { return null; } @Override public String getTypeName() { return typeName; } @Override public Object get(String attrName) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } @Override public void set(String attrName, Object val) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } @Override public FieldMapping fieldMapping() { return null; } @Override public Map<String, Object> getValuesMap() throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } public void setNull(String attrName) throws AtlasException { set(attrName, null); } public boolean getBoolean(String attrName) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } public byte getByte(String attrName) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } public short getShort(String attrName) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } public int getInt(String attrName) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } public long getLong(String attrName) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } public float getFloat(String attrName) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } public double getDouble(String attrName) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } public BigInteger getBigInt(String attrName) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } public BigDecimal getBigDecimal(String attrName) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } public Date getDate(String attrName) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } public String getString(String attrName) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } public void setBoolean(String attrName, boolean val) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } public void setByte(String attrName, byte val) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } public void setShort(String attrName, short val) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } public void setInt(String attrName, int val) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } public void setLong(String attrName, long val) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } public void setFloat(String attrName, float val) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } public void setDouble(String attrName, double val) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } public void setBigInt(String attrName, BigInteger val) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } public void setBigDecimal(String attrName, BigDecimal val) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } public void setDate(String attrName, Date val) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } public void setString(String attrName, String val) throws AtlasException { throw new AtlasException("Get/Set not supported on an Id object"); } public boolean isValueSet(String attrName) throws AtlasException { throw new AtlasException("Attributes not set on an Id object"); } @Override public String getSignatureHash(MessageDigest digester) throws AtlasException { digester.update(id.getBytes(Charset.forName("UTF-8"))); digester.update(typeName.getBytes(Charset.forName("UTF-8"))); byte[] digest = digester.digest(); return SHA256Utils.toString(digest); } private static long nextNegativeLong() { long ret = s_nextId.getAndDecrement(); if (ret > 0) { ret *= -1; } else if (ret == 0) { ret = Long.MIN_VALUE; } return ret; } } <|start_filename|>repository/src/main/java/org/apache/atlas/gremlin/GremlinExpressionFactory.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS_METHOD IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.gremlin; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.atlas.AtlasException; import org.apache.atlas.groovy.AbstractFunctionExpression; import org.apache.atlas.groovy.ArithmeticExpression; import org.apache.atlas.groovy.ArithmeticExpression.ArithmeticOperator; import org.apache.atlas.groovy.CastExpression; import org.apache.atlas.groovy.ClosureExpression; import org.apache.atlas.groovy.FieldExpression; import org.apache.atlas.groovy.FunctionCallExpression; import org.apache.atlas.groovy.GroovyExpression; import org.apache.atlas.groovy.IdentifierExpression; import org.apache.atlas.groovy.ListExpression; import org.apache.atlas.groovy.LiteralExpression; import org.apache.atlas.groovy.TraversalStepType; import org.apache.atlas.groovy.TypeCoersionExpression; import org.apache.atlas.groovy.VariableAssignmentExpression; import org.apache.atlas.query.GraphPersistenceStrategies; import org.apache.atlas.query.IntSequence; import org.apache.atlas.query.TypeUtils.FieldInfo; import org.apache.atlas.repository.graph.AtlasGraphProvider; import org.apache.atlas.repository.graphdb.AtlasEdgeDirection; import org.apache.atlas.repository.graphdb.GremlinVersion; import org.apache.atlas.typesystem.types.IDataType; import org.apache.atlas.typesystem.types.TypeSystem; import org.apache.atlas.typesystem.types.cache.TypeCache.TYPE_FILTER; import org.apache.atlas.util.AtlasRepositoryConfiguration; import com.google.common.collect.ImmutableList; /** * Factory to generate Groovy expressions representing Gremlin syntax that that * are independent of the specific version of Gremlin that is being used. * */ public abstract class GremlinExpressionFactory { private static final String G_VARIABLE = "g"; private static final String IT_VARIABLE = "it"; protected static final String SET_CLASS = "Set"; private static final String OBJECT_FIELD = "object"; protected static final String V_METHOD = "V"; protected static final String FILTER_METHOD = "filter"; private static final String PATH_METHOD = "path"; private static final String AS_METHOD = "as"; private static final String IN_OPERATOR = "in"; protected static final String HAS_METHOD = "has"; protected static final String TO_LOWER_CASE_METHOD = "toLowerCase"; protected static final String SELECT_METHOD = "select"; protected static final String ORDER_METHOD = "order"; protected static final String FILL_METHOD = "fill"; protected static final String MATCHES = "matches"; public static final GremlinExpressionFactory INSTANCE = AtlasGraphProvider.getGraphInstance() .getSupportedGremlinVersion() == GremlinVersion.THREE ? new Gremlin3ExpressionFactory() : new Gremlin2ExpressionFactory(); /** * Returns the unqualified name of the class used in this version of gremlin to * represent Gremlin queries as they are being generated. * @return */ public abstract String getTraversalExpressionClass(); /** * Gets the expression to use as the parent when translating the loop * expression in a loop * * @param inputQry * the * @return */ public abstract GroovyExpression getLoopExpressionParent(GroovyExpression inputQry); /** * Generates a loop expression. * * @param parent * the parent of the loop expression * @param emitExpr * Expression with the value that should be emitted by the loop * expression. * @param loopExpr * the query expression that is being executed repeatedly * executed in a loop * @param alias * The alias of the expression being looped over * @param times * the number of times to repeat, or null if a times condition * should not be used. * @return */ public abstract GroovyExpression generateLoopExpression(GroovyExpression parent, GraphPersistenceStrategies s, IDataType dataType, GroovyExpression loopExpr, String alias, Integer times); /** * Generates a logical (and/or) expression with the given operands. * @param parent * @param operator * @param operands * @return */ public abstract GroovyExpression generateLogicalExpression(GroovyExpression parent, String operator, List<GroovyExpression> operands); /** * Generates a back reference expression that refers to the given alias. * * @param parent * @param inSelect * @param alias * @return */ public abstract GroovyExpression generateBackReferenceExpression(GroovyExpression parent, boolean inSelect, String alias); /** * Generates a select expression * * @param parent * @param sourceNames * the names of the select fields * @param srcExprs * the corresponding values to return * @return */ public abstract GroovyExpression generateSelectExpression(GroovyExpression parent, List<LiteralExpression> sourceNames, List<GroovyExpression> srcExprs); /** * Generates a an expression that gets the value of the given property from the * vertex presented by the parent. * * @param parent * @param fInfo * @param propertyName * @param inSelect * @return */ public abstract GroovyExpression generateFieldExpression(GroovyExpression parent, FieldInfo fInfo, String propertyName, boolean inSelect); /** * Generates a has expression that checks whether the vertices match a specific condition * * @param s * @param parent the object that we should call apply the "has" condition to. * @param propertyName the name of the property whose value we are comparing * @param symbol comparsion operator symbol ('=','<', etc.) * @param requiredValue the value to compare against * @param fInfo info about the field whose value we are checking * @return * @throws AtlasException */ public abstract GroovyExpression generateHasExpression(GraphPersistenceStrategies s, GroovyExpression parent, String propertyName, String symbol, GroovyExpression requiredValue, FieldInfo fInfo) throws AtlasException; public abstract GroovyExpression generateLikeExpressionUsingFilter(GroovyExpression parent, String propertyName, GroovyExpression propertyValue) throws AtlasException; /** * Generates a range expression * * @param parent * @param startIndex * @param endIndex * @return */ public abstract GroovyExpression generateRangeExpression(GroovyExpression parent, int startIndex, int endIndex); /** * Determines if the specified expression is a range method call. * * @param expr * @return */ public abstract boolean isRangeExpression(GroovyExpression expr); /** * Set the start index and end index of a range expression * * @param expr * @param startIndex * @param endIndex */ public abstract void setRangeParameters(GroovyExpression expr, int startIndex, int endIndex); /** * If the specified function expression is a range expression, returns the start and end index parameters * otherwise returns null. * * @param expr * @return int array with two elements - element 0 is start index, element 1 is end index */ public abstract int[] getRangeParameters(AbstractFunctionExpression expr); /** * Generates an order by expression * * @param parent * @param translatedOrderBy * @param isAscending * @return */ public abstract GroovyExpression generateOrderByExpression(GroovyExpression parent, List<GroovyExpression> translatedOrderBy, boolean isAscending); /** * Determines if specified expression is an order method call * * @param expr * @return */ public boolean isOrderExpression(GroovyExpression expr) { if (expr instanceof FunctionCallExpression) { FunctionCallExpression functionCallExpression = (FunctionCallExpression) expr; if (functionCallExpression.getFunctionName().equals(ORDER_METHOD)) { return true; } } return false; } /** * Returns the Groovy expressions that should be used as the parents when * translating an order by expression. This is needed because Gremlin 2 and * 3 handle order by expressions very differently. * */ public abstract List<GroovyExpression> getOrderFieldParents(); /** * Returns the expression that represents an anonymous graph traversal. * * @return */ public abstract GroovyExpression getAnonymousTraversalExpression(); public boolean isLeafAnonymousTraversalExpression(GroovyExpression expr) { if(!(expr instanceof FunctionCallExpression)) { return false; } FunctionCallExpression functionCallExpr = (FunctionCallExpression)expr; if(functionCallExpr.getCaller() != null) { return false; } return functionCallExpr.getFunctionName().equals("_") & functionCallExpr.getArguments().size() == 0; } /** * Returns an expression representing * * @return */ public abstract GroovyExpression getFieldInSelect(); /** * Generates the expression the serves as the root of the Gremlin query. * @param varExpr variable containing the vertices to traverse * @return */ protected abstract GroovyExpression initialExpression(GroovyExpression varExpr, GraphPersistenceStrategies s); /** * Generates an expression that tests whether the vertex represented by the 'toTest' * expression represents an instance of the specified type, checking both the type * and super type names. * * @param s * @param typeName * @param itRef * @return */ protected abstract GroovyExpression typeTestExpression(GraphPersistenceStrategies s, String typeName, GroovyExpression vertexExpr); /** /** * Generates a sequence of groovy expressions that filter the vertices to only * those that match the specified type. If GraphPersistenceStrategies.collectTypeInstancesIntoVar() * is set and the gremlin optimizer is disabled, the vertices are put into a variable whose name is generated * from the specified IntSequence. The last item in the result will be a graph traversal restricted to only * the matching vertices. */ public List<GroovyExpression> generateTypeTestExpression(GraphPersistenceStrategies s, GroovyExpression parent, String typeName, IntSequence intSeq) throws AtlasException { if(AtlasRepositoryConfiguration.isGremlinOptimizerEnabled()) { GroovyExpression superTypeAttributeNameExpr = new LiteralExpression(s.superTypeAttributeName()); GroovyExpression typeNameExpr = new LiteralExpression(typeName); GroovyExpression superTypeMatchesExpr = new FunctionCallExpression(TraversalStepType.FILTER, HAS_METHOD, superTypeAttributeNameExpr, typeNameExpr); GroovyExpression typeAttributeNameExpr = new LiteralExpression(s.typeAttributeName()); GroovyExpression typeMatchesExpr = new FunctionCallExpression(TraversalStepType.FILTER, HAS_METHOD, typeAttributeNameExpr, typeNameExpr); GroovyExpression result = new FunctionCallExpression(TraversalStepType.FILTER, parent, "or", typeMatchesExpr, superTypeMatchesExpr); return Collections.singletonList(result); } else { if (s.filterBySubTypes()) { return typeTestExpressionUsingInFilter(s, parent, typeName); } else if (s.collectTypeInstancesIntoVar()) { return typeTestExpressionMultiStep(s, typeName, intSeq); } else { return typeTestExpressionUsingFilter(s, parent, typeName); } } } private List<GroovyExpression> typeTestExpressionUsingInFilter(GraphPersistenceStrategies s, GroovyExpression parent, final String typeName) throws AtlasException { List<GroovyExpression> typeNames = new ArrayList<>(); typeNames.add(new LiteralExpression(typeName)); Map<TYPE_FILTER, String> filters = new HashMap<TYPE_FILTER, String>() {{ put(TYPE_FILTER.SUPERTYPE, typeName); }}; ImmutableList<String> subTypes = TypeSystem.getInstance().getTypeNames(filters); if (!subTypes.isEmpty()) { for (String subType : subTypes) { typeNames.add(new LiteralExpression(subType)); } } GroovyExpression inFilterExpr = generateHasExpression(s, parent, s.typeAttributeName(), IN_OPERATOR, new ListExpression(typeNames), null); return Collections.singletonList(inFilterExpr); } private List<GroovyExpression> typeTestExpressionMultiStep(GraphPersistenceStrategies s, String typeName, IntSequence intSeq) { String varName = "_var_" + intSeq.next(); GroovyExpression varExpr = new IdentifierExpression(varName); List<GroovyExpression> result = new ArrayList<>(); result.add(newSetVar(varName)); result.add(fillVarWithTypeInstances(s, typeName, varName)); result.add(fillVarWithSubTypeInstances(s, typeName, varName)); result.add(initialExpression(varExpr, s)); return result; } private GroovyExpression newSetVar(String varName) { GroovyExpression castExpr = new TypeCoersionExpression(new ListExpression(), SET_CLASS); return new VariableAssignmentExpression(varName, castExpr); } private GroovyExpression fillVarWithTypeInstances(GraphPersistenceStrategies s, String typeName, String fillVar) { GroovyExpression graphExpr = getAllVerticesExpr(); GroovyExpression typeAttributeNameExpr = new LiteralExpression(s.typeAttributeName()); GroovyExpression typeNameExpr = new LiteralExpression(typeName); GroovyExpression hasExpr = new FunctionCallExpression(graphExpr, HAS_METHOD, typeAttributeNameExpr, typeNameExpr); GroovyExpression fillExpr = new FunctionCallExpression(hasExpr, FILL_METHOD, new IdentifierExpression(fillVar)); return fillExpr; } private GroovyExpression fillVarWithSubTypeInstances(GraphPersistenceStrategies s, String typeName, String fillVar) { GroovyExpression graphExpr = getAllVerticesExpr(); GroovyExpression superTypeAttributeNameExpr = new LiteralExpression(s.superTypeAttributeName()); GroovyExpression typeNameExpr = new LiteralExpression(typeName); GroovyExpression hasExpr = new FunctionCallExpression(graphExpr, HAS_METHOD, superTypeAttributeNameExpr, typeNameExpr); GroovyExpression fillExpr = new FunctionCallExpression(hasExpr, FILL_METHOD, new IdentifierExpression(fillVar)); return fillExpr; } private List<GroovyExpression> typeTestExpressionUsingFilter(GraphPersistenceStrategies s, GroovyExpression parent, String typeName) { GroovyExpression itExpr = getItVariable(); GroovyExpression typeTestExpr = typeTestExpression(s, typeName, itExpr); GroovyExpression closureExpr = new ClosureExpression(typeTestExpr); GroovyExpression filterExpr = new FunctionCallExpression(parent, FILTER_METHOD, closureExpr); return Collections.singletonList(filterExpr); } /** * Generates an expression which checks whether the vertices in the query have * a field with the given name. * * @param parent * @param fieldName * @return */ public GroovyExpression generateUnaryHasExpression(GroovyExpression parent, String fieldName) { return new FunctionCallExpression(TraversalStepType.FILTER, parent, HAS_METHOD, new LiteralExpression(fieldName)); } /** * Generates a path expression * * @param parent * @return */ public GroovyExpression generatePathExpression(GroovyExpression parent) { return new FunctionCallExpression(TraversalStepType.MAP_TO_VALUE, parent, PATH_METHOD); } /** * Generates the emit expression used in loop expressions. * @param s * @param dataType * @return */ protected GroovyExpression generateLoopEmitExpression(GraphPersistenceStrategies s, IDataType dataType) { return typeTestExpression(s, dataType.getName(), getCurrentObjectExpression()); } /** * Generates an alias expression * * @param parent * @param alias * @return */ public GroovyExpression generateAliasExpression(GroovyExpression parent, String alias) { return new FunctionCallExpression(TraversalStepType.SIDE_EFFECT, parent, AS_METHOD, new LiteralExpression(alias)); } /** * Generates an expression that gets the vertices adjacent to the vertex in 'parent' * in the specified direction. * * @param parent * @param dir * @return */ public GroovyExpression generateAdjacentVerticesExpression(GroovyExpression parent, AtlasEdgeDirection dir) { return new FunctionCallExpression(TraversalStepType.FLAT_MAP_TO_ELEMENTS, parent, getGremlinFunctionName(dir)); } private String getGremlinFunctionName(AtlasEdgeDirection dir) { switch(dir) { case IN: return "in"; case OUT: return "out"; case BOTH: return "both"; default: throw new RuntimeException("Unknown Atlas Edge Direction: " + dir); } } /** * Generates an expression that gets the vertices adjacent to the vertex in 'parent' * in the specified direction, following only edges with the given label. * * @param parent * @param dir * @return */ public GroovyExpression generateAdjacentVerticesExpression(GroovyExpression parent, AtlasEdgeDirection dir, String label) { return new FunctionCallExpression(TraversalStepType.FLAT_MAP_TO_ELEMENTS, parent, getGremlinFunctionName(dir), new LiteralExpression(label)); } /** * Generates an arithmetic expression, e.g. a + b * */ public GroovyExpression generateArithmeticExpression(GroovyExpression left, String operator, GroovyExpression right) throws AtlasException { ArithmeticOperator op = ArithmeticOperator.lookup(operator); return new ArithmeticExpression(left, op, right); } public abstract GroovyExpression generateGroupByExpression(GroovyExpression parent, GroovyExpression groupByExpression, GroovyExpression aggregationFunction); protected GroovyExpression getItVariable() { return new IdentifierExpression(IT_VARIABLE); } protected GroovyExpression getAllVerticesExpr() { GroovyExpression gExpr = getGraphExpression(); return new FunctionCallExpression(TraversalStepType.START, gExpr, V_METHOD); } protected IdentifierExpression getGraphExpression() { return new IdentifierExpression(TraversalStepType.SOURCE, G_VARIABLE); } protected GroovyExpression getCurrentObjectExpression() { return new FieldExpression(getItVariable(), OBJECT_FIELD); } //assumes cast already performed public GroovyExpression generateCountExpression(GroovyExpression itExpr) { GroovyExpression collectionExpr = new CastExpression(itExpr,"Collection"); return new FunctionCallExpression(collectionExpr, "size"); } public GroovyExpression generateMinExpression(GroovyExpression itExpr, GroovyExpression mapFunction) { return getAggregrationExpression(itExpr, mapFunction, "min"); } public GroovyExpression generateMaxExpression(GroovyExpression itExpr, GroovyExpression mapFunction) { return getAggregrationExpression(itExpr, mapFunction, "max"); } public GroovyExpression generateSumExpression(GroovyExpression itExpr, GroovyExpression mapFunction) { return getAggregrationExpression(itExpr, mapFunction, "sum"); } private GroovyExpression getAggregrationExpression(GroovyExpression itExpr, GroovyExpression mapFunction, String functionName) { GroovyExpression collectionExpr = new CastExpression(itExpr,"Collection"); ClosureExpression collectFunction = new ClosureExpression(mapFunction); GroovyExpression transformedList = new FunctionCallExpression(collectionExpr, "collect", collectFunction); return new FunctionCallExpression(transformedList, functionName); } public GroovyExpression getClosureArgumentValue() { return getItVariable(); } /** * Specifies the parent to use when translating the select list in * a group by statement. * * @return */ public abstract GroovyExpression getGroupBySelectFieldParent(); public GroovyExpression generateFillExpression(GroovyExpression parent, GroovyExpression variable) { return new FunctionCallExpression(TraversalStepType.END,parent , "fill", variable); } /** * Generates an anonymous graph traversal initialized with the specified value. In Gremlin 3, we need * to use a different syntax for this when the object is a map, so that information needs to be provided * to this method so that the correct syntax is used. * * @param isMap true if the value contains Map instances, false if it contains Vertex instances * @param valueCollection the source objects to start the traversal from. */ public abstract GroovyExpression generateSeededTraversalExpresssion(boolean isMap, GroovyExpression valueCollection); /** * Returns the current value of the traverser. This is used when generating closure expressions that * need to operate on the current value in the graph graversal. * * @param traverser * @return */ public abstract GroovyExpression getCurrentTraverserObject(GroovyExpression traverser); /** * Generates an expression that transforms the current value of the traverser by * applying the function specified * * @param parent * @param closureExpression * @return */ public abstract GroovyExpression generateMapExpression(GroovyExpression parent, ClosureExpression closureExpression); /** * Returns whether a select statement generates a map (or Gremlin 2 "Row") when it contains the specified * number of aliases. * */ public abstract boolean isSelectGeneratesMap(int aliasCount); /** * Generates an expression to get the value of the value from the row map * generated by select() with the specified key. * */ public abstract GroovyExpression generateGetSelectedValueExpression(LiteralExpression key, GroovyExpression rowMapExpr); public GroovyExpression removeExtraMapFromPathInResult(GroovyExpression parent) { GroovyExpression listItem = getItVariable(); GroovyExpression tailExpr = new FunctionCallExpression(listItem, "tail"); return new FunctionCallExpression(parent, "collect", new ClosureExpression(tailExpr)); } /** * Generates a toList expression to execute the gremlin query and * store the result in a new list. * * @param expr * @return */ public GroovyExpression generateToListExpression(GroovyExpression expr) { return new FunctionCallExpression(TraversalStepType.END, expr, "toList"); } /** * Finds aliases that absolutely must be brought along with this expression into * the output expression and cannot just be recreated there. For example, in the * Gremlin 2 loop expression, the loop semantics break of the alias is simply recreated * in the output expression. * @param expr * @return */ public abstract List<String> getAliasesRequiredByExpression(GroovyExpression expr); /** * Checks if the given expression is an alias expression, and if so * returns the alias from the expression. Otherwise, null is * returned. */ public String getAliasNameIfRelevant(GroovyExpression expr) { if(!(expr instanceof FunctionCallExpression)) { return null; } FunctionCallExpression fc = (FunctionCallExpression)expr; if(! fc.getFunctionName().equals(AS_METHOD)) { return null; } LiteralExpression aliasName = (LiteralExpression)fc.getArguments().get(0); return aliasName.getValue().toString(); } public abstract boolean isRepeatExpression(GroovyExpression expr); } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/store/graph/v1/EntityGraphRetriever.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.store.graph.v1; import com.sun.istack.Nullable; import org.apache.atlas.AtlasClient; import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.instance.AtlasClassification; import org.apache.atlas.model.instance.AtlasEntity; import org.apache.atlas.model.instance.AtlasEntity.AtlasEntitiesWithExtInfo; import org.apache.atlas.model.instance.AtlasEntity.AtlasEntityExtInfo; import org.apache.atlas.model.instance.AtlasEntity.AtlasEntityWithExtInfo; import org.apache.atlas.model.instance.AtlasEntityHeader; import org.apache.atlas.model.instance.AtlasObjectId; import org.apache.atlas.model.instance.AtlasStruct; import org.apache.atlas.model.typedef.AtlasRelationshipDef; import org.apache.atlas.model.typedef.AtlasRelationshipEndDef; import org.apache.atlas.model.typedef.AtlasStructDef.AtlasAttributeDef; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.graph.GraphHelper; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasEdgeDirection; import org.apache.atlas.repository.graphdb.AtlasElement; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.type.*; import org.apache.atlas.type.AtlasStructType.AtlasAttribute; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.ATLAS_TYPE_BIGDECIMAL; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.ATLAS_TYPE_BIGINTEGER; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.ATLAS_TYPE_BOOLEAN; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.ATLAS_TYPE_BYTE; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.ATLAS_TYPE_DATE; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.ATLAS_TYPE_DOUBLE; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.ATLAS_TYPE_FLOAT; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.ATLAS_TYPE_INT; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.ATLAS_TYPE_LONG; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.ATLAS_TYPE_SHORT; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.ATLAS_TYPE_STRING; import static org.apache.atlas.repository.graph.GraphHelper.EDGE_LABEL_PREFIX; import static org.apache.atlas.repository.store.graph.v1.AtlasGraphUtilsV1.getIdFromVertex; import static org.apache.atlas.type.AtlasStructType.AtlasAttribute.AtlasRelationshipEdgeDirection; public final class EntityGraphRetriever { private static final Logger LOG = LoggerFactory.getLogger(EntityGraphRetriever.class); private static final GraphHelper graphHelper = GraphHelper.getInstance(); private final AtlasTypeRegistry typeRegistry; public EntityGraphRetriever(AtlasTypeRegistry typeRegistry) { this.typeRegistry = typeRegistry; } public AtlasEntity toAtlasEntity(String guid) throws AtlasBaseException { return toAtlasEntity(getEntityVertex(guid)); } public AtlasEntity toAtlasEntity(AtlasObjectId objId) throws AtlasBaseException { return toAtlasEntity(getEntityVertex(objId)); } public AtlasEntity toAtlasEntity(AtlasVertex entityVertex) throws AtlasBaseException { return mapVertexToAtlasEntity(entityVertex, null); } public AtlasEntityWithExtInfo toAtlasEntityWithExtInfo(String guid) throws AtlasBaseException { return toAtlasEntityWithExtInfo(getEntityVertex(guid)); } public AtlasEntityWithExtInfo toAtlasEntityWithExtInfo(AtlasObjectId objId) throws AtlasBaseException { return toAtlasEntityWithExtInfo(getEntityVertex(objId)); } public AtlasEntityWithExtInfo toAtlasEntityWithExtInfo(AtlasVertex entityVertex) throws AtlasBaseException { AtlasEntityExtInfo entityExtInfo = new AtlasEntityExtInfo(); AtlasEntity entity = mapVertexToAtlasEntity(entityVertex, entityExtInfo); AtlasEntityWithExtInfo ret = new AtlasEntityWithExtInfo(entity, entityExtInfo); ret.compact(); return ret; } public AtlasEntitiesWithExtInfo toAtlasEntitiesWithExtInfo(List<String> guids) throws AtlasBaseException { AtlasEntitiesWithExtInfo ret = new AtlasEntitiesWithExtInfo(); for (String guid : guids) { AtlasVertex vertex = getEntityVertex(guid); AtlasEntity entity = mapVertexToAtlasEntity(vertex, ret); ret.addEntity(entity); } ret.compact(); return ret; } public AtlasEntityHeader toAtlasEntityHeader(String guid) throws AtlasBaseException { return toAtlasEntityHeader(getEntityVertex(guid)); } public AtlasEntityHeader toAtlasEntityHeader(AtlasVertex entityVertex) throws AtlasBaseException { return toAtlasEntityHeader(entityVertex, Collections.<String>emptySet()); } public AtlasEntityHeader toAtlasEntityHeader(AtlasVertex atlasVertex, Set<String> attributes) throws AtlasBaseException { return atlasVertex != null ? mapVertexToAtlasEntityHeader(atlasVertex, attributes) : null; } private AtlasVertex getEntityVertex(String guid) throws AtlasBaseException { AtlasVertex ret = AtlasGraphUtilsV1.findByGuid(guid); if (ret == null) { throw new AtlasBaseException(AtlasErrorCode.INSTANCE_GUID_NOT_FOUND, guid); } return ret; } private AtlasVertex getEntityVertex(AtlasObjectId objId) throws AtlasBaseException { AtlasVertex ret = null; if (! AtlasTypeUtil.isValid(objId)) { throw new AtlasBaseException(AtlasErrorCode.INVALID_OBJECT_ID, objId.toString()); } if (AtlasTypeUtil.isAssignedGuid(objId)) { ret = AtlasGraphUtilsV1.findByGuid(objId.getGuid()); } else { AtlasEntityType entityType = typeRegistry.getEntityTypeByName(objId.getTypeName()); Map<String, Object> uniqAttributes = objId.getUniqueAttributes(); ret = AtlasGraphUtilsV1.getVertexByUniqueAttributes(entityType, uniqAttributes); } if (ret == null) { throw new AtlasBaseException(AtlasErrorCode.INSTANCE_GUID_NOT_FOUND, objId.toString()); } return ret; } private AtlasEntity mapVertexToAtlasEntity(AtlasVertex entityVertex, AtlasEntityExtInfo entityExtInfo) throws AtlasBaseException { String guid = GraphHelper.getGuid(entityVertex); AtlasEntity entity = entityExtInfo != null ? entityExtInfo.getEntity(guid) : null; if (entity == null) { if (LOG.isDebugEnabled()) { LOG.debug("Mapping graph vertex to atlas entity for guid {}", guid); } entity = new AtlasEntity(); if (entityExtInfo != null) { entityExtInfo.addReferredEntity(guid, entity); } mapSystemAttributes(entityVertex, entity); mapAttributes(entityVertex, entity, entityExtInfo); mapRelationshipAttributes(entityVertex, entity); mapClassifications(entityVertex, entity, entityExtInfo); } return entity; } private AtlasEntityHeader mapVertexToAtlasEntityHeader(AtlasVertex entityVertex) throws AtlasBaseException { return mapVertexToAtlasEntityHeader(entityVertex, Collections.<String>emptySet()); } private AtlasEntityHeader mapVertexToAtlasEntityHeader(AtlasVertex entityVertex, Set<String> attributes) throws AtlasBaseException { AtlasEntityHeader ret = new AtlasEntityHeader(); String typeName = entityVertex.getProperty(Constants.TYPE_NAME_PROPERTY_KEY, String.class); String guid = entityVertex.getProperty(Constants.GUID_PROPERTY_KEY, String.class); ret.setTypeName(typeName); ret.setGuid(guid); ret.setStatus(GraphHelper.getStatus(entityVertex)); ret.setClassificationNames(GraphHelper.getTraitNames(entityVertex)); AtlasEntityType entityType = typeRegistry.getEntityTypeByName(typeName); if (entityType != null) { for (AtlasAttribute uniqueAttribute : entityType.getUniqAttributes().values()) { Object attrValue = getVertexAttribute(entityVertex, uniqueAttribute); if (attrValue != null) { ret.setAttribute(uniqueAttribute.getName(), attrValue); } } Object name = getVertexAttribute(entityVertex, entityType.getAttribute(AtlasClient.NAME)); Object description = getVertexAttribute(entityVertex, entityType.getAttribute(AtlasClient.DESCRIPTION)); Object owner = getVertexAttribute(entityVertex, entityType.getAttribute(AtlasClient.OWNER)); Object displayText = name != null ? name : ret.getAttribute(AtlasClient.QUALIFIED_NAME); ret.setAttribute(AtlasClient.NAME, name); ret.setAttribute(AtlasClient.DESCRIPTION, description); ret.setAttribute(AtlasClient.OWNER, owner); if (displayText != null) { ret.setDisplayText(displayText.toString()); } if (CollectionUtils.isNotEmpty(attributes)) { for (String attrName : attributes) { String nonQualifiedAttrName = toNonQualifiedName(attrName); if (ret.hasAttribute(attrName)) { continue; } Object attrValue = getVertexAttribute(entityVertex, entityType.getAttribute(nonQualifiedAttrName)); if (attrValue != null) { ret.setAttribute(nonQualifiedAttrName, attrValue); } } } } return ret; } private String toNonQualifiedName(String attrName) { String ret; if (attrName.contains(".")) { String[] attributeParts = attrName.split("\\."); ret = attributeParts[attributeParts.length - 1]; } else { ret = attrName; } return ret; } private AtlasEntity mapSystemAttributes(AtlasVertex entityVertex, AtlasEntity entity) { if (LOG.isDebugEnabled()) { LOG.debug("Mapping system attributes for type {}", entity.getTypeName()); } entity.setGuid(GraphHelper.getGuid(entityVertex)); entity.setTypeName(GraphHelper.getTypeName(entityVertex)); entity.setStatus(GraphHelper.getStatus(entityVertex)); entity.setVersion(GraphHelper.getVersion(entityVertex).longValue()); entity.setCreatedBy(GraphHelper.getCreatedByAsString(entityVertex)); entity.setUpdatedBy(GraphHelper.getModifiedByAsString(entityVertex)); entity.setCreateTime(new Date(GraphHelper.getCreatedTime(entityVertex))); entity.setUpdateTime(new Date(GraphHelper.getModifiedTime(entityVertex))); return entity; } private void mapAttributes(AtlasVertex entityVertex, AtlasStruct struct, AtlasEntityExtInfo entityExtInfo) throws AtlasBaseException { AtlasType objType = typeRegistry.getType(struct.getTypeName()); if (!(objType instanceof AtlasStructType)) { throw new AtlasBaseException(AtlasErrorCode.TYPE_NAME_INVALID, struct.getTypeName()); } AtlasStructType structType = (AtlasStructType) objType; for (AtlasAttribute attribute : structType.getAllAttributes().values()) { Object attrValue = mapVertexToAttribute(entityVertex, attribute, entityExtInfo); struct.setAttribute(attribute.getName(), attrValue); } } public List<AtlasClassification> getClassifications(String guid) throws AtlasBaseException { AtlasVertex instanceVertex = AtlasGraphUtilsV1.findByGuid(guid); if (instanceVertex == null) { throw new AtlasBaseException(AtlasErrorCode.INSTANCE_GUID_NOT_FOUND, guid); } return getClassifications(instanceVertex, null); } public AtlasClassification getClassification(String guid, String classificationName) throws AtlasBaseException { AtlasVertex instanceVertex = AtlasGraphUtilsV1.findByGuid(guid); if (instanceVertex == null) { throw new AtlasBaseException(AtlasErrorCode.INSTANCE_GUID_NOT_FOUND, guid); } List<AtlasClassification> classifications = getClassifications(instanceVertex, classificationName); if(CollectionUtils.isEmpty(classifications)) { throw new AtlasBaseException(AtlasErrorCode.CLASSIFICATION_NOT_FOUND, classificationName); } return classifications.get(0); } private List<AtlasClassification> getClassifications(AtlasVertex instanceVertex, @Nullable String classificationNameFilter) throws AtlasBaseException { List<AtlasClassification> classifications = new ArrayList<>(); List<String> classificationNames = GraphHelper.getTraitNames(instanceVertex); if (CollectionUtils.isNotEmpty(classificationNames)) { for (String classificationName : classificationNames) { AtlasClassification classification; if (StringUtils.isNotEmpty(classificationNameFilter)) { if (classificationName.equals(classificationNameFilter)) { classification = getClassification(instanceVertex, classificationName); classifications.add(classification); return classifications; } } else { classification = getClassification(instanceVertex, classificationName); classifications.add(classification); } } if (StringUtils.isNotEmpty(classificationNameFilter)) { //Should not reach here if classification present throw new AtlasBaseException(AtlasErrorCode.CLASSIFICATION_NOT_FOUND, classificationNameFilter); } } return classifications; } private AtlasClassification getClassification(AtlasVertex instanceVertex, String classificationName) throws AtlasBaseException { AtlasClassification ret = null; if (LOG.isDebugEnabled()) { LOG.debug("mapping classification {} to atlas entity", classificationName); } Iterable<AtlasEdge> edges = instanceVertex.getEdges(AtlasEdgeDirection.OUT, classificationName); AtlasEdge edge = (edges != null && edges.iterator().hasNext()) ? edges.iterator().next() : null; if (edge != null) { ret = new AtlasClassification(classificationName); mapAttributes(edge.getInVertex(), ret, null); } return ret; } private void mapClassifications(AtlasVertex entityVertex, AtlasEntity entity, AtlasEntityExtInfo entityExtInfo) throws AtlasBaseException { final List<AtlasClassification> classifications = getClassifications(entityVertex, null); entity.setClassifications(classifications); } private Object mapVertexToAttribute(AtlasVertex entityVertex, AtlasAttribute attribute, AtlasEntityExtInfo entityExtInfo) throws AtlasBaseException { Object ret = null; AtlasType attrType = attribute.getAttributeType(); String vertexPropertyName = attribute.getQualifiedName(); String edgeLabel = EDGE_LABEL_PREFIX + vertexPropertyName; boolean isOwnedAttribute = attribute.isOwnedRef(); AtlasRelationshipEdgeDirection edgeDirection = attribute.getRelationshipEdgeDirection(); if (LOG.isDebugEnabled()) { LOG.debug("Mapping vertex {} to atlas entity {}.{}", entityVertex, attribute.getDefinedInDef().getName(), attribute.getName()); } switch (attrType.getTypeCategory()) { case PRIMITIVE: ret = mapVertexToPrimitive(entityVertex, vertexPropertyName, attribute.getAttributeDef()); break; case ENUM: ret = GraphHelper.getProperty(entityVertex, vertexPropertyName); break; case STRUCT: ret = mapVertexToStruct(entityVertex, edgeLabel, null, entityExtInfo); break; case OBJECT_ID_TYPE: ret = mapVertexToObjectId(entityVertex, edgeLabel, null, entityExtInfo, isOwnedAttribute, edgeDirection); break; case ARRAY: ret = mapVertexToArray(entityVertex, (AtlasArrayType) attrType, vertexPropertyName, entityExtInfo, isOwnedAttribute, edgeDirection); break; case MAP: ret = mapVertexToMap(entityVertex, (AtlasMapType) attrType, vertexPropertyName, entityExtInfo, isOwnedAttribute, edgeDirection); break; case CLASSIFICATION: // do nothing break; } return ret; } private Map<String, Object> mapVertexToMap(AtlasVertex entityVertex, AtlasMapType atlasMapType, final String propertyName, AtlasEntityExtInfo entityExtInfo, boolean isOwnedAttribute, AtlasRelationshipEdgeDirection edgeDirection) throws AtlasBaseException { List<String> mapKeys = GraphHelper.getListProperty(entityVertex, propertyName); if (CollectionUtils.isEmpty(mapKeys)) { return null; } if (LOG.isDebugEnabled()) { LOG.debug("Mapping map attribute {} for vertex {}", atlasMapType.getTypeName(), entityVertex); } Map<String, Object> ret = new HashMap<>(mapKeys.size()); AtlasType mapValueType = atlasMapType.getValueType(); for (String mapKey : mapKeys) { final String keyPropertyName = propertyName + "." + mapKey; final String edgeLabel = EDGE_LABEL_PREFIX + keyPropertyName; final Object keyValue = GraphHelper.getMapValueProperty(mapValueType, entityVertex, keyPropertyName); Object mapValue = mapVertexToCollectionEntry(entityVertex, mapValueType, keyValue, edgeLabel, entityExtInfo, isOwnedAttribute, edgeDirection); if (mapValue != null) { ret.put(mapKey, mapValue); } } return ret; } private List<Object> mapVertexToArray(AtlasVertex entityVertex, AtlasArrayType arrayType, String propertyName, AtlasEntityExtInfo entityExtInfo, boolean isOwnedAttribute, AtlasRelationshipEdgeDirection edgeDirection) throws AtlasBaseException { AtlasType arrayElementType = arrayType.getElementType(); List<Object> arrayElements = GraphHelper.getArrayElementsProperty(arrayElementType, entityVertex, propertyName); if (CollectionUtils.isEmpty(arrayElements)) { return null; } if (LOG.isDebugEnabled()) { LOG.debug("Mapping array attribute {} for vertex {}", arrayElementType.getTypeName(), entityVertex); } List arrValues = new ArrayList(arrayElements.size()); String edgeLabel = EDGE_LABEL_PREFIX + propertyName; for (Object element : arrayElements) { Object arrValue = mapVertexToCollectionEntry(entityVertex, arrayElementType, element, edgeLabel, entityExtInfo, isOwnedAttribute, edgeDirection); if (arrValue != null) { arrValues.add(arrValue); } } return arrValues; } private Object mapVertexToCollectionEntry(AtlasVertex entityVertex, AtlasType arrayElement, Object value, String edgeLabel, AtlasEntityExtInfo entityExtInfo, boolean isOwnedAttribute, AtlasRelationshipEdgeDirection edgeDirection) throws AtlasBaseException { Object ret = null; switch (arrayElement.getTypeCategory()) { case PRIMITIVE: case ENUM: ret = value; break; case ARRAY: case MAP: case CLASSIFICATION: break; case STRUCT: ret = mapVertexToStruct(entityVertex, edgeLabel, (AtlasEdge) value, entityExtInfo); break; case OBJECT_ID_TYPE: ret = mapVertexToObjectId(entityVertex, edgeLabel, (AtlasEdge) value, entityExtInfo, isOwnedAttribute, edgeDirection); break; default: break; } return ret; } public Object mapVertexToPrimitive(AtlasElement entityVertex, final String vertexPropertyName, AtlasAttributeDef attrDef) { Object ret = null; if (GraphHelper.getSingleValuedProperty(entityVertex, vertexPropertyName, Object.class) == null) { return null; } switch (attrDef.getTypeName().toLowerCase()) { case ATLAS_TYPE_STRING: ret = GraphHelper.getSingleValuedProperty(entityVertex, vertexPropertyName, String.class); break; case ATLAS_TYPE_SHORT: ret = GraphHelper.getSingleValuedProperty(entityVertex, vertexPropertyName, Short.class); break; case ATLAS_TYPE_INT: ret = GraphHelper.getSingleValuedProperty(entityVertex, vertexPropertyName, Integer.class); break; case ATLAS_TYPE_BIGINTEGER: ret = GraphHelper.getSingleValuedProperty(entityVertex, vertexPropertyName, BigInteger.class); break; case ATLAS_TYPE_BOOLEAN: ret = GraphHelper.getSingleValuedProperty(entityVertex, vertexPropertyName, Boolean.class); break; case ATLAS_TYPE_BYTE: ret = GraphHelper.getSingleValuedProperty(entityVertex, vertexPropertyName, Byte.class); break; case ATLAS_TYPE_LONG: ret = GraphHelper.getSingleValuedProperty(entityVertex, vertexPropertyName, Long.class); break; case ATLAS_TYPE_FLOAT: ret = GraphHelper.getSingleValuedProperty(entityVertex, vertexPropertyName, Float.class); break; case ATLAS_TYPE_DOUBLE: ret = GraphHelper.getSingleValuedProperty(entityVertex, vertexPropertyName, Double.class); break; case ATLAS_TYPE_BIGDECIMAL: ret = GraphHelper.getSingleValuedProperty(entityVertex, vertexPropertyName, BigDecimal.class); break; case ATLAS_TYPE_DATE: ret = new Date(GraphHelper.getSingleValuedProperty(entityVertex, vertexPropertyName, Long.class)); break; default: break; } return ret; } private AtlasObjectId mapVertexToObjectId(AtlasVertex entityVertex, String edgeLabel, AtlasEdge edge, AtlasEntityExtInfo entityExtInfo, boolean isOwnedAttribute, AtlasRelationshipEdgeDirection edgeDirection) throws AtlasBaseException { AtlasObjectId ret = null; if (edge == null) { edge = graphHelper.getEdgeForLabel(entityVertex, edgeLabel, edgeDirection); } if (GraphHelper.elementExists(edge)) { AtlasVertex referenceVertex = edge.getInVertex(); if (StringUtils.equals(getIdFromVertex(referenceVertex), getIdFromVertex(entityVertex))) { referenceVertex = edge.getOutVertex(); } if (referenceVertex != null) { if (entityExtInfo != null && isOwnedAttribute) { AtlasEntity entity = mapVertexToAtlasEntity(referenceVertex, entityExtInfo); if (entity != null) { ret = AtlasTypeUtil.getAtlasObjectId(entity); } } else { ret = new AtlasObjectId(GraphHelper.getGuid(referenceVertex), GraphHelper.getTypeName(referenceVertex)); } } } return ret; } private AtlasStruct mapVertexToStruct(AtlasVertex entityVertex, String edgeLabel, AtlasEdge edge, AtlasEntityExtInfo entityExtInfo) throws AtlasBaseException { AtlasStruct ret = null; if (edge == null) { edge = graphHelper.getEdgeForLabel(entityVertex, edgeLabel); } if (GraphHelper.elementExists(edge)) { final AtlasVertex referenceVertex = edge.getInVertex(); ret = new AtlasStruct(GraphHelper.getTypeName(referenceVertex)); mapAttributes(referenceVertex, ret, entityExtInfo); } return ret; } private Object getVertexAttribute(AtlasVertex vertex, AtlasAttribute attribute) throws AtlasBaseException { return vertex != null && attribute != null ? mapVertexToAttribute(vertex, attribute, null) : null; } private void mapRelationshipAttributes(AtlasVertex entityVertex, AtlasEntity entity) throws AtlasBaseException { AtlasEntityType entityType = typeRegistry.getEntityTypeByName(entity.getTypeName()); if (entityType == null) { throw new AtlasBaseException(AtlasErrorCode.TYPE_NAME_INVALID, entity.getTypeName()); } for (AtlasAttribute attribute : entityType.getRelationshipAttributes().values()) { Object attrValue = mapVertexToRelationshipAttribute(entityVertex, entityType, attribute); entity.setRelationshipAttribute(attribute.getName(), attrValue); } } private Object mapVertexToRelationshipAttribute(AtlasVertex entityVertex, AtlasEntityType entityType, AtlasAttribute attribute) throws AtlasBaseException { Object ret = null; AtlasRelationshipDef relationshipDef = graphHelper.getRelationshipDef(entityVertex, entityType, attribute.getName()); if (relationshipDef == null) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_INVALID, "relationshipDef is null"); } AtlasRelationshipEndDef endDef1 = relationshipDef.getEndDef1(); AtlasRelationshipEndDef endDef2 = relationshipDef.getEndDef2(); AtlasEntityType endDef1Type = typeRegistry.getEntityTypeByName(endDef1.getType()); AtlasEntityType endDef2Type = typeRegistry.getEntityTypeByName(endDef2.getType()); AtlasRelationshipEndDef attributeEndDef = null; if (endDef1Type.isTypeOrSuperTypeOf(entityType.getTypeName()) && StringUtils.equals(endDef1.getName(), attribute.getName())) { attributeEndDef = endDef1; } else if (endDef2Type.isTypeOrSuperTypeOf(entityType.getTypeName()) && StringUtils.equals(endDef2.getName(), attribute.getName())) { attributeEndDef = endDef2; } if (attributeEndDef == null) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_INVALID, relationshipDef.toString()); } switch (attributeEndDef.getCardinality()) { case SINGLE: ret = mapRelatedVertexToObjectId(entityVertex, attribute); break; case LIST: case SET: ret = mapRelationshipArrayAttribute(entityVertex, attribute); break; } return ret; } private AtlasObjectId mapRelatedVertexToObjectId(AtlasVertex entityVertex, AtlasAttribute attribute) throws AtlasBaseException { AtlasEdge edge = graphHelper.getEdgeForLabel(entityVertex, attribute.getRelationshipEdgeLabel(), attribute.getRelationshipEdgeDirection()); return mapRelatedVertexToObjectId(entityVertex, edge); } private List<AtlasObjectId> mapRelationshipArrayAttribute(AtlasVertex entityVertex, AtlasAttribute attribute) throws AtlasBaseException { List<AtlasObjectId> ret = new ArrayList<>(); Iterator<AtlasEdge> edges = null; if (attribute.getRelationshipEdgeDirection() == AtlasRelationshipEdgeDirection.IN) { edges = graphHelper.getIncomingEdgesByLabel(entityVertex, attribute.getRelationshipEdgeLabel()); } else if (attribute.getRelationshipEdgeDirection() == AtlasRelationshipEdgeDirection.OUT) { edges = graphHelper.getOutGoingEdgesByLabel(entityVertex, attribute.getRelationshipEdgeLabel()); } if (edges != null) { while (edges.hasNext()) { AtlasEdge relationshipEdge = edges.next(); AtlasObjectId objectId = mapRelatedVertexToObjectId(entityVertex, relationshipEdge); ret.add(objectId); } } return ret; } private AtlasObjectId mapRelatedVertexToObjectId(AtlasVertex entityVertex, AtlasEdge edge) throws AtlasBaseException { AtlasObjectId ret = null; if (GraphHelper.elementExists(edge)) { AtlasVertex referenceVertex = edge.getInVertex(); if (StringUtils.equals(getIdFromVertex(referenceVertex), getIdFromVertex(entityVertex))) { referenceVertex = edge.getOutVertex(); } if (referenceVertex != null) { ret = new AtlasObjectId(GraphHelper.getGuid(referenceVertex), GraphHelper.getTypeName(referenceVertex)); } } return ret; } } <|start_filename|>repository/src/main/java/org/apache/atlas/discovery/EntityLineageService.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.discovery; import org.apache.atlas.AtlasClient; import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.annotation.GraphTransaction; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.instance.AtlasEntityHeader; import org.apache.atlas.model.lineage.AtlasLineageInfo; import org.apache.atlas.model.lineage.AtlasLineageInfo.LineageDirection; import org.apache.atlas.model.lineage.AtlasLineageInfo.LineageRelation; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.graph.GraphHelper; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.repository.store.graph.v1.EntityGraphRetriever; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.util.AtlasGremlinQueryProvider; import org.apache.atlas.util.AtlasGremlinQueryProvider.AtlasGremlinQuery; import org.apache.commons.collections.CollectionUtils; import org.springframework.stereotype.Service; import javax.inject.Inject; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; @Service public class EntityLineageService implements AtlasLineageService { private static final String INPUT_PROCESS_EDGE = "__Process.inputs"; private static final String OUTPUT_PROCESS_EDGE = "__Process.outputs"; private final AtlasGraph graph; private final AtlasGremlinQueryProvider gremlinQueryProvider; private final EntityGraphRetriever entityRetriever; @Inject EntityLineageService(AtlasTypeRegistry typeRegistry, AtlasGraph atlasGraph) throws DiscoveryException { this.graph = atlasGraph; this.gremlinQueryProvider = AtlasGremlinQueryProvider.INSTANCE; this.entityRetriever = new EntityGraphRetriever(typeRegistry); } @Override @GraphTransaction public AtlasLineageInfo getAtlasLineageInfo(String guid, LineageDirection direction, int depth) throws AtlasBaseException { AtlasLineageInfo lineageInfo; if (!entityExists(guid)) { throw new AtlasBaseException(AtlasErrorCode.INSTANCE_GUID_NOT_FOUND, guid); } if (direction != null) { if (direction.equals(LineageDirection.INPUT)) { lineageInfo = getLineageInfo(guid, LineageDirection.INPUT, depth); } else if (direction.equals(LineageDirection.OUTPUT)) { lineageInfo = getLineageInfo(guid, LineageDirection.OUTPUT, depth); } else if (direction.equals(LineageDirection.BOTH)) { lineageInfo = getBothLineageInfo(guid, depth); } else { throw new AtlasBaseException(AtlasErrorCode.INSTANCE_LINEAGE_INVALID_PARAMS, "direction", direction.toString()); } } else { throw new AtlasBaseException(AtlasErrorCode.INSTANCE_LINEAGE_INVALID_PARAMS, "direction", null); } return lineageInfo; } private AtlasLineageInfo getLineageInfo(String guid, LineageDirection direction, int depth) throws AtlasBaseException { Map<String, AtlasEntityHeader> entities = new HashMap<>(); Set<LineageRelation> relations = new HashSet<>(); String lineageQuery = getLineageQuery(guid, direction, depth); List paths = (List) graph.executeGremlinScript(lineageQuery, true); if (CollectionUtils.isNotEmpty(paths)) { for (Object path : paths) { if (path instanceof List) { List vertices = (List) path; if (CollectionUtils.isNotEmpty(vertices)) { AtlasEntityHeader prev = null; for (Object vertex : vertices) { if (!(vertex instanceof AtlasVertex)) { continue; } AtlasEntityHeader entity = entityRetriever.toAtlasEntityHeader((AtlasVertex)vertex); if (!entities.containsKey(entity.getGuid())) { entities.put(entity.getGuid(), entity); } if (prev != null) { if (direction.equals(LineageDirection.INPUT)) { relations.add(new LineageRelation(entity.getGuid(), prev.getGuid())); } else if (direction.equals(LineageDirection.OUTPUT)) { relations.add(new LineageRelation(prev.getGuid(), entity.getGuid())); } } prev = entity; } } } } } return new AtlasLineageInfo(guid, entities, relations, direction, depth); } private AtlasLineageInfo getBothLineageInfo(String guid, int depth) throws AtlasBaseException { AtlasLineageInfo inputLineage = getLineageInfo(guid, LineageDirection.INPUT, depth); AtlasLineageInfo outputLineage = getLineageInfo(guid, LineageDirection.OUTPUT, depth); AtlasLineageInfo ret = inputLineage; ret.getRelations().addAll(outputLineage.getRelations()); ret.getGuidEntityMap().putAll(outputLineage.getGuidEntityMap()); ret.setLineageDirection(LineageDirection.BOTH); return ret; } private String getLineageQuery(String entityGuid, LineageDirection direction, int depth) throws AtlasBaseException { String lineageQuery = null; if (direction.equals(LineageDirection.INPUT)) { lineageQuery = generateLineageQuery(entityGuid, depth, OUTPUT_PROCESS_EDGE, INPUT_PROCESS_EDGE); } else if (direction.equals(LineageDirection.OUTPUT)) { lineageQuery = generateLineageQuery(entityGuid, depth, INPUT_PROCESS_EDGE, OUTPUT_PROCESS_EDGE); } return lineageQuery; } private String generateLineageQuery(String entityGuid, int depth, String incomingFrom, String outgoingTo) { String lineageQuery; if (depth < 1) { String query = gremlinQueryProvider.getQuery(AtlasGremlinQuery.FULL_LINEAGE); lineageQuery = String.format(query, entityGuid, incomingFrom, outgoingTo); } else { String query = gremlinQueryProvider.getQuery(AtlasGremlinQuery.PARTIAL_LINEAGE); lineageQuery = String.format(query, entityGuid, incomingFrom, outgoingTo, depth); } return lineageQuery; } private boolean entityExists(String guid) { boolean ret = false; Iterator<AtlasVertex> results = graph.query() .has(Constants.GUID_PROPERTY_KEY, guid) .vertices().iterator(); while (results.hasNext()) { AtlasVertex entityVertex = results.next(); List<String> superTypes = GraphHelper.getSuperTypeNames(entityVertex); ret = (CollectionUtils.isNotEmpty(superTypes)) ? superTypes.contains(AtlasClient.DATA_SET_SUPER_TYPE) : false; } return ret; } } <|start_filename|>graphdb/titan0/src/main/java/org/apache/atlas/repository/graphdb/titan0/Titan0Edge.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan0; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasVertex; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Vertex; /** * Titan 0.5.4 implementation of AtlasEdge. */ public class Titan0Edge extends Titan0Element<Edge> implements AtlasEdge<Titan0Vertex, Titan0Edge> { public Titan0Edge(Titan0Graph graph, Edge edge) { super(graph, edge); } @Override public String getLabel() { return wrappedElement.getLabel(); } @Override public Titan0Edge getE() { return this; } @Override public AtlasVertex<Titan0Vertex, Titan0Edge> getInVertex() { Vertex v = wrappedElement.getVertex(Direction.IN); return GraphDbObjectFactory.createVertex(graph, v); } @Override public AtlasVertex<Titan0Vertex, Titan0Edge> getOutVertex() { Vertex v = wrappedElement.getVertex(Direction.OUT); return GraphDbObjectFactory.createVertex(graph, v); } @Override public String toString() { return "Titan0Edge [id=" + getId() + "]"; } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/store/graph/AtlasTypeDefGraphStore.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.store.graph; import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.AtlasException; import org.apache.atlas.GraphTransactionInterceptor; import org.apache.atlas.annotation.GraphTransaction; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.listener.ActiveStateChangeHandler; import org.apache.atlas.listener.ChangedTypeDefs; import org.apache.atlas.listener.TypeDefChangeListener; import org.apache.atlas.model.SearchFilter; import org.apache.atlas.model.typedef.*; import org.apache.atlas.model.typedef.AtlasStructDef.AtlasAttributeDef; import org.apache.atlas.model.typedef.AtlasStructDef.AtlasConstraintDef; import org.apache.atlas.repository.util.FilterUtil; import org.apache.atlas.store.AtlasTypeDefStore; import org.apache.atlas.type.*; import org.apache.atlas.type.AtlasTypeRegistry.AtlasTransientTypeRegistry; import org.apache.atlas.util.AtlasRepositoryConfiguration; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.Predicate; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Abstract class for graph persistence store for TypeDef */ public abstract class AtlasTypeDefGraphStore implements AtlasTypeDefStore, ActiveStateChangeHandler { private static final Logger LOG = LoggerFactory.getLogger(AtlasTypeDefGraphStore.class); private final AtlasTypeRegistry typeRegistry; private final Set<TypeDefChangeListener> typeDefChangeListeners; private final int typeUpdateLockMaxWaitTimeSeconds; protected AtlasTypeDefGraphStore(AtlasTypeRegistry typeRegistry, Set<TypeDefChangeListener> typeDefChangeListeners) { this.typeRegistry = typeRegistry; this.typeDefChangeListeners = typeDefChangeListeners; this.typeUpdateLockMaxWaitTimeSeconds = AtlasRepositoryConfiguration.getTypeUpdateLockMaxWaitTimeInSeconds(); } protected abstract AtlasEnumDefStore getEnumDefStore(AtlasTypeRegistry typeRegistry); protected abstract AtlasStructDefStore getStructDefStore(AtlasTypeRegistry typeRegistry); protected abstract AtlasClassificationDefStore getClassificationDefStore(AtlasTypeRegistry typeRegistry); protected abstract AtlasEntityDefStore getEntityDefStore(AtlasTypeRegistry typeRegistry); protected abstract AtlasRelationshipDefStore getRelationshipDefStore(AtlasTypeRegistry typeRegistry); @Override public void init() throws AtlasBaseException { AtlasTransientTypeRegistry ttr = null; boolean commitUpdates = false; try { ttr = typeRegistry.lockTypeRegistryForUpdate(typeUpdateLockMaxWaitTimeSeconds); ttr.clear(); AtlasTypesDef typesDef = new AtlasTypesDef(getEnumDefStore(ttr).getAll(), getStructDefStore(ttr).getAll(), getClassificationDefStore(ttr).getAll(), getEntityDefStore(ttr).getAll(), getRelationshipDefStore(ttr).getAll()); rectifyTypeErrorsIfAny(typesDef); ttr.addTypes(typesDef); commitUpdates = true; } finally { typeRegistry.releaseTypeRegistryForUpdate(ttr, commitUpdates); } } @Override public AtlasEnumDef getEnumDefByName(String name) throws AtlasBaseException { AtlasEnumDef ret = typeRegistry.getEnumDefByName(name); if (ret == null) { throw new AtlasBaseException(AtlasErrorCode.TYPE_NAME_NOT_FOUND, name); } return ret; } @Override public AtlasEnumDef getEnumDefByGuid(String guid) throws AtlasBaseException { AtlasEnumDef ret = typeRegistry.getEnumDefByGuid(guid); if (ret == null) { throw new AtlasBaseException(AtlasErrorCode.TYPE_GUID_NOT_FOUND, guid); } return ret; } @Override @GraphTransaction public AtlasEnumDef updateEnumDefByName(String name, AtlasEnumDef enumDef) throws AtlasBaseException { AtlasTransientTypeRegistry ttr = lockTypeRegistryAndReleasePostCommit(); tryUpdateByName(name, enumDef, ttr); return getEnumDefStore(ttr).updateByName(name, enumDef); } @Override @GraphTransaction public AtlasEnumDef updateEnumDefByGuid(String guid, AtlasEnumDef enumDef) throws AtlasBaseException { AtlasTransientTypeRegistry ttr = lockTypeRegistryAndReleasePostCommit(); tryUpdateByGUID(guid, enumDef, ttr); return getEnumDefStore(ttr).updateByGuid(guid, enumDef); } @Override public AtlasStructDef getStructDefByName(String name) throws AtlasBaseException { AtlasStructDef ret = typeRegistry.getStructDefByName(name); if (ret == null) { throw new AtlasBaseException(AtlasErrorCode.TYPE_NAME_NOT_FOUND, name); } return ret; } @Override public AtlasStructDef getStructDefByGuid(String guid) throws AtlasBaseException { AtlasStructDef ret = typeRegistry.getStructDefByGuid(guid); if (ret == null) { throw new AtlasBaseException(AtlasErrorCode.TYPE_GUID_NOT_FOUND, guid); } return ret; } @Override public AtlasRelationshipDef getRelationshipDefByName(String name) throws AtlasBaseException { AtlasRelationshipDef ret = typeRegistry.getRelationshipDefByName(name); if (ret == null) { throw new AtlasBaseException(AtlasErrorCode.TYPE_NAME_NOT_FOUND, name); } return ret; } @Override public AtlasRelationshipDef getRelationshipDefByGuid(String guid) throws AtlasBaseException { AtlasRelationshipDef ret = typeRegistry.getRelationshipDefByGuid(guid); if (ret == null) { throw new AtlasBaseException(AtlasErrorCode.TYPE_GUID_NOT_FOUND, guid); } return ret; } @Override @GraphTransaction public AtlasStructDef updateStructDefByName(String name, AtlasStructDef structDef) throws AtlasBaseException { AtlasTransientTypeRegistry ttr = lockTypeRegistryAndReleasePostCommit(); tryUpdateByName(name, structDef, ttr); return getStructDefStore(ttr).updateByName(name, structDef); } @Override @GraphTransaction public AtlasStructDef updateStructDefByGuid(String guid, AtlasStructDef structDef) throws AtlasBaseException { AtlasTransientTypeRegistry ttr = lockTypeRegistryAndReleasePostCommit(); tryUpdateByGUID(guid, structDef, ttr); return getStructDefStore(ttr).updateByGuid(guid, structDef); } @Override public AtlasClassificationDef getClassificationDefByName(String name) throws AtlasBaseException { AtlasClassificationDef ret = typeRegistry.getClassificationDefByName(name); if (ret == null) { throw new AtlasBaseException(AtlasErrorCode.TYPE_NAME_NOT_FOUND, name); } return ret; } @Override public AtlasClassificationDef getClassificationDefByGuid(String guid) throws AtlasBaseException { AtlasClassificationDef ret = typeRegistry.getClassificationDefByGuid(guid); if (ret == null) { throw new AtlasBaseException(AtlasErrorCode.TYPE_GUID_NOT_FOUND, guid); } return ret; } @Override @GraphTransaction public AtlasClassificationDef updateClassificationDefByName(String name, AtlasClassificationDef classificationDef) throws AtlasBaseException { AtlasTransientTypeRegistry ttr = lockTypeRegistryAndReleasePostCommit(); tryUpdateByName(name, classificationDef, ttr); return getClassificationDefStore(ttr).updateByName(name, classificationDef); } @Override @GraphTransaction public AtlasClassificationDef updateClassificationDefByGuid(String guid, AtlasClassificationDef classificationDef) throws AtlasBaseException { AtlasTransientTypeRegistry ttr = lockTypeRegistryAndReleasePostCommit(); tryUpdateByGUID(guid, classificationDef, ttr); return getClassificationDefStore(ttr).updateByGuid(guid, classificationDef); } @Override public AtlasEntityDef getEntityDefByName(String name) throws AtlasBaseException { AtlasEntityDef ret = typeRegistry.getEntityDefByName(name); if (ret == null) { throw new AtlasBaseException(AtlasErrorCode.TYPE_NAME_NOT_FOUND, name); } return ret; } @Override public AtlasEntityDef getEntityDefByGuid(String guid) throws AtlasBaseException { AtlasEntityDef ret = typeRegistry.getEntityDefByGuid(guid); if (ret == null) { throw new AtlasBaseException(AtlasErrorCode.TYPE_GUID_NOT_FOUND, guid); } return ret; } @Override @GraphTransaction public AtlasEntityDef updateEntityDefByName(String name, AtlasEntityDef entityDef) throws AtlasBaseException { AtlasTransientTypeRegistry ttr = lockTypeRegistryAndReleasePostCommit(); tryUpdateByName(name, entityDef, ttr); return getEntityDefStore(ttr).updateByName(name, entityDef); } @Override @GraphTransaction public AtlasEntityDef updateEntityDefByGuid(String guid, AtlasEntityDef entityDef) throws AtlasBaseException { AtlasTransientTypeRegistry ttr = lockTypeRegistryAndReleasePostCommit(); tryUpdateByGUID(guid, entityDef, ttr); return getEntityDefStore(ttr).updateByGuid(guid, entityDef); } @Override @GraphTransaction public AtlasRelationshipDef updateRelationshipDefByName(String name, AtlasRelationshipDef relationshipDef) throws AtlasBaseException { AtlasTransientTypeRegistry ttr = lockTypeRegistryAndReleasePostCommit(); tryUpdateByName(name, relationshipDef, ttr); return getRelationshipDefStore(ttr).updateByName(name, relationshipDef); } @Override @GraphTransaction public AtlasRelationshipDef updateRelationshipDefByGuid(String guid, AtlasRelationshipDef relationshipDef) throws AtlasBaseException { AtlasTransientTypeRegistry ttr = lockTypeRegistryAndReleasePostCommit(); tryUpdateByGUID(guid, relationshipDef, ttr); return getRelationshipDefStore(ttr).updateByGuid(guid, relationshipDef); } @Override @GraphTransaction public AtlasTypesDef createTypesDef(AtlasTypesDef typesDef) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeDefGraphStore.createTypesDef(enums={}, structs={}, classifications={}, entities={}, relationships={})", CollectionUtils.size(typesDef.getEnumDefs()), CollectionUtils.size(typesDef.getStructDefs()), CollectionUtils.size(typesDef.getClassificationDefs()), CollectionUtils.size(typesDef.getEntityDefs()), CollectionUtils.size(typesDef.getRelationshipDefs())); } AtlasTransientTypeRegistry ttr = lockTypeRegistryAndReleasePostCommit(); tryTypeCreation(typesDef, ttr); AtlasTypesDef ret = addToGraphStore(typesDef, ttr); if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeDefGraphStore.createTypesDef(enums={}, structs={}, classfications={}, entities={}, relationships={})", CollectionUtils.size(typesDef.getEnumDefs()), CollectionUtils.size(typesDef.getStructDefs()), CollectionUtils.size(typesDef.getClassificationDefs()), CollectionUtils.size(typesDef.getEntityDefs()), CollectionUtils.size(typesDef.getRelationshipDefs())); } return ret; } @Override @GraphTransaction public AtlasTypesDef createUpdateTypesDef(AtlasTypesDef typesToCreate, AtlasTypesDef typesToUpdate) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeDefGraphStore.createUpdateTypesDef({}, {})", typesToCreate, typesToUpdate); } AtlasTransientTypeRegistry ttr = lockTypeRegistryAndReleasePostCommit(); if (!typesToUpdate.isEmpty()) { ttr.updateTypesWithNoRefResolve(typesToUpdate); } // Translate any NOT FOUND errors to BAD REQUEST tryTypeCreation(typesToCreate, ttr); AtlasTypesDef ret = addToGraphStore(typesToCreate, ttr); if (!typesToUpdate.isEmpty()) { AtlasTypesDef updatedTypes = updateGraphStore(typesToUpdate, ttr); if (CollectionUtils.isNotEmpty(updatedTypes.getEnumDefs())) { for (AtlasEnumDef enumDef : updatedTypes.getEnumDefs()) { ret.getEnumDefs().add(enumDef); } } if (CollectionUtils.isNotEmpty(updatedTypes.getStructDefs())) { for (AtlasStructDef structDef : updatedTypes.getStructDefs()) { ret.getStructDefs().add(structDef); } } if (CollectionUtils.isNotEmpty(updatedTypes.getClassificationDefs())) { for (AtlasClassificationDef classificationDef : updatedTypes.getClassificationDefs()) { ret.getClassificationDefs().add(classificationDef); } } if (CollectionUtils.isNotEmpty(updatedTypes.getEntityDefs())) { for (AtlasEntityDef entityDef : updatedTypes.getEntityDefs()) { ret.getEntityDefs().add(entityDef); } } } if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeDefGraphStore.createUpdateTypesDef({}, {}): {}", typesToCreate, typesToUpdate, ret); } return ret; } @Override @GraphTransaction public AtlasTypesDef updateTypesDef(AtlasTypesDef typesDef) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeDefGraphStore.updateTypesDef(enums={}, structs={}, classfications={}, entities={}, relationships{})", CollectionUtils.size(typesDef.getEnumDefs()), CollectionUtils.size(typesDef.getStructDefs()), CollectionUtils.size(typesDef.getClassificationDefs()), CollectionUtils.size(typesDef.getEntityDefs()), CollectionUtils.size(typesDef.getRelationshipDefs())); } AtlasTransientTypeRegistry ttr = lockTypeRegistryAndReleasePostCommit(); // Translate any NOT FOUND errors to BAD REQUEST try { ttr.updateTypes(typesDef); } catch (AtlasBaseException e) { if (AtlasErrorCode.TYPE_NAME_NOT_FOUND == e.getAtlasErrorCode()) { throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, e.getMessage()); } else { throw e; } } AtlasTypesDef ret = updateGraphStore(typesDef, ttr); if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeDefGraphStore.updateTypesDef(enums={}, structs={}, classfications={}, entities={}, relationships={})", CollectionUtils.size(typesDef.getEnumDefs()), CollectionUtils.size(typesDef.getStructDefs()), CollectionUtils.size(typesDef.getClassificationDefs()), CollectionUtils.size(typesDef.getEntityDefs()), CollectionUtils.size(typesDef.getRelationshipDefs())); } return ret; } @Override @GraphTransaction public void deleteTypesDef(AtlasTypesDef typesDef) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeDefGraphStore.deleteTypesDef(enums={}, structs={}, classfications={}, entities={}, relationships={})", CollectionUtils.size(typesDef.getEnumDefs()), CollectionUtils.size(typesDef.getStructDefs()), CollectionUtils.size(typesDef.getClassificationDefs()), CollectionUtils.size(typesDef.getEntityDefs()), CollectionUtils.size(typesDef.getRelationshipDefs())); } AtlasTransientTypeRegistry ttr = lockTypeRegistryAndReleasePostCommit(); AtlasEnumDefStore enumDefStore = getEnumDefStore(ttr); AtlasStructDefStore structDefStore = getStructDefStore(ttr); AtlasClassificationDefStore classifiDefStore = getClassificationDefStore(ttr); AtlasEntityDefStore entityDefStore = getEntityDefStore(ttr); AtlasRelationshipDefStore relationshipDefStore = getRelationshipDefStore(ttr); List<Object> preDeleteStructDefs = new ArrayList<>(); List<Object> preDeleteClassifiDefs = new ArrayList<>(); List<Object> preDeleteEntityDefs = new ArrayList<>(); List<Object> preDeleteRelationshipDefs = new ArrayList<>(); // pre deletes // do the relationships first. if (CollectionUtils.isNotEmpty(typesDef.getRelationshipDefs())) { for (AtlasRelationshipDef relationshipDef : typesDef.getRelationshipDefs()) { if (StringUtils.isNotBlank(relationshipDef.getGuid())) { preDeleteRelationshipDefs.add(relationshipDefStore.preDeleteByGuid(relationshipDef.getGuid())); } else { preDeleteRelationshipDefs.add(relationshipDefStore.preDeleteByName(relationshipDef.getName())); } } } if (CollectionUtils.isNotEmpty(typesDef.getStructDefs())) { for (AtlasStructDef structDef : typesDef.getStructDefs()) { if (StringUtils.isNotBlank(structDef.getGuid())) { preDeleteStructDefs.add(structDefStore.preDeleteByGuid(structDef.getGuid())); } else { preDeleteStructDefs.add(structDefStore.preDeleteByName(structDef.getName())); } } } if (CollectionUtils.isNotEmpty(typesDef.getClassificationDefs())) { for (AtlasClassificationDef classifiDef : typesDef.getClassificationDefs()) { if (StringUtils.isNotBlank(classifiDef.getGuid())) { preDeleteClassifiDefs.add(classifiDefStore.preDeleteByGuid(classifiDef.getGuid())); } else { preDeleteClassifiDefs.add(classifiDefStore.preDeleteByName(classifiDef.getName())); } } } if (CollectionUtils.isNotEmpty(typesDef.getEntityDefs())) { for (AtlasEntityDef entityDef : typesDef.getEntityDefs()) { if (StringUtils.isNotBlank(entityDef.getGuid())) { preDeleteEntityDefs.add(entityDefStore.preDeleteByGuid(entityDef.getGuid())); } else { preDeleteEntityDefs.add(entityDefStore.preDeleteByName(entityDef.getName())); } } } // run the actual deletes // run the relationshipDef delete first - in case there is a enumDef or entityDef dependancy that is going to be deleted. if (CollectionUtils.isNotEmpty(typesDef.getRelationshipDefs())) { int i = 0; for (AtlasRelationshipDef relationshipDef : typesDef.getRelationshipDefs()) { if (StringUtils.isNotBlank(relationshipDef.getGuid())) { relationshipDefStore.deleteByGuid(relationshipDef.getGuid(), preDeleteRelationshipDefs.get(i)); } else { relationshipDefStore.deleteByName(relationshipDef.getName(), preDeleteRelationshipDefs.get(i)); } i++; } } if (CollectionUtils.isNotEmpty(typesDef.getStructDefs())) { int i = 0; for (AtlasStructDef structDef : typesDef.getStructDefs()) { if (StringUtils.isNotBlank(structDef.getGuid())) { structDefStore.deleteByGuid(structDef.getGuid(), preDeleteStructDefs.get(i)); } else { structDefStore.deleteByName(structDef.getName(), preDeleteStructDefs.get(i)); } i++; } } if (CollectionUtils.isNotEmpty(typesDef.getClassificationDefs())) { int i = 0; for (AtlasClassificationDef classifiDef : typesDef.getClassificationDefs()) { if (StringUtils.isNotBlank(classifiDef.getGuid())) { classifiDefStore.deleteByGuid(classifiDef.getGuid(), preDeleteClassifiDefs.get(i)); } else { classifiDefStore.deleteByName(classifiDef.getName(), preDeleteClassifiDefs.get(i)); } i++; } } if (CollectionUtils.isNotEmpty(typesDef.getEntityDefs())) { int i = 0; for (AtlasEntityDef entityDef : typesDef.getEntityDefs()) { if (StringUtils.isNotBlank(entityDef.getGuid())) { entityDefStore.deleteByGuid(entityDef.getGuid(), preDeleteEntityDefs.get(i)); } else { entityDefStore.deleteByName(entityDef.getName(), preDeleteEntityDefs.get(i)); } i++; } } if (CollectionUtils.isNotEmpty(typesDef.getEnumDefs())) { for (AtlasEnumDef enumDef : typesDef.getEnumDefs()) { if (StringUtils.isNotBlank(enumDef.getGuid())) { enumDefStore.deleteByGuid(enumDef.getGuid()); } else { enumDefStore.deleteByName(enumDef.getName()); } } } // Remove all from ttr.removeTypesDef(typesDef); if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeDefGraphStore.deleteTypesDef(enums={}, structs={}, classfications={}, entities={})", CollectionUtils.size(typesDef.getEnumDefs()), CollectionUtils.size(typesDef.getStructDefs()), CollectionUtils.size(typesDef.getClassificationDefs()), CollectionUtils.size(typesDef.getEntityDefs())); } } @Override public AtlasTypesDef searchTypesDef(SearchFilter searchFilter) throws AtlasBaseException { final AtlasTypesDef typesDef = new AtlasTypesDef(); Predicate searchPredicates = FilterUtil.getPredicateFromSearchFilter(searchFilter); for(AtlasEnumType enumType : typeRegistry.getAllEnumTypes()) { if (searchPredicates.evaluate(enumType)) { typesDef.getEnumDefs().add(enumType.getEnumDef()); } } for(AtlasStructType structType : typeRegistry.getAllStructTypes()) { if (searchPredicates.evaluate(structType)) { typesDef.getStructDefs().add(structType.getStructDef()); } } for(AtlasClassificationType classificationType : typeRegistry.getAllClassificationTypes()) { if (searchPredicates.evaluate(classificationType)) { typesDef.getClassificationDefs().add(classificationType.getClassificationDef()); } } for(AtlasEntityType entityType : typeRegistry.getAllEntityTypes()) { if (searchPredicates.evaluate(entityType)) { typesDef.getEntityDefs().add(entityType.getEntityDef()); } } for(AtlasRelationshipType relationshipType : typeRegistry.getAllRelationshipTypes()) { if (searchPredicates.evaluate(relationshipType)) { typesDef.getRelationshipDefs().add(relationshipType.getRelationshipDef()); } } return typesDef; } @Override public AtlasBaseTypeDef getByName(String name) throws AtlasBaseException { if (StringUtils.isBlank(name)) { throw new AtlasBaseException(AtlasErrorCode.TYPE_NAME_INVALID, "", name); } AtlasType type = typeRegistry.getType(name); return getTypeDefFromType(type); } @Override public AtlasBaseTypeDef getByGuid(String guid) throws AtlasBaseException { if (StringUtils.isBlank(guid)) { throw new AtlasBaseException(AtlasErrorCode.TYPE_GUID_NOT_FOUND, guid); } AtlasType type = typeRegistry.getTypeByGuid(guid); return getTypeDefFromType(type); } @Override public void instanceIsActive() throws AtlasException { try { init(); } catch (AtlasBaseException e) { LOG.error("Failed to init after becoming active", e); } } @Override public void instanceIsPassive() throws AtlasException { LOG.info("Not reacting to a Passive state change"); } private AtlasBaseTypeDef getTypeDefFromType(AtlasType type) throws AtlasBaseException { AtlasBaseTypeDef ret; switch (type.getTypeCategory()) { case ENUM: ret = ((AtlasEnumType) type).getEnumDef(); break; case STRUCT: ret = ((AtlasStructType) type).getStructDef(); break; case CLASSIFICATION: ret = ((AtlasClassificationType) type).getClassificationDef(); break; case ENTITY: ret = ((AtlasEntityType) type).getEntityDef(); break; case PRIMITIVE: case OBJECT_ID_TYPE: case ARRAY: case MAP: default: throw new AtlasBaseException(AtlasErrorCode.SYSTEM_TYPE, type.getTypeCategory().name()); } return ret; } private AtlasTransientTypeRegistry lockTypeRegistryAndReleasePostCommit() throws AtlasBaseException { AtlasTransientTypeRegistry ttr = typeRegistry.lockTypeRegistryForUpdate(typeUpdateLockMaxWaitTimeSeconds); new TypeRegistryUpdateHook(ttr); return ttr; } private void rectifyTypeErrorsIfAny(AtlasTypesDef typesDef) { final Set<String> entityNames = new HashSet<>(); if (CollectionUtils.isNotEmpty(typesDef.getEntityDefs())) { for (AtlasEntityDef entityDef : typesDef.getEntityDefs()) { entityNames.add(entityDef.getName()); } } if (CollectionUtils.isNotEmpty(typesDef.getStructDefs())) { for (AtlasStructDef structDef : typesDef.getStructDefs()) { rectifyAttributesIfNeeded(entityNames, structDef); } removeDuplicateTypeIfAny(typesDef.getStructDefs()); } if (CollectionUtils.isNotEmpty(typesDef.getClassificationDefs())) { for (AtlasClassificationDef classificationDef : typesDef.getClassificationDefs()) { rectifyAttributesIfNeeded(entityNames, classificationDef); } removeDuplicateTypeIfAny(typesDef.getClassificationDefs()); } if (CollectionUtils.isNotEmpty(typesDef.getEntityDefs())) { for (AtlasEntityDef entityDef : typesDef.getEntityDefs()) { rectifyAttributesIfNeeded(entityNames, entityDef); } removeDuplicateTypeIfAny(typesDef.getEntityDefs()); } } private <T extends AtlasBaseTypeDef> void removeDuplicateTypeIfAny(List<T> defList) { final Set<String> entityDefNames = new HashSet<>(); for (int i = 0; i < defList.size(); i++) { if (!entityDefNames.add((defList.get(i)).getName())) { LOG.warn(" Found Duplicate Type => " + defList.get(i).getName()); defList.remove(i); i--; } } } private void rectifyAttributesIfNeeded(final Set<String> entityNames, AtlasStructDef structDef) { List<AtlasAttributeDef> attributeDefs = structDef.getAttributeDefs(); if (CollectionUtils.isNotEmpty(attributeDefs)) { for (AtlasAttributeDef attributeDef : attributeDefs) { if (!hasOwnedReferenceConstraint(attributeDef.getConstraints())) { continue; } Set<String> referencedTypeNames = AtlasTypeUtil.getReferencedTypeNames(attributeDef.getTypeName()); boolean valid = false; for (String referencedTypeName : referencedTypeNames) { if (entityNames.contains(referencedTypeName)) { valid = true; break; } } if (!valid) { rectifyOwnedReferenceError(structDef, attributeDef); } } } } private boolean hasOwnedReferenceConstraint(List<AtlasConstraintDef> constraints) { if (CollectionUtils.isNotEmpty(constraints)) { for (AtlasConstraintDef constraint : constraints) { if (constraint.isConstraintType(AtlasConstraintDef.CONSTRAINT_TYPE_OWNED_REF)) { return true; } } } return false; } private void rectifyOwnedReferenceError(AtlasStructDef structDef, AtlasAttributeDef attributeDef) { List<AtlasConstraintDef> constraints = attributeDef.getConstraints(); if (CollectionUtils.isNotEmpty(constraints)) { for (int i = 0; i < constraints.size(); i++) { AtlasConstraintDef constraint = constraints.get(i); if (constraint.isConstraintType(AtlasConstraintDef.CONSTRAINT_TYPE_OWNED_REF)) { LOG.warn("Invalid constraint ownedRef for attribute {}.{}", structDef.getName(), attributeDef.getName()); constraints.remove(i); i--; } } } } private AtlasTypesDef addToGraphStore(AtlasTypesDef typesDef, AtlasTransientTypeRegistry ttr) throws AtlasBaseException { AtlasTypesDef ret = new AtlasTypesDef(); AtlasEnumDefStore enumDefStore = getEnumDefStore(ttr); AtlasStructDefStore structDefStore = getStructDefStore(ttr); AtlasClassificationDefStore classifiDefStore = getClassificationDefStore(ttr); AtlasEntityDefStore entityDefStore = getEntityDefStore(ttr); AtlasRelationshipDefStore relationshipDefStore = getRelationshipDefStore(ttr); List<Object> preCreateStructDefs = new ArrayList<>(); List<Object> preCreateClassifiDefs = new ArrayList<>(); List<Object> preCreateEntityDefs = new ArrayList<>(); List<Object> preCreateRelationshipDefs = new ArrayList<>(); // for enumerations run the create if (CollectionUtils.isNotEmpty(typesDef.getEnumDefs())) { for (AtlasEnumDef enumDef : typesDef.getEnumDefs()) { AtlasEnumDef createdDef = enumDefStore.create(enumDef); ttr.updateGuid(createdDef.getName(), createdDef.getGuid()); ret.getEnumDefs().add(createdDef); } } // run the preCreates if (CollectionUtils.isNotEmpty(typesDef.getStructDefs())) { for (AtlasStructDef structDef : typesDef.getStructDefs()) { preCreateStructDefs.add(structDefStore.preCreate(structDef)); } } if (CollectionUtils.isNotEmpty(typesDef.getClassificationDefs())) { for (AtlasClassificationDef classifiDef : typesDef.getClassificationDefs()) { preCreateClassifiDefs.add(classifiDefStore.preCreate(classifiDef)); } } if (CollectionUtils.isNotEmpty(typesDef.getEntityDefs())) { for (AtlasEntityDef entityDef : typesDef.getEntityDefs()) { preCreateEntityDefs.add(entityDefStore.preCreate(entityDef)); } } if (CollectionUtils.isNotEmpty(typesDef.getRelationshipDefs())) { for (AtlasRelationshipDef relationshipDef : typesDef.getRelationshipDefs()) { preCreateRelationshipDefs.add(relationshipDefStore.preCreate(relationshipDef)); } } if (CollectionUtils.isNotEmpty(typesDef.getStructDefs())) { int i = 0; for (AtlasStructDef structDef : typesDef.getStructDefs()) { AtlasStructDef createdDef = structDefStore.create(structDef, preCreateStructDefs.get(i)); ttr.updateGuid(createdDef.getName(), createdDef.getGuid()); ret.getStructDefs().add(createdDef); i++; } } if (CollectionUtils.isNotEmpty(typesDef.getClassificationDefs())) { int i = 0; for (AtlasClassificationDef classifiDef : typesDef.getClassificationDefs()) { AtlasClassificationDef createdDef = classifiDefStore.create(classifiDef, preCreateClassifiDefs.get(i)); ttr.updateGuid(createdDef.getName(), createdDef.getGuid()); ret.getClassificationDefs().add(createdDef); i++; } } if (CollectionUtils.isNotEmpty(typesDef.getEntityDefs())) { int i = 0; for (AtlasEntityDef entityDef : typesDef.getEntityDefs()) { AtlasEntityDef createdDef = entityDefStore.create(entityDef, preCreateEntityDefs.get(i)); ttr.updateGuid(createdDef.getName(), createdDef.getGuid()); ret.getEntityDefs().add(createdDef); i++; } } if (CollectionUtils.isNotEmpty(typesDef.getRelationshipDefs())) { int i = 0; for (AtlasRelationshipDef relationshipDef : typesDef.getRelationshipDefs()) { AtlasRelationshipDef createdDef = relationshipDefStore.create(relationshipDef, preCreateRelationshipDefs.get(i)); ttr.updateGuid(createdDef.getName(), createdDef.getGuid()); ret.getRelationshipDefs().add(createdDef); i++; } } return ret; } private AtlasTypesDef updateGraphStore(AtlasTypesDef typesDef, AtlasTransientTypeRegistry ttr) throws AtlasBaseException { AtlasTypesDef ret = new AtlasTypesDef(); AtlasEnumDefStore enumDefStore = getEnumDefStore(ttr); AtlasStructDefStore structDefStore = getStructDefStore(ttr); AtlasClassificationDefStore classifiDefStore = getClassificationDefStore(ttr); AtlasEntityDefStore entityDefStore = getEntityDefStore(ttr); AtlasRelationshipDefStore relationDefStore = getRelationshipDefStore(ttr); if (CollectionUtils.isNotEmpty(typesDef.getEnumDefs())) { for (AtlasEnumDef enumDef : typesDef.getEnumDefs()) { ret.getEnumDefs().add(enumDefStore.update(enumDef)); } } if (CollectionUtils.isNotEmpty(typesDef.getStructDefs())) { for (AtlasStructDef structDef : typesDef.getStructDefs()) { ret.getStructDefs().add(structDefStore.update(structDef)); } } if (CollectionUtils.isNotEmpty(typesDef.getClassificationDefs())) { for (AtlasClassificationDef classifiDef : typesDef.getClassificationDefs()) { ret.getClassificationDefs().add(classifiDefStore.update(classifiDef)); } } if (CollectionUtils.isNotEmpty(typesDef.getEntityDefs())) { for (AtlasEntityDef entityDef : typesDef.getEntityDefs()) { ret.getEntityDefs().add(entityDefStore.update(entityDef)); } } if (CollectionUtils.isNotEmpty(typesDef.getRelationshipDefs())) { for (AtlasRelationshipDef relationshipDef : typesDef.getRelationshipDefs()) { ret.getRelationshipDefs().add(relationDefStore.update(relationshipDef)); } } return ret; } private class TypeRegistryUpdateHook extends GraphTransactionInterceptor.PostTransactionHook { private final AtlasTransientTypeRegistry ttr; private TypeRegistryUpdateHook(AtlasTransientTypeRegistry ttr) { super(); this.ttr = ttr; } @Override public void onComplete(boolean isSuccess) { if (LOG.isDebugEnabled()) { LOG.debug("==> TypeRegistryUpdateHook.onComplete({})", isSuccess); } typeRegistry.releaseTypeRegistryForUpdate(ttr, isSuccess); if (isSuccess) { notifyListeners(ttr); } if (LOG.isDebugEnabled()) { LOG.debug("<== TypeRegistryUpdateHook.onComplete({})", isSuccess); } } private void notifyListeners(AtlasTransientTypeRegistry ttr) { if (CollectionUtils.isNotEmpty(typeDefChangeListeners)) { ChangedTypeDefs changedTypeDefs = new ChangedTypeDefs(ttr.getAddedTypes(), ttr.getUpdatedTypes(), ttr.getDeleteedTypes()); for (TypeDefChangeListener changeListener : typeDefChangeListeners) { try { changeListener.onChange(changedTypeDefs); } catch (Throwable t) { LOG.error("OnChange failed for listener {}", changeListener.getClass().getName(), t); } } } } } private void tryUpdateByName(String name, AtlasBaseTypeDef typeDef, AtlasTransientTypeRegistry ttr) throws AtlasBaseException { try { ttr.updateTypeByName(name, typeDef); } catch (AtlasBaseException e) { if (AtlasErrorCode.TYPE_NAME_NOT_FOUND == e.getAtlasErrorCode()) { throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, e.getMessage()); } else { throw e; } } } private void tryUpdateByGUID(String guid, AtlasBaseTypeDef typeDef, AtlasTransientTypeRegistry ttr) throws AtlasBaseException { try { ttr.updateTypeByGuid(guid, typeDef); } catch (AtlasBaseException e) { if (AtlasErrorCode.TYPE_GUID_NOT_FOUND == e.getAtlasErrorCode()) { throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, e.getMessage()); } else { throw e; } } } private void tryTypeCreation(AtlasTypesDef typesDef, AtlasTransientTypeRegistry ttr) throws AtlasBaseException { // Translate any NOT FOUND errors to BAD REQUEST try { ttr.addTypes(typesDef); } catch (AtlasBaseException e) { if (AtlasErrorCode.TYPE_NAME_NOT_FOUND == e.getAtlasErrorCode() || AtlasErrorCode.TYPE_GUID_NOT_FOUND == e.getAtlasErrorCode()) { throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, e.getMessage()); } else { throw e; } } } } <|start_filename|>repository/src/test/java/org/apache/atlas/repository/graph/GraphBackedSearchIndexerMockTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graph; import org.apache.atlas.AtlasException; import org.apache.atlas.ha.HAConfiguration; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.IndexException; import org.apache.atlas.repository.RepositoryException; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.AtlasGraphManagement; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.commons.configuration.Configuration; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; public class GraphBackedSearchIndexerMockTest implements IAtlasGraphProvider { @Mock private Configuration configuration; @Mock private AtlasGraph graph; @Mock private AtlasGraphManagement management; @Mock private AtlasTypeRegistry typeRegistry; @BeforeMethod public void setup() { MockitoAnnotations.initMocks(this); } @Test public void testSearchIndicesAreInitializedOnConstructionWhenHAIsDisabled() throws IndexException, RepositoryException { when(configuration.getBoolean(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY, false)).thenReturn(false); when(graph.getManagementSystem()).thenReturn(management); when(management.containsPropertyKey(Constants.VERTEX_TYPE_PROPERTY_KEY)).thenReturn(true); GraphBackedSearchIndexer graphBackedSearchIndexer = new GraphBackedSearchIndexer(this, configuration, typeRegistry); verify(management).containsPropertyKey(Constants.VERTEX_TYPE_PROPERTY_KEY); } @Test public void testSearchIndicesAreNotInitializedOnConstructionWhenHAIsEnabled() throws IndexException, RepositoryException { when(configuration.containsKey(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY)).thenReturn(true); when(configuration.getBoolean(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY)).thenReturn(true); when(graph.getManagementSystem()).thenReturn(management); when(management.containsPropertyKey(Constants.VERTEX_TYPE_PROPERTY_KEY)).thenReturn(true); new GraphBackedSearchIndexer(this, configuration, typeRegistry); verifyZeroInteractions(management); } @Test public void testIndicesAreReinitializedWhenServerBecomesActive() throws AtlasException { when(configuration.containsKey(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY)).thenReturn(true); when(configuration.getBoolean(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY)).thenReturn(true); when(graph.getManagementSystem()).thenReturn(management); when(management.containsPropertyKey(Constants.VERTEX_TYPE_PROPERTY_KEY)).thenReturn(true); GraphBackedSearchIndexer graphBackedSearchIndexer = new GraphBackedSearchIndexer(this, configuration, typeRegistry); graphBackedSearchIndexer.instanceIsActive(); verify(management).containsPropertyKey(Constants.VERTEX_TYPE_PROPERTY_KEY); } @Override public AtlasGraph get() { return graph; } } <|start_filename|>repository/src/main/java/org/apache/atlas/util/AttributeValueMap.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.util; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.atlas.repository.graph.GraphHelper; import org.apache.atlas.typesystem.IReferenceableInstance; /** * Map of attribute values to a collection of IndexedInstances with that attribute value. * * @see GraphHelper#getVerticesForInstancesByUniqueAttributes * */ public class AttributeValueMap { //need collection in case they are adding the same entity twice? private Map<Object,Collection<IndexedInstance>> valueMap_ = new HashMap<>(); public void put(Object value, IReferenceableInstance instance, int index) { IndexedInstance wrapper = new IndexedInstance(instance, index); Collection<IndexedInstance> existingValues = valueMap_.get(value); if(existingValues == null) { //only expect 1 value existingValues = new HashSet<>(1); valueMap_.put(value, existingValues); } existingValues.add(wrapper); } public Collection<IndexedInstance> get(Object value) { return valueMap_.get(value); } public Set<Object> getAttributeValues() { return valueMap_.keySet(); } } <|start_filename|>repository/src/test/java/org/apache/atlas/repository/store/graph/v1/AtlasRelationshipStoreHardDeleteV1Test.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.store.graph.v1; import com.google.common.collect.ImmutableList; import org.apache.atlas.TestModules; import org.apache.atlas.model.instance.AtlasEntity; import org.testng.annotations.Guice; import static org.apache.atlas.type.AtlasTypeUtil.getAtlasObjectId; /** * Inverse reference update test with {@link HardDeleteHandlerV1} */ @Guice(modules = TestModules.HardDeleteModule.class) public class AtlasRelationshipStoreHardDeleteV1Test extends AtlasRelationshipStoreV1Test { @Override protected void verifyRelationshipAttributeUpdate_NonComposite_OneToMany(AtlasEntity jane) throws Exception { // Max should have been removed from the subordinates list, leaving only John. verifyRelationshipAttributeList(jane, "subordinates", ImmutableList.of(employeeNameIdMap.get("John"))); } @Override protected void verifyRelationshipAttributeUpdate_NonComposite_ManyToOne(AtlasEntity a1, AtlasEntity a2, AtlasEntity a3, AtlasEntity b) { verifyRelationshipAttributeValue(a1, "oneB", null); verifyRelationshipAttributeValue(a2, "oneB", null); verifyRelationshipAttributeList(b, "manyA", ImmutableList.of(getAtlasObjectId(a3))); } @Override protected void verifyRelationshipAttributeUpdate_NonComposite_OneToOne(AtlasEntity a1, AtlasEntity b) { verifyRelationshipAttributeValue(a1, "b", null); } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/store/graph/v1/HardDeleteHandlerV1.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.store.graph.v1; import org.apache.atlas.annotation.ConditionalOnAtlasProperty; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.type.AtlasTypeRegistry; import org.springframework.stereotype.Component; import javax.inject.Inject; @Component @ConditionalOnAtlasProperty(property = "atlas.DeleteHandlerV1.impl") public class HardDeleteHandlerV1 extends DeleteHandlerV1 { @Inject public HardDeleteHandlerV1(AtlasTypeRegistry typeRegistry) { super(typeRegistry, true, false); } @Override protected void _deleteVertex(AtlasVertex instanceVertex, boolean force) { graphHelper.removeVertex(instanceVertex); } @Override protected void deleteEdge(AtlasEdge edge, boolean force) throws AtlasBaseException { graphHelper.removeEdge(edge); } } <|start_filename|>typesystem/src/test/java/org/apache/atlas/typesystem/json/SerializationJavaTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.typesystem.json; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import org.apache.atlas.AtlasException; import org.apache.atlas.typesystem.ITypedInstance; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.Struct; import org.apache.atlas.typesystem.types.AttributeDefinition; import org.apache.atlas.typesystem.types.BaseTest; import org.apache.atlas.typesystem.types.ClassType; import org.apache.atlas.typesystem.types.DataTypes; import org.apache.atlas.typesystem.types.EnumTypeDefinition; import org.apache.atlas.typesystem.types.HierarchicalTypeDefinition; import org.apache.atlas.typesystem.types.Multiplicity; import org.apache.atlas.typesystem.types.StructTypeDefinition; import org.apache.atlas.typesystem.types.TraitType; import org.apache.atlas.typesystem.types.TypeSystem; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.testng.Assert; import static org.apache.atlas.typesystem.types.utils.TypesUtil.createClassTypeDef; import static org.apache.atlas.typesystem.types.utils.TypesUtil.createRequiredAttrDef; import static org.apache.atlas.typesystem.types.utils.TypesUtil.createTraitTypeDef; public class SerializationJavaTest extends BaseTest { @BeforeMethod public void setup() throws Exception { super.setup(); } /* * Class Hierarchy is: * Department(name : String, employees : Array[Person]) * Person(name : String, department : Department, manager : Manager) * Manager(subordinates : Array[Person]) extends Person * * Persons can have SecurityClearance(level : Int) clearance. */ @Test public void test1() throws AtlasException { TypeSystem ts = getTypeSystem(); HierarchicalTypeDefinition<ClassType> deptTypeDef = createClassTypeDef("Department", ImmutableSet.<String>of(), createRequiredAttrDef("name", DataTypes.STRING_TYPE), new AttributeDefinition("employees", String.format("array<%s>", "Person"), Multiplicity.COLLECTION, true, "department")); HierarchicalTypeDefinition<ClassType> personTypeDef = createClassTypeDef("Person", ImmutableSet.<String>of(), createRequiredAttrDef("name", DataTypes.STRING_TYPE), new AttributeDefinition("department", "Department", Multiplicity.REQUIRED, false, "employees"), new AttributeDefinition("manager", "Manager", Multiplicity.OPTIONAL, false, "subordinates")); HierarchicalTypeDefinition<ClassType> managerTypeDef = createClassTypeDef("Manager", ImmutableSet.of("Person"), new AttributeDefinition("subordinates", String.format("array<%s>", "Person"), Multiplicity.COLLECTION, false, "manager")); HierarchicalTypeDefinition<TraitType> securityClearanceTypeDef = createTraitTypeDef("SecurityClearance", ImmutableSet.<String>of(), createRequiredAttrDef("level", DataTypes.INT_TYPE)); ts.defineTypes(ImmutableList.<EnumTypeDefinition>of(), ImmutableList.<StructTypeDefinition>of(), ImmutableList.of(securityClearanceTypeDef), ImmutableList.of(deptTypeDef, personTypeDef, managerTypeDef)); Referenceable hrDept = new Referenceable("Department"); Referenceable john = new Referenceable("Person"); Referenceable jane = new Referenceable("Manager", "SecurityClearance"); hrDept.set("name", "hr"); john.set("name", "John"); john.set("department", hrDept); jane.set("name", "Jane"); jane.set("department", hrDept); john.set("manager", jane); hrDept.set("employees", ImmutableList.of(john, jane)); jane.set("subordinates", ImmutableList.of(john)); jane.getTrait("SecurityClearance").set("level", 1); ClassType deptType = ts.getDataType(ClassType.class, "Department"); ITypedReferenceableInstance hrDept2 = deptType.convert(hrDept, Multiplicity.REQUIRED); String hrDeptStr = hrDept2.toString(); Assert.assertEquals(hrDeptStr, "{\n" + "\tid : (type: Department, id: <unassigned>)\n" + "\tname : \thr\n" + "\temployees : \t[{\n" + "\tid : (type: Person, id: <unassigned>)\n" + "\tname : \tJohn\n" + "\tdepartment : (type: Department, id: <unassigned>)\n" + "\tmanager : (type: Manager, id: <unassigned>)\n" + "}, {\n" + "\tid : (type: Manager, id: <unassigned>)\n" + "\tsubordinates : \t[{\n" + "\tid : (type: Person, id: <unassigned>)\n" + "\tname : \tJohn\n" + "\tdepartment : (type: Department, id: <unassigned>)\n" + "\tmanager : (type: Manager, id: <unassigned>)\n" + "}]\n" + "\tname : \tJane\n" + "\tdepartment : (type: Department, id: <unassigned>)\n" + "\tmanager : <null>\n" + "\n" + "\tSecurityClearance : \t{\n" + "\t\tlevel : \t\t1\n" + "\t}}]\n" + "}"); String jsonStr = Serialization$.MODULE$.toJson(hrDept2); //System.out.println(jsonStr); hrDept2 = Serialization$.MODULE$.fromJson(jsonStr); Assert.assertEquals(hrDept2.toString(), hrDeptStr); } @Test public void testTrait() throws AtlasException { TypeSystem ts = getTypeSystem(); HierarchicalTypeDefinition<TraitType> securityClearanceTypeDef = createTraitTypeDef("SecurityClearance2", ImmutableSet.<String>of(), createRequiredAttrDef("level", DataTypes.INT_TYPE)); ts.defineTypes(ImmutableList.<EnumTypeDefinition>of(), ImmutableList.<StructTypeDefinition>of(), ImmutableList.of(securityClearanceTypeDef), ImmutableList.<HierarchicalTypeDefinition<ClassType>>of()); Struct s = new Struct("SecurityClearance2"); s.set("level", 1); TraitType tType = ts.getDataType(TraitType.class, "SecurityClearance2"); ITypedInstance t = tType.convert(s, Multiplicity.REQUIRED); String jsonStr = Serialization$.MODULE$.toJson(t); ITypedInstance t2 = Serialization$.MODULE$.traitFromJson(jsonStr); Assert.assertEquals(t.toString(), t2.toString()); } } <|start_filename|>graphdb/titan1/src/main/java/org/apache/atlas/repository/graphdb/titan1/Titan1Graph.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan1; import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.thinkaurelius.titan.core.Cardinality; import com.thinkaurelius.titan.core.PropertyKey; import com.thinkaurelius.titan.core.SchemaViolationException; import com.thinkaurelius.titan.core.TitanGraph; import com.thinkaurelius.titan.core.TitanIndexQuery; import com.thinkaurelius.titan.core.schema.TitanGraphIndex; import com.thinkaurelius.titan.core.schema.TitanManagement; import com.thinkaurelius.titan.core.util.TitanCleanup; import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.groovy.GroovyExpression; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.AtlasGraphManagement; import org.apache.atlas.repository.graphdb.AtlasGraphQuery; import org.apache.atlas.repository.graphdb.AtlasIndexQuery; import org.apache.atlas.repository.graphdb.AtlasSchemaViolationException; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.repository.graphdb.GremlinVersion; import org.apache.atlas.repository.graphdb.titan1.query.Titan1GraphQuery; import org.apache.atlas.repository.graphdb.utils.IteratorToIterableAdapter; import org.apache.atlas.typesystem.types.IDataType; import org.apache.tinkerpop.gremlin.groovy.CompilerCustomizerProvider; import org.apache.tinkerpop.gremlin.groovy.DefaultImportCustomizerProvider; import org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine; import org.apache.tinkerpop.gremlin.process.traversal.P; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; import org.apache.tinkerpop.gremlin.process.traversal.step.util.ImmutablePath; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Element; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.structure.io.IoCore; import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONMapper; import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONWriter; import javax.script.Bindings; import javax.script.ScriptEngine; import javax.script.ScriptException; import java.io.IOException; import java.io.OutputStream; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * Titan 1.0.0 implementation of AtlasGraph. */ public class Titan1Graph implements AtlasGraph<Titan1Vertex, Titan1Edge> { private final ConvertGremlinValueFunction GREMLIN_VALUE_CONVERSION_FUNCTION = new ConvertGremlinValueFunction(); private final class ConvertGremlinValueFunction implements Function<Object, Object> { @Override public Object apply(Object input) { return convertGremlinValue(input); } } private final Set<String> multiProperties; public Titan1Graph() { //determine multi-properties once at startup TitanManagement mgmt = null; try { mgmt = Titan1GraphDatabase.getGraphInstance().openManagement(); Iterable<PropertyKey> keys = mgmt.getRelationTypes(PropertyKey.class); multiProperties = new HashSet<>(); for (PropertyKey key : keys) { if (key.cardinality() != Cardinality.SINGLE) { multiProperties.add(key.name()); } } } finally { if (mgmt != null) { mgmt.rollback(); } } } @Override public AtlasEdge<Titan1Vertex, Titan1Edge> addEdge(AtlasVertex<Titan1Vertex, Titan1Edge> outVertex, AtlasVertex<Titan1Vertex, Titan1Edge> inVertex, String edgeLabel) { try { Vertex oV = outVertex.getV().getWrappedElement(); Vertex iV = inVertex.getV().getWrappedElement(); Edge edge = oV.addEdge(edgeLabel, iV); return GraphDbObjectFactory.createEdge(this, edge); } catch (SchemaViolationException e) { throw new AtlasSchemaViolationException(e); } } @Override public AtlasGraphQuery<Titan1Vertex, Titan1Edge> query() { return new Titan1GraphQuery(this); } @Override public AtlasEdge<Titan1Vertex, Titan1Edge> getEdge(String edgeId) { Iterator<Edge> it = getGraph().edges(edgeId); Edge e = getSingleElement(it, edgeId); return GraphDbObjectFactory.createEdge(this, e); } @Override public void removeEdge(AtlasEdge<Titan1Vertex, Titan1Edge> edge) { Edge wrapped = edge.getE().getWrappedElement(); wrapped.remove(); } @Override public void removeVertex(AtlasVertex<Titan1Vertex, Titan1Edge> vertex) { Vertex wrapped = vertex.getV().getWrappedElement(); wrapped.remove(); } @Override public Iterable<AtlasEdge<Titan1Vertex, Titan1Edge>> getEdges() { Iterator<Edge> edges = getGraph().edges(); return wrapEdges(edges); } @Override public Iterable<AtlasVertex<Titan1Vertex, Titan1Edge>> getVertices() { Iterator<Vertex> vertices = getGraph().vertices(); return wrapVertices(vertices); } @Override public AtlasVertex<Titan1Vertex, Titan1Edge> addVertex() { Vertex result = getGraph().addVertex(); return GraphDbObjectFactory.createVertex(this, result); } @Override public void commit() { getGraph().tx().commit(); } @Override public void rollback() { getGraph().tx().rollback(); } @Override public AtlasIndexQuery<Titan1Vertex, Titan1Edge> indexQuery(String fulltextIndex, String graphQuery) { return indexQuery(fulltextIndex, graphQuery, 0); } @Override public AtlasIndexQuery<Titan1Vertex, Titan1Edge> indexQuery(String fulltextIndex, String graphQuery, int offset) { TitanIndexQuery query = getGraph().indexQuery(fulltextIndex, graphQuery).offset(offset); return new Titan1IndexQuery(this, query); } @Override public AtlasGraphManagement getManagementSystem() { return new Titan1GraphManagement(this, getGraph().openManagement()); } @Override public void shutdown() { getGraph().close(); } @Override public Set<String> getEdgeIndexKeys() { return getIndexKeys(Edge.class); } @Override public Set<String> getVertexIndexKeys() { return getIndexKeys(Vertex.class); } private Set<String> getIndexKeys(Class<? extends Element> titanElementClass) { TitanManagement mgmt = getGraph().openManagement(); Iterable<TitanGraphIndex> indices = mgmt.getGraphIndexes(titanElementClass); Set<String> result = new HashSet<String>(); for (TitanGraphIndex index : indices) { result.add(index.name()); } mgmt.commit(); return result; } @Override public AtlasVertex<Titan1Vertex, Titan1Edge> getVertex(String vertexId) { Iterator<Vertex> it = getGraph().vertices(vertexId); Vertex vertex = getSingleElement(it, vertexId); return GraphDbObjectFactory.createVertex(this, vertex); } public static <T> T getSingleElement(Iterator<T> it, String id) { if (!it.hasNext()) { return null; } T element = it.next(); if (it.hasNext()) { throw new RuntimeException("Multiple items were found with the id " + id); } return element; } @Override public Iterable<AtlasVertex<Titan1Vertex, Titan1Edge>> getVertices(String key, Object value) { AtlasGraphQuery<Titan1Vertex, Titan1Edge> query = query(); query.has(key, value); return query.vertices(); } private Object convertGremlinValue(Object rawValue) { if (rawValue instanceof Vertex) { return GraphDbObjectFactory.createVertex(this, (Vertex) rawValue); } else if (rawValue instanceof Edge) { return GraphDbObjectFactory.createEdge(this, (Edge) rawValue); } else if (rawValue instanceof Map) { Map<String,Object> rowValue = (Map<String,Object>)rawValue; return Maps.transformValues(rowValue, GREMLIN_VALUE_CONVERSION_FUNCTION); } else if (rawValue instanceof ImmutablePath) { ImmutablePath path = (ImmutablePath) rawValue; return convertGremlinValue(path.objects()); } else if (rawValue instanceof List) { return Lists.transform((List)rawValue, GREMLIN_VALUE_CONVERSION_FUNCTION); } else if (rawValue instanceof Collection) { throw new UnsupportedOperationException("Unhandled collection type: " + rawValue.getClass()); } return rawValue; } @Override public GremlinVersion getSupportedGremlinVersion() { return GremlinVersion.THREE; } @Override public void clear() { TitanGraph graph = getGraph(); if (graph.isOpen()) { // only a shut down graph can be cleared graph.close(); } TitanCleanup.clear(graph); } private TitanGraph getGraph() { return Titan1GraphDatabase.getGraphInstance(); } @Override public void exportToGson(OutputStream os) throws IOException { GraphSONMapper mapper = getGraph().io(IoCore.graphson()).mapper().create(); GraphSONWriter.Builder builder = GraphSONWriter.build(); builder.mapper(mapper); GraphSONWriter writer = builder.create(); writer.writeGraph(os, getGraph()); } @Override public GremlinGroovyScriptEngine getGremlinScriptEngine() { Set<String> extraImports = new HashSet<String>(); extraImports.add(java.util.function.Function.class.getName()); Set<String> extraStaticImports = new HashSet<String>(); extraStaticImports.add(P.class.getName() + ".*"); extraStaticImports.add(__.class.getName() + ".*"); CompilerCustomizerProvider provider = new DefaultImportCustomizerProvider(extraImports, extraStaticImports); GremlinGroovyScriptEngine scriptEngine = new GremlinGroovyScriptEngine(provider); return scriptEngine; } @Override public void releaseGremlinScriptEngine(ScriptEngine scriptEngine) { if (scriptEngine instanceof GremlinGroovyScriptEngine) { try { ((GremlinGroovyScriptEngine)scriptEngine).close(); } catch (Exception e) { // ignore } } } @Override public Object executeGremlinScript(String query, boolean isPath) throws AtlasBaseException { Object result = executeGremlinScript(query); return convertGremlinValue(result); } private Object executeGremlinScript(String gremlinQuery) throws AtlasBaseException { GremlinGroovyScriptEngine scriptEngine = getGremlinScriptEngine(); try { Bindings bindings = scriptEngine.createBindings(); bindings.put("graph", getGraph()); bindings.put("g", getGraph().traversal()); Object result = scriptEngine.eval(gremlinQuery, bindings); return result; } catch (ScriptException e) { throw new AtlasBaseException(AtlasErrorCode.GREMLIN_SCRIPT_EXECUTION_FAILED, gremlinQuery); } finally { releaseGremlinScriptEngine(scriptEngine); } } @Override public Object executeGremlinScript(ScriptEngine scriptEngine, Map<? extends String, ? extends Object> userBindings, String query, boolean isPath) throws ScriptException { Bindings bindings = scriptEngine.createBindings(); bindings.putAll(userBindings); bindings.put("g", getGraph()); Object result = scriptEngine.eval(query, bindings); return convertGremlinValue(result); } @Override public GroovyExpression generatePersisentToLogicalConversionExpression(GroovyExpression expr, IDataType<?> type) { //nothing special needed, value is stored in required type return expr; } @Override public boolean isPropertyValueConversionNeeded(IDataType<?> type) { return false; } @Override public boolean requiresInitialIndexedPredicate() { return false; } @Override public GroovyExpression getInitialIndexedPredicate(GroovyExpression parent) { return parent; } @Override public GroovyExpression addOutputTransformationPredicate(GroovyExpression expr, boolean isSelect, boolean isPath) { return expr; } public Iterable<AtlasVertex<Titan1Vertex, Titan1Edge>> wrapVertices(Iterator<? extends Vertex> it) { Iterable<? extends Vertex> iterable = new IteratorToIterableAdapter<>(it); return wrapVertices(iterable); } public Iterable<AtlasVertex<Titan1Vertex, Titan1Edge>> wrapVertices(Iterable<? extends Vertex> it) { return Iterables.transform(it, new Function<Vertex, AtlasVertex<Titan1Vertex, Titan1Edge>>() { @Override public AtlasVertex<Titan1Vertex, Titan1Edge> apply(Vertex input) { return GraphDbObjectFactory.createVertex(Titan1Graph.this, input); } }); } public Iterable<AtlasEdge<Titan1Vertex, Titan1Edge>> wrapEdges(Iterator<? extends Edge> it) { Iterable<? extends Edge> iterable = new IteratorToIterableAdapter<>(it); return wrapEdges(iterable); } public Iterable<AtlasEdge<Titan1Vertex, Titan1Edge>> wrapEdges(Iterable<? extends Edge> it) { return Iterables.transform(it, new Function<Edge, AtlasEdge<Titan1Vertex, Titan1Edge>>() { @Override public AtlasEdge<Titan1Vertex, Titan1Edge> apply(Edge input) { return GraphDbObjectFactory.createEdge(Titan1Graph.this, input); } }); } @Override public boolean isMultiProperty(String propertyName) { return multiProperties.contains(propertyName); } public void addMultiProperties(Set<String> names) { multiProperties.addAll(names); } } <|start_filename|>dashboardv2/public/js/views/tag/TagDetailTableLayoutView.js<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(['require', 'backbone', 'hbs!tmpl/tag/TagDetailTableLayoutView_tmpl', 'utils/CommonViewFunction', 'utils/Utils', 'collection/VTagList', 'utils/Messages' ], function(require, Backbone, TagDetailTableLayoutView_tmpl, CommonViewFunction, Utils, VTagList, Messages) { 'use strict'; var TagDetailTableLayoutView = Backbone.Marionette.LayoutView.extend( /** @lends TagDetailTableLayoutView */ { _viewName: 'TagDetailTableLayoutView', template: TagDetailTableLayoutView_tmpl, /** Layout sub regions */ regions: { RTagTermTableLayoutView: "#r_tagTermTableLayoutView" }, /** ui selector cache */ ui: { detailValue: "[data-id='detailValue']", addTag: "[data-id='addTag']", deleteTag: "[data-id='delete']", editTag: "[data-id='edit']", }, /** ui events hash */ events: function() { var events = {}; events["click " + this.ui.addTag] = function(e) { this.addModalView(e); }; events["click " + this.ui.deleteTag] = function(e) { this.deleteTagDataModal(e); }; events["click " + this.ui.editTag] = function(e) { this.editTagDataModal(e); }; return events; }, /** * intialize a new TagDetailTableLayoutView Layout * @constructs */ initialize: function(options) { _.extend(this, _.pick(options, 'entity', 'guid', 'term', 'entityName', 'fetchCollection', 'enumDefCollection', 'classificationDefCollection')); this.collectionObject = this.entity; this.tagTermCollection = new VTagList(); var tagorterm = _.toArray(this.collectionObject.classifications), tagTermList = [], that = this; _.each(tagorterm, function(object) { var checkTagOrTerm = Utils.checkTagOrTerm(object); if (that.term) { if (checkTagOrTerm.term) { tagTermList.push(object); } } else { if (checkTagOrTerm.tag) { tagTermList.push(object); } } }); this.tagTermCollection.set(tagTermList); this.commonTableOptions = { collection: this.tagTermCollection, includeFilter: false, includePagination: true, includePageSize: false, includeFooterRecords: true, gridOpts: { className: "table table-hover backgrid table-quickMenu", emptyText: 'No records found!' }, filterOpts: {}, paginatorOpts: {} }; }, bindEvents: function() {}, onRender: function() { this.renderTableLayoutView(); }, renderTableLayoutView: function() { var that = this; require(['utils/TableLayout'], function(TableLayout) { var cols = new Backgrid.Columns(that.getSchemaTableColumns()); that.RTagTermTableLayoutView.show(new TableLayout(_.extend({}, that.commonTableOptions, { columns: cols }))); }); }, getSchemaTableColumns: function() { var that = this; var col = {}; return this.tagTermCollection.constructor.getTableCols({ TagorTerm: { label: (this.term) ? "Terms" : "Tags", cell: "String", editable: false, sortable: false, formatter: _.extend({}, Backgrid.CellFormatter.prototype, { fromRaw: function(rawValue, model) { return model.get('typeName'); } }) }, Attributes: { label: "Attributes", cell: "html", editable: false, sortable: false, formatter: _.extend({}, Backgrid.CellFormatter.prototype, { fromRaw: function(rawValue, model) { var values = model.get('attributes'); var data = that.classificationDefCollection.findWhere({ 'name': model.get('typeName') }); var attributeDefs = Utils.getNestedSuperTypeObj({ data: data.toJSON(), collection: that.classificationDefCollection, attrMerge: true }); var tagValue = 'NA', dataType; if (!_.isEmpty(attributeDefs)) { var stringValue = ""; _.each(_.sortBy(_.map(attributeDefs, function(obj) { obj['sortKey'] = obj.name && _.isString(obj.name) ? obj.name.toLowerCase() : "-"; return obj; }), 'sortKey'), function(sortedObj) { var val = _.isNull(values[sortedObj.name]) ? "-" : values[sortedObj.name], key = sortedObj.name; if (sortedObj.typeName === "date") { val = new Date(val) } stringValue += "<tr><td class='html-cell string-cell renderable'>" + _.escape(key) + "</td><td class='html-cell string-cell renderable' data-type=" + sortedObj.typeName + ">" + _.escape(val) + "</td>"; }); tagValue = "<div class='mainAttrTable'><table class='attriTable'><tr><th class='html-cell string-cell renderable'>Name</th><th class='html-cell string-cell renderable'>Value</th>" + stringValue + "</table></div>"; } return tagValue; } }) }, tool: { label: "Tool", cell: "html", editable: false, sortable: false, formatter: _.extend({}, Backgrid.CellFormatter.prototype, { fromRaw: function(rawValue, model) { var deleteData = '<button class="btn btn-atlasAction btn-atlas no-margin-bottom typeLOV" data-id="delete" data-name="' + model.get('typeName') + '"><i class="fa fa-trash"></i></button>', editData = '<button class="btn btn-atlasAction btn-atlas no-margin-bottom typeLOV" data-id="edit" data-name="' + model.get('typeName') + '"><i class="fa fa-pencil"></i></button>'; if (model.get('attributes') === undefined) { return deleteData; } else { return deleteData + editData; } } }) }, }, this.tagTermCollection); }, addModalView: function(e) { var that = this; require(['views/tag/addTagModalView'], function(AddTagModalView) { var view = new AddTagModalView({ guid: that.guid, modalCollection: that.collection, enumDefCollection: that.enumDefCollection }); // view.saveTagData = function() { //override saveTagData function // } }); }, deleteTagDataModal: function(e) { var tagName = $(e.currentTarget).data("name"), that = this; if (that.term) { var modal = CommonViewFunction.deleteTagModel({ msg: "<div class='ellipsis'>Remove: " + "<b>" + _.escape(tagName) + "</b> assignment from" + " " + "<b>" + this.entityName + "?</b></div>", titleMessage: Messages.removeTerm, buttonText: "Remove", }); } else { var modal = CommonViewFunction.deleteTagModel({ msg: "<div class='ellipsis'>Remove: " + "<b>" + _.escape(tagName) + "</b> assignment from" + " " + "<b>" + this.entityName + "?</b></div>", titleMessage: Messages.removeTag, buttonText: "Remove", }); } modal.on('ok', function() { that.deleteTagData(e); }); modal.on('closeModal', function() { modal.trigger('cancel'); }); }, deleteTagData: function(e) { var that = this, tagName = $(e.currentTarget).data("name"); CommonViewFunction.deleteTag({ 'tagName': tagName, 'guid': that.guid, 'tagOrTerm': (that.term ? "term" : "tag"), showLoader: function() { that.$('.fontLoader').show(); that.$('.tableOverlay').show(); }, hideLoader: function() { that.$('.fontLoader').hide(); that.$('.tableOverlay').hide(); }, callback: function() { this.hideLoader(); if (that.fetchCollection) { that.fetchCollection(); } } }); }, editTagDataModal: function(e) { var that = this, tagName = $(e.currentTarget).data('name'), tagModel = _.findWhere(that.collectionObject.classifications, { typeName: tagName }); require([ 'views/tag/addTagModalView' ], function(AddTagModalView) { var view = new AddTagModalView({ 'tagModel': tagModel, callback: function() { that.fetchCollection(); }, guid: that.guid, 'enumDefCollection': that.enumDefCollection }); }); } }); return TagDetailTableLayoutView; }); <|start_filename|>repository/src/test/java/org/apache/atlas/repository/graph/GraphBackedRepositoryHardDeleteTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graph; import org.apache.atlas.AtlasClient; import org.apache.atlas.AtlasException; import org.apache.atlas.TestUtils; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.typesystem.IReferenceableInstance; import org.apache.atlas.typesystem.IStruct; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.ITypedStruct; import org.apache.atlas.typesystem.exception.EntityNotFoundException; import org.apache.atlas.typesystem.exception.NullRequiredAttributeException; import org.apache.atlas.typesystem.types.TypeSystem; import org.testng.Assert; import java.util.List; import java.util.Map; import static org.apache.atlas.TestUtils.COLUMNS_ATTR_NAME; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNull; import static org.testng.Assert.fail; import static org.testng.AssertJUnit.assertNotNull; public class GraphBackedRepositoryHardDeleteTest extends GraphBackedMetadataRepositoryDeleteTestBase { @Override DeleteHandler getDeleteHandler(TypeSystem typeSystem) { return new HardDeleteHandler(typeSystem); } @Override protected void assertTestDeleteEntityWithTraits(String guid) { //entity is deleted. So, no assertions } @Override protected void assertTableForTestDeleteReference(String tableId) { //entity is deleted. So, no assertions } @Override protected void assertColumnForTestDeleteReference(ITypedReferenceableInstance tableInstance) throws AtlasException { List<ITypedReferenceableInstance> columns = (List<ITypedReferenceableInstance>) tableInstance.get(COLUMNS_ATTR_NAME); assertNull(columns); } @Override protected void assertProcessForTestDeleteReference(ITypedReferenceableInstance processInstance) throws Exception { //assert that outputs is empty ITypedReferenceableInstance newProcess = repositoryService.getEntityDefinition(processInstance.getId()._getId()); assertNull(newProcess.get(AtlasClient.PROCESS_ATTRIBUTE_OUTPUTS)); } @Override protected void assertEntityDeleted(String id) throws Exception { try { repositoryService.getEntityDefinition(id); fail("Expected EntityNotFoundException"); } catch(EntityNotFoundException e) { // expected } } @Override protected void assertDeletedColumn(ITypedReferenceableInstance tableInstance) throws AtlasException { assertEquals(((List<IReferenceableInstance>) tableInstance.get(COLUMNS_ATTR_NAME)).size(), 2); } @Override protected void assertTestDeleteEntities(ITypedReferenceableInstance tableInstance) { int vertexCount = getVertices(Constants.ENTITY_TYPE_PROPERTY_KEY, TestUtils.TABLE_TYPE).size(); assertEquals(vertexCount, 0); vertexCount = getVertices(Constants.ENTITY_TYPE_PROPERTY_KEY, TestUtils.COLUMN_TYPE).size(); assertEquals(vertexCount, 0); } @Override protected void assertVerticesDeleted(List<AtlasVertex> vertices) { assertEquals(vertices.size(), 0); } @Override protected void assertTestUpdateEntity_MultiplicityOneNonCompositeReference(String janeGuid) throws Exception { // Verify that max is no longer a subordinate of jane. ITypedReferenceableInstance jane = repositoryService.getEntityDefinition(janeGuid); List<ITypedReferenceableInstance> subordinates = (List<ITypedReferenceableInstance>) jane.get("subordinates"); Assert.assertEquals(subordinates.size(), 1); } @Override protected void assertJohnForTestDisconnectBidirectionalReferences(ITypedReferenceableInstance john, String janeGuid) throws Exception { assertNull(john.get("manager")); } @Override protected void assertMaxForTestDisconnectBidirectionalReferences(Map<String, String> nameGuidMap) throws Exception { // Verify that the Department.employees reference to the deleted employee // was disconnected. ITypedReferenceableInstance hrDept = repositoryService.getEntityDefinition(nameGuidMap.get("hr")); List<ITypedReferenceableInstance> employees = (List<ITypedReferenceableInstance>) hrDept.get("employees"); Assert.assertEquals(employees.size(), 3); String maxGuid = nameGuidMap.get("Max"); for (ITypedReferenceableInstance employee : employees) { Assert.assertNotEquals(employee.getId()._getId(), maxGuid); } // Verify that the Manager.subordinates reference to the deleted employee // Max was disconnected. ITypedReferenceableInstance jane = repositoryService.getEntityDefinition(nameGuidMap.get("Jane")); List<ITypedReferenceableInstance> subordinates = (List<ITypedReferenceableInstance>) jane.get("subordinates"); assertEquals(subordinates.size(), 1); // Verify that max's Person.mentor unidirectional reference to john was disconnected. ITypedReferenceableInstance john = repositoryService.getEntityDefinition(nameGuidMap.get("John")); assertNull(john.get("mentor")); } @Override protected void assertTestDisconnectUnidirectionalArrayReferenceFromClassType( List<ITypedReferenceableInstance> columns, String columnGuid) { assertEquals(columns.size(), 4); for (ITypedReferenceableInstance column : columns) { assertFalse(column.getId()._getId().equals(columnGuid)); } } @Override protected void assertTestDisconnectUnidirectionalArrayReferenceFromStructAndTraitTypes(String structContainerGuid) throws Exception { // Verify that the unidirectional references from the struct and trait instances // to the deleted entities were disconnected. ITypedReferenceableInstance structContainerConvertedEntity = repositoryService.getEntityDefinition(structContainerGuid); ITypedStruct struct = (ITypedStruct) structContainerConvertedEntity.get("struct"); assertNull(struct.get("target")); IStruct trait = structContainerConvertedEntity.getTrait("TestTrait"); assertNotNull(trait); assertNull(trait.get("target")); } @Override protected void assertTestDisconnectMapReferenceFromClassType(String mapOwnerGuid) throws Exception { // Verify map references from mapOwner were disconnected. ITypedReferenceableInstance mapOwnerInstance = repositoryService.getEntityDefinition(mapOwnerGuid); assertNull(mapOwnerInstance.get("map")); assertNull(mapOwnerInstance.get("biMap")); AtlasVertex mapOwnerVertex = GraphHelper.getInstance().getVertexForGUID(mapOwnerGuid); Object object = mapOwnerVertex.getProperty("MapOwner.map.value1", String.class); assertNull(object); object = mapOwnerVertex.getProperty("MapOwner.biMap.value1", String.class); assertNull(object); } @Override protected void assertTestDeleteTargetOfMultiplicityRequiredReference() throws Exception { Assert.fail("Lower bound on attribute Manager.subordinates was not enforced - " + NullRequiredAttributeException.class.getSimpleName() + " was expected but none thrown"); } @Override protected void assertTestLowerBoundsIgnoredOnDeletedEntities(List<ITypedReferenceableInstance> employees) { Assert.assertEquals(employees.size(), 1, "References to deleted employees were not disconnected"); } @Override protected void assertTestLowerBoundsIgnoredOnCompositeDeletedEntities(String hrDeptGuid) throws Exception { try { repositoryService.getEntityDefinition(hrDeptGuid); Assert.fail(EntityNotFoundException.class.getSimpleName() + " was expected but none thrown"); } catch (EntityNotFoundException e) { // good } } @Override protected void verifyTestDeleteEntityWithDuplicateReferenceListElements(List columnsPropertyValue) { // With hard deletes enabled, verify that duplicate edge IDs for deleted edges // were removed from the array property list. Assert.assertEquals(columnsPropertyValue.size(), 2); } } <|start_filename|>webapp/src/main/java/org/apache/atlas/web/filters/AtlasAuthorizationFilter.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.web.filters; import com.google.common.base.Strings; import org.apache.atlas.AtlasClient; import org.apache.atlas.authorize.AtlasAccessRequest; import org.apache.atlas.authorize.AtlasAuthorizationException; import org.apache.atlas.authorize.AtlasAuthorizer; import org.apache.atlas.authorize.AtlasAuthorizerFactory; import org.apache.atlas.authorize.AtlasResourceTypes; import org.json.simple.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; import org.springframework.web.filter.GenericFilterBean; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Set; @Component public class AtlasAuthorizationFilter extends GenericFilterBean { private static final Logger LOG = LoggerFactory.getLogger(AtlasAuthorizationFilter.class); private static boolean isDebugEnabled = LOG.isDebugEnabled(); private AtlasAuthorizer authorizer = null; private final String BASE_URL = "/" + AtlasClient.BASE_URI; public AtlasAuthorizationFilter() { if (isDebugEnabled) { LOG.debug("==> AtlasAuthorizationFilter() -- " + "Now initializing the Apache Atlas Authorizer!!!"); } try { authorizer = AtlasAuthorizerFactory.getAtlasAuthorizer(); if (authorizer != null) { authorizer.init(); } else { LOG.warn("AtlasAuthorizer not initialized properly, please check the application logs and add proper configurations."); } } catch (AtlasAuthorizationException e) { LOG.error("Unable to obtain AtlasAuthorizer. ", e); } } @Override public void destroy() { if (isDebugEnabled) { LOG.debug("==> AtlasAuthorizationFilter destroy"); } if (authorizer != null) { authorizer.cleanUp(); } super.destroy(); } @SuppressWarnings("unchecked") @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if (isDebugEnabled) { LOG.debug("==> AuthorizationFilter.doFilter"); } HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; AtlasResponseRequestWrapper responseWrapper = new AtlasResponseRequestWrapper(response); responseWrapper.setHeader("X-Frame-Options", "DENY"); String pathInfo = request.getServletPath(); if (!Strings.isNullOrEmpty(pathInfo) && (pathInfo.startsWith(BASE_URL) || BASE_URL.startsWith(pathInfo))) { if (isDebugEnabled) { LOG.debug("{} is a valid REST API request!!!", pathInfo); } String userName = null; Set<String> groups = new HashSet<>(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null) { userName = auth.getName(); Collection<? extends GrantedAuthority> authorities = auth.getAuthorities(); for (GrantedAuthority c : authorities) { groups.add(c.getAuthority()); } } else { if (LOG.isErrorEnabled()) { LOG.error("Cannot obtain Security Context"); } throw new ServletException("Cannot obtain Security Context"); } AtlasAccessRequest atlasRequest = new AtlasAccessRequest(request, userName, groups); if (isDebugEnabled) { LOG.debug("============================\nUserName :: {}\nGroups :: {}\nURL :: {}\nAction :: {}\nrequest.getServletPath() :: {}\n============================\n", atlasRequest.getUser(), atlasRequest.getUserGroups(), request.getRequestURL(), atlasRequest.getAction(), pathInfo); } boolean accessAllowed = false; Set<AtlasResourceTypes> atlasResourceTypes = atlasRequest.getResourceTypes(); if (atlasResourceTypes.size() == 1 && atlasResourceTypes.contains(AtlasResourceTypes.UNKNOWN)) { // Allowing access to unprotected resource types if (LOG.isDebugEnabled()) { LOG.debug("Allowing access to unprotected resource types {}", atlasResourceTypes); } accessAllowed = true; } else { try { if (authorizer != null) { accessAllowed = authorizer.isAccessAllowed(atlasRequest); } } catch (AtlasAuthorizationException e) { if (LOG.isErrorEnabled()) { LOG.error("Access Restricted. Could not process the request :: {}", e); } } if (isDebugEnabled) { LOG.debug("Authorizer result :: {}", accessAllowed); } } if (accessAllowed) { if (isDebugEnabled) { LOG.debug("Access is allowed so forwarding the request!!!"); } chain.doFilter(req, res); } else { JSONObject json = new JSONObject(); json.put("AuthorizationError", "You are not authorized for " + atlasRequest.getAction().name() + " on " + atlasResourceTypes + " : " + atlasRequest.getResource()); response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.sendError(HttpServletResponse.SC_FORBIDDEN, json.toString()); if (isDebugEnabled) { LOG.debug("You are not authorized for {} on {} : {}\nReturning 403 since the access is blocked update!!!!", atlasRequest.getAction().name(), atlasResourceTypes, atlasRequest.getResource()); } } } else { if (isDebugEnabled) { LOG.debug("Ignoring request {}", pathInfo); } chain.doFilter(req, res); } } } <|start_filename|>repository/src/test/java/org/apache/atlas/repository/graph/GraphBackedSearchIndexerTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graph; import com.google.inject.Inject; import org.apache.atlas.AtlasException; import org.apache.atlas.TestModules; import org.apache.atlas.TestUtils; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.AtlasGraphIndex; import org.apache.atlas.repository.graphdb.AtlasGraphManagement; import org.apache.atlas.repository.graphdb.AtlasPropertyKey; import org.apache.atlas.typesystem.types.ClassType; import org.apache.atlas.typesystem.types.DataTypes; import org.apache.atlas.typesystem.types.EnumType; import org.apache.atlas.typesystem.types.EnumValue; import org.apache.atlas.typesystem.types.HierarchicalTypeDefinition; import org.apache.atlas.typesystem.types.TypeSystem; import org.apache.atlas.typesystem.types.utils.TypesUtil; import org.apache.commons.lang.RandomStringUtils; import org.testng.annotations.Guice; import org.testng.annotations.Test; import java.util.Arrays; import java.util.Set; import static org.apache.atlas.typesystem.types.utils.TypesUtil.createClassTypeDef; import static org.testng.Assert.*; @Guice(modules = TestModules.TestOnlyModule.class) public class GraphBackedSearchIndexerTest { @Inject private GraphBackedSearchIndexer graphBackedSearchIndexer; @Test public void verifySystemMixedIndexes() { AtlasGraph graph = TestUtils.getGraph(); AtlasGraphManagement managementSystem = graph.getManagementSystem(); try { AtlasGraphIndex vertexIndex = managementSystem.getGraphIndex(Constants.VERTEX_INDEX); assertNotNull(vertexIndex); assertTrue(vertexIndex.isMixedIndex()); assertFalse(vertexIndex.isEdgeIndex()); assertTrue(vertexIndex.isVertexIndex()); AtlasGraphIndex edgeIndex = managementSystem.getGraphIndex(Constants.EDGE_INDEX); assertNotNull(edgeIndex); assertTrue(edgeIndex.isMixedIndex()); assertTrue(edgeIndex.isEdgeIndex()); assertFalse(edgeIndex.isVertexIndex()); verifyVertexIndexContains(managementSystem, Constants.STATE_PROPERTY_KEY); } finally { managementSystem.rollback(); } } @Test public void verifySystemCompositeIndexes() { AtlasGraph graph = TestUtils.getGraph(); AtlasGraphManagement managementSystem = graph.getManagementSystem(); try { verifySystemCompositeIndex(managementSystem, Constants.GUID_PROPERTY_KEY, true); verifyVertexIndexContains(managementSystem, Constants.GUID_PROPERTY_KEY); verifySystemCompositeIndex(managementSystem, Constants.ENTITY_TYPE_PROPERTY_KEY, false); verifyVertexIndexContains(managementSystem, Constants.ENTITY_TYPE_PROPERTY_KEY); verifySystemCompositeIndex(managementSystem, Constants.SUPER_TYPES_PROPERTY_KEY, false); verifyVertexIndexContains(managementSystem, Constants.SUPER_TYPES_PROPERTY_KEY); verifySystemCompositeIndex(managementSystem, Constants.TRAIT_NAMES_PROPERTY_KEY, false); verifyVertexIndexContains(managementSystem, Constants.TRAIT_NAMES_PROPERTY_KEY); } finally { managementSystem.rollback(); } } @Test public void verifyFullTextIndex() { AtlasGraph graph = TestUtils.getGraph(); AtlasGraphManagement managementSystem = graph.getManagementSystem(); try { AtlasGraphIndex fullTextIndex = managementSystem.getGraphIndex(Constants.FULLTEXT_INDEX); assertTrue(fullTextIndex.isMixedIndex()); Arrays.asList(fullTextIndex.getFieldKeys()).contains( managementSystem.getPropertyKey(Constants.ENTITY_TEXT_PROPERTY_KEY)); } finally { managementSystem.rollback(); } } @Test public void verifyTypeStoreIndexes() { AtlasGraph graph = TestUtils.getGraph(); AtlasGraphManagement managementSystem = graph.getManagementSystem(); try { verifySystemCompositeIndex(managementSystem, Constants.TYPENAME_PROPERTY_KEY, true); verifyVertexIndexContains(managementSystem, Constants.TYPENAME_PROPERTY_KEY); verifySystemCompositeIndex(managementSystem, Constants.VERTEX_TYPE_PROPERTY_KEY, false); verifyVertexIndexContains(managementSystem, Constants.VERTEX_TYPE_PROPERTY_KEY); } finally { managementSystem.rollback(); } } @Test public void verifyUserDefinedTypeIndex() throws AtlasException { AtlasGraph graph = TestUtils.getGraph(); AtlasGraphManagement managementSystem = graph.getManagementSystem(); try { TypeSystem typeSystem = TypeSystem.getInstance(); String enumName = "randomEnum" + RandomStringUtils.randomAlphanumeric(10); EnumType managedType = typeSystem.defineEnumType(enumName, new EnumValue("randomEnumValue", 0)); HierarchicalTypeDefinition<ClassType> databaseTypeDefinition = createClassTypeDef("Database", "Database type description", null, TypesUtil.createUniqueRequiredAttrDef("name", DataTypes.STRING_TYPE), TypesUtil.createRequiredAttrDef("managedType", managedType)); ClassType databaseType = typeSystem.defineClassType(databaseTypeDefinition); graphBackedSearchIndexer.onAdd(Arrays.asList(databaseType)); verifySystemCompositeIndex(managementSystem, "Database.name" + Constants.ENTITY_TYPE_PROPERTY_KEY, false); verifyVertexIndexContains(managementSystem, "Database.name" + Constants.ENTITY_TYPE_PROPERTY_KEY); verifySystemCompositeIndex(managementSystem, "Database.name" + Constants.SUPER_TYPES_PROPERTY_KEY, false); verifyVertexIndexContains(managementSystem, "Database.managedType"); } finally { //search indexer uses its own titan management transaction managementSystem.rollback(); } } private void verifyVertexIndexContains(AtlasGraphManagement managementSystem, String indexName) { AtlasGraphIndex vertexIndex = managementSystem.getGraphIndex(Constants.VERTEX_INDEX); Set<AtlasPropertyKey> fieldKeys = vertexIndex.getFieldKeys(); Arrays.asList(fieldKeys).contains(managementSystem.getPropertyKey(indexName)); } private void verifySystemCompositeIndex(AtlasGraphManagement managementSystem, String indexName, boolean isUnique) { AtlasGraphIndex systemIndex = managementSystem.getGraphIndex(indexName); assertNotNull(systemIndex); assertTrue(systemIndex.isCompositeIndex()); if (isUnique) { assertTrue(systemIndex.isUnique()); } else { assertFalse(systemIndex.isUnique()); } } } <|start_filename|>webapp/src/test/java/org/apache/atlas/notification/NotificationHookConsumerKafkaTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.notification; import org.apache.atlas.AtlasClient; import org.apache.atlas.AtlasException; import org.apache.atlas.AtlasServiceException; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.kafka.AtlasKafkaMessage; import org.apache.atlas.kafka.KafkaNotification; import org.apache.atlas.kafka.NotificationProvider; import org.apache.atlas.model.instance.AtlasEntity; import org.apache.atlas.notification.hook.HookNotification; import org.apache.atlas.repository.converters.AtlasInstanceConverter; import org.apache.atlas.repository.store.graph.AtlasEntityStore; import org.apache.atlas.repository.store.graph.v1.EntityStream; import org.apache.atlas.type.AtlasType; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.web.service.ServiceState; import org.apache.commons.lang.RandomStringUtils; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import static org.apache.atlas.notification.hook.HookNotification.HookNotificationMessage; import java.util.List; import org.apache.atlas.kafka.AtlasKafkaConsumer; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.*; import org.apache.commons.configuration.Configuration; import org.apache.atlas.ApplicationProperties; import static org.testng.Assert.*; public class NotificationHookConsumerKafkaTest { public static final String NAME = "name"; public static final String DESCRIPTION = "description"; public static final String QUALIFIED_NAME = "qualifiedName"; private NotificationInterface notificationInterface = NotificationProvider.get(); @Mock private AtlasEntityStore atlasEntityStore; @Mock private ServiceState serviceState; @Mock private AtlasInstanceConverter instanceConverter; @Mock private AtlasTypeRegistry typeRegistry; private KafkaNotification kafkaNotification; @BeforeTest public void setup() throws AtlasException, InterruptedException, AtlasBaseException { MockitoAnnotations.initMocks(this); AtlasType mockType = mock(AtlasType.class); when(typeRegistry.getType(anyString())).thenReturn(mockType); AtlasEntity.AtlasEntitiesWithExtInfo mockEntity = mock(AtlasEntity.AtlasEntitiesWithExtInfo.class); when(instanceConverter.toAtlasEntities(anyList())).thenReturn(mockEntity); kafkaNotification = startKafkaServer(); } @AfterTest public void shutdown() { kafkaNotification.close(); kafkaNotification.stop(); } @Test public void testConsumerConsumesNewMessageWithAutoCommitDisabled() throws AtlasException, InterruptedException, AtlasBaseException { try { produceMessage(new HookNotification.EntityCreateRequest("test_user1", createEntity())); NotificationConsumer<HookNotificationMessage> consumer = createNewConsumer(kafkaNotification, false); NotificationHookConsumer notificationHookConsumer = new NotificationHookConsumer(notificationInterface, atlasEntityStore, serviceState, instanceConverter, typeRegistry); NotificationHookConsumer.HookConsumer hookConsumer = notificationHookConsumer.new HookConsumer(consumer); consumeOneMessage(consumer, hookConsumer); verify(atlasEntityStore).createOrUpdate(any(EntityStream.class), anyBoolean()); // produce another message, and make sure it moves ahead. If commit succeeded, this would work. produceMessage(new HookNotification.EntityCreateRequest("test_user2", createEntity())); consumeOneMessage(consumer, hookConsumer); verify(atlasEntityStore,times(2)).createOrUpdate(any(EntityStream.class), anyBoolean()); reset(atlasEntityStore); } finally { kafkaNotification.close(); } } @Test(dependsOnMethods = "testConsumerConsumesNewMessageWithAutoCommitDisabled") public void testConsumerRemainsAtSameMessageWithAutoCommitEnabled() throws Exception { try { produceMessage(new HookNotification.EntityCreateRequest("test_user3", createEntity())); NotificationConsumer<HookNotificationMessage> consumer = createNewConsumer(kafkaNotification, true); assertNotNull (consumer); NotificationHookConsumer notificationHookConsumer = new NotificationHookConsumer(notificationInterface, atlasEntityStore, serviceState, instanceConverter, typeRegistry); NotificationHookConsumer.HookConsumer hookConsumer = notificationHookConsumer.new HookConsumer(consumer); consumeOneMessage(consumer, hookConsumer); verify(atlasEntityStore).createOrUpdate(any(EntityStream.class), anyBoolean()); // produce another message, but this will not be consumed, as commit code is not executed in hook consumer. produceMessage(new HookNotification.EntityCreateRequest("test_user4", createEntity())); consumeOneMessage(consumer, hookConsumer); verify(atlasEntityStore,times(2)).createOrUpdate(any(EntityStream.class), anyBoolean()); } finally { kafkaNotification.close(); } } AtlasKafkaConsumer<HookNotificationMessage> createNewConsumer(KafkaNotification kafkaNotification, boolean autoCommitEnabled) { return (AtlasKafkaConsumer) kafkaNotification.createConsumers(NotificationInterface.NotificationType.HOOK, 1, autoCommitEnabled).get(0); } void consumeOneMessage(NotificationConsumer<HookNotificationMessage> consumer, NotificationHookConsumer.HookConsumer hookConsumer) throws InterruptedException { try { long startTime = System.currentTimeMillis(); //fetch starting time while ((System.currentTimeMillis() - startTime) < 10000) { List<AtlasKafkaMessage<HookNotificationMessage>> messages = consumer.receive(); for (AtlasKafkaMessage<HookNotificationMessage> msg : messages) { hookConsumer.handleMessage(msg); } if (messages.size() > 0) { break; } } } catch (AtlasServiceException | AtlasException e) { Assert.fail("Consumer failed with exception ", e); } } Referenceable createEntity() { final Referenceable entity = new Referenceable(AtlasClient.DATA_SET_SUPER_TYPE); entity.set(NAME, "db" + randomString()); entity.set(DESCRIPTION, randomString()); entity.set(QUALIFIED_NAME, randomString()); return entity; } KafkaNotification startKafkaServer() throws AtlasException, InterruptedException { Configuration applicationProperties = ApplicationProperties.get(); applicationProperties.setProperty("atlas.kafka.data", "target/" + RandomStringUtils.randomAlphanumeric(5)); kafkaNotification = new KafkaNotification(applicationProperties); kafkaNotification.start(); Thread.sleep(2000); return kafkaNotification; } protected String randomString() { return RandomStringUtils.randomAlphanumeric(10); } private void produceMessage(HookNotificationMessage message) throws NotificationException { kafkaNotification.send(NotificationInterface.NotificationType.HOOK, message); } } <|start_filename|>webapp/src/main/java/org/apache/atlas/web/errors/AtlasBaseExceptionMapper.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.web.errors; import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.type.AtlasType; import org.springframework.stereotype.Component; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; /** * AtlasBaseException mapper for Jersey. */ @Provider @Component public class AtlasBaseExceptionMapper implements ExceptionMapper<AtlasBaseException> { @Override public Response toResponse(AtlasBaseException exception) { final long id = ThreadLocalRandom.current().nextLong(); // Only log the exception is there's an internal error if (exception.getAtlasErrorCode().getHttpCode() == Response.Status.INTERNAL_SERVER_ERROR) { ExceptionMapperUtil.logException(id, exception); } return buildAtlasBaseExceptionResponse(exception); } protected Response buildAtlasBaseExceptionResponse(AtlasBaseException baseException) { Map<String, String> errorJsonMap = new LinkedHashMap<>(); AtlasErrorCode errorCode = baseException.getAtlasErrorCode(); errorJsonMap.put("errorCode", errorCode.getErrorCode()); errorJsonMap.put("errorMessage", baseException.getMessage()); Response.ResponseBuilder responseBuilder = Response.status(errorCode.getHttpCode()); // No body for 204 (and maybe 304) if (Response.Status.NO_CONTENT != errorCode.getHttpCode()) { responseBuilder.entity(AtlasType.toJson(errorJsonMap)); } return responseBuilder.build(); } } <|start_filename|>graphdb/titan1/src/main/java/org/apache/atlas/repository/graphdb/titan1/Titan1GraphIndex.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan1; import java.util.HashSet; import java.util.Set; import org.apache.atlas.repository.graphdb.AtlasGraphIndex; import org.apache.atlas.repository.graphdb.AtlasPropertyKey; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Vertex; import com.thinkaurelius.titan.core.PropertyKey; import com.thinkaurelius.titan.core.schema.TitanGraphIndex; /** * Represents an Index in Titan 1. */ public class Titan1GraphIndex implements AtlasGraphIndex { private TitanGraphIndex wrapped; public Titan1GraphIndex(TitanGraphIndex toWrap) { this.wrapped = toWrap; } @Override public boolean isEdgeIndex() { return Edge.class.isAssignableFrom(wrapped.getIndexedElement()); } @Override public boolean isVertexIndex() { return Vertex.class.isAssignableFrom(wrapped.getIndexedElement()); } @Override public boolean isUnique() { return wrapped.isUnique(); } @Override public Set<AtlasPropertyKey> getFieldKeys() { PropertyKey[] keys = wrapped.getFieldKeys(); Set<AtlasPropertyKey> result = new HashSet<AtlasPropertyKey>(); for(PropertyKey key : keys) { result.add(GraphDbObjectFactory.createPropertyKey(key)); } return result; } @Override public int hashCode() { int result = 17; result = 37*result + wrapped.hashCode(); return result; } @Override public boolean equals(Object other) { if (!(other instanceof Titan1GraphIndex)) { return false; } Titan1GraphIndex otherKey = (Titan1GraphIndex)other; return otherKey.wrapped.equals(wrapped); } @Override public boolean isMixedIndex() { return wrapped.isMixedIndex(); } @Override public boolean isCompositeIndex() { return wrapped.isCompositeIndex(); } } <|start_filename|>repository/src/test/java/org/apache/atlas/TestUtils.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import org.apache.atlas.annotation.GraphTransaction; import org.apache.atlas.listener.EntityChangeListener; import org.apache.atlas.listener.TypesChangeListener; import org.apache.atlas.repository.MetadataRepository; import org.apache.atlas.repository.audit.InMemoryEntityAuditRepository; import org.apache.atlas.repository.graph.AtlasGraphProvider; import org.apache.atlas.repository.graph.GraphBackedMetadataRepository; import org.apache.atlas.repository.graph.GraphBackedSearchIndexer; import org.apache.atlas.repository.graph.GraphHelper; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.GremlinVersion; import org.apache.atlas.repository.typestore.GraphBackedTypeStore; import org.apache.atlas.repository.typestore.ITypeStore; import org.apache.atlas.services.DefaultMetadataService; import org.apache.atlas.services.MetadataService; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.typesystem.IInstance; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.TypesDef; import org.apache.atlas.typesystem.json.InstanceSerialization; import org.apache.atlas.typesystem.persistence.Id; import org.apache.atlas.typesystem.types.*; import org.apache.atlas.typesystem.types.DataTypes.TypeCategory; import org.apache.atlas.typesystem.types.cache.DefaultTypeCache; import org.apache.atlas.typesystem.types.cache.TypeCache; import org.apache.atlas.typesystem.types.utils.TypesUtil; import org.apache.atlas.util.AtlasRepositoryConfiguration; import org.apache.commons.configuration.Configuration; import org.apache.commons.lang.RandomStringUtils; import org.codehaus.jettison.json.JSONArray; import org.testng.Assert; import org.testng.SkipException; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static org.apache.atlas.typesystem.types.utils.TypesUtil.*; import static org.testng.Assert.assertEquals; /** * Test utility class. */ public final class TestUtils { public static final long TEST_DATE_IN_LONG = 1418265358440L; public static final String EMPLOYEES_ATTR = "employees"; public static final String DEPARTMENT_ATTR = "department"; public static final String ASSETS_ATTR = "assets"; public static final String POSITIONS_ATTR = "positions"; public static final String ASSET_TYPE = "TestAsset"; public static final String DATABASE_TYPE = "hive_database"; public static final String DATABASE_NAME = "foo"; public static final String TABLE_TYPE = "hive_table"; public static final String PROCESS_TYPE = "hive_process"; public static final String COLUMN_TYPE = "column_type"; public static final String TABLE_NAME = "bar"; public static final String CLASSIFICATION = "classification"; public static final String PII = "PII"; public static final String SUPER_TYPE_NAME = "Base"; public static final String STORAGE_DESC_TYPE = "hive_storagedesc"; public static final String PARTITION_STRUCT_TYPE = "partition_struct_type"; public static final String PARTITION_CLASS_TYPE = "partition_class_type"; public static final String SERDE_TYPE = "serdeType"; public static final String COLUMNS_MAP = "columnsMap"; public static final String COLUMNS_ATTR_NAME = "columns"; public static final String NAME = "name"; private TestUtils() { } /** * Dumps the graph in GSON format in the path returned. * * @param graph handle to graph * @return path to the dump file * @throws Exception */ public static String dumpGraph(AtlasGraph<?,?> graph) throws Exception { File tempFile = File.createTempFile("graph", ".gson"); System.out.println("tempFile.getPath() = " + tempFile.getPath()); GraphHelper.dumpToLog(graph); FileOutputStream os = null; try { os = new FileOutputStream(tempFile); graph.exportToGson(os); } finally { if(os != null) { try { os.close(); } catch(IOException e) { e.printStackTrace(); } } } return tempFile.getPath(); } /** * Class Hierarchy is: * Department(name : String, employees : Array[Person]) * Person(name : String, department : Department, manager : Manager) * Manager(subordinates : Array[Person]) extends Person * <p/> * Persons can have SecurityClearance(level : Int) clearance. */ public static void defineDeptEmployeeTypes(TypeSystem ts) throws AtlasException { String _description = "_description"; EnumTypeDefinition orgLevelEnum = new EnumTypeDefinition("OrgLevel", "OrgLevel"+_description, new EnumValue("L1", 1), new EnumValue("L2", 2)); StructTypeDefinition addressDetails = createStructTypeDef("Address", "Address"+_description, createRequiredAttrDef("street", DataTypes.STRING_TYPE), createRequiredAttrDef("city", DataTypes.STRING_TYPE)); HierarchicalTypeDefinition<ClassType> deptTypeDef = createClassTypeDef(DEPARTMENT_TYPE, "Department"+_description, ImmutableSet.<String>of(), createRequiredAttrDef(NAME, DataTypes.STRING_TYPE), new AttributeDefinition(EMPLOYEES_ATTR, String.format("array<%s>", "Person"), Multiplicity.OPTIONAL, true, DEPARTMENT_ATTR), new AttributeDefinition(POSITIONS_ATTR, String.format("map<%s,%s>", DataTypes.STRING_TYPE.getName(), "Person"), Multiplicity.OPTIONAL, false, null) ); HierarchicalTypeDefinition<ClassType> personTypeDef = createClassTypeDef("Person", "Person"+_description, ImmutableSet.<String>of(), createRequiredAttrDef(NAME, DataTypes.STRING_TYPE), createOptionalAttrDef("orgLevel", "OrgLevel"), createOptionalAttrDef("address", "Address"), new AttributeDefinition(DEPARTMENT_ATTR, "Department", Multiplicity.REQUIRED, false, EMPLOYEES_ATTR), new AttributeDefinition("manager", "Manager", Multiplicity.OPTIONAL, false, "subordinates"), new AttributeDefinition("mentor", "Person", Multiplicity.OPTIONAL, false, null), new AttributeDefinition(ASSETS_ATTR, String.format("array<%s>", ASSET_TYPE) , Multiplicity.OPTIONAL, false, null), createOptionalAttrDef("birthday", DataTypes.DATE_TYPE), createOptionalAttrDef("hasPets", DataTypes.BOOLEAN_TYPE), createOptionalAttrDef("numberOfCars", DataTypes.BYTE_TYPE), createOptionalAttrDef("houseNumber", DataTypes.SHORT_TYPE), createOptionalAttrDef("carMileage", DataTypes.INT_TYPE), createOptionalAttrDef("shares", DataTypes.LONG_TYPE), createOptionalAttrDef("salary", DataTypes.DOUBLE_TYPE), createOptionalAttrDef("age", DataTypes.FLOAT_TYPE), createOptionalAttrDef("numberOfStarsEstimate", DataTypes.BIGINTEGER_TYPE), createOptionalAttrDef("approximationOfPi", DataTypes.BIGDECIMAL_TYPE), createOptionalAttrDef("isOrganDonor", DataTypes.BOOLEAN_TYPE) ); HierarchicalTypeDefinition<ClassType> assetTypeDef = createClassTypeDef(ASSET_TYPE, "Asset"+_description, ImmutableSet.<String>of(), createRequiredAttrDef(NAME, DataTypes.STRING_TYPE), new AttributeDefinition("childAssets", String.format("array<%s>", ASSET_TYPE) , Multiplicity.OPTIONAL, false, null) ); HierarchicalTypeDefinition<ClassType> managerTypeDef = createClassTypeDef("Manager", "Manager"+_description, ImmutableSet.of("Person"), new AttributeDefinition("subordinates", String.format("array<%s>", "Person"), Multiplicity.COLLECTION, false, "manager")); HierarchicalTypeDefinition<TraitType> securityClearanceTypeDef = createTraitTypeDef("SecurityClearance", "SecurityClearance"+_description, ImmutableSet.<String>of(), createRequiredAttrDef("level", DataTypes.INT_TYPE)); ts.defineTypes(ImmutableList.of(orgLevelEnum), ImmutableList.of(addressDetails), ImmutableList.of(securityClearanceTypeDef), ImmutableList.of(deptTypeDef, personTypeDef, managerTypeDef, assetTypeDef)); } public static final String DEPARTMENT_TYPE = "Department"; public static final String PERSON_TYPE = "Person"; public static ITypedReferenceableInstance createDeptEg1(TypeSystem ts) throws AtlasException { Referenceable hrDept = new Referenceable(DEPARTMENT_TYPE); Referenceable john = new Referenceable(PERSON_TYPE); Referenceable jane = new Referenceable("Manager", "SecurityClearance"); Referenceable johnAddr = new Referenceable("Address"); Referenceable janeAddr = new Referenceable("Address"); Referenceable julius = new Referenceable("Manager"); Referenceable juliusAddr = new Referenceable("Address"); Referenceable max = new Referenceable("Person"); Referenceable maxAddr = new Referenceable("Address"); hrDept.set(NAME, "hr"); john.set(NAME, "John"); john.set(DEPARTMENT_ATTR, hrDept); johnAddr.set("street", "Stewart Drive"); johnAddr.set("city", "Sunnyvale"); john.set("address", johnAddr); john.set("birthday",new Date(1950, 5, 15)); john.set("isOrganDonor", true); john.set("hasPets", true); john.set("numberOfCars", 1); john.set("houseNumber", 153); john.set("carMileage", 13364); john.set("shares", 15000); john.set("salary", 123345.678); john.set("age", 50); john.set("numberOfStarsEstimate", new BigInteger("1000000000000000000000")); john.set("approximationOfPi", new BigDecimal("3.141592653589793238462643383279502884197169399375105820974944592307816406286")); jane.set(NAME, "Jane"); jane.set(DEPARTMENT_ATTR, hrDept); janeAddr.set("street", "Great America Parkway"); janeAddr.set("city", "Santa Clara"); jane.set("address", janeAddr); janeAddr.set("street", "Great America Parkway"); julius.set(NAME, "Julius"); julius.set(DEPARTMENT_ATTR, hrDept); juliusAddr.set("street", "Madison Ave"); juliusAddr.set("city", "Newtonville"); julius.set("address", juliusAddr); julius.set("subordinates", ImmutableList.<Referenceable>of()); max.set(NAME, "Max"); max.set(DEPARTMENT_ATTR, hrDept); maxAddr.set("street", "Ripley St"); maxAddr.set("city", "Newton"); max.set("address", maxAddr); max.set("manager", jane); max.set("mentor", julius); max.set("birthday",new Date(1979, 3, 15)); max.set("isOrganDonor", true); max.set("hasPets", true); max.set("age", 36); max.set("numberOfCars", 2); max.set("houseNumber", 17); max.set("carMileage", 13); max.set("shares", Long.MAX_VALUE); max.set("salary", Double.MAX_VALUE); max.set("numberOfStarsEstimate", new BigInteger("1000000000000000000000000000000")); max.set("approximationOfPi", new BigDecimal("3.1415926535897932")); john.set("manager", jane); john.set("mentor", max); hrDept.set(EMPLOYEES_ATTR, ImmutableList.of(john, jane, julius, max)); jane.set("subordinates", ImmutableList.of(john, max)); jane.getTrait("SecurityClearance").set("level", 1); ClassType deptType = ts.getDataType(ClassType.class, "Department"); ITypedReferenceableInstance hrDept2 = deptType.convert(hrDept, Multiplicity.REQUIRED); Assert.assertNotNull(hrDept2); return hrDept2; } public static TypesDef simpleType(){ HierarchicalTypeDefinition<ClassType> superTypeDefinition = createClassTypeDef("h_type", ImmutableSet.<String>of(), createOptionalAttrDef("attr", DataTypes.STRING_TYPE)); StructTypeDefinition structTypeDefinition = new StructTypeDefinition("s_type", "structType", new AttributeDefinition[]{createRequiredAttrDef(NAME, DataTypes.STRING_TYPE)}); HierarchicalTypeDefinition<TraitType> traitTypeDefinition = createTraitTypeDef("t_type", "traitType", ImmutableSet.<String>of()); EnumValue values[] = {new EnumValue("ONE", 1),}; EnumTypeDefinition enumTypeDefinition = new EnumTypeDefinition("e_type", "enumType", values); return TypesUtil.getTypesDef(ImmutableList.of(enumTypeDefinition), ImmutableList.of(structTypeDefinition), ImmutableList.of(traitTypeDefinition), ImmutableList.of(superTypeDefinition)); } public static TypesDef simpleTypeUpdated(){ HierarchicalTypeDefinition<ClassType> superTypeDefinition = createClassTypeDef("h_type", ImmutableSet.<String>of(), createOptionalAttrDef("attr", DataTypes.STRING_TYPE)); HierarchicalTypeDefinition<ClassType> newSuperTypeDefinition = createClassTypeDef("new_h_type", ImmutableSet.<String>of(), createOptionalAttrDef("attr", DataTypes.STRING_TYPE)); StructTypeDefinition structTypeDefinition = new StructTypeDefinition("s_type", "structType", new AttributeDefinition[]{createRequiredAttrDef(NAME, DataTypes.STRING_TYPE)}); HierarchicalTypeDefinition<TraitType> traitTypeDefinition = createTraitTypeDef("t_type", "traitType", ImmutableSet.<String>of()); EnumValue values[] = {new EnumValue("ONE", 1),}; EnumTypeDefinition enumTypeDefinition = new EnumTypeDefinition("e_type", "enumType", values); return TypesUtil.getTypesDef(ImmutableList.of(enumTypeDefinition), ImmutableList.of(structTypeDefinition), ImmutableList.of(traitTypeDefinition), ImmutableList.of(superTypeDefinition, newSuperTypeDefinition)); } public static TypesDef simpleTypeUpdatedDiff() { HierarchicalTypeDefinition<ClassType> newSuperTypeDefinition = createClassTypeDef("new_h_type", ImmutableSet.<String>of(), createOptionalAttrDef("attr", DataTypes.STRING_TYPE)); return TypesUtil.getTypesDef(ImmutableList.<EnumTypeDefinition>of(), ImmutableList.<StructTypeDefinition>of(), ImmutableList.<HierarchicalTypeDefinition<TraitType>>of(), ImmutableList.of(newSuperTypeDefinition)); } public static TypesDef defineHiveTypes() { String _description = "_description"; HierarchicalTypeDefinition<ClassType> superTypeDefinition = createClassTypeDef(SUPER_TYPE_NAME, ImmutableSet.<String>of(), createOptionalAttrDef("namespace", DataTypes.STRING_TYPE), createOptionalAttrDef("cluster", DataTypes.STRING_TYPE), createOptionalAttrDef("colo", DataTypes.STRING_TYPE)); HierarchicalTypeDefinition<ClassType> databaseTypeDefinition = createClassTypeDef(DATABASE_TYPE, DATABASE_TYPE + _description,ImmutableSet.of(SUPER_TYPE_NAME), TypesUtil.createUniqueRequiredAttrDef(NAME, DataTypes.STRING_TYPE), createOptionalAttrDef("created", DataTypes.DATE_TYPE), createOptionalAttrDef("isReplicated", DataTypes.BOOLEAN_TYPE), new AttributeDefinition("parameters", new DataTypes.MapType(DataTypes.STRING_TYPE, DataTypes.STRING_TYPE).getName(), Multiplicity.OPTIONAL, false, null), createRequiredAttrDef("description", DataTypes.STRING_TYPE)); StructTypeDefinition structTypeDefinition = new StructTypeDefinition("serdeType", "serdeType" + _description, new AttributeDefinition[]{createRequiredAttrDef(NAME, DataTypes.STRING_TYPE), createRequiredAttrDef("serde", DataTypes.STRING_TYPE), createOptionalAttrDef("description", DataTypes.STRING_TYPE)}); EnumValue values[] = {new EnumValue("MANAGED", 1), new EnumValue("EXTERNAL", 2),}; EnumTypeDefinition enumTypeDefinition = new EnumTypeDefinition("tableType", "tableType" + _description, values); HierarchicalTypeDefinition<ClassType> columnsDefinition = createClassTypeDef(COLUMN_TYPE, ImmutableSet.<String>of(), createUniqueRequiredAttrDef(NAME, DataTypes.STRING_TYPE), createRequiredAttrDef("type", DataTypes.STRING_TYPE)); StructTypeDefinition partitionDefinition = new StructTypeDefinition("partition_struct_type", "partition_struct_type" + _description, new AttributeDefinition[]{createRequiredAttrDef(NAME, DataTypes.STRING_TYPE),}); AttributeDefinition[] attributeDefinitions = new AttributeDefinition[]{ new AttributeDefinition("location", DataTypes.STRING_TYPE.getName(), Multiplicity.OPTIONAL, false, null), new AttributeDefinition("inputFormat", DataTypes.STRING_TYPE.getName(), Multiplicity.OPTIONAL, false, null), new AttributeDefinition("outputFormat", DataTypes.STRING_TYPE.getName(), Multiplicity.OPTIONAL, false, null), new AttributeDefinition("compressed", DataTypes.BOOLEAN_TYPE.getName(), Multiplicity.REQUIRED, false, null), new AttributeDefinition("numBuckets", DataTypes.INT_TYPE.getName(), Multiplicity.OPTIONAL, false, null), }; HierarchicalTypeDefinition<ClassType> storageDescClsDef = new HierarchicalTypeDefinition<>(ClassType.class, STORAGE_DESC_TYPE, STORAGE_DESC_TYPE + _description, ImmutableSet.of(SUPER_TYPE_NAME), attributeDefinitions); AttributeDefinition[] partClsAttributes = new AttributeDefinition[]{ new AttributeDefinition("values", DataTypes.arrayTypeName(DataTypes.STRING_TYPE.getName()), Multiplicity.OPTIONAL, false, null), new AttributeDefinition("table", TABLE_TYPE, Multiplicity.REQUIRED, false, null), new AttributeDefinition("createTime", DataTypes.LONG_TYPE.getName(), Multiplicity.OPTIONAL, false, null), new AttributeDefinition("lastAccessTime", DataTypes.LONG_TYPE.getName(), Multiplicity.OPTIONAL, false, null), new AttributeDefinition("sd", STORAGE_DESC_TYPE, Multiplicity.REQUIRED, true, null), new AttributeDefinition("columns", DataTypes.arrayTypeName(COLUMN_TYPE), Multiplicity.OPTIONAL, true, null), new AttributeDefinition("parameters", new DataTypes.MapType(DataTypes.STRING_TYPE, DataTypes.STRING_TYPE).getName(), Multiplicity.OPTIONAL, false, null),}; HierarchicalTypeDefinition<ClassType> partClsDef = new HierarchicalTypeDefinition<>(ClassType.class, "partition_class_type", "partition_class_type" + _description, ImmutableSet.of(SUPER_TYPE_NAME), partClsAttributes); HierarchicalTypeDefinition<ClassType> processClsType = new HierarchicalTypeDefinition<>(ClassType.class, PROCESS_TYPE, PROCESS_TYPE + _description, ImmutableSet.<String>of(), new AttributeDefinition[]{ new AttributeDefinition("outputs", "array<" + TABLE_TYPE + ">", Multiplicity.OPTIONAL, false, null) }); HierarchicalTypeDefinition<ClassType> tableTypeDefinition = createClassTypeDef(TABLE_TYPE, TABLE_TYPE + _description, ImmutableSet.of(SUPER_TYPE_NAME), TypesUtil.createUniqueRequiredAttrDef(NAME, DataTypes.STRING_TYPE), createRequiredAttrDef("description", DataTypes.STRING_TYPE), createRequiredAttrDef("type", DataTypes.STRING_TYPE), createOptionalAttrDef("created", DataTypes.DATE_TYPE), // enum new AttributeDefinition("tableType", "tableType", Multiplicity.REQUIRED, false, null), // array of strings new AttributeDefinition("columnNames", String.format("array<%s>", DataTypes.STRING_TYPE.getName()), Multiplicity.OPTIONAL, false, null), // array of classes new AttributeDefinition("columns", String.format("array<%s>", COLUMN_TYPE), Multiplicity.OPTIONAL, true, null), // array of structs new AttributeDefinition("partitions", String.format("array<%s>", "partition_struct_type"), Multiplicity.OPTIONAL, true, null), // map of primitives new AttributeDefinition("parametersMap", DataTypes.mapTypeName(DataTypes.STRING_TYPE.getName(), DataTypes.STRING_TYPE.getName()), Multiplicity.OPTIONAL, true, null), //map of classes - new AttributeDefinition(COLUMNS_MAP, DataTypes.mapTypeName(DataTypes.STRING_TYPE.getName(), COLUMN_TYPE), Multiplicity.OPTIONAL, true, null), //map of structs new AttributeDefinition("partitionsMap", DataTypes.mapTypeName(DataTypes.STRING_TYPE.getName(), "partition_struct_type"), Multiplicity.OPTIONAL, true, null), // struct reference new AttributeDefinition("serde1", "serdeType", Multiplicity.OPTIONAL, false, null), new AttributeDefinition("serde2", "serdeType", Multiplicity.OPTIONAL, false, null), // class reference new AttributeDefinition("database", DATABASE_TYPE, Multiplicity.REQUIRED, false, null), //class reference as composite new AttributeDefinition("databaseComposite", DATABASE_TYPE, Multiplicity.OPTIONAL, true, null)); HierarchicalTypeDefinition<TraitType> piiTypeDefinition = createTraitTypeDef(PII, PII + _description, ImmutableSet.<String>of()); HierarchicalTypeDefinition<TraitType> classificationTypeDefinition = createTraitTypeDef(CLASSIFICATION, CLASSIFICATION + _description, ImmutableSet.<String>of(), createRequiredAttrDef("tag", DataTypes.STRING_TYPE)); HierarchicalTypeDefinition<TraitType> fetlClassificationTypeDefinition = createTraitTypeDef("fetl" + CLASSIFICATION, "fetl" + CLASSIFICATION + _description, ImmutableSet.of(CLASSIFICATION), createRequiredAttrDef("tag", DataTypes.STRING_TYPE)); return TypesUtil.getTypesDef(ImmutableList.of(enumTypeDefinition), ImmutableList.of(structTypeDefinition, partitionDefinition), ImmutableList.of(classificationTypeDefinition, fetlClassificationTypeDefinition, piiTypeDefinition), ImmutableList.of(superTypeDefinition, databaseTypeDefinition, columnsDefinition, tableTypeDefinition, storageDescClsDef, partClsDef, processClsType)); } public static Collection<IDataType> createHiveTypes(TypeSystem typeSystem) throws Exception { if (!typeSystem.isRegistered(TABLE_TYPE)) { TypesDef typesDef = defineHiveTypes(); return typeSystem.defineTypes(typesDef).values(); } return new ArrayList<>(); } public static final String randomString() { return RandomStringUtils.randomAlphanumeric(10); } public static Referenceable createDBEntity() { Referenceable entity = new Referenceable(DATABASE_TYPE); String dbName = RandomStringUtils.randomAlphanumeric(10); entity.set(NAME, dbName); entity.set("description", "us db"); return entity; } public static Referenceable createTableEntity(String dbId) { Referenceable entity = new Referenceable(TABLE_TYPE); String tableName = RandomStringUtils.randomAlphanumeric(10); entity.set(NAME, tableName); entity.set("description", "random table"); entity.set("type", "type"); entity.set("tableType", "MANAGED"); entity.set("database", new Id(dbId, 0, DATABASE_TYPE)); entity.set("created", new Date()); return entity; } public static Referenceable createColumnEntity() { Referenceable entity = new Referenceable(COLUMN_TYPE); entity.set(NAME, RandomStringUtils.randomAlphanumeric(10)); entity.set("type", "VARCHAR(32)"); return entity; } /** * Creates an entity in the graph and does basic validation * of the GuidMapping that was created in the process. * */ public static String createInstance(MetadataService metadataService, Referenceable entity) throws Exception { RequestContext.createContext(); String entityjson = InstanceSerialization.toJson(entity, true); JSONArray entitiesJson = new JSONArray(); entitiesJson.put(entityjson); CreateUpdateEntitiesResult creationResult = metadataService.createEntities(entitiesJson.toString()); Map<String,String> guidMap = creationResult.getGuidMapping().getGuidAssignments(); Map<Id, Referenceable> referencedObjects = findReferencedObjects(entity); for(Map.Entry<Id,Referenceable> entry : referencedObjects.entrySet()) { Id foundId = entry.getKey(); if(foundId.isUnassigned()) { String guid = guidMap.get(entry.getKey()._getId()); Referenceable obj = entry.getValue(); loadAndDoSimpleValidation(guid,obj, metadataService); } } List<String> guids = creationResult.getCreatedEntities(); if (guids != null && guids.size() > 0) { return guids.get(guids.size() - 1); } return null; } private static Map<Id,Referenceable> findReferencedObjects(Referenceable ref) { Map<Id, Referenceable> result = new HashMap<>(); findReferencedObjects(ref, result); return result; } private static void findReferencedObjects(Referenceable ref, Map<Id, Referenceable> seen) { Id guid = ref.getId(); if(seen.containsKey(guid)) { return; } seen.put(guid, ref); for(Map.Entry<String, Object> attr : ref.getValuesMap().entrySet()) { Object value = attr.getValue(); if(value instanceof Referenceable) { findReferencedObjects((Referenceable)value, seen); } else if(value instanceof List) { for(Object o : (List)value) { if(o instanceof Referenceable) { findReferencedObjects((Referenceable)o, seen); } } } else if(value instanceof Map) { for(Object o : ((Map)value).values()) { if(o instanceof Referenceable) { findReferencedObjects((Referenceable)o, seen); } } } } } /** * Clears the state in the request context. * */ public static void resetRequestContext() { //reset the context while preserving the user String user = RequestContext.get().getUser(); RequestContext.createContext(); RequestContext.get().setUser(user); } /** * Triggers the Atlas initialization process using the specified MetadataRepository. * This causes the built-in types and their indices to be created. */ public static void setupGraphProvider(MetadataRepository repo) throws AtlasException { TypeCache typeCache = null; try { typeCache = AtlasRepositoryConfiguration.getTypeCache().newInstance(); } catch(Throwable t) { typeCache = new DefaultTypeCache(); } final GraphBackedSearchIndexer indexer = new GraphBackedSearchIndexer(new AtlasTypeRegistry()); Configuration config = ApplicationProperties.get(); ITypeStore typeStore = new GraphBackedTypeStore(AtlasGraphProvider.getGraphInstance()); DefaultMetadataService defaultMetadataService = new DefaultMetadataService(repo, typeStore, new HashSet<TypesChangeListener>() {{ add(indexer); }}, new HashSet<EntityChangeListener>(), TypeSystem.getInstance(), config, typeCache, // Fixme: Can we work with Noop new InMemoryEntityAuditRepository()); //commit the created types getGraph().commit(); } public static AtlasGraph getGraph() { return AtlasGraphProvider.getGraphInstance(); } /** * Adds a proxy wrapper around the specified MetadataService that automatically * resets the request context before every call. * * @param delegate * @return */ public static MetadataService addSessionCleanupWrapper(final MetadataService delegate) { return (MetadataService)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{MetadataService.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { resetRequestContext(); Object result = method.invoke(delegate, args); return result; } catch(InvocationTargetException e) { e.getCause().printStackTrace(); throw e.getCause(); } catch(Throwable t) { t.printStackTrace(); throw t; } } }); } /** * Adds a proxy wrapper around the specified MetadataRepository that automatically * resets the request context before every call and either commits or rolls * back the graph transaction after every call. * * @param delegate * @return */ public static MetadataRepository addTransactionWrapper(final MetadataRepository delegate) { return (MetadataRepository)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{MetadataRepository.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { boolean useTransaction = GraphBackedMetadataRepository.class.getMethod( method.getName(), method.getParameterTypes()) .isAnnotationPresent(GraphTransaction.class); try { resetRequestContext(); Object result = method.invoke(delegate, args); if(useTransaction) { System.out.println("Committing changes"); getGraph().commit(); System.out.println("Commit succeeded."); } return result; } catch(InvocationTargetException e) { e.getCause().printStackTrace(); if(useTransaction) { System.out.println("Rolling back changes due to exception."); getGraph().rollback(); } throw e.getCause(); } catch(Throwable t) { t.printStackTrace(); if(useTransaction) { System.out.println("Rolling back changes due to exception."); getGraph().rollback(); } throw t; } } }); } /** * Loads the entity and does sanity testing of the GuidMapping that was * created during the operation. * */ public static ITypedReferenceableInstance loadAndDoSimpleValidation(String guid, Referenceable original, MetadataRepository repositoryService) throws AtlasException { ITypedReferenceableInstance loaded = repositoryService.getEntityDefinition(guid); doSimpleValidation(original, loaded); return loaded; } /** * Loads the entity and does sanity testing of the GuidMapping that was * created during the operation. * */ public static ITypedReferenceableInstance loadAndDoSimpleValidation(String guid, Referenceable original, MetadataService repositoryService) throws AtlasException { ITypedReferenceableInstance loaded = repositoryService.getEntityDefinition(guid); doSimpleValidation(original, loaded); return loaded; } private static void doSimpleValidation(Referenceable original, IInstance loaded) throws AtlasException { assertEquals(loaded.getTypeName(), original.getTypeName()); ClassType ct = TypeSystem.getInstance().getDataType(ClassType.class, loaded.getTypeName()); //compare primitive fields for(AttributeInfo field : ct.fieldMapping.fields.values()) { if(field.dataType().getTypeCategory() == TypeCategory.PRIMITIVE) { if(original.get(field.name) != null) { Object rawLoadedValue = loaded.get(field.name); Object rawProvidedValue = original.get(field.name); Object convertedLoadedValue = field.dataType().convert(rawLoadedValue, Multiplicity.REQUIRED); Object convertedProvidedValue = field.dataType().convert(rawProvidedValue, Multiplicity.REQUIRED); assertEquals(convertedLoadedValue, convertedProvidedValue); } } } } /** * Validates that the two String Collections contain the same items, without * regard to order. * */ public static void assertContentsSame(Collection<String> actual, Collection<String> expected) { assertEquals(actual.size(), expected.size()); Set<String> checker = new HashSet<>(); checker.addAll(expected); checker.removeAll(actual); assertEquals(checker.size(), 0); } public static void skipForGremlin3EnabledGraphDb() throws SkipException { //ATLAS-1579 Currently, some tests are skipped for titan1 backened. As these tests are hard coded to use Gremlin2. See ATLAS-1579, ATLAS-1591 once it is fixed, please remove it. if (TestUtils.getGraph().getSupportedGremlinVersion() == GremlinVersion.THREE) { throw new SkipException ("This test requires Gremlin2. Skipping test "); } } } <|start_filename|>repository/src/main/java/org/apache/atlas/gremlin/Gremlin3ExpressionFactory.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.gremlin; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.atlas.AtlasException; import org.apache.atlas.groovy.AbstractFunctionExpression; import org.apache.atlas.groovy.CastExpression; import org.apache.atlas.groovy.ClosureExpression; import org.apache.atlas.groovy.ComparisonExpression; import org.apache.atlas.groovy.ComparisonExpression.ComparisonOperator; import org.apache.atlas.groovy.ComparisonOperatorExpression; import org.apache.atlas.groovy.FieldExpression; import org.apache.atlas.groovy.FunctionCallExpression; import org.apache.atlas.groovy.GroovyExpression; import org.apache.atlas.groovy.IdentifierExpression; import org.apache.atlas.groovy.LiteralExpression; import org.apache.atlas.groovy.LogicalExpression; import org.apache.atlas.groovy.LogicalExpression.LogicalOperator; import org.apache.atlas.groovy.TernaryOperatorExpression; import org.apache.atlas.groovy.TraversalStepType; import org.apache.atlas.groovy.TypeCoersionExpression; import org.apache.atlas.query.GraphPersistenceStrategies; import org.apache.atlas.query.TypeUtils.FieldInfo; import org.apache.atlas.repository.graph.AtlasGraphProvider; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.typesystem.types.AttributeInfo; import org.apache.atlas.typesystem.types.IDataType; /** * Generates gremlin query expressions using Gremlin 3 syntax. * */ public class Gremlin3ExpressionFactory extends GremlinExpressionFactory { private static final String VERTEX_LIST_CLASS = "List<Vertex>"; private static final String VERTEX_ARRAY_CLASS = "Vertex[]"; private static final String OBJECT_ARRAY_CLASS = "Object[]"; private static final String VERTEX_CLASS = "Vertex"; private static final String FUNCTION_CLASS = "Function"; private static final String VALUE_METHOD = "value"; private static final String IS_PRESENT_METHOD = "isPresent"; private static final String MAP_METHOD = "map"; private static final String VALUES_METHOD = "values"; private static final String GET_METHOD = "get"; private static final String OR_ELSE_METHOD = "orElse"; private static final String PROPERTY_METHOD = "property"; private static final String BY_METHOD = "by"; private static final String EQ_METHOD = "eq"; private static final String EMIT_METHOD = "emit"; private static final String TIMES_METHOD = "times"; private static final String REPEAT_METHOD = "repeat"; private static final String RANGE_METHOD = "range"; private static final String LAST_METHOD = "last"; private static final String TO_STRING_METHOD = "toString"; private static final GroovyExpression EMPTY_STRING_EXPRESSION = new LiteralExpression(""); @Override public GroovyExpression generateLogicalExpression(GroovyExpression parent, String operator, List<GroovyExpression> operands) { return new FunctionCallExpression(TraversalStepType.FILTER, parent, operator, operands); } @Override public GroovyExpression generateBackReferenceExpression(GroovyExpression parent, boolean inSelect, String alias) { if (inSelect) { return getFieldInSelect(); } else { return new FunctionCallExpression(TraversalStepType.MAP_TO_ELEMENT, parent, SELECT_METHOD, new LiteralExpression(alias)); } } @Override public GroovyExpression typeTestExpression(GraphPersistenceStrategies s, String typeName, GroovyExpression itRef) { LiteralExpression superTypeAttrExpr = new LiteralExpression(s.superTypeAttributeName()); LiteralExpression typeNameExpr = new LiteralExpression(typeName); LiteralExpression typeAttrExpr = new LiteralExpression(s.typeAttributeName()); FunctionCallExpression result = new FunctionCallExpression(TraversalStepType.FILTER, HAS_METHOD, typeAttrExpr, new FunctionCallExpression(EQ_METHOD, typeNameExpr)); result = new FunctionCallExpression(TraversalStepType.FILTER, result, "or"); result = new FunctionCallExpression(TraversalStepType.FILTER, result, HAS_METHOD, superTypeAttrExpr, new FunctionCallExpression(EQ_METHOD, typeNameExpr)); return result; } @Override public GroovyExpression generateLoopExpression(GroovyExpression parent,GraphPersistenceStrategies s, IDataType dataType, GroovyExpression loopExpr, String alias, Integer times) { GroovyExpression emitExpr = generateLoopEmitExpression(s, dataType); GroovyExpression result = new FunctionCallExpression(TraversalStepType.BRANCH, parent, REPEAT_METHOD, loopExpr); if (times != null) { GroovyExpression timesExpr = new LiteralExpression(times); result = new FunctionCallExpression(TraversalStepType.SIDE_EFFECT, result, TIMES_METHOD, timesExpr); } result = new FunctionCallExpression(TraversalStepType.SIDE_EFFECT, result, EMIT_METHOD, emitExpr); return result; } @Override public GroovyExpression getLoopExpressionParent(GroovyExpression inputQry) { GroovyExpression curTraversal = getAnonymousTraversalStartExpression(); return curTraversal; } private IdentifierExpression getAnonymousTraversalStartExpression() { return new IdentifierExpression(TraversalStepType.START, "__"); } @Override public GroovyExpression generateSelectExpression(GroovyExpression parent, List<LiteralExpression> sourceNames, List<GroovyExpression> srcExprs) { FunctionCallExpression result = new FunctionCallExpression(TraversalStepType.MAP_TO_VALUE, parent, SELECT_METHOD, sourceNames); for (GroovyExpression expr : srcExprs) { GroovyExpression closure = new ClosureExpression(expr); GroovyExpression castClosure = new TypeCoersionExpression(closure, FUNCTION_CLASS); result = new FunctionCallExpression(TraversalStepType.SIDE_EFFECT, result, BY_METHOD, castClosure); } return result; } @Override public GroovyExpression generateFieldExpression(GroovyExpression parent, FieldInfo fInfo, String propertyName, boolean inSelect) { AttributeInfo attrInfo = fInfo.attrInfo(); IDataType attrType = attrInfo.dataType(); GroovyExpression propertyNameExpr = new LiteralExpression(propertyName); //Whether it is the user or shared graph does not matter here, since we're //just getting the conversion expression. Ideally that would be moved someplace else. AtlasGraph graph = AtlasGraphProvider.getGraphInstance(); if (inSelect) { GroovyExpression expr = new FunctionCallExpression(parent, PROPERTY_METHOD, propertyNameExpr); expr = new FunctionCallExpression(expr, OR_ELSE_METHOD, LiteralExpression.NULL); return graph.generatePersisentToLogicalConversionExpression(expr, attrType); } else { GroovyExpression unmapped = new FunctionCallExpression(TraversalStepType.FLAT_MAP_TO_VALUES, parent, VALUES_METHOD, propertyNameExpr); if (graph.isPropertyValueConversionNeeded(attrType)) { GroovyExpression toConvert = new FunctionCallExpression(getItVariable(), GET_METHOD); GroovyExpression conversionFunction = graph.generatePersisentToLogicalConversionExpression(toConvert, attrType); return new FunctionCallExpression(TraversalStepType.MAP_TO_VALUE, unmapped, MAP_METHOD, new ClosureExpression(conversionFunction)); } else { return unmapped; } } } private ComparisonOperator getGroovyOperator(String symbol) throws AtlasException { String toFind = symbol; if (toFind.equals("=")) { toFind = "=="; } return ComparisonOperator.lookup(toFind); } private String getComparisonFunction(String op) throws AtlasException { if (op.equals("=")) { return "eq"; } if (op.equals("!=")) { return "neq"; } if (op.equals(">")) { return "gt"; } if (op.equals(">=")) { return "gte"; } if (op.equals("<")) { return "lt"; } if (op.equals("<=")) { return "lte"; } throw new AtlasException("Comparison operator " + op + " not supported in Gremlin"); } @Override public GroovyExpression generateHasExpression(GraphPersistenceStrategies s, GroovyExpression parent, String propertyName, String symbol, GroovyExpression requiredValue, FieldInfo fInfo) throws AtlasException { AttributeInfo attrInfo = fInfo.attrInfo(); IDataType attrType = attrInfo.dataType(); GroovyExpression propertNameExpr = new LiteralExpression(propertyName); if (s.isPropertyValueConversionNeeded(attrType)) { // for some types, the logical value cannot be stored directly in // the underlying graph, // and conversion logic is needed to convert the persistent form of // the value // to the actual value. In cases like this, we generate a conversion // expression to // do this conversion and use the filter step to perform the // comparsion in the gremlin query GroovyExpression itExpr = getItVariable(); GroovyExpression vertexExpr = new CastExpression(new FunctionCallExpression(itExpr, GET_METHOD), VERTEX_CLASS); GroovyExpression propertyValueExpr = new FunctionCallExpression(vertexExpr, VALUE_METHOD, propertNameExpr); GroovyExpression conversionExpr = s.generatePersisentToLogicalConversionExpression(propertyValueExpr, attrType); GroovyExpression propertyIsPresentExpression = new FunctionCallExpression( new FunctionCallExpression(vertexExpr, PROPERTY_METHOD, propertNameExpr), IS_PRESENT_METHOD); GroovyExpression valueMatchesExpr = new ComparisonExpression(conversionExpr, getGroovyOperator(symbol), requiredValue); GroovyExpression filterCondition = new LogicalExpression(propertyIsPresentExpression, LogicalOperator.AND, valueMatchesExpr); GroovyExpression filterFunction = new ClosureExpression(filterCondition); return new FunctionCallExpression(TraversalStepType.FILTER, parent, FILTER_METHOD, filterFunction); } else { GroovyExpression valueMatches = new FunctionCallExpression(getComparisonFunction(symbol), requiredValue); return new FunctionCallExpression(TraversalStepType.FILTER, parent, HAS_METHOD, propertNameExpr, valueMatches); } } @Override public GroovyExpression generateLikeExpressionUsingFilter(GroovyExpression parent, String propertyName, GroovyExpression propertyValue) throws AtlasException { GroovyExpression itExpr = getItVariable(); GroovyExpression nameExpr = new FieldExpression(itExpr, propertyName); GroovyExpression matchesExpr = new FunctionCallExpression(nameExpr, MATCHES, escapePropertyValue(propertyValue)); GroovyExpression closureExpr = new ClosureExpression(matchesExpr); return new FunctionCallExpression(TraversalStepType.FILTER, parent, FILTER_METHOD, closureExpr); } private GroovyExpression escapePropertyValue(GroovyExpression propertyValue) { GroovyExpression ret = propertyValue; if (propertyValue instanceof LiteralExpression) { LiteralExpression exp = (LiteralExpression) propertyValue; if (exp != null && exp.getValue() instanceof String) { String stringValue = (String) exp.getValue(); // replace '*' with ".*", replace '?' with '.' stringValue = stringValue.replaceAll("\\*", ".*") .replaceAll("\\?", "."); ret = new LiteralExpression(stringValue); } } return ret; } @Override protected GroovyExpression initialExpression(GroovyExpression varExpr, GraphPersistenceStrategies s) { // this bit of groovy magic converts the set of vertices in varName into // a String containing the ids of all the vertices. This becomes the // argument // to g.V(). This is needed because Gremlin 3 does not support // _() // s"g.V(${varName}.collect{it.id()} as String[])" GroovyExpression gExpr = getGraphExpression(); GroovyExpression varRefExpr = new TypeCoersionExpression(varExpr, OBJECT_ARRAY_CLASS); GroovyExpression matchingVerticesExpr = new FunctionCallExpression(TraversalStepType.START, gExpr, V_METHOD, varRefExpr); GroovyExpression isEmpty = new FunctionCallExpression(varExpr, "isEmpty"); GroovyExpression emptyGraph = getEmptyTraversalExpression(); GroovyExpression expr = new TernaryOperatorExpression(isEmpty, emptyGraph, matchingVerticesExpr); return s.addInitialQueryCondition(expr); } private GroovyExpression getEmptyTraversalExpression() { GroovyExpression emptyGraph = new FunctionCallExpression(TraversalStepType.START, getGraphExpression(), V_METHOD, EMPTY_STRING_EXPRESSION); return emptyGraph; } @Override public GroovyExpression generateRangeExpression(GroovyExpression parent, int startIndex, int endIndex) { //treat as barrier step, since limits need to be applied globally (even though it //is technically a filter step) return new FunctionCallExpression(TraversalStepType.BARRIER, parent, RANGE_METHOD, new LiteralExpression(startIndex), new LiteralExpression(endIndex)); } @Override public boolean isRangeExpression(GroovyExpression expr) { return (expr instanceof FunctionCallExpression && ((FunctionCallExpression)expr).getFunctionName().equals(RANGE_METHOD)); } @Override public int[] getRangeParameters(AbstractFunctionExpression expr) { if (isRangeExpression(expr)) { FunctionCallExpression rangeExpression = (FunctionCallExpression) expr; List<GroovyExpression> arguments = rangeExpression.getArguments(); int startIndex = (int)((LiteralExpression)arguments.get(0)).getValue(); int endIndex = (int)((LiteralExpression)arguments.get(1)).getValue(); return new int[]{startIndex, endIndex}; } else { return null; } } @Override public void setRangeParameters(GroovyExpression expr, int startIndex, int endIndex) { if (isRangeExpression(expr)) { FunctionCallExpression rangeExpression = (FunctionCallExpression) expr; rangeExpression.setArgument(0, new LiteralExpression(Integer.valueOf(startIndex))); rangeExpression.setArgument(1, new LiteralExpression(Integer.valueOf(endIndex))); } else { throw new IllegalArgumentException(expr + " is not a valid range expression"); } } @Override public List<GroovyExpression> getOrderFieldParents() { List<GroovyExpression> result = new ArrayList<>(1); result.add(null); return result; } @Override public GroovyExpression generateOrderByExpression(GroovyExpression parent, List<GroovyExpression> translatedOrderBy, boolean isAscending) { GroovyExpression orderByExpr = translatedOrderBy.get(0); GroovyExpression orderByClosure = new ClosureExpression(orderByExpr); GroovyExpression orderByClause = new TypeCoersionExpression(orderByClosure, FUNCTION_CLASS); GroovyExpression aExpr = new IdentifierExpression("a"); GroovyExpression bExpr = new IdentifierExpression("b"); GroovyExpression aCompExpr = new FunctionCallExpression(new FunctionCallExpression(aExpr, TO_STRING_METHOD), TO_LOWER_CASE_METHOD); GroovyExpression bCompExpr = new FunctionCallExpression(new FunctionCallExpression(bExpr, TO_STRING_METHOD), TO_LOWER_CASE_METHOD); GroovyExpression comparisonExpr = null; if (isAscending) { comparisonExpr = new ComparisonOperatorExpression(aCompExpr, bCompExpr); } else { comparisonExpr = new ComparisonOperatorExpression(bCompExpr, aCompExpr); } ClosureExpression comparisonFunction = new ClosureExpression(comparisonExpr, "a", "b"); FunctionCallExpression orderCall = new FunctionCallExpression(TraversalStepType.BARRIER, parent, ORDER_METHOD); return new FunctionCallExpression(TraversalStepType.SIDE_EFFECT, orderCall, BY_METHOD, orderByClause, comparisonFunction); } @Override public GroovyExpression getAnonymousTraversalExpression() { return null; } @Override public GroovyExpression getFieldInSelect() { // this logic is needed to remove extra results from // what is emitted by repeat loops. Technically // for queries that don't have a loop in them we could just use "it" // the reason for this is that in repeat loops with an alias, // although the alias gets set to the right value, for some // reason the select actually includes all vertices that were traversed // through in the loop. In these cases, we only want the last vertex // traversed in the loop to be selected. The logic here handles that // case by converting the result to a list and just selecting the // last item from it. GroovyExpression itExpr = getItVariable(); GroovyExpression expr1 = new TypeCoersionExpression(itExpr, VERTEX_ARRAY_CLASS); GroovyExpression expr2 = new TypeCoersionExpression(expr1, VERTEX_LIST_CLASS); return new FunctionCallExpression(expr2, LAST_METHOD); } @Override public GroovyExpression generateGroupByExpression(GroovyExpression parent, GroovyExpression groupByExpression, GroovyExpression aggregationFunction) { GroovyExpression result = new FunctionCallExpression(TraversalStepType.BARRIER, parent, "group"); GroovyExpression groupByClosureExpr = new TypeCoersionExpression(new ClosureExpression(groupByExpression), "Function"); result = new FunctionCallExpression(TraversalStepType.SIDE_EFFECT, result, "by", groupByClosureExpr); result = new FunctionCallExpression(TraversalStepType.END, result, "toList"); GroovyExpression mapValuesClosure = new ClosureExpression(new FunctionCallExpression(new CastExpression(getItVariable(), "Map"), "values")); result = new FunctionCallExpression(result, "collect", mapValuesClosure); //when we call Map.values(), we end up with an extra list around the result. We remove this by calling toList().get(0). This //leaves us with a list of lists containing the vertices that match each group. We then apply the aggregation functions //specified in the select list to each of these inner lists. result = new FunctionCallExpression(result ,"toList"); result = new FunctionCallExpression(result, "get", new LiteralExpression(0)); GroovyExpression aggregrationFunctionClosure = new ClosureExpression(aggregationFunction); result = new FunctionCallExpression(result, "collect", aggregrationFunctionClosure); return result; } @Override public GroovyExpression generateSeededTraversalExpresssion(boolean isMap, GroovyExpression valueCollection) { GroovyExpression coersedExpression = new TypeCoersionExpression(valueCollection, isMap ? "Map[]" : "Vertex[]"); if(isMap) { return new FunctionCallExpression(TraversalStepType.START, "__", coersedExpression); } else { //We cannot always use an anonymous traversal because that breaks repeat steps return new FunctionCallExpression(TraversalStepType.START, getEmptyTraversalExpression(), "inject", coersedExpression); } } @Override public GroovyExpression getGroupBySelectFieldParent() { return null; } @Override public String getTraversalExpressionClass() { return "GraphTraversal"; } @Override public boolean isSelectGeneratesMap(int aliasCount) { //in Gremlin 3, you only get a map if there is more than 1 alias. return aliasCount > 1; } @Override public GroovyExpression generateMapExpression(GroovyExpression parent, ClosureExpression closureExpression) { return new FunctionCallExpression(TraversalStepType.MAP_TO_ELEMENT, parent, "map", closureExpression); } @Override public GroovyExpression generateGetSelectedValueExpression(LiteralExpression key, GroovyExpression rowMapExpr) { rowMapExpr = new CastExpression(rowMapExpr, "Map"); GroovyExpression getExpr = new FunctionCallExpression(rowMapExpr, "get", key); return getExpr; } @Override public GroovyExpression getCurrentTraverserObject(GroovyExpression traverser) { return new FunctionCallExpression(traverser, "get"); } public List<String> getAliasesRequiredByExpression(GroovyExpression expr) { return Collections.emptyList(); } @Override public boolean isRepeatExpression(GroovyExpression expr) { if(!(expr instanceof FunctionCallExpression)) { return false; } return ((FunctionCallExpression)expr).getFunctionName().equals(REPEAT_METHOD); } } <|start_filename|>graphdb/titan1/src/main/java/org/apache/atlas/repository/graphdb/titan1/query/NativeTitan1GraphQuery.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan1.query; import com.thinkaurelius.titan.core.TitanEdge; import com.thinkaurelius.titan.core.TitanGraphQuery; import com.thinkaurelius.titan.core.TitanVertex; import com.thinkaurelius.titan.core.attribute.Contain; import com.thinkaurelius.titan.core.attribute.Text; import com.thinkaurelius.titan.graphdb.query.TitanPredicate; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasGraphQuery.ComparisionOperator; import org.apache.atlas.repository.graphdb.AtlasGraphQuery.MatchingOperator; import org.apache.atlas.repository.graphdb.AtlasGraphQuery.QueryOperator; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.repository.graphdb.titan.query.NativeTitanGraphQuery; import org.apache.atlas.repository.graphdb.titan1.Titan1Edge; import org.apache.atlas.repository.graphdb.titan1.Titan1Graph; import org.apache.atlas.repository.graphdb.titan1.Titan1GraphDatabase; import org.apache.atlas.repository.graphdb.titan1.Titan1Vertex; import org.apache.tinkerpop.gremlin.process.traversal.Compare; import org.apache.tinkerpop.gremlin.structure.Vertex; import java.util.*; /** * Titan 1.0.0 implementation of NativeTitanGraphQuery. */ public class NativeTitan1GraphQuery implements NativeTitanGraphQuery<Titan1Vertex, Titan1Edge> { private Titan1Graph graph; private TitanGraphQuery<?> query; public NativeTitan1GraphQuery(Titan1Graph graph) { this.query = Titan1GraphDatabase.getGraphInstance().query(); this.graph = graph; } @Override public Iterable<AtlasVertex<Titan1Vertex, Titan1Edge>> vertices() { Iterable<TitanVertex> it = query.vertices(); return graph.wrapVertices(it); } @Override public Iterable<AtlasEdge<Titan1Vertex, Titan1Edge>> edges() { Iterable<TitanEdge> it = query.edges(); return graph.wrapEdges(it); } @Override public Iterable<AtlasVertex<Titan1Vertex, Titan1Edge>> vertices(int limit) { Iterable<TitanVertex> it = query.limit(limit).vertices(); return graph.wrapVertices(it); } @Override public Iterable<AtlasVertex<Titan1Vertex, Titan1Edge>> vertices(int offset, int limit) { List<Vertex> result = new ArrayList<>(limit); Iterator<? extends Vertex> iter = query.limit(offset + limit).vertices().iterator(); for (long resultIdx = 0; iter.hasNext() && result.size() < limit; resultIdx++) { if (resultIdx < offset) { continue; } result.add(iter.next()); } return graph.wrapVertices(result); } @Override public void in(String propertyName, Collection<? extends Object> values) { query.has(propertyName, Contain.IN, values); } @Override public void has(String propertyName, QueryOperator op, Object value) { TitanPredicate pred; if (op instanceof ComparisionOperator) { Compare c = getGremlinPredicate((ComparisionOperator) op); pred = TitanPredicate.Converter.convert(c); } else { pred = getGremlinPredicate((MatchingOperator)op); } query.has(propertyName, pred, value); } private Text getGremlinPredicate(MatchingOperator op) { switch (op) { case CONTAINS: return Text.CONTAINS; case PREFIX: return Text.PREFIX; case SUFFIX: return Text.CONTAINS_REGEX; case REGEX: return Text.REGEX; default: throw new RuntimeException("Unsupported matching operator:" + op); } } private Compare getGremlinPredicate(ComparisionOperator op) { switch (op) { case EQUAL: return Compare.eq; case GREATER_THAN: return Compare.gt; case GREATER_THAN_EQUAL: return Compare.gte; case LESS_THAN: return Compare.lt; case LESS_THAN_EQUAL: return Compare.lte; case NOT_EQUAL: return Compare.neq; default: throw new RuntimeException("Unsupported comparison operator:" + op); } } } <|start_filename|>repository/src/test/java/org/apache/atlas/util/CompiledQueryCacheKeyTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.util; import org.apache.atlas.query.QueryParams; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotSame; /** * Tests hashcode/equals behavior of CompiledQueryCacheKey * * */ public class CompiledQueryCacheKeyTest { @Test public void testNoQueryParams() { CompiledQueryCacheKey e1 = new CompiledQueryCacheKey("query 1"); CompiledQueryCacheKey e2 = new CompiledQueryCacheKey("query 1"); CompiledQueryCacheKey e3 = new CompiledQueryCacheKey("query 2"); assertKeysEqual(e1, e2); assertKeysDifferent(e2, e3); } @Test public void testWithQueryParams() { CompiledQueryCacheKey e1 = new CompiledQueryCacheKey("query 1", new QueryParams(10,10)); CompiledQueryCacheKey e2 = new CompiledQueryCacheKey("query 1", new QueryParams(10,10)); CompiledQueryCacheKey e3 = new CompiledQueryCacheKey("query 2", new QueryParams(10,10)); assertKeysEqual(e1, e2); assertKeysDifferent(e2, e3); } @Test public void testOnlyQueryParamsDifferent() { CompiledQueryCacheKey e1 = new CompiledQueryCacheKey("query 1", new QueryParams(10,10)); CompiledQueryCacheKey e2 = new CompiledQueryCacheKey("query 1", new QueryParams(20,10)); assertKeysDifferent(e1, e2); } @Test public void testOnlyDslDifferent() { CompiledQueryCacheKey e1 = new CompiledQueryCacheKey("query 1", new QueryParams(10,10)); CompiledQueryCacheKey e2 = new CompiledQueryCacheKey("query 2", new QueryParams(10,10)); assertKeysDifferent(e1, e2); } @Test public void testMixOfQueryParamsAndNone() { CompiledQueryCacheKey e1 = new CompiledQueryCacheKey("query 1", new QueryParams(10,10)); CompiledQueryCacheKey e2 = new CompiledQueryCacheKey("query 1"); assertKeysDifferent(e1, e2); } private void assertKeysEqual(CompiledQueryCacheKey e1, CompiledQueryCacheKey e2) { assertEquals(e1.hashCode(), e2.hashCode()); assertEquals(e1, e2); assertEquals(e2, e1); } private void assertKeysDifferent(CompiledQueryCacheKey e1, CompiledQueryCacheKey e2) { assertNotSame(e1.hashCode(), e2.hashCode()); assertNotSame(e1, e2); assertNotSame(e2, e1); } } <|start_filename|>typesystem/src/main/java/org/apache/atlas/typesystem/types/TypeSystem.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.typesystem.types; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import org.apache.atlas.AtlasException; import org.apache.atlas.classification.InterfaceAudience; import org.apache.atlas.typesystem.TypesDef; import org.apache.atlas.typesystem.exception.TypeExistsException; import org.apache.atlas.typesystem.exception.TypeNotFoundException; import org.apache.atlas.typesystem.types.cache.DefaultTypeCache; import org.apache.atlas.typesystem.types.cache.TypeCache; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Singleton; import java.lang.reflect.Constructor; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.concurrent.ConcurrentHashMap; @Singleton @InterfaceAudience.Private @Deprecated public class TypeSystem { private static final Logger LOG = LoggerFactory.getLogger(TypeSystem.class); private static final TypeSystem INSTANCE = new TypeSystem(); private static ThreadLocal<SimpleDateFormat> dateFormat = new ThreadLocal<SimpleDateFormat>() { @Override public SimpleDateFormat initialValue() { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); return dateFormat; } }; private TypeCache typeCache = new DefaultTypeCache(); private IdType idType; private Map<String, IDataType> coreTypes; public TypeSystem() { initialize(); } public static TypeSystem getInstance() { return INSTANCE; } /** * This is only used for testing purposes. Not intended for public use. */ @InterfaceAudience.Private public TypeSystem reset() { typeCache.clear(); // clear all entries in cache initialize(); return this; } public void setTypeCache(TypeCache typeCache) { this.typeCache = typeCache; } private void initialize() { coreTypes = new ConcurrentHashMap<>(); registerPrimitiveTypes(); registerCoreTypes(); } public ImmutableList<String> getCoreTypes() { return ImmutableList.copyOf(coreTypes.keySet()); } public ImmutableList<String> getTypeNames() throws AtlasException { List<String> typeNames = new ArrayList<>(typeCache.getAllTypeNames()); return ImmutableList.copyOf(typeNames); } public ImmutableList<String> getTypeNamesByCategory(final DataTypes.TypeCategory typeCategory) throws AtlasException { return getTypeNames(new HashMap<TypeCache.TYPE_FILTER, String>() {{ put(TypeCache.TYPE_FILTER.CATEGORY, typeCategory.name()); }}); } public ImmutableList<String> getTypeNames(Map<TypeCache.TYPE_FILTER, String> filterMap) throws AtlasException { return ImmutableList.copyOf(typeCache.getTypeNames(filterMap)); } private void registerPrimitiveTypes() { coreTypes.put(DataTypes.BOOLEAN_TYPE.getName(), DataTypes.BOOLEAN_TYPE); coreTypes.put(DataTypes.BYTE_TYPE.getName(), DataTypes.BYTE_TYPE); coreTypes.put(DataTypes.SHORT_TYPE.getName(), DataTypes.SHORT_TYPE); coreTypes.put(DataTypes.INT_TYPE.getName(), DataTypes.INT_TYPE); coreTypes.put(DataTypes.LONG_TYPE.getName(), DataTypes.LONG_TYPE); coreTypes.put(DataTypes.FLOAT_TYPE.getName(), DataTypes.FLOAT_TYPE); coreTypes.put(DataTypes.DOUBLE_TYPE.getName(), DataTypes.DOUBLE_TYPE); coreTypes.put(DataTypes.BIGINTEGER_TYPE.getName(), DataTypes.BIGINTEGER_TYPE); coreTypes.put(DataTypes.BIGDECIMAL_TYPE.getName(), DataTypes.BIGDECIMAL_TYPE); coreTypes.put(DataTypes.DATE_TYPE.getName(), DataTypes.DATE_TYPE); coreTypes.put(DataTypes.STRING_TYPE.getName(), DataTypes.STRING_TYPE); } /* * The only core OOB type we will define is the Struct to represent the Identity of an Instance. */ private void registerCoreTypes() { idType = new IdType(); coreTypes.put(idType.getStructType().getName(), idType.getStructType()); } public IdType getIdType() { return idType; } public boolean isRegistered(String typeName) throws AtlasException { return isCoreType(typeName) || typeCache.has(typeName); } protected boolean isCoreType(String typeName) { return coreTypes.containsKey(typeName); } public IDataType getDataType(String name) throws AtlasException { if (isCoreType(name)) { return coreTypes.get(name); } if (typeCache.has(name)) { return typeCache.get(name); } /* * is this an Array Type? */ String arrElemType = TypeUtils.parseAsArrayType(name); if (arrElemType != null) { IDataType dT = defineArrayType(getDataType(arrElemType)); return dT; } /* * is this a Map Type? */ String[] mapType = TypeUtils.parseAsMapType(name); if (mapType != null) { IDataType dT = defineMapType(getDataType(mapType[0]), getDataType(mapType[1])); return dT; } /* * Invoke cache callback to possibly obtain type from other storage. */ IDataType dT = typeCache.onTypeFault(name); if (dT != null) { return dT; } throw new TypeNotFoundException(String.format("Unknown datatype: %s", name)); } public <T extends IDataType> T getDataType(Class<T> cls, String name) throws AtlasException { try { IDataType dt = getDataType(name); return cls.cast(dt); } catch (ClassCastException cce) { throw new AtlasException(cce); } } public StructType defineStructType(String name, boolean errorIfExists, AttributeDefinition... attrDefs) throws AtlasException { return defineStructType(name, null, errorIfExists, attrDefs); } public StructType defineStructType(String name, String description, boolean errorIfExists, AttributeDefinition... attrDefs) throws AtlasException { StructTypeDefinition structDef = new StructTypeDefinition(name, description, attrDefs); defineTypes(ImmutableList.<EnumTypeDefinition>of(), ImmutableList.of(structDef), ImmutableList.<HierarchicalTypeDefinition<TraitType>>of(), ImmutableList.<HierarchicalTypeDefinition<ClassType>>of()); return getDataType(StructType.class, structDef.typeName); } /** * construct a temporary StructType for a Query Result. This is not registered in the * typeSystem. * The attributes in the typeDefinition can only reference permanent types. * @param name struct type name * @param attrDefs struct type definition * @return temporary struct type * @throws AtlasException */ public StructType defineQueryResultType(String name, Map<String, IDataType> tempTypes, AttributeDefinition... attrDefs) throws AtlasException { AttributeInfo[] infos = new AttributeInfo[attrDefs.length]; for (int i = 0; i < attrDefs.length; i++) { infos[i] = new AttributeInfo(this, attrDefs[i], tempTypes); } return new StructType(this, name, null, infos); } public TraitType defineTraitType(HierarchicalTypeDefinition<TraitType> traitDef) throws AtlasException { defineTypes(ImmutableList.<EnumTypeDefinition>of(), ImmutableList.<StructTypeDefinition>of(), ImmutableList.of(traitDef), ImmutableList.<HierarchicalTypeDefinition<ClassType>>of()); return getDataType(TraitType.class, traitDef.typeName); } public ClassType defineClassType(HierarchicalTypeDefinition<ClassType> classDef) throws AtlasException { defineTypes(ImmutableList.<EnumTypeDefinition>of(), ImmutableList.<StructTypeDefinition>of(), ImmutableList.<HierarchicalTypeDefinition<TraitType>>of(), ImmutableList.of(classDef)); return getDataType(ClassType.class, classDef.typeName); } public Map<String, IDataType> defineTraitTypes(HierarchicalTypeDefinition<TraitType>... traitDefs) throws AtlasException { TransientTypeSystem transientTypes = new TransientTypeSystem(ImmutableList.<EnumTypeDefinition>of(), ImmutableList.<StructTypeDefinition>of(), ImmutableList.copyOf(traitDefs), ImmutableList.<HierarchicalTypeDefinition<ClassType>>of()); return transientTypes.defineTypes(false); } public Map<String, IDataType> defineClassTypes(HierarchicalTypeDefinition<ClassType>... classDefs) throws AtlasException { TransientTypeSystem transientTypes = new TransientTypeSystem(ImmutableList.<EnumTypeDefinition>of(), ImmutableList.<StructTypeDefinition>of(), ImmutableList.<HierarchicalTypeDefinition<TraitType>>of(), ImmutableList.copyOf(classDefs)); return transientTypes.defineTypes(false); } public Map<String, IDataType> updateTypes(TypesDef typesDef) throws AtlasException { ImmutableList<EnumTypeDefinition> enumDefs = ImmutableList.copyOf(typesDef.enumTypesAsJavaList()); ImmutableList<StructTypeDefinition> structDefs = ImmutableList.copyOf(typesDef.structTypesAsJavaList()); ImmutableList<HierarchicalTypeDefinition<TraitType>> traitDefs = ImmutableList.copyOf(typesDef.traitTypesAsJavaList()); ImmutableList<HierarchicalTypeDefinition<ClassType>> classDefs = ImmutableList.copyOf(typesDef.classTypesAsJavaList()); TransientTypeSystem transientTypes = new TransientTypeSystem(enumDefs, structDefs, traitDefs, classDefs); return transientTypes.defineTypes(true); } public Map<String, IDataType> defineTypes(TypesDef typesDef) throws AtlasException { ImmutableList<EnumTypeDefinition> enumDefs = ImmutableList.copyOf(typesDef.enumTypesAsJavaList()); ImmutableList<StructTypeDefinition> structDefs = ImmutableList.copyOf(typesDef.structTypesAsJavaList()); ImmutableList<HierarchicalTypeDefinition<TraitType>> traitDefs = ImmutableList.copyOf(typesDef.traitTypesAsJavaList()); ImmutableList<HierarchicalTypeDefinition<ClassType>> classDefs = ImmutableList.copyOf(typesDef.classTypesAsJavaList()); return defineTypes(enumDefs, structDefs, traitDefs, classDefs); } public Map<String, IDataType> defineTypes(ImmutableList<EnumTypeDefinition> enumDefs, ImmutableList<StructTypeDefinition> structDefs, ImmutableList<HierarchicalTypeDefinition<TraitType>> traitDefs, ImmutableList<HierarchicalTypeDefinition<ClassType>> classDefs) throws AtlasException { TransientTypeSystem transientTypes = new TransientTypeSystem(enumDefs, structDefs, traitDefs, classDefs); return transientTypes.defineTypes(false); } public DataTypes.ArrayType defineArrayType(IDataType elemType) throws AtlasException { assert elemType != null; DataTypes.ArrayType dT = new DataTypes.ArrayType(elemType); return dT; } public DataTypes.MapType defineMapType(IDataType keyType, IDataType valueType) throws AtlasException { assert keyType != null; assert valueType != null; DataTypes.MapType dT = new DataTypes.MapType(keyType, valueType); return dT; } public EnumType defineEnumType(String name, EnumValue... values) throws AtlasException { return defineEnumType(new EnumTypeDefinition(name, values)); } public EnumType defineEnumType(String name, String description, EnumValue... values) throws AtlasException { return defineEnumType(new EnumTypeDefinition(name, description, values)); } public EnumType defineEnumType(EnumTypeDefinition eDef) throws AtlasException { assert eDef.name != null; if (isRegistered(eDef.name)) { throw new AtlasException(String.format("Redefinition of type %s not supported", eDef.name)); } EnumType eT = new EnumType(this, eDef.name, eDef.description, eDef.version, eDef.enumValues); typeCache.put(eT); return eT; } public SimpleDateFormat getDateFormat() { return dateFormat.get(); } public boolean allowNullsInCollections() { return false; } /** * Create an instance of {@link TransientTypeSystem} with the types defined in the {@link TypesDef}. * * As part of this, a set of verifications are run on the types defined. * @param typesDef The new list of types to be created or updated. * @param isUpdate True, if types are updated, false otherwise. * @return {@link TransientTypeSystem} that holds the newly added types. * @throws AtlasException */ public TransientTypeSystem createTransientTypeSystem(TypesDef typesDef, boolean isUpdate) throws AtlasException { ImmutableList<EnumTypeDefinition> enumDefs = ImmutableList.copyOf(typesDef.enumTypesAsJavaList()); ImmutableList<StructTypeDefinition> structDefs = ImmutableList.copyOf(typesDef.structTypesAsJavaList()); ImmutableList<HierarchicalTypeDefinition<TraitType>> traitDefs = ImmutableList.copyOf(typesDef.traitTypesAsJavaList()); ImmutableList<HierarchicalTypeDefinition<ClassType>> classDefs = ImmutableList.copyOf(typesDef.classTypesAsJavaList()); TransientTypeSystem transientTypeSystem = new TransientTypeSystem(enumDefs, structDefs, traitDefs, classDefs); transientTypeSystem.verifyTypes(isUpdate); return transientTypeSystem; } /** * Commit the given types to this {@link TypeSystem} instance. * * This step should be called only after the types have been committed to the backend stores successfully. * @param typesAdded newly added types. * @throws AtlasException */ public void commitTypes(Map<String, IDataType> typesAdded) throws AtlasException { for (Map.Entry<String, IDataType> typeEntry : typesAdded.entrySet()) { IDataType type = typeEntry.getValue(); //Add/replace the new type in the typesystem typeCache.put(type); } } public class TransientTypeSystem extends TypeSystem { final ImmutableList<StructTypeDefinition> structDefs; final ImmutableList<HierarchicalTypeDefinition<TraitType>> traitDefs; final ImmutableList<HierarchicalTypeDefinition<ClassType>> classDefs; private final ImmutableList<EnumTypeDefinition> enumDefs; Map<String, StructTypeDefinition> structNameToDefMap = new HashMap<>(); Map<String, HierarchicalTypeDefinition<TraitType>> traitNameToDefMap = new HashMap<>(); Map<String, HierarchicalTypeDefinition<ClassType>> classNameToDefMap = new HashMap<>(); Map<String, IDataType> transientTypes = null; List<AttributeInfo> recursiveRefs = new ArrayList<>(); List<DataTypes.ArrayType> recursiveArrayTypes = new ArrayList<>(); List<DataTypes.MapType> recursiveMapTypes = new ArrayList<>(); TransientTypeSystem(ImmutableList<EnumTypeDefinition> enumDefs, ImmutableList<StructTypeDefinition> structDefs, ImmutableList<HierarchicalTypeDefinition<TraitType>> traitDefs, ImmutableList<HierarchicalTypeDefinition<ClassType>> classDefs) { this.enumDefs = enumDefs; this.structDefs = structDefs; this.traitDefs = traitDefs; this.classDefs = classDefs; transientTypes = new HashMap<>(); } private IDataType dataType(String name) throws AtlasException { if (transientTypes.containsKey(name)) { return transientTypes.get(name); } return TypeSystem.this.getDataType(IDataType.class, name); } /* * Step 1: * - validate cannot redefine types * - setup shallow Type instances to facilitate recursive type graphs */ private void validateAndSetupShallowTypes(boolean update) throws AtlasException { for (EnumTypeDefinition eDef : enumDefs) { assert eDef.name != null; if (!update) { if (TypeSystem.this.isRegistered(eDef.name)) { throw new TypeExistsException(String.format("Redefinition of type %s is not supported", eDef.name)); } else if (transientTypes.containsKey(eDef.name)) { LOG.warn("Found duplicate definition of type {}. Ignoring..", eDef.name); continue; } } EnumType eT = new EnumType(this, eDef.name, eDef.description, eDef.version, eDef.enumValues); transientTypes.put(eDef.name, eT); } for (StructTypeDefinition sDef : structDefs) { assert sDef.typeName != null; if (!update) { if (TypeSystem.this.isRegistered(sDef.typeName)) { throw new TypeExistsException(String.format("Redefinition of type %s is not supported", sDef.typeName)); } else if (transientTypes.containsKey(sDef.typeName)) { LOG.warn("Found duplicate definition of type {}. Ignoring..", sDef.typeName); continue; } } StructType sT = new StructType(this, sDef.typeName, sDef.typeDescription, sDef.typeVersion, sDef.attributeDefinitions.length); structNameToDefMap.put(sDef.typeName, sDef); transientTypes.put(sDef.typeName, sT); } for (HierarchicalTypeDefinition<TraitType> traitDef : traitDefs) { assert traitDef.typeName != null; if (!update) { if (TypeSystem.this.isRegistered(traitDef.typeName)) { throw new TypeExistsException(String.format("Redefinition of type %s is not supported", traitDef.typeName)); } else if (transientTypes.containsKey(traitDef.typeName)) { LOG.warn("Found duplicate definition of type {}. Ignoring..", traitDef.typeName); continue; } } TraitType tT = new TraitType(this, traitDef.typeName, traitDef.typeDescription, traitDef.typeVersion, traitDef.superTypes, traitDef.attributeDefinitions.length); traitNameToDefMap.put(traitDef.typeName, traitDef); transientTypes.put(traitDef.typeName, tT); } for (HierarchicalTypeDefinition<ClassType> classDef : classDefs) { assert classDef.typeName != null; if (!update) { if (TypeSystem.this.isRegistered(classDef.typeName)) { throw new TypeExistsException(String.format("Redefinition of type %s is not supported", classDef.typeName)); } else if (transientTypes.containsKey(classDef.typeName)) { LOG.warn("Found duplicate definition of type {}. Ignoring..", classDef.typeName); continue; } } ClassType cT = new ClassType(this, classDef.typeName, classDef.typeDescription, classDef.typeVersion, classDef.superTypes, classDef.attributeDefinitions.length); classNameToDefMap.put(classDef.typeName, classDef); transientTypes.put(classDef.typeName, cT); } } @Override public boolean isRegistered(String typeName) throws AtlasException { return transientTypes.containsKey(typeName) || TypeSystem.this.isRegistered(typeName); } private <U extends HierarchicalType> void validateSuperTypes(Class<U> cls, HierarchicalTypeDefinition<U> def) throws AtlasException { for (String superTypeName : def.superTypes) { IDataType dT = dataType(superTypeName); if (dT == null) { throw new AtlasException( String.format("Unknown superType %s in definition of type %s", superTypeName, def.typeName)); } if (!cls.isAssignableFrom(dT.getClass())) { throw new AtlasException( String.format("SuperType %s must be a %s, in definition of type %s", superTypeName, cls.getName(), def.typeName)); } } } /* * Step 2: * - for Hierarchical Types, validate SuperTypes. * - for each Hierarchical Type setup their SuperTypes Graph */ private void validateAndSetupSuperTypes() throws AtlasException { for (HierarchicalTypeDefinition<TraitType> traitDef : traitDefs) { validateSuperTypes(TraitType.class, traitDef); TraitType traitType = getDataType(TraitType.class, traitDef.typeName); traitType.setupSuperTypesGraph(); } for (HierarchicalTypeDefinition<ClassType> classDef : classDefs) { validateSuperTypes(ClassType.class, classDef); ClassType classType = getDataType(ClassType.class, classDef.typeName); classType.setupSuperTypesGraph(); } } private AttributeInfo constructAttributeInfo(AttributeDefinition attrDef) throws AtlasException { AttributeInfo info = new AttributeInfo(this, attrDef, null); if (transientTypes.keySet().contains(attrDef.dataTypeName)) { recursiveRefs.add(info); } if (info.dataType().getTypeCategory() == DataTypes.TypeCategory.ARRAY) { DataTypes.ArrayType arrType = (DataTypes.ArrayType) info.dataType(); if (transientTypes.keySet().contains(arrType.getElemType().getName())) { recursiveArrayTypes.add(arrType); } } if (info.dataType().getTypeCategory() == DataTypes.TypeCategory.MAP) { DataTypes.MapType mapType = (DataTypes.MapType) info.dataType(); if (transientTypes.keySet().contains(mapType.getKeyType().getName())) { recursiveMapTypes.add(mapType); } else if (transientTypes.keySet().contains(mapType.getValueType().getName())) { recursiveMapTypes.add(mapType); } } if (info.multiplicity.upper > 1 && !(info.dataType().getTypeCategory() == DataTypes.TypeCategory.MAP || info.dataType().getTypeCategory() == DataTypes.TypeCategory.ARRAY)) { throw new AtlasException( String.format("A multiplicty of more than one requires a collection type for attribute '%s'", info.name)); } return info; } private StructType constructStructureType(StructTypeDefinition def) throws AtlasException { AttributeInfo[] infos = new AttributeInfo[def.attributeDefinitions.length]; for (int i = 0; i < def.attributeDefinitions.length; i++) { infos[i] = constructAttributeInfo(def.attributeDefinitions[i]); } StructType type = new StructType(this, def.typeName, def.typeDescription, def.typeVersion, infos); transientTypes.put(def.typeName, type); return type; } private <U extends HierarchicalType> U constructHierarchicalType(Class<U> cls, HierarchicalTypeDefinition<U> def) throws AtlasException { AttributeInfo[] infos = new AttributeInfo[def.attributeDefinitions.length]; for (int i = 0; i < def.attributeDefinitions.length; i++) { infos[i] = constructAttributeInfo(def.attributeDefinitions[i]); } try { Constructor<U> cons = cls.getDeclaredConstructor(TypeSystem.class, String.class, String.class, String.class, ImmutableSet.class, AttributeInfo[].class); U type = cons.newInstance(this, def.typeName, def.typeDescription, def.typeVersion, def.superTypes, infos); transientTypes.put(def.typeName, type); return type; } catch (Exception e) { e.printStackTrace(); throw new AtlasException(String.format("Cannot construct Type of MetaType %s - %s", cls.getName(), def.typeName), e); } } /* * Step 3: * - Order Hierarchical Types in order of SuperType before SubType. * - Construct all the Types */ private void orderAndConstructTypes() throws AtlasException { List<TraitType> traitTypes = new ArrayList<>(); for (String traitTypeName : traitNameToDefMap.keySet()) { traitTypes.add(getDataType(TraitType.class, traitTypeName)); } traitTypes = HierarchicalTypeDependencySorter.sortTypes(traitTypes); List<ClassType> classTypes = new ArrayList<>(); for (String classTypeName : classNameToDefMap.keySet()) { classTypes.add(getDataType(ClassType.class, classTypeName)); } classTypes = HierarchicalTypeDependencySorter.sortTypes(classTypes); for (StructTypeDefinition structDef : structDefs) { constructStructureType(structDef); } for (TraitType traitType : traitTypes) { constructHierarchicalType(TraitType.class, traitNameToDefMap.get(traitType.getName())); } for (ClassType classType : classTypes) { constructHierarchicalType(ClassType.class, classNameToDefMap.get(classType.getName())); } } /* * Step 4: * - fix up references in recursive AttrInfo and recursive Collection Types. */ private void setupRecursiveTypes() throws AtlasException { for (AttributeInfo info : recursiveRefs) { info.setDataType(dataType(info.dataType().getName())); } for (DataTypes.ArrayType arrType : recursiveArrayTypes) { arrType.setElemType(dataType(arrType.getElemType().getName())); } for (DataTypes.MapType mapType : recursiveMapTypes) { mapType.setKeyType(dataType(mapType.getKeyType().getName())); mapType.setValueType(dataType(mapType.getValueType().getName())); } } /** * Step 5: * - Validate that the update can be done */ private void validateUpdateIsPossible() throws TypeUpdateException, AtlasException { //If the type is modified, validate that update can be done for (IDataType newType : transientTypes.values()) { IDataType oldType = null; try { oldType = TypeSystem.this.getDataType(IDataType.class, newType.getName()); } catch (TypeNotFoundException e) { LOG.debug(String.format("No existing type %s found - update OK", newType.getName())); } if (oldType != null) { oldType.validateUpdate(newType); } } } Map<String, IDataType> defineTypes(boolean update) throws AtlasException { verifyTypes(update); Map<String, IDataType> typesAdded = getTypesAdded(); commitTypes(typesAdded); return typesAdded; } @Override public ImmutableList<String> getTypeNames() throws AtlasException { Set<String> typeNames = transientTypes.keySet(); typeNames.addAll(TypeSystem.this.getTypeNames()); return ImmutableList.copyOf(typeNames); } //get from transient types. Else, from main type system @Override public IDataType getDataType(String name) throws AtlasException { if (transientTypes != null) { if (transientTypes.containsKey(name)) { return transientTypes.get(name); } /* * is this an Array Type? */ String arrElemType = TypeUtils.parseAsArrayType(name); if (arrElemType != null) { IDataType dT = defineArrayType(getDataType(IDataType.class, arrElemType)); return dT; } /* * is this a Map Type? */ String[] mapType = TypeUtils.parseAsMapType(name); if (mapType != null) { IDataType dT = defineMapType(getDataType(IDataType.class, mapType[0]), getDataType(IDataType.class, mapType[1])); return dT; } } return TypeSystem.this.getDataType(name); } @Override public StructType defineStructType(String name, boolean errorIfExists, AttributeDefinition... attrDefs) throws AtlasException { throw new AtlasException("Internal Error: define type called on TransientTypeSystem"); } @Override public TraitType defineTraitType(HierarchicalTypeDefinition traitDef) throws AtlasException { throw new AtlasException("Internal Error: define type called on TransientTypeSystem"); } @Override public ClassType defineClassType(HierarchicalTypeDefinition<ClassType> classDef) throws AtlasException { throw new AtlasException("Internal Error: define type called on TransientTypeSystem"); } @Override public Map<String, IDataType> defineTypes(ImmutableList<EnumTypeDefinition> enumDefs, ImmutableList<StructTypeDefinition> structDefs, ImmutableList<HierarchicalTypeDefinition<TraitType>> traitDefs, ImmutableList<HierarchicalTypeDefinition<ClassType>> classDefs) throws AtlasException { throw new AtlasException("Internal Error: define type called on TransientTypeSystem"); } @Override public DataTypes.ArrayType defineArrayType(IDataType elemType) throws AtlasException { return super.defineArrayType(elemType); } @Override public DataTypes.MapType defineMapType(IDataType keyType, IDataType valueType) throws AtlasException { return super.defineMapType(keyType, valueType); } void verifyTypes(boolean isUpdate) throws AtlasException { validateAndSetupShallowTypes(isUpdate); validateAndSetupSuperTypes(); orderAndConstructTypes(); setupRecursiveTypes(); if (isUpdate) { validateUpdateIsPossible(); } } @Override public void commitTypes(Map<String, IDataType> typesAdded) throws AtlasException { TypeSystem.this.commitTypes(typesAdded); } public Map<String, IDataType> getTypesAdded() { return new HashMap<>(transientTypes); } /** * The core types do not change and they are registered * once in the main type system. */ @Override public ImmutableList<String> getCoreTypes() { return TypeSystem.this.getCoreTypes(); } } public class IdType { private static final String ID_ATTRNAME = "guid"; private static final String TYPENAME_ATTRNAME = "typeName"; private static final String STATE_ATTRNAME = "state"; private static final String VERSION_ATTRNAME = "version"; private static final String TYP_NAME = "__IdType"; private StructType type; private IdType() { AttributeDefinition idAttr = new AttributeDefinition(ID_ATTRNAME, DataTypes.STRING_TYPE.getName(), Multiplicity.REQUIRED, false, null); AttributeDefinition typNmAttr = new AttributeDefinition(TYPENAME_ATTRNAME, DataTypes.STRING_TYPE.getName(), Multiplicity.REQUIRED, false, null); AttributeDefinition stateAttr = new AttributeDefinition(STATE_ATTRNAME, DataTypes.STRING_TYPE.getName(), Multiplicity.REQUIRED, false, null); AttributeDefinition versionAttr = new AttributeDefinition(VERSION_ATTRNAME, DataTypes.INT_TYPE.getName(), Multiplicity.REQUIRED, false, null); try { AttributeInfo[] infos = new AttributeInfo[4]; infos[0] = new AttributeInfo(TypeSystem.this, idAttr, null); infos[1] = new AttributeInfo(TypeSystem.this, typNmAttr, null); infos[2] = new AttributeInfo(TypeSystem.this, stateAttr, null); infos[3] = new AttributeInfo(TypeSystem.this, versionAttr, null); type = new StructType(TypeSystem.this, TYP_NAME, null, infos); } catch (AtlasException me) { throw new RuntimeException(me); } } public StructType getStructType() { return type; } public String getName() { return TYP_NAME; } public String idAttrName() { return ID_ATTRNAME; } public String typeNameAttrName() { return TYPENAME_ATTRNAME; } public String stateAttrName() { return STATE_ATTRNAME; } public String versionAttrName() { return VERSION_ATTRNAME; } } public static final String ID_STRUCT_ID_ATTRNAME = IdType.ID_ATTRNAME; public static final String ID_STRUCT_TYP_NAME = IdType.TYP_NAME; } <|start_filename|>repository/src/test/java/org/apache/atlas/TestModules.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas; import com.google.inject.AbstractModule; import com.google.inject.Binder; import com.google.inject.Provider; import com.google.inject.Singleton; import com.google.inject.matcher.Matchers; import com.google.inject.multibindings.Multibinder; import org.apache.atlas.annotation.GraphTransaction; import org.apache.atlas.discovery.*; import org.apache.atlas.discovery.graph.GraphBackedDiscoveryService; import org.apache.atlas.graph.GraphSandboxUtil; import org.apache.atlas.listener.EntityChangeListener; import org.apache.atlas.listener.TypeDefChangeListener; import org.apache.atlas.listener.TypesChangeListener; import org.apache.atlas.repository.MetadataRepository; import org.apache.atlas.repository.audit.EntityAuditListener; import org.apache.atlas.repository.audit.EntityAuditRepository; import org.apache.atlas.repository.graph.DeleteHandler; import org.apache.atlas.repository.graph.GraphBackedMetadataRepository; import org.apache.atlas.repository.graph.GraphBackedSearchIndexer; import org.apache.atlas.repository.graph.HardDeleteHandler; import org.apache.atlas.repository.graph.SoftDeleteHandler; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.impexp.ExportService; import org.apache.atlas.repository.store.graph.AtlasEntityDefStore; import org.apache.atlas.repository.store.graph.AtlasEntityStore; import org.apache.atlas.repository.store.graph.AtlasRelationshipDefStore; import org.apache.atlas.repository.store.graph.AtlasRelationshipStore; import org.apache.atlas.repository.store.graph.v1.*; import org.apache.atlas.repository.typestore.GraphBackedTypeStore; import org.apache.atlas.repository.typestore.ITypeStore; import org.apache.atlas.repository.typestore.StoreBackedTypeCache; import org.apache.atlas.service.Service; import org.apache.atlas.services.DefaultMetadataService; import org.apache.atlas.services.MetadataService; import org.apache.atlas.store.AtlasTypeDefStore; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.typesystem.types.TypeSystem; import org.apache.atlas.typesystem.types.cache.TypeCache; import org.apache.atlas.util.AtlasRepositoryConfiguration; import org.apache.atlas.util.SearchTracker; import org.apache.commons.configuration.Configuration; import org.mockito.Mockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestModules { static class MockNotifier implements Provider<AtlasEntityChangeNotifier> { @Override public AtlasEntityChangeNotifier get() { return Mockito.mock(AtlasEntityChangeNotifier.class); } } // Test only DI modules public static class TestOnlyModule extends AbstractModule { private static final Logger LOG = LoggerFactory.getLogger(TestOnlyModule.class); static class TypeSystemProvider implements Provider<TypeSystem> { @Override public TypeSystem get() { return TypeSystem.getInstance(); } } static class AtlasConfigurationProvider implements Provider<Configuration> { @Override public Configuration get() { try { return ApplicationProperties.get(); } catch (AtlasException e) { throw new RuntimeException(e); } } } static class AtlasGraphProvider implements Provider<AtlasGraph> { @Override public AtlasGraph get() { return org.apache.atlas.repository.graph.AtlasGraphProvider.getGraphInstance(); } } @Override protected void configure() { GraphSandboxUtil.create(); bindAuditRepository(binder()); bindDeleteHandler(binder()); bind(AtlasGraph.class).toProvider(AtlasGraphProvider.class); // allow for dynamic binding of the metadata repo & graph service // bind the MetadataRepositoryService interface to an implementation bind(MetadataRepository.class).to(GraphBackedMetadataRepository.class).asEagerSingleton(); bind(TypeSystem.class).toProvider(TypeSystemProvider.class).in(Singleton.class); bind(Configuration.class).toProvider(AtlasConfigurationProvider.class).in(Singleton.class); // bind the ITypeStore interface to an implementation bind(ITypeStore.class).to(GraphBackedTypeStore.class).asEagerSingleton(); bind(AtlasTypeDefStore.class).to(AtlasTypeDefGraphStoreV1.class).asEagerSingleton(); //For testing bind(AtlasEntityDefStore.class).to(AtlasEntityDefStoreV1.class).asEagerSingleton(); bind(AtlasRelationshipDefStore.class).to(AtlasRelationshipDefStoreV1.class).asEagerSingleton(); bind(AtlasTypeRegistry.class).asEagerSingleton(); bind(EntityGraphMapper.class).asEagerSingleton(); bind(ExportService.class).asEagerSingleton(); //GraphBackedSearchIndexer must be an eager singleton to force the search index creation to happen before //we try to restore the type system (otherwise we'll end up running queries //before we have any indices during the initial graph setup) Multibinder<TypesChangeListener> typesChangeListenerBinder = Multibinder.newSetBinder(binder(), TypesChangeListener.class); typesChangeListenerBinder.addBinding().to(GraphBackedSearchIndexer.class).asEagerSingleton(); // New typesdef/instance change listener should also be bound to the corresponding implementation Multibinder<TypeDefChangeListener> typeDefChangeListenerMultibinder = Multibinder.newSetBinder(binder(), TypeDefChangeListener.class); typeDefChangeListenerMultibinder.addBinding().to(DefaultMetadataService.class); typeDefChangeListenerMultibinder.addBinding().to(GraphBackedSearchIndexer.class).asEagerSingleton(); bind(SearchTracker.class).asEagerSingleton(); bind(AtlasEntityStore.class).to(AtlasEntityStoreV1.class); bind(AtlasRelationshipStore.class).to(AtlasRelationshipStoreV1.class); // bind the MetadataService interface to an implementation bind(MetadataService.class).to(DefaultMetadataService.class).asEagerSingleton(); // bind the DiscoveryService interface to an implementation bind(DiscoveryService.class).to(GraphBackedDiscoveryService.class).asEagerSingleton(); bind(AtlasDiscoveryService.class).to(EntityDiscoveryService.class).asEagerSingleton(); bind(LineageService.class).to(DataSetLineageService.class).asEagerSingleton(); bind(AtlasLineageService.class).to(EntityLineageService.class).asEagerSingleton(); bindTypeCache(); //Add EntityAuditListener as EntityChangeListener Multibinder<EntityChangeListener> entityChangeListenerBinder = Multibinder.newSetBinder(binder(), EntityChangeListener.class); entityChangeListenerBinder.addBinding().to(EntityAuditListener.class); final GraphTransactionInterceptor graphTransactionInterceptor = new GraphTransactionInterceptor(new AtlasGraphProvider().get()); requestInjection(graphTransactionInterceptor); bindInterceptor(Matchers.any(), Matchers.annotatedWith(GraphTransaction.class), graphTransactionInterceptor); } protected void bindTypeCache() { bind(TypeCache.class).to(AtlasRepositoryConfiguration.getTypeCache()).asEagerSingleton(); } protected void bindDeleteHandler(Binder binder) { binder.bind(DeleteHandler.class).to(AtlasRepositoryConfiguration.getDeleteHandlerImpl()).asEagerSingleton(); binder.bind(DeleteHandlerV1.class).to(AtlasRepositoryConfiguration.getDeleteHandlerV1Impl()).asEagerSingleton(); } protected void bindAuditRepository(Binder binder) { Class<? extends EntityAuditRepository> auditRepoImpl = AtlasRepositoryConfiguration.getAuditRepositoryImpl(); //Map EntityAuditRepository interface to configured implementation binder.bind(EntityAuditRepository.class).to(auditRepoImpl).asEagerSingleton(); if(Service.class.isAssignableFrom(auditRepoImpl)) { Class<? extends Service> auditRepoService = (Class<? extends Service>)auditRepoImpl; //if it's a service, make sure that it gets properly closed at shutdown Multibinder<Service> serviceBinder = Multibinder.newSetBinder(binder, Service.class); serviceBinder.addBinding().to(auditRepoService); } } } public static class SoftDeleteModule extends TestOnlyModule { @Override protected void bindDeleteHandler(Binder binder) { bind(DeleteHandler.class).to(SoftDeleteHandler.class).asEagerSingleton(); bind(DeleteHandlerV1.class).to(SoftDeleteHandlerV1.class).asEagerSingleton(); bind(AtlasEntityChangeNotifier.class).toProvider(MockNotifier.class); } } public static class HardDeleteModule extends TestOnlyModule { @Override protected void bindDeleteHandler(Binder binder) { bind(DeleteHandler.class).to(HardDeleteHandler.class).asEagerSingleton(); bind(DeleteHandlerV1.class).to(HardDeleteHandlerV1.class).asEagerSingleton(); bind(AtlasEntityChangeNotifier.class).toProvider(MockNotifier.class); } } /** * Guice module which sets TypeCache implementation class configuration property to {@link StoreBackedTypeCache}. * */ public static class StoreBackedTypeCacheTestModule extends TestOnlyModule { @Override protected void bindTypeCache() { bind(TypeCache.class).to(StoreBackedTypeCache.class).asEagerSingleton(); } } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/memory/HierarchicalTypeStore.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.memory; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.apache.atlas.repository.RepositoryException; import org.apache.atlas.typesystem.persistence.Id; import org.apache.atlas.typesystem.persistence.ReferenceableInstance; import org.apache.atlas.typesystem.persistence.StructInstance; import org.apache.atlas.typesystem.types.AttributeInfo; import org.apache.atlas.typesystem.types.HierarchicalType; import org.apache.atlas.typesystem.types.IConstructableType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.locks.ReentrantReadWriteLock; @Deprecated public abstract class HierarchicalTypeStore { final MemRepository repository; final IConstructableType hierarchicalType; final ArrayList<String> typeNameList; final ImmutableMap<AttributeInfo, IAttributeStore> attrStores; final ImmutableList<HierarchicalTypeStore> superTypeStores; /** * Map Id to position in storage lists. */ Map<Id, Integer> idPosMap; List<Integer> freePositions; int nextPos; /** * Lock for each Class/Trait. */ ReentrantReadWriteLock lock; HierarchicalTypeStore(MemRepository repository, HierarchicalType hierarchicalType) throws RepositoryException { this.hierarchicalType = (IConstructableType) hierarchicalType; this.repository = repository; ImmutableMap.Builder<AttributeInfo, IAttributeStore> b = new ImmutableBiMap.Builder<>(); typeNameList = Lists.newArrayList((String) null); ImmutableList<AttributeInfo> l = hierarchicalType.immediateAttrs; for (AttributeInfo i : l) { b.put(i, AttributeStores.createStore(i)); } attrStores = b.build(); ImmutableList.Builder<HierarchicalTypeStore> b1 = new ImmutableList.Builder<>(); Set<String> allSuperTypeNames = hierarchicalType.getAllSuperTypeNames(); for (String s : allSuperTypeNames) { b1.add(repository.getStore(s)); } superTypeStores = b1.build(); nextPos = 0; idPosMap = new HashMap<>(); freePositions = new ArrayList<>(); lock = new ReentrantReadWriteLock(); } /** * Assign a storage position to an Id. * - try to assign from freePositions * - ensure storage capacity. * - add entry in idPosMap. * @param id * @return * @throws RepositoryException */ int assignPosition(Id id) throws RepositoryException { int pos = -1; if (!freePositions.isEmpty()) { pos = freePositions.remove(0); } else { pos = nextPos++; ensureCapacity(pos); } idPosMap.put(id, pos); for (HierarchicalTypeStore s : superTypeStores) { s.assignPosition(id); } return pos; } /** * - remove from idPosMap * - add to freePositions. * @throws RepositoryException */ void releaseId(Id id) { Integer pos = idPosMap.get(id); if (pos != null) { idPosMap.remove(id); freePositions.add(pos); for (HierarchicalTypeStore s : superTypeStores) { s.releaseId(id); } } } void acquireReadLock() { lock.readLock().lock(); } void acquireWriteLock() { lock.writeLock().lock(); } void releaseReadLock() { lock.readLock().unlock(); } void releaseWriteLock() { lock.writeLock().unlock(); } protected void storeFields(int pos, StructInstance s) throws RepositoryException { for (Map.Entry<AttributeInfo, IAttributeStore> e : attrStores.entrySet()) { IAttributeStore attributeStore = e.getValue(); attributeStore.store(pos, hierarchicalType, s); } } protected void loadFields(int pos, StructInstance s) throws RepositoryException { for (Map.Entry<AttributeInfo, IAttributeStore> e : attrStores.entrySet()) { IAttributeStore attributeStore = e.getValue(); attributeStore.load(pos, hierarchicalType, s); } } /** * - store the typeName * - store the immediate attributes in the respective IAttributeStore * - call store on each SuperType. * @param i * @throws RepositoryException */ void store(ReferenceableInstance i) throws RepositoryException { int pos = idPosMap.get(i.getId()); typeNameList.set(pos, i.getTypeName()); storeFields(pos, i); for (HierarchicalTypeStore s : superTypeStores) { s.store(i); } } /** * - copy over the immediate attribute values from the respective IAttributeStore * - call load on each SuperType. * @param i * @throws RepositoryException */ void load(ReferenceableInstance i) throws RepositoryException { int pos = idPosMap.get(i.getId()); loadFields(pos, i); for (HierarchicalTypeStore s : superTypeStores) { s.load(i); } } public void ensureCapacity(int pos) throws RepositoryException { while (typeNameList.size() < pos + 1) { typeNameList.add(null); } for (Map.Entry<AttributeInfo, IAttributeStore> e : attrStores.entrySet()) { IAttributeStore attributeStore = e.getValue(); attributeStore.ensureCapacity(pos); } } } <|start_filename|>graphdb/titan0/src/main/java/org/apache/atlas/repository/graphdb/titan0/Titan0GraphManagement.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan0; import com.thinkaurelius.titan.core.Cardinality; import com.thinkaurelius.titan.core.PropertyKey; import com.thinkaurelius.titan.core.schema.Mapping; import com.thinkaurelius.titan.core.schema.PropertyKeyMaker; import com.thinkaurelius.titan.core.schema.TitanGraphIndex; import com.thinkaurelius.titan.core.schema.TitanManagement; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.Vertex; import org.apache.atlas.repository.graphdb.AtlasCardinality; import org.apache.atlas.repository.graphdb.AtlasGraphIndex; import org.apache.atlas.repository.graphdb.AtlasGraphManagement; import org.apache.atlas.repository.graphdb.AtlasPropertyKey; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Titan 0.5.4 implementation of AtlasGraphManagement. */ public class Titan0GraphManagement implements AtlasGraphManagement { private static final Logger LOG = LoggerFactory.getLogger(Titan0GraphManagement.class); private final Titan0Graph graph; private final TitanManagement management; private Set<String> newMultProperties = new HashSet<>(); public Titan0GraphManagement(Titan0Graph graph, TitanManagement managementSystem) { this.graph = graph; management = managementSystem; } @Override public void createEdgeIndex(String index, String backingIndex) { buildMixedIndex(index, Edge.class, backingIndex); } private void buildMixedIndex(String index, Class<? extends Element> titanClass, String backingIndex) { management.buildIndex(index, titanClass).buildMixedIndex(backingIndex); } @Override public void createFullTextIndex(String indexName, AtlasPropertyKey propertyKey, String backingIndex) { PropertyKey fullText = TitanObjectFactory.createPropertyKey(propertyKey); management.buildIndex(indexName, Vertex.class) .addKey(fullText, com.thinkaurelius.titan.core.schema.Parameter.of("mapping", Mapping.TEXT)) .buildMixedIndex(backingIndex); } @Override public boolean containsPropertyKey(String propertyKey) { return management.containsPropertyKey(propertyKey); } @Override public void rollback() { management.rollback(); } @Override public void commit() { graph.addMultiProperties(newMultProperties); newMultProperties.clear(); management.commit(); } @Override public AtlasPropertyKey makePropertyKey(String propertyName, Class propertyClass, AtlasCardinality cardinality) { if (cardinality.isMany()) { newMultProperties.add(propertyName); } PropertyKeyMaker propertyKeyBuilder = management.makePropertyKey(propertyName).dataType(propertyClass); if (cardinality != null) { Cardinality titanCardinality = TitanObjectFactory.createCardinality(cardinality); propertyKeyBuilder.cardinality(titanCardinality); } PropertyKey propertyKey = propertyKeyBuilder.make(); return GraphDbObjectFactory.createPropertyKey(propertyKey); } @Override public void deletePropertyKey(String propertyKey) { PropertyKey titanPropertyKey = management.getPropertyKey(propertyKey); if (null == titanPropertyKey) return; for (int i = 0;; i++) { String deletedKeyName = titanPropertyKey + "_deleted_" + i; if (null == management.getPropertyKey(deletedKeyName)) { management.changeName(titanPropertyKey, deletedKeyName); break; } } } @Override public AtlasPropertyKey getPropertyKey(String propertyName) { return GraphDbObjectFactory.createPropertyKey(management.getPropertyKey(propertyName)); } @Override public void createExactMatchIndex(String propertyName, boolean enforceUniqueness, List<AtlasPropertyKey> propertyKeys) { TitanManagement.IndexBuilder indexBuilder = management.buildIndex(propertyName, Vertex.class); for(AtlasPropertyKey key : propertyKeys) { PropertyKey titanKey = TitanObjectFactory.createPropertyKey(key); indexBuilder.addKey(titanKey); } if (enforceUniqueness) { indexBuilder.unique(); } indexBuilder.buildCompositeIndex(); } @Override public void createVertexIndex(String propertyName, String backingIndex, List<AtlasPropertyKey> propertyKeys) { TitanManagement.IndexBuilder indexBuilder = management.buildIndex(propertyName, Vertex.class); for(AtlasPropertyKey key : propertyKeys) { PropertyKey titanKey = TitanObjectFactory.createPropertyKey(key); indexBuilder.addKey(titanKey); } indexBuilder.buildMixedIndex(backingIndex); } @Override public void addVertexIndexKey(String indexName, AtlasPropertyKey propertyKey) { PropertyKey titanKey = TitanObjectFactory.createPropertyKey(propertyKey); TitanGraphIndex vertexIndex = management.getGraphIndex(indexName); management.addIndexKey(vertexIndex, titanKey); } /* * (non-Javadoc) * * @see * org.apache.atlas.repository.graphdb.AtlasGraphManagement#getGraphIndex( * java.lang.String) */ @Override public AtlasGraphIndex getGraphIndex(String indexName) { TitanGraphIndex index = management.getGraphIndex(indexName); return GraphDbObjectFactory.createGraphIndex(index); } } <|start_filename|>repository/src/test/java/org/apache/atlas/utils/HiveModel.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.utils; import org.apache.atlas.TestUtils; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.Struct; import org.apache.atlas.typesystem.persistence.Id; import org.apache.atlas.typesystem.types.ClassType; import org.apache.atlas.typesystem.types.Multiplicity; import org.apache.atlas.typesystem.types.TypeSystem; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; /** * Allows easy creation of entities for classes in the hive test model. * */ public class HiveModel { public static class StructInstance { public String getTypeName() { return getClass().getSimpleName(); } public Struct toStruct() throws Exception { Struct entity = new Struct(getTypeName()); addDeclaredFields(getClass(), entity); return entity; } protected void addDeclaredFields(Class clazz, Struct r) throws Exception { for (Field f : clazz.getDeclaredFields()) { if (Modifier.isTransient(f.getModifiers())) { continue; } String fieldName = f.getName(); f.setAccessible(true); Object value = f.get(this); if (value instanceof List) { List listValue = (List) value; List toSet = new ArrayList(listValue.size()); for (Object listItem : listValue) { Object toAdd = null; toAdd = convertValue(listItem); toSet.add(toAdd); } r.set(fieldName, toSet); } else { Object converted = convertValue(value); r.set(fieldName, converted); } } if (clazz != StructInstance.class) { addDeclaredFields(clazz.getSuperclass(), r); } } private Object convertValue(Object toConvert) throws Exception { if (toConvert instanceof ClassInstance) { return ((ClassInstance) toConvert).toReferenceable(); } if (toConvert instanceof StructInstance) { return ((StructInstance) toConvert).toStruct(); } else { return toConvert; } } } public static class ClassInstance<T> extends StructInstance { private transient final Id guid; private transient List<String> traits = new ArrayList(); public T withTrait(String name) { traits.add(name); return getInstance(); } public T withTraits(List<String> names) { traits.addAll(names); return getInstance(); } public T getInstance() { return (T) this; } public ClassInstance() { guid = new Id(getTypeName()); } public Referenceable toReferenceable() throws Exception { String[] traitArray = new String[traits.size()]; traitArray = traits.toArray(traitArray); Referenceable entity = new Referenceable(getTypeName(), traitArray); entity.replaceWithNewId(guid); addDeclaredFields(getClass(), entity); return entity; } public List<ITypedReferenceableInstance> getTypedReferencebles() throws Exception { List<ITypedReferenceableInstance> result = new ArrayList(); for (ClassInstance containedInstance : getAllInstances()) { Referenceable entity = containedInstance.toReferenceable(); ClassType type = TypeSystem.getInstance().getDataType(ClassType.class, entity.getTypeName()); ITypedReferenceableInstance converted = type.convert(entity, Multiplicity.REQUIRED); result.add(converted); } return result; } protected List<ClassInstance> getAllInstances() { return (List) Collections.singletonList(this); } public Id getId() { return guid; } } public static class NamedInstance<T> extends ClassInstance<T> { private final String name; public NamedInstance(String name) { super(); this.name = name; } } public static class HiveOrder extends StructInstance { private String col; private int order; public HiveOrder(String col, int order) { super(); this.col = col; this.order = order; } } public static class DB extends NamedInstance<DB> { private String owner; private int createTime; private String clusterName; public DB(String name, String owner, int createTime, String clusterName) { super(name); this.owner = owner; this.createTime = createTime; this.clusterName = clusterName; } } public static class StorageDescriptor extends ClassInstance<StorageDescriptor> { private String inputFormat; private String outputFormat; private List<HiveOrder> sortCols; public StorageDescriptor(String inputFormat, String outputFormat, List<HiveOrder> sortCols) { super(); this.inputFormat = inputFormat; this.outputFormat = outputFormat; this.sortCols = sortCols; } } public static class Column extends NamedInstance<Column> { private String type; private StorageDescriptor sd; public Column(String name, String type) { super(name); this.type = type; } public void setStorageDescriptor(StorageDescriptor sd) { this.sd = sd; } } public static class Table extends NamedInstance<Table> { private DB db; private Date created; private StorageDescriptor sd; private transient List<Column> colDefs; public Table(String name, DB db, StorageDescriptor sd, List<Column> colDefs) { this(name, db, sd, new Date(TestUtils.TEST_DATE_IN_LONG), colDefs); } public Table(String name, DB db, StorageDescriptor sd, Date created, List<Column> colDefs) { super(name); this.colDefs = colDefs; this.db = db; this.sd = sd; this.created = created; for (Column col : colDefs) { col.setStorageDescriptor(sd); } } public List<Column> getColumns() { return colDefs; } @Override protected List<ClassInstance> getAllInstances() { List<ClassInstance> result = new ArrayList(colDefs.size() + 2); result.add(sd); result.addAll(colDefs); result.add(this); return result; } } public static class Partition extends ClassInstance<Partition> { private List<String> values; private Table table; public Partition(List<String> values, Table table) { super(); this.values = values; this.table = table; } } public static class LoadProcess extends NamedInstance<LoadProcess> { private List<Table> inputTables; private Table outputTable; public LoadProcess(String name, List<Table> inputTables, Table outputTable) { super(name); this.inputTables = inputTables; this.outputTable = outputTable; } } public static class View extends NamedInstance<View> { private DB db; private List<Table> inputTables; public View(String name, DB db, List<Table> inputTables) { super(name); this.db = db; this.inputTables = inputTables; } } } <|start_filename|>catalog/src/main/java/org/apache/atlas/catalog/query/QueryExpression.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.catalog.query; import com.tinkerpop.pipes.Pipe; import org.apache.atlas.catalog.VertexWrapper; import java.util.Collection; /** * Represents a query expression. */ public interface QueryExpression { /** * Evaluate the expression based on properties of the provied vertex. * * @param vWrapper vertex wrapper that expression is applied to * @return result of expression evaluation */ boolean evaluate(VertexWrapper vWrapper); /** * Evaluate the expression based on the provided value. * * @param value value used to evaluate expression * @return */ boolean evaluate(Object value); /** * Get the complete set of properties which are contained in the expression. * * @return collection of expression properties */ Collection<String> getProperties(); /** * Get the pipe representation of the expression. * * @return pipe representation */ Pipe asPipe(); /** * Negate the expression. */ void setNegate(); /** * Get the negate status of the expression. * * @return true if the expression is negated, false otherwise */ boolean isNegate(); /** * Determine whether the expression is being applied to a projection. * * @return true if expression is being applied to a projection, false otherwise */ boolean isProjectionExpression(); /** * Get the field name used in the expression. * * @return expression field name or null if there is no field name */ String getField(); /** * Set the expressions field name. * * @param fieldName field name */ void setField(String fieldName); /** * Get the expected value for the expression. * * @return expected value or null if there isn't a expected value */ String getExpectedValue(); } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/store/graph/AtlasEnumDefStore.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.store.graph; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.SearchFilter; import org.apache.atlas.model.typedef.AtlasEnumDef; import org.apache.atlas.model.typedef.AtlasEnumDef.AtlasEnumDefs; import java.util.List; /** * Interface for graph persistence store for AtlasEnumDef */ public interface AtlasEnumDefStore { AtlasEnumDef create(AtlasEnumDef enumDef) throws AtlasBaseException; List<AtlasEnumDef> getAll() throws AtlasBaseException; AtlasEnumDef getByName(String name) throws AtlasBaseException; AtlasEnumDef getByGuid(String guid) throws AtlasBaseException; AtlasEnumDef update(AtlasEnumDef enumDef) throws AtlasBaseException; AtlasEnumDef updateByName(String name, AtlasEnumDef enumDef) throws AtlasBaseException; AtlasEnumDef updateByGuid(String guid, AtlasEnumDef enumDef) throws AtlasBaseException; void deleteByName(String name) throws AtlasBaseException; void deleteByGuid(String guid) throws AtlasBaseException; } <|start_filename|>repository/src/main/java/org/apache/atlas/services/DefaultMetadataService.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.services; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import org.apache.atlas.AtlasClient; import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.AtlasException; import org.apache.atlas.CreateUpdateEntitiesResult; import org.apache.atlas.EntityAuditEvent; import org.apache.atlas.RequestContext; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.ha.HAConfiguration; import org.apache.atlas.listener.ActiveStateChangeHandler; import org.apache.atlas.listener.ChangedTypeDefs; import org.apache.atlas.listener.EntityChangeListener; import org.apache.atlas.listener.TypeDefChangeListener; import org.apache.atlas.listener.TypesChangeListener; import org.apache.atlas.model.legacy.EntityResult; import org.apache.atlas.repository.MetadataRepository; import org.apache.atlas.repository.RepositoryException; import org.apache.atlas.repository.audit.EntityAuditRepository; import org.apache.atlas.repository.graph.GraphHelper; import org.apache.atlas.repository.typestore.ITypeStore; import org.apache.atlas.type.AtlasTypeUtil; import org.apache.atlas.typesystem.IReferenceableInstance; import org.apache.atlas.typesystem.IStruct; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.ITypedStruct; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.Struct; import org.apache.atlas.typesystem.TypesDef; import org.apache.atlas.typesystem.exception.EntityNotFoundException; import org.apache.atlas.typesystem.exception.TypeNotFoundException; import org.apache.atlas.typesystem.json.InstanceSerialization; import org.apache.atlas.typesystem.json.TypesSerialization; import org.apache.atlas.typesystem.persistence.Id; import org.apache.atlas.typesystem.persistence.ReferenceableInstance; import org.apache.atlas.typesystem.types.*; import org.apache.atlas.typesystem.types.cache.TypeCache; import org.apache.atlas.utils.ParamChecker; import org.apache.commons.configuration.Configuration; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.inject.Inject; import javax.inject.Singleton; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Simple wrapper over TypeSystem and MetadataRepository services with hooks * for listening to changes to the repository. */ @Singleton @Component @Deprecated public class DefaultMetadataService implements MetadataService, ActiveStateChangeHandler, TypeDefChangeListener { private enum OperationType { CREATE, UPDATE, DELETE }; private static final Logger LOG = LoggerFactory.getLogger(DefaultMetadataService.class); private final short maxAuditResults; private static final String CONFIG_MAX_AUDIT_RESULTS = "atlas.audit.maxResults"; private static final short DEFAULT_MAX_AUDIT_RESULTS = 1000; private final TypeSystem typeSystem; private final MetadataRepository repository; private final ITypeStore typeStore; private final Collection<TypesChangeListener> typeChangeListeners = new LinkedHashSet<>(); private final Collection<EntityChangeListener> entityChangeListeners = new LinkedHashSet<>(); private EntityAuditRepository auditRepository; @Inject public DefaultMetadataService(final MetadataRepository repository, final ITypeStore typeStore, final Set<TypesChangeListener> typesChangeListeners, final Set<EntityChangeListener> entityChangeListeners, final TypeSystem typeSystem, final Configuration configuration, TypeCache typeCache, EntityAuditRepository auditRepository) throws AtlasException { this.typeStore = typeStore; this.typeSystem = typeSystem; /** * Ideally a TypeCache implementation should have been injected in the TypeSystemProvider, * but a singleton of TypeSystem is constructed privately within the class so that * clients of TypeSystem would never instantiate a TypeSystem object directly in * their code. As soon as a client makes a call to TypeSystem.getInstance(), they * should have the singleton ready for consumption. Manually inject TypeSystem with * the Guice-instantiated type cache here, before types are restored. * This allows cache implementations to participate in Guice dependency injection. */ this.typeSystem.setTypeCache(typeCache); this.repository = repository; this.typeChangeListeners.addAll(typesChangeListeners); this.entityChangeListeners.addAll(entityChangeListeners); if (!HAConfiguration.isHAEnabled(configuration)) { restoreTypeSystem(); } maxAuditResults = configuration.getShort(CONFIG_MAX_AUDIT_RESULTS, DEFAULT_MAX_AUDIT_RESULTS); this.auditRepository = auditRepository; } private void restoreTypeSystem() throws AtlasException { LOG.info("Restoring type system from the store"); TypesDef typesDef = typeStore.restore(); refreshCache(typesDef); LOG.info("Restored type system from the store"); } private void refreshCache(TypesDef typesDef) throws AtlasException { if (typesDef != null && !typesDef.isEmpty()) { TypeSystem.TransientTypeSystem transientTypeSystem = typeSystem.createTransientTypeSystem(typesDef, true); Map<String, IDataType> typesAdded = transientTypeSystem.getTypesAdded(); LOG.info("Number of types got from transient type system: {}", typesAdded.size()); typeSystem.commitTypes(typesAdded); } } /** * Creates a new type based on the type system to enable adding * entities (instances for types). * * @param typeDefinition definition as json * @return a unique id for this type */ @Override public JSONObject createType(String typeDefinition) throws AtlasException { return createOrUpdateTypes(OperationType.CREATE, typeDefinition, false); } private JSONObject createOrUpdateTypes(OperationType opType, String typeDefinition, boolean isUpdate) throws AtlasException { typeDefinition = ParamChecker.notEmpty(typeDefinition, "type definition"); TypesDef typesDef = validateTypeDefinition(opType, typeDefinition); try { final TypeSystem.TransientTypeSystem transientTypeSystem = typeSystem.createTransientTypeSystem(typesDef, isUpdate); final Map<String, IDataType> typesAdded = transientTypeSystem.getTypesAdded(); try { /* Create indexes first so that if index creation fails then we rollback the typesystem and also do not persist the graph */ if (isUpdate) { onTypesUpdated(typesAdded); } else { onTypesAdded(typesAdded); } typeStore.store(transientTypeSystem, ImmutableList.copyOf(typesAdded.keySet())); typeSystem.commitTypes(typesAdded); } catch (Throwable t) { throw new AtlasException("Unable to persist types ", t); } return new JSONObject() {{ put(AtlasClient.TYPES, typesAdded.keySet()); }}; } catch (JSONException e) { LOG.error("Unable to create response for types={}", typeDefinition, e); throw new AtlasException("Unable to create response ", e); } } @Override public JSONObject updateType(String typeDefinition) throws AtlasException { return createOrUpdateTypes(OperationType.UPDATE, typeDefinition, true); } private TypesDef validateTypeDefinition(OperationType opType, String typeDefinition) throws AtlasException { final String exceptionErrorMessageFormat = "%s for '%s' failed: %s"; try { TypesDef typesDef = TypesSerialization.fromJson(typeDefinition); if (typesDef.isEmpty()) { throw new IllegalArgumentException("Invalid type definition"); } for (HierarchicalTypeDefinition<ClassType> t : typesDef.classTypesAsJavaList()) { if (!AtlasTypeUtil.isValidTypeName(t.typeName)) throw new AtlasException( String.format(exceptionErrorMessageFormat, opType.toString(), t.typeName, AtlasTypeUtil.getInvalidTypeNameErrorMessage())); } for (StructTypeDefinition t : typesDef.structTypesAsJavaList()) { if (!AtlasTypeUtil.isValidTypeName(t.typeName)) throw new AtlasException( String.format(exceptionErrorMessageFormat, opType.toString(), t.typeName, AtlasTypeUtil.getInvalidTypeNameErrorMessage())); } for (EnumTypeDefinition t : typesDef.enumTypesAsJavaList()) { if (!AtlasTypeUtil.isValidTypeName(t.name)) throw new AtlasException( String.format(exceptionErrorMessageFormat, opType.toString(), t.name, AtlasTypeUtil.getInvalidTypeNameErrorMessage())); } for (HierarchicalTypeDefinition<TraitType> t : typesDef.traitTypesAsJavaList()) { if (!AtlasTypeUtil.isValidTraitTypeName(t.typeName)) throw new AtlasException( String.format(exceptionErrorMessageFormat, opType.toString(), t.typeName, AtlasTypeUtil.getInvalidTraitTypeNameErrorMessage())); } return typesDef; } catch (Exception e) { LOG.error("Unable to deserialize json={}", typeDefinition, e); throw new IllegalArgumentException("Unable to deserialize json " + typeDefinition, e); } } /** * Return the definition for the given type. * * @param typeName name for this type, must be unique * @return type definition as JSON */ @Override public String getTypeDefinition(String typeName) throws AtlasException { final IDataType dataType = typeSystem.getDataType(IDataType.class, typeName); return TypesSerialization.toJson(typeSystem, dataType.getName()); } /** * Return the list of type names in the type system which match the specified filter. * * @return list of type names * @param filterMap - Map of filter for type names. Valid keys are CATEGORY, SUPERTYPE, NOT_SUPERTYPE * For example, CATEGORY = TRAIT && SUPERTYPE contains 'X' && SUPERTYPE !contains 'Y' * If there is no filter, all the types are returned */ @Override public List<String> getTypeNames(Map<TypeCache.TYPE_FILTER, String> filterMap) throws AtlasException { return typeSystem.getTypeNames(filterMap); } /** * Creates an entity, instance of the type. * * @param entityInstanceDefinition json array of entity definitions * @return guids - list of guids */ @Override public CreateUpdateEntitiesResult createEntities(String entityInstanceDefinition) throws AtlasException { entityInstanceDefinition = ParamChecker.notEmpty(entityInstanceDefinition, "Entity instance definition"); ITypedReferenceableInstance[] typedInstances = deserializeClassInstances(entityInstanceDefinition); return createEntities(typedInstances); } public CreateUpdateEntitiesResult createEntities(ITypedReferenceableInstance[] typedInstances) throws AtlasException { final CreateUpdateEntitiesResult result = repository.createEntities(typedInstances); onEntitiesAdded(result.getCreatedEntities()); return result; } @Override public ITypedReferenceableInstance[] deserializeClassInstances(String entityInstanceDefinition) throws AtlasException { return GraphHelper.deserializeClassInstances(typeSystem, entityInstanceDefinition); } @Override public ITypedReferenceableInstance getTypedReferenceableInstance(Referenceable entityInstance) throws AtlasException { return GraphHelper.getTypedReferenceableInstance(typeSystem, entityInstance); } /** * Return the definition for the given guid. * * @param guid guid * @return entity definition as JSON */ @Override public String getEntityDefinitionJson(String guid) throws AtlasException { guid = ParamChecker.notEmpty(guid, "entity id"); final ITypedReferenceableInstance instance = repository.getEntityDefinition(guid); return InstanceSerialization.toJson(instance, true); } /** * Return the definition for the given guid. * * @param guid guid * @return entity definition as JSON */ @Override public ITypedReferenceableInstance getEntityDefinition(String guid) throws AtlasException { guid = ParamChecker.notEmpty(guid, "entity id"); final ITypedReferenceableInstance instance = repository.getEntityDefinition(guid); return instance; } @Override public ITypedReferenceableInstance getEntityDefinitionReference(String entityType, String attribute, String value) throws AtlasException { validateTypeExists(entityType); validateUniqueAttribute(entityType, attribute); return repository.getEntityDefinition(entityType, attribute, value); } @Override public String getEntityDefinition(String entityType, String attribute, String value) throws AtlasException { final ITypedReferenceableInstance instance = getEntityDefinitionReference(entityType, attribute, value); return InstanceSerialization.toJson(instance, true); } /** * Validate that attribute is unique attribute * @param entityType the entity type * @param attributeName the name of the attribute */ private void validateUniqueAttribute(String entityType, String attributeName) throws AtlasException { ClassType type = typeSystem.getDataType(ClassType.class, entityType); AttributeInfo attribute = type.fieldMapping().fields.get(attributeName); if(attribute == null) { throw new IllegalArgumentException( String.format("%s is not an attribute in %s", attributeName, entityType)); } if (!attribute.isUnique) { throw new IllegalArgumentException( String.format("%s.%s is not a unique attribute", entityType, attributeName)); } } /** * Return the list of entity guids for the given type in the repository. * * @param entityType type * @return list of entity guids for the given type in the repository */ @Override public List<String> getEntityList(String entityType) throws AtlasException { validateTypeExists(entityType); return repository.getEntityList(entityType); } /** * Updates an entity, instance of the type based on the guid set. * * @param entityInstanceDefinition json array of entity definitions * @return guids - json array of guids */ @Override public CreateUpdateEntitiesResult updateEntities(String entityInstanceDefinition) throws AtlasException { entityInstanceDefinition = ParamChecker.notEmpty(entityInstanceDefinition, "Entity instance definition"); ITypedReferenceableInstance[] typedInstances = deserializeClassInstances(entityInstanceDefinition); CreateUpdateEntitiesResult result = repository.updateEntities(typedInstances); onEntitiesAddedUpdated(result.getEntityResult()); return result; } /** * Updates an entity, instance of the type based on the guid set. * * @param entityInstanceDefinitions * @return guids - json array of guids */ @Override public CreateUpdateEntitiesResult updateEntities(ITypedReferenceableInstance[] entityInstanceDefinitions) throws AtlasException { CreateUpdateEntitiesResult result = repository.updateEntities(entityInstanceDefinitions); onEntitiesAddedUpdated(result.getEntityResult()); return result; } private void onEntitiesAddedUpdated(EntityResult entityResult) throws AtlasException { onEntitiesAdded(entityResult.getCreatedEntities()); onEntitiesUpdated(entityResult.getUpdateEntities()); //Note: doesn't access deletedEntities from entityResult onEntitiesDeleted(RequestContext.get().getDeletedEntities()); } @Override public CreateUpdateEntitiesResult updateEntityAttributeByGuid(String guid, String attributeName, String value) throws AtlasException { guid = ParamChecker.notEmpty(guid, "entity id"); attributeName = ParamChecker.notEmpty(attributeName, "attribute name"); value = ParamChecker.notEmpty(value, "attribute value"); ITypedReferenceableInstance existInstance = validateEntityExists(guid); ClassType type = typeSystem.getDataType(ClassType.class, existInstance.getTypeName()); ITypedReferenceableInstance newInstance = type.createInstance(); AttributeInfo attributeInfo = type.fieldMapping.fields.get(attributeName); if (attributeInfo == null) { throw new AtlasException("Invalid property " + attributeName + " for entity " + existInstance.getTypeName()); } DataTypes.TypeCategory attrTypeCategory = attributeInfo.dataType().getTypeCategory(); switch(attrTypeCategory) { case PRIMITIVE: newInstance.set(attributeName, value); break; case CLASS: Id id = new Id(value, 0, attributeInfo.dataType().getName()); newInstance.set(attributeName, id); break; default: throw new AtlasException("Update of " + attrTypeCategory + " is not supported"); } ((ReferenceableInstance)newInstance).replaceWithNewId(new Id(guid, 0, newInstance.getTypeName())); CreateUpdateEntitiesResult result = repository.updatePartial(newInstance); onEntitiesAddedUpdated(result.getEntityResult()); return result; } private ITypedReferenceableInstance validateEntityExists(String guid) throws EntityNotFoundException, RepositoryException { final ITypedReferenceableInstance instance = repository.getEntityDefinition(guid); if (instance == null) { throw new EntityNotFoundException(String.format("Entity with guid %s not found ", guid)); } return instance; } @Override public CreateUpdateEntitiesResult updateEntityPartialByGuid(String guid, Referenceable newEntity) throws AtlasException { guid = ParamChecker.notEmpty(guid, "guid cannot be null"); newEntity = ParamChecker.notNull(newEntity, "updatedEntity cannot be null"); ITypedReferenceableInstance existInstance = validateEntityExists(guid); ITypedReferenceableInstance newInstance = validateAndConvertToTypedInstance(newEntity, existInstance.getTypeName()); ((ReferenceableInstance)newInstance).replaceWithNewId(new Id(guid, 0, newInstance.getTypeName())); CreateUpdateEntitiesResult result = repository.updatePartial(newInstance); onEntitiesAddedUpdated(result.getEntityResult()); return result; } @Override public ITypedReferenceableInstance validateAndConvertToTypedInstance(IReferenceableInstance updatedEntity, String typeName) throws AtlasException { ClassType type = typeSystem.getDataType(ClassType.class, typeName); ITypedReferenceableInstance newInstance = type.createInstance(updatedEntity.getId()); for (String attributeName : updatedEntity.getValuesMap().keySet()) { AttributeInfo attributeInfo = type.fieldMapping.fields.get(attributeName); if (attributeInfo == null) { throw new AtlasException("Invalid property " + attributeName + " for entity " + updatedEntity); } DataTypes.TypeCategory attrTypeCategory = attributeInfo.dataType().getTypeCategory(); Object value = updatedEntity.get(attributeName); switch (attrTypeCategory) { case CLASS: if (value != null) { if (value instanceof Referenceable) { newInstance.set(attributeName, value); } else { Id id = new Id((String) value, 0, attributeInfo.dataType().getName()); newInstance.set(attributeName, id); } } break; case ENUM: case PRIMITIVE: case ARRAY: case STRUCT: case MAP: newInstance.set(attributeName, value); break; case TRAIT: //TODO - handle trait updates as well? default: throw new AtlasException("Update of " + attrTypeCategory + " is not supported"); } } return newInstance; } @Override public CreateUpdateEntitiesResult updateEntityByUniqueAttribute(String typeName, String uniqueAttributeName, String attrValue, Referenceable updatedEntity) throws AtlasException { typeName = ParamChecker.notEmpty(typeName, "typeName"); uniqueAttributeName = ParamChecker.notEmpty(uniqueAttributeName, "uniqueAttributeName"); attrValue = ParamChecker.notNull(attrValue, "unique attribute value"); updatedEntity = ParamChecker.notNull(updatedEntity, "updatedEntity"); ITypedReferenceableInstance oldInstance = getEntityDefinitionReference(typeName, uniqueAttributeName, attrValue); final ITypedReferenceableInstance newInstance = validateAndConvertToTypedInstance(updatedEntity, typeName); ((ReferenceableInstance)newInstance).replaceWithNewId(oldInstance.getId()); CreateUpdateEntitiesResult result = repository.updatePartial(newInstance); onEntitiesAddedUpdated(result.getEntityResult()); return result; } private void validateTypeExists(String entityType) throws AtlasException { entityType = ParamChecker.notEmpty(entityType, "entity type"); IDataType type = typeSystem.getDataType(IDataType.class, entityType); if (type.getTypeCategory() != DataTypes.TypeCategory.CLASS) { throw new IllegalArgumentException("type " + entityType + " not a CLASS type"); } } /** * Gets the list of trait names for a given entity represented by a guid. * * @param guid globally unique identifier for the entity * @return a list of trait names for the given entity guid * @throws AtlasException */ @Override public List<String> getTraitNames(String guid) throws AtlasException { guid = ParamChecker.notEmpty(guid, "entity id"); return repository.getTraitNames(guid); } /** * Adds a new trait to the list of existing entities represented by their respective guids * @param entityGuids list of guids of entities * @param traitInstance trait instance json that needs to be added to entities * @throws AtlasException */ @Override public void addTrait(List<String> entityGuids, ITypedStruct traitInstance) throws AtlasException { Preconditions.checkNotNull(entityGuids, "entityGuids list cannot be null"); Preconditions.checkNotNull(traitInstance, "Trait instance cannot be null"); final String traitName = traitInstance.getTypeName(); // ensure trait type is already registered with the TypeSystem if (!typeSystem.isRegistered(traitName)) { String msg = String.format("trait=%s should be defined in type system before it can be added", traitName); LOG.error(msg); throw new TypeNotFoundException(msg); } //ensure trait is not already registered with any of the given entities for (String entityGuid : entityGuids) { Preconditions.checkArgument(!getTraitNames(entityGuid).contains(traitName), "trait=%s is already defined for entity=%s", traitName, entityGuid); } repository.addTrait(entityGuids, traitInstance); for (String entityGuid : entityGuids) { onTraitAddedToEntity(repository.getEntityDefinition(entityGuid), traitInstance); } } /** * Adds a new trait to an existing entity represented by a guid. * * @param guid globally unique identifier for the entity * @param traitInstanceDefinition trait instance json that needs to be added to entity * @throws AtlasException */ @Override public void addTrait(String guid, String traitInstanceDefinition) throws AtlasException { guid = ParamChecker.notEmpty(guid, "entity id"); traitInstanceDefinition = ParamChecker.notEmpty(traitInstanceDefinition, "trait instance definition"); ITypedStruct traitInstance = deserializeTraitInstance(traitInstanceDefinition); addTrait(guid, traitInstance); } public void addTrait(String guid, ITypedStruct traitInstance) throws AtlasException { final String traitName = traitInstance.getTypeName(); // ensure trait type is already registered with the TS if (!typeSystem.isRegistered(traitName)) { String msg = String.format("trait=%s should be defined in type system before it can be added", traitName); LOG.error(msg); throw new TypeNotFoundException(msg); } // ensure trait is not already defined Preconditions .checkArgument(!getTraitNames(guid).contains(traitName), "trait=%s is already defined for entity=%s", traitName, guid); repository.addTrait(guid, traitInstance); onTraitAddedToEntity(repository.getEntityDefinition(guid), traitInstance); } private ITypedStruct deserializeTraitInstance(String traitInstanceDefinition) throws AtlasException { return createTraitInstance(InstanceSerialization.fromJsonStruct(traitInstanceDefinition, true)); } @Override public ITypedStruct createTraitInstance(Struct traitInstance) throws AtlasException { try { final String entityTypeName = ParamChecker.notEmpty(traitInstance.getTypeName(), "entity type"); TraitType traitType = typeSystem.getDataType(TraitType.class, entityTypeName); return traitType.convert(traitInstance, Multiplicity.REQUIRED); } catch (TypeNotFoundException e) { throw e; } catch (Exception e) { throw new AtlasException("Error deserializing trait instance", e); } } @Override public IStruct getTraitDefinition(String guid, final String traitName) throws AtlasException { guid = ParamChecker.notEmpty(guid, "entity id"); final ITypedReferenceableInstance instance = repository.getEntityDefinition(guid); return instance.getTrait(traitName); } /** * Deletes a given trait from an existing entity represented by a guid. * * @param guid globally unique identifier for the entity * @param traitNameToBeDeleted name of the trait * @throws AtlasException */ @Override public void deleteTrait(String guid, String traitNameToBeDeleted) throws AtlasException { guid = ParamChecker.notEmpty(guid, "entity id"); traitNameToBeDeleted = ParamChecker.notEmpty(traitNameToBeDeleted, "trait name"); // ensure trait type is already registered with the TS if (!typeSystem.isRegistered(traitNameToBeDeleted)) { final String msg = String.format("trait=%s should be defined in type system before it can be deleted", traitNameToBeDeleted); LOG.error(msg); throw new TypeNotFoundException(msg); } repository.deleteTrait(guid, traitNameToBeDeleted); onTraitDeletedFromEntity(repository.getEntityDefinition(guid), traitNameToBeDeleted); } private void onTypesAdded(Map<String, IDataType> typesAdded) throws AtlasException { for (TypesChangeListener listener : typeChangeListeners) { listener.onAdd(typesAdded.values()); } } private void onEntitiesAdded(List<String> guids) throws AtlasException { List<ITypedReferenceableInstance> entities = loadEntities(guids); for (EntityChangeListener listener : entityChangeListeners) { listener.onEntitiesAdded(entities, false); } } private List<ITypedReferenceableInstance> loadEntities(List<String> guids) throws RepositoryException, EntityNotFoundException { return repository.getEntityDefinitions(guids.toArray(new String[guids.size()])); } private void onTypesUpdated(Map<String, IDataType> typesUpdated) throws AtlasException { for (TypesChangeListener listener : typeChangeListeners) { listener.onChange(typesUpdated.values()); } } private void onEntitiesUpdated(List<String> guids) throws AtlasException { List<ITypedReferenceableInstance> entities = loadEntities(guids); for (EntityChangeListener listener : entityChangeListeners) { listener.onEntitiesUpdated(entities, false); } } private void onTraitAddedToEntity(ITypedReferenceableInstance entity, IStruct trait) throws AtlasException { Collection<IStruct> traits = Collections.singletonList(trait); for (EntityChangeListener listener : entityChangeListeners) { listener.onTraitsAdded(entity, traits); } } private void onTraitDeletedFromEntity(ITypedReferenceableInstance entity, String traitName) throws AtlasException { Collection<String> traitNames = Collections.singletonList(traitName); for (EntityChangeListener listener : entityChangeListeners) { listener.onTraitsDeleted(entity, traitNames); } } public void registerListener(EntityChangeListener listener) { entityChangeListeners.add(listener); } public void unregisterListener(EntityChangeListener listener) { entityChangeListeners.remove(listener); } @Override public List<EntityAuditEvent> getAuditEvents(String guid, String startKey, short count) throws AtlasException { guid = ParamChecker.notEmpty(guid, "entity id"); startKey = ParamChecker.notEmptyIfNotNull(startKey, "start key"); ParamChecker.lessThan(count, maxAuditResults, "count"); return auditRepository.listEvents(guid, startKey, count); } /* (non-Javadoc) * @see org.apache.atlas.services.MetadataService#deleteEntities(java.lang.String) */ @Override public EntityResult deleteEntities(List<String> deleteCandidateGuids) throws AtlasException { ParamChecker.notEmpty(deleteCandidateGuids, "delete candidate guids"); return deleteGuids(deleteCandidateGuids); } @Override public EntityResult deleteEntityByUniqueAttribute(String typeName, String uniqueAttributeName, String attrValue) throws AtlasException { typeName = ParamChecker.notEmpty(typeName, "delete candidate typeName"); uniqueAttributeName = ParamChecker.notEmpty(uniqueAttributeName, "delete candidate unique attribute name"); attrValue = ParamChecker.notEmpty(attrValue, "delete candidate unique attribute value"); //Throws EntityNotFoundException if the entity could not be found by its unique attribute ITypedReferenceableInstance instance = getEntityDefinitionReference(typeName, uniqueAttributeName, attrValue); final Id instanceId = instance.getId(); List<String> deleteCandidateGuids = new ArrayList<String>() {{ add(instanceId._getId());}}; return deleteGuids(deleteCandidateGuids); } private EntityResult deleteGuids(List<String> deleteCandidateGuids) throws AtlasException { EntityResult entityResult = repository.deleteEntities(deleteCandidateGuids); onEntitiesAddedUpdated(entityResult); return entityResult; } private void onEntitiesDeleted(List<ITypedReferenceableInstance> entities) throws AtlasException { for (EntityChangeListener listener : entityChangeListeners) { listener.onEntitiesDeleted(entities, false); } } /** * Create or restore the {@link TypeSystem} cache on server activation. * * When an instance is passive, types could be created outside of its cache by the active instance. * Hence, when this instance becomes active, it needs to restore the cache from the backend store. * The first time initialization happens, the indices for these types also needs to be created. * This must happen only from the active instance, as it updates shared backend state. */ @Override public void instanceIsActive() throws AtlasException { LOG.info("Reacting to active state: restoring type system"); restoreTypeSystem(); } @Override public void instanceIsPassive() { LOG.info("Reacting to passive state: no action right now"); } @Override public void onChange(ChangedTypeDefs changedTypeDefs) throws AtlasBaseException { // All we need here is a restore of the type-system LOG.info("TypeSystem reset invoked by TypeRegistry changes"); try { TypesDef typesDef = typeStore.restore(); typeSystem.reset(); TypeSystem.TransientTypeSystem transientTypeSystem = typeSystem.createTransientTypeSystem(typesDef, false); Map<String, IDataType> typesAdded = transientTypeSystem.getTypesAdded(); LOG.info("Number of types got from transient type system: {}", typesAdded.size()); typeSystem.commitTypes(typesAdded); } catch (AtlasException e) { LOG.error("Failed to restore type-system after TypeRegistry changes", e); throw new AtlasBaseException(AtlasErrorCode.INTERNAL_ERROR, e); } } } <|start_filename|>repository/src/test/java/org/apache/atlas/services/MetricsServiceTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.services; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.metrics.AtlasMetrics; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.commons.configuration.Configuration; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; public class MetricsServiceTest { private Configuration mockConfig = mock(Configuration.class); private AtlasTypeRegistry mockTypeRegistry = mock(AtlasTypeRegistry.class); private AtlasGraph mockGraph = mock(AtlasGraph.class); private MetricsService metricsService; private List<Map> mockMapList = new ArrayList<>(); private Number mockCount = 10; @BeforeClass public void init() throws AtlasBaseException { Map<String, Object> mockMap = new HashMap<>(); mockMap.put("a", 1); mockMap.put("b", 2); mockMap.put("c", 3); mockMapList.add(mockMap); when(mockConfig.getInt(anyString(), anyInt())).thenReturn(5); assertEquals(mockConfig.getInt("test", 1), 5); when(mockConfig.getString(anyString(), anyString())) .thenReturn("count()", "count()", "count()", "count()", "count()", "toList()", "count()", "toList()"); when(mockTypeRegistry.getAllEntityDefNames()).thenReturn(Arrays.asList("a", "b", "c")); setupMockGraph(); metricsService = new MetricsService(mockConfig, mockGraph); } private void setupMockGraph() throws AtlasBaseException { if (mockGraph == null) mockGraph = mock(AtlasGraph.class); when(mockGraph.executeGremlinScript(anyString(), eq(false))).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { if (((String)invocationOnMock.getArguments()[0]).contains("count()")) { return mockCount; } else { return mockMapList; } } }); } @Test public void testGetMetrics() throws InterruptedException, AtlasBaseException { assertNotNull(metricsService); AtlasMetrics metrics = metricsService.getMetrics(false); assertNotNull(metrics); Number aCount = metrics.getMetric("entity", "a"); assertNotNull(aCount); assertEquals(aCount, 1); Number bCount = metrics.getMetric("entity", "b"); assertNotNull(bCount); assertEquals(bCount, 2); Number cCount = metrics.getMetric("entity", "c"); assertNotNull(cCount); assertEquals(cCount, 3); Number aTags = metrics.getMetric("tag", "a"); assertNotNull(aTags); assertEquals(aTags, 1); Number bTags = metrics.getMetric("tag", "b"); assertNotNull(bTags); assertEquals(bTags, 2); Number cTags = metrics.getMetric("tag", "c"); assertNotNull(cTags); assertEquals(cTags, 3); verify(mockGraph, atLeastOnce()).executeGremlinScript(anyString(), anyBoolean()); // Subsequent call within the cache timeout window metricsService.getMetrics(false); verifyZeroInteractions(mockGraph); // Now test the cache refresh Thread.sleep(6000); metricsService.getMetrics(true); verify(mockGraph, atLeastOnce()).executeGremlinScript(anyString(), anyBoolean()); } } <|start_filename|>dashboardv2/public/js/views/business_catalog/TreeLayoutView.js<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(['require', 'backbone', 'hbs!tmpl/business_catalog/TreeLayoutView_tmpl', 'utils/Utils', 'collection/VCatalogList', 'utils/CommonViewFunction', 'utils/Messages', 'utils/UrlLinks' ], function(require, Backbone, TreeLayoutView_tmpl, Utils, VCatalogList, CommonViewFunction, Messages, UrlLinks) { 'use strict'; var TreeLayoutView = Backbone.Marionette.LayoutView.extend( /** @lends TreeLayoutView */ { _viewName: 'TreeLayoutView', template: TreeLayoutView_tmpl, /** Layout sub regions */ regions: {}, /** ui selector cache */ ui: { Parent: '[data-id="Parent"]', childList: '[data-id="childList"]', liClick: 'li a[data-href]', backTaxanomy: '[data-id="backTaxanomy"]', expandArrow: '[data-id="expandArrow"]', searchTermInput: '[data-id="searchTermInput"]', refreshTaxanomy: '[data-id="refreshTaxanomy"]', descriptionAssign: '[data-id="descriptionAssign"]', }, /** ui events hash */ events: function() { var events = {}; events['dblclick ' + this.ui.liClick] = function(e) { this.changeArrowState(e); }; events['click ' + this.ui.liClick] = function(e) { var that = this; that.addActiveClass(e); that.url = $(e.currentTarget).data('href'); if (this.viewBased) { Utils.setUrl({ url: '#!/taxonomy/detailCatalog' + that.url, mergeBrowserUrl: false, updateTabState: function() { return { taxonomyUrl: this.url, stateChanged: true }; }, trigger: true }); } }; events['click ' + this.ui.backTaxanomy] = 'backButtonTaxanomy'; events['click ' + this.ui.refreshTaxanomy] = 'refreshButtonTaxanomy'; events['click ' + this.ui.expandArrow] = 'changeArrowState'; events["change " + this.ui.searchTermInput] = function() { var termUrl = this.termCollection.url.split("/", 5).join("/") + "/" + this.ui.searchTermInput.val().split(".").join("/terms/"); this.fetchCollection(termUrl, true); if (this.viewBased) { Utils.setUrl({ url: "#!/taxonomy/detailCatalog" + termUrl, mergeBrowserUrl: false, trigger: true, updateTabState: function() { return { taxonomyUrl: this.url, stateChanged: true }; } }); } }; return events; }, /** * intialize a new TreeLayoutView Layout * @constructs */ initialize: function(options) { _.extend(this, _.pick(options, 'url', 'viewBased')); this.parentCollection = new VCatalogList(); this.childCollection = new VCatalogList(); this.taxanomy = new VCatalogList(); this.termCollection = new VCatalogList(); }, bindEvents: function() { var that = this; this.listenTo(this.parentCollection, 'reset', function() { if (this.parentCollection.fullCollection.models.length) { this.generateTree(true); } else { if (Utils.getUrlState.isTaxonomyTab() || Utils.getUrlState.isInitial()) { this.createDefaultTaxonomy(); } } }, this); this.listenTo(this.childCollection, 'reset', function() { this.generateTree(); }, this); this.listenTo(this.taxanomy, 'reset', function() { this.searchResult(); }, this); this.listenTo(this.termCollection, 'reset', function() { this.termSearchData(); }, this); this.listenTo(this.childCollection, 'error', function(model, response) { this.hideLoader(); }, this); this.listenTo(this.parentCollection, 'error', function(model, response) { this.hideLoader(); }, this); }, onRender: function() { var that = this; this.bindEvents(); that.ui.backTaxanomy.hide(); this.fetchCollection(this.url, true); this.$el.on("click", '.termPopoverList li', function(e) { that[$(this).find("a").data('fn')](e); }); $('body').click(function(e) { if (that.$('.termPopoverList').length) { if ($(e.target).hasClass('termPopover')) { return; } that.$('.termPopover').popover('hide'); } }); this.fetchTaxanomyCollections(); if (!this.viewBased) { this.ui.descriptionAssign.show(); } else { this.ui.descriptionAssign.hide(); } }, backButtonTaxanomy: function(e) { var that = this; this.backButton = true; var dataURL = this.$('.taxonomyTree').find('li[data-id="Parent"]').find("a").data('href').split("/terms"); var backUrl = dataURL.pop(); if (dataURL.join("/terms").length) { this.ui.backTaxanomy.show(); var currentURL = "#!/taxonomy/detailCatalog" + dataURL.join("/terms"); this.fetchCollection(dataURL.join("/terms"), true); this.url = dataURL.join("/terms"); if (this.viewBased) { Utils.setUrl({ url: currentURL, mergeBrowserUrl: false, trigger: true, updateTabState: function() { return { taxonomyUrl: this.url, stateChanged: true }; } }); } } }, manualRender: function(url) { var splitUrl = this.url.split('/terms'); if (url && this.url != url) { if (splitUrl.length > 1 && splitUrl[splitUrl.length - 1] == "") { var checkUrl = splitUrl; checkUrl.pop(); if (url != checkUrl) { this.fetchCollection(url, true); } } else if (Utils.getUrlState.getQueryParams() && Utils.getUrlState.getQueryParams().load == "true") { if (this.viewBased) { Utils.setUrl({ url: "#!/taxonomy/detailCatalog" + url, mergeBrowserUrl: false, trigger: false, updateTabState: function() { return { taxonomyUrl: this.url, stateChanged: true }; } }); } this.fetchCollection(url, true); } else { this.fetchCollection(url, true); } } if (!url && Utils.getUrlState.isTaxonomyTab()) { this.selectFirstElement(); } }, changeArrowState: function(e) { var scope = this.$('[data-id="expandArrow"]'); if (e) { scope = $(e.currentTarget); } if (scope.is('a')) { var url = scope.data('href'); scope = scope.parent().find("i.toggleArrow"); } else if (scope.is('i')) { var url = scope.parent().find("a").data('href'); } if (scope.hasClass('fa-angle-down')) { scope.toggleClass('fa-angle-right fa-angle-down'); this.ui.childList.hide(); } else { if (e && $(e.currentTarget).parents('li.parentChild').length) { scope.parent('li').find('.tools .taxanomyloader').show(); this.url = url; this.fetchCollection(url, true); if (this.viewBased) { Utils.setUrl({ url: "#!/taxonomy/detailCatalog" + url, mergeBrowserUrl: false, trigger: true, updateTabState: function() { return { taxonomyUrl: this.url, stateChanged: true }; } }); } } else { scope.toggleClass('fa-angle-right fa-angle-down'); this.ui.childList.show(); } } }, fetchCollection: function(url, isParent) { if (url) { this.url = url; } else { var parentURL = this.ui.Parent.find('a').data('href'); if (parentURL) { this.url = parentURL; } else { this.url = UrlLinks.taxonomiesApiUrl(); } } this.showLoader(); if (isParent) { this.parentCollection.url = this.url; this.parentCollection.fullCollection.reset(undefined, { silent: true }); this.parentCollection.fetch({ reset: true, cache: true }); } else { this.childCollection.url = this.url + "?hierarchy/path:."; this.childCollection.fullCollection.reset(undefined, { silent: true }); this.childCollection.fetch({ reset: true, cache: true }); } }, showLoader: function() { this.$('.taxonomyTree').find('li.active .tools .taxanomyloader').show(); this.$('.contentLoading').show(); }, hideLoader: function() { this.$('.taxanomyloader').hide(); this.$('.contentLoading').hide(); }, addActiveClass: function(e) { this.$('ul.taxonomyTree').find('li').removeClass('active'); if (e.jquery) { e.parent('li').addClass('active'); } else { if (e.currentTarget) { $(e.currentTarget).parent('li').addClass('active'); } else { if ($(e).parent.length) { $(e).parent('li').addClass('active'); } else { $(e).parents('li').addClass('active'); } } } }, fetchTaxanomyCollections: function() { this.taxanomy.fetch({ reset: true }); }, refreshButtonTaxanomy: function() { this.fetchTaxanomyCollections(); var url = ""; if (this.$('.taxonomyTree').find('.active').parents('.parentChild').length) { url = this.$('.taxonomyTree').find('.active a').data('href').split("/").slice(0, -2).join("/"); this.refresh = this.$('.taxonomyTree').find('.active a').data('href'); } else { url = this.$('.taxonomyTree').find('.active a').data('href'); this.refresh = this.$('.taxonomyTree').find('.active a').data('href'); } this.fetchCollection(url, true); }, searchResult: function() { var that = this; _.each(this.taxanomy.models, function(model, key) { var name = model.get('name'); that.termCollection.url = UrlLinks.taxonomiesTermsApiUrl(name) }); this.termCollection.fetch({ reset: true }); }, termSearchData: function() { var that = this; var str = '<option></option>'; this.termCollection.fullCollection.comparator = function(model) { return model.get('name'); }; this.termCollection.fullCollection.sort().each(function(model) { str += '<option>' + model.get('name') + '</option>'; }); this.ui.searchTermInput.html(str); // this.ui.searchTermInput.setAttribute('data-href' : that.termCollection.url); this.ui.searchTermInput.select2({ placeholder: "Search Term", allowClear: true }); }, onSearchTerm: function() { Utils.setUrl({ url: '#!/search/searchResult', urlParams: { query: this.$('.taxonomyTree').find('li.active').find("a").data('name'), searchType: "dsl", dslChecked: true }, updateTabState: function() { return { searchUrl: this.url, stateChanged: true }; }, mergeBrowserUrl: false, trigger: true }); }, selectFirstElement: function() { var dataURL = this.$('.taxonomyTree').find('li[data-id="Parent"]').find("a").data('href'); if (dataURL) { this.url = dataURL; if (this.viewBased && Utils.getUrlState.isTaxonomyTab()) { Utils.setUrl({ url: "#!/taxonomy/detailCatalog" + dataURL, mergeBrowserUrl: false, trigger: true, updateTabState: function() { return { taxonomyUrl: this.url, stateChanged: true }; } }); } } }, generateTree: function(isParent) { var parentLi = "", childLi = "", that = this; function createTaxonomy(url) { var href = false; _.each(that.parentCollection.fullCollection.models, function(model, key) { if (model.get('terms')) { href = model.get('terms').href; } else if (model.get('href')) { href = model.get('href') + "/terms"; } var hrefUrl = "/api" + model.get('href').split("/api")[1]; if (hrefUrl) { var backUrlCheck = hrefUrl.split("taxonomies/"); if (backUrlCheck.length > 1) { if (backUrlCheck[1].split("/terms").length <= 1) { that.ui.backTaxanomy.hide(); } else { that.ui.backTaxanomy.show(); } } } var name = Utils.checkTagOrTerm(model.get('name'), true); if (name.name) { if (that.viewBased) { parentLi = '<div class="tools"><i class="fa fa-refresh fa-spin-custom taxanomyloader"></i><i class="fa fa-ellipsis-h termPopover"></i></div><i class="fa fa-angle-right toggleArrow" data-id="expandArrow" data-href="' + hrefUrl + '"></i><a href="javascript:void(0)" data-href="' + hrefUrl + '" data-name="`' + model.get('name') + '`">' + name.name + '</a>'; } else { parentLi = '<div class="tools"><i class="fa fa-refresh fa-spin-custom taxanomyloader"></i></div><i class="fa fa-angle-right toggleArrow" data-id="expandArrow" data-href="' + hrefUrl + '"></i><a href="javascript:void(0)" data-href="' + hrefUrl + '" data-name="`' + model.get('name') + '`">' + name.name + '</a>'; } } }); if (href) { var hrefUrl = "/api" + href.split("/api")[1]; that.fetchCollection(hrefUrl); } that.ui.childList.html(''); that.ui.Parent.addClass('active'); that.ui.Parent.html(parentLi); } function createTerm() { that.childCollection.fullCollection.comparator = function(model) { return model.get('name').toLowerCase(); }; that.childCollection.fullCollection.sort().each(function(model, key) { var name = Utils.checkTagOrTerm(model.get('name'), true); var hrefUrl = "/api" + model.get('href').split("/api")[1]; if (name.name) { if (that.viewBased) { childLi += '<li class="children"><div class="tools"><i class="fa fa-refresh fa-spin-custom taxanomyloader"></i><i class="fa fa-ellipsis-h termPopover" ></i></div><i class="fa fa-angle-right toggleArrow" data-id="expandArrow" data-href="' + hrefUrl + '"></i><a href="javascript:void(0)" data-href="' + hrefUrl + '" data-name="`' + model.get('name') + '`">' + name.name + '</a></li>'; } else { childLi += '<li class="children"><div class="tools"><i class="fa fa-refresh fa-spin-custom taxanomyloader"></i></div><i class="fa fa-angle-right toggleArrow" data-id="expandArrow" data-href="' + hrefUrl + '"></i><a href="javascript:void(0)" data-href="' + hrefUrl + '" data-name="`' + model.get('name') + '`">' + name.name + '</a></li>'; } } }); that.ui.childList.html(childLi); } if (isParent) { createTaxonomy(); } else { this.changeArrowState(); createTerm(); if (Utils.getUrlState.isInitial() || Utils.getUrlState.getQueryUrl().lastValue == "taxonomy") { this.selectFirstElement(); } if (this.refresh) { this.addActiveClass(this.$('.taxonomyTree').find('a[data-href="' + this.refresh + '"]')); this.refresh = undefined; } } this.hideLoader(); if (this.viewBased) { this.$('.termPopover').popover({ placement: 'bottom', html: true, trigger: 'manual', container: this.$el, template: '<div class="popover fixedPopover fade bottom in"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>', content: function() { var li = "<li class='listTerm'><i class='fa fa-plus'></i> <a href='javascript:void(0)' data-fn='onAddTerm'>Create Subterm</a></li>"; /* "<li class='listTerm' ><i class='fa fa-arrow-right'></i> <a href='javascript:void(0)' data-fn='moveTerm'>Move Term</a></li>" + "<li class='listTerm' ><i class='fa fa-edit'></i> <a href='javascript:void(0)' data-fn='onEditTerm'>Edit Term</a></li>" +*/ var termDataURL = Utils.getUrlState.getQueryUrl().hash.split("terms"); if (termDataURL.length > 1) { li = "<li class='listTerm' ><i class='fa fa-search'></i> <a href='javascript:void(0)' data-fn='onSearchTerm'>Search Assets</a></li>" + li; li += "<li class='listTerm'><i class='fa fa-trash'></i> <a href='javascript:void(0)' data-fn='deleteTerm'>Delete Term</a></li>"; } return "<ul class='termPopoverList'>" + li + "</ul>"; } }); this.$('.termPopover').off('click').on('click', function(e) { // if any other popovers are visible, hide them e.preventDefault(); that.$('.termPopover').not(this).popover('hide'); $(this).popover('show'); }); } }, onAddTerm: function(e) { var that = this; require([ 'views/business_catalog/AddTermLayoutView', 'modules/Modal' ], function(AddTermLayoutView, Modal) { var view = new AddTermLayoutView({ url: that.$('.taxonomyTree').find('li.active').find("a").data("href"), model: new that.parentCollection.model() }); var modal = new Modal({ title: 'Create Sub-term', content: view, okCloses: true, showFooter: true, allowCancel: true, okText: 'Create', }).open(); modal.$el.find('button.ok').attr('disabled', true); modal.on('ok', function() { that.saveAddTerm(view); }); view.ui.termName.on('keyup', function() { if (this.value.indexOf(' ') >= 0) { modal.$el.find('button.ok').prop('disabled', true); view.ui.termName.addClass("addTermDisable"); view.$('.alertTerm').show(); } else { modal.$el.find('button.ok').prop('disabled', false); view.ui.termName.removeClass("addTermDisable"); view.$('.alertTerm').hide(); } }); view.on('closeModal', function() { modal.trigger('cancel'); }); }); }, saveAddTerm: function(view) { var that = this; var url = view.url; view.model.url = url + "/terms/" + view.ui.termName.val(); this.showLoader(); view.model.set({ description: view.ui.termDetail.val() }).save(null, { success: function(model, response) { that.create = true; that.fetchTaxanomyCollections(); that.fetchCollection(url, true); Utils.notifySuccess({ content: "Term " + view.ui.termName.val() + Messages.addSuccessMessage }); }, complete: function() { that.hideLoader(); } }); }, deleteTerm: function(e) { var termName = this.$('.taxonomyTree').find('li.active a').data("name"), assetName = $(e.target).data("assetname"), that = this, modal = CommonViewFunction.deleteTagModel({ msg: "<div class='ellipsis'>Delete: " + "<b>" + _.escape(termName) + "?</b></div>" + "<p class='termNote'>Assets mapped to this term will be unclassified.</p>", titleMessage: Messages.deleteTerm, buttonText: "Delete" }); modal.on('ok', function() { that.deleteTermData(e); }); modal.on('closeModal', function() { modal.trigger('cancel'); }); }, deleteTermData: function(e) { var that = this; this.showLoader(); require(['models/VCatalog'], function(VCatalog) { var termModel = new VCatalog(), url = that.$('.taxonomyTree').find('li.active a').data('href'); var termName = that.$('.taxonomyTree').find('li.active a').text(); termModel.deleteTerm(url, { skipDefaultError: true, success: function(data) { Utils.notifySuccess({ content: "Term " + termName + Messages.deleteSuccessMessage }); var termURL = url.split("/").slice(0, -2).join("/"); if (that.viewBased) { Utils.setUrl({ url: "#!/taxonomy/detailCatalog" + termURL, mergeBrowserUrl: false, trigger: true, updateTabState: function() { return { taxonomyUrl: this.url, stateChanged: true }; } }); } that.fetchCollection(termURL, true); }, cust_error: function(model, response) { var message = "Term " + termName + Messages.deleteErrorMessage; if (response && response.responseJSON) { message = response.responseJSON.errorMessage; } Utils.notifyError({ content: message }); }, complete: function() { that.hideLoader(); } }); }); }, moveTerm: function() { var that = this; require([ 'views/business_catalog/MoveTermLayoutView', 'modules/Modal' ], function(MoveTermLayoutView, Modal) { var view = new MoveTermLayoutView({ taxanomyCollection: that.collection }); var modal = new Modal({ title: 'Move Term', content: view, okCloses: true, showFooter: true, allowCancel: true, okText: 'Move', }).open(); // modal.on('ok', function() { // that.saveAddTerm(view); // }); view.on('closeModal', function() { modal.trigger('cancel'); }); }); }, createDefaultTaxonomy: function() { var that = this; require([ 'views/business_catalog/AddTermLayoutView', 'modules/Modal' ], function(AddTermLayoutView, Modal) { var view = new AddTermLayoutView({ url: UrlLinks.taxonomiesApiUrl(), model: new that.parentCollection.model(), defaultTerm: true }); var modal = new Modal({ title: 'Taxonomy', content: view, okCloses: true, showFooter: true, allowCancel: true, okText: 'Create', }).open(); modal.$el.find('button.ok').attr('disabled', true); modal.on('ok', function() { that.saveDefaultTaxonomy(view); }); view.ui.termName.on('keyup', function() { if (this.value.indexOf(' ') >= 0) { modal.$el.find('button.ok').prop('disabled', true); view.ui.termName.addClass("addTermDisable"); view.$('.alertTerm').show(); } else { modal.$el.find('button.ok').prop('disabled', false); view.ui.termName.removeClass("addTermDisable"); view.$('.alertTerm').hide(); } }); view.on('closeModal', function() { modal.trigger('cancel'); }); }); }, saveDefaultTaxonomy: function(view) { var that = this; var url = view.url; view.model.url = url + "/" + view.ui.termName.val(); this.showLoader(); view.model.set({ description: view.ui.termDetail.val() }).save(null, { skipDefaultError: true, success: function(model, response) { that.fetchCollection(view.model.url, true); Utils.notifySuccess({ content: "Default taxonomy " + view.ui.termName.val() + Messages.addSuccessMessage }); }, cust_error: function(model, response) { Utils.notifyError({ content: "Default taxonomy " + view.ui.termName.val() + Messages.addErrorMessage }); }, complete: function() { that.hideLoader(); } }); } }); return TreeLayoutView; }); <|start_filename|>intg/src/main/java/org/apache/atlas/model/SearchFilter.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.model; import com.sun.jersey.core.util.MultivaluedMapImpl; import org.codehaus.jackson.annotate.JsonAutoDetect; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.map.annotate.JsonSerialize; import javax.ws.rs.core.MultivaluedMap; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; import static org.codehaus.jackson.annotate.JsonAutoDetect.Visibility.NONE; import static org.codehaus.jackson.annotate.JsonAutoDetect.Visibility.PUBLIC_ONLY; /** * Generic filter, to specify search criteria using name/value pairs. */ @JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) @JsonIgnoreProperties(ignoreUnknown=true) @XmlRootElement @XmlAccessorType(XmlAccessType.PROPERTY) public class SearchFilter { public static final String PARAM_TYPE = "type"; public static final String PARAM_NAME = "name"; public static final String PARAM_SUPERTYPE = "supertype"; public static final String PARAM_NOT_SUPERTYPE = "notsupertype"; /** * to specify whether the result should be sorted? If yes, whether asc or desc. */ public enum SortType { NONE, ASC, DESC } private MultivaluedMap<String, String> params = null; private long startIndex = 0; private long maxRows = Long.MAX_VALUE; private boolean getCount = true; private String sortBy = null; private SortType sortType = null; public SearchFilter() { setParams(null); } public SearchFilter(MultivaluedMap<String, String> params) { setParams(params); } public MultivaluedMap<String, String> getParams() { return params; } public void setParams(MultivaluedMap<String, String> params) { this.params = params; } public String getParam(String name) { String ret = null; if (name != null && params != null) { ret = params.getFirst(name); } return ret; } public List<String> getParams(String name) { List<String> ret = null; if (name != null && params != null) { ret = params.get(name); } return ret; } public void setParam(String name, String value) { if (name != null) { if (params == null) { params = new MultivaluedMapImpl(); } params.add(name, value); } } public void setParam(String name, List<String> values) { if (name != null) { if (params == null) { params = new MultivaluedMapImpl(); } params.put(name, values); } } public long getStartIndex() { return startIndex; } public void setStartIndex(long startIndex) { this.startIndex = startIndex; } public long getMaxRows() { return maxRows; } public void setMaxRows(long maxRows) { this.maxRows = maxRows; } public boolean isGetCount() { return getCount; } public void setGetCount(boolean getCount) { this.getCount = getCount; } public String getSortBy() { return sortBy; } public void setSortBy(String sortBy) { this.sortBy = sortBy; } public SortType getSortType() { return sortType; } public void setSortType(SortType sortType) { this.sortType = sortType; } } <|start_filename|>typesystem/src/test/java/org/apache/atlas/typesystem/types/ValidationTest.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.typesystem.types; import com.google.common.collect.ImmutableSet; import org.apache.atlas.typesystem.types.utils.TypesUtil; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class ValidationTest { @DataProvider(name = "attributeData") private Object[][] createAttributeData() { return new String[][]{{null, "type"}, {"", "type"}, {"name", null}, {"name", ""}}; } @Test(dataProvider = "attributeData", expectedExceptions = {IllegalArgumentException.class}) public void testAttributes(String name, String type) { TypesUtil.createRequiredAttrDef(name, type); } @DataProvider(name = "enumValueData") private Object[][] createEnumValueData() { return new String[][]{{null}, {""}}; } @Test(dataProvider = "enumValueData", expectedExceptions = {IllegalArgumentException.class}) public void testEnumValue(String name) { new EnumValue(name, 1); } @DataProvider(name = "enumTypeData") private Object[][] createEnumTypeData() { EnumValue value = new EnumValue("name", 1); return new Object[][]{{null, value}, {"", value}, {"name"}}; } @Test(dataProvider = "enumTypeData", expectedExceptions = {IllegalArgumentException.class}) public void testEnumType(String name, EnumValue... values) { new EnumTypeDefinition(name, values); } @DataProvider(name = "structTypeData") private Object[][] createStructTypeData() { AttributeDefinition value = TypesUtil.createRequiredAttrDef("name", "type"); return new Object[][]{{null, value}, {"", value}, {"name"}}; } @Test(dataProvider = "structTypeData", expectedExceptions = {IllegalArgumentException.class}) public void testStructType(String name, AttributeDefinition... values) { new StructTypeDefinition(name, values); } @DataProvider(name = "classTypeData") private Object[][] createClassTypeData() { return new Object[][]{{null}, {""}}; } @Test(dataProvider = "classTypeData", expectedExceptions = {IllegalArgumentException.class}) public void testClassType(String name) { AttributeDefinition value = TypesUtil.createRequiredAttrDef("name", "type"); TypesUtil.createClassTypeDef(name, ImmutableSet.of("super"), value); } @Test(dataProvider = "classTypeData", expectedExceptions = {IllegalArgumentException.class}) public void testTraitType(String name) { AttributeDefinition value = TypesUtil.createRequiredAttrDef("name", "type"); TypesUtil.createTraitTypeDef(name, ImmutableSet.of("super"), value); } @Test public void testValidTypes() { AttributeDefinition attribute = TypesUtil.createRequiredAttrDef("name", "type"); //class with no attributes TypesUtil.createClassTypeDef("name", ImmutableSet.of("super")); //class with no super types TypesUtil.createClassTypeDef("name", ImmutableSet.<String>of(), attribute); //trait with no attributes TypesUtil.createTraitTypeDef("name", ImmutableSet.of("super")); //trait with no super types TypesUtil.createTraitTypeDef("name", ImmutableSet.<String>of(), attribute); } } <|start_filename|>catalog/src/main/java/org/apache/atlas/catalog/definition/TaxonomyResourceDefinition.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.catalog.definition; import com.tinkerpop.pipes.PipeFunction; import com.tinkerpop.pipes.transform.TransformFunctionPipe; import org.apache.atlas.catalog.Request; import org.apache.atlas.catalog.TaxonomyResourceProvider; import org.apache.atlas.catalog.VertexWrapper; import org.apache.atlas.catalog.exception.InvalidPayloadException; import org.apache.atlas.catalog.projection.Projection; import org.apache.atlas.catalog.projection.ProjectionResult; import org.apache.atlas.typesystem.types.DataTypes; import org.apache.atlas.typesystem.types.utils.TypesUtil; import java.util.*; /** * Taxonomy resource definition. */ public class TaxonomyResourceDefinition extends BaseResourceDefinition { public TaxonomyResourceDefinition() { registerProperty(TypesUtil.createUniqueRequiredAttrDef("name", DataTypes.STRING_TYPE)); registerProperty(TypesUtil.createOptionalAttrDef("description", DataTypes.STRING_TYPE)); registerProperty(TypesUtil.createOptionalAttrDef(TaxonomyResourceProvider.NAMESPACE_ATTRIBUTE_NAME, DataTypes.STRING_TYPE)); //todo: combine with above registrations instanceProperties.add("name"); instanceProperties.add("description"); instanceProperties.add("creation_time"); collectionProperties.add("name"); collectionProperties.add("description"); projections.put("terms", getTermsProjection()); } @Override public void validateCreatePayload(Request request) throws InvalidPayloadException { super.validateCreatePayload(request); if (String.valueOf(request.getQueryProperties().get("name")).contains(".")) { throw new InvalidPayloadException("The \"name\" property may not contain the character '.'"); } } @Override public String getTypeName() { return "Taxonomy"; } @Override public String getIdPropertyName() { return "name"; } @Override public String resolveHref(Map<String, Object> properties) { return String.format("v1/taxonomies/%s", properties.get("name")); } private Projection getTermsProjection() { final String termsProjectionName = "terms"; return new Projection(termsProjectionName, Projection.Cardinality.SINGLE, new TransformFunctionPipe<>(new PipeFunction<VertexWrapper, Collection<ProjectionResult>>() { private String baseHref = "v1/taxonomies/"; @Override public Collection<ProjectionResult> compute(VertexWrapper v) { Map<String, Object> map = new HashMap<>(); map.put("href", baseHref + v.getProperty("name") + "/terms"); return Collections.singleton(new ProjectionResult(termsProjectionName, v, Collections.singleton(map))); } })); } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/converters/AtlasObjectIdConverter.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.converters; import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.AtlasException; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.TypeCategory; import org.apache.atlas.model.instance.AtlasEntity; import org.apache.atlas.model.instance.AtlasObjectId; import org.apache.atlas.type.AtlasEntityType; import org.apache.atlas.type.AtlasType; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.typesystem.IReferenceableInstance; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.persistence.Id; import org.apache.atlas.typesystem.persistence.StructInstance; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import java.util.Map; public class AtlasObjectIdConverter extends AtlasAbstractFormatConverter { public AtlasObjectIdConverter(AtlasFormatConverters registry, AtlasTypeRegistry typeRegistry) { this(registry, typeRegistry, TypeCategory.OBJECT_ID_TYPE); } protected AtlasObjectIdConverter(AtlasFormatConverters registry, AtlasTypeRegistry typeRegistry, TypeCategory typeCategory) { super(registry, typeRegistry, typeCategory); } @Override public Object fromV1ToV2(Object v1Obj, AtlasType type, AtlasFormatConverter.ConverterContext converterContext) throws AtlasBaseException { Object ret = null; if (v1Obj != null) { if (v1Obj instanceof Id) { Id id = (Id) v1Obj; ret = new AtlasObjectId(id._getId(), id.getTypeName()); } else if (v1Obj instanceof IReferenceableInstance) { IReferenceableInstance refInst = (IReferenceableInstance) v1Obj; String guid = refInst.getId()._getId(); ret = new AtlasObjectId(guid, refInst.getTypeName()); if (!converterContext.entityExists(guid) && hasAnyAssignedAttribute(refInst)) { AtlasEntityType entityType = typeRegistry.getEntityTypeByName(refInst.getTypeName()); AtlasEntityFormatConverter converter = (AtlasEntityFormatConverter) converterRegistry.getConverter(TypeCategory.ENTITY); AtlasEntity entity = converter.fromV1ToV2(v1Obj, entityType, converterContext); converterContext.addReferredEntity(entity); } } } return ret; } @Override public Object fromV2ToV1(Object v2Obj, AtlasType type, ConverterContext converterContext) throws AtlasBaseException { Id ret = null; if (v2Obj != null) { if (v2Obj instanceof Map) { Map v2Map = (Map) v2Obj; String idStr = (String)v2Map.get(AtlasObjectId.KEY_GUID); String typeName = type.getTypeName(); if (StringUtils.isEmpty(idStr)) { throw new AtlasBaseException(AtlasErrorCode.INSTANCE_GUID_NOT_FOUND); } ret = new Id(idStr, 0, typeName); } else if (v2Obj instanceof AtlasObjectId) { // transient-id ret = new Id(((AtlasObjectId) v2Obj).getGuid(), 0, type.getTypeName()); } else if (v2Obj instanceof AtlasEntity) { AtlasEntity entity = (AtlasEntity) v2Obj; ret = new Id(((AtlasObjectId) v2Obj).getGuid(), 0, type.getTypeName()); } else { throw new AtlasBaseException(AtlasErrorCode.TYPE_CATEGORY_INVALID, type.getTypeCategory().name()); } } return ret; } private boolean hasAnyAssignedAttribute(IReferenceableInstance rInstance) { boolean ret = false; if (rInstance instanceof StructInstance) { StructInstance sInstance = (StructInstance) rInstance; Map<String, Object> attributes = null; try { attributes = sInstance.getValuesMap(); } catch (AtlasException e) { // ignore } if (MapUtils.isNotEmpty(attributes)) { for (String attrName : attributes.keySet()) { try { if (sInstance.isValueSet(attrName)) { ret = true; break; } } catch (AtlasException e) { // ignore } } } } else if (rInstance instanceof Referenceable) { Referenceable referenceable = (Referenceable) rInstance; ret = MapUtils.isNotEmpty(referenceable.getValuesMap()); } return ret; } } <|start_filename|>repository/src/test/java/org/apache/atlas/repository/store/graph/v1/HardDeleteHandlerV1Test.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.store.graph.v1; import org.apache.atlas.AtlasClient; import org.apache.atlas.AtlasException; import org.apache.atlas.TestModules; import org.apache.atlas.TestUtils; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.instance.AtlasEntity; import org.apache.atlas.model.instance.AtlasEntityHeader; import org.apache.atlas.model.instance.AtlasObjectId; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.graph.GraphHelper; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.typesystem.IStruct; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.ITypedStruct; import org.testng.Assert; import org.testng.annotations.Guice; import java.util.List; import java.util.Map; import static org.apache.atlas.TestUtils.COLUMNS_ATTR_NAME; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNull; import static org.testng.Assert.fail; import static org.testng.AssertJUnit.assertNotNull; @Guice(modules = TestModules.HardDeleteModule.class) public class HardDeleteHandlerV1Test extends AtlasDeleteHandlerV1Test { @Override protected void assertTableForTestDeleteReference(String tableId) { //entity is deleted. So, no assertions } @Override protected void assertColumnForTestDeleteReference(final AtlasEntity.AtlasEntityWithExtInfo tableInstance) throws AtlasBaseException { List<AtlasObjectId> columns = (List<AtlasObjectId>) tableInstance.getEntity().getAttribute(COLUMNS_ATTR_NAME); assertNull(columns); } @Override protected void assertProcessForTestDeleteReference(final AtlasEntityHeader processInstance) throws Exception { //assert that outputs is empty ITypedReferenceableInstance newProcess = metadataService.getEntityDefinition(processInstance.getGuid()); assertNull(newProcess.get(AtlasClient.PROCESS_ATTRIBUTE_OUTPUTS)); } @Override protected void assertEntityDeleted(String id) throws Exception { try { entityStore.getById(id); fail("Expected EntityNotFoundException"); } catch (AtlasBaseException e) { // expected } } @Override protected void assertDeletedColumn(final AtlasEntity.AtlasEntityWithExtInfo tableInstance) throws AtlasException { final List<AtlasObjectId> columns = (List<AtlasObjectId>) tableInstance.getEntity().getAttribute(COLUMNS_ATTR_NAME); Assert.assertEquals(columns.size(), 2); } @Override protected void assertTestDeleteEntities(AtlasEntity.AtlasEntityWithExtInfo tableInstance) { int vertexCount = getVertices(Constants.ENTITY_TYPE_PROPERTY_KEY, TestUtils.TABLE_TYPE).size(); assertEquals(vertexCount, 0); vertexCount = getVertices(Constants.ENTITY_TYPE_PROPERTY_KEY, TestUtils.COLUMN_TYPE).size(); assertEquals(vertexCount, 0); } @Override protected void assertVerticesDeleted(List<AtlasVertex> vertices) { assertEquals(vertices.size(), 0); } @Override protected void assertTestUpdateEntity_MultiplicityOneNonCompositeReference(String janeGuid) throws Exception { // Verify that max is no longer a subordinate of jane. ITypedReferenceableInstance jane = metadataService.getEntityDefinition(janeGuid); List<ITypedReferenceableInstance> subordinates = (List<ITypedReferenceableInstance>) jane.get("subordinates"); Assert.assertEquals(subordinates.size(), 1); } @Override protected void assertJohnForTestDisconnectBidirectionalReferences(final AtlasEntity.AtlasEntityWithExtInfo john, final String janeGuid) throws Exception { assertNull(john.getEntity().getAttribute("manager")); } @Override protected void assertMaxForTestDisconnectBidirectionalReferences(Map<String, String> nameGuidMap) throws Exception { // Verify that the Department.employees reference to the deleted employee // was disconnected. ITypedReferenceableInstance hrDept = metadataService.getEntityDefinition(nameGuidMap.get("hr")); List<ITypedReferenceableInstance> employees = (List<ITypedReferenceableInstance>) hrDept.get("employees"); Assert.assertEquals(employees.size(), 3); String maxGuid = nameGuidMap.get("Max"); for (ITypedReferenceableInstance employee : employees) { Assert.assertNotEquals(employee.getId()._getId(), maxGuid); } // Verify that the Manager.subordinates reference to the deleted employee // Max was disconnected. ITypedReferenceableInstance jane = metadataService.getEntityDefinition(nameGuidMap.get("Jane")); List<ITypedReferenceableInstance> subordinates = (List<ITypedReferenceableInstance>) jane.get("subordinates"); assertEquals(subordinates.size(), 1); // Verify that max's Person.mentor unidirectional reference to john was disconnected. ITypedReferenceableInstance john = metadataService.getEntityDefinition(nameGuidMap.get("John")); assertNull(john.get("mentor")); } @Override protected void assertTestDisconnectUnidirectionalArrayReferenceFromClassType( List<AtlasObjectId> columns, String columnGuid) { assertEquals(columns.size(), 2); for (AtlasObjectId column : columns) { assertFalse(column.getGuid().equals(columnGuid)); } } protected void assertTestDisconnectMapReferenceFromClassType(final String mapOwnerGuid) throws Exception { // Verify map references from mapOwner were disconnected. AtlasEntity.AtlasEntityWithExtInfo mapOwnerInstance = entityStore.getById(mapOwnerGuid); Map<String, AtlasObjectId> map = (Map<String, AtlasObjectId>) mapOwnerInstance.getEntity().getAttribute("map"); Assert.assertNull(map); Map<String, AtlasObjectId> biMap = (Map<String, AtlasObjectId>) mapOwnerInstance.getEntity().getAttribute("biMap"); Assert.assertNull(biMap); AtlasVertex mapOwnerVertex = GraphHelper.getInstance().getVertexForGUID(mapOwnerGuid); Object object = mapOwnerVertex.getProperty("MapOwner.map.value1", String.class); assertNull(object); object = mapOwnerVertex.getProperty("MapOwner.biMap.value1", String.class); assertNull(object); } @Override protected void assertTestDisconnectUnidirectionalArrayReferenceFromStructAndTraitTypes(String structContainerGuid) throws Exception { // Verify that the unidirectional references from the struct and trait instances // to the deleted entities were disconnected. ITypedReferenceableInstance structContainerConvertedEntity = metadataService.getEntityDefinition(structContainerGuid); ITypedStruct struct = (ITypedStruct) structContainerConvertedEntity.get("struct"); assertNull(struct.get("target")); IStruct trait = structContainerConvertedEntity.getTrait("TestTrait"); assertNotNull(trait); assertNull(trait.get("target")); } } <|start_filename|>repository/src/main/java/org/apache/atlas/gremlin/optimizer/FunctionGenerator.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.gremlin.optimizer; import java.util.List; import org.apache.atlas.gremlin.GremlinExpressionFactory; import org.apache.atlas.groovy.AbstractFunctionExpression; import org.apache.atlas.groovy.ClosureExpression; import org.apache.atlas.groovy.ClosureExpression.VariableDeclaration; import org.apache.atlas.groovy.FunctionCallExpression; import org.apache.atlas.groovy.GroovyExpression; import org.apache.atlas.groovy.IdentifierExpression; /** * Extracts common expressions from an or-containing expression * into functions. These expressions would otherwise be duplicated * as part of expanding the "or". Doing this shortens the overall length * of the Gremlin script so we can maximize query performance. * */ public class FunctionGenerator implements CallHierarchyVisitor { //Function length constants. //These assume we won't reach more than 9 function definition. Even if we do, this is still //a reasonable approximation. private static final int INITIAL_FUNCTION_DEF_LENGTH = "def f1={};".length(); private final int functionDefLength; private static final int FUNCTION_CALL_OVERHEAD = "f1()".length(); /** * The expression that should be the first (deepest) expression * in the body of the next generated function. As we go up the * expression tree in the post visit, this is updated based on the * expressions we see. During the post visits, if it is null, * the body expression is set to the expression we're visiting. * As we go up the tree, it is nulled out if we create a function * or encounter an or expression. This guarantees that the * next function body will not contain any or expressions * and that it will not have expressions that are already * part of some other function. */ private GroovyExpression nextFunctionBodyStart; /** * The number of times expressions will be duplicated. */ private int scaleFactor = 1; private final OptimizationContext context; /** * The current depth in the expression tree. */ private int depth = 0; /** * The name of the last function that was generated. If set, * we can safely update this function instead of creating a new one. */ private String currentFunctionName; /** * The updated expression we will pass back to the caller. */ private GroovyExpression newRootExpression; private final GremlinExpressionFactory factory; public FunctionGenerator(GremlinExpressionFactory factory, OptimizationContext context) { this.context = context; this.factory = factory; functionDefLength = ("def f1={" + factory.getTraversalExpressionClass() + " x->};").length(); } @Override public boolean preVisitFunctionCaller(AbstractFunctionExpression expr) { depth++; if (IsOr.INSTANCE.apply(expr)) { FunctionCallExpression functionCall = (FunctionCallExpression) expr; scaleFactor *= functionCall.getArguments().size(); } if (newRootExpression == null) { newRootExpression = expr; } return true; } @Override public void visitNonFunctionCaller(GroovyExpression expr) { if (nextFunctionBodyStart == null) { nextFunctionBodyStart = expr; } } @Override public void visitNullCaller() { //nothing to do } @Override public boolean postVisitFunctionCaller(AbstractFunctionExpression expr) { boolean isRootExpr = depth == 1; visitParentExpression(expr); //The root expression has no parent. To simplify the logic, we create //a dummy expression so it does have a parent, then call visitParentExpression again //to examine the root expression. if (isRootExpr) { FunctionCallExpression dummyParent = new FunctionCallExpression(expr, "dummy"); visitParentExpression(dummyParent); newRootExpression = dummyParent.getCaller(); } depth--; return true; } /** * Checks to see if the *caller* of this expression should become part * of a function. If so, either a new function is created, or the * expression becomes part of the last function we created. * * @param parentExpr */ private void visitParentExpression(AbstractFunctionExpression parentExpr) { if (nextFunctionBodyStart == null) { nextFunctionBodyStart = parentExpr; } if (currentFunctionName != null) { updateCurrentFunction(parentExpr); } else { createFunctionIfNeeded(parentExpr); } if (GremlinQueryOptimizer.isOrExpression(parentExpr)) { //reset currentFunctionName = null; //don't include 'or' in generated functions nextFunctionBodyStart = null; } } /** * Creates a function whose body goes from the child of parentExpr * up to (and including) the functionBodyEndExpr. * @param parentExpr */ private void createFunctionIfNeeded(AbstractFunctionExpression parentExpr) { GroovyExpression potentialFunctionBody = parentExpr.getCaller(); if (creatingFunctionShortensGremlin(potentialFunctionBody)) { GroovyExpression functionCall = null; if (nextFunctionBodyStart instanceof AbstractFunctionExpression) { //The function body start is a a function call. In this //case, we generate a function that takes one argument, which //is a graph traversal. We have an expression tree that //looks kind of like the following: // // parentExpr // / // / caller // |/_ // potentialFunctionBody // / // / caller // |/_ // ... // / // / caller // |/_ // nextFunctionBodyStart // / // / caller // |/_ // oldCaller // // // Note that potentialFunctionBody and nextFunctionBodyStart // could be the same expression. Let's say that the next // function name is f1 // // We reshuffle these expressions to the following: // // parentExpr // / // / caller // |/_ // f1(oldCaller) // // // potentialFunctionBody <- body of new function "f1(GraphTraversal x)" // / // / caller // |/_ // ... // / // / caller // |/_ // nextFunctionBodyStart // / // / caller // |/_ // x // // As an example, suppose parentExpr is g.V().or(x,y).has(a).has(b).has(c) // where has(a) is nextFunctionBodyStart. // // We generate a function f1 = { GraphTraversal x -> x.has(a).has(b) } // parentExpr would become : f1(g.V().or(x,y)).has(c) AbstractFunctionExpression nextFunctionBodyStartFunction= (AbstractFunctionExpression) nextFunctionBodyStart; String variableName = "x"; IdentifierExpression var = new IdentifierExpression(variableName); GroovyExpression oldCaller = nextFunctionBodyStartFunction.getCaller(); nextFunctionBodyStartFunction.setCaller(var); currentFunctionName = context.addFunctionDefinition(new VariableDeclaration(factory.getTraversalExpressionClass(), "x"), potentialFunctionBody); functionCall = new FunctionCallExpression(potentialFunctionBody.getType(), currentFunctionName, oldCaller); } else { //The function body start is a not a function call. In this //case, we generate a function that takes no arguments. // As an example, suppose parentExpr is g.V().has(a).has(b).has(c) // where g is nextFunctionBodyStart. // // We generate a function f1 = { g.V().has(a).has(b) } // parentExpr would become : f1().has(c) currentFunctionName = context.addFunctionDefinition(null, potentialFunctionBody); functionCall = new FunctionCallExpression(potentialFunctionBody.getType(), currentFunctionName); } //functionBodyEnd is now part of a function definition, don't propagate it nextFunctionBodyStart = null; parentExpr.setCaller(functionCall); } } /** * Adds the caller of parentExpr to the current body of the last * function that was created. * * @param parentExpr */ private void updateCurrentFunction(AbstractFunctionExpression parentExpr) { GroovyExpression expr = parentExpr.getCaller(); if (expr instanceof AbstractFunctionExpression) { AbstractFunctionExpression exprAsFunction = (AbstractFunctionExpression) expr; GroovyExpression exprCaller = exprAsFunction.getCaller(); parentExpr.setCaller(exprCaller); updateCurrentFunctionDefintion(exprAsFunction); } } private void updateCurrentFunctionDefintion(AbstractFunctionExpression exprToAdd) { ClosureExpression functionBodyClosure = context.getUserDefinedFunctionBody(currentFunctionName); if (functionBodyClosure == null) { throw new IllegalStateException("User-defined function " + currentFunctionName + " not found!"); } List<GroovyExpression> exprs = functionBodyClosure.getStatements(); GroovyExpression currentFunctionBody = exprs.get(exprs.size() - 1); //Update the expression so it is called by the current return //value of the function. exprToAdd.setCaller(currentFunctionBody); functionBodyClosure.replaceStatement(exprs.size() - 1, exprToAdd); } //Determines if extracting this expression into a function will shorten //the overall length of the Groovy script. private boolean creatingFunctionShortensGremlin(GroovyExpression headExpr) { int tailLength = getTailLength(); int length = headExpr.toString().length() - tailLength; int overhead = 0; if (nextFunctionBodyStart instanceof AbstractFunctionExpression) { overhead = functionDefLength; } else { overhead = INITIAL_FUNCTION_DEF_LENGTH; } overhead += FUNCTION_CALL_OVERHEAD * scaleFactor; //length * scaleFactor = space taken by having the expression be inlined [scaleFactor] times //overhead + length = space taken by the function definition and its calls return length * scaleFactor > overhead + length; } private int getTailLength() { if (nextFunctionBodyStart == null) { return 0; } if (!(nextFunctionBodyStart instanceof AbstractFunctionExpression)) { return 0; } AbstractFunctionExpression bodyEndAsFunction = (AbstractFunctionExpression) nextFunctionBodyStart; return bodyEndAsFunction.getCaller().toString().length(); } public GroovyExpression getNewRootExpression() { return newRootExpression; } } <|start_filename|>server-api/src/main/java/org/apache/atlas/listener/EntityChangeListener.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.listener; import org.apache.atlas.AtlasException; import org.apache.atlas.typesystem.IStruct; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import java.util.Collection; /** * Entity (a Typed instance) change notification listener. */ public interface EntityChangeListener { /** * This is upon adding new entities to the repository. * * @param entities the created entities * * @param isImport * @throws AtlasException if the listener notification fails */ void onEntitiesAdded(Collection<ITypedReferenceableInstance> entities, boolean isImport) throws AtlasException; /** * This is upon updating an entity. * * @param entities the updated entities * * @param isImport * @throws AtlasException if the listener notification fails */ void onEntitiesUpdated(Collection<ITypedReferenceableInstance> entities, boolean isImport) throws AtlasException; /** * This is upon adding a new trait to a typed instance. * * @param entity the entity * @param traits trait that needs to be added to entity * * @throws AtlasException if the listener notification fails */ void onTraitsAdded(ITypedReferenceableInstance entity, Collection<? extends IStruct> traits) throws AtlasException; /** * This is upon deleting a trait from a typed instance. * * @param entity the entity * @param traitNames trait name for the instance that needs to be deleted from entity * * @throws AtlasException if the listener notification fails */ void onTraitsDeleted(ITypedReferenceableInstance entity, Collection<String> traitNames) throws AtlasException; /** * This is upon updating a trait from a typed instance. * * @param entity the entity * @param traits trait that needs to be added to entity * * @throws AtlasException if the listener notification fails */ void onTraitsUpdated(ITypedReferenceableInstance entity, Collection<? extends IStruct> traits) throws AtlasException; /** * This is upon deleting entities from the repository. * * @param entities the deleted entities * @param isImport * @throws AtlasException */ void onEntitiesDeleted(Collection<ITypedReferenceableInstance> entities, boolean isImport) throws AtlasException; } <|start_filename|>addons/hive-bridge/src/main/java/org/apache/atlas/hive/hook/HiveHook.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.hive.hook; import com.google.common.annotations.VisibleForTesting; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.apache.atlas.AtlasClient; import org.apache.atlas.AtlasConstants; import org.apache.atlas.hive.bridge.ColumnLineageUtils; import org.apache.atlas.hive.bridge.HiveMetaStoreBridge; import org.apache.atlas.hive.model.HiveDataTypes; import org.apache.atlas.hook.AtlasHook; import org.apache.atlas.hook.AtlasHookException; import org.apache.atlas.notification.hook.HookNotification; import org.apache.atlas.typesystem.Referenceable; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.metastore.TableType; import org.apache.hadoop.hive.metastore.api.Database; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.ql.hooks.Entity; import org.apache.hadoop.hive.ql.hooks.Entity.Type; import org.apache.hadoop.hive.ql.hooks.ExecuteWithHookContext; import org.apache.hadoop.hive.ql.hooks.HookContext; import org.apache.hadoop.hive.ql.hooks.LineageInfo; import org.apache.hadoop.hive.ql.hooks.ReadEntity; import org.apache.hadoop.hive.ql.hooks.WriteEntity; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.metadata.Partition; import org.apache.hadoop.hive.ql.metadata.Table; import org.apache.hadoop.hive.ql.plan.HiveOperation; import org.apache.hadoop.hive.shims.Utils; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.util.ShutdownHookManager; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.MalformedURLException; import java.net.URI; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * AtlasHook sends lineage information to the AtlasSever. */ public class HiveHook extends AtlasHook implements ExecuteWithHookContext { private static final Logger LOG = LoggerFactory.getLogger(HiveHook.class); public static final String CONF_PREFIX = "atlas.hook.hive."; private static final String MIN_THREADS = CONF_PREFIX + "minThreads"; private static final String MAX_THREADS = CONF_PREFIX + "maxThreads"; private static final String KEEP_ALIVE_TIME = CONF_PREFIX + "keepAliveTime"; public static final String CONF_SYNC = CONF_PREFIX + "synchronous"; public static final String QUEUE_SIZE = CONF_PREFIX + "queueSize"; public static final String HOOK_NUM_RETRIES = CONF_PREFIX + "numRetries"; public static final String SEP = ":".intern(); static final String IO_SEP = "->".intern(); private static final Map<String, HiveOperation> OPERATION_MAP = new HashMap<>(); // wait time determines how long we wait before we exit the jvm on // shutdown. Pending requests after that will not be sent. private static final int WAIT_TIME = 3; private static ExecutorService executor = null; private static final int minThreadsDefault = 1; private static final int maxThreadsDefault = 5; private static final long keepAliveTimeDefault = 10; private static final int queueSizeDefault = 10000; private static final HiveConf hiveConf; static { try { // initialize the async facility to process hook calls. We don't // want to do this inline since it adds plenty of overhead for the query. boolean isSync = atlasProperties.getBoolean(CONF_SYNC, Boolean.FALSE); if(!isSync) { int minThreads = atlasProperties.getInt(MIN_THREADS, minThreadsDefault); int maxThreads = atlasProperties.getInt(MAX_THREADS, maxThreadsDefault); long keepAliveTime = atlasProperties.getLong(KEEP_ALIVE_TIME, keepAliveTimeDefault); int queueSize = atlasProperties.getInt(QUEUE_SIZE, queueSizeDefault); executor = new ThreadPoolExecutor(minThreads, maxThreads, keepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(queueSize), new ThreadFactoryBuilder().setNameFormat("Atlas Logger %d").build()); ShutdownHookManager.get().addShutdownHook(new Thread() { @Override public void run() { try { LOG.info("==> Shutdown of Atlas Hive Hook"); executor.shutdown(); executor.awaitTermination(WAIT_TIME, TimeUnit.SECONDS); executor = null; } catch (InterruptedException ie) { LOG.info("Interrupt received in shutdown."); } finally { LOG.info("<== Shutdown of Atlas Hive Hook"); } // shutdown client } }, AtlasConstants.ATLAS_SHUTDOWN_HOOK_PRIORITY); } setupOperationMap(); } catch (Exception e) { LOG.info("Attempting to send msg while shutdown in progress.", e); } hiveConf = new HiveConf(); LOG.info("Created Atlas Hook"); } private static void setupOperationMap() { //Populate OPERATION_MAP - string to HiveOperation mapping for (HiveOperation hiveOperation : HiveOperation.values()) { OPERATION_MAP.put(hiveOperation.getOperationName(), hiveOperation); } } @Override protected String getNumberOfRetriesPropertyKey() { return HOOK_NUM_RETRIES; } @Override public void run(final HookContext hookContext) throws Exception { // clone to avoid concurrent access try { final HiveEventContext event = new HiveEventContext(); event.setInputs(hookContext.getInputs()); event.setOutputs(hookContext.getOutputs()); event.setHookType(hookContext.getHookType()); final UserGroupInformation ugi = hookContext.getUgi() == null ? Utils.getUGI() : hookContext.getUgi(); event.setUgi(ugi); event.setUser(getUser(hookContext.getUserName(), hookContext.getUgi())); event.setOperation(OPERATION_MAP.get(hookContext.getOperationName())); event.setQueryId(hookContext.getQueryPlan().getQueryId()); event.setQueryStr(hookContext.getQueryPlan().getQueryStr()); event.setQueryStartTime(hookContext.getQueryPlan().getQueryStartTime()); event.setQueryType(hookContext.getQueryPlan().getQueryPlan().getQueryType()); event.setLineageInfo(hookContext.getLinfo()); if (executor == null) { collect(event); notifyAsPrivilegedAction(event); } else { executor.submit(new Runnable() { @Override public void run() { try { ugi.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { collect(event); return event; } }); notifyAsPrivilegedAction(event); } catch (Throwable e) { LOG.error("Atlas hook failed due to error ", e); } } }); } } catch (Throwable t) { LOG.error("Submitting to thread pool failed due to error ", t); } } void notifyAsPrivilegedAction(final HiveEventContext event) { try { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notifyEntities(event.getMessages()); return event; } }; //Notify as 'hive' service user in doAs mode UserGroupInformation realUser = event.getUgi().getRealUser(); if (realUser != null) { LOG.info("Sending notification for event {} as service user {} #messages {} ", event.getOperation(), realUser.getShortUserName(), event.getMessages().size()); realUser.doAs(privilegedNotify); } else { LOG.info("Sending notification for event {} as current user {} #messages {} ", event.getOperation(), event.getUgi().getShortUserName(), event.getMessages().size()); event.getUgi().doAs(privilegedNotify); } } catch(Throwable e) { LOG.error("Error during notify {} ", event.getOperation(), e); } } private void collect(HiveEventContext event) throws Exception { assert event.getHookType() == HookContext.HookType.POST_EXEC_HOOK : "Non-POST_EXEC_HOOK not supported!"; LOG.info("Entered Atlas hook for hook type {}, operation {} , user {} as {}", event.getHookType(), event.getOperation(), event.getUgi().getRealUser(), event.getUgi().getShortUserName()); HiveMetaStoreBridge dgiBridge = new HiveMetaStoreBridge(atlasProperties, hiveConf); switch (event.getOperation()) { case CREATEDATABASE: handleEventOutputs(dgiBridge, event, Type.DATABASE); break; case CREATETABLE: LinkedHashMap<Type, Referenceable> tablesCreated = handleEventOutputs(dgiBridge, event, Type.TABLE); if (tablesCreated != null && tablesCreated.size() > 0) { handleExternalTables(dgiBridge, event, tablesCreated); } break; case CREATETABLE_AS_SELECT: case CREATEVIEW: case ALTERVIEW_AS: case LOAD: case EXPORT: case IMPORT: case QUERY: case TRUNCATETABLE: registerProcess(dgiBridge, event); break; case ALTERTABLE_RENAME: case ALTERVIEW_RENAME: renameTable(dgiBridge, event); break; case ALTERTABLE_FILEFORMAT: case ALTERTABLE_CLUSTER_SORT: case ALTERTABLE_BUCKETNUM: case ALTERTABLE_PROPERTIES: case ALTERVIEW_PROPERTIES: case ALTERTABLE_SERDEPROPERTIES: case ALTERTABLE_SERIALIZER: case ALTERTABLE_ADDCOLS: case ALTERTABLE_REPLACECOLS: case ALTERTABLE_PARTCOLTYPE: handleEventOutputs(dgiBridge, event, Type.TABLE); break; case ALTERTABLE_RENAMECOL: renameColumn(dgiBridge, event); break; case ALTERTABLE_LOCATION: LinkedHashMap<Type, Referenceable> tablesUpdated = handleEventOutputs(dgiBridge, event, Type.TABLE); if (tablesUpdated != null && tablesUpdated.size() > 0) { //Track altered lineage in case of external tables handleExternalTables(dgiBridge, event, tablesUpdated); } break; case ALTERDATABASE: case ALTERDATABASE_OWNER: handleEventOutputs(dgiBridge, event, Type.DATABASE); break; case DROPTABLE: case DROPVIEW: deleteTable(dgiBridge, event); break; case DROPDATABASE: deleteDatabase(dgiBridge, event); break; default: } } private void deleteTable(HiveMetaStoreBridge dgiBridge, HiveEventContext event) { for (WriteEntity output : event.getOutputs()) { if (Type.TABLE.equals(output.getType())) { deleteTable(dgiBridge, event, output); } } } private void deleteTable(HiveMetaStoreBridge dgiBridge, HiveEventContext event, WriteEntity output) { final String tblQualifiedName = HiveMetaStoreBridge.getTableQualifiedName(dgiBridge.getClusterName(), output.getTable()); LOG.info("Deleting table {} ", tblQualifiedName); event.addMessage( new HookNotification.EntityDeleteRequest(event.getUser(), HiveDataTypes.HIVE_TABLE.getName(), AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, tblQualifiedName)); } private void deleteDatabase(HiveMetaStoreBridge dgiBridge, HiveEventContext event) { if (event.getOutputs().size() > 1) { LOG.info("Starting deletion of tables and databases with cascade {} ", event.getQueryStr()); } else { LOG.info("Starting deletion of database {} ", event.getQueryStr()); } for (WriteEntity output : event.getOutputs()) { if (Type.TABLE.equals(output.getType())) { deleteTable(dgiBridge, event, output); } else if (Type.DATABASE.equals(output.getType())) { final String dbQualifiedName = HiveMetaStoreBridge.getDBQualifiedName(dgiBridge.getClusterName(), output.getDatabase().getName()); event.addMessage( new HookNotification.EntityDeleteRequest(event.getUser(), HiveDataTypes.HIVE_DB.getName(), AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, dbQualifiedName)); } } } private Pair<String, String> findChangedColNames(List<FieldSchema> oldColList, List<FieldSchema> newColList) { HashMap<FieldSchema, Integer> oldColHashMap = new HashMap<>(); HashMap<FieldSchema, Integer> newColHashMap = new HashMap<>(); for (int i = 0; i < oldColList.size(); i++) { oldColHashMap.put(oldColList.get(i), i); newColHashMap.put(newColList.get(i), i); } String changedColStringOldName = oldColList.get(0).getName(); String changedColStringNewName = changedColStringOldName; for (FieldSchema oldCol : oldColList) { if (!newColHashMap.containsKey(oldCol)) { changedColStringOldName = oldCol.getName(); break; } } for (FieldSchema newCol : newColList) { if (!oldColHashMap.containsKey(newCol)) { changedColStringNewName = newCol.getName(); break; } } return Pair.of(changedColStringOldName, changedColStringNewName); } private void renameColumn(HiveMetaStoreBridge dgiBridge, HiveEventContext event) throws AtlasHookException { try { assert event.getInputs() != null && event.getInputs().size() == 1; assert event.getOutputs() != null && event.getOutputs().size() > 0; Table oldTable = event.getInputs().iterator().next().getTable(); List<FieldSchema> oldColList = oldTable.getAllCols(); Table outputTbl = event.getOutputs().iterator().next().getTable(); outputTbl = dgiBridge.hiveClient.getTable(outputTbl.getDbName(), outputTbl.getTableName()); List<FieldSchema> newColList = outputTbl.getAllCols(); assert oldColList.size() == newColList.size(); Pair<String, String> changedColNamePair = findChangedColNames(oldColList, newColList); String oldColName = changedColNamePair.getLeft(); String newColName = changedColNamePair.getRight(); for (WriteEntity writeEntity : event.getOutputs()) { if (writeEntity.getType() == Type.TABLE) { Table newTable = writeEntity.getTable(); createOrUpdateEntities(dgiBridge, event, writeEntity, true, oldTable); final String newQualifiedTableName = HiveMetaStoreBridge.getTableQualifiedName(dgiBridge.getClusterName(), newTable); String oldColumnQFName = HiveMetaStoreBridge.getColumnQualifiedName(newQualifiedTableName, oldColName); String newColumnQFName = HiveMetaStoreBridge.getColumnQualifiedName(newQualifiedTableName, newColName); Referenceable newColEntity = new Referenceable(HiveDataTypes.HIVE_COLUMN.getName()); newColEntity.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, newColumnQFName); event.addMessage(new HookNotification.EntityPartialUpdateRequest(event.getUser(), HiveDataTypes.HIVE_COLUMN.getName(), AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, oldColumnQFName, newColEntity)); } } handleEventOutputs(dgiBridge, event, Type.TABLE); } catch(Exception e) { throw new AtlasHookException("HiveHook.renameColumn() failed.", e); } } private void renameTable(HiveMetaStoreBridge dgiBridge, HiveEventContext event) throws AtlasHookException { try { //crappy, no easy of getting new name assert event.getInputs() != null && event.getInputs().size() == 1; assert event.getOutputs() != null && event.getOutputs().size() > 0; //Update entity if not exists ReadEntity oldEntity = event.getInputs().iterator().next(); Table oldTable = oldEntity.getTable(); for (WriteEntity writeEntity : event.getOutputs()) { if (writeEntity.getType() == Entity.Type.TABLE) { Table newTable = writeEntity.getTable(); //Hive sends with both old and new table names in the outputs which is weird. So skipping that with the below check if (!newTable.getDbName().equals(oldTable.getDbName()) || !newTable.getTableName().equals(oldTable.getTableName())) { final String oldQualifiedName = HiveMetaStoreBridge.getTableQualifiedName(dgiBridge.getClusterName(), oldTable); final String newQualifiedName = HiveMetaStoreBridge.getTableQualifiedName(dgiBridge.getClusterName(), newTable); //Create/update old table entity - create entity with oldQFNme and old tableName if it doesnt exist. If exists, will update //We always use the new entity while creating the table since some flags, attributes of the table are not set in inputEntity and Hive.getTable(oldTableName) also fails since the table doesnt exist in hive anymore final LinkedHashMap<Type, Referenceable> tables = createOrUpdateEntities(dgiBridge, event, writeEntity, true); Referenceable tableEntity = tables.get(Type.TABLE); //Reset regular column QF Name to old Name and create a new partial notification request to replace old column QFName to newName to retain any existing traits replaceColumnQFName(event, (List<Referenceable>) tableEntity.get(HiveMetaStoreBridge.COLUMNS), oldQualifiedName, newQualifiedName); //Reset partition key column QF Name to old Name and create a new partial notification request to replace old column QFName to newName to retain any existing traits replaceColumnQFName(event, (List<Referenceable>) tableEntity.get(HiveMetaStoreBridge.PART_COLS), oldQualifiedName, newQualifiedName); //Reset SD QF Name to old Name and create a new partial notification request to replace old SD QFName to newName to retain any existing traits replaceSDQFName(event, tableEntity, oldQualifiedName, newQualifiedName); //Reset Table QF Name to old Name and create a new partial notification request to replace old Table QFName to newName replaceTableQFName(event, oldTable, newTable, tableEntity, oldQualifiedName, newQualifiedName); } } } } catch(Exception e) { throw new AtlasHookException("HiveHook.renameTable() failed.", e); } } private Referenceable replaceTableQFName(HiveEventContext event, Table oldTable, Table newTable, final Referenceable tableEntity, final String oldTableQFName, final String newTableQFName) throws HiveException { tableEntity.set(AtlasClient.NAME, oldTable.getTableName().toLowerCase()); tableEntity.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, oldTableQFName); //Replace table entity with new name final Referenceable newEntity = new Referenceable(HiveDataTypes.HIVE_TABLE.getName()); newEntity.set(AtlasClient.NAME, newTable.getTableName().toLowerCase()); newEntity.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, newTableQFName); ArrayList<String> alias_list = new ArrayList<>(); alias_list.add(oldTable.getTableName().toLowerCase()); newEntity.set(HiveMetaStoreBridge.TABLE_ALIAS_LIST, alias_list); event.addMessage(new HookNotification.EntityPartialUpdateRequest(event.getUser(), HiveDataTypes.HIVE_TABLE.getName(), AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, oldTableQFName, newEntity)); return newEntity; } private List<Referenceable> replaceColumnQFName(final HiveEventContext event, final List<Referenceable> cols, final String oldTableQFName, final String newTableQFName) { List<Referenceable> newColEntities = new ArrayList<>(); for (Referenceable col : cols) { final String colName = (String) col.get(AtlasClient.NAME); String oldColumnQFName = HiveMetaStoreBridge.getColumnQualifiedName(oldTableQFName, colName); String newColumnQFName = HiveMetaStoreBridge.getColumnQualifiedName(newTableQFName, colName); col.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, oldColumnQFName); Referenceable newColEntity = new Referenceable(HiveDataTypes.HIVE_COLUMN.getName()); ///Only QF Name changes newColEntity.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, newColumnQFName); event.addMessage(new HookNotification.EntityPartialUpdateRequest(event.getUser(), HiveDataTypes.HIVE_COLUMN.getName(), AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, oldColumnQFName, newColEntity)); newColEntities.add(newColEntity); } return newColEntities; } private Referenceable replaceSDQFName(final HiveEventContext event, Referenceable tableEntity, final String oldTblQFName, final String newTblQFName) { //Reset storage desc QF Name to old Name final Referenceable sdRef = ((Referenceable) tableEntity.get(HiveMetaStoreBridge.STORAGE_DESC)); sdRef.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, HiveMetaStoreBridge.getStorageDescQFName(oldTblQFName)); //Replace SD QF name fir st to retain tags final String oldSDQFName = HiveMetaStoreBridge.getStorageDescQFName(oldTblQFName); final String newSDQFName = HiveMetaStoreBridge.getStorageDescQFName(newTblQFName); final Referenceable newSDEntity = new Referenceable(HiveDataTypes.HIVE_STORAGEDESC.getName()); newSDEntity.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, newSDQFName); event.addMessage(new HookNotification.EntityPartialUpdateRequest(event.getUser(), HiveDataTypes.HIVE_STORAGEDESC.getName(), AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, oldSDQFName, newSDEntity)); return newSDEntity; } private LinkedHashMap<Type, Referenceable> createOrUpdateEntities(HiveMetaStoreBridge dgiBridge, HiveEventContext event, Entity entity, boolean skipTempTables, Table existTable) throws AtlasHookException { try { Database db = null; Table table = null; Partition partition = null; LinkedHashMap<Type, Referenceable> result = new LinkedHashMap<>(); List<Referenceable> entities = new ArrayList<>(); switch (entity.getType()) { case DATABASE: db = entity.getDatabase(); break; case TABLE: table = entity.getTable(); db = dgiBridge.hiveClient.getDatabase(table.getDbName()); break; case PARTITION: partition = entity.getPartition(); table = partition.getTable(); db = dgiBridge.hiveClient.getDatabase(table.getDbName()); break; default: LOG.info("{}: entity-type not handled by Atlas hook. Ignored", entity.getType()); } if (db != null) { db = dgiBridge.hiveClient.getDatabase(db.getName()); } if (db != null) { Referenceable dbEntity = dgiBridge.createDBInstance(db); entities.add(dbEntity); result.put(Type.DATABASE, dbEntity); Referenceable tableEntity = null; if (table != null) { if (existTable != null) { table = existTable; } else { table = dgiBridge.hiveClient.getTable(table.getDbName(), table.getTableName()); } //If its an external table, even though the temp table skip flag is on, // we create the table since we need the HDFS path to temp table lineage. if (skipTempTables && table.isTemporary() && !TableType.EXTERNAL_TABLE.equals(table.getTableType())) { LOG.debug("Skipping temporary table registration {} since it is not an external table {} ", table.getTableName(), table.getTableType().name()); } else { tableEntity = dgiBridge.createTableInstance(dbEntity, table); entities.add(tableEntity); result.put(Type.TABLE, tableEntity); } } event.addMessage(new HookNotification.EntityUpdateRequest(event.getUser(), entities)); } return result; } catch(Exception e) { throw new AtlasHookException("HiveHook.createOrUpdateEntities() failed.", e); } } private LinkedHashMap<Type, Referenceable> createOrUpdateEntities(HiveMetaStoreBridge dgiBridge, HiveEventContext event, Entity entity, boolean skipTempTables) throws AtlasHookException { try { return createOrUpdateEntities(dgiBridge, event, entity, skipTempTables, null); } catch (Exception e) { throw new AtlasHookException("HiveHook.createOrUpdateEntities() failed.", e); } } private LinkedHashMap<Type, Referenceable> handleEventOutputs(HiveMetaStoreBridge dgiBridge, HiveEventContext event, Type entityType) throws AtlasHookException { try { for (Entity entity : event.getOutputs()) { if (entity.getType() == entityType) { return createOrUpdateEntities(dgiBridge, event, entity, true); } } return null; } catch(Exception e) { throw new AtlasHookException("HiveHook.handleEventOutputs() failed.", e); } } private static Entity getEntityByType(Set<? extends Entity> entities, Type entityType) { for (Entity entity : entities) { if (entity.getType() == entityType) { return entity; } } return null; } public static String lower(String str) { if (StringUtils.isEmpty(str)) { return null; } return str.toLowerCase().trim(); } private void registerProcess(HiveMetaStoreBridge dgiBridge, HiveEventContext event) throws AtlasHookException { try { Set<ReadEntity> inputs = event.getInputs(); Set<WriteEntity> outputs = event.getOutputs(); //Even explain CTAS has operation name as CREATETABLE_AS_SELECT if (inputs.isEmpty() && outputs.isEmpty()) { LOG.info("Explain statement. Skipping..."); return; } if (event.getQueryId() == null) { LOG.info("Query id/plan is missing for {}", event.getQueryStr()); } final SortedMap<ReadEntity, Referenceable> source = new TreeMap<>(entityComparator); final SortedMap<WriteEntity, Referenceable> target = new TreeMap<>(entityComparator); final Set<String> dataSets = new HashSet<>(); final Set<Referenceable> entities = new LinkedHashSet<>(); boolean isSelectQuery = isSelectQuery(event); // filter out select queries which do not modify data if (!isSelectQuery) { SortedSet<ReadEntity> sortedHiveInputs = new TreeSet<>(entityComparator); if (event.getInputs() != null) { sortedHiveInputs.addAll(event.getInputs()); } SortedSet<WriteEntity> sortedHiveOutputs = new TreeSet<>(entityComparator); if (event.getOutputs() != null) { sortedHiveOutputs.addAll(event.getOutputs()); } for (ReadEntity readEntity : sortedHiveInputs) { processHiveEntity(dgiBridge, event, readEntity, dataSets, source, entities); } for (WriteEntity writeEntity : sortedHiveOutputs) { processHiveEntity(dgiBridge, event, writeEntity, dataSets, target, entities); } if (source.size() > 0 || target.size() > 0) { Referenceable processReferenceable = getProcessReferenceable(dgiBridge, event, sortedHiveInputs, sortedHiveOutputs, source, target); // setup Column Lineage List<Referenceable> sourceList = new ArrayList<>(source.values()); List<Referenceable> targetList = new ArrayList<>(target.values()); List<Referenceable> colLineageProcessInstances = new ArrayList<>(); try { Map<String, Referenceable> columnQNameToRef = ColumnLineageUtils.buildColumnReferenceableMap(sourceList, targetList); colLineageProcessInstances = createColumnLineageProcessInstances(processReferenceable, event.lineageInfo, columnQNameToRef); } catch (Exception e) { LOG.warn("Column lineage process setup failed with exception {}", e); } colLineageProcessInstances.add(0, processReferenceable); entities.addAll(colLineageProcessInstances); event.addMessage(new HookNotification.EntityUpdateRequest(event.getUser(), new ArrayList<>(entities))); } else { LOG.info("Skipped query {} since it has no getInputs() or resulting getOutputs()", event.getQueryStr()); } } else { LOG.info("Skipped query {} for processing since it is a select query ", event.getQueryStr()); } } catch(Exception e) { throw new AtlasHookException("HiveHook.registerProcess() failed.", e); } } private <T extends Entity> void processHiveEntity(HiveMetaStoreBridge dgiBridge, HiveEventContext event, T entity, Set<String> dataSetsProcessed, SortedMap<T, Referenceable> dataSets, Set<Referenceable> entities) throws AtlasHookException { try { if (entity.getType() == Type.TABLE || entity.getType() == Type.PARTITION) { final String tblQFName = HiveMetaStoreBridge.getTableQualifiedName(dgiBridge.getClusterName(), entity.getTable()); if (!dataSetsProcessed.contains(tblQFName)) { LinkedHashMap<Type, Referenceable> result = createOrUpdateEntities(dgiBridge, event, entity, false); dataSets.put(entity, result.get(Type.TABLE)); dataSetsProcessed.add(tblQFName); entities.addAll(result.values()); } } else if (entity.getType() == Type.DFS_DIR) { URI location = entity.getLocation(); if (location != null) { final String pathUri = lower(new Path(location).toString()); LOG.debug("Registering DFS Path {} ", pathUri); if (!dataSetsProcessed.contains(pathUri)) { Referenceable hdfsPath = dgiBridge.fillHDFSDataSet(pathUri); dataSets.put(entity, hdfsPath); dataSetsProcessed.add(pathUri); entities.add(hdfsPath); } } } } catch(Exception e) { throw new AtlasHookException("HiveHook.processHiveEntity() failed.", e); } } private boolean isSelectQuery(HiveEventContext event) { if (event.getOperation() == HiveOperation.QUERY) { //Select query has only one output if (event.getOutputs().size() == 1) { WriteEntity output = event.getOutputs().iterator().next(); /* Strangely select queries have DFS_DIR as the type which seems like a bug in hive. Filter out by checking if the path is a temporary URI * Insert into/overwrite queries onto local or dfs paths have DFS_DIR or LOCAL_DIR as the type and WriteType.PATH_WRITE and tempUri = false * Insert into a temporary table has isTempURI = false. So will not skip as expected */ if (output.getType() == Type.DFS_DIR || output.getType() == Type.LOCAL_DIR) { if (output.getWriteType() == WriteEntity.WriteType.PATH_WRITE && output.isTempURI()) { return true; } } } } return false; } private void handleExternalTables(final HiveMetaStoreBridge dgiBridge, final HiveEventContext event, final LinkedHashMap<Type, Referenceable> tables) throws HiveException, MalformedURLException { List<Referenceable> entities = new ArrayList<>(); final WriteEntity hiveEntity = (WriteEntity) getEntityByType(event.getOutputs(), Type.TABLE); Table hiveTable = hiveEntity == null ? null : hiveEntity.getTable(); //Refresh to get the correct location if(hiveTable != null) { hiveTable = dgiBridge.hiveClient.getTable(hiveTable.getDbName(), hiveTable.getTableName()); } if (hiveTable != null && TableType.EXTERNAL_TABLE.equals(hiveTable.getTableType())) { LOG.info("Registering external table process {} ", event.getQueryStr()); final String location = lower(hiveTable.getDataLocation().toString()); final ReadEntity dfsEntity = new ReadEntity(); dfsEntity.setTyp(Type.DFS_DIR); dfsEntity.setD(new Path(location)); SortedMap<ReadEntity, Referenceable> hiveInputsMap = new TreeMap<ReadEntity, Referenceable>(entityComparator) {{ put(dfsEntity, dgiBridge.fillHDFSDataSet(location)); }}; SortedMap<WriteEntity, Referenceable> hiveOutputsMap = new TreeMap<WriteEntity, Referenceable>(entityComparator) {{ put(hiveEntity, tables.get(Type.TABLE)); }}; SortedSet<ReadEntity> sortedIps = new TreeSet<>(entityComparator); sortedIps.addAll(hiveInputsMap.keySet()); SortedSet<WriteEntity> sortedOps = new TreeSet<>(entityComparator); sortedOps.addAll(hiveOutputsMap.keySet()); Referenceable processReferenceable = getProcessReferenceable(dgiBridge, event, sortedIps, sortedOps, hiveInputsMap, hiveOutputsMap); entities.addAll(tables.values()); entities.add(processReferenceable); event.addMessage(new HookNotification.EntityUpdateRequest(event.getUser(), entities)); } } private static boolean isCreateOp(HiveEventContext hiveEvent) { return HiveOperation.CREATETABLE.equals(hiveEvent.getOperation()) || HiveOperation.CREATEVIEW.equals(hiveEvent.getOperation()) || HiveOperation.ALTERVIEW_AS.equals(hiveEvent.getOperation()) || HiveOperation.ALTERTABLE_LOCATION.equals(hiveEvent.getOperation()) || HiveOperation.CREATETABLE_AS_SELECT.equals(hiveEvent.getOperation()); } private Referenceable getProcessReferenceable(HiveMetaStoreBridge dgiBridge, HiveEventContext hiveEvent, final SortedSet<ReadEntity> sortedHiveInputs, final SortedSet<WriteEntity> sortedHiveOutputs, SortedMap<ReadEntity, Referenceable> source, SortedMap<WriteEntity, Referenceable> target) throws HiveException { Referenceable processReferenceable = new Referenceable(HiveDataTypes.HIVE_PROCESS.getName()); String queryStr = lower(hiveEvent.getQueryStr()); processReferenceable.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, getProcessQualifiedName(dgiBridge, hiveEvent, sortedHiveInputs, sortedHiveOutputs, source, target)); LOG.debug("Registering query: {}", queryStr); List<Referenceable> sourceList = new ArrayList<>(source.values()); List<Referenceable> targetList = new ArrayList<>(target.values()); //The serialization code expected a list if (sourceList != null && !sourceList.isEmpty()) { processReferenceable.set("inputs", sourceList); } if (targetList != null && !targetList.isEmpty()) { processReferenceable.set("outputs", targetList); } processReferenceable.set(AtlasClient.NAME, queryStr); processReferenceable.set("operationType", hiveEvent.getOperation().getOperationName()); processReferenceable.set("startTime", new Date(hiveEvent.getQueryStartTime())); processReferenceable.set("userName", hiveEvent.getUser()); processReferenceable.set("queryText", queryStr); processReferenceable.set("queryId", hiveEvent.getQueryId()); processReferenceable.set("queryPlan", "Not Supported"); processReferenceable.set(AtlasConstants.CLUSTER_NAME_ATTRIBUTE, dgiBridge.getClusterName()); List<String> recentQueries = new ArrayList<>(1); recentQueries.add(queryStr); processReferenceable.set("recentQueries", recentQueries); processReferenceable.set("endTime", new Date(System.currentTimeMillis())); //TODO set queryGraph return processReferenceable; } private List<Referenceable> createColumnLineageProcessInstances( Referenceable processRefObj, Map<String, List<ColumnLineageUtils.HiveColumnLineageInfo>> lineageInfo, Map<String, Referenceable> columnQNameToRef ) { List<Referenceable> l = new ArrayList<>(); for(Map.Entry<String, List<ColumnLineageUtils.HiveColumnLineageInfo>> e : lineageInfo.entrySet()) { Referenceable destCol = columnQNameToRef.get(e.getKey()); if (destCol == null ) { LOG.debug("Couldn't find output Column {}", e.getKey()); continue; } List<Referenceable> outRef = new ArrayList<>(); outRef.add(destCol); List<Referenceable> inputRefs = new ArrayList<>(); for(ColumnLineageUtils.HiveColumnLineageInfo cLI : e.getValue()) { Referenceable srcCol = columnQNameToRef.get(cLI.inputColumn); if (srcCol == null ) { LOG.debug("Couldn't find input Column {}", cLI.inputColumn); continue; } inputRefs.add(srcCol); } if (inputRefs.size() > 0 ) { Referenceable r = new Referenceable(HiveDataTypes.HIVE_COLUMN_LINEAGE.getName()); r.set("name", processRefObj.get(AtlasClient.NAME) + ":" + outRef.get(0).get(AtlasClient.NAME)); r.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, processRefObj.get(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME) + ":" + outRef.get(0).get(AtlasClient.NAME)); r.set("inputs", inputRefs); r.set("outputs", outRef); r.set("query", processRefObj); r.set("depenendencyType", e.getValue().get(0).depenendencyType); r.set("expression", e.getValue().get(0).expr); l.add(r); } else{ LOG.debug("No input references found for lineage of column {}", destCol.get(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME)); } } return l; } @VisibleForTesting static String getProcessQualifiedName(HiveMetaStoreBridge dgiBridge, HiveEventContext eventContext, final SortedSet<ReadEntity> sortedHiveInputs, final SortedSet<WriteEntity> sortedHiveOutputs, SortedMap<ReadEntity, Referenceable> hiveInputsMap, SortedMap<WriteEntity, Referenceable> hiveOutputsMap) throws HiveException { HiveOperation op = eventContext.getOperation(); if (isCreateOp(eventContext)) { Entity entity = getEntityByType(sortedHiveOutputs, Type.TABLE); if (entity != null) { Table outTable = entity.getTable(); //refresh table outTable = dgiBridge.hiveClient.getTable(outTable.getDbName(), outTable.getTableName()); return HiveMetaStoreBridge.getTableProcessQualifiedName(dgiBridge.getClusterName(), outTable); } } StringBuilder buffer = new StringBuilder(op.getOperationName()); boolean ignoreHDFSPathsinQFName = ignoreHDFSPathsinQFName(op, sortedHiveInputs, sortedHiveOutputs); if ( ignoreHDFSPathsinQFName && LOG.isDebugEnabled()) { LOG.debug("Ignoring HDFS paths in qualifiedName for {} {} ", op, eventContext.getQueryStr()); } addInputs(dgiBridge, op, sortedHiveInputs, buffer, hiveInputsMap, ignoreHDFSPathsinQFName); buffer.append(IO_SEP); addOutputs(dgiBridge, op, sortedHiveOutputs, buffer, hiveOutputsMap, ignoreHDFSPathsinQFName); LOG.info("Setting process qualified name to {}", buffer); return buffer.toString(); } private static boolean ignoreHDFSPathsinQFName(final HiveOperation op, final Set<ReadEntity> inputs, final Set<WriteEntity> outputs) { switch (op) { case LOAD: case IMPORT: return isPartitionBasedQuery(outputs); case EXPORT: return isPartitionBasedQuery(inputs); case QUERY: return true; } return false; } private static boolean isPartitionBasedQuery(Set<? extends Entity> entities) { for (Entity entity : entities) { if (Type.PARTITION.equals(entity.getType())) { return true; } } return false; } private static void addInputs(HiveMetaStoreBridge hiveBridge, HiveOperation op, SortedSet<ReadEntity> sortedInputs, StringBuilder buffer, final Map<ReadEntity, Referenceable> refs, final boolean ignoreHDFSPathsInQFName) throws HiveException { if (refs != null) { if (sortedInputs != null) { Set<String> dataSetsProcessed = new LinkedHashSet<>(); for (Entity input : sortedInputs) { if (!dataSetsProcessed.contains(input.getName().toLowerCase())) { //HiveOperation.QUERY type encompasses INSERT, INSERT_OVERWRITE, UPDATE, DELETE, PATH_WRITE operations if (ignoreHDFSPathsInQFName && (Type.DFS_DIR.equals(input.getType()) || Type.LOCAL_DIR.equals(input.getType()))) { LOG.debug("Skipping dfs dir input addition to process qualified name {} ", input.getName()); } else if (refs.containsKey(input)) { if ( input.getType() == Type.PARTITION || input.getType() == Type.TABLE) { final Date createTime = HiveMetaStoreBridge.getTableCreatedTime(hiveBridge.hiveClient.getTable(input.getTable().getDbName(), input.getTable().getTableName())); addDataset(buffer, refs.get(input), createTime.getTime()); } else { addDataset(buffer, refs.get(input)); } } dataSetsProcessed.add(input.getName().toLowerCase()); } } } } } private static void addDataset(StringBuilder buffer, Referenceable ref, final long createTime) { addDataset(buffer, ref); buffer.append(SEP); buffer.append(createTime); } private static void addDataset(StringBuilder buffer, Referenceable ref) { buffer.append(SEP); String dataSetQlfdName = (String) ref.get(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME); // '/' breaks query parsing on ATLAS buffer.append(dataSetQlfdName.toLowerCase().replaceAll("/", "")); } private static void addOutputs(HiveMetaStoreBridge hiveBridge, HiveOperation op, SortedSet<WriteEntity> sortedOutputs, StringBuilder buffer, final Map<WriteEntity, Referenceable> refs, final boolean ignoreHDFSPathsInQFName) throws HiveException { if (refs != null) { Set<String> dataSetsProcessed = new LinkedHashSet<>(); if (sortedOutputs != null) { for (WriteEntity output : sortedOutputs) { final Entity entity = output; if (!dataSetsProcessed.contains(output.getName().toLowerCase())) { //HiveOperation.QUERY type encompasses INSERT, INSERT_OVERWRITE, UPDATE, DELETE, PATH_WRITE operations if (addQueryType(op, (WriteEntity) entity)) { buffer.append(SEP); buffer.append(((WriteEntity) entity).getWriteType().name()); } if (ignoreHDFSPathsInQFName && (Type.DFS_DIR.equals(output.getType()) || Type.LOCAL_DIR.equals(output.getType()))) { LOG.debug("Skipping dfs dir output addition to process qualified name {} ", output.getName()); } else if (refs.containsKey(output)) { if ( output.getType() == Type.PARTITION || output.getType() == Type.TABLE) { final Date createTime = HiveMetaStoreBridge.getTableCreatedTime(hiveBridge.hiveClient.getTable(output.getTable().getDbName(), output.getTable().getTableName())); addDataset(buffer, refs.get(output), createTime.getTime()); } else { addDataset(buffer, refs.get(output)); } } dataSetsProcessed.add(output.getName().toLowerCase()); } } } } } private static boolean addQueryType(HiveOperation op, WriteEntity entity) { if (entity.getWriteType() != null && HiveOperation.QUERY.equals(op)) { switch (entity.getWriteType()) { case INSERT: case INSERT_OVERWRITE: case UPDATE: case DELETE: return true; case PATH_WRITE: //Add query type only for DFS paths and ignore local paths since they are not added as outputs if ( !Type.LOCAL_DIR.equals(entity.getType())) { return true; } break; default: } } return false; } public static class HiveEventContext { private Set<ReadEntity> inputs; private Set<WriteEntity> outputs; private String user; private UserGroupInformation ugi; private HiveOperation operation; private HookContext.HookType hookType; private JSONObject jsonPlan; private String queryId; private String queryStr; private Long queryStartTime; public Map<String, List<ColumnLineageUtils.HiveColumnLineageInfo>> lineageInfo; private List<HookNotification.HookNotificationMessage> messages = new ArrayList<>(); private String queryType; public void setInputs(Set<ReadEntity> inputs) { this.inputs = inputs; } public void setOutputs(Set<WriteEntity> outputs) { this.outputs = outputs; } public void setUser(String user) { this.user = user; } public void setUgi(UserGroupInformation ugi) { this.ugi = ugi; } public void setOperation(HiveOperation operation) { this.operation = operation; } public void setHookType(HookContext.HookType hookType) { this.hookType = hookType; } public void setQueryId(String queryId) { this.queryId = queryId; } public void setQueryStr(String queryStr) { this.queryStr = queryStr; } public void setQueryStartTime(Long queryStartTime) { this.queryStartTime = queryStartTime; } public void setQueryType(String queryType) { this.queryType = queryType; } public void setLineageInfo(LineageInfo lineageInfo){ try { this.lineageInfo = ColumnLineageUtils.buildLineageMap(lineageInfo); LOG.debug("Column Lineage Map => {} ", this.lineageInfo.entrySet()); }catch (Throwable e){ LOG.warn("Column Lineage Map build failed with exception {}", e); } } public Set<ReadEntity> getInputs() { return inputs; } public Set<WriteEntity> getOutputs() { return outputs; } public String getUser() { return user; } public UserGroupInformation getUgi() { return ugi; } public HiveOperation getOperation() { return operation; } public HookContext.HookType getHookType() { return hookType; } public String getQueryId() { return queryId; } public String getQueryStr() { return queryStr; } public Long getQueryStartTime() { return queryStartTime; } public String getQueryType() { return queryType; } public void addMessage(HookNotification.HookNotificationMessage message) { messages.add(message); } public List<HookNotification.HookNotificationMessage> getMessages() { return messages; } } @VisibleForTesting static final class EntityComparator implements Comparator<Entity> { @Override public int compare(Entity o1, Entity o2) { String s1 = o1.getName(); String s2 = o2.getName(); if (s1 == null || s2 == null){ s1 = o1.getD().toString(); s2 = o2.getD().toString(); } return s1.toLowerCase().compareTo(s2.toLowerCase()); } } @VisibleForTesting static final Comparator<Entity> entityComparator = new EntityComparator(); } <|start_filename|>graphdb/titan0/src/main/java/org/apache/atlas/repository/graphdb/titan0/Titan0PropertyKey.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan0; import org.apache.atlas.repository.graphdb.AtlasCardinality; import org.apache.atlas.repository.graphdb.AtlasPropertyKey; import com.thinkaurelius.titan.core.PropertyKey; /** * Titan 0.5.4 implementaiton of AtlasPropertyKey. */ public class Titan0PropertyKey implements AtlasPropertyKey { private PropertyKey wrappedPropertyKey; public Titan0PropertyKey(PropertyKey toWrap) { wrappedPropertyKey = toWrap; } /* * (non-Javadoc) * * @see org.apache.atlas.repository.graphdb.AtlasPropertyKey#getName() */ @Override public String getName() { return wrappedPropertyKey.getName(); } /** * @return */ public PropertyKey getWrappedPropertyKey() { return wrappedPropertyKey; } @Override public AtlasCardinality getCardinality() { return GraphDbObjectFactory.createCardinality(wrappedPropertyKey.getCardinality()); } @Override public boolean equals(Object other) { if (!(other instanceof Titan0PropertyKey)) { return false; } Titan0PropertyKey otherKey = (Titan0PropertyKey) other; return wrappedPropertyKey.equals(otherKey.wrappedPropertyKey); } @Override public int hashCode() { int result = 17; result = 37 * result + wrappedPropertyKey.hashCode(); return result; } @Override public String toString() { return wrappedPropertyKey.getName(); } } <|start_filename|>webapp/src/main/java/org/apache/atlas/web/security/AtlasAbstractAuthenticationProvider.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.atlas.web.security; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.Groups; import org.apache.hadoop.security.UserGroupInformation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import java.util.ArrayList; import java.util.List; public abstract class AtlasAbstractAuthenticationProvider implements AuthenticationProvider { private static final Logger LOG = LoggerFactory.getLogger(AtlasAbstractAuthenticationProvider.class); @Override public boolean supports(Class<?> authentication) { return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication); } /** * * @param authentication * @return */ public Authentication getAuthenticationWithGrantedAuthority( Authentication authentication) { UsernamePasswordAuthenticationToken result = null; if (authentication != null && authentication.isAuthenticated()) { final List<GrantedAuthority> grantedAuths = getAuthorities(authentication .getName()); final UserDetails userDetails = new User(authentication.getName(), authentication.getCredentials().toString(), grantedAuths); result = new UsernamePasswordAuthenticationToken(userDetails, authentication.getCredentials(), grantedAuths); result.setDetails(authentication.getDetails()); return result; } return authentication; } /** * This method will be modified when actual roles are introduced. * */ protected List<GrantedAuthority> getAuthorities(String username) { final List<GrantedAuthority> grantedAuths = new ArrayList<>(); grantedAuths.add(new SimpleGrantedAuthority("DATA_SCIENTIST")); return grantedAuths; } public Authentication getAuthenticationWithGrantedAuthorityFromUGI( Authentication authentication) { UsernamePasswordAuthenticationToken result = null; if (authentication != null && authentication.isAuthenticated()) { List<GrantedAuthority> grantedAuthsUGI = getAuthoritiesFromUGI(authentication .getName()); final UserDetails userDetails = new User(authentication.getName(), authentication.getCredentials().toString(), grantedAuthsUGI); result = new UsernamePasswordAuthenticationToken(userDetails, authentication.getCredentials(), grantedAuthsUGI); result.setDetails(authentication.getDetails()); return result; } return authentication; } public static List<GrantedAuthority> getAuthoritiesFromUGI(String userName) { List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>(); UserGroupInformation ugi = UserGroupInformation.createRemoteUser(userName); if (ugi != null) { String[] userGroups = ugi.getGroupNames(); if (userGroups != null) { for (String group : userGroups) { grantedAuths.add(new SimpleGrantedAuthority(group)); } } } // if group empty take groups from UGI LDAP-based group mapping if (grantedAuths != null && grantedAuths.isEmpty()) { try { Configuration config = new Configuration(); Groups gp = new Groups(config); List<String> userGroups = gp.getGroups(userName); if (userGroups != null) { for (String group : userGroups) { grantedAuths.add(new SimpleGrantedAuthority(group)); } } } catch (java.io.IOException e) { LOG.error("Exception while fetching groups ", e); } } return grantedAuths; } } <|start_filename|>client/src/main/java/org/apache/atlas/EntityAuditEvent.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas; import org.apache.atlas.typesystem.IReferenceableInstance; import org.apache.atlas.typesystem.json.InstanceSerialization; import java.util.Objects; /** * Structure of entity audit event */ public class EntityAuditEvent { public enum EntityAuditAction { ENTITY_CREATE, ENTITY_UPDATE, ENTITY_DELETE, TAG_ADD, TAG_DELETE, TAG_UPDATE, ENTITY_IMPORT_CREATE, ENTITY_IMPORT_UPDATE, ENTITY_IMPORT_DELETE, } private String entityId; private long timestamp; private String user; private EntityAuditAction action; private String details; private String eventKey; private IReferenceableInstance entityDefinition; public EntityAuditEvent() { } public EntityAuditEvent(String entityId, Long ts, String user, EntityAuditAction action, String details, IReferenceableInstance entityDefinition) throws AtlasException { this.entityId = entityId; this.timestamp = ts; this.user = user; this.action = action; this.details = details; this.entityDefinition = entityDefinition; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EntityAuditEvent that = (EntityAuditEvent) o; return timestamp == that.timestamp && Objects.equals(entityId, that.entityId) && Objects.equals(user, that.user) && action == that.action && Objects.equals(details, that.details) && Objects.equals(eventKey, that.eventKey) && Objects.equals(entityDefinition, that.entityDefinition); } @Override public int hashCode() { return Objects.hash(entityId, timestamp, user, action, details, eventKey, entityDefinition); } @Override public String toString() { return SerDe.GSON.toJson(this); } public static EntityAuditEvent fromString(String eventString) { return SerDe.GSON.fromJson(eventString, EntityAuditEvent.class); } public String getEntityId() { return entityId; } public long getTimestamp() { return timestamp; } public String getUser() { return user; } public EntityAuditAction getAction() { return action; } public String getDetails() { return details; } public void setEntityId(String entityId) { this.entityId = entityId; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public void setUser(String user) { this.user = user; } public void setAction(EntityAuditAction action) { this.action = action; } public void setDetails(String details) { this.details = details; } public String getEventKey() { return eventKey; } public void setEventKey(String eventKey) { this.eventKey = eventKey; } public IReferenceableInstance getEntityDefinition() { return entityDefinition; } public String getEntityDefinitionString() { if (entityDefinition != null) { return InstanceSerialization.toJson(entityDefinition, true); } return null; } public void setEntityDefinition(String entityDefinition) { this.entityDefinition = InstanceSerialization.fromJsonReferenceable(entityDefinition, true); } } <|start_filename|>dashboardv2/public/js/views/business_catalog/BusinessCatalogDetailLayoutView.js<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(['require', 'backbone', 'hbs!tmpl/business_catalog/BusinessCatalogDetailLayoutView_tmpl', 'utils/Utils', 'models/VEntity', 'models/VCatalog', 'utils/Messages' ], function(require, Backbone, BusinessCatalogDetailLayoutViewTmpl, Utils, VEntity, VCatalog, Messages) { 'use strict'; var BusinessCatalogDetailLayoutView = Backbone.Marionette.LayoutView.extend( /** @lends BusinessCatalogDetailLayoutView */ { _viewName: 'BusinessCatalogDetailLayoutView', template: BusinessCatalogDetailLayoutViewTmpl, /** Layout sub regions */ regions: {}, /** ui selector cache */ ui: { title: '[data-id="title"]', editButton: '[data-id="editButton"]', description: '[data-id="description"]', editBox: '[data-id="editBox"]', createDate: '[data-id="createDate"]' }, /** ui events hash */ events: function() { var events = {}; events["click " + this.ui.editButton] = 'onEditButton'; events["click " + this.ui.cancelButton] = 'onCancelButtonClick'; return events; }, /** * intialize a new BusinessCatalogDetailLayoutView Layout * @constructs */ initialize: function(options) { _.extend(this, _.pick(options, 'url', 'collection')); this.bindEvents(); }, bindEvents: function() { var that = this; this.listenTo(this.collection, 'error', function(model, response) { this.$('.fontLoader').hide(); if (response && response.responseJSON && response.responseJSON.message) { Utils.notifyError({ content: response.responseJSON.message }); } }, this); this.listenTo(this.collection, 'reset', function() { this.$('.fontLoader').hide(); this.$('.hide').removeClass('hide'); this.model = this.collection.first(); var name = this.model.get('name'), description = this.model.get('description'), createdDate = this.model.get('creation_time'); if (name) { this.ui.title.show(); this.termName = Utils.checkTagOrTerm(name, true); this.ui.title.html('<span>' + this.termName.name + '</span>'); } else { this.ui.title.hide(); } if (description) { this.ui.description.show(); this.ui.description.html('<span>' + _.escape(description) + '</span>'); } else { this.ui.description.hide(); } if (createdDate) { var splitDate = createdDate.split(":"); this.ui.createDate.html('<strong> Date Created: </strong> ' + splitDate[0] + " " + splitDate[1] + ":" + splitDate[2] + ":" + splitDate[3] + " (GMT)"); } Utils.hideTitleLoader(this.$('.fontLoader'), this.$('.catlogDetail')); }, this); }, onRender: function() { var that = this; Utils.showTitleLoader(this.$('.page-title .fontLoader'), this.$('.catlogDetail')); }, fetchCollection: function() { this.collection.fetch({ reset: true }); }, onEditButton: function(e) { var that = this; $(e.currentTarget).blur(); require([ 'views/tag/CreateTagLayoutView', 'modules/Modal' ], function(CreateTagLayoutView, Modal) { var view = new CreateTagLayoutView({ 'termCollection': that.collection, 'descriptionData': that.model.get('description'), 'tag': _.unescape(that.termName.name) }); var modal = new Modal({ title: 'Edit Term', content: view, cancelText: "Cancel", okText: 'Save', allowCancel: true, }).open(); view.ui.description.on('keyup', function(e) { that.textAreaChangeEvent(view, modal); }); modal.$el.find('button.ok').prop('disabled', true); modal.on('ok', function() { that.onSaveDescriptionClick(view); }); modal.on('closeModal', function() { modal.trigger('cancel'); }); }); }, textAreaChangeEvent: function(view, modal) { if (view.description == view.ui.description.val()) { modal.$el.find('button.ok').prop('disabled', true); } else { modal.$el.find('button.ok').prop('disabled', false); } }, onSaveDescriptionClick: function(view) { view.description = view.ui.description.val(); this.onSaveButton(this.collection.first().toJSON(), Messages.updateTermDescriptionMessage, view); this.ui.description.show(); }, onSaveButton: function(saveObject, message, view) { var that = this, termModel = new VCatalog(); termModel.url = function() { return that.collection.url; }; Utils.showTitleLoader(this.$('.page-title .fontLoader'), this.$('.catlogDetail')); termModel.set({ "description": view.ui.description.val() }).save(null, { type: "PUT", success: function(model, response) { that.collection.fetch({ reset: true }); Utils.notifySuccess({ content: message }); } }); } }); return BusinessCatalogDetailLayoutView; }); <|start_filename|>repository/src/test/java/org/apache/atlas/repository/typestore/StoreBackedTypeCacheTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.typestore; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import org.apache.atlas.AtlasException; import org.apache.atlas.TestModules; import org.apache.atlas.TestUtils; import org.apache.atlas.typesystem.types.AttributeInfo; import org.apache.atlas.typesystem.types.ClassType; import org.apache.atlas.typesystem.types.DataTypes.TypeCategory; import org.apache.atlas.typesystem.types.HierarchicalType; import org.apache.atlas.typesystem.types.IDataType; import org.apache.atlas.typesystem.types.TraitType; import org.apache.atlas.typesystem.types.TypeSystem; import org.apache.atlas.typesystem.types.TypeUtils; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Guice; import org.testng.annotations.Test; import javax.inject.Inject; import java.util.HashMap; import java.util.Map; /** * Unit test for {@link StoreBackedTypeCache} */ @Guice(modules = TestModules.TestOnlyModule.class) public class StoreBackedTypeCacheTest { @Inject private ITypeStore typeStore; @Inject private StoreBackedTypeCache typeCache; private TypeSystem ts; private Map<String, ClassType> classTypesToTest = new HashMap<>(); @Inject public StoreBackedTypeCacheTest() { } @BeforeClass public void setUp() throws Exception { //force graph to be initialized up front TestUtils.getGraph(); ts = TypeSystem.getInstance(); ts.reset(); ts.setTypeCache(typeCache); // Populate the type store for testing. TestUtils.defineDeptEmployeeTypes(ts); TestUtils.createHiveTypes(ts); ImmutableList<String> typeNames = ts.getTypeNames(); typeStore.store(ts, typeNames); ClassType type = ts.getDataType(ClassType.class, "Manager"); classTypesToTest.put("Manager", type); type = ts.getDataType(ClassType.class, TestUtils.TABLE_TYPE); classTypesToTest.put(TestUtils.TABLE_TYPE, type); } @AfterClass public void tearDown() throws Exception { ts.reset(); // AtlasGraphProvider.cleanup(); } @BeforeMethod public void setupTestMethod() throws Exception { typeCache.clear(); } @Test public void testGetClassType() throws Exception { for (Map.Entry<String, ClassType> typeEntry : classTypesToTest.entrySet()) { // Not cached yet Assert.assertFalse(typeCache.isCachedInMemory(typeEntry.getKey())); IDataType dataType = ts.getDataType(IDataType.class, typeEntry.getKey()); // Verify the type is now cached. Assert.assertTrue(typeCache.isCachedInMemory(typeEntry.getKey())); Assert.assertTrue(dataType instanceof ClassType); ClassType cachedType = (ClassType)dataType; // Verify that get() also loaded and cached any dependencies of this type from the type store. verifyHierarchicalType(cachedType, typeEntry.getValue()); } } @Test public void testGetTraitType() throws Exception { ImmutableList<String> traitNames = ts.getTypeNamesByCategory(TypeCategory.TRAIT); for (String traitTypeName : traitNames) { // Not cached yet Assert.assertFalse(typeCache.isCachedInMemory(traitTypeName)); IDataType dataType = typeCache.get(traitTypeName); // Verify the type is now cached. Assert.assertTrue(typeCache.isCachedInMemory(traitTypeName)); Assert.assertTrue(dataType instanceof TraitType); TraitType cachedType = (TraitType)dataType; // Verify that get() also loaded and cached any dependencies of this type from the type store. verifyHierarchicalType(cachedType, ts.getDataType(TraitType.class, traitTypeName)); } } private <T extends HierarchicalType> void verifyHierarchicalType(T dataType, T expectedDataType) throws AtlasException { Assert.assertEquals(dataType.numFields, expectedDataType.numFields); Assert.assertEquals(dataType.immediateAttrs.size(), expectedDataType.immediateAttrs.size()); Assert.assertEquals(dataType.fieldMapping().fields.size(), expectedDataType.fieldMapping().fields.size()); ImmutableSet<String> superTypes = dataType.superTypes; Assert.assertEquals(superTypes.size(), expectedDataType.superTypes.size()); // Verify that any attribute and super types were also cached. for (String superTypeName : superTypes) { Assert.assertTrue(typeCache.has(superTypeName)); } for (AttributeInfo attrInfo : dataType.fieldMapping().fields.values()) { switch (attrInfo.dataType().getTypeCategory()) { case CLASS: case STRUCT: case ENUM: Assert.assertTrue(typeCache.has(attrInfo.dataType().getName()), attrInfo.dataType().getName() + " should be cached"); break; case ARRAY: String elementTypeName = TypeUtils.parseAsArrayType(attrInfo.dataType().getName()); if (!ts.getCoreTypes().contains(elementTypeName)) { Assert.assertTrue(typeCache.has(elementTypeName), elementTypeName + " should be cached"); } break; case MAP: String[] mapTypeNames = TypeUtils.parseAsMapType(attrInfo.dataType().getName()); for (String typeName : mapTypeNames) { if (!ts.getCoreTypes().contains(typeName)) { Assert.assertTrue(typeCache.has(typeName), typeName + " should be cached"); } } break; default: break; } } } } <|start_filename|>webapp/src/test/java/org/apache/atlas/notification/EntityNotificationIT.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.notification; import com.google.common.collect.ImmutableSet; import org.apache.atlas.AtlasClient; import org.apache.atlas.kafka.NotificationProvider; import org.apache.atlas.notification.entity.EntityNotification; import org.apache.atlas.typesystem.IReferenceableInstance; import org.apache.atlas.typesystem.IStruct; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.Struct; import org.apache.atlas.typesystem.json.InstanceSerialization; import org.apache.atlas.typesystem.json.TypesSerialization$; import org.apache.atlas.typesystem.persistence.Id; import org.apache.atlas.typesystem.types.HierarchicalTypeDefinition; import org.apache.atlas.typesystem.types.TraitType; import org.apache.atlas.typesystem.types.utils.TypesUtil; import org.apache.atlas.web.integration.BaseResourceIT; import org.testng.annotations.BeforeClass; import java.util.Collections; import java.util.LinkedList; import java.util.List; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; /** * Entity Notification Integration Tests. */ public class EntityNotificationIT extends BaseResourceIT { private final String DATABASE_NAME = "db" + randomString(); private final String TABLE_NAME = "table" + randomString(); private NotificationInterface notificationInterface = NotificationProvider.get(); private Id tableId; private Id dbId; private String traitName; private NotificationConsumer notificationConsumer; @BeforeClass public void setUp() throws Exception { super.setUp(); createTypeDefinitionsV1(); Referenceable HiveDBInstance = createHiveDBInstanceBuiltIn(DATABASE_NAME); dbId = createInstance(HiveDBInstance); notificationConsumer = notificationInterface.createConsumers(NotificationInterface.NotificationType.ENTITIES, 1).get(0); } public void testCreateEntity() throws Exception { Referenceable tableInstance = createHiveTableInstanceBuiltIn(DATABASE_NAME, TABLE_NAME, dbId); tableId = createInstance(tableInstance); final String guid = tableId._getId(); waitForNotification(notificationConsumer, MAX_WAIT_TIME, newNotificationPredicate(EntityNotification.OperationType.ENTITY_CREATE, HIVE_TABLE_TYPE_BUILTIN, guid)); } public void testUpdateEntity() throws Exception { final String property = "description"; final String newValue = "New description!"; final String guid = tableId._getId(); atlasClientV1.updateEntityAttribute(guid, property, newValue); waitForNotification(notificationConsumer, MAX_WAIT_TIME, newNotificationPredicate(EntityNotification.OperationType.ENTITY_UPDATE, HIVE_TABLE_TYPE_BUILTIN, guid)); } public void testDeleteEntity() throws Exception { final String tableName = "table-" + randomString(); final String dbName = "db-" + randomString(); Referenceable HiveDBInstance = createHiveDBInstanceBuiltIn(dbName); Id dbId = createInstance(HiveDBInstance); Referenceable tableInstance = createHiveTableInstanceBuiltIn(dbName, tableName, dbId); final Id tableId = createInstance(tableInstance); final String guid = tableId._getId(); waitForNotification(notificationConsumer, MAX_WAIT_TIME, newNotificationPredicate(EntityNotification.OperationType.ENTITY_CREATE, HIVE_TABLE_TYPE_BUILTIN, guid)); final String name = (String) tableInstance.get(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME); atlasClientV1.deleteEntity(HIVE_TABLE_TYPE_BUILTIN, AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, name); waitForNotification(notificationConsumer, MAX_WAIT_TIME, newNotificationPredicate(EntityNotification.OperationType.ENTITY_DELETE, HIVE_TABLE_TYPE_BUILTIN, guid)); } public void testAddTrait() throws Exception { String superSuperTraitName = "SuperTrait" + randomString(); createTrait(superSuperTraitName); String superTraitName = "SuperTrait" + randomString(); createTrait(superTraitName, superSuperTraitName); traitName = "Trait" + randomString(); createTrait(traitName, superTraitName); Struct traitInstance = new Struct(traitName); String traitInstanceJSON = InstanceSerialization.toJson(traitInstance, true); LOG.debug("Trait instance = {}", traitInstanceJSON); final String guid = tableId._getId(); atlasClientV1.addTrait(guid, traitInstance); EntityNotification entityNotification = waitForNotification(notificationConsumer, MAX_WAIT_TIME, newNotificationPredicate(EntityNotification.OperationType.TRAIT_ADD, HIVE_TABLE_TYPE_BUILTIN, guid)); IReferenceableInstance entity = entityNotification.getEntity(); assertTrue(entity.getTraits().contains(traitName)); List<IStruct> allTraits = entityNotification.getAllTraits(); List<String> allTraitNames = new LinkedList<>(); for (IStruct struct : allTraits) { allTraitNames.add(struct.getTypeName()); } assertTrue(allTraitNames.contains(traitName)); assertTrue(allTraitNames.contains(superTraitName)); assertTrue(allTraitNames.contains(superSuperTraitName)); String anotherTraitName = "Trait" + randomString(); createTrait(anotherTraitName, superTraitName); traitInstance = new Struct(anotherTraitName); traitInstanceJSON = InstanceSerialization.toJson(traitInstance, true); LOG.debug("Trait instance = {}", traitInstanceJSON); atlasClientV1.addTrait(guid, traitInstance); entityNotification = waitForNotification(notificationConsumer, MAX_WAIT_TIME, newNotificationPredicate(EntityNotification.OperationType.TRAIT_ADD, HIVE_TABLE_TYPE_BUILTIN, guid)); allTraits = entityNotification.getAllTraits(); allTraitNames = new LinkedList<>(); for (IStruct struct : allTraits) { allTraitNames.add(struct.getTypeName()); } assertTrue(allTraitNames.contains(traitName)); assertTrue(allTraitNames.contains(anotherTraitName)); // verify that the super type shows up twice in all traits assertEquals(2, Collections.frequency(allTraitNames, superTraitName)); } public void testDeleteTrait() throws Exception { final String guid = tableId._getId(); atlasClientV1.deleteTrait(guid, traitName); EntityNotification entityNotification = waitForNotification(notificationConsumer, MAX_WAIT_TIME, newNotificationPredicate(EntityNotification.OperationType.TRAIT_DELETE, HIVE_TABLE_TYPE_BUILTIN, guid)); assertFalse(entityNotification.getEntity().getTraits().contains(traitName)); } // ----- helper methods --------------------------------------------------- private void createTrait(String traitName, String ... superTraitNames) throws Exception { HierarchicalTypeDefinition<TraitType> trait = TypesUtil.createTraitTypeDef(traitName, ImmutableSet.copyOf(superTraitNames)); String traitDefinitionJSON = TypesSerialization$.MODULE$.toJson(trait, true); LOG.debug("Trait definition = {}", traitDefinitionJSON); createType(traitDefinitionJSON); } } <|start_filename|>webapp/src/test/java/org/apache/atlas/util/RestUtilsTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.util; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.typedef.AtlasEntityDef; import org.apache.atlas.model.typedef.AtlasStructDef; import org.apache.atlas.model.typedef.AtlasStructDef.AtlasAttributeDef; import org.apache.atlas.model.typedef.AtlasTypesDef; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.converters.TypeConverterUtil; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.repository.store.graph.v1.AtlasGraphUtilsV1; import org.apache.atlas.repository.store.graph.v1.AtlasStructDefStoreV1; import org.apache.atlas.repository.store.graph.v1.AtlasTypeDefGraphStoreV1; import org.apache.atlas.type.AtlasEntityType; import org.apache.atlas.type.AtlasStructType; import org.apache.atlas.type.AtlasStructType.AtlasAttribute; import org.apache.atlas.type.AtlasType; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.type.AtlasTypeRegistry.AtlasTransientTypeRegistry; import org.apache.atlas.typesystem.TypesDef; import org.apache.atlas.typesystem.json.TypesSerialization; import org.apache.atlas.typesystem.types.AttributeDefinition; import org.apache.atlas.typesystem.types.ClassType; import org.apache.atlas.typesystem.types.DataTypes; import org.apache.atlas.typesystem.types.DataTypes.TypeCategory; import org.apache.atlas.typesystem.types.EnumTypeDefinition; import org.apache.atlas.typesystem.types.HierarchicalTypeDefinition; import org.apache.atlas.typesystem.types.Multiplicity; import org.apache.atlas.typesystem.types.StructTypeDefinition; import org.apache.atlas.typesystem.types.TraitType; import org.apache.atlas.typesystem.types.utils.TypesUtil; import org.testng.Assert; import org.testng.annotations.Test; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; /** * Validates that conversion from V1 to legacy types (and back) is consistent. This also tests * that the conversion logic in AtlasStructDefStoreV1 is consistent with the conversion logic * in RestUtils. This tests particularly focuses on composite attributes, since a defect was * found in that area. */ public class RestUtilsTest { @Test(enabled=false) // FIXME: On conversion back to V1, reverse attribute name // "containingDatabase" // in tables attribute in "database" type is lost. See ATLAS-1528. public void testBidirectonalCompositeMappingConsistent() throws AtlasBaseException { HierarchicalTypeDefinition<ClassType> dbV1Type = TypesUtil.createClassTypeDef("database", ImmutableSet.<String> of(), new AttributeDefinition("tables", DataTypes.arrayTypeName("table"), Multiplicity.OPTIONAL, true, "containingDatabase")); HierarchicalTypeDefinition<ClassType> tableV1Type = TypesUtil.createClassTypeDef("table", ImmutableSet.<String> of(), new AttributeDefinition("containingDatabase", "database", Multiplicity.OPTIONAL, false, "tables")); testV1toV2toV1Conversion(Arrays.asList(dbV1Type, tableV1Type), new boolean[] { true, false }); } @Test(enabled=false) // FIXME: On conversion back to V1, reverse attribute name // "containingDatabase" is lost // in "table" attribute in "database". See ATLAS-1528. public void testBidirectonalNonCompositeMappingConsistent() throws AtlasBaseException { HierarchicalTypeDefinition<ClassType> dbV1Type = TypesUtil.createClassTypeDef("database", ImmutableSet.<String> of(), new AttributeDefinition("tables", DataTypes.arrayTypeName("table"), Multiplicity.OPTIONAL, false, "containingDatabase")); HierarchicalTypeDefinition<ClassType> tableV1Type = TypesUtil.createClassTypeDef("table", ImmutableSet.<String> of(), new AttributeDefinition("containingDatabase", "database", Multiplicity.OPTIONAL, false, "tables")); testV1toV2toV1Conversion(Arrays.asList(dbV1Type, tableV1Type), new boolean[] { false, false }); } private AtlasTypeDefGraphStoreV1 makeTypeStore(AtlasTypeRegistry reg) { AtlasTypeDefGraphStoreV1 result = mock(AtlasTypeDefGraphStoreV1.class); for (AtlasEntityType type : reg.getAllEntityTypes()) { String typeName = type.getTypeName(); AtlasVertex typeVertex = mock(AtlasVertex.class); when(result.isTypeVertex(eq(typeVertex), any(TypeCategory.class))).thenReturn(true); when(typeVertex.getProperty(eq(Constants.TYPE_CATEGORY_PROPERTY_KEY), eq(TypeCategory.class))) .thenReturn(TypeCategory.CLASS); String attributeListPropertyKey = AtlasGraphUtilsV1.getTypeDefPropertyKey(typeName); when(typeVertex.getProperty(eq(attributeListPropertyKey), eq(List.class))) .thenReturn(new ArrayList<>(type.getAllAttributes().keySet())); for (AtlasAttribute attribute : type.getAllAttributes().values()) { String attributeDefPropertyKey = AtlasGraphUtilsV1.getTypeDefPropertyKey(typeName, attribute.getName()); String attributeJson = AtlasStructDefStoreV1.toJsonFromAttribute(attribute); when(typeVertex.getProperty(eq(attributeDefPropertyKey), eq(String.class))).thenReturn(attributeJson); } when(result.findTypeVertexByName(eq(typeName))).thenReturn(typeVertex); } return result; } private AtlasAttributeDef convertToJsonAndBack(AtlasTypeRegistry registry, AtlasStructDef structDef, AtlasAttributeDef attributeDef, boolean compositeExpected) throws AtlasBaseException { AtlasTypeDefGraphStoreV1 typeDefStore = makeTypeStore(registry); AtlasStructType structType = (AtlasStructType) registry.getType(structDef.getName()); AtlasAttribute attribute = structType.getAttribute(attributeDef.getName()); String attribJson = AtlasStructDefStoreV1.toJsonFromAttribute(attribute); Map attrInfo = AtlasType.fromJson(attribJson, Map.class); Assert.assertEquals(attrInfo.get("isComposite"), compositeExpected); return AtlasStructDefStoreV1.toAttributeDefFromJson(structDef, attrInfo, typeDefStore); } private void testV1toV2toV1Conversion(List<HierarchicalTypeDefinition<ClassType>> typesToTest, boolean[] compositeExpected) throws AtlasBaseException { List<AtlasEntityDef> convertedEntityDefs = convertV1toV2(typesToTest); AtlasTypeRegistry registry = createRegistry(convertedEntityDefs); for(int i = 0 ; i < convertedEntityDefs.size(); i++) { AtlasEntityDef def = convertedEntityDefs.get(i); for (AtlasAttributeDef attrDef : def.getAttributeDefs()) { AtlasAttributeDef converted = convertToJsonAndBack(registry, def, attrDef, compositeExpected[i]); Assert.assertEquals(converted, attrDef); } } List<HierarchicalTypeDefinition<ClassType>> convertedBackTypeDefs = convertV2toV1(convertedEntityDefs); for (int i = 0; i < typesToTest.size(); i++) { HierarchicalTypeDefinition<ClassType> convertedBack = convertedBackTypeDefs.get(i); Assert.assertEquals(convertedBack, typesToTest.get(i)); AttributeDefinition[] attributeDefinitions = convertedBack.attributeDefinitions; if (attributeDefinitions.length > 0) { Assert.assertEquals(attributeDefinitions[0].isComposite, compositeExpected[i]); } } } private List<HierarchicalTypeDefinition<ClassType>> convertV2toV1(List<AtlasEntityDef> toConvert) throws AtlasBaseException { AtlasTypeRegistry reg = createRegistry(toConvert); List<HierarchicalTypeDefinition<ClassType>> result = new ArrayList<>(toConvert.size()); for (int i = 0; i < toConvert.size(); i++) { AtlasEntityDef entityDef = toConvert.get(i); AtlasEntityType entity = reg.getEntityTypeByName(entityDef.getName()); HierarchicalTypeDefinition<ClassType> converted = TypeConverterUtil.toTypesDef(entity, reg) .classTypesAsJavaList().get(0); result.add(converted); } return result; } private AtlasTypeRegistry createRegistry(List<AtlasEntityDef> toConvert) throws AtlasBaseException { AtlasTypeRegistry reg = new AtlasTypeRegistry(); AtlasTransientTypeRegistry tmp = reg.lockTypeRegistryForUpdate(); tmp.addTypes(toConvert); reg.releaseTypeRegistryForUpdate(tmp, true); return reg; } private List<AtlasEntityDef> convertV1toV2(List<HierarchicalTypeDefinition<ClassType>> types) throws AtlasBaseException { ImmutableList<HierarchicalTypeDefinition<ClassType>> classTypeList = ImmutableList .<HierarchicalTypeDefinition<ClassType>> builder().addAll(types).build(); TypesDef toConvert = TypesUtil.getTypesDef(ImmutableList.<EnumTypeDefinition> of(), ImmutableList.<StructTypeDefinition> of(), ImmutableList.<HierarchicalTypeDefinition<TraitType>> of(), classTypeList); String json = TypesSerialization.toJson(toConvert); AtlasTypeRegistry emptyRegistry = new AtlasTypeRegistry(); AtlasTypesDef converted = TypeConverterUtil.toAtlasTypesDef(json, emptyRegistry); List<AtlasEntityDef> convertedEntityDefs = converted.getEntityDefs(); return convertedEntityDefs; } } <|start_filename|>repository/src/test/java/org/apache/atlas/repository/graph/GraphHelperMockTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graph; import org.apache.atlas.repository.RepositoryException; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasEdgeDirection; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.Iterator; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; public class GraphHelperMockTest { private GraphHelper graphHelperInstance; private AtlasGraph graph; @BeforeClass public void setup() { MockitoAnnotations.initMocks(this); graph = mock(AtlasGraph.class); graphHelperInstance = GraphHelper.getInstance(graph); } @Test(expectedExceptions = RepositoryException.class) public void testGetOrCreateEdgeLabelWithMaxRetries() throws Exception { final String edgeLabel = "testLabel"; AtlasVertex v1 = mock(AtlasVertex.class); AtlasVertex v2 = mock(AtlasVertex.class); Iterable noEdgesIterable = new Iterable<AtlasEdge>() { @Override public Iterator<AtlasEdge> iterator() { return new Iterator<AtlasEdge>() { @Override public boolean hasNext() { return false; } @Override public AtlasEdge next() { return null; } @Override public void remove() { } }; } }; when(v2.getEdges(AtlasEdgeDirection.IN)).thenReturn(noEdgesIterable); when(v1.getEdges(AtlasEdgeDirection.OUT)).thenReturn(noEdgesIterable); when(v1.getId()).thenReturn("1234"); when(v2.getId()).thenReturn("5678"); when(graph.addEdge(v1, v2, edgeLabel)).thenThrow(new RuntimeException("Unique property constraint violated")); graphHelperInstance.getOrCreateEdge(v1, v2, edgeLabel); } @Test public void testGetOrCreateEdgeLabelWithRetries() throws Exception { final String edgeLabel = "testLabel"; AtlasVertex v1 = mock(AtlasVertex.class); AtlasVertex v2 = mock(AtlasVertex.class); AtlasEdge edge = mock(AtlasEdge.class); Iterable noEdgesIterable = new Iterable<AtlasEdge>() { @Override public Iterator<AtlasEdge> iterator() { return new Iterator<AtlasEdge>() { @Override public boolean hasNext() { return false; } @Override public AtlasEdge next() { return null; } @Override public void remove() { } }; } }; when(v2.getEdges(AtlasEdgeDirection.IN)).thenReturn(noEdgesIterable); when(v1.getEdges(AtlasEdgeDirection.OUT)).thenReturn(noEdgesIterable); when(v1.getId()).thenReturn("v1"); when(v2.getId()).thenReturn("v2"); when(edge.getId()).thenReturn("edge"); when(graph.addEdge(v1, v2, edgeLabel)) .thenThrow(new RuntimeException("Unique property constraint violated")).thenReturn(edge); AtlasEdge redge = graphHelperInstance.getOrCreateEdge(v1, v2, edgeLabel); assertEquals(edge, redge); } } <|start_filename|>intg/src/test/java/org/apache/atlas/model/ModelTestUtil.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.model; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.instance.AtlasClassification; import org.apache.atlas.model.instance.AtlasEntity; import org.apache.atlas.model.instance.AtlasStruct; import org.apache.atlas.model.typedef.*; import org.apache.atlas.model.typedef.AtlasEnumDef.AtlasEnumElementDef; import org.apache.atlas.model.typedef.AtlasStructDef.AtlasAttributeDef; import org.apache.atlas.type.AtlasClassificationType; import org.apache.atlas.type.AtlasEntityType; import org.apache.atlas.type.AtlasStructType; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.type.AtlasTypeRegistry.AtlasTransientTypeRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicInteger; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.ATLAS_BUILTIN_TYPES; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.ATLAS_PRIMITIVE_TYPES; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.ATLAS_RELATIONSHIP_ATTRIBUTE_TYPES; public final class ModelTestUtil { private static final Logger LOG = LoggerFactory.getLogger(ModelTestUtil.class); private static final String PREFIX_ENUM_DEF = "testEnumDef-"; private static final String PREFIX_STRUCT_DEF = "testStructDef-"; private static final String PREFIX_ENTITY_DEF = "testEntityDef-"; private static final String PREFIX_CLASSIFICATION_DEF = "testClassificationDef-"; private static final String PREFIX_ATTRIBUTE_NAME = "attr-"; private static final String PREFIX_STRUCT = "testStruct-"; private static final String PREFIX_ENTITY = "testEntity-"; private static final String PREFIX_CLASSIFICATION = "testClassification-"; private static final int MAX_ENUM_ELEMENT_COUNT = 30; private static final AtomicInteger IDX_ENUM_DEF = new AtomicInteger(); private static final AtomicInteger IDX_ENTITY_DEF = new AtomicInteger(); private static final AtomicInteger IDX_CLASSIFICATION_DEF = new AtomicInteger(); private static final AtomicInteger IDX_STRUCT_DEF = new AtomicInteger(); private static final AtomicInteger IDX_CLASSIFICATION = new AtomicInteger(); private static final AtomicInteger IDX_ENTITY = new AtomicInteger(); private static final AtomicInteger IDX_STRUCT = new AtomicInteger(); private static final AtlasTypeRegistry TYPE_REGISTRY; private static final AtlasEnumDef ENUM_DEF; private static final AtlasEnumDef ENUM_DEF_WITH_NO_DEFAULT; private static final AtlasStructDef STRUCT_DEF; private static final AtlasEntityDef ENTITY_DEF; private static final AtlasEntityDef ENTITY_DEF_WITH_SUPER_TYPE; private static final AtlasEntityDef ENTITY_DEF_WITH_SUPER_TYPES; private static final AtlasClassificationDef CLASSIFICATION_DEF; private static final AtlasClassificationDef CLASSIFICATION_DEF_WITH_SUPER_TYPE; private static final AtlasClassificationDef CLASSIFICATION_DEF_WITH_SUPER_TYPES; static { TYPE_REGISTRY = new AtlasTypeRegistry(); ENUM_DEF = newEnumDef(true); ENUM_DEF_WITH_NO_DEFAULT = newEnumDef(false); STRUCT_DEF = newStructDef(); ENTITY_DEF = newEntityDef(); ENTITY_DEF_WITH_SUPER_TYPE = newEntityDef(new AtlasEntityDef[] { ENTITY_DEF }); ENTITY_DEF_WITH_SUPER_TYPES = newEntityDef(new AtlasEntityDef[] { ENTITY_DEF, ENTITY_DEF_WITH_SUPER_TYPE }); CLASSIFICATION_DEF = newClassificationDef(); CLASSIFICATION_DEF_WITH_SUPER_TYPE = newClassificationDef(new AtlasClassificationDef[] { CLASSIFICATION_DEF }); CLASSIFICATION_DEF_WITH_SUPER_TYPES = newClassificationDef( new AtlasClassificationDef[] { CLASSIFICATION_DEF, CLASSIFICATION_DEF_WITH_SUPER_TYPE }); } private ModelTestUtil() { } public static AtlasTypeRegistry getTypesRegistry() { return TYPE_REGISTRY; } public static AtlasEnumDef getEnumDef() { return ENUM_DEF; } public static AtlasEnumDef getEnumDefWithNoDefault() { return ENUM_DEF_WITH_NO_DEFAULT; } public static AtlasStructDef getStructDef() { return STRUCT_DEF; } public static AtlasEntityDef getEntityDef() { return ENTITY_DEF; } public static AtlasEntityDef getEntityDefWithSuperType() { return ENTITY_DEF_WITH_SUPER_TYPE; } public static AtlasEntityDef getEntityDefWithSuperTypes() { return ENTITY_DEF_WITH_SUPER_TYPES; } public static AtlasClassificationDef getClassificationDef() { return CLASSIFICATION_DEF; } public static AtlasClassificationDef getClassificationDefWithSuperType() { return CLASSIFICATION_DEF_WITH_SUPER_TYPE; } public static AtlasClassificationDef getClassificationDefWithSuperTypes() { return CLASSIFICATION_DEF_WITH_SUPER_TYPES; } public static AtlasEnumDef newEnumDef() { return newEnumDef(getTypesRegistry(), true); } public static AtlasEnumDef newEnumDef(boolean hasDefaultValue) { return newEnumDef(getTypesRegistry(), hasDefaultValue); } public static AtlasEnumDef newEnumDef(AtlasTypeRegistry typesRegistry) { return newEnumDef(getTypesRegistry(), true); } public static AtlasEnumDef newEnumDef(AtlasTypeRegistry typesRegistry, boolean hasDefaultValue) { int enumDefIdx = IDX_ENUM_DEF.getAndIncrement(); AtlasEnumDef ret = new AtlasEnumDef(); ret.setName(PREFIX_ENUM_DEF + enumDefIdx); ret.setDescription(ret.getName()); int numElements = ThreadLocalRandom.current().nextInt(1, MAX_ENUM_ELEMENT_COUNT); for (int i = 0; i < numElements; i++) { String elementName = "element-" + i; ret.addElement(new AtlasEnumElementDef(elementName, elementName.toUpperCase(), i)); } if (hasDefaultValue) { int idxDefault = ThreadLocalRandom.current().nextInt(0, numElements); ret.setDefaultValue(ret.getElementDefs().get(idxDefault).getValue()); } AtlasTransientTypeRegistry ttr = null; boolean commit = false; try { ttr = typesRegistry.lockTypeRegistryForUpdate(); ttr.addType(ret); commit = true; } catch (AtlasBaseException excp) { LOG.error("failed to create enum-def", excp); ret = null; } finally { typesRegistry.releaseTypeRegistryForUpdate(ttr, commit); } return ret; } public static AtlasStructDef newStructDef() { return newStructDef(getTypesRegistry()); } public static AtlasStructDef newStructDef(AtlasTypeRegistry typesRegistry) { int structDefIdx = IDX_STRUCT_DEF.getAndIncrement(); AtlasStructDef ret = new AtlasStructDef(); ret.setName(PREFIX_STRUCT_DEF + structDefIdx); ret.setDescription(ret.getName()); ret.setAttributeDefs(newAttributeDefsWithAllBuiltInTypes(PREFIX_ATTRIBUTE_NAME)); AtlasTransientTypeRegistry ttr = null; boolean commit = false; try { ttr = typesRegistry.lockTypeRegistryForUpdate(); ttr.addType(ret); commit = true; } catch (AtlasBaseException excp) { LOG.error("failed to create struct-def", excp); ret = null; } finally { typesRegistry.releaseTypeRegistryForUpdate(ttr, commit); } return ret; } public static AtlasEntityDef newEntityDef() { return newEntityDef(getTypesRegistry(), null); } public static AtlasEntityDef newEntityDef(AtlasEntityDef[] superTypes) { return newEntityDef(getTypesRegistry(), superTypes); } public static AtlasEntityDef newEntityDef(AtlasTypeRegistry typesRegistry) { return newEntityDef(getTypesRegistry(), null); } public static AtlasEntityDef newEntityDef(AtlasTypeRegistry typesRegistry, AtlasEntityDef[] superTypes) { int entDefIdx = IDX_ENTITY_DEF.getAndIncrement(); AtlasEntityDef ret = new AtlasEntityDef(); ret.setName(PREFIX_ENTITY_DEF + entDefIdx); ret.setDescription(ret.getName()); ret.setAttributeDefs(newAttributeDefsWithAllBuiltInTypes(PREFIX_ATTRIBUTE_NAME)); if (superTypes != null) { for (AtlasEntityDef superType : superTypes) { ret.addSuperType(superType.getName()); } } AtlasTransientTypeRegistry ttr = null; boolean commit = false; try { ttr = typesRegistry.lockTypeRegistryForUpdate(); ttr.addType(ret); commit = true; } catch (AtlasBaseException excp) { LOG.error("failed to create entity-def", excp); ret = null; } finally { typesRegistry.releaseTypeRegistryForUpdate(ttr, commit); } return ret; } public static AtlasEntityDef newEntityDefWithSuperTypes() { return newEntityDefWithSuperTypes(getTypesRegistry()); } public static AtlasEntityDef newEntityDefWithSuperTypes(AtlasTypeRegistry typesRegistry) { return newEntityDef(typesRegistry, new AtlasEntityDef[] { ENTITY_DEF, ENTITY_DEF_WITH_SUPER_TYPE }); } public static AtlasClassificationDef newClassificationDef() { return newClassificationDef(getTypesRegistry(), null); } public static AtlasClassificationDef newClassificationDef(AtlasClassificationDef[] superTypes) { return newClassificationDef(getTypesRegistry(), superTypes); } public static AtlasClassificationDef newClassificationDef(AtlasTypeRegistry typesRegistry) { return newClassificationDef(typesRegistry, null); } public static AtlasClassificationDef newClassificationDef(AtlasTypeRegistry typesRegistry, AtlasClassificationDef[] superTypes) { int classificationDefIdx = IDX_CLASSIFICATION_DEF.getAndIncrement(); AtlasClassificationDef ret = new AtlasClassificationDef(); ret.setName(PREFIX_CLASSIFICATION_DEF + classificationDefIdx); ret.setDescription(ret.getName()); ret.setAttributeDefs(newAttributeDefsWithAllBuiltInTypes(PREFIX_ATTRIBUTE_NAME)); if (superTypes != null) { for (AtlasClassificationDef superType : superTypes) { ret.addSuperType(superType.getName()); } } AtlasTransientTypeRegistry ttr = null; boolean commit = false; try { ttr = typesRegistry.lockTypeRegistryForUpdate(); ttr.addType(ret); commit = true; } catch (AtlasBaseException excp) { LOG.error("failed to create classification-def", excp); ret = null; } finally { typesRegistry.releaseTypeRegistryForUpdate(ttr, commit); } return ret; } public static AtlasEntity newEntity(AtlasEntityDef entityDef) { return newEntity(entityDef, getTypesRegistry()); } public static AtlasEntity newEntity(AtlasEntityDef entityDef, AtlasTypeRegistry typesRegistry) { AtlasEntity ret = null; AtlasEntityType entityType = typesRegistry.getEntityTypeByName(entityDef.getName()); if (entityType != null) { ret = entityType.createDefaultValue(); } else { LOG.error("failed to get entity-type {}", entityDef.getName()); } return ret; } public static AtlasStruct newStruct(AtlasStructDef structDef) { return newStruct(structDef, getTypesRegistry()); } public static AtlasStruct newStruct(AtlasStructDef structDef, AtlasTypeRegistry typesRegistry) { AtlasStruct ret = null; AtlasStructType structType = typesRegistry.getStructTypeByName(structDef.getName()); if (structType != null) { ret = structType.createDefaultValue(); } else { LOG.error("failed to get struct-type {}", structDef.getName()); } return ret; } public static AtlasClassification newClassification(AtlasClassificationDef classificationDef) { return newClassification(classificationDef, getTypesRegistry()); } public static AtlasClassification newClassification(AtlasClassificationDef classificationDef, AtlasTypeRegistry typesRegistry) { AtlasClassification ret = null; AtlasClassificationType classificationType = typesRegistry.getClassificationTypeByName(classificationDef.getName()); if (classificationType != null) { ret = classificationType.createDefaultValue(); } else { LOG.error("failed to get classification-type {}", classificationDef.getName()); } return ret; } public static List<AtlasAttributeDef> newAttributeDefsWithAllBuiltInTypes(String attrNamePrefix) { List<AtlasAttributeDef> ret = new ArrayList<>(); // add all built-in types for (String ATLAS_BUILTIN_TYPE2 : ATLAS_BUILTIN_TYPES) { ret.add(getAttributeDef(attrNamePrefix, ATLAS_BUILTIN_TYPE2)); } // add enum types ret.add(getAttributeDef(attrNamePrefix, ENUM_DEF.getName())); ret.add(getAttributeDef(attrNamePrefix, ENUM_DEF_WITH_NO_DEFAULT.getName())); // add array of built-in types for (String ATLAS_BUILTIN_TYPE1 : ATLAS_BUILTIN_TYPES) { ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getArrayTypeName(ATLAS_BUILTIN_TYPE1))); } // add array of enum types ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getArrayTypeName(ENUM_DEF.getName()))); ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getArrayTypeName(ENUM_DEF_WITH_NO_DEFAULT.getName()))); // add few map types for (String ATLAS_PRIMITIVE_TYPE3 : ATLAS_PRIMITIVE_TYPES) { ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getMapTypeName(ATLAS_PRIMITIVE_TYPE3, getRandomBuiltInType()))); } // add map types with enum as key ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getMapTypeName(ENUM_DEF.getName(), getRandomBuiltInType()))); ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getMapTypeName(ENUM_DEF_WITH_NO_DEFAULT.getName(), getRandomBuiltInType()))); // add map types with enum as value ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getMapTypeName(getRandomPrimitiveType(), ENUM_DEF.getName()))); ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getMapTypeName(getRandomPrimitiveType(), ENUM_DEF_WITH_NO_DEFAULT.getName()))); // add few array of arrays for (String ATLAS_BUILTIN_TYPE : ATLAS_BUILTIN_TYPES) { ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getArrayTypeName(AtlasBaseTypeDef.getArrayTypeName(getRandomBuiltInType())))); } ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getArrayTypeName(ENUM_DEF.getName()))); ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getArrayTypeName(ENUM_DEF_WITH_NO_DEFAULT.getName()))); // add few array of maps for (String ATLAS_PRIMITIVE_TYPE2 : ATLAS_PRIMITIVE_TYPES) { ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getArrayTypeName( AtlasBaseTypeDef.getMapTypeName(ATLAS_PRIMITIVE_TYPE2, getRandomBuiltInType())))); } ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getArrayTypeName( AtlasBaseTypeDef.getMapTypeName(ENUM_DEF.getName(), getRandomBuiltInType())))); ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getArrayTypeName( AtlasBaseTypeDef.getMapTypeName(ENUM_DEF_WITH_NO_DEFAULT.getName(), getRandomBuiltInType())))); ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getArrayTypeName( AtlasBaseTypeDef.getMapTypeName(getRandomPrimitiveType(), ENUM_DEF.getName())))); ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getArrayTypeName( AtlasBaseTypeDef.getMapTypeName(getRandomPrimitiveType(), ENUM_DEF_WITH_NO_DEFAULT.getName())))); // add few map of arrays for (String ATLAS_PRIMITIVE_TYPE1 : ATLAS_PRIMITIVE_TYPES) { ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getMapTypeName(ATLAS_PRIMITIVE_TYPE1, AtlasBaseTypeDef.getArrayTypeName(getRandomBuiltInType())))); } // add few map of maps for (String ATLAS_PRIMITIVE_TYPE : ATLAS_PRIMITIVE_TYPES) { ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getMapTypeName(ATLAS_PRIMITIVE_TYPE, AtlasBaseTypeDef.getMapTypeName(ATLAS_PRIMITIVE_TYPE, getRandomBuiltInType())))); } return ret; } /** * Valid types for attributes in relationships. This has good coverage of all attribute type and includes enums * maps and arrays. * This test does not use getRandomBuiltInType() style - so that it is deterministic. * * It does cover very nested maps / arrays. * @param attrNamePrefix * @return */ public static List<AtlasAttributeDef> newAttributeDefsWithAllBuiltInTypesForRelationship(String attrNamePrefix) { List<AtlasAttributeDef> ret = new ArrayList<>(); // add enum types ret.add(getAttributeDef(attrNamePrefix, ENUM_DEF.getName())); ret.add(getAttributeDef(attrNamePrefix, ENUM_DEF_WITH_NO_DEFAULT.getName())); // add array of enum types ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getArrayTypeName(ENUM_DEF.getName()))); ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getArrayTypeName(ENUM_DEF_WITH_NO_DEFAULT.getName()))); for (String attributeType : ATLAS_RELATIONSHIP_ATTRIBUTE_TYPES) { // simple attributes ret.add(getAttributeDef(attrNamePrefix, attributeType)); // array ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getArrayTypeName(attributeType))); // map types with enum as key ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getMapTypeName(ENUM_DEF.getName(), attributeType))); // map types with enum as key no default ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getMapTypeName(ENUM_DEF_WITH_NO_DEFAULT.getName(), attributeType))); // map types attribute as key enum no default as value ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getMapTypeName(attributeType, ENUM_DEF_WITH_NO_DEFAULT.getName()))); // map types with enum as value ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getMapTypeName(attributeType, ENUM_DEF.getName()))); for (String attributeType2 : ATLAS_RELATIONSHIP_ATTRIBUTE_TYPES) { // add map types ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getMapTypeName(attributeType, attributeType2))); // add array of arrays ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getArrayTypeName(AtlasBaseTypeDef.getArrayTypeName(attributeType2)))); // add array of maps ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getArrayTypeName( AtlasBaseTypeDef.getMapTypeName(attributeType, attributeType2)))); // add map of arrays ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getMapTypeName(attributeType, AtlasBaseTypeDef.getArrayTypeName(attributeType2)))); // add map of maps ret.add(getAttributeDef(attrNamePrefix, AtlasBaseTypeDef.getMapTypeName(attributeType, AtlasBaseTypeDef.getMapTypeName(attributeType, attributeType2)))); } } return ret; } public static String getDefaultAttributeName(String attrType) { return PREFIX_ATTRIBUTE_NAME + attrType; } private static AtlasAttributeDef getAttributeDef(String attrNamePrefix, String attrType) { return new AtlasAttributeDef(attrNamePrefix + attrType, attrType); } private static String getRandomPrimitiveType() { return ATLAS_PRIMITIVE_TYPES[ThreadLocalRandom.current().nextInt(0, ATLAS_PRIMITIVE_TYPES.length)]; } private static String getRandomBuiltInType() { return ATLAS_BUILTIN_TYPES[ThreadLocalRandom.current().nextInt(0, ATLAS_BUILTIN_TYPES.length)]; } } <|start_filename|>graphdb/titan1/src/main/java/org/apache/atlas/repository/graphdb/titan1/GraphDbObjectFactory.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan1; import org.apache.atlas.repository.graphdb.AtlasCardinality; import org.apache.atlas.repository.graphdb.AtlasGraphIndex; import org.apache.atlas.repository.graphdb.titan1.query.Titan1GraphQuery; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Vertex; import com.thinkaurelius.titan.core.Cardinality; import com.thinkaurelius.titan.core.PropertyKey; import com.thinkaurelius.titan.core.schema.TitanGraphIndex; /** * Factory that serves up instances of graph database abstraction layer classes * that correspond to Titan/Tinkerpop3 classes. */ public final class GraphDbObjectFactory { private GraphDbObjectFactory() { } /** * Creates a Titan1Edge that corresponds to the given Gremlin Edge. * * @param graph The graph the edge should be created in * @param source The gremlin edge */ public static Titan1Edge createEdge(Titan1Graph graph, Edge source) { if (source == null) { return null; } return new Titan1Edge(graph, source); } /** * Creates a Titan1GraphQuery that corresponds to the given GraphQuery. * * @param graph the graph that is being quried */ public static Titan1GraphQuery createQuery(Titan1Graph graph, boolean isChildQuery) { return new Titan1GraphQuery(graph, isChildQuery); } /** * Creates a Titan1Vertex that corresponds to the given Gremlin Vertex. * * @param graph The graph that contains the vertex * @param source the Gremlin vertex */ public static Titan1Vertex createVertex(Titan1Graph graph, Vertex source) { if (source == null) { return null; } return new Titan1Vertex(graph, source); } /** * @param propertyKey The Gremlin propertyKey. * */ public static Titan1PropertyKey createPropertyKey(PropertyKey propertyKey) { if (propertyKey == null) { return null; } return new Titan1PropertyKey(propertyKey); } /** * @param index The gremlin index. * @return */ public static AtlasGraphIndex createGraphIndex(TitanGraphIndex index) { if (index == null) { return null; } return new Titan1GraphIndex(index); } /** * Converts a Multiplicity to a Cardinality. * * @param cardinality * @return */ public static AtlasCardinality createCardinality(Cardinality cardinality) { if (cardinality == Cardinality.SINGLE) { return AtlasCardinality.SINGLE; } else if (cardinality == Cardinality.LIST) { return AtlasCardinality.LIST; } return AtlasCardinality.SET; } } <|start_filename|>intg/src/main/java/org/apache/atlas/type/AtlasEnumType.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.type; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.typedef.AtlasEnumDef; import org.apache.atlas.model.typedef.AtlasEnumDef.AtlasEnumElementDef; /** * class that implements behaviour of an enum-type. */ public class AtlasEnumType extends AtlasType { private final AtlasEnumDef enumDef; private final Map<String, AtlasEnumElementDef> elementDefs; private final String defaultValue; public AtlasEnumType(AtlasEnumDef enumDef) { super(enumDef); Map<String, AtlasEnumElementDef> e = new HashMap<>(); for (AtlasEnumElementDef elementDef : enumDef.getElementDefs()) { e.put(elementDef.getValue().toLowerCase(), elementDef); } String d = enumDef.getDefaultValue(); if (d == null) { AtlasEnumElementDef defElem = enumDef.getElementDefs().size() > 0 ? enumDef.getElementDefs().get(0) : null; if (defElem != null) { d = defElem.getValue(); } } this.enumDef = enumDef; this.elementDefs = Collections.unmodifiableMap(e); this.defaultValue = d; } public AtlasEnumDef getEnumDef() { return enumDef; } @Override public void resolveReferences(AtlasTypeRegistry typeRegistry) throws AtlasBaseException { } @Override public Object createDefaultValue() { return defaultValue; } @Override public boolean isValidValue(Object obj) { if (obj != null) { return elementDefs.containsKey(obj.toString().toLowerCase()); } return true; } @Override public Object getNormalizedValue(Object obj) { if (obj != null) { AtlasEnumElementDef elementDef = elementDefs.get(obj.toString().toLowerCase()); if (elementDef != null) { return elementDef.getValue(); } } return null; } public AtlasEnumElementDef getEnumElementDef(String value) { if (value != null) { return elementDefs.get(value.toLowerCase()); } return null; } public AtlasEnumElementDef getEnumElementDef(Number ordinal) { if (ordinal != null) { for (AtlasEnumElementDef elementDef : elementDefs.values()) { if (elementDef.getOrdinal().longValue() == ordinal.longValue()) { return elementDef; } } } return null; } } <|start_filename|>graphdb/titan0/src/main/java/org/apache/atlas/repository/graphdb/titan0/Titan0GraphIndex.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan0; import java.util.HashSet; import java.util.Set; import org.apache.atlas.repository.graphdb.AtlasGraphIndex; import org.apache.atlas.repository.graphdb.AtlasPropertyKey; import com.thinkaurelius.titan.core.PropertyKey; import com.thinkaurelius.titan.core.schema.TitanGraphIndex; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Vertex; /** * Titan 0.5.4 implementation of AtlasGraphIndex. */ public class Titan0GraphIndex implements AtlasGraphIndex { private TitanGraphIndex wrappedIndex; public Titan0GraphIndex(TitanGraphIndex toWrap) { wrappedIndex = toWrap; } /* (non-Javadoc) * @see org.apache.atlas.repository.graphdb.AtlasGraphIndex#isMixedIndex() */ @Override public boolean isMixedIndex() { return wrappedIndex.isMixedIndex(); } /* (non-Javadoc) * @see org.apache.atlas.repository.graphdb.AtlasGraphIndex#isEdgeIndex() */ @Override public boolean isEdgeIndex() { return Edge.class.isAssignableFrom(wrappedIndex.getIndexedElement()); } /* (non-Javadoc) * @see org.apache.atlas.repository.graphdb.AtlasGraphIndex#isVertexIndex() */ @Override public boolean isVertexIndex() { return Vertex.class.isAssignableFrom(wrappedIndex.getIndexedElement()); } /* (non-Javadoc) * @see org.apache.atlas.repository.graphdb.AtlasGraphIndex#isCompositeIndex() */ @Override public boolean isCompositeIndex() { return wrappedIndex.isCompositeIndex(); } /* (non-Javadoc) * @see org.apache.atlas.repository.graphdb.AtlasGraphIndex#isUnique() */ @Override public boolean isUnique() { return wrappedIndex.isUnique(); } /* (non-Javadoc) * @see org.apache.atlas.repository.graphdb.AtlasGraphIndex#getFieldKeys() */ @Override public Set<AtlasPropertyKey> getFieldKeys() { PropertyKey[] keys = wrappedIndex.getFieldKeys(); Set<AtlasPropertyKey> result = new HashSet<>(); for(PropertyKey key : keys) { result.add(GraphDbObjectFactory.createPropertyKey(key)); } return result; } } <|start_filename|>webapp/src/test/java/org/apache/atlas/notification/NotificationHookConsumerIT.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.notification; import org.apache.atlas.EntityAuditEvent; import org.apache.atlas.kafka.NotificationProvider; import org.apache.atlas.notification.hook.HookNotification; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.persistence.Id; import org.apache.atlas.web.integration.BaseResourceIT; import org.codehaus.jettison.json.JSONArray; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.List; import static org.testng.Assert.assertEquals; public class NotificationHookConsumerIT extends BaseResourceIT { private static final String TEST_USER = "testuser"; public static final String NAME = "name"; public static final String DESCRIPTION = "description"; public static final String QUALIFIED_NAME = "qualifiedName"; public static final String CLUSTER_NAME = "clusterName"; private NotificationInterface notificationInterface = NotificationProvider.get(); @BeforeClass public void setUp() throws Exception { super.setUp(); createTypeDefinitionsV1(); } @AfterClass public void teardown() throws Exception { notificationInterface.close(); } private void sendHookMessage(HookNotification.HookNotificationMessage message) throws NotificationException { notificationInterface.send(NotificationInterface.NotificationType.HOOK, message); } @Test public void testMessageHandleFailureConsumerContinues() throws Exception { //send invalid message - update with invalid type sendHookMessage(new HookNotification.EntityPartialUpdateRequest(TEST_USER, randomString(), null, null, new Referenceable(randomString()))); //send valid message final Referenceable entity = new Referenceable(DATABASE_TYPE_BUILTIN); String dbName = "db" + randomString(); entity.set(NAME, dbName); entity.set(DESCRIPTION, randomString()); entity.set(QUALIFIED_NAME, dbName); entity.set(CLUSTER_NAME, randomString()); sendHookMessage(new HookNotification.EntityCreateRequest(TEST_USER, entity)); waitFor(MAX_WAIT_TIME, new Predicate() { @Override public boolean evaluate() throws Exception { JSONArray results = searchByDSL(String.format("%s where name='%s'", DATABASE_TYPE_BUILTIN, entity.get(NAME))); return results.length() == 1; } }); } @Test public void testCreateEntity() throws Exception { final Referenceable entity = new Referenceable(DATABASE_TYPE_BUILTIN); String dbName = "db" + randomString(); entity.set(NAME, dbName); entity.set(DESCRIPTION, randomString()); entity.set(QUALIFIED_NAME, dbName); entity.set(CLUSTER_NAME, randomString()); sendHookMessage(new HookNotification.EntityCreateRequest(TEST_USER, entity)); waitFor(MAX_WAIT_TIME, new Predicate() { @Override public boolean evaluate() throws Exception { JSONArray results = searchByDSL(String.format("%s where qualifiedName='%s'", DATABASE_TYPE_BUILTIN, entity.get(QUALIFIED_NAME))); return results.length() == 1; } }); //Assert that user passed in hook message is used in audit Referenceable instance = atlasClientV1.getEntity(DATABASE_TYPE_BUILTIN, QUALIFIED_NAME, (String) entity.get(QUALIFIED_NAME)); List<EntityAuditEvent> events = atlasClientV1.getEntityAuditEvents(instance.getId()._getId(), (short) 1); assertEquals(events.size(), 1); assertEquals(events.get(0).getUser(), TEST_USER); } @Test public void testUpdateEntityPartial() throws Exception { final Referenceable entity = new Referenceable(DATABASE_TYPE_BUILTIN); final String dbName = "db" + randomString(); entity.set(NAME, dbName); entity.set(DESCRIPTION, randomString()); entity.set(QUALIFIED_NAME, dbName); entity.set(CLUSTER_NAME, randomString()); atlasClientV1.createEntity(entity); final Referenceable newEntity = new Referenceable(DATABASE_TYPE_BUILTIN); newEntity.set("owner", randomString()); sendHookMessage( new HookNotification.EntityPartialUpdateRequest(TEST_USER, DATABASE_TYPE_BUILTIN, QUALIFIED_NAME, dbName, newEntity)); waitFor(MAX_WAIT_TIME, new Predicate() { @Override public boolean evaluate() throws Exception { Referenceable localEntity = atlasClientV1.getEntity(DATABASE_TYPE_BUILTIN, QUALIFIED_NAME, dbName); return (localEntity.get("owner") != null && localEntity.get("owner").equals(newEntity.get("owner"))); } }); //Its partial update and un-set fields are not updated Referenceable actualEntity = atlasClientV1.getEntity(DATABASE_TYPE_BUILTIN, QUALIFIED_NAME, dbName); assertEquals(actualEntity.get(DESCRIPTION), entity.get(DESCRIPTION)); } @Test public void testUpdatePartialUpdatingQualifiedName() throws Exception { final Referenceable entity = new Referenceable(DATABASE_TYPE_BUILTIN); final String dbName = "db" + randomString(); entity.set(NAME, dbName); entity.set(DESCRIPTION, randomString()); entity.set(QUALIFIED_NAME, dbName); entity.set(CLUSTER_NAME, randomString()); atlasClientV1.createEntity(entity); final Referenceable newEntity = new Referenceable(DATABASE_TYPE_BUILTIN); final String newName = "db" + randomString(); newEntity.set(QUALIFIED_NAME, newName); sendHookMessage( new HookNotification.EntityPartialUpdateRequest(TEST_USER, DATABASE_TYPE_BUILTIN, QUALIFIED_NAME, dbName, newEntity)); waitFor(MAX_WAIT_TIME, new Predicate() { @Override public boolean evaluate() throws Exception { JSONArray results = searchByDSL(String.format("%s where qualifiedName='%s'", DATABASE_TYPE_BUILTIN, newName)); return results.length() == 1; } }); //no entity with the old qualified name JSONArray results = searchByDSL(String.format("%s where qualifiedName='%s'", DATABASE_TYPE_BUILTIN, dbName)); assertEquals(results.length(), 0); } @Test public void testDeleteByQualifiedName() throws Exception { Referenceable entity = new Referenceable(DATABASE_TYPE_BUILTIN); final String dbName = "db" + randomString(); entity.set(NAME, dbName); entity.set(DESCRIPTION, randomString()); entity.set(QUALIFIED_NAME, dbName); entity.set(CLUSTER_NAME, randomString()); final String dbId = atlasClientV1.createEntity(entity).get(0); sendHookMessage( new HookNotification.EntityDeleteRequest(TEST_USER, DATABASE_TYPE_BUILTIN, QUALIFIED_NAME, dbName)); waitFor(MAX_WAIT_TIME, new Predicate() { @Override public boolean evaluate() throws Exception { Referenceable getEntity = atlasClientV1.getEntity(dbId); return getEntity.getId().getState() == Id.EntityState.DELETED; } }); } @Test public void testUpdateEntityFullUpdate() throws Exception { Referenceable entity = new Referenceable(DATABASE_TYPE_BUILTIN); final String dbName = "db" + randomString(); entity.set(NAME, dbName); entity.set(DESCRIPTION, randomString()); entity.set(QUALIFIED_NAME, dbName); entity.set(CLUSTER_NAME, randomString()); atlasClientV1.createEntity(entity); final Referenceable newEntity = new Referenceable(DATABASE_TYPE_BUILTIN); newEntity.set(NAME, randomString()); newEntity.set(DESCRIPTION, randomString()); newEntity.set("owner", randomString()); newEntity.set(QUALIFIED_NAME, dbName); newEntity.set(CLUSTER_NAME, randomString()); //updating unique attribute sendHookMessage(new HookNotification.EntityUpdateRequest(TEST_USER, newEntity)); waitFor(MAX_WAIT_TIME, new Predicate() { @Override public boolean evaluate() throws Exception { JSONArray results = searchByDSL(String.format("%s where qualifiedName='%s'", DATABASE_TYPE_BUILTIN, newEntity.get(QUALIFIED_NAME))); return results.length() == 1; } }); Referenceable actualEntity = atlasClientV1.getEntity(DATABASE_TYPE_BUILTIN, QUALIFIED_NAME, dbName); assertEquals(actualEntity.get(DESCRIPTION), newEntity.get(DESCRIPTION)); assertEquals(actualEntity.get("owner"), newEntity.get("owner")); } } <|start_filename|>repository/src/main/java/org/apache/atlas/util/TypeDefSorter.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.util; import org.apache.atlas.model.typedef.AtlasClassificationDef; import org.apache.atlas.model.typedef.AtlasEntityDef; import org.apache.atlas.model.typedef.AtlasStructDef; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class TypeDefSorter { private static final Logger LOG = LoggerFactory.getLogger(TypeDefSorter.class); public static <T extends AtlasStructDef> List<T> sortTypes(List<T> types) { Map<String, T> typesByName = new HashMap<>(); for (T type : types) { typesByName.put(type.getName(), type); } List<T> result = new ArrayList<>(types.size()); Set<T> processed = new HashSet<>(); for (T type : types) { addToResult(type, result, processed, typesByName); } return result; } private static <T extends AtlasStructDef> void addToResult(T type, List<T> result, Set<T> processed, Map<String, T> typesByName) { if (processed.contains(type)) { return; } processed.add(type); Set<String> superTypeNames = new HashSet<>(); if (type.getClass().equals(AtlasClassificationDef.class)) { try { AtlasClassificationDef classificationDef = AtlasClassificationDef.class.cast(type); superTypeNames.addAll(classificationDef.getSuperTypes()); } catch (ClassCastException ex) { LOG.warn("Casting to ClassificationDef failed"); } } if (type.getClass().equals(AtlasEntityDef.class)) { try { AtlasEntityDef entityDef = AtlasEntityDef.class.cast(type); superTypeNames.addAll(entityDef.getSuperTypes()); } catch (ClassCastException ex) { LOG.warn("Casting to AtlasEntityDef failed"); } } for (String superTypeName : superTypeNames) { // Recursively add any supertypes first to the result. T superType = typesByName.get(superTypeName); if (superType != null) { addToResult(superType, result, processed, typesByName); } } result.add(type); } } <|start_filename|>webapp/src/main/java/org/apache/atlas/web/rest/LineageREST.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.web.rest; import org.apache.atlas.discovery.AtlasLineageService; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.lineage.AtlasLineageInfo; import org.apache.atlas.model.lineage.AtlasLineageInfo.LineageDirection; import org.apache.atlas.utils.AtlasPerfTracer; import org.apache.atlas.web.util.Servlets; import org.slf4j.Logger; import org.springframework.stereotype.Service; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; /** * REST interface for an entity's lineage information */ @Path("v2/lineage") @Singleton @Service public class LineageREST { private static final Logger PERF_LOG = AtlasPerfTracer.getPerfLogger("rest.LineageREST"); private final AtlasLineageService atlasLineageService; private static final String DEFAULT_DIRECTION = "BOTH"; private static final String DEFAULT_DEPTH = "3"; @Context private HttpServletRequest httpServletRequest; @Inject public LineageREST(AtlasLineageService atlasLineageService) { this.atlasLineageService = atlasLineageService; } /** * Returns lineage info about entity. * @param guid - unique entity id * @param direction - input, output or both * @param depth - number of hops for lineage * @return AtlasLineageInfo * @throws AtlasBaseException * @HTTP 200 If Lineage exists for the given entity * @HTTP 400 Bad query parameters * @HTTP 404 If no lineage is found for the given entity */ @GET @Path("/{guid}") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) public AtlasLineageInfo getLineageGraph(@PathParam("guid") String guid, @QueryParam("direction") @DefaultValue(DEFAULT_DIRECTION) LineageDirection direction, @QueryParam("depth") @DefaultValue(DEFAULT_DEPTH) int depth) throws AtlasBaseException { AtlasPerfTracer perf = null; try { if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "LineageREST.getLineageGraph(" + guid + "," + direction + "," + depth + ")"); } return atlasLineageService.getAtlasLineageInfo(guid, direction, depth); } finally { AtlasPerfTracer.log(perf); } } } <|start_filename|>catalog/src/main/java/org/apache/atlas/catalog/DefaultPropertyMapper.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.catalog; import org.apache.atlas.AtlasException; import org.apache.atlas.catalog.exception.CatalogRuntimeException; import org.apache.atlas.repository.Constants; import org.apache.atlas.typesystem.types.FieldMapping; import org.apache.atlas.typesystem.types.HierarchicalType; import org.apache.atlas.typesystem.types.TypeSystem; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Default property mapper which translates property names to/from name exposed in API to internal fully qualified name. */ public class DefaultPropertyMapper implements PropertyMapper { //todo: abstract HierarchicalType private Map<String, HierarchicalType> typeInstances = new HashMap<>(); private final Map<String, String> m_qualifiedToCleanMap = new HashMap<>(); private final Map<String, String> m_cleanToQualifiedMap = new HashMap<>(); public DefaultPropertyMapper() { this(Collections.<String, String>emptyMap(), Collections.<String, String>emptyMap()); } public DefaultPropertyMapper(Map<String, String> qualifiedToCleanMap, Map<String, String> cleanToQualifiedMap) { setDefaultMappings(); m_qualifiedToCleanMap.putAll(qualifiedToCleanMap); m_cleanToQualifiedMap.putAll(cleanToQualifiedMap); } @Override public String toCleanName(String propName, String type) { HierarchicalType dataType = getDataType(type); String replacement = m_qualifiedToCleanMap.get(propName); if (replacement == null && dataType != null) { FieldMapping fieldMap = dataType.fieldMapping(); if (! fieldMap.fields.containsKey(propName) && propName.contains(".")) { String cleanName = propName.substring(propName.lastIndexOf('.') + 1); if (fieldMap.fields.containsKey(cleanName)) { replacement = cleanName; } } } if (replacement == null) { replacement = propName; } return replacement; } @Override public String toFullyQualifiedName(String propName, String type) { HierarchicalType dataType = getDataType(type); String replacement = m_cleanToQualifiedMap.get(propName); if (replacement == null && dataType != null) { FieldMapping fieldMap = dataType.fieldMapping(); if (fieldMap.fields.containsKey(propName)) { try { replacement = dataType.getQualifiedName(propName); } catch (AtlasException e) { throw new CatalogRuntimeException(String.format( "Unable to resolve fully qualified property name for type '%s': %s", type, e), e); } } } if (replacement == null) { replacement = propName; } return replacement; } //todo: abstract this via AtlasTypeSystem protected synchronized HierarchicalType getDataType(String type) { HierarchicalType dataType = typeInstances.get(type); //todo: are there still cases where type can be null? if (dataType == null) { dataType = createDataType(type); typeInstances.put(type, dataType); } return dataType; } protected HierarchicalType createDataType(String type) { try { return TypeSystem.getInstance().getDataType(HierarchicalType.class, type); } catch (AtlasException e) { throw new CatalogRuntimeException("Unable to get type instance from type system for type: " + type, e); } } private void setDefaultMappings() { //todo: these are all internal "__*" properties //todo: should be able to ask type system for the "clean" name for these m_qualifiedToCleanMap.put(Constants.GUID_PROPERTY_KEY, "id"); m_cleanToQualifiedMap.put("id", Constants.GUID_PROPERTY_KEY); m_qualifiedToCleanMap.put(Constants.TIMESTAMP_PROPERTY_KEY, "creation_time"); m_cleanToQualifiedMap.put("creation_time", Constants.TIMESTAMP_PROPERTY_KEY); m_qualifiedToCleanMap.put(Constants.MODIFICATION_TIMESTAMP_PROPERTY_KEY, "modified_time"); m_cleanToQualifiedMap.put("modified_time", Constants.MODIFICATION_TIMESTAMP_PROPERTY_KEY); m_qualifiedToCleanMap.put(Constants.ENTITY_TYPE_PROPERTY_KEY, "type"); m_cleanToQualifiedMap.put("type", Constants.ENTITY_TYPE_PROPERTY_KEY); m_qualifiedToCleanMap.put(Constants.VERSION_PROPERTY_KEY, "version"); m_cleanToQualifiedMap.put("version", Constants.VERSION_PROPERTY_KEY); m_qualifiedToCleanMap.put(Constants.TRAIT_NAMES_PROPERTY_KEY, "trait_names"); m_cleanToQualifiedMap.put("trait_names", Constants.TRAIT_NAMES_PROPERTY_KEY); m_qualifiedToCleanMap.put(Constants.SUPER_TYPES_PROPERTY_KEY, "super_types"); m_cleanToQualifiedMap.put("super_types", Constants.SUPER_TYPES_PROPERTY_KEY); m_qualifiedToCleanMap.put(Constants.STATE_PROPERTY_KEY, "state"); m_cleanToQualifiedMap.put("state", Constants.STATE_PROPERTY_KEY); m_qualifiedToCleanMap.put(Constants.CREATED_BY_KEY, "created_by"); m_cleanToQualifiedMap.put("created_by", Constants.CREATED_BY_KEY); m_qualifiedToCleanMap.put(Constants.MODIFIED_BY_KEY, "modified_by"); m_cleanToQualifiedMap.put("modified_by", Constants.MODIFIED_BY_KEY); } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/graph/EntityProcessor.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graph; import org.apache.atlas.AtlasException; import org.apache.atlas.repository.RepositoryException; import org.apache.atlas.typesystem.IReferenceableInstance; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.persistence.Id; import org.apache.atlas.typesystem.types.DataTypes; import org.apache.atlas.typesystem.types.ObjectGraphWalker; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; @Deprecated public final class EntityProcessor implements ObjectGraphWalker.NodeProcessor { private final Map<Id, IReferenceableInstance> idToInstanceMap; public EntityProcessor() { idToInstanceMap = new LinkedHashMap<>(); } public Collection<IReferenceableInstance> getInstances() { ArrayList<IReferenceableInstance> instances = new ArrayList<>(idToInstanceMap.values()); Collections.reverse(instances); return instances; } @Override public void processNode(ObjectGraphWalker.Node nd) throws AtlasException { IReferenceableInstance ref = null; Id id = null; if (nd.attributeName == null) { ref = (IReferenceableInstance) nd.instance; id = ref.getId(); } else if (nd.aInfo.dataType().getTypeCategory() == DataTypes.TypeCategory.CLASS) { if (nd.value != null && (nd.value instanceof Id)) { id = (Id) nd.value; } } if (id != null) { if (id.isUnassigned()) { if (ref != null) { if (idToInstanceMap.containsKey(id)) { // Oops throw new RepositoryException( String.format("Unexpected internal error: Id %s processed again", id)); } idToInstanceMap.put(id, ref); } } } } public void addInstanceIfNotExists(ITypedReferenceableInstance ref) { if(!idToInstanceMap.containsKey(ref.getId())) { idToInstanceMap.put(ref.getId(), ref); } } } <|start_filename|>notification/src/test/java/org/apache/atlas/kafka/KafkaConsumerTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.kafka; import kafka.message.MessageAndMetadata; import org.apache.atlas.notification.AbstractNotification; import org.apache.atlas.notification.MessageVersion; import org.apache.atlas.notification.NotificationInterface; import org.apache.atlas.notification.IncompatibleVersionException; import org.apache.atlas.notification.VersionedMessage; import org.apache.atlas.notification.entity.EntityNotificationImplTest; import org.apache.atlas.notification.hook.HookNotification; import org.apache.atlas.typesystem.IStruct; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.Struct; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.consumer.OffsetAndMetadata; import org.apache.kafka.common.TopicPartition; import org.codehaus.jettison.json.JSONException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Arrays; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.*; /** * KafkaConsumer tests. */ public class KafkaConsumerTest { private static final String TRAIT_NAME = "MyTrait"; @Mock private KafkaConsumer kafkaConsumer; @BeforeMethod public void setup() { MockitoAnnotations.initMocks(this); } @Test public void testReceive() throws Exception { MessageAndMetadata<String, String> messageAndMetadata = mock(MessageAndMetadata.class); Referenceable entity = getEntity(TRAIT_NAME); HookNotification.EntityUpdateRequest message = new HookNotification.EntityUpdateRequest("user1", entity); String json = AbstractNotification.GSON.toJson(new VersionedMessage<>(new MessageVersion("1.0.0"), message)); kafkaConsumer.assign(Arrays.asList(new TopicPartition("ATLAS_HOOK", 0))); List<ConsumerRecord> klist = new ArrayList<>(); klist.add(new ConsumerRecord<String, String>("ATLAS_HOOK", 0, 0L, "mykey", json)); TopicPartition tp = new TopicPartition("ATLAS_HOOK",0); Map mp = new HashMap(); mp.put(tp,klist); ConsumerRecords records = new ConsumerRecords(mp); when(kafkaConsumer.poll(100)).thenReturn(records); when(messageAndMetadata.message()).thenReturn(json); AtlasKafkaConsumer consumer = new AtlasKafkaConsumer(NotificationInterface.NotificationType.HOOK.getDeserializer(), kafkaConsumer, false, 100L); List<AtlasKafkaMessage<HookNotification.HookNotificationMessage>> messageList = consumer.receive(); assertTrue(messageList.size() > 0); HookNotification.HookNotificationMessage consumedMessage = messageList.get(0).getMessage(); assertMessagesEqual(message, consumedMessage, entity); } @Test public void testNextVersionMismatch() throws Exception { MessageAndMetadata<String, String> messageAndMetadata = mock(MessageAndMetadata.class); Referenceable entity = getEntity(TRAIT_NAME); HookNotification.EntityUpdateRequest message = new HookNotification.EntityUpdateRequest("user1", entity); String json = AbstractNotification.GSON.toJson(new VersionedMessage<>(new MessageVersion("2.0.0"), message)); kafkaConsumer.assign(Arrays.asList(new TopicPartition("ATLAS_HOOK", 0))); List<ConsumerRecord> klist = new ArrayList<>(); klist.add(new ConsumerRecord<String, String>("ATLAS_HOOK", 0, 0L, "mykey", json)); TopicPartition tp = new TopicPartition("ATLAS_HOOK",0); Map mp = new HashMap(); mp.put(tp,klist); ConsumerRecords records = new ConsumerRecords(mp); when(kafkaConsumer.poll(100L)).thenReturn(records); when(messageAndMetadata.message()).thenReturn(json); AtlasKafkaConsumer consumer =new AtlasKafkaConsumer(NotificationInterface.NotificationType.HOOK.getDeserializer(), kafkaConsumer ,false, 100L); try { List<AtlasKafkaMessage<HookNotification.HookNotificationMessage>> messageList = consumer.receive(); assertTrue(messageList.size() > 0); HookNotification.HookNotificationMessage consumedMessage = messageList.get(0).getMessage(); fail("Expected VersionMismatchException!"); } catch (IncompatibleVersionException e) { e.printStackTrace(); } } @Test public void testCommitIsCalledIfAutoCommitDisabled() { TopicPartition tp = new TopicPartition("ATLAS_HOOK",0); AtlasKafkaConsumer consumer =new AtlasKafkaConsumer(NotificationInterface.NotificationType.HOOK.getDeserializer(), kafkaConsumer, false, 100L); consumer.commit(tp, 1); verify(kafkaConsumer).commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(1))); } @Test public void testCommitIsNotCalledIfAutoCommitEnabled() { TopicPartition tp = new TopicPartition("ATLAS_HOOK",0); AtlasKafkaConsumer consumer =new AtlasKafkaConsumer(NotificationInterface.NotificationType.HOOK.getDeserializer(), kafkaConsumer, true , 100L); consumer.commit(tp, 1); verify(kafkaConsumer, never()).commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(1))); } private Referenceable getEntity(String traitName) { Referenceable entity = EntityNotificationImplTest.getEntity("id"); List<IStruct> traitInfo = new LinkedList<>(); IStruct trait = new Struct(traitName, Collections.<String, Object>emptyMap()); traitInfo.add(trait); return entity; } private void assertMessagesEqual(HookNotification.EntityUpdateRequest message, HookNotification.HookNotificationMessage consumedMessage, Referenceable entity) throws JSONException { assertEquals(consumedMessage.getType(), message.getType()); assertEquals(consumedMessage.getUser(), message.getUser()); assertTrue(consumedMessage instanceof HookNotification.EntityUpdateRequest); HookNotification.EntityUpdateRequest deserializedEntityUpdateRequest = (HookNotification.EntityUpdateRequest) consumedMessage; Referenceable deserializedEntity = deserializedEntityUpdateRequest.getEntities().get(0); assertEquals(deserializedEntity.getId(), entity.getId()); assertEquals(deserializedEntity.getTypeName(), entity.getTypeName()); assertEquals(deserializedEntity.getTraits(), entity.getTraits()); assertEquals(deserializedEntity.getTrait(TRAIT_NAME), entity.getTrait(TRAIT_NAME)); } } <|start_filename|>server-api/src/main/java/org/apache/atlas/RequestContextV1.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas; import org.apache.atlas.metrics.Metrics; import org.apache.atlas.model.instance.AtlasObjectId; import org.apache.atlas.typesystem.types.TypeSystem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; public class RequestContextV1 { private static final Logger LOG = LoggerFactory.getLogger(RequestContextV1.class); private static final ThreadLocal<RequestContextV1> CURRENT_CONTEXT = new ThreadLocal<>(); private Set<AtlasObjectId> createdEntityIds = new LinkedHashSet<>(); private Set<AtlasObjectId> updatedEntityIds = new LinkedHashSet<>(); private Set<AtlasObjectId> deletedEntityIds = new LinkedHashSet<>(); private String user; private final long requestTime; TypeSystem typeSystem = TypeSystem.getInstance(); private Metrics metrics = new Metrics(); private RequestContextV1() { requestTime = System.currentTimeMillis(); } //To handle gets from background threads where createContext() is not called //createContext called for every request in the filter public static RequestContextV1 get() { RequestContextV1 ret = CURRENT_CONTEXT.get(); if (ret == null) { ret = new RequestContextV1(); CURRENT_CONTEXT.set(ret); } return ret; } public static void clear() { CURRENT_CONTEXT.remove(); } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public void recordEntityCreate(Collection<AtlasObjectId> createdEntityIds) { this.createdEntityIds.addAll(createdEntityIds); } public void recordEntityCreate(AtlasObjectId createdEntityId) { this.createdEntityIds.add(createdEntityId); } public void recordEntityUpdate(Collection<AtlasObjectId> updatedEntityIds) { this.updatedEntityIds.addAll(updatedEntityIds); } public void recordEntityUpdate(AtlasObjectId entityId) { this.updatedEntityIds.add(entityId); } public void recordEntityDelete(AtlasObjectId entityId) { deletedEntityIds.add(entityId); } public Collection<AtlasObjectId> getCreatedEntityIds() { return createdEntityIds; } public Collection<AtlasObjectId> getUpdatedEntityIds() { return updatedEntityIds; } public Collection<AtlasObjectId> getDeletedEntityIds() { return deletedEntityIds; } public long getRequestTime() { return requestTime; } public boolean isDeletedEntity(AtlasObjectId entityId) { return deletedEntityIds.contains(entityId); } public static Metrics getMetrics() { return get().metrics; } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/store/graph/AtlasClassificationDefStore.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.store.graph; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.SearchFilter; import org.apache.atlas.model.typedef.AtlasClassificationDef; import org.apache.atlas.model.typedef.AtlasClassificationDef.AtlasClassificationDefs; import java.util.List; /** * Interface for graph persistence store for AtlasClassificationDef */ public interface AtlasClassificationDefStore { Object preCreate(AtlasClassificationDef classificationDef) throws AtlasBaseException; AtlasClassificationDef create(AtlasClassificationDef classifiDef, Object preCreateResult) throws AtlasBaseException; List<AtlasClassificationDef> getAll() throws AtlasBaseException; AtlasClassificationDef getByName(String name) throws AtlasBaseException; AtlasClassificationDef getByGuid(String guid) throws AtlasBaseException; AtlasClassificationDef update(AtlasClassificationDef classifiDef) throws AtlasBaseException; AtlasClassificationDef updateByName(String name, AtlasClassificationDef classifiDef) throws AtlasBaseException; AtlasClassificationDef updateByGuid(String guid, AtlasClassificationDef classifiDef) throws AtlasBaseException; Object preDeleteByName(String name) throws AtlasBaseException; void deleteByName(String name, Object preDeleteResult) throws AtlasBaseException; Object preDeleteByGuid(String guid) throws AtlasBaseException; void deleteByGuid(String guid, Object preDeleteResult) throws AtlasBaseException; } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/graph/GraphBackedMetadataRepository.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graph; import com.google.common.base.Preconditions; import org.apache.atlas.AtlasException; import org.apache.atlas.CreateUpdateEntitiesResult; import org.apache.atlas.GraphTransactionInterceptor; import org.apache.atlas.RequestContext; import org.apache.atlas.annotation.GraphTransaction; import org.apache.atlas.model.instance.GuidMapping; import org.apache.atlas.model.legacy.EntityResult; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.MetadataRepository; import org.apache.atlas.repository.RepositoryException; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.AtlasGraphQuery; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.ITypedStruct; import org.apache.atlas.typesystem.exception.EntityExistsException; import org.apache.atlas.typesystem.exception.EntityNotFoundException; import org.apache.atlas.typesystem.exception.TraitNotFoundException; import org.apache.atlas.typesystem.persistence.Id; import org.apache.atlas.typesystem.types.AttributeInfo; import org.apache.atlas.typesystem.types.ClassType; import org.apache.atlas.typesystem.types.DataTypes; import org.apache.atlas.typesystem.types.IDataType; import org.apache.atlas.typesystem.types.TypeSystem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.inject.Inject; import javax.inject.Singleton; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * An implementation backed by a Graph database provided * as a Graph Service. */ @Singleton @Component @Deprecated public class GraphBackedMetadataRepository implements MetadataRepository { private static final Logger LOG = LoggerFactory.getLogger(GraphBackedMetadataRepository.class); private static TypeSystem typeSystem = TypeSystem.getInstance(); private static final GraphHelper graphHelper = GraphHelper.getInstance(); private DeleteHandler deleteHandler; private final AtlasGraph atlasGraph; private final GraphToTypedInstanceMapper graphToInstanceMapper; @Inject public GraphBackedMetadataRepository(DeleteHandler deleteHandler, AtlasGraph atlasGraph) { this.atlasGraph = atlasGraph; this.graphToInstanceMapper = new GraphToTypedInstanceMapper(atlasGraph); this.deleteHandler = deleteHandler; } public GraphToTypedInstanceMapper getGraphToInstanceMapper() { return graphToInstanceMapper; } @Override public String getTypeAttributeName() { return Constants.ENTITY_TYPE_PROPERTY_KEY; } @Override public String getStateAttributeName() { return Constants.STATE_PROPERTY_KEY; } /** * Returns the property key used to store super type names. * * @return property key used to store super type names. */ @Override public String getSuperTypeAttributeName() { return Constants.SUPER_TYPES_PROPERTY_KEY; } public String getIdAttributeName() { return Constants.GUID_PROPERTY_KEY; } @Override public String getVersionAttributeName() { return Constants.VERSION_PROPERTY_KEY; } @Override public String getTraitLabel(IDataType<?> dataType, String traitName) { return GraphHelper.getTraitLabel(dataType.getName(), traitName); } @Override public String getFieldNameInVertex(IDataType<?> dataType, AttributeInfo aInfo) throws AtlasException { if (aInfo.name.startsWith(Constants.INTERNAL_PROPERTY_KEY_PREFIX)) { return aInfo.name; } return GraphHelper.encodePropertyKey(GraphHelper.getQualifiedFieldName(dataType, aInfo.name)); } public String getFieldNameInVertex(IDataType<?> dataType, String attrName) throws AtlasException { return GraphHelper.getQualifiedFieldName(dataType, attrName); } @Override public String getEdgeLabel(IDataType<?> dataType, AttributeInfo aInfo) throws AtlasException { return GraphHelper.getEdgeLabel(dataType, aInfo); } @Override @GraphTransaction public CreateUpdateEntitiesResult createEntities(ITypedReferenceableInstance... entities) throws RepositoryException, EntityExistsException { if (LOG.isDebugEnabled()) { LOG.debug("adding entities={}", entities); } try { TypedInstanceToGraphMapper instanceToGraphMapper = new TypedInstanceToGraphMapper(graphToInstanceMapper, deleteHandler); instanceToGraphMapper.mapTypedInstanceToGraph(TypedInstanceToGraphMapper.Operation.CREATE, entities); List<String> createdGuids = RequestContext.get().getCreatedEntityIds(); CreateUpdateEntitiesResult result = new CreateUpdateEntitiesResult(); EntityResult entityResult = new EntityResult(createdGuids, null, null); GuidMapping mapping = instanceToGraphMapper.createGuidMapping(); result.setEntityResult(entityResult); result.setGuidMapping(mapping); return result; } catch (EntityExistsException e) { throw e; } catch (AtlasException e) { throw new RepositoryException(e); } } @Override @GraphTransaction public ITypedReferenceableInstance getEntityDefinition(String guid) throws RepositoryException, EntityNotFoundException { return getEntityDefinitions(guid).get(0); } @Override @GraphTransaction public List<ITypedReferenceableInstance> getEntityDefinitions(String... guids) throws RepositoryException, EntityNotFoundException { if (LOG.isDebugEnabled()) { LOG.debug("Retrieving entities with guids={}", Arrays.toString(guids)); } RequestContext context = RequestContext.get(); ITypedReferenceableInstance[] result = new ITypedReferenceableInstance[guids.length]; // Map of the guids of instances not in the cache to their index(es) in the result. // This is used to put the loaded instances into the location(s) corresponding // to their guid in the result. Note that a set is needed since guids can // appear more than once in the list. Map<String, Set<Integer>> uncachedGuids = new HashMap<>(); for (int i = 0; i < guids.length; i++) { String guid = guids[i]; // First, check the cache. ITypedReferenceableInstance cached = context.getInstanceV1(guid); if (cached != null) { result[i] = cached; } else { Set<Integer> indices = uncachedGuids.get(guid); if (indices == null) { indices = new HashSet<>(1); uncachedGuids.put(guid, indices); } indices.add(i); } } List<String> guidsToFetch = new ArrayList<>(uncachedGuids.keySet()); Map<String, AtlasVertex> instanceVertices = graphHelper.getVerticesForGUIDs(guidsToFetch); // search for missing entities if (instanceVertices.size() != guidsToFetch.size()) { Set<String> missingGuids = new HashSet<String>(guidsToFetch); missingGuids.removeAll(instanceVertices.keySet()); if (!missingGuids.isEmpty()) { if (LOG.isDebugEnabled()) { LOG.debug("Failed to find guids={}", missingGuids); } throw new EntityNotFoundException( "Could not find entities in the repository with guids: " + missingGuids.toString()); } } for (String guid : guidsToFetch) { try { ITypedReferenceableInstance entity = graphToInstanceMapper.mapGraphToTypedInstance(guid, instanceVertices.get(guid)); for(int index : uncachedGuids.get(guid)) { result[index] = entity; } } catch (AtlasException e) { throw new RepositoryException(e); } } return Arrays.asList(result); } @Override @GraphTransaction public ITypedReferenceableInstance getEntityDefinition(String entityType, String attribute, Object value) throws AtlasException { if (LOG.isDebugEnabled()) { LOG.debug("Retrieving entity with type={} and {}={}", entityType, attribute, value); } IDataType type = typeSystem.getDataType(IDataType.class, entityType); String propertyKey = getFieldNameInVertex(type, attribute); AtlasVertex instanceVertex = graphHelper.findVertex(propertyKey, value, Constants.ENTITY_TYPE_PROPERTY_KEY, entityType, Constants.STATE_PROPERTY_KEY, Id.EntityState.ACTIVE.name()); String guid = GraphHelper.getGuid(instanceVertex); ITypedReferenceableInstance cached = RequestContext.get().getInstanceV1(guid); if(cached != null) { return cached; } return graphToInstanceMapper.mapGraphToTypedInstance(guid, instanceVertex); } @Override @GraphTransaction public List<String> getEntityList(String entityType) throws RepositoryException { if (LOG.isDebugEnabled()) { LOG.debug("Retrieving entity list for type={}", entityType); } AtlasGraphQuery query = getGraph().query().has(Constants.ENTITY_TYPE_PROPERTY_KEY, entityType); Iterator<AtlasVertex> results = query.vertices().iterator(); if (!results.hasNext()) { return Collections.emptyList(); } ArrayList<String> entityList = new ArrayList<>(); while (results.hasNext()) { AtlasVertex vertex = results.next(); entityList.add(GraphHelper.getGuid(vertex)); } return entityList; } /** * Gets the list of trait names for a given entity represented by a guid. * * @param guid globally unique identifier for the entity * @return a list of trait names for the given entity guid * @throws RepositoryException */ @Override @GraphTransaction public List<String> getTraitNames(String guid) throws AtlasException { if (LOG.isDebugEnabled()) { LOG.debug("Retrieving trait names for entity={}", guid); } AtlasVertex instanceVertex = graphHelper.getVertexForGUID(guid); return GraphHelper.getTraitNames(instanceVertex); } /** * Adds a new trait to the list of entities represented by their respective guids * @param entityGuids list of globally unique identifier for the entities * @param traitInstance trait instance that needs to be added to entities * @throws RepositoryException */ @Override @GraphTransaction public void addTrait(List<String> entityGuids, ITypedStruct traitInstance) throws RepositoryException { Preconditions.checkNotNull(entityGuids, "entityGuids list cannot be null"); Preconditions.checkNotNull(traitInstance, "Trait instance cannot be null"); if (LOG.isDebugEnabled()) { LOG.debug("Adding a new trait={} for entities={}", traitInstance.getTypeName(), entityGuids); } GraphTransactionInterceptor.lockObjectAndReleasePostCommit(entityGuids); for (String entityGuid : entityGuids) { addTraitImpl(entityGuid, traitInstance); } } /** * Adds a new trait to an existing entity represented by a guid. * * @param guid globally unique identifier for the entity * @param traitInstance trait instance that needs to be added to entity * @throws RepositoryException */ @Override @GraphTransaction public void addTrait(String guid, ITypedStruct traitInstance) throws RepositoryException { Preconditions.checkNotNull(guid, "guid cannot be null"); Preconditions.checkNotNull(traitInstance, "Trait instance cannot be null"); GraphTransactionInterceptor.lockObjectAndReleasePostCommit(guid); addTraitImpl(guid, traitInstance); } private void addTraitImpl(String guid, ITypedStruct traitInstance) throws RepositoryException { final String traitName = traitInstance.getTypeName(); if (LOG.isDebugEnabled()) { LOG.debug("Adding a new trait={} for entity={}", traitName, guid); } try { AtlasVertex instanceVertex = graphHelper.getVertexForGUID(guid); // add the trait instance as a new vertex final String typeName = GraphHelper.getTypeName(instanceVertex); TypedInstanceToGraphMapper instanceToGraphMapper = new TypedInstanceToGraphMapper(graphToInstanceMapper, deleteHandler); instanceToGraphMapper.mapTraitInstanceToVertex(traitInstance, typeSystem.getDataType(ClassType.class, typeName), instanceVertex); // update the traits in entity once adding trait instance is successful GraphHelper.addProperty(instanceVertex, Constants.TRAIT_NAMES_PROPERTY_KEY, traitName); GraphHelper.setProperty(instanceVertex, Constants.MODIFICATION_TIMESTAMP_PROPERTY_KEY, RequestContext.get().getRequestTime()); GraphHelper.setProperty(instanceVertex, Constants.MODIFIED_BY_KEY, RequestContext.get().getUser()); } catch (RepositoryException e) { throw e; } catch (Exception e) { throw new RepositoryException(e); } } /** * Deletes a given trait from an existing entity represented by a guid. * * @param guid globally unique identifier for the entity * @param traitNameToBeDeleted name of the trait * @throws RepositoryException */ @Override @GraphTransaction public void deleteTrait(String guid, String traitNameToBeDeleted) throws TraitNotFoundException, EntityNotFoundException, RepositoryException { LOG.debug("Deleting trait={} from entity={}", traitNameToBeDeleted, guid); GraphTransactionInterceptor.lockObjectAndReleasePostCommit(guid); AtlasVertex instanceVertex = graphHelper.getVertexForGUID(guid); List<String> traitNames = GraphHelper.getTraitNames(instanceVertex); if (!traitNames.contains(traitNameToBeDeleted)) { throw new TraitNotFoundException( "Could not find trait=" + traitNameToBeDeleted + " in the repository for entity: " + guid); } try { final String entityTypeName = GraphHelper.getTypeName(instanceVertex); String relationshipLabel = GraphHelper.getTraitLabel(entityTypeName, traitNameToBeDeleted); AtlasEdge edge = graphHelper.getEdgeForLabel(instanceVertex, relationshipLabel); if(edge != null) { deleteHandler.deleteEdgeReference(edge, DataTypes.TypeCategory.TRAIT, false, true); } // update the traits in entity once trait removal is successful traitNames.remove(traitNameToBeDeleted); updateTraits(instanceVertex, traitNames); } catch (Exception e) { throw new RepositoryException(e); } } private void updateTraits(AtlasVertex instanceVertex, List<String> traitNames) { // remove the key instanceVertex.removeProperty(Constants.TRAIT_NAMES_PROPERTY_KEY); // add it back again for (String traitName : traitNames) { GraphHelper.addProperty(instanceVertex, Constants.TRAIT_NAMES_PROPERTY_KEY, traitName); } GraphHelper.setProperty(instanceVertex, Constants.MODIFICATION_TIMESTAMP_PROPERTY_KEY, RequestContext.get().getRequestTime()); GraphHelper.setProperty(instanceVertex, Constants.MODIFIED_BY_KEY, RequestContext.get().getUser()); } @Override @GraphTransaction public CreateUpdateEntitiesResult updateEntities(ITypedReferenceableInstance... entitiesUpdated) throws RepositoryException { if (LOG.isDebugEnabled()) { LOG.debug("updating entity {}", entitiesUpdated); } try { TypedInstanceToGraphMapper instanceToGraphMapper = new TypedInstanceToGraphMapper(graphToInstanceMapper, deleteHandler); instanceToGraphMapper.mapTypedInstanceToGraph(TypedInstanceToGraphMapper.Operation.UPDATE_FULL, entitiesUpdated); CreateUpdateEntitiesResult result = new CreateUpdateEntitiesResult(); RequestContext requestContext = RequestContext.get(); result.setEntityResult(createEntityResultFromContext(requestContext)); GuidMapping mapping = instanceToGraphMapper.createGuidMapping(); result.setGuidMapping(mapping); return result; } catch (AtlasException e) { throw new RepositoryException(e); } } @Override @GraphTransaction public CreateUpdateEntitiesResult updatePartial(ITypedReferenceableInstance entity) throws RepositoryException { if (LOG.isDebugEnabled()) { LOG.debug("updating entity {}", entity); } try { TypedInstanceToGraphMapper instanceToGraphMapper = new TypedInstanceToGraphMapper(graphToInstanceMapper, deleteHandler); instanceToGraphMapper.mapTypedInstanceToGraph(TypedInstanceToGraphMapper.Operation.UPDATE_PARTIAL, entity); RequestContext requestContext = RequestContext.get(); CreateUpdateEntitiesResult result = new CreateUpdateEntitiesResult(); GuidMapping mapping = instanceToGraphMapper.createGuidMapping(); result.setEntityResult(createEntityResultFromContext(requestContext)); result.setGuidMapping(mapping); return result; } catch (AtlasException e) { throw new RepositoryException(e); } } @Override @GraphTransaction public EntityResult deleteEntities(List<String> guids) throws RepositoryException { if (guids == null || guids.size() == 0) { throw new IllegalArgumentException("guids must be non-null and non-empty"); } // Retrieve vertices for requested guids. Map<String, AtlasVertex> vertices = graphHelper.getVerticesForGUIDs(guids); Collection<AtlasVertex> deletionCandidates = vertices.values(); if(LOG.isDebugEnabled()) { for(String guid : guids) { if(! vertices.containsKey(guid)) { // Entity does not exist - treat as non-error, since the caller // wanted to delete the entity and it's already gone. LOG.debug("Deletion request ignored for non-existent entity with guid " + guid); } } } if (deletionCandidates.isEmpty()) { LOG.info("No deletion candidate entities were found for guids %s", guids); return new EntityResult(Collections.<String>emptyList(), Collections.<String>emptyList(), Collections.<String>emptyList()); } try { deleteHandler.deleteEntities(deletionCandidates); } catch (AtlasException e) { throw new RepositoryException(e); } RequestContext requestContext = RequestContext.get(); return createEntityResultFromContext(requestContext); } private EntityResult createEntityResultFromContext(RequestContext requestContext) { return new EntityResult( requestContext.getCreatedEntityIds(), requestContext.getUpdatedEntityIds(), requestContext.getDeletedEntityIds()); } public AtlasGraph getGraph() throws RepositoryException { return atlasGraph; } } <|start_filename|>common/src/main/java/org/apache/atlas/ha/HAConfiguration.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.ha; import org.apache.atlas.security.SecurityProperties; import org.apache.commons.configuration.Configuration; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * A wrapper for getting configuration entries related to HighAvailability. */ public final class HAConfiguration { public static final String ATLAS_SERVER_ZK_ROOT_DEFAULT = "/apache_atlas"; private HAConfiguration() { } public static final String ATLAS_SERVER_HA_PREFIX = "atlas.server.ha."; public static final String ZOOKEEPER_PREFIX = "zookeeper."; public static final String ATLAS_SERVER_HA_ZK_ROOT_KEY = ATLAS_SERVER_HA_PREFIX + ZOOKEEPER_PREFIX + "zkroot"; public static final String ATLAS_SERVER_HA_ENABLED_KEY = ATLAS_SERVER_HA_PREFIX + "enabled"; public static final String ATLAS_SERVER_ADDRESS_PREFIX = "atlas.server.address."; public static final String ATLAS_SERVER_IDS = "atlas.server.ids"; public static final String HA_ZOOKEEPER_CONNECT = ATLAS_SERVER_HA_PREFIX + ZOOKEEPER_PREFIX + "connect"; public static final int DEFAULT_ZOOKEEPER_CONNECT_SLEEPTIME_MILLIS = 1000; public static final String HA_ZOOKEEPER_RETRY_SLEEPTIME_MILLIS = ATLAS_SERVER_HA_PREFIX + ZOOKEEPER_PREFIX + "retry.sleeptime.ms"; public static final String HA_ZOOKEEPER_NUM_RETRIES = ATLAS_SERVER_HA_PREFIX + ZOOKEEPER_PREFIX + "num.retries"; public static final int DEFAULT_ZOOKEEPER_CONNECT_NUM_RETRIES = 3; public static final String HA_ZOOKEEPER_SESSION_TIMEOUT_MS = ATLAS_SERVER_HA_PREFIX + ZOOKEEPER_PREFIX + "session.timeout.ms"; public static final int DEFAULT_ZOOKEEPER_SESSION_TIMEOUT_MILLIS = 20000; public static final String HA_ZOOKEEPER_ACL = ATLAS_SERVER_HA_PREFIX + ZOOKEEPER_PREFIX + "acl"; public static final String HA_ZOOKEEPER_AUTH = ATLAS_SERVER_HA_PREFIX + ZOOKEEPER_PREFIX + "auth"; /** * Return whether HA is enabled or not. * @param configuration underlying configuration instance * @return */ public static boolean isHAEnabled(Configuration configuration) { boolean ret = false; if (configuration.containsKey(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY)) { ret = configuration.getBoolean(ATLAS_SERVER_HA_ENABLED_KEY); } else { String[] ids = configuration.getStringArray(HAConfiguration.ATLAS_SERVER_IDS); ret = ids != null && ids.length > 1; } return ret; } /** * Get the web server address that a server instance with the passed ID is bound to. * * This method uses the property {@link SecurityProperties#TLS_ENABLED} to determine whether * the URL is http or https. * * @param configuration underlying configuration * @param serverId serverId whose host:port property is picked to build the web server address. * @return */ public static String getBoundAddressForId(Configuration configuration, String serverId) { String hostPort = configuration.getString(ATLAS_SERVER_ADDRESS_PREFIX +serverId); boolean isSecure = configuration.getBoolean(SecurityProperties.TLS_ENABLED); String protocol = (isSecure) ? "https://" : "http://"; return protocol + hostPort; } public static List<String> getServerInstances(Configuration configuration) { String[] serverIds = configuration.getStringArray(ATLAS_SERVER_IDS); List<String> serverInstances = new ArrayList<>(serverIds.length); for (String serverId : serverIds) { serverInstances.add(getBoundAddressForId(configuration, serverId)); } return serverInstances; } /** * A collection of Zookeeper specific configuration that is used by High Availability code. */ public static class ZookeeperProperties { private String connectString; private String zkRoot; private int retriesSleepTimeMillis; private int numRetries; private int sessionTimeout; private String acl; private String auth; public ZookeeperProperties(String connectString, String zkRoot, int retriesSleepTimeMillis, int numRetries, int sessionTimeout, String acl, String auth) { this.connectString = connectString; this.zkRoot = zkRoot; this.retriesSleepTimeMillis = retriesSleepTimeMillis; this.numRetries = numRetries; this.sessionTimeout = sessionTimeout; this.acl = acl; this.auth = auth; } public String getConnectString() { return connectString; } public int getRetriesSleepTimeMillis() { return retriesSleepTimeMillis; } public int getNumRetries() { return numRetries; } public int getSessionTimeout() { return sessionTimeout; } public String getAcl() { return acl; } public String getAuth() { return auth; } public String getZkRoot() { return zkRoot; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ZookeeperProperties that = (ZookeeperProperties) o; return retriesSleepTimeMillis == that.retriesSleepTimeMillis && numRetries == that.numRetries && sessionTimeout == that.sessionTimeout && Objects.equals(connectString, that.connectString) && Objects.equals(zkRoot, that.zkRoot) && Objects.equals(acl, that.acl) && Objects.equals(auth, that.auth); } @Override public int hashCode() { return Objects.hash(connectString, zkRoot, retriesSleepTimeMillis, numRetries, sessionTimeout, acl, auth); } public boolean hasAcl() { return getAcl()!=null; } public boolean hasAuth() { return getAuth()!=null; } } public static ZookeeperProperties getZookeeperProperties(Configuration configuration) { String zookeeperConnectString = configuration.getString("atlas.kafka." + ZOOKEEPER_PREFIX + "connect"); if (configuration.containsKey(HA_ZOOKEEPER_CONNECT)) { zookeeperConnectString = configuration.getString(HA_ZOOKEEPER_CONNECT); } String zkRoot = configuration.getString(ATLAS_SERVER_HA_ZK_ROOT_KEY, ATLAS_SERVER_ZK_ROOT_DEFAULT); int retriesSleepTimeMillis = configuration.getInt(HA_ZOOKEEPER_RETRY_SLEEPTIME_MILLIS, DEFAULT_ZOOKEEPER_CONNECT_SLEEPTIME_MILLIS); int numRetries = configuration.getInt(HA_ZOOKEEPER_NUM_RETRIES, DEFAULT_ZOOKEEPER_CONNECT_NUM_RETRIES); int sessionTimeout = configuration.getInt(HA_ZOOKEEPER_SESSION_TIMEOUT_MS, DEFAULT_ZOOKEEPER_SESSION_TIMEOUT_MILLIS); String acl = configuration.getString(HA_ZOOKEEPER_ACL); String auth = configuration.getString(HA_ZOOKEEPER_AUTH); return new ZookeeperProperties(zookeeperConnectString, zkRoot, retriesSleepTimeMillis, numRetries, sessionTimeout, acl, auth); } } <|start_filename|>repository/src/test/java/org/apache/atlas/repository/graph/ReverseReferenceUpdateSoftDeleteTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graph; import org.apache.atlas.TestModules; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.persistence.Id; import org.testng.Assert; import org.testng.annotations.Guice; import java.util.Iterator; import java.util.List; /** * Run tests in {@link ReverseReferenceUpdateTestBase} with soft delete enabled. * */ @Guice(modules = TestModules.SoftDeleteModule.class) public class ReverseReferenceUpdateSoftDeleteTest extends ReverseReferenceUpdateTestBase { @Override void assertTestOneToOneReference(Object actual, ITypedReferenceableInstance expectedValue, ITypedReferenceableInstance referencingInstance) throws Exception { // Verify reference was not disconnected if soft deletes are enabled. Assert.assertNotNull(actual); Assert.assertTrue(actual instanceof ITypedReferenceableInstance); ITypedReferenceableInstance referenceValue = (ITypedReferenceableInstance) actual; Assert.assertEquals(referenceValue.getId()._getId(), expectedValue.getId()._getId()); //Verify reference edge was marked as DELETED. AtlasVertex vertexForGUID = GraphHelper.getInstance().getVertexForGUID(referencingInstance.getId()._getId()); String edgeLabel = GraphHelper.getEdgeLabel(typeB, typeB.fieldMapping.fields.get("a")); AtlasEdge edgeForLabel = GraphHelper.getInstance().getEdgeForLabel(vertexForGUID, edgeLabel); Assert.assertNotNull(edgeForLabel); String edgeState = edgeForLabel.getProperty(Constants.STATE_PROPERTY_KEY, String.class); Assert.assertEquals(edgeState, Id.EntityState.DELETED.name()); } @Override void assertTestOneToManyReference(Object object, ITypedReferenceableInstance referencingInstance) throws Exception { // Verify reference was not disconnected if soft deletes are enabled. Assert.assertTrue(object instanceof List); List<ITypedReferenceableInstance> refValues = (List<ITypedReferenceableInstance>) object; Assert.assertEquals(refValues.size(), 2); // Verify that one of the reference edges is marked DELETED. AtlasVertex vertexForGUID = GraphHelper.getInstance().getVertexForGUID(referencingInstance.getId()._getId()); String edgeLabel = GraphHelper.getEdgeLabel(typeB, typeB.fieldMapping.fields.get("manyA")); Iterator<AtlasEdge> outGoingEdgesByLabel = GraphHelper.getInstance().getOutGoingEdgesByLabel(vertexForGUID, edgeLabel); boolean found = false; while (outGoingEdgesByLabel.hasNext()) { AtlasEdge edge = outGoingEdgesByLabel.next(); String edgeState = edge.getProperty(Constants.STATE_PROPERTY_KEY, String.class); if (edgeState.equals(Id.EntityState.DELETED.name())) { found = true; break; } } Assert.assertTrue(found, "One edge for label " + edgeLabel + " should be marked " + Id.EntityState.DELETED.name()); } } <|start_filename|>server-api/src/main/java/org/apache/atlas/metrics/Metrics.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.metrics; import java.util.LinkedHashMap; import java.util.Map; public class Metrics { public static class Counters { private short invocations = 0; private long totalTimeMSecs = 0; @Override public String toString() { return "[count=" + invocations + ", totalTimeMSec=" + totalTimeMSecs + "]"; } public short getInvocations() { return invocations; } public long getTotalTimeMSecs() { return totalTimeMSecs; } } Map<String, Counters> countersMap = new LinkedHashMap<>(); public void record(String name, long timeMsecs) { Counters counter = countersMap.get(name); if (counter == null) { counter = new Counters(); countersMap.put(name, counter); } counter.invocations++; counter.totalTimeMSecs += timeMsecs; } @Override public String toString() { return countersMap.toString(); } public boolean isEmpty() { return countersMap.isEmpty(); } public Counters getCounters(String name) { return countersMap.get(name); } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/converters/AtlasInstanceConverter.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.converters; import org.apache.atlas.model.legacy.EntityResult; import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.AtlasException; import org.apache.atlas.CreateUpdateEntitiesResult; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.TypeCategory; import org.apache.atlas.model.instance.AtlasClassification; import org.apache.atlas.model.instance.AtlasEntity; import org.apache.atlas.model.instance.AtlasEntity.AtlasEntitiesWithExtInfo; import org.apache.atlas.model.instance.AtlasEntityHeader; import org.apache.atlas.model.instance.EntityMutationResponse; import org.apache.atlas.model.instance.EntityMutations; import org.apache.atlas.model.instance.EntityMutations.EntityOperation; import org.apache.atlas.model.instance.GuidMapping; import org.apache.atlas.services.MetadataService; import org.apache.atlas.type.AtlasClassificationType; import org.apache.atlas.type.AtlasEntityType; import org.apache.atlas.type.AtlasType; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.typesystem.IReferenceableInstance; import org.apache.atlas.typesystem.IStruct; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.ITypedStruct; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.Struct; import org.apache.atlas.typesystem.exception.EntityExistsException; import org.apache.atlas.typesystem.exception.EntityNotFoundException; import org.apache.atlas.typesystem.exception.TraitNotFoundException; import org.apache.atlas.typesystem.exception.TypeNotFoundException; import org.apache.atlas.repository.converters.AtlasFormatConverter.ConverterContext; import org.apache.atlas.typesystem.types.ValueConversionException; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.inject.Inject; import javax.inject.Singleton; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; @Singleton @Component public class AtlasInstanceConverter { private static final Logger LOG = LoggerFactory.getLogger(AtlasInstanceConverter.class); private AtlasTypeRegistry typeRegistry; private AtlasFormatConverters instanceFormatters; private MetadataService metadataService; @Inject public AtlasInstanceConverter(AtlasTypeRegistry typeRegistry, AtlasFormatConverters instanceFormatters, MetadataService metadataService) { this.typeRegistry = typeRegistry; this.instanceFormatters = instanceFormatters; this.metadataService = metadataService; } public ITypedReferenceableInstance[] getITypedReferenceables(Collection<AtlasEntity> entities) throws AtlasBaseException { ITypedReferenceableInstance[] entitiesInOldFormat = new ITypedReferenceableInstance[entities.size()]; AtlasFormatConverter.ConverterContext ctx = new AtlasFormatConverter.ConverterContext(); for(Iterator<AtlasEntity> i = entities.iterator(); i.hasNext(); ) { ctx.addEntity(i.next()); } Iterator<AtlasEntity> entityIterator = entities.iterator(); for (int i = 0; i < entities.size(); i++) { ITypedReferenceableInstance typedInstance = getITypedReferenceable(entityIterator.next()); entitiesInOldFormat[i] = typedInstance; } return entitiesInOldFormat; } public ITypedReferenceableInstance getITypedReferenceable(AtlasEntity entity) throws AtlasBaseException { try { return metadataService.getEntityDefinition(entity.getGuid()); } catch (AtlasException e) { LOG.error("Exception while getting a typed reference for the entity ", e); throw toAtlasBaseException(e); } } public ITypedReferenceableInstance getITypedReferenceable(String guid) throws AtlasBaseException { try { return metadataService.getEntityDefinition(guid); } catch (AtlasException e) { LOG.error("Exception while getting a typed reference for the entity ", e); throw toAtlasBaseException(e); } } public Referenceable getReferenceable(AtlasEntity entity, final ConverterContext ctx) throws AtlasBaseException { AtlasFormatConverter converter = instanceFormatters.getConverter(TypeCategory.ENTITY); AtlasType entityType = typeRegistry.getType(entity.getTypeName()); Referenceable ref = (Referenceable) converter.fromV2ToV1(entity, entityType, ctx); return ref; } public ITypedStruct getTrait(AtlasClassification classification) throws AtlasBaseException { AtlasFormatConverter converter = instanceFormatters.getConverter(TypeCategory.CLASSIFICATION); AtlasType classificationType = typeRegistry.getType(classification.getTypeName()); Struct trait = (Struct)converter.fromV2ToV1(classification, classificationType, new ConverterContext()); try { return metadataService.createTraitInstance(trait); } catch (AtlasException e) { LOG.error("Exception while getting a typed reference for the entity ", e); throw toAtlasBaseException(e); } } public AtlasClassification getClassification(IStruct classification) throws AtlasBaseException { AtlasFormatConverter converter = instanceFormatters.getConverter(TypeCategory.CLASSIFICATION); AtlasClassificationType classificationType = typeRegistry.getClassificationTypeByName(classification.getTypeName()); if (classificationType == null) { throw new AtlasBaseException(AtlasErrorCode.TYPE_NAME_INVALID, TypeCategory.CLASSIFICATION.name(), classification.getTypeName()); } AtlasClassification ret = (AtlasClassification)converter.fromV1ToV2(classification, classificationType, new AtlasFormatConverter.ConverterContext()); return ret; } public AtlasEntitiesWithExtInfo toAtlasEntity(IReferenceableInstance referenceable) throws AtlasBaseException { AtlasEntityFormatConverter converter = (AtlasEntityFormatConverter) instanceFormatters.getConverter(TypeCategory.ENTITY); AtlasEntityType entityType = typeRegistry.getEntityTypeByName(referenceable.getTypeName()); if (entityType == null) { throw new AtlasBaseException(AtlasErrorCode.TYPE_NAME_INVALID, TypeCategory.ENTITY.name(), referenceable.getTypeName()); } // validate try { metadataService.validateAndConvertToTypedInstance(referenceable, entityType.getTypeName()); } catch (AtlasException excp) { throw toAtlasBaseException(excp); } ConverterContext ctx = new ConverterContext(); AtlasEntity entity = converter.fromV1ToV2(referenceable, entityType, ctx); ctx.addEntity(entity); return ctx.getEntities(); } public static EntityMutationResponse toEntityMutationResponse(EntityResult entityResult) { CreateUpdateEntitiesResult result = new CreateUpdateEntitiesResult(); result.setEntityResult(entityResult); return toEntityMutationResponse(result); } public static EntityMutationResponse toEntityMutationResponse(CreateUpdateEntitiesResult result) { EntityMutationResponse response = new EntityMutationResponse(); for (String guid : result.getCreatedEntities()) { AtlasEntityHeader header = new AtlasEntityHeader(); header.setGuid(guid); response.addEntity(EntityMutations.EntityOperation.CREATE, header); } for (String guid : result.getUpdatedEntities()) { AtlasEntityHeader header = new AtlasEntityHeader(); header.setGuid(guid); response.addEntity(EntityMutations.EntityOperation.UPDATE, header); } for (String guid : result.getDeletedEntities()) { AtlasEntityHeader header = new AtlasEntityHeader(); header.setGuid(guid); response.addEntity(EntityMutations.EntityOperation.DELETE, header); } GuidMapping guidMapping = result.getGuidMapping(); if(guidMapping != null) { response.setGuidAssignments(guidMapping.getGuidAssignments()); } return response; } public static AtlasBaseException toAtlasBaseException(AtlasException e) { if (e instanceof EntityExistsException) { return new AtlasBaseException(AtlasErrorCode.INSTANCE_ALREADY_EXISTS, e.getMessage()); } if ( e instanceof EntityNotFoundException || e instanceof TraitNotFoundException) { return new AtlasBaseException(AtlasErrorCode.INSTANCE_NOT_FOUND, e.getMessage()); } if ( e instanceof TypeNotFoundException) { return new AtlasBaseException(AtlasErrorCode.TYPE_NAME_NOT_FOUND, e.getMessage()); } if (e instanceof ValueConversionException) { return new AtlasBaseException(AtlasErrorCode.INVALID_VALUE, e, e.getMessage()); } return new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, e.getMessage()); } public AtlasEntity.AtlasEntitiesWithExtInfo toAtlasEntities(List<Referenceable> referenceables) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> toAtlasEntities"); } AtlasFormatConverter.ConverterContext context = new AtlasFormatConverter.ConverterContext(); for (Referenceable referenceable : referenceables) { AtlasEntity entity = fromV1toV2Entity(referenceable, context); context.addEntity(entity); } if (LOG.isDebugEnabled()) { LOG.debug("<== toAtlasEntities"); } return context.getEntities(); } public AtlasEntitiesWithExtInfo toAtlasEntities(String entitiesJson) throws AtlasBaseException, AtlasException { ITypedReferenceableInstance[] referenceables = metadataService.deserializeClassInstances(entitiesJson); AtlasEntityFormatConverter converter = (AtlasEntityFormatConverter) instanceFormatters.getConverter(TypeCategory.ENTITY); ConverterContext context = new ConverterContext(); AtlasEntitiesWithExtInfo ret = null; if (referenceables != null) { for (IReferenceableInstance referenceable : referenceables) { AtlasEntityType entityType = typeRegistry.getEntityTypeByName(referenceable.getTypeName()); if (entityType == null) { throw new AtlasBaseException(AtlasErrorCode.TYPE_NAME_INVALID, TypeCategory.ENTITY.name(), referenceable.getTypeName()); } AtlasEntity entity = converter.fromV1ToV2(referenceable, entityType, context); context.addEntity(entity); } ret = context.getEntities(); } return ret; } private AtlasEntity fromV1toV2Entity(Referenceable referenceable, AtlasFormatConverter.ConverterContext context) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> fromV1toV2Entity"); } AtlasEntityFormatConverter converter = (AtlasEntityFormatConverter) instanceFormatters.getConverter(TypeCategory.ENTITY); AtlasEntity entity = converter.fromV1ToV2(referenceable, typeRegistry.getType(referenceable.getTypeName()), context); if (LOG.isDebugEnabled()) { LOG.debug("<== fromV1toV2Entity"); } return entity; } public CreateUpdateEntitiesResult toCreateUpdateEntitiesResult(EntityMutationResponse reponse) { CreateUpdateEntitiesResult ret = null; if (reponse != null) { Map<EntityOperation, List<AtlasEntityHeader>> mutatedEntities = reponse.getMutatedEntities(); Map<String, String> guidAssignments = reponse.getGuidAssignments(); ret = new CreateUpdateEntitiesResult(); if (MapUtils.isNotEmpty(guidAssignments)) { ret.setGuidMapping(new GuidMapping(guidAssignments)); } if (MapUtils.isNotEmpty(mutatedEntities)) { EntityResult entityResult = new EntityResult(); for (Map.Entry<EntityOperation, List<AtlasEntityHeader>> e : mutatedEntities.entrySet()) { switch (e.getKey()) { case CREATE: List<AtlasEntityHeader> createdEntities = mutatedEntities.get(EntityOperation.CREATE); if (CollectionUtils.isNotEmpty(createdEntities)) { Collections.reverse(createdEntities); entityResult.set(EntityResult.OP_CREATED, getGuids(createdEntities)); } break; case UPDATE: List<AtlasEntityHeader> updatedEntities = mutatedEntities.get(EntityOperation.UPDATE); if (CollectionUtils.isNotEmpty(updatedEntities)) { Collections.reverse(updatedEntities); entityResult.set(EntityResult.OP_UPDATED, getGuids(updatedEntities)); } break; case PARTIAL_UPDATE: List<AtlasEntityHeader> partialUpdatedEntities = mutatedEntities.get(EntityOperation.PARTIAL_UPDATE); if (CollectionUtils.isNotEmpty(partialUpdatedEntities)) { Collections.reverse(partialUpdatedEntities); entityResult.set(EntityResult.OP_UPDATED, getGuids(partialUpdatedEntities)); } break; case DELETE: List<AtlasEntityHeader> deletedEntities = mutatedEntities.get(EntityOperation.DELETE); if (CollectionUtils.isNotEmpty(deletedEntities)) { Collections.reverse(deletedEntities); entityResult.set(EntityResult.OP_DELETED, getGuids(deletedEntities)); } break; } } ret.setEntityResult(entityResult); } } return ret; } public List<String> getGuids(List<AtlasEntityHeader> entities) { List<String> ret = null; if (CollectionUtils.isNotEmpty(entities)) { ret = new ArrayList<>(); for (AtlasEntityHeader entity : entities) { ret.add(entity.getGuid()); } } return ret; } } <|start_filename|>repository/src/main/java/org/apache/atlas/discovery/graph/GraphBackedDiscoveryService.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.discovery.graph; import org.apache.atlas.AtlasClient; import org.apache.atlas.annotation.GraphTransaction; import org.apache.atlas.discovery.DiscoveryException; import org.apache.atlas.discovery.DiscoveryService; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.query.Expressions; import org.apache.atlas.query.GremlinEvaluator; import org.apache.atlas.query.GremlinQuery; import org.apache.atlas.query.GremlinQueryResult; import org.apache.atlas.query.GremlinTranslator; import org.apache.atlas.query.QueryParams; import org.apache.atlas.query.QueryParser; import org.apache.atlas.query.QueryProcessor; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.MetadataRepository; import org.apache.atlas.repository.graph.GraphHelper; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.AtlasIndexQuery; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.util.CompiledQueryCacheKey; import org.apache.atlas.util.NoopGremlinQuery; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import scala.util.Either; import scala.util.parsing.combinator.Parsers; import javax.inject.Inject; import javax.inject.Singleton; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Graph backed implementation of Search. */ @Singleton @Component public class GraphBackedDiscoveryService implements DiscoveryService { private static final Logger LOG = LoggerFactory.getLogger(GraphBackedDiscoveryService.class); private final AtlasGraph graph; private final DefaultGraphPersistenceStrategy graphPersistenceStrategy; public final static String SCORE = "score"; /** * Where the vertex' internal gremlin id is stored in the Map produced by extractResult() */ public final static String GREMLIN_ID_KEY = "id"; /** * Where the id of an edge's incoming vertex is stored in the Map produced by extractResult() */ public final static String GREMLIN_INVERTEX_KEY = "inVertex"; /** * Where the id of an edge's outgoing vertex is stored in the Map produced by extractResult() */ public final static String GREMLIN_OUTVERTEX_KEY = "outVertex"; /** * Where an edge's label is stored in the Map produced by extractResult() */ public final static String GREMLIN_LABEL_KEY = "label"; @Inject GraphBackedDiscoveryService(MetadataRepository metadataRepository, AtlasGraph atlasGraph) throws DiscoveryException { this.graph = atlasGraph; this.graphPersistenceStrategy = new DefaultGraphPersistenceStrategy(metadataRepository); } //For titan 0.5.4, refer to http://s3.thinkaurelius.com/docs/titan/0.5.4/index-backends.html for indexed query //http://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query // .html#query-string-syntax for query syntax @Override @GraphTransaction public String searchByFullText(String query, QueryParams queryParams) throws DiscoveryException { String graphQuery = String.format("v.\"%s\":(%s)", Constants.ENTITY_TEXT_PROPERTY_KEY, query); LOG.debug("Full text query: {}", graphQuery); Iterator<AtlasIndexQuery.Result<?, ?>> results =graph.indexQuery(Constants.FULLTEXT_INDEX, graphQuery).vertices(); JSONArray response = new JSONArray(); int index = 0; while (results.hasNext() && index < queryParams.offset()) { results.next(); index++; } while (results.hasNext() && response.length() < queryParams.limit()) { AtlasIndexQuery.Result<?,?> result = results.next(); AtlasVertex<?,?> vertex = result.getVertex(); JSONObject row = new JSONObject(); String guid = GraphHelper.getGuid(vertex); if (guid != null) { //Filter non-class entities try { row.put("guid", guid); row.put(AtlasClient.TYPENAME, GraphHelper.getTypeName(vertex)); row.put(SCORE, result.getScore()); } catch (JSONException e) { LOG.error("Unable to create response", e); throw new DiscoveryException("Unable to create response"); } response.put(row); } } return response.toString(); } @Override @GraphTransaction public String searchByDSL(String dslQuery, QueryParams queryParams) throws DiscoveryException { GremlinQueryResult queryResult = evaluate(dslQuery, queryParams); return queryResult.toJson(); } public GremlinQueryResult evaluate(String dslQuery, QueryParams queryParams) throws DiscoveryException { if(LOG.isDebugEnabled()) { LOG.debug("Executing dsl query={}", dslQuery); } try { GremlinQuery gremlinQuery = parseAndTranslateDsl(dslQuery, queryParams); if(gremlinQuery instanceof NoopGremlinQuery) { return new GremlinQueryResult(dslQuery, ((NoopGremlinQuery)gremlinQuery).getDataType(), Collections.emptyList()); } return new GremlinEvaluator(gremlinQuery, graphPersistenceStrategy, graph).evaluate(); } catch (Exception e) { // unable to catch ExpressionException throw new DiscoveryException("Invalid expression : " + dslQuery, e); } } private GremlinQuery parseAndTranslateDsl(String dslQuery, QueryParams queryParams) throws DiscoveryException { CompiledQueryCacheKey entry = new CompiledQueryCacheKey(dslQuery, queryParams); GremlinQuery gremlinQuery = QueryProcessor.compiledQueryCache().get(entry); if(gremlinQuery == null) { Expressions.Expression validatedExpression = parseQuery(dslQuery, queryParams); //If the final limit is 0, don't launch the query, return with 0 rows if (validatedExpression instanceof Expressions.LimitExpression && ((Integer)((Expressions.LimitExpression) validatedExpression).limit().rawValue()) == 0) { gremlinQuery = new NoopGremlinQuery(validatedExpression.dataType()); } else { gremlinQuery = new GremlinTranslator(validatedExpression, graphPersistenceStrategy).translate(); if (LOG.isDebugEnabled()) { LOG.debug("Query = {}", validatedExpression); LOG.debug("Expression Tree = {}", validatedExpression.treeString()); LOG.debug("Gremlin Query = {}", gremlinQuery.queryStr()); } } QueryProcessor.compiledQueryCache().put(entry, gremlinQuery); } return gremlinQuery; } private Expressions.Expression parseQuery(String dslQuery, QueryParams queryParams) throws DiscoveryException { Either<Parsers.NoSuccess, Expressions.Expression> either = QueryParser.apply(dslQuery, queryParams); if (either.isRight()) { Expressions.Expression expression = either.right().get(); Expressions.Expression validatedExpression = QueryProcessor.validate(expression); return validatedExpression; } else { throw new DiscoveryException("Invalid expression : " + dslQuery + ". " + either.left()); } } /** * Assumes the User is familiar with the persistence structure of the Repository. * The given query is run uninterpreted against the underlying Graph Store. * The results are returned as a List of Rows. each row is a Map of Key,Value pairs. * * @param gremlinQuery query in gremlin dsl format * @return List of Maps * @throws org.apache.atlas.discovery.DiscoveryException */ @Override @GraphTransaction public List<Map<String, String>> searchByGremlin(String gremlinQuery) throws DiscoveryException { LOG.debug("Executing gremlin query={}", gremlinQuery); try { Object o = graph.executeGremlinScript(gremlinQuery, false); return extractResult(o); } catch (AtlasBaseException e) { throw new DiscoveryException(e); } } private List<Map<String, String>> extractResult(final Object o) throws DiscoveryException { List<Map<String, String>> result = new ArrayList<>(); if (o instanceof List) { List l = (List) o; for (Object value : l) { Map<String, String> oRow = new HashMap<>(); if (value instanceof Map) { @SuppressWarnings("unchecked") Map<Object, Object> iRow = (Map) value; for (Map.Entry e : iRow.entrySet()) { Object k = e.getKey(); Object v = e.getValue(); oRow.put(k.toString(), v.toString()); } } else if (value instanceof AtlasVertex) { AtlasVertex<?,?> vertex = (AtlasVertex<?,?>)value; for (String key : vertex.getPropertyKeys()) { Object propertyValue = GraphHelper.getProperty(vertex, key); if (propertyValue != null) { oRow.put(key, propertyValue.toString()); } } oRow.put(GREMLIN_ID_KEY, vertex.getId().toString()); } else if (value instanceof String) { oRow.put("", value.toString()); } else if(value instanceof AtlasEdge) { AtlasEdge edge = (AtlasEdge) value; oRow.put(GREMLIN_ID_KEY, edge.getId().toString()); oRow.put(GREMLIN_LABEL_KEY, edge.getLabel()); oRow.put(GREMLIN_INVERTEX_KEY, edge.getInVertex().getId().toString()); oRow.put(GREMLIN_OUTVERTEX_KEY, edge.getOutVertex().getId().toString()); for (String propertyKey : edge.getPropertyKeys()) { oRow.put(propertyKey, GraphHelper.getProperty(edge, propertyKey).toString()); } } else { throw new DiscoveryException(String.format("Cannot process result %s", String.valueOf(value))); } result.add(oRow); } } else { result.add(new HashMap<String, String>() {{ put("result", o.toString()); }}); } return result; } } <|start_filename|>repository/src/main/java/org/apache/atlas/gremlin/optimizer/UpdatedExpressions.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.gremlin.optimizer; import java.util.ArrayList; import java.util.List; import org.apache.atlas.groovy.GroovyExpression; /** * Represents a list of updated expressions. */ public class UpdatedExpressions { private List<List<GroovyExpression>> updatedChildren = new ArrayList<>(); private boolean changed = false; public UpdatedExpressions(boolean changed, List<List<GroovyExpression>> updatedChildren) { this.changed = changed; this.updatedChildren = updatedChildren; } public List<List<GroovyExpression>> getUpdatedChildren() { return updatedChildren; } public boolean hasChanges() { return changed; } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/store/graph/v1/AtlasEntityChangeNotifier.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.store.graph.v1; import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.AtlasException; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.listener.EntityChangeListener; import org.apache.atlas.model.instance.AtlasClassification; import org.apache.atlas.model.instance.AtlasEntityHeader; import org.apache.atlas.model.instance.EntityMutationResponse; import org.apache.atlas.model.instance.EntityMutations.EntityOperation; import org.apache.atlas.repository.Constants; import org.apache.atlas.repository.converters.AtlasInstanceConverter; import org.apache.atlas.repository.graph.FullTextMapperV2; import org.apache.atlas.repository.graph.GraphHelper; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.ITypedStruct; import org.apache.atlas.util.AtlasRepositoryConfiguration; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.inject.Inject; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; @Component public class AtlasEntityChangeNotifier { private static final Logger LOG = LoggerFactory.getLogger(AtlasEntityChangeNotifier.class); private final Set<EntityChangeListener> entityChangeListeners; private final AtlasInstanceConverter instanceConverter; @Inject private FullTextMapperV2 fullTextMapperV2; @Inject public AtlasEntityChangeNotifier(Set<EntityChangeListener> entityChangeListeners, AtlasInstanceConverter instanceConverter) { this.entityChangeListeners = entityChangeListeners; this.instanceConverter = instanceConverter; } public void onEntitiesMutated(EntityMutationResponse entityMutationResponse, boolean isImport) throws AtlasBaseException { if (CollectionUtils.isEmpty(entityChangeListeners) || instanceConverter == null) { return; } List<AtlasEntityHeader> createdEntities = entityMutationResponse.getCreatedEntities(); List<AtlasEntityHeader> updatedEntities = entityMutationResponse.getUpdatedEntities(); List<AtlasEntityHeader> partiallyUpdatedEntities = entityMutationResponse.getPartialUpdatedEntities(); List<AtlasEntityHeader> deletedEntities = entityMutationResponse.getDeletedEntities(); // complete full text mapping before calling toITypedReferenceable(), from notifyListners(), to // include all vertex updates in the current graph-transaction doFullTextMapping(createdEntities); doFullTextMapping(updatedEntities); doFullTextMapping(partiallyUpdatedEntities); notifyListeners(createdEntities, EntityOperation.CREATE, isImport); notifyListeners(updatedEntities, EntityOperation.UPDATE, isImport); notifyListeners(partiallyUpdatedEntities, EntityOperation.PARTIAL_UPDATE, isImport); notifyListeners(deletedEntities, EntityOperation.DELETE, isImport); } public void onClassificationAddedToEntity(String entityId, List<AtlasClassification> classifications) throws AtlasBaseException { // Only new classifications need to be used for a partial full text string which can be // appended to the existing fullText updateFullTextMapping(entityId, classifications); ITypedReferenceableInstance entity = toITypedReferenceable(entityId); List<ITypedStruct> traits = toITypedStructs(classifications); if (entity == null || CollectionUtils.isEmpty(traits)) { return; } for (EntityChangeListener listener : entityChangeListeners) { try { listener.onTraitsAdded(entity, traits); } catch (AtlasException e) { throw new AtlasBaseException(AtlasErrorCode.NOTIFICATION_FAILED, e, getListenerName(listener), "TraitAdd"); } } } public void onClassificationDeletedFromEntity(String entityId, List<String> traitNames) throws AtlasBaseException { // Since the entity has already been modified in the graph, we need to recursively remap the entity doFullTextMapping(entityId); ITypedReferenceableInstance entity = toITypedReferenceable(entityId); if (entity == null || CollectionUtils.isEmpty(traitNames)) { return; } for (EntityChangeListener listener : entityChangeListeners) { try { listener.onTraitsDeleted(entity, traitNames); } catch (AtlasException e) { throw new AtlasBaseException(AtlasErrorCode.NOTIFICATION_FAILED, e, getListenerName(listener), "TraitDelete"); } } } public void onClassificationUpdatedToEntity(String entityId, List<AtlasClassification> classifications) throws AtlasBaseException { // Since the classification attributes are updated in the graph, we need to recursively remap the entityText doFullTextMapping(entityId); ITypedReferenceableInstance entity = toITypedReferenceable(entityId); List<ITypedStruct> traits = toITypedStructs(classifications); if (entity == null || CollectionUtils.isEmpty(traits)) { return; } for (EntityChangeListener listener : entityChangeListeners) { try { listener.onTraitsUpdated(entity, traits); } catch (AtlasException e) { throw new AtlasBaseException(AtlasErrorCode.NOTIFICATION_FAILED, e, getListenerName(listener), "TraitUpdate"); } } } private String getListenerName(EntityChangeListener listener) { return listener.getClass().getSimpleName(); } private void notifyListeners(List<AtlasEntityHeader> entityHeaders, EntityOperation operation, boolean isImport) throws AtlasBaseException { if (CollectionUtils.isEmpty(entityHeaders)) { return; } List<ITypedReferenceableInstance> typedRefInsts = toITypedReferenceable(entityHeaders); for (EntityChangeListener listener : entityChangeListeners) { try { switch (operation) { case CREATE: listener.onEntitiesAdded(typedRefInsts, isImport); break; case UPDATE: case PARTIAL_UPDATE: listener.onEntitiesUpdated(typedRefInsts, isImport); break; case DELETE: listener.onEntitiesDeleted(typedRefInsts, isImport); break; } } catch (AtlasException e) { throw new AtlasBaseException(AtlasErrorCode.NOTIFICATION_FAILED, e, getListenerName(listener), operation.toString()); } } } private List<ITypedReferenceableInstance> toITypedReferenceable(List<AtlasEntityHeader> entityHeaders) throws AtlasBaseException { List<ITypedReferenceableInstance> ret = new ArrayList<>(entityHeaders.size()); for (AtlasEntityHeader entityHeader : entityHeaders) { ret.add(instanceConverter.getITypedReferenceable(entityHeader.getGuid())); } return ret; } private ITypedReferenceableInstance toITypedReferenceable(String entityId) throws AtlasBaseException { ITypedReferenceableInstance ret = null; if (StringUtils.isNotEmpty(entityId)) { ret = instanceConverter.getITypedReferenceable(entityId); } return ret; } private List<ITypedStruct> toITypedStructs(List<AtlasClassification> classifications) throws AtlasBaseException { List<ITypedStruct> ret = null; if (classifications != null) { ret = new ArrayList<>(classifications.size()); for (AtlasClassification classification : classifications) { if (classification != null) { ret.add(instanceConverter.getTrait(classification)); } } } return ret; } private void doFullTextMapping(List<AtlasEntityHeader> atlasEntityHeaders) { if (CollectionUtils.isEmpty(atlasEntityHeaders)) { return; } try { if(!AtlasRepositoryConfiguration.isFullTextSearchEnabled()) { return; } } catch (AtlasException e) { LOG.warn("Unable to determine if FullText is disabled. Proceeding with FullText mapping"); } for (AtlasEntityHeader atlasEntityHeader : atlasEntityHeaders) { String guid = atlasEntityHeader.getGuid(); AtlasVertex atlasVertex = AtlasGraphUtilsV1.findByGuid(guid); if(atlasVertex == null) { continue; } try { String fullText = fullTextMapperV2.getIndexTextForEntity(guid); GraphHelper.setProperty(atlasVertex, Constants.ENTITY_TEXT_PROPERTY_KEY, fullText); } catch (AtlasBaseException e) { LOG.error("FullText mapping failed for Vertex[ guid = {} ]", guid, e); } } } private void updateFullTextMapping(String entityId, List<AtlasClassification> classifications) { try { if(!AtlasRepositoryConfiguration.isFullTextSearchEnabled()) { return; } } catch (AtlasException e) { LOG.warn("Unable to determine if FullText is disabled. Proceeding with FullText mapping"); } if (StringUtils.isEmpty(entityId) || CollectionUtils.isEmpty(classifications)) { return; } AtlasVertex atlasVertex = AtlasGraphUtilsV1.findByGuid(entityId); if(atlasVertex == null) { return; } if (atlasVertex == null) { LOG.warn("updateFullTextMapping(): no entity exists with guid {}", entityId); return; } try { String classificationFullText = fullTextMapperV2.getIndexTextForClassifications(entityId, classifications); String existingFullText = (String) GraphHelper.getProperty(atlasVertex, Constants.ENTITY_TEXT_PROPERTY_KEY); String newFullText = existingFullText + " " + classificationFullText; GraphHelper.setProperty(atlasVertex, Constants.ENTITY_TEXT_PROPERTY_KEY, newFullText); } catch (AtlasBaseException e) { LOG.error("FullText mapping failed for Vertex[ guid = {} ]", entityId, e); } } private void doFullTextMapping(String guid) { AtlasEntityHeader entityHeader = new AtlasEntityHeader(); entityHeader.setGuid(guid); doFullTextMapping(Collections.singletonList(entityHeader)); } } <|start_filename|>webapp/src/main/java/org/apache/atlas/web/resources/DataSetLineageResource.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.web.resources; import org.apache.atlas.AtlasClient; import org.apache.atlas.discovery.DiscoveryException; import org.apache.atlas.discovery.LineageService; import org.apache.atlas.typesystem.exception.EntityNotFoundException; import org.apache.atlas.utils.AtlasPerfTracer; import org.apache.atlas.web.util.Servlets; import org.codehaus.jettison.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; /** * Jersey Resource for Hive Table Lineage. */ @Path("lineage/hive") @Singleton @Service @Deprecated public class DataSetLineageResource { private static final Logger LOG = LoggerFactory.getLogger(DataSetLineageResource.class); private static final Logger PERF_LOG = AtlasPerfTracer.getPerfLogger("rest.DataSetLineageResource"); private final LineageService lineageService; /** * Created by the Guice ServletModule and injected with the * configured LineageService. * * @param lineageService lineage service handle */ @Inject public DataSetLineageResource(LineageService lineageService) { this.lineageService = lineageService; } /** * Returns the inputs graph for a given entity. * * @param tableName table name */ @GET @Path("table/{tableName}/inputs/graph") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) public Response inputsGraph(@Context HttpServletRequest request, @PathParam("tableName") String tableName) { if (LOG.isDebugEnabled()) { LOG.debug("==> DataSetLineageResource.inputsGraph({})", tableName); } AtlasPerfTracer perf = null; try { if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DataSetLineageResource.inputsGraph(tableName=" + tableName + ")"); } final String jsonResult = lineageService.getInputsGraph(tableName); JSONObject response = new JSONObject(); response.put(AtlasClient.REQUEST_ID, Servlets.getRequestId()); response.put("tableName", tableName); response.put(AtlasClient.RESULTS, new JSONObject(jsonResult)); return Response.ok(response).build(); } catch (EntityNotFoundException e) { LOG.error("table entity not found for {}", tableName); throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.NOT_FOUND)); } catch (DiscoveryException | IllegalArgumentException e) { LOG.error("Unable to get lineage inputs graph for table {}", tableName, e); throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.BAD_REQUEST)); } catch (WebApplicationException e) { LOG.error("Unable to get lineage inputs graph for table {}", tableName, e); throw e; } catch (Throwable e) { LOG.error("Unable to get lineage inputs graph for table {}", tableName, e); throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR)); } finally { AtlasPerfTracer.log(perf); } } /** * Returns the outputs graph for a given entity. * * @param tableName table name */ @GET @Path("table/{tableName}/outputs/graph") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) public Response outputsGraph(@Context HttpServletRequest request, @PathParam("tableName") String tableName) { if (LOG.isDebugEnabled()) { LOG.debug("==> DataSetLineageResource.outputsGraph({})", tableName); } AtlasPerfTracer perf = null; try { if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DataSetLineageResource.outputsGraph(tableName=" + tableName + ")"); } final String jsonResult = lineageService.getOutputsGraph(tableName); JSONObject response = new JSONObject(); response.put(AtlasClient.REQUEST_ID, Servlets.getRequestId()); response.put("tableName", tableName); response.put(AtlasClient.RESULTS, new JSONObject(jsonResult)); return Response.ok(response).build(); } catch (EntityNotFoundException e) { LOG.error("table entity not found for {}", tableName); throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.NOT_FOUND)); } catch (DiscoveryException | IllegalArgumentException e) { LOG.error("Unable to get lineage outputs graph for table {}", tableName, e); throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.BAD_REQUEST)); } catch (WebApplicationException e) { LOG.error("Unable to get lineage outputs graph for table {}", tableName, e); throw e; } catch (Throwable e) { LOG.error("Unable to get lineage outputs graph for table {}", tableName, e); throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR)); } finally { AtlasPerfTracer.log(perf); } } /** * Return the schema for the given tableName. * * @param tableName table name */ @GET @Path("table/{tableName}/schema") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) public Response schema(@Context HttpServletRequest request, @PathParam("tableName") String tableName) { if (LOG.isDebugEnabled()) { LOG.debug("==> DataSetLineageResource.schema({})", tableName); } AtlasPerfTracer perf = null; try { if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DataSetLineageResource.schema(tableName=" + tableName + ")"); } final String jsonResult = lineageService.getSchema(tableName); JSONObject response = new JSONObject(); response.put(AtlasClient.REQUEST_ID, Servlets.getRequestId()); response.put("tableName", tableName); response.put(AtlasClient.RESULTS, new JSONObject(jsonResult)); return Response.ok(response).build(); } catch (EntityNotFoundException e) { LOG.error("table entity not found for {}", tableName); throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.NOT_FOUND)); } catch (DiscoveryException | IllegalArgumentException e) { LOG.error("Unable to get schema for table {}", tableName, e); throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.BAD_REQUEST)); } catch (WebApplicationException e) { LOG.error("Unable to get schema for table {}", tableName, e); throw e; } catch (Throwable e) { LOG.error("Unable to get schema for table {}", tableName, e); throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR)); } finally { AtlasPerfTracer.log(perf); } } } <|start_filename|>repository/src/test/java/org/apache/atlas/DBSandboxer.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas; import org.apache.atlas.graph.GraphSandboxUtil; import org.apache.atlas.repository.graph.AtlasGraphProvider; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.testng.ITestContext; import org.testng.TestListenerAdapter; import org.testng.xml.XmlClass; import java.util.List; public class DBSandboxer extends TestListenerAdapter { @Override public void onStart(ITestContext context) { // This will only work if each test is run individually (test suite has only one running test) // If there are multiple tests the the sandbox folder name is not provided and the GraphSandboxUtil provisions // a unique name List<XmlClass> testClassesToRun = context.getCurrentXmlTest().getClasses(); if (CollectionUtils.isNotEmpty(testClassesToRun) && 1 == testClassesToRun.size()) { XmlClass currentTestClass = testClassesToRun.get(0); if (null != currentTestClass && StringUtils.isNotEmpty(currentTestClass.getName())) { GraphSandboxUtil.create(currentTestClass.getName()); } else { GraphSandboxUtil.create(); } } else { GraphSandboxUtil.create(); } } @Override public void onFinish(ITestContext context) { AtlasGraphProvider.cleanup(); } } <|start_filename|>repository/src/test/java/org/apache/atlas/lineage/EntityLineageServiceTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.lineage; import com.google.common.collect.ImmutableList; import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.BaseRepositoryTest; import org.apache.atlas.TestModules; import org.apache.atlas.TestUtils; import org.apache.atlas.discovery.EntityLineageService; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.instance.AtlasEntity.Status; import org.apache.atlas.model.instance.AtlasEntityHeader; import org.apache.atlas.model.legacy.EntityResult; import org.apache.atlas.model.lineage.AtlasLineageInfo; import org.apache.atlas.model.lineage.AtlasLineageInfo.LineageDirection; import org.apache.atlas.model.lineage.AtlasLineageInfo.LineageRelation; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.persistence.Id; import org.apache.commons.collections.ArrayStack; import org.apache.commons.lang.RandomStringUtils; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Guice; import org.testng.annotations.Test; import javax.inject.Inject; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; /** * Unit tests for the new v2 Instance LineageService. */ @Guice(modules = TestModules.TestOnlyModule.class) public class EntityLineageServiceTest extends BaseRepositoryTest { @Inject private EntityLineageService lineageService; @BeforeClass public void setUp() throws Exception { super.setUp(); } @AfterClass public void tearDown() throws Exception { super.tearDown(); } /** * Circular Lineage Test. */ @Test public void testCircularLineage() throws Exception{ TestUtils.skipForGremlin3EnabledGraphDb(); String entityGuid = getEntityId(HIVE_TABLE_TYPE, "name", "table2"); AtlasLineageInfo circularLineage = getInputLineageInfo(entityGuid, 5); assertNotNull(circularLineage); System.out.println("circular lineage = " + circularLineage); Map<String, AtlasEntityHeader> entities = circularLineage.getGuidEntityMap(); assertNotNull(entities); Set<LineageRelation> relations = circularLineage.getRelations(); assertNotNull(relations); Assert.assertEquals(entities.size(), 4); Assert.assertEquals(relations.size(), 4); Assert.assertEquals(circularLineage.getLineageDepth(), 5); Assert.assertEquals(circularLineage.getLineageDirection(), LineageDirection.INPUT); assertTrue(entities.containsKey(circularLineage.getBaseEntityGuid())); } /** * Input Lineage Tests. */ @Test(dataProvider = "invalidQueryParamsProvider") public void testGetInputLineageInfoInvalidParams(final String guid, final AtlasLineageInfo.LineageDirection direction, final int depth, AtlasErrorCode errorCode) throws Exception { testInvalidQueryParams(errorCode, new Invoker() { @Override void run() throws AtlasBaseException { lineageService.getAtlasLineageInfo(guid, direction, depth); } }); } @Test public void testGetInputLineageInfo() throws Exception { TestUtils.skipForGremlin3EnabledGraphDb(); String entityGuid = getEntityId(HIVE_TABLE_TYPE, "name", "sales_fact_monthly_mv"); AtlasLineageInfo inputLineage = getInputLineageInfo(entityGuid, 4); assertNotNull(inputLineage); System.out.println("input lineage = " + inputLineage); Map<String, AtlasEntityHeader> entities = inputLineage.getGuidEntityMap(); assertNotNull(entities); Set<LineageRelation> relations = inputLineage.getRelations(); assertNotNull(relations); Assert.assertEquals(entities.size(), 6); Assert.assertEquals(relations.size(), 5); Assert.assertEquals(inputLineage.getLineageDepth(), 4); Assert.assertEquals(inputLineage.getLineageDirection(), LineageDirection.INPUT); assertTrue(entities.containsKey(inputLineage.getBaseEntityGuid())); } /** * Output Lineage Tests. */ @Test(dataProvider = "invalidQueryParamsProvider") public void testGetOutputLineageInvalidParams(final String guid, final LineageDirection direction, final int depth, AtlasErrorCode errorCode) throws Exception { testInvalidQueryParams(errorCode, new Invoker() { @Override void run() throws AtlasBaseException { lineageService.getAtlasLineageInfo(guid, direction, depth); } }); } @Test public void testGetOutputLineageInfo() throws Exception { TestUtils.skipForGremlin3EnabledGraphDb(); String entityGuid = getEntityId(HIVE_TABLE_TYPE, "name", "sales_fact"); AtlasLineageInfo outputLineage = getOutputLineageInfo(entityGuid, 4); assertNotNull(outputLineage); System.out.println("output lineage = " + outputLineage); Map<String, AtlasEntityHeader> entities = outputLineage.getGuidEntityMap(); assertNotNull(entities); Set<LineageRelation> relations = outputLineage.getRelations(); assertNotNull(relations); Assert.assertEquals(entities.size(), 5); Assert.assertEquals(relations.size(), 4); Assert.assertEquals(outputLineage.getLineageDepth(), 4); Assert.assertEquals(outputLineage.getLineageDirection(), LineageDirection.OUTPUT); assertTrue(entities.containsKey(outputLineage.getBaseEntityGuid())); } /** * Both Lineage Tests. */ @Test(dataProvider = "invalidQueryParamsProvider") public void testGetLineageInfoInvalidParams(final String guid, final LineageDirection direction, final int depth, AtlasErrorCode errorCode) throws Exception { testInvalidQueryParams(errorCode, new Invoker() { @Override void run() throws AtlasBaseException { lineageService.getAtlasLineageInfo(guid, direction, depth); } }); } @Test public void testGetLineageInfo() throws Exception { TestUtils.skipForGremlin3EnabledGraphDb(); String entityGuid = getEntityId(HIVE_TABLE_TYPE, "name", "sales_fact_monthly_mv"); AtlasLineageInfo bothLineage = getBothLineageInfo(entityGuid, 5); assertNotNull(bothLineage); System.out.println("both lineage = " + bothLineage); Map<String, AtlasEntityHeader> entities = bothLineage.getGuidEntityMap(); assertNotNull(entities); Set<LineageRelation> relations = bothLineage.getRelations(); assertNotNull(relations); Assert.assertEquals(entities.size(), 6); Assert.assertEquals(relations.size(), 5); Assert.assertEquals(bothLineage.getLineageDepth(), 5); Assert.assertEquals(bothLineage.getLineageDirection(), AtlasLineageInfo.LineageDirection.BOTH); assertTrue(entities.containsKey(bothLineage.getBaseEntityGuid())); } @DataProvider(name = "invalidQueryParamsProvider") private Object[][] params() throws Exception { String entityGuid = getEntityId(HIVE_TABLE_TYPE, "name", "sales_fact_monthly_mv"); // String guid, LineageDirection direction, int depth, AtlasErrorCode errorCode return new Object[][]{ {"", null, 0, AtlasErrorCode.INSTANCE_GUID_NOT_FOUND}, {" ", null, 0, AtlasErrorCode.INSTANCE_GUID_NOT_FOUND}, {null, null, 0, AtlasErrorCode.INSTANCE_GUID_NOT_FOUND}, {"invalidGuid", LineageDirection.OUTPUT, 6, AtlasErrorCode.INSTANCE_GUID_NOT_FOUND}, {entityGuid, null, -10, AtlasErrorCode.INSTANCE_LINEAGE_INVALID_PARAMS}, {entityGuid, null, 5, AtlasErrorCode.INSTANCE_LINEAGE_INVALID_PARAMS} }; } abstract class Invoker { abstract void run() throws AtlasBaseException; } public void testInvalidQueryParams(AtlasErrorCode expectedErrorCode, Invoker Invoker) throws Exception { try { Invoker.run(); fail("Expected " + expectedErrorCode.toString()); } catch(AtlasBaseException e) { assertEquals(e.getAtlasErrorCode(), expectedErrorCode); } } private AtlasLineageInfo getInputLineageInfo(String guid, int depth) throws Exception { return lineageService.getAtlasLineageInfo(guid, LineageDirection.INPUT, depth); } private AtlasLineageInfo getOutputLineageInfo(String guid, int depth) throws Exception { return lineageService.getAtlasLineageInfo(guid, AtlasLineageInfo.LineageDirection.OUTPUT, depth); } private AtlasLineageInfo getBothLineageInfo(String guid, int depth) throws Exception { return lineageService.getAtlasLineageInfo(guid, AtlasLineageInfo.LineageDirection.BOTH, depth); } @Test public void testNewLineageWithDelete() throws Exception { TestUtils.skipForGremlin3EnabledGraphDb(); String tableName = "table" + random(); createTable(tableName, 3, true); String entityGuid = getEntityId(HIVE_TABLE_TYPE, "name", tableName); AtlasLineageInfo inputLineage = getInputLineageInfo(entityGuid, 5); assertNotNull(inputLineage); System.out.println("input lineage = " + inputLineage); Map<String, AtlasEntityHeader> entitiesInput = inputLineage.getGuidEntityMap(); assertNotNull(entitiesInput); assertEquals(entitiesInput.size(), 3); Set<LineageRelation> relationsInput = inputLineage.getRelations(); assertNotNull(relationsInput); assertEquals(relationsInput.size(), 2); AtlasEntityHeader tableEntityInput = entitiesInput.get(entityGuid); assertEquals(tableEntityInput.getStatus(), Status.ACTIVE); AtlasLineageInfo outputLineage = getOutputLineageInfo(entityGuid, 5); assertNotNull(outputLineage); System.out.println("output lineage = " + outputLineage); Map<String, AtlasEntityHeader> entitiesOutput = outputLineage.getGuidEntityMap(); assertNotNull(entitiesOutput); assertEquals(entitiesOutput.size(), 3); Set<LineageRelation> relationsOutput = outputLineage.getRelations(); assertNotNull(relationsOutput); assertEquals(relationsOutput.size(), 2); AtlasEntityHeader tableEntityOutput = entitiesOutput.get(entityGuid); assertEquals(tableEntityOutput.getStatus(), Status.ACTIVE); AtlasLineageInfo bothLineage = getBothLineageInfo(entityGuid, 5); assertNotNull(bothLineage); System.out.println("both lineage = " + bothLineage); Map<String, AtlasEntityHeader> entitiesBoth = bothLineage.getGuidEntityMap(); assertNotNull(entitiesBoth); assertEquals(entitiesBoth.size(), 5); Set<LineageRelation> relationsBoth = bothLineage.getRelations(); assertNotNull(relationsBoth); assertEquals(relationsBoth.size(), 4); AtlasEntityHeader tableEntityBoth = entitiesBoth.get(entityGuid); assertEquals(tableEntityBoth.getStatus(), Status.ACTIVE); //Delete the table entity. Lineage for entity returns the same results as before. //Lineage for table name throws EntityNotFoundException EntityResult deleteResult = repository.deleteEntities(Arrays.asList(entityGuid)); assertTrue(deleteResult.getDeletedEntities().contains(entityGuid)); inputLineage = getInputLineageInfo(entityGuid, 5); tableEntityInput = inputLineage.getGuidEntityMap().get(entityGuid); assertEquals(tableEntityInput.getStatus(), Status.DELETED); assertEquals(inputLineage.getGuidEntityMap().size(), 3); outputLineage = getOutputLineageInfo(entityGuid, 5); tableEntityOutput = outputLineage.getGuidEntityMap().get(entityGuid); assertEquals(tableEntityOutput.getStatus(), Status.DELETED); assertEquals(outputLineage.getGuidEntityMap().size(), 3); bothLineage = getBothLineageInfo(entityGuid, 5); tableEntityBoth = bothLineage.getGuidEntityMap().get(entityGuid); assertEquals(tableEntityBoth.getStatus(), Status.DELETED); assertEquals(bothLineage.getGuidEntityMap().size(), 5); } private void createTable(String tableName, int numCols, boolean createLineage) throws Exception { String dbId = getEntityId(DATABASE_TYPE, "name", "Sales"); Id salesDB = new Id(dbId, 0, DATABASE_TYPE); //Create the entity again and schema should return the new schema List<Referenceable> columns = new ArrayStack(); for (int i = 0; i < numCols; i++) { columns.add(column("col" + random(), "int", "column descr")); } Referenceable sd = storageDescriptor("hdfs://host:8000/apps/warehouse/sales", "TextInputFormat", "TextOutputFormat", true, ImmutableList.of(column("time_id", "int", "time id"))); Id table = table(tableName, "test table", salesDB, sd, "fetl", "External", columns); if (createLineage) { Id inTable = table("table" + random(), "test table", salesDB, sd, "fetl", "External", columns); Id outTable = table("table" + random(), "test table", salesDB, sd, "fetl", "External", columns); loadProcess("process" + random(), "hive query for monthly summary", "Tim ETL", ImmutableList.of(inTable), ImmutableList.of(table), "create table as select ", "plan", "id", "graph", "ETL"); loadProcess("process" + random(), "hive query for monthly summary", "Tim ETL", ImmutableList.of(table), ImmutableList.of(outTable), "create table as select ", "plan", "id", "graph", "ETL"); } } private String random() { return RandomStringUtils.randomAlphanumeric(5); } private String getEntityId(String typeName, String attributeName, String attributeValue) throws Exception { return repository.getEntityDefinition(typeName, attributeName, attributeValue).getId()._getId(); } } <|start_filename|>graphdb/common/src/test/java/org/apache/atlas/graph/GraphSandboxUtil.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.graph; import org.apache.atlas.ApplicationProperties; import org.apache.atlas.AtlasException; import org.apache.commons.configuration.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.UUID; public class GraphSandboxUtil { private static final Logger LOG = LoggerFactory.getLogger(GraphSandboxUtil.class); public static void create(String sandboxName) { Configuration configuration; try { configuration = ApplicationProperties.get(); String newStorageDir = System.getProperty("atlas.data") + File.separatorChar + "storage" + File.separatorChar + sandboxName; configuration.setProperty("atlas.graph.storage.directory", newStorageDir); String newIndexerDir = System.getProperty("atlas.data") + File.separatorChar + "index" + File.separatorChar + sandboxName; configuration.setProperty("atlas.graph.index.search.directory", newIndexerDir); LOG.debug("New Storage dir : {}", newStorageDir); LOG.debug("New Indexer dir : {}", newIndexerDir); } catch (AtlasException ignored) {} } public static void create() { // Append a suffix to isolate the database for each instance UUID uuid = UUID.randomUUID(); create(uuid.toString()); } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/converters/TypeConverterUtil.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.converters; import static org.apache.atlas.AtlasErrorCode.INVALID_TYPE_DEFINITION; import static org.apache.atlas.model.typedef.AtlasStructDef.AtlasConstraintDef.CONSTRAINT_TYPE_OWNED_REF; import static org.apache.atlas.model.typedef.AtlasStructDef.AtlasConstraintDef.CONSTRAINT_TYPE_INVERSE_REF; import static org.apache.atlas.model.typedef.AtlasStructDef.AtlasConstraintDef.CONSTRAINT_PARAM_ATTRIBUTE; import static org.apache.atlas.type.AtlasTypeUtil.isArrayType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Set; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.typedef.AtlasClassificationDef; import org.apache.atlas.model.typedef.AtlasEntityDef; import org.apache.atlas.model.typedef.AtlasEnumDef; import org.apache.atlas.model.typedef.AtlasEnumDef.AtlasEnumElementDef; import org.apache.atlas.model.typedef.AtlasStructDef; import org.apache.atlas.model.typedef.AtlasStructDef.AtlasAttributeDef; import org.apache.atlas.model.typedef.AtlasStructDef.AtlasAttributeDef.Cardinality; import org.apache.atlas.model.typedef.AtlasStructDef.AtlasConstraintDef; import org.apache.atlas.model.typedef.AtlasTypeDefHeader; import org.apache.atlas.model.typedef.AtlasTypesDef; import org.apache.atlas.repository.store.graph.v1.AtlasStructDefStoreV1; import org.apache.atlas.type.AtlasClassificationType; import org.apache.atlas.type.AtlasEntityType; import org.apache.atlas.type.AtlasEnumType; import org.apache.atlas.type.AtlasStructType; import org.apache.atlas.type.AtlasStructType.AtlasAttribute; import org.apache.atlas.type.AtlasType; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.type.AtlasTypeUtil; import org.apache.atlas.typesystem.TypesDef; import org.apache.atlas.typesystem.json.TypesSerialization; import org.apache.atlas.typesystem.types.AttributeDefinition; import org.apache.atlas.typesystem.types.ClassType; import org.apache.atlas.typesystem.types.EnumTypeDefinition; import org.apache.atlas.typesystem.types.EnumValue; import org.apache.atlas.typesystem.types.HierarchicalTypeDefinition; import org.apache.atlas.typesystem.types.Multiplicity; import org.apache.atlas.typesystem.types.StructTypeDefinition; import org.apache.atlas.typesystem.types.TraitType; import org.apache.atlas.typesystem.types.utils.TypesUtil; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; public final class TypeConverterUtil { private TypeConverterUtil() {} private static final Logger LOG = LoggerFactory.getLogger(TypeConverterUtil.class); public static TypesDef toTypesDef(AtlasType type, AtlasTypeRegistry typeRegistry) throws AtlasBaseException { final TypesDef ret; if (type instanceof AtlasEnumType) { ret = TypeConverterUtil.enumToTypesDef((AtlasEnumType) type); } else if (type instanceof AtlasEntityType) { ret = TypeConverterUtil.entityToTypesDef((AtlasEntityType) type, typeRegistry); } else if (type instanceof AtlasClassificationType) { ret = TypeConverterUtil.classificationToTypesDef((AtlasClassificationType) type, typeRegistry); } else if (type instanceof AtlasStructType) { ret = TypeConverterUtil.structToTypesDef((AtlasStructType) type, typeRegistry); } else { ret = new TypesDef(); } return ret; } private static TypesDef enumToTypesDef(AtlasEnumType enumType) { TypesDef ret = null; AtlasEnumDef enumDef = enumType.getEnumDef(); String enumName = enumDef.getName(); String enumDesc = enumDef.getDescription(); String enumVersion = enumDef.getTypeVersion(); EnumValue[] enumValues = getEnumValues(enumDef.getElementDefs()); if (enumName != null && enumValues != null && enumValues.length > 0) { EnumTypeDefinition enumTypeDef = new EnumTypeDefinition(enumName, enumDesc, enumVersion, enumValues); ret = TypesUtil.getTypesDef(ImmutableList.of(enumTypeDef), ImmutableList.<StructTypeDefinition>of(), ImmutableList.<HierarchicalTypeDefinition<TraitType>>of(), ImmutableList.<HierarchicalTypeDefinition<ClassType>>of()); } return ret; } private static TypesDef structToTypesDef(AtlasStructType structType, AtlasTypeRegistry registry) throws AtlasBaseException { String typeName = structType.getStructDef().getName(); String typeDesc = structType.getStructDef().getDescription(); String typeVersion = structType.getStructDef().getTypeVersion(); AttributeDefinition[] attributes = getAttributes(structType, registry); StructTypeDefinition structTypeDef = TypesUtil.createStructTypeDef(typeName, typeDesc, typeVersion, attributes); TypesDef ret = TypesUtil.getTypesDef(ImmutableList.<EnumTypeDefinition>of(), ImmutableList.of(structTypeDef), ImmutableList.<HierarchicalTypeDefinition<TraitType>>of(), ImmutableList.<HierarchicalTypeDefinition<ClassType>>of()); return ret; } private static TypesDef entityToTypesDef(AtlasEntityType entityType, AtlasTypeRegistry registry) throws AtlasBaseException { String typeName = entityType.getEntityDef().getName(); String typeDesc = entityType.getEntityDef().getDescription(); String typeVersion = entityType.getEntityDef().getTypeVersion(); ImmutableSet superTypes = ImmutableSet.copyOf(entityType.getEntityDef().getSuperTypes()); AttributeDefinition[] attributes = getAttributes(entityType, registry); HierarchicalTypeDefinition<ClassType> classType = TypesUtil.createClassTypeDef(typeName, typeDesc, typeVersion, superTypes, attributes); TypesDef ret = TypesUtil.getTypesDef(ImmutableList.<EnumTypeDefinition>of(), ImmutableList.<StructTypeDefinition>of(), ImmutableList.<HierarchicalTypeDefinition<TraitType>>of(), ImmutableList.of(classType)); return ret; } private static TypesDef classificationToTypesDef(AtlasClassificationType classificationType, AtlasTypeRegistry registry) throws AtlasBaseException { String typeName = classificationType.getClassificationDef().getName(); String typeDesc = classificationType.getClassificationDef().getDescription(); String typeVersion = classificationType.getClassificationDef().getTypeVersion(); ImmutableSet superTypes = ImmutableSet.copyOf(classificationType.getClassificationDef().getSuperTypes()); AttributeDefinition[] attributes = getAttributes(classificationType, registry); HierarchicalTypeDefinition traitType = TypesUtil.createTraitTypeDef(typeName, typeDesc, typeVersion, superTypes, attributes); TypesDef ret = TypesUtil.getTypesDef(ImmutableList.<EnumTypeDefinition>of(), ImmutableList.<StructTypeDefinition>of(), ImmutableList.<HierarchicalTypeDefinition<TraitType>>of(traitType), ImmutableList.<HierarchicalTypeDefinition<ClassType>>of()); return ret; } public static AtlasTypesDef toAtlasTypesDef(String typeDefinition, AtlasTypeRegistry registry) throws AtlasBaseException { AtlasTypesDef ret = new AtlasTypesDef(); try { if (StringUtils.isEmpty(typeDefinition)) { throw new AtlasBaseException(INVALID_TYPE_DEFINITION, typeDefinition); } TypesDef typesDef = TypesSerialization.fromJson(typeDefinition); if (CollectionUtils.isNotEmpty(typesDef.enumTypesAsJavaList())) { List<AtlasEnumDef> enumDefs = toAtlasEnumDefs(typesDef.enumTypesAsJavaList()); ret.setEnumDefs(enumDefs); } if (CollectionUtils.isNotEmpty(typesDef.structTypesAsJavaList())) { List<AtlasStructDef> structDefs = toAtlasStructDefs(typesDef.structTypesAsJavaList()); ret.setStructDefs(structDefs); } if (CollectionUtils.isNotEmpty(typesDef.classTypesAsJavaList())) { List<AtlasEntityDef> entityDefs = toAtlasEntityDefs(typesDef.classTypesAsJavaList(), registry); ret.setEntityDefs(entityDefs); } if (CollectionUtils.isNotEmpty(typesDef.traitTypesAsJavaList())) { List<AtlasClassificationDef> classificationDefs = toAtlasClassificationDefs(typesDef.traitTypesAsJavaList()); ret.setClassificationDefs(classificationDefs); } } catch (Exception e) { LOG.error("Invalid type definition = {}", typeDefinition, e); throw new AtlasBaseException(INVALID_TYPE_DEFINITION, typeDefinition); } return ret; } public static ImmutableList<String> getTypeNames(List<AtlasTypeDefHeader> atlasTypesDefs) { List<String> ret = new ArrayList<String>(); if (CollectionUtils.isNotEmpty(atlasTypesDefs)) { for (AtlasTypeDefHeader atlasTypesDef : atlasTypesDefs) { ret.add(atlasTypesDef.getName()); } } return ImmutableList.copyOf(ret); } public static List<String> getTypeNames(AtlasTypesDef typesDef) { List<AtlasTypeDefHeader> atlasTypesDefs = AtlasTypeUtil.toTypeDefHeader(typesDef); return getTypeNames(atlasTypesDefs); } private static List<AtlasEnumDef> toAtlasEnumDefs(List<EnumTypeDefinition> enumTypeDefinitions) { List<AtlasEnumDef> ret = new ArrayList<AtlasEnumDef>(); for (EnumTypeDefinition enumType : enumTypeDefinitions) { AtlasEnumDef enumDef = new AtlasEnumDef(); enumDef.setName(enumType.name); enumDef.setDescription(enumType.description); enumDef.setTypeVersion(enumType.version); enumDef.setElementDefs(getAtlasEnumElementDefs(enumType.enumValues)); ret.add(enumDef); } return ret; } private static List<AtlasStructDef> toAtlasStructDefs(List<StructTypeDefinition> structTypeDefinitions) throws AtlasBaseException { List<AtlasStructDef> ret = new ArrayList<AtlasStructDef>(); for (StructTypeDefinition structType : structTypeDefinitions) { AtlasStructDef structDef = new AtlasStructDef(); List<AtlasAttributeDef> attrDefs = new ArrayList<AtlasAttributeDef>(); structDef.setName(structType.typeName); structDef.setDescription(structType.typeDescription); structDef.setTypeVersion(structType.typeVersion); AttributeDefinition[] attrDefinitions = structType.attributeDefinitions; for (AttributeDefinition attrDefinition : attrDefinitions) { attrDefs.add(toAtlasAttributeDef(attrDefinition)); } structDef.setAttributeDefs(attrDefs); ret.add(structDef); } return ret; } private static List<AtlasClassificationDef> toAtlasClassificationDefs(List<HierarchicalTypeDefinition<TraitType>> traitTypeDefinitions) throws AtlasBaseException { List<AtlasClassificationDef> ret = new ArrayList<AtlasClassificationDef>(); for (HierarchicalTypeDefinition<TraitType> traitType : traitTypeDefinitions) { AtlasClassificationDef classifDef = new AtlasClassificationDef(); List<AtlasAttributeDef> attrDefs = new ArrayList<AtlasAttributeDef>(); classifDef.setName(traitType.typeName); classifDef.setDescription(traitType.typeDescription); classifDef.setTypeVersion(traitType.typeVersion); classifDef.setSuperTypes(traitType.superTypes); AttributeDefinition[] attrDefinitions = traitType.attributeDefinitions; for (AttributeDefinition attrDefinition : attrDefinitions) { attrDefs.add(toAtlasAttributeDef(attrDefinition)); } classifDef.setAttributeDefs(attrDefs); ret.add(classifDef); } return ret; } private static List<AtlasEntityDef> toAtlasEntityDefs(List<HierarchicalTypeDefinition<ClassType>> classTypeDefinitions, AtlasTypeRegistry registry) throws AtlasBaseException { List<AtlasEntityDef> atlasEntityDefs = new ArrayList<AtlasEntityDef>(); for (HierarchicalTypeDefinition<ClassType> classType : classTypeDefinitions) { List<AtlasAttributeDef> attrDefs = new ArrayList<AtlasAttributeDef>(); AtlasEntityDef atlasEntityDef = new AtlasEntityDef(); String classTypeDefName = classType.typeName; atlasEntityDef.setName(classTypeDefName); atlasEntityDef.setDescription(classType.typeDescription); atlasEntityDef.setTypeVersion(classType.typeVersion); atlasEntityDef.setSuperTypes(classType.superTypes); AttributeDefinition[] attrDefinitions = classType.attributeDefinitions; for (AttributeDefinition oldAttr : attrDefinitions) { AtlasAttributeDef newAttr = toAtlasAttributeDef(oldAttr); attrDefs.add(newAttr); } atlasEntityDef.setAttributeDefs(attrDefs); atlasEntityDefs.add(atlasEntityDef); } return atlasEntityDefs; } private static String getArrayTypeName(String attrType) { String ret = null; if (isArrayType(attrType)) { Set<String> typeNames = AtlasTypeUtil.getReferencedTypeNames(attrType); if (typeNames.size() > 0) { ret = typeNames.iterator().next(); } } return ret; } private static List<AtlasEnumElementDef> getAtlasEnumElementDefs(EnumValue[] enums) { List<AtlasEnumElementDef> ret = new ArrayList<AtlasEnumElementDef>(); for (EnumValue enumElem : enums) { ret.add(new AtlasEnumElementDef(enumElem.value, null, enumElem.ordinal)); } return ret; } private static EnumValue[] getEnumValues(List<AtlasEnumElementDef> enumDefs) { List<EnumValue> ret = new ArrayList<EnumValue>(); if (CollectionUtils.isNotEmpty(enumDefs)) { for (AtlasEnumElementDef enumDef : enumDefs) { if (enumDef != null) { ret.add(new EnumValue(enumDef.getValue(), enumDef.getOrdinal())); } } } return ret.toArray(new EnumValue[ret.size()]); } public static AtlasAttributeDef toAtlasAttributeDef(final AttributeDefinition attrDefinition) { AtlasAttributeDef ret = new AtlasAttributeDef(); ret.setName(attrDefinition.name); ret.setTypeName(attrDefinition.dataTypeName); ret.setIsIndexable(attrDefinition.isIndexable); ret.setIsUnique(attrDefinition.isUnique); if (attrDefinition.isComposite) { ret.addConstraint(new AtlasConstraintDef(CONSTRAINT_TYPE_OWNED_REF)); } if (StringUtils.isNotBlank(attrDefinition.reverseAttributeName)) { ret.addConstraint(new AtlasConstraintDef(CONSTRAINT_TYPE_INVERSE_REF, new HashMap<String, Object>() {{ put(CONSTRAINT_PARAM_ATTRIBUTE, attrDefinition.reverseAttributeName); }})); } // Multiplicity attribute mapping Multiplicity multiplicity = attrDefinition.multiplicity; int minCount = multiplicity.lower; int maxCount = multiplicity.upper; boolean isUnique = multiplicity.isUnique; if (minCount == 0) { ret.setIsOptional(true); ret.setValuesMinCount(0); } else { ret.setIsOptional(false); ret.setValuesMinCount(minCount); } if (maxCount < 2) { ret.setCardinality(Cardinality.SINGLE); ret.setValuesMaxCount(1); } else { if (!isUnique) { ret.setCardinality(Cardinality.LIST); } else { ret.setCardinality(Cardinality.SET); } ret.setValuesMaxCount(maxCount); } return ret; } private static AttributeDefinition[] getAttributes(AtlasStructType structType, AtlasTypeRegistry registry) throws AtlasBaseException { List<AttributeDefinition> ret = new ArrayList<>(); List<AtlasAttributeDef> attrDefs = structType.getStructDef().getAttributeDefs(); if (CollectionUtils.isNotEmpty(attrDefs)) { for (AtlasAttributeDef attrDef : attrDefs) { AtlasAttribute attribute = structType.getAttribute(attrDef.getName()); ret.add(AtlasStructDefStoreV1.toAttributeDefintion(attribute)); } } return ret.toArray(new AttributeDefinition[ret.size()]); } } <|start_filename|>webapp/src/main/java/org/apache/atlas/web/filters/AuditFilter.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.web.filters; import org.apache.atlas.AtlasClient; import org.apache.atlas.AtlasException; import org.apache.atlas.RequestContext; import org.apache.atlas.RequestContextV1; import org.apache.atlas.metrics.Metrics; import org.apache.atlas.util.AtlasRepositoryConfiguration; import org.apache.atlas.web.util.DateTimeHelper; import org.apache.atlas.web.util.Servlets; import org.apache.commons.configuration.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Date; import java.util.UUID; /** * This records audit information as part of the filter after processing the request * and also introduces a UUID into request and response for tracing requests in logs. */ @Component public class AuditFilter implements Filter { private static final Logger AUDIT_LOG = LoggerFactory.getLogger("AUDIT"); private static final Logger LOG = LoggerFactory.getLogger(AuditFilter.class); private static final Logger METRICS_LOG = LoggerFactory.getLogger("METRICS"); @Override public void init(FilterConfig filterConfig) throws ServletException { LOG.info("AuditFilter initialization started"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { final String requestTimeISO9601 = DateTimeHelper.formatDateUTC(new Date()); final HttpServletRequest httpRequest = (HttpServletRequest) request; final String requestId = UUID.randomUUID().toString(); final Thread currentThread = Thread.currentThread(); final String oldName = currentThread.getName(); String user = getUserFromRequest(httpRequest); try { currentThread.setName(formatName(oldName, requestId)); RequestContext requestContext = RequestContext.createContext(); requestContext.setUser(user); recordAudit(httpRequest, requestTimeISO9601, user); filterChain.doFilter(request, response); } finally { // put the request id into the response so users can trace logs for this request ((HttpServletResponse) response).setHeader(AtlasClient.REQUEST_ID, requestId); currentThread.setName(oldName); recordMetrics(); RequestContext.clear(); RequestContextV1.clear(); } } private String formatName(String oldName, String requestId) { return oldName + " - " + requestId; } private void recordAudit(HttpServletRequest httpRequest, String whenISO9601, String who) { final String fromHost = httpRequest.getRemoteHost(); final String fromAddress = httpRequest.getRemoteAddr(); final String whatRequest = httpRequest.getMethod(); final String whatURL = Servlets.getRequestURL(httpRequest); final String whatAddrs = httpRequest.getLocalAddr(); final String whatUrlPath = httpRequest.getRequestURL().toString();//url path without query string if (!isOperationExcludedFromAudit(whatRequest, whatUrlPath.toLowerCase(), null)) { audit(who, fromAddress, whatRequest, fromHost, whatURL, whatAddrs, whenISO9601); } else { if(LOG.isDebugEnabled()) { LOG.debug(" Skipping Audit for {} ", whatURL); } } } private String getUserFromRequest(HttpServletRequest httpRequest) { // look for the user in the request final String userFromRequest = Servlets.getUserFromRequest(httpRequest); return userFromRequest == null ? "UNKNOWN" : userFromRequest; } public static void audit(String who, String fromAddress, String whatRequest, String fromHost, String whatURL, String whatAddrs, String whenISO9601) { AUDIT_LOG.info("Audit: {}/{}-{} performed request {} {} ({}) at time {}", who, fromAddress, fromHost, whatRequest, whatURL, whatAddrs, whenISO9601); } public static void recordMetrics() { //record metrics Metrics requestMetrics = RequestContext.getMetrics(); if (!requestMetrics.isEmpty()) { METRICS_LOG.info("{}", requestMetrics); } } boolean isOperationExcludedFromAudit(String requestHttpMethod, String requestOperation, Configuration config) { try { return AtlasRepositoryConfiguration.isExcludedFromAudit(config, requestHttpMethod, requestOperation); } catch (AtlasException e) { return false; } } @Override public void destroy() { // do nothing } } <|start_filename|>intg/src/main/java/org/apache/atlas/model/instance/AtlasRelationship.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.model.instance; import org.apache.atlas.model.typedef.AtlasRelationshipDef; import org.codehaus.jackson.annotate.JsonAutoDetect; import org.codehaus.jackson.annotate.JsonIgnore; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.map.annotate.JsonSerialize; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; import java.util.Date; import java.util.Map; import java.util.Objects; import java.util.concurrent.atomic.AtomicLong; import static org.codehaus.jackson.annotate.JsonAutoDetect.Visibility.NONE; import static org.codehaus.jackson.annotate.JsonAutoDetect.Visibility.PUBLIC_ONLY; /** * Atlas relationship instance. */ @JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) @JsonIgnoreProperties(ignoreUnknown=true) @XmlRootElement @XmlAccessorType(XmlAccessType.PROPERTY) public class AtlasRelationship extends AtlasStruct implements Serializable { private static final long serialVersionUID = 1L; private String guid = null; private AtlasObjectId end1 = null; private AtlasObjectId end2 = null; private String label = null; private Status status = Status.ACTIVE; private String createdBy = null; private String updatedBy = null; private Date createTime = null; private Date updateTime = null; private Long version = 0L; public enum Status { ACTIVE, DELETED } @JsonIgnore private static AtomicLong s_nextId = new AtomicLong(System.nanoTime()); public AtlasRelationship() { super(); init(); } public AtlasRelationship(String typeName) { this(typeName, null); } public AtlasRelationship(String typeName, Map<String, Object> attributes) { super(typeName, attributes); init(); } public AtlasRelationship(String typeName, AtlasObjectId end1, AtlasObjectId end2) { super(typeName); init(nextInternalId(), end1, end2, null, null, null, null, null, null, 0L); } public AtlasRelationship(String typeName, String attrName, Object attrValue) { super(typeName, attrName, attrValue); init(); } public AtlasRelationship(AtlasRelationshipDef relationshipDef) { this(relationshipDef != null ? relationshipDef.getName() : null); } public AtlasRelationship(AtlasRelationship other) { super(other); if (other != null) { init(other.guid, other.end1, other.end2, other.label, other.status, other.createdBy, other.updatedBy, other.createTime, other.updateTime, other.version); } } public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public String getUpdatedBy() { return updatedBy; } public void setUpdatedBy(String updatedBy) { this.updatedBy = updatedBy; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } public AtlasObjectId getEnd1() { return end1; } public void setEnd1(AtlasObjectId end1) { this.end1 = end1; } public AtlasObjectId getEnd2() { return end2; } public void setEnd2(AtlasObjectId end2) { this.end2 = end2; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } private static String nextInternalId() { return "-" + Long.toString(s_nextId.getAndIncrement()); } private void init() { init(nextInternalId(), null, null, null, null, null, null, null, null, 0L); } private void init(String guid, AtlasObjectId end1, AtlasObjectId end2, String label, Status status, String createdBy, String updatedBy, Date createTime, Date updateTime, Long version) { setGuid(guid); setEnd1(end1); setEnd2(end2); setLabel(label); setStatus(status); setCreatedBy(createdBy); setUpdatedBy(updatedBy); setCreateTime(createTime); setUpdateTime(updateTime); setVersion(version); } @Override public StringBuilder toString(StringBuilder sb) { if (sb == null) { sb = new StringBuilder(); } sb.append("AtlasRelationship{"); super.toString(sb); sb.append("guid='").append(guid).append('\''); sb.append(", end1=").append(end1); sb.append(", end2=").append(end2); sb.append(", label='").append(label).append('\''); sb.append(", status=").append(status); sb.append(", createdBy='").append(createdBy).append('\''); sb.append(", updatedBy='").append(updatedBy).append('\''); dumpDateField(", createTime=", createTime, sb); dumpDateField(", updateTime=", updateTime, sb); sb.append(", version=").append(version); sb.append('}'); return sb; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } AtlasRelationship that = (AtlasRelationship) o; return Objects.equals(guid, that.guid) && Objects.equals(end1, that.end1) && Objects.equals(end2, that.end2) && Objects.equals(label, that.label) && status == that.status && Objects.equals(createdBy, that.createdBy) && Objects.equals(updatedBy, that.updatedBy) && Objects.equals(createTime, that.createTime) && Objects.equals(updateTime, that.updateTime) && Objects.equals(version, that.version); } @Override public int hashCode() { return Objects.hash(super.hashCode(), guid, end1, end2, label, status, createdBy, updatedBy, createTime, updateTime, version); } @Override public String toString() { return toString(new StringBuilder()).toString(); } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/memory/IAttributeStore.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.memory; import org.apache.atlas.repository.RepositoryException; import org.apache.atlas.typesystem.persistence.StructInstance; import org.apache.atlas.typesystem.types.IConstructableType; @Deprecated public interface IAttributeStore { /** * Store the attribute's value from the 'instance' into this store. * @param pos * @param instance * @throws RepositoryException */ void store(int pos, IConstructableType type, StructInstance instance) throws RepositoryException; /** * load the Instance with the value from position 'pos' for the attribute. * @param pos * @param instance * @throws RepositoryException */ void load(int pos, IConstructableType type, StructInstance instance) throws RepositoryException; /** * Ensure store have space for the given pos. * @param pos * @throws RepositoryException */ void ensureCapacity(int pos) throws RepositoryException; } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/converters/AtlasArrayFormatConverter.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.converters; import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.TypeCategory; import org.apache.atlas.type.AtlasArrayType; import org.apache.atlas.type.AtlasType; import org.apache.atlas.type.AtlasTypeRegistry; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; public class AtlasArrayFormatConverter extends AtlasAbstractFormatConverter { public AtlasArrayFormatConverter(AtlasFormatConverters registry, AtlasTypeRegistry typeRegistry) { super(registry, typeRegistry, TypeCategory.ARRAY); } @Override public Collection fromV1ToV2(Object v1Obj, AtlasType type, ConverterContext ctx) throws AtlasBaseException { Collection ret = null; if (v1Obj != null) { if (v1Obj instanceof Set) { ret = new LinkedHashSet(); } else { ret = new ArrayList(); } AtlasArrayType arrType = (AtlasArrayType) type; AtlasType elemType = arrType.getElementType(); AtlasFormatConverter elemConverter = converterRegistry.getConverter(elemType.getTypeCategory()); if (v1Obj instanceof Collection) { Collection v1List = (Collection) v1Obj; for (Object v1Elem : v1List) { Object convertedVal = elemConverter.fromV1ToV2(v1Elem, elemType, ctx); ret.add(convertedVal); } } else { Object convertedVal = elemConverter.fromV1ToV2(v1Obj, elemType, ctx); ret.add(convertedVal); } } return ret; } @Override public Collection fromV2ToV1(Object v2Obj, AtlasType type, ConverterContext ctx) throws AtlasBaseException { Collection ret = null; if (v2Obj != null) { if (v2Obj instanceof List) { ret = new ArrayList(); } else if (v2Obj instanceof Set) { ret = new LinkedHashSet(); } else { throw new AtlasBaseException(AtlasErrorCode.UNEXPECTED_TYPE, "List or Set", v2Obj.getClass().getCanonicalName()); } AtlasArrayType arrType = (AtlasArrayType) type; AtlasType elemType = arrType.getElementType(); AtlasFormatConverter elemConverter = converterRegistry.getConverter(elemType.getTypeCategory()); Collection v2List = (Collection) v2Obj; for (Object v2Elem : v2List) { Object convertedVal = elemConverter.fromV2ToV1(v2Elem, elemType, ctx); ret.add(convertedVal); } } return ret; } } <|start_filename|>repository/src/main/java/org/apache/atlas/gremlin/optimizer/OptimizationContext.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.gremlin.optimizer; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.atlas.groovy.AbstractFunctionExpression; import org.apache.atlas.groovy.ClosureExpression; import org.apache.atlas.groovy.ClosureExpression.VariableDeclaration; import org.apache.atlas.groovy.GroovyExpression; import org.apache.atlas.groovy.IdentifierExpression; import org.apache.atlas.groovy.ListExpression; import org.apache.atlas.groovy.TypeCoersionExpression; import org.apache.atlas.groovy.VariableAssignmentExpression; /** * Maintains state information during gremlin optimization. */ public class OptimizationContext { private static final String TMP_ALIAS_NAME = "__tmp"; private static final String FINAL_ALIAS_NAME = "__res"; private static final String RESULT_VARIABLE = "r"; private final List<GroovyExpression> initialStatements = new ArrayList<>(); private GroovyExpression resultExpression = getResultVariable(); private int counter = 1; private final Map<String, ClosureExpression> functionBodies = new HashMap<>(); private AbstractFunctionExpression rangeExpression; public OptimizationContext() { } /** * @return */ public List<GroovyExpression> getInitialStatements() { return initialStatements; } public void prependStatement(GroovyExpression expr) { initialStatements.add(0, expr); } public String getUniqueFunctionName() { return "f" + (counter++); } public GroovyExpression getDefineResultVariableStmt() { GroovyExpression castExpression = new TypeCoersionExpression(new ListExpression(), "Set"); GroovyExpression resultVarDef = new VariableAssignmentExpression(RESULT_VARIABLE, castExpression); return resultVarDef; } public void setResultExpression(GroovyExpression expr) { resultExpression = expr; } public GroovyExpression getResultExpression() { return resultExpression; } public GroovyExpression getResultVariable() { return new IdentifierExpression(RESULT_VARIABLE); } public ClosureExpression getUserDefinedFunctionBody(String functionName) { return functionBodies.get(functionName); } public String addFunctionDefinition(VariableDeclaration decl, GroovyExpression body) { String functionName = getUniqueFunctionName(); List<VariableDeclaration> decls = (decl == null) ? Collections.<VariableDeclaration>emptyList() : Collections.singletonList(decl); ClosureExpression bodyClosure = new ClosureExpression(body, decls); VariableAssignmentExpression expr = new VariableAssignmentExpression(functionName, bodyClosure); initialStatements.add(expr); functionBodies.put(functionName, bodyClosure); return functionName; } public String getFinalAliasName() { return FINAL_ALIAS_NAME; } public String getTempAliasName() { return TMP_ALIAS_NAME; } public void setRangeExpression(AbstractFunctionExpression rangeExpression) { this.rangeExpression = rangeExpression; } public AbstractFunctionExpression getRangeExpression() { return rangeExpression; } } <|start_filename|>authorization/src/test/java/org/apache/atlas/authorize/simple/PolicyUtilTest.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.authorize.simple; import static org.testng.AssertJUnit.assertEquals; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.atlas.authorize.simple.SimpleAtlasAuthorizer; import org.apache.atlas.authorize.AtlasActionTypes; import org.apache.atlas.authorize.AtlasResourceTypes; import org.apache.atlas.authorize.simple.PolicyDef; import org.apache.atlas.authorize.simple.PolicyParser; import org.apache.atlas.authorize.simple.PolicyUtil; import org.testng.annotations.Test; public class PolicyUtilTest { @Test public void testCreatePermissionMap() { HashMap<AtlasResourceTypes, List<String>> resourceMap = new HashMap<>(); List<String> resource1List = new ArrayList<>(); resource1List.add("*abc"); resourceMap.put(AtlasResourceTypes.ENTITY, resource1List); List<String> resource2List = new ArrayList<>(); resource2List.add("*xyz"); resourceMap.put(AtlasResourceTypes.OPERATION, resource2List); List<String> resource3List = new ArrayList<>(); resource3List.add("PII"); resourceMap.put(AtlasResourceTypes.TYPE, resource3List); Map<String, HashMap<AtlasResourceTypes, List<String>>> permissionMap = new HashMap<>(); permissionMap.put("grp1", resourceMap); List<String> policies = new ArrayList<>(); policies.add("hivePolicy;;usr1:r,usr2:rw;;grp1:rwu,grp2:u;;entity:*abc,operation:*xyz,type:PII"); List<PolicyDef> policyDefList = new PolicyParser().parsePolicies(policies); Map<String, Map<AtlasResourceTypes, List<String>>> createdPermissionMap = new PolicyUtil().createPermissionMap(policyDefList, AtlasActionTypes.READ, SimpleAtlasAuthorizer.AtlasAccessorTypes.GROUP); assertEquals(permissionMap, createdPermissionMap); } @Test public void testMergeCreatePermissionMap() { HashMap<AtlasResourceTypes, List<String>> resourceMap = new HashMap<>(); List<String> resource1List = new ArrayList<>(); resource1List.add("*abc"); resourceMap.put(AtlasResourceTypes.ENTITY, resource1List); List<String> resource2List = new ArrayList<>(); resource2List.add("*x"); resource2List.add("*xyz"); resourceMap.put(AtlasResourceTypes.OPERATION, resource2List); List<String> resource3List = new ArrayList<>(); resource3List.add("PII"); resourceMap.put(AtlasResourceTypes.TYPE, resource3List); Map<String, HashMap<AtlasResourceTypes, List<String>>> permissionMap = new HashMap<>(); permissionMap.put("grp1", resourceMap); List<String> policies = new ArrayList<>(); policies.add("hivePolicys;;;;grp1:rwu;;entity:*abc,operation:*xyz,operation:*x"); policies.add("hivePolicy;;;;grp1:rwu;;entity:*abc,operation:*xyz"); policies.add("hivePolicy;;usr1:r,usr2:rw;;grp1:rwu;;entity:*abc,operation:*xyz"); policies.add("hivePolicy;;usr1:r,usr2:rw;;grp1:rwu,grp2:u;;entity:*abc,operation:*xyz,type:PII"); List<PolicyDef> policyDefList = new PolicyParser().parsePolicies(policies); Map<String, Map<AtlasResourceTypes, List<String>>> createdPermissionMap = new PolicyUtil().createPermissionMap(policyDefList, AtlasActionTypes.READ, SimpleAtlasAuthorizer.AtlasAccessorTypes.GROUP); assertEquals(permissionMap, createdPermissionMap); } } <|start_filename|>authorization/src/main/java/org/apache/atlas/authorize/simple/PolicyParser.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.authorize.simple; import org.apache.atlas.authorize.AtlasActionTypes; import org.apache.atlas.authorize.AtlasResourceTypes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.tools.jline_embedded.internal.Log; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; public class PolicyParser { private static Logger LOG = LoggerFactory.getLogger(PolicyParser.class); private static boolean isDebugEnabled = LOG.isDebugEnabled(); public static final int POLICYNAME = 0; public static final int USER_INDEX = 1; public static final int USERNAME = 0; public static final int USER_AUTHORITIES = 1; public static final int GROUP_INDEX = 2; public static final int GROUPNAME = 0; public static final int GROUP_AUTHORITIES = 1; public static final int RESOURCE_INDEX = 3; public static final int RESOURCE_TYPE = 0; public static final int RESOURCE_NAME = 1; private List<AtlasActionTypes> getListOfAutorities(String auth) { if (isDebugEnabled) { LOG.debug("==> PolicyParser getListOfAutorities"); } List<AtlasActionTypes> authorities = new ArrayList<>(); for (int i = 0; i < auth.length(); i++) { char access = auth.toLowerCase().charAt(i); switch (access) { case 'r': authorities.add(AtlasActionTypes.READ); break; case 'w': authorities.add(AtlasActionTypes.CREATE); break; case 'u': authorities.add(AtlasActionTypes.UPDATE); break; case 'd': authorities.add(AtlasActionTypes.DELETE); break; default: if (LOG.isErrorEnabled()) { LOG.error("Invalid action: '{}'", access); } break; } } if (isDebugEnabled) { LOG.debug("<== PolicyParser getListOfAutorities"); } return authorities; } public List<PolicyDef> parsePolicies(List<String> policies) { if (isDebugEnabled) { LOG.debug("==> PolicyParser parsePolicies"); } List<PolicyDef> policyDefs = new ArrayList<>(); for (String policy : policies) { PolicyDef policyDef = parsePolicy(policy); if (policyDef != null) { policyDefs.add(policyDef); } } if (isDebugEnabled) { LOG.debug("<== PolicyParser parsePolicies"); LOG.debug(policyDefs.toString()); } return policyDefs; } private PolicyDef parsePolicy(String data) { if (isDebugEnabled) { LOG.debug("==> PolicyParser parsePolicy"); } PolicyDef def = null; String[] props = data.split(";;"); if (props.length < RESOURCE_INDEX) { LOG.warn("skipping invalid policy line: {}", data); } else { def = new PolicyDef(); def.setPolicyName(props[POLICYNAME]); parseUsers(props[USER_INDEX], def); parseGroups(props[GROUP_INDEX], def); parseResources(props[RESOURCE_INDEX], def); if (isDebugEnabled) { LOG.debug("policy successfully parsed!!!"); LOG.debug("<== PolicyParser parsePolicy"); } } return def; } private boolean validateEntity(String entity) { if (isDebugEnabled) { LOG.debug("==> PolicyParser validateEntity"); } boolean isValidEntity = Pattern.matches("(.+:.+)+", entity); boolean isEmpty = entity.isEmpty(); if (!isValidEntity || isEmpty) { if (isDebugEnabled) { LOG.debug("group/user/resource not properly define in Policy"); LOG.debug("<== PolicyParser validateEntity"); } return false; } else { if (isDebugEnabled) { LOG.debug("<== PolicyParser validateEntity"); } return true; } } private void parseUsers(String usersDef, PolicyDef def) { if (isDebugEnabled) { LOG.debug("==> PolicyParser parseUsers"); } String[] users = usersDef.split(","); String[] userAndRole = null; Map<String, List<AtlasActionTypes>> usersMap = new HashMap<>(); if (validateEntity(usersDef)) { for (String user : users) { if (!Pattern.matches("(.+:.+)+", user)) { continue; } userAndRole = user.split(":"); if (def.getUsers() != null) { usersMap = def.getUsers(); } List<AtlasActionTypes> userAutorities = getListOfAutorities(userAndRole[USER_AUTHORITIES]); usersMap.put(userAndRole[USERNAME], userAutorities); def.setUsers(usersMap); } } else { def.setUsers(usersMap); } if (isDebugEnabled) { LOG.debug("<== PolicyParser parseUsers"); } } private void parseGroups(String groupsDef, PolicyDef def) { if (isDebugEnabled) { LOG.debug("==> PolicyParser parseGroups"); } String[] groups = groupsDef.split("\\,"); String[] groupAndRole = null; Map<String, List<AtlasActionTypes>> groupsMap = new HashMap<>(); if (validateEntity(groupsDef.trim())) { for (String group : groups) { if (!Pattern.matches("(.+:.+)+", group)) { continue; } groupAndRole = group.split("[:]"); if (def.getGroups() != null) { groupsMap = def.getGroups(); } List<AtlasActionTypes> groupAutorities = getListOfAutorities(groupAndRole[GROUP_AUTHORITIES]); groupsMap.put(groupAndRole[GROUPNAME], groupAutorities); def.setGroups(groupsMap); } } else { def.setGroups(groupsMap); } if (isDebugEnabled) { LOG.debug("<== PolicyParser parseGroups"); } } private void parseResources(String resourceDef, PolicyDef def) { if (isDebugEnabled) { LOG.debug("==> PolicyParser parseResources"); } String[] resources = resourceDef.split(","); String[] resourceTypeAndName = null; Map<AtlasResourceTypes, List<String>> resourcesMap = new HashMap<>(); if (validateEntity(resourceDef)) { for (String resource : resources) { if (!Pattern.matches("(.+:.+)+", resource)) { continue; } resourceTypeAndName = resource.split("[:]"); if (def.getResources() != null) { resourcesMap = def.getResources(); } AtlasResourceTypes resourceType = null; String type = resourceTypeAndName[RESOURCE_TYPE].toUpperCase(); if (type.equalsIgnoreCase("ENTITY")) { resourceType = AtlasResourceTypes.ENTITY; } else if (type.equalsIgnoreCase("OPERATION")) { resourceType = AtlasResourceTypes.OPERATION; } else if (type.equalsIgnoreCase("TYPE")) { resourceType = AtlasResourceTypes.TYPE; } else if (type.equalsIgnoreCase("TAXONOMY")) { resourceType = AtlasResourceTypes.TAXONOMY; } else if (type.equalsIgnoreCase("TERM")) { resourceType = AtlasResourceTypes.TERM; } else if (type.equalsIgnoreCase("RELATIONSHIP")) { resourceType = AtlasResourceTypes.RELATIONSHIP; } else { Log.warn(type + " is invalid resource please check PolicyStore file"); continue; } List<String> resourceList = resourcesMap.get(resourceType); if (resourceList == null) { resourceList = new ArrayList<>(); } resourceList.add(resourceTypeAndName[RESOURCE_NAME]); resourcesMap.put(resourceType, resourceList); def.setResources(resourcesMap); } } else { def.setResources(resourcesMap); } if (isDebugEnabled) { LOG.debug("<== PolicyParser parseResources"); } } } <|start_filename|>intg/src/test/java/org/apache/atlas/TestUtilsV2.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import org.apache.atlas.model.instance.AtlasEntity; import org.apache.atlas.model.instance.AtlasEntity.AtlasEntitiesWithExtInfo; import org.apache.atlas.model.instance.AtlasEntity.AtlasEntityWithExtInfo; import org.apache.atlas.model.instance.AtlasObjectId; import org.apache.atlas.model.instance.AtlasStruct; import org.apache.atlas.model.typedef.AtlasBaseTypeDef; import org.apache.atlas.model.typedef.AtlasClassificationDef; import org.apache.atlas.model.typedef.AtlasEntityDef; import org.apache.atlas.model.typedef.AtlasEnumDef; import org.apache.atlas.model.typedef.AtlasEnumDef.AtlasEnumElementDef; import org.apache.atlas.model.typedef.AtlasStructDef; import org.apache.atlas.model.typedef.AtlasStructDef.AtlasAttributeDef; import org.apache.atlas.model.typedef.AtlasStructDef.AtlasAttributeDef.Cardinality; import org.apache.atlas.model.typedef.AtlasStructDef.AtlasConstraintDef; import org.apache.atlas.model.typedef.AtlasTypesDef; import org.apache.atlas.type.AtlasTypeUtil; import org.apache.commons.lang.RandomStringUtils; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import static org.apache.atlas.type.AtlasTypeUtil.createStructTypeDef; /** * Test utility class. */ public final class TestUtilsV2 { public static final long TEST_DATE_IN_LONG = 1418265358440L; private static AtomicInteger seq = new AtomicInteger(); private TestUtilsV2() { } /** * Class Hierarchy is: * Department(name : String, employees : Array[Person]) * Person(name : String, department : Department, manager : Manager) * Manager(subordinates : Array[Person]) extends Person * <p/> * Persons can have SecurityClearance(level : Int) clearance. */ public static AtlasTypesDef defineDeptEmployeeTypes() { String _description = "_description"; AtlasEnumDef orgLevelEnum = new AtlasEnumDef("OrgLevel", "OrgLevel"+_description, "1.0", Arrays.asList( new AtlasEnumElementDef("L1", "Element"+_description, 1), new AtlasEnumElementDef("L2", "Element"+_description, 2) )); AtlasStructDef addressDetails = createStructTypeDef("Address", "Address"+_description, AtlasTypeUtil.createRequiredAttrDef("street", "string"), AtlasTypeUtil.createRequiredAttrDef("city", "string")); AtlasEntityDef deptTypeDef = AtlasTypeUtil.createClassTypeDef(DEPARTMENT_TYPE, "Department"+_description, ImmutableSet.<String>of(), AtlasTypeUtil.createUniqueRequiredAttrDef("name", "string"), new AtlasAttributeDef("employees", String.format("array<%s>", "Employee"), true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, new ArrayList<AtlasStructDef.AtlasConstraintDef>() {{ add(new AtlasStructDef.AtlasConstraintDef(AtlasConstraintDef.CONSTRAINT_TYPE_OWNED_REF)); }})); AtlasEntityDef personTypeDef = AtlasTypeUtil.createClassTypeDef("Person", "Person"+_description, ImmutableSet.<String>of(), AtlasTypeUtil.createUniqueRequiredAttrDef("name", "string"), AtlasTypeUtil.createOptionalAttrDef("address", "Address"), AtlasTypeUtil.createOptionalAttrDef("birthday", "date"), AtlasTypeUtil.createOptionalAttrDef("hasPets", "boolean"), AtlasTypeUtil.createOptionalAttrDef("numberOfCars", "byte"), AtlasTypeUtil.createOptionalAttrDef("houseNumber", "short"), AtlasTypeUtil.createOptionalAttrDef("carMileage", "int"), AtlasTypeUtil.createOptionalAttrDef("age", "float"), AtlasTypeUtil.createOptionalAttrDef("numberOfStarsEstimate", "biginteger"), AtlasTypeUtil.createOptionalAttrDef("approximationOfPi", "bigdecimal") ); AtlasEntityDef employeeTypeDef = AtlasTypeUtil.createClassTypeDef("Employee", "Employee"+_description, ImmutableSet.of("Person"), AtlasTypeUtil.createOptionalAttrDef("orgLevel", "OrgLevel"), new AtlasAttributeDef("department", "Department", false, AtlasAttributeDef.Cardinality.SINGLE, 1, 1, false, false, new ArrayList<AtlasConstraintDef>()), new AtlasAttributeDef("manager", "Manager", true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, new ArrayList<AtlasConstraintDef>() {{ add(new AtlasConstraintDef( AtlasConstraintDef.CONSTRAINT_TYPE_INVERSE_REF, new HashMap<String, Object>() {{ put(AtlasConstraintDef.CONSTRAINT_PARAM_ATTRIBUTE, "subordinates"); }})); }}), new AtlasAttributeDef("mentor", EMPLOYEE_TYPE, true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), AtlasTypeUtil.createOptionalAttrDef("shares", "long"), AtlasTypeUtil.createOptionalAttrDef("salary", "double") ); employeeTypeDef.getAttribute("department").addConstraint( new AtlasConstraintDef( AtlasConstraintDef.CONSTRAINT_TYPE_INVERSE_REF, new HashMap<String, Object>() {{ put(AtlasConstraintDef.CONSTRAINT_PARAM_ATTRIBUTE, "employees"); }})); AtlasEntityDef managerTypeDef = AtlasTypeUtil.createClassTypeDef("Manager", "Manager"+_description, ImmutableSet.of("Employee"), new AtlasAttributeDef("subordinates", String.format("array<%s>", "Employee"), false, AtlasAttributeDef.Cardinality.SET, 1, 10, false, false, Collections.<AtlasConstraintDef>emptyList())); AtlasClassificationDef securityClearanceTypeDef = AtlasTypeUtil.createTraitTypeDef("SecurityClearance", "SecurityClearance"+_description, ImmutableSet.<String>of(), AtlasTypeUtil.createRequiredAttrDef("level", "int")); return new AtlasTypesDef(ImmutableList.of(orgLevelEnum), ImmutableList.of(addressDetails), ImmutableList.of(securityClearanceTypeDef), ImmutableList.of(deptTypeDef, personTypeDef, employeeTypeDef, managerTypeDef)); } public static AtlasTypesDef defineInverseReferenceTestTypes() { AtlasEntityDef aDef = AtlasTypeUtil.createClassTypeDef("A", ImmutableSet.<String>of(), AtlasTypeUtil.createUniqueRequiredAttrDef("name", "string"), new AtlasAttributeDef("b", "B", true, Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), // 1-1 new AtlasAttributeDef("oneB", "B", true, Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), // 1-* new AtlasAttributeDef("manyB", AtlasBaseTypeDef.getArrayTypeName("B"), true, Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), new AtlasAttributeDef("mapToB", AtlasBaseTypeDef.getMapTypeName("string", "B"), true, Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>singletonList(new AtlasConstraintDef( AtlasConstraintDef.CONSTRAINT_TYPE_INVERSE_REF, Collections.<String, Object>singletonMap(AtlasConstraintDef.CONSTRAINT_PARAM_ATTRIBUTE, "mappedFromA"))))); // *-* AtlasEntityDef bDef = AtlasTypeUtil.createClassTypeDef("B", ImmutableSet.<String>of(), AtlasTypeUtil.createUniqueRequiredAttrDef("name", "string"), new AtlasAttributeDef("a", "A", true, Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>singletonList(new AtlasConstraintDef( AtlasConstraintDef.CONSTRAINT_TYPE_INVERSE_REF, Collections.<String, Object>singletonMap(AtlasConstraintDef.CONSTRAINT_PARAM_ATTRIBUTE, "b")))), new AtlasAttributeDef("manyA", AtlasBaseTypeDef.getArrayTypeName("A"), true, Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>singletonList(new AtlasConstraintDef( AtlasConstraintDef.CONSTRAINT_TYPE_INVERSE_REF, Collections.<String, Object>singletonMap(AtlasConstraintDef.CONSTRAINT_PARAM_ATTRIBUTE, "oneB")))), new AtlasAttributeDef("manyToManyA", AtlasBaseTypeDef.getArrayTypeName("A"), true, Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>singletonList(new AtlasConstraintDef( AtlasConstraintDef.CONSTRAINT_TYPE_INVERSE_REF, Collections.<String, Object>singletonMap(AtlasConstraintDef.CONSTRAINT_PARAM_ATTRIBUTE, "manyB")))), new AtlasAttributeDef("mappedFromA", "A", true, Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList())); return new AtlasTypesDef(ImmutableList.<AtlasEnumDef>of(), ImmutableList.<AtlasStructDef>of(), ImmutableList.<AtlasClassificationDef>of(), ImmutableList.<AtlasEntityDef>of(aDef, bDef)); } public static AtlasTypesDef defineValidUpdatedDeptEmployeeTypes() { String _description = "_description_updated"; AtlasEnumDef orgLevelEnum = new AtlasEnumDef("OrgLevel", "OrgLevel"+_description, "1.0", Arrays.asList( new AtlasEnumElementDef("L1", "Element"+ _description, 1), new AtlasEnumElementDef("L2", "Element"+ _description, 2) )); AtlasStructDef addressDetails = createStructTypeDef("Address", "Address"+_description, AtlasTypeUtil.createRequiredAttrDef("street", "string"), AtlasTypeUtil.createRequiredAttrDef("city", "string"), AtlasTypeUtil.createOptionalAttrDef("zip", "int")); AtlasEntityDef deptTypeDef = AtlasTypeUtil.createClassTypeDef(DEPARTMENT_TYPE, "Department"+_description, ImmutableSet.<String>of(), AtlasTypeUtil.createUniqueRequiredAttrDef("name", "string"), AtlasTypeUtil.createOptionalAttrDef("dep-code", "string"), new AtlasAttributeDef("employees", String.format("array<%s>", "Employee"), true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, new ArrayList<AtlasStructDef.AtlasConstraintDef>() {{ add(new AtlasStructDef.AtlasConstraintDef(AtlasConstraintDef.CONSTRAINT_TYPE_OWNED_REF)); }})); AtlasEntityDef personTypeDef = AtlasTypeUtil.createClassTypeDef("Person", "Person"+_description, ImmutableSet.<String>of(), AtlasTypeUtil.createUniqueRequiredAttrDef("name", "string"), AtlasTypeUtil.createOptionalAttrDef("email", "string"), AtlasTypeUtil.createOptionalAttrDef("address", "Address"), AtlasTypeUtil.createOptionalAttrDef("birthday", "date"), AtlasTypeUtil.createOptionalAttrDef("hasPets", "boolean"), AtlasTypeUtil.createOptionalAttrDef("numberOfCars", "byte"), AtlasTypeUtil.createOptionalAttrDef("houseNumber", "short"), AtlasTypeUtil.createOptionalAttrDef("carMileage", "int"), AtlasTypeUtil.createOptionalAttrDef("age", "float"), AtlasTypeUtil.createOptionalAttrDef("numberOfStarsEstimate", "biginteger"), AtlasTypeUtil.createOptionalAttrDef("approximationOfPi", "bigdecimal") ); AtlasEntityDef employeeTypeDef = AtlasTypeUtil.createClassTypeDef("Employee", "Employee"+_description, ImmutableSet.of("Person"), AtlasTypeUtil.createOptionalAttrDef("orgLevel", "OrgLevel"), AtlasTypeUtil.createOptionalAttrDef("empCode", "string"), new AtlasAttributeDef("department", "Department", false, AtlasAttributeDef.Cardinality.SINGLE, 1, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), new AtlasAttributeDef("manager", "Manager", true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, new ArrayList<AtlasConstraintDef>() {{ add(new AtlasConstraintDef( AtlasConstraintDef.CONSTRAINT_TYPE_INVERSE_REF, new HashMap<String, Object>() {{ put(AtlasConstraintDef.CONSTRAINT_PARAM_ATTRIBUTE, "subordinates"); }})); }}), new AtlasAttributeDef("mentor", EMPLOYEE_TYPE, true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), AtlasTypeUtil.createOptionalAttrDef("shares", "long"), AtlasTypeUtil.createOptionalAttrDef("salary", "double") ); AtlasEntityDef managerTypeDef = AtlasTypeUtil.createClassTypeDef("Manager", "Manager"+_description, ImmutableSet.of("Employee"), new AtlasAttributeDef("subordinates", String.format("array<%s>", "Employee"), false, AtlasAttributeDef.Cardinality.SET, 1, 10, false, false, Collections.<AtlasConstraintDef>emptyList())); AtlasClassificationDef securityClearanceTypeDef = AtlasTypeUtil.createTraitTypeDef("SecurityClearance", "SecurityClearance"+_description, ImmutableSet.<String>of(), AtlasTypeUtil.createRequiredAttrDef("level", "int")); return new AtlasTypesDef(ImmutableList.of(orgLevelEnum), ImmutableList.of(addressDetails), ImmutableList.of(securityClearanceTypeDef), ImmutableList.of(deptTypeDef, personTypeDef, employeeTypeDef, managerTypeDef)); } public static AtlasTypesDef defineInvalidUpdatedDeptEmployeeTypes() { String _description = "_description_updated"; // Test ordinal changes AtlasEnumDef orgLevelEnum = new AtlasEnumDef("OrgLevel", "OrgLevel"+_description, "1.0", Arrays.asList( new AtlasEnumElementDef("L2", "Element"+ _description, 1), new AtlasEnumElementDef("L1", "Element"+ _description, 2), new AtlasEnumElementDef("L3", "Element"+ _description, 3) )); AtlasStructDef addressDetails = createStructTypeDef("Address", "Address"+_description, AtlasTypeUtil.createRequiredAttrDef("street", "string"), AtlasTypeUtil.createRequiredAttrDef("city", "string"), AtlasTypeUtil.createRequiredAttrDef("zip", "int")); AtlasEntityDef deptTypeDef = AtlasTypeUtil.createClassTypeDef(DEPARTMENT_TYPE, "Department"+_description, ImmutableSet.<String>of(), AtlasTypeUtil.createRequiredAttrDef("name", "string"), AtlasTypeUtil.createRequiredAttrDef("dep-code", "string"), new AtlasAttributeDef("employees", String.format("array<%s>", "Person"), true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, new ArrayList<AtlasStructDef.AtlasConstraintDef>() {{ add(new AtlasStructDef.AtlasConstraintDef(AtlasConstraintDef.CONSTRAINT_TYPE_OWNED_REF)); }})); AtlasEntityDef personTypeDef = AtlasTypeUtil.createClassTypeDef("Person", "Person"+_description, ImmutableSet.<String>of(), AtlasTypeUtil.createRequiredAttrDef("name", "string"), AtlasTypeUtil.createRequiredAttrDef("emp-code", "string"), AtlasTypeUtil.createOptionalAttrDef("orgLevel", "OrgLevel"), AtlasTypeUtil.createOptionalAttrDef("address", "Address"), new AtlasAttributeDef("department", "Department", false, AtlasAttributeDef.Cardinality.SINGLE, 1, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), new AtlasAttributeDef("manager", "Manager", true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, new ArrayList<AtlasConstraintDef>() {{ add(new AtlasConstraintDef( AtlasConstraintDef.CONSTRAINT_TYPE_INVERSE_REF, new HashMap<String, Object>() {{ put(AtlasConstraintDef.CONSTRAINT_PARAM_ATTRIBUTE, "subordinates"); }})); }}), new AtlasAttributeDef("mentor", "Person", true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), AtlasTypeUtil.createOptionalAttrDef("birthday", "date"), AtlasTypeUtil.createOptionalAttrDef("hasPets", "boolean"), AtlasTypeUtil.createOptionalAttrDef("numberOfCars", "byte"), AtlasTypeUtil.createOptionalAttrDef("houseNumber", "short"), AtlasTypeUtil.createOptionalAttrDef("carMileage", "int"), AtlasTypeUtil.createOptionalAttrDef("shares", "long"), AtlasTypeUtil.createOptionalAttrDef("salary", "double"), AtlasTypeUtil.createRequiredAttrDef("age", "float"), AtlasTypeUtil.createOptionalAttrDef("numberOfStarsEstimate", "biginteger"), AtlasTypeUtil.createOptionalAttrDef("approximationOfPi", "bigdecimal") ); return new AtlasTypesDef(ImmutableList.of(orgLevelEnum), ImmutableList.of(addressDetails), ImmutableList.<AtlasClassificationDef>of(), ImmutableList.of(deptTypeDef, personTypeDef)); } public static final String DEPARTMENT_TYPE = "Department"; public static final String EMPLOYEE_TYPE = "Employee"; public static final String MANAGER_TYPE = "Manager"; public static final String ADDRESS_TYPE = "Address"; public static AtlasEntitiesWithExtInfo createDeptEg2() { AtlasEntitiesWithExtInfo entitiesWithExtInfo = new AtlasEntitiesWithExtInfo(); /******* Department - HR *******/ AtlasEntity hrDept = new AtlasEntity(DEPARTMENT_TYPE, "name", "hr"); AtlasObjectId hrDeptId = AtlasTypeUtil.getAtlasObjectId(hrDept); /******* Address Entities *******/ AtlasStruct janeAddr = new AtlasStruct(ADDRESS_TYPE); janeAddr.setAttribute("street", "Great America Parkway"); janeAddr.setAttribute("city", "Santa Clara"); AtlasStruct juliusAddr = new AtlasStruct(ADDRESS_TYPE); juliusAddr.setAttribute("street", "Madison Ave"); juliusAddr.setAttribute("city", "Newtonville"); AtlasStruct maxAddr = new AtlasStruct(ADDRESS_TYPE); maxAddr.setAttribute("street", "Ripley St"); maxAddr.setAttribute("city", "Newton"); AtlasStruct johnAddr = new AtlasStruct(ADDRESS_TYPE); johnAddr.setAttribute("street", "Stewart Drive"); johnAddr.setAttribute("city", "Sunnyvale"); /******* Manager - Jane (John and Max subordinates) *******/ AtlasEntity jane = new AtlasEntity(MANAGER_TYPE); AtlasObjectId janeId = AtlasTypeUtil.getAtlasObjectId(jane); jane.setAttribute("name", "Jane"); jane.setAttribute("department", hrDeptId); jane.setAttribute("address", janeAddr); /******* Manager - Julius (no subordinates) *******/ AtlasEntity julius = new AtlasEntity(MANAGER_TYPE); AtlasObjectId juliusId = AtlasTypeUtil.getAtlasObjectId(julius); julius.setAttribute("name", "Julius"); julius.setAttribute("department", hrDeptId); julius.setAttribute("address", juliusAddr); julius.setAttribute("subordinates", ImmutableList.of()); /******* Employee - Max (Manager: Jane, Mentor: Julius) *******/ AtlasEntity max = new AtlasEntity(EMPLOYEE_TYPE); AtlasObjectId maxId = AtlasTypeUtil.getAtlasObjectId(max); max.setAttribute("name", "Max"); max.setAttribute("department", hrDeptId); max.setAttribute("address", maxAddr); max.setAttribute("manager", janeId); max.setAttribute("mentor", juliusId); max.setAttribute("birthday",new Date(1979, 3, 15)); max.setAttribute("hasPets", true); max.setAttribute("age", 36); max.setAttribute("numberOfCars", 2); max.setAttribute("houseNumber", 17); max.setAttribute("carMileage", 13); max.setAttribute("shares", Long.MAX_VALUE); max.setAttribute("salary", Double.MAX_VALUE); max.setAttribute("numberOfStarsEstimate", new BigInteger("1000000000000000000000000000000")); max.setAttribute("approximationOfPi", new BigDecimal("3.1415926535897932")); /******* Employee - John (Manager: Jane, Mentor: Max) *******/ AtlasEntity john = new AtlasEntity(EMPLOYEE_TYPE); AtlasObjectId johnId = AtlasTypeUtil.getAtlasObjectId(john); john.setAttribute("name", "John"); john.setAttribute("department", hrDeptId); john.setAttribute("address", johnAddr); john.setAttribute("manager", janeId); john.setAttribute("mentor", maxId); john.setAttribute("birthday",new Date(1950, 5, 15)); john.setAttribute("hasPets", true); john.setAttribute("numberOfCars", 1); john.setAttribute("houseNumber", 153); john.setAttribute("carMileage", 13364); john.setAttribute("shares", 15000); john.setAttribute("salary", 123345.678); john.setAttribute("age", 50); john.setAttribute("numberOfStarsEstimate", new BigInteger("1000000000000000000000")); john.setAttribute("approximationOfPi", new BigDecimal("3.141592653589793238462643383279502884197169399375105820974944592307816406286")); jane.setAttribute("subordinates", ImmutableList.of(johnId, maxId)); hrDept.setAttribute("employees", ImmutableList.of(janeId, juliusId, maxId, johnId)); entitiesWithExtInfo.addEntity(hrDept); entitiesWithExtInfo.addEntity(jane); entitiesWithExtInfo.addEntity(julius); entitiesWithExtInfo.addEntity(max); entitiesWithExtInfo.addEntity(john); return entitiesWithExtInfo; } public static Map<String, AtlasEntity> createDeptEg1() { Map<String, AtlasEntity> deptEmpEntities = new HashMap<>(); AtlasEntity hrDept = new AtlasEntity(DEPARTMENT_TYPE); AtlasEntity john = new AtlasEntity(EMPLOYEE_TYPE); AtlasEntity jane = new AtlasEntity("Manager"); AtlasEntity johnAddr = new AtlasEntity("Address"); AtlasEntity janeAddr = new AtlasEntity("Address"); AtlasEntity julius = new AtlasEntity("Manager"); AtlasEntity juliusAddr = new AtlasEntity("Address"); AtlasEntity max = new AtlasEntity(EMPLOYEE_TYPE); AtlasEntity maxAddr = new AtlasEntity("Address"); AtlasObjectId deptId = new AtlasObjectId(hrDept.getGuid(), hrDept.getTypeName()); hrDept.setAttribute("name", "hr"); john.setAttribute("name", "John"); john.setAttribute("department", deptId); johnAddr.setAttribute("street", "Stewart Drive"); johnAddr.setAttribute("city", "Sunnyvale"); john.setAttribute("address", johnAddr); john.setAttribute("birthday",new Date(1950, 5, 15)); john.setAttribute("hasPets", true); john.setAttribute("numberOfCars", 1); john.setAttribute("houseNumber", 153); john.setAttribute("carMileage", 13364); john.setAttribute("shares", 15000); john.setAttribute("salary", 123345.678); john.setAttribute("age", 50); john.setAttribute("numberOfStarsEstimate", new BigInteger("1000000000000000000000")); john.setAttribute("approximationOfPi", new BigDecimal("3.141592653589793238462643383279502884197169399375105820974944592307816406286")); jane.setAttribute("name", "Jane"); jane.setAttribute("department", deptId); janeAddr.setAttribute("street", "Great America Parkway"); janeAddr.setAttribute("city", "Santa Clara"); jane.setAttribute("address", janeAddr); janeAddr.setAttribute("street", "Great America Parkway"); julius.setAttribute("name", "Julius"); julius.setAttribute("department", deptId); juliusAddr.setAttribute("street", "Madison Ave"); juliusAddr.setAttribute("city", "Newtonville"); julius.setAttribute("address", juliusAddr); julius.setAttribute("subordinates", ImmutableList.of()); AtlasObjectId janeId = AtlasTypeUtil.getAtlasObjectId(jane); AtlasObjectId johnId = AtlasTypeUtil.getAtlasObjectId(john); //TODO - Change to MANAGER_TYPE for JULIUS AtlasObjectId maxId = new AtlasObjectId(max.getGuid(), EMPLOYEE_TYPE); AtlasObjectId juliusId = new AtlasObjectId(julius.getGuid(), EMPLOYEE_TYPE); max.setAttribute("name", "Max"); max.setAttribute("department", deptId); maxAddr.setAttribute("street", "Ripley St"); maxAddr.setAttribute("city", "Newton"); max.setAttribute("address", maxAddr); max.setAttribute("manager", janeId); max.setAttribute("mentor", juliusId); max.setAttribute("birthday",new Date(1979, 3, 15)); max.setAttribute("hasPets", true); max.setAttribute("age", 36); max.setAttribute("numberOfCars", 2); max.setAttribute("houseNumber", 17); max.setAttribute("carMileage", 13); max.setAttribute("shares", Long.MAX_VALUE); max.setAttribute("salary", Double.MAX_VALUE); max.setAttribute("numberOfStarsEstimate", new BigInteger("1000000000000000000000000000000")); max.setAttribute("approximationOfPi", new BigDecimal("3.1415926535897932")); john.setAttribute("manager", janeId); john.setAttribute("mentor", maxId); hrDept.setAttribute("employees", ImmutableList.of(johnId, janeId, juliusId, maxId)); jane.setAttribute("subordinates", ImmutableList.of(johnId, maxId)); deptEmpEntities.put(jane.getGuid(), jane); deptEmpEntities.put(john.getGuid(), john); deptEmpEntities.put(julius.getGuid(), julius); deptEmpEntities.put(max.getGuid(), max); deptEmpEntities.put(deptId.getGuid(), hrDept); return deptEmpEntities; } public static final String DATABASE_TYPE = "hive_database"; public static final String DATABASE_NAME = "foo"; public static final String TABLE_TYPE = "hive_table"; public static final String PROCESS_TYPE = "hive_process"; public static final String COLUMN_TYPE = "column_type"; public static final String TABLE_NAME = "bar"; public static final String CLASSIFICATION = "classification"; public static final String PII = "PII"; public static final String PHI = "PHI"; public static final String SUPER_TYPE_NAME = "Base"; public static final String STORAGE_DESC_TYPE = "hive_storagedesc"; public static final String PARTITION_STRUCT_TYPE = "partition_struct_type"; public static final String PARTITION_CLASS_TYPE = "partition_class_type"; public static final String SERDE_TYPE = "serdeType"; public static final String COLUMNS_MAP = "columnsMap"; public static final String COLUMNS_ATTR_NAME = "columns"; public static final String NAME = "name"; public static AtlasTypesDef simpleType(){ AtlasEntityDef superTypeDefinition = AtlasTypeUtil.createClassTypeDef("h_type", ImmutableSet.<String>of(), AtlasTypeUtil.createOptionalAttrDef("attr", "string")); AtlasStructDef structTypeDefinition = new AtlasStructDef("s_type", "structType", "1.0", Arrays.asList(AtlasTypeUtil.createRequiredAttrDef("name", "string"))); AtlasClassificationDef traitTypeDefinition = AtlasTypeUtil.createTraitTypeDef("t_type", "traitType", ImmutableSet.<String>of()); AtlasEnumDef enumTypeDefinition = new AtlasEnumDef("e_type", "enumType", "1.0", Arrays.asList(new AtlasEnumElementDef("ONE", "Element Description", 1))); return AtlasTypeUtil.getTypesDef(ImmutableList.of(enumTypeDefinition), ImmutableList.of(structTypeDefinition), ImmutableList.of(traitTypeDefinition), ImmutableList.of(superTypeDefinition)); } public static AtlasTypesDef simpleTypeUpdated(){ AtlasEntityDef superTypeDefinition = AtlasTypeUtil.createClassTypeDef("h_type", ImmutableSet.<String>of(), AtlasTypeUtil.createOptionalAttrDef("attr", "string")); AtlasEntityDef newSuperTypeDefinition = AtlasTypeUtil.createClassTypeDef("new_h_type", ImmutableSet.<String>of(), AtlasTypeUtil.createOptionalAttrDef("attr", "string")); AtlasStructDef structTypeDefinition = new AtlasStructDef("s_type", "structType", "1.0", Arrays.asList(AtlasTypeUtil.createRequiredAttrDef("name", "string"))); AtlasClassificationDef traitTypeDefinition = AtlasTypeUtil.createTraitTypeDef("t_type", "traitType", ImmutableSet.<String>of()); AtlasEnumDef enumTypeDefinition = new AtlasEnumDef("e_type", "enumType", Arrays.asList(new AtlasEnumElementDef("ONE", "Element Description", 1))); return AtlasTypeUtil.getTypesDef(ImmutableList.of(enumTypeDefinition), ImmutableList.of(structTypeDefinition), ImmutableList.of(traitTypeDefinition), ImmutableList.of(superTypeDefinition, newSuperTypeDefinition)); } public static AtlasTypesDef simpleTypeUpdatedDiff() { AtlasEntityDef newSuperTypeDefinition = AtlasTypeUtil.createClassTypeDef("new_h_type", ImmutableSet.<String>of(), AtlasTypeUtil.createOptionalAttrDef("attr", "string")); return AtlasTypeUtil.getTypesDef(ImmutableList.<AtlasEnumDef>of(), ImmutableList.<AtlasStructDef>of(), ImmutableList.<AtlasClassificationDef>of(), ImmutableList.of(newSuperTypeDefinition)); } public static AtlasTypesDef defineHiveTypes() { String _description = "_description"; AtlasEntityDef superTypeDefinition = AtlasTypeUtil.createClassTypeDef(SUPER_TYPE_NAME, "SuperType_description", ImmutableSet.<String>of(), AtlasTypeUtil.createOptionalAttrDef("namespace", "string"), AtlasTypeUtil.createOptionalAttrDef("cluster", "string"), AtlasTypeUtil.createOptionalAttrDef("colo", "string")); AtlasEntityDef databaseTypeDefinition = AtlasTypeUtil.createClassTypeDef(DATABASE_TYPE, DATABASE_TYPE + _description,ImmutableSet.of(SUPER_TYPE_NAME), AtlasTypeUtil.createUniqueRequiredAttrDef(NAME, "string"), AtlasTypeUtil.createOptionalAttrDef("isReplicated", "boolean"), AtlasTypeUtil.createOptionalAttrDef("created", "string"), AtlasTypeUtil.createOptionalAttrDef("parameters", "map<string,string>"), AtlasTypeUtil.createRequiredAttrDef("description", "string")); AtlasStructDef structTypeDefinition = new AtlasStructDef("serdeType", "serdeType" + _description, "1.0", Arrays.asList( AtlasTypeUtil.createRequiredAttrDef("name", "string"), AtlasTypeUtil.createRequiredAttrDef("serde", "string"), AtlasTypeUtil.createOptionalAttrDef("description", "string"))); AtlasEnumElementDef values[] = { new AtlasEnumElementDef("MANAGED", "Element Description", 1), new AtlasEnumElementDef("EXTERNAL", "Element Description", 2)}; AtlasEnumDef enumTypeDefinition = new AtlasEnumDef("tableType", "tableType" + _description, "1.0", Arrays.asList(values)); AtlasEntityDef columnsDefinition = AtlasTypeUtil.createClassTypeDef(COLUMN_TYPE, COLUMN_TYPE + "_description", ImmutableSet.<String>of(), AtlasTypeUtil.createUniqueRequiredAttrDef("name", "string"), AtlasTypeUtil.createRequiredAttrDef("type", "string"), AtlasTypeUtil.createOptionalAttrDef("description", "string"), new AtlasAttributeDef("table", TABLE_TYPE, true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, new ArrayList<AtlasStructDef.AtlasConstraintDef>() {{ add(new AtlasStructDef.AtlasConstraintDef( AtlasConstraintDef.CONSTRAINT_TYPE_INVERSE_REF, new HashMap<String, Object>() {{ put(AtlasConstraintDef.CONSTRAINT_PARAM_ATTRIBUTE, "columns"); }})); }}) ); AtlasStructDef partitionDefinition = new AtlasStructDef("partition_struct_type", "partition_struct_type" + _description, "1.0", Arrays.asList(AtlasTypeUtil.createRequiredAttrDef("name", "string"))); AtlasAttributeDef[] attributeDefinitions = new AtlasAttributeDef[]{ new AtlasAttributeDef("location", "string", true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), new AtlasAttributeDef("inputFormat", "string", true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), new AtlasAttributeDef("outputFormat", "string", true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), new AtlasAttributeDef("compressed", "boolean", false, AtlasAttributeDef.Cardinality.SINGLE, 1, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), new AtlasAttributeDef("numBuckets", "int", true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), }; AtlasEntityDef storageDescClsDef = new AtlasEntityDef(STORAGE_DESC_TYPE, STORAGE_DESC_TYPE + _description, "1.0", Arrays.asList(attributeDefinitions), ImmutableSet.of(SUPER_TYPE_NAME)); AtlasAttributeDef[] partClsAttributes = new AtlasAttributeDef[]{ new AtlasAttributeDef("values", "array<string>", true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), new AtlasAttributeDef("table", TABLE_TYPE, true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), new AtlasAttributeDef("createTime", "long", true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), new AtlasAttributeDef("lastAccessTime", "long", true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), new AtlasAttributeDef("sd", STORAGE_DESC_TYPE, false, AtlasAttributeDef.Cardinality.SINGLE, 1, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), new AtlasAttributeDef("columns", String.format("array<%s>", COLUMN_TYPE), true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), new AtlasAttributeDef("parameters", String.format("map<%s,%s>", "string", "string"), true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList())}; AtlasEntityDef partClsDef = new AtlasEntityDef("partition_class_type", "partition_class_type" + _description, "1.0", Arrays.asList(partClsAttributes), ImmutableSet.of(SUPER_TYPE_NAME)); AtlasEntityDef processClsType = new AtlasEntityDef(PROCESS_TYPE, PROCESS_TYPE + _description, "1.0", Arrays.asList(new AtlasAttributeDef("outputs", "array<" + TABLE_TYPE + ">", true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList())), ImmutableSet.<String>of()); AtlasEntityDef tableTypeDefinition = AtlasTypeUtil.createClassTypeDef(TABLE_TYPE, TABLE_TYPE + _description, ImmutableSet.of(SUPER_TYPE_NAME), AtlasTypeUtil.createUniqueRequiredAttrDef("name", "string"), AtlasTypeUtil.createOptionalAttrDef("description", "string"), AtlasTypeUtil.createRequiredAttrDef("type", "string"), AtlasTypeUtil.createOptionalAttrDef("created", "date"), // enum new AtlasAttributeDef("tableType", "tableType", false, AtlasAttributeDef.Cardinality.SINGLE, 1, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), // array of strings new AtlasAttributeDef("columnNames", String.format("array<%s>", "string"), true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), // array of classes new AtlasAttributeDef("columns", String.format("array<%s>", COLUMN_TYPE), true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, new ArrayList<AtlasStructDef.AtlasConstraintDef>() {{ add(new AtlasStructDef.AtlasConstraintDef(AtlasConstraintDef.CONSTRAINT_TYPE_OWNED_REF)); }}), // array of structs new AtlasAttributeDef("partitions", String.format("array<%s>", "partition_struct_type"), true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), // map of primitives new AtlasAttributeDef("parametersMap", String.format("map<%s,%s>", "string", "string"), true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), //map of classes - new AtlasAttributeDef(COLUMNS_MAP, String.format("map<%s,%s>", "string", COLUMN_TYPE), true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, new ArrayList<AtlasStructDef.AtlasConstraintDef>() {{ add(new AtlasStructDef.AtlasConstraintDef( AtlasConstraintDef.CONSTRAINT_TYPE_OWNED_REF)); }} ), //map of structs new AtlasAttributeDef("partitionsMap", String.format("map<%s,%s>", "string", "partition_struct_type"), true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), // struct reference new AtlasAttributeDef("serde1", "serdeType", true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), new AtlasAttributeDef("serde2", "serdeType", true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), // class reference new AtlasAttributeDef("database", DATABASE_TYPE, false, AtlasAttributeDef.Cardinality.SINGLE, 1, 1, false, false, Collections.<AtlasConstraintDef>emptyList()), //class reference as composite new AtlasAttributeDef("databaseComposite", DATABASE_TYPE, true, AtlasAttributeDef.Cardinality.SINGLE, 0, 1, false, false, new ArrayList<AtlasStructDef.AtlasConstraintDef>() {{ add(new AtlasStructDef.AtlasConstraintDef( AtlasConstraintDef.CONSTRAINT_TYPE_OWNED_REF)); }} )); AtlasClassificationDef piiTypeDefinition = AtlasTypeUtil.createTraitTypeDef(PII, PII + _description, ImmutableSet.<String>of()); AtlasClassificationDef classificationTypeDefinition = AtlasTypeUtil.createTraitTypeDef(CLASSIFICATION, CLASSIFICATION + _description, ImmutableSet.<String>of(), AtlasTypeUtil.createRequiredAttrDef("tag", "string")); AtlasClassificationDef fetlClassificationTypeDefinition = AtlasTypeUtil.createTraitTypeDef("fetl" + CLASSIFICATION, "fetl" + CLASSIFICATION + _description, ImmutableSet.of(CLASSIFICATION), AtlasTypeUtil.createRequiredAttrDef("tag", "string")); AtlasClassificationDef phiTypeDefinition = AtlasTypeUtil.createTraitTypeDef(PHI, PHI + _description, ImmutableSet.<String>of(), AtlasTypeUtil.createRequiredAttrDef("stringAttr", "string"), AtlasTypeUtil.createRequiredAttrDef("booleanAttr", "boolean"), AtlasTypeUtil.createRequiredAttrDef("integerAttr", "int")); return AtlasTypeUtil.getTypesDef(ImmutableList.of(enumTypeDefinition), ImmutableList.of(structTypeDefinition, partitionDefinition), ImmutableList.of(classificationTypeDefinition, fetlClassificationTypeDefinition, piiTypeDefinition, phiTypeDefinition), ImmutableList.of(superTypeDefinition, databaseTypeDefinition, columnsDefinition, tableTypeDefinition, storageDescClsDef, partClsDef, processClsType)); } public static final String randomString() { return RandomStringUtils.randomAlphanumeric(10); } public static AtlasEntity createDBEntity() { String dbName = RandomStringUtils.randomAlphanumeric(10); return createDBEntity(dbName); } public static AtlasEntity createDBEntity(String dbName) { AtlasEntity entity = new AtlasEntity(DATABASE_TYPE); entity.setAttribute(NAME, dbName); entity.setAttribute("description", "us db"); return entity; } public static AtlasEntityWithExtInfo createDBEntityV2() { AtlasEntity dbEntity = new AtlasEntity(DATABASE_TYPE); dbEntity.setAttribute(NAME, RandomStringUtils.randomAlphanumeric(10)); dbEntity.setAttribute("description", "us db"); return new AtlasEntityWithExtInfo(dbEntity); } public static AtlasEntity createTableEntity(AtlasEntity dbEntity) { String tableName = RandomStringUtils.randomAlphanumeric(10); return createTableEntity(dbEntity, tableName); } public static AtlasEntity createTableEntity(AtlasEntity dbEntity, String name) { AtlasEntity entity = new AtlasEntity(TABLE_TYPE); entity.setAttribute(NAME, name); entity.setAttribute("description", "random table"); entity.setAttribute("type", "type"); entity.setAttribute("tableType", "MANAGED"); entity.setAttribute("database", AtlasTypeUtil.getAtlasObjectId(dbEntity)); entity.setAttribute("created", new Date()); Map<String, Object> partAttributes = new HashMap<String, Object>() {{ put("name", "part0"); }}; final AtlasStruct partitionStruct = new AtlasStruct("partition_struct_type", partAttributes); entity.setAttribute("partitions", new ArrayList<AtlasStruct>() {{ add(partitionStruct); }}); entity.setAttribute("parametersMap", new java.util.HashMap<String, String>() {{ put("key1", "value1"); }}); return entity; } public static AtlasEntityWithExtInfo createTableEntityV2(AtlasEntity dbEntity) { AtlasEntity tblEntity = new AtlasEntity(TABLE_TYPE); tblEntity.setAttribute(NAME, RandomStringUtils.randomAlphanumeric(10)); tblEntity.setAttribute("description", "random table"); tblEntity.setAttribute("type", "type"); tblEntity.setAttribute("tableType", "MANAGED"); tblEntity.setAttribute("database", AtlasTypeUtil.getAtlasObjectId(dbEntity)); tblEntity.setAttribute("created", new Date()); final AtlasStruct partitionStruct = new AtlasStruct("partition_struct_type", "name", "part0"); tblEntity.setAttribute("partitions", new ArrayList<AtlasStruct>() {{ add(partitionStruct); }}); tblEntity.setAttribute("parametersMap", new java.util.HashMap<String, String>() {{ put("key1", "value1"); }}); AtlasEntityWithExtInfo ret = new AtlasEntityWithExtInfo(tblEntity); ret.addReferredEntity(dbEntity); return ret; } public static AtlasEntityWithExtInfo createprimitiveEntityV2() { AtlasEntity defaultprimitive = new AtlasEntity(createPrimitiveEntityDef()); defaultprimitive.setAttribute("name", "testname"); defaultprimitive.setAttribute("description","test"); defaultprimitive.setAttribute("check","check"); AtlasEntityWithExtInfo ret = new AtlasEntityWithExtInfo(defaultprimitive); return ret; } public static AtlasEntityDef createPrimitiveEntityDef() { AtlasEntityDef newtestEntityDef = new AtlasEntityDef("newtest"); AtlasAttributeDef attrName = new AtlasAttributeDef("name", AtlasBaseTypeDef.ATLAS_TYPE_STRING); AtlasAttributeDef attrDescription = new AtlasAttributeDef("description", AtlasBaseTypeDef.ATLAS_TYPE_STRING); attrDescription.setIsOptional(false); AtlasAttributeDef attrcheck = new AtlasAttributeDef("check", AtlasBaseTypeDef.ATLAS_TYPE_STRING); attrcheck.setIsOptional(true); AtlasAttributeDef attrSourceCode = new AtlasAttributeDef("sourcecode", AtlasBaseTypeDef.ATLAS_TYPE_STRING); attrSourceCode.setDefaultValue("Hello World"); attrSourceCode.setIsOptional(true); AtlasAttributeDef attrCost = new AtlasAttributeDef("Cost", AtlasBaseTypeDef.ATLAS_TYPE_INT); attrCost.setIsOptional(true); attrCost.setDefaultValue("30"); AtlasAttributeDef attrDiskUsage = new AtlasAttributeDef("diskUsage", AtlasBaseTypeDef.ATLAS_TYPE_FLOAT); attrDiskUsage.setIsOptional(true); attrDiskUsage.setDefaultValue("70.50"); AtlasAttributeDef attrisStoreUse = new AtlasAttributeDef("isstoreUse", AtlasBaseTypeDef.ATLAS_TYPE_BOOLEAN); attrisStoreUse.setIsOptional(true); attrisStoreUse.setDefaultValue("true"); newtestEntityDef.addAttribute(attrName); newtestEntityDef.addAttribute(attrDescription); newtestEntityDef.addAttribute(attrcheck); newtestEntityDef.addAttribute(attrSourceCode); newtestEntityDef.addAttribute(attrCost); newtestEntityDef.addAttribute(attrDiskUsage); newtestEntityDef.addAttribute(attrisStoreUse); return newtestEntityDef; } public static AtlasEntity createColumnEntity(AtlasEntity tableEntity) { return createColumnEntity(tableEntity, "col" + seq.addAndGet(1)); } public static AtlasEntity createColumnEntity(AtlasEntity tableEntity, String colName) { AtlasEntity entity = new AtlasEntity(COLUMN_TYPE); entity.setAttribute(NAME, colName); entity.setAttribute("type", "VARCHAR(32)"); entity.setAttribute("table", AtlasTypeUtil.getAtlasObjectId(tableEntity)); return entity; } public static AtlasEntity createProcessEntity(List<AtlasObjectId> inputs, List<AtlasObjectId> outputs) { AtlasEntity entity = new AtlasEntity(PROCESS_TYPE); entity.setAttribute(NAME, RandomStringUtils.randomAlphanumeric(10)); entity.setAttribute("inputs", inputs); entity.setAttribute("outputs", outputs); return entity; } public static List<AtlasClassificationDef> getClassificationWithValidSuperType() { AtlasClassificationDef securityClearanceTypeDef = AtlasTypeUtil.createTraitTypeDef("SecurityClearance1", "SecurityClearance_description", ImmutableSet.<String>of(), AtlasTypeUtil.createRequiredAttrDef("level", "int")); AtlasClassificationDef janitorSecurityClearanceTypeDef = AtlasTypeUtil.createTraitTypeDef("JanitorClearance", "JanitorClearance_description", ImmutableSet.of("SecurityClearance1"), AtlasTypeUtil.createRequiredAttrDef("level", "int")); return Arrays.asList(securityClearanceTypeDef, janitorSecurityClearanceTypeDef); } public static List<AtlasClassificationDef> getClassificationWithValidAttribute(){ return getClassificationWithValidSuperType(); } public static List<AtlasEntityDef> getEntityWithValidSuperType() { AtlasEntityDef developerTypeDef = AtlasTypeUtil.createClassTypeDef("Developer", "Developer_description", ImmutableSet.of("Employee"), new AtlasAttributeDef("language", String.format("array<%s>", "string"), false, AtlasAttributeDef.Cardinality.SET, 1, 10, false, false, Collections.<AtlasConstraintDef>emptyList())); return Arrays.asList(developerTypeDef); } public static List<AtlasEntityDef> getEntityWithValidAttribute() { List<AtlasEntityDef> entityDefs = getEntityWithValidSuperType(); entityDefs.get(1).getSuperTypes().clear(); return entityDefs; } public static AtlasClassificationDef getClassificationWithInvalidSuperType() { AtlasClassificationDef classificationDef = simpleType().getClassificationDefs().get(0); classificationDef.getSuperTypes().add("!@#$%"); return classificationDef; } public static AtlasEntityDef getEntityWithInvalidSuperType() { AtlasEntityDef entityDef = simpleType().getEntityDefs().get(0); entityDef.addSuperType("!@#$%"); return entityDef; } } <|start_filename|>intg/src/main/java/org/apache/atlas/model/instance/EntityMutations.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.model.instance; import org.apache.commons.collections.CollectionUtils; import org.codehaus.jackson.annotate.JsonAutoDetect; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.map.annotate.JsonSerialize; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Objects; import static org.codehaus.jackson.annotate.JsonAutoDetect.Visibility.NONE; import static org.codehaus.jackson.annotate.JsonAutoDetect.Visibility.PUBLIC_ONLY; @JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) @JsonIgnoreProperties(ignoreUnknown=true) @XmlRootElement @XmlAccessorType(XmlAccessType.PROPERTY) public class EntityMutations implements Serializable { private List<EntityMutation> entityMutations = new ArrayList<>(); public enum EntityOperation { CREATE, UPDATE, PARTIAL_UPDATE, DELETE } public static final class EntityMutation implements Serializable { private EntityOperation op; private AtlasEntity entity; public EntityMutation(EntityOperation op, AtlasEntity entity) { this.op = op; this.entity = entity; } public StringBuilder toString(StringBuilder sb) { if ( sb == null) { sb = new StringBuilder(); } sb.append("EntityMutation {"); sb.append("op=").append(op); if (entity != null) { sb.append(", entity="); entity.toString(sb); } sb.append("}"); return sb; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EntityMutation that = (EntityMutation) o; return op == that.op && Objects.equals(entity, that.entity); } @Override public int hashCode() { return Objects.hash(op, entity); } @Override public String toString() { return toString(new StringBuilder()).toString(); } } public EntityMutations(List<EntityMutation> entityMutations) { this.entityMutations = entityMutations; } public StringBuilder toString(StringBuilder sb) { if ( sb == null) { sb = new StringBuilder(); } sb.append("EntityMutations{"); if (CollectionUtils.isNotEmpty(entityMutations)) { for (int i = 0; i < entityMutations.size(); i++) { if (i > 0) { sb.append(","); } entityMutations.get(i).toString(sb); } } sb.append("}"); return sb; } @Override public String toString() { return toString(new StringBuilder()).toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EntityMutations that = (EntityMutations) o; return Objects.equals(entityMutations, that.entityMutations); } @Override public int hashCode() { return Objects.hash(entityMutations); } } <|start_filename|>webapp/src/main/java/org/apache/atlas/web/util/LineageUtils.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.web.util; import org.apache.atlas.AtlasClient; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.instance.AtlasEntity; import org.apache.atlas.model.instance.AtlasEntityHeader; import org.apache.atlas.model.lineage.AtlasLineageInfo; import org.apache.atlas.model.typedef.AtlasBaseTypeDef; import org.apache.atlas.model.typedef.AtlasEntityDef; import org.apache.atlas.type.AtlasEntityType; import org.apache.atlas.type.AtlasType; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.typesystem.Struct; import org.apache.atlas.typesystem.json.InstanceSerialization; import org.apache.atlas.typesystem.types.TypeSystem; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.ATLAS_TYPE_ARRAY_PREFIX; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.ATLAS_TYPE_ARRAY_SUFFIX; public final class LineageUtils { private LineageUtils() {} private static final String VERTICES_ATTR_NAME = "vertices"; private static final String EDGES_ATTR_NAME = "edges"; private static final String VERTEX_ID_ATTR_NAME = "vertexId"; private static final String TEMP_STRUCT_ID_RESULT = "__IdType"; private static final AtomicInteger COUNTER = new AtomicInteger(); public static String toLineageStruct(AtlasLineageInfo lineageInfo, AtlasTypeRegistry registry) throws AtlasBaseException { String ret = null; if (lineageInfo != null) { Map<String, AtlasEntityHeader> entities = lineageInfo.getGuidEntityMap(); Set<AtlasLineageInfo.LineageRelation> relations = lineageInfo.getRelations(); AtlasLineageInfo.LineageDirection direction = lineageInfo.getLineageDirection(); Map<String, Struct> verticesMap = new HashMap<>(); // Lineage Entities mapping -> verticesMap (vertices) for (String guid : entities.keySet()) { AtlasEntityHeader entityHeader = entities.get(guid); if (isDataSet(entityHeader.getTypeName(), registry)) { Map<String, Object> vertexIdMap = new HashMap<>(); TypeSystem.IdType idType = TypeSystem.getInstance().getIdType(); vertexIdMap.put(idType.idAttrName(), guid); vertexIdMap.put(idType.stateAttrName(), (entityHeader.getStatus() == AtlasEntity.Status.ACTIVE) ? "ACTIVE" : "DELETED"); vertexIdMap.put(idType.typeNameAttrName(), entityHeader.getTypeName()); Object qualifiedName = entityHeader.getAttribute(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME); if (qualifiedName == null) { qualifiedName = entityHeader.getDisplayText(); } Map<String, Object> values = new HashMap<>(); values.put(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, qualifiedName); values.put(VERTEX_ID_ATTR_NAME, constructResultStruct(vertexIdMap, true)); values.put(AtlasClient.NAME, entityHeader.getDisplayText()); verticesMap.put(guid, constructResultStruct(values, false)); } } // Lineage Relations mapping -> edgesMap (edges) Map<String, List<String>> edgesMap = new HashMap<>(); for (AtlasLineageInfo.LineageRelation relation : relations) { String fromEntityId = relation.getFromEntityId(); String toEntityId = relation.getToEntityId(); if (direction == AtlasLineageInfo.LineageDirection.INPUT) { if (!edgesMap.containsKey(toEntityId)) { edgesMap.put(toEntityId, new ArrayList<String>()); } edgesMap.get(toEntityId).add(fromEntityId); } else if (direction == AtlasLineageInfo.LineageDirection.OUTPUT) { if (!edgesMap.containsKey(fromEntityId)) { edgesMap.put(fromEntityId, new ArrayList<String>()); } edgesMap.get(fromEntityId).add(toEntityId); } } Map<String, Object> map = new HashMap<>(); map.put(VERTICES_ATTR_NAME, verticesMap); map.put(EDGES_ATTR_NAME, edgesMap); ret = InstanceSerialization.toJson(constructResultStruct(map, false), false); } return ret; } private static Struct constructResultStruct(Map<String, Object> values, boolean idType) { if (idType) { return new Struct(TEMP_STRUCT_ID_RESULT, values); } return new Struct(org.apache.atlas.query.TypeUtils.TEMP_STRUCT_NAME_PREFIX() + COUNTER.getAndIncrement(), values); } private static boolean isDataSet(String typeName, AtlasTypeRegistry registry) throws AtlasBaseException { boolean ret = false; AtlasType type = registry.getType(typeName); if (type instanceof AtlasEntityType) { AtlasEntityType entityType = (AtlasEntityType) type; ret = entityType.getAllSuperTypes().contains(AtlasBaseTypeDef.ATLAS_TYPE_DATASET); } return ret; } } <|start_filename|>intg/src/main/java/org/apache/atlas/model/instance/AtlasObjectId.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.model.instance; import java.io.Serializable; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.Objects; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSeeAlso; import org.apache.atlas.model.PList; import org.apache.atlas.model.SearchFilter.SortType; import org.apache.atlas.model.typedef.AtlasBaseTypeDef; import org.codehaus.jackson.annotate.JsonAutoDetect; import static org.codehaus.jackson.annotate.JsonAutoDetect.Visibility.PUBLIC_ONLY; import static org.codehaus.jackson.annotate.JsonAutoDetect.Visibility.NONE; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.map.annotate.JsonSerialize; /** * Reference to an object-instance of an Atlas type - like entity. */ @JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) @JsonIgnoreProperties(ignoreUnknown=true) @XmlRootElement @XmlAccessorType(XmlAccessType.PROPERTY) public class AtlasObjectId implements Serializable { private static final long serialVersionUID = 1L; public static final String KEY_GUID = "guid"; public static final String KEY_TYPENAME = "typeName"; public static final String KEY_UNIQUE_ATTRIBUTES = "uniqueAttributes"; private String guid; private String typeName; private Map<String, Object> uniqueAttributes; public AtlasObjectId() { this(null, null, (Map<String, Object>)null); } public AtlasObjectId(String guid) { this(guid, null, (Map<String, Object>)null); } public AtlasObjectId(String guid, String typeName) { this(guid, typeName, (Map<String, Object>)null); } public AtlasObjectId(String typeName, Map<String, Object> uniqueAttributes) { this(null, typeName, uniqueAttributes); } public AtlasObjectId(String typeName, final String attrName, final Object attrValue) { this(null, typeName, new HashMap<String, Object>() {{ put(attrName, attrValue); }}); } public AtlasObjectId(String guid, String typeName, Map<String, Object> uniqueAttributes) { setGuid(guid); setTypeName(typeName); setUniqueAttributes(uniqueAttributes); } public AtlasObjectId(AtlasObjectId other) { if (other != null) { setGuid(other.getGuid()); setTypeName(other.getTypeName()); setUniqueAttributes(other.getUniqueAttributes()); } } public AtlasObjectId(Map objIdMap) { if (objIdMap != null) { Object g = objIdMap.get(KEY_GUID); Object t = objIdMap.get(KEY_TYPENAME); Object u = objIdMap.get(KEY_UNIQUE_ATTRIBUTES); if (g != null) { setGuid(g.toString()); } if (t != null) { setTypeName(t.toString()); } if (u != null && u instanceof Map) { setUniqueAttributes((Map)u); } } } public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } public Map<String, Object> getUniqueAttributes() { return uniqueAttributes; } public void setUniqueAttributes(Map<String, Object> uniqueAttributes) { this.uniqueAttributes = uniqueAttributes; } public StringBuilder toString(StringBuilder sb) { if (sb == null) { sb = new StringBuilder(); } sb.append("AtlasObjectId{"); sb.append("guid='").append(guid).append('\''); sb.append(", typeName='").append(typeName).append('\''); sb.append(", uniqueAttributes={"); AtlasBaseTypeDef.dumpObjects(uniqueAttributes, sb); sb.append('}'); sb.append('}'); return sb; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AtlasObjectId that = (AtlasObjectId) o; // if guid is null, equality should be based on typeName/uniqueAttributes if (guid != null && Objects.equals(guid, that.guid)) { return true; } return Objects.equals(typeName, that.typeName) && Objects.equals(uniqueAttributes, that.uniqueAttributes); } @Override public int hashCode() { return guid != null ? Objects.hash(guid) : Objects.hash(typeName, uniqueAttributes); } @Override public String toString() { return toString(new StringBuilder()).toString(); } /** * REST serialization friendly list. */ @JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) @JsonIgnoreProperties(ignoreUnknown=true) @XmlRootElement @XmlAccessorType(XmlAccessType.PROPERTY) @XmlSeeAlso(AtlasObjectId.class) public static class AtlasObjectIds extends PList<AtlasObjectId> { private static final long serialVersionUID = 1L; public AtlasObjectIds() { super(); } public AtlasObjectIds(List<AtlasObjectId> list) { super(list); } public AtlasObjectIds(List list, long startIndex, int pageSize, long totalCount, SortType sortType, String sortBy) { super(list, startIndex, pageSize, totalCount, sortType, sortBy); } } } <|start_filename|>authorization/src/main/java/org/apache/atlas/authorize/simple/SimpleAtlasAuthorizer.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.authorize.simple; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.Map; import org.apache.atlas.ApplicationProperties; import org.apache.atlas.AtlasException; import org.apache.atlas.authorize.AtlasAccessRequest; import org.apache.atlas.authorize.AtlasActionTypes; import org.apache.atlas.authorize.AtlasAuthorizationException; import org.apache.atlas.authorize.AtlasAuthorizer; import org.apache.atlas.authorize.AtlasResourceTypes; import org.apache.atlas.utils.PropertiesUtil; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOCase; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.VisibleForTesting; public final class SimpleAtlasAuthorizer implements AtlasAuthorizer { public enum AtlasAccessorTypes { USER, GROUP } private static final Logger LOG = LoggerFactory.getLogger(SimpleAtlasAuthorizer.class); private boolean isDebugEnabled = LOG.isDebugEnabled(); private final static String WILDCARD_ASTERISK = "*"; private final static String WILDCARDS = "*?"; private boolean optIgnoreCase = false; private Map<String, Map<AtlasResourceTypes, List<String>>> userReadMap = null; private Map<String, Map<AtlasResourceTypes, List<String>>> userWriteMap = null; private Map<String, Map<AtlasResourceTypes, List<String>>> userUpdateMap = null; private Map<String, Map<AtlasResourceTypes, List<String>>> userDeleteMap = null; private Map<String, Map<AtlasResourceTypes, List<String>>> groupReadMap = null; private Map<String, Map<AtlasResourceTypes, List<String>>> groupWriteMap = null; private Map<String, Map<AtlasResourceTypes, List<String>>> groupUpdateMap = null; private Map<String, Map<AtlasResourceTypes, List<String>>> groupDeleteMap = null; public SimpleAtlasAuthorizer() { } @Override public void init() { if (isDebugEnabled) { LOG.debug("==> SimpleAtlasAuthorizer init"); } try { PolicyParser parser = new PolicyParser(); optIgnoreCase = Boolean.valueOf(PropertiesUtil.getProperty("optIgnoreCase", "false")); if (isDebugEnabled) { LOG.debug("Read from PropertiesUtil --> optIgnoreCase :: {}", optIgnoreCase); } InputStream policyStoreStream = ApplicationProperties.getFileAsInputStream(ApplicationProperties.get(), "atlas.auth.policy.file", "policy-store.txt"); List<String> policies = null; try { policies = FileReaderUtil.readFile(policyStoreStream); } finally { policyStoreStream.close(); } List<PolicyDef> policyDef = parser.parsePolicies(policies); userReadMap = PolicyUtil.createPermissionMap(policyDef, AtlasActionTypes.READ, AtlasAccessorTypes.USER); userWriteMap = PolicyUtil.createPermissionMap(policyDef, AtlasActionTypes.CREATE, AtlasAccessorTypes.USER); userUpdateMap = PolicyUtil.createPermissionMap(policyDef, AtlasActionTypes.UPDATE, AtlasAccessorTypes.USER); userDeleteMap = PolicyUtil.createPermissionMap(policyDef, AtlasActionTypes.DELETE, AtlasAccessorTypes.USER); groupReadMap = PolicyUtil.createPermissionMap(policyDef, AtlasActionTypes.READ, AtlasAccessorTypes.GROUP); groupWriteMap = PolicyUtil.createPermissionMap(policyDef, AtlasActionTypes.CREATE, AtlasAccessorTypes.GROUP); groupUpdateMap = PolicyUtil.createPermissionMap(policyDef, AtlasActionTypes.UPDATE, AtlasAccessorTypes.GROUP); groupDeleteMap = PolicyUtil.createPermissionMap(policyDef, AtlasActionTypes.DELETE, AtlasAccessorTypes.GROUP); if (isDebugEnabled) { LOG.debug("\n\nUserReadMap :: {}\nGroupReadMap :: {}", userReadMap, groupReadMap); LOG.debug("\n\nUserWriteMap :: {}\nGroupWriteMap :: {}", userWriteMap, groupWriteMap); LOG.debug("\n\nUserUpdateMap :: {}\nGroupUpdateMap :: {}", userUpdateMap, groupUpdateMap); LOG.debug("\n\nUserDeleteMap :: {}\nGroupDeleteMap :: {}", userDeleteMap, groupDeleteMap); } } catch (IOException | AtlasException e) { if (LOG.isErrorEnabled()) { LOG.error("SimpleAtlasAuthorizer could not be initialized properly due to : ", e); } throw new RuntimeException(e); } } @Override public boolean isAccessAllowed(AtlasAccessRequest request) throws AtlasAuthorizationException { if (isDebugEnabled) { LOG.debug("==> SimpleAtlasAuthorizer isAccessAllowed"); LOG.debug("isAccessAllowd({})", request); } String user = request.getUser(); Set<String> groups = request.getUserGroups(); AtlasActionTypes action = request.getAction(); String resource = request.getResource(); Set<AtlasResourceTypes> resourceTypes = request.getResourceTypes(); if (isDebugEnabled) LOG.debug("Checking for :: \nUser :: {}\nGroups :: {}\nAction :: {}\nResource :: {}", user, groups, action, resource); boolean isAccessAllowed = false; boolean isUser = user != null; boolean isGroup = groups != null; if ((!isUser && !isGroup) || action == null || resource == null) { if (isDebugEnabled) { LOG.debug("Please check the formation AtlasAccessRequest."); } return isAccessAllowed; } else { if (isDebugEnabled) { LOG.debug("checkAccess for Operation :: {} on Resource {}:{}", action, resourceTypes, resource); } switch (action) { case READ: isAccessAllowed = checkAccess(user, resourceTypes, resource, userReadMap); isAccessAllowed = isAccessAllowed || checkAccessForGroups(groups, resourceTypes, resource, groupReadMap); break; case CREATE: isAccessAllowed = checkAccess(user, resourceTypes, resource, userWriteMap); isAccessAllowed = isAccessAllowed || checkAccessForGroups(groups, resourceTypes, resource, groupWriteMap); break; case UPDATE: isAccessAllowed = checkAccess(user, resourceTypes, resource, userUpdateMap); isAccessAllowed = isAccessAllowed || checkAccessForGroups(groups, resourceTypes, resource, groupUpdateMap); break; case DELETE: isAccessAllowed = checkAccess(user, resourceTypes, resource, userDeleteMap); isAccessAllowed = isAccessAllowed || checkAccessForGroups(groups, resourceTypes, resource, groupDeleteMap); break; default: if (isDebugEnabled) { LOG.debug("Invalid Action {}\nRaising AtlasAuthorizationException!!!", action); } throw new AtlasAuthorizationException("Invalid Action :: " + action); } } if (isDebugEnabled) { LOG.debug("<== SimpleAtlasAuthorizer isAccessAllowed = {}", isAccessAllowed); } return isAccessAllowed; } private boolean checkAccess(String accessor, Set<AtlasResourceTypes> resourceTypes, String resource, Map<String, Map<AtlasResourceTypes, List<String>>> map) { if (isDebugEnabled) { LOG.debug("==> SimpleAtlasAuthorizer checkAccess"); LOG.debug("Now checking access for accessor : {}\nResource Types : {}\nResource : {}\nMap : {}", accessor, resourceTypes, resource, map); } boolean result = true; Map<AtlasResourceTypes, List<String>> rescMap = map.get(accessor); if (rescMap != null) { for (AtlasResourceTypes resourceType : resourceTypes) { List<String> accessList = rescMap.get(resourceType); if (isDebugEnabled) { LOG.debug("\nChecking for resource : {} in list : {}\n", resource, accessList); } if (accessList != null) { result = result && isMatch(resource, accessList); } else { result = false; } } } else { result = false; if (isDebugEnabled) LOG.debug("Key {} missing. Returning with result : {}", accessor, result); } if (isDebugEnabled) { LOG.debug("Check for {} :: {}", accessor, result); LOG.debug("<== SimpleAtlasAuthorizer checkAccess"); } return result; } private boolean checkAccessForGroups(Set<String> groups, Set<AtlasResourceTypes> resourceType, String resource, Map<String, Map<AtlasResourceTypes, List<String>>> map) { boolean isAccessAllowed = false; if (isDebugEnabled) { LOG.debug("==> SimpleAtlasAuthorizer checkAccessForGroups"); } if(CollectionUtils.isNotEmpty(groups)) { for (String group : groups) { isAccessAllowed = checkAccess(group, resourceType, resource, map); if (isAccessAllowed) { break; } } } if (isDebugEnabled) { LOG.debug("<== SimpleAtlasAuthorizer checkAccessForGroups"); } return isAccessAllowed; } private boolean resourceMatchHelper(List<String> policyResource) { boolean isMatchAny = false; if (isDebugEnabled) { LOG.debug("==> SimpleAtlasAuthorizer resourceMatchHelper"); } boolean optWildCard = true; List<String> policyValues = new ArrayList<>(); if (policyResource != null) { boolean isWildCardPresent = !optWildCard; for (String policyValue : policyResource) { if (StringUtils.isEmpty(policyValue)) { continue; } if (StringUtils.containsOnly(policyValue, WILDCARD_ASTERISK)) { isMatchAny = true; } else if (!isWildCardPresent && StringUtils.containsAny(policyValue, WILDCARDS)) { isWildCardPresent = true; } policyValues.add(policyValue); } optWildCard = optWildCard && isWildCardPresent; } else { isMatchAny = false; } if (isDebugEnabled) { LOG.debug("<== SimpleAtlasAuthorizer resourceMatchHelper"); } return isMatchAny; } private boolean isMatch(String resource, List<String> policyValues) { if (isDebugEnabled) { LOG.debug("==> SimpleAtlasAuthorizer isMatch"); } boolean isMatchAny = resourceMatchHelper(policyValues); boolean isMatch = false; boolean allValuesRequested = isAllValuesRequested(resource); if (allValuesRequested || isMatchAny) { isMatch = isMatchAny; } else { for (String policyValue : policyValues) { if (policyValue.contains("*")) { isMatch = optIgnoreCase ? FilenameUtils.wildcardMatch(resource, policyValue, IOCase.INSENSITIVE) : FilenameUtils.wildcardMatch(resource, policyValue, IOCase.SENSITIVE); } else { isMatch = optIgnoreCase ? StringUtils.equalsIgnoreCase(resource, policyValue) : StringUtils.equals( resource, policyValue); } if (isMatch) { break; } } } if (!isMatch) { if (isDebugEnabled) { StringBuilder sb = new StringBuilder(); sb.append("["); for (String policyValue : policyValues) { sb.append(policyValue); sb.append(" "); } sb.append("]"); LOG.debug("AtlasDefaultResourceMatcher.isMatch returns FALSE, (resource={}, policyValues={})", resource, sb.toString()); } } if (isDebugEnabled) { LOG.debug("<== SimpleAtlasAuthorizer isMatch({}): {}", resource, isMatch); } return isMatch; } private boolean isAllValuesRequested(String resource) { return StringUtils.isEmpty(resource) || WILDCARD_ASTERISK.equals(resource); } @Override public void cleanUp() { if (isDebugEnabled) { LOG.debug("==> +SimpleAtlasAuthorizer cleanUp"); } userReadMap = null; userWriteMap = null; userUpdateMap = null; userDeleteMap = null; groupReadMap = null; groupWriteMap = null; groupUpdateMap = null; groupDeleteMap = null; if (isDebugEnabled) { LOG.debug("<== +SimpleAtlasAuthorizer cleanUp"); } } /* * NOTE :: This method is added for setting the maps for testing purpose. */ @VisibleForTesting public void setResourcesForTesting(Map<String, Map<AtlasResourceTypes, List<String>>> userMap, Map<String, Map<AtlasResourceTypes, List<String>>> groupMap, AtlasActionTypes actionTypes) { switch (actionTypes) { case READ: this.userReadMap = userMap; this.groupReadMap = groupMap; break; case CREATE: this.userWriteMap = userMap; this.groupWriteMap = groupMap; break; case UPDATE: this.userUpdateMap = userMap; this.groupUpdateMap = groupMap; break; case DELETE: this.userDeleteMap = userMap; this.groupDeleteMap = groupMap; break; default: if (isDebugEnabled) { LOG.debug("No such action available"); } break; } } } <|start_filename|>intg/src/main/java/org/apache/atlas/type/AtlasTypeRegistry.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.type; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.ATLAS_TYPE_ARRAY_PREFIX; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.ATLAS_TYPE_ARRAY_SUFFIX; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.ATLAS_TYPE_MAP_KEY_VAL_SEP; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.ATLAS_TYPE_MAP_PREFIX; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.ATLAS_TYPE_MAP_SUFFIX; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import javax.inject.Singleton; import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.typedef.AtlasBaseTypeDef; import org.apache.atlas.model.typedef.AtlasClassificationDef; import org.apache.atlas.model.typedef.AtlasEntityDef; import org.apache.atlas.model.typedef.AtlasEnumDef; import org.apache.atlas.model.typedef.AtlasRelationshipDef; import org.apache.atlas.model.typedef.AtlasStructDef; import org.apache.atlas.model.typedef.AtlasTypesDef; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; /** * registry for all types defined in Atlas. */ @Singleton @Component public class AtlasTypeRegistry { private static final Logger LOG = LoggerFactory.getLogger(AtlasStructType.class); private static final int DEFAULT_LOCK_MAX_WAIT_TIME_IN_SECONDS = 15; protected RegistryData registryData; private final TypeRegistryUpdateSynchronizer updateSynchronizer; public AtlasTypeRegistry() { registryData = new RegistryData(); updateSynchronizer = new TypeRegistryUpdateSynchronizer(this); } // used only by AtlasTransientTypeRegistry protected AtlasTypeRegistry(AtlasTypeRegistry other) { registryData = new RegistryData(); updateSynchronizer = other.updateSynchronizer; } public Collection<String> getAllTypeNames() { return registryData.allTypes.getAllTypeNames(); } public Collection<AtlasType> getAllTypes() { return registryData.allTypes.getAllTypes(); } public boolean isRegisteredType(String typeName) { return registryData.allTypes.isKnownType(typeName); } public AtlasType getType(String typeName) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeRegistry.getType({})", typeName); } AtlasType ret = registryData.allTypes.getTypeByName(typeName); if (ret == null) { if (typeName.startsWith(ATLAS_TYPE_ARRAY_PREFIX) && typeName.endsWith(ATLAS_TYPE_ARRAY_SUFFIX)) { int startIdx = ATLAS_TYPE_ARRAY_PREFIX.length(); int endIdx = typeName.length() - ATLAS_TYPE_ARRAY_SUFFIX.length(); String elementTypeName = typeName.substring(startIdx, endIdx); ret = new AtlasArrayType(elementTypeName, this); } else if (typeName.startsWith(ATLAS_TYPE_MAP_PREFIX) && typeName.endsWith(ATLAS_TYPE_MAP_SUFFIX)) { int startIdx = ATLAS_TYPE_MAP_PREFIX.length(); int endIdx = typeName.length() - ATLAS_TYPE_MAP_SUFFIX.length(); String[] keyValueTypes = typeName.substring(startIdx, endIdx).split(ATLAS_TYPE_MAP_KEY_VAL_SEP, 2); String keyTypeName = keyValueTypes.length > 0 ? keyValueTypes[0] : null; String valueTypeName = keyValueTypes.length > 1 ? keyValueTypes[1] : null; ret = new AtlasMapType(keyTypeName, valueTypeName, this); } else { throw new AtlasBaseException(AtlasErrorCode.TYPE_NAME_NOT_FOUND, typeName); } } if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeRegistry.getType({}): {}", typeName, ret); } return ret; } public AtlasType getTypeByGuid(String guid) { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeRegistry.getTypeByGuid({})", guid); } AtlasType ret = registryData.allTypes.getTypeByGuid(guid); if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeRegistry.getTypeByGuid({}): {}", guid, ret); } return ret; } public AtlasBaseTypeDef getTypeDefByName(String name) { return registryData.getTypeDefByName(name); } public AtlasBaseTypeDef getTypeDefByGuid(String guid) { return registryData.getTypeDefByGuid(guid); } public Collection<AtlasEnumDef> getAllEnumDefs() { return registryData.enumDefs.getAll(); } public AtlasEnumDef getEnumDefByGuid(String guid) { return registryData.enumDefs.getTypeDefByGuid(guid); } public AtlasEnumDef getEnumDefByName(String name) { return registryData.enumDefs.getTypeDefByName(name); } public Collection<String> getAllEnumDefNames() { return registryData.enumDefs.getAllNames(); } public Collection<AtlasEnumType> getAllEnumTypes() { return registryData.enumDefs.getAllTypes(); } public AtlasEnumType getEnumTypeByName(String name) { return registryData.enumDefs.getTypeByName(name); } public Collection<AtlasStructDef> getAllStructDefs() { return registryData.structDefs.getAll(); } public AtlasStructDef getStructDefByGuid(String guid) { return registryData.structDefs.getTypeDefByGuid(guid); } public AtlasStructDef getStructDefByName(String name) { return registryData.structDefs.getTypeDefByName(name); } public Collection<String> getAllStructDefNames() { return registryData.structDefs.getAllNames(); } public Collection<AtlasStructType> getAllStructTypes() { return registryData.structDefs.getAllTypes(); } public AtlasStructType getStructTypeByName(String name) { return registryData.structDefs.getTypeByName(name); } public Collection<AtlasClassificationDef> getAllClassificationDefs() { return registryData.classificationDefs.getAll(); } public AtlasClassificationDef getClassificationDefByGuid(String guid) { return registryData.classificationDefs.getTypeDefByGuid(guid); } public AtlasClassificationDef getClassificationDefByName(String name) { return registryData.classificationDefs.getTypeDefByName(name); } public Collection<String> getAllClassificationDefNames() { return registryData.classificationDefs.getAllNames(); } public Collection<AtlasClassificationType> getAllClassificationTypes() { return registryData.classificationDefs.getAllTypes(); } public AtlasClassificationType getClassificationTypeByName(String name) { return registryData.classificationDefs.getTypeByName(name); } public Collection<AtlasRelationshipDef> getAllRelationshipDefs() { return registryData.relationshipDefs.getAll(); } public Collection<AtlasEntityDef> getAllEntityDefs() { return registryData.entityDefs.getAll(); } public AtlasEntityDef getEntityDefByGuid(String guid) { return registryData.entityDefs.getTypeDefByGuid(guid); } public AtlasEntityDef getEntityDefByName(String name) { return registryData.entityDefs.getTypeDefByName(name); } public Collection<String> getAllEntityDefNames() { return registryData.entityDefs.getAllNames(); } public Collection<AtlasEntityType> getAllEntityTypes() { return registryData.entityDefs.getAllTypes(); } public AtlasEntityType getEntityTypeByName(String name) { return registryData.entityDefs.getTypeByName(name); } /** * @return relationshipTypes */ public Collection<AtlasRelationshipType> getAllRelationshipTypes() { return registryData.relationshipDefs.getAllTypes(); } public AtlasRelationshipDef getRelationshipDefByGuid(String guid) { return registryData.relationshipDefs.getTypeDefByGuid(guid); } public AtlasRelationshipDef getRelationshipDefByName(String name) { return registryData.relationshipDefs.getTypeDefByName(name); } public AtlasRelationshipType getRelationshipTypeByName(String name) { return registryData.relationshipDefs.getTypeByName(name); } public AtlasTransientTypeRegistry lockTypeRegistryForUpdate() throws AtlasBaseException { return lockTypeRegistryForUpdate(DEFAULT_LOCK_MAX_WAIT_TIME_IN_SECONDS); } public AtlasTransientTypeRegistry lockTypeRegistryForUpdate(int lockMaxWaitTimeInSeconds) throws AtlasBaseException { return updateSynchronizer.lockTypeRegistryForUpdate(lockMaxWaitTimeInSeconds); } public void releaseTypeRegistryForUpdate(AtlasTransientTypeRegistry transientTypeRegistry, boolean commitUpdates) { updateSynchronizer.releaseTypeRegistryForUpdate(transientTypeRegistry, commitUpdates); } static class RegistryData { final TypeCache allTypes; final TypeDefCache<AtlasEnumDef, AtlasEnumType> enumDefs; final TypeDefCache<AtlasStructDef, AtlasStructType> structDefs; final TypeDefCache<AtlasClassificationDef, AtlasClassificationType> classificationDefs; final TypeDefCache<AtlasEntityDef, AtlasEntityType> entityDefs; final TypeDefCache<AtlasRelationshipDef, AtlasRelationshipType> relationshipDefs; final TypeDefCache<? extends AtlasBaseTypeDef, ? extends AtlasType>[] allDefCaches; RegistryData() { allTypes = new TypeCache(); enumDefs = new TypeDefCache<>(allTypes); structDefs = new TypeDefCache<>(allTypes); classificationDefs = new TypeDefCache<>(allTypes); entityDefs = new TypeDefCache<>(allTypes); relationshipDefs = new TypeDefCache<>(allTypes); allDefCaches = new TypeDefCache[] { enumDefs, structDefs, classificationDefs, entityDefs, relationshipDefs }; init(); } void init() { allTypes.addType(new AtlasBuiltInTypes.AtlasBooleanType()); allTypes.addType(new AtlasBuiltInTypes.AtlasByteType()); allTypes.addType(new AtlasBuiltInTypes.AtlasShortType()); allTypes.addType(new AtlasBuiltInTypes.AtlasIntType()); allTypes.addType(new AtlasBuiltInTypes.AtlasLongType()); allTypes.addType(new AtlasBuiltInTypes.AtlasFloatType()); allTypes.addType(new AtlasBuiltInTypes.AtlasDoubleType()); allTypes.addType(new AtlasBuiltInTypes.AtlasBigIntegerType()); allTypes.addType(new AtlasBuiltInTypes.AtlasBigDecimalType()); allTypes.addType(new AtlasBuiltInTypes.AtlasDateType()); allTypes.addType(new AtlasBuiltInTypes.AtlasStringType()); allTypes.addType(new AtlasBuiltInTypes.AtlasObjectIdType()); } AtlasBaseTypeDef getTypeDefByName(String name) { AtlasBaseTypeDef ret = null; if (name != null) { for (TypeDefCache typeDefCache : allDefCaches) { ret = typeDefCache.getTypeDefByName(name); if (ret != null) { break; } } } return ret; } AtlasBaseTypeDef getTypeDefByGuid(String guid) { AtlasBaseTypeDef ret = null; if (guid != null) { for (TypeDefCache typeDefCache : allDefCaches) { ret = typeDefCache.getTypeDefByGuid(guid); if (ret != null) { break; } } } return ret; } void updateGuid(String typeName, String guid) { if (typeName != null) { enumDefs.updateGuid(typeName, guid); structDefs.updateGuid(typeName, guid); classificationDefs.updateGuid(typeName, guid); entityDefs.updateGuid(typeName, guid); relationshipDefs.updateGuid(typeName, guid); } } void removeByGuid(String guid) { if (guid != null) { enumDefs.removeTypeDefByGuid(guid); structDefs.removeTypeDefByGuid(guid); classificationDefs.removeTypeDefByGuid(guid); entityDefs.removeTypeDefByGuid(guid); relationshipDefs.removeTypeDefByGuid(guid); } } void removeByName(String typeName) { if (typeName != null) { enumDefs.removeTypeDefByName(typeName); structDefs.removeTypeDefByName(typeName); classificationDefs.removeTypeDefByName(typeName); entityDefs.removeTypeDefByName(typeName); relationshipDefs.removeTypeDefByName(typeName); } } void clear() { allTypes.clear(); enumDefs.clear(); structDefs.clear(); classificationDefs.clear(); entityDefs.clear(); relationshipDefs.clear(); init(); } } public static class AtlasTransientTypeRegistry extends AtlasTypeRegistry { private List<AtlasBaseTypeDef> addedTypes = new ArrayList<>(); private List<AtlasBaseTypeDef> updatedTypes = new ArrayList<>(); private List<AtlasBaseTypeDef> deletedTypes = new ArrayList<>(); private AtlasTransientTypeRegistry(AtlasTypeRegistry parent) throws AtlasBaseException { super(parent); addTypesWithNoRefResolve(parent.getAllEnumDefs()); addTypesWithNoRefResolve(parent.getAllStructDefs()); addTypesWithNoRefResolve(parent.getAllClassificationDefs()); addTypesWithNoRefResolve(parent.getAllEntityDefs()); addTypesWithNoRefResolve(parent.getAllRelationshipDefs()); addedTypes.clear(); updatedTypes.clear(); deletedTypes.clear(); } private void resolveReferences() throws AtlasBaseException { for (AtlasType type : registryData.allTypes.getAllTypes()) { type.resolveReferences(this); } for (AtlasType type : registryData.allTypes.getAllTypes()) { type.resolveReferencesPhase2(this); } for (AtlasType type : registryData.allTypes.getAllTypes()) { type.resolveReferencesPhase3(this); } } public void clear() { registryData.clear(); } public void addType(AtlasBaseTypeDef typeDef) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeRegistry.addType({})", typeDef); } if (typeDef != null) { addTypeWithNoRefResolve(typeDef); resolveReferences(); } if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeRegistry.addType({})", typeDef); } } public void updateGuid(String typeName, String guid) { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeRegistry.updateGuid({}, {})", typeName, guid); } registryData.updateGuid(typeName, guid); if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeRegistry.updateGuid({}, {})", typeName, guid); } } public void addTypes(Collection<? extends AtlasBaseTypeDef> typeDefs) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeRegistry.addTypes(length={})", (typeDefs == null ? 0 : typeDefs.size())); } if (CollectionUtils.isNotEmpty(typeDefs)) { addTypesWithNoRefResolve(typeDefs); resolveReferences(); } if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeRegistry.addTypes(length={})", (typeDefs == null ? 0 : typeDefs.size())); } } public void addTypes(AtlasTypesDef typesDef) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeRegistry.addTypes({})", typesDef); } if (typesDef != null) { addTypesWithNoRefResolve(typesDef.getEnumDefs()); addTypesWithNoRefResolve(typesDef.getStructDefs()); addTypesWithNoRefResolve(typesDef.getClassificationDefs()); addTypesWithNoRefResolve(typesDef.getEntityDefs()); addTypesWithNoRefResolve(typesDef.getRelationshipDefs()); resolveReferences(); } if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeRegistry.addTypes({})", typesDef); } } public void updateType(AtlasBaseTypeDef typeDef) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeRegistry.updateType({})", typeDef); } if (typeDef != null) { updateTypeWithNoRefResolve(typeDef); resolveReferences(); } if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeRegistry.updateType({})", typeDef); } } public void updateTypeByGuid(String guid, AtlasBaseTypeDef typeDef) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeRegistry.updateTypeByGuid({})", guid); } if (guid != null && typeDef != null) { updateTypeByGuidWithNoRefResolve(guid, typeDef); resolveReferences(); } if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeRegistry.updateTypeByGuid({})", guid); } } public void updateTypeByName(String name, AtlasBaseTypeDef typeDef) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeRegistry.updateEnumDefByName({})", name); } if (name != null && typeDef != null) { updateTypeByNameWithNoRefResolve(name, typeDef); resolveReferences(); } if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeRegistry.updateEnumDefByName({})", name); } } public void updateTypes(Collection<? extends AtlasBaseTypeDef> typeDefs) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeRegistry.updateTypes(length={})", (typeDefs == null ? 0 : typeDefs.size())); } if (CollectionUtils.isNotEmpty(typeDefs)) { updateTypesWithNoRefResolve(typeDefs); resolveReferences(); } if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeRegistry.updateTypes(length={})", (typeDefs == null ? 0 : typeDefs.size())); } } public void updateTypes(AtlasTypesDef typesDef) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeRegistry.updateTypes({})", typesDef); } if (typesDef != null) { updateTypesWithNoRefResolve(typesDef); resolveReferences(); } if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeRegistry.updateTypes({})", typesDef); } } public void updateTypesWithNoRefResolve(AtlasTypesDef typesDef) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeRegistry.updateTypesWithNoRefResolve({})", typesDef); } if (typesDef != null) { updateTypesWithNoRefResolve(typesDef.getEnumDefs()); updateTypesWithNoRefResolve(typesDef.getStructDefs()); updateTypesWithNoRefResolve(typesDef.getClassificationDefs()); updateTypesWithNoRefResolve(typesDef.getEntityDefs()); updateTypesWithNoRefResolve(typesDef.getRelationshipDefs()); } if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeRegistry.updateTypesWithNoRefResolve({})", typesDef); } } public void removeTypesDef(AtlasTypesDef typesDef) throws AtlasBaseException { if (null != typesDef && !typesDef.isEmpty()) { removeTypesWithNoRefResolve(typesDef.getEnumDefs()); removeTypesWithNoRefResolve(typesDef.getStructDefs()); removeTypesWithNoRefResolve(typesDef.getClassificationDefs()); removeTypesWithNoRefResolve(typesDef.getEntityDefs()); removeTypesWithNoRefResolve(typesDef.getRelationshipDefs()); resolveReferences(); } } private void removeTypesWithNoRefResolve(Collection<? extends AtlasBaseTypeDef> typeDefs) { if (CollectionUtils.isNotEmpty(typeDefs)) { for (AtlasBaseTypeDef typeDef : typeDefs) { if (StringUtils.isNotEmpty(typeDef.getGuid())) { removeTypeByGuidWithNoRefResolve(typeDef); } else { removeTypeByNameWithNoRefResolve(typeDef); } } } } private void removeTypeByNameWithNoRefResolve(AtlasBaseTypeDef typeDef) { switch (typeDef.getCategory()) { case ENUM: registryData.enumDefs.removeTypeDefByName(typeDef.getName()); break; case STRUCT: registryData.structDefs.removeTypeDefByName(typeDef.getName()); break; case CLASSIFICATION: registryData.classificationDefs.removeTypeDefByName(typeDef.getName()); break; case ENTITY: registryData.entityDefs.removeTypeDefByName(typeDef.getName()); break; case RELATIONSHIP: registryData.relationshipDefs.removeTypeDefByName(typeDef.getName()); break; } deletedTypes.add(typeDef); } private void removeTypeByGuidWithNoRefResolve(AtlasBaseTypeDef typeDef) { switch (typeDef.getCategory()) { case ENUM: registryData.enumDefs.removeTypeDefByGuid(typeDef.getGuid()); break; case STRUCT: registryData.structDefs.removeTypeDefByGuid(typeDef.getGuid()); break; case CLASSIFICATION: registryData.classificationDefs.removeTypeDefByGuid(typeDef.getGuid()); break; case ENTITY: registryData.entityDefs.removeTypeDefByGuid(typeDef.getGuid()); break; case RELATIONSHIP: registryData.relationshipDefs.removeTypeDefByGuid(typeDef.getGuid()); break; } deletedTypes.add(typeDef); } public void removeTypeByGuid(String guid) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeRegistry.removeTypeByGuid({})", guid); } if (guid != null) { AtlasBaseTypeDef typeDef = getTypeDefByGuid(guid); registryData.removeByGuid(guid); resolveReferences(); if (typeDef != null) { deletedTypes.add(typeDef); } } if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeRegistry.removeTypeByGuid({})", guid); } } public void removeTypeByName(String name) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeRegistry.removeTypeByName({})", name); } if (name != null) { AtlasBaseTypeDef typeDef = getTypeDefByName(name); registryData.removeByName(name); resolveReferences(); if (typeDef != null) { deletedTypes.add(typeDef); } } if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeRegistry.removeEnumDefByName({})", name); } } public List<AtlasBaseTypeDef> getAddedTypes() { return addedTypes; } public List<AtlasBaseTypeDef> getUpdatedTypes() { return updatedTypes; } public List<AtlasBaseTypeDef> getDeleteedTypes() { return deletedTypes; } private void addTypeWithNoRefResolve(AtlasBaseTypeDef typeDef) throws AtlasBaseException{ if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeRegistry.addTypeWithNoRefResolve({})", typeDef); } if (typeDef != null) { if (this.isRegisteredType(typeDef.getName())) { throw new AtlasBaseException(AtlasErrorCode.TYPE_ALREADY_EXISTS, typeDef.getName()); } if (typeDef.getClass().equals(AtlasEnumDef.class)) { AtlasEnumDef enumDef = (AtlasEnumDef) typeDef; registryData.enumDefs.addType(enumDef, new AtlasEnumType(enumDef)); } else if (typeDef.getClass().equals(AtlasStructDef.class)) { AtlasStructDef structDef = (AtlasStructDef) typeDef; registryData.structDefs.addType(structDef, new AtlasStructType(structDef)); } else if (typeDef.getClass().equals(AtlasClassificationDef.class)) { AtlasClassificationDef classificationDef = (AtlasClassificationDef) typeDef; registryData.classificationDefs.addType(classificationDef, new AtlasClassificationType(classificationDef)); } else if (typeDef.getClass().equals(AtlasEntityDef.class)) { AtlasEntityDef entityDef = (AtlasEntityDef) typeDef; registryData.entityDefs.addType(entityDef, new AtlasEntityType(entityDef)); } else if (typeDef.getClass().equals(AtlasRelationshipDef.class)) { AtlasRelationshipDef relationshipDef = (AtlasRelationshipDef) typeDef; registryData.relationshipDefs.addType(relationshipDef, new AtlasRelationshipType(relationshipDef)); } addedTypes.add(typeDef); } if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeRegistry.addTypeWithNoRefResolve({})", typeDef); } } private void addTypesWithNoRefResolve(Collection<? extends AtlasBaseTypeDef> typeDefs) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeRegistry.addTypesWithNoRefResolve(length={})", (typeDefs == null ? 0 : typeDefs.size())); } if (CollectionUtils.isNotEmpty(typeDefs)) { for (AtlasBaseTypeDef typeDef : typeDefs) { addTypeWithNoRefResolve(typeDef); } } if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeRegistry.addTypesWithNoRefResolve(length={})", (typeDefs == null ? 0 : typeDefs.size())); } } private void updateTypeWithNoRefResolve(AtlasBaseTypeDef typeDef) { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeRegistry.updateType({})", typeDef); } if (typeDef != null) { if (StringUtils.isNotBlank(typeDef.getGuid())) { updateTypeByGuidWithNoRefResolve(typeDef.getGuid(), typeDef); } else if (StringUtils.isNotBlank(typeDef.getName())) { updateTypeByNameWithNoRefResolve(typeDef.getName(), typeDef); } } if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeRegistry.updateType({})", typeDef); } } private void updateTypeByGuidWithNoRefResolve(String guid, AtlasBaseTypeDef typeDef) { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeRegistry.updateTypeByGuidWithNoRefResolve({})", guid); } if (guid != null && typeDef != null) { // ignore if (typeDef.getClass().equals(AtlasEnumDef.class)) { AtlasEnumDef enumDef = (AtlasEnumDef) typeDef; registryData.enumDefs.removeTypeDefByGuid(guid); registryData.enumDefs.addType(enumDef, new AtlasEnumType(enumDef)); } else if (typeDef.getClass().equals(AtlasStructDef.class)) { AtlasStructDef structDef = (AtlasStructDef) typeDef; registryData.structDefs.removeTypeDefByGuid(guid); registryData.structDefs.addType(structDef, new AtlasStructType(structDef)); } else if (typeDef.getClass().equals(AtlasClassificationDef.class)) { AtlasClassificationDef classificationDef = (AtlasClassificationDef) typeDef; registryData.classificationDefs.removeTypeDefByGuid(guid); registryData.classificationDefs.addType(classificationDef, new AtlasClassificationType(classificationDef)); } else if (typeDef.getClass().equals(AtlasEntityDef.class)) { AtlasEntityDef entityDef = (AtlasEntityDef) typeDef; registryData.entityDefs.removeTypeDefByGuid(guid); registryData.entityDefs.addType(entityDef, new AtlasEntityType(entityDef)); } else if (typeDef.getClass().equals(AtlasRelationshipDef.class)) { AtlasRelationshipDef relationshipDef = (AtlasRelationshipDef) typeDef; registryData.relationshipDefs.removeTypeDefByGuid(guid); registryData.relationshipDefs.addType(relationshipDef, new AtlasRelationshipType(relationshipDef)); } updatedTypes.add(typeDef); } if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeRegistry.updateTypeByGuidWithNoRefResolve({})", guid); } } private void updateTypeByNameWithNoRefResolve(String name, AtlasBaseTypeDef typeDef) { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeRegistry.updateTypeByNameWithNoRefResolve({})", name); } if (name != null && typeDef != null) { if (typeDef.getClass().equals(AtlasEnumDef.class)) { AtlasEnumDef enumDef = (AtlasEnumDef) typeDef; registryData.enumDefs.removeTypeDefByName(name); registryData.enumDefs.addType(enumDef, new AtlasEnumType(enumDef)); } else if (typeDef.getClass().equals(AtlasStructDef.class)) { AtlasStructDef structDef = (AtlasStructDef) typeDef; registryData.structDefs.removeTypeDefByName(name); registryData.structDefs.addType(structDef, new AtlasStructType(structDef)); } else if (typeDef.getClass().equals(AtlasClassificationDef.class)) { AtlasClassificationDef classificationDef = (AtlasClassificationDef) typeDef; registryData.classificationDefs.removeTypeDefByName(name); registryData.classificationDefs.addType(classificationDef, new AtlasClassificationType(classificationDef)); } else if (typeDef.getClass().equals(AtlasEntityDef.class)) { AtlasEntityDef entityDef = (AtlasEntityDef) typeDef; registryData.entityDefs.removeTypeDefByName(name); registryData.entityDefs.addType(entityDef, new AtlasEntityType(entityDef)); } else if (typeDef.getClass().equals(AtlasRelationshipDef.class)) { AtlasRelationshipDef relationshipDef = (AtlasRelationshipDef) typeDef; registryData.relationshipDefs.removeTypeDefByName(name); registryData.relationshipDefs.addType(relationshipDef, new AtlasRelationshipType(relationshipDef)); } updatedTypes.add(typeDef); } if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeRegistry.updateTypeByNameWithNoRefResolve({})", name); } } private void updateTypesWithNoRefResolve(Collection<? extends AtlasBaseTypeDef> typeDefs) { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeRegistry.updateTypesWithNoRefResolve(length={})", (typeDefs == null ? 0 : typeDefs.size())); } if (CollectionUtils.isNotEmpty(typeDefs)) { for (AtlasBaseTypeDef typeDef : typeDefs) { updateTypeWithNoRefResolve(typeDef); } } if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeRegistry.updateTypesWithNoRefResolve(length={})", (typeDefs == null ? 0 : typeDefs.size())); } } } static class TypeRegistryUpdateSynchronizer { private final AtlasTypeRegistry typeRegistry; private final ReentrantLock typeRegistryUpdateLock; private AtlasTransientTypeRegistry typeRegistryUnderUpdate = null; private String lockedByThread = null; TypeRegistryUpdateSynchronizer(AtlasTypeRegistry typeRegistry) { this.typeRegistry = typeRegistry; this.typeRegistryUpdateLock = new ReentrantLock(); } AtlasTransientTypeRegistry lockTypeRegistryForUpdate(int lockMaxWaitTimeInSeconds) throws AtlasBaseException { LOG.debug("==> lockTypeRegistryForUpdate()"); boolean alreadyLockedByCurrentThread = typeRegistryUpdateLock.isHeldByCurrentThread(); if (!alreadyLockedByCurrentThread) { if (LOG.isDebugEnabled()) { LOG.debug("lockTypeRegistryForUpdate(): waiting for lock to be released by thread {}", lockedByThread); } } else { LOG.warn("lockTypeRegistryForUpdate(): already locked. currentLockCount={}", typeRegistryUpdateLock.getHoldCount()); } try { boolean isLocked = typeRegistryUpdateLock.tryLock(lockMaxWaitTimeInSeconds, TimeUnit.SECONDS); if (!isLocked) { throw new AtlasBaseException(AtlasErrorCode.FAILED_TO_OBTAIN_TYPE_UPDATE_LOCK); } } catch (InterruptedException excp) { throw new AtlasBaseException(AtlasErrorCode.FAILED_TO_OBTAIN_TYPE_UPDATE_LOCK, excp); } if (!alreadyLockedByCurrentThread) { if (LOG.isDebugEnabled()) { LOG.debug("lockTypeRegistryForUpdate(): wait over..got the lock"); } typeRegistryUnderUpdate = new AtlasTransientTypeRegistry(typeRegistry); lockedByThread = Thread.currentThread().getName(); } LOG.debug("<== lockTypeRegistryForUpdate()"); return typeRegistryUnderUpdate; } void releaseTypeRegistryForUpdate(AtlasTransientTypeRegistry ttr, boolean commitUpdates) { LOG.debug("==> releaseTypeRegistryForUpdate()"); if (typeRegistryUpdateLock.isHeldByCurrentThread()) { try { if (typeRegistryUnderUpdate != ttr) { LOG.error("releaseTypeRegistryForUpdate(): incorrect typeRegistry returned for release" + ": found=" + ttr + "; expected=" + typeRegistryUnderUpdate, new Exception().fillInStackTrace()); } else if (typeRegistryUpdateLock.getHoldCount() == 1) { if (ttr != null && commitUpdates) { typeRegistry.registryData = ttr.registryData; } } if (typeRegistryUpdateLock.getHoldCount() == 1) { lockedByThread = null; typeRegistryUnderUpdate = null; } else { LOG.warn("releaseTypeRegistryForUpdate(): pendingReleaseCount={}", typeRegistryUpdateLock.getHoldCount() - 1); } } finally { typeRegistryUpdateLock.unlock(); } } else { LOG.error("releaseTypeRegistryForUpdate(): current thread does not hold the lock", new Exception().fillInStackTrace()); } LOG.debug("<== releaseTypeRegistryForUpdate()"); } } } class TypeCache { private final Map<String, AtlasType> typeGuidMap; private final Map<String, AtlasType> typeNameMap; public TypeCache() { typeGuidMap = new ConcurrentHashMap<>(); typeNameMap = new ConcurrentHashMap<>(); } public TypeCache(TypeCache other) { typeGuidMap = new ConcurrentHashMap<>(other.typeGuidMap); typeNameMap = new ConcurrentHashMap<>(other.typeNameMap); } public void addType(AtlasType type) { if (type != null) { if (StringUtils.isNotEmpty(type.getTypeName())) { typeNameMap.put(type.getTypeName(), type); } } } public void addType(AtlasBaseTypeDef typeDef, AtlasType type) { if (typeDef != null && type != null) { if (StringUtils.isNotEmpty(typeDef.getGuid())) { typeGuidMap.put(typeDef.getGuid(), type); } if (StringUtils.isNotEmpty(typeDef.getName())) { typeNameMap.put(typeDef.getName(), type); } } } public boolean isKnownType(String typeName) { return typeNameMap.containsKey(typeName); } public Collection<String> getAllTypeNames() { return Collections.unmodifiableCollection(typeNameMap.keySet()); } public Collection<AtlasType> getAllTypes() { return Collections.unmodifiableCollection(typeNameMap.values()); } public AtlasType getTypeByGuid(String guid) { return guid != null ? typeGuidMap.get(guid) : null; } public AtlasType getTypeByName(String name) { return name != null ? typeNameMap.get(name) : null; } public void updateGuid(String typeName, String currGuid, String newGuid) { if (currGuid != null) { typeGuidMap.remove(currGuid); } if (typeName != null && newGuid != null) { AtlasType type = typeNameMap.get(typeName); if (type != null) { typeGuidMap.put(newGuid, type); } } } public void removeTypeByGuid(String guid) { if (guid != null) { typeGuidMap.remove(guid); } } public void removeTypeByName(String name) { if (name != null) { typeNameMap.remove(name); } } public void clear() { typeGuidMap.clear(); typeNameMap.clear(); } } class TypeDefCache<T1 extends AtlasBaseTypeDef, T2 extends AtlasType> { private static final Logger LOG = LoggerFactory.getLogger(TypeDefCache.class); private final TypeCache typeCache; private final Map<String, T1> typeDefGuidMap; private final Map<String, T1> typeDefNameMap; private final Map<String, T2> typeNameMap; public TypeDefCache(TypeCache typeCache) { this.typeCache = typeCache; this.typeDefGuidMap = new ConcurrentHashMap<>(); this.typeDefNameMap = new ConcurrentHashMap<>(); this.typeNameMap = new ConcurrentHashMap<>(); } public TypeDefCache(TypeDefCache other, TypeCache typeCache) { this.typeCache = typeCache; this.typeDefGuidMap = new ConcurrentHashMap<>(other.typeDefGuidMap); this.typeDefNameMap = new ConcurrentHashMap<>(other.typeDefNameMap); this.typeNameMap = new ConcurrentHashMap<>(other.typeNameMap); } public void addType(T1 typeDef, T2 type) { if (typeDef != null && type != null) { if (StringUtils.isNotEmpty(typeDef.getGuid())) { typeDefGuidMap.put(typeDef.getGuid(), typeDef); } if (StringUtils.isNotEmpty(typeDef.getName())) { typeDefNameMap.put(typeDef.getName(), typeDef); typeNameMap.put(typeDef.getName(), type); } typeCache.addType(typeDef, type); } } public Collection<T1> getAll() { return Collections.unmodifiableCollection(typeDefNameMap.values()); } public Collection<String> getAllNames() { return Collections.unmodifiableCollection(typeDefNameMap.keySet()); } public T1 getTypeDefByGuid(String guid) { return guid != null ? typeDefGuidMap.get(guid) : null; } public T1 getTypeDefByName(String name) { return name != null ? typeDefNameMap.get(name) : null; } public Collection<T2> getAllTypes() { return Collections.unmodifiableCollection(typeNameMap.values()); } public T2 getTypeByName(String name) { return name != null ? typeNameMap.get(name) : null; } public void updateGuid(String typeName, String newGuid) { if (typeName != null) { T1 typeDef = typeDefNameMap.get(typeName); if (typeDef != null) { String currGuid = typeDef.getGuid(); if (!typeDefGuidMap.containsKey(newGuid) || !StringUtils.equals(currGuid, newGuid)) { if(LOG.isDebugEnabled()) { if (!typeDefGuidMap.containsKey(newGuid)) { LOG.debug("TypeDefGuidMap doesn't contain entry for guid {}. Adding new entry", newGuid); } else { LOG.debug("Removing entry for guid {} and adding entry for guid {}", currGuid, newGuid); } } if (currGuid != null) { typeDefGuidMap.remove(currGuid); } typeDef.setGuid(newGuid); if (newGuid != null) { typeDefGuidMap.put(newGuid, typeDef); } typeCache.updateGuid(typeName, currGuid, newGuid); } } } } public void removeTypeDefByGuid(String guid) { if (guid != null) { T1 typeDef = typeDefGuidMap.remove(guid); typeCache.removeTypeByGuid(guid); String name = typeDef != null ? typeDef.getName() : null; if (name != null) { typeDefNameMap.remove(name); typeNameMap.remove(name); typeCache.removeTypeByName(name); } } } public void removeTypeDefByName(String name) { if (name != null) { T1 typeDef = typeDefNameMap.remove(name); typeNameMap.remove(name); typeCache.removeTypeByName(name); String guid = typeDef != null ? typeDef.getGuid() : null; if (guid != null) { typeDefGuidMap.remove(guid); typeCache.removeTypeByGuid(guid); } } } public void clear() { typeCache.clear(); typeDefGuidMap.clear(); typeDefNameMap.clear(); typeNameMap.clear(); } } <|start_filename|>addons/sqoop-bridge/src/main/java/org/apache/atlas/sqoop/hook/SqoopHook.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.sqoop.hook; import org.apache.atlas.ApplicationProperties; import org.apache.atlas.AtlasClient; import org.apache.atlas.AtlasConstants; import org.apache.atlas.hive.bridge.HiveMetaStoreBridge; import org.apache.atlas.hive.model.HiveDataTypes; import org.apache.atlas.hook.AtlasHook; import org.apache.atlas.hook.AtlasHookException; import org.apache.atlas.notification.hook.HookNotification; import org.apache.atlas.sqoop.model.SqoopDataTypes; import org.apache.atlas.typesystem.Referenceable; import org.apache.commons.configuration.Configuration; import org.apache.commons.lang3.StringUtils; import org.apache.sqoop.SqoopJobDataPublisher; import org.apache.sqoop.util.ImportException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * AtlasHook sends lineage information to the AtlasSever. */ public class SqoopHook extends SqoopJobDataPublisher { private static final Logger LOG = LoggerFactory.getLogger(SqoopHook.class); public static final String CONF_PREFIX = "atlas.hook.sqoop."; public static final String HOOK_NUM_RETRIES = CONF_PREFIX + "numRetries"; public static final String ATLAS_CLUSTER_NAME = "atlas.cluster.name"; public static final String DEFAULT_CLUSTER_NAME = "primary"; public static final String USER = "userName"; public static final String DB_STORE_TYPE = "dbStoreType"; public static final String DB_STORE_USAGE = "storeUse"; public static final String SOURCE = "source"; public static final String DESCRIPTION = "description"; public static final String STORE_URI = "storeUri"; public static final String OPERATION = "operation"; public static final String START_TIME = "startTime"; public static final String END_TIME = "endTime"; public static final String CMD_LINE_OPTS = "commandlineOpts"; // multiple inputs and outputs for process public static final String INPUTS = "inputs"; public static final String OUTPUTS = "outputs"; static { org.apache.hadoop.conf.Configuration.addDefaultResource("sqoop-site.xml"); } public Referenceable createHiveDatabaseInstance(String clusterName, String dbName) { Referenceable dbRef = new Referenceable(HiveDataTypes.HIVE_DB.getName()); dbRef.set(AtlasConstants.CLUSTER_NAME_ATTRIBUTE, clusterName); dbRef.set(AtlasClient.NAME, dbName); dbRef.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, HiveMetaStoreBridge.getDBQualifiedName(clusterName, dbName)); return dbRef; } public Referenceable createHiveTableInstance(String clusterName, Referenceable dbRef, String tableName, String dbName) { Referenceable tableRef = new Referenceable(HiveDataTypes.HIVE_TABLE.getName()); tableRef.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, HiveMetaStoreBridge.getTableQualifiedName(clusterName, dbName, tableName)); tableRef.set(AtlasClient.NAME, tableName.toLowerCase()); tableRef.set(HiveMetaStoreBridge.DB, dbRef); return tableRef; } private Referenceable createDBStoreInstance(SqoopJobDataPublisher.Data data) throws ImportException { Referenceable storeRef = new Referenceable(SqoopDataTypes.SQOOP_DBDATASTORE.getName()); String table = data.getStoreTable(); String query = data.getStoreQuery(); if (StringUtils.isBlank(table) && StringUtils.isBlank(query)) { throw new ImportException("Both table and query cannot be empty for DBStoreInstance"); } String usage = table != null ? "TABLE" : "QUERY"; String source = table != null ? table : query; String name = getSqoopDBStoreName(data); storeRef.set(AtlasClient.NAME, name); storeRef.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, name); storeRef.set(SqoopHook.DB_STORE_TYPE, data.getStoreType()); storeRef.set(SqoopHook.DB_STORE_USAGE, usage); storeRef.set(SqoopHook.STORE_URI, data.getUrl()); storeRef.set(SqoopHook.SOURCE, source); storeRef.set(SqoopHook.DESCRIPTION, ""); storeRef.set(AtlasClient.OWNER, data.getUser()); return storeRef; } private Referenceable createSqoopProcessInstance(Referenceable dbStoreRef, Referenceable hiveTableRef, SqoopJobDataPublisher.Data data, String clusterName) { Referenceable procRef = new Referenceable(SqoopDataTypes.SQOOP_PROCESS.getName()); final String sqoopProcessName = getSqoopProcessName(data, clusterName); procRef.set(AtlasClient.NAME, sqoopProcessName); procRef.set(AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, sqoopProcessName); procRef.set(SqoopHook.OPERATION, data.getOperation()); if (isImportOperation(data)) { procRef.set(SqoopHook.INPUTS, dbStoreRef); procRef.set(SqoopHook.OUTPUTS, hiveTableRef); } else { procRef.set(SqoopHook.INPUTS, hiveTableRef); procRef.set(SqoopHook.OUTPUTS, dbStoreRef); } procRef.set(SqoopHook.USER, data.getUser()); procRef.set(SqoopHook.START_TIME, new Date(data.getStartTime())); procRef.set(SqoopHook.END_TIME, new Date(data.getEndTime())); Map<String, String> sqoopOptionsMap = new HashMap<>(); Properties options = data.getOptions(); for (Object k : options.keySet()) { sqoopOptionsMap.put((String)k, (String) options.get(k)); } procRef.set(SqoopHook.CMD_LINE_OPTS, sqoopOptionsMap); return procRef; } static String getSqoopProcessName(Data data, String clusterName) { StringBuilder name = new StringBuilder(String.format("sqoop %s --connect %s", data.getOperation(), data.getUrl())); if (StringUtils.isNotEmpty(data.getStoreTable())) { name.append(" --table ").append(data.getStoreTable()); } if (StringUtils.isNotEmpty(data.getStoreQuery())) { name.append(" --query ").append(data.getStoreQuery()); } name.append(String.format(" --hive-%s --hive-database %s --hive-table %s --hive-cluster %s", data.getOperation(), data.getHiveDB().toLowerCase(), data.getHiveTable().toLowerCase(), clusterName)); return name.toString(); } static String getSqoopDBStoreName(SqoopJobDataPublisher.Data data) { StringBuilder name = new StringBuilder(String.format("%s --url %s", data.getStoreType(), data.getUrl())); if (StringUtils.isNotEmpty(data.getStoreTable())) { name.append(" --table ").append(data.getStoreTable()); } if (StringUtils.isNotEmpty(data.getStoreQuery())) { name.append(" --query ").append(data.getStoreQuery()); } return name.toString(); } static boolean isImportOperation(SqoopJobDataPublisher.Data data) { return data.getOperation().toLowerCase().equals("import"); } @Override public void publish(SqoopJobDataPublisher.Data data) throws AtlasHookException { try { Configuration atlasProperties = ApplicationProperties.get(); String clusterName = atlasProperties.getString(ATLAS_CLUSTER_NAME, DEFAULT_CLUSTER_NAME); Referenceable dbStoreRef = createDBStoreInstance(data); Referenceable dbRef = createHiveDatabaseInstance(clusterName, data.getHiveDB()); Referenceable hiveTableRef = createHiveTableInstance(clusterName, dbRef, data.getHiveTable(), data.getHiveDB()); Referenceable procRef = createSqoopProcessInstance(dbStoreRef, hiveTableRef, data, clusterName); int maxRetries = atlasProperties.getInt(HOOK_NUM_RETRIES, 3); HookNotification.HookNotificationMessage message = new HookNotification.EntityCreateRequest(AtlasHook.getUser(), dbStoreRef, dbRef, hiveTableRef, procRef); AtlasHook.notifyEntities(Arrays.asList(message), maxRetries); } catch(Exception e) { throw new AtlasHookException("SqoopHook.publish() failed.", e); } } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/audit/EntityAuditListener.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.audit; import org.apache.atlas.AtlasException; import org.apache.atlas.EntityAuditEvent; import org.apache.atlas.EntityAuditEvent.EntityAuditAction; import org.apache.atlas.RequestContextV1; import org.apache.atlas.listener.EntityChangeListener; import org.apache.atlas.typesystem.IReferenceableInstance; import org.apache.atlas.typesystem.IStruct; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.json.InstanceSerialization; import org.apache.atlas.typesystem.types.AttributeInfo; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.inject.Inject; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Listener on entity create/update/delete, tag add/delete. Adds the corresponding audit event to the audit repository. */ @Component public class EntityAuditListener implements EntityChangeListener { private static final Logger LOG = LoggerFactory.getLogger(EntityAuditListener.class); private EntityAuditRepository auditRepository; @Inject public EntityAuditListener(EntityAuditRepository auditRepository) { this.auditRepository = auditRepository; } @Override public void onEntitiesAdded(Collection<ITypedReferenceableInstance> entities, boolean isImport) throws AtlasException { List<EntityAuditEvent> events = new ArrayList<>(); for (ITypedReferenceableInstance entity : entities) { EntityAuditEvent event = createEvent(entity, isImport ? EntityAuditAction.ENTITY_IMPORT_CREATE : EntityAuditAction.ENTITY_CREATE); events.add(event); } auditRepository.putEvents(events); } @Override public void onEntitiesUpdated(Collection<ITypedReferenceableInstance> entities, boolean isImport) throws AtlasException { List<EntityAuditEvent> events = new ArrayList<>(); for (ITypedReferenceableInstance entity : entities) { EntityAuditEvent event = createEvent(entity, isImport ? EntityAuditAction.ENTITY_IMPORT_UPDATE : EntityAuditAction.ENTITY_UPDATE); events.add(event); } auditRepository.putEvents(events); } @Override public void onTraitsAdded(ITypedReferenceableInstance entity, Collection<? extends IStruct> traits) throws AtlasException { if (traits != null) { for (IStruct trait : traits) { EntityAuditEvent event = createEvent(entity, EntityAuditAction.TAG_ADD, "Added trait: " + InstanceSerialization.toJson(trait, true)); auditRepository.putEvents(event); } } } @Override public void onTraitsDeleted(ITypedReferenceableInstance entity, Collection<String> traitNames) throws AtlasException { if (traitNames != null) { for (String traitName : traitNames) { EntityAuditEvent event = createEvent(entity, EntityAuditAction.TAG_DELETE, "Deleted trait: " + traitName); auditRepository.putEvents(event); } } } @Override public void onTraitsUpdated(ITypedReferenceableInstance entity, Collection<? extends IStruct> traits) throws AtlasException { if (traits != null) { for (IStruct trait : traits) { EntityAuditEvent event = createEvent(entity, EntityAuditAction.TAG_UPDATE, "Updated trait: " + InstanceSerialization.toJson(trait, true)); auditRepository.putEvents(event); } } } @Override public void onEntitiesDeleted(Collection<ITypedReferenceableInstance> entities, boolean isImport) throws AtlasException { List<EntityAuditEvent> events = new ArrayList<>(); for (ITypedReferenceableInstance entity : entities) { EntityAuditEvent event = createEvent(entity, isImport ? EntityAuditAction.ENTITY_IMPORT_DELETE : EntityAuditAction.ENTITY_DELETE, "Deleted entity"); events.add(event); } auditRepository.putEvents(events); } public List<EntityAuditEvent> getAuditEvents(String guid) throws AtlasException{ return auditRepository.listEvents(guid, null, (short) 10); } private EntityAuditEvent createEvent(ITypedReferenceableInstance entity, EntityAuditAction action) throws AtlasException { String detail = getAuditEventDetail(entity, action); return createEvent(entity, action, detail); } private EntityAuditEvent createEvent(ITypedReferenceableInstance entity, EntityAuditAction action, String details) throws AtlasException { return new EntityAuditEvent(entity.getId()._getId(), RequestContextV1.get().getRequestTime(), RequestContextV1.get().getUser(), action, details, entity); } private String getAuditEventDetail(ITypedReferenceableInstance entity, EntityAuditAction action) throws AtlasException { Map<String, Object> prunedAttributes = pruneEntityAttributesForAudit(entity); String auditPrefix = getAuditPrefix(action); String auditString = auditPrefix + InstanceSerialization.toJson(entity, true); byte[] auditBytes = auditString.getBytes(StandardCharsets.UTF_8); long auditSize = auditBytes != null ? auditBytes.length : 0; long auditMaxSize = auditRepository.repositoryMaxSize(); if (auditMaxSize >= 0 && auditSize > auditMaxSize) { // don't store attributes in audit LOG.warn("audit record too long: entityType={}, guid={}, size={}; maxSize={}. entity attribute values not stored in audit", entity.getTypeName(), entity.getId()._getId(), auditSize, auditMaxSize); Map<String, Object> attrValues = entity.getValuesMap(); clearAttributeValues(entity); auditString = auditPrefix + InstanceSerialization.toJson(entity, true); addAttributeValues(entity, attrValues); } restoreEntityAttributes(entity, prunedAttributes); return auditString; } private void clearAttributeValues(IReferenceableInstance entity) throws AtlasException { Map<String, Object> attributesMap = entity.getValuesMap(); if (MapUtils.isNotEmpty(attributesMap)) { for (String attribute : attributesMap.keySet()) { entity.setNull(attribute); } } } private void addAttributeValues(ITypedReferenceableInstance entity, Map<String, Object> attributesMap) throws AtlasException { if (MapUtils.isNotEmpty(attributesMap)) { for (String attr : attributesMap.keySet()) { entity.set(attr, attributesMap.get(attr)); } } } private Map<String, Object> pruneEntityAttributesForAudit(ITypedReferenceableInstance entity) throws AtlasException { Map<String, Object> ret = null; Map<String, Object> entityAttributes = entity.getValuesMap(); List<String> excludeAttributes = auditRepository.getAuditExcludeAttributes(entity.getTypeName()); if (CollectionUtils.isNotEmpty(excludeAttributes) && MapUtils.isNotEmpty(entityAttributes)) { Map<String, AttributeInfo> attributeInfoMap = entity.fieldMapping().fields; for (String attrName : entityAttributes.keySet()) { Object attrValue = entityAttributes.get(attrName); AttributeInfo attrInfo = attributeInfoMap.get(attrName); if (excludeAttributes.contains(attrName)) { if (ret == null) { ret = new HashMap<>(); } ret.put(attrName, attrValue); entity.setNull(attrName); } else if (attrInfo.isComposite) { if (attrValue instanceof Collection) { for (Object attribute : (Collection) attrValue) { if (attribute instanceof ITypedReferenceableInstance) { ret = pruneAttributes(ret, (ITypedReferenceableInstance) attribute); } } } else if (attrValue instanceof ITypedReferenceableInstance) { ret = pruneAttributes(ret, (ITypedReferenceableInstance) attrValue); } } } } return ret; } private Map<String, Object> pruneAttributes(Map<String, Object> ret, ITypedReferenceableInstance attribute) throws AtlasException { ITypedReferenceableInstance attrInstance = attribute; Map<String, Object> prunedAttrs = pruneEntityAttributesForAudit(attrInstance); if (MapUtils.isNotEmpty(prunedAttrs)) { if (ret == null) { ret = new HashMap<>(); } ret.put(attrInstance.getId()._getId(), prunedAttrs); } return ret; } private void restoreEntityAttributes(ITypedReferenceableInstance entity, Map<String, Object> prunedAttributes) throws AtlasException { if (MapUtils.isEmpty(prunedAttributes)) { return; } Map<String, Object> entityAttributes = entity.getValuesMap(); if (MapUtils.isNotEmpty(entityAttributes)) { Map<String, AttributeInfo> attributeInfoMap = entity.fieldMapping().fields; for (String attrName : entityAttributes.keySet()) { Object attrValue = entityAttributes.get(attrName); AttributeInfo attrInfo = attributeInfoMap.get(attrName); if (prunedAttributes.containsKey(attrName)) { entity.set(attrName, prunedAttributes.get(attrName)); } else if (attrInfo.isComposite) { if (attrValue instanceof Collection) { for (Object attributeEntity : (Collection) attrValue) { if (attributeEntity instanceof ITypedReferenceableInstance) { restoreAttributes(prunedAttributes, (ITypedReferenceableInstance) attributeEntity); } } } else if (attrValue instanceof ITypedReferenceableInstance) { restoreAttributes(prunedAttributes, (ITypedReferenceableInstance) attrValue); } } } } } private void restoreAttributes(Map<String, Object> prunedAttributes, ITypedReferenceableInstance attributeEntity) throws AtlasException { Object obj = prunedAttributes.get(attributeEntity.getId()._getId()); if (obj instanceof Map) { restoreEntityAttributes(attributeEntity, (Map) obj); } } private String getAuditPrefix(EntityAuditAction action) { final String ret; switch (action) { case ENTITY_CREATE: ret = "Created: "; break; case ENTITY_UPDATE: ret = "Updated: "; break; case ENTITY_DELETE: ret = "Deleted: "; break; case TAG_ADD: ret = "Added trait: "; break; case TAG_DELETE: ret = "Deleted trait: "; break; case TAG_UPDATE: ret = "Updated trait: "; break; case ENTITY_IMPORT_CREATE: ret = "Created by import: "; break; case ENTITY_IMPORT_UPDATE: ret = "Updated by import: "; break; case ENTITY_IMPORT_DELETE: ret = "Deleted by import: "; break; default: ret = "Unknown: "; } return ret; } } <|start_filename|>repository/src/main/java/org/apache/atlas/gremlin/optimizer/IsOr.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.gremlin.optimizer; import com.google.common.base.Function; import org.apache.atlas.groovy.FunctionCallExpression; import org.apache.atlas.groovy.GroovyExpression; import org.apache.atlas.groovy.TraversalStepType; /** * Function that tests whether the expression is an 'or' * graph traversal function. */ public final class IsOr implements Function<GroovyExpression, Boolean> { public static final IsOr INSTANCE = new IsOr(); private IsOr() { } @Override public Boolean apply(GroovyExpression expr) { if (!(expr instanceof FunctionCallExpression)) { return false; } if (expr.getType() != TraversalStepType.FILTER) { return false; } FunctionCallExpression functionCall = (FunctionCallExpression)expr; return functionCall.getFunctionName().equals("or"); } } <|start_filename|>repository/src/main/java/org/apache/atlas/discovery/SearchContext.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.discovery; import org.apache.atlas.model.discovery.SearchParameters; import org.apache.atlas.model.discovery.SearchParameters.FilterCriteria; import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.type.AtlasClassificationType; import org.apache.atlas.type.AtlasEntityType; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import java.util.HashSet; import java.util.Set; public class SearchContext { private final SearchParameters searchParameters; private final AtlasTypeRegistry typeRegistry; private final AtlasGraph graph; private final Set<String> indexedKeys; private final Set<String> entityAttributes; private final AtlasEntityType entityType; private final AtlasClassificationType classificationType; private SearchProcessor searchProcessor; private boolean terminateSearch = false; public SearchContext(SearchParameters searchParameters, AtlasTypeRegistry typeRegistry, AtlasGraph graph, Set<String> indexedKeys) { this.searchParameters = searchParameters; this.typeRegistry = typeRegistry; this.graph = graph; this.indexedKeys = indexedKeys; this.entityAttributes = new HashSet<>(); this.entityType = typeRegistry.getEntityTypeByName(searchParameters.getTypeName()); this.classificationType = typeRegistry.getClassificationTypeByName(searchParameters.getClassification()); if (needFullTextrocessor()) { addProcessor(new FullTextSearchProcessor(this)); } if (needClassificationProcessor()) { addProcessor(new ClassificationSearchProcessor(this)); } if (needEntityProcessor()) { addProcessor(new EntitySearchProcessor(this)); } } public SearchParameters getSearchParameters() { return searchParameters; } public AtlasTypeRegistry getTypeRegistry() { return typeRegistry; } public AtlasGraph getGraph() { return graph; } public Set<String> getIndexedKeys() { return indexedKeys; } public Set<String> getEntityAttributes() { return entityAttributes; } public AtlasEntityType getEntityType() { return entityType; } public AtlasClassificationType getClassificationType() { return classificationType; } public SearchProcessor getSearchProcessor() { return searchProcessor; } public boolean terminateSearch() { return this.terminateSearch; } public void terminateSearch(boolean terminateSearch) { this.terminateSearch = terminateSearch; } public StringBuilder toString(StringBuilder sb) { if (sb == null) { sb = new StringBuilder(); } sb.append("searchParameters="); if (searchParameters != null) { searchParameters.toString(sb); } return sb; } @Override public String toString() { return toString(new StringBuilder()).toString(); } boolean needFullTextrocessor() { return StringUtils.isNotEmpty(searchParameters.getQuery()); } boolean needClassificationProcessor() { return classificationType != null && (entityType == null || hasAttributeFilter(searchParameters.getTagFilters())); } boolean needEntityProcessor() { return entityType != null; } private boolean hasAttributeFilter(FilterCriteria filterCriteria) { return filterCriteria != null && (CollectionUtils.isNotEmpty(filterCriteria.getCriterion()) || StringUtils.isNotEmpty(filterCriteria.getAttributeName())); } private void addProcessor(SearchProcessor processor) { if (this.searchProcessor == null) { this.searchProcessor = processor; } else { this.searchProcessor.addProcessor(processor); } } } <|start_filename|>intg/src/test/java/org/apache/atlas/TestRelationshipUtilsV2.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.instance.AtlasEntity; import org.apache.atlas.model.instance.AtlasEntity.AtlasEntitiesWithExtInfo; import org.apache.atlas.model.instance.AtlasStruct; import org.apache.atlas.model.typedef.AtlasBaseTypeDef; import org.apache.atlas.model.typedef.AtlasClassificationDef; import org.apache.atlas.model.typedef.AtlasEntityDef; import org.apache.atlas.model.typedef.AtlasEnumDef; import org.apache.atlas.model.typedef.AtlasEnumDef.AtlasEnumElementDef; import org.apache.atlas.model.typedef.AtlasRelationshipDef; import org.apache.atlas.model.typedef.AtlasRelationshipEndDef; import org.apache.atlas.model.typedef.AtlasStructDef; import org.apache.atlas.model.typedef.AtlasTypesDef; import org.apache.atlas.type.AtlasTypeUtil; import org.apache.commons.lang.StringUtils; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.getArrayTypeName; import static org.apache.atlas.model.typedef.AtlasBaseTypeDef.getMapTypeName; import static org.apache.atlas.model.typedef.AtlasRelationshipDef.PropagateTags.ONE_TO_TWO; import static org.apache.atlas.model.typedef.AtlasRelationshipDef.RelationshipCategory.AGGREGATION; import static org.apache.atlas.model.typedef.AtlasRelationshipDef.RelationshipCategory.ASSOCIATION; import static org.apache.atlas.model.typedef.AtlasStructDef.AtlasAttributeDef.Cardinality.SET; import static org.apache.atlas.model.typedef.AtlasStructDef.AtlasAttributeDef.Cardinality.SINGLE; import static org.apache.atlas.type.AtlasTypeUtil.createClassTypeDef; import static org.apache.atlas.type.AtlasTypeUtil.createOptionalAttrDef; import static org.apache.atlas.type.AtlasTypeUtil.createRequiredAttrDef; import static org.apache.atlas.type.AtlasTypeUtil.createStructTypeDef; import static org.apache.atlas.type.AtlasTypeUtil.createTraitTypeDef; import static org.apache.atlas.type.AtlasTypeUtil.createUniqueRequiredAttrDef; import static org.apache.atlas.type.AtlasTypeUtil.getAtlasObjectId; /** * Test utility class for relationship. */ public final class TestRelationshipUtilsV2 { public static final String ORG_LEVEL_TYPE = "OrgLevel"; public static final String SECURITY_CLEARANCE_TYPE = "SecurityClearance"; public static final String ADDRESS_TYPE = "Address"; public static final String PERSON_TYPE = "Person"; public static final String MANAGER_TYPE = "Manager"; public static final String DEPARTMENT_TYPE = "Department"; public static final String EMPLOYEE_TYPE = "Employee"; public static final String EMPLOYEE_DEPARTMENT_TYPE = "EmployeeDepartment"; public static final String EMPLOYEE_MANAGER_TYPE = "EmployeeManager"; public static final String EMPLOYEE_MENTOR_TYPE = "EmployeeMentor"; public static final String TYPE_A = "A"; public static final String TYPE_B = "B"; public static final String DEFAULT_VERSION = "1.0"; private TestRelationshipUtilsV2() { } public static AtlasTypesDef getDepartmentEmployeeTypes() throws AtlasBaseException { /******* Person Type *******/ AtlasEntityDef personType = createClassTypeDef(PERSON_TYPE, description(PERSON_TYPE), superType(null), createUniqueRequiredAttrDef("name", "string"), createOptionalAttrDef("address", ADDRESS_TYPE), createOptionalAttrDef("birthday", "date"), createOptionalAttrDef("hasPets", "boolean"), createOptionalAttrDef("numberOfCars", "byte"), createOptionalAttrDef("houseNumber", "short"), createOptionalAttrDef("carMileage", "int"), createOptionalAttrDef("age", "float"), createOptionalAttrDef("numberOfStarsEstimate", "biginteger"), createOptionalAttrDef("approximationOfPi", "bigdecimal")); /******* Employee Type *******/ AtlasEntityDef employeeType = createClassTypeDef(EMPLOYEE_TYPE, description(EMPLOYEE_TYPE), superType(PERSON_TYPE), createOptionalAttrDef("orgLevel", ORG_LEVEL_TYPE), createOptionalAttrDef("shares", "long"), createOptionalAttrDef("salary", "double")); /******* Department Type *******/ AtlasEntityDef departmentType = createClassTypeDef(DEPARTMENT_TYPE, description(DEPARTMENT_TYPE), superType(null), createUniqueRequiredAttrDef("name", "string")); /******* Manager Type *******/ AtlasEntityDef managerType = createClassTypeDef(MANAGER_TYPE, description(MANAGER_TYPE), superType(EMPLOYEE_TYPE)); /******* Address Type *******/ AtlasStructDef addressType = createStructTypeDef(ADDRESS_TYPE, description(ADDRESS_TYPE), createRequiredAttrDef("street", "string"), createRequiredAttrDef("city", "string")); /******* Organization Level Type *******/ AtlasEnumDef orgLevelType = new AtlasEnumDef(ORG_LEVEL_TYPE, description(ORG_LEVEL_TYPE), DEFAULT_VERSION, getOrgLevelElements()); /******* Security Clearance Type *******/ AtlasClassificationDef securityClearanceType = createTraitTypeDef(SECURITY_CLEARANCE_TYPE, description(SECURITY_CLEARANCE_TYPE), superType(null), createRequiredAttrDef("level", "int")); /******* [Department -> Employee] Relationship *******/ AtlasRelationshipDef employeeDepartmentType = new AtlasRelationshipDef(EMPLOYEE_DEPARTMENT_TYPE, description(EMPLOYEE_DEPARTMENT_TYPE), DEFAULT_VERSION, AGGREGATION, ONE_TO_TWO, new AtlasRelationshipEndDef(EMPLOYEE_TYPE, "department", SINGLE), new AtlasRelationshipEndDef(DEPARTMENT_TYPE, "employees", SET, true)); /******* [Manager -> Employee] Relationship *******/ AtlasRelationshipDef employeeManagerType = new AtlasRelationshipDef(EMPLOYEE_MANAGER_TYPE, description(EMPLOYEE_MANAGER_TYPE), DEFAULT_VERSION, AGGREGATION, ONE_TO_TWO, new AtlasRelationshipEndDef(EMPLOYEE_TYPE, "manager", SINGLE), new AtlasRelationshipEndDef(MANAGER_TYPE, "subordinates", SET, true)); /******* [Mentor -> Employee] Relationship *******/ AtlasRelationshipDef employeeMentorType = new AtlasRelationshipDef(EMPLOYEE_MENTOR_TYPE, description(EMPLOYEE_MENTOR_TYPE), DEFAULT_VERSION, ASSOCIATION, ONE_TO_TWO, new AtlasRelationshipEndDef(EMPLOYEE_TYPE, "mentor", SINGLE), new AtlasRelationshipEndDef(EMPLOYEE_TYPE, "mentees", SET)); return new AtlasTypesDef(ImmutableList.of(orgLevelType), ImmutableList.of(addressType), ImmutableList.of(securityClearanceType), ImmutableList.of(personType, employeeType, departmentType, managerType), ImmutableList.of(employeeDepartmentType, employeeManagerType, employeeMentorType)); } public static AtlasEntitiesWithExtInfo getDepartmentEmployeeInstances() { AtlasEntitiesWithExtInfo ret = new AtlasEntitiesWithExtInfo(); /******* Department - HR *******/ AtlasEntity hrDept = new AtlasEntity(DEPARTMENT_TYPE, "name", "hr"); /******* Address *******/ AtlasStruct janeAddr = new AtlasStruct(ADDRESS_TYPE); janeAddr.setAttribute("street", "Great America Parkway"); janeAddr.setAttribute("city", "Santa Clara"); AtlasStruct juliusAddr = new AtlasStruct(ADDRESS_TYPE); juliusAddr.setAttribute("street", "Madison Ave"); juliusAddr.setAttribute("city", "Newtonville"); AtlasStruct maxAddr = new AtlasStruct(ADDRESS_TYPE); maxAddr.setAttribute("street", "Ripley St"); maxAddr.setAttribute("city", "Newton"); AtlasStruct johnAddr = new AtlasStruct(ADDRESS_TYPE); johnAddr.setAttribute("street", "Stewart Drive"); johnAddr.setAttribute("city", "Sunnyvale"); /******* Manager - Jane (John and Max subordinates) *******/ AtlasEntity jane = new AtlasEntity(MANAGER_TYPE); jane.setAttribute("name", "Jane"); jane.setRelationshipAttribute("department", getAtlasObjectId(hrDept)); jane.setAttribute("address", janeAddr); /******* Manager - Julius (no subordinates) *******/ AtlasEntity julius = new AtlasEntity(MANAGER_TYPE); julius.setAttribute("name", "Julius"); julius.setRelationshipAttribute("department", getAtlasObjectId(hrDept)); julius.setAttribute("address", juliusAddr); /******* Employee - Max (Manager: Jane, Mentor: Julius) *******/ AtlasEntity max = new AtlasEntity(EMPLOYEE_TYPE); max.setAttribute("name", "Max"); max.setRelationshipAttribute("department", getAtlasObjectId(hrDept)); max.setAttribute("address", maxAddr); max.setRelationshipAttribute("manager", getAtlasObjectId(jane)); max.setRelationshipAttribute("mentor", getAtlasObjectId(julius)); max.setAttribute("birthday",new Date(1979, 3, 15)); max.setAttribute("hasPets", true); max.setAttribute("age", 36); max.setAttribute("numberOfCars", 2); max.setAttribute("houseNumber", 17); max.setAttribute("carMileage", 13); max.setAttribute("shares", Long.MAX_VALUE); max.setAttribute("salary", Double.MAX_VALUE); max.setAttribute("numberOfStarsEstimate", new BigInteger("1000000000000000000000000000000")); max.setAttribute("approximationOfPi", new BigDecimal("3.1415926535897932")); /******* Employee - John (Manager: Jane, Mentor: Max) *******/ AtlasEntity john = new AtlasEntity(EMPLOYEE_TYPE); john.setAttribute("name", "John"); john.setRelationshipAttribute("department", getAtlasObjectId(hrDept)); john.setAttribute("address", johnAddr); john.setRelationshipAttribute("manager", getAtlasObjectId(jane)); john.setRelationshipAttribute("mentor", getAtlasObjectId(max)); john.setAttribute("birthday",new Date(1950, 5, 15)); john.setAttribute("hasPets", true); john.setAttribute("numberOfCars", 1); john.setAttribute("houseNumber", 153); john.setAttribute("carMileage", 13364); john.setAttribute("shares", 15000); john.setAttribute("salary", 123345.678); john.setAttribute("age", 50); john.setAttribute("numberOfStarsEstimate", new BigInteger("1000000000000000000000")); john.setAttribute("approximationOfPi", new BigDecimal("3.141592653589793238462643383279502884197169399375105820974944592307816406286")); ret.addEntity(hrDept); ret.addEntity(jane); ret.addEntity(julius); ret.addEntity(max); ret.addEntity(john); return ret; } public static AtlasTypesDef getInverseReferenceTestTypes() throws AtlasBaseException { AtlasEntityDef aType = createClassTypeDef(TYPE_A, superType(null), createUniqueRequiredAttrDef("name", "string")); AtlasEntityDef bType = createClassTypeDef(TYPE_B, superType(null), createUniqueRequiredAttrDef("name", "string")); AtlasRelationshipDef relationshipType1 = new AtlasRelationshipDef("TypeA_to_TypeB_on_b", description("TypeA_to_TypeB_on_b"), DEFAULT_VERSION, ASSOCIATION, ONE_TO_TWO, new AtlasRelationshipEndDef(TYPE_A, "b", SINGLE), new AtlasRelationshipEndDef(TYPE_B, "a", SINGLE)); AtlasRelationshipDef relationshipType2 = new AtlasRelationshipDef("TypeA_to_TypeB_on_oneB", description("TypeA_to_TypeB_on_oneB"), DEFAULT_VERSION, ASSOCIATION, ONE_TO_TWO, new AtlasRelationshipEndDef(TYPE_A, "oneB", SINGLE), new AtlasRelationshipEndDef(TYPE_B, "manyA", SET)); AtlasRelationshipDef relationshipType3 = new AtlasRelationshipDef("TypeA_to_TypeB_on_manyB", description("TypeA_to_TypeB_on_manyB"), DEFAULT_VERSION, ASSOCIATION, ONE_TO_TWO, new AtlasRelationshipEndDef(TYPE_A, "manyB", SET), new AtlasRelationshipEndDef(TYPE_B, "manyToManyA", SET)); AtlasRelationshipDef relationshipType4 = new AtlasRelationshipDef("TypeB_to_TypeA_on_mappedFromA", description("TypeB_to_TypeA_on_mappedFromA"), DEFAULT_VERSION, ASSOCIATION, ONE_TO_TWO, new AtlasRelationshipEndDef(TYPE_B, "mappedFromA", SINGLE), new AtlasRelationshipEndDef(TYPE_A, "mapToB", SET)); return new AtlasTypesDef(ImmutableList.<AtlasEnumDef>of(), ImmutableList.<AtlasStructDef>of(), ImmutableList.<AtlasClassificationDef>of(), ImmutableList.of(aType, bType), ImmutableList.of(relationshipType1, relationshipType2, relationshipType3, relationshipType4)); } private static List<AtlasEnumElementDef> getOrgLevelElements() { return Arrays.asList( new AtlasEnumElementDef("L1", description("L1"), 1), new AtlasEnumElementDef("L2", description("L2"), 2), new AtlasEnumElementDef("L3", description("L3"), 3) ); } private static String description(String typeName) { return typeName + " description"; } private static ImmutableSet<String> superType(String superTypeName) { return StringUtils.isNotEmpty(superTypeName) ? ImmutableSet.of(superTypeName) : ImmutableSet.<String>of(); } } <|start_filename|>repository/src/main/java/org/apache/atlas/repository/IRepository.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository; import org.apache.atlas.typesystem.IReferenceableInstance; import org.apache.atlas.typesystem.ITypedReferenceableInstance; import org.apache.atlas.typesystem.persistence.Id; import org.apache.atlas.typesystem.types.ClassType; import org.apache.atlas.typesystem.types.HierarchicalType; import org.apache.atlas.typesystem.types.TraitType; import java.util.List; /** * Metadata Repository interface. */ @Deprecated public interface IRepository { ITypedReferenceableInstance create(IReferenceableInstance i) throws RepositoryException; ITypedReferenceableInstance update(ITypedReferenceableInstance i) throws RepositoryException; void delete(ITypedReferenceableInstance i) throws RepositoryException; Id newId(String typeName); ITypedReferenceableInstance get(Id id) throws RepositoryException; void defineClass(ClassType type) throws RepositoryException; void defineTrait(TraitType type) throws RepositoryException; void defineTypes(List<HierarchicalType> types) throws RepositoryException; } <|start_filename|>typesystem/src/main/java/org/apache/atlas/typesystem/Referenceable.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.typesystem; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.apache.atlas.AtlasException; import org.apache.atlas.classification.InterfaceAudience; import org.apache.atlas.typesystem.persistence.AtlasSystemAttributes; import org.apache.atlas.typesystem.persistence.Id; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; /** * Represents a Class Instance that has not been associated with a FieldMapping. */ public class Referenceable extends Struct implements IReferenceableInstance { private Id id; private final ImmutableMap<String, IStruct> traits; private final ImmutableList<String> traitNames; private AtlasSystemAttributes systemAttributes; public Referenceable(String typeName, String... traitNames) { super(typeName); id = new Id(typeName); this.traitNames = ImmutableList.copyOf(traitNames); ImmutableMap.Builder<String, IStruct> b = new ImmutableMap.Builder<>(); for (String t : traitNames) { b.put(t, new Struct(t)); } traits = b.build(); this.systemAttributes = new AtlasSystemAttributes(); } public Referenceable(String typeName, Map<String, Object> values) { super(typeName, values); id = new Id(typeName); traitNames = ImmutableList.of(); traits = ImmutableMap.of(); this.systemAttributes = new AtlasSystemAttributes(); } public Referenceable(String guid, String typeName, Map<String, Object> values) { super(typeName, values); id = new Id(guid, 0, typeName); traitNames = ImmutableList.of(); traits = ImmutableMap.of(); this.systemAttributes = new AtlasSystemAttributes(); } /** * Not public - only use during deserialization * @param guid the unique id * @param typeName the type name * @param values the entity attribute values */ @InterfaceAudience.Private public Referenceable(String guid, String typeName, Map<String, Object> values, List<String> _traitNames, Map<String, IStruct> _traits) { super(typeName, values); id = new Id(guid, 0, typeName); traitNames = ImmutableList.copyOf(_traitNames); traits = ImmutableMap.copyOf(_traits); this.systemAttributes = new AtlasSystemAttributes(); } /** * Not public - only use during deserialization * @param id entity id * @param typeName the type name * @param values the entity attribute values */ @InterfaceAudience.Private public Referenceable(Id id, String typeName, Map<String, Object> values, List<String> _traitNames, Map<String, IStruct> _traits) { super(typeName, values); this.id = id; traitNames = ImmutableList.copyOf(_traitNames); traits = ImmutableMap.copyOf(_traits); this.systemAttributes = new AtlasSystemAttributes(); } /** * Not public - only use during deserialization * @param id entity id * @param typeName the type name * @param values the entity attribute values */ @InterfaceAudience.Private public Referenceable(Id id, String typeName, Map<String, Object> values, List<String> _traitNames, Map<String, IStruct> _traits, AtlasSystemAttributes systemAttributes) { super(typeName, values); this.id = id; traitNames = ImmutableList.copyOf(_traitNames); traits = ImmutableMap.copyOf(_traits); this.systemAttributes = systemAttributes; } /** * Construct a Referenceable from the given IReferenceableInstance. * * @param instance the referenceable instance to copy * * @throws AtlasException if the referenceable can not be created */ public Referenceable(IReferenceableInstance instance) throws AtlasException { this(instance.getId(), instance.getTypeName(), instance.getValuesMap(), instance.getTraits(), getTraits(instance)); } /** * No-arg constructor for serialization. */ @SuppressWarnings("unused") private Referenceable() { super(null, null); id = null; traitNames = ImmutableList.of(); traits = ImmutableMap.of(); } @Override public ImmutableList<String> getTraits() { return traitNames; } @Override public Id getId() { return id; } @Override public IStruct getTrait(String typeName) { return traits.get(typeName); } @Override public AtlasSystemAttributes getSystemAttributes(){ return systemAttributes; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass() || !super.equalsContents(o)) return false; Referenceable that = (Referenceable) o; return Objects.equals(id, that.id) && Objects.equals(traits, that.traits) && Objects.equals(traitNames, that.traitNames); } @Override public int hashCode() { return Objects.hash(super.hashCode(), id, traits, traitNames); } /** * Matches traits, values associated with this Referenceable and skips the id match * @param o The Referenceable which needs to be matched with * @return */ public boolean equalsContents(Object o) { if(this == o) { return true; } if(o == null) { return false; } if (o.getClass() != getClass()) { return false; } if(!super.equalsContents(o)) { return false; } Referenceable obj = (Referenceable)o; if (!traitNames.equals(obj.getTraits())) { return false; } return true; } public String toString() { return "{" + "Id='" + id + '\'' + ", traits=" + traitNames + ", values=" + getValuesMap() + '}'; } @Override public String toShortString() { return String.format("entity[type=%s guid=%s]", typeName, id._getId()); } public void replaceWithNewId(Id id) { this.id = id; } private static Map<String, IStruct> getTraits(IReferenceableInstance instance) throws AtlasException { Map<String, IStruct> traits = new HashMap<>(); for (String traitName : instance.getTraits() ) { traits.put(traitName, new Struct(traitName, instance.getTrait(traitName).getValuesMap())); } return traits; } } <|start_filename|>repository/src/test/java/org/apache/atlas/repository/impexp/ImportServiceTestUtils.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.impexp; import com.google.common.collect.Sets; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.impexp.AtlasExportResult; import org.apache.atlas.model.impexp.AtlasImportRequest; import org.apache.atlas.model.impexp.AtlasImportResult; import org.apache.atlas.model.typedef.AtlasTypesDef; import org.apache.atlas.repository.store.bootstrap.AtlasTypeDefStoreInitializer; import org.apache.atlas.store.AtlasTypeDefStore; import org.apache.atlas.type.AtlasType; import org.apache.atlas.type.AtlasTypeRegistry; import org.testng.Assert; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; public class ImportServiceTestUtils { public static void verifyImportedEntities(List<String> creationOrder, List<String> processedEntities) { Set<String> lhs = com.google.common.collect.Sets.newHashSet(creationOrder); Set<String> rhs = com.google.common.collect.Sets.newHashSet(processedEntities); Set<String> difference = Sets.difference(lhs, rhs); Assert.assertNotNull(difference); Assert.assertEquals(difference.size(), 0); } public static void verifyImportedMetrics(AtlasExportResult exportResult, AtlasImportResult importResult) { Map<String, Integer> metricsForCompare = getImportMetricsForCompare(importResult); for (Map.Entry<String, Integer> entry : exportResult.getMetrics().entrySet()) { if(entry.getKey().startsWith("entity") == false || entry.getKey().contains("withExtInfo") || entry.getKey().contains("Column") || entry.getKey().contains("StorageDesc")) continue; Assert.assertTrue(metricsForCompare.containsKey(entry.getKey())); Assert.assertEquals(entry.getValue(), metricsForCompare.get(entry.getKey())); } } private static Map<String,Integer> getImportMetricsForCompare(AtlasImportResult result) { Map<String, Integer> r = new HashMap<>(); for (Map.Entry<String, Integer> entry : result.getMetrics().entrySet()) { r.put(entry.getKey().replace(":updated", "").replace(":created", ""), entry.getValue()); } return r; } public static void loadModelFromJson(String fileName, AtlasTypeDefStore typeDefStore, AtlasTypeRegistry typeRegistry) throws IOException, AtlasBaseException { AtlasTypesDef typesFromJson = getAtlasTypesDefFromFile(fileName); createTypesAsNeeded(typesFromJson, typeDefStore, typeRegistry); } private static void createTypesAsNeeded(AtlasTypesDef typesFromJson, AtlasTypeDefStore typeDefStore, AtlasTypeRegistry typeRegistry) throws AtlasBaseException { AtlasTypesDef typesToCreate = AtlasTypeDefStoreInitializer.getTypesToCreate(typesFromJson, typeRegistry); if (!typesToCreate.isEmpty()) { typeDefStore.createTypesDef(typesToCreate); } } private static AtlasTypesDef getAtlasTypesDefFromFile(String fileName) throws IOException { String sampleTypes = ZipFileResourceTestUtils.getModelJson(fileName); return AtlasType.fromJson(sampleTypes, AtlasTypesDef.class); } public static AtlasImportRequest getDefaultImportRequest() { return new AtlasImportRequest(); } public static AtlasImportResult runImportWithParameters(ImportService importService, AtlasImportRequest request, ZipSource source) throws AtlasBaseException, IOException { final String requestingIP = "1.0.0.0"; final String hostName = "localhost"; final String userName = "admin"; AtlasImportResult result = importService.run(source, request, userName, hostName, requestingIP); Assert.assertEquals(result.getOperationStatus(), AtlasImportResult.OperationStatus.SUCCESS); return result; } public static void runAndVerifyQuickStart_v1_Import(ImportService importService, ZipSource zipSource) throws AtlasBaseException, IOException { AtlasExportResult exportResult = zipSource.getExportResult(); List<String> creationOrder = zipSource.getCreationOrder(); AtlasImportRequest request = getDefaultImportRequest(); AtlasImportResult result = runImportWithParameters(importService, request, zipSource); Assert.assertNotNull(result); verifyImportedMetrics(exportResult, result); verifyImportedEntities(creationOrder, result.getProcessedEntities()); } } <|start_filename|>client/src/test/java/org/apache/atlas/AtlasClientTest.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import org.apache.atlas.model.legacy.EntityResult; import org.apache.atlas.typesystem.Referenceable; import org.apache.atlas.typesystem.json.InstanceSerialization; import org.apache.commons.configuration.Configuration; import org.apache.hadoop.security.UserGroupInformation; import org.codehaus.jettison.json.JSONObject; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import java.net.ConnectException; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.List; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; public class AtlasClientTest { @Mock private WebResource service; @Mock private WebResource.Builder resourceBuilderMock; @Mock private Configuration configuration; @Mock private Client client; @BeforeMethod public void setup() { MockitoAnnotations.initMocks(this); } @Test public void shouldVerifyServerIsReady() throws AtlasServiceException { setupRetryParams(); AtlasClient atlasClient = new AtlasClient(service, configuration); WebResource.Builder builder = setupBuilder(AtlasClient.API.VERSION, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); when(response.getEntity(String.class)).thenReturn("{\"Version\":\"version-rrelease\",\"Name\":\"apache-atlas\"," + "\"Description\":\"Metadata Management and Data Governance Platform over Hadoop\"}"); when(builder.method(AtlasClient.API.VERSION.getMethod(), ClientResponse.class, null)).thenReturn(response); assertTrue(atlasClient.isServerReady()); } @Test public void testCreateEntity() throws Exception { setupRetryParams(); AtlasClient atlasClient = new AtlasClient(service, configuration); WebResource.Builder builder = setupBuilder(AtlasClient.API.CREATE_ENTITY, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.CREATED.getStatusCode()); JSONObject jsonResponse = new JSONObject(new EntityResult(Arrays.asList("id"), null, null).toString()); when(response.getEntity(String.class)).thenReturn(jsonResponse.toString()); when(response.getLength()).thenReturn(jsonResponse.length()); String entityJson = InstanceSerialization.toJson(new Referenceable("type"), true); when(builder.method(anyString(), Matchers.<Class>any(), anyString())).thenReturn(response); List<String> ids = atlasClient.createEntity(entityJson); assertEquals(ids.size(), 1); assertEquals(ids.get(0), "id"); } private WebResource.Builder setupBuilder(AtlasClient.API api, WebResource webResource) { when(webResource.path(api.getPath())).thenReturn(service); return getBuilder(service); } @Test public void shouldReturnFalseIfServerIsNotReady() throws AtlasServiceException { setupRetryParams(); AtlasClient atlasClient = new AtlasClient(service, configuration); WebResource.Builder builder = setupBuilder(AtlasClient.API.VERSION, service); when(builder.method(AtlasClient.API.VERSION.getMethod(), ClientResponse.class, null)).thenThrow( new ClientHandlerException()); assertFalse(atlasClient.isServerReady()); } @Test public void shouldReturnFalseIfServiceIsUnavailable() throws AtlasServiceException { setupRetryParams(); AtlasClient atlasClient = new AtlasClient(service, configuration); WebResource.Builder builder = setupBuilder(AtlasClient.API.VERSION, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.SERVICE_UNAVAILABLE.getStatusCode()); when(response.getClientResponseStatus()).thenReturn(ClientResponse.Status.SERVICE_UNAVAILABLE); when(builder.method(AtlasClient.API.VERSION.getMethod(), ClientResponse.class, null)).thenReturn(response); assertFalse(atlasClient.isServerReady()); } @Test(expectedExceptions = AtlasServiceException.class) public void shouldThrowErrorIfAnyResponseOtherThanServiceUnavailable() throws AtlasServiceException { setupRetryParams(); AtlasClient atlasClient = new AtlasClient(service, configuration); WebResource.Builder builder = setupBuilder(AtlasClient.API.VERSION, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); when(response.getClientResponseStatus()).thenReturn(ClientResponse.Status.INTERNAL_SERVER_ERROR); when(builder.method(AtlasClient.API.VERSION.getMethod(), ClientResponse.class, null)).thenReturn(response); atlasClient.isServerReady(); fail("Should throw exception"); } @Test public void shouldGetAdminStatus() throws AtlasServiceException { setupRetryParams(); AtlasClient atlasClient = new AtlasClient(service, configuration); WebResource.Builder builder = setupBuilder(AtlasClient.API.STATUS, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); String activeStatus = "{\"Status\":\"Active\"}"; when(response.getEntity(String.class)).thenReturn(activeStatus); when(response.getLength()).thenReturn(activeStatus.length()); when(builder.method(AtlasClient.API.STATUS.getMethod(), ClientResponse.class, null)).thenReturn(response); // Fix after AtlasBaseClient // atlasClient.setService(); String status = atlasClient.getAdminStatus(); assertEquals(status, "Active"); } @Test(expectedExceptions = AtlasServiceException.class) public void shouldReturnStatusAsUnknownOnException() throws AtlasServiceException { setupRetryParams(); AtlasClient atlasClient = new AtlasClient(service, configuration); WebResource.Builder builder = setupBuilder(AtlasClient.API.STATUS, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); when(response.getClientResponseStatus()).thenReturn(ClientResponse.Status.INTERNAL_SERVER_ERROR); when(builder.method(AtlasClient.API.STATUS.getMethod(), ClientResponse.class, null)).thenReturn(response); String status = atlasClient.getAdminStatus(); fail("Should fail with AtlasServiceException"); } @Test public void shouldReturnStatusAsUnknownIfJSONIsInvalid() throws AtlasServiceException { setupRetryParams(); AtlasClient atlasClient = new AtlasClient(service, configuration); WebResource.Builder builder = setupBuilder(AtlasClient.API.STATUS, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); when(response.getEntity(String.class)).thenReturn("{\"status\":\"Active\"}"); when(builder.method(AtlasClient.API.STATUS.getMethod(), ClientResponse.class, null)).thenReturn(response); String status = atlasClient.getAdminStatus(); assertEquals(status, AtlasClient.UNKNOWN_STATUS); } @Test public void shouldReturnBaseURLAsPassedInURL() { AtlasClient atlasClient = new AtlasClient(service, configuration); String serviceURL = atlasClient.determineActiveServiceURL(new String[]{"http://localhost:21000"}, client); assertEquals(serviceURL, "http://localhost:21000"); } @Test public void shouldSelectActiveAmongMultipleServersIfHAIsEnabled() { setupRetryParams(); when(client.resource(UriBuilder.fromUri("http://localhost:31000").build())).thenReturn(service); when(client.resource(UriBuilder.fromUri("http://localhost:41000").build())).thenReturn(service); WebResource.Builder builder = setupBuilder(AtlasClient.API.STATUS, service); ClientResponse firstResponse = mock(ClientResponse.class); when(firstResponse.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); String passiveStatus = "{\"Status\":\"PASSIVE\"}"; when(firstResponse.getEntity(String.class)).thenReturn(passiveStatus); when(firstResponse.getLength()).thenReturn(passiveStatus.length()); ClientResponse secondResponse = mock(ClientResponse.class); when(secondResponse.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); String activeStatus = "{\"Status\":\"ACTIVE\"}"; when(secondResponse.getEntity(String.class)).thenReturn(activeStatus); when(secondResponse.getLength()).thenReturn(activeStatus.length()); when(builder.method(AtlasClient.API.STATUS.getMethod(), ClientResponse.class, null)). thenReturn(firstResponse).thenReturn(firstResponse).thenReturn(firstResponse). thenReturn(secondResponse); AtlasClient atlasClient = new AtlasClient(service, configuration); String serviceURL = atlasClient.determineActiveServiceURL( new String[]{"http://localhost:31000", "http://localhost:41000"}, client); assertEquals(serviceURL, "http://localhost:41000"); } @Test public void shouldRetryUntilServiceBecomesActive() { setupRetryParams(); when(client.resource(UriBuilder.fromUri("http://localhost:31000").build())).thenReturn(service); WebResource.Builder builder = setupBuilder(AtlasClient.API.STATUS, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); when(response.getEntity(String.class)).thenReturn("{\"Status\":\"BECOMING_ACTIVE\"}"); ClientResponse nextResponse = mock(ClientResponse.class); when(nextResponse.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); String activeStatus = "{\"Status\":\"ACTIVE\"}"; when(response.getEntity(String.class)).thenReturn(activeStatus); when(response.getLength()).thenReturn(activeStatus.length()); when(builder.method(AtlasClient.API.STATUS.getMethod(), ClientResponse.class, null)). thenReturn(response).thenReturn(response).thenReturn(nextResponse); AtlasClient atlasClient = new AtlasClient(service, configuration); String serviceURL = atlasClient.determineActiveServiceURL( new String[] {"http://localhost:31000","http://localhost:41000"}, client); assertEquals(serviceURL, "http://localhost:31000"); } @Test public void shouldRetryIfCannotConnectToServiceInitially() { setupRetryParams(); when(client.resource(UriBuilder.fromUri("http://localhost:31000").build())).thenReturn(service); WebResource.Builder builder = setupBuilder(AtlasClient.API.STATUS, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); when(response.getEntity(String.class)).thenReturn("{\"Status\":\"BECOMING_ACTIVE\"}"); ClientResponse nextResponse = mock(ClientResponse.class); when(nextResponse.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); String activeStatus = "{\"Status\":\"ACTIVE\"}"; when(response.getEntity(String.class)).thenReturn(activeStatus); when(response.getLength()).thenReturn(activeStatus.length()); when(builder.method(AtlasClient.API.STATUS.getMethod(), ClientResponse.class, null)). thenThrow(new ClientHandlerException("Simulating connection exception")). thenReturn(response). thenReturn(nextResponse); AtlasClient atlasClient = new AtlasClient(service, configuration); atlasClient.setService(service); atlasClient.setConfiguration(configuration); String serviceURL = atlasClient.determineActiveServiceURL( new String[] {"http://localhost:31000","http://localhost:41000"}, client); assertEquals(serviceURL, "http://localhost:31000"); } @Test(expectedExceptions = IllegalArgumentException.class) public void shouldThrowExceptionIfActiveServerIsNotFound() { setupRetryParams(); when(client.resource(UriBuilder.fromUri("http://localhost:31000").build())).thenReturn(service); WebResource.Builder builder = setupBuilder(AtlasClient.API.STATUS, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); when(response.getEntity(String.class)).thenReturn("{\"Status\":\"BECOMING_ACTIVE\"}"); when(builder.method(AtlasClient.API.STATUS.getMethod(), ClientResponse.class, null)). thenThrow(new ClientHandlerException("Simulating connection exception")). thenReturn(response). thenReturn(response); AtlasClient atlasClient = new AtlasClient(service, configuration); String serviceURL = atlasClient.determineActiveServiceURL( new String[] {"http://localhost:31000","http://localhost:41000"}, client); assertNull(serviceURL); } @Test public void shouldRetryAPICallsOnClientHandlerException() throws AtlasServiceException, URISyntaxException { setupRetryParams(); ResourceCreator resourceCreator = mock(ResourceCreator.class); WebResource resourceObject = mock(WebResource.class); when(resourceObject.getURI()). thenReturn(new URI("http://localhost:31000/api/atlas/types")). thenReturn(new URI("http://localhost:41000/api/atlas/types")). thenReturn(new URI("http://localhost:41000/api/atlas/types")); WebResource.Builder builder = getBuilder(resourceObject); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); String activeStatus = "{\"Status\":\"ACTIVE\"}"; when(response.getEntity(String.class)).thenReturn(activeStatus); when(response.getLength()).thenReturn(activeStatus.length()); when(builder.method(AtlasClient.API.LIST_TYPES.getMethod(), ClientResponse.class, null)). thenThrow(new ClientHandlerException("simulating exception in calling API", new ConnectException())). thenReturn(response); when(resourceCreator.createResource()).thenReturn(resourceObject); AtlasClient atlasClient = getClientForTest("http://localhost:31000","http://localhost:41000"); atlasClient.setService(service); atlasClient.setConfiguration(configuration); atlasClient.callAPIWithRetries(AtlasClient.API.LIST_TYPES, null, resourceCreator); verify(client).destroy(); verify(client).resource(UriBuilder.fromUri("http://localhost:31000").build()); verify(client).resource(UriBuilder.fromUri("http://localhost:41000").build()); } @Test public void shouldRetryWithSameClientIfSingleAddressIsUsed() throws URISyntaxException, AtlasServiceException { setupRetryParams(); ResourceCreator resourceCreator = mock(ResourceCreator.class); WebResource resourceObject = mock(WebResource.class); when(resourceObject.getURI()). thenReturn(new URI("http://localhost:31000/api/atlas/types")); WebResource.Builder builder = getBuilder(resourceObject); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); String activeStatus = "{\"Status\":\"ACTIVE\"}"; when(response.getEntity(String.class)).thenReturn(activeStatus); when(response.getLength()).thenReturn(activeStatus.length()); when(builder.method(AtlasClient.API.LIST_TYPES.getMethod(), ClientResponse.class, null)). thenThrow(new ClientHandlerException("simulating exception in calling API", new ConnectException())). thenReturn(response); when(resourceCreator.createResource()).thenReturn(resourceObject); when(configuration.getString("atlas.http.authentication.type", "simple")).thenReturn("simple"); AtlasClient atlasClient = getClientForTest("http://localhost:31000"); atlasClient.setService(resourceObject); atlasClient.setConfiguration(configuration); atlasClient.callAPIWithRetries(AtlasClient.API.LIST_TYPES, null, resourceCreator); verify(client).destroy(); verify(client, times(2)).resource(UriBuilder.fromUri("http://localhost:31000").build()); } @Test public void shouldRetryAPICallsOnServiceUnavailable() throws AtlasServiceException, URISyntaxException { setupRetryParams(); ResourceCreator resourceCreator = mock(ResourceCreator.class); WebResource resourceObject = mock(WebResource.class); when(resourceObject.getURI()). thenReturn(new URI("http://localhost:31000/api/atlas/types")). thenReturn(new URI("http://localhost:41000/api/atlas/types")). thenReturn(new URI("http://localhost:41000/api/atlas/types")); WebResource.Builder builder = getBuilder(resourceObject); ClientResponse firstResponse = mock(ClientResponse.class); when(firstResponse.getStatus()).thenReturn(Response.Status.SERVICE_UNAVAILABLE.getStatusCode()); when(firstResponse.getClientResponseStatus()).thenReturn(ClientResponse.Status.SERVICE_UNAVAILABLE); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); String activeStatus = "{\"Status\":\"ACTIVE\"}"; when(response.getEntity(String.class)).thenReturn(activeStatus); when(response.getLength()).thenReturn(activeStatus.length()); when(builder.method(AtlasClient.API.LIST_TYPES.getMethod(), ClientResponse.class, null)). thenThrow(new ClientHandlerException("simulating exception in calling API", new ConnectException())). thenReturn(firstResponse). thenReturn(response); when(resourceCreator.createResource()).thenReturn(resourceObject); AtlasClient atlasClient = getClientForTest("http://localhost:31000","http://localhost:41000"); atlasClient.setService(resourceObject); atlasClient.setConfiguration(configuration); atlasClient.callAPIWithRetries(AtlasClient.API.LIST_TYPES, null, resourceCreator); verify(client).destroy(); verify(client).resource(UriBuilder.fromUri("http://localhost:31000").build()); verify(client).resource(UriBuilder.fromUri("http://localhost:41000").build()); } private WebResource.Builder getBuilder(WebResource resourceObject) { when(resourceObject.getRequestBuilder()).thenReturn(resourceBuilderMock); when(resourceObject.path(anyString())).thenReturn(resourceObject); when(resourceBuilderMock.accept(AtlasBaseClient.JSON_MEDIA_TYPE)).thenReturn(resourceBuilderMock); when(resourceBuilderMock.type(AtlasBaseClient.JSON_MEDIA_TYPE)).thenReturn(resourceBuilderMock); return resourceBuilderMock; } private void setupRetryParams() { when(configuration.getInt(AtlasClient.ATLAS_CLIENT_HA_RETRIES_KEY, AtlasClient.DEFAULT_NUM_RETRIES)). thenReturn(3); when(configuration.getInt(AtlasClient.ATLAS_CLIENT_HA_SLEEP_INTERVAL_MS_KEY, AtlasClient.DEFAULT_SLEEP_BETWEEN_RETRIES_MS)). thenReturn(1); } private AtlasClient getClientForTest(final String... baseUrls) { return new AtlasClient((UserGroupInformation)null, (String)null, baseUrls) { boolean firstCall = true; @Override protected String determineActiveServiceURL(String[] baseUrls, Client client) { String returnUrl = baseUrls[0]; if (baseUrls.length > 1 && !firstCall) { returnUrl = baseUrls[1]; } firstCall = false; return returnUrl; } @Override protected Configuration getClientProperties() { return configuration; } @Override protected Client getClient(Configuration configuration, UserGroupInformation ugi, String doAsUser) { return client; } }; } } <|start_filename|>repository/src/test/java/org/apache/atlas/repository/graph/Gremlin2QueryOptimizerTest.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graph; import org.apache.atlas.gremlin.Gremlin2ExpressionFactory; import org.apache.atlas.gremlin.GremlinExpressionFactory; import org.testng.annotations.Test; @Test public class Gremlin2QueryOptimizerTest extends AbstractGremlinQueryOptimizerTest { private static GremlinExpressionFactory FACTORY = null; @Override protected GremlinExpressionFactory getFactory() { if (null == FACTORY) { FACTORY = new Gremlin2ExpressionFactory(); } return FACTORY; } @Override protected String getExpectedGremlinForTestPullHasExpressionsOutOfHas() { return "g.V().has('prop1',T.'eq','Fred').has('prop2',T.'eq','George').and(out('out1'),out('out2'))"; } @Override protected String getExpectedGremlinForTestOrGrouping() { return "def r=(([]) as Set);" + "g.V().has('prop1',T.'eq','Fred').fill(r);" + "g.V().has('prop2',T.'eq','George').fill(r);" + "g.V().or(out('out1'),out('out2')).fill(r);" + "r"; } @Override protected String getExpectedGremlinForTestAndOfOrs() { return "def r=(([]) as Set);" + "g.V().has('p1',T.'eq','e1').has('p3',T.'eq','e3').fill(r);" + "g.V().has('p1',T.'eq','e1').has('p4',T.'eq','e4').fill(r);" + "g.V().has('p2',T.'eq','e2').has('p3',T.'eq','e3').fill(r);" + "g.V().has('p2',T.'eq','e2').has('p4',T.'eq','e4').fill(r);" + "r"; } @Override protected String getExpectedGremlinForTestAndWithMultiCallArguments() { return "g.V().has('p1',T.'eq','e1').has('p2',T.'eq','e2').has('p3',T.'eq','e3').has('p4',T.'eq','e4')"; } @Override protected String getExpectedGremlinForTestOrOfAnds() { return "def r=(([]) as Set);" + "g.V().has('p1',T.'eq','e1').has('p2',T.'eq','e2').fill(r);" + "g.V().has('p3',T.'eq','e3').has('p4',T.'eq','e4').fill(r);" + "r"; } @Override protected String getExpectedGremlinForTestHasNotMovedToResult() { return "def r=(([]) as Set);" + "def f1={GremlinPipeline x->x.has('p3',T.'eq','e3').as('_src').select(['_src']).fill(r)};" + "f1(g.V().has('p1',T.'eq','e1'));" + "f1(g.V().has('p2',T.'eq','e2'));" + "r._().transform({((Row)it).getColumn('_src')}).as('_src').select(['src1'],{it})"; } @Override protected String getExpectedGremlinForOptimizeLoopExpression() { return "def r=(([]) as Set);" + "g.V().has('__typeName','DataSet').has('name',T.'eq','Fred').fill(r);" + "g.V().has('__superTypeNames','DataSet').has('name',T.'eq','Fred').fill(r);" + "r._().as('label').in('inputTables').out('outputTables').loop('label',{((it.'path'.contains(it.'object'))?(false):(true))},{it.'object'.'__typeName' == 'string' || ((it.'object'.'__superTypeNames')?(it.'object'.'__superTypeNames'.contains('string')):(false))}).enablePath().toList()"; } @Override protected String getExpectedGremlinForTestLongStringEndingWithOr() { return "def r=(([]) as Set);" + "def f1={g.V().has('name',T.'eq','Fred').has('age',T.'eq','13').out('livesIn').has('state',T.'eq','Massachusetts')};" + "def f2={GremlinPipeline x->x.has('p5',T.'eq','e5').has('p6',T.'eq','e6')};" + "f2(f1().has('p1',T.'eq','e1').has('p3',T.'eq','e3')).has('p7',T.'eq','e7').fill(r);" + "f2(f1().has('p1',T.'eq','e1').has('p3',T.'eq','e3')).has('p8',T.'eq','e8').fill(r);" + "f2(f1().has('p1',T.'eq','e1').has('p4',T.'eq','e4')).has('p7',T.'eq','e7').fill(r);" + "f2(f1().has('p1',T.'eq','e1').has('p4',T.'eq','e4')).has('p8',T.'eq','e8').fill(r);" + "f2(f1().has('p2',T.'eq','e2').has('p3',T.'eq','e3')).has('p7',T.'eq','e7').fill(r);" + "f2(f1().has('p2',T.'eq','e2').has('p3',T.'eq','e3')).has('p8',T.'eq','e8').fill(r);" + "f2(f1().has('p2',T.'eq','e2').has('p4',T.'eq','e4')).has('p7',T.'eq','e7').fill(r);" + "f2(f1().has('p2',T.'eq','e2').has('p4',T.'eq','e4')).has('p8',T.'eq','e8').fill(r);" + "r"; } @Override protected String getExpectedGremlinForTestLongStringNotEndingWithOr() { return "def r=(([]) as Set);" + "def f1={g.V().has('name',T.'eq','Fred').has('age',T.'eq','13').out('livesIn').has('state',T.'eq','Massachusetts')};" + "def f2={GremlinPipeline x->x.has('p5',T.'eq','e5').has('p6',T.'eq','e6')};" + "def f3={GremlinPipeline x->x.has('p9',T.'eq','e9').fill(r)};" + "f3(f2(f1().has('p1',T.'eq','e1').has('p3',T.'eq','e3')).has('p7',T.'eq','e7'));" + "f3(f2(f1().has('p1',T.'eq','e1').has('p3',T.'eq','e3')).has('p8',T.'eq','e8'));" + "f3(f2(f1().has('p1',T.'eq','e1').has('p4',T.'eq','e4')).has('p7',T.'eq','e7'));" + "f3(f2(f1().has('p1',T.'eq','e1').has('p4',T.'eq','e4')).has('p8',T.'eq','e8'));" + "f3(f2(f1().has('p2',T.'eq','e2').has('p3',T.'eq','e3')).has('p7',T.'eq','e7'));" + "f3(f2(f1().has('p2',T.'eq','e2').has('p3',T.'eq','e3')).has('p8',T.'eq','e8'));" + "f3(f2(f1().has('p2',T.'eq','e2').has('p4',T.'eq','e4')).has('p7',T.'eq','e7'));" + "f3(f2(f1().has('p2',T.'eq','e2').has('p4',T.'eq','e4')).has('p8',T.'eq','e8'));" + "r"; } @Override protected String getExpectedGremlinForTestToListConversion() { return "def r=(([]) as Set);" + "g.V().has('prop1',T.'eq','Fred').fill(r);" + "g.V().has('prop2',T.'eq','George').fill(r);" + "r._().toList()"; } @Override protected String getExpectedGremlinForTestToListWithExtraStuff() { return "def r=(([]) as Set);" + "g.V().has('prop1',T.'eq','Fred').fill(r);" + "g.V().has('prop2',T.'eq','George').fill(r);" + "r._().toList().size()"; } @Override protected String getExpectedGremlinForTestAddClosureWithExitExpressionDifferentFromExpr() { return "def r=(([]) as Set);" + "g.V().has('prop1',T.'eq','Fred').out('knows').out('livesIn').fill(r);" + "g.V().has('prop2',T.'eq','George').out('knows').out('livesIn').fill(r);" + "r._().toList().size()"; } @Override protected String getExpectedGremlinForTestAddClosureNoExitExpression() { return "def r=(([]) as Set);" + "g.V().has('prop1',T.'eq','Fred').out('knows').out('livesIn').fill(r);" + "g.V().has('prop2',T.'eq','George').out('knows').out('livesIn').fill(r);" + "r"; } @Override protected String getExpectedGremlinForTestAddClosureWithExitExpressionEqualToExpr() { return "def r=(([]) as Set);" + "g.V().has('prop1',T.'eq','Fred').out('knows').out('livesIn').fill(r);" + "g.V().has('prop2',T.'eq','George').out('knows').out('livesIn').fill(r);" + "r._().toList()"; } @Override protected String getExpectedGremlinForTestClosureNotCreatedWhenNoOrs() { return "g.V().has('prop1',T.'eq','Fred').has('prop2',T.'eq','George').out('knows').out('livesIn')"; } @Override protected String getExpectedGremlinForTestOrFollowedByAnd() { return "def r=(([]) as Set);" + "def f1={GremlinPipeline x->x.has('age',T.'eq','13').has('age',T.'eq','14').fill(r)};" + "f1(g.V().has('name',T.'eq','Fred'));" + "f1(g.V().has('name',T.'eq','George'));" + "r"; } @Override protected String getExpectedGremlinForTestOrFollowedByOr() { return "def r=(([]) as Set);" + "g.V().has('name',T.'eq','Fred').has('age',T.'eq','13').fill(r);" + "g.V().has('name',T.'eq','Fred').has('age',T.'eq','14').fill(r);" + "g.V().has('name',T.'eq','George').has('age',T.'eq','13').fill(r);" + "g.V().has('name',T.'eq','George').has('age',T.'eq','14').fill(r);" + "r"; } @Override protected String getExpectedGremlinForTestMassiveOrExpansion() { return "def r=(([]) as Set);" + "def f1={g.V().has('h1',T.'eq','h2').has('h3',T.'eq','h4')};" + "def f2={GremlinPipeline x->x.has('ha0',T.'eq','hb0').has('hc0',T.'eq','hd0')};" + "def f3={GremlinPipeline x->x.has('ha1',T.'eq','hb1').has('hc1',T.'eq','hd1')};" + "def f4={GremlinPipeline x->x.has('ha2',T.'eq','hb2').has('hc2',T.'eq','hd2')};" + "def f5={GremlinPipeline x->x.has('ha3',T.'eq','hb3').has('hc3',T.'eq','hd3')};" + "def f6={GremlinPipeline x->x.has('ha4',T.'eq','hb4').has('hc4',T.'eq','hd4').has('h5',T.'eq','h6').has('h7',T.'eq','h8').fill(r)};" + "f6(f5(f4(f3(f2(f1().has('p10',T.'eq','e10')).has('p11',T.'eq','e11')).has('p12',T.'eq','e12')).has('p13',T.'eq','e13')).has('p14',T.'eq','e14'));" + "f6(f5(f4(f3(f2(f1().has('p10',T.'eq','e10')).has('p11',T.'eq','e11')).has('p12',T.'eq','e12')).has('p13',T.'eq','e13')).has('p24',T.'eq','e24'));" + "f6(f5(f4(f3(f2(f1().has('p10',T.'eq','e10')).has('p11',T.'eq','e11')).has('p12',T.'eq','e12')).has('p23',T.'eq','e23')).has('p14',T.'eq','e14'));" + "f6(f5(f4(f3(f2(f1().has('p10',T.'eq','e10')).has('p11',T.'eq','e11')).has('p12',T.'eq','e12')).has('p23',T.'eq','e23')).has('p24',T.'eq','e24'));" + "f6(f5(f4(f3(f2(f1().has('p10',T.'eq','e10')).has('p11',T.'eq','e11')).has('p22',T.'eq','e22')).has('p13',T.'eq','e13')).has('p14',T.'eq','e14'));" + "f6(f5(f4(f3(f2(f1().has('p10',T.'eq','e10')).has('p11',T.'eq','e11')).has('p22',T.'eq','e22')).has('p13',T.'eq','e13')).has('p24',T.'eq','e24'));" + "f6(f5(f4(f3(f2(f1().has('p10',T.'eq','e10')).has('p11',T.'eq','e11')).has('p22',T.'eq','e22')).has('p23',T.'eq','e23')).has('p14',T.'eq','e14'));" + "f6(f5(f4(f3(f2(f1().has('p10',T.'eq','e10')).has('p11',T.'eq','e11')).has('p22',T.'eq','e22')).has('p23',T.'eq','e23')).has('p24',T.'eq','e24'));" + "f6(f5(f4(f3(f2(f1().has('p10',T.'eq','e10')).has('p21',T.'eq','e21')).has('p12',T.'eq','e12')).has('p13',T.'eq','e13')).has('p14',T.'eq','e14'));" + "f6(f5(f4(f3(f2(f1().has('p10',T.'eq','e10')).has('p21',T.'eq','e21')).has('p12',T.'eq','e12')).has('p13',T.'eq','e13')).has('p24',T.'eq','e24'));" + "f6(f5(f4(f3(f2(f1().has('p10',T.'eq','e10')).has('p21',T.'eq','e21')).has('p12',T.'eq','e12')).has('p23',T.'eq','e23')).has('p14',T.'eq','e14'));" + "f6(f5(f4(f3(f2(f1().has('p10',T.'eq','e10')).has('p21',T.'eq','e21')).has('p12',T.'eq','e12')).has('p23',T.'eq','e23')).has('p24',T.'eq','e24'));" + "f6(f5(f4(f3(f2(f1().has('p10',T.'eq','e10')).has('p21',T.'eq','e21')).has('p22',T.'eq','e22')).has('p13',T.'eq','e13')).has('p14',T.'eq','e14'));" + "f6(f5(f4(f3(f2(f1().has('p10',T.'eq','e10')).has('p21',T.'eq','e21')).has('p22',T.'eq','e22')).has('p13',T.'eq','e13')).has('p24',T.'eq','e24'));" + "f6(f5(f4(f3(f2(f1().has('p10',T.'eq','e10')).has('p21',T.'eq','e21')).has('p22',T.'eq','e22')).has('p23',T.'eq','e23')).has('p14',T.'eq','e14'));" + "f6(f5(f4(f3(f2(f1().has('p10',T.'eq','e10')).has('p21',T.'eq','e21')).has('p22',T.'eq','e22')).has('p23',T.'eq','e23')).has('p24',T.'eq','e24'));" + "f6(f5(f4(f3(f2(f1().has('p20',T.'eq','e20')).has('p11',T.'eq','e11')).has('p12',T.'eq','e12')).has('p13',T.'eq','e13')).has('p14',T.'eq','e14'));" + "f6(f5(f4(f3(f2(f1().has('p20',T.'eq','e20')).has('p11',T.'eq','e11')).has('p12',T.'eq','e12')).has('p13',T.'eq','e13')).has('p24',T.'eq','e24'));" + "f6(f5(f4(f3(f2(f1().has('p20',T.'eq','e20')).has('p11',T.'eq','e11')).has('p12',T.'eq','e12')).has('p23',T.'eq','e23')).has('p14',T.'eq','e14'));" + "f6(f5(f4(f3(f2(f1().has('p20',T.'eq','e20')).has('p11',T.'eq','e11')).has('p12',T.'eq','e12')).has('p23',T.'eq','e23')).has('p24',T.'eq','e24'));" + "f6(f5(f4(f3(f2(f1().has('p20',T.'eq','e20')).has('p11',T.'eq','e11')).has('p22',T.'eq','e22')).has('p13',T.'eq','e13')).has('p14',T.'eq','e14'));" + "f6(f5(f4(f3(f2(f1().has('p20',T.'eq','e20')).has('p11',T.'eq','e11')).has('p22',T.'eq','e22')).has('p13',T.'eq','e13')).has('p24',T.'eq','e24'));" + "f6(f5(f4(f3(f2(f1().has('p20',T.'eq','e20')).has('p11',T.'eq','e11')).has('p22',T.'eq','e22')).has('p23',T.'eq','e23')).has('p14',T.'eq','e14'));" + "f6(f5(f4(f3(f2(f1().has('p20',T.'eq','e20')).has('p11',T.'eq','e11')).has('p22',T.'eq','e22')).has('p23',T.'eq','e23')).has('p24',T.'eq','e24'));" + "f6(f5(f4(f3(f2(f1().has('p20',T.'eq','e20')).has('p21',T.'eq','e21')).has('p12',T.'eq','e12')).has('p13',T.'eq','e13')).has('p14',T.'eq','e14'));" + "f6(f5(f4(f3(f2(f1().has('p20',T.'eq','e20')).has('p21',T.'eq','e21')).has('p12',T.'eq','e12')).has('p13',T.'eq','e13')).has('p24',T.'eq','e24'));" + "f6(f5(f4(f3(f2(f1().has('p20',T.'eq','e20')).has('p21',T.'eq','e21')).has('p12',T.'eq','e12')).has('p23',T.'eq','e23')).has('p14',T.'eq','e14'));" + "f6(f5(f4(f3(f2(f1().has('p20',T.'eq','e20')).has('p21',T.'eq','e21')).has('p12',T.'eq','e12')).has('p23',T.'eq','e23')).has('p24',T.'eq','e24'));" + "f6(f5(f4(f3(f2(f1().has('p20',T.'eq','e20')).has('p21',T.'eq','e21')).has('p22',T.'eq','e22')).has('p13',T.'eq','e13')).has('p14',T.'eq','e14'));" + "f6(f5(f4(f3(f2(f1().has('p20',T.'eq','e20')).has('p21',T.'eq','e21')).has('p22',T.'eq','e22')).has('p13',T.'eq','e13')).has('p24',T.'eq','e24'));" + "f6(f5(f4(f3(f2(f1().has('p20',T.'eq','e20')).has('p21',T.'eq','e21')).has('p22',T.'eq','e22')).has('p23',T.'eq','e23')).has('p14',T.'eq','e14'));" + "f6(f5(f4(f3(f2(f1().has('p20',T.'eq','e20')).has('p21',T.'eq','e21')).has('p22',T.'eq','e22')).has('p23',T.'eq','e23')).has('p24',T.'eq','e24'));" + "r"; } @Override protected String getExpectedGremlinForTestAndFollowedByAnd() { return "g.V().has('name',T.'eq','Fred').has('name',T.'eq','George').has('age',T.'eq','13').has('age',T.'eq','14')"; } @Override protected String getExpectedGremlinForTestAndFollowedByOr() { return "def r=(([]) as Set);" + "def f1={g.V().has('name',T.'eq','Fred').has('name',T.'eq','George')};f1().has('age',T.'eq','13').fill(r);" + "f1().has('age',T.'eq','14').fill(r);" + "r"; } @Override protected String getExpectedGremlinForTestInitialAlias() { return "def r=(([]) as Set);" + "g.V().as('x').has('name',T.'eq','Fred').fill(r);" + "g.V().as('x').has('name',T.'eq','George').fill(r);" + "r"; } @Override protected String getExpectedGremlinForTestFinalAlias() { return "def r=(([]) as Set);" + "g.V().has('name',T.'eq','Fred').as('x').fill(r);" + "g.V().has('name',T.'eq','George').as('x').fill(r);" + "r"; } @Override protected String getExpectedGremlinForTestAliasInMiddle() { return "def r=(([]) as Set);" + "g.V().has('name',T.'eq','Fred').as('x').has('age',T.'eq','13').fill(r);" + "g.V().has('name',T.'eq','Fred').as('x').has('age',T.'eq','14').fill(r);" + "g.V().has('name',T.'eq','George').as('x').has('age',T.'eq','13').fill(r);" + "g.V().has('name',T.'eq','George').as('x').has('age',T.'eq','14').fill(r);" + "r"; } @Override protected String getExpectedGreminForTestMultipleAliases() { return "def r=(([]) as Set);" + "def f1={GremlinPipeline x->x.as('y').fill(r)};" + "f1(g.V().has('name',T.'eq','Fred').as('x').has('age',T.'eq','13'));" + "f1(g.V().has('name',T.'eq','Fred').as('x').has('age',T.'eq','14'));" + "f1(g.V().has('name',T.'eq','George').as('x').has('age',T.'eq','13'));" + "f1(g.V().has('name',T.'eq','George').as('x').has('age',T.'eq','14'));" + "r"; } @Override protected String getExpectedGremlinForTestAliasInOrExpr() { return "def r=(([]) as Set);" + "g.V().has('name',T.'eq','Fred').fill(r);" + "g.V().or(has('name',T.'eq','George').as('george')).fill(r);" + "r"; } @Override protected String getExpectedGremlinForTestAliasInAndExpr() { return "g.V().has('name',T.'eq','Fred').and(has('name',T.'eq','George').as('george'))"; } @Override protected String getExpectedGremlinForTestFlatMapExprInAnd() { return "g.V().has('name',T.'eq','Fred').and(out('knows').has('name',T.'eq','George'))"; } @Override protected String getExpectedGremlinForTestFlatMapExprInOr() { return "def r=(([]) as Set);" + "g.V().has('name',T.'eq','Fred').fill(r);" + "g.V().or(out('knows').has('name',T.'eq','George')).fill(r);" + "r"; } @Override protected String getExpectedGremlinForTestFieldExpressionPushedToResultExpression() { return "def r=(([]) as Set);" + "g.V().has('name',T.'eq','Fred').fill(r);" + "g.V().or(out('knows').has('name',T.'eq','George')).fill(r);" + "r._().'name'"; } @Override protected String getExpectedGremlinFortestOrWithNoChildren() { return "def r=(([]) as Set);" + "r"; } @Override protected String getExpectedGremlinForTestFinalAliasNeeded() { return "def r=(([]) as Set);" + "def f1={g.V().has('name',T.'eq','Fred').as('person').out('livesIn')};" + "def f2={GremlinPipeline x->x.as('city').out('state').has('name',T.'eq','Massachusetts').as('__res').select(['person', 'city', '__res']).fill(r)};" + "f2(f1().has('name',T.'eq','Chicago'));" + "f2(f1().has('name',T.'eq','Boston'));" + "r._().as('__tmp').transform({((Row)it).getColumn('person')}).as('person').back('__tmp').transform({((Row)it).getColumn('city')}).as('city').back('__tmp').transform({((Row)it).getColumn('__res')}).as('__res').path().toList().collect({it.tail()})"; } @Override protected String getExpectedGremlinForTestSimpleRangeExpression() { return "def r=(([]) as Set);" + "def f1={GremlinPipeline x->x.has('age',T.'eq','34').out('eats').has('size',T.'eq','small').has('color',T.'eq','blue') [0..<10].fill(r)};" + "f1(g.V().has('name',T.'eq','Fred'));" + "f1(g.V().has('name',T.'eq','George'));" + "r._() [0..<10].toList().size()"; } @Override protected String getExpectedGremlinForTestRangeWithNonZeroOffset() { return "def r=(([]) as Set);" + "g.V().has('__typeName',T.'eq','OMAS_OMRSAsset').fill(r);" + "g.V().has('__superTypeNames',T.'eq','OMAS_OMRSAsset').fill(r);" + "r._() [5..<10].as('inst').select(['inst'])"; } @Override protected String getExpectedGremlinForTestRangeWithOrderBy() { return "def r=(([]) as Set);" + "g.V().has('__typeName',T.'eq','OMAS_OMRSAsset').fill(r);" + "g.V().has('__superTypeNames',T.'eq','OMAS_OMRSAsset').fill(r);" + "r._() [5..<10].as('inst').order({((it.'name' != null)?(it.'name'.toLowerCase()):(it.'name')) <=> ((it.'name' != null)?(it.'name'.toLowerCase()):(it.'name'))})"; } } <|start_filename|>graphdb/titan0/src/main/java/org/apache/atlas/repository/graphdb/titan0/query/NativeTitan0GraphQuery.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan0.query; import com.google.common.collect.Lists; import com.thinkaurelius.titan.core.TitanGraphQuery; import com.thinkaurelius.titan.core.attribute.Contain; import com.thinkaurelius.titan.core.attribute.Text; import com.thinkaurelius.titan.graphdb.query.TitanPredicate; import com.tinkerpop.blueprints.Compare; import com.tinkerpop.blueprints.Vertex; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasGraphQuery.ComparisionOperator; import org.apache.atlas.repository.graphdb.AtlasGraphQuery.MatchingOperator; import org.apache.atlas.repository.graphdb.AtlasGraphQuery.QueryOperator; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.repository.graphdb.titan.query.NativeTitanGraphQuery; import org.apache.atlas.repository.graphdb.titan0.Titan0Edge; import org.apache.atlas.repository.graphdb.titan0.Titan0Graph; import org.apache.atlas.repository.graphdb.titan0.Titan0GraphDatabase; import org.apache.atlas.repository.graphdb.titan0.Titan0Vertex; import java.util.*; /** * Titan 0.5.4 implementation of NativeTitanGraphQuery. * * @author jeff * */ public class NativeTitan0GraphQuery implements NativeTitanGraphQuery<Titan0Vertex, Titan0Edge> { private Titan0Graph graph; private TitanGraphQuery<?> query; public NativeTitan0GraphQuery(Titan0Graph graph) { query = Titan0GraphDatabase.getGraphInstance().query(); this.graph = graph; } @Override public Iterable<AtlasVertex<Titan0Vertex, Titan0Edge>> vertices() { Iterable it = query.vertices(); return graph.wrapVertices(it); } @Override public Iterable<AtlasEdge<Titan0Vertex, Titan0Edge>> edges() { Iterable it = query.edges(); return graph.wrapEdges(it); } @Override public Iterable<AtlasVertex<Titan0Vertex, Titan0Edge>> vertices(int limit) { Iterable it = query.limit(limit).vertices(); return graph.wrapVertices(it); } @Override public Iterable<AtlasVertex<Titan0Vertex, Titan0Edge>> vertices(int offset, int limit) { List<Vertex> result = new ArrayList<>(limit); Iterator<Vertex> iter = query.limit(offset + limit).vertices().iterator(); for (long resultIdx = 0; iter.hasNext() && result.size() < limit; resultIdx++) { if (resultIdx < offset) { continue; } result.add(iter.next()); } return graph.wrapVertices(result); } @Override public void in(String propertyName, Collection<?> values) { query.has(propertyName, Contain.IN, values); } @Override public void has(String propertyName, QueryOperator op, Object value) { TitanPredicate pred; if (op instanceof ComparisionOperator) { Compare c = getGremlinPredicate((ComparisionOperator) op); pred = TitanPredicate.Converter.convert(c); } else { pred = getGremlinPredicate((MatchingOperator) op); } query.has(propertyName, pred, value); } private Text getGremlinPredicate(MatchingOperator op) { switch (op) { case CONTAINS: return Text.CONTAINS; case PREFIX: return Text.PREFIX; case SUFFIX: return Text.CONTAINS_REGEX; case REGEX: return Text.REGEX; default: throw new RuntimeException("Unsupported matching operator:" + op); } } private Compare getGremlinPredicate(ComparisionOperator op) { switch (op) { case EQUAL: return Compare.EQUAL; case GREATER_THAN: return Compare.GREATER_THAN; case GREATER_THAN_EQUAL: return Compare.GREATER_THAN_EQUAL; case LESS_THAN: return Compare.LESS_THAN; case LESS_THAN_EQUAL: return Compare.LESS_THAN_EQUAL; case NOT_EQUAL: return Compare.NOT_EQUAL; default: throw new RuntimeException("Unsupported comparison operator:" + op); } } } <|start_filename|>dashboardv2/public/js/views/business_catalog/BusinessCatalogHeader.js<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(['require', 'hbs!tmpl/business_catalog/BusinessCatalogHeader', 'utils/CommonViewFunction', 'utils/Globals' ], function(require, tmpl, CommonViewFunction, Globals) { 'use strict'; var BusinessCatalogHeader = Marionette.LayoutView.extend({ template: tmpl, templateHelpers: function() {}, regions: {}, events: {}, initialize: function(options) { _.extend(this, _.pick(options, 'url', 'collection')); this.value = []; }, /** * After Page Render createBrudCrum called. * @return {[type]} [description] */ render: function() { var that = this; $(this.el).html(this.template()); if (Globals.userLogedIn.status) { that.$('.userName').text(Globals.userLogedIn.response.userName); } var that = this; if (this.url) { this.value = CommonViewFunction.breadcrumbUrlMaker(this.url); } this.listenTo(this.collection, 'reset', function() { setTimeout(function() { that.createBrudCrum(); }, 0); }, this); return this; }, createBrudCrum: function() { var li = "", value = this.value, that = this; CommonViewFunction.breadcrumbMaker({ urlList: this.value, scope: this.$('.breadcrumb') }); } }); return BusinessCatalogHeader; }); <|start_filename|>authorization/src/test/java/org/apache/atlas/authorize/simple/PolicyParserTest.java<|end_filename|> /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.authorize.simple; import static org.testng.AssertJUnit.assertEquals; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.atlas.authorize.AtlasActionTypes; import org.apache.atlas.authorize.AtlasResourceTypes; import org.apache.atlas.authorize.simple.PolicyDef; import org.apache.atlas.authorize.simple.PolicyParser; import org.testng.annotations.Test; public class PolicyParserTest { @Test public void testParsePoliciesWithAllProperties() { List<String> policies = new ArrayList<>(); policies.add("hivePolicy;;usr1:r,usr2:rw;;grp1:rwu,grp2:u;;entity:*abc,operation:*xyz,type:PII"); /* Creating group data */ Map<String, List<AtlasActionTypes>> groupMap = new HashMap<>(); List<AtlasActionTypes> accessList1 = new ArrayList<>(); accessList1.add(AtlasActionTypes.READ); accessList1.add(AtlasActionTypes.CREATE); accessList1.add(AtlasActionTypes.UPDATE); groupMap.put("grp1", accessList1); List<AtlasActionTypes> accessList2 = new ArrayList<>(); accessList2.add(AtlasActionTypes.UPDATE); groupMap.put("grp2", accessList2); /* Creating user data */ Map<String, List<AtlasActionTypes>> usersMap = new HashMap<>(); List<AtlasActionTypes> usr1AccessList = new ArrayList<>(); usr1AccessList.add(AtlasActionTypes.READ); usersMap.put("usr1", usr1AccessList); List<AtlasActionTypes> usr2AccessList = new ArrayList<>(); usr2AccessList.add(AtlasActionTypes.READ); usr2AccessList.add(AtlasActionTypes.CREATE); usersMap.put("usr2", usr2AccessList); /* Creating resources data */ Map<AtlasResourceTypes, List<String>> resourceMap = new HashMap<>(); List<String> resource1List = new ArrayList<>(); resource1List.add("*abc"); resourceMap.put(AtlasResourceTypes.ENTITY, resource1List); List<String> resource2List = new ArrayList<>(); resource2List.add("*xyz"); resourceMap.put(AtlasResourceTypes.OPERATION, resource2List); List<String> resource3List = new ArrayList<>(); resource3List.add("PII"); resourceMap.put(AtlasResourceTypes.TYPE, resource3List); List<PolicyDef> policyDefs = new PolicyParser().parsePolicies(policies); for (PolicyDef def : policyDefs) { assertEquals(def.getPolicyName(), "hivePolicy"); assertEquals(def.getGroups(), groupMap); assertEquals(def.getUsers(), usersMap); assertEquals(def.getResources(), resourceMap); } } @Test public void testParsePoliciesWithOutUserProperties() { List<String> policies = new ArrayList<>(); policies.add("hivePolicy;;;;grp1:rwu,grp2:u;;entity:*abc,operation:*xyz,type:PII"); // Creating group data Map<String, List<AtlasActionTypes>> groupMap = new HashMap<>(); List<AtlasActionTypes> accessList1 = new ArrayList<>(); accessList1.add(AtlasActionTypes.READ); accessList1.add(AtlasActionTypes.CREATE); accessList1.add(AtlasActionTypes.UPDATE); groupMap.put("grp1", accessList1); List<AtlasActionTypes> accessList2 = new ArrayList<>(); accessList2.add(AtlasActionTypes.UPDATE); groupMap.put("grp2", accessList2); // Creating user data Map<String, List<AtlasActionTypes>> usersMap = new HashMap<>(); // Creating resources data Map<AtlasResourceTypes, List<String>> resourceMap = new HashMap<>(); List<String> resource1List = new ArrayList<>(); resource1List.add("*abc"); resourceMap.put(AtlasResourceTypes.ENTITY, resource1List); List<String> resource2List = new ArrayList<>(); resource2List.add("*xyz"); resourceMap.put(AtlasResourceTypes.OPERATION, resource2List); List<String> resource3List = new ArrayList<>(); resource3List.add("PII"); resourceMap.put(AtlasResourceTypes.TYPE, resource3List); List<PolicyDef> policyDefs = new PolicyParser().parsePolicies(policies); for (PolicyDef def : policyDefs) { assertEquals(def.getPolicyName(), "hivePolicy"); assertEquals(def.getGroups(), groupMap); assertEquals(def.getUsers(), usersMap); assertEquals(def.getResources(), resourceMap); } } @Test public void testParsePoliciesWithOutGroupProperties() { List<String> policies = new ArrayList<>(); policies.add("hivePolicy;;usr1:r,usr2:rw;;;;entity:*abc,operation:*xyz,type:PII"); // Creating group data Map<String, List<AtlasActionTypes>> groupMap = new HashMap<>(); // Creating user data Map<String, List<AtlasActionTypes>> usersMap = new HashMap<>(); List<AtlasActionTypes> usr1AccessList = new ArrayList<>(); usr1AccessList.add(AtlasActionTypes.READ); usersMap.put("usr1", usr1AccessList); List<AtlasActionTypes> usr2AccessList = new ArrayList<>(); usr2AccessList.add(AtlasActionTypes.READ); usr2AccessList.add(AtlasActionTypes.CREATE); usersMap.put("usr2", usr2AccessList); // Creating resources data Map<AtlasResourceTypes, List<String>> resourceMap = new HashMap<>(); List<String> resource1List = new ArrayList<>(); resource1List.add("*abc"); resourceMap.put(AtlasResourceTypes.ENTITY, resource1List); List<String> resource2List = new ArrayList<>(); resource2List.add("*xyz"); resourceMap.put(AtlasResourceTypes.OPERATION, resource2List); List<String> resource3List = new ArrayList<>(); resource3List.add("PII"); resourceMap.put(AtlasResourceTypes.TYPE, resource3List); List<PolicyDef> policyDefs = new PolicyParser().parsePolicies(policies); for (PolicyDef def : policyDefs) { assertEquals(def.getPolicyName(), "hivePolicy"); assertEquals(def.getGroups(), groupMap); assertEquals(def.getUsers(), usersMap); assertEquals(def.getResources(), resourceMap); } } } <|start_filename|>graphdb/titan0/src/main/java/org/apache/atlas/repository/graphdb/titan0/Titan0VertexQuery.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.titan0; import com.google.common.base.Preconditions; import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasEdgeDirection; import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.repository.graphdb.AtlasVertexQuery; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.VertexQuery; /** * Titan 0.5.4 implementation of AtlasVertexQuery. */ public class Titan0VertexQuery implements AtlasVertexQuery<Titan0Vertex, Titan0Edge> { private Titan0Graph graph; private VertexQuery vertexQuery; public Titan0VertexQuery(Titan0Graph graph, VertexQuery vertexQuery) { this.vertexQuery = vertexQuery; this.graph = graph; } @Override public AtlasVertexQuery<Titan0Vertex, Titan0Edge> direction(AtlasEdgeDirection queryDirection) { vertexQuery.direction(TitanObjectFactory.createDirection(queryDirection)); return this; } @Override public Iterable<AtlasVertex<Titan0Vertex, Titan0Edge>> vertices() { Iterable<Vertex> vertices = vertexQuery.vertices(); return graph.wrapVertices(vertices); } @Override public Iterable<AtlasVertex<Titan0Vertex, Titan0Edge>> vertices(int limit) { Preconditions.checkArgument(limit >=0, "Limit should be greater than or equals to 0"); Iterable<Vertex> vertices = vertexQuery.limit(limit).vertices(); return graph.wrapVertices(vertices); } @Override public Iterable<AtlasEdge<Titan0Vertex, Titan0Edge>> edges() { Iterable<Edge> edges = vertexQuery.edges(); return graph.wrapEdges(edges); } @Override public Iterable<AtlasEdge<Titan0Vertex, Titan0Edge>> edges(int limit) { Preconditions.checkArgument(limit >=0, "Limit should be greater than or equals to 0"); Iterable<Edge> edges = vertexQuery.limit(limit).edges(); return graph.wrapEdges(edges); } @Override public long count() { return vertexQuery.count(); } } <|start_filename|>repository/src/test/java/org/apache/atlas/repository/store/graph/v1/AtlasRelationshipStoreV1Test.java<|end_filename|> /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.store.graph.v1; import com.google.common.collect.ImmutableList; import org.apache.atlas.RequestContextV1; import org.apache.atlas.TestModules; import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.model.instance.AtlasEntity; import org.apache.atlas.model.instance.AtlasEntity.AtlasEntitiesWithExtInfo; import org.apache.atlas.model.instance.AtlasEntity.AtlasEntityWithExtInfo; import org.apache.atlas.model.instance.AtlasEntityHeader; import org.apache.atlas.model.instance.AtlasObjectId; import org.apache.atlas.model.instance.EntityMutationResponse; import org.apache.atlas.model.typedef.AtlasTypesDef; import org.apache.atlas.repository.graph.AtlasGraphProvider; import org.apache.atlas.repository.graph.GraphBackedSearchIndexer; import org.apache.atlas.repository.store.graph.AtlasEntityStore; import org.apache.atlas.repository.store.graph.AtlasRelationshipStore; import org.apache.atlas.store.AtlasTypeDefStore; import org.apache.atlas.type.AtlasEntityType; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.commons.collections.CollectionUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeTest; import org.testng.annotations.Guice; import org.testng.annotations.Test; import javax.inject.Inject; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.apache.atlas.TestRelationshipUtilsV2.EMPLOYEE_TYPE; import static org.apache.atlas.TestRelationshipUtilsV2.getDepartmentEmployeeInstances; import static org.apache.atlas.TestRelationshipUtilsV2.getDepartmentEmployeeTypes; import static org.apache.atlas.TestRelationshipUtilsV2.getInverseReferenceTestTypes; import static org.apache.atlas.TestUtils.NAME; import static org.apache.atlas.type.AtlasTypeUtil.getAtlasObjectId; import static org.mockito.Mockito.mock; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; @Guice(modules = TestModules.TestOnlyModule.class) public abstract class AtlasRelationshipStoreV1Test { @Inject AtlasTypeRegistry typeRegistry; @Inject AtlasTypeDefStore typeDefStore; @Inject DeleteHandlerV1 deleteHandler; @Inject EntityGraphMapper graphMapper; AtlasEntityStore entityStore; AtlasRelationshipStore relationshipStore; AtlasEntityChangeNotifier mockChangeNotifier = mock(AtlasEntityChangeNotifier.class); protected Map<String, AtlasObjectId> employeeNameIdMap = new HashMap<>(); @BeforeClass public void setUp() throws Exception { new GraphBackedSearchIndexer(typeRegistry); // create employee relationship types AtlasTypesDef employeeTypes = getDepartmentEmployeeTypes(); typeDefStore.createTypesDef(employeeTypes); AtlasEntitiesWithExtInfo employeeInstances = getDepartmentEmployeeInstances(); EntityMutationResponse response = entityStore.createOrUpdate(new AtlasEntityStream(employeeInstances), false); for (AtlasEntityHeader entityHeader : response.getCreatedEntities()) { employeeNameIdMap.put((String) entityHeader.getAttribute(NAME), getAtlasObjectId(entityHeader)); } init(); AtlasTypesDef testTypes = getInverseReferenceTestTypes(); typeDefStore.createTypesDef(testTypes); } @BeforeTest public void init() throws Exception { entityStore = new AtlasEntityStoreV1(deleteHandler, typeRegistry, mockChangeNotifier, graphMapper); relationshipStore = new AtlasRelationshipStoreV1(typeRegistry); RequestContextV1.clear(); } @AfterClass public void clear() { AtlasGraphProvider.cleanup(); } @Test public void testDepartmentEmployeeEntitiesUsingRelationship() throws Exception { AtlasObjectId hrId = employeeNameIdMap.get("hr"); AtlasObjectId maxId = employeeNameIdMap.get("Max"); AtlasObjectId johnId = employeeNameIdMap.get("John"); AtlasObjectId juliusId = employeeNameIdMap.get("Julius"); AtlasObjectId janeId = employeeNameIdMap.get("Jane"); AtlasEntity hrDept = getEntityFromStore(hrId.getGuid()); AtlasEntity max = getEntityFromStore(maxId.getGuid()); AtlasEntity john = getEntityFromStore(johnId.getGuid()); AtlasEntity julius = getEntityFromStore(juliusId.getGuid()); AtlasEntity jane = getEntityFromStore(janeId.getGuid()); // Department relationship attributes List<AtlasObjectId> deptEmployees = toAtlasObjectIds(hrDept.getRelationshipAttribute("employees")); assertNotNull(deptEmployees); assertEquals(deptEmployees.size(), 4); assertObjectIdsContains(deptEmployees, maxId); assertObjectIdsContains(deptEmployees, johnId); assertObjectIdsContains(deptEmployees, juliusId); assertObjectIdsContains(deptEmployees, janeId); // Max employee validation AtlasObjectId maxDepartmentId = toAtlasObjectId(max.getRelationshipAttribute("department")); assertNotNull(maxDepartmentId); assertObjectIdEquals(maxDepartmentId, hrId); AtlasObjectId maxManagerId = toAtlasObjectId(max.getRelationshipAttribute("manager")); assertNotNull(maxManagerId); assertObjectIdEquals(maxManagerId, janeId); AtlasObjectId maxMentorId = toAtlasObjectId(max.getRelationshipAttribute("mentor")); assertNotNull(maxMentorId); assertObjectIdEquals(maxMentorId, juliusId); List<AtlasObjectId> maxMenteesId = toAtlasObjectIds(max.getRelationshipAttribute("mentees")); assertNotNull(maxMenteesId); assertEquals(maxMenteesId.size(), 1); assertObjectIdEquals(maxMenteesId.get(0), johnId); // John Employee validation AtlasObjectId johnDepartmentId = toAtlasObjectId(john.getRelationshipAttribute("department")); assertNotNull(johnDepartmentId); assertObjectIdEquals(johnDepartmentId, hrId); AtlasObjectId johnManagerId = toAtlasObjectId(john.getRelationshipAttribute("manager")); assertNotNull(johnManagerId); assertObjectIdEquals(johnManagerId, janeId); AtlasObjectId johnMentorId = toAtlasObjectId(john.getRelationshipAttribute("mentor")); assertNotNull(johnMentorId); assertObjectIdEquals(johnMentorId, maxId); List<AtlasObjectId> johnMenteesId = toAtlasObjectIds(john.getRelationshipAttribute("mentees")); assertEmpty(johnMenteesId); // Jane Manager validation AtlasObjectId janeDepartmentId = toAtlasObjectId(jane.getRelationshipAttribute("department")); assertNotNull(janeDepartmentId); assertObjectIdEquals(janeDepartmentId, hrId); AtlasObjectId janeManagerId = toAtlasObjectId(jane.getRelationshipAttribute("manager")); assertNull(janeManagerId); AtlasObjectId janeMentorId = toAtlasObjectId(jane.getRelationshipAttribute("mentor")); assertNull(janeMentorId); List<AtlasObjectId> janeMenteesId = toAtlasObjectIds(jane.getRelationshipAttribute("mentees")); assertEmpty(janeMenteesId); List<AtlasObjectId> janeSubordinateIds = toAtlasObjectIds(jane.getRelationshipAttribute("subordinates")); assertNotNull(janeSubordinateIds); assertEquals(janeSubordinateIds.size(), 2); assertObjectIdsContains(janeSubordinateIds, maxId); assertObjectIdsContains(janeSubordinateIds, johnId); // Julius Manager validation AtlasObjectId juliusDepartmentId = toAtlasObjectId(julius.getRelationshipAttribute("department")); assertNotNull(juliusDepartmentId); assertObjectIdEquals(juliusDepartmentId, hrId); AtlasObjectId juliusManagerId = toAtlasObjectId(julius.getRelationshipAttribute("manager")); assertNull(juliusManagerId); AtlasObjectId juliusMentorId = toAtlasObjectId(julius.getRelationshipAttribute("mentor")); assertNull(juliusMentorId); List<AtlasObjectId> juliusMenteesId = toAtlasObjectIds(julius.getRelationshipAttribute("mentees")); assertNotNull(juliusMenteesId); assertEquals(juliusMenteesId.size(), 1); assertObjectIdsContains(juliusMenteesId, maxId); List<AtlasObjectId> juliusSubordinateIds = toAtlasObjectIds(julius.getRelationshipAttribute("subordinates")); assertEmpty(juliusSubordinateIds); } @Test public void testRelationshipAttributeUpdate_NonComposite_OneToMany() throws Exception { AtlasObjectId maxId = employeeNameIdMap.get("Max"); AtlasObjectId juliusId = employeeNameIdMap.get("Julius"); AtlasObjectId janeId = employeeNameIdMap.get("Jane"); // Change Max's Employee.manager reference to Julius and apply the change as a partial update. // This should also update Julius to add Max to the inverse Manager.subordinates reference. AtlasEntity maxEntityForUpdate = new AtlasEntity(EMPLOYEE_TYPE); maxEntityForUpdate.setRelationshipAttribute("manager", juliusId); AtlasEntityType employeeType = typeRegistry.getEntityTypeByName(EMPLOYEE_TYPE); Map<String, Object> uniqAttributes = Collections.<String, Object>singletonMap("name", "Max"); EntityMutationResponse updateResponse = entityStore.updateByUniqueAttributes(employeeType, uniqAttributes , new AtlasEntityWithExtInfo(maxEntityForUpdate)); List<AtlasEntityHeader> partialUpdatedEntities = updateResponse.getPartialUpdatedEntities(); assertEquals(partialUpdatedEntities.size(), 3); // 3 entities should have been updated: // * Max to change the Employee.manager reference // * Julius to add Max to Manager.subordinates // * Jane to remove Max from Manager.subordinates AtlasEntitiesWithExtInfo updatedEntities = entityStore.getByIds(ImmutableList.of(maxId.getGuid(), juliusId.getGuid(), janeId.getGuid())); // Max's manager updated as Julius AtlasEntity maxEntity = updatedEntities.getEntity(maxId.getGuid()); verifyRelationshipAttributeValue(maxEntity, "manager", juliusId.getGuid()); // Max added to the subordinate list of Julius AtlasEntity juliusEntity = updatedEntities.getEntity(juliusId.getGuid()); verifyRelationshipAttributeList(juliusEntity, "subordinates", ImmutableList.of(maxId)); // Max removed from the subordinate list of Julius AtlasEntity janeEntity = updatedEntities.getEntity(janeId.getGuid()); // Jane's subordinates list includes John and Max for soft delete // Jane's subordinates list includes only John for hard delete verifyRelationshipAttributeUpdate_NonComposite_OneToMany(janeEntity); } @Test public void testRelationshipAttributeUpdate_NonComposite_ManyToOne() throws Exception { AtlasEntity a1 = new AtlasEntity("A"); a1.setAttribute(NAME, "a1_name"); AtlasEntity a2 = new AtlasEntity("A"); a2.setAttribute(NAME, "a2_name"); AtlasEntity a3 = new AtlasEntity("A"); a3.setAttribute(NAME, "a3_name"); AtlasEntity b = new AtlasEntity("B"); b.setAttribute(NAME, "b_name"); AtlasEntitiesWithExtInfo entitiesWithExtInfo = new AtlasEntitiesWithExtInfo(); entitiesWithExtInfo.addEntity(a1); entitiesWithExtInfo.addEntity(a2); entitiesWithExtInfo.addEntity(a3); entitiesWithExtInfo.addEntity(b); entityStore.createOrUpdate(new AtlasEntityStream(entitiesWithExtInfo) , false); AtlasEntity bPartialUpdate = new AtlasEntity("B"); bPartialUpdate.setRelationshipAttribute("manyA", ImmutableList.of(getAtlasObjectId(a1), getAtlasObjectId(a2))); init(); EntityMutationResponse response = entityStore.updateByUniqueAttributes(typeRegistry.getEntityTypeByName("B"), Collections.singletonMap(NAME, b.getAttribute(NAME)), new AtlasEntityWithExtInfo(bPartialUpdate)); // Verify 3 entities were updated: // * set b.manyA reference to a1 and a2 // * set inverse a1.oneB reference to b // * set inverse a2.oneB reference to b assertEquals(response.getPartialUpdatedEntities().size(), 3); AtlasEntitiesWithExtInfo updatedEntities = entityStore.getByIds(ImmutableList.of(a1.getGuid(), a2.getGuid(), b.getGuid())); AtlasEntity a1Entity = updatedEntities.getEntity(a1.getGuid()); verifyRelationshipAttributeValue(a1Entity, "oneB", b.getGuid()); AtlasEntity a2Entity = updatedEntities.getEntity(a2.getGuid()); verifyRelationshipAttributeValue(a2Entity, "oneB", b.getGuid()); AtlasEntity bEntity = updatedEntities.getEntity(b.getGuid()); verifyRelationshipAttributeList(bEntity, "manyA", ImmutableList.of(getAtlasObjectId(a1), getAtlasObjectId(a2))); bPartialUpdate.setRelationshipAttribute("manyA", ImmutableList.of(getAtlasObjectId(a3))); init(); response = entityStore.updateByUniqueAttributes(typeRegistry.getEntityTypeByName("B"), Collections.singletonMap(NAME, b.getAttribute(NAME)), new AtlasEntityWithExtInfo(bPartialUpdate)); // Verify 4 entities were updated: // * set b.manyA reference to a3 // * set inverse a3.oneB reference to b // * disconnect inverse a1.oneB reference to b // * disconnect inverse a2.oneB reference to b assertEquals(response.getPartialUpdatedEntities().size(), 4); init(); updatedEntities = entityStore.getByIds(ImmutableList.of(a1.getGuid(), a2.getGuid(), a3.getGuid(), b.getGuid())); a1Entity = updatedEntities.getEntity(a1.getGuid()); a2Entity = updatedEntities.getEntity(a2.getGuid()); bEntity = updatedEntities.getEntity(b.getGuid()); AtlasEntity a3Entity = updatedEntities.getEntity(a3.getGuid()); verifyRelationshipAttributeValue(a3Entity, "oneB", b.getGuid()); verifyRelationshipAttributeUpdate_NonComposite_ManyToOne(a1Entity, a2Entity, a3Entity, bEntity); } @Test public void testRelationshipAttributeUpdate_NonComposite_OneToOne() throws Exception { AtlasEntity a1 = new AtlasEntity("A"); a1.setAttribute(NAME, "a1_name"); AtlasEntity a2 = new AtlasEntity("A"); a2.setAttribute(NAME, "a2_name"); AtlasEntity b = new AtlasEntity("B"); b.setAttribute(NAME, "b_name"); AtlasEntitiesWithExtInfo entitiesWithExtInfo = new AtlasEntitiesWithExtInfo(); entitiesWithExtInfo.addEntity(a1); entitiesWithExtInfo.addEntity(a2); entitiesWithExtInfo.addEntity(b); EntityMutationResponse response = entityStore.createOrUpdate(new AtlasEntityStream(entitiesWithExtInfo) , false); AtlasEntity partialUpdateB = new AtlasEntity("B"); partialUpdateB.setRelationshipAttribute("a", getAtlasObjectId(a1)); init(); AtlasEntityType bType = typeRegistry.getEntityTypeByName("B"); response = entityStore.updateByUniqueAttributes(bType, Collections.singletonMap(NAME, b.getAttribute(NAME)), new AtlasEntityWithExtInfo(partialUpdateB)); List<AtlasEntityHeader> partialUpdatedEntitiesHeader = response.getPartialUpdatedEntities(); // Verify 2 entities were updated: // * set b.a reference to a1 // * set inverse a1.b reference to b assertEquals(partialUpdatedEntitiesHeader.size(), 2); AtlasEntitiesWithExtInfo partialUpdatedEntities = entityStore.getByIds(ImmutableList.of(a1.getGuid(), b.getGuid())); AtlasEntity a1Entity = partialUpdatedEntities.getEntity(a1.getGuid()); verifyRelationshipAttributeValue(a1Entity, "b", b.getGuid()); AtlasEntity bEntity = partialUpdatedEntities.getEntity(b.getGuid()); verifyRelationshipAttributeValue(bEntity, "a", a1.getGuid()); init(); // Update b.a to reference a2. partialUpdateB.setRelationshipAttribute("a", getAtlasObjectId(a2)); response = entityStore.updateByUniqueAttributes(bType, Collections.<String, Object>singletonMap(NAME, b.getAttribute(NAME)), new AtlasEntityWithExtInfo(partialUpdateB)); partialUpdatedEntitiesHeader = response.getPartialUpdatedEntities(); // Verify 3 entities were updated: // * set b.a reference to a2 // * set a2.b reference to b // * disconnect a1.b reference assertEquals(partialUpdatedEntitiesHeader.size(), 3); partialUpdatedEntities = entityStore.getByIds(ImmutableList.of(a1.getGuid(), a2.getGuid(), b.getGuid())); bEntity = partialUpdatedEntities.getEntity(b.getGuid()); verifyRelationshipAttributeValue(bEntity, "a", a2.getGuid()); AtlasEntity a2Entity = partialUpdatedEntities.getEntity(a2.getGuid()); verifyRelationshipAttributeValue(a2Entity, "b", b.getGuid()); a1Entity = partialUpdatedEntities.getEntity(a1.getGuid()); verifyRelationshipAttributeUpdate_NonComposite_OneToOne(a1Entity, bEntity); } @Test public void testRelationshipAttributeUpdate_NonComposite_ManyToMany() throws Exception { AtlasEntity a1 = new AtlasEntity("A"); a1.setAttribute(NAME, "a1_name"); AtlasEntity a2 = new AtlasEntity("A"); a2.setAttribute(NAME, "a2_name"); AtlasEntity a3 = new AtlasEntity("A"); a3.setAttribute(NAME, "a3_name"); AtlasEntity b1 = new AtlasEntity("B"); b1.setAttribute(NAME, "b1_name"); AtlasEntity b2 = new AtlasEntity("B"); b2.setAttribute(NAME, "b2_name"); AtlasEntitiesWithExtInfo entitiesWithExtInfo = new AtlasEntitiesWithExtInfo(); entitiesWithExtInfo.addEntity(a1); entitiesWithExtInfo.addEntity(a2); entitiesWithExtInfo.addEntity(a3); entitiesWithExtInfo.addEntity(b1); entitiesWithExtInfo.addEntity(b2); entityStore.createOrUpdate(new AtlasEntityStream(entitiesWithExtInfo) , false); AtlasEntity b1PartialUpdate = new AtlasEntity("B"); b1PartialUpdate.setRelationshipAttribute("manyToManyA", ImmutableList.of(getAtlasObjectId(a1), getAtlasObjectId(a2))); init(); EntityMutationResponse response = entityStore.updateByUniqueAttributes(typeRegistry.getEntityTypeByName("B"), Collections.singletonMap(NAME, b1.getAttribute(NAME)), new AtlasEntityWithExtInfo(b1PartialUpdate)); List<AtlasEntityHeader> updatedEntityHeaders = response.getPartialUpdatedEntities(); assertEquals(updatedEntityHeaders.size(), 3); AtlasEntitiesWithExtInfo updatedEntities = entityStore.getByIds(ImmutableList.of(a1.getGuid(), a2.getGuid(), b1.getGuid())); AtlasEntity b1Entity = updatedEntities.getEntity(b1.getGuid()); verifyRelationshipAttributeList(b1Entity, "manyToManyA", ImmutableList.of(getAtlasObjectId(a1), getAtlasObjectId(a2))); AtlasEntity a1Entity = updatedEntities.getEntity(a1.getGuid()); verifyRelationshipAttributeList(a1Entity, "manyB", ImmutableList.of(getAtlasObjectId(b1))); AtlasEntity a2Entity = updatedEntities.getEntity(a2.getGuid()); verifyRelationshipAttributeList(a2Entity, "manyB", ImmutableList.of(getAtlasObjectId(b1))); } protected abstract void verifyRelationshipAttributeUpdate_NonComposite_OneToOne(AtlasEntity a1, AtlasEntity b); protected abstract void verifyRelationshipAttributeUpdate_NonComposite_OneToMany(AtlasEntity entity) throws Exception; protected abstract void verifyRelationshipAttributeUpdate_NonComposite_ManyToOne(AtlasEntity a1, AtlasEntity a2, AtlasEntity a3, AtlasEntity b); private static void assertObjectIdsContains(List<AtlasObjectId> objectIds, AtlasObjectId objectId) { assertTrue(CollectionUtils.isNotEmpty(objectIds)); assertTrue(objectIds.contains(objectId)); } private static void assertObjectIdEquals(AtlasObjectId objId1, AtlasObjectId objId2) { assertTrue(objId1.equals(objId2)); } private static void assertEmpty(List collection) { assertTrue(collection != null && collection.isEmpty()); } private static List<AtlasObjectId> toAtlasObjectIds(Object objectIds) { if (objectIds instanceof List) { return (List<AtlasObjectId>) objectIds; } return null; } private static AtlasObjectId toAtlasObjectId(Object objectId) { if (objectId instanceof AtlasObjectId) { return (AtlasObjectId) objectId; } return null; } private AtlasEntity getEntityFromStore(String guid) throws AtlasBaseException { AtlasEntityWithExtInfo entity = guid != null ? entityStore.getById(guid) : null; return entity != null ? entity.getEntity() : null; } protected static void verifyRelationshipAttributeList(AtlasEntity entity, String relationshipAttrName, List<AtlasObjectId> expectedValues) { Object refValue = entity.getRelationshipAttribute(relationshipAttrName); assertTrue(refValue instanceof List); List<AtlasObjectId> refList = (List<AtlasObjectId>) refValue; assertEquals(refList.size(), expectedValues.size()); if (expectedValues.size() > 0) { assertTrue(refList.containsAll(expectedValues)); } } protected static void verifyRelationshipAttributeValue(AtlasEntity entity, String relationshipAttrName, String expectedGuid) { Object refValue = entity.getRelationshipAttribute(relationshipAttrName); if (expectedGuid == null) { assertNull(refValue); } else { assertTrue(refValue instanceof AtlasObjectId); AtlasObjectId referencedObjectId = (AtlasObjectId) refValue; assertEquals(referencedObjectId.getGuid(), expectedGuid); } } }
nixonrodrigues/incubator-atlas
<|start_filename|>game.asm<|end_filename|> ;;; Some instructions ;;;;; ; LDX: load x ; STX: store x ; SEI: set interrupt disable ; CLD: clear decimal ; TXS: transfer X to stack pointer ;;; ; Variables char_vel_x = $0001 char_vel_y = $0002 ;;; Important Registers ; PPU PPU_CTRL = $2000 PPU_MASK = $2001 PPU_STATUS = $2002 OAM_ADDR = $2003 OAM_DATA = $2004 PPU_SCROLL = $2005 PPU_ADDR = $2006 PPU_DATA = $2007 OAM_DMA = $4014 ; APU SQ1_VOL = $4000 SQ1_LO = $4002 SQ1_HI = $4003 APU_STATUS = $4015 ; CONTROLLER INPUT JOY1 = $4016 .segment "HEADER" .byte "NES", $1A .byte 2 .byte 1 .byte $01, $00 .segment "STARTUP" .segment "CODE" reset: sei ; disable IRQs cld ; disable decimal mode ; ldx #$40 ; stx $4017 ; disable APU frame IRQ ldx #$FF txs ; set up stack inx ; now X = 0 lda PPU_STATUS ldx #%00000000 stx PPU_CTRL ; disable NMI ldx #%00000000 stx PPU_MASK ; disable rendering ; stx $4010 ; disable DMC IRQs lda PPU_STATUS ; PPU warm up vblankwait1: ; First wait for vblank to make sure PPU is ready bit PPU_STATUS ; PPU status register bpl vblankwait1 vblankwait2: bit PPU_STATUS bpl vblankwait2 lda #$00 ldx #$00 clear_memory: sta $0000, X sta $0100, X sta $0200, X sta $0300, X sta $0400, X sta $0500, X sta $0600, X sta $0700, X inx cpx #$00 bne clear_memory ; Loading nametable lda PPU_STATUS ; reading PPUSTATUS lda #$20 ; writing 0x2000 in PPUADDR to write on PPU, the address for nametable 0 sta PPU_ADDR lda #$00 sta PPU_ADDR lda #<background_nametable ; saving nametable in RAM sta $0000 lda #>background_nametable sta $0001 ldx #$00 ldy #$00 nametable_loop: lda ($00), Y sta PPU_DATA iny cpy #$00 bne nametable_loop inc $0001 inx cpx #$04 ; size of nametable 0: 0x0400 bne nametable_loop ; Color setup for background lda PPU_STATUS lda #$3F ; writing 0x3F00, pallete RAM indexes sta PPU_ADDR lda #$00 sta PPU_ADDR ldx #$00 background_color_loop: lda background_pallete, X sta PPU_DATA inx cpx #$10 ; size of pallete RAM: 0x0020, until 0x3F10 is background palletes bne background_color_loop ; after 0x3F10, there should be sprite palletes ; Sprites color setup lda PPU_STATUS lda #$3F sta PPU_ADDR lda #$10 sta PPU_ADDR ldx #$00 sprite_color_loop: lda background_pallete, X sta PPU_DATA inx cpx #$10 bne sprite_color_loop ; Code for reseting scroll lda #$00 sta PPU_SCROLL lda #$00 sta PPU_SCROLL ; Turning on NMI and rendering lda #%10010000 sta PPU_CTRL ; PPUCTRL lda #%00011010 ; show background sta PPU_MASK ; PPUMASK, controls rendering of sprites and backgrounds ; Let's try some audio ; enable apu lda #%00000001 sta APU_STATUS lda #$01 sta char_vel_x forever: ; Reading input data lda #$01 sta JOY1 lda #$00 sta JOY1 ; Order: A B Select Start Up Down Left Right ; only one bit is read at a time, so we have to read JOY1 eight times ; A lda JOY1 and #%00000001 cmp #%00000001 bne A_not_pressed A_not_pressed: ; B lda JOY1 and #%00000001 cmp #%00000001 bne B_not_pressed B_not_pressed: ; Select lda JOY1 and #%00000001 cmp #%00000001 bne Select_not_pressed Select_not_pressed: ; Start lda JOY1 and #%00000001 cmp #%00000001 bne Start_not_pressed Start_not_pressed: ; Up lda JOY1 and #%00000001 cmp #%00000001 bne Up_not_pressed dec char_vel_y Up_not_pressed: ; Down lda JOY1 and #%00000001 cmp #%00000001 bne Down_not_pressed inc char_vel_y Down_not_pressed: ; Left lda JOY1 and #%00000001 cmp #%00000001 bne Left_not_pressed dec char_vel_x Left_not_pressed: ; Right lda JOY1 and #%00000001 cmp #%00000001 bne Right_not_pressed inc char_vel_x Right_not_pressed: jmp forever nmi: nmi_sprites: lda #$00 sta OAM_ADDR lda #$02 sta OAM_DMA ;; Draw character lda #$08 ; Top of the screen clc adc char_vel_y sta $0200 ; Sprite 1 Y Position lda #$08 clc adc char_vel_y sta $0204 ; Sprite 2 Y Position lda #$10 clc adc char_vel_y sta $0208 ; Sprite 3 Y Position lda #$10 clc adc char_vel_y sta $020C ; Sprite 4 Y Position lda #$3A ; Top Left section of Mario standing still sta $0201 ; Sprite 1 Tile Number lda #$37 ; Top Right section of Mario standing still sta $0205 ; Sprite 2 Tile Number lda #$4F ; Bottom Left section of Mario standing still sta $0209 ; Sprite 3 Tile Number lda #$4F ; Bottom Right section of Mario standing still sta $020D ; Sprite 4 Tile Number lda #$00 ; No attributes, using first sprite palette which is number 0 sta $0202 ; Sprite 1 Attributes sta $0206 ; Sprite 2 Attributes sta $020A ; Sprite 3 Attributes lda #$40 ; Flip horizontal attribute sta $020E ; Sprite 4 Attributes lda #$08 ; Left of the screen. clc adc char_vel_x sta $0203 ; Sprite 1 X Position lda #$10 clc adc char_vel_x sta $0207 ; Sprite 2 X Position lda #$08 clc adc char_vel_x sta $020B ; Sprite 3 X Position lda #$10 clc adc char_vel_x sta $020F ; Sprite 4 X Position rti irq: rti play_a440: pha lda #%10011111 sta SQ1_VOL ; lda #%11111101 ; Low: 0xFD ; sta SQ1_LO ; lda #%11111000 ; High: 0x00 ; sta SQ1_HI ldx #$27 lda periodTableLo, X sta SQ1_LO lda periodTableHi, X ora #%10011000 sta SQ1_HI pla rts play_a220: pha lda #%10011111 sta SQ1_VOL lda #%11111011 sta SQ1_LO lda #%11111001 sta SQ1_HI pla rts periodTableLo: .byte $F1,$7f,$13,$ad,$4d,$f3,$9d,$4c,$00,$b8,$74,$34 .byte $F8,$BF,$89,$56,$26,$f9,$ce,$a6,$80,$5c,$3a,$1a .byte $FB,$DF,$c4,$ab,$93,$7c,$67,$52,$3f,$2d,$1c,$0c .byte $FD,$EF,$e1,$d5,$c9,$bd,$b3,$a9,$9f,$96,$8e,$86 .byte $7E,$77,$70,$6a,$64,$5e,$59,$54,$4f,$4b,$46,$42 .byte $3F,$3B,$38,$34,$31,$2f,$2c,$29,$27,$25,$23,$21 .byte $1F,$1D,$1b,$1a,$18,$17,$15,$14 periodTableHi: .byte $07,$07,$07,$06,$06,$05,$05,$05,$05,$04,$04,$04 .byte $03,$03,$03,$03,$03,$02,$02,$02,$02,$02,$02,$02 .byte $01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01,$01 .byte $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00 .byte $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00 .byte $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00 .byte $00,$00,$00,$00,$00,$00,$00,$00 background_nametable: .incbin "backgrounds/bk1.nam" background_pallete: .incbin "backgrounds/bag.pal" ;.segment "RODATA" .segment "VECTORS" .word nmi ; when non-maskable interrupt happens, goes to label nmi .word reset ; when the processor first turns on or is reset, goes to reset .word irq ; using external interrupt IRQ .segment "CHARS" .incbin "chr/mario.chr" ; includes 8KB graphics
sampaio23/nesgame
<|start_filename|>src/sections/pricing.js<|end_filename|> import { useState, useCallback } from 'react'; import { keyframes } from '@emotion/core';/** @jsx jsx */ import { jsx, Box, Grid, Container, Flex, Text, Button } from 'theme-ui'; import SectionHeading from 'components/section-heading'; import PriceTable from 'components/cards/price-table'; import Switch from 'components/switch'; const data = [ { id: 1, title: 'Pacote de startup', subtitle: 'Para a equipe de startup que trabalha com a nova pilha de dados central', amount: { monthly: 25.99, annual: 25.99 * 12 - 10, }, isRecommended: false, buttonText: 'Comece o teste grátis', features: [ { id: 1, isAvailable: true, title: 'Acesso final a todos os cursos, exercícios e avaliações', }, { id: 2, isAvailable: true, title: `Acesso gratuito para todo tipo de correções de exercícios com downloads.`, }, { id: 3, isAvailable: true, title: `Total de correções de avaliação com sistema de acesso de download gratuito`, }, { id: 4, isAvailable: false, title: `Download ilimitado de cursos no conteúdo do aplicativo móvel`, }, { id: 5, isAvailable: false, title: `Baixe e imprima cursos e exercícios em PDF`, }, ], }, { id: 2, title: 'Pacote Premium', subtitle: 'Para os usuários Pro que trabalham com stacks moderna', amount: { monthly: 49.99, annual: 49.99 * 12 - 10, }, isRecommended: true, buttonText: 'Comece o teste grátis', features: [ { id: 1, isAvailable: true, title: 'Acesso final a todos os cursos, exercícios e avaliações', }, { id: 2, isAvailable: true, title: `Acesso gratuito para todo tipo de correções de exercícios com downloads.`, }, { id: 3, isAvailable: true, title: `Total assessment corrections with free download access system`, }, { id: 4, isAvailable: true, title: `Download ilimitado de cursos no conteúdo do aplicativo móvel`, }, { id: 5, isAvailable: true, title: `Baixe e imprima cursos e exercícios em PDF`, }, ], }, ]; const Pricing = () => { const [isMonthly, setIsMonthly] = useState(true); const handlePlan = () => { setIsMonthly(!isMonthly); }; return ( <Box as="section" id="pricing" sx={styles.section}> <Container> <SectionHeading sx={styles.heading} title="Que negócio combina perfeitamente com você" description="Conheça nossos planos" /> <Flex sx={styles.priceSwitcher}> <Text as="span">Plano Mensal</Text> <Switch isMonthly={isMonthly} handlePlan={handlePlan} /> <Text as="span">Plano Anual</Text> </Flex> <Box sx={styles.priceWrapper}> {data?.map((price, index) => ( <PriceTable price={price} isAnnual={!isMonthly} key={`${isMonthly}-${index}`} /> ))} </Box> </Container> </Box> ); }; export default Pricing; const fadeIn = keyframes` from { opacity: 0; } to { opacity: 1; } `; const fadeIn2 = keyframes` from { transform: translateY(50%); opacity: 0; } to { transform: translateY(0); opacity: 1; } `; const styles = { section: { backgroundColor: '#F9FAFC', pt: [11], pb: [11], }, heading: { mb: 3, h2: { fontSize: [6, null, null, 8], }, p: { color: '#858B91', fontSize: 3, m: ['10px auto', null, null, '0 auto'], }, }, priceSwitcher: { display: 'flex', alignItems: 'center', margin: [ '35px auto 50px', null, null, '0 auto 30px', null, '60px auto 50px', ], maxWidth: 300, p: 2, span: { color: 'text', fontWeight: 500, outline: 0, p: 0, minHeight: 'auto', }, }, priceWrapper: { display: ['block', null, null, 'flex'], alignItems: 'center', justifyContent: 'center', '.priceCard': { '.priceHeader': { animation: `${fadeIn} 0.8s linear`, }, 'ul > li': { animation: `${fadeIn2} 0.7s linear`, }, '.priceAmount': { animation: `${fadeIn} 0.9s linear`, }, '.priceButton': { animation: `${fadeIn2} 0.7s linear`, }, }, }, }; <|start_filename|>src/sections/testimonials.js<|end_filename|> import dynamic from 'next/dynamic';/** @jsx jsx */ import { jsx, Box, Container } from 'theme-ui'; import { Swiper, SwiperSlide } from 'swiper/react'; import SectionHeading from 'components/section-heading'; const Testimonial = dynamic(() => import('components/cards/testimonial')); // import Testimonial from 'components/cards/testimonial'; import avatar1 from 'assets/images/testimonials/1.png'; import avatar2 from 'assets/images/testimonials/2.png'; import avatar3 from 'assets/images/testimonials/3.png'; import avatar4 from 'assets/images/testimonials/4.png'; import avatar5 from 'assets/images/testimonials/5.png'; import avatar6 from 'assets/images/testimonials/6.png'; import avatar7 from 'assets/images/testimonials/7.png'; import avatar8 from 'assets/images/testimonials/8.png'; const data = [ [ { id: 1, avatar: avatar1, name: '<NAME>', username: '@hi.veona', text: `Gostaria apenas de cumprimentar Estelle Pestana. Ela tem sido muito profissional e não mede esforços para me ajudar. Sua paciência comigo enquanto eu continuamente mudava meus planos deve ser elogiada. Seu serviço reafirma por que eu sempre escolho reservar por meio de uma agência em vez de diretamente. Obrigada`, }, { id: 2, avatar: avatar2, name: '<NAME>', username: '@hello.mimmie', text: `Gostaria de aproveitar esta oportunidade para agradecer à SA Places pelo excelente serviço prestado a nós e em particular a Estelle. Você me deu o melhor lugar de todos alguns momentos depois que falei com você.`, }, ], [ { id: 3, avatar: avatar3, name: '<NAME>', username: '@merryn.manley', text: `Muito obrigado pelo seu serviço amável e eficiente. Já recomendei e com certeza continuarei recomendando seus serviços a outras pessoas no futuro.`, }, { id: 4, avatar: avatar4, name: '<NAME>', username: '@hey.nku', text: `Gostaria apenas de cumprimentar Estelle Pestana. Ela tem sido muito profissional e não mede esforços para me ajudar. Sua paciência comigo enquanto eu continuamente mudava meus planos deve ser elogiada. Seu serviço reafirma por que eu sempre escolho reservar por meio de uma agência em vez de diretamente. Obrigada`, }, ], [ { id: 5, avatar: avatar5, name: '<NAME>', username: '@cherice.me', text: `Obrigado por toda sua ajuda. Seu serviço foi excelente e muito RÁPIDO.`, }, { id: 6, avatar: avatar6, name: '<NAME>', username: '@myself.thais', text: `Para a nossa recente viagem a S.A., reservei várias acomodações através do SA Places. Só queria dizer que tudo correu perfeitamente com todas as reservas e também a sua reserva foi muito rápida e profissional. Espero ter a oportunidade de visitar novamente a África do Sul em breve, então farei minhas reservas com sua empresa novamente. Eu também irei recomendar`, }, ], [ { id: 7, avatar: avatar7, name: '<NAME>', username: '@hi.veona', text: `Gostaria apenas de cumprimentar Estelle Pestana. Ela tem sido muito profissional e não mede esforços para me ajudar. Sua paciência comigo enquanto eu continuamente mudava meus planos deve ser elogiada. Seu serviço reafirma por que eu sempre escolho reservar por meio de uma agência em vez de diretamente. Obrigada`, }, { id: 8, avatar: avatar8, name: '<NAME>', username: '@hello.mimmie', text: `Gostaria de aproveitar a oportunidade para agradecer à SA Places pelo excelente serviço prestado a nós e em particular a Estelle. Você me deu o melhor lugar de todos alguns momentos depois que falei com você.`, }, ], [ { id: 9, avatar: avatar1, name: '<NAME>', username: '@merryn.manley', text: `Muito obrigado pelo seu serviço amável e eficiente. Já recomendei e com certeza continuarei recomendando seus serviços a outras pessoas no futuro.`, }, { id: 10, avatar: avatar2, name: '<NAME>', username: '@hey.nku', text: `Gostaria apenas de cumprimentar Estelle Pestana. Ela tem sido muito profissional e não mede esforços para me ajudar. Sua paciência comigo enquanto eu continuamente mudava meus planos deve ser elogiada. Seu serviço reafirma por que eu sempre escolho reservar por meio de uma agência em vez de diretamente. Obrigada`, }, ], [ { id: 11, avatar: avatar3, name: '<NAME>', username: '@cherice.me', text: `Obrigado por toda sua ajuda. Seu serviço foi excelente e muito RÁPIDO.`, }, { id: 12, avatar: avatar4, name: '<NAME>', username: '@myself.thais', text: `Para a nossa recente viagem a S.A., reservei várias acomodações através do SA Places. Só queria dizer que tudo correu perfeitamente com todas as reservas e também a sua reserva foi muito rápida e profissional. Espero ter a oportunidade de visitar novamente a África do Sul em breve, então farei minhas reservas com sua empresa novamente. Eu também irei recomendar`, }, ], ]; const Testimonials = () => { const options = { spaceBetween: 20, loop: true, grabCursor: true, centeredSlides: true, breakpoints: { 0: { slidesPerView: 1, }, 640: { slidesPerView: 2, }, 1366: { slidesPerView: 3, }, 1600: { slidesPerView: 4, }, }, }; return ( <section id="testimonials" sx={styles.section}> <Container> <SectionHeading sx={styles.heading} title="O que o cliente fala sobre nós" description="Depoimento de cliente" /> </Container> <Swiper sx={styles.carousel} {...options}> {data.map((item, index) => ( <SwiperSlide key={index}> {item.map((slide) => ( <Testimonial key={slide.id} data={slide} /> ))} </SwiperSlide> ))} </Swiper> {/* <Box sx={styles.testimonials}></Box> */} </section> ); }; export default Testimonials; const styles = { section: { backgroundColor: '#FFFCF7', pt: [10, null, null, 9, 10, 11, 11], pb: [7, null, null, 7, 7, 9, 9], }, heading: { mb: [7, null, null, null, 8], h2: { fontSize: [6, null, null, 8], }, p: { color: '#858B91', fontSize: 3, m: ['10px auto', null, null, '0 auto'], }, }, carousel: { '&.swiper-container': { pb: [8], pl: [6, null, null, 0], pr: [6, null, null, 0], }, }, }; <|start_filename|>src/sections/premium-feature.js<|end_filename|> /** @jsx jsx */ import { jsx, Box, Container, Grid } from 'theme-ui'; import SectionHeading from 'components/section-heading'; import Accordion from 'components/accordion/accordion'; import Image from 'components/image'; import messenger from 'assets/images/messenger.png'; import emoji from 'assets/images/icons/emoji-2.png'; const data = [ { title: 'Organize o conteúdo do seu projeto', contents: ( <div> Obtenha seus exames de sangue entregues em vamos coletar uma amostra da vitória de os gerentes que fornecem as melhores diretrizes de sistema de design de todos os tempos. </div> ), }, { title: 'Colabore seus documentos facilmente', contents: ( <div> Obtenha seus exames de sangue entregues em vamos coletar uma amostra da vitória de os gerentes que fornecem as melhores diretrizes de sistema de design de todos os tempos. </div> ), }, { title: `Construa a base de conhecimento de sua equipe`, contents: ( <div> Obtenha seus exames de sangue entregues em vamos coletar uma amostra da vitória de os gerentes que fornecem as melhores diretrizes de sistema de design de todos os tempos. </div> ), }, ]; const PremiumFeature = () => { return ( <section id="features" sx={styles.section}> <Container> <Grid sx={styles.grid}> <Box as="figure" sx={styles.illustration}> <Image src={messenger} alt="messenger" /> </Box> <Box sx={styles.rightContent}> <SectionHeading emoji={emoji} sx={styles.heading} title="Conheça nossos recursos premium que o farão impressionar" description="Construa um local de trabalho incrível e expanda seus negócios com a plataforma tudo-em-um da Gusto com conteúdos incríveis." /> <Box sx={styles.accordionGroup}> <Accordion items={data} /> </Box> </Box> </Grid> </Container> </section> ); }; export default PremiumFeature; const styles = { section: { pt: [6, null, null, 6, 8, 9], pb: [6, null, null, null, 7, 9, 11, null], }, grid: { alignItems: 'center', gridTemplateColumns: [ '1fr', null, null, null, '1fr 431px', '1fr 530px', '1fr 550px', ], }, heading: { textAlign: ['left', null, null, 'center', 'left'], ml: [null, null, null, 'auto'], maxWidth: [null, null, null, 520, 660], h2: { fontSize: [null, null, null, 10, 8, 10, 40], img: { maxWidth: [24, null, null, 30, 25, null, '100%'], top: ['4px', '8px', null, null, '4px', '8px'], }, }, p: { fontSize: [null, null, null, 2], }, }, illustration: { mb: [-6, null, null, -8, 0], }, accordionGroup: { m: [null, null, null, '0 auto', 'unset'], maxWidth: [null, null, null, 600, 'none'], }, }; <|start_filename|>src/components/header/header.data.js<|end_filename|> import lock from 'assets/images/icons/lock.png'; export default [ { path: 'home', label: 'Home', }, { path: 'support', label: 'Suporte', }, { path: 'features', label: 'Features', }, { path: 'pricing', label: 'Preços', }, { path: 'testimonials', label: 'Testemunhos', }, ]; <|start_filename|>next.config.js<|end_filename|> const withPlugins = require('next-compose-plugins'); const optimizedImages = require('next-optimized-images'); const nextConfiguration = { future: { webpack5: true }, target: 'serverless', // produzirá páginas independentes que não requerem um servidor monolítico. É compatível apenas com o next start ou plataformas de implantação Serverless (como ZEIT Now) - você não pode usar a API do servidor personalizado. }; module.exports = withPlugins([optimizedImages], nextConfiguration); <|start_filename|>src/components/header/header.js<|end_filename|> /** @jsx jsx */ import { jsx, Box, Container, Flex, Button } from 'theme-ui'; import Sticky from 'react-stickynode'; import { useState } from 'react'; import { DrawerProvider } from 'contexts/drawer/drawer-provider'; import NavbarDrawer from './navbar-drawer'; import Image from 'components/image'; import Logo from 'components/logo'; import { NavLink } from 'components/link'; import menuItems from './header.data'; import lock from 'assets/images/icons/lock.png'; export default function Header() { const [state, setState] = useState({ isMobileMenu: false, isSticky: false, }); const handleCloseMenu = () => { setState({ ...state, isMobileMenu: false, }); }; return ( <DrawerProvider> <Box sx={styles.headerWrapper}> <Sticky enabled={true} top={0} activeClass="is-sticky" innerZ={100}> <Box as="header" variant="layout.header" className={state.isMobileMenu ? 'is-mobile-menu' : ''} > <Container> <Box sx={styles.headerInner}> <Logo sx={styles.logo} isSticky={state.isSticky} /> <Flex as="nav" sx={styles.navbar} className={state.isMobileMenu ? 'navbar active' : 'navbar'} > <Box as="ul" sx={styles.navList} className={state.isMobileMenu ? 'active' : ''} > {menuItems.map(({ path, label }, i) => ( <li key={i}> <NavLink path={path} label={label} onClick={handleCloseMenu} /> </li> ))} </Box> </Flex> <Flex sx={styles.buttonGroup}> <button sx={styles.login}> <Image src={lock} alt="lock icon" /> Login </button> <Button variant="text" sx={styles.getStarted}> Iniciar </Button> </Flex> <NavbarDrawer /> </Box> </Container> </Box> </Sticky> </Box> </DrawerProvider> ); } const styles = { headerWrapper: { backgroundColor: 'transparent', header: { position: 'fixed', left: 0, right: 0, py: [4], transition: 'all 0.3s ease-in-out 0s', '&.is-mobile-menu': { backgroundColor: 'white', }, }, '.is-sticky': { header: { backgroundColor: 'white', py: ['13px'], boxShadow: '0 6px 13px rgba(38,78,118,0.1)', }, }, }, headerInner: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', // position: ['relative', null, null, 'static'], }, logo: { mr: [null, null, null, null, 30, 12], }, navbar: { display: ['none', null, null, null, 'flex'], alignItems: 'center', flexGrow: 1, // justifyContent: 'center', li: { display: 'flex', alignItems: 'center', a: { cursor: 'pointer', transition: 'all 0.3s ease-in-out 0s', }, }, }, navList: { display: ['flex'], listStyle: 'none', flexGrow: 1, p: 0, '.nav-item': { cursor: 'pointer', fontWeight: 400, padding: 0, margin: [null, null, null, null, '0 15px'], }, '.active': { color: 'primary', }, }, getStarted: { backgroundColor: '#FFF0D7', color: '#E6A740', p: ['0 16px'], minHeight: 45, ml: [6], display: ['none', null, null, null, 'flex'], }, login: { backgroundColor: 'transparent', position: ['absolute', null, null, null, 'static'], color: 'text', fontSize: [2], fontWeight: 500, top: '50%', p: 0, transform: ['translateY(-50%)', null, null, null, 'none'], right: 79, border: 0, fontFamily: 'body', display: 'flex', alignItems: 'center', outline: 0, img: { maxWidth: 14, mr: 2, }, }, menuButton: { position: 'relative', right: '-6px', p: 0, }, closeButton: { height: '32px', padding: '0', minHeight: 'auto', width: '32px', position: 'relative', right: '-10px', path: { stroke: 'text', }, }, }; <|start_filename|>src/pages/index.js<|end_filename|> import React from 'react'; import { ThemeProvider } from 'theme-ui'; import theme from 'theme'; import SEO from 'components/seo'; import Layout from 'components/layout'; import Banner from 'sections/banner'; import Support from 'sections/support'; import PremiumFeature from 'sections/premium-feature'; import AppFeature from 'sections/app-feature'; import Dashboard from 'sections/dashboard'; import Pricing from 'sections/pricing'; import Testimonials from 'sections/testimonials'; import Subscribe from 'sections/subscribe'; export default function IndexPage() { return ( <ThemeProvider theme={theme}> <Layout> <SEO title="Startup Agency Alpha Landing" description="Coleção de modelos de landings gratuitos de topo de linha, criados com o react / next js. Gratuito para baixar, basta editar e implantar!" /> <Banner /> <Support /> <PremiumFeature /> <AppFeature /> <Dashboard /> <Pricing /> <Testimonials /> <Subscribe /> </Layout> </ThemeProvider> ); } <|start_filename|>src/components/footer/footer.js<|end_filename|> /** @jsx jsx */ import { jsx, Flex, Box, Text, Container } from 'theme-ui'; import { rgba } from 'polished'; import { Link } from 'components/link'; import Logo from 'components/logo'; const menuItems = [ { path: '#home', label: 'Home', }, { path: '#advertise', label: 'Anunciar', }, { path: '#supports', label: 'Suporte', }, { path: '#marketing', label: 'Marketing', }, { path: '#faq', label: 'FAQ', }, ]; export default function Footer() { return ( <Box as="footer" sx={styles.footer}> <Container> <Flex sx={styles.footerInner}> <Flex sx={styles.copyright}> <Logo isWhite /> <Text as="span"> &copy; Copyright by {new Date().getFullYear()} RedQ, Inc </Text> </Flex> <Flex as="ul" sx={styles.footerNav}> {menuItems?.map((item, index) => ( <li key={index}> <Link path={item?.path}>{item?.label}</Link> </li> ))} </Flex> </Flex> </Container> </Box> ); } const styles = { footer: { backgroundColor: '#2B293E', pt: [6], pb: [6], }, footerInner: { alignItems: 'center', justifyContent: 'space-between', flexDirection: ['column', null, null, null, 'row'], }, copyright: { alignItems: 'center', flexDirection: ['column', null, null, null, 'row'], span: { color: rgba('white', 0.7), fontSize: 1, lineHeight: '18px', ml: [null, null, null, null, 3], mt: [3, null, null, null, 0], }, }, footerNav: { listStyle: 'none', // flexDirection: ['column', null, null, null, 'row'], m: ['25px 0 0', null, null, null, 0], p: 0, li: { '+ li': { ml: [3, null, null, null, 4], }, a: { color: 'white', cursor: 'pointer', textDecoration: 'none', fontSize: [1, null, null, 2], }, }, }, }; <|start_filename|>src/sections/support.js<|end_filename|> /** @jsx jsx */ import { jsx, Container, Grid, Box, Flex, Heading, Text } from 'theme-ui'; import Image from 'components/image'; import support from 'assets/images/support.png'; import rightArrow from 'assets/images/icons/right-arrow.png'; const data = [ { id: 1, icon: support, title: 'Você precisa de ajuda, suporte?', description: `Obtenha seus testes de anúncios de site entregues em vamos coletar amostras da vitória dos serviços de gerenciamento de atualização.`, }, { id: 2, icon: support, title: 'Você precisa de ajuda, suporte?', description: `Obtenha seus testes de anúncios de site entregues em vamos coletar amostras da vitória dos serviços de gerenciamento de atualização.`, }, ]; const Support = () => { return ( <Box as="section" id="support" sx={styles.section}> <Container> <Grid sx={styles.grid}> {data?.map((item) => ( <Flex key={item.id} sx={styles.supportItem}> <Flex as="figure" sx={styles.media}> <Image src={item?.icon} alt={item?.title} /> </Flex> <Box sx={styles.content}> <Heading> {item?.title} <Image src={rightArrow} alt="rightArrow" /> </Heading> <Text as="p">{item?.description}</Text> </Box> </Flex> ))} </Grid> </Container> </Box> ); }; export default Support; const styles = { section: { pt: [9, null, null, 10, 11, 11, 11], pb: [7, null, null, 8, null, 9, 10], }, grid: { gap: ['30px 30px'], justifyContent: 'center', gridTemplateColumns: [ 'repeat(1, 1fr)', null, null, 'repeat(2, 1fr)', null, 'repeat(2, 540px)', ], }, supportItem: { backgroundColor: '#F6F8FB', borderRadius: 7, flexDirection: ['column', null, null, null, null, 'row'], alignItems: 'flex-start', p: ['25px 25px 20px', null, null, null, '35px 30px', '45px 40px 50px'], transition: '0.3s ease-in-out 0s', ':hover': { backgroundColor: 'white', boxShadow: '0px 15px 60px rgba(63, 90, 130, 0.12)', }, }, media: { alignItems: 'center', mr: [6], mb: [5, null, null, null, null, 0], minWidth: [80], img: { maxWidth: [60, null, null, null, null, '100%'], }, }, content: { mt: ['-7px'], h2: { fontWeight: 700, fontSize: [2, null, null, null, 4], lineHeight: 1.5, color: 'textSecondary', display: 'flex', alignItems: 'center', justifyContent: 'space-between', }, p: { fontSize: [1, null, null, null, 15], lineHeight: [2.13], color: 'headingSecondary', mt: [3], }, }, }; <|start_filename|>src/sections/dashboard.js<|end_filename|> /** @jsx jsx */ import { useRef, useEffect, useState } from 'react'; import { rgba } from 'polished';/** @jsx jsx */ import { jsx, Box, Container } from 'theme-ui'; import Tabs, { TabPane } from 'rc-tabs'; import TabTitle from 'components/tabs/tab-title'; import TabContent from 'components/tabs/tab-content'; import Currency from 'components/icons/currency'; import Cog from 'components/icons/cog'; import PieChart from 'components/icons/pie-chart'; import Suitcase from 'components/icons/suitcase'; import BarChart from 'components/icons/bar-chart'; import dashboard from 'assets/images/dashboard.png'; const data = [ { id: 1, tabPane: [ { icon: <Currency />, title: 'Visão geral do orçamento', }, ], tabContent: [ { image: dashboard, title: `Recurso de primeira qualidade que melhora a classificação e o desempenho do seu site`, description: `Construa um local de trabalho incrível e expanda seus negócios com a plataforma tudo-em-um da Gusto com conteúdos incríveis. Faça a entrega de seus testes em let home coletar amostras da vitória do sistema de design de suprimentos.`, readMore: '#introduce-quality', }, ], }, { id: 2, tabPane: [ { icon: <Cog />, title: 'Criar & ajustar', }, ], tabContent: [ { image: dashboard, title: `Recurso de segunda qualidade que melhora a classificação e o desempenho do seu site`, description: `Construa um local de trabalho incrível e expanda seus negócios com a plataforma tudo-em-um da Gusto com conteúdos incríveis. Faça a entrega de seus testes em let home coletar amostras da vitória do sistema de design de suprimentos.`, readMore: '#introduce-quality', }, ], }, { id: 3, tabPane: [ { icon: <PieChart />, title: 'Ver relatórios', }, ], tabContent: [ { image: dashboard, title: `Recurso de terceira qualidade que aumenta a classificação e o desempenho do seu site`, description: `Construa um local de trabalho incrível e expanda seus negócios com a plataforma tudo-em-um da Gusto com conteúdos incríveis. Faça a entrega de seus testes em let home coletar amostras da vitória do sistema de design de suprimentos.`, readMore: '#introduce-quality', }, ], }, { id: 4, tabPane: [ { icon: <Suitcase />, title: 'Otimize o site', }, ], tabContent: [ { image: dashboard, title: `Recurso de quarta qualidade que melhora a classificação e o desempenho do seu site`, description: `Construa um local de trabalho incrível e expanda seus negócios com a plataforma tudo-em-um da Gusto com conteúdos incríveis. Faça a entrega de seus testes em let home coletar amostras da vitória do sistema de design de suprimentos.`, readMore: '#introduce-quality', }, ], }, { id: 5, tabPane: [ { icon: <BarChart />, title: 'Painel Personalizado', }, ], tabContent: [ { image: dashboard, title: `Quinto recurso de qualidade que melhora a classificação e o desempenho do seu site`, description: `Construa um local de trabalho incrível e expanda seus negócios com a plataforma tudo-em-um da Gusto com conteúdos incríveis. Faça a entrega de seus testes em let home coletar amostras da vitória do sistema de design de suprimentos.`, readMore: '#introduce-quality', }, ], }, ]; const Dashboard = () => { const containerRef = useRef(); const [containerOffset, setContainerOffset] = useState({ left: null, top: null, }); useEffect(() => { setContainerOffset({ left: containerRef.current.offsetLeft, top: containerRef.current.offsetTop, }); }, [containerRef]); return ( <Box as="section" sx={styles.section}> <Container ref={containerRef} /> <Box sx={{ pl: containerOffset.left + 30, ...styles.container }}> <Tabs sx={styles.tabs} animated={{ tabPane: true }} defaultActiveKey="2" > {data?.map((tab) => ( <TabPane key={tab?.id} tab={<TabTitle tab={tab.tabPane} />}> <TabContent tabContent={tab?.tabContent} /> </TabPane> ))} </Tabs> </Box> </Box> ); }; export default Dashboard; const styles = { section: { backgroundColor: '#353448', pt: [9, null, null, 11, 10, 12, null], pb: [9, null, null, null, 0], }, container: { maxWidth: ['none !important'], pr: [6, null, null, 0], }, tabs: { border: 0, color: 'white', '.rc-tabs-nav': { mb: [8, null, null, 7, 10, null, 12], }, '.rc-tabs-nav-wrap': { '::before': { backgroundColor: rgba('#fff', 0.1), content: ['none', null, null, `''`], height: 1, position: 'absolute', left: 0, top: 51, width: '100%', }, '::after': { borderColor: ['primary'], }, }, '.rc-tabs-nav-list': { display: ['flex'], }, '.rc-tabs-tab': { backgroundColor: 'transparent', '+ .rc-tabs-tab': { ml: [5, null, null, 5, 8, 12], // mt: [0, null, null, 0], }, 'svg g, svg path': { transition: '0.3s ease-in-out 0s', }, }, '.rc-tabs-tab-btn': { alignItems: 'center', display: ['flex', null, null, 'block'], outline: '0 none', fontSize: [null, null, null, 15, 2], }, '.rc-tabs-tab-active': { 'svg g, svg path': { fill: 'primary', opacity: 1, }, h5: { color: 'primary', }, }, '.rc-tabs-ink-bar': { backgroundColor: 'primary', borderRadius: 5, bottom: [47], display: ['none', null, null, 'block'], }, '.rc-tabs-tabpane': { outline: '0 none', }, }, }; <|start_filename|>repo.config.json<|end_filename|> { "project_name": "Agency Alpha Landing Page", "type": "landing-page", "template_url": "./public/cover.png", "logo_url": "./src/assets/images/logo.png", "web": "./" } <|start_filename|>src/components/subscription-form.js<|end_filename|> /** @jsx jsx */ import { jsx, Flex, Input, Button, Label } from 'theme-ui'; import { useState, useEffect } from 'react'; const SubscriptionForm = ({ buttonLabel, ...props }) => { const [id, setId] = useState(''); useEffect(() => { setId(Date.now()); }, []); return ( <Flex as="form" sx={styles.form} {...props}> <Label htmlFor={`email-${id}`} variant="styles.srOnly"> Email </Label> <Input type="email" id={`email-${id}`} placeholder="Insira o Endereço de Email" /> <Button>{buttonLabel ?? 'Iniciar'}</Button> </Flex> ); }; export default SubscriptionForm; const styles = { form: { input: { flexGrow: 1, p: ['0 20px', null, null, null, '0 25px'], minHeight: [60], height: 'auto', width: 'auto', }, button: { ml: [3], }, }, };
solrachix/landing-page-template_4
<|start_filename|>examples/miningTools.js<|end_filename|> /** * This example will trigger the bot to equip the best tool for mining the target block. */ if (process.argv.length < 4 || process.argv.length > 6) { console.log('Usage : node miningTools.js <host> <port> [<name>] [<password>]') process.exit(1) } // Load libraries const mineflayer = require('mineflayer') const toolPlugin = require('mineflayer-tool').plugin // Create the bot const bot = mineflayer.createBot({ host: process.argv[2], port: process.argv[3], username: process.argv[4] || 'MiningTool_Bot', password: process.argv[5] }) // Load the tool plugin bot.loadPlugin(toolPlugin) // Listen for chat events bot.on('chat', async (username, message) => { // Only listen for when someone says 'get tool' if (message !== 'get tool') return // Get the player who said it const player = bot.players[username] // Print an error in chat if the bot can't see the player if (!player) { bot.chat("I can't see you!") return } // Get the block below the player const blockPos = player.entity.position.offset(0, -1, 0) const block = bot.blockAt(blockPos) // Let the player know it's working bot.chat(`Getting best tool for ${block.name}`) // Equip the best tool for mining that block bot.tool.equipForBlock(block) // You can also specify other options and use await /* const mcData = require('minecraft-data')(bot.version) bot.tool.chestLocations = bot.findBlocks({ matching: mcData.blocksByName.chest.id, maxDistance: 16, count: 999 }) try { await bot.tool.equipForBlock(block, { requireHarvest: true, getFromChest: true }) await bot.dig(block) } catch (err) { console.log(err) } */ })
PrismarineJS/mineflayer-tool
<|start_filename|>api/error.go<|end_filename|> package api import ( "github.com/pkg/errors" ) type ( Error struct { Err error StatusCode int Message string } ) func (e *Error) Error() string { return e.Message } func NewError(err error, message string, status int) *Error { return &Error{ Err: err, Message: message, StatusCode: status, } } func NewErrorWrap(err error, prefix, suffix, message string, status int) *Error { return &Error{ Err: errors.Wrapf(err, "%s/%s", prefix, suffix), Message: message, StatusCode: status, } }
renosyah/AyoLesPortal
<|start_filename|>test/fixtures/extend-symbol/app/extend/application.js<|end_filename|> 'use strict'; const symbol = require('../../../../utils').symbol; module.exports = { get [symbol.view]() { return 'view'; }, }; <|start_filename|>test/fixtures/plugin/app/proxy/UserInfoQuery.js<|end_filename|> 'use strict'; module.exports = function(app) { class UserInfoQuery extends app.Proxy { constructor(ctx) { super(ctx); } * query() { return { foo: 'bar', }; } } return UserInfoQuery; }; <|start_filename|>test/fixtures/framework-symbol/node_modules/framework2/index.js<|end_filename|> 'use strict'; const EggApplication = require('../../../egg').Application; class Framework2 extends EggApplication { get [Symbol.for('egg#eggPath')]() { return __dirname; } } module.exports = Framework2; <|start_filename|>test/fixtures/extend/node_modules/a/app/extend/context.js<|end_filename|> 'use strict'; module.exports = { pluginaContext: 'plugin a context', }; <|start_filename|>test/fixtures/dont-load-plugin/config/plugin.js<|end_filename|> const path = require('path'); exports.testMe = { enable: true, env: ['local'], path: path.join(__dirname, '../../../plugins/test-me') }; exports.testMeAli = { enable: true, path: path.join(__dirname, '../../../plugins/test-me-ali') }; <|start_filename|>test/fixtures/controller-app/app/controller/number.js<|end_filename|> 'use strict'; module.exports = 123; <|start_filename|>test/fixtures/load-plugin-unittest/app/extend/application.unittest.js<|end_filename|> 'use strict'; module.exports = { unittest: true, }; <|start_filename|>test/fixtures/no-dep-plugin/config/plugin.js<|end_filename|> 'use strict'; const path = require('path'); module.exports = { customA: { enable: true, path: path.join(__dirname, '../plugins/a'), }, customB: { enable: false, package: '@ali/b', }, }; <|start_filename|>test/fixtures/context-loader/app/pathname/a/b/c.js<|end_filename|> 'use strict'; module.exports = app => { return class xxx extends app.BaseContextClass { * getPathname() { return this.pathName; } * getName() { return this.config.name; } }; }; <|start_filename|>test/fixtures/load_dirs/inject/a.js<|end_filename|> 'use strict'; module.exports = class A { constructor(inject) { inject.a = true; } }; <|start_filename|>test/loader/mixin/load_custom_agent.test.js<|end_filename|> 'use strict'; const assert = require('assert'); const utils = require('../../utils'); describe('test/loader/mixin/load_custom_agent.test.js', function() { let agent; before(function() { agent = utils.createApp('plugin'); agent.loader.loadPlugin(); agent.loader.loadConfig(); agent.loader.loadCustomAgent(); }); after(() => agent.close()); it('should load agent.js', function() { assert(agent.b === 'plugin b'); assert(agent.c === 'plugin c'); assert(agent.agent === 'agent'); }); it('should agent.js of plugin before application\'s', function() { assert(agent.dateB <= agent.date); assert(agent.dateC <= agent.date); }); it('should not load plugin that is disabled', function() { assert(!agent.a); }); }); <|start_filename|>test/loader/get_appname.test.js<|end_filename|> 'use strict'; const mm = require('mm'); const assert = require('assert'); const utils = require('../utils'); describe('test/loader/get_appname.test.js', () => { let app; afterEach(mm.restore); afterEach(() => app && app.close()); it('should get appname', () => { app = utils.createApp('appname'); assert(app.loader.getAppname() === 'appname'); }); it('should throw when appname is not found', done => { const pkg = utils.getFilepath('app-noname/package.json'); try { utils.createApp('app-noname'); } catch (err) { assert(err.message.includes(`name is required from ${pkg}`)); done(); } }); }); <|start_filename|>test/fixtures/config-env/config/config.default.js<|end_filename|> 'use strict'; module.exports = { egg: 'config-default', }; <|start_filename|>test/fixtures/context-loader/app/router.js<|end_filename|> 'use strict'; module.exports = app => { app.get('/depth', function*() { this.body = { one: this.depth.one.get(), two: this.depth.two.two.get(), three: this.depth.three.three.three.get(), four: this.depth.four.four.four.four.get(), } }); app.get('/type', function*() { this.body = { class: this.type.class.get(), functionClass: this.type.functionClass.get(), object: this.type.object.get(), generator: yield this.type.generator(), null: this.type.null, number: this.type.number, }; }); app.get('/service', function* () { this.body = { service1: this.service1.user.userInfo, service2: this.service2.user.userInfo, }; }); app.get('/pathname', function* () { this.body = yield this.pathname.a.b.c.getPathname(); }); app.get('/config', function* () { this.body = yield this.pathname.a.b.c.getName(); }); app.get('/BaseContextClass/service', function*() { this.body = this.service.user.info; }) }; <|start_filename|>test/utils/router.test.js<|end_filename|> 'use strict'; const assert = require('assert'); const request = require('supertest'); const utils = require('../utils'); describe('test/utils/router.test.js', () => { let app; before(() => { app = utils.createApp('router-app'); app.loader.loadAll(); return app.ready(); }); after(() => app.close()); describe('router.resources', () => { describe('normal', () => { it('should GET /posts', () => { return request(app.callback()) .get('/posts') .expect(200) .expect('index'); }); it('should GET /posts/new', () => { return request(app.callback()) .get('/posts/new') .expect(200) .expect('new'); }); it('should POST /posts', () => { return request(app.callback()) .post('/posts') .expect(200) .expect('create'); }); it('should GET /posts/:id', () => { return request(app.callback()) .get('/posts/123') .expect(200) .expect('show - 123'); }); it('should GET /posts/:id/edit', () => { return request(app.callback()) .get('/posts/123/edit') .expect(200) .expect('edit - 123'); }); it('should PATCH /posts/:id', () => { return request(app.callback()) .patch('/posts/123') .expect(200) .expect('update - 123'); }); it('should PUT /posts/:id', () => { return request(app.callback()) .put('/posts/123') .expect(200) .expect('update - 123'); }); it('should DELETE /posts/:id', () => { return request(app.callback()) .delete('/posts/123') .expect(200) .expect('destroy - 123'); }); }); describe('controller url', () => { it('should GET /members', () => { return request(app.callback()) .get('/members') .expect(200) .expect('index'); }); it('should GET /members/index', () => { return request(app.callback()) .get('/members/index') .expect(200) .expect('index'); }); it('should GET /members/new', () => { return request(app.callback()) .get('/members/new') .expect(200) .expect('new'); }); it('should GET /members/:id', () => { return request(app.callback()) .get('/members/1231') .expect(200) .expect('show - 1231'); }); it('should POST /members', () => { return request(app.callback()) .post('/members') .expect(404); }); it('should PUT /members/:id', () => { return request(app.callback()) .put('/members/1231') .expect(404); }); it('should GET /POSTS', () => { return request(app.callback()) .get('/POSTS') .expect(404); }); it('should GET /members/delete/:id', () => { return request(app.callback()) .delete('/members/delete/1') .expect(200) .expect('delete - 1'); }); it('should GET /members/del/:id', () => { return request(app.callback()) .del('/members/del/1') .expect(200) .expect('delete - 1'); }); it('should GET /packages/(.*)', () => { return request(app.callback()) .get('/packages/urllib') .expect('urllib'); }); }); describe('no name', function() { it('should GET /comments', () => { return request(app.callback()) .get('/comments') .expect('index') .expect(200); }); it('should POST /comments', () => { return request(app.callback()) .post('/comments') .expect('new') .expect(200); }); }); describe('async controller', () => { it('should execute by the correct order', () => { return request(app.callback()) .get('/mix') .expect([ 'generator before', 'async', 'generator after' ]) .expect(200); }); }); }); describe('router.url', () => { it('should work', () => { assert(app.url('posts') === '/posts'); assert(app.router.url('posts') === '/posts'); assert(app.router.url('members') === '/members'); assert(app.router.url('post', { id: 1 }) === '/posts/1'); assert(app.router.url('member', { id: 1 }) === '/members/1'); assert(app.router.url('new_post') === '/posts/new'); assert(app.router.url('new_member') === '/members/new'); assert(app.router.url('edit_post', { id: 1 }) === '/posts/1/edit'); assert(app.router.url('params', { a: 1, b: 2 }) === '/params/1/2'); // no match params assert(app.router.url('edit_post', {}) === '/posts/:id/edit'); assert(app.router.url('noname') === ''); assert(app.router.url('comment_index', { id: 1, a: 1 }) === '/comments/1?filter=&a=1'); }); it('should work with unknow params', () => { assert(app.router.url('posts', { name: 'foo', page: 2 }) === '/posts?name=foo&page=2'); assert(app.router.url('posts', { name: 'foo&?', page: 2 }) === '/posts?name=foo%26%3F&page=2'); assert(app.router.url('edit_post', { id: 10, page: 2 }) === '/posts/10/edit?page=2'); assert(app.router.url('edit_post', { i: 2, id: 10 }) === '/posts/10/edit?i=2'); assert(app.router.url('edit_post', { id: 10, page: 2, tags: [ 'chair', 'develop' ] }) === '/posts/10/edit?page=2&tags=chair&tags=develop'); assert(app.router.url('edit_post', { id: [ 10 ], page: [ 2 ], tags: [ 'chair', 'develop' ] }) === '/posts/10/edit?page=2&tags=chair&tags=develop'); assert(app.router.url('edit_post', { id: [ 10, 11 ], page: [ 2 ], tags: [ 'chair', 'develop' ] }) === '/posts/10/edit?page=2&tags=chair&tags=develop'); }); it('should not support regular url', () => { assert.throws(() => { app.router.url('packages', [ 'urllib' ]); }, 'Can\'t get the url for regExp /^\/packages\/(.*)/ for by name \'posts\''); }); }); describe('router.pathFor', () => { it('should work', () => { assert(app.router.pathFor('posts') === '/posts'); }); }); describe('router.method', () => { it('router method include HEAD', () => { assert(app.router.methods.includes('HEAD')); }); }); describe('router middleware', () => { it('should support all kinds of middlewares', () => { return request(app.callback()) .get('/middleware') .expect(200) .expect([ 'generator', 'async', 'common' ]); }); it('should support all kinds of middlewares with name', () => { return request(app.callback()) .get('/named_middleware') .expect(200) .expect([ 'generator', 'async', 'common' ]); }); it('should support all kinds of middlewares with register', () => { return request(app.callback()) .get('/register_middleware') .expect(200) .expect([ 'generator', 'async', 'common' ]); }); it('should app.router support all kinds of middlewares', () => { return request(app.callback()) .get('/router_middleware') .expect(200) .expect([ 'generator', 'async', 'common' ]); }); }); describe('redirect', () => { it('should app.redirect to target', () => { return request(app.callback()) .get('/redirect') .expect(302) .expect('location', '/middleware'); }); it('should app.router.redirect to target', () => { return request(app.callback()) .get('/router_redirect') .expect(301) .expect('location', '/middleware'); }); }); describe('controller mutli url', () => { it('should GET /url1', () => { return request(app.callback()) .get('/url1') .expect(200) .expect('index'); }); it('should GET /url2', () => { return request(app.callback()) .get('/url2') .expect(200) .expect('index'); }); it('use middlewares /urlm1', () => { return request(app.callback()) .get('/urlm1') .expect(200) .expect([ 'generator', 'async', 'common' ]); }); it('use middlewares /urlm2', () => { return request(app.callback()) .get('/urlm2') .expect(200) .expect([ 'generator', 'async', 'common' ]); }); }); describe('controller not exist', () => { it('should check when app.router.VERB', () => { try { app.router.get('/test', app.controller.not_exist); throw new Error('should not run here'); } catch (err) { assert(err.message.includes('controller not exists')); } }); it('should check when app.router.VERB with controller string', () => { try { app.get('/hello', 'not.exist.controller'); throw new Error('should not run here'); } catch (err) { assert(err.message.includes('controller \'not.exist.controller\' not exists')); } }); it('should check when app.router.resources', () => { try { app.router.resources('/test', app.controller.not_exist); throw new Error('should not run here'); } catch (err) { assert(err.message.includes('controller not exists')); } }); it('should check when app.router.resources with controller string', () => { try { app.router.resources('/test', 'not.exist.controller'); throw new Error('should not run here'); } catch (err) { assert(err.message.includes('controller \'not.exist.controller\' not exists')); } }); }); describe('router middleware', () => { before(() => { app = utils.createApp('router-in-app'); app.loader.loadAll(); return app.ready(); }); it('should always load router middleware at last', () => { return request(app.callback()) .get('/') .expect(200) .expect('foo'); }); }); }); <|start_filename|>test/fixtures/context-loader/app/type/function-class.js<|end_filename|> 'use strict'; module.exports = app => ( class Service { constructor(ctx) { this.ctx = ctx; } get() { return this.ctx.name + ':' + app.config.name; } } ); <|start_filename|>test/fixtures/extend/app/extend/response.js<|end_filename|> 'use strict'; module.exports = { appResponse: 'app response', overridePlugin: 'will override plugin', set status(code) { this._explicitStatus = true; this.res.statusCode = code; this.res.statusMessage = 'http status code ' + code; }, get etag() { return 'etag ok'; }, }; <|start_filename|>test/loader/mixin/load_agent_extend.test.js<|end_filename|> 'use strict'; const assert = require('assert'); const utils = require('../../utils'); describe('test/loader/mixin/load_agent_extend.test.js', function() { let agent; before(function() { agent = utils.createApp('agent'); agent.loader.loadPlugin(); agent.loader.loadConfig(); agent.loader.loadAgentExtend(); }); after(() => agent.close()); it('should load extend from chair, plugin and agent', function() { assert(agent.poweredBy); assert(agent.a); assert(agent.b); assert(agent.foo); assert(agent.bar); }); it('should override chair by plugin', function() { assert(agent.a === 'plugin a'); assert(agent.b === 'plugin b'); assert(agent.poweredBy === 'plugin a'); }); it('should override plugin by agent', function() { assert(agent.foo === 'agent bar'); assert(agent.bar === 'foo'); }); }); <|start_filename|>test/loader/get_load_units.test.js<|end_filename|> 'use strict'; const mm = require('mm'); const assert = require('assert'); const utils = require('../utils'); describe('test/get_load_units.test.js', function() { let app; afterEach(mm.restore); afterEach(() => app.close()); it('should get plugin dir', function() { app = utils.createApp('plugin'); app.loader.loadPlugin(); // delete cache delete app.loader.dirs; const units = app.loader.getLoadUnits(); assert(units.length === 12); assert(units[10].type === 'framework'); assert(units[10].path === utils.getFilepath('egg')); assert(units[11].type === 'app'); assert(units[11].path === utils.getFilepath('plugin')); }); it('should not get plugin dir', function() { app = utils.createApp('plugin'); const units = app.loader.getLoadUnits(); assert(units.length === 2); }); }); <|start_filename|>test/fixtures/configmeta/config/config.js<|end_filename|> 'use strict'; const HttpClient2 = require('urllib').HttpClient2; const urllib = new HttpClient2(); exports.urllib = { keepAlive: false, foo: null, bar: undefined, n: 1, dd: new Date(), httpclient: urllib, }; exports.buffer = new Buffer('1234'); exports.array = []; exports.console = console; exports.zero = 0; exports.number = 1; exports.ok = true; exports.f = false; exports.no = null; exports.empty = {}; exports.date = new Date(); exports.ooooo = urllib; <|start_filename|>test/fixtures/extends-app-service/app/router.js<|end_filename|> module.exports = function (app) { app.get('/user', app.controller.user); }; <|start_filename|>test/fixtures/timing/block.js<|end_filename|> 'use strict'; module.exports = () => { const start = Date.now(); while (Date.now() - start < 1000) {} }; <|start_filename|>test/fixtures/extend/app/extend/request.js<|end_filename|> 'use strict'; module.exports = { appRequest: 'app request', }; <|start_filename|>test/fixtures/plugin-from/config/plugin.js<|end_filename|> 'use strict'; exports.a = true; <|start_filename|>test/fixtures/router-in-app/config/config.default.js<|end_filename|> 'use strict'; exports.middleware = [ 'foo' ]; <|start_filename|>test/fixtures/router-app/app/controller/package.js<|end_filename|> 'use strict'; exports.get = function* () { this.body = this.params[0]; }; <|start_filename|>test/fixtures/extend-controller-service/app/controller/api.js<|end_filename|> 'use strict'; module.exports = app => { return class ApiController extends app.Controller { * successAction() { const res = yield this.service.api.get(); this.success({ foo: res }); } * failAction() { this.fail('something wrong'); } }; }; <|start_filename|>test/fixtures/controller-app/app/controller/resource_object.js<|end_filename|> 'use strict'; exports.index = function* () { this.body = 'index'; }; exports.create = async ctx => { ctx.body = 'create'; }; <|start_filename|>test/fixtures/timing/config/plugin.js<|end_filename|> 'use strict'; require('../block')(); <|start_filename|>test/fixtures/router-app/app/middleware/common.js<|end_filename|> 'use strict'; module.exports = function() { return function(ctx, next) { return next().then(() => { ctx.body.push('common'); }); }; }; <|start_filename|>test/fixtures/load_dirs/inject/b.js<|end_filename|> 'use strict'; module.exports = inject => { inject.b = true; return {}; }; <|start_filename|>test/fixtures/middleware-redefined/config/config.js<|end_filename|> exports.middleware = [ 'status' ]; <|start_filename|>test/fixtures/plugin/plugin-proxy/config/config.default.js<|end_filename|> exports.proxy = {}; <|start_filename|>benchmark/middleware/app/middleware/generator.js<|end_filename|> 'use strict'; let index = 0; module.exports = function () { return function* (next) { yield next; this.body.push(`generator middleware #${++index}`); }; }; <|start_filename|>test/fixtures/env-disable/config/plugin.js<|end_filename|> 'use strict'; module.exports = { a: { enable: true, package: '@ali/a', }, b: { enable: true, package: '@ali/b', }, }; <|start_filename|>test/fixtures/helper/node_modules/b/app/extend/helper.js<|end_filename|> exports.b = function(){ return 'plugin b'; } exports.override = function() { return 'plugin b'; }; <|start_filename|>test/fixtures/timing/preload.js<|end_filename|> 'use strict'; process.scriptStartTime = Date.now(); <|start_filename|>test/fixtures/egg/config/config.unittest.js<|end_filename|> 'use strict'; module.exports = { egg: 'egg-unittest', }; <|start_filename|>test/fixtures/extend/node_modules/a/app/extend/request.js<|end_filename|> 'use strict'; module.exports = { pluginaRequest: 'plugin a request', }; <|start_filename|>test/fixtures/framework-symbol/index.js<|end_filename|> 'use strict'; const Application = require('framework2'); class Framework extends Application { constructor(options) { super(options); } get [Symbol.for('egg#eggPath')]() { return __dirname; } } module.exports = Framework; <|start_filename|>test/fixtures/config/app/services/foo.js<|end_filename|> 'use strict'; var util = require('./util/bar'); module.exports = function() { return { bar: function*(ctx) { console.log(ctx); } }; }; <|start_filename|>test/fixtures/plugin/config/config.js<|end_filename|> exports.plugin = 'override plugin'; exports.middleware = []; <|start_filename|>test/fixtures/config-array/plugin/b/config/config.default.js<|end_filename|> 'use strict'; exports.array = [ 1, 2 ]; <|start_filename|>test/fixtures/extend/app/extend/call.js<|end_filename|> 'use strict'; module.exports = app => { return { call: true, }; }; <|start_filename|>test/fixtures/extend/node_modules/b/app/extend/context/index.js<|end_filename|> 'use strict'; module.exports = { pluginbContext: 'plugin b context', }; <|start_filename|>test/fixtures/controller-app/app/controller/class.js<|end_filename|> 'use strict'; module.exports = class HomeController { constructor(ctx) { this.ctx = ctx; } callFunction() { this.ctx.body = 'done'; } * callGeneratorFunction() { this.ctx.body = yield this.ctx.service.home.info(); } * callGeneratorFunctionWithArg(ctx) { ctx.body = yield ctx.service.home.info(); } async callAsyncFunction() { this.ctx.body = await this.ctx.service.home.info(); } async callAsyncFunctionWithArg(ctx) { ctx.body = await ctx.service.home.info(); } // won't be loaded get nofunction() { return 'done'; } get request() { return this.ctx.request; } set body(val) { this.ctx.body = val; } }; <|start_filename|>test/fixtures/boot-before-close/app.js<|end_filename|> 'use strict'; module.exports = class BootHook { constructor(app) { this.app = app; this.app.bootLog = this.app.bootLog || []; } async beforeClose() { this.app.bootLog.push('beforeClose in app'); } }; <|start_filename|>test/fixtures/extend/node_modules/a/app/extend/response.js<|end_filename|> 'use strict'; module.exports = { pluginaResponse: 'plugin a response', }; <|start_filename|>test/fixtures/custom-loader/app/adapter/docker.js<|end_filename|> 'use strict'; class DockerAdapter { constructor(app) { this.app = app; } async inspectDocker() { return this.app.config.customLoader.adapter; } } module.exports = DockerAdapter; <|start_filename|>test/utils/timing.test.js<|end_filename|> 'use strict'; const assert = require('assert'); const Timing = require('../../lib/utils/timing'); describe('test/utils/timing.test.js', () => { it('should trace', () => { const timing = new Timing(); timing.start('a'); timing.end('a'); timing.start('b'); timing.end('b'); const json = timing.toJSON(); assert(json.length === 3); assert(json[1].name === 'a'); assert(json[1].end - json[1].start === json[1].duration); assert(json[1].pid === process.pid); assert(json[2].name === 'b'); assert(json[2].end - json[2].start === json[2].duration); assert(json[2].pid === process.pid); }); it('should set item when start', () => { const timing = new Timing(); timing.start('a'); const json = timing.toJSON(); assert(json[1].name === 'a'); assert(json[1].start); assert(json[1].end === undefined); assert(json[1].duration === undefined); }); it('should ignore start when name is empty', () => { const timing = new Timing(); timing.start(); const json = timing.toJSON(); assert(json.length === 1); }); it('should throw when name exists', () => { const timing = new Timing(); timing.start('a'); assert(timing.toJSON().length === 2); timing.start('a'); assert(timing.toJSON().length === 3); }); it('should ignore end when name dont exist', () => { const timing = new Timing(); timing.end(); assert(timing.toJSON().length === 1); }); it('should enable/disable', () => { const timing = new Timing(); timing.start('a'); timing.end('a'); timing.disable(); timing.start('b'); timing.end('b'); timing.enable(); timing.start('c'); timing.end('c'); const json = timing.toJSON(); assert(json[1].name === 'a'); assert(json[2].name === 'c'); assert(json.length === 3); }); it('should clear', () => { const timing = new Timing(); timing.start('a'); timing.end('a'); const json = timing.toJSON(); assert(json[1].name === 'a'); timing.clear(); timing.start('b'); timing.end('b'); const json2 = timing.toJSON(); assert(json2[0].name === 'b'); assert(json2.length === 1); }); it('should throw when end and name dont exists', () => { const timing = new Timing(); assert.throws(() => { timing.end('a'); }, /should run timing.start\('a'\) first/); }); it('should init process start time', () => { const timing = new Timing(); const processStart = timing.toJSON().find(item => item.name === 'Process Start'); assert(processStart); assert(processStart.start); assert(processStart.end); }); }); <|start_filename|>test/fixtures/helper/config/plugin.js<|end_filename|> exports.a = false; exports.b = true; <|start_filename|>test/fixtures/ready/app.js<|end_filename|> 'use strict'; module.exports = app => { setTimeout(app.readyCallback('a'), 100); setTimeout(app.readyCallback('b'), 500); }; <|start_filename|>test/fixtures/application/node_modules/b/app/extend/application.js<|end_filename|> 'use strict'; module.exports = { b: 'plugin b', foo: 'bar plugin b' }; <|start_filename|>test/fixtures/extend/node_modules/a/app/extend/application.js<|end_filename|> 'use strict'; module.exports = { pluginaApplication: 'plugin a application', }; <|start_filename|>test/fixtures/extend/app/extend/application.js<|end_filename|> 'use strict'; module.exports = { get appApplication() { return 'app application'; }, }; <|start_filename|>test/fixtures/realpath/config/plugin.js<|end_filename|> 'use strict'; exports.a = { enable: true, pacakge: 'b', }; <|start_filename|>test/fixtures/timing/app.js<|end_filename|> 'use strict'; const path = require('path'); const block = require('./block'); module.exports = app => { block(); app.beforeStart(function* () { block(); }) const directory = path.join(app.baseDir, 'app/proxy'); app.loader.loadToContext(directory, 'proxy'); app.loader.loadController(); }; <|start_filename|>test/fixtures/egg/config/plugin.js<|end_filename|> 'use strict'; const path = require('path'); module.exports = { session: { enable: true, path: path.join(__dirname, '../node_modules/session'), }, hsfclient: { enable: false, path: path.join(__dirname, '../plugins/hsfclient'), }, configclient: { enable: false, path: path.join(__dirname, '../plugins/configclient'), }, eagleeye: { enable: false, path: path.join(__dirname, '../plugins/eagleeye'), }, diamond: { enable: false, path: path.join(__dirname, '../plugins/diamond'), }, zzz: { enable: true, path: path.join(__dirname, '../plugins/zzz'), }, package: { enable: true, package: 'package', }, opt: { enable: false, package: 'opt', }, }; <|start_filename|>test/fixtures/noplugin/config/plugin.js<|end_filename|> 'use strict'; module.exports = { session: false, zzz: false, package: false, }; <|start_filename|>test/fixtures/router-in-app/app/middleware/foo.js<|end_filename|> 'use strict'; module.exports = () => { return (ctx, next) => { ctx.foo = 'foo'; return next(); }; }; <|start_filename|>test/fixtures/middleware-aa/app.js<|end_filename|> 'use strict'; module.exports = app => { app.use(require('./app/middleware/custom')()); }; <|start_filename|>test/fixtures/context-loader/app/extend/context.js<|end_filename|> 'use strict'; module.exports = { name: 'context', }; <|start_filename|>test/fixtures/scope/config/plugin.js<|end_filename|> 'use strict'; module.exports = { a: { enable: true, package: 'a', }, }; <|start_filename|>test/fixtures/context-loader/app/service/post.js<|end_filename|> 'use strict'; module.exports = app => class UserService1 extends app.Service { get postInfo() { return 'post'; } }; <|start_filename|>test/fixtures/plugin-path-package/config/plugin.js<|end_filename|> 'use strict'; const path = require('path'); module.exports = { session: { path: path.join(__dirname, '../session'), }, hsfclient: { package: 'hsfclient', }, }; <|start_filename|>test/fixtures/plugin/app/router.js<|end_filename|> 'use strict'; module.exports = function(app) { app.get('/', function*() { const foo2 = yield this.service.foo2(); const foo3 = yield this.service.foo3.foo3(); this.body = { foo2: foo2, foo3: foo3, foo4: !!this.service.foo4, foo5: !!this.service.fooDir.foo5, foo: !!this.service.foo, bar2: !!this.service.bar2, }; }); app.get('/proxy', function*() { this.body = { coupon: yield this.proxy.couponQuery.query(), userInfo: yield this.proxy.userInfoQuery.query(), onlyClass: yield this.proxy.onlyClassQuery.query(), }; }); }; <|start_filename|>test/fixtures/custom-loader/config/config.default.js<|end_filename|> 'use strict'; module.exports = { pkgName: 'custom_loader', customLoader: { adapter: { directory: 'app/adapter', inject: 'app', }, util: { directory: 'app/util', inject: 'app', }, repository: { directory: 'app/repository', inject: 'ctx', }, plugin: { directory: 'app/plugin', inject: 'app', loadunit: true, }, }, }; <|start_filename|>test/loader/mixin/load_application_extend.test.js<|end_filename|> 'use strict'; const assert = require('assert'); const utils = require('../../utils'); describe('test/loader/mixin/load_application_extend.test.js', function() { let app; before(function() { app = utils.createApp('application'); app.loader.loadPlugin(); app.loader.loadConfig(); app.loader.loadApplicationExtend(); }); after(() => app.close()); it('should load extend from chair, plugin and application', function() { assert(app.poweredBy); assert(app.a); assert(app.b); assert(app.foo); assert(app.bar); }); it('should override chair by plugin', function() { assert(app.a === 'plugin a'); assert(app.b === 'plugin b'); assert(app.poweredBy === 'plugin a'); }); it('should override plugin by app', function() { assert(app.foo === 'app bar'); assert(app.bar === 'foo'); }); }); <|start_filename|>test/fixtures/boot/app/plugin/boot-plugin-empty/app.js<|end_filename|> 'use strict'; module.exports = 'not function'; <|start_filename|>test/fixtures/controller-params/app/controller/class.js<|end_filename|> 'use strict'; module.exports = class HomeController { constructor(ctx) { this.ctx = ctx; } * generatorFunction(...args) { this.ctx.body = 'done'; return args; } async asyncFunction(...args) { this.ctx.body = 'done'; return args; } }; <|start_filename|>test/fixtures/extend/node_modules/b/app/extend/request.js<|end_filename|> 'use strict'; module.exports = { pluginbRequest: 'plugin b request', get pluginb() { return 'pluginb'; }, get ip() { return '0.0.0.0'; }, set ip(_) { }, }; <|start_filename|>test/fixtures/services_loader_verify/app/service/foo.js<|end_filename|> 'use strict'; module.exports = function() { return { *bar(ctx) { console.log(ctx); }, * bar1(ctx) { console.log(ctx); }, aa: function*(ctx) { console.log(ctx); } }; }; <|start_filename|>test/fixtures/config/app/controller/foo.js<|end_filename|> 'use strict'; var util = require('./util/a'); module.exports = function() { return { a: function*() { util.b(); this.body = 'hello'; } }; }; <|start_filename|>test/fixtures/boot/app/plugin/boot-plugin/app.js<|end_filename|> 'use strict'; const sleep = require('mz-modules/sleep'); const assert = require('assert'); module.exports = app => { app.bootLog.push('app.js in plugin'); // make sure app.js change app.config.appSet = true on configWillLoad assert(app.config.appSet === true); app.beforeStart(async () => { await sleep(5); app.bootLog.push('beforeStart'); }); app.ready(()=> { app.bootLog.push('ready'); }); }; <|start_filename|>test/fixtures/beforestart-with-timeout-env/app.js<|end_filename|> 'use strict'; const sleep = require('ko-sleep'); module.exports = function (app) { app.beforeStart(function* () { yield sleep(11000); app.beforeStartFunction = true; }); app.beforeStartFunction = false; }; <|start_filename|>test/fixtures/middleware-redefined/app/middleware/custom.js<|end_filename|> 'use strict'; module.exports = function() { return function* appCustom() { this.body = 'app custom'; }; }; <|start_filename|>test/fixtures/preload-app-config/a/config/config.js<|end_filename|> 'use strict'; module.exports = function(antx, appConfig) { appConfig.app.sub.val = 2; return { plugin: { sub: appConfig.app.sub, val: appConfig.app.val, }, } }; <|start_filename|>test/fixtures/other-directory/app/other-service/user.js<|end_filename|> 'use strict'; module.exports = app => { return class UserService extends app.Service {}; }; <|start_filename|>test/fixtures/router-app/app/controller/async.js<|end_filename|> 'use strict'; module.exports = app => { return class AsyncController extends app.Controller { async index() { this.ctx.body.push('async'); } } }; <|start_filename|>test/fixtures/extend-env/app/extend/application.custom.js<|end_filename|> 'use strict'; exports.a = 'a1'; exports.custom = true; <|start_filename|>test/fixtures/app-core-middleware/config/config.default.js<|end_filename|> exports.coreMiddleware = []; <|start_filename|>test/fixtures/extend/node_modules/b/app/extend/application.js<|end_filename|> 'use strict'; module.exports = { pluginbApplication: 'plugin b application', }; <|start_filename|>lib/loader/mixin/config.js<|end_filename|> 'use strict'; const debug = require('debug')('egg-core:config'); const path = require('path'); const extend = require('extend2'); const assert = require('assert'); const { Console } = require('console'); module.exports = { /** * Load config/config.js * * Will merge config.default.js 和 config.${env}.js * * @function EggLoader#loadConfig * @since 1.0.0 */ loadConfig() { this.timing.start('Load Config'); this.configMeta = {}; const target = {}; // Load Application config first const appConfig = this._preloadAppConfig(); // plugin config.default // framework config.default // app config.default // plugin config.{env} // framework config.{env} // app config.{env} for (const filename of this.getTypeFiles('config')) { for (const unit of this.getLoadUnits()) { const isApp = unit.type === 'app'; const config = this._loadConfig(unit.path, filename, isApp ? undefined : appConfig, unit.type); if (!config) { continue; } debug('Loaded config %s/%s, %j', unit.path, filename, config); extend(true, target, config); } } // load env from process.env.EGG_APP_CONFIG const envConfig = this._loadConfigFromEnv(); debug('Loaded config from env, %j', envConfig); extend(true, target, envConfig); // You can manipulate the order of app.config.coreMiddleware and app.config.appMiddleware in app.js target.coreMiddleware = target.coreMiddlewares = target.coreMiddleware || []; target.appMiddleware = target.appMiddlewares = target.middleware || []; this.config = target; this.timing.end('Load Config'); }, _preloadAppConfig() { const names = [ 'config.default', `config.${this.serverEnv}`, ]; const target = {}; for (const filename of names) { const config = this._loadConfig(this.options.baseDir, filename, undefined, 'app'); extend(true, target, config); } return target; }, _loadConfig(dirpath, filename, extraInject, type) { const isPlugin = type === 'plugin'; const isApp = type === 'app'; let filepath = this.resolveModule(path.join(dirpath, 'config', filename)); // let config.js compatible if (filename === 'config.default' && !filepath) { filepath = this.resolveModule(path.join(dirpath, 'config/config')); } const config = this.loadFile(filepath, this.appInfo, extraInject); if (!config) return null; if (isPlugin || isApp) { assert(!config.coreMiddleware, 'Can not define coreMiddleware in app or plugin'); } if (!isApp) { assert(!config.middleware, 'Can not define middleware in ' + filepath); } // store config meta, check where is the property of config come from. this._setConfigMeta(config, filepath); return config; }, _loadConfigFromEnv() { const envConfigStr = process.env.EGG_APP_CONFIG; if (!envConfigStr) return; try { const envConfig = JSON.parse(envConfigStr); this._setConfigMeta(envConfig, '<process.env.EGG_APP_CONFIG>'); return envConfig; } catch (err) { this.options.logger.warn('[egg-loader] process.env.EGG_APP_CONFIG is not invalid JSON: %s', envConfigStr); } }, _setConfigMeta(config, filepath) { config = extend(true, {}, config); setConfig(config, filepath); extend(true, this.configMeta, config); }, }; function setConfig(obj, filepath) { for (const key of Object.keys(obj)) { const val = obj[key]; // ignore console if (key === 'console' && val && typeof val.Console === 'function' && val.Console === Console) { obj[key] = filepath; continue; } if (val && Object.getPrototypeOf(val) === Object.prototype && Object.keys(val).length > 0) { setConfig(val, filepath); continue; } obj[key] = filepath; } } <|start_filename|>test/fixtures/extend/app/controller/home.js<|end_filename|> 'use strict'; module.exports = function*() { const status = Number(this.query.status || 200); this.status = status; this.etag = '2.2.2.2'; this.body = { returnAppContext: this.appContext, returnPluginbContext: this.pluginbContext, returnAppRequest: this.request.appRequest, returnPluginbRequest: this.request.pluginbRequest, returnAppResponse: this.response.appResponse, returnPluginbResponse: this.response.pluginbResponse, returnAppApplication: this.app.appApplication, returnPluginbApplication: this.app.pluginbApplication, status: this.status, etag: this.etag, }; }; <|start_filename|>test/fixtures/beforestart-error/app.js<|end_filename|> 'use strict'; const assert = require('assert'); module.exports = app => { app.isReady = true; app.beforeStart(function*() { if (!app.isReady) throw new Error('not ready'); }); app.isReady = false; }; <|start_filename|>test/fixtures/router-in-app/app.js<|end_filename|> 'use strict'; module.exports = app => { app.router; } <|start_filename|>test/fixtures/middleware-aa/app/middleware/router.js<|end_filename|> 'use strict'; module.exports = function() { return async (ctx, next) => { ctx.set('router', 'router'); await next(); }; }; <|start_filename|>test/jest.test.js<|end_filename|> 'use strict'; const path = require('path'); const assert = require('assert'); const coffee = require('coffee'); describe('test/jest.test.js', () => { it('should works without error with jest', async () => { const { stdout, stderr } = await coffee .fork(require.resolve('jest/bin/jest'), [], { cwd: path.resolve(__dirname, './fixtures/egg-jest'), }) // .debug() .end(); assert((stdout + stderr).includes('Test Suites: 1 passed, 1 total')); }); }); <|start_filename|>test/fixtures/middleware-match/config/config.js<|end_filename|> exports.status = { match(ctx) { return ctx.method === 'GET'; }, }; <|start_filename|>test/fixtures/timing/agent.js<|end_filename|> 'use strict'; const block = require('./block'); module.exports = agent => { block(); agent.beforeStart(function* () { block(); }) }; <|start_filename|>test/fixtures/egg-jest/app/extend/application.js<|end_filename|> 'use strict'; module.exports = { get Proxy() { return this.BaseContextClass; }, }; <|start_filename|>test/fixtures/egg-jest/index.js<|end_filename|> 'use strict'; const fs = require('fs'); const path = require('path'); const rimraf = require('mz-modules/rimraf'); const EggCore = require('../../../').EggCore; const EggLoader = require('../../../').EggLoader; class AppLoader extends EggLoader { loadAll() { this.loadPlugin(); this.loadConfig(); this.loadApplicationExtend(); this.loadContextExtend(); this.loadRequestExtend(); this.loadResponseExtend(); this.loadCustomApp(); this.loadMiddleware(); this.loadService(); this.loadController(); this.loadRouter(); } } class EggApplication extends EggCore { constructor(options) { super(options); this.on('error', err => { console.error(err); }) } get [Symbol.for('egg#eggPath')]() { return __dirname; } get [Symbol.for('egg#loader')]() { return AppLoader; } } module.exports.Application = EggApplication; <|start_filename|>test/fixtures/application/app/extend/application.js<|end_filename|> 'use strict'; module.exports = { foo: 'app bar', bar: 'foo' }; <|start_filename|>test/fixtures/router-app/app/middleware/generator_both.js<|end_filename|> 'use strict'; module.exports = function() { return function*(next) { this.body = []; this.body.push('generator before'); yield next; this.body.push('generator after'); }; }; <|start_filename|>test/fixtures/plugin-egg-plugin/node_modules/a/config/plugin.js<|end_filename|> 'use strict'; module.exports = { name: 'a', dep: [ 'b' ], }; <|start_filename|>test/fixtures/controller-next-argument/app/controller/home.js<|end_filename|> 'use strict'; exports.next = function*(next) { yield next; this.body = 'done'; }; <|start_filename|>test/fixtures/controller-app/app/controller/generator_function_ctx.js<|end_filename|> 'use strict'; module.exports = function* (ctx) { ctx.body = 'done'; }; <|start_filename|>test/fixtures/context-loader/app/service/user.js<|end_filename|> 'use strict'; module.exports = app => class UserService1 extends app.Service { get info() { const post = this.service.post.postInfo; return `user:${post}`; } }; <|start_filename|>test/fixtures/extend/app/router.js<|end_filename|> 'use strict'; module.exports = function(app) { app.get('/', app.controller.home); app.get('/merge/app_override_chair', app.controller.merge.appOverrideChair); app.get('/merge/app_override_plugin', app.controller.merge.appOverridePlugin); app.get('/merge/plugin_override_chair', app.controller.merge.pluginOverrideChair); }; <|start_filename|>test/fixtures/run-with-debug/index.js<|end_filename|> 'use strict'; const EggApplication = require('../egg').Application; const utils = require('../../utils'); class Application extends EggApplication { get [Symbol.for('egg#eggPath')]() { return __dirname; } toJSON() { return { name: this.name, plugins: this.plugins, config: this.config, }; } } const app = utils.createApp('application', { Application }); app.loader.loadAll(); app.ready(err => { process.exit(err ? 1 : 0); }); <|start_filename|>test/fixtures/beforestart-timeout/app.js<|end_filename|> 'use strict'; module.exports = function(app) { app.beforeStart(function*() { yield sleep(11000); }); }; function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } <|start_filename|>test/fixtures/helper/app/extend/context.js<|end_filename|> 'use strict'; module.exports = { get helper() { return new this.app.Helper(this); }, }; <|start_filename|>test/fixtures/egg-ts-js/app/service/lord.js<|end_filename|> module.exports = class LordService { jsService() { return 'from js service'; } } <|start_filename|>test/fixtures/router-app/app/middleware/generator.js<|end_filename|> 'use strict'; module.exports = function() { return function*(next) { yield next; this.body.push('generator'); }; }; <|start_filename|>test/fixtures/extend-controller-service/app/service/api.js<|end_filename|> 'use strict'; module.exports = app => { return class ApiService extends app.Service { * get() { return yield this.getData(); } }; }; <|start_filename|>test/utils.js<|end_filename|> 'use strict'; const path = require('path'); const EggApplication = require('./fixtures/egg').Application; module.exports = { getFilepath(name) { return path.join(__dirname, 'fixtures', name); }, createApp(name, options) { const baseDir = this.getFilepath(name); options = options || {}; options.baseDir = baseDir; options.type = options.type || 'application'; let CustomApplication = EggApplication; if (options.Application) { CustomApplication = options.Application; } return new CustomApplication(options); }, symbol: { view: Symbol('view'), }, }; <|start_filename|>test/fixtures/helper/app/extend/application.js<|end_filename|> 'use strict'; exports.Helper = class Helper { constructor(ctx) { this.ctx = ctx; this.app = ctx.app; } }; <|start_filename|>test/fixtures/boot-timeout/app.js<|end_filename|> 'use strict'; const sleep = require('mz-modules/sleep'); module.exports = class TimeoutHook { async didLoad() { await sleep(10); } }; <|start_filename|>test/fixtures/scope-env/config/plugin.en.js<|end_filename|> 'use strict'; module.exports = { a: { enable: false, package: 'a', }, b: { enable: true, package: 'b', }, }; <|start_filename|>test/loader/get_framework_paths.test.js<|end_filename|> 'use strict'; const mm = require('mm'); const assert = require('assert'); const utils = require('../utils'); const EggLoader = require('../..').EggLoader; class Application { constructor() { this.loader = new EggLoader({ baseDir: utils.getFilepath('eggpath'), app: this, logger: console, }); } get [Symbol.for('egg#eggPath')]() { return utils.getFilepath('egg'); } close() {} } describe('test/loader/get_framework_paths.test.js', function() { let app; afterEach(mm.restore); afterEach(() => app && app.close()); it('should get from paramter', function() { app = utils.createApp('eggpath'); assert.deepEqual(app.loader.eggPaths, [ utils.getFilepath('egg') ]); }); it('should get from framework using symbol', function() { app = utils.createApp('eggpath', { Application: require(utils.getFilepath('framework-symbol')), }); assert.deepEqual(app.loader.eggPaths, [ utils.getFilepath('egg'), utils.getFilepath('framework-symbol/node_modules/framework2'), utils.getFilepath('framework-symbol'), ]); }); it('should throw when one of the Application do not specify symbol', () => { assert.throws(() => { utils.createApp('eggpath', { Application: require(utils.getFilepath('framework-nosymbol')), }); }, /Symbol.for\('egg#eggPath'\) is required on Application/); }); it('should remove dulplicate eggPath', () => { app = utils.createApp('eggpath', { Application: require(utils.getFilepath('framework-dulp')), }); assert.deepEqual(app.loader.eggPaths, [ utils.getFilepath('egg'), utils.getFilepath('framework-dulp'), ]); }); it('should when Application do not extend EggCore', () => { app = utils.createApp('eggpath', { Application, }); assert(app.loader.eggPaths.length === 1); assert(app.loader.eggPaths[0] === utils.getFilepath('egg')); }); it('should assert eggPath type', () => { assert.throws(() => { utils.createApp('eggpath', { Application: require(utils.getFilepath('framework-wrong-eggpath')), }); }, /Symbol.for\('egg#eggPath'\) should be string/); }); }); <|start_filename|>test/fixtures/extend/node_modules/b/app/extend/response.js<|end_filename|> 'use strict'; module.exports = { pluginbResponse: 'plugin b response', overridePlugin: 'will be overridden' }; <|start_filename|>test/fixtures/plugin-dep-disable/config/plugin.js<|end_filename|> 'use strict'; exports.e = false; <|start_filename|>test/fixtures/framework-dulp/index.js<|end_filename|> 'use strict'; const EggApplication = require('../egg').Application; class Application extends EggApplication { get [Symbol.for('egg#eggPath')]() { return __dirname; } } class Application2 extends Application { get [Symbol.for('egg#eggPath')]() { return __dirname; } } module.exports = Application2; <|start_filename|>test/fixtures/config/app/controller/util/a.js<|end_filename|> module.exports = { a: 1, b: function() { } }; <|start_filename|>test/fixtures/preload-app-config/config/config.js<|end_filename|> 'use strict'; module.exports = function(antx, appConfig) { return { app: { sub: { val: 1 }, val: 2, }, appInApp: appConfig != null, }; }; <|start_filename|>test/fixtures/middleware-override/config/config.js<|end_filename|> exports.middleware = ['static', 'custom']; <|start_filename|>test/fixtures/middleware-redefined/app/middleware/static.js<|end_filename|> 'use strict'; module.exports = function() { return function*(next) { if (this.path === '/static') { this.body = 'static'; return; } yield next; }; }; <|start_filename|>test/loader/mixin/load_extend.test.js<|end_filename|> 'use strict'; const request = require('supertest'); const mm = require('mm'); const assert = require('assert'); const utils = require('../../utils'); describe('test/loader/mixin/load_extend.test.js', () => { let app; before(function() { app = utils.createApp('extend'); app.loader.loadPlugin(); app.loader.loadConfig(); app.loader.loadRequestExtend(); app.loader.loadResponseExtend(); app.loader.loadApplicationExtend(); app.loader.loadContextExtend(); app.loader.loadController(); app.loader.loadRouter(); }); after(() => app.close()); afterEach(mm.restore); it('should load app.context app.request app.response', () => { assert(app.context.appContext); assert(app.context.pluginbContext); assert(!app.context.pluginaContext); assert(app.request.appRequest); assert(app.request.pluginbRequest); assert(!app.request.pluginaRequest); assert(app.response.appResponse); assert(app.response.pluginbResponse); assert(!app.response.pluginaResponse); assert(app.appApplication); assert(app.pluginbApplication); assert(!app.pluginaApplication); return request(app.callback()) .get('/') .expect({ returnAppContext: 'app context', returnPluginbContext: 'plugin b context', returnAppRequest: 'app request', returnPluginbRequest: 'plugin b request', returnAppResponse: 'app response', returnPluginbResponse: 'plugin b response', returnAppApplication: 'app application', returnPluginbApplication: 'plugin b application', status: 200, etag: 'etag ok', }) .expect(200); }); it('should load application overriding framework', async () => { await request(app.callback()) .get('/merge/app_override_chair') .expect({ value: 'app ajax patch', }) .expect(200); }); it('should load plugin overriding framework', async () => { await request(app.callback()) .get('/merge/plugin_override_chair') .expect({ value: '0.0.0.0', }) .expect(200); }); it('should load application overriding plugin', async () => { await request(app.callback()) .get('/merge/app_override_plugin') .expect({ value: 'will override plugin', }) .expect(200); }); it('should throw when no deps', function() { assert.throws(() => { const app = utils.createApp('load_context_error'); app.loader.loadContextExtend(); }, /Cannot find module 'this is a pen'/); }); it('should throw when syntax error', function() { assert.throws(() => { const app = utils.createApp('load_context_syntax_error'); app.loader.loadContextExtend(); }, /Parse Error: Unexpected token/); }); it('should extend symbol', function() { const app = utils.createApp('extend-symbol'); app.loader.loadApplicationExtend(); assert.equal(app[utils.symbol.view], 'view'); }); it('should load application by custom env', function() { mm(process.env, 'EGG_SERVER_ENV', 'custom'); const app = utils.createApp('extend-env'); app.loader.loadPlugin(); app.loader.loadApplicationExtend(); assert(app.custom === true); // application.custom.js override application.js assert(app.a === 'a1'); // application.custom.js in plugin also can override application.js in app assert(app.b === 'b1'); }); it('should not load extend that returned function', function() { const proto = {}; app.loader.loadExtend('call', proto); assert(proto.call === undefined); }); describe('load unittest extend', () => { let app; after(() => app.close()); it('should load unittext.js when unittest', async () => { app = utils.createApp('load-plugin-unittest'); app.loader.loadPlugin(); app.loader.loadApplicationExtend(); assert(app.unittest === true); assert(app.local !== true); }); it('should load unittext.js when mm.env(default)', async () => { mm(process.env, 'EGG_SERVER_ENV', 'local'); mm(process.env, 'EGG_MOCK_SERVER_ENV', 'local'); app = utils.createApp('load-plugin-unittest'); app.loader.loadPlugin(); app.loader.loadApplicationExtend(); assert(app.unittest === true); assert(app.local === true); }); }); }); <|start_filename|>test/fixtures/loadfile/es-module-default.js<|end_filename|> "use strict"; exports.__esModule = true; exports["default"] = { fn() {} }; <|start_filename|>test/fixtures/config-env-app-config/config/config.default.js<|end_filename|> 'use strict'; module.exports = { egg: 'config-default', foo: { bar: 'a', bar2: 'b', }, }; <|start_filename|>test/fixtures/custom-loader/app/plugin/a.js<|end_filename|> 'use strict'; class PluginA { getName() { return 'plugina'; } } module.exports = PluginA; <|start_filename|>test/fixtures/router-in-app/app/router.js<|end_filename|> 'use strict'; module.exports = app => { app.get('/', ctx => { ctx.body = ctx.foo; }); } <|start_filename|>test/fixtures/plugin-complex-deps/config/plugin.js<|end_filename|> 'use strict'; const path = require('path'); exports.tracelog = { enable: true, path: path.join(__dirname, '../plugin/tracelog'), }; exports.rpcServer = { enable: false, path: path.join(__dirname, '../plugin/rpc-server'), }; exports.gw = { enable: false, path: path.join(__dirname, '../plugin/gw'), }; <|start_filename|>test/fixtures/service-unique/app/router.js<|end_filename|> module.exports = function (app) { app.get('/same', 'same'); }; <|start_filename|>test/fixtures/helper/app/controller/home.js<|end_filename|> module.exports = function*() { try { this.body = ` app: ${this.helper.exists(this.helper.app)} plugin a: ${this.helper.exists(this.helper.a)} plugin b: ${this.helper.exists(this.helper.b)} override: ${this.helper.override()} not exists on locals: ${this.helper.exists(this.notExistsApp)} `; } catch(e) { console.log(e); } } <|start_filename|>test/fixtures/plugin/app/proxy/OnlyClassQuery.js<|end_filename|> 'use strict'; const Proxy = require('../../../egg/proxy'); class OnlyCLassQuery extends Proxy { constructor(ctx) { super(ctx); } * query() { return { foo: 'clz', }; } } module.exports = OnlyCLassQuery; <|start_filename|>test/loader/mixin/load_helper_extend.test.js<|end_filename|> 'use strict'; const request = require('supertest'); const utils = require('../../utils'); describe('test/loader/mixin/load_helper_extend.test.js', function() { describe('helper', () => { let app; before(function() { app = utils.createApp('helper'); app.loader.loadPlugin(); app.loader.loadConfig(); app.loader.loadApplicationExtend(); app.loader.loadContextExtend(); app.loader.loadHelperExtend(); app.loader.loadController(); app.loader.loadRouter(); }); after(() => app.close()); it('should load extend from chair, plugin and helper', async () => { await request(app.callback()) .get('/') .expect(/app: true/) .expect(/plugin a: false/) .expect(/plugin b: true/) .expect(200); }); it('should override chair by application', async () => { await request(app.callback()) .get('/') .expect(/override: app/) .expect(200); }); it('should not call directly', async () => { await request(app.callback()) .get('/') .expect(/not exists on locals: false/) .expect(200); }); }); describe('no Helper', () => { let app; after(() => app.close()); it('should not extend helper', () => { app = utils.createApp('no-helper'); // should not throw app.loader.loadHelperExtend(); }); }); }); <|start_filename|>test/fixtures/subdir-proxy/app/proxy/foo/subdir2/sub2.js<|end_filename|> 'use strict'; module.exports = app => { return class Sub2 extends app.Service { constructor(ctx) { super(ctx); } * get(name) { return { name: name, bar: 'bar3', }; } } }; <|start_filename|>test/fixtures/plugin/app/proxy/couponQuery.js<|end_filename|> 'use strict'; module.exports = function(app) { class CouponQuery extends app.Proxy { constructor(ctx) { super(ctx); } * query() { return { coupon: 100, }; } } return CouponQuery; }; <|start_filename|>test/fixtures/boot-willReady-error/app.js<|end_filename|> 'use strict'; const sleep = require('mz-modules/sleep'); module.exports = class { constructor(app) { this.app = app; app.bootLog = []; } configDidLoad() { this.app.bootLog.push('configDidLoad'); } async didLoad() { await sleep(1); this.app.bootLog.push('didLoad'); } async willReady() { await sleep(1); throw new Error('willReady error'); } async didReady() { await sleep(1); this.app.bootLog.push('didReady'); } async beforeClose() { await sleep(1); this.app.bootLog.push('beforeClose'); } }; <|start_filename|>test/fixtures/scope-env/config/config.en_prod.js<|end_filename|> 'use strict'; module.exports = { from: 'en_prod', }; <|start_filename|>test/fixtures/service-unique/app/controller/same.js<|end_filename|> module.exports = function* () { const ctx = this.service.ctx.get(); this.body = String(ctx === this); }; <|start_filename|>test/fixtures/plugin-framework/config/plugin.js<|end_filename|> 'use strict'; exports.hsfclient = true; <|start_filename|>test/fixtures/beforestart-params-error/app.js<|end_filename|> 'use strict'; module.exports = function(app) { app.beforeStart(); }; <|start_filename|>test/loader/get_app_info.test.js<|end_filename|> 'use strict'; const path = require('path'); const mm = require('mm'); const assert = require('assert'); const utils = require('../utils'); describe('test/loader/get_app_info.test.js', () => { let app; afterEach(() => app.close()); afterEach(mm.restore); it('should get appInfo', () => { app = utils.createApp('appinfo'); assert(app.loader.appInfo.name === 'appinfo'); assert(app.loader.appInfo.baseDir === path.join(__dirname, '../fixtures/appinfo')); assert(app.loader.appInfo.env === 'unittest'); assert(app.loader.appInfo.HOME === process.env.HOME); assert.deepEqual(app.loader.appInfo.pkg, { name: 'appinfo', }); }); it('should get root when unittest', () => { mm(process.env, 'EGG_SERVER_ENV', 'unittest'); app = utils.createApp('appinfo'); assert(app.loader.appInfo.root === path.join(__dirname, '../fixtures/appinfo')); }); it('should get root when unittest', () => { mm(process.env, 'EGG_SERVER_ENV', 'local'); app = utils.createApp('appinfo'); assert(app.loader.appInfo.root === path.join(__dirname, '../fixtures/appinfo')); }); it('should get root when unittest', () => { mm(process.env, 'EGG_SERVER_ENV', 'default'); app = utils.createApp('appinfo'); assert(app.loader.appInfo.root === process.env.HOME); }); }); <|start_filename|>test/fixtures/context-loader/config/config.default.js<|end_filename|> 'use strict'; exports.name = 'config'; <|start_filename|>benchmark/middleware/app/router.js<|end_filename|> 'use strict'; module.exports = app => { const asyncMiddlewares = []; const generatorMiddlewares = []; const transferMiddlewares = []; for (let i = 0; i < 20; i++) { asyncMiddlewares.push(app.middlewares.async()); generatorMiddlewares.push(app.middlewares.generator()); } app.get('/async', ...asyncMiddlewares, 'home.async'); app.get('/generator', ...generatorMiddlewares, 'home.generator'); } <|start_filename|>test/fixtures/app-before-close/app.js<|end_filename|> 'use strict'; module.exports = app => { app.closeFn = false; app.closeGeneratorFn = false; app.closeAsyncFn = false; app.closeOrderArray = []; app.beforeClose(() => { app.closeFn = true; app.closeOrderArray.push('closeFn'); }); app.beforeClose(function* () { app.closeGeneratorFn = true; app.closeOrderArray.push('closeGeneratorFn'); }); app.beforeClose(function() { app.closeOrderArray.push('closeAsyncFn'); return new Promise(resolve => { app.closeAsyncFn = true; resolve(); }); }); let count = 0; function onlyOnce() { if (count === 0) { app.onlyOnce = false; } else { app.onlyOnce = true; } count++; } app.beforeClose(onlyOnce); app.beforeClose(onlyOnce); app.beforeClose(() => { app.closeEvent = 'before'; }); app.once('close', () => { app.closeEvent = 'after'; }); app.beforeClose(() => { if (!app.callCount) { app.callCount = 1; } else { app.callCount++; } }); }; <|start_filename|>test/fixtures/egg-jest/config/plugin.js<|end_filename|> 'use strict'; const path = require('path'); module.exports = { session: { enable: true, path: path.join(__dirname, '../node_modules/session'), }, hsfclient: { enable: false, path: path.join(__dirname, '../plugins/hsfclient'), }, }; <|start_filename|>test/fixtures/boot-before-close/app/plugin/boot-plugin-dep/app.js<|end_filename|> 'use strict'; module.exports = app => { app.beforeClose(async () => { app.bootLog.push('beforeClose in plugin dep'); }); }; <|start_filename|>test/fixtures/plugin-complex-dependencies/config/plugin.js<|end_filename|> 'use strict'; const path = require('path'); exports.rpc = { enable: true, path: path.join(__dirname, '../plugin/rpc'), }; exports.ldc = { enable: true, path: path.join(__dirname, '../plugin/ldc'), }; exports.zoneclient = { enable: true, path: path.join(__dirname, '../plugin/zoneclient'), }; exports.zookeeper = { enable: true, path: path.join(__dirname, '../plugin/zookeeper'), }; exports.vip = { enable: true, path: path.join(__dirname, '../plugin/vip'), }; exports.ddcs = { enable: true, path: path.join(__dirname, '../plugin/ddcs'), }; <|start_filename|>test/fixtures/deprecate/app/extend/application.js<|end_filename|> 'use strict'; module.exports = { get env() { this.deprecate('please use app.config.env instead'); return this.deprecate; }, }; <|start_filename|>test/fixtures/boot/app/plugin/boot-plugin-dep/agent.js<|end_filename|> 'use strict'; module.exports = class Boot { constructor(agent) { this.agent = agent; } configDidLoad() { this.agent.bootLog.push('configDidLoad in plugin'); } }; <|start_filename|>test/fixtures/middleware-disable/config/config.js<|end_filename|> exports.status = { enable: false, }; <|start_filename|>test/fixtures/egg/config/config.default.js<|end_filename|> 'use strict'; module.exports = { coreMiddleware: ['status'], urllib: { keepAlive: true, keepAliveTimeout: 30000, timeout: 30000, maxSockets: Infinity, maxFreeSockets: 256, }, egg: 'egg', }; <|start_filename|>test/fixtures/context-loader/app/service1/user.js<|end_filename|> 'use strict'; module.exports = app => class UserService1 extends app.Service { get userInfo() { return 'service1'; } }; <|start_filename|>test/fixtures/load_context_error/app/extend/context.js<|end_filename|> 'use strict'; require('this is a pen'); exports.customCon = function * () { this.body = 'test'; }; <|start_filename|>test/fixtures/proxy-override/node_modules/a/app/proxy/queryProxy.js<|end_filename|> 'use strict'; module.exports = function(app) { class QueryProxy extends app.Proxy { constructor(ctx) { super(ctx); } * query() { return { foo: 'bar', }; } } return QueryProxy; }; <|start_filename|>test/fixtures/extend-controller-service/app.js<|end_filename|> 'use strict'; module.exports = app => { class CustomController extends app.Controller { success(result) { this.ctx.body = { success: true, result, }; } fail(message) { this.ctx.body = { success: false, message, }; } } class CustomService extends app.Service { * getData() { return 'bar'; } } app.Controller = CustomController; app.Service = CustomService; }; <|start_filename|>test/fixtures/context-loader/app/depth/two/two.js<|end_filename|> 'use strict'; module.exports = class Two { constructor(ctx) { this.ctx = ctx; } get() { return this.ctx.name + ':two'; } } <|start_filename|>test/fixtures/application/node_modules/a/app/extend/application.js<|end_filename|> 'use strict'; module.exports = { a: 'plugin a', poweredBy: 'plugin a' }; <|start_filename|>test/fixtures/controller-app/app/controller/admin/config.js<|end_filename|> 'use strict'; module.exports = app => { return class AdminConfig extends app.Controller { * getName() { this.ctx.body = this.pathName; } * getFullPath() { this.ctx.body = this.fullPath; } }; }; <|start_filename|>test/fixtures/custom-loader/config/b/app/plugin/b.js<|end_filename|> 'use strict'; class PluginB { getName() { return 'pluginb'; } } module.exports = PluginB; <|start_filename|>test/fixtures/framework-symbol/config/config.js<|end_filename|> 'use strict'; module.exports = { framework1: 'framework1', }; <|start_filename|>test/fixtures/framework-symbol/node_modules/framework2/config/config.js<|end_filename|> 'use strict'; module.exports = { framework2: 'framework2', }; <|start_filename|>test/fixtures/custom-loader/app/util/sub/fn.js<|end_filename|> 'use strict'; module.exports = app => { return { echo() { return `echo ${app.config.pkgName}`; }, } }; <|start_filename|>test/fixtures/egg/plugins/hsfclient/package.json<|end_filename|> { "eggPlugin": { "name": "hsfclient", "dep": ["eagleeye", "configclient", "diamond"] } } <|start_filename|>test/fixtures/boot/app/plugin/boot-plugin-dep/app.js<|end_filename|> 'use strict'; module.exports = class Boot { constructor(app) { this.app = app; } configDidLoad() { this.app.bootLog.push('configDidLoad in plugin'); } }; <|start_filename|>test/fixtures/scope/config/plugin.en.js<|end_filename|> 'use strict'; module.exports = { a: false, }; <|start_filename|>test/fixtures/load_context_syntax_error/app/extend/context.js<|end_filename|> 'use strict'; exports.customCon = function * () { this.body = 'test'; <|start_filename|>test/fixtures/controller-app/app/service/home.js<|end_filename|> 'use strict'; module.exports = app => { return class HomeService extends app.Service { info() { return new Promise(resolve => { resolve('done'); }) } }; }; <|start_filename|>test/fixtures/egg-jest/__tests__/index.js<|end_filename|> 'use strict'; const path = require('path'); const assert = require('assert'); const EggApplication = require('../').Application; test('should works', async () => { const app = new EggApplication({ baseDir: path.resolve(__dirname, '../'), type: 'application', }); app.loader.loadAll(); expect(!!app.Proxy).toBe(true); expect(!!app.config.urllib.keepAlive).toBe(true); }); <|start_filename|>test/fixtures/load_dirs/dao/TestClass.js<|end_filename|> 'use strict'; module.exports = class TestClass { constructor(app, fullpath) { this.user = { name: 'kai.fangk', }; this.app = app; this.path = fullpath; } } <|start_filename|>test/fixtures/egg/app/extend/application.js<|end_filename|> 'use strict'; const symbol = require('../../../../utils').symbol; module.exports = { get Proxy() { return this.BaseContextClass; }, get [symbol.view]() { return 'egg'; }, }; <|start_filename|>test/fixtures/boot/config/plugin.js<|end_filename|> 'use strict'; const path = require('path'); exports.bootPlugin = { enable: true, path: path.join(__dirname, '../app/plugin/boot-plugin'), }; exports.bootPluginDep = { enable: true, path: path.join(__dirname, '../app/plugin/boot-plugin-dep'), }; exports.bootPluginEmpty = { enable: true, path: path.join(__dirname, '../app/plugin/boot-plugin-empty'), }; <|start_filename|>test/fixtures/service-unique/app/service/ctx.js<|end_filename|> 'use strict'; module.exports = function (app) { class CtxService extends app.Service { get() { return this.ctx; } } return CtxService; }; <|start_filename|>test/fixtures/egg/app/middleware/status.js<|end_filename|> 'use strict'; module.exports = function() { return (ctx, next) => { if (ctx.path === '/status') { ctx.body = 'egg status'; return; } return next(); }; }; <|start_filename|>test/fixtures/middleware-aa/config/config.js<|end_filename|> exports.middleware = [ 'static', 'match', 'common' ]; exports.match = { match: '/match', }; exports.common = { match: '/common', }; <|start_filename|>test/fixtures/load-plugin-by-env/config/plugin.unittest.js<|end_filename|> 'use strict'; const path = require('path'); exports.a = false; exports.b = { enable: true, path: path.join(__dirname, '../plugins/b'), } <|start_filename|>test/fixtures/extend-controller-service/app/router.js<|end_filename|> 'use strict'; module.exports = app => { app.get('/success', 'api.successAction'); app.get('/fail', 'api.failAction'); }; <|start_filename|>test/index.test.js<|end_filename|> 'use strict'; const assert = require('assert'); const EggCore = require('..'); describe('test/index.test.js', () => { it('should expose properties', () => { assert(EggCore.EggCore); assert(EggCore.EggLoader); assert(EggCore.BaseContextClass); assert(EggCore.utils); }); }); <|start_filename|>test/fixtures/controller-app/app/controller/class_inherited.js<|end_filename|> 'use strict'; class BaseController { constructor(ctx) { this.ctx = ctx; } callInheritedFunction() { this.ctx.body = 'inherited'; } callOverriddenFunction() { this.ctx.body = 'base'; } } module.exports = class HomeController extends BaseController { callOverriddenFunction() { this.ctx.body = 'own'; } }; <|start_filename|>test/fixtures/controller-params/app/router.js<|end_filename|> 'use strict'; module.exports = app => { app.get('/generator-function', 'generatorFunction'); app.get('/object-function', 'object.callFunction'); app.get('/class-function', 'class.asyncFunction'); }; <|start_filename|>test/fixtures/beforestart/app.js<|end_filename|> 'use strict'; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments)).next()); }); }; const sleep = require('ko-sleep'); module.exports = function (app) { app.beforeStart(function() { app.beforeStartFunction = true; }); app.beforeStart(function* () { yield sleep(1000); app.beforeStartGeneratorFunction = true; }); app.beforeStart(function () { return __awaiter(this, void 0, void 0, function* () { yield sleep(1000); app.beforeStartTranslateAsyncFunction = true; }); }); app.beforeStart(async () => { await sleep(1000); app.beforeStartAsyncFunction = true; }); app.beforeStartFunction = false; app.beforeStartTranslateAsyncFunction = false; app.beforeStartGeneratorFunction = false; app.beforeStartAsyncFunction = false; }; <|start_filename|>test/fixtures/scope-env/config/plugin.prod.js<|end_filename|> 'use strict'; module.exports = { b: false, c: { enable: true, package: 'c', }, }; <|start_filename|>test/fixtures/context-loader/app/service2/user.js<|end_filename|> 'use strict'; module.exports = app => class UserService2 extends app.Service { get userInfo() { return 'service2'; } }; <|start_filename|>test/fixtures/extend/app/controller/merge.js<|end_filename|> 'use strict'; exports.appOverrideChair = function*() { this.body = { value: this.ajax() }; }; exports.pluginOverrideChair = function*() { this.body = { value: this.ip }; }; exports.appOverridePlugin = function*() { this.body = { value: this.response.overridePlugin }; }; <|start_filename|>test/fixtures/custom-loader/app/util/test.js<|end_filename|> 'use strict'; exports.sayHi = name => `hi, ${name}`; <|start_filename|>test/fixtures/plugin/node_modules/b/agent.js<|end_filename|> 'use strict'; module.exports = function(agent) { agent.dateB = Date.now(); agent.b = 'plugin b'; }; <|start_filename|>test/fixtures/middleware-aa/app/router.js<|end_filename|> 'use strict'; module.exports = app => { app.get('/router', app.middlewares.router(), controller); app.get('/static', controller); app.get('/match', controller); app.get('/common', controller); app.get('/', controller); }; function* controller() { this.body = 'hello'; }; <|start_filename|>test/fixtures/scope-env/config/config.prod.js<|end_filename|> 'use strict'; module.exports = { from: 'prod', }; <|start_filename|>test/fixtures/boot/app/plugin/boot-plugin/agent.js<|end_filename|> 'use strict'; const sleep = require('mz-modules/sleep'); module.exports = agent => { agent.bootLog.push('agent.js in plugin'); agent.beforeStart(async () => { await sleep(5); agent.bootLog.push('beforeStart'); }); agent.ready(()=> { agent.bootLog.push('ready'); }); }; <|start_filename|>test/fixtures/controller-app/app/router.js<|end_filename|> 'use strict'; module.exports = app => { app.get('/async-function', 'asyncFunction'); app.get('/generator-function', 'generatorFunction'); app.get('/generator-function-ctx', 'generatorFunctionCtx'); app.get('/object-function', 'object.callFunction'); app.get('/object-generator-function', 'object.callGeneratorFunction'); app.get('/subObject-generator-function', 'object.subObject.callGeneratorFunction'); app.get('/subSubObject-generator-function', 'object.subObject.subSubObject.callGeneratorFunction'); app.get('/object-generator-function-arg', 'object.callGeneratorFunctionWithArg'); app.get('/object-async-function', 'object.callAsyncFunction'); app.get('/object-async-function-arg', 'object.callAsyncFunctionWithArg'); app.get('/class-function', 'class.callFunction'); app.get('/class-generator-function', 'class.callGeneratorFunction'); app.get('/class-generator-function-arg', 'class.callGeneratorFunctionWithArg'); app.get('/class-async-function', 'class.callAsyncFunction'); app.get('/class-async-function-arg', 'class.callAsyncFunctionWithArg'); app.get('/class-inherited-function', 'classInherited.callInheritedFunction'); app.get('/class-overridden-function', 'classInherited.callOverriddenFunction'); app.get('/class-wrap-function', 'classWrapFunction.get'); app.get('/class-pathname', 'admin.config.getName'); app.get('/class-fullpath', 'admin.config.getFullPath'); app.resources('/resources-class', 'resourceClass'); app.resources('/resources-object', 'resourceObject'); }; <|start_filename|>test/fixtures/plugin/node_modules/c/agent.js<|end_filename|> 'use strict'; module.exports = function(agent) { agent.dateC = Date.now(); agent.c = 'plugin c'; }; <|start_filename|>benchmark/middleware/start.js<|end_filename|> 'use strict'; const EggApplication = require('../../test/fixtures/egg').Application; const app = new EggApplication({ baseDir: __dirname, type: 'application', }); app.loader.loadAll(); app.listen(7001); console.log('server started at 7001'); <|start_filename|>test/loader/egg_loader.test.js<|end_filename|> 'use strict'; const assert = require('assert'); const os = require('os'); const mm = require('mm'); const path = require('path'); const utils = require('../utils'); const EggLoader = require('../../lib/loader/egg_loader'); const getPlugins = require('egg-utils').getPlugins; describe('test/loader/egg_loader.test.js', () => { let app; before(() => { app = utils.createApp('nothing'); }); it('should container FileLoader and ContextLoader', () => { assert(app.loader.FileLoader); assert(app.loader.ContextLoader); }); describe('loader.getHomedir()', () => { afterEach(mm.restore); it('should return process.env.HOME', () => { if (os.userInfo && os.userInfo().homedir) { const userInfo = os.userInfo(); delete userInfo.homedir; mm(os, 'userInfo', () => userInfo); } assert(app.loader.getHomedir() === process.env.HOME); }); it('should return /home/admin when process.env.HOME is not exist', () => { mm(process.env, 'HOME', ''); mm(os, 'userInfo', null); mm(os, 'homedir', null); assert(app.loader.getHomedir() === '/home/admin'); }); it('should return when EGG_HOME exists', () => { mm(process.env, 'EGG_HOME', '/path/to/home'); assert(app.loader.getHomedir() === '/path/to/home'); }); }); describe('new Loader()', () => { it('should pass', () => { const loader = new EggLoader({ baseDir: path.join(__dirname, '../fixtures/nothing'), app: {}, logger: console, }); loader.loadPlugin(); }); it('should get plugin with egg-utils', () => { getPlugins({ baseDir: path.join(__dirname, '../fixtures/nothing'), framework: path.join(__dirname, '../fixtures/egg'), }); }); it('should loadFile auto resolve file', () => { const loader = new EggLoader({ baseDir: path.join(__dirname, '../fixtures/nothing'), app: {}, logger: console, }); let ret = loader.loadFile(path.join(__dirname, '../fixtures/load_file/function.js'), 1, 2); assert(ret[0] === 1); assert(ret[1] === 2); ret = loader.loadFile(path.join(__dirname, '../fixtures/load_file/function'), 1, 2); assert(ret[0] === 1); assert(ret[1] === 2); }); }); it('should be loaded by loadToApp', () => { const baseDir = path.join(__dirname, '../fixtures/load_to_app'); const directory = path.join(baseDir, 'app/model'); const prop = Symbol(); const app = {}; const loader = new EggLoader({ baseDir, app, logger: console, }); loader.loadToApp(directory, prop); assert(app[prop].user); }); it('should be loaded by loadToContext', () => { const baseDir = path.join(__dirname, '../fixtures/load_to_app'); const directory = path.join(baseDir, 'app/service'); const prop = Symbol(); const app = { context: {} }; const loader = new EggLoader({ baseDir, app, logger: console, }); loader.loadToContext(directory, prop); assert(app.context[prop].user); }); }); <|start_filename|>test/fixtures/extend/app/extend/context.js<|end_filename|> 'use strict'; module.exports = { get appContext() { return 'app context'; }, ajax: function() { return 'app ajax patch'; } }; <|start_filename|>test/fixtures/config/config/config.js<|end_filename|> 'use strict'; exports.loader = { service: { ignore: 'util/**' }, controller: { ignore: 'util/**' } }; exports.name = 'config-test'; exports.test = 1; exports.urllib = { keepAlive: false }; <|start_filename|>test/fixtures/context-loader/app/depth/three/three/three.js<|end_filename|> 'use strict'; module.exports = class Three { constructor(ctx) { this.ctx = ctx; } get() { return this.ctx.name + ':three'; } } <|start_filename|>test/fixtures/controller-app/app/controller/resource_class.js<|end_filename|> 'use strict'; module.exports = app => { return class Resource extends app.Controller { * index(ctx) { ctx.body = 'index'; } async create(ctx) { ctx.body = 'create'; } }; }; <|start_filename|>test/fixtures/controller-params/config/config.default.js<|end_filename|> 'use strict'; exports.controller = { supportParams: true, }; <|start_filename|>test/fixtures/load_dirs/filter/class.js<|end_filename|> 'use strict'; module.exports = class User {} <|start_filename|>test/fixtures/config-array/plugin/a/config/config.default.js<|end_filename|> 'use strict'; exports.array = [ 1, 2, 3 ]; <|start_filename|>test/fixtures/plugin-optional-dependencies/config/plugin.js<|end_filename|> 'use strict'; // d(opt) <-- a --> b -> c(opt) // / / // e(opt) <- <-- module.exports = { a: { enable: true, package: 'a', }, b: { enable: true, package: 'b', }, c: { enable: false, package: 'c', }, d: { enable: false, package: 'd', }, e: { enable: true, package: 'e', }, f: { enable: true, package: 'f', }, }; <|start_filename|>test/fixtures/plugin-implicit-enable-dependencies/config/plugin.js<|end_filename|> 'use strict'; const path = require('path'); exports.tracelog = { enable: true, path: path.join(__dirname, '../plugin/tracelog'), }; exports.gateway = { enable: true, path: path.join(__dirname, '../plugin/gateway'), }; exports.rpcServer = { enable: false, path: path.join(__dirname, '../plugin/rpc_server'), }; exports.ldc = { enable: true, path: path.join(__dirname, '../plugin/ldc'), }; exports.zoneclient = { enable: false, path: path.join(__dirname, '../plugin/zoneclient'), }; <|start_filename|>test/fixtures/timing/index.js<|end_filename|> 'use strict'; const fs = require('fs'); const path = require('path'); const EggApplication = require('../egg').Application; const utils = require('../../utils'); class Application extends EggApplication { get [Symbol.for('egg#eggPath')]() { return __dirname; } toJSON() { return { name: this.name, plugins: this.plugins, config: this.config, }; } } const app = utils.createApp('application', { Application }); app.loader.loadAll(); app.ready(err => { fs.writeFileSync(path.join(__dirname, 'timing.json'), JSON.stringify(app.timing.toJSON())); process.exit(err ? 1 : 0); }); <|start_filename|>test/loader/mixin/load_custom_loader.test.js<|end_filename|> 'use strict'; const assert = require('assert'); const request = require('supertest'); const utils = require('../../utils'); describe('test/loader/mixin/load_custom_loader.test.js', function() { let app; before(function() { app = utils.createApp('custom-loader'); app.loader.loadPlugin(); app.loader.loadConfig(); app.loader.loadController(); app.loader.loadRouter(); app.loader.loadCustomLoader(); }); after(() => app.close()); it('should load to app', async () => { const res = await app.adapter.docker.inspectDocker(); assert(res); assert(res.inject === 'app'); }); it('should support exports load to app', () => { assert(app.util.test.sayHi('egg') === 'hi, egg'); assert(app.util.sub.fn.echo() === 'echo custom_loader'); }); it('should load to ctx', async () => { await request(app.callback()) .get('/users/popomore') .expect({ adapter: { directory: 'app/adapter', inject: 'app', }, repository: 'popomore', }) .expect(200); }); it('should support loadunit', async () => { let name = app.plugin.a.getName(); assert(name === 'plugina'); name = app.plugin.b.getName(); assert(name === 'pluginb'); }); it('should loadConfig first', () => { const app = utils.createApp('custom-loader'); try { app.loader.loadCustomLoader(); throw new Error('should not run'); } catch (err) { assert(err.message === 'should loadConfig first'); } finally { app.close(); } }); it('support set directory', () => { const app = utils.createApp('custom-loader'); try { app.loader.config = { customLoader: { custom: { }, }, }; app.loader.loadCustomLoader(); throw new Error('should not run'); } catch (err) { assert(err.message === 'directory is required for config.customLoader.custom'); } finally { app.close(); } }); it('inject support app/ctx', () => { const app = utils.createApp('custom-loader'); try { app.loader.config = { customLoader: { custom: { directory: 'a', inject: 'unknown', }, }, }; app.loader.loadCustomLoader(); throw new Error('should not run'); } catch (err) { assert(err.message === 'inject only support app or ctx'); } finally { app.close(); } }); it('should not overwrite the existing property', () => { const app = utils.createApp('custom-loader'); try { app.loader.config = { customLoader: { config: { directory: 'app/config', inject: 'app', }, }, }; app.loader.loadCustomLoader(); throw new Error('should not run'); } catch (err) { assert(err.message === 'customLoader should not override app.config'); } finally { app.close(); } try { app.loader.config = { customLoader: { cookies: { directory: 'app/cookies', inject: 'ctx', }, }, }; app.loader.loadCustomLoader(); throw new Error('should not run'); } catch (err) { assert(err.message === 'customLoader should not override ctx.cookies'); } finally { app.close(); } }); }); <|start_filename|>test/fixtures/middleware-override/node_modules/b/app/middleware/status.js<|end_filename|> 'use strict'; module.exports = function() { return function* bStatus(next) { if (this.path === '/status') { this.body = 'status'; return; } yield next; }; }; <|start_filename|>test/fixtures/middleware-ignore/config/config.js<|end_filename|> exports.status = { ignore(ctx) { return ctx.method === 'GET'; }, }; <|start_filename|>test/fixtures/plugin/plugin-middleware/config/config.default.js<|end_filename|> exports.middleware = []; <|start_filename|>test/fixtures/controller-app/app/controller/object.js<|end_filename|> 'use strict'; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments)).next()); }); }; module.exports = { callFunction() { this.body = 'done'; }, * callGeneratorFunction() { this.body = yield this.service.home.info(); }, * callGeneratorFunctionWithArg(ctx) { ctx.body = yield ctx.service.home.info(); }, subObject: { * callGeneratorFunction() { this.body = yield this.service.home.info(); }, subSubObject: { * callGeneratorFunction() { this.body = yield this.service.home.info(); }, }, }, callAsyncFunction() { return __awaiter(this, void 0, void 0, function* () { this.body = yield this.service.home.info(); }); }, callAsyncFunctionWithArg(ctx) { return __awaiter(this, void 0, void 0, function* () { ctx.body = yield ctx.service.home.info(); }); }, get nofunction() { return 'done'; } }; <|start_filename|>test/fixtures/middleware-app-disable/config/config.js<|end_filename|> exports.middleware = [ 'static' ]; exports.static = { enable: false, }; <|start_filename|>test/loader/mixin/load_service.test.js<|end_filename|> 'use strict'; const path = require('path'); const request = require('supertest'); const mm = require('mm'); const assert = require('assert'); const utils = require('../../utils'); describe('test/loader/mixin/load_service.test.js', function() { let app; afterEach(mm.restore); afterEach(() => app.close()); it('should load from application and plugin', async () => { app = utils.createApp('plugin'); app.loader.loadPlugin(); app.loader.loadConfig(); app.loader.loadApplicationExtend(); app.loader.loadCustomApp(); app.loader.loadService(); app.loader.loadController(); app.loader.loadRouter(); assert(app.serviceClasses.foo); assert(app.serviceClasses.foo2); assert(!app.serviceClasses.bar1); assert(app.serviceClasses.bar2); assert(app.serviceClasses.foo4); await request(app.callback()) .get('/') .expect({ foo2: 'foo2', foo3: 'foo3', foo4: true, foo5: true, foo: true, bar2: true, }) .expect(200); }); it('should throw when dulplicate', function() { assert.throws(() => { app = utils.createApp('service-override'); app.loader.loadPlugin(); app.loader.loadConfig(); app.loader.loadService(); }, /can't overwrite property 'foo'/); }); it('should check es6', function() { app = utils.createApp('services_loader_verify'); app.loader.loadPlugin(); app.loader.loadConfig(); app.loader.loadApplicationExtend(); app.loader.loadService(); assert('foo' in app.serviceClasses); assert('bar' in app.serviceClasses.foo); assert('bar1' in app.serviceClasses.foo); assert('aa' in app.serviceClasses.foo); }); it('should each request has unique ctx', async () => { app = utils.createApp('service-unique'); app.loader.loadPlugin(); app.loader.loadConfig(); app.loader.loadApplicationExtend(); app.loader.loadCustomApp(); app.loader.loadService(); app.loader.loadController(); app.loader.loadRouter(); await request(app.callback()) .get('/same?t=1') .expect('true') .expect(200); await request(app.callback()) .get('/same?t=2') .expect('true') .expect(200); }); it('should extend app.Service', async () => { app = utils.createApp('extends-app-service'); app.loader.loadPlugin(); app.loader.loadConfig(); app.loader.loadApplicationExtend(); app.loader.loadCustomApp(); app.loader.loadService(); app.loader.loadController(); app.loader.loadRouter(); await request(app.callback()) .get('/user') .expect(function(res) { assert(res.body.user === '123mock'); }) .expect(200); }); describe('subdir', function() { it('should load 2 level dir', async () => { mm(process.env, 'NO_DEPRECATION', '*'); app = utils.createApp('subdir-services'); app.loader.loadPlugin(); app.loader.loadConfig(); app.loader.loadApplicationExtend(); app.loader.loadCustomApp(); app.loader.loadService(); app.loader.loadController(); app.loader.loadRouter(); await request(app.callback()) .get('/') .expect({ user: { uid: '123', }, cif: { uid: '123cif', cif: true, }, bar1: { name: 'bar1name', bar: 'bar1', }, bar2: { name: 'bar2name', bar: 'bar2', }, 'foo.subdir2.sub2': { name: 'bar3name', bar: 'bar3', }, subdir11bar: { bar: 'bar111', }, ok: { ok: true, }, cmd: { cmd: 'hihi', method: 'GET', url: '/', }, serviceIsSame: true, oldStyle: '/', }) .expect(200); }); }); describe('service in other directory', () => { before(() => { const baseDir = utils.getFilepath('other-directory'); app = utils.createApp('other-directory'); app.loader.loadCustomApp(); app.loader.loadService({ directory: path.join(baseDir, 'app/other-service'), }); return app.ready(); }); it('should load', () => { assert(app.serviceClasses.user); }); }); }); <|start_filename|>test/fixtures/controller-app/app/controller/async_function.js<|end_filename|> 'use strict'; module.exports = async ctx => { ctx.body = 'done'; }; <|start_filename|>test/fixtures/subdir-proxy/app/router.js<|end_filename|> module.exports = function (app) { app.get('/', function*() { this.body = { user: yield this.proxy.user.get('123'), cif: yield this.proxy.cif.user.get('123cif'), bar1: yield this.proxy.foo.bar.get('bar1name'), bar2: yield this.proxy.foo.subdir.bar.get('bar2name'), 'foo.subdir2.sub2': yield this.proxy.foo.subdir2.sub2.get('bar3name'), subdir11bar: !!this.proxy.foo.subdir1, ok: yield this.proxy.ok.get(), cmd: yield this.proxy.certifyPersonal.mobileHi.doCertify.exec('hihi'), proxyIsSame: this.proxy.certifyPersonal === this.proxy.certifyPersonal, oldStyle: yield this.proxy.oldStyle.url(this), }; }); } <|start_filename|>test/fixtures/boot-before-close/app/plugin/boot-plugin/app.js<|end_filename|> 'use strict'; const assert = require('assert'); module.exports = class BootHook { constructor(app) { this.app = app; } async beforeClose() { this.app.bootLog.push('beforeClose in plugin'); } }; <|start_filename|>test/fixtures/middleware-override/node_modules/a/app/middleware/a.js<|end_filename|> 'use strict'; module.exports = function() { return function*() { this.body = 'plugin a a'; }; }; <|start_filename|>test/fixtures/extend-env/plugins/a/app/extend/application.custom.js<|end_filename|> 'use strict'; exports.b = 'b1'; <|start_filename|>test/fixtures/scope-env/config/config.default.js<|end_filename|> 'use strict'; module.exports = { from: 'default', }; <|start_filename|>test/fixtures/no-middleware/config/config.js<|end_filename|> 'use strict'; module.exports = { middleware: ['a'], }; <|start_filename|>test/fixtures/plugin/agent.js<|end_filename|> 'use strict'; module.exports = function(agent) { agent.date = Date.now(); agent.agent = 'agent'; }; <|start_filename|>test/fixtures/controller-params/app/controller/object.js<|end_filename|> 'use strict'; module.exports = { * callFunction(...args) { this.body = 'done'; return args; }, }; <|start_filename|>test/egg-ts.test.js<|end_filename|> 'use strict'; const mm = require('mm'); const request = require('supertest'); const assert = require('assert'); const utils = require('./utils'); const path = require('path'); const coffee = require('coffee'); const loaderUtil = require('../lib/utils'); describe('test/egg-ts.test.js', () => { let app; beforeEach(() => { require.extensions['.ts'] = require.extensions['.js']; loaderUtil.extensions['.ts'] = require.extensions['.js']; }); afterEach(() => { mm.restore(); delete require.extensions['.ts']; delete loaderUtil.extensions['.ts']; }); describe('load ts file', () => { describe('load app', () => { it('should success', async () => { mm(process.env, 'EGG_TYPESCRIPT', 'true'); app = utils.createApp('egg-ts'); app.Helper = class Helper {}; app.loader.loadPlugin(); app.loader.loadConfig(); app.loader.loadApplicationExtend(); app.loader.loadAgentExtend(); app.loader.loadRequestExtend(); app.loader.loadResponseExtend(); app.loader.loadContextExtend(); app.loader.loadHelperExtend(); app.loader.loadCustomApp(); app.loader.loadService(); app.loader.loadController(); app.loader.loadRouter(); app.loader.loadPlugin(); app.loader.loadMiddleware(); await request(app.callback()) .get('/') .expect(res => { assert(res.text.includes('from extend context')); assert(res.text.includes('from extend application')); assert(res.text.includes('from extend request')); assert(res.text.includes('from extend agent')); assert(res.text.includes('from extend helper')); assert(res.text.includes('from extend response')); assert(res.text.includes('from custom app')); assert(res.text.includes('from plugins')); assert(res.text.includes('from config.default')); assert(res.text.includes('from middleware')); assert(res.text.includes('from service')); }) .expect(200); }); }); describe('load agent', () => { it('should success', async () => { mm(process.env, 'EGG_TYPESCRIPT', 'true'); app = utils.createApp('egg-ts'); app.Helper = class Helper {}; app.loader.loadPlugin(); app.loader.loadConfig(); app.loader.loadApplicationExtend(); app.loader.loadAgentExtend(); app.loader.loadRequestExtend(); app.loader.loadResponseExtend(); app.loader.loadContextExtend(); app.loader.loadHelperExtend(); app.loader.loadCustomAgent(); app.loader.loadService(); app.loader.loadController(); app.loader.loadRouter(); app.loader.loadPlugin(); app.loader.loadMiddleware(); await request(app.callback()) .get('/') .expect(res => { assert(res.text.includes('from extend context')); assert(res.text.includes('from extend application')); assert(res.text.includes('from extend request')); assert(res.text.includes('from extend agent')); assert(res.text.includes('from extend helper')); assert(res.text.includes('from extend response')); assert(res.text.includes('from custom agent')); assert(res.text.includes('from plugins')); assert(res.text.includes('from config.default')); assert(res.text.includes('from middleware')); assert(res.text.includes('from service')); }) .expect(200); }); }); }); it('should not load d.ts files while typescript was true', async () => { mm(process.env, 'EGG_TYPESCRIPT', 'true'); app = utils.createApp('egg-ts-js'); app.loader.loadController(); assert(!app.controller.god); assert(app.controller.test); }); it('should support load ts,js files', async () => { mm(process.env, 'EGG_TYPESCRIPT', 'true'); app = utils.createApp('egg-ts-js'); app.loader.loadService(); assert(app.serviceClasses.lord); assert(app.serviceClasses.test); }); it('should not load ts files while EGG_TYPESCRIPT was not exist', async () => { app = utils.createApp('egg-ts-js'); app.loader.loadApplicationExtend(); app.loader.loadService(); assert(!app.appExtend); assert(app.serviceClasses.lord); assert(!app.serviceClasses.test); }); it('should not load ts files while EGG_TYPESCRIPT was true but no extensions', async () => { mm(process.env, 'EGG_TYPESCRIPT', 'true'); mm(loaderUtil, 'extensions', [ '.js', '.json' ]); app = utils.createApp('egg-ts-js'); app.loader.loadService(); assert(app.serviceClasses.lord); assert(!app.serviceClasses.test); }); it('should compile app-ts without error', async () => { await coffee .spawn('node', [ '--require', 'ts-node/register/type-check', path.resolve(__dirname, './fixtures/app-ts/app.ts') ], { env: Object.assign({}, process.env, { TS_NODE_PROJECT: path.resolve(__dirname, './fixtures/app-ts/tsconfig.json'), }), }) // .debug() .expect('code', 0) .end(); }); it('should compile error with app-ts/error', async () => { await coffee .spawn('node', [ '--require', 'ts-node/register/type-check', path.resolve(__dirname, './fixtures/app-ts/app-error.ts') ], { env: Object.assign({}, process.env, { TS_NODE_PROJECT: path.resolve(__dirname, './fixtures/app-ts/tsconfig.json'), }), }) // .debug() .expect('stderr', /Property 'abb' does not exist on type 'EggCore<{ env: string; }>'/) .expect('stderr', /Property 'abc' does not exist on type 'typeof BaseContextClass'/) .expect('stderr', /'loadPlugin' is protected/) .expect('stderr', /'loadConfig' is protected/) .expect('stderr', /'loadApplicationExtend' is protected/) .expect('stderr', /'loadAgentExtend' is protected/) .expect('stderr', /'loadRequestExtend' is protected/) .expect('stderr', /'loadResponseExtend' is protected/) .expect('stderr', /'loadContextExtend' is protected/) .expect('stderr', /'loadHelperExtend' is protected/) .expect('stderr', /'loadCustomAgent' is protected/) .expect('stderr', /'loadService' is protected/) .expect('stderr', /'loadController' is protected/) .expect('stderr', /Property 'checkEnvType' does not exist on type 'string'/) .expect('stderr', /'ctx' is protected/) .expect('code', 1) .end(); }); }); <|start_filename|>test/fixtures/router-app/app/router.js<|end_filename|> module.exports = function (app) { const common = app.middlewares.common(); const asyncMw = app.middlewares.async(); const generator = app.middlewares.generator(); const generatorBoth = app.middlewares.generatorBoth(); app .get('/locals/router', app.controller.locals.router) .get('/members/index', 'members.index') .delete('/members/delete/:id', 'members.delete') .del('/members/del/:id', 'members.delete') .resources('posts', '/posts', 'posts') .resources('members', '/members', app.controller.members) .resources('/comments', app.controller.comments) .get('comment_index', '/comments/:id?filter=', app.controller.comments.index) .get('params', '/params/:a/:b', app.controller.locals.router) .get('/middleware', common, asyncMw, generator, 'middleware') .get('middleware', '/named_middleware', common, asyncMw, generator, 'middleware') .get('/mix', generatorBoth , 'async.index') .register('/comments', [ 'post' ] , app.controller.comments.new) .register('/register_middleware', [ 'get' ], [ common, asyncMw, generator, 'middleware' ]) .redirect('/redirect', '/middleware', 302); app.router .get('/router_middleware', common, asyncMw, generator, 'middleware') .redirect('/router_redirect', '/middleware'); app.get('packages', /^\/packages\/(.*)/, 'package.get'); app.get([ '/url1', '/url2' ], 'members.index') app.get([ '/urlm1', '/urlm2' ], common, asyncMw, generator, 'middleware') }; <|start_filename|>lib/loader/mixin/router.js<|end_filename|> 'use strict'; const path = require('path'); module.exports = { /** * Load app/router.js * @function EggLoader#loadRouter * @since 1.0.0 */ loadRouter() { this.timing.start('Load Router'); // 加载 router.js this.loadFile(path.join(this.options.baseDir, 'app/router')); this.timing.end('Load Router'); }, }; <|start_filename|>test/fixtures/helper/app/extend/helper.js<|end_filename|> exports.app = function() { return 'app'; }; exports.override = function() { return 'app'; }; exports.exists = function(obj) { return obj !== undefined; }; <|start_filename|>test/loader/mixin/load_config.test.js<|end_filename|> 'use strict'; const path = require('path'); const assert = require('assert'); const mm = require('mm'); const utils = require('../../utils'); const Application = require('../../..').EggCore; describe('test/loader/mixin/load_config.test.js', () => { let app; afterEach(() => app.close()); afterEach(mm.restore); it('should load application config overriding default of egg', () => { app = utils.createApp('config'); const loader = app.loader; loader.loadPlugin(); loader.loadConfig(); assert(loader.config.name === 'config-test'); assert(loader.config.test === 1); // 支持嵌套覆盖 assert.deepEqual(loader.config.urllib, { keepAlive: false, keepAliveTimeout: 30000, timeout: 30000, maxSockets: Infinity, maxFreeSockets: 256, }); }); it('should load plugin config overriding default of egg', () => { app = utils.createApp('plugin'); const loader = app.loader; loader.loadPlugin(); loader.loadConfig(); assert(loader.config.name === 'override default'); }); it('should load application config overriding plugin', () => { app = utils.createApp('plugin'); const loader = app.loader; loader.loadPlugin(); loader.loadConfig(); assert(loader.config.plugin === 'override plugin'); }); // egg config.default // framework config.default // egg config.local // framework config.local it('should load config by env', () => { app = utils.createApp('config-env'); const loader = app.loader; loader.loadPlugin(); loader.loadConfig(); assert(loader.config.egg === 'egg-unittest'); }); it('should override config by env.EGG_APP_CONFIG', () => { mm(process.env, 'EGG_APP_CONFIG', JSON.stringify({ egg: 'env_egg', foo: { bar: 'env_bar', }, })); app = utils.createApp('config-env-app-config'); const loader = app.loader; loader.loadPlugin(); loader.loadConfig(); assert(loader.config.egg === 'env_egg'); assert(loader.config.foo.bar === 'env_bar'); assert(loader.config.foo.bar2 === 'b'); assert(loader.configMeta.egg === '<process.env.EGG_APP_CONFIG>'); assert(loader.configMeta.foo.bar === '<process.env.EGG_APP_CONFIG>'); }); it('should override config with invalid env.EGG_APP_CONFIG', () => { mm(process.env, 'EGG_APP_CONFIG', 'abc'); app = utils.createApp('config-env-app-config'); const loader = app.loader; loader.loadPlugin(); loader.loadConfig(); assert(loader.config.egg === 'egg-unittest'); assert(loader.config.foo.bar === 'a'); assert(loader.config.foo.bar2 === 'b'); }); it('should not load config of plugin that is disabled', () => { app = utils.createApp('plugin'); const loader = app.loader; loader.loadPlugin(); loader.loadConfig(); assert(!loader.config.pluginA); }); it('should throw when plugin define middleware', () => { const pluginDir = utils.getFilepath('plugin/plugin-middleware'); app = utils.createApp('plugin', { plugins: { middleware: { enable: true, path: pluginDir, }, }, }); const loader = app.loader; try { loader.loadPlugin(); loader.loadConfig(); throw new Error('should not run'); } catch (err) { assert(err.message.includes(`Can not define middleware in ${path.join(pluginDir, 'config/config.default.js')}`)); } }); it('should throw when app define coreMiddleware', () => { app = utils.createApp('app-core-middleware'); assert.throws(() => { app.loader.loadPlugin(); app.loader.loadConfig(); }, new RegExp('Can not define coreMiddleware in app or plugin')); }); it('should read appinfo from the function of config', () => { app = utils.createApp('preload-app-config'); const loader = app.loader; loader.loadPlugin(); loader.loadConfig(); assert(loader.config.plugin.val === 2); assert(loader.config.plugin.val === 2); assert(loader.config.plugin.sub !== loader.config.app.sub); assert(loader.config.appInApp === false); }); it('should load config without coreMiddleware', () => { app = new Application({ baseDir: path.join(__dirname, '../../fixtures/no-core-middleware'), }); app.loader.loadPlugin(); app.loader.loadConfig(); assert(app.config.coreMiddleware.length === 0); }); it('should override array', () => { app = utils.createApp('config-array'); app.loader.loadPlugin(); app.loader.loadConfig(); assert.deepEqual(app.config.array, [ 1, 2 ]); }); it('should generate configMeta', () => { app = utils.createApp('configmeta'); app.loader.loadPlugin(); app.loader.loadConfig(); const configMeta = app.loader.configMeta; const configPath = utils.getFilepath('configmeta/config/config.js'); assert(configMeta.console === configPath); assert(configMeta.array === configPath); assert(configMeta.buffer === configPath); assert(configMeta.ok === configPath); assert(configMeta.f === configPath); assert(configMeta.empty === configPath); assert(configMeta.zero === configPath); assert(configMeta.number === configPath); assert(configMeta.no === configPath); assert(configMeta.date === configPath); assert(configMeta.ooooo === configPath); assert(configMeta.urllib.keepAlive === configPath); assert(configMeta.urllib.timeout === utils.getFilepath('egg/config/config.default.js')); assert(configMeta.urllib.foo === configPath); assert(configMeta.urllib.n === configPath); assert(configMeta.urllib.dd === configPath); assert(configMeta.urllib.httpclient === configPath); // undefined will be ignore assert(!configMeta.urllib.bar); }); describe('get config with scope', () => { it('should return without scope when env = default', async () => { mm(process.env, 'EGG_SERVER_ENV', 'default'); app = utils.createApp('scope-env'); const loader = app.loader; loader.loadPlugin(); app.loader.loadConfig(); assert(loader.config.from === 'default'); }); it('should return without scope when env = prod', async () => { mm(process.env, 'EGG_SERVER_ENV', 'prod'); app = utils.createApp('scope-env'); const loader = app.loader; loader.loadPlugin(); app.loader.loadConfig(); assert(loader.config.from === 'prod'); }); it('should return with scope when env = default', async () => { mm(process.env, 'EGG_SERVER_ENV', 'default'); mm(process.env, 'EGG_SERVER_SCOPE', 'en'); app = utils.createApp('scope-env'); const loader = app.loader; loader.loadPlugin(); app.loader.loadConfig(); assert(loader.config.from === 'en'); }); it('should return with scope when env = prod', async () => { mm(process.env, 'EGG_SERVER_ENV', 'prod'); mm(process.env, 'EGG_SERVER_SCOPE', 'en'); app = utils.createApp('scope-env'); const loader = app.loader; loader.loadPlugin(); app.loader.loadConfig(); assert(loader.config.from === 'en_prod'); }); }); }); <|start_filename|>test/fixtures/custom_session_invaild/config/config.js<|end_filename|> exports.middleware = [ 'session' ]; exports.hsf = { enable: false };
beary/egg-core
<|start_filename|>GameDev/week5/homework/solution/UITutorialCompleted/Library/PackageCache/com.unity.test-framework@1.1.16/UnityEditor.TestRunner/TestRunner/Callbacks/WindowResultUpdaterDataHolder.cs<|end_filename|> using System.Collections.Generic; using UnityEditor; using UnityEditor.TestTools.TestRunner.GUI; namespace TestRunner.Callbacks { internal class WindowResultUpdaterDataHolder : ScriptableSingleton<WindowResultUpdaterDataHolder> { public List<TestRunnerResult> CachedResults = new List<TestRunnerResult>(); } } <|start_filename|>GameDev/week5/homework/solution/UITutorialCompleted/Library/PackageCache/com.unity.test-framework@1.1.16/UnityEditor.TestRunner/GUI/TestListTreeView/TestTreeViewItem.cs<|end_filename|> using System; using System.Reflection; using System.Text; using UnityEditor.IMGUI.Controls; using UnityEditor.TestTools.TestRunner.Api; using UnityEngine.TestTools.TestRunner.GUI; namespace UnityEditor.TestTools.TestRunner.GUI { internal sealed class TestTreeViewItem : TreeViewItem { public TestRunnerResult result; internal ITestAdaptor m_Test; public Type type; public MethodInfo method; private const int k_ResultTestMaxLength = 15000; public bool IsGroupNode { get { return m_Test.IsSuite; } } public string FullName { get { return m_Test.FullName; } } public string GetAssemblyName() { var test = m_Test; while (test != null) { if (test.IsTestAssembly) { return test.FullName; } test = test.Parent; } return null; } public TestTreeViewItem(ITestAdaptor test, int depth, TreeViewItem parent) : base(GetId(test), depth, parent, test.Name) { m_Test = test; if (test.TypeInfo != null) { type = test.TypeInfo.Type; } if (test.Method != null) { method = test.Method.MethodInfo; } displayName = test.Name.Replace("\n", ""); icon = Icons.s_UnknownImg; } private static int GetId(ITestAdaptor test) { return test.UniqueName.GetHashCode(); } public void SetResult(TestRunnerResult testResult) { result = testResult; result.SetResultChangedCallback(ResultUpdated); ResultUpdated(result); } public string GetResultText() { var durationString = String.Format("{0:0.000}", result.duration); var sb = new StringBuilder(string.Format("{0} ({1}s)", displayName.Trim(), durationString)); if (!string.IsNullOrEmpty(result.description)) { sb.AppendFormat("\n{0}", result.description); } if (!string.IsNullOrEmpty(result.messages)) { sb.Append("\n---\n"); sb.Append(result.messages.Trim()); } if (!string.IsNullOrEmpty(result.stacktrace)) { sb.Append("\n---\n"); sb.Append(result.stacktrace.Trim()); } if (!string.IsNullOrEmpty(result.output)) { sb.Append("\n---\n"); sb.Append(result.output.Trim()); } if (sb.Length > k_ResultTestMaxLength) { sb.Length = k_ResultTestMaxLength; sb.AppendFormat("...\n\n---MESSAGE TRUNCATED AT {0} CHARACTERS---", k_ResultTestMaxLength); } return sb.ToString().Trim(); } private void ResultUpdated(TestRunnerResult testResult) { switch (testResult.resultStatus) { case TestRunnerResult.ResultStatus.Passed: icon = Icons.s_SuccessImg; break; case TestRunnerResult.ResultStatus.Failed: icon = Icons.s_FailImg; break; case TestRunnerResult.ResultStatus.Inconclusive: icon = Icons.s_InconclusiveImg; break; case TestRunnerResult.ResultStatus.Skipped: icon = Icons.s_IgnoreImg; break; default: if (testResult.ignoredOrSkipped) { icon = Icons.s_IgnoreImg; } else if (testResult.notRunnable) { icon = Icons.s_FailImg; } else { icon = Icons.s_UnknownImg; } break; } } } } <|start_filename|>GameDev/week5/homework/solution/UITutorialCompleted/Library/PackageCache/com.unity.test-framework@1.1.16/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/XboxOnePlatformSetup.cs<|end_filename|> namespace UnityEditor.TestTools.TestRunner { internal class XboxOnePlatformSetup : IPlatformSetup { private XboxOneDeployMethod oldXboxOneDeployMethod; private XboxOneDeployDrive oldXboxOneDeployDrive; private string oldXboxOneAdditionalDebugPorts; public void Setup() { oldXboxOneDeployMethod = EditorUserBuildSettings.xboxOneDeployMethod; oldXboxOneDeployDrive = EditorUserBuildSettings.xboxOneDeployDrive; oldXboxOneAdditionalDebugPorts = EditorUserBuildSettings.xboxOneAdditionalDebugPorts; EditorUserBuildSettings.xboxOneDeployMethod = XboxOneDeployMethod.Package; EditorUserBuildSettings.xboxOneDeployDrive = XboxOneDeployDrive.Default; // This causes the XboxOne post processing systems to open this port in your package manifest. // In addition it will open the ephemeral range for debug connections as well. // Failure to do this will cause connection problems. EditorUserBuildSettings.xboxOneAdditionalDebugPorts = "34999"; } public void PostBuildAction() { } public void PostSuccessfulBuildAction() { } public void PostSuccessfulLaunchAction() { } public void CleanUp() { EditorUserBuildSettings.xboxOneDeployMethod = oldXboxOneDeployMethod; EditorUserBuildSettings.xboxOneDeployDrive = oldXboxOneDeployDrive; // This causes the XboxOne post processing systems to open this port in your package manifest. // In addition it will open the ephemeral range for debug connections as well. // Failure to do this will cause connection problems. EditorUserBuildSettings.xboxOneAdditionalDebugPorts = oldXboxOneAdditionalDebugPorts; } } } <|start_filename|>GameDev/week5/homework/solution/UITutorialCompleted/Library/PackageCache/com.unity.test-framework@1.1.16/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/StadiaPlatformSetup.cs<|end_filename|> namespace UnityEditor.TestTools.TestRunner { internal class StadiaPlatformSetup : IPlatformSetup { public void Setup() { } public void PostBuildAction() { } public void PostSuccessfulBuildAction() { } public void PostSuccessfulLaunchAction() { } public void CleanUp() { } } } <|start_filename|>GameDev/week5/homework/solution/UITutorialCompleted/Library/PackageCache/com.unity.test-framework@1.1.16/UnityEditor.TestRunner/TestLaunchers/PlatformSetup/UwpPlatformSetup.cs<|end_filename|> using System; namespace UnityEditor.TestTools.TestRunner { internal class UwpPlatformSetup : IPlatformSetup { private const string k_SettingsBuildConfiguration = "BuildConfiguration"; private bool m_InternetClientServer; private bool m_PrivateNetworkClientServer; public void Setup() { m_InternetClientServer = PlayerSettings.WSA.GetCapability(PlayerSettings.WSACapability.InternetClientServer); m_PrivateNetworkClientServer = PlayerSettings.WSA.GetCapability(PlayerSettings.WSACapability.PrivateNetworkClientServer); PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.InternetClientServer, true); PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.PrivateNetworkClientServer, true); // This setting is initialized only when Window Store App is selected from the Build Settings window, and // is typically an empty strings when running tests via UTR on the command-line. bool wsaSettingNotInitialized = string.IsNullOrEmpty(EditorUserBuildSettings.wsaArchitecture); // If WSA build settings aren't fully initialized or running from a build machine, specify a default build configuration. // Otherwise we can use the existing configuration specified by the user in Build Settings. if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("UNITY_THISISABUILDMACHINE")) || wsaSettingNotInitialized) { EditorUserBuildSettings.wsaSubtarget = WSASubtarget.PC; EditorUserBuildSettings.wsaArchitecture = "x64"; EditorUserBuildSettings.SetPlatformSettings(BuildPipeline.GetBuildTargetName(BuildTarget.WSAPlayer), k_SettingsBuildConfiguration, WSABuildType.Debug.ToString()); EditorUserBuildSettings.wsaUWPBuildType = WSAUWPBuildType.ExecutableOnly; PlayerSettings.SetIl2CppCompilerConfiguration(BuildTargetGroup.WSA, Il2CppCompilerConfiguration.Debug); } } public void PostBuildAction() { } public void PostSuccessfulBuildAction() { } public void PostSuccessfulLaunchAction() { } public void CleanUp() { PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.InternetClientServer, m_InternetClientServer); PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.PrivateNetworkClientServer, m_PrivateNetworkClientServer); } } } <|start_filename|>GameDev/week5/homework/solution/UITutorialCompleted/Library/PackageCache/com.unity.test-framework@1.1.16/UnityEditor.TestRunner/TestRunner/Callbacks/WindowResultUpdater.cs<|end_filename|> using System.Linq; using TestRunner.Callbacks; using UnityEditor.TestTools.TestRunner.Api; namespace UnityEditor.TestTools.TestRunner.GUI { internal class WindowResultUpdater : ICallbacks, ITestTreeRebuildCallbacks { public WindowResultUpdater() { var cachedResults = WindowResultUpdaterDataHolder.instance.CachedResults; var testList = TestRunnerWindow.s_Instance.m_SelectedTestTypes; foreach (var result in cachedResults) { testList.UpdateResult(result); } cachedResults.Clear(); } public void RunStarted(ITestAdaptor testsToRun) { } public void RunFinished(ITestResultAdaptor testResults) { if (TestRunnerWindow.s_Instance != null) { TestRunnerWindow.s_Instance.RebuildUIFilter(); } } public void TestStarted(ITestAdaptor testName) { } public void TestFinished(ITestResultAdaptor test) { var result = new TestRunnerResult(test); if (TestRunnerWindow.s_Instance == null) { WindowResultUpdaterDataHolder.instance.CachedResults.Add(result); return; } TestRunnerWindow.s_Instance.m_SelectedTestTypes.UpdateResult(result); } public void TestTreeRebuild(ITestAdaptor test) { if (TestRunnerWindow.s_Instance == null) { return; } TestRunnerWindow.s_Instance.m_SelectedTestTypes.UpdateTestTree(test); } } } <|start_filename|>GameDev/week5/homework/solution/UITutorialCompleted/Library/PackageCache/com.unity.test-framework@1.1.16/UnityEngine.TestRunner/TestRunner/TestRunnerFilter.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.IO; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Filters; using UnityEngine.TestRunner.NUnitExtensions.Filters; namespace UnityEngine.TestTools.TestRunner.GUI { [Serializable] internal class TestRunnerFilter { #pragma warning disable 649 public string[] assemblyNames; public string[] groupNames; public string[] categoryNames; public static TestRunnerFilter empty = new TestRunnerFilter(); public string[] testNames; public int testRepetitions = 1; public bool synchronousOnly = false; public static string AssemblyNameFromPath(string path) { string output = Path.GetFileName(path); if (output != null && output.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) return output.Substring(0, output.Length - 4); return output; } private bool CategoryMatches(IEnumerable<string> categories) { if (categoryNames == null || categoryNames.Length == 0) return true; foreach (string category in categories) { if (categoryNames.Contains(category)) return true; } return false; } private bool IDMatchesAssembly(string id) { if (AreOptionalFiltersEmpty()) return true; if (assemblyNames == null || assemblyNames.Length == 0) return true; int openingBracket = id.IndexOf('['); int closingBracket = id.IndexOf(']'); if (openingBracket >= 0 && openingBracket < id.Length && closingBracket > openingBracket && openingBracket < id.Length) { //Some assemblies are absolute and explicitly part of the test ID e.g. //"[/path/to/assembly-name.dll][rest of ID ...]" //While some are minimal assembly names e.g. //"[assembly-name][rest of ID ...]" //Strip them down to just the assembly name string assemblyNameFromID = AssemblyNameFromPath(id.Substring(openingBracket + 1, closingBracket - openingBracket - 1)); foreach (string assemblyName in assemblyNames) { if (assemblyName.Equals(assemblyNameFromID, StringComparison.OrdinalIgnoreCase)) return true; } } return false; } private bool NameMatches(string name) { if (AreOptionalFiltersEmpty()) return true; if (groupNames == null || groupNames.Length == 0) return true; foreach (var nameFromFilter in groupNames) { //Strict regex match for test group name on its own if (Regex.IsMatch(name, nameFromFilter)) return true; //Match test names that end with parametrized test values and full nunit generated test names that have . separators var regex = nameFromFilter.TrimEnd('$') + @"[\.|\(.*\)]"; if (Regex.IsMatch(name, regex)) return true; } return false; } private bool AreOptionalFiltersEmpty() { if (assemblyNames != null && assemblyNames.Length != 0) return false; if (groupNames != null && groupNames.Length != 0) return false; if (testNames != null && testNames.Length != 0) return false; return true; } private bool NameMatchesExactly(string name) { if (AreOptionalFiltersEmpty()) return true; if (testNames == null || testNames.Length == 0) return true; foreach (var exactName in testNames) { if (name == exactName) return true; } return false; } private static void ClearAncestors(IEnumerable<IClearableResult> newResultList, string parentID) { if (string.IsNullOrEmpty(parentID)) return; foreach (var result in newResultList) { if (result.Id == parentID) { result.Clear(); ClearAncestors(newResultList, result.ParentId); break; } } } public void ClearResults(List<IClearableResult> newResultList) { foreach (var result in newResultList) { if (!result.IsSuite && CategoryMatches(result.Categories)) { if (IDMatchesAssembly(result.Id) && NameMatches(result.FullName) && NameMatchesExactly(result.FullName)) { result.Clear(); ClearAncestors(newResultList, result.ParentId); } } } } public ITestFilter BuildNUnitFilter() { var filters = new List<ITestFilter>(); if (testNames != null && testNames.Length != 0) { var nameFilter = new OrFilter(testNames.Select(n => new FullNameFilter(n)).ToArray()); filters.Add(nameFilter); } if (groupNames != null && groupNames.Length != 0) { var exactNamesFilter = new OrFilter(groupNames.Select(n => { var f = new FullNameFilter(n); f.IsRegex = true; return f; }).ToArray()); filters.Add(exactNamesFilter); } if (assemblyNames != null && assemblyNames.Length != 0) { var assemblyFilter = new OrFilter(assemblyNames.Select(c => new AssemblyNameFilter(c)).ToArray()); filters.Add(assemblyFilter); } if (categoryNames != null && categoryNames.Length != 0) { var categoryFilter = new OrFilter(categoryNames.Select(c => new CategoryFilterExtended(c) {IsRegex = true}).ToArray()); filters.Add(categoryFilter); } if (synchronousOnly) { filters.Add(new SynchronousFilter()); } return filters.Count == 0 ? TestFilter.Empty : new AndFilter(filters.ToArray()); } internal interface IClearableResult { string Id { get; } string FullName { get; } string ParentId { get; } bool IsSuite { get; } List<string> Categories { get; } void Clear(); } } } <|start_filename|>GameDev/week5/homework/solution/UITutorialCompleted/Library/PackageCache/com.unity.test-framework@1.1.16/UnityEditor.TestRunner/TestLaunchers/DelayedCallback.cs<|end_filename|> namespace UnityEditor.TestTools.TestRunner { internal class DelayedCallback { private System.Action m_Callback; private double m_CallbackTime; private double m_Delay; public DelayedCallback(System.Action function, double timeFromNow) { m_Callback = function; m_CallbackTime = EditorApplication.timeSinceStartup + timeFromNow; m_Delay = timeFromNow; EditorApplication.update += Update; } public void Clear() { EditorApplication.update -= Update; m_CallbackTime = 0.0; m_Callback = null; } private void Update() { if (EditorApplication.timeSinceStartup > m_CallbackTime) { // Clear state before firing callback to ensure reset (callback could call ExitGUI) var callback = m_Callback; Clear(); callback?.Invoke(); } } public void Reset() { if (m_Callback != null) { m_CallbackTime = EditorApplication.timeSinceStartup + m_Delay; } } } } <|start_filename|>GameDev/week5/homework/solution/UITutorialCompleted/Library/PackageCache/com.unity.test-framework@1.1.16/UnityEditor.TestRunner/TestRunner/EnumeratorStepHelper.cs<|end_filename|> using System.Collections; using System.Reflection; namespace UnityEditor.TestTools.TestRunner { internal class EnumeratorStepHelper { private static int m_PC; public static void SetEnumeratorPC(int pc) { m_PC = pc; } /// <summary> /// Gets the current enumerator PC /// </summary> /// <returns> /// The PC /// 0 if no current Enumeration /// </returns> public static int GetEnumeratorPC(IEnumerator enumerator) { if (enumerator == null) { return 0; } return (int)GetPCFieldInfo(enumerator).GetValue(enumerator); } public static bool UpdateEnumeratorPcIfNeeded(IEnumerator enumerator) { if (m_PC != 0) { GetPCFieldInfo(enumerator).SetValue(enumerator, m_PC); m_PC = 0; return true; } return false; } private static FieldInfo GetPCFieldInfo(IEnumerator enumerator) { var field = enumerator.GetType().GetField("$PC", BindingFlags.NonPublic | BindingFlags.Instance); if (field == null) // Roslyn field = enumerator.GetType().GetField("<>1__state", BindingFlags.NonPublic | BindingFlags.Instance); return field; } } }
MinyMeep1/BitCamp
<|start_filename|>node_modules/react-group/index.js<|end_filename|> var React = require('react'); var PropTypes = require('prop-types'); /** * React component to render collection of items separated by space or other separator. * * @visibleName React Group */ function Group(props) { var children = React.Children.toArray(props.children).filter(Boolean); if (children.length === 1) { return children; } // Insert separators var separator = props.separator; var separatorIsElement = React.isValidElement(separator); var items = [children.shift()]; children.forEach(function(item, index) { if (separatorIsElement) { var key = 'separator-' + (item.key || index); separator = React.cloneElement(separator, { key: key }); } items.push(separator, item); }); return items; } Group.propTypes = { /** Items */ children: PropTypes.node, /** Custom separator (space by default) */ separator: PropTypes.node, }; Group.defaultProps = { separator: ' ', }; module.exports = Group; <|start_filename|>node_modules/q-i/index.js<|end_filename|> 'use strict'; const isPlainObject = require('is-plain-object'); const stringifyObject = require('stringify-object'); const ansi = require('ansi-styles'); const internals = ['Array', 'Object', 'Function']; const style = (v, s) => `${ansi[s].open}${v}${ansi[s].close}`; const color = (v, c) => `${ansi.color[c].open}${v}${ansi.color.close}`; const getArraySize = o => Array.isArray(o) && o.length; const getObjectSize = o => isPlainObject(o) && Object.keys(o).length; const getFunctionSize = o => typeof o === 'function' && o.toString().split('\n').length; const getConstructor = v => { if (v === null) { return 'Null'; } if (v === undefined) { return 'Undefined'; } return v.constructor && v.constructor.name; }; const printers = { Null: v => style(v, 'italic'), Undefined: v => style(v, 'italic'), Boolean: v => color(v, 'magenta'), Number: v => color(v, 'cyan'), String: v => color(v, 'green'), RegExp: v => color(v, 'yellow'), }; function stringify(object, options) { const maxItems = (options && options.maxItems) || 30; const maxLines = (options && options.maxLines) || 1; return stringifyObject(object, { indent: ' ', transform: (obj, key, originalResult) => { const value = obj[key]; const arraySize = getArraySize(value); if (arraySize > maxItems) { return [key, style(`Array[${arraySize}]`, 'dim')]; } const objectSize = getObjectSize(value); if (objectSize > maxItems) { return style(`Object {${objectSize}}`, 'dim'); } const functionSize = getFunctionSize(value); if (functionSize > maxLines) { return style(`Function ${value.name || ''}`, 'dim'); } const ctr = getConstructor(value); if (printers[ctr]) { return printers[ctr](originalResult); } if (ctr && internals.indexOf(ctr) === -1) { return `${ctr} ${originalResult}`; } return originalResult; }, }); } function print(object, options) { // eslint-disable-next-line no-console console.log(stringify(object, options)); } module.exports = { print, stringify, };
401-advanced-javascript-hanna-alemu/lab-33-context-Api
<|start_filename|>src/main/java/de/fuberlin/wiwiss/pubby/sources/FilteredDataSource.java<|end_filename|> package de.fuberlin.wiwiss.pubby.sources; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.Resource; import de.fuberlin.wiwiss.pubby.ModelUtil; /** * A {@link DataSource} that wraps another data source in such a way * that the resulting data source is only capable of describing a * subset of the IRI space. This is usually done for performance, to * prevent the underlying data source from attempting to describe resources * that we know it doesn't have anything of value about. */ public abstract class FilteredDataSource implements DataSource { private final DataSource wrapped; public FilteredDataSource(DataSource wrapped) { this.wrapped = wrapped; } /** * Determines whether a given IRI is considered to be described in the * wrapped data source or not. * * @param absoluteIRI Any syntactically valid IRI * @return <code>true</code> if that IRI is described in the data source */ public abstract boolean canDescribe(String absoluteIRI); @Override public Model describeResource(String iri) { if (!canDescribe(iri)) return ModelUtil.EMPTY_MODEL; return wrapped.describeResource(iri); } @Override public Map<Property, Integer> getHighIndegreeProperties(String resourceIRI) { if (!canDescribe(resourceIRI)) return null; return wrapped.getHighIndegreeProperties(resourceIRI); } @Override public Map<Property, Integer> getHighOutdegreeProperties(String resourceIRI) { if (!canDescribe(resourceIRI)) return null; return wrapped.getHighOutdegreeProperties(resourceIRI); } @Override public Model listPropertyValues(String resourceIRI, Property property, boolean isInverse) { if (!canDescribe(resourceIRI)) return ModelUtil.EMPTY_MODEL; return wrapped.listPropertyValues(resourceIRI, property, isInverse); } @Override public List<Resource> getIndex() { List<Resource> result = new ArrayList<Resource>(); for (Resource r: wrapped.getIndex()) { if (canDescribe(r.getURI())) { result.add(r); } } return result; } } <|start_filename|>src/main/java/de/fuberlin/wiwiss/pubby/servlets/PageURLServlet.java<|end_filename|> package de.fuberlin.wiwiss.pubby.servlets; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.velocity.context.Context; import de.fuberlin.wiwiss.pubby.Configuration; import de.fuberlin.wiwiss.pubby.HypermediaControls; import de.fuberlin.wiwiss.pubby.ResourceDescription; /** * A servlet for serving the HTML page describing a resource. * Invokes a Velocity template. */ public class PageURLServlet extends BaseServlet { public boolean doGet(String relativeURI, HttpServletRequest request, HttpServletResponse response, Configuration config) throws ServletException, IOException { HypermediaControls controller = config.getControls(relativeURI, false); if (controller == null) return false; ResourceDescription description = controller.getResourceDescription(); if (description == null) return false; VelocityHelper template = new VelocityHelper(getServletContext(), response); Context context = template.getVelocityContext(); context.put("project_name", config.getProjectName()); context.put("project_link", config.getProjectLink()); context.put("uri", description.getURI()); context.put("server_base", config.getWebApplicationBaseURI()); context.put("rdf_link", controller.getDataURL()); context.put("title", description.getTitle()); context.put("comment", description.getComment()); context.put("image", description.getImageURL()); context.put("properties", description.getProperties()); context.put("showLabels", config.showLabels()); addPageMetadata(context, controller, description.getModel()); template.renderXHTML("page.vm"); return true; } private static final long serialVersionUID = 3363621132360159793L; } <|start_filename|>src/main/java/de/fuberlin/wiwiss/pubby/vocab/CONF.java<|end_filename|> package de.fuberlin.wiwiss.pubby.vocab; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.Resource; public class CONF { public static final String NS = "http://richard.cyganiak.de/2007/pubby/config.rdf#"; private static final Model m = ModelFactory.createDefaultModel(); public static final Resource Configuration = m.createResource(NS + "Configuration"); // Configuration properties public static final Property projectName = m.createProperty(NS + "projectName"); public static final Property projectHomepage = m.createProperty(NS + "projectHomepage"); public static final Property webBase = m.createProperty(NS + "webBase"); public static final Property usePrefixesFrom = m.createProperty(NS + "usePrefixesFrom"); public static final Property labelProperty = m.createProperty(NS + "labelProperty"); public static final Property commentProperty = m.createProperty(NS + "commentProperty"); public static final Property imageProperty = m.createProperty(NS + "imageProperty"); public static final Property defaultLanguage = m.createProperty(NS + "defaultLanguage"); public static final Property indexResource = m.createProperty(NS + "indexResource"); public static final Property dataset = m.createProperty(NS + "dataset"); public static final Property showLabels = m.createProperty(NS + "showLabels"); public static final Property loadVocabulary = m.createProperty(NS + "loadVocabulary"); // Dataset subclasses public static final Resource AnnotationProvider = m.createResource(NS + "AnnotationProvider"); // Dataset properties public static final Property datasetBase = m.createProperty(NS + "datasetBase"); public static final Property datasetURIPattern = m.createProperty(NS + "datasetURIPattern"); public static final Property webResourcePrefix = m.createProperty(NS + "webResourcePrefix"); public static final Property supportsIRIs = m.createProperty(NS + "supportsIRIs"); public static final Property addSameAsStatements = m.createProperty(NS + "addSameAsStatements"); public static final Property sparqlEndpoint = m.createProperty(NS + "sparqlEndpoint"); public static final Property sparqlDefaultGraph = m.createProperty(NS + "sparqlDefaultGraph"); public static final Property supportsSPARQL11 = m.createProperty(NS + "supportsSPARQL11"); public static final Property loadRDF = m.createProperty(NS + "loadRDF"); public static final Property rdfDocumentMetadata = m.createProperty(NS + "rdfDocumentMetadata"); public static final Property metadataTemplate = m.createProperty(NS + "metadataTemplate"); public static final Property contentType = m.createProperty(NS + "contentType"); public static final Property resourceDescriptionQuery = m.createProperty(NS + "resourceDescriptionQuery"); public static final Property propertyListQuery = m.createProperty(NS + "propertyListQuery"); public static final Property inversePropertyListQuery = m.createProperty(NS + "inversePropertyListQuery"); public static final Property anonymousPropertyDescriptionQuery = m.createProperty(NS + "anonymousPropertyDescriptionQuery"); public static final Property anonymousInversePropertyDescriptionQuery = m.createProperty(NS + "anonymousInversePropertyDescriptionQuery"); public static final Property browsableNamespace = m.createProperty(NS + "browsableNamespace"); public static final Property queryParamSelect = m.createProperty(NS + "queryParamSelect"); public static final Property queryParamGraph = m.createProperty(NS + "queryParamGraph"); // Terms to annotate vocabulary public static final Property weight = m.createProperty(NS + "weight"); public static final Property pluralLabel = m.createProperty(NS + "pluralLabel"); public static final Resource HighOutdregreeProperty = m.createResource(NS + "HighOutdegreeProperty"); public static final Resource HighIndregreeProperty = m.createResource(NS + "HighIndegreeProperty"); } <|start_filename|>src/main/java/de/fuberlin/wiwiss/pubby/PubbyIRIEscaper.java<|end_filename|> package de.fuberlin.wiwiss.pubby; /** * IRI rewriter that implements special behaviour for Pubby: Any IRI * within a certain namespace (the namespace that Pubby is serving) * will have characters that interfer with IRI derferencing %-escaped. * Any IRI outside that namespace is left alone. The escaped characters * are '#' and '?'. * * This rewriter can also encode URIs to IRIs as part of the rewriting * process. Pubby always wants to work on IRIs. Most data sources use * IRIs. Some don't, and all characters outside US-ASCII appear %-encoded * in their IRIs. If configured to encode URIs to IRIs, then in the rewritten * identifiers we will see proper Unicode characters instead of %-encoded * sequences. Note that we do this only within the namespace. * * TODO: The URI-to-IRI rewriting should probably be a separate class. */ public class PubbyIRIEscaper extends IRIRewriter { private final String namespace; private final boolean encodeURIsToIRIs; public PubbyIRIEscaper(String namespace, boolean encodeURIsToIRIs) { this.namespace = namespace; this.encodeURIsToIRIs = encodeURIsToIRIs; } @Override public String rewrite(String absoluteIRI) { if (absoluteIRI.startsWith(namespace)) { if (encodeURIsToIRIs) { // absoluteIRI is really a URI absoluteIRI = IRIEncoder.toIRI(absoluteIRI); } return escapeSpecialCharacters(absoluteIRI); } return absoluteIRI; } @Override public String unrewrite(String absoluteIRI) { if (absoluteIRI.startsWith(namespace)) { if (encodeURIsToIRIs) { absoluteIRI = IRIEncoder.toURI(absoluteIRI); // It's now really a URI, not an IRI } return unescapeSpecialCharacters(absoluteIRI); } return absoluteIRI; } /** * Escapes any characters that have special meaning in IRIs so that * they are safe for use in a Pubby path */ public static String escapeSpecialCharacters(String absoluteIRI) { return absoluteIRI.replace("#", "%23").replace("?", "%3F"); } /** * Reverses the escaping done by {@link #unescapeSpecialCharacters(String)}. */ public static String unescapeSpecialCharacters(String absoluteIRI) { return absoluteIRI.replace("%23", "#").replace("%3F", "?"); } } <|start_filename|>src/main/java/de/fuberlin/wiwiss/pubby/vocab/META.java<|end_filename|> package de.fuberlin.wiwiss.pubby.vocab; public class META { public static final String NS = "http://example.org/metadata#"; } <|start_filename|>src/main/java/de/fuberlin/wiwiss/pubby/URIPrefixer.java<|end_filename|> package de.fuberlin.wiwiss.pubby; import java.util.Iterator; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.ResourceFactory; import com.hp.hpl.jena.shared.PrefixMapping; /** * Helper class that splits URIs into prefix and local name * according to a Jena PrefixMapping. */ public class URIPrefixer { private final Resource resource; private final String prefix; private final String localName; public URIPrefixer(String uri, PrefixMapping prefixes) { this(ResourceFactory.createResource(uri), prefixes); } public URIPrefixer(Resource resource, PrefixMapping prefixes) { this.resource = resource; String uri = resource.getURI(); Iterator<String> it = prefixes.getNsPrefixMap().keySet().iterator(); while (it.hasNext() && uri != null) { String entryPrefix = it.next(); String entryURI = prefixes.getNsPrefixURI(entryPrefix); if (uri.startsWith(entryURI)) { prefix = entryPrefix; localName = uri.substring(entryURI.length()); return; } } prefix = null; localName = null; } public boolean hasPrefix() { return prefix != null; } public String getPrefix() { return prefix; } public String getLocalName() { if (resource.isAnon()) return null; if (localName == null) { Matcher matcher = Pattern.compile("([^#/:?]+)[#/:?]*$").matcher(resource.getURI()); if (matcher.find()) { return matcher.group(1); } return ""; // Only happens if the URI contains only excluded chars } return localName; } public String toTurtle() { if (resource.isAnon()) return "[]"; if (hasPrefix()) { return getPrefix() + ":" + getLocalName(); } return "<" + resource.getURI() + ">"; } } <|start_filename|>src/main/java/de/fuberlin/wiwiss/pubby/servlets/RootServlet.java<|end_filename|> package de.fuberlin.wiwiss.pubby.servlets; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import de.fuberlin.wiwiss.pubby.Configuration; import de.fuberlin.wiwiss.pubby.HypermediaControls; import de.fuberlin.wiwiss.pubby.IRIEncoder; /** * A catch-all servlet managing the URI space of the web application. */ public class RootServlet extends BaseServlet { private static final long serialVersionUID = -4812044304620174504L; protected boolean doGet(String relativeURI, HttpServletRequest request, HttpServletResponse response, Configuration config) throws IOException, ServletException { // static/ directory handled by default servlet if (relativeURI.startsWith("static/")) { getServletContext().getNamedDispatcher("default").forward(request, response); return true; } // Older versions of Pubby used to have /pathpage and /pathdata, // more limited versions of what is now /values and /values.data. // 301-redirect the old locations to the new ones. Matcher m = Pattern.compile("^(pathpage|pathdata)(/.*)$").matcher(relativeURI); if (m.matches()) { String valuesURL = config.getWebApplicationBaseURI() + ("pathpage".equals(m.group(1)) ? "values" : "values.data") + m.group(2); response.setStatus(301); response.sendRedirect(IRIEncoder.toURI(valuesURL)); return true; } // Homepage. if ("".equals(relativeURI)) { // Get the URL where a description of the index resource may be found String indexURL = HypermediaControls.createFromIRI(config.getIndexIRI(), config).getBrowsableURL(); if (!config.getWebApplicationBaseURI().equals(indexURL)) { // We need to redirect to the URL response.sendRedirect(IRIEncoder.toURI(indexURL)); return true; } } // Assume it's a resource URI -- will produce 404 if not getServletContext().getNamedDispatcher("WebURIServlet").forward(request, response); return true; } } <|start_filename|>src/main/java/de/fuberlin/wiwiss/pubby/servlets/RequestParamHandler.java<|end_filename|> package de.fuberlin.wiwiss.pubby.servlets; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Vector; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; /** * Analyzes an HttpServletRequest to check for the presence * of an ?output=n3 or =ttl or =rdfxml request parameter in * the URI. If present, returns a modified HttpServletRequest * that has the appropriate MIME type in the Accept: header. * This request can then be fed into the rest of our content * negotiation based tooling. */ public class RequestParamHandler { private static final String ATTRIBUTE_NAME_IS_HANDLED = "OutputRequestParamHandler.isHandled"; private final static Map<String,String> mimeTypes = new HashMap<String,String>(); static { mimeTypes.put("rdfxml", "application/rdf+xml"); mimeTypes.put("xml", "application/rdf+xml"); // Explicitly asking for output=turtle will still return // the N3 media type because browsers tend to *display* // text/* media types, while they tend to *download* // application/* media types. Displaying serves users better, // so we report the content as N3 even though it actually is // Turtle. mimeTypes.put("ttl", "text/rdf+n3;charset=utf-8"); mimeTypes.put("turtle", "text/rdf+n3;charset=utf-8"); // mimeTypes.put("turtle", "application/x-turtle"); // mimeTypes.put("ttl", "application/x-turtle"); mimeTypes.put("n3", "text/rdf+n3;charset=utf-8"); mimeTypes.put("nt", "text/plain"); mimeTypes.put("text", "text/plain"); } /** * Removes the "output=foobar" part of a URI if present. */ public static String removeOutputRequestParam(String uri) { // Remove the param: output=[a-z0-9]* // There are two cases. The param can occur at the end of the URI, // this is matched by the first part: [?&]param$ // Or it can occur elsewhere, then it's matched by param& with a // lookbehind that requires [?&] to occur before the pattern. return uri.replaceFirst("([?&]output=[a-z0-9]*$)|((?<=[?&])output=[a-z0-9]*&)", ""); } private final HttpServletRequest request; private final String requestedType; public RequestParamHandler(HttpServletRequest request) { this.request = request; requestedType = identifyRequestedType(request.getParameter("output")); } public boolean isMatchingRequest() { if ("true".equals(request.getAttribute(ATTRIBUTE_NAME_IS_HANDLED))) { return false; } return requestedType != null; } public HttpServletRequest getModifiedRequest() { return new WrappedRequest(); } private String identifyRequestedType(String parameterValue) { if (mimeTypes.containsKey(parameterValue)) { return parameterValue; } return null; } @SuppressWarnings("rawtypes") // The API uses raw types private class WrappedRequest extends HttpServletRequestWrapper { WrappedRequest() { super(request); setAttribute(ATTRIBUTE_NAME_IS_HANDLED, "true"); } @Override public String getHeader(String name) { if ("accept".equals(name.toLowerCase())) { return (String) mimeTypes.get(requestedType); } return super.getHeader(name); } @Override public Enumeration getHeaderNames() { final Enumeration realHeaders = super.getHeaderNames(); return new Enumeration() { private String prefetched = null; public boolean hasMoreElements() { while (prefetched == null && realHeaders.hasMoreElements()) { String next = (String) realHeaders.nextElement(); if (!"accept".equals(next.toLowerCase())) { prefetched = next; } } return (prefetched != null); } public Object nextElement() { return prefetched; } }; } @Override public Enumeration getHeaders(String name) { if ("accept".equals(name.toLowerCase())) { Vector<Object> v = new Vector<Object>(); v.add(getHeader(name)); return v.elements(); } return super.getHeaders(name); } } } <|start_filename|>src/main/java/de/fuberlin/wiwiss/pubby/servlets/WebURIServlet.java<|end_filename|> package de.fuberlin.wiwiss.pubby.servlets; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import de.fuberlin.wiwiss.pubby.Configuration; import de.fuberlin.wiwiss.pubby.HypermediaControls; import de.fuberlin.wiwiss.pubby.IRIEncoder; import de.fuberlin.wiwiss.pubby.negotiation.ContentTypeNegotiator; import de.fuberlin.wiwiss.pubby.negotiation.MediaRangeSpec; import de.fuberlin.wiwiss.pubby.negotiation.PubbyNegotiator; /** * Servlet that handles the public URIs of mapped resources. * It redirects either to the page URL or to the data URL, * based on content negotiation. * * TODO: This should provide only a 303 service. The conneg stuff should happen in new generic versions of the representation-producing servlets. */ public class WebURIServlet extends BaseServlet { public boolean doGet(String relativeURI, HttpServletRequest request, HttpServletResponse response, Configuration config) throws IOException { HypermediaControls controller = config.getControls(relativeURI, true); // It's a resource with an IRI we can't handle if (controller == null) return false; // It's a resource that's not in our namespace. // We don't provide a 303 service for those, only browsable pages. if (!controller.isHosted()) return false; response.addHeader("Vary", "Accept, User-Agent"); ContentTypeNegotiator negotiator = PubbyNegotiator.getPubbyNegotiator(); MediaRangeSpec bestMatch = negotiator.getBestMatch( request.getHeader("Accept"), request.getHeader("User-Agent")); if (bestMatch == null) { response.setStatus(406); response.setContentType("text/plain"); response.getOutputStream().println( "406 Not Acceptable: The requested data format is not supported. " + "Only HTML and RDF are available."); return true; } response.setStatus(303); response.setContentType("text/plain"); String location; if ("text/html".equals(bestMatch.getMediaType())) { location = controller.getPageURL(); } else { location = controller.getDataURL(); } response.addHeader("Location", IRIEncoder.toURI(location)); response.getOutputStream().println( "303 See Other: For a description of this item, see " + location); return true; } private static final long serialVersionUID = 3797268342314917283L; } <|start_filename|>src/main/java/de/fuberlin/wiwiss/pubby/ResourceDescription.java<|end_filename|> package de.fuberlin.wiwiss.pubby; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.shared.PrefixMapping; import com.hp.hpl.jena.shared.impl.PrefixMappingImpl; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.XSD; import de.fuberlin.wiwiss.pubby.VocabularyStore.CachedPropertyCollection; /** * A convenient interface to an RDF description of a resource. * Provides access to its label, a textual comment, detailed * representations of its properties, and so on. * * TODO: Sort out who constructs these. Perhaps only the data source and this class itself should? */ public class ResourceDescription { private final static int HIGH_DEGREE_CUTOFF = 10; private final HypermediaControls hypermediaResource; private final Model model; private final Resource resource; private final Configuration config; private final Map<Property, Integer> highIndegreeProperties; private final Map<Property, Integer> highOutdegreeProperties; private PrefixMapping prefixes = null; private List<ResourceProperty> properties = null; public ResourceDescription(HypermediaControls controller, Model model, Configuration config) { this(controller, model, null, null, config, false); } public ResourceDescription(HypermediaControls controller, Model model, Map<Property, Integer> highIndegreeProperties, Map<Property, Integer> highOutdegreeProperties, Configuration config) { this(controller, model, highIndegreeProperties, highOutdegreeProperties, config, true); } private ResourceDescription(HypermediaControls controller, Model model, Map<Property, Integer> highIndegreeProperties, Map<Property, Integer> highOutdegreeProperties, Configuration config, boolean learnHighDegreeProps) { this.hypermediaResource = controller; this.model = model; this.resource = model.getResource(controller.getAbsoluteIRI()); this.config = config; this.highIndegreeProperties = highIndegreeProperties == null ? Collections.<Property, Integer>emptyMap() : highIndegreeProperties; this.highOutdegreeProperties = highOutdegreeProperties == null ? Collections.<Property, Integer>emptyMap() : highOutdegreeProperties; if (learnHighDegreeProps) { learnHighDegreeProperties(true, HIGH_DEGREE_CUTOFF); learnHighDegreeProperties(false, HIGH_DEGREE_CUTOFF); } } private ResourceDescription(Resource resource, Model model, Configuration config) { this.hypermediaResource = null; this.model = model; this.resource = resource; this.config = config; this.highIndegreeProperties = Collections.<Property, Integer>emptyMap(); this.highOutdegreeProperties = Collections.<Property, Integer>emptyMap(); } public String getURI() { return resource.getURI(); } public Model getModel() { return model; } /** * If {@link #getLabel()} is non null, return the label. If it is null, * generate an attempt at a human-readable title from the URI. If the * resource is blank, return null. */ public String getTitle() { if (!resource.isResource()) return null; Literal l = getLabel(); String label = l == null ? null : l.getLexicalForm(); String lang = l == null ? null : l.getLanguage(); if (label == null) { label = new URIPrefixer(resource, getPrefixes()).getLocalName(); } if ("".equals(label)) { // Prefix mapping assigns an empty local name label = resource.getURI(); lang = null; } return toTitleCase(label, lang); } public Literal getLabel() { Collection<RDFNode> candidates = getValuesFromMultipleProperties(config.getLabelProperties()); return getBestLanguageMatch(candidates, config.getDefaultLanguage()); } public String getComment() { Collection<RDFNode> candidates = getValuesFromMultipleProperties(config.getCommentProperties()); Literal l = getBestLanguageMatch(candidates, config.getDefaultLanguage()); if (l == null) return null; return toSentenceCase(l.getLexicalForm(), l.getLanguage()); } public String getImageURL() { Collection<RDFNode> candidates = getValuesFromMultipleProperties(config.getImageProperties()); Iterator<RDFNode> it = candidates.iterator(); while (it.hasNext()) { RDFNode candidate = (RDFNode) it.next(); if (candidate.isURIResource()) { return ((Resource) candidate.as(Resource.class)).getURI(); } } return null; } public ResourceProperty getProperty(Property property, boolean isInverse) { for (ResourceProperty p: getProperties()) { if (p.getURI().equals(property.getURI()) && p.isInverse() == isInverse) { return p; } } return null; } public List<ResourceProperty> getProperties() { if (properties == null) { properties = buildProperties(); } return properties; } private List<ResourceProperty> buildProperties() { Map<String,PropertyBuilder> propertyBuilders = new HashMap<String,PropertyBuilder>(); StmtIterator it = resource.listProperties(); while (it.hasNext()) { Statement stmt = it.nextStatement(); if (isEmptyLiteral(stmt.getObject())) continue; Property predicate = stmt.getPredicate(); String key = "=>" + predicate; if (!propertyBuilders.containsKey(key)) { propertyBuilders.put(key, new PropertyBuilder( predicate, false, config.getVocabularyStore())); } // TODO: Should distinguish clearly here between adding a // simple value, adding a complex (inlined) value, and // omitting a value. But how to decide whether blank nodes // are omitted or included as complex value? The decision has // already been made earlier when the model was built. propertyBuilders.get(key).addValue(stmt.getObject()); } it = model.listStatements(null, null, resource); while (it.hasNext()) { Statement stmt = it.nextStatement(); Property predicate = stmt.getPredicate(); String key = "<=" + predicate; if (!propertyBuilders.containsKey(key)) { propertyBuilders.put(key, new PropertyBuilder( predicate, true, config.getVocabularyStore())); } // TODO: See TODO above propertyBuilders.get(key).addValue(stmt.getSubject()); } for (Property p: highIndegreeProperties.keySet()) { String key = "<=" + p; if (!propertyBuilders.containsKey(key)) { propertyBuilders.put(key, new PropertyBuilder( p, true, config.getVocabularyStore())); } propertyBuilders.get(key).addHighDegreeArcs(highIndegreeProperties.get(p)); } for (Property p: highOutdegreeProperties.keySet()) { String key = "=>" + p; if (!propertyBuilders.containsKey(key)) { propertyBuilders.put(key, new PropertyBuilder( p, false, config.getVocabularyStore())); } propertyBuilders.get(key).addHighDegreeArcs(highOutdegreeProperties.get(p)); } List<ResourceProperty> results = new ArrayList<ResourceProperty>(); Iterator<PropertyBuilder> it2 = propertyBuilders.values().iterator(); while (it2.hasNext()) { PropertyBuilder propertyBuilder = (PropertyBuilder) it2.next(); results.add(propertyBuilder.toProperty()); } Collections.sort(results); return results; } /** * Checks whether a node is an empty literal that should better be skipped. * The logic is that those literals are probably an error on the data * producer side and are best not shown to the user in HTML views. */ private boolean isEmptyLiteral(RDFNode node) { if (!node.isLiteral()) return false; Literal l = node.asLiteral(); if (l.getDatatypeURI() == null || l.getDatatypeURI().startsWith(RDF.getURI()) || l.getDatatypeURI().startsWith(XSD.getURI())) { if ("".equals(l.getLexicalForm())) return true; } return false; } /** * Returns a prefix mapping containing all prefixes from the input model * and from the configuration, with the configuration taking precedence. */ private PrefixMapping getPrefixes() { if (prefixes == null) { prefixes = new PrefixMappingImpl(); prefixes.setNsPrefixes(model); for (String prefix: config.getPrefixes().getNsPrefixMap().keySet()) { prefixes.setNsPrefix(prefix, config.getPrefixes().getNsPrefixURI(prefix)); } } return prefixes; } private Collection<RDFNode> getValuesFromMultipleProperties( Collection<Property> properties) { Collection<RDFNode> results = new ArrayList<RDFNode>(); Iterator<Property> it = properties.iterator(); while (it.hasNext()) { com.hp.hpl.jena.rdf.model.Property property = (com.hp.hpl.jena.rdf.model.Property) it.next(); StmtIterator labelIt = resource.listProperties(property); while (labelIt.hasNext()) { RDFNode label = labelIt.nextStatement().getObject(); results.add(label); } } return results; } // TODO: There is some better (?) code doing the same in VocabularyStore.I18nStringValueCache private Literal getBestLanguageMatch(Collection<RDFNode> nodes, String lang) { Iterator<RDFNode> it = nodes.iterator(); Literal aLiteral = null; while (it.hasNext()) { RDFNode candidate = it.next(); if (!candidate.isLiteral()) continue; Literal literal = candidate.asLiteral(); if (lang == null || lang.equals(literal.getLanguage())) { return literal; } aLiteral = literal; } return aLiteral; } public class ResourceProperty implements Comparable<ResourceProperty> { private final Property predicate; private final URIPrefixer predicatePrefixer; private final boolean isInverse; private final List<Value> simpleValues; private final List<ResourceDescription> complexValues; private final int omittedValues; private final VocabularyStore vocabularyStore; public ResourceProperty(Property predicate, boolean isInverse, List<Value> simpleValues, List<ResourceDescription> complexVaues, int omittedValues, VocabularyStore vocabularyStore) { this.predicate = predicate; this.predicatePrefixer = new URIPrefixer(predicate, getPrefixes()); this.isInverse = isInverse; this.simpleValues = simpleValues; this.complexValues = complexVaues; this.omittedValues = omittedValues; this.vocabularyStore = vocabularyStore; } public boolean isInverse() { return isInverse; } public String getURI() { return predicate.getURI(); } public String getBrowsableURL() { HypermediaControls controls = HypermediaControls.createFromIRI( predicate.getURI(), config); if (controls == null) return predicate.getURI(); return controls.getBrowsableURL(); } public boolean hasPrefix() { return predicatePrefixer.hasPrefix(); } public String getPrefix() { return predicatePrefixer.getPrefix(); } public String getLocalName() { return predicatePrefixer.getLocalName(); } public String getLabel() { return getLabel(isMultiValued()); } public String getLabel(boolean preferPlural) { Literal label = vocabularyStore.getLabel(predicate.getURI(), preferPlural); if (label == null) return null; return toTitleCase(label.getLexicalForm(), label.getLanguage()); } public String getInverseLabel() { return getInverseLabel(isMultiValued()); } public String getInverseLabel(boolean preferPlural) { Literal label = vocabularyStore.getInverseLabel(predicate.getURI(), preferPlural); if (label == null) return null; return toTitleCase(label.getLexicalForm(), label.getLanguage()); } /** * Note: This bypasses conf:showLabels, always assuming <code>true</code> * @return "Is Widget Of", "Widgets", "ex:widget", whatever is most appropriate */ public String getCompleteLabel() { if (isInverse && getInverseLabel() != null) { return getInverseLabel(); } String result; if (getLabel() != null) { result = getLabel(); } else if (hasPrefix()) { result = getPrefix() + ":" + getLocalName(); } else { result = "?:" + getLocalName(); } return isInverse ? "Is " + result + " of" : result; } public String getDescription() { return vocabularyStore.getDescription(predicate.getURI()).getLexicalForm(); } public List<Value> getSimpleValues() { return simpleValues; } public List<ResourceDescription> getComplexValues() { return complexValues; } public boolean hasOnlySimpleValues() { return omittedValues == 0 && complexValues.isEmpty(); } public int getValueCount() { return omittedValues + complexValues.size() + simpleValues.size(); } public boolean isMultiValued() { return simpleValues.size() + omittedValues + complexValues.size() > 1; } public String getValuesPageURL() { if (hypermediaResource == null) { return null; } return isInverse ? hypermediaResource.getInverseValuesPageURL(predicate) : hypermediaResource.getValuesPageURL(predicate); } public int compareTo(ResourceProperty other) { if (!(other instanceof ResourceProperty)) { return 0; } ResourceProperty otherProperty = (ResourceProperty) other; int myWeight = config.getVocabularyStore().getWeight( predicate, isInverse); int otherWeight = config.getVocabularyStore().getWeight( otherProperty.predicate, other.isInverse); if (myWeight < otherWeight) return -1; if (myWeight > otherWeight) return 1; String propertyLocalName = getLocalName(); String otherLocalName = otherProperty.getLocalName(); if (propertyLocalName.compareTo(otherLocalName) != 0) { return propertyLocalName.compareTo(otherLocalName); } if (this.isInverse() != otherProperty.isInverse()) { return (this.isInverse()) ? 1 : -1; } return 0; } } private class PropertyBuilder { private final Property predicate; private final boolean isInverse; private final List<Value> values = new ArrayList<Value>(); private final List<ResourceDescription> blankNodeDescriptions = new ArrayList<ResourceDescription>(); private int highDegreeArcCount = 0; private VocabularyStore vocabularyStore; PropertyBuilder(Property predicate, boolean isInverse, VocabularyStore vocabularyStore) { this.predicate = predicate; this.isInverse = isInverse; this.vocabularyStore = vocabularyStore; } void addValue(RDFNode valueNode) { if (valueNode.isAnon()) { blankNodeDescriptions.add(new ResourceDescription( valueNode.asResource(), getModel(), config)); return; } values.add(new Value(valueNode, predicate, vocabularyStore)); } void addHighDegreeArcs(int count) { highDegreeArcCount += count; } ResourceProperty toProperty() { Collections.sort(values); return new ResourceProperty(predicate, isInverse, values, blankNodeDescriptions, highDegreeArcCount, vocabularyStore); } } public class Value implements Comparable<Value> { private final RDFNode node; private URIPrefixer prefixer; private Property predicate; private VocabularyStore vocabularyStore; public Value(RDFNode valueNode, Property predicate, VocabularyStore vocabularyStore) { this.node = valueNode; this.predicate = predicate; this.vocabularyStore = vocabularyStore; if (valueNode.isURIResource()) { prefixer = new URIPrefixer((Resource) valueNode.as(Resource.class), getPrefixes()); } } public Node getNode() { return node.asNode(); } public String getBrowsableURL() { if (!node.isURIResource()) return null; HypermediaControls controls = HypermediaControls.createFromIRI( node.asResource().getURI(), config); if (controls == null) return node.asResource().getURI(); return controls.getPageURL(); } public boolean hasPrefix() { return prefixer != null && prefixer.hasPrefix(); } public String getPrefix() { if (prefixer == null) { return null; } return prefixer.getPrefix(); } public String getLocalName() { if (prefixer == null) { return null; } return prefixer.getLocalName(); } public String getLabel() { if (!node.isResource()) return null; Literal result = null; if (node.isURIResource()) { if (predicate.equals(RDF.type)) { // Look up class labels in vocabulary store result = vocabularyStore.getLabel(node.asNode().getURI(), false); } else if (node.isURIResource()) { // If it's not a class, see if we happen to have a label cached result = vocabularyStore.getCachedLabel(node.asResource().getURI(), false); } } if (result == null) { // Use any label that may be included in the description model result = new ResourceDescription(node.asResource(), model, config).getLabel(); } if (result == null) return null; return toTitleCase(result.getLexicalForm(), result.getLanguage()); } public String getDescription() { return vocabularyStore.getDescription(node.asNode().getURI()).getLexicalForm(); } public String getDatatypeLabel() { if (!node.isLiteral()) return null; String uri = ((Literal) node.as(Literal.class)).getDatatypeURI(); if (uri == null) return null; URIPrefixer datatypePrefixer = new URIPrefixer(uri, getPrefixes()); if (datatypePrefixer.hasPrefix()) { return datatypePrefixer.toTurtle(); } else { return "?:" + datatypePrefixer.getLocalName(); } } public boolean isType() { return predicate.equals(RDF.type); } public int compareTo(Value other) { if (!(other instanceof Value)) { return 0; } Value otherValue = (Value) other; if (getNode().isURI() && otherValue.getNode().isURI()) { return getNode().getURI().compareTo(otherValue.getNode().getURI()); } if (getNode().isURI()) { return 1; } if (otherValue.getNode().isURI()) { return -1; } if (getNode().isBlank() && otherValue.getNode().isBlank()) { return getNode().getBlankNodeLabel().compareTo(otherValue.getNode().getBlankNodeLabel()); } if (getNode().isBlank()) { return 1; } if (otherValue.getNode().isBlank()) { return -1; } // TODO Typed literals, language literals return getNode().getLiteralLexicalForm().compareTo(otherValue.getNode().getLiteralLexicalForm()); } } /** * Converts a string to Sentence Case. In our implementation, this simply * means the first letter is uppercased if it isn't already. Also trims * surrounding whitespace. */ public String toSentenceCase(String s, String lang) { if (s == null) return null; s = s.trim(); if ("".equals(s)) return null; return s.substring(0, 1).toUpperCase() + s.substring(1); } /** * Converts a string to Title Case. Also trims surrounding whitespace * and collapses consecutive whitespace characters within into a single * space. If the language is English or null, English rules are used. * Also splits CamelCase into separate words to better deal with poor labels. */ public String toTitleCase(String s, String lang) { if (s == null) return null; if (lang == null) { lang = config.getDefaultLanguage(); } s = camelCaseBoundaryPattern.matcher(s).replaceAll(" "); s = s.replace(" - ", " \u2013 "); Set<String> uncapitalizedWords = Collections.emptySet(); if (lang == null || "".equals(lang) || english.matcher(lang).matches()) { uncapitalizedWords = englishUncapitalizedWords; } StringBuffer result = new StringBuffer(); Matcher matcher = wordPattern.matcher(s); boolean first = true; int offset = 0; while (matcher.find()) { result.append(normalizeWhitespace( s.substring(offset, matcher.start()), first)); offset = matcher.end(); String word = matcher.group(); if ("".equals(word)) continue; if (first || !uncapitalizedWords.contains(word.toLowerCase())) { word = word.substring(0, 1).toUpperCase() + word.substring(1); } else { word = word.substring(0, 1).toLowerCase() + word.substring(1); } result.append(word); first = false; } result.append(normalizeWhitespace( s.substring(offset), true)); return result.toString(); } private static Pattern wordPattern = Pattern.compile("[^ \t\r\n-]+|"); private static Pattern camelCaseBoundaryPattern = Pattern.compile( "(?<=(\\p{javaLowerCase}|\\p{javaUpperCase})\\p{javaLowerCase})" + "(?=\\p{javaUpperCase})"); private static Pattern english = Pattern.compile("^en(-.*)?$", Pattern.CASE_INSENSITIVE); private static Set<String> englishUncapitalizedWords = new HashSet<String>(Arrays.asList( // Prepositions "above", "about", "across", "against", "along", "among", "around", "at", "before", "behind", "below", "beneath", "beside", "between", "beyond", "by", "down", "during", "except", "for", "from", "in", "inside", "into", "like", "near", "of", "off", "on", "since", "to", "toward", "through", "under", "until", "up", "upon", "with", "within", // Articles "a", "an", "the", // Conjunctions "and", "but", "for", "nor", "or", "so", "yet" )); private String normalizeWhitespace(String s, boolean squash) { s = s.replaceAll("[ \t\r\n]+", " "); if (squash && " ".equals(s)) return ""; return s; } private void learnHighDegreeProperties(boolean isInverse, int limit) { CachedPropertyCollection knownHighProps = isInverse ? config.getVocabularyStore().getHighIndegreeProperties() : config.getVocabularyStore().getHighOutdegreeProperties(); Map<Property, Integer> highCounts = isInverse ? highIndegreeProperties : highOutdegreeProperties; StmtIterator it = isInverse ? model.listStatements(null, null, resource) : resource.listProperties(); Map<Property, Integer> valueCounts = new HashMap<Property, Integer>(); while (it.hasNext()) { Property p = it.next().getPredicate(); if (!valueCounts.containsKey(p)) { valueCounts.put(p, 0); } valueCounts.put(p, valueCounts.get(p) + 1); } for (Property p: valueCounts.keySet()) { if (valueCounts.get(p) <= limit) continue; knownHighProps.reportAdditional(p); if (isInverse) { model.removeAll(null, p, resource); } else { resource.removeAll(p); } highCounts.put(p, valueCounts.get(p)); } } } <|start_filename|>src/main/java/de/fuberlin/wiwiss/pubby/ConfigurationException.java<|end_filename|> package de.fuberlin.wiwiss.pubby; public class ConfigurationException extends RuntimeException { public ConfigurationException(String message) { super(message); } private static final long serialVersionUID = -8983028379468516491L; } <|start_filename|>src/main/java/de/fuberlin/wiwiss/pubby/servlets/ValuesURLServlet.java<|end_filename|> package de.fuberlin.wiwiss.pubby.servlets; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.velocity.context.Context; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Property; import de.fuberlin.wiwiss.pubby.Configuration; import de.fuberlin.wiwiss.pubby.HypermediaControls; import de.fuberlin.wiwiss.pubby.ResourceDescription; import de.fuberlin.wiwiss.pubby.ResourceDescription.ResourceProperty; /** * A servlet for rendering an HTML page listing resources * related to a given resource via a given property. URIs and * literals are displayed as simple values. Blank nodes are * displayed as complete resource descriptions. */ public class ValuesURLServlet extends ValuesBaseServlet { public boolean doGet(HypermediaControls controller, Property predicate, boolean isInverse, HttpServletRequest request, HttpServletResponse response, Configuration config) throws IOException { ResourceDescription resource = controller.getResourceDescription(); if (resource == null) return false; Model descriptions = config.getDataSource().listPropertyValues( controller.getAbsoluteIRI(), predicate, isInverse); if (descriptions.isEmpty()) return false; ResourceProperty property = new ResourceDescription( controller, descriptions, config).getProperty(predicate, isInverse); if (property == null) return false; // Can happen if prefix is declared in URI space of a data source rather than in web space VelocityHelper template = new VelocityHelper(getServletContext(), response); Context context = template.getVelocityContext(); context.put("project_name", config.getProjectName()); context.put("project_link", config.getProjectLink()); context.put("uri", resource.getURI()); context.put("server_base", config.getWebApplicationBaseURI()); context.put("title", resource.getTitle()); context.put("head_title", resource.getTitle() + " \u00BB " + property.getCompleteLabel()); context.put("property", property); context.put("back_uri", controller.getBrowsableURL()); context.put("back_label", resource.getTitle()); context.put("rdf_link", isInverse ? controller.getInverseValuesDataURL(predicate) : controller.getValuesDataURL(predicate)); context.put("showLabels", config.showLabels()); addPageMetadata(context, controller, resource.getModel()); template.renderXHTML("valuespage.vm"); return true; } private static final long serialVersionUID = -2597664961896022667L; } <|start_filename|>src/main/java/de/fuberlin/wiwiss/pubby/servlets/ServletContextInitializer.java<|end_filename|> package de.fuberlin.wiwiss.pubby.servlets; import java.io.File; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.shared.JenaException; import com.hp.hpl.jena.util.FileManager; import de.fuberlin.wiwiss.pubby.Configuration; import de.fuberlin.wiwiss.pubby.ConfigurationException; public class ServletContextInitializer implements ServletContextListener { public final static String SERVER_CONFIGURATION = ServletContextInitializer.class.getName() + ".serverConfiguration"; public final static String ERROR_MESSAGE = ServletContextInitializer.class.getName() + ".errorMessage"; @Override public void contextInitialized(ServletContextEvent sce) { ServletContext context = sce.getServletContext(); try { String configFileName = context.getInitParameter("config-file"); if (configFileName == null) { throw new ConfigurationException("Missing context parameter \"config-file\" in /WEB-INF/web.xml"); } File configFile = new File(configFileName); if (!configFile.isAbsolute()) { configFile = new File(context.getRealPath("/") + "/WEB-INF/" + configFileName); } String url = configFile.getAbsoluteFile().toURI().toString(); try { Model m = FileManager.get().loadModel(url); Configuration conf = Configuration.create(m); context.setAttribute(SERVER_CONFIGURATION, conf); } catch (JenaException ex) { throw new ConfigurationException( "Error parsing configuration file <" + url + ">: " + ex.getMessage()); } } catch (ConfigurationException ex) { log(ex, context); } } @Override public void contextDestroyed(ServletContextEvent sce) { // Do nothing special. } private void log(Exception ex, ServletContext context) { context.log("######## PUBBY CONFIGURATION ERROR ######## "); context.log(ex.getMessage()); context.log("########################################### "); context.setAttribute(ERROR_MESSAGE, ex.getMessage()); } } <|start_filename|>src/main/java/de/fuberlin/wiwiss/pubby/IRIEncoder.java<|end_filename|> package de.fuberlin.wiwiss.pubby; import java.io.UnsupportedEncodingException; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Implements the IRI-to-URI and URI-to-IRI conversions defined in * RFC 3987. * * TODO: This really needs some unit tests * TODO: Make this an IRIRewriter? */ public class IRIEncoder { /** * Converts a URI to an IRI by removing unnecessary percent-encoding * of UTF-8 sequences. */ public static String toIRI(String uri) { StringBuffer decoded = new StringBuffer(); Matcher matcher = percentEncoding.matcher(uri); while (matcher.find()) { matcher.appendReplacement(decoded, decode(matcher.group())); } matcher.appendTail(decoded); return decoded.toString(); } private static final Pattern percentEncoding = Pattern.compile("(%[0-9a-fA-F][0-9a-fA-F])+"); /** * Converts an IRI to a URI by percent-encoding characters outside of * the US-ASCII range. */ public static String toURI(String iri) { try { StringBuffer encoded = new StringBuffer(); for (int i = 0; i < iri.length(); i++) { if ((int) iri.charAt(i) <= 128) { encoded.append(iri.charAt(i)); continue; } for (byte b: iri.substring(i, i + 1).getBytes("utf-8")) { appendOctet(encoded, b); } } return encoded.toString(); } catch (UnsupportedEncodingException ex) { // Can't happen return iri; } } private static char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; private static String decode(String percentEncoded) { StringBuffer decoded = new StringBuffer(); int[] octets = toBytes(percentEncoded); int i = 0; while (i < octets.length) { if (octets[i] <= 0x7F) { // US-ASCII character. Decode, except if it's one of // %, reserved, or not allowed in IRIs. In that case, re-encode. if (isUnreservedASCII((char) octets[i])) { decoded.append((char) octets[i]); } else { // FIXME: Strictly speaking, the spec says that the original // percent-encoding remains unchanged, meaning lower-case // hex digits would remain lower-case. We upper-case them // here by re-encoding. appendOctet(decoded, (byte) octets[i]); } i++; continue; } if (isContinuationOctet(octets[i])) { appendOctet(decoded, (byte) octets[i]); i++; continue; } int bytesInSequence = getBytesInSequence(octets[i]); if (i + bytesInSequence > octets.length) { // Not enough continuation bytes to complete the character. // Re-encode one byte, then let the main loop eat the rest. appendOctet(decoded, (byte) octets[i]); i++; continue; } // Next, check if the next n bytes are all continuation bytes. boolean enoughContinuationBytes = true; for (int j = 1; j < bytesInSequence; j++) { if (!isContinuationOctet(octets[i + j])) { // Nope enoughContinuationBytes = false; break; } } if (!enoughContinuationBytes) { // Re-encode one byte, and let the main loop eat the rest. appendOctet(decoded, (byte) octets[i]); i++; continue; } // UTF-8 encoding looks fine. Decode to one character. // FIXME: RFC 3987 says here: // 4. Re-percent-encode all octets produced in step 3 that in UTF-8 // represent characters that are not appropriate according to // sections 2.2, 4.1, and 6.1. // This is about weird unicode characters that are inappropriate // in IRIs for various reasons. We ignore this currently. decoded.append(toCharacter(octets, i, bytesInSequence)); i += bytesInSequence; } return decoded.toString(); } private static boolean isContinuationOctet(int octet) { return (octet & 0xC0) == 0x80; } private static void appendOctet(StringBuffer sb, byte octet) { sb.append('%'); sb.append(hexDigits[(octet >> 4) & 0x0F]); sb.append(hexDigits[octet & 0x0F]); } private static int getBytesInSequence(int octet) { // See table in http://en.wikipedia.org/wiki/UTF-8#Description if ((octet & 0x80) == 0) return 1; if ((octet & 0xC0) == 0x80) return 0; // Continuation octet if ((octet & 0xE0) == 0xC0) return 2; if ((octet & 0xF0) == 0xE0) return 3; if ((octet & 0xF8) == 0xF0) return 4; if ((octet & 0xFC) == 0xF8) return 5; if ((octet & 0xFE) == 0xFC) return 6; return 0; // Shouldn't happen } private static char toCharacter(int[] octets, int offset, int length) { byte[] bytes = new byte[length]; for (int i = 0; i < length; i++) { bytes[i] = (byte) octets[offset + i]; } try { return new String(bytes, "utf-8").charAt(0); } catch (UnsupportedEncodingException ex) { // Can't happen throw new RuntimeException(ex); } } private static boolean isUnreservedASCII(char c) { // unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '.' || c == '_' || c == '~'; } private static int[] toBytes(String percentEncoded) { int length = percentEncoded.length() / 3; int[] result = new int[length]; for (int i = 0; i < length; i++) { result[i] = toByte(percentEncoded.charAt(i * 3 + 1), percentEncoded.charAt(i * 3 + 2)); } return result; } private static int toByte(char hex1, char hex2) { return (toByte(hex1) << 4) | toByte(hex2); } private static int toByte(char hex) { if (hex >= '0' && hex <= '9') { return hex - '0'; } if (hex >= 'a' && hex <= 'f') { return hex - 'a' + 10; } if (hex >= 'A' && hex <= 'F') { return hex - 'A' + 10; } throw new IllegalArgumentException("Not a hex digit: " + hex); } } <|start_filename|>src/main/java/de/fuberlin/wiwiss/pubby/sources/RewrittenDataSource.java<|end_filename|> package de.fuberlin.wiwiss.pubby.sources; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.vocabulary.OWL; import de.fuberlin.wiwiss.pubby.IRIRewriter; import de.fuberlin.wiwiss.pubby.ModelUtil; /** * Wraps a {@link DataSource} by applying a {@link IRIRewriter}. The result * is a data source that contains the same data as the original, but with * all IRIs replaced according to the rewriter. * * Optionally, may add <code>owl:sameAs</code> statements to indicate that the * rewritten and original IRIs identify the same entity. */ public class RewrittenDataSource implements DataSource { private final DataSource original; private final IRIRewriter rewriter; private final boolean addSameAs; public RewrittenDataSource(DataSource original, IRIRewriter rewriter) { this(original, rewriter, false); } public RewrittenDataSource(DataSource original, IRIRewriter rewriter, boolean addSameAsStatements) { this.original = original; this.rewriter = rewriter; this.addSameAs = addSameAsStatements; } private boolean isOriginalIRI(String absoluteIRI) { try { rewriter.unrewrite(absoluteIRI); return false; } catch (IllegalArgumentException ex) { // Tried to unrewrite an IRI that is already in original form return true; } } @Override public boolean canDescribe(String absoluteIRI) { if (isOriginalIRI(absoluteIRI)) { // According to our logic, the original namespace is empty // because we transplanted it. It only contains a sameAs // statements for every resource in it. return addSameAs && original.canDescribe(absoluteIRI); } return original.canDescribe(rewriter.unrewrite(absoluteIRI)); } @Override public Model describeResource(String iri) { if (isOriginalIRI(iri)) { // According to our logic, the original namespace is empty // because we transplanted it. It only contains a sameAs // statements for every resource in it. if (!addSameAs || original.describeResource(iri).isEmpty()) { return ModelUtil.EMPTY_MODEL; } Model result = ModelFactory.createDefaultModel(); addSameAsStatement(result, rewriter.rewrite(iri)); return result; } // Normal case -- a rewritten IRI Model result = rewriter.rewrite( original.describeResource( rewriter.unrewrite(iri))); if (addSameAs && !result.isEmpty()) { addSameAsStatement(result, iri); } return result; } @Override public Map<Property, Integer> getHighIndegreeProperties(String resourceIRI) { if (isOriginalIRI(resourceIRI)) return null; return rewriter.rewrite( original.getHighIndegreeProperties( rewriter.unrewrite(resourceIRI))); } @Override public Map<Property, Integer> getHighOutdegreeProperties(String resourceIRI) { if (isOriginalIRI(resourceIRI)) return null; return rewriter.rewrite( original.getHighOutdegreeProperties( rewriter.unrewrite(resourceIRI))); } @Override public Model listPropertyValues(String resourceIRI, Property property, boolean isInverse) { if (isOriginalIRI(resourceIRI)) { // According to our logic, the original namespace is empty // because we transplanted it. It only contains a sameAs // statements for every resource in it. if (!addSameAs || !property.equals(OWL.sameAs) || !isInverse || original.describeResource(resourceIRI).isEmpty()) { return ModelUtil.EMPTY_MODEL; } Model result = ModelFactory.createDefaultModel(); addSameAsStatement(result, rewriter.rewrite(resourceIRI)); return result; } // Normal case -- a rewritten IRI Model result = rewriter.rewrite( original.listPropertyValues( rewriter.unrewrite(resourceIRI), rewriter.unrewrite(property), isInverse)); if (addSameAs && !result.isEmpty() && property.equals(OWL.sameAs) && !isInverse) { addSameAsStatement(result, resourceIRI); } return result; } @Override public List<Resource> getIndex() { List<Resource> originalIndex = original.getIndex(); List<Resource> result = new ArrayList<Resource>(originalIndex.size()); for (Resource r: originalIndex) { result.add(rewriter.rewrite(r)); } return result; } private void addSameAsStatement(Model model, String rewrittenIRI) { String originalIRI = rewriter.unrewrite(rewrittenIRI); Resource rewritten = model.getResource(rewrittenIRI); Resource unrewritten = model.getResource(originalIRI); if (rewritten.equals(unrewritten)) return; rewritten.addProperty(OWL.sameAs, unrewritten); ModelUtil.addNSIfUndefined(model, "owl", OWL.NS); } } <|start_filename|>src/main/java/de/fuberlin/wiwiss/pubby/servlets/BaseServlet.java<|end_filename|> package de.fuberlin.wiwiss.pubby.servlets; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.velocity.context.Context; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.shared.PrefixMapping; import com.hp.hpl.jena.sparql.vocabulary.FOAF; import com.hp.hpl.jena.vocabulary.RDFS; import de.fuberlin.wiwiss.pubby.Configuration; import de.fuberlin.wiwiss.pubby.Dataset; import de.fuberlin.wiwiss.pubby.HypermediaControls; import de.fuberlin.wiwiss.pubby.MetadataConfiguration; import de.fuberlin.wiwiss.pubby.ModelUtil; /** * An abstract base servlet for servlets that manage a namespace of resources. * This class handles preprocessing of the request to extract the * resource URI relative to the namespace root, and manages the * {@link Configuration} instance shared by all servlets. */ public abstract class BaseServlet extends HttpServlet { private Configuration config; private String initError; public void init() throws ServletException { config = (Configuration) getServletContext().getAttribute( ServletContextInitializer.SERVER_CONFIGURATION); if (config == null) { initError = (String) getServletContext().getAttribute( ServletContextInitializer.ERROR_MESSAGE); } } // TODO: This should be somewhere else, doesn't fit here protected void addDocumentMetadata(Model model, HypermediaControls controller, String documentURL, String title) { ModelUtil.addNSIfUndefined(model, "foaf", FOAF.getURI()); ModelUtil.addNSIfUndefined(model, "rdfs", RDFS.getURI()); // Add document metadata Resource topic = model.getResource(controller.getAbsoluteIRI()); Resource document = model.getResource(documentURL); document.addProperty(FOAF.primaryTopic, topic); document.addProperty(RDFS.label, title); // Add custom metadata for (Dataset dataset: config.getDatasets()) { MetadataConfiguration metadata = dataset.getMetadataConfiguration(); metadata.addCustomMetadata(model, document); metadata.addMetadataFromTemplate(model, controller); } } // TODO: This should be somewhere else, doesn't fit here protected void addPageMetadata(Context context, HypermediaControls controller, PrefixMapping prefixes) { try { Model metadataModel = ModelFactory.createDefaultModel(); for (Dataset dataset: config.getDatasets()) { MetadataConfiguration metadata = dataset.getMetadataConfiguration(); Resource document = metadata.addMetadataFromTemplate(metadataModel, controller); // Replaced the commented line by the following one because the // RDF graph we want to talk about is a specific representation // of the data identified by the getDataURL() URI. // Olaf, May 28, 2010 // context.put("metadata", metadata.getResource(resource.getDataURL())); context.put("metadata", document); } Map<String,String> nsSet = metadataModel.getNsPrefixMap(); nsSet.putAll(prefixes.getNsPrefixMap()); context.put("prefixes", nsSet.entrySet()); context.put("blankNodesMap", new HashMap<Resource,String>()); } catch (Exception e) { context.put("metadata", Boolean.FALSE); } } protected abstract boolean doGet( String relativeURI, HttpServletRequest request, HttpServletResponse response, Configuration config) throws IOException, ServletException; public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (initError != null) { sendInitialization500(response, initError); return; } String relativeURI = request.getRequestURI().substring( request.getContextPath().length() + request.getServletPath().length()); // Some servlet containers keep the leading slash, some don't if (!"".equals(relativeURI) && "/".equals(relativeURI.substring(0, 1))) { relativeURI = relativeURI.substring(1); } if (!doGet(relativeURI, request, response, config)) { send404(response, null); } } protected void send404(HttpServletResponse response, String resourceURI) throws IOException { response.setStatus(404); VelocityHelper template = new VelocityHelper(getServletContext(), response); Context context = template.getVelocityContext(); context.put("project_name", config.getProjectName()); context.put("project_link", config.getProjectLink()); context.put("server_base", config.getWebApplicationBaseURI()); context.put("title", "404 Not Found"); if (resourceURI != null) { context.put("uri", resourceURI); } template.renderXHTML("404.vm"); } protected void sendInitialization500(HttpServletResponse response, String message) throws IOException { response.setStatus(500); VelocityHelper template = new VelocityHelper(getServletContext(), response); Context context = template.getVelocityContext(); context.put("message", message); context.put("title", "Configuration error"); template.renderXHTML("500init.vm"); } protected String addQueryString(String dataURL, HttpServletRequest request) { if (request.getParameter("output") == null) { return dataURL; } return dataURL + "?output=" + request.getParameter("output"); } private static final long serialVersionUID = 7594710471966527559L; } <|start_filename|>src/main/java/de/fuberlin/wiwiss/pubby/sources/IndexDataSource.java<|end_filename|> package de.fuberlin.wiwiss.pubby.sources; import java.util.List; import java.util.Map; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.ResourceFactory; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.vocabulary.RDFS; /** * A {@link DataSource} that wraps another data source and adds an * index of the resources in that data source. */ public class IndexDataSource implements DataSource { private final String indexIRI; private final DataSource wrapped; public IndexDataSource(String indexIRI, DataSource wrapped) { this.indexIRI = indexIRI; this.wrapped = wrapped; } @Override public boolean canDescribe(String absoluteIRI) { return indexIRI.equals(absoluteIRI) || wrapped.canDescribe(absoluteIRI); } @Override public Model describeResource(String iri) { if (!indexIRI.equals(iri)) return wrapped.describeResource(iri); Model result = ModelFactory.createDefaultModel(); result.setNsPrefix("sioc", SIOC_NS); result.setNsPrefix("rdfs", RDFS.getURI()); Resource index = result.createResource(indexIRI); // TODO: Get label from the vocabulary store, and make it i18nable index.addProperty(RDFS.label, "Index of Resources", "en"); for (Resource r: wrapped.getIndex()) { index.addProperty(siocContainerOf, r); } return result; } private final static String SIOC_NS = "http://rdfs.org/sioc/ns#"; private final static Property siocContainerOf = ResourceFactory.createProperty(SIOC_NS + "container_of"); @Override public Map<Property, Integer> getHighIndegreeProperties(String resourceIRI) { return wrapped.getHighIndegreeProperties(resourceIRI); } @Override public Map<Property, Integer> getHighOutdegreeProperties(String resourceIRI) { return wrapped.getHighOutdegreeProperties(resourceIRI); } /** * Describe the index resource, and extract all the statements that * have our property and the right subject/object. */ @Override public Model listPropertyValues(String resourceIRI, Property property, boolean isInverse) { if (!indexIRI.equals(resourceIRI)) { return wrapped.listPropertyValues(resourceIRI, property, isInverse); } Model all = describeResource(resourceIRI); Resource r = all.getResource(resourceIRI); StmtIterator it = isInverse ? all.listStatements(null, property, r) : all.listStatements(r, property, (RDFNode) null); Model result = ModelFactory.createDefaultModel(); while (it.hasNext()) { result.add(it.next()); } return result; } @Override public List<Resource> getIndex() { // We could add the indexIRI as an additional resource here, but we // don't want it to show up in the list of resources generated in // describeResource(), and we don't want it turn an otherwise // empty dataset into a non-empty one. return wrapped.getIndex(); } } <|start_filename|>src/main/java/de/fuberlin/wiwiss/pubby/sources/ModelDataSource.java<|end_filename|> package de.fuberlin.wiwiss.pubby.sources; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.NodeIterator; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.ResIterator; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.ResourceFactory; import de.fuberlin.wiwiss.pubby.ModelUtil; /** * A data source backed by a Jena model. */ public class ModelDataSource implements DataSource { private Model model; public ModelDataSource(Model model) { this.model = model; } @Override public boolean canDescribe(String absoluteIRI) { return true; } @Override public Model describeResource(String resourceURI) { Resource r = ResourceFactory.createResource(resourceURI); if (model.contains(r, null, (RDFNode) null) || model.contains(null, null, r)) { return model; } return ModelUtil.EMPTY_MODEL; } @Override public Map<Property, Integer> getHighIndegreeProperties(String resourceURI) { return null; } @Override public Map<Property, Integer> getHighOutdegreeProperties(String resourceURI) { return null; } @Override public Model listPropertyValues(String resourceURI, Property property, boolean isInverse) { return model; } @Override public List<Resource> getIndex() { List<Resource> result = new ArrayList<Resource>(); ResIterator subjects = model.listSubjects(); while (subjects.hasNext() && result.size() < DataSource.MAX_INDEX_SIZE) { Resource r = subjects.next(); if (r.isAnon()) continue; result.add(r); } NodeIterator objects = model.listObjects(); while (objects.hasNext() && result.size() < DataSource.MAX_INDEX_SIZE) { RDFNode o = objects.next(); if (!o.isURIResource()) continue; result.add(o.asResource()); } return result; } } <|start_filename|>src/main/webapp/static/style.css<|end_filename|> html { margin: 0; padding: 0; } body { font-family: sans-serif; font-size: 80%; margin: 0; padding: 1.2em 2em; } #rdficon { float: right; position: relative; top: -28px; } #header { border-bottom: 2px solid #696; margin: 0 0 1.2em; padding: 0 0 0.3em; } #footer { border-top: 2px solid #696; margin: 1.2em 0 0; padding: 0.3em 0 0; } #homelink { display: inline; } #homelink, #homelink a { color: #666; } #homelink a { font-weight: bold; text-decoration: none; } #homelink a:hover { color: red; text-decoration: underline; } h1 { display: inline; font-weight: normal; font-size: 200%; margin: 0; text-align: left; } h2 { font-weight: normal; font-size: 124%; margin: 1.2em 0 0.2em; } .page-resource-uri { font-size: 116%; margin: 0.2em 0; } .page-resource-uri a { color: #666; text-decoration: none; } .page-resource-uri a:hover { color: red; text-decoration: underline; } img { border: none; } table.description { border-collapse: collapse; clear: left; font-size: 100%; margin: 0 0 1em; width: 100%; } table.description th { background: white; text-align: left; } table.description td, table.description th { line-height: 1.2em; padding: 0.3em 0.5em; vertical-align: top; } table.description ul { margin: 0; padding-left: 1.4em; } table.description li { list-style-position: outside; list-style-type: square; margin-left: 0; padding-left: 0; } table.description .property-column { width: 13em; } .uri { white-space: nowrap; } .uri a, a.uri { text-decoration: none; } .unbound { color: #888; } table.description a small, .metadata-table a small { font-size: 100%; color: #55a; } table.description small, .metadata-table a small { font-size: 100%; color: #666; } table.description .property { white-space: nowrap; padding-right: 1.5em; } h1, h2 { color: #810; } body { background: #cec; } table.description .container > td { background: #c0e2c0; padding: 0.2em 0.8em; } table.description .even td { background: #d4f6d4; } table.description .odd td { background: #f0fcf0; } .image { background: white; float: left; margin: 0 1.5em 1.5em 0; padding: 2px; } a.expander { text-decoration: none; } .metadata-label { font-size: 100%; background: #f0fcf0; padding: 3px; } .metadata-table { font-size: 100%; border-left: 3px solid #f0fcf0; border-bottom: 3px solid #f0fcf0; border-right: 3px solid #f0fcf0; background: #d4f6d4; border-top: 0px solid none; margin: 0px; } .metadata-table td { padding: 3px; } <|start_filename|>src/main/java/de/fuberlin/wiwiss/pubby/servlets/DataURLServlet.java<|end_filename|> package de.fuberlin.wiwiss.pubby.servlets; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.vocabulary.RDFS; import de.fuberlin.wiwiss.pubby.Configuration; import de.fuberlin.wiwiss.pubby.HypermediaControls; import de.fuberlin.wiwiss.pubby.ModelResponse; import de.fuberlin.wiwiss.pubby.ResourceDescription; /** * Servlet for serving RDF documents containing a description * of a given resource. */ public class DataURLServlet extends BaseServlet { @Override protected boolean doGet(String relativeURI, HttpServletRequest request, HttpServletResponse response, Configuration config) throws IOException { HypermediaControls controller = config.getControls(relativeURI, false); ResourceDescription description = controller == null ? null : controller.getResourceDescription(); // Check if resource exists in dataset if (description == null) { response.setStatus(404); response.setContentType("text/plain"); response.getOutputStream().println("Nothing known about <" + controller.getAbsoluteIRI() + ">"); return true; } Model model = description.getModel(); addHighDegreePropertyLinks(model, controller); addDocumentMetadata(model, controller, addQueryString(controller.getDataURL(), request), "RDF description of " + description.getTitle()); ModelResponse server = new ModelResponse(model, request, response); server.serve(); return true; } private void addHighDegreePropertyLinks(Model model, HypermediaControls controller) { // TODO: This should re-use the logic from ResourceDescription and ResourceProperty to decide where to create these links // Add links to RDF documents with descriptions of the blank nodes Resource r = model.getResource(controller.getAbsoluteIRI()); StmtIterator it = r.listProperties(); while (it.hasNext()) { Statement stmt = it.nextStatement(); if (!stmt.getObject().isAnon()) continue; String pathDataURL = controller.getValuesDataURL(stmt.getPredicate()); if (pathDataURL == null) continue; ((Resource) stmt.getResource()).addProperty(RDFS.seeAlso, model.createResource(pathDataURL)); } it = model.listStatements(null, null, r); while (it.hasNext()) { Statement stmt = it.nextStatement(); if (!stmt.getSubject().isAnon()) continue; String pathDataURL = controller.getInverseValuesDataURL(stmt.getPredicate()); if (pathDataURL == null) continue; ((Resource) stmt.getSubject().as(Resource.class)).addProperty(RDFS.seeAlso, model.createResource(pathDataURL)); } } private static final long serialVersionUID = 6825866213915066364L; } <|start_filename|>src/main/java/de/fuberlin/wiwiss/pubby/VocabularyStore.java<|end_filename|> package de.fuberlin.wiwiss.pubby; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.shared.JenaException; import com.hp.hpl.jena.vocabulary.OWL; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; import com.hp.hpl.jena.vocabulary.XSD; import de.fuberlin.wiwiss.pubby.sources.DataSource; import de.fuberlin.wiwiss.pubby.vocab.CONF; /** * A store for labels, descriptions and other metadata of classes and * properties. Values are retrieved from a {@link DataSource} and * cached. */ public class VocabularyStore { private DataSource dataSource; private String defaultLanguage = "en"; /** * Needs to be set before the instance is used! This is to allow creation * of the store before the dataset is fully assembled. */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public void setDefaultLanguage(String defaultLanguage) { this.defaultLanguage = defaultLanguage; } private final I18nStringValueCache labels = new I18nStringValueCache(RDFS.label, false); private final I18nStringValueCache pluralLabels = new I18nStringValueCache(CONF.pluralLabel, false); private final I18nStringValueCache inverseLabels = new I18nStringValueCache(RDFS.label, true); private final I18nStringValueCache inversePluralLabels = new I18nStringValueCache(CONF.pluralLabel, true); private final I18nStringValueCache descriptions = new I18nStringValueCache(RDFS.comment, false); private final IntegerValueCache weights = new IntegerValueCache(CONF.weight, false); private final IntegerValueCache inverseWeights = new IntegerValueCache(CONF.weight, true); private final CachedPropertyCollection highIndegreeProperties = new CachedPropertyCollection(CONF.HighIndregreeProperty); private final CachedPropertyCollection highOutdegreeProperties = new CachedPropertyCollection(CONF.HighOutdregreeProperty); public Literal getLabel(String iri, boolean preferPlural) { return getLabel(iri, preferPlural, defaultLanguage); } public Literal getLabel(String iri, boolean preferPlural, String language) { if (preferPlural) { Literal pluralLabel = pluralLabels.get(iri, language); return pluralLabel == null ? getLabel(iri, false, language) : pluralLabel; } return labels.get(iri, language); } /** * Returns a label, only taking into account previously cached values, * without querying the data sources. Fast. * @param iri IRI of the resource whose label to return * @param preferPlural Return <tt>conf:pluralLabel</tt> if available * @return The best label found, or null if none */ public Literal getCachedLabel(String iri, boolean preferPlural) { if (preferPlural) { Literal pluralLabel = pluralLabels.getCached(iri, defaultLanguage); return pluralLabel == null ? getCachedLabel(iri, false) : pluralLabel; } return labels.getCached(iri, defaultLanguage); } public Literal getInverseLabel(String iri, boolean preferPlural) { return getInverseLabel(iri, preferPlural, defaultLanguage); } public Literal getInverseLabel(String iri, boolean preferPlural, String language) { if (preferPlural) { Literal pluralLabel = inversePluralLabels.get(iri, language); return pluralLabel == null ? getInverseLabel(iri, false, language) : pluralLabel; } return inverseLabels.get(iri, language); } public Literal getDescription(String iri) { return getDescription(iri, defaultLanguage); } public Literal getDescription(String iri, String language) { return descriptions.get(iri, language); } /** * Returns the <tt>conf:weight</tt> of the property. The inverse's weight * can be requested; if no inverse weight is specified then the "forward" * weight is used. * * @param property The property whose weight to return * @param forInverse If true, look for the inverse's weight first * @return The conf:weight assigned to the property */ public int getWeight(Property property, boolean forInverse) { Integer result = forInverse ? inverseWeights.get(property.getURI()) : null; if (result == null) result = weights.get(property.getURI()); return result == null ? 0 : result.intValue(); } public CachedPropertyCollection getHighIndegreeProperties() { return highIndegreeProperties; } public CachedPropertyCollection getHighOutdegreeProperties() { return highOutdegreeProperties; } public class CachedPropertyCollection { private final Resource type; private Collection<Property> cache = null; CachedPropertyCollection(Resource type) { this.type = type; } public Collection<Property> get() { if (dataSource == null) return Collections.emptyList(); if (cache != null) return cache; cache = new ArrayList<Property>(); Model result = dataSource.listPropertyValues(type.getURI(), RDF.type, true); StmtIterator it = result.listStatements(null, RDF.type, type); while (it.hasNext()) { Resource r = it.next().getSubject(); if (!r.isURIResource()) continue; cache.add(r.as(Property.class)); } return cache; } public void reportAdditional(Property p) { if (cache == null) get(); if (cache.contains(p)) return; cache.add(p); } } private abstract class ValueCache<K> { private final Property property; private final boolean inverse; private final Map<String, K> cache = new HashMap<String, K>(); ValueCache(Property property, boolean inverse) { this.property = property; this.inverse = inverse; } abstract K pickBestValue(Set<RDFNode> candidates); K get(String iri) { if (cache.containsKey(iri)) { return cache.get(iri); } K best = null; if (dataSource.canDescribe(iri)) { best = pickBestFromModel(dataSource.describeResource(iri), iri); } cache.put(iri, best); return best; } K getCached(String iri) { return cache.get(iri); } private K pickBestFromModel(Model m, String iri) { Resource r = m.getResource(iri); Set<RDFNode> nodes = inverse ? getInverseValues(r) : getValues(r); return pickBestValue(nodes); } private Set<RDFNode> getValues(Resource r) { Set<RDFNode> nodes = new HashSet<RDFNode>(); StmtIterator it = r.listProperties(property); while (it.hasNext()) { nodes.add(it.next().getObject()); } return nodes; } private Set<RDFNode> getInverseValues(Resource r) { Set<RDFNode> nodes = new HashSet<RDFNode>(); StmtIterator it = r.listProperties(OWL.inverseOf); while (it.hasNext()) { RDFNode object = it.next().getObject(); if (!object.isResource()) continue; StmtIterator it2 = object.asResource().listProperties(property); while (it2.hasNext()) { nodes.add(it2.next().getObject()); } } return nodes; } } // Currently not needed -- all strings are i18n // private class StringValueCache extends ValueCache<String> { // StringValueCache(Property p, boolean inverse) { super(p, inverse); } // @Override // String pickBestValue(Set<RDFNode> candidates) { // for (RDFNode node: candidates) { // if (!node.isLiteral()) continue; // Literal l = node.asLiteral(); // String dt = l.getDatatypeURI(); // if (dt == null || dt.equals(XSD.xstring.getURI()) || dt.equals(RDF.getURI() + "langString")) { // return l.getLexicalForm(); // } // } // return null; // } // } private class I18nStringValueCache extends ValueCache<Collection<Literal>> { I18nStringValueCache(Property p, boolean inverse) { super (p, inverse); } Literal get(String iri, String preferredLang) { return getBestMatch(get(iri), preferredLang); } Literal getCached(String iri, String preferredLang) { return getBestMatch(getCached(iri), preferredLang); } private Literal getBestMatch(Collection<Literal> candidates, String preferredLang) { if (candidates == null) return null; Literal bestMatch = null; int bestMatchLength = -1; for (Literal l: candidates) { int matchLength = getMatchLength(l.getLanguage(), preferredLang); if (matchLength >= bestMatchLength) { bestMatch = l; bestMatchLength = matchLength; } } return bestMatch; } private int getMatchLength(String langTag1, String langTag2) { // TODO: This is very dodgy. It reports a decent match between "xx" and "xxx". Requires some research to do properly. int i = 0; while (i < langTag1.length() && i < langTag2.length()) { char c1 = langTag1.charAt(i); char c2 = langTag2.charAt(i); if (Character.toLowerCase(c1) != Character.toLowerCase(c2)) break; i++; } return i; } @Override Collection<Literal> pickBestValue(Set<RDFNode> candidates) { Collection<Literal> result = new ArrayList<Literal>(candidates.size()); for (RDFNode node: candidates) { if (!node.isLiteral()) continue; Literal l = node.asLiteral(); String dt = l.getDatatypeURI(); if (dt == null || dt.equals(XSD.xstring.getURI()) || dt.equals(RDF.getURI() + "langString")) { result.add(l); } } return result; } } private class IntegerValueCache extends ValueCache<Integer> { IntegerValueCache(Property p, boolean inverse) { super(p, inverse); } @Override Integer pickBestValue(Set<RDFNode> candidates) { for (RDFNode node: candidates) { if (!node.isLiteral()) continue; try { return node.asLiteral().getInt(); } catch (JenaException ex) { continue; } } return null; } } } <|start_filename|>src/main/java/de/fuberlin/wiwiss/pubby/servlets/ValuesBaseServlet.java<|end_filename|> package de.fuberlin.wiwiss.pubby.servlets; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.ResourceFactory; import de.fuberlin.wiwiss.pubby.Configuration; import de.fuberlin.wiwiss.pubby.HypermediaControls; import de.fuberlin.wiwiss.pubby.IRIEncoder; import de.fuberlin.wiwiss.pubby.PubbyIRIEscaper; /** * Abstract base servlet for servlets that handle a property of a given * resource. The base servlet takes care of extracting the resource's URI * and the property's URI from the requested URL, and mapping everything to * the data sources. Concrete subclasses then take care of generating the * response. */ public abstract class ValuesBaseServlet extends BaseServlet { private static Pattern prefixedNamePattern = Pattern.compile("(-?)([^!:/]*):([^:/]*)/(.*)"); private static Pattern fullIRIPattern = Pattern.compile("(-?)!(.*?)///(.*)"); public abstract boolean doGet(HypermediaControls controller, Property property, boolean isInverse, HttpServletRequest request, HttpServletResponse response, Configuration config) throws IOException, ServletException; public boolean doGet(String relativeURI, HttpServletRequest request, HttpServletResponse response, Configuration config) throws IOException, ServletException { boolean isInverse; Property property; Matcher matcher = prefixedNamePattern.matcher(relativeURI); if (matcher.matches()) { String prefix = matcher.group(2); if (config.getPrefixes().getNsPrefixURI(prefix) == null) { return false; } String localName = matcher.group(3); relativeURI = matcher.group(4); // Keep just last part property = ResourceFactory.createProperty( config.getPrefixes().getNsPrefixURI(prefix), localName); } else { matcher = fullIRIPattern.matcher(relativeURI); if (!matcher.matches()) { return false; } String propertyIRI = IRIEncoder.toIRI( PubbyIRIEscaper.unescapeSpecialCharacters(matcher.group(2))); relativeURI = matcher.group(3); // Keep just last part property = ResourceFactory.createProperty(propertyIRI); } isInverse = "-".equals(matcher.group(1)); HypermediaControls controller = config.getControls(relativeURI, false); if (controller == null) { return false; } return doGet(controller, property, isInverse, request, response, config); } private static final long serialVersionUID = 7393467141233996715L; }
alemando/pubby
<|start_filename|>src/ServiceFabric.Extensions.Data.Indexing.Test/Models/Address.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ServiceFabric.Extensions.Data.Indexing.Persistent.Test.Models { public sealed class Address { public string AddressLine1 { get; set; } public string AddressLine2 { get; set; } public string City { get; set; } public string State { get; set; } public int Zipcode { get; set; } public static Address CreateRandom(Random random) { return new Address { AddressLine1 = new string((char)random.Next('a', 'z'), random.Next(10, 20)), AddressLine2 = null, City = new string((char)random.Next('a', 'z'), random.Next(5, 10)), State = "WA", Zipcode = random.Next(10000, 99999), }; } } } <|start_filename|>src/ServiceFabric.Extensions.Data.Indexing/IReliableIndexedDictionary.cs<|end_filename|> using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.ServiceFabric.Data.Collections; using Microsoft.ServiceFabric.Data; namespace ServiceFabric.Extensions.Data.Indexing.Persistent { /// <summary> /// Represents a reliable collection of key/value pairs that are persisted and replicated, with support for reverse indexing and full-text search. /// /// To use, call the 'Indexed' variants of the IReliableStateManager methods: /// - GetOrAddIndexedAsync() instead of GetOrAddAsync() /// - TryGetIndexedAsync() instead of TryGetAsync() /// - RemoveIndexedAsync() instead of RemoveAsync() /// </summary> public interface IReliableIndexedDictionary<TKey, TValue> : IReliableDictionary2<TKey, TValue> where TKey : IComparable<TKey>, IEquatable<TKey> { /// <summary> /// Creates an async enumerator over the given index of the reliable collection to retrieve all distinct index values. /// The type <typeparamref name="TFilter"/> must match the type of the <see cref="FilterableIndex{TKey, TValue, TFilter}"/>. /// </summary> Task<IAsyncEnumerable<TFilter>> CreateIndexEnumerableAsync<TFilter>(ITransaction tx, string index) where TFilter : IComparable<TFilter>, IEquatable<TFilter>; IAsyncEnumerable<KeyValuePair<TKey, TValue>> GetAllAsync(ITransaction tx, IEnumerable<TKey> keys, TimeSpan timeout, CancellationToken token); /// <summary> /// Creates an async enumerator over the given index of the reliable collection to retrieve all distinct index values. /// The type <typeparamref name="TFilter"/> must match the type of the <see cref="FilterableIndex{TKey, TValue, TFilter}"/>. /// </summary> Task<IAsyncEnumerable<TFilter>> CreateIndexEnumerableAsync<TFilter>(ITransaction tx, string index, EnumerationMode enumerationMode) where TFilter : IComparable<TFilter>, IEquatable<TFilter>; /// <summary> /// Creates an async enumerator over the given index of the reliable collection to retrieve all distinct index values. /// The type <typeparamref name="TFilter"/> must match the type of the <see cref="FilterableIndex{TKey, TValue, TFilter}"/>. /// </summary> Task<IAsyncEnumerable<TFilter>> CreateIndexEnumerableAsync<TFilter>(ITransaction tx, string index, EnumerationMode enumerationMode, TimeSpan timeout, CancellationToken token) where TFilter : IComparable<TFilter>, IEquatable<TFilter>; /// <summary> /// Retrieve all keys and values from the reliable collection that match the given filter using the specified index name. /// The index is defined in the IReliableStateManager.GetOrAddIndexedAsync() call that retrieves this reliable collection. /// The type <typeparamref name="TFilter"/> must match the type of the <see cref="FilterableIndex{TKey, TValue, TFilter}"/>. /// </summary> Task<IAsyncEnumerable<KeyValuePair<TKey, TValue>>> FilterAsync<TFilter>(ITransaction tx, string index, TFilter filter) where TFilter : IComparable<TFilter>, IEquatable<TFilter>; /// <summary> /// Retrieve all keys and values from the reliable collection that match the given filter using the specified index name. /// The index is defined in the IReliableStateManager.GetOrAddIndexedAsync() call that retrieves this reliable collection. /// The type <typeparamref name="TFilter"/> must match the type of the <see cref="FilterableIndex{TKey, TValue, TFilter}"/>. /// </summary> Task<IAsyncEnumerable<KeyValuePair<TKey, TValue>>> FilterAsync<TFilter>(ITransaction tx, string index, TFilter filter, TimeSpan timeout, CancellationToken token) where TFilter : IComparable<TFilter>, IEquatable<TFilter>; /// <summary> /// Retrieve all keys and values from the reliable collection that fall within the given range (inclusively or exclusively) using the specified index name. /// The index is defined in the IReliableStateManager.GetOrAddIndexedAsync() call that retrieves this reliable collection. /// The type <typeparamref name="TFilter"/> must match the type of the <see cref="FilterableIndex{TKey, TValue, TFilter}"/>. /// </summary> Task<IAsyncEnumerable<KeyValuePair<TKey, TValue>>> RangeFilterAsync<TFilter>(ITransaction tx, string index, TFilter startFilter, RangeFilterType startType, TFilter endFilter, RangeFilterType endType) where TFilter : IComparable<TFilter>, IEquatable<TFilter>; /// <summary> /// Retrieve all keys and values from the reliable collection that fall within the given range (inclusively or exclusively) using the specified index name. /// The index is defined in the IReliableStateManager.GetOrAddIndexedAsync() call that retrieves this reliable collection. /// The type <typeparamref name="TFilter"/> must match the type of the <see cref="FilterableIndex{TKey, TValue, TFilter}"/>. /// </summary> Task<IAsyncEnumerable<KeyValuePair<TKey, TValue>>> RangeFilterAsync<TFilter>(ITransaction tx, string index, TFilter startFilter, RangeFilterType startType, TFilter endFilter, RangeFilterType endType, TimeSpan timeout, CancellationToken token) where TFilter : IComparable<TFilter>, IEquatable<TFilter>; /// <summary> /// Retrieve all keys and values from the reliable collection from the beginning to the end value (inclusively or exclusively) using the specified index name. /// The index is defined in the IReliableStateManager.GetOrAddIndexedAsync() call that retrieves this reliable collection. /// The type <typeparamref name="TFilter"/> must match the type of the <see cref="FilterableIndex{TKey, TValue, TFilter}"/>. /// </summary> Task<IAsyncEnumerable<KeyValuePair<TKey, TValue>>> RangeToFilterAsync<TFilter>(ITransaction tx, string index, TFilter endFilter, RangeFilterType endType, TimeSpan timeout, CancellationToken token) where TFilter : IComparable<TFilter>, IEquatable<TFilter>; /// <summary> /// Retrieve all keys and values from the reliable collection from the beginning value (inclusively or exclusively) to the end using the specified index name. /// The index is defined in the IReliableStateManager.GetOrAddIndexedAsync() call that retrieves this reliable collection. /// The type <typeparamref name="TFilter"/> must match the type of the <see cref="FilterableIndex{TKey, TValue, TFilter}"/>. /// </summary> Task<IAsyncEnumerable<KeyValuePair<TKey, TValue>>> RangeFromFilterAsync<TFilter>(ITransaction tx, string index, TFilter startFilter, RangeFilterType startType, TimeSpan timeout, CancellationToken token) where TFilter : IComparable<TFilter>, IEquatable<TFilter>; /// <summary> /// Performs a full-text search over the reliable collection. Returns all keys and values from the reliable /// collection that match the given search using all searchable index definitions. /// The indexes are defined in the IReliableStateManager.GetOrAddIndexedAsync() call that retrieves this reliable collection. /// </summary> Task<IAsyncEnumerable<KeyValuePair<TKey, TValue>>> SearchAsync(ITransaction tx, string search); /// <summary> /// Performs a full-text search over the reliable collection. Returns all keys and values from the reliable /// collection that match the given search using all searchable index definitions. /// The indexes are defined in the IReliableStateManager.GetOrAddIndexedAsync() call that retrieves this reliable collection. /// </summary> Task<IAsyncEnumerable<KeyValuePair<TKey, TValue>>> SearchAsync(ITransaction tx, string search, int count); /// <summary> /// Performs a full-text search over the reliable collection. Returns all keys and values from the reliable /// collection that match the given search using all searchable index definitions. /// The indexes are defined in the IReliableStateManager.GetOrAddIndexedAsync() call that retrieves this reliable collection. /// </summary> Task<IAsyncEnumerable<KeyValuePair<TKey, TValue>>> SearchAsync(ITransaction tx, string search, int count, TimeSpan timeout, CancellationToken token); /// <summary> /// Retrieve all keys from the reliable collection that match the given filter. /// The index is defined in the IReliableStateManager.GetOrAddIndexedAsync() call that retrieves this reliable collection. /// The type <typeparamref name="TFilter"/> must match the type of the <see cref="FilterableIndex{TKey, TValue, TFilter}"/>. /// </summary> Task<IEnumerable<TKey>> FilterKeysOnlyAsync<TFilter>(ITransaction tx, string propertyName, TFilter filter, TimeSpan timeSpan, CancellationToken cancellationToken) where TFilter : IComparable<TFilter>, IEquatable<TFilter>; /// <summary> /// Retrieve all keys from the reliable collection that fall within the given range from the start value (inclusively or exclusively) through the end of the dictionary. /// The index is defined in the IReliableStateManager.GetOrAddIndexedAsync() call that retrieves this reliable collection. /// The type <typeparamref name="TFilter"/> must match the type of the <see cref="FilterableIndex{TKey, TValue, TFilter}"/>. /// </summary> Task<IEnumerable<TKey>> RangeFromFilterKeysOnlyAsync<TFilter>(ITransaction tx, string propertyName, TFilter startFilter, RangeFilterType startType, TimeSpan timeSpan, CancellationToken cancellationToken) where TFilter : IComparable<TFilter>, IEquatable<TFilter>; /// <summary> /// Retrieve all keys from the reliable collection that fall within the given range from the start of the dictionary to the end value (inclusively or exclusively). /// The index is defined in the IReliableStateManager.GetOrAddIndexedAsync() call that retrieves this reliable collection. /// The type <typeparamref name="TFilter"/> must match the type of the <see cref="FilterableIndex{TKey, TValue, TFilter}"/>. /// </summary> Task<IEnumerable<TKey>> RangeToFilterKeysOnlyAsync<TFilter>(ITransaction tx, string propertyName, TFilter endFilter, RangeFilterType endType, TimeSpan timeSpan, CancellationToken cancellationToken) where TFilter : IComparable<TFilter>, IEquatable<TFilter>; } } <|start_filename|>src/ServiceFabric.Extensions.Data.Indexing/SearchableIndex.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.ServiceFabric.Data.Collections; using Microsoft.ServiceFabric.Data; namespace ServiceFabric.Extensions.Data.Indexing.Persistent { /// <summary> /// Defintion for an index that supports full-text search within a string property. /// This will create an <see cref="IReliableDictionary2{string, TKey[]}"/> to store the index. /// </summary> public sealed class SearchableIndex<TKey, TValue> : IIndexDefinition<TKey, TValue> where TKey : IComparable<TKey>, IEquatable<TKey> { public string Name { get; } public Func<TKey, TValue, string> Property { get; } private IReliableDictionary2<string, TKey[]> _index; /// <summary> /// Creates a new full-text search index. The property value must be deterministic based on the input key and value. /// The value is generally a property of the key or value, but it can also be a composite or generated property. /// </summary> public SearchableIndex(string name, Func<TKey, TValue, string> property) { Name = name ?? throw new ArgumentNullException(nameof(name)); Property = property ?? throw new ArgumentNullException(nameof(property)); } /// <summary> /// Retrieves all keys that satisfy the given full-text search, or an empty array if there are no matches. /// </summary> public async Task<IEnumerable<TKey>> SearchAsync(ITransaction tx, string search, int count, TimeSpan timeout, CancellationToken token) { var keys = new HashSet<TKey>(); var words = GetDistinctWords(search); foreach (var word in words) { var result = await _index.TryGetValueAsync(tx, word, timeout, token).ConfigureAwait(false); if (result.HasValue) { keys.AddRange(result.Value); } if (keys.Count >= count) break; } return keys.Take(count); } /// <summary> /// Try to load the existing reliable collection for this index and cache it. /// This is called internally and should not be directly called. /// </summary> async Task<bool> IIndexDefinition<TKey, TValue>.TryGetIndexAsync(IReliableStateManager stateManager, Uri baseName) { var indexName = GetIndexName(baseName); var result = await stateManager.TryGetAsync<IReliableDictionary2<string, TKey[]>>(indexName).ConfigureAwait(false); if (!result.HasValue) return false; _index = result.Value; return true; } /// <summary> /// Load or create the reliable collection for this index and cache it. /// This is called internally and should not be directly called. /// </summary> async Task IIndexDefinition<TKey, TValue>.GetOrAddIndexAsync(ITransaction tx, IReliableStateManager stateManager, Uri baseName, TimeSpan timeout) { var indexName = GetIndexName(baseName); _index = await stateManager.GetOrAddAsync<IReliableDictionary2<string, TKey[]>>(tx, indexName, timeout).ConfigureAwait(false); } /// <summary> /// Delete the existing reliable collection for this index. /// This is called internally and should not be directly called. /// </summary> async Task IIndexDefinition<TKey, TValue>.RemoveIndexAsync(ITransaction tx, IReliableStateManager stateManager, Uri baseName, TimeSpan timeout) { var indexName = GetIndexName(baseName); await stateManager.RemoveAsync(tx, indexName, timeout).ConfigureAwait(false); _index = null; } /// <summary> /// Notify the index that a key and value was added to the primary reliable collection. /// This is called by <see cref="IReliableIndexedDictionary{TKey, TValue}"/> internally and should not be directly called. /// </summary> Task IIndexDefinition<TKey, TValue>.AddAsync(ITransaction tx, TKey key, TValue value, TimeSpan timeout, CancellationToken token) { var text = Property.Invoke(key, value); var words = GetDistinctWords(text); return AddAsync(tx, key, words, timeout, token); } /// <summary> /// Notify the index that a key and value was updated in the primary reliable collection. /// This is called by <see cref="IReliableIndexedDictionary{TKey, TValue}"/> internally and should not be directly called. /// </summary> async Task IIndexDefinition<TKey, TValue>.UpdateAsync(ITransaction tx, TKey key, TValue oldValue, TValue newValue, TimeSpan timeout, CancellationToken token) { var oldText = Property.Invoke(key, oldValue); var newText = Property.Invoke(key, newValue); var oldWords = GetDistinctWords(oldText); var newWords = GetDistinctWords(newText); // Ignore overlapping words that existing before and after updates. var wordsToRemove = oldWords.Except(newWords); var wordsToAdd = newWords.Except(oldWords); // This loses the locking order - need to adjust this. await RemoveAsync(tx, key, wordsToRemove, timeout, token).ConfigureAwait(false); await AddAsync(tx, key, wordsToAdd, timeout, token).ConfigureAwait(false); } /// <summary> /// Notify the index that a key and value was removed in the primary reliable collection. /// This is called by <see cref="IReliableIndexedDictionary{TKey, TValue}"/> internally and should not be directly called. /// </summary> Task IIndexDefinition<TKey, TValue>.RemoveAsync(ITransaction tx, TKey key, TValue value, TimeSpan timeout, CancellationToken token) { var text = Property.Invoke(key, value); var words = GetDistinctWords(text); return RemoveAsync(tx, key, words, timeout, token); } /// <summary> /// Notify the index that the primary reliable collection was cleared. /// This is called by <see cref="IReliableIndexedDictionary{TKey, TValue}"/> internally and should not be directly called. /// </summary> Task IIndexDefinition<TKey, TValue>.ClearAsync(TimeSpan timeout, CancellationToken token) { return _index.ClearAsync(timeout, token); } private async Task AddAsync(ITransaction tx, TKey key, IEnumerable<string> words, TimeSpan timeout, CancellationToken token) { foreach (var word in words) { await _index.AddOrUpdateAsync(tx, word, f => new[] { key }, (f, keys) => keys.CopyAndAdd(key), timeout, token).ConfigureAwait(false); } } private async Task RemoveAsync(ITransaction tx, TKey key, IEnumerable<string> words, TimeSpan timeout, CancellationToken token) { foreach (var word in words) { // This key should exist in the index for each word. var result = await _index.TryGetValueAsync(tx, word, LockMode.Update, timeout, token).ConfigureAwait(false); if (!result.HasValue) throw new KeyNotFoundException(); // Remove this key from the index. var updatedIndex = result.Value.CopyAndRemove(key); if (updatedIndex.Length > 0) { // Update the index. await _index.SetAsync(tx, word, updatedIndex, timeout, token).ConfigureAwait(false); } else { // Remove the index completely if this was the last key with this filter value. await _index.TryRemoveAsync(tx, word, timeout, token).ConfigureAwait(false); } } } private static List<string> GetDistinctWords(string text) { if (string.IsNullOrEmpty(text)) return new List<string>(); var words = new HashSet<string>(); // Split on whitespace. This doesn't work correctly for markdown (e.g. HTML/XML) foreach (var word in text.Split((char[])null, StringSplitOptions.RemoveEmptyEntries)) { int start = 0; int end = word.Length; // Trim non-letters/digits from the start and end. while (start < end && !char.IsLetterOrDigit(word[start])) start++; while (end > start && !char.IsLetterOrDigit(word[end - 1])) end--; // Only add unique words that have at least one character left. if (start < end) { // Normalize on lower-case letters. words.Add(word.Substring(start, end - start).ToLower()); } } // Sort the words, so we always take reliable collection locks in the same order. var result = new List<string>(words); result.Sort(); return result; } private Uri GetIndexName(Uri baseName) { return new Uri(baseName, $"search/{Name}"); } } } <|start_filename|>src/ServiceFabric.Extensions.Data.Indexing/DictionaryFetchAsyncEnumerable.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.ServiceFabric.Data; namespace ServiceFabric.Extensions.Data.Indexing.Persistent { sealed class DictionaryFetchAsyncEnumerable<TKey, TValue> : IAsyncEnumerable<KeyValuePair<TKey, TValue>> where TKey : IEquatable<TKey>, IComparable<TKey> { private readonly ITransaction Tx; private readonly IReliableIndexedDictionary<TKey, TValue> Dictionary; private readonly IEnumerable<TKey> Keys; private readonly TimeSpan Timeout; private readonly CancellationToken Token; public DictionaryFetchAsyncEnumerable(ITransaction tx, IReliableIndexedDictionary<TKey, TValue> dictionary, IEnumerable<TKey> keys, TimeSpan timeout, CancellationToken token) { Tx = tx; Dictionary = dictionary; Keys = keys; Timeout = timeout; Token = token; } public IAsyncEnumerator<KeyValuePair<TKey, TValue>> GetAsyncEnumerator() { return new DictionaryFetchAsyncEnumerator<TKey, TValue>(Tx, Dictionary, Keys, Timeout, Token); } } internal class DictionaryFetchAsyncEnumerator<TKey, TValue> : IAsyncEnumerator<KeyValuePair<TKey, TValue>> where TKey : IEquatable<TKey>, IComparable<TKey> { private readonly ITransaction Tx; private readonly IReliableIndexedDictionary<TKey, TValue> Dictionary; private readonly IEnumerator<TKey> Keys; private readonly TimeSpan Timeout; private readonly CancellationToken Token; public DictionaryFetchAsyncEnumerator(ITransaction tx, IReliableIndexedDictionary<TKey, TValue> dictionary, IEnumerable<TKey> keys, TimeSpan timeout, CancellationToken token) { Tx = tx; Dictionary = dictionary; Keys = keys.GetEnumerator(); Timeout = timeout; Token = token; } public KeyValuePair<TKey, TValue> Current { get; private set; } public void Dispose() { Keys.Dispose(); } public async Task<bool> MoveNextAsync(CancellationToken cancellationToken) { if (Keys.MoveNext()) { var result = await Dictionary.TryGetValueAsync(Tx, Keys.Current, Timeout, Token).ConfigureAwait(false); if (!result.HasValue) return await MoveNextAsync(cancellationToken); // TODO: since we're doing snapshot reads, the value may have changed since we read the index. We should validate the key-value still match the filter/search/etc. // Note: In queryable this is still done because the OData are still applied to the remaining KeyValue set Current = new KeyValuePair<TKey, TValue>(Keys.Current, result.Value); return true; } return false; } public void Reset() { Keys.Reset(); } } } <|start_filename|>src/ServiceFabric.Extensions.Data.Indexing.Test/SearchableIndexTests.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ServiceFabric.Extensions.Data.Indexing.Persistent.Test.Models; using Microsoft.ServiceFabric.Data.Mocks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ServiceFabric.Extensions.Data.Indexing.Persistent.Test { [TestClass] public class SearchableIndexTests { [TestMethod] public async Task SingleSearchIndex() { var stateManager = new MockReliableStateManager(); var dictionary = await stateManager.GetOrAddIndexedAsync("test", new SearchableIndex<Guid, Person>("name", (k, p) => p.Name)); // Add person using normal IReliableDictionary APIs. This should update the index as well. var john = new Person { Name = "<NAME>" }; var jane = new Person { Name = "<NAME>" }; using (var tx = stateManager.CreateTransaction()) { await dictionary.AddAsync(tx, john.Id, john); await dictionary.AddAsync(tx, jane.Id, jane); await tx.CommitAsync(); } using (var tx = stateManager.CreateTransaction()) { // Search by first names. This should return the respective people we added above. var johnSearch = new List<KeyValuePair<Guid, Person>>(await dictionary.SearchAsync(tx, "John").Result.ToEnumerable()); Assert.AreEqual(1, johnSearch.Count()); Assert.AreEqual(john.Id, johnSearch.First().Key); Assert.AreSame(john, johnSearch.First().Value); var janeSearch = new List<KeyValuePair<Guid, Person>>(await dictionary.SearchAsync(tx, "Jane").Result.ToEnumerable()); Assert.AreEqual(1, janeSearch.Count()); Assert.AreEqual(jane.Id, janeSearch.First().Key); Assert.AreSame(jane, janeSearch.First().Value); // Search the index for the last name. This should return both. var doeSearch = new List<KeyValuePair<Guid, Person>>(await dictionary.SearchAsync(tx, "Doe").Result.ToEnumerable()); Assert.AreEqual(2, doeSearch.Count()); CollectionAssert.Contains(doeSearch.Select(x => x.Value).ToArray(), john); CollectionAssert.Contains(doeSearch.Select(x => x.Value).ToArray(), jane); // Search the index for the last name as lower-case. This should also return both. doeSearch = new List<KeyValuePair<Guid, Person>>(await dictionary.SearchAsync(tx, "doe").Result.ToEnumerable()); Assert.AreEqual(2, doeSearch.Count()); CollectionAssert.Contains(doeSearch.Select(x => x.Value).ToArray(), john); CollectionAssert.Contains(doeSearch.Select(x => x.Value).ToArray(), jane); // Search the index for a non-existent string. var nobody = new List<KeyValuePair<Guid, Person>>(await dictionary.SearchAsync(tx, "unknown").Result.ToEnumerable()); Assert.AreEqual(0, nobody.Count()); // Search the index for the last name as lower-case with a count limit. This should return one. doeSearch = new List<KeyValuePair<Guid, Person>>(await dictionary.SearchAsync(tx, "doe", count: 1).Result.ToEnumerable()); Assert.AreEqual(1, doeSearch.Count()); var singleActual = doeSearch.Select(x => x.Value).First(); Assert.IsTrue(singleActual == john || singleActual == jane); await tx.CommitAsync(); } } [TestMethod] public async Task MultipleSearchIndexes() { var stateManager = new MockReliableStateManager(); var dictionary = await stateManager.GetOrAddIndexedAsync("test", new SearchableIndex<Guid, Person>("name", (k, p) => p.Name), new SearchableIndex<Guid, Person>("address", (k, p) => p.Address.AddressLine1)); // Add person using normal IReliableDictionary APIs. This should update the index as well. var mark = new Person { Name = "<NAME>", Address = new Address { AddressLine1 = "123 Main St." } }; var jane = new Person { Name = "<NAME>", Address = new Address { AddressLine1 = "456 Johnson St." } }; using (var tx = stateManager.CreateTransaction()) { await dictionary.AddAsync(tx, mark.Id, mark); await dictionary.AddAsync(tx, jane.Id, jane); await tx.CommitAsync(); } using (var tx = stateManager.CreateTransaction()) { // Search for 'Johnson' should return both people (Mark for name match, and Jane for address match). var johnsonSearch = new List<KeyValuePair<Guid, Person>>(await dictionary.SearchAsync(tx, "Johnson").Result.ToEnumerable()); Assert.AreEqual(2, johnsonSearch.Count()); CollectionAssert.Contains(johnsonSearch.Select(x => x.Value).ToArray(), mark); CollectionAssert.Contains(johnsonSearch.Select(x => x.Value).ToArray(), jane); // Search for 'Main' should only return Mark (address match). var mainSearch = new List<KeyValuePair<Guid, Person>>(await dictionary.SearchAsync(tx, "Main").Result.ToEnumerable()); Assert.AreEqual(1, mainSearch.Count()); CollectionAssert.Contains(mainSearch.Select(x => x.Value).ToArray(), mark); // Search for '<NAME> Jane' should return both people ('and' word should be ignored). var markJaneSearch = new List<KeyValuePair<Guid, Person>>(await dictionary.SearchAsync(tx, "<NAME>").Result.ToEnumerable()); Assert.AreEqual(2, markJaneSearch.Count()); CollectionAssert.Contains(markJaneSearch.Select(x => x.Value).ToArray(), mark); CollectionAssert.Contains(markJaneSearch.Select(x => x.Value).ToArray(), jane); // Search for 'Street' should not return anybody. var streetSearch = new List<KeyValuePair<Guid, Person>>(await dictionary.SearchAsync(tx, "Street").Result.ToEnumerable()); Assert.AreEqual(0, streetSearch.Count()); await tx.CommitAsync(); } } } } <|start_filename|>src/ServiceFabric.Extensions.Data.Indexing.Test/Models/Person.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ServiceFabric.Extensions.Data.Indexing.Persistent.Test.Models { public sealed class Person { public Guid Id { get; set; } = Guid.NewGuid(); public string Name { get; set; } public int Age { get; set; } public Address Address { get; set; } public static Person CreateRandom(Random random) { return new Person { Name = new string((char)random.Next('a', 'z'), random.Next(5, 10)), Age = random.Next(20, 50), Address = Address.CreateRandom(random), }; } } } <|start_filename|>src/ServiceFabric.Extensions.Data.Indexing.Test/IndexExtensionsTests.cs<|end_filename|> using System; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.ServiceFabric.Data.Mocks; using Microsoft.ServiceFabric.Data; namespace ServiceFabric.Extensions.Data.Indexing.Persistent.Test { [TestClass] public class IndexExtensionsTests { [TestMethod] public async Task TryGetIndexed_NoIndexes() { var stateManager = new MockReliableStateManager(); var result = await stateManager.TryGetIndexedAsync<int, string>("test"); Assert.IsFalse(result.HasValue); Assert.IsNull(result.Value); Assert.AreEqual(0, await GetReliableStateCountAsync(stateManager)); } [TestMethod] public async Task TryGetIndexed_OneIndex() { var stateManager = new MockReliableStateManager(); var result = await stateManager.TryGetIndexedAsync("test", new FilterableIndex<int, string, string>("index", (k, v) => v)); Assert.IsFalse(result.HasValue); Assert.IsNull(result.Value); Assert.AreEqual(0, await GetReliableStateCountAsync(stateManager)); } [TestMethod] public async Task GetOrAddIndexed_NoIndexes() { var stateManager = new MockReliableStateManager(); var dictionary = await stateManager.GetOrAddIndexedAsync<int, string>("test"); Assert.IsNotNull(dictionary); Assert.AreEqual(1, await GetReliableStateCountAsync(stateManager)); } [TestMethod] public async Task GetOrAddIndexed_OneIndex() { var stateManager = new MockReliableStateManager(); var dictionary = await stateManager.GetOrAddIndexedAsync("test", new FilterableIndex<int, string, string>("index", (k, v) => v)); Assert.IsNotNull(dictionary); Assert.AreEqual(2, await GetReliableStateCountAsync(stateManager)); } [TestMethod] public async Task RemoveIndexed_NoIndexes() { var stateManager = new MockReliableStateManager(); await stateManager.GetOrAddIndexedAsync<int, string>("test"); await stateManager.RemoveIndexedAsync<int, string>("test"); Assert.AreEqual(0, await GetReliableStateCountAsync(stateManager)); } [TestMethod] public async Task RemoveIndexed_OneIndex() { var stateManager = new MockReliableStateManager(); var result = await stateManager.TryGetIndexedAsync("test", new FilterableIndex<int, string, string>("index", (k, v) => v)); await stateManager.RemoveIndexedAsync("test", new FilterableIndex<int, string, string>("index", (k, v) => v)); Assert.AreEqual(0, await GetReliableStateCountAsync(stateManager)); } private static async Task<int> GetReliableStateCountAsync(IReliableStateManager stateManager) { int count = 0; var enumerator = stateManager.GetAsyncEnumerator(); while (await enumerator.MoveNextAsync(CancellationToken.None)) count++; return count; } } } <|start_filename|>src/ServiceFabric.Extensions.Data.Indexing/CollectionExtensions.cs<|end_filename|> using System; using System.Collections.Generic; namespace ServiceFabric.Extensions.Data.Indexing.Persistent { internal static class CollectionExtensions { public static void AddRange<T>(this HashSet<T> set, IEnumerable<T> items) { foreach (var item in items) { set.Add(item); } } public static T[] CopyAndAdd<T>(this T[] array, T value) { if (array == null) throw new ArgumentNullException(nameof(array)); var newArray = new T[array.Length + 1]; Array.Copy(array, newArray, array.Length); newArray[array.Length] = value; return newArray; } public static T[] CopyAndRemove<T>(this T[] array, T value) { if (array == null) throw new ArgumentNullException(nameof(array)); int index = Array.IndexOf(array, value); if (index < 0) throw new KeyNotFoundException(); var newArray = new T[array.Length - 1]; Array.Copy(array, 0, newArray, 0, index); Array.Copy(array, index + 1, newArray, index, newArray.Length - index); return newArray; } } } <|start_filename|>src/ServiceFabric.Extensions.Data.Mocks/MockReliableStateManager.cs<|end_filename|> using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.ServiceFabric.Data.Collections; using Microsoft.ServiceFabric.Data.Notifications; namespace Microsoft.ServiceFabric.Data.Mocks { public class MockReliableStateManager : IReliableStateManager { private readonly ConcurrentDictionary<Uri, IReliableState> _state = new ConcurrentDictionary<Uri, IReliableState>(); private IDictionary<Type, Type> _stateTypeMap = new Dictionary<Type, Type> { { typeof(IReliableDictionary<,>), typeof(MockReliableDictionary<,>) }, { typeof(IReliableDictionary2<,>), typeof(MockReliableDictionary<,>) }, }; public event EventHandler<NotifyTransactionChangedEventArgs> TransactionChanged; public event EventHandler<NotifyStateManagerChangedEventArgs> StateManagerChanged; public ITransaction CreateTransaction() { return new MockTransaction(); } public IAsyncEnumerator<IReliableState> GetAsyncEnumerator() { return new MockAsyncEnumerator<IReliableState>(_state.Values.GetEnumerator()); } public Task<T> GetOrAddAsync<T>(string name) where T : IReliableState { return GetOrAddAsync<T>(GetUri(name)); } public Task<T> GetOrAddAsync<T>(string name, TimeSpan timeout) where T : IReliableState { return GetOrAddAsync<T>(GetUri(name), timeout); } public Task<T> GetOrAddAsync<T>(ITransaction tx, string name) where T : IReliableState { return GetOrAddAsync<T>(tx, GetUri(name)); } public Task<T> GetOrAddAsync<T>(ITransaction tx, string name, TimeSpan timeout) where T : IReliableState { return GetOrAddAsync<T>(tx, GetUri(name), timeout); } public Task<T> GetOrAddAsync<T>(Uri name) where T : IReliableState { return GetOrAddAsync<T>(name, TimeSpan.Zero); } public async Task<T> GetOrAddAsync<T>(Uri name, TimeSpan timeout) where T : IReliableState { using (var tx = CreateTransaction()) { var result = await GetOrAddAsync<T>(tx, name, timeout).ConfigureAwait(false); await tx.CommitAsync().ConfigureAwait(false); return result; } } public Task<T> GetOrAddAsync<T>(ITransaction tx, Uri name) where T : IReliableState { return GetOrAddAsync<T>(tx, name, TimeSpan.Zero); } public Task<T> GetOrAddAsync<T>(ITransaction tx, Uri name, TimeSpan timeout) where T : IReliableState { return Task.FromResult((T)_state.GetOrAdd(name, n => CreateReliableState<T>(n))); } public Task RemoveAsync(string name) { return RemoveAsync(GetUri(name)); } public Task RemoveAsync(string name, TimeSpan timeout) { return RemoveAsync(GetUri(name), timeout); } public Task RemoveAsync(ITransaction tx, string name) { return RemoveAsync(tx, GetUri(name)); } public Task RemoveAsync(ITransaction tx, string name, TimeSpan timeout) { return RemoveAsync(tx, GetUri(name), timeout); } public Task RemoveAsync(Uri name) { return RemoveAsync(name, TimeSpan.Zero); } public async Task RemoveAsync(Uri name, TimeSpan timeout) { using (var tx = CreateTransaction()) { await RemoveAsync(tx, name, timeout).ConfigureAwait(false); await tx.CommitAsync().ConfigureAwait(false); } } public Task RemoveAsync(ITransaction tx, Uri name) { return RemoveAsync(tx, name, TimeSpan.Zero); } public Task RemoveAsync(ITransaction tx, Uri name, TimeSpan timeout) { if (!_state.TryRemove(name, out IReliableState value)) throw new KeyNotFoundException(); return Task.CompletedTask; } public bool TryAddStateSerializer<T>(IStateSerializer<T> stateSerializer) { throw new NotImplementedException(); } public Task<ConditionalValue<T>> TryGetAsync<T>(string name) where T : IReliableState { return TryGetAsync<T>(GetUri(name)); } public Task<ConditionalValue<T>> TryGetAsync<T>(Uri name) where T : IReliableState { if (_state.TryGetValue(name, out IReliableState value)) return Task.FromResult(new ConditionalValue<T>(true, (T)value)); return Task.FromResult(new ConditionalValue<T>()); } private T CreateReliableState<T>(Uri name) where T : IReliableState { var t = typeof(T); if (!_stateTypeMap.TryGetValue(t.GetGenericTypeDefinition(), out Type stateType)) throw new ArgumentException(); return (T)Activator.CreateInstance(stateType.MakeGenericType(t.GetGenericArguments()), name); } private static Uri GetUri(string name) { return new Uri($"urn:{name}"); } } } <|start_filename|>src/ServiceFabric.Extensions.Data.Indexing/ReliableCollectionExtensions.cs<|end_filename|> using Microsoft.ServiceFabric.Data.Collections; using System; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.ServiceFabric.Data; namespace ServiceFabric.Extensions.Data.Indexing.Persistent { internal enum IsolationLevel : byte { Snapshot = 0, ReadCommittedSnapshot = 1, ReadCommitted = 2, ReadRepeatable = 4, } internal static class ReliableCollectionExtensions { public static Task<ConditionalValue<TValue>> TryGetValueAsync<TKey, TValue>(this IReliableDictionary<TKey, TValue> dictionary, ITransaction tx, TKey key, IsolationLevel isolation, TimeSpan timeout, CancellationToken token) where TKey : IComparable<TKey>, IEquatable<TKey> { // Get TStore from dictionary. var dictionaryType = dictionary.GetType(); var dataStoreField = dictionaryType.GetField("dataStore", BindingFlags.NonPublic | BindingFlags.Instance); var store = dataStoreField?.GetValue(dictionary); // If we can't get the underlying TStore from the dictionary, fall back to a read with default isolation level. if (store == null) return dictionary.TryGetValueAsync(tx, key, timeout, token); // Create underlying TStore transaction. var storeType = store.GetType(); var createOrFindTransactionMethod = storeType.GetMethod("CreateOrFindTransaction", new[] { tx.GetType() }); var createOrFindResult = createOrFindTransactionMethod.Invoke(store, new[] { tx }); // Get the TStore transaction from the ConditionalValue<>. var conditionalValueType = createOrFindResult.GetType(); var valueProperty = conditionalValueType.GetProperty("Value", BindingFlags.Public | BindingFlags.Instance); var storeTx = valueProperty.GetValue(createOrFindResult); // Set the isolation level. var storeTxType = storeTx.GetType(); var isolationProperty = storeTxType.GetProperty("Isolation", BindingFlags.Public | BindingFlags.Instance); isolationProperty.SetValue(storeTx, Enum.ToObject(isolationProperty.PropertyType, (byte)isolation)); // Call GetAsync() on TStore. var getAsyncMethod = storeType.GetMethod("GetAsync", new[] { storeTxType, typeof(TKey), typeof(TimeSpan), typeof(CancellationToken) }); return (Task<ConditionalValue<TValue>>)getAsyncMethod.Invoke(store, new[] { storeTx, key, timeout, token }); } } } <|start_filename|>src/ServiceFabric.Extensions.Data.Mocks/MockAsyncEnumerable.cs<|end_filename|> using System; using System.Collections.Generic; namespace Microsoft.ServiceFabric.Data.Mocks { public sealed class MockAsyncEnumerable<T> : IAsyncEnumerable<T> { private readonly IEnumerable<T> _enumerable; public MockAsyncEnumerable(IEnumerable<T> enumerable) { _enumerable = enumerable ?? throw new ArgumentNullException(nameof(enumerable)); } public IAsyncEnumerator<T> GetAsyncEnumerator() { return new MockAsyncEnumerator<T>(_enumerable.GetEnumerator()); } } } <|start_filename|>src/ServiceFabric.Extensions.Data.Indexing/IIndexDefinition.cs<|end_filename|> using System; using System.Threading; using System.Threading.Tasks; using Microsoft.ServiceFabric.Data; namespace ServiceFabric.Extensions.Data.Indexing.Persistent { public interface IIndexDefinition<TKey, TValue> where TKey : IComparable<TKey>, IEquatable<TKey> { string Name { get; } Task<bool> TryGetIndexAsync(IReliableStateManager stateManager, Uri baseName); Task GetOrAddIndexAsync(ITransaction tx, IReliableStateManager stateManager, Uri baseName, TimeSpan timeout); Task RemoveIndexAsync(ITransaction tx, IReliableStateManager stateManager, Uri baseName, TimeSpan timeout); Task AddAsync(ITransaction tx, TKey key, TValue value, TimeSpan timeout, CancellationToken token); Task UpdateAsync(ITransaction tx, TKey key, TValue oldValue, TValue newValue, TimeSpan timeout, CancellationToken token); Task RemoveAsync(ITransaction tx, TKey key, TValue value, TimeSpan timeout, CancellationToken token); Task ClearAsync(TimeSpan timeout, CancellationToken token); } } <|start_filename|>src/ServiceFabric.Extensions.Data.Indexing.Test/Extensions/AsyncEnumerableExtensions.cs<|end_filename|> using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.ServiceFabric.Data; namespace ServiceFabric.Extensions.Data.Indexing.Persistent.Test { public static class AsyncEnumerableExtensions { public static async Task<IEnumerable<T>> ToEnumerable<T>(this IAsyncEnumerable<T> enumerable, CancellationToken token = default(CancellationToken)) { var results = new List<T>(); using (var enumerator = enumerable.GetAsyncEnumerator()) { while (await enumerator.MoveNextAsync(token).ConfigureAwait(false)) { results.Add(enumerator.Current); } } return results; } } }
ashishnegi/service-fabric-indexing
<|start_filename|>larq_compute_engine/core/bgemm/bgemm.h<|end_filename|> #ifndef COMPUTE_ENGINE_CORE_BGEMM_BGEMM_H_ #define COMPUTE_ENGINE_CORE_BGEMM_BGEMM_H_ #include "larq_compute_engine/core/bgemm/kernels_common.h" #include "larq_compute_engine/core/bgemm/ruy_trmul_params.h" #include "ruy/context.h" #include "ruy/context_get_ctx.h" #include "ruy/matrix.h" #include "ruy/platform.h" #include "ruy/prepare_packed_matrices.h" #include "ruy/profiler/instrumentation.h" #include "ruy/trmul.h" #include "tensorflow/lite/kernels/cpu_backend_context.h" #include "tensorflow/lite/kernels/cpu_backend_gemm_params.h" #include "tensorflow/lite/kernels/cpu_backend_gemm_ruy.h" using namespace tflite; using namespace tflite::cpu_backend_gemm; namespace compute_engine { namespace core { namespace bgemm { template <typename AccumScalar, typename DstScalar> void BGemm(const MatrixParams<TBitpacked>& lhs_params, const TBitpacked* lhs_data, const MatrixParams<TBitpacked>& rhs_params, const TBitpacked* rhs_data, const MatrixParams<DstScalar>& dst_params, DstScalar* dst_data, const OutputTransform<DstScalar>& output_transform, CpuBackendContext* context) { ruy::profiler::ScopeLabel label("BGemm (Ruy)"); static_assert(std::is_signed<DstScalar>::value, "The DstScalar should be signed."); // Get ruy context auto ruy_ctx = get_ctx(context->ruy_context()); // Set up the matrix layouts and mul_params. ruy::Matrix<TBitpacked> lhs; ruy::Matrix<TBitpacked> rhs; ruy::Matrix<DstScalar> dst; // We allow these matrices to be cached. Note that this doesn't force them // to be cached; it means that the `cache_policy` of the MatrixParams will // be respected. cpu_backend_gemm::detail::MakeRuyMatrix(lhs_params, lhs_data, &lhs, /*use_caching=*/true); cpu_backend_gemm::detail::MakeRuyMatrix(rhs_params, rhs_data, &rhs, /*use_caching=*/true); cpu_backend_gemm::detail::MakeRuyMatrix(dst_params, dst_data, &dst); // We have to make this a `const` matrix because otherwise gcc will try to // use the non-const versions of `matrix.data()` ruy::Mat<TBitpacked> internal_lhs = ruy::ToInternal((const ruy::Matrix<TBitpacked>)lhs); ruy::Mat<TBitpacked> internal_rhs = ruy::ToInternal((const ruy::Matrix<TBitpacked>)rhs); ruy::Mat<DstScalar> internal_dst = ruy::ToInternal(dst); BinaryMulParams<AccumScalar, DstScalar> mul_params; mul_params.output_transform = output_transform; #if RUY_PLATFORM_NEON constexpr bool HasOptimizedNeonKernel = std::is_same<AccumScalar, std::int16_t>::value || std::is_same<DstScalar, float>::value || std::is_same<DstScalar, std::int8_t>::value; constexpr auto SelectedPath = HasOptimizedNeonKernel ? ruy::Path::kNeon : ruy::Path::kStandardCpp; #else constexpr auto SelectedPath = ruy::Path::kStandardCpp; #endif ruy::TrMulParams bgemm_trmul_params; PopulateBGemmTrMulParams<SelectedPath>(ruy::Transpose(internal_lhs), internal_rhs, internal_dst, mul_params, &bgemm_trmul_params); ruy::PreparePackedMatrices(ruy_ctx, &bgemm_trmul_params); ruy::TrMul(ruy_ctx, &bgemm_trmul_params); ruy_ctx->GetMainAllocator()->FreeAll(); } } // namespace bgemm } // namespace core } // namespace compute_engine #endif // COMPUTE_ENGINE_CORE_BGEMM_BGEMM_H_ <|start_filename|>larq_compute_engine/core/bitpacking/utils.h<|end_filename|> #ifndef COMPUTE_ENGINE_CORE_BITPACKING_UTILS_H_ #define COMPUTE_ENGINE_CORE_BITPACKING_UTILS_H_ #include "larq_compute_engine/core/bitpacking/bitpack.h" #include "tensorflow/lite/kernels/internal/types.h" namespace compute_engine { namespace core { namespace bitpacking { using namespace tflite; inline int GetBitpackedTensorSize(const RuntimeShape& shape) { const int dims = shape.DimensionsCount(); // Pack the tensor along the last dimension const int rows = FlatSizeSkipDim(shape, dims - 1); const int cols = shape.Dims(dims - 1); return GetBitpackedMatrixSize(rows, cols); } // Convenience function for bitpacking a tensor along its last dimension // and updating the tensor shape template <class T> inline void bitpack_tensor(const RuntimeShape& in_shape, const T* in_data, const std::int32_t zero_point, TBitpacked* out_data) { const int dims = in_shape.DimensionsCount(); // Pack the tensor along the last dimension const int rows = FlatSizeSkipDim(in_shape, dims - 1); const int cols = in_shape.Dims(dims - 1); bitpack_matrix(in_data, rows, cols, out_data, zero_point); } // Convenience function for going from a shape to the packed shape inline RuntimeShape bitpacked_shape(const RuntimeShape& in_shape) { const int dims = in_shape.DimensionsCount(); RuntimeShape out_shape(in_shape); out_shape.SetDim(dims - 1, GetBitpackedSize(in_shape.Dims(dims - 1))); return out_shape; } } // namespace bitpacking } // namespace core } // namespace compute_engine #endif // COMPUTE_ENGINE_CORE_BITPACKING_UTILS_H_ <|start_filename|>larq_compute_engine/mlir/tf_tfl_passes.h<|end_filename|> #ifndef LARQ_COMPUTE_ENGINE_MLIR_TF_TFL_PASSES_H_ #define LARQ_COMPUTE_ENGINE_MLIR_TF_TFL_PASSES_H_ #include <functional> #include "larq_compute_engine/mlir/transforms/passes.h" #include "mlir/Pass/PassManager.h" #include "tensorflow/compiler/mlir/lite/quantization/quantization_config.h" namespace tensorflow { // Add the TF to TFLite passes into a pass_manager. void AddTFToLCETFLConversionPasses( const mlir::TFL::QuantizationSpecs& quant_specs, mlir::OpPassManager* pass_manager, const LCETarget target = LCETarget::ARM, const bool experimental_enable_bitpacked_activations = false); } // namespace tensorflow #endif // LARQ_COMPUTE_ENGINE_MLIR_TF_TFL_PASSES_H_ <|start_filename|>larq_compute_engine/core/indirect_bgemm/kernel_8x4x2_aarch64.h<|end_filename|> #ifndef COMPUTE_ENGINE_INDIRECT_BGEMM_KERNEL_8x4x2_AARCH64_H_ #define COMPUTE_ENGINE_INDIRECT_BGEMM_KERNEL_8x4x2_AARCH64_H_ #ifndef __aarch64__ #pragma GCC error "ERROR: This file should only be compiled for Aarch64." #endif #include <arm_neon.h> #include <cstdint> #include <type_traits> #include "larq_compute_engine/core/bconv2d/output_transform.h" #include "larq_compute_engine/core/bconv2d/params.h" #include "larq_compute_engine/core/indirect_bgemm/kernel.h" #include "larq_compute_engine/core/types.h" #include "ruy/profiler/instrumentation.h" #include "tensorflow/lite/kernels/internal/types.h" namespace compute_engine { namespace core { namespace indirect_bgemm { namespace kernel_8x4x2_aarch64 { #define IF_IS_GROUPED(a) ".if %c[is_grouped]\n\t" a ".endif\n\t" // This block of instructions takes as input the activation vector registers // a_0, ..., a_3 and the weight vector registers w_0, ..., w_3, and computes // 'binary multiplication and accumulation' (BMLA) using XOR and popcount // instructions, adding the results to the 16-bit accumulator vector registers // accum_0, ..., accum_3. // It also reloads data for the next loop iteration into a_0, ..., a_3 and // w_0, ..., w_3 from the pointers a_ptr_0, ..., a_ptr_3 and w_ptr. Note that // the accumulator loads use pairs of "load single lane" `ld1` instructions // rather than "load and duplicate" `ld1r` instructions. This is because `ld1r` // of 64-bit elements uses the F0/F1 (ASIMD) pipelines, whereas the 64-bit // single-lane "ld1" instructions use only the L0/L1 (load) pipelines. See // https://github.com/larq/compute-engine/pull/521 for more details. #define XOR_POPCOUNT_ACCUM_LOAD_BLOCK_64 \ "eor v0.16b, %[a_0].16b, %[w_0].16b\n\t" \ "eor v1.16b, %[a_1].16b, %[w_0].16b\n\t" \ "eor v2.16b, %[a_2].16b, %[w_0].16b\n\t" \ "eor v3.16b, %[a_3].16b, %[w_0].16b\n\t" \ "eor v4.16b, %[a_0].16b, %[w_1].16b\n\t" \ "eor v5.16b, %[a_1].16b, %[w_1].16b\n\t" \ "eor v6.16b, %[a_2].16b, %[w_1].16b\n\t" \ "eor v7.16b, %[a_3].16b, %[w_1].16b\n\t" \ "eor v8.16b, %[a_0].16b, %[w_2].16b\n\t" \ "eor v9.16b, %[a_1].16b, %[w_2].16b\n\t" \ "eor v10.16b, %[a_2].16b, %[w_2].16b\n\t" \ "eor v11.16b, %[a_3].16b, %[w_2].16b\n\t" \ "ldr %q[w_0], [%[w_ptr]]\n\t" \ "eor v12.16b, %[a_0].16b, %[w_3].16b\n\t" \ "eor v13.16b, %[a_1].16b, %[w_3].16b\n\t" \ "eor v14.16b, %[a_2].16b, %[w_3].16b\n\t" \ "eor v15.16b, %[a_3].16b, %[w_3].16b\n\t" \ "ldr %q[w_1], [%[w_ptr], #16]\n\t" \ "cnt v0.16b, v0.16b\n\t" \ "cnt v1.16b, v1.16b\n\t" \ "ld1 {%[a_0].d}[0], [%[a_ptr_0]]\n\t" \ "cnt v2.16b, v2.16b\n\t" \ "cnt v3.16b, v3.16b\n\t" \ "ld1 {%[a_1].d}[0], [%[a_ptr_1]]\n\t" \ "cnt v4.16b, v4.16b\n\t" \ "cnt v5.16b, v5.16b\n\t" \ "ld1 {%[a_2].d}[0], [%[a_ptr_2]]\n\t" \ "cnt v6.16b, v6.16b\n\t" \ "cnt v7.16b, v7.16b\n\t" \ "ld1 {%[a_3].d}[0], [%[a_ptr_3]]\n\t" \ "cnt v8.16b, v8.16b\n\t" \ "cnt v9.16b, v9.16b\n\t" \ "ld1 {%[a_0].d}[1], [%[a_ptr_0]], #8\n\t" \ "cnt v10.16b, v10.16b\n\t" \ "cnt v11.16b, v11.16b\n\t" \ "ld1 {%[a_1].d}[1], [%[a_ptr_1]], #8\n\t" \ "cnt v12.16b, v12.16b\n\t" \ "cnt v13.16b, v13.16b\n\t" \ "ld1 {%[a_2].d}[1], [%[a_ptr_2]], #8\n\t" \ "cnt v14.16b, v14.16b\n\t" \ "cnt v15.16b, v15.16b\n\t" \ "ld1 {%[a_3].d}[1], [%[a_ptr_3]], #8\n\t" \ "addp v0.16b, v0.16b, v4.16b\n\t" \ "addp v1.16b, v1.16b, v5.16b\n\t" \ "addp v2.16b, v2.16b, v6.16b\n\t" \ "addp v3.16b, v3.16b, v7.16b\n\t" \ "ldr %q[w_2], [%[w_ptr], #32]\n\t" \ "addp v8.16b, v8.16b, v12.16b\n\t" \ "addp v9.16b, v9.16b, v13.16b\n\t" \ "addp v10.16b, v10.16b, v14.16b\n\t" \ "addp v11.16b, v11.16b, v15.16b\n\t" \ "ldr %q[w_3], [%[w_ptr], #48]\n\t" \ "addp v0.16b, v0.16b, v8.16b\n\t" \ "addp v1.16b, v1.16b, v9.16b\n\t" \ "addp v2.16b, v2.16b, v10.16b\n\t" \ "addp v3.16b, v3.16b, v11.16b\n\t" \ "add %[w_ptr], %[w_ptr], #64\n\t" \ "uadalp %[accum_0].8h, v0.16b\n\t" \ "uadalp %[accum_1].8h, v1.16b\n\t" \ "uadalp %[accum_2].8h, v2.16b\n\t" \ "uadalp %[accum_3].8h, v3.16b\n\t" /** * Accumulation loops * * There are two variants of the accumulation loop: one for when we know the * depth is greater than one, i.e. the number of input channels is greater than * 64; and one for when we know the depth is equal to one, i.e. the number of * input channels is equal to 64. The latter case allows for a slight * optimisation. * * The accumulation loops use inline assembly but are equivalent to the * following pseudocode: * * accum_0 = 0; * accum_1 = 0; * accum_2 = 0; * accum_3 = 0; * * // This block is removed in the depth=1 case * // The first set of activations is already loaded, so this +1 * // ensures that the first 'block' loads the next set of activations. * a_ptr_0 = indirection_ptr[0] + 1; * a_ptr_1 = indirection_ptr[1] + 1; * a_ptr_2 = indirection_ptr[2] + 1; * a_ptr_3 = indirection_ptr[3] + 1; * indirection_ptr += 4; * * int fs = filter_size; * do { * // This loop is removed in the depth=1 case * for (int d = 0; d < depth - 1; d++) { * XOR_POPCOUNT_ACCUM_LOAD_BLOCK_64 * } * * // Before the final inner (depth loop) iteration, set the activation * // pointers so that the activations for the next outer loop iteration * // are loaded correctly. * a_ptr_0 = indirection_ptr[0]; * a_ptr_1 = indirection_ptr[1]; * a_ptr_2 = indirection_ptr[2]; * a_ptr_3 = indirection_ptr[3]; * indirection_ptr += 4; * * XOR_POPCOUNT_ACCUM_LOAD_BLOCK_64 * } while (--fs > 0); */ template <bool IsGrouped> inline void AccumulationLoop_Depth2OrMore( const std::int32_t filter_size, const std::int32_t depth, const std::size_t input_depth_offset, int32x4_t weights[4], int32x4_t activations[4], uint16x8_t accumulators[4], const TBitpacked*& weights_ptr, const TBitpacked* const* indirection_ptr) { ruy::profiler::ScopeLabel label("Accumulation loop (depth > 1)"); // Declare these variables so we can use named registers in the ASM block. const TBitpacked* a_ptr_0; const TBitpacked* a_ptr_1; const TBitpacked* a_ptr_2; const TBitpacked* a_ptr_3; if (IsGrouped) { a_ptr_0 = indirection_ptr[0] + input_depth_offset + 2; a_ptr_1 = indirection_ptr[1] + input_depth_offset + 2; a_ptr_2 = indirection_ptr[2] + input_depth_offset + 2; a_ptr_3 = indirection_ptr[3] + input_depth_offset + 2; } else { a_ptr_0 = indirection_ptr[0] + 2; a_ptr_1 = indirection_ptr[1] + 2; a_ptr_2 = indirection_ptr[2] + 2; a_ptr_3 = indirection_ptr[3] + 2; } auto fs_index = filter_size; asm volatile( // clang-format off "add %[indirection_ptr], %[indirection_ptr], #32\n\t" // w1 is the inner (depth) loop counter "sub w1, %w[depth], #1\n\t" // Zero-out the accumulator registers "movi %[accum_0].8h, #0\n\t" "movi %[accum_1].8h, #0\n\t" "movi %[accum_2].8h, #0\n\t" "movi %[accum_3].8h, #0\n\t" "0:\n\t" // Loop start label "subs w1, w1, #1\n\t" XOR_POPCOUNT_ACCUM_LOAD_BLOCK_64 "bgt 0b\n\t" // Inner loop branch "ldp %[a_ptr_0], %[a_ptr_1], [%[indirection_ptr]]\n\t" "ldp %[a_ptr_2], %[a_ptr_3], [%[indirection_ptr], #16]\n\t" "add %[indirection_ptr], %[indirection_ptr], #32\n\t" "sub w1, %w[depth], #1\n\t" "subs %w[fs_index], %w[fs_index], #1\n\t" IF_IS_GROUPED( "add %[a_ptr_0], %[a_ptr_0], %[input_depth_offset], lsl #2\n" "add %[a_ptr_1], %[a_ptr_1], %[input_depth_offset], lsl #2\n" "add %[a_ptr_2], %[a_ptr_2], %[input_depth_offset], lsl #2\n" "add %[a_ptr_3], %[a_ptr_3], %[input_depth_offset], lsl #2\n") XOR_POPCOUNT_ACCUM_LOAD_BLOCK_64 "bgt 0b\n\t" // Outer loop branch // clang-format on : [accum_0] "=&w"(accumulators[0]), [accum_1] "=&w"(accumulators[1]), [accum_2] "=&w"(accumulators[2]), [accum_3] "=&w"(accumulators[3]), [w_ptr] "+r"(weights_ptr), [indirection_ptr] "+r"(indirection_ptr), [a_ptr_0] "+r"(a_ptr_0), [a_ptr_1] "+r"(a_ptr_1), [a_ptr_2] "+r"(a_ptr_2), [a_ptr_3] "+r"(a_ptr_3), [fs_index] "+r"(fs_index) : [w_0] "w"(weights[0]), [w_1] "w"(weights[1]), [w_2] "w"(weights[2]), [w_3] "w"(weights[3]), [a_0] "w"(activations[0]), [a_1] "w"(activations[1]), [a_2] "w"(activations[2]), [a_3] "w"(activations[3]), [depth] "r"(depth), [input_depth_offset] "r"(input_depth_offset), [is_grouped] "i"(IsGrouped) : "cc", "memory", "x1", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15"); } template <bool IsGrouped> inline void AccumulationLoop_Depth1( const std::int32_t filter_size, const std::size_t input_depth_offset, int32x4_t weights[4], int32x4_t activations[4], uint16x8_t accumulators[4], const TBitpacked*& weights_ptr, const TBitpacked* const* indirection_ptr) { ruy::profiler::ScopeLabel label("Accumulation loop (depth = 1)"); // Declare these variables so we can use named registers in the ASM block. const TBitpacked* a_ptr_0; const TBitpacked* a_ptr_1; const TBitpacked* a_ptr_2; const TBitpacked* a_ptr_3; auto fs_index = filter_size; asm volatile( // clang-format off "add %[indirection_ptr], %[indirection_ptr], #32\n\t" // Zero-out the accumulator registers "movi %[accum_0].8h, #0\n\t" "movi %[accum_1].8h, #0\n\t" "movi %[accum_2].8h, #0\n\t" "movi %[accum_3].8h, #0\n\t" "0:\n\t" // Loop label "ldp %[a_ptr_0], %[a_ptr_1], [%[indirection_ptr]]\n\t" "ldp %[a_ptr_2], %[a_ptr_3], [%[indirection_ptr], #16]\n\t" "add %[indirection_ptr], %[indirection_ptr], #32\n\t" "subs %w[fs_index], %w[fs_index], #1\n\t" IF_IS_GROUPED( "add %[a_ptr_0], %[a_ptr_0], %[input_depth_offset], lsl #2\n" "add %[a_ptr_1], %[a_ptr_1], %[input_depth_offset], lsl #2\n" "add %[a_ptr_2], %[a_ptr_2], %[input_depth_offset], lsl #2\n" "add %[a_ptr_3], %[a_ptr_3], %[input_depth_offset], lsl #2\n") XOR_POPCOUNT_ACCUM_LOAD_BLOCK_64 "bgt 0b\n\t" // Loop branch // clang-format on : [accum_0] "=&w"(accumulators[0]), [accum_1] "=&w"(accumulators[1]), [accum_2] "=&w"(accumulators[2]), [accum_3] "=&w"(accumulators[3]), [w_ptr] "+r"(weights_ptr), [indirection_ptr] "+r"(indirection_ptr), [a_ptr_0] "=&r"(a_ptr_0), [a_ptr_1] "=&r"(a_ptr_1), [a_ptr_2] "=&r"(a_ptr_2), [a_ptr_3] "=&r"(a_ptr_3), [fs_index] "+r"(fs_index) : [w_0] "w"(weights[0]), [w_1] "w"(weights[1]), [w_2] "w"(weights[2]), [w_3] "w"(weights[3]), [a_0] "w"(activations[0]), [a_1] "w"(activations[1]), [a_2] "w"(activations[2]), [a_3] "w"(activations[3]), [input_depth_offset] "r"(input_depth_offset), [is_grouped] "i"(IsGrouped) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15"); } #undef XOR_POPCOUNT_ACCUM_LOAD_BLOCK_64 /** * Output transforms * * These destination-type-specific functions take the accumulator values and * perform the output transform, before storing the results in the output array. * They additionally reload data into the weight and activation registers for * the first iteration of the next accumulation loop. */ // Float output transform template <bool IsGrouped> inline void OutputTransformAndLoadNextAndStore( std::int32_t& c_out_index, const std::size_t input_depth_offset, const std::int32_t group_end_output_channel, uint16x8_t accumulators[4], int32x4_t weights[4], int32x4_t activations[4], const bconv2d::OutputTransform<float>& output_transform, const TBitpacked* weights_ptr, const TBitpacked* const* indirection_ptr, float*& output_ptr_0, float*& output_ptr_1, float*& output_ptr_2, float*& output_ptr_3) { ruy::profiler::ScopeLabel label("Float output transform and store"); // Declare result registers. float32x4x2_t results[4]; asm("ldp x0, x1, [%[indirection_ptr]]\n\t" "ldp x2, x3, [%[indirection_ptr], #16]\n\t" // Use "unsigned shift left long" instructions to perform the // back-transformation left-shift and extend the result to int32. "ld1r {v0.4s}, [%[clamp_min_addr]]\n\t" "ushll %[result_00].4s, %[accum_0].4h, #1\n\t" "ushll %[result_10].4s, %[accum_1].4h, #1\n\t" "ld1r {v1.4s}, [%[clamp_max_addr]]\n\t" "ushll %[result_20].4s, %[accum_2].4h, #1\n\t" "ushll %[result_30].4s, %[accum_3].4h, #1\n\t" "ldr q2, [%[multiplier_addr]]\n\t" "ushll2 %[result_31].4s, %[accum_3].8h, #1\n\t" "ushll2 %[result_21].4s, %[accum_2].8h, #1\n\t" "ldr q3, [%[multiplier_addr], #16]\n\t" "ushll2 %[result_11].4s, %[accum_1].8h, #1\n\t" "ushll2 %[result_01].4s, %[accum_0].8h, #1\n\t" IF_IS_GROUPED("add x0, x0, %[input_depth_offset], lsl #2\n" "add x1, x1, %[input_depth_offset], lsl #2\n" "add x2, x2, %[input_depth_offset], lsl #2\n" "add x3, x3, %[input_depth_offset], lsl #2\n") // Perform clamping "ldr q4, [%[bias_addr]]\n\t" "smax %[result_30].4s, %[result_30].4s, v0.4s\n\t" "smax %[result_31].4s, %[result_31].4s, v0.4s\n\t" "ldr q5, [%[bias_addr], #16]\n\t" "smax %[result_20].4s, %[result_20].4s, v0.4s\n\t" "smax %[result_21].4s, %[result_21].4s, v0.4s\n\t" "ldr %q[w_0], [%[w_ptr], #-64]\n\t" "smax %[result_10].4s, %[result_10].4s, v0.4s\n\t" "smax %[result_11].4s, %[result_11].4s, v0.4s\n\t" "ldr %q[w_1], [%[w_ptr], #-48]\n\t" "smax %[result_00].4s, %[result_00].4s, v0.4s\n\t" "smax %[result_01].4s, %[result_01].4s, v0.4s\n\t" "ld1 {%[a_0].d}[0], [x0]\n\t" "smin %[result_30].4s, %[result_30].4s, v1.4s\n\t" "smin %[result_31].4s, %[result_31].4s, v1.4s\n\t" "ld1 {%[a_1].d}[0], [x1]\n\t" "smin %[result_20].4s, %[result_20].4s, v1.4s\n\t" "smin %[result_21].4s, %[result_21].4s, v1.4s\n\t" "ld1 {%[a_2].d}[0], [x2]\n\t" "smin %[result_10].4s, %[result_10].4s, v1.4s\n\t" "smin %[result_11].4s, %[result_11].4s, v1.4s\n\t" "ld1 {%[a_3].d}[0], [x3]\n\t" "smin %[result_00].4s, %[result_00].4s, v1.4s\n\t" "smin %[result_01].4s, %[result_01].4s, v1.4s\n\t" // Convert to float, multiply by the multiplier, and add the bias. Note // that the float conversion instructions ("scvtf") are *very* slow and // block the Neon pipeline. It is therefore important for optimal // performance to interleave the float multiply and add instructions // between the "scvtf" instructions. "ld1 {%[a_0].d}[1], [x0]\n\t" "scvtf %[result_30].4s, %[result_30].4s\n\t" "scvtf %[result_31].4s, %[result_31].4s\n\t" "ld1 {%[a_1].d}[1], [x1]\n\t" "scvtf %[result_20].4s, %[result_20].4s\n\t" "fmul %[result_30].4s, %[result_30].4s, v2.4s\n\t" "scvtf %[result_21].4s, %[result_21].4s\n\t" "ld1 {%[a_2].d}[1], [x2]\n\t" "fmul %[result_31].4s, %[result_31].4s, v3.4s\n\t" "fadd %[result_30].4s, %[result_30].4s, v4.4s\n\t" "scvtf %[result_10].4s, %[result_10].4s\n\t" "ld1 {%[a_3].d}[1], [x3]\n\t" "fmul %[result_20].4s, %[result_20].4s, v2.4s\n\t" "fadd %[result_31].4s, %[result_31].4s, v5.4s\n\t" "scvtf %[result_11].4s, %[result_11].4s\n\t" "ldr %q[w_2], [%[w_ptr], #-32]\n\t" "fmul %[result_21].4s, %[result_21].4s, v3.4s\n\t" "fadd %[result_20].4s, %[result_20].4s, v4.4s\n\t" "scvtf %[result_00].4s, %[result_00].4s\n\t" "ldr %q[w_3], [%[w_ptr], #-16]\n\t" "fmul %[result_10].4s, %[result_10].4s, v2.4s\n\t" "fadd %[result_21].4s, %[result_21].4s, v5.4s\n\t" "scvtf %[result_01].4s, %[result_01].4s\n\t" "fmul %[result_11].4s, %[result_11].4s, v3.4s\n\t" "fadd %[result_10].4s, %[result_10].4s, v4.4s\n\t" "fmul %[result_00].4s, %[result_00].4s, v2.4s\n\t" "fmul %[result_01].4s, %[result_01].4s, v3.4s\n\t" "fadd %[result_11].4s, %[result_11].4s, v5.4s\n\t" "fadd %[result_00].4s, %[result_00].4s, v4.4s\n\t" "fadd %[result_01].4s, %[result_01].4s, v5.4s\n\t" : [w_0] "=&w"(weights[0]), [w_1] "=&w"(weights[1]), [w_2] "=&w"(weights[2]), [w_3] "=&w"(weights[3]), [a_0] "=&w"(activations[0]), [a_1] "=&w"(activations[1]), [a_2] "=&w"(activations[2]), [a_3] "=&w"(activations[3]), [result_00] "=&w"(results[0].val[0]), [result_01] "=&w"(results[0].val[1]), [result_10] "=&w"(results[1].val[0]), [result_11] "=&w"(results[1].val[1]), [result_20] "=&w"(results[2].val[0]), [result_21] "=&w"(results[2].val[1]), [result_30] "=&w"(results[3].val[0]), [result_31] "=&w"(results[3].val[1]) : [accum_0] "w"(accumulators[0]), [accum_1] "w"(accumulators[1]), [accum_2] "w"(accumulators[2]), [accum_3] "w"(accumulators[3]), [clamp_min_addr] "r"(&output_transform.clamp_min), [clamp_max_addr] "r"(&output_transform.clamp_max), [multiplier_addr] "r"(output_transform.multiplier + c_out_index), [bias_addr] "r"(output_transform.bias + c_out_index), [w_ptr] "r"(weights_ptr), [indirection_ptr] "r"(indirection_ptr), [input_depth_offset] "r"(input_depth_offset), [is_grouped] "i"(IsGrouped) : "memory", "x0", "x1", "x2", "x3", "v0", "v1", "v2", "v3", "v4", "v5"); if (LCE_LIKELY(group_end_output_channel - c_out_index >= 8)) { vst1q_f32(output_ptr_3, results[3].val[0]); vst1q_f32(output_ptr_3 + 4, results[3].val[1]); output_ptr_3 += 8; vst1q_f32(output_ptr_2, results[2].val[0]); vst1q_f32(output_ptr_2 + 4, results[2].val[1]); output_ptr_2 += 8; vst1q_f32(output_ptr_1, results[1].val[0]); vst1q_f32(output_ptr_1 + 4, results[1].val[1]); output_ptr_1 += 8; vst1q_f32(output_ptr_0, results[0].val[0]); vst1q_f32(output_ptr_0 + 4, results[0].val[1]); output_ptr_0 += 8; c_out_index += 8; } else { #define STORE_SINGLE_ELEMENT_LOW(index) \ vst1q_lane_f32(output_ptr_3++, results[3].val[0], index); \ vst1q_lane_f32(output_ptr_2++, results[2].val[0], index); \ vst1q_lane_f32(output_ptr_1++, results[1].val[0], index); \ vst1q_lane_f32(output_ptr_0++, results[0].val[0], index); #define STORE_SINGLE_ELEMENT_HIGH(index) \ vst1q_lane_f32(output_ptr_3++, results[3].val[1], index); \ vst1q_lane_f32(output_ptr_2++, results[2].val[1], index); \ vst1q_lane_f32(output_ptr_1++, results[1].val[1], index); \ vst1q_lane_f32(output_ptr_0++, results[0].val[1], index); STORE_SINGLE_ELEMENT_LOW(0) if (group_end_output_channel - c_out_index >= 2) { STORE_SINGLE_ELEMENT_LOW(1) if (group_end_output_channel - c_out_index >= 3) { STORE_SINGLE_ELEMENT_LOW(2) if (group_end_output_channel - c_out_index >= 4) { STORE_SINGLE_ELEMENT_LOW(3) if (group_end_output_channel - c_out_index >= 5) { STORE_SINGLE_ELEMENT_HIGH(0) if (group_end_output_channel - c_out_index >= 6) { STORE_SINGLE_ELEMENT_HIGH(1) if (group_end_output_channel - c_out_index >= 7) { STORE_SINGLE_ELEMENT_HIGH(2) } } } } } } #undef STORE_SINGLE_ELEMENT_LOW #undef STORE_SINGLE_ELEMENT_HIGH c_out_index = group_end_output_channel; } } // Int8 output transform template <bool IsGrouped> inline void OutputTransformAndLoadNextAndStore( std::int32_t& c_out_index, const std::size_t input_depth_offset, const std::int32_t group_end_output_channel, uint16x8_t accumulators[4], int32x4_t weights[4], int32x4_t activations[4], const bconv2d::OutputTransform<std::int8_t>& output_transform, const TBitpacked* weights_ptr, const TBitpacked* const* indirection_ptr, std::int8_t*& output_ptr_0, std::int8_t*& output_ptr_1, std::int8_t*& output_ptr_2, std::int8_t*& output_ptr_3) { ruy::profiler::ScopeLabel label("Int8 output transform and store"); // Declare result registers. These are wider than we need for just the final // int8 values, which is necessary for intermediate results. int8x16x2_t results[4]; asm("ldp x0, x1, [%[indirection_ptr]]\n\t" "ldp x2, x3, [%[indirection_ptr], #16]\n\t" // Use "unsigned shift left long" instructions to perform the // back-transformation left-shift and extend the result to int32. "ld1r {v0.4s}, [%[clamp_min_addr]]\n\t" "ushll %[result_00].4s, %[accum_0].4h, #1\n\t" "ushll %[result_10].4s, %[accum_1].4h, #1\n\t" "ld1r {v1.4s}, [%[clamp_max_addr]]\n\t" "ushll %[result_20].4s, %[accum_2].4h, #1\n\t" "ushll %[result_30].4s, %[accum_3].4h, #1\n\t" "ldr q2, [%[multiplier_addr]]\n\t" "ushll2 %[result_31].4s, %[accum_3].8h, #1\n\t" "ushll2 %[result_21].4s, %[accum_2].8h, #1\n\t" "ldr q3, [%[multiplier_addr], #16]\n\t" "ushll2 %[result_11].4s, %[accum_1].8h, #1\n\t" "ushll2 %[result_01].4s, %[accum_0].8h, #1\n\t" IF_IS_GROUPED("add x0, x0, %[input_depth_offset], lsl #2\n" "add x1, x1, %[input_depth_offset], lsl #2\n" "add x2, x2, %[input_depth_offset], lsl #2\n" "add x3, x3, %[input_depth_offset], lsl #2\n") // Perform clamping "ldr q4, [%[bias_addr]]\n\t" "smax %[result_30].4s, %[result_30].4s, v0.4s\n\t" "smax %[result_31].4s, %[result_31].4s, v0.4s\n\t" "ldr q5, [%[bias_addr], #16]\n\t" "smax %[result_20].4s, %[result_20].4s, v0.4s\n\t" "smax %[result_21].4s, %[result_21].4s, v0.4s\n\t" "ldr %q[w_0], [%[w_ptr], #-64]\n\t" "smax %[result_10].4s, %[result_10].4s, v0.4s\n\t" "smax %[result_11].4s, %[result_11].4s, v0.4s\n\t" "ldr %q[w_1], [%[w_ptr], #-48]\n\t" "smax %[result_00].4s, %[result_00].4s, v0.4s\n\t" "smax %[result_01].4s, %[result_01].4s, v0.4s\n\t" "ld1 {%[a_0].d}[0], [x0]\n\t" "smin %[result_30].4s, %[result_30].4s, v1.4s\n\t" "smin %[result_31].4s, %[result_31].4s, v1.4s\n\t" "ld1 {%[a_1].d}[0], [x1]\n\t" "smin %[result_20].4s, %[result_20].4s, v1.4s\n\t" "smin %[result_21].4s, %[result_21].4s, v1.4s\n\t" "ld1 {%[a_2].d}[0], [x2]\n\t" "smin %[result_10].4s, %[result_10].4s, v1.4s\n\t" "smin %[result_11].4s, %[result_11].4s, v1.4s\n\t" "ld1 {%[a_3].d}[0], [x3]\n\t" "smin %[result_00].4s, %[result_00].4s, v1.4s\n\t" "smin %[result_01].4s, %[result_01].4s, v1.4s\n\t" // Convert to float, multiply by the multiplier, add the bias, convert // back to integer, and use a series of "saturating extract narrow" // instructions to narrow the result to Int8. Note that the float // conversion instructions ("scvtf" and "fcvtns") are *very* slow and // block the Neon pipeline. It is therefore important for optimal // performance to interleave other instructions between them. "ld1 {%[a_0].d}[1], [x0]\n\t" "scvtf %[result_30].4s, %[result_30].4s\n\t" "scvtf %[result_31].4s, %[result_31].4s\n\t" "ld1 {%[a_1].d}[1], [x1]\n\t" "scvtf %[result_20].4s, %[result_20].4s\n\t" "fmul %[result_30].4s, %[result_30].4s, v2.4s\n\t" "scvtf %[result_21].4s, %[result_21].4s\n\t" "ld1 {%[a_2].d}[1], [x2]\n\t" "fmul %[result_31].4s, %[result_31].4s, v3.4s\n\t" "fadd %[result_30].4s, %[result_30].4s, v4.4s\n\t" "scvtf %[result_10].4s, %[result_10].4s\n\t" "ld1 {%[a_3].d}[1], [x3]\n\t" "fmul %[result_20].4s, %[result_20].4s, v2.4s\n\t" "fadd %[result_31].4s, %[result_31].4s, v5.4s\n\t" "scvtf %[result_11].4s, %[result_11].4s\n\t" "ldr %q[w_2], [%[w_ptr], #-32]\n\t" "fmul %[result_21].4s, %[result_21].4s, v3.4s\n\t" "fadd %[result_20].4s, %[result_20].4s, v4.4s\n\t" "fcvtns %[result_30].4s, %[result_30].4s\n\t" "ldr %q[w_3], [%[w_ptr], #-16]\n\t" "fmul %[result_10].4s, %[result_10].4s, v2.4s\n\t" "fadd %[result_21].4s, %[result_21].4s, v5.4s\n\t" "fcvtns %[result_31].4s, %[result_31].4s\n\t" "sqxtn %[result_30].4h, %[result_30].4s\n\t" "fmul %[result_11].4s, %[result_11].4s, v3.4s\n\t" "scvtf %[result_00].4s, %[result_00].4s\n\t" "sqxtn2 %[result_30].8h, %[result_31].4s\n\t" "fadd %[result_10].4s, %[result_10].4s, v4.4s\n\t" "scvtf %[result_01].4s, %[result_01].4s\n\t" "fmul %[result_00].4s, %[result_00].4s, v2.4s\n\t" "fadd %[result_11].4s, %[result_11].4s, v5.4s\n\t" "fcvtns %[result_20].4s, %[result_20].4s\n\t" "fmul %[result_01].4s, %[result_01].4s, v3.4s\n\t" "fadd %[result_00].4s, %[result_00].4s, v4.4s\n\t" "fcvtns %[result_21].4s, %[result_21].4s\n\t" "sqxtn %[result_20].4h, %[result_20].4s\n\t" "fadd %[result_01].4s, %[result_01].4s, v5.4s\n\t" "fcvtns %[result_10].4s, %[result_10].4s\n\t" "sqxtn2 %[result_20].8h, %[result_21].4s\n\t" "fcvtns %[result_11].4s, %[result_11].4s\n\t" "sqxtn %[result_10].4h, %[result_10].4s\n\t" "sqxtn %[result_30].8b, %[result_30].8h\n\t" "fcvtns %[result_00].4s, %[result_00].4s\n\t" "sqxtn2 %[result_10].8h, %[result_11].4s\n\t" "sqxtn %[result_20].8b, %[result_20].8h\n\t" "fcvtns %[result_01].4s, %[result_01].4s\n\t" "sqxtn %[result_00].4h, %[result_00].4s\n\t" "sqxtn2 %[result_00].8h, %[result_01].4s\n\t" "sqxtn %[result_10].8b, %[result_10].8h\n\t" "sqxtn %[result_00].8b, %[result_00].8h\n\t" : [w_0] "=&w"(weights[0]), [w_1] "=&w"(weights[1]), [w_2] "=&w"(weights[2]), [w_3] "=&w"(weights[3]), [a_0] "=&w"(activations[0]), [a_1] "=&w"(activations[1]), [a_2] "=&w"(activations[2]), [a_3] "=&w"(activations[3]), [result_00] "=&w"(results[0].val[0]), [result_01] "=&w"(results[0].val[1]), [result_10] "=&w"(results[1].val[0]), [result_11] "=&w"(results[1].val[1]), [result_20] "=&w"(results[2].val[0]), [result_21] "=&w"(results[2].val[1]), [result_30] "=&w"(results[3].val[0]), [result_31] "=&w"(results[3].val[1]) : [accum_0] "w"(accumulators[0]), [accum_1] "w"(accumulators[1]), [accum_2] "w"(accumulators[2]), [accum_3] "w"(accumulators[3]), [clamp_min_addr] "r"(&output_transform.clamp_min), [clamp_max_addr] "r"(&output_transform.clamp_max), [multiplier_addr] "r"(output_transform.multiplier + c_out_index), [bias_addr] "r"(output_transform.bias + c_out_index), [w_ptr] "r"(weights_ptr), [indirection_ptr] "r"(indirection_ptr), [input_depth_offset] "r"(input_depth_offset), [is_grouped] "i"(IsGrouped) : "memory", "x0", "x1", "x2", "x3", "v0", "v1", "v2", "v3", "v4", "v5"); if (LCE_LIKELY(group_end_output_channel - c_out_index >= 8)) { vst1_s8(output_ptr_3, vget_low_s8(results[3].val[0])); output_ptr_3 += 8; vst1_s8(output_ptr_2, vget_low_s8(results[2].val[0])); output_ptr_2 += 8; vst1_s8(output_ptr_1, vget_low_s8(results[1].val[0])); output_ptr_1 += 8; vst1_s8(output_ptr_0, vget_low_s8(results[0].val[0])); output_ptr_0 += 8; c_out_index += 8; } else { #define STORE_SINGLE_ELEMENT(index) \ vst1_lane_s8(output_ptr_3++, vget_low_s8(results[3].val[0]), index); \ vst1_lane_s8(output_ptr_2++, vget_low_s8(results[2].val[0]), index); \ vst1_lane_s8(output_ptr_1++, vget_low_s8(results[1].val[0]), index); \ vst1_lane_s8(output_ptr_0++, vget_low_s8(results[0].val[0]), index); STORE_SINGLE_ELEMENT(0) if (group_end_output_channel - c_out_index >= 2) { STORE_SINGLE_ELEMENT(1) if (group_end_output_channel - c_out_index >= 3) { STORE_SINGLE_ELEMENT(2) if (group_end_output_channel - c_out_index >= 4) { STORE_SINGLE_ELEMENT(3) if (group_end_output_channel - c_out_index >= 5) { STORE_SINGLE_ELEMENT(4) if (group_end_output_channel - c_out_index >= 6) { STORE_SINGLE_ELEMENT(5) if (group_end_output_channel - c_out_index >= 7) { STORE_SINGLE_ELEMENT(6) } } } } } } #undef STORE_SINGLE_ELEMENT c_out_index = group_end_output_channel; } } #undef IF_IS_GROUPED } // namespace kernel_8x4x2_aarch64 /** * A 8x4x2 Neon micro-kernel for float or int8 output on Aarch64. */ template <typename DstScalar, bool Depth2OrMore, bool IsGrouped> class Kernel8x4x2Aarch64 : public Kernel { static_assert(std::is_same<DstScalar, float>::value || std::is_same<DstScalar, std::int8_t>::value, ""); static_assert(sizeof(TBitpacked) == 4, ""); const bconv2d::OutputTransform<DstScalar> output_transform; public: Kernel8x4x2Aarch64( const bconv2d::BConv2DParams* bconv2d_params, const RuntimeShape& bitpacked_input_shape, const RuntimeShape& output_shape, const bconv2d::OutputTransform<DstScalar>& output_transform) : Kernel(8, 4, 2, bconv2d_params, bitpacked_input_shape, output_shape), output_transform(output_transform) {} void Run(const std::int32_t pixel_start, const std::int32_t pixel_end, void* output_ptr) const override { ruy::profiler::ScopeLabel label( "Indirect BGEMM block (8x4x2, Aarch64 optimised)"); TFLITE_DCHECK_GE(this->input_depth, 1); TFLITE_DCHECK_GE(this->output_channels, 1); TFLITE_DCHECK_GE(this->filter_size, 1); TFLITE_DCHECK_GE(this->groups, 1); TFLITE_DCHECK_EQ(this->input_depth % this->groups, 0); TFLITE_DCHECK_EQ(this->output_channels % this->groups, 0); const auto input_depth_per_group = this->input_depth / this->groups; const auto output_channels_per_group = this->output_channels / this->groups; if (this->filter_size < 1 || input_depth_per_group < 1 || output_channels_per_group < 1) { return; } for (std::int32_t p_index = pixel_start; p_index < pixel_end; p_index += 4) { const TBitpacked* weights_ptr = this->packed_weights.data(); const TBitpacked* const* indirection_ptr = this->indirection_buffer.data() + p_index * this->filter_size; auto output_ptr_0 = reinterpret_cast<DstScalar*>(output_ptr) + p_index * this->output_channels; auto output_ptr_1 = output_ptr_0 + this->output_channels; auto output_ptr_2 = output_ptr_1 + this->output_channels; auto output_ptr_3 = output_ptr_2 + this->output_channels; // At the end of the output array we might get a block where the number of // pixels is less than 4. When this happens we set the 'leftover' output // pointer equal to the first output pointer, so that there's no risk of // writing beyond the array bounds. At the end we write to the output // array 'back to front' so that the outputs for the first pixel are // written last, which means that the result will still be correct. const std::int32_t remaining_pixels = pixel_end - p_index; if (remaining_pixels < 4) { output_ptr_3 = output_ptr_0; if (remaining_pixels < 3) { output_ptr_2 = output_ptr_0; if (remaining_pixels < 2) { output_ptr_1 = output_ptr_0; } } } // Pre-load weights and activations. int32x4_t weights[4] = { vld1q_s32(weights_ptr), vld1q_s32(weights_ptr + 4), vld1q_s32(weights_ptr + 8), vld1q_s32(weights_ptr + 12)}; weights_ptr += 16; int32x4_t activations[4] = { vreinterpretq_s32_s64( vld1q_dup_s64((std::int64_t*)indirection_ptr[0])), vreinterpretq_s32_s64( vld1q_dup_s64((std::int64_t*)indirection_ptr[1])), vreinterpretq_s32_s64( vld1q_dup_s64((std::int64_t*)indirection_ptr[2])), vreinterpretq_s32_s64( vld1q_dup_s64((std::int64_t*)indirection_ptr[3]))}; std::size_t input_depth_offset = 0; std::int32_t group_end_output_channel = output_channels_per_group; std::int32_t c_out_index = 0; do { uint16x8_t accumulators[4]; if (Depth2OrMore) { kernel_8x4x2_aarch64::AccumulationLoop_Depth2OrMore<IsGrouped>( this->filter_size, input_depth_per_group / 2, input_depth_offset, weights, activations, accumulators, weights_ptr, indirection_ptr); } else { kernel_8x4x2_aarch64::AccumulationLoop_Depth1<IsGrouped>( this->filter_size, input_depth_offset, weights, activations, accumulators, weights_ptr, indirection_ptr); } std::int32_t next_group_end_output_channel = group_end_output_channel; if (IsGrouped && c_out_index >= group_end_output_channel - 8) { input_depth_offset += input_depth_per_group; next_group_end_output_channel = group_end_output_channel + output_channels_per_group; } kernel_8x4x2_aarch64::OutputTransformAndLoadNextAndStore<IsGrouped>( c_out_index, input_depth_offset, group_end_output_channel, accumulators, weights, activations, output_transform, weights_ptr, indirection_ptr, output_ptr_0, output_ptr_1, output_ptr_2, output_ptr_3); if (IsGrouped) { group_end_output_channel = next_group_end_output_channel; } } while (c_out_index < this->output_channels); } } }; } // namespace indirect_bgemm } // namespace core } // namespace compute_engine #endif // COMPUTE_ENGINE_INDIRECT_BGEMM_KERNEL_8x4x2_AARCH64_H_ <|start_filename|>larq_compute_engine/core/bitpacking/tests/bitpack_aarch64_test.cc<|end_filename|> #include "larq_compute_engine/core/bitpacking/bitpack_aarch64.h" #include <gmock/gmock.h> #include <array> #include <cstdint> #include <vector> #include "larq_compute_engine/core/bitpacking/bitpack.h" #include "larq_compute_engine/core/types.h" namespace compute_engine { namespace core { namespace bitpacking { template <typename DstScalar> void test_bitpacking_order(const int num_4x32_blocks) { static_assert(std::is_same<DstScalar, float>::value || std::is_same<DstScalar, std::int8_t>::value, ""); const int num_blocks = 4 * num_4x32_blocks; const int n = 32 * num_blocks; DstScalar input[n]; const DstScalar zero_point = std::is_same<DstScalar, std::int8_t>::value ? -42 : 0; TBitpacked output[num_blocks]; for (auto i = 0; i < n; ++i) { // Try to get the position of bit i by packing the one-hot vector e_i for (auto j = 0; j < n; ++j) { if (j == i) input[j] = zero_point - 5; else input[j] = zero_point + 5; } // Run bitpacking bitpack_aarch64_4x32(input, num_blocks, output, zero_point); // See where in the output the bit has popped up int bit_index = -1; int bits_found = 0; for (auto j = 0; j < num_blocks; ++j) { for (auto k = 0; k < 32; ++k) { if (output[j] & (TBitpacked(1) << k)) { bit_index = k + j * 32; bits_found++; } } } // We should have exactly one enabled bit... EXPECT_EQ(bits_found, 1); // ...and it should be in the i^th position. EXPECT_EQ(bit_index, i); } } TEST(BitpackingAarch64, Float_1x4x32) { test_bitpacking_order<float>(1); } TEST(BitpackingAarch64, Float_2x4x32) { test_bitpacking_order<float>(2); } TEST(BitpackingAarch64, Float_3x4x32) { test_bitpacking_order<float>(3); } TEST(BitpackingAarch64, Float_11x4x32) { test_bitpacking_order<float>(11); } TEST(BitpackingAarch64, Float_17x4x32) { test_bitpacking_order<float>(17); } TEST(BitpackingAarch64, Int8_1x4x32) { test_bitpacking_order<std::int8_t>(1); } TEST(BitpackingAarch64, Int8_2x4x32) { test_bitpacking_order<std::int8_t>(2); } TEST(BitpackingAarch64, Int8_3x4x32) { test_bitpacking_order<std::int8_t>(3); } TEST(BitpackingAarch64, Int8_11x4x32) { test_bitpacking_order<std::int8_t>(11); } TEST(BitpackingAarch64, Int8_17x4x32) { test_bitpacking_order<std::int8_t>(17); } } // namespace bitpacking } // namespace core } // namespace compute_engine <|start_filename|>larq_compute_engine/core/bconv2d/params.h<|end_filename|> #ifndef LARQ_COMPUTE_ENGINE_CORE_BCONV2D_PARAMS #define LARQ_COMPUTE_ENGINE_CORE_BCONV2D_PARAMS #include <cstdint> #include "tensorflow/lite/c/builtin_op_data.h" namespace compute_engine { namespace core { namespace bconv2d { struct BConv2DParams { // Input and filter shapes std::int32_t filter_width; std::int32_t filter_height; std::int32_t channels_in; std::int32_t channels_out; std::int32_t groups; // Strides std::int32_t stride_height; std::int32_t stride_width; // Dilations std::int32_t dilation_height_factor; std::int32_t dilation_width_factor; // Padding TfLitePadding padding_type; TfLitePaddingValues padding_values; std::int32_t pad_value; // Must be 0 or 1 }; } // namespace bconv2d } // namespace core } // namespace compute_engine #endif // LARQ_COMPUTE_ENGINE_CORE_BCONV2D_PARAMS <|start_filename|>larq_compute_engine/core/bgemm/kernels_common.h<|end_filename|> #ifndef COMPUTE_ENGINE_CORE_BGEMM_KERNELS_COMMON_H_ #define COMPUTE_ENGINE_CORE_BGEMM_KERNELS_COMMON_H_ #include "larq_compute_engine/core/bconv2d/output_transform.h" #include "larq_compute_engine/core/types.h" #include "ruy/kernel_common.h" namespace compute_engine { namespace core { namespace bgemm { using namespace ruy; using ruy::Order; // To fix Windows build using namespace bitpacking; using bconv2d::OutputTransform; // Our version of `ruy::MulParams`; The original is in `ruy/mul_params.h`. // We simply use our `OutputTransform` struct. template <typename tAccumScalar, typename tDstScalar> struct BinaryMulParams { using AccumScalar = tAccumScalar; using DstScalar = tDstScalar; OutputTransform<DstScalar> output_transform; using StandardCppKernelLhsLayout = FixedKernelLayout<Order::kColMajor, 1, 1>; using StandardCppKernelRhsLayout = FixedKernelLayout<Order::kColMajor, 1, 1>; }; // A specialisation for the writing-bitpacked-output case, where the C++ LHS // kernel layout must have `bitpacking_bitwidth` columns (so that that many // channels can be bitpacked at once). template <typename tAccumScalar> struct BinaryMulParams<tAccumScalar, TBitpacked> { using AccumScalar = tAccumScalar; using DstScalar = TBitpacked; OutputTransform<DstScalar> output_transform; using StandardCppKernelLhsLayout = FixedKernelLayout<Order::kColMajor, 1, bitpacking_bitwidth>; using StandardCppKernelRhsLayout = FixedKernelLayout<Order::kColMajor, 1, 1>; }; template <typename DstScalar, int LhsCols, int RhsCols> struct BinaryKernelParams { const TBitpacked* lhs_base_ptr; const TBitpacked* rhs_base_ptr; DstScalar* dst_base_ptr; std::int32_t start_row; std::int32_t start_col; std::int32_t last_row; std::int32_t last_col; std::int32_t dst_rows; std::int32_t dst_cols; std::int32_t lhs_stride; std::int32_t rhs_stride; std::int32_t dst_stride; std::int32_t depth; OutputTransform<DstScalar> output_transform; DstScalar dst_tmp_buf[LhsCols * RhsCols]; // Used for float or int8 output }; template <typename AccumScalar, typename DstScalar, int LhsCols, int RhsCols> inline void MakeBinaryKernelParams( const PMat<TBitpacked>& lhs, const PMat<TBitpacked>& rhs, int start_row, int start_col, int end_row, int end_col, Mat<DstScalar>* dst, const BinaryMulParams<AccumScalar, DstScalar>& mul_params, BinaryKernelParams<DstScalar, LhsCols, RhsCols>* params) { RUY_DCHECK_EQ(start_row % LhsCols, 0); RUY_DCHECK_EQ(start_col % RhsCols, 0); RUY_DCHECK_EQ(end_row % LhsCols, 0); RUY_DCHECK_EQ(end_col % RhsCols, 0); if (std::is_same<DstScalar, TBitpacked>::value) { RUY_DCHECK_EQ(start_row % 8, 0); RUY_DCHECK_EQ(end_row % 8, 0); } params->lhs_base_ptr = lhs.data + start_row * lhs.layout.stride; params->rhs_base_ptr = rhs.data + start_col * rhs.layout.stride; if (std::is_same<DstScalar, TBitpacked>::value) { // When writing bitpacked output with multiple threads, the start/end row // will not necessarily be aligned to a TBitpacked boundary (though they are // guaranteed to be aligned to a byte boundary). For example, start_row // could be 8, in which case we'd be writing into the second byte of each // TBitpacked value. Hence the need for char pointer arithmetic. params->dst_base_ptr = (DstScalar*)((char*)(dst->data.get() + start_col * GetBitpackedSize(dst->layout.stride)) + start_row / 8); } else { params->dst_base_ptr = dst->data.get() + start_col * dst->layout.stride + start_row; } params->start_row = start_row; params->start_col = start_col; params->last_row = end_row - LhsCols; params->last_col = end_col - RhsCols; params->dst_rows = dst->layout.rows; params->dst_cols = dst->layout.cols; params->lhs_stride = sizeof(TBitpacked) * lhs.layout.stride; params->rhs_stride = sizeof(TBitpacked) * rhs.layout.stride; params->dst_stride = sizeof(DstScalar) * (std::is_same<DstScalar, TBitpacked>::value ? GetBitpackedSize(dst->layout.stride) : dst->layout.stride); params->depth = lhs.layout.rows; // This is a four word copy, but that's okay. params->output_transform = mul_params.output_transform; RUY_DCHECK_LT(params->last_row, params->dst_rows); RUY_DCHECK_LT(params->last_col, params->dst_cols); } } // namespace bgemm } // namespace core } // namespace compute_engine #endif // COMPUTE_ENGINE_CORE_BGEMM_KERNELS_COMMON_H_ <|start_filename|>larq_compute_engine/core/bgemm/ruy_trmul_params.h<|end_filename|> #ifndef COMPUTE_ENGINE_CORE_BGEMM_RUY_TRMUL_PARAMS_H_ #define COMPUTE_ENGINE_CORE_BGEMM_RUY_TRMUL_PARAMS_H_ #include "larq_compute_engine/core/bgemm/kernels.h" #include "larq_compute_engine/core/bgemm/ruy_pack.h" #include "ruy/create_trmul_params.h" #include "ruy/mul_params.h" #include "ruy/path.h" #include "ruy/trmul_params.h" namespace compute_engine { namespace core { namespace bgemm { inline bool IsColMajorTrMul(const ruy::TrMulParams& params) { return IsColMajor(params.src[Side::kLhs].layout) && IsColMajor(params.src[Side::kRhs].layout) && IsColMajor(params.dst.layout); } template <ruy::Path ThePath, typename DstScalar, typename MulParamsType> void PopulateBGemmTrMulParams(const Mat<TBitpacked>& lhs, const Mat<TBitpacked>& rhs, Mat<DstScalar>& dst, const MulParamsType& mul_params, ruy::TrMulParams* params) { params->src[Side::kLhs] = EraseType(lhs); params->src[Side::kRhs] = EraseType(rhs); params->dst = EraseType(dst); static_assert(alignof(MulParamsType) <= kMaxMulParamsAlignment, ""); static_assert(sizeof(MulParamsType) <= kMaxMulParamsSize, ""); static_assert(std::is_trivially_copyable<MulParamsType>::value, ""); auto* dst_mul_params = reinterpret_cast<MulParamsType*>(params->mul_params_bytes); std::memcpy(dst_mul_params, &mul_params, sizeof(MulParamsType)); // Optimised code paths only support all matrices being column-major if (!IsColMajorTrMul(*params) && ThePath != ruy::Path::kStandardCpp) { PopulateBGemmTrMulParams<ruy::Path::kStandardCpp>(lhs, rhs, dst, mul_params, params); return; }; using Kernel = BGemmKernel<ThePath, DstScalar, MulParamsType>; using LhsKernelLayout = typename Kernel::LhsLayout; using RhsKernelLayout = typename Kernel::RhsLayout; params->path = ThePath; ruy::detail::CreatePackedMatrix<TBitpacked, TBitpacked>( Side::kLhs, ToKernelLayout<LhsKernelLayout>(), params); ruy::detail::CreatePackedMatrix<TBitpacked, TBitpacked>( Side::kRhs, ToKernelLayout<RhsKernelLayout>(), params); params->run_pack[Side::kLhs] = &RunRuyPack<ThePath, LhsKernelLayout>; params->run_pack[Side::kRhs] = &RunRuyPack<ThePath, RhsKernelLayout>; params->run_kernel = &RunBGemmKernel<ThePath, DstScalar, MulParamsType>; } } // namespace bgemm } // namespace core } // namespace compute_engine #endif // COMPUTE_ENGINE_CORE_BGEMM_RUY_TRMUL_PARAMS_H_ <|start_filename|>larq_compute_engine/tflite/kernels/utils.h<|end_filename|> #ifndef COMPUTE_ENGINE_TFLITE_KERNEL_UTILS_H #define COMPUTE_ENGINE_TFLITE_KERNEL_UTILS_H #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/schema/schema_generated.h" namespace tflite { // Converts the flatbuffer activation to what is used at runtime. inline TfLiteFusedActivation ConvertActivation( ActivationFunctionType activation) { switch (activation) { case ActivationFunctionType_NONE: return kTfLiteActNone; case ActivationFunctionType_RELU: return kTfLiteActRelu; case ActivationFunctionType_RELU_N1_TO_1: return kTfLiteActReluN1To1; case ActivationFunctionType_RELU6: return kTfLiteActRelu6; default: return kTfLiteActNone; } } // Converts the flatbuffer padding enum to TFLite padding inline TfLitePadding ConvertPadding(Padding padding) { switch (padding) { case Padding_SAME: return kTfLitePaddingSame; case Padding_VALID: return kTfLitePaddingValid; } return kTfLitePaddingUnknown; } // Converts the TFLite padding enum to what is used at runtime. inline PaddingType RuntimePaddingType(TfLitePadding padding) { switch (padding) { case TfLitePadding::kTfLitePaddingSame: return PaddingType::kSame; case TfLitePadding::kTfLitePaddingValid: return PaddingType::kValid; case TfLitePadding::kTfLitePaddingUnknown: default: return PaddingType::kNone; } } } // namespace tflite #endif // COMPUTE_ENGINE_TFLITE_KERNEL_UTILS_H <|start_filename|>larq_compute_engine/mlir/transforms/bitpack_weights.cc<|end_filename|> #include "larq_compute_engine/mlir/ir/lce_ops.h" #include "larq_compute_engine/mlir/transforms/bitpack.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/IR/PatternMatch.h" #include "mlir/Pass/Pass.h" #include "mlir/Transforms/GreedyPatternRewriteDriver.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" namespace mlir { namespace TFL { namespace { struct BitpackWeightsLCE : public PassWrapper<BitpackWeightsLCE, FunctionPass> { void runOnFunction() override; }; bool IsConv2DFilter(Attribute filter) { if (!filter.isa<DenseElementsAttr>()) return false; auto filter_type = filter.getType().cast<ShapedType>(); return filter_type.getElementType().isF32() && filter_type.getShape().size() == 4; } #include "larq_compute_engine/mlir/transforms/generated_bitpack_weights.inc" void BitpackWeightsLCE::runOnFunction() { OwningRewritePatternList patterns(&getContext()); auto func = getFunction(); TFL::populateWithGenerated(patterns); (void)applyPatternsAndFoldGreedily(func, std::move(patterns)); } } // namespace // Creates an instance of the TensorFlow dialect BitpackWeights pass. std::unique_ptr<OperationPass<FuncOp>> CreateBitpackWeightsLCEPass() { return std::make_unique<BitpackWeightsLCE>(); } static PassRegistration<BitpackWeightsLCE> pass("tfl-lce-bitpack-weights", "Bitpack binary weights"); } // namespace TFL } // namespace mlir <|start_filename|>larq_compute_engine/mlir/tf_to_tfl_flatbuffer.cc<|end_filename|> #include "larq_compute_engine/mlir/tf_to_tfl_flatbuffer.h" #include "llvm/Support/raw_ostream.h" #include "mlir/IR/BuiltinOps.h" #include "mlir/Pass/PassManager.h" #include "tensorflow/compiler/mlir/lite/flatbuffer_export.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_executor.h" #include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/stream_executor/lib/statusor.h" namespace tensorflow { namespace { using mlir::ModuleOp; using mlir::Operation; bool IsControlFlowV1Op(Operation* op) { return mlir::isa<mlir::tf_executor::SwitchOp, mlir::tf_executor::MergeOp, mlir::tf_executor::EnterOp, mlir::tf_executor::ExitOp, mlir::tf_executor::NextIterationSinkOp, mlir::tf_executor::NextIterationSourceOp>(op); } mlir::LogicalResult IsValidGraph(mlir::ModuleOp module) { auto result = module.walk([&](Operation* op) { return IsControlFlowV1Op(op) ? mlir::WalkResult::interrupt() : mlir::WalkResult::advance(); }); if (result.wasInterrupted()) { module.emitError( "The graph has Control Flow V1 ops. TFLite converter doesn't support " "Control Flow V1 ops. Consider using Control Flow V2 ops instead. See " "https://www.tensorflow.org/api_docs/python/tf/compat/v1/" "enable_control_flow_v2."); return mlir::failure(); } return mlir::success(); } // Truncates names to a maximum length of ~50 characters since LCE op location // names can be very long otherwise. class TruncateOpOrArgLocNameMapper : public OpOrArgLocNameMapper { protected: std::string GetName(OpOrVal op_or_val) override { auto name = OpOrArgLocNameMapper::GetName(op_or_val); if (name.length() > 50) return name.substr(0, 50); return name; } }; } // namespace Status ConvertTFExecutorToFlatbuffer(mlir::ModuleOp module, bool export_to_mlir, std::string* result, mlir::PassManager* pass_manager) { // Explicitly disable dumping Op details on failures. module.getContext()->printOpOnDiagnostic(false); // Register a warning handler only log to std out. mlir::ScopedDiagnosticHandler s( module.getContext(), [](mlir::Diagnostic& diag) { if (diag.getSeverity() == mlir::DiagnosticSeverity::Warning) { for (auto& note : diag.getNotes()) { std::cout << note.str() << "\n"; LOG(WARNING) << note.str() << "\n"; } } return mlir::failure(); }); mlir::StatusScopedDiagnosticHandler statusHandler(module.getContext(), /*propagate=*/true); if (failed(IsValidGraph(module)) || failed(pass_manager->run(module))) { return statusHandler.ConsumeStatus(); } if (export_to_mlir) { llvm::raw_string_ostream os(*result); module.print(os); return Status::OK(); } // This is the only modification compared to the upstream tensorflow file TruncateOpOrArgLocNameMapper op_or_arg_name_mapper; tflite::FlatbufferExportOptions options; options.emit_builtin_tflite_ops = true; options.emit_custom_ops = true; options.op_or_arg_name_mapper = &op_or_arg_name_mapper; if (!tflite::MlirToFlatBufferTranslateFunction(module, options, result)) { return statusHandler.ConsumeStatus(); } if (mlir::failed(module.verify())) { return tensorflow::errors::Unknown("Final module is invalid"); } return Status::OK(); } } // namespace tensorflow <|start_filename|>larq_compute_engine/core/bgemm/kernels_arm32.h<|end_filename|> #ifndef COMPUTE_ENGINE_CORE_BGEMM_KERNELS_ARM32_H_ #define COMPUTE_ENGINE_CORE_BGEMM_KERNELS_ARM32_H_ #include <cstdint> #include "larq_compute_engine/core/bgemm/kernels_common.h" #include "larq_compute_engine/core/types.h" #include "ruy/profiler/instrumentation.h" using namespace ruy; #if RUY_PLATFORM_NEON && RUY_OPT(ASM) && RUY_PLATFORM_NEON_32 #define RUY_OFFSET_LHS_BASE_PTR 0 #define RUY_OFFSET_RHS_BASE_PTR 4 #define RUY_OFFSET_DST_BASE_PTR 8 #define RUY_OFFSET_START_ROW 12 #define RUY_OFFSET_START_COL 16 #define RUY_OFFSET_LAST_ROW 20 #define RUY_OFFSET_LAST_COL 24 #define RUY_OFFSET_DST_ROWS 28 #define RUY_OFFSET_DST_COLS 32 #define RUY_OFFSET_LHS_STRIDE 36 #define RUY_OFFSET_RHS_STRIDE 40 #define RUY_OFFSET_DST_STRIDE 44 #define RUY_OFFSET_DEPTH 48 #define RUY_OFFSET_OUTPUT_TRANSFORM_CLAMP_MIN 52 #define RUY_OFFSET_OUTPUT_TRANSFORM_CLAMP_MAX 56 #define RUY_OFFSET_OUTPUT_TRANSFORM_MULTIPLIER 60 #define RUY_OFFSET_OUTPUT_TRANSFORM_BIAS 64 #define RUY_STACK_OFFSET_SIZE 96 #define RUY_STACK_OFFSET_DST_COL_PTR 0 #define RUY_STACK_OFFSET_DST_PTR 16 #define RUY_STACK_OFFSET_ROW 32 #define RUY_STACK_OFFSET_COL 48 #define RUY_STACK_OFFSET_LHS_COL_PTR 64 #define RUY_STACK_OFFSET_RHS_COL_PTR 80 template <typename Params> void CheckOffsetsInKernelParams(const Params&) { static_assert(offsetof(Params, lhs_base_ptr) == RUY_OFFSET_LHS_BASE_PTR, ""); static_assert(offsetof(Params, rhs_base_ptr) == RUY_OFFSET_RHS_BASE_PTR, ""); static_assert(offsetof(Params, dst_base_ptr) == RUY_OFFSET_DST_BASE_PTR, ""); static_assert(offsetof(Params, start_row) == RUY_OFFSET_START_ROW, ""); static_assert(offsetof(Params, start_col) == RUY_OFFSET_START_COL, ""); static_assert(offsetof(Params, last_row) == RUY_OFFSET_LAST_ROW, ""); static_assert(offsetof(Params, last_col) == RUY_OFFSET_LAST_COL, ""); static_assert(offsetof(Params, lhs_stride) == RUY_OFFSET_LHS_STRIDE, ""); static_assert(offsetof(Params, rhs_stride) == RUY_OFFSET_RHS_STRIDE, ""); static_assert(offsetof(Params, dst_stride) == RUY_OFFSET_DST_STRIDE, ""); static_assert(offsetof(Params, depth) == RUY_OFFSET_DEPTH, ""); const std::size_t OT_OFFSET = offsetof(Params, output_transform); // For float output static_assert(OT_OFFSET + offsetof(OutputTransform<float>, clamp_min) == RUY_OFFSET_OUTPUT_TRANSFORM_CLAMP_MIN, ""); static_assert(OT_OFFSET + offsetof(OutputTransform<float>, clamp_max) == RUY_OFFSET_OUTPUT_TRANSFORM_CLAMP_MAX, ""); static_assert(OT_OFFSET + offsetof(OutputTransform<float>, multiplier) == RUY_OFFSET_OUTPUT_TRANSFORM_MULTIPLIER, ""); static_assert(OT_OFFSET + offsetof(OutputTransform<float>, bias) == RUY_OFFSET_OUTPUT_TRANSFORM_BIAS, ""); // For int8 output static_assert(OT_OFFSET + offsetof(OutputTransform<std::int8_t>, clamp_min) == RUY_OFFSET_OUTPUT_TRANSFORM_CLAMP_MIN, ""); static_assert(OT_OFFSET + offsetof(OutputTransform<std::int8_t>, clamp_max) == RUY_OFFSET_OUTPUT_TRANSFORM_CLAMP_MAX, ""); static_assert( OT_OFFSET + offsetof(OutputTransform<std::int8_t>, multiplier) == RUY_OFFSET_OUTPUT_TRANSFORM_MULTIPLIER, ""); static_assert(OT_OFFSET + offsetof(OutputTransform<std::int8_t>, bias) == RUY_OFFSET_OUTPUT_TRANSFORM_BIAS, ""); } #define MAKE_ZERO(reg) "vmov.s8 " #reg ", #0\n" #define IF_FLOAT_OUTPUT(a) ".if %c[float_output]\n" a ".endif\n" #define IF_INT8_OUTPUT(a) ".if %c[int8_output]\n" a ".endif\n" #define IF_FLOAT_ELIF_INT8_OUTPUT(a, b) \ ".if %c[float_output]\n" a ".elseif %c[int8_output]\n" b ".endif\n" // clang-format off #define LCE_BMLA(Vd, Vr, Vl0, Vl1, Vl2, Vl3) \ "veor.s8 q12, " #Vr", " #Vl0 "\n" \ "veor.s8 q13, " #Vr", " #Vl1 "\n" \ "veor.s8 q14, " #Vr", " #Vl2 "\n" \ "veor.s8 q15, " #Vr", " #Vl3 "\n" \ "vcnt.s8 q12, q12\n" \ "vcnt.s8 q13, q13\n" \ "vcnt.s8 q14, q14\n" \ "vcnt.s8 q15, q15\n" \ "vpadd.i8 d24, d24, d25\n" \ "vpadd.i8 d25, d26, d27\n" \ "vpadd.i8 d28, d28, d29\n" \ "vpadd.i8 d29, d30, d31\n" \ "vpadd.i8 d24, d24, d25\n" \ "vpadd.i8 d25, d28, d29\n" \ "vpaddl.u8 q12, q12\n" \ "vpadal.u16 " #Vd" , q12\n" // clang-format on // This is a very naive and first attempt on using the SIMD registers for BGEMM. // The following optimizations still need to be implemented: // 1. Using the entire register space which the architecture provides. This can // be achieved in two ways: // - 4x4 destination matrices and unrolling the depth loop // - 8x8 destination matrices (requires dymanic changing of temporary // registers in BMLA) // 2. taking advantage of out-of-order cpu by dual dispatching the load/compute // instructions // The asm kernel below has the following NEON register allocation: // // v8, v9, v10, v11 are int32 accumulators. // During accumulation, v0 -- v3 are used to load data from LHS and // v4 -- v7 from RHS: // // int32 RHS 4x4 block // /--------------------------------------\ // |v4.s[0] ... v7.s[0] | // | ... ... | // |v4.s[3] ... v7.s[3] | // \--------------------------------------/ // int32 LHS 4x4 block // /--------------------\ /--------------------------------------\ // |v0.s[0] ... v0.s[3] | |v8.s[0] ... v11.s[0] | // |v1.s[0] ... v1.s[3] | |v8.s[1] ... v11.s[1] | // |v2.s[0] ... v2.s[3] | |v8.s[2] ... v11.s[2] | // |v3.s[0] ... v3.s[3] | |v8.s[3] ... v11.s[3] | // \--------------------/ \--------------------------------------/ // int32 accumulators 4x4 block // // No attempt had been made so far at implementing the RUY_OPT_MAX_STREAMING // optimization for this kernel. template <typename DstScalar> void BinaryKernelNeon4x4(BinaryKernelParams<DstScalar, 4, 4>& params) { CheckOffsetsInKernelParams(params); ruy::profiler::ScopeLabel label( "Binary Kernel (4x4) (kNeon, optimized for out-of-order cores)"); static_assert(sizeof(TBitpacked) == 4, "Correctness of this function relies on the size of TBitpacked " "being 4 bytes."); TBitpacked* lhs_col_ptr = const_cast<TBitpacked*>(params.lhs_base_ptr); TBitpacked* rhs_col_ptr = const_cast<TBitpacked*>(params.rhs_base_ptr); TBitpacked* lhs_ptr = lhs_col_ptr; TBitpacked* rhs_ptr = rhs_col_ptr; DstScalar* dst_col_ptr = params.dst_base_ptr; DstScalar* dst_ptr = dst_col_ptr; int row = params.start_row; int col = params.start_col; asm volatile( "sub sp, sp, #" RUY_STR(RUY_STACK_OFFSET_SIZE) "\n" // auto dst_col_ptr = params.dst_base_ptr; "ldr r1, [%[params], #" RUY_STR(RUY_OFFSET_DST_BASE_PTR) "]\n" "str r1, [sp, #" RUY_STR(RUY_STACK_OFFSET_DST_COL_PTR) "]\n" // auto dst_ptr = dst_col_ptr; "ldr r2, [%[params], #" RUY_STR(RUY_OFFSET_DST_BASE_PTR) "]\n" "str r2, [sp, #" RUY_STR(RUY_STACK_OFFSET_DST_PTR) "]\n" // auto row = params.start_row "ldr r1, [%[params], #" RUY_STR(RUY_OFFSET_START_ROW) "]\n" "str r1, [sp, #" RUY_STR(RUY_STACK_OFFSET_ROW) "]\n" // auto col = params.start_col "ldr r3, [%[params], #" RUY_STR(RUY_OFFSET_START_COL) "]\n" "str r3, [sp, #" RUY_STR(RUY_STACK_OFFSET_COL) "]\n" // auto lhs_col_ptr = params.lhs_base_ptr "ldr r1, [%[params], #" RUY_STR(RUY_OFFSET_LHS_BASE_PTR) "]\n" "str r1, [sp, #" RUY_STR(RUY_STACK_OFFSET_LHS_COL_PTR) "]\n" // auto rhs_col_ptr = params.rhs_base_ptr "ldr r2, [%[params], #" RUY_STR(RUY_OFFSET_RHS_BASE_PTR) "]\n" "str r2, [sp, #" RUY_STR(RUY_STACK_OFFSET_RHS_COL_PTR) "]\n" // Clear accumulators. MAKE_ZERO(q8) MAKE_ZERO(q9) MAKE_ZERO(q10) MAKE_ZERO(q11) // Load the first 64 bytes of LHS and RHS data. "vld1.32 {d0, d1, d2, d3}, [%[lhs_ptr]]!\n" "vld1.32 {d4, d5, d6, d7}, [%[lhs_ptr]]!\n" "vld1.32 {d8, d9, d10, d11}, [%[rhs_ptr]]!\n" "vld1.32 {d12, d13, d14, d15}, [%[rhs_ptr]]!\n" // w1 is the number of levels of depth that we have already loaded // LHS and RHS data for. The RHS is stored in col-wise. Therefore, for 32-bit elements, // one register can hold 4 levels of depth. "mov r1, #4\n" // Main loop of the whole GEMM, over rows and columns of the // destination matrix. "1:\n" LCE_BMLA(q8, q4, q0, q1, q2, q3) LCE_BMLA(q9, q5, q0, q1, q2, q3) LCE_BMLA(q10, q6, q0, q1, q2, q3) LCE_BMLA(q11, q7, q0, q1, q2, q3) // Accumulation loop "ldr r2, [%[params], #" RUY_STR(RUY_OFFSET_DEPTH) "]\n" "cmp r1, r2\n" "beq 79f\n" "2:\n" "vld1.32 {d0, d1, d2, d3}, [%[lhs_ptr]]!\n" "vld1.32 {d4, d5, d6, d7}, [%[lhs_ptr]]!\n" "vld1.32 {d8, d9, d10, d11}, [%[rhs_ptr]]!\n" "vld1.32 {d12, d13, d14, d15}, [%[rhs_ptr]]!\n" "add r1, r1, #4\n" "ldr r2, [%[params], #" RUY_STR(RUY_OFFSET_DEPTH) "]\n" "cmp r1, r2\n" LCE_BMLA(q8, q4, q0, q1, q2, q3) LCE_BMLA(q9, q5, q0, q1, q2, q3) LCE_BMLA(q10, q6, q0, q1, q2, q3) LCE_BMLA(q11, q7, q0, q1, q2, q3) "blt 2b\n" "79:\n" // End of accumulation. The registers v8 -- v11 contain the final // int32 accumulator values of the current 4x4 destination block. // Logic to advance to the next block in preparation for the next // iteration of the main loop. For now, we only want to compute // the LHS and RHS data pointers, lhs_col_ptr and rhs_col_ptr. We are // not yet ready to update the values of row and col, as we still need // the current values for the rest of the work on the current block. "ldr r3, [%[params], #" RUY_STR(RUY_OFFSET_LAST_ROW) "]\n" "ldr r1, [sp, #" RUY_STR(RUY_STACK_OFFSET_ROW) "]\n" "cmp r1, r3\n" // Have we finished the last row? "bge 4f\n" // If finished last row, go to 4 // Not finished last row: then advance to next row. "ldr r1, [%[params], #" RUY_STR(RUY_OFFSET_LHS_STRIDE) "]\n" "ldr r4, [sp, #" RUY_STR(RUY_STACK_OFFSET_LHS_COL_PTR) "]\n" "add r4, r4, r1, lsl #2\n" "str r4, [sp, #" RUY_STR(RUY_STACK_OFFSET_LHS_COL_PTR) "]\n" "b 5f\n" "4:\n" // Finished last row... "ldr r5, [%[params], #" RUY_STR(RUY_OFFSET_LHS_BASE_PTR) "]\n" // Go back to first row "str r5, [sp, #" RUY_STR(RUY_STACK_OFFSET_LHS_COL_PTR) "]\n" // Now we need to advance to the next column. If we already // finished the last column, then in principle we are done, however // we can't just return here, as we need to allow the end work of the // current block to complete. The good news is that at this point it // doesn't matter what data we load for the next column, since // we will exit from the main loop below before actually storing // anything computed from that data. "ldr r4, [%[params], #" RUY_STR(RUY_OFFSET_LAST_COL) "]\n" "ldr r8, [sp, #" RUY_STR(RUY_STACK_OFFSET_COL) "]\n" "cmp r8, r4\n" // Have we finished the last column? "bge 5f\n" // If yes, just carry on without updating the column pointer. // Not finished last column: then advance to next column. "ldr r1, [%[params], #" RUY_STR(RUY_OFFSET_RHS_STRIDE) "]\n" "ldr r10, [sp, #" RUY_STR(RUY_STACK_OFFSET_RHS_COL_PTR) "]\n" "add r10, r10, r1, lsl #2\n" "str r10, [sp, #" RUY_STR(RUY_STACK_OFFSET_RHS_COL_PTR) "]\n" "5:\n" // Set the LHS and RHS data pointers to the start of the columns just // computed. "ldr r4, [sp, #" RUY_STR(RUY_STACK_OFFSET_LHS_COL_PTR) "]\n" "mov %[lhs_ptr], r4\n" "ldr r5, [sp, #" RUY_STR(RUY_STACK_OFFSET_RHS_COL_PTR) "]\n" "mov %[rhs_ptr], r5\n" // post-accumulation transformation: // // q13 = |BKADD|BKADD|BKADD|BKADD| // q14 = |MULT0|MULT1|MULT2|MULT3| // q15 = |BIAS0|BIAS1|BIAS2|BIAS3| // // Load multiplication bias "ldr r1, [%[params], #" RUY_STR(RUY_OFFSET_OUTPUT_TRANSFORM_MULTIPLIER) "]\n" // Offset these base pointers as needed given the current row, col. "ldr r8, [sp, #" RUY_STR(RUY_STACK_OFFSET_ROW) "]\n" "add r1, r1, r8, lsl #2\n" // Load 4 bias-multiplication values. "vld1.32 {d28, d29}, [r1]!\n" // Load addition bias, r8 still holds "row offset" "ldr r1, [%[params], #" RUY_STR(RUY_OFFSET_OUTPUT_TRANSFORM_BIAS) "]\n" // Offset these base pointers as needed given the current row, col. "add r1, r1, r8, lsl #2\n" // Load 4 bias-addition values. "vld1.32 {d30, d31}, [r1]!\n" // Now that we know what LHS and RHS data the next iteration of the // main loop will need to load, we start loading the first 64 bytes of // each of LHS and RHS, into v0 -- v3 and v4 -- v7 as we don't need // them anymore in the rest of the work on the current block. "vld1.32 {d0, d1, d2, d3}, [%[lhs_ptr]]!\n" "vld1.32 {d4, d5, d6, d7}, [%[lhs_ptr]]!\n" "vld1.32 {d8, d9, d10, d11}, [%[rhs_ptr]]!\n" "vld1.32 {d12, d13, d14, d15}, [%[rhs_ptr]]!\n" // Load the clamp_max bound (in parallel with the shift) "ldr r1, [%[params], #" RUY_STR(RUY_OFFSET_OUTPUT_TRANSFORM_CLAMP_MIN) "]\n" "vdup q12.32, r1 \n" // clamp_min // Perform the backtransformation shift (in int32) "vshl q8.s32, q8.s32, #1\n" "vshl q9.s32, q9.s32, #1\n" "vshl q10.s32, q10.s32, #1\n" "vshl q11.s32, q11.s32, #1\n" // Load the clamp_max bound (in parallel with the clamp_min) "ldr r2, [%[params], #" RUY_STR(RUY_OFFSET_OUTPUT_TRANSFORM_CLAMP_MAX) "]\n" "vdup q13.32, r2\n" // clamp_max // Perform the activation function, by clamping // Apply the clamp_min bound "vmax q8.s32, q8.s32, q12.s32\n" "vmax q9.s32, q9.s32, q12.s32\n" "vmax q10.s32, q10.s32, q12.s32\n" "vmax q11.s32, q11.s32, q12.s32\n" // Apply the clamp_max bound "vmin q8.s32, q8.s32, q13.s32\n" "vmin q9.s32, q9.s32, q13.s32\n" "vmin q10.s32, q10.s32, q13.s32\n" "vmin q11.s32, q11.s32, q13.s32\n" // Convert to single precision float "vcvt.f32.s32 q8, q8\n" "vcvt.f32.s32 q9, q9\n" "vcvt.f32.s32 q10, q10\n" "vcvt.f32.s32 q11, q11\n" // Perform the post multiplications "vmul.f32 q8, q8, q14\n" "vmul.f32 q9, q9, q14\n" "vmul.f32 q10, q10, q14\n" "vmul.f32 q11, q11, q14\n" // Perform the post additions "vadd.f32 q8, q8, q15\n" "vadd.f32 q9, q9, q15\n" "vadd.f32 q10, q10, q15\n" "vadd.f32 q11, q11, q15\n" IF_INT8_OUTPUT( // Convert to signed integer, rounding to nearest. // Arm32 NEON has an instruction (vcvtr) to convert from float->int // with rounding-to-nearest behaviour, but for some reason when used here // truncation (rounding-to-zero) behaviour was observed instead. It's // unclear what the issue is - perhaps QEMU doesn't correctly emulate the // rounding behaviour? // The work-around is to first convert from float to fixed-point (24 // integer bits, 8 fractional bits)... "vcvt.s32.f32 q8, q8, #8\n" "vcvt.s32.f32 q9, q9, #8\n" "vcvt.s32.f32 q10, q10, #8\n" "vcvt.s32.f32 q11, q11, #8\n" // ...and then use "vector saturating shift right and narrow, by immediate // value, with rounding" instructions to round to the nearest integer and // simultaneously narrow the result to int16. "vqrshrn.s32 d16, q8, #8\n" "vqrshrn.s32 d18, q9, #8\n" "vqrshrn.s32 d20, q10, #8\n" "vqrshrn.s32 d22, q11, #8\n" // Narrow to int8 with "signed saturating extract narrow" instructions. "vqmovn.s16 d16, q8\n" "vqmovn.s16 d18, q9\n" "vqmovn.s16 d20, q10\n" "vqmovn.s16 d22, q11\n" ) // Done post-accumuation transformation. // Compute how much of the 4x4 block of destination values that // we have computed, fit in the destination matrix. Typically, all of // it fits, but when the destination matrix shape is not a multiple // of 4x4, there are some 4x4 blocks along the boundaries that do // not fit entirely. "ldr r1, [%[params], #" RUY_STR(RUY_OFFSET_DST_ROWS) "]\n" "ldr r8, [sp, #" RUY_STR(RUY_STACK_OFFSET_ROW) "]\n" "sub r1, r1, r8\n" "ldr r2, [%[params], #" RUY_STR(RUY_OFFSET_DST_COLS) "]\n" "ldr r4, [sp, #" RUY_STR(RUY_STACK_OFFSET_COL) "]\n" "sub r2, r2, r4\n" "mov r3, #4\n" "mov r5, #4\n" "cmp r1, #4\n" // Compute r1 = how many rows of the 4x4 block fit "it gt\n" "movgt r1, r3\n" // Compute r2 = how many cols of the 4x4 block fit "cmp r2, #4\n" "it gt\n" "movgt r2, r5\n" // Test if r1==4 && r2 == 4, i.e. if all of the 4x4 block fits. "cmp r1, r3\n" "it eq\n" "cmpeq r2, r5\n" // Yes, all of the 4x4 block fits, go to fast path. "beq 30f\n" // Not all of the 4x4 block fits. // Set (r3 address, r4 stride) to write to dst_tmp_buf "mov r3, %[dst_tmp_buf]\n" IF_FLOAT_ELIF_INT8_OUTPUT( "mov r4, #16\n" , "mov r4, #4\n" ) "b 31f\n" "30:\n" // Yes, all of the 4x4 block fits. // Set (x3 address, x4 stride) to write directly to destination matrix. "ldr r3, [sp, #" RUY_STR(RUY_STACK_OFFSET_DST_PTR) "]\n" "ldr r4, [%[params], #" RUY_STR(RUY_OFFSET_DST_STRIDE) "]\n" "31:\n" // Write our values to the destination described by // (x3 address, x4 stride). IF_FLOAT_ELIF_INT8_OUTPUT( "vst1.32 {d16, d17}, [r3], r4\n" "vst1.32 {d18, d19}, [r3], r4\n" MAKE_ZERO(q8) MAKE_ZERO(q9) "vst1.32 {d20, d21}, [r3], r4\n" "vst1.32 {d22, d23}, [r3]\n" MAKE_ZERO(q10) MAKE_ZERO(q11) , "vst1.32 {d16[0]}, [r3], r4\n" "vst1.32 {d18[0]}, [r3], r4\n" MAKE_ZERO(q8) MAKE_ZERO(q9) "vst1.32 {d20[0]}, [r3], r4\n" "vst1.32 {d22[0]}, [r3]\n" MAKE_ZERO(q10) MAKE_ZERO(q11) ) // If all of the 4x4 block fits, we just finished writing it to the // destination, so we skip the next part. "beq 41f\n" // Not all of the 4x4 block fits in the destination matrix. We just // wrote it to dst_tmp_buf. Now we perform the slow scalar loop over // it to copy into the destination matrix the part that fits. "ldr r8, [%[params], #" RUY_STR(RUY_OFFSET_DST_STRIDE) "]\n" "mov r3, %[dst_tmp_buf]\n" "ldr r4, [sp, #" RUY_STR(RUY_STACK_OFFSET_DST_PTR) "]\n" "mov r6, #0\n" "50:\n" "mov r5, #0\n" "51:\n" IF_FLOAT_ELIF_INT8_OUTPUT( "ldr r10, [r3, r5, lsl #2]\n" "str r10, [r4, r5, lsl #2]\n" , "ldrb r10, [r3, r5]\n" "strb r10, [r4, r5]\n" ) "add r5, r5, #1\n" "cmp r5, r1\n" "blt 51b\n" "add r6, r6, #1\n" IF_FLOAT_ELIF_INT8_OUTPUT( "add r3, r3, #16\n" , "add r3, r3, #4\n" ) "add r4, r4, r8\n" "cmp r6, r2\n" "blt 50b\n" "41:\n" "ldr r4, [sp, #" RUY_STR(RUY_STACK_OFFSET_DST_PTR) "]\n" IF_FLOAT_ELIF_INT8_OUTPUT( "add r4, r4, #16\n" , "add r4, r4, #4\n" ) "str r4, [sp, #" RUY_STR(RUY_STACK_OFFSET_DST_PTR) "]\n" // At this point we have completely finished writing values to the // destination matrix for the current block. // Reload some params --- we had used r3, r5, r10 for a few other things // since the last time we had loaded them. "ldr r5, [%[params], #" RUY_STR(RUY_OFFSET_LHS_BASE_PTR) "]\n" "ldr r6, [%[params], #" RUY_STR(RUY_OFFSET_START_ROW) "]\n" "ldr r3, [%[params], #" RUY_STR(RUY_OFFSET_LAST_ROW) "]\n" // Move to the next block of the destination matrix, for the next iter // of the main loop. Notice that lhs_col_ptr, rhs_col_ptr have already // been updated earlier. // Have we reached the end row? "ldr r8, [sp, #" RUY_STR(RUY_STACK_OFFSET_ROW) "]\n" "cmp r8, r3\n" "beq 20f\n" // yes, end row. // Not end row. Move to the next row. "add r8, r8, #4\n" // Store new value of row "str r8, [sp, #" RUY_STR(RUY_STACK_OFFSET_ROW) "]\n" "b 21f\n" "20:\n" // Was already at end row. // Move back to first row. "str r6, [sp, #" RUY_STR(RUY_STACK_OFFSET_ROW) "]\n" // Move to the next column. "ldr r4, [sp, #" RUY_STR(RUY_STACK_OFFSET_COL) "]\n" "add r4, r4, #4\n" "str r4, [sp, #" RUY_STR(RUY_STACK_OFFSET_COL) "]\n" "ldr r8, [%[params], #" RUY_STR(RUY_OFFSET_DST_STRIDE) "]\n" "ldr r1, [sp, #" RUY_STR(RUY_STACK_OFFSET_DST_COL_PTR) "]\n" // Increment dst_col_ptr by 4 * dst_stride (i.e. 4 columns) "add r1, r1, r8, lsl #2\n" // Store dst_col_ptr "str r1, [sp, #" RUY_STR(RUY_STACK_OFFSET_DST_COL_PTR) "]\n" // Store dst_ptr "str r1, [sp, #" RUY_STR(RUY_STACK_OFFSET_DST_PTR) "]\n" "21:\n" // Main loop exit condition: have we hit the end column? "ldr r4, [%[params], #" RUY_STR(RUY_OFFSET_LAST_COL) "]\n" "ldr r8, [sp, #" RUY_STR(RUY_STACK_OFFSET_COL) "]\n" "cmp r8, r4\n" // r1 is the number of levels of depth that we have already loaded // LHS and RHS data for. "mov r1, #4\n" "ble 1b\n" "add sp, sp, #" RUY_STR(RUY_STACK_OFFSET_SIZE) "\n" : [lhs_ptr] "+r"(lhs_ptr), [rhs_ptr] "+r"(rhs_ptr) : [ params ] "r"(&params), [dst_tmp_buf] "r"(params.dst_tmp_buf), [float_output]"i"(std::is_same<DstScalar, float>::value), [int8_output]"i"(std::is_same<DstScalar, std::int8_t>::value) : "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #undef MAKE_ZERO #undef IF_FLOAT_OUTPUT #undef IF_INT8_OUTPUT #undef IF_FLOAT_ELIF_INT8_OUTPUT #undef RUY_STACK_OFFSET_SIZE #undef RUY_STACK_OFFSET_DST_COL_PTR #undef RUY_STACK_OFFSET_DST_PTR #undef RUY_STACK_OFFSET_ROW #undef RUY_STACK_OFFSET_COL #undef RUY_STACK_OFFSET_LHS_COL_PTR #undef RUY_STACK_OFFSET_RHS_COL_PTR #undef RUY_OFFSET_LHS_BASE_PTR #undef RUY_OFFSET_RHS_BASE_PTR #undef RUY_OFFSET_DST_BASE_PTR #undef RUY_OFFSET_START_ROW #undef RUY_OFFSET_START_COL #undef RUY_OFFSET_LAST_ROW #undef RUY_OFFSET_LAST_COL #undef RUY_OFFSET_DST_ROWS #undef RUY_OFFSET_DST_COLS #undef RUY_OFFSET_LHS_STRIDE #undef RUY_OFFSET_RHS_STRIDE #undef RUY_OFFSET_DST_STRIDE #undef RUY_OFFSET_DEPTH #undef RUY_OFFSET_OUTPUT_TRANSFORM_MULTIPLIER #undef RUY_OFFSET_OUTPUT_TRANSFORM_BIAS #undef RUY_OFFSET_OUTPUT_TRANSFORM_CLAMP_MIN #undef RUY_OFFSET_OUTPUT_TRANSFORM_CLAMP_MAX #endif // RUY_PLATFORM_NEON && RUY_OPT(ASM) && RUY_PLATFORM_NEON_32 #endif // COMPUTE_ENGINE_CORE_BGEMM_KERNELS_ARM32_H_ <|start_filename|>larq_compute_engine/core/indirect_bgemm/select_kernel.h<|end_filename|> #ifndef COMPUTE_ENGINE_INDIRECT_BGEMM_SELECT_KERNEL_H_ #define COMPUTE_ENGINE_INDIRECT_BGEMM_SELECT_KERNEL_H_ #include <cstdint> #include <memory> #include <type_traits> #include "larq_compute_engine/core/indirect_bgemm/kernel.h" #ifdef __aarch64__ #include "larq_compute_engine/core/indirect_bgemm/kernel_8x4x1_aarch64.h" #include "larq_compute_engine/core/indirect_bgemm/kernel_8x4x2_aarch64.h" #include "larq_compute_engine/core/indirect_bgemm/kernel_8x4x4_aarch64.h" #endif #include "larq_compute_engine/core/bconv2d/output_transform.h" #include "larq_compute_engine/core/bconv2d/params.h" #include "larq_compute_engine/core/indirect_bgemm/kernel_4x2_portable.h" #include "tensorflow/lite/kernels/internal/types.h" namespace compute_engine { namespace core { namespace indirect_bgemm { // These functions allow us to select which kernel to use at runtime based on // any parameter we choose: destination scalar; conv params; input/output // shapes; even detected CPU features. // Select a kernel for float or int8 output. template <typename DstScalar> inline std::unique_ptr<Kernel> SelectRuntimeKernel( const bconv2d::BConv2DParams* bconv2d_params, const ::tflite::RuntimeShape& bitpacked_input_shape, const ::tflite::RuntimeShape& output_shape, const bconv2d::OutputTransform<DstScalar>& output_transform) { static_assert(std::is_same<DstScalar, float>::value || std::is_same<DstScalar, std::int8_t>::value, ""); #ifdef __aarch64__ // There are optimised assembly kernels for float and int8 output on Aarch64. // They all use int16 accumulators. A different kernel is selected depending // on whether the bitpacked number of input channels is a multiple of 4, 2, or // 1, and whether that multiple is 1 or more than 1. const auto max_accumulator_value = bitpacking_bitwidth * bitpacked_input_shape.FlatSize() / bconv2d_params->groups; const bool fits_in_uint16_accumulators = max_accumulator_value < std::numeric_limits<std::uint16_t>::max(); if (fits_in_uint16_accumulators) { const auto input_depth_per_group = bitpacked_input_shape.Dims(3) / bconv2d_params->groups; if (input_depth_per_group % 4 == 0) { if (input_depth_per_group > 4) { if (bconv2d_params->groups > 1) { return std::make_unique<Kernel8x4x4Aarch64<DstScalar, true, true>>( bconv2d_params, bitpacked_input_shape, output_shape, output_transform); } else { return std::make_unique<Kernel8x4x4Aarch64<DstScalar, true, false>>( bconv2d_params, bitpacked_input_shape, output_shape, output_transform); } } else { if (bconv2d_params->groups > 1) { return std::make_unique<Kernel8x4x4Aarch64<DstScalar, false, true>>( bconv2d_params, bitpacked_input_shape, output_shape, output_transform); } else { return std::make_unique<Kernel8x4x4Aarch64<DstScalar, false, false>>( bconv2d_params, bitpacked_input_shape, output_shape, output_transform); } } } else if (input_depth_per_group % 2 == 0) { if (input_depth_per_group > 2) { if (bconv2d_params->groups > 1) { return std::make_unique<Kernel8x4x2Aarch64<DstScalar, true, true>>( bconv2d_params, bitpacked_input_shape, output_shape, output_transform); } else { return std::make_unique<Kernel8x4x2Aarch64<DstScalar, true, false>>( bconv2d_params, bitpacked_input_shape, output_shape, output_transform); } } else { if (bconv2d_params->groups > 1) { return std::make_unique<Kernel8x4x2Aarch64<DstScalar, false, true>>( bconv2d_params, bitpacked_input_shape, output_shape, output_transform); } else { return std::make_unique<Kernel8x4x2Aarch64<DstScalar, false, false>>( bconv2d_params, bitpacked_input_shape, output_shape, output_transform); } } } else { if (input_depth_per_group > 1) { if (bconv2d_params->groups > 1) { return std::make_unique<Kernel8x4x1Aarch64<DstScalar, true, true>>( bconv2d_params, bitpacked_input_shape, output_shape, output_transform); } else { return std::make_unique<Kernel8x4x1Aarch64<DstScalar, true, false>>( bconv2d_params, bitpacked_input_shape, output_shape, output_transform); } } else { if (bconv2d_params->groups > 1) { return std::make_unique<Kernel8x4x1Aarch64<DstScalar, false, true>>( bconv2d_params, bitpacked_input_shape, output_shape, output_transform); } else { return std::make_unique<Kernel8x4x1Aarch64<DstScalar, false, false>>( bconv2d_params, bitpacked_input_shape, output_shape, output_transform); } } } } #endif // Fallback C++ kernel return std::make_unique<Kernel4x2Portable<DstScalar>>( bconv2d_params, bitpacked_input_shape, output_shape, output_transform); } // A specialisation: select a kernel for bitpacked output. template <> inline std::unique_ptr<Kernel> SelectRuntimeKernel<TBitpacked>( const bconv2d::BConv2DParams* bconv2d_params, const ::tflite::RuntimeShape& bitpacked_input_shape, const ::tflite::RuntimeShape& output_shape, const bconv2d::OutputTransform<TBitpacked>& output_transform) { // Only the C++ kernel currently supports bitpacked output. return std::make_unique<Kernel4x2Portable<TBitpacked>>( bconv2d_params, bitpacked_input_shape, output_shape, output_transform); } } // namespace indirect_bgemm } // namespace core } // namespace compute_engine #endif // COMPUTE_ENGINE_INDIRECT_BGEMM_SELECT_KERNEL_H_ <|start_filename|>larq_compute_engine/core/bitpacking/tests/bitpack_test.cc<|end_filename|> #include "larq_compute_engine/core/bitpacking/bitpack.h" #include <gtest/gtest.h> #include <array> #include <cstdint> #include <random> #include <vector> #include "absl/strings/str_cat.h" namespace compute_engine { namespace core { namespace bitpacking { class BitpackingTest : public ::testing::TestWithParam<std::tuple<int, int, std::int32_t>> {}; template <typename TIn> void runBitpackingTest(const int num_rows, const int num_cols, const std::int32_t zero_point) { if (std::is_same<TIn, float>::value && zero_point != 0) { GTEST_SKIP(); } const int num_packed_cols = GetBitpackedSize(num_cols); std::random_device rd; std::mt19937 gen(rd()); std::vector<TIn> input_matrix(num_rows * num_cols); std::vector<TBitpacked> output_matrix( GetBitpackedMatrixSize(num_rows, num_cols)); // Generate some random data for the input. if (std::is_same<TIn, float>::value) { std::generate(std::begin(input_matrix), std::end(input_matrix), [&gen]() { return std::uniform_real_distribution<>(-1.5, 1.5)(gen); }); } else if (std::is_same<TIn, std::int8_t>::value) { std::generate(std::begin(input_matrix), std::end(input_matrix), [&gen]() { return std::uniform_int_distribution<>(-128, 127)(gen); }); } else { EXPECT_FALSE(true); } // Perform the bitpacking. bitpack_matrix(input_matrix.data(), num_rows, num_cols, output_matrix.data(), zero_point); // Verify correctness of the results. for (auto i = 0; i < num_rows; i++) { for (auto j = 0; j < bitpacking_bitwidth * num_packed_cols; j++) { const bool packed_bit = output_matrix.at(i * num_packed_cols + j / bitpacking_bitwidth) & (TBitpacked(1) << (j % bitpacking_bitwidth)); if (j < num_cols) { // If this bit position corresponds to an actual value, compare against // the sign of that value... bool expected_bit; if (std::is_same<TIn, float>::value) { assert(zero_point == 0); expected_bit = input_matrix.at(i * num_cols + j) < 0; } else { expected_bit = static_cast<std::int32_t>( input_matrix.at(i * num_cols + j)) < zero_point; } EXPECT_EQ(packed_bit, expected_bit); } else { // ...otherwise it's a 'padding' bit, and we expect it to be zero. EXPECT_EQ(packed_bit, 0); } } } } TEST_P(BitpackingTest, BitpackFloats) { runBitpackingTest<float>(std::get<0>(GetParam()), std::get<1>(GetParam()), std::get<2>(GetParam())); } TEST_P(BitpackingTest, BitpackInt8) { runBitpackingTest<std::int8_t>(std::get<0>(GetParam()), std::get<1>(GetParam()), std::get<2>(GetParam())); } std::string TestName( const ::testing::TestParamInfo<BitpackingTest::ParamType>& info) { // We have to treat the zero point specially, because we can't have a // hyphen in the name, and so can't naturally represent negative numbers. std::string param_zp_value_str = absl::StrCat(std::get<2>(info.param) >= 0 ? "Pos" : "Neg", std::abs(std::get<2>(info.param))); return absl::StrCat("Rows_", std::get<0>(info.param), "__Cols_", std::get<1>(info.param), "__ZeroPoint_", param_zp_value_str); } INSTANTIATE_TEST_SUITE_P(Bitpacking, BitpackingTest, ::testing::Combine( // num_rows ::testing::Values(1, 2, 3, 8, 10, 15, 64), // num_cols ::testing::Values(1, 3, 16, 32, 33, 63, 64, 128), // zero_point ::testing::Values(-1000, -1, 0, 23, 127, 128)), TestName); } // namespace bitpacking } // namespace core } // namespace compute_engine <|start_filename|>larq_compute_engine/core/bmaxpool.h<|end_filename|> #ifndef COMPUTE_ENGINE_CORE_BMAXPOOL_H_ #define COMPUTE_ENGINE_CORE_BMAXPOOL_H_ #include "larq_compute_engine/core/types.h" #include "tensorflow/lite/kernels/internal/common.h" #include "tensorflow/lite/kernels/internal/types.h" #include "tensorflow/lite/kernels/padding.h" namespace compute_engine { namespace core { using namespace tflite; struct BMaxPoolParams { std::int32_t filter_height{0}; std::int32_t filter_width{0}; std::int32_t stride_height{0}; std::int32_t stride_width{0}; TfLitePaddingValues padding{}; TfLitePadding padding_type{}; }; // Effectively takes the AND of everything in the filter region void BMaxPool(const BMaxPoolParams& params, const RuntimeShape& input_shape, const TBitpacked* input_data, const RuntimeShape& output_shape, TBitpacked* output_data) { TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4); TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4); const int batches = MatchingDim(input_shape, 0, output_shape, 0); const int input_height = input_shape.Dims(1); const int input_width = input_shape.Dims(2); const int output_height = output_shape.Dims(1); const int output_width = output_shape.Dims(2); const int filter_height = params.filter_height; const int filter_width = params.filter_width; const int stride_height = params.stride_height; const int stride_width = params.stride_width; const int channels = MatchingDim(input_shape, 3, output_shape, 3); for (int batch = 0; batch < batches; ++batch) { for (int out_y = 0; out_y < output_height; ++out_y) { for (int out_x = 0; out_x < output_width; ++out_x) { const int in_x_origin = (out_x * stride_width) - params.padding.width; const int in_y_origin = (out_y * stride_height) - params.padding.height; // Compute the boundaries of the filter region clamped so as to // ensure that the filter window fits in the input array. const int filter_x_start = std::max(0, -in_x_origin); const int filter_y_start = std::max(0, -in_y_origin); const int in_x = in_x_origin + filter_x_start; const int in_y = in_y_origin + filter_y_start; const int filter_x_count = std::min(filter_width - filter_x_start, input_width - in_x); const int filter_y_count = std::min(filter_height - filter_y_start, input_height - in_y); // How far to jump to the next input pixel in the x direction const int x_stride = channels; // How far to jump to the next input pixel in the y direction, and // 'back' to the first pixel in the x direction. const int y_stride = channels * (input_width - filter_x_count); // Get the pointer to the input pixel corresponding top-left filter // corner, channel 0 const TBitpacked* in_base = &input_data[Offset(input_shape, batch, in_y, in_x, 0)]; TBitpacked* out_ptr = &output_data[Offset(output_shape, batch, out_y, out_x, 0)]; for (int channel = 0; channel < channels; ++channel) { const TBitpacked* in_ptr = in_base + channel; // Start with all ones TBitpacked max = ~TBitpacked(0); for (int y = 0; y < filter_y_count; ++y) { for (int x = 0; x < filter_x_count; ++x) { max &= *in_ptr; in_ptr += x_stride; } in_ptr += y_stride; } *out_ptr++ = max; } } } } } } // namespace core } // namespace compute_engine #endif // COMPUTE_ENGINE_CORE_MAXPOOL_H_ <|start_filename|>larq_compute_engine/core/indirect_bgemm/kernel_4x2_portable.h<|end_filename|> #ifndef COMPUTE_ENGINE_INDIRECT_BGEMM_KERNEL_4x2_PORTABLE_H_ #define COMPUTE_ENGINE_INDIRECT_BGEMM_KERNEL_4x2_PORTABLE_H_ #include <cstdint> #include <type_traits> #include "larq_compute_engine/core/bconv2d/output_transform.h" #include "larq_compute_engine/core/bconv2d/params.h" #include "larq_compute_engine/core/bitpacking/bitpack.h" #include "larq_compute_engine/core/indirect_bgemm/kernel.h" #include "larq_compute_engine/core/types.h" #include "ruy/profiler/instrumentation.h" #include "tensorflow/lite/kernels/internal/types.h" namespace compute_engine { namespace core { namespace indirect_bgemm { /** * A 4x2 C++ micro-kernel for float or int8 output. */ template <typename DstScalar> class Kernel4x2Portable : public Kernel { static_assert(std::is_same<DstScalar, float>::value || std::is_same<DstScalar, std::int8_t>::value, ""); const bconv2d::OutputTransform<DstScalar> output_transform; public: Kernel4x2Portable(const bconv2d::BConv2DParams* bconv2d_params, const RuntimeShape& bitpacked_input_shape, const RuntimeShape& output_shape, const bconv2d::OutputTransform<DstScalar>& output_transform) : Kernel(4, 2, 1, bconv2d_params, bitpacked_input_shape, output_shape), output_transform(output_transform) {} void Run(const std::int32_t pixel_start, const std::int32_t pixel_end, void* output_ptr) const override { ruy::profiler::ScopeLabel label("Indirect BGEMM block (4x2, portable)"); TFLITE_DCHECK_GE(this->input_depth, 1); TFLITE_DCHECK_GE(this->output_channels, 1); TFLITE_DCHECK_GE(this->filter_size, 1); TFLITE_DCHECK_GE(this->groups, 1); TFLITE_DCHECK_EQ(this->input_depth % this->groups, 0); TFLITE_DCHECK_EQ(this->output_channels % this->groups, 0); const auto input_depth_per_group = this->input_depth / this->groups; const auto output_channels_per_group = this->output_channels / this->groups; for (std::int32_t p_index = pixel_start; p_index < pixel_end; p_index += 2) { const TBitpacked* weights_ptr = this->packed_weights.data(); const TBitpacked* const* indirection_ptr = this->indirection_buffer.data() + p_index * this->filter_size; auto output_ptr_0 = reinterpret_cast<DstScalar*>(output_ptr) + p_index * this->output_channels; auto output_ptr_1 = output_ptr_0 + this->output_channels; // At the end of the output array we might get a block where the number of // pixels is less than 2, if the overall output size is not a multiple // of 2. When this happens we set the 'leftover' output pointer equal to // the first output pointer, so that there's no risk of writing beyond the // array bounds. At the end, when we write to the output array, we do it // 'back to front' so that the outputs for the first pixel are written // last, which means that the result will still be correct. if (pixel_end - p_index < 2) { output_ptr_1 = output_ptr_0; } std::size_t input_depth_offset = 0; std::int32_t group_end_output_channel = output_channels_per_group; std::int32_t c_out_index = 0; do { // Accumulators std::int32_t acc_00 = 0, acc_01 = 0; std::int32_t acc_10 = 0, acc_11 = 0; std::int32_t acc_20 = 0, acc_21 = 0; std::int32_t acc_30 = 0, acc_31 = 0; std::int32_t f_size_index = this->filter_size; do { const TBitpacked* activations_ptr_0 = indirection_ptr[0] + input_depth_offset; const TBitpacked* activations_ptr_1 = indirection_ptr[1] + input_depth_offset; indirection_ptr += 2; std::int32_t depth_index = input_depth_per_group; do { const TBitpacked w_0 = weights_ptr[0]; const TBitpacked w_1 = weights_ptr[1]; const TBitpacked w_2 = weights_ptr[2]; const TBitpacked w_3 = weights_ptr[3]; weights_ptr += 4; const TBitpacked a_0 = *activations_ptr_0++; const TBitpacked a_1 = *activations_ptr_1++; acc_00 += xor_popcount(w_0, a_0); acc_10 += xor_popcount(w_1, a_0); acc_20 += xor_popcount(w_2, a_0); acc_30 += xor_popcount(w_3, a_0); acc_01 += xor_popcount(w_0, a_1); acc_11 += xor_popcount(w_1, a_1); acc_21 += xor_popcount(w_2, a_1); acc_31 += xor_popcount(w_3, a_1); } while (--depth_index > 0); } while (--f_size_index > 0); if (LCE_LIKELY(group_end_output_channel - c_out_index >= 4)) { output_ptr_1[0] = output_transform.Run(acc_01, c_out_index); output_ptr_1[1] = output_transform.Run(acc_11, c_out_index + 1); output_ptr_1[2] = output_transform.Run(acc_21, c_out_index + 2); output_ptr_1[3] = output_transform.Run(acc_31, c_out_index + 3); output_ptr_1 += 4; output_ptr_0[0] = output_transform.Run(acc_00, c_out_index); output_ptr_0[1] = output_transform.Run(acc_10, c_out_index + 1); output_ptr_0[2] = output_transform.Run(acc_20, c_out_index + 2); output_ptr_0[3] = output_transform.Run(acc_30, c_out_index + 3); output_ptr_0 += 4; c_out_index += 4; } else { if (group_end_output_channel - c_out_index >= 2) { output_ptr_1[0] = output_transform.Run(acc_01, c_out_index); output_ptr_1[1] = output_transform.Run(acc_11, c_out_index + 1); output_ptr_1 += 2; output_ptr_0[0] = output_transform.Run(acc_00, c_out_index); output_ptr_0[1] = output_transform.Run(acc_10, c_out_index + 1); output_ptr_0 += 2; acc_01 = acc_21; acc_00 = acc_20; c_out_index += 2; } if (group_end_output_channel - c_out_index >= 1) { output_ptr_1[0] = output_transform.Run(acc_01, c_out_index); output_ptr_1 += 1; output_ptr_0[0] = output_transform.Run(acc_00, c_out_index); output_ptr_0 += 1; c_out_index += 1; } } indirection_ptr -= 2 * this->filter_size; if (c_out_index == group_end_output_channel) { input_depth_offset += input_depth_per_group; group_end_output_channel += output_channels_per_group; } } while (c_out_index < this->output_channels); } } }; /** * A 4x2 C++ micro-kernel for bitpacked output. */ template <> class Kernel4x2Portable<TBitpacked> : public Kernel { const bconv2d::OutputTransform<TBitpacked> output_transform; public: Kernel4x2Portable( const bconv2d::BConv2DParams* bconv2d_params, const RuntimeShape& bitpacked_input_shape, const RuntimeShape& output_shape, const bconv2d::OutputTransform<TBitpacked>& output_transform) : Kernel(4, 2, 1, bconv2d_params, bitpacked_input_shape, output_shape), output_transform(output_transform) {} void Run(const std::int32_t pixel_start, const std::int32_t pixel_end, void* output_ptr) const override { ruy::profiler::ScopeLabel label("Indirect BGEMM block (4x2, portable)"); TFLITE_DCHECK_GE(this->input_depth, 1); TFLITE_DCHECK_GE(this->output_channels, 1); TFLITE_DCHECK_GE(this->filter_size, 1); TFLITE_DCHECK_GE(this->groups, 1); TFLITE_DCHECK_EQ(this->input_depth % this->groups, 0); TFLITE_DCHECK_EQ(this->output_channels % this->groups, 0); const auto input_depth_per_group = this->input_depth / this->groups; const auto output_channels_per_group = this->output_channels / this->groups; for (std::int32_t p_index = pixel_start; p_index < pixel_end; p_index += 2) { const TBitpacked* weights_ptr = this->packed_weights.data(); const TBitpacked* const* indirection_ptr = this->indirection_buffer.data() + p_index * this->filter_size; auto output_ptr_0 = reinterpret_cast<TBitpacked*>(output_ptr) + p_index * bitpacking::GetBitpackedSize(this->output_channels); auto output_ptr_1 = output_ptr_0 + bitpacking::GetBitpackedSize(this->output_channels); // At the end of the output array we might get a block where the number of // pixels is less than 2, if the overall output size is not a multiple // of 2. When this happens we set the 'leftover' output pointer equal to // the first output pointer, so that there's no risk of writing beyond the // array bounds. At the end, when we write to the output array, we do it // 'back to front' so that the outputs for the first pixel are written // last, which means that the result will still be correct. if (pixel_end - p_index < 2) { output_ptr_1 = output_ptr_0; } // We will accumulate bits into these per-pixel columns and write a // bitpacked value when the columns are full. TBitpacked output_col_0 = 0, output_col_1 = 0; std::size_t input_depth_offset = 0; std::int32_t group_end_output_channel = output_channels_per_group; std::int32_t c_out_index = 0; do { // Accumulators std::int32_t acc_00 = 0, acc_01 = 0; std::int32_t acc_10 = 0, acc_11 = 0; std::int32_t acc_20 = 0, acc_21 = 0; std::int32_t acc_30 = 0, acc_31 = 0; std::int32_t f_size_index = filter_size; do { const TBitpacked* activations_ptr_0 = indirection_ptr[0] + input_depth_offset; const TBitpacked* activations_ptr_1 = indirection_ptr[1] + input_depth_offset; indirection_ptr += 2; std::int32_t depth_index = input_depth_per_group; do { const TBitpacked w_0 = weights_ptr[0]; const TBitpacked w_1 = weights_ptr[1]; const TBitpacked w_2 = weights_ptr[2]; const TBitpacked w_3 = weights_ptr[3]; weights_ptr += 4; const TBitpacked a_0 = *activations_ptr_0++; const TBitpacked a_1 = *activations_ptr_1++; acc_00 += xor_popcount(w_0, a_0); acc_10 += xor_popcount(w_1, a_0); acc_20 += xor_popcount(w_2, a_0); acc_30 += xor_popcount(w_3, a_0); acc_01 += xor_popcount(w_0, a_1); acc_11 += xor_popcount(w_1, a_1); acc_21 += xor_popcount(w_2, a_1); acc_31 += xor_popcount(w_3, a_1); } while (--depth_index > 0); } while (--f_size_index > 0); // Correctness of the following section relies on the bitpacking // bitwidth being 32. static_assert(bitpacking_bitwidth == 32, ""); const int base_output_index = c_out_index % 16; output_col_0 |= TBitpacked(output_transform.Run(acc_00, c_out_index)) << base_output_index; output_col_0 |= TBitpacked(output_transform.Run(acc_10, c_out_index + 1)) << (base_output_index + 1); output_col_0 |= TBitpacked(output_transform.Run(acc_20, c_out_index + 2)) << (base_output_index + 2); output_col_0 |= TBitpacked(output_transform.Run(acc_30, c_out_index + 3)) << (base_output_index + 3); output_col_1 |= TBitpacked(output_transform.Run(acc_01, c_out_index)) << base_output_index; output_col_1 |= TBitpacked(output_transform.Run(acc_11, c_out_index + 1)) << (base_output_index + 1); output_col_1 |= TBitpacked(output_transform.Run(acc_21, c_out_index + 2)) << (base_output_index + 2); output_col_1 |= TBitpacked(output_transform.Run(acc_31, c_out_index + 3)) << (base_output_index + 3); indirection_ptr -= 2 * filter_size; if (group_end_output_channel - c_out_index > 4) { c_out_index += 4; } else { const int gap_to_group_end = group_end_output_channel - c_out_index; if (gap_to_group_end < 4) { output_col_0 &= (TBitpacked(1) << (base_output_index + gap_to_group_end)) - 1; output_col_1 &= (TBitpacked(1) << (base_output_index + gap_to_group_end)) - 1; } c_out_index = group_end_output_channel; input_depth_offset += input_depth_per_group; group_end_output_channel += output_channels_per_group; } // If on the next iteration we will have 'wrapped around' the output // columns, write the bottom halves to the output array. if (c_out_index % 16 < base_output_index) { *((std::int16_t*)output_ptr_1) = (std::int16_t)output_col_1; *((std::int16_t*)output_ptr_0) = (std::int16_t)output_col_0; output_col_1 >>= 16; output_col_0 >>= 16; output_ptr_1 = (TBitpacked*)(((std::int16_t*)output_ptr_1) + 1); output_ptr_0 = (TBitpacked*)(((std::int16_t*)output_ptr_0) + 1); } } while (c_out_index < this->output_channels); // If we've got to the end and there are still un-written bits, make sure // they get written now. if (this->output_channels % 16 > 0) { *((std::int16_t*)output_ptr_1) = (std::int16_t)output_col_1; *((std::int16_t*)output_ptr_0) = (std::int16_t)output_col_0; } } } }; } // namespace indirect_bgemm } // namespace core } // namespace compute_engine #endif // COMPUTE_ENGINE_INDIRECT_BGEMM_KERNEL_4x2_PORTABLE_H_ <|start_filename|>larq_compute_engine/tflite/tests/bconv2d_op_model.h<|end_filename|> #ifndef LARQ_COMPUTE_ENGINE_TFLITE_TESTS_BCONV2D_OP #define LARQ_COMPUTE_ENGINE_TFLITE_TESTS_BCONV2D_OP #include <vector> #include "flatbuffers/flexbuffers.h" // TF:flatbuffers #include "larq_compute_engine/core/types.h" #include "larq_compute_engine/tflite/tests/utils.h" #include "tensorflow/lite/kernels/test_util.h" using namespace tflite; namespace compute_engine { namespace tflite { TfLiteRegistration* Register_BCONV_2D_OPT(); namespace testing { using compute_engine::core::TBitpacked; typedef TfLiteRegistration* (*register_function)(void); class BaseBConv2DOpModel : public SingleOpModel { public: BaseBConv2DOpModel( register_function registration, const TensorData& input, const TensorData& filter, const TensorData& output, const TensorData& post_activation_multiplier, const TensorData& post_activation_bias, const TensorData& thresholds, int channels_in, int stride_width = 1, int stride_height = 1, enum Padding padding = Padding_VALID, int pad_values = 0, enum ActivationFunctionType activation = ActivationFunctionType_NONE, int dilation_width_factor = 1, int dilation_height_factor = 1, int num_threads = -1) { input_ = AddInput(input); filter_ = AddInput(filter); post_activation_multiplier_ = AddInput(post_activation_multiplier); post_activation_bias_ = AddInput(post_activation_bias); thresholds_ = AddInput(thresholds); output_ = AddOutput(output); flexbuffers::Builder fbb; fbb.Map([&]() { fbb.Int("channels_in", channels_in); fbb.Int("stride_height", stride_height); fbb.Int("stride_width", stride_width); fbb.Int("dilation_height_factor", dilation_height_factor); fbb.Int("dilation_width_factor", dilation_width_factor); fbb.Int("padding", (int)padding); fbb.Int("pad_values", pad_values); fbb.Int("fused_activation_function", (int)activation); }); fbb.Finish(); SetCustomOp("LceBconv2d", fbb.GetBuffer(), registration); BuildInterpreter({GetShape(input_), GetShape(filter_)}, num_threads, /*allow_fp32_relax_to_fp16=*/false, /*apply_delegate=*/true); } protected: int input_; int filter_; int output_; int post_activation_multiplier_; int post_activation_bias_; int thresholds_; }; template <typename PostType, typename TOutput> class BConv2DOpModel : public BaseBConv2DOpModel { public: using BaseBConv2DOpModel::BaseBConv2DOpModel; void SetFilter(const std::vector<TBitpacked>& f) { PopulateTensor(filter_, f); } void SetInput(const std::vector<TBitpacked>& data) { PopulateTensor(input_, data); } void SetPostActivationMultiplier(const std::vector<PostType>& f) { PopulateTensor(post_activation_multiplier_, f); } void SetPostActivationBias(const std::vector<PostType>& f) { PopulateTensor(post_activation_bias_, f); } void SetThresholds(const std::vector<std::int32_t>& f) { PopulateTensor(thresholds_, f); } std::vector<TOutput> GetOutput() { return ExtractVector<TOutput>(output_); } std::vector<int> GetOutputShape() { return GetTensorShape(output_); } }; } // namespace testing } // namespace tflite } // namespace compute_engine #endif // LARQ_COMPUTE_ENGINE_TFLITE_TESTS_BCONV2D_OP <|start_filename|>larq_compute_engine/core/bitpacking/bitpack.h<|end_filename|> #ifndef COMPUTE_ENGINE_CORE_BITPACKING_BITPACK_H_ #define COMPUTE_ENGINE_CORE_BITPACKING_BITPACK_H_ #include <array> #include <cstdint> #include <cstring> #include <limits> #include "larq_compute_engine/core/types.h" #ifdef __aarch64__ #include "larq_compute_engine/core/bitpacking/bitpack_aarch64.h" #endif #include "flatbuffers/base.h" // Used for the FLATBUFFERS_LITTLEENDIAN macro #include "ruy/profiler/instrumentation.h" #include "tensorflow/lite/kernels/internal/types.h" namespace compute_engine { namespace core { namespace bitpacking { // Utility functions constexpr int GetBitpackedSize(int unpacked_elements) { return CeilDiv(unpacked_elements, bitpacking_bitwidth); } constexpr int GetBitpackedMatrixSize(int rows, int cols) { return rows * GetBitpackedSize(cols); } template <class TIn> inline void bitpack_bitfield_quantized(const TIn* in, TBitpacked* out, const TIn zero_point) { ruy::profiler::ScopeLabel label( "Bitpack bitfield (quantized input, unoptimised)"); struct bf { unsigned int b0 : 1; unsigned int b1 : 1; unsigned int b2 : 1; unsigned int b3 : 1; unsigned int b4 : 1; unsigned int b5 : 1; unsigned int b6 : 1; unsigned int b7 : 1; unsigned int b8 : 1; unsigned int b9 : 1; unsigned int b10 : 1; unsigned int b11 : 1; unsigned int b12 : 1; unsigned int b13 : 1; unsigned int b14 : 1; unsigned int b15 : 1; unsigned int b16 : 1; unsigned int b17 : 1; unsigned int b18 : 1; unsigned int b19 : 1; unsigned int b20 : 1; unsigned int b21 : 1; unsigned int b22 : 1; unsigned int b23 : 1; unsigned int b24 : 1; unsigned int b25 : 1; unsigned int b26 : 1; unsigned int b27 : 1; unsigned int b28 : 1; unsigned int b29 : 1; unsigned int b30 : 1; unsigned int b31 : 1; }; union bf_i32 { bf t; TBitpacked i32; }; bf_i32 i; i.t.b0 = in[0] < zero_point; i.t.b1 = in[1] < zero_point; i.t.b2 = in[2] < zero_point; i.t.b3 = in[3] < zero_point; i.t.b4 = in[4] < zero_point; i.t.b5 = in[5] < zero_point; i.t.b6 = in[6] < zero_point; i.t.b7 = in[7] < zero_point; i.t.b8 = in[8] < zero_point; i.t.b9 = in[9] < zero_point; i.t.b10 = in[10] < zero_point; i.t.b11 = in[11] < zero_point; i.t.b12 = in[12] < zero_point; i.t.b13 = in[13] < zero_point; i.t.b14 = in[14] < zero_point; i.t.b15 = in[15] < zero_point; i.t.b16 = in[16] < zero_point; i.t.b17 = in[17] < zero_point; i.t.b18 = in[18] < zero_point; i.t.b19 = in[19] < zero_point; i.t.b20 = in[20] < zero_point; i.t.b21 = in[21] < zero_point; i.t.b22 = in[22] < zero_point; i.t.b23 = in[23] < zero_point; i.t.b24 = in[24] < zero_point; i.t.b25 = in[25] < zero_point; i.t.b26 = in[26] < zero_point; i.t.b27 = in[27] < zero_point; i.t.b28 = in[28] < zero_point; i.t.b29 = in[29] < zero_point; i.t.b30 = in[30] < zero_point; i.t.b31 = in[31] < zero_point; *out = i.i32; } template <class T> inline void bitpack_bitfield(const T* fptr, TBitpacked* buf) { ruy::profiler::ScopeLabel label( "Bitpack bitfield (non-quantized input, unoptimised)"); struct bf { unsigned int b0 : 1; unsigned int b1 : 1; unsigned int b2 : 1; unsigned int b3 : 1; unsigned int b4 : 1; unsigned int b5 : 1; unsigned int b6 : 1; unsigned int b7 : 1; unsigned int b8 : 1; unsigned int b9 : 1; unsigned int b10 : 1; unsigned int b11 : 1; unsigned int b12 : 1; unsigned int b13 : 1; unsigned int b14 : 1; unsigned int b15 : 1; unsigned int b16 : 1; unsigned int b17 : 1; unsigned int b18 : 1; unsigned int b19 : 1; unsigned int b20 : 1; unsigned int b21 : 1; unsigned int b22 : 1; unsigned int b23 : 1; unsigned int b24 : 1; unsigned int b25 : 1; unsigned int b26 : 1; unsigned int b27 : 1; unsigned int b28 : 1; unsigned int b29 : 1; unsigned int b30 : 1; unsigned int b31 : 1; }; union bf_i32 { bf t; TBitpacked i32; }; bf_i32 i; i.t.b0 = fptr[0] < 0; i.t.b1 = fptr[1] < 0; i.t.b2 = fptr[2] < 0; i.t.b3 = fptr[3] < 0; i.t.b4 = fptr[4] < 0; i.t.b5 = fptr[5] < 0; i.t.b6 = fptr[6] < 0; i.t.b7 = fptr[7] < 0; i.t.b8 = fptr[8] < 0; i.t.b9 = fptr[9] < 0; i.t.b10 = fptr[10] < 0; i.t.b11 = fptr[11] < 0; i.t.b12 = fptr[12] < 0; i.t.b13 = fptr[13] < 0; i.t.b14 = fptr[14] < 0; i.t.b15 = fptr[15] < 0; i.t.b16 = fptr[16] < 0; i.t.b17 = fptr[17] < 0; i.t.b18 = fptr[18] < 0; i.t.b19 = fptr[19] < 0; i.t.b20 = fptr[20] < 0; i.t.b21 = fptr[21] < 0; i.t.b22 = fptr[22] < 0; i.t.b23 = fptr[23] < 0; i.t.b24 = fptr[24] < 0; i.t.b25 = fptr[25] < 0; i.t.b26 = fptr[26] < 0; i.t.b27 = fptr[27] < 0; i.t.b28 = fptr[28] < 0; i.t.b29 = fptr[29] < 0; i.t.b30 = fptr[30] < 0; i.t.b31 = fptr[31] < 0; *buf = i.i32; } // Helper function template <class TIn> inline void bitpack_bitfield(const TIn* in, TBitpacked* out, const TIn zero_point) { // Note: The expressions in these if-statements are known at compile-time so // they are all optimied away constexpr bool is_quantized = !std::is_floating_point<TIn>::value; if (is_quantized) { bitpack_bitfield_quantized(in, out, zero_point); } else { TFLITE_DCHECK_EQ(zero_point, 0); bitpack_bitfield(in, out); } } template <class TIn> inline void bitpack_array(const TIn* input_array, const std::size_t n, TBitpacked* bitpacked_array, const TIn zero_point) { int num_packed_elems = n / bitpacking_bitwidth; int elements_left = n - bitpacking_bitwidth * num_packed_elems; const TIn* in = input_array; TBitpacked* out = bitpacked_array; #ifdef __aarch64__ if (FLATBUFFERS_LITTLEENDIAN && ((std::is_same<TIn, float>::value && zero_point == 0) || std::is_same<TIn, std::int8_t>::value)) { const int num_4x32_blocks = num_packed_elems / 4; bitpack_aarch64_4x32(in, num_4x32_blocks, out, zero_point); in += bitpacking_bitwidth * 4 * num_4x32_blocks; out += 4 * num_4x32_blocks; num_packed_elems %= 4; } #endif while (num_packed_elems--) { bitpack_bitfield(in, out++, zero_point); in += bitpacking_bitwidth; } // If padding is needed, copy the remaining elements to a buffer and add // enough zeros to fill the bitpacking_bitwidth. This function assumes enough // memory for padding is already allocated in the output array // `bitpacked_array`. if (elements_left != 0) { std::array<TIn, bitpacking_bitwidth> padding_buffer = {{0}}; memcpy(padding_buffer.data(), in, elements_left * sizeof(TIn)); for (size_t i = elements_left; i < bitpacking_bitwidth; ++i) padding_buffer[i] = zero_point; bitpack_bitfield(padding_buffer.data(), out, zero_point); } } // Bitpacks each row of a row-major matrix template <class TIn> inline void bitpack_matrix(const TIn* input, const std::size_t input_num_rows, const std::size_t input_num_cols, TBitpacked* output, const std::int32_t zero_point = 0) { // Calculate the size of the bitpacked rows const std::size_t output_num_cols = GetBitpackedSize(input_num_cols); // The public API has an Int32 zero-point, to match the TFLite spec, but // bitpacking is trivial if the zero-point is outside the TIn representable // range. if (zero_point <= std::numeric_limits<TIn>::lowest()) { // All values must represent >= 0, so the bitpacked bits will all be 0. std::fill(output, output + input_num_rows * output_num_cols, TBitpacked(0)); return; } if (zero_point > std::numeric_limits<TIn>::max()) { // All values must represent < 0, so the bitpacked bits will all be 1. // Unlike the >= 0 case above, this needs more caution, because while // the bitpacking bits will all be 1, any padding bits, if applicable, still // must be zero. if (input_num_cols % bitpacking_bitwidth == 0) { // First, the easy case where there's no padding: just binary ones. std::fill(output, output + input_num_rows * output_num_cols, ~TBitpacked(0)); } else { // With padding, all elements of each output column will be binary ones, // except the final element, which will have a prefix of ones with a // suffix of zeroes. const TBitpacked value_with_padding = (1 << (input_num_cols % bitpacking_bitwidth)) - 1; int rows = input_num_rows; while (rows--) { std::fill(output, output + output_num_cols - 1, ~TBitpacked(0)); output += output_num_cols; *(output - 1) = value_with_padding; } } return; } // Now that we know that the zero point is within the range of TIn, we can // cast it safely. const TIn zero_point_TIn = static_cast<TIn>(zero_point); if (input_num_cols % bitpacking_bitwidth == 0) { // If each row can be bitpacked without any padding, then we can treat // the matrix as one flat array and bitpack it all in one go. bitpack_array(input, input_num_cols * input_num_rows, output, zero_point_TIn); } else { // Iterate through each row of the input matrix and bitpack the row into the // corresponding memory location of the output matrix for (std::size_t row_index = 0; row_index < input_num_rows; ++row_index) { bitpack_array(input, input_num_cols, output, zero_point_TIn); input += input_num_cols; output += output_num_cols; } } } template <typename TUnpacked> void unpack_bitfield(const TBitpacked in, TUnpacked*& out, std::size_t num_elements, const TUnpacked zero_bit_result, const TUnpacked one_bit_result) { ruy::profiler::ScopeLabel label("Unpack bitfield (unoptimised)"); for (size_t i = 0; i < num_elements; ++i) { *out++ = (in & (TBitpacked(1) << i)) ? one_bit_result : zero_bit_result; } } // The matrix is stored in row-major mode. // Every row is bitpacked as TBitpacked, with canonical order // The argument `num_cols` is the *unpacked* number of cols! // Enough output memory is assumed. template <typename TUnpacked> inline void unpack_matrix(const TBitpacked* input_data, const std::size_t num_rows, const std::size_t num_cols, TUnpacked* output_data, const TUnpacked zero_bit_result = TUnpacked(+1), const TUnpacked one_bit_result = TUnpacked(-1)) { const TBitpacked* in_ptr = input_data; TUnpacked* out_ptr = output_data; for (size_t row_index = 0; row_index < num_rows; ++row_index) { int num_full_blocks = num_cols / bitpacking_bitwidth; int elements_left = num_cols - bitpacking_bitwidth * num_full_blocks; while (num_full_blocks--) { unpack_bitfield(*in_ptr++, out_ptr, bitpacking_bitwidth, zero_bit_result, one_bit_result); } if (elements_left != 0) { unpack_bitfield(*in_ptr++, out_ptr, elements_left, zero_bit_result, one_bit_result); } } } } // namespace bitpacking } // namespace core } // namespace compute_engine #endif // COMPUTE_ENGINE_CORE_BITPACKING_BITPACK_H_ <|start_filename|>larq_compute_engine/mlir/tf_to_tfl_flatbuffer.h<|end_filename|> #ifndef LARQ_COMPUTE_ENGINE_MLIR_TF_TO_TFL_FLATBUFFER_H_ #define LARQ_COMPUTE_ENGINE_MLIR_TF_TO_TFL_FLATBUFFER_H_ #include "mlir/IR/BuiltinOps.h" #include "mlir/Pass/PassManager.h" #include "tensorflow/stream_executor/lib/statusor.h" namespace tensorflow { // This is a fork of ConvertTFExecutorToTFLOrFlatbuffer to enable custom // OpOrArgLocNameMapper // https://github.com/tensorflow/tensorflow/blob/v2.5.0/tensorflow/compiler/mlir/lite/tf_to_tfl_flatbuffer.h#L55-L69 Status ConvertTFExecutorToFlatbuffer(mlir::ModuleOp module, bool export_to_mlir, std::string* result, mlir::PassManager* pass_manager); } // namespace tensorflow #endif // LARQ_COMPUTE_ENGINE_MLIR_TF_TO_TFL_FLATBUFFER_H_ <|start_filename|>larq_compute_engine/core/types.h<|end_filename|> #ifndef COMPUTE_ENGINE_CORE_TYPES_H_ #define COMPUTE_ENGINE_CORE_TYPES_H_ #include <bitset> #include <cstdint> #include <limits> #include <type_traits> #include "tensorflow/lite/kernels/internal/cppmath.h" namespace compute_engine { namespace core { #if defined(__GNUC__) #define LCE_LIKELY(condition) (__builtin_expect(!!(condition), 1)) #define LCE_UNLIKELY(condition) (__builtin_expect(condition, 0)) #else #define LCE_LIKELY(condition) (condition) #define LCE_UNLIKELY(condition) (condition) #endif #if defined(__GNUC__) #define FORCE_INLINE __attribute__((always_inline)) inline #else #define FORCE_INLINE inline #endif // Check that 0 <= index < limit using a single comparison, assuming // that 0 <= limit if Index is signed. Intended for use in performance // critical contexts where 0 <= index < limit is almost always true. inline bool FastBoundsCheck(const int index, const int limit) { return LCE_LIKELY((unsigned)index < (unsigned)limit); } // In our kernels we may occasionally read (but never write) beyond the end of // an array. This is the maximum number of extra bytes that will be read, and // should be added as padding to the end of tensor allocations. #define LCE_EXTRA_BYTES 16 // Define these once here, so they can be included everywhere. using TBitpacked = std::int32_t; constexpr std::size_t bitpacking_bitwidth = std::numeric_limits<typename std::make_unsigned<TBitpacked>::type>::digits; inline int xor_popcount(const TBitpacked& a, const TBitpacked& b) { return std::bitset<bitpacking_bitwidth>(a ^ b).count(); } // Clamp an int32 value to int8 range inline std::int8_t saturate(std::int32_t x) { #ifdef __arm__ std::int8_t y; asm("ssat %[y], #8, %[x]\n" : [y] "=r"(y) : [x] "r"(x)); return y; #else x = std::min<std::int32_t>(x, std::numeric_limits<std::int8_t>::max()); x = std::max<std::int32_t>(x, std::numeric_limits<std::int8_t>::lowest()); return static_cast<std::int8_t>(x); #endif } // arithmetic right shift and clamp an int32 value to int8 range template <int shift> inline std::int8_t shift_saturate(std::int32_t x) { #ifdef __arm__ std::int8_t y; asm("ssat %[y], #8, %[x], asr %[shift]\n" : [y] "=r"(y) : [x] "r"(x), [shift] "i"(shift)); return y; #else x = x >> shift; x = std::min<std::int32_t>(x, std::numeric_limits<std::int8_t>::max()); x = std::max<std::int32_t>(x, std::numeric_limits<std::int8_t>::lowest()); return static_cast<std::int8_t>(x); #endif } // Round-to-nearest. Handling of ties is allowed to be anything, as discussed in // https://github.com/tensorflow/tensorflow/issues/25087 inline std::int32_t round(float x) { #if defined(__thumb__) && defined(__VFP_FP__) && !defined(__SOFTFP__) // The `vcvtr` instructions follows the IEEE 754 rounding standard which // rounds halfway points to the nearest *even* integer. std::int32_t y; asm("vcvtr.s32.f32 %[x], %[x] \n" "vmov %[y], %[x] \n" : [y] "=r"(y) : [x] "t"(x)); // The "t" means `x` will be in an FPU register return y; #else return ::tflite::TfLiteRound(x); #endif } template <typename T, typename S> constexpr T CeilDiv(T a, S b) { return (a + b - 1) / b; } template <typename T, typename S> constexpr T Ceil(T a, S b) { return CeilDiv(a, b) * b; } } // namespace core } // namespace compute_engine #endif // COMPUTE_ENGINE_CORE_TYPES_H_ <|start_filename|>larq_compute_engine/tflite/kernels/bmaxpool.cc<|end_filename|> #include "larq_compute_engine/core/bmaxpool.h" #include "flatbuffers/flexbuffers.h" #include "larq_compute_engine/tflite/kernels/utils.h" #include "ruy/profiler/instrumentation.h" #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/kernels/kernel_util.h" using namespace tflite; namespace ce = compute_engine; namespace compute_engine { namespace tflite { namespace bmaxpool { using ce::core::TBitpacked; void* Init(TfLiteContext* context, const char* buffer, size_t length) { auto* poolparams = new core::BMaxPoolParams{}; const std::uint8_t* buffer_t = reinterpret_cast<const std::uint8_t*>(buffer); const flexbuffers::Map& m = flexbuffers::GetRoot(buffer_t, length).AsMap(); poolparams->filter_height = m["filter_height"].AsInt32(); poolparams->filter_width = m["filter_width"].AsInt32(); poolparams->stride_height = m["stride_height"].AsInt32(); poolparams->stride_width = m["stride_width"].AsInt32(); poolparams->padding_type = ConvertPadding((Padding)m["padding"].AsInt32()); return poolparams; } void Free(TfLiteContext* context, void* buffer) { delete reinterpret_cast<core::BMaxPoolParams*>(buffer); } TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { core::BMaxPoolParams* poolparams = reinterpret_cast<core::BMaxPoolParams*>(node->user_data); TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); TfLiteTensor* output = GetOutput(context, node, 0); const TfLiteTensor* input = GetInput(context, node, 0); TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4); TF_LITE_ENSURE_EQ(context, input->type, kTfLiteInt32); TF_LITE_ENSURE_EQ(context, output->type, kTfLiteInt32); TF_LITE_ENSURE(context, poolparams->stride_height != 0); TF_LITE_ENSURE(context, poolparams->stride_width != 0); TF_LITE_ENSURE(context, poolparams->filter_height != 0); TF_LITE_ENSURE(context, poolparams->filter_width != 0); int height = SizeOfDimension(input, 1); int width = SizeOfDimension(input, 2); // Matching GetWindowedOutputSize in TensorFlow. int out_width, out_height; poolparams->padding = ComputePaddingHeightWidth( poolparams->stride_height, poolparams->stride_width, 1, 1, height, width, poolparams->filter_height, poolparams->filter_width, poolparams->padding_type, &out_height, &out_width); TfLiteIntArray* output_size = TfLiteIntArrayCreate(4); output_size->data[0] = SizeOfDimension(input, 0); output_size->data[1] = out_height; output_size->data[2] = out_width; output_size->data[3] = SizeOfDimension(input, 3); return context->ResizeTensor(context, output, output_size); } TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { ruy::profiler::ScopeLabel label("Binary MaxPool"); core::BMaxPoolParams* poolparams = reinterpret_cast<core::BMaxPoolParams*>(node->user_data); TfLiteTensor* output = GetOutput(context, node, 0); const TfLiteTensor* input = GetInput(context, node, 0); core::BMaxPool(*poolparams, GetTensorShape(input), GetTensorData<TBitpacked>(input), GetTensorShape(output), GetTensorData<TBitpacked>(output)); return kTfLiteOk; } } // namespace bmaxpool TfLiteRegistration* Register_BMAXPOOL_2D() { static TfLiteRegistration r = {bmaxpool::Init, bmaxpool::Free, bmaxpool::Prepare, bmaxpool::Eval}; return &r; } } // namespace tflite } // namespace compute_engine <|start_filename|>larq_compute_engine/mlir/python/pybind_export.cc<|end_filename|> #include "pybind11/pybind11.h" #include "pybind11/pytypes.h" #include "pybind11/stl.h" namespace tensorflow { using std::string; pybind11::bytes ConvertGraphDefToTFLiteFlatBuffer( const pybind11::bytes& graphdef_bytes, const std::vector<string>& input_arrays, const std::vector<string>& input_dtypes, const std::vector<std::vector<int>>& input_shapes, const std::vector<string>& output_arrays, const bool should_quantize, const std::string& target_str, const pybind11::object& default_ranges, const bool experimental_enable_bitpacked_activations); pybind11::bytes ConvertSavedModelToTFLiteFlatBuffer( const std::string& saved_model_dir, const std::vector<std::string>& saved_model_tags, const std::vector<std::string>& exported_names, const int saved_model_version, const std::string& target_str, const pybind11::object& default_ranges, const bool experimental_enable_bitpacked_activations); } // namespace tensorflow PYBIND11_MODULE(_tf_tfl_flatbuffer, m) { m.def("convert_graphdef_to_tflite_flatbuffer", &tensorflow::ConvertGraphDefToTFLiteFlatBuffer); m.def("convert_saved_model_to_tflite_flatbuffer", &tensorflow::ConvertSavedModelToTFLiteFlatBuffer); }; <|start_filename|>larq_compute_engine/tflite/kernels/bconv2d.cc<|end_filename|> #include <cmath> #include <cstdint> #include "flatbuffers/flexbuffers.h" #include "larq_compute_engine/core/bconv2d/optimized_bgemm.h" #include "larq_compute_engine/core/bconv2d/optimized_indirect_bgemm.h" #include "larq_compute_engine/core/bconv2d/params.h" #include "larq_compute_engine/core/bconv2d/reference.h" #include "larq_compute_engine/core/bconv2d/zero_padding_correction.h" #include "larq_compute_engine/core/indirect_bgemm/kernel.h" #include "larq_compute_engine/core/indirect_bgemm/select_kernel.h" #include "larq_compute_engine/core/types.h" #include "larq_compute_engine/tflite/kernels/utils.h" #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/kernels/cpu_backend_context.h" #include "tensorflow/lite/kernels/internal/quantization_util.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/kernels/kernel_util.h" #include "tensorflow/lite/kernels/padding.h" using namespace tflite; namespace compute_engine { namespace tflite { namespace bconv2d { using core::TBitpacked; using namespace core::bconv2d; using namespace core::bitpacking; enum class KernelType { // The reference implementation with for-loops. kReference, // The Ruy implementation with im2col and hand-optimized BGEMM kernels. kOptimizedBGEMM, // The XNNPack-derived implementation with indirect BGEMM kernels. kOptimizedIndirectBGEMM, }; constexpr int kTensorNotAllocated = -1; struct OpData { BConv2DParams params; // Fused activation function TfLiteFusedActivation fused_activation_function; // Computed output transform values. These are only used when writing // float/int8 output. std::int32_t output_transform_clamp_min; std::int32_t output_transform_clamp_max; std::vector<float> output_transform_multiplier; std::vector<float> output_transform_bias; // This is used when we have 'same-zero' padding. std::vector<float> padding_buffer; // This is used for the 'indirect bgemm' kernel type. std::unique_ptr<core::indirect_bgemm::Kernel> indirect_bgemm_kernel; // IDs are the arbitrary identifiers used by TF Lite to identify and access // memory buffers. They are unique in the entire TF Lite context. int im2col_id = kTensorNotAllocated; // In node->temporaries there is a list of tensor id's that are part // of this node in particular. The indices below are offsets into this array. // So in pseudo-code: `node->temporaries[index] = id;` std::int32_t im2col_index = -1; bool successfully_initialized = false; bool one_time_setup_complete = false; }; #define LCE_ENSURE_PARAM(op_data, context, a) \ do { \ if (!(a)) { \ TF_LITE_KERNEL_LOG((context), "%s:%d %s was not true.", __FILE__, \ __LINE__, #a); \ return op_data; \ } \ } while (0) void* Init(TfLiteContext* context, const char* buffer, std::size_t length) { auto* op_data = new OpData{}; auto* bconv2d_params = &op_data->params; const std::uint8_t* buffer_t = reinterpret_cast<const std::uint8_t*>(buffer); const flexbuffers::Map& m = flexbuffers::GetRoot(buffer_t, length).AsMap(); // Read the op's input arguments into the `bconv2d_params` struct LCE_ENSURE_PARAM(op_data, context, !m["stride_height"].IsNull()); LCE_ENSURE_PARAM(op_data, context, !m["stride_width"].IsNull()); LCE_ENSURE_PARAM(op_data, context, !m["dilation_height_factor"].IsNull()); LCE_ENSURE_PARAM(op_data, context, !m["dilation_width_factor"].IsNull()); LCE_ENSURE_PARAM(op_data, context, !m["padding"].IsNull()); LCE_ENSURE_PARAM(op_data, context, !m["pad_values"].IsNull()); LCE_ENSURE_PARAM(op_data, context, !m["channels_in"].IsNull()); LCE_ENSURE_PARAM(op_data, context, !m["fused_activation_function"].IsNull()); bconv2d_params->stride_height = m["stride_height"].AsInt32(); bconv2d_params->stride_width = m["stride_width"].AsInt32(); bconv2d_params->dilation_height_factor = m["dilation_height_factor"].AsInt32(); bconv2d_params->dilation_width_factor = m["dilation_width_factor"].AsInt32(); bconv2d_params->padding_type = ConvertPadding((Padding)m["padding"].AsInt32()); bconv2d_params->pad_value = m["pad_values"].AsInt32(); if (bconv2d_params->pad_value != 0 && bconv2d_params->pad_value != 1) { TF_LITE_KERNEL_LOG(context, "Attribute pad_values must be 0 or 1."); return op_data; } // The input and filters are bitpacked along the channel in axis, which means // we cannot infer the 'true' input shape, so there's an explicit integer // attribute added to the op in the converter. bconv2d_params->channels_in = m["channels_in"].AsInt32(); op_data->fused_activation_function = ConvertActivation( (ActivationFunctionType)m["fused_activation_function"].AsInt32()); // It's not possible to return an error code in this method. If we get to here // without returning early, initialisation has succeeded without error, and so // we set this flag. If it's unset in Prepare, we report the error there. op_data->successfully_initialized = true; return op_data; } void Free(TfLiteContext* context, void* buffer) { delete reinterpret_cast<OpData*>(buffer); } template <KernelType kernel_type> TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { auto* op_data = reinterpret_cast<OpData*>(node->user_data); auto* bconv2d_params = &op_data->params; // If an error happened in Init, then return an error code. if (!op_data->successfully_initialized) return kTfLiteError; TF_LITE_ENSURE_EQ(context, node->inputs->size, 5); const auto* input = GetInput(context, node, 0); const auto* filter = GetInput(context, node, 1); const auto* post_activation_multiplier = GetInput(context, node, 2); const auto* post_activation_bias = GetInput(context, node, 3); const auto* thresholds = GetInput(context, node, 4); auto* output = GetOutput(context, node, 0); TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4); TF_LITE_ENSURE_EQ(context, NumDimensions(filter), 4); TF_LITE_ENSURE_EQ(context, input->type, kTfLiteInt32); TF_LITE_ENSURE_EQ(context, filter->type, kTfLiteInt32); TF_LITE_ENSURE_MSG(context, output->type == kTfLiteInt32 || output->type == kTfLiteInt8 || output->type == kTfLiteFloat32, "Supported output types are int8, int32, and float32."); // Read the filter dimensions bconv2d_params->channels_out = SizeOfDimension(filter, 0); bconv2d_params->filter_height = SizeOfDimension(filter, 1); bconv2d_params->filter_width = SizeOfDimension(filter, 2); if (SizeOfDimension(filter, 3) == GetBitpackedSize(bconv2d_params->channels_in)) { bconv2d_params->groups = 1; } else { TF_LITE_ENSURE_MSG( context, kernel_type != KernelType::kOptimizedBGEMM, "Grouped binary convolutions are not supported with this kernel."); TF_LITE_ENSURE_EQ(context, GetBitpackedSize(bconv2d_params->channels_in) % SizeOfDimension(filter, 3), 0); const std::int32_t groups = GetBitpackedSize(bconv2d_params->channels_in) / SizeOfDimension(filter, 3); const std::int32_t group_size = bconv2d_params->channels_in / groups; TF_LITE_ENSURE_EQ(context, group_size % core::bitpacking_bitwidth, 0); TF_LITE_ENSURE_EQ(context, bconv2d_params->channels_out % groups, 0); bconv2d_params->groups = groups; } if (bconv2d_params->padding_type == kTfLitePaddingSame && bconv2d_params->pad_value == 0) { TF_LITE_ENSURE_MSG( context, (kernel_type == KernelType::kReference && bconv2d_params->channels_in % 2 == 0) || (kernel_type != KernelType::kReference && output->type == kTfLiteFloat32 && op_data->fused_activation_function == kTfLiteActNone), "Zero-padding is only supported by the reference kernel with an even " "number of input channels, or when using " "float output with no fused activation function."); } // Compute the padding and output values (height, width) int out_width, out_height; bconv2d_params->padding_values = ComputePaddingHeightWidth( bconv2d_params->stride_height, bconv2d_params->stride_width, bconv2d_params->dilation_height_factor, bconv2d_params->dilation_width_factor, SizeOfDimension(input, 1), SizeOfDimension(input, 2), bconv2d_params->filter_height, bconv2d_params->filter_width, bconv2d_params->padding_type, &out_height, &out_width); if (output->type == kTfLiteInt32) { TF_LITE_ENSURE_EQ(context, NumDimensions(thresholds), 1); TF_LITE_ENSURE_EQ(context, thresholds->type, kTfLiteInt32); TF_LITE_ENSURE_EQ(context, SizeOfDimension(thresholds, 0), bconv2d_params->channels_out); } else { TF_LITE_ENSURE_EQ(context, post_activation_multiplier->type, kTfLiteFloat32); TF_LITE_ENSURE_EQ(context, post_activation_bias->type, kTfLiteFloat32); TF_LITE_ENSURE_EQ(context, NumDimensions(post_activation_multiplier), 1); TF_LITE_ENSURE_EQ(context, NumDimensions(post_activation_bias), 1); TF_LITE_ENSURE_EQ(context, SizeOfDimension(post_activation_multiplier, 0), bconv2d_params->channels_out); TF_LITE_ENSURE_EQ(context, SizeOfDimension(post_activation_bias, 0), bconv2d_params->channels_out); } if (output->type == kTfLiteInt8) { TF_LITE_ENSURE_EQ(context, output->quantization.type, kTfLiteAffineQuantization); } if (kernel_type == KernelType::kOptimizedIndirectBGEMM) { TF_LITE_ENSURE_MSG( context, input->allocation_type != kTfLiteDynamic, "The input tensor must not have dynamic allocation type"); } // Determine the output dimensions and allocate the output buffer TfLiteIntArray* output_shape = TfLiteIntArrayCreate(4); output_shape->data[0] = SizeOfDimension(input, 0); output_shape->data[1] = out_height; output_shape->data[2] = out_width; output_shape->data[3] = output->type == kTfLiteInt32 ? GetBitpackedSize(bconv2d_params->channels_out) : bconv2d_params->channels_out; TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, output, output_shape)); // Figure out how many temporary buffers we need int temporaries_count = 0; const bool need_im2col = kernel_type == KernelType::kOptimizedBGEMM && (bconv2d_params->stride_width != 1 || bconv2d_params->stride_height != 1 || bconv2d_params->dilation_width_factor != 1 || bconv2d_params->dilation_height_factor != 1 || bconv2d_params->filter_width != 1 || bconv2d_params->filter_height != 1); // Pre-allocate temporary tensors if (need_im2col) { op_data->im2col_index = temporaries_count++; } else { op_data->im2col_index = -1; } if (temporaries_count != 0) { // Allocate int array of that size TfLiteIntArrayFree(node->temporaries); node->temporaries = TfLiteIntArrayCreate(temporaries_count); } // Now allocate the buffers if (need_im2col) { // Allocate the im2col tensor if necessary if (op_data->im2col_id == kTensorNotAllocated) { context->AddTensors(context, 1, &op_data->im2col_id); node->temporaries->data[op_data->im2col_index] = op_data->im2col_id; } // Resize the im2col tensor const std::int32_t bitpacked_channels_in = GetBitpackedSize(bconv2d_params->channels_in); TfLiteIntArray* im2col_size = TfLiteIntArrayCopy(output_shape); im2col_size->data[3] = bitpacked_channels_in * bconv2d_params->filter_height * bconv2d_params->filter_width; TfLiteTensor* im2col = GetTemporary(context, node, op_data->im2col_index); im2col->type = kTfLiteInt32; im2col->allocation_type = kTfLiteArenaRw; TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, im2col, im2col_size)); } // Prepare could be called multiple times; when the input tensor is resized, // we shoud always re-do the one-time setup. op_data->one_time_setup_complete = false; return kTfLiteOk; } inline void GetConvParamsType(const OpData* op_data, ConvParams& conv2d_params) { const auto* bconv2d_params = &op_data->params; // Padding conv2d_params.padding_type = RuntimePaddingType(bconv2d_params->padding_type); conv2d_params.padding_values.width = bconv2d_params->padding_values.width; conv2d_params.padding_values.height = bconv2d_params->padding_values.height; // Strides conv2d_params.stride_height = bconv2d_params->stride_height; conv2d_params.stride_width = bconv2d_params->stride_width; // Dilations conv2d_params.dilation_height_factor = bconv2d_params->dilation_height_factor; conv2d_params.dilation_width_factor = bconv2d_params->dilation_width_factor; // Activation function conv2d_params.quantized_activation_min = op_data->output_transform_clamp_min; conv2d_params.quantized_activation_max = op_data->output_transform_clamp_max; } void OneTimeSetup(TfLiteContext* context, TfLiteNode* node, OpData* op_data) { const auto* bconv2d_params = &op_data->params; const auto* filter = GetInput(context, node, 1); const auto* post_activation_multiplier = GetInput(context, node, 2); const auto* post_activation_bias = GetInput(context, node, 3); const auto* output = GetOutput(context, node, 0); // Division is safe because at this point we know that channels_in is a // multiple of the number of groups. const std::int32_t channels_in_per_group = bconv2d_params->channels_in / bconv2d_params->groups; // For 'same-zero' padding, compute the padding-correction. if (bconv2d_params->padding_type == kTfLitePaddingSame && bconv2d_params->pad_value == 0) { op_data->padding_buffer.resize(zero_padding_correction::GetCacheSize( bconv2d_params->filter_height, bconv2d_params->filter_width, bconv2d_params->channels_out, bconv2d_params->dilation_height_factor, bconv2d_params->dilation_width_factor)); zero_padding_correction::CacheCorrectionValues( GetTensorData<TBitpacked>(filter), bconv2d_params->filter_height, bconv2d_params->filter_width, bconv2d_params->channels_out, channels_in_per_group, bconv2d_params->dilation_height_factor, bconv2d_params->dilation_width_factor, GetTensorData<float>(post_activation_multiplier), op_data->padding_buffer.data()); } // If applicable, fuse the back-transformation and int8 scale/zero-point into // the output transform multiplier/bias. if (output->type == kTfLiteFloat32 || output->type == kTfLiteInt8) { op_data->output_transform_multiplier.resize( bconv2d_params->channels_out + LCE_EXTRA_BYTES / sizeof(float)); op_data->output_transform_bias.resize(bconv2d_params->channels_out + LCE_EXTRA_BYTES / sizeof(float)); const auto filter_shape = GetTensorShape(GetInput(context, node, 1)); const std::int32_t backtransform_add = filter_shape.Dims(1) * filter_shape.Dims(2) * channels_in_per_group; const double output_scale = output->type == kTfLiteInt8 ? output->params.scale : 1.0; const double output_zero_point = output->type == kTfLiteInt8 ? output->params.zero_point : 0.0; for (int i = 0; i < bconv2d_params->channels_out; ++i) { const double post_mul = GetTensorData<float>(post_activation_multiplier)[i]; const double post_bias = GetTensorData<float>(post_activation_bias)[i]; op_data->output_transform_multiplier.at(i) = -1 * post_mul / output_scale; op_data->output_transform_bias.at(i) = (post_bias + static_cast<double>(backtransform_add) * post_mul) / output_scale + output_zero_point; } std::int32_t nominal_clamp_min, nominal_clamp_max; CalculateActivationRange(op_data->fused_activation_function, &nominal_clamp_min, &nominal_clamp_max); nominal_clamp_min = std::max(nominal_clamp_min, -1 * backtransform_add); nominal_clamp_max = std::min(nominal_clamp_max, backtransform_add); op_data->output_transform_clamp_min = -1 * nominal_clamp_max + backtransform_add; op_data->output_transform_clamp_max = -1 * nominal_clamp_min + backtransform_add; } op_data->one_time_setup_complete = true; } // Fill in the OutputTransform values for float and/or int8 outputs template <typename DstScalar> void GetOutputTransform(OutputTransform<DstScalar>& output_transform, TfLiteContext* context, TfLiteNode* node, OpData* op_data) { static_assert(std::is_same<DstScalar, float>::value || std::is_same<DstScalar, std::int8_t>::value, ""); output_transform.clamp_min = op_data->output_transform_clamp_min; output_transform.clamp_max = op_data->output_transform_clamp_max; output_transform.multiplier = op_data->output_transform_multiplier.data(); output_transform.bias = op_data->output_transform_bias.data(); } // Fill in the OutputTransform values for bitpacked outputs void GetOutputTransform(OutputTransform<TBitpacked>& output_transform, TfLiteContext* context, TfLiteNode* node, OpData* op_data) { const auto* thresholds = GetInput(context, node, 4); output_transform.thresholds = GetTensorData<std::int32_t>(thresholds); } template <typename AccumScalar, typename DstScalar> void EvalOptBGEMM(TfLiteContext* context, TfLiteNode* node, OpData* op_data) { if (!op_data->one_time_setup_complete) { OneTimeSetup(context, node, op_data); } auto* bconv2d_params = &op_data->params; const auto* input = GetInput(context, node, 0); const auto* filter = GetInput(context, node, 1); auto* output = GetOutput(context, node, 0); TfLiteTensor* im2col = op_data->im2col_index >= 0 ? GetTemporary(context, node, op_data->im2col_index) : nullptr; // Using the standard TF Lite ConvParams struct. This requires extra step of // converting the BConv2DParams but unifies the interface with the default // TFLite API for Conv2D params which is used in internal TFLite im2col // functions. ConvParams conv2d_params; GetConvParamsType(op_data, conv2d_params); conv2d_params.input_offset = input->params.zero_point; OutputTransform<DstScalar> output_transform; GetOutputTransform(output_transform, context, node, op_data); // `BConv2D` wants the *unpacked* output shape. auto unpacked_output_shape = GetTensorShape(output); unpacked_output_shape.SetDim(3, bconv2d_params->channels_out); // We pass the shape of the original unpacked filter, so that all the shape // information is correct (number of channels etc), but we pass the packed // weights data. // Likewise, we pass the original output shape even if we are going to // write bitpacked output directly. BConv2DOptimizedBGEMM<AccumScalar, DstScalar>( conv2d_params, GetTensorShape(input), GetTensorData<TBitpacked>(input), GetTensorShape(filter), GetTensorData<TBitpacked>(filter), output_transform, unpacked_output_shape, GetTensorData<DstScalar>(output), GetTensorShape(im2col), GetTensorData<TBitpacked>(im2col), op_data->padding_buffer.data(), bconv2d_params->pad_value, CpuBackendContext::GetFromContext(context)); } template <typename DstScalar> void EvalOptIndirectBGEMM(TfLiteContext* context, TfLiteNode* node, OpData* op_data) { if (!op_data->one_time_setup_complete) { OneTimeSetup(context, node, op_data); } auto* bconv2d_params = &op_data->params; const auto* input = GetInput(context, node, 0); const auto* filter = GetInput(context, node, 1); auto* output = GetOutput(context, node, 0); const auto bitpacked_input_shape = GetTensorShape(input); const auto output_shape = GetTensorShape(output); if (!op_data->indirect_bgemm_kernel) { OutputTransform<DstScalar> output_transform; GetOutputTransform(output_transform, context, node, op_data); op_data->indirect_bgemm_kernel = std::move(core::indirect_bgemm::SelectRuntimeKernel( &op_data->params, bitpacked_input_shape, output_shape, output_transform)); op_data->indirect_bgemm_kernel->PackWeights( GetTensorData<TBitpacked>(filter)); op_data->indirect_bgemm_kernel->FillIndirectionBuffer( &op_data->params, bitpacked_input_shape, output_shape, GetTensorData<TBitpacked>(input)); } BConv2DOptimizedIndirectBGEMM<DstScalar>( op_data->indirect_bgemm_kernel.get(), bconv2d_params, bitpacked_input_shape, output_shape, GetTensorData<DstScalar>(output), op_data->padding_buffer.data(), bconv2d_params->pad_value); } template <typename DstScalar> void EvalRef(TfLiteContext* context, TfLiteNode* node, OpData* op_data) { if (!op_data->one_time_setup_complete) { OneTimeSetup(context, node, op_data); } const auto* input = GetInput(context, node, 0); const auto* packed_filter = GetInput(context, node, 1); auto* output = GetOutput(context, node, 0); OutputTransform<DstScalar> output_transform; GetOutputTransform(output_transform, context, node, op_data); BConv2DReference<std::int32_t, DstScalar>( &op_data->params, GetTensorShape(input), GetTensorData<TBitpacked>(input), GetTensorShape(packed_filter), GetTensorData<TBitpacked>(packed_filter), output_transform, GetTensorShape(output), GetTensorData<DstScalar>(output)); } template <KernelType kernel_type, typename DstScalar> inline TfLiteStatus EvalChooseKernelType(TfLiteContext* context, TfLiteNode* node, OpData* op_data) { if (kernel_type == KernelType::kOptimizedBGEMM) { #if RUY_PLATFORM_ARM_64 // On 64 bit Arm only there is an optimised kernel with 16-bit accumulators. // It is safe to use this without risk of overflow as long as the maximum // value of the convolution (filter height * filter width * input channels, // plus some overhead to account for potential padding) is less than 2^16. // We will almost always take this path: for a 3x3 filter there would need // to be > 7000 input channels to present an overflow risk. const int depth = op_data->params.filter_height * op_data->params.filter_width * op_data->params.channels_in; if (depth + 512 < 1 << 16) { EvalOptBGEMM<std::int16_t, DstScalar>(context, node, op_data); return kTfLiteOk; } #endif // In all other cases, use 32-bit accumulators. EvalOptBGEMM<std::int32_t, DstScalar>(context, node, op_data); return kTfLiteOk; } else if (kernel_type == KernelType::kOptimizedIndirectBGEMM) { EvalOptIndirectBGEMM<DstScalar>(context, node, op_data); return kTfLiteOk; } else if (kernel_type == KernelType::kReference) { EvalRef<DstScalar>(context, node, op_data); return kTfLiteOk; } return kTfLiteError; } template <KernelType kernel_type> TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteType output_type = GetOutput(context, node, 0)->type; auto* op_data = reinterpret_cast<OpData*>(node->user_data); if (output_type == kTfLiteFloat32) { return EvalChooseKernelType<kernel_type, float>(context, node, op_data); } else if (output_type == kTfLiteInt8) { return EvalChooseKernelType<kernel_type, std::int8_t>(context, node, op_data); } else if (output_type == kTfLiteInt32) { return EvalChooseKernelType<kernel_type, TBitpacked>(context, node, op_data); } return kTfLiteError; } } // namespace bconv2d TfLiteRegistration* Register_BCONV_2D_REF() { static TfLiteRegistration r = { bconv2d::Init, bconv2d::Free, bconv2d::Prepare<bconv2d::KernelType::kReference>, bconv2d::Eval<bconv2d::KernelType::kReference>}; return &r; } TfLiteRegistration* Register_BCONV_2D_OPT_BGEMM() { static TfLiteRegistration r = { bconv2d::Init, bconv2d::Free, bconv2d::Prepare<bconv2d::KernelType::kOptimizedBGEMM>, bconv2d::Eval<bconv2d::KernelType::kOptimizedBGEMM>}; return &r; } TfLiteRegistration* Register_BCONV_2D_OPT_INDIRECT_BGEMM() { static TfLiteRegistration r = { bconv2d::Init, bconv2d::Free, bconv2d::Prepare<bconv2d::KernelType::kOptimizedIndirectBGEMM>, bconv2d::Eval<bconv2d::KernelType::kOptimizedIndirectBGEMM>}; return &r; } // Use this registration wrapper to decide which implementation to use. TfLiteRegistration* Register_BCONV_2D() { #if defined TFLITE_WITH_RUY return Register_BCONV_2D_OPT_BGEMM(); #else return Register_BCONV_2D_REF(); #endif } } // namespace tflite } // namespace compute_engine <|start_filename|>larq_compute_engine/mlir/transforms/bitpack.h<|end_filename|> #ifndef LARQ_COMPUTE_ENGINE_MLIR_TRANSFORMS_BITPACK_H_ #define LARQ_COMPUTE_ENGINE_MLIR_TRANSFORMS_BITPACK_H_ #include "mlir/IR/Attributes.h" #include "mlir/IR/Builders.h" #include "mlir/IR/BuiltinTypes.h" namespace mlir { namespace TFL { DenseElementsAttr Bitpack(mlir::Builder* builder, Attribute x); DenseElementsAttr Unpack(Attribute x, ShapedType result_type); } // namespace TFL } // namespace mlir #endif <|start_filename|>larq_compute_engine/mlir/transforms/bitpack.cc<|end_filename|> #include "larq_compute_engine/mlir/transforms/bitpack.h" #include <cmath> #include <vector> #include "larq_compute_engine/core/bitpacking/bitpack.h" #include "larq_compute_engine/core/types.h" #include "mlir/Dialect/Quant/QuantTypes.h" namespace mlir { namespace TFL { using compute_engine::core::bitpacking_bitwidth; using compute_engine::core::round; using compute_engine::core::saturate; using compute_engine::core::TBitpacked; using namespace compute_engine::core::bitpacking; DenseElementsAttr Bitpack(mlir::Builder* builder, Attribute x) { if (!x) return nullptr; // ShapedType is something like tensor<1x2x3xf32> and element_type is f32 auto shaped_type = x.getType().cast<ShapedType>(); auto shape = shaped_type.getShape(); auto element_type = shaped_type.getElementType(); int num_rows = shape[0] * shape[1] * shape[2]; int unpacked_channels = shape[3]; int packed_channels = GetBitpackedSize(unpacked_channels); std::vector<TBitpacked> new_values(num_rows * packed_channels); if (element_type.isF32()) { const auto& dense_elements_iter = x.cast<DenseElementsAttr>().getValues<float>(); std::vector<float> old_values(num_rows * unpacked_channels); int i = 0; for (float x : dense_elements_iter) { old_values[i++] = x; } assert(i == num_rows * unpacked_channels); bitpack_matrix(old_values.data(), num_rows, unpacked_channels, new_values.data()); } else { // constant-fold bitpacking int8 tensors is currently not supported return nullptr; } RankedTensorType out_tensor_type = RankedTensorType::get({shape[0], shape[1], shape[2], packed_channels}, builder->getIntegerType(bitpacking_bitwidth)); return DenseElementsAttr::get<TBitpacked>(out_tensor_type, new_values); } DenseElementsAttr Unpack(Attribute x, ShapedType result_type) { if (!x) return nullptr; if (!result_type.hasStaticShape()) return nullptr; auto input_shape = x.getType().cast<ShapedType>().getShape(); auto output_shape = result_type.getShape(); auto output_type = result_type.getElementType(); int num_rows = output_shape[0] * output_shape[1] * output_shape[2]; int unpacked_channels = output_shape[3]; int packed_channels = GetBitpackedSize(unpacked_channels); if (input_shape[0] != output_shape[0] || input_shape[1] != output_shape[1] || input_shape[2] != output_shape[2] || input_shape[3] != packed_channels) { return nullptr; } std::vector<TBitpacked> old_values(num_rows * packed_channels); const auto& dense_elements_iter = x.cast<DenseElementsAttr>().getValues<TBitpacked>(); int i = 0; for (TBitpacked x : dense_elements_iter) { old_values[i++] = x; } assert(i == num_rows * packed_channels); if (output_type.isF32()) { std::vector<float> new_values(num_rows * unpacked_channels); unpack_matrix(old_values.data(), num_rows, unpacked_channels, new_values.data()); return DenseElementsAttr::get<float>(result_type, new_values); } else { auto quant_type = output_type.cast<mlir::quant::UniformQuantizedType>(); const double scale = quant_type.getScale(); const int zero_point = quant_type.getZeroPoint(); std::int8_t zero_bit_result = saturate(zero_point + round(+1.0 / scale)); std::int8_t one_bit_result = saturate(zero_point + round(-1.0 / scale)); std::vector<std::int8_t> new_values(num_rows * unpacked_channels); unpack_matrix(old_values.data(), num_rows, unpacked_channels, new_values.data(), zero_bit_result, one_bit_result); return DenseElementsAttr::get<std::int8_t>(result_type, new_values); } } } // namespace TFL } // namespace mlir <|start_filename|>Dockerfile<|end_filename|> FROM ubuntu:18.04 RUN apt-get update && apt-get install curl zip unzip git build-essential openjdk-8-jdk-headless python3-dev python3-pip qemu-user -y --no-install-recommends && rm -rf /var/lib/apt/lists/* RUN curl -L https://github.com/bazelbuild/bazelisk/releases/download/v1.7.4/bazelisk-linux-amd64 > /usr/local/bin/bazelisk && chmod +x /usr/local/bin/bazelisk RUN ln -s /usr/bin/python3 /usr/local/bin/python && ln -s /usr/bin/pip3 /usr/local/bin/pip RUN pip install six numpy --no-cache-dir WORKDIR /compute-engine COPY . . RUN ./third_party/install_android.sh ENV MANYLINUX2010=1 RUN ./configure.py RUN bazelisk --version <|start_filename|>larq_compute_engine/core/indirect_bgemm/kernel.h<|end_filename|> #ifndef COMPUTE_ENGINE_INDIRECT_BGEMM_KERNEL_H_ #define COMPUTE_ENGINE_INDIRECT_BGEMM_KERNEL_H_ #include <cstdint> #include <vector> #include "larq_compute_engine/core/bconv2d/output_transform.h" #include "larq_compute_engine/core/bconv2d/params.h" #include "larq_compute_engine/core/types.h" #include "tensorflow/lite/kernels/internal/types.h" namespace compute_engine { namespace core { namespace indirect_bgemm { class Kernel { public: const std::int32_t block_size_output_channels; const std::int32_t block_size_pixels; const std::int32_t block_size_depth; const std::int32_t input_depth; const std::int32_t output_channels; const std::int32_t filter_size; const std::int32_t groups; const std::int32_t num_output_pixels; std::vector<TBitpacked> packed_weights; std::vector<const TBitpacked*> indirection_buffer; std::vector<TBitpacked> zero_buffer; Kernel(const std::int32_t block_size_output_channels, const std::int32_t block_size_pixels, const std::int32_t block_size_depth, const bconv2d::BConv2DParams* bconv2d_params, const RuntimeShape& bitpacked_input_shape, const RuntimeShape& output_shape) : block_size_output_channels(block_size_output_channels), block_size_pixels(block_size_pixels), block_size_depth(block_size_depth), input_depth(bitpacked_input_shape.Dims(3)), output_channels(bconv2d_params->channels_out), filter_size(bconv2d_params->filter_height * bconv2d_params->filter_width), groups(bconv2d_params->groups), num_output_pixels(bitpacked_input_shape.Dims(0) * output_shape.Dims(1) * output_shape.Dims(2)) {} /** * Pack the weights in the correct order. This procedure is (heavily) * adapted from the following XNNPack function: * https://github.com/google/XNNPACK/blob/80a8ac59849bfdae8d2e1409f5642baa502c0b9e/src/packing.c#L429-L484 */ void PackWeights(const TBitpacked* weights_ptr) { const auto input_depth_per_group = input_depth / groups; const auto output_channels_per_group = output_channels / groups; const auto rounded_up_output_channels_per_group = Ceil(output_channels_per_group, block_size_output_channels); packed_weights.resize(groups * rounded_up_output_channels_per_group * filter_size * input_depth_per_group + /* padding */ block_size_output_channels * block_size_depth); std::int32_t packed_weights_index = 0; for (std::int32_t group_id = 0; group_id < groups; group_id++) { for (std::int32_t block_start = 0; block_start < output_channels_per_group; block_start += block_size_output_channels) { const std::int32_t block_size = std::min(output_channels_per_group - block_start, block_size_output_channels); for (std::int32_t fi = 0; fi < filter_size; fi++) { for (std::int32_t ci = 0; ci < input_depth_per_group; ci += block_size_depth) { for (std::int32_t block_offset = 0; block_offset < block_size; block_offset++) { for (std::int32_t ci_offset = 0; ci_offset < block_size_depth; ci_offset++) { const std::int32_t weights_index = (group_id * output_channels_per_group * filter_size * input_depth_per_group) + ((block_start + block_offset) * filter_size * input_depth_per_group) + fi * input_depth_per_group + ci + ci_offset; packed_weights.at(packed_weights_index++) = weights_ptr[weights_index]; } } packed_weights_index += (block_size_output_channels - block_size) * block_size_depth; } } } } } /** * Fill the indirection buffer. This procedure is (heavily) adapted from the * following XNNPack function: * https://github.com/google/XNNPACK/blob/80a8ac59849bfdae8d2e1409f5642baa502c0b9e/src/indirection.c#L18-L76 */ void FillIndirectionBuffer(const bconv2d::BConv2DParams* bconv2d_params, const RuntimeShape& bitpacked_input_shape, const RuntimeShape& output_shape, const TBitpacked* input_ptr) { const auto filter_height = bconv2d_params->filter_height; const auto filter_width = bconv2d_params->filter_width; const auto stride_height = bconv2d_params->stride_height; const auto stride_width = bconv2d_params->stride_width; const auto dilation_height = bconv2d_params->dilation_height_factor; const auto dilation_width = bconv2d_params->dilation_width_factor; const auto input_padding_top = bconv2d_params->padding_values.height; const auto input_padding_left = bconv2d_params->padding_values.width; const auto input_height = bitpacked_input_shape.Dims(1); const auto input_width = bitpacked_input_shape.Dims(2); const auto output_height = output_shape.Dims(1); const auto output_width = output_shape.Dims(2); const auto output_size = num_output_pixels; const auto tiled_output_size = Ceil(output_size, block_size_pixels); // Create the indirection buffer with padding (+ block_size_pixels) and fill // it with pointers to the first element of the input, so that the padding // at the end of the array contains pointers to valid memory. indirection_buffer.assign( tiled_output_size * filter_size + block_size_pixels, input_ptr); // Assign the zero buffer that will be used for padding. zero_buffer.assign(filter_size * input_depth, 0); for (std::int32_t output_tile_start = 0; output_tile_start < tiled_output_size; output_tile_start += block_size_pixels) { for (std::int32_t output_tile_offset = 0; output_tile_offset < block_size_pixels; output_tile_offset++) { const std::int32_t output_index = std::min(output_tile_start + output_tile_offset, output_size - 1); const std::int32_t batch_index = output_index / (output_height * output_width); const std::int32_t output_x = output_index % output_width; const std::int32_t output_y = (output_index % (output_height * output_width)) / output_width; for (std::int32_t f_y = 0; f_y < filter_height; f_y++) { const std::int32_t input_y = output_y * stride_height + f_y * dilation_height - input_padding_top; if (0 <= input_y && input_y < input_height) { for (std::int32_t f_x = 0; f_x < filter_width; f_x++) { const std::int32_t input_x = output_x * stride_width + f_x * dilation_width - input_padding_left; const std::int32_t kernel_index = f_y * filter_width + f_x; const std::int32_t index = output_tile_start * filter_size + kernel_index * block_size_pixels + output_tile_offset; if (FastBoundsCheck(input_x, input_width)) { indirection_buffer.at(index) = (input_ptr + (batch_index * input_height * input_width + input_y * input_width + input_x) * input_depth); } else { indirection_buffer.at(index) = zero_buffer.data(); } } } else { for (std::int32_t f_x = 0; f_x < filter_width; f_x++) { const std::int32_t kernel_index = f_y * filter_width + f_x; const std::int32_t index = output_tile_start * filter_size + kernel_index * block_size_pixels + output_tile_offset; indirection_buffer.at(index) = zero_buffer.data(); } } } } } } // To be implemented by concrete subclasses. virtual void Run(const std::int32_t pixel_start, const std::int32_t pixel_end, void* output_ptr) const = 0; void Dispatch(void* output_ptr) const { // TODO: implement multithreading here. Run(0, num_output_pixels, output_ptr); }; virtual ~Kernel() {} }; } // namespace indirect_bgemm } // namespace core } // namespace compute_engine #endif // COMPUTE_ENGINE_INDIRECT_BGEMM_KERNEL_H_ <|start_filename|>larq_compute_engine/core/bconv2d/optimized_indirect_bgemm.h<|end_filename|> #ifndef COMPUTE_ENGINE_CORE_BCONV2D_OPTIMIZED_INDIRECT_BGEMM_H_ #define COMPUTE_ENGINE_CORE_BCONV2D_OPTIMIZED_INDIRECT_BGEMM_H_ #include "larq_compute_engine/core/bconv2d/zero_padding_correction.h" #include "larq_compute_engine/core/indirect_bgemm/kernel.h" #include "ruy/profiler/instrumentation.h" #include "tensorflow/lite/kernels/internal/types.h" namespace compute_engine { namespace core { namespace bconv2d { template <typename AccumScalar, typename DstScalar> inline void BConv2DOptimizedIndirectBGEMM( const indirect_bgemm::Kernel* kernel, const BConv2DParams* bconv2d_params, const RuntimeShape& bitpacked_input_shape, const RuntimeShape& output_shape, DstScalar* output_ptr, const float* padding_buffer, const int pad_value) { ruy::profiler::ScopeLabel label("BConv2D (optimized, indirect BGEMM)"); // If writing bitpacked output with a channel count that isn't a multiple of // 32 (i.e. where padding bits will be required in the output), fill the // output tensor with zeroes in advance so that the BGEMM doesn't have to // worry about doing the padding. if (std::is_same<DstScalar, TBitpacked>::value && (kernel->output_channels % bitpacking_bitwidth != 0)) { std::fill( output_ptr, output_ptr + kernel->num_output_pixels * bitpacking::GetBitpackedSize(kernel->output_channels), TBitpacked(0)); } kernel->Dispatch(reinterpret_cast<void*>(output_ptr)); if (std::is_same<DstScalar, float>::value && bconv2d_params->padding_type == TfLitePadding::kTfLitePaddingSame && pad_value == 0) { ruy::profiler::ScopeLabel label("Zero padding correction"); const int stride_width = bconv2d_params->stride_width; const int stride_height = bconv2d_params->stride_height; const int dilation_width_factor = bconv2d_params->dilation_width_factor; const int dilation_height_factor = bconv2d_params->dilation_height_factor; const int batches = MatchingDim(bitpacked_input_shape, 0, output_shape, 0); const int input_depth_per_group = bconv2d_params->channels_in / bconv2d_params->groups; const int input_width = bitpacked_input_shape.Dims(2); const int input_height = bitpacked_input_shape.Dims(1); const int filter_height = bconv2d_params->filter_height; const int filter_width = bconv2d_params->filter_width; const int output_depth = output_shape.Dims(3); const int output_width = output_shape.Dims(2); const int output_height = output_shape.Dims(1); zero_padding_correction::ApplyCorrection( batches, input_height, input_width, input_depth_per_group, filter_height, filter_width, output_depth, stride_height, stride_width, dilation_height_factor, dilation_width_factor, reinterpret_cast<float*>(output_ptr), output_height, output_width, padding_buffer); } } } // namespace bconv2d } // namespace core } // namespace compute_engine #endif // COMPUTE_ENGINE_CORE_BCONV2D_OPTIMIZED_INDIRECT_BGEMM_H_ <|start_filename|>larq_compute_engine/core/bconv2d/output_transform.h<|end_filename|> #ifndef COMPUTE_ENGINE_CORE_BCONV2D_OUTPUT_TRANSFORM_H_ #define COMPUTE_ENGINE_CORE_BCONV2D_OUTPUT_TRANSFORM_H_ #include <algorithm> #include <cstdint> #include <limits> #include "larq_compute_engine/core/types.h" #include "tensorflow/lite/kernels/internal/common.h" #include "tensorflow/lite/kernels/internal/cppmath.h" namespace compute_engine { namespace core { namespace bconv2d { // Clamp an int32 value to int8 range inline std::int8_t saturate(std::int32_t x) { #ifdef __arm__ std::int8_t y; asm("ssat %[y], #8, %[x]\n" : [y] "=r"(y) : [x] "r"(x)); return y; #else x = std::min<std::int32_t>(x, std::numeric_limits<std::int8_t>::max()); x = std::max<std::int32_t>(x, std::numeric_limits<std::int8_t>::lowest()); return static_cast<std::int8_t>(x); #endif } // Round-to-nearest. Handling of ties is allowed to be anything, as discussed in // https://github.com/tensorflow/tensorflow/issues/25087 inline std::int32_t round(float x) { #if defined(__thumb__) && defined(__VFP_FP__) && !defined(__SOFTFP__) // The `vcvtr` instructions follows the IEEE 754 rounding standard which // rounds halfway points to the nearest *even* integer. std::int32_t y; asm("vcvtr.s32.f32 %[x], %[x] \n" "vmov %[y], %[x] \n" : [y] "=r"(y) : [x] "t"(x)); // The "t" means `x` will be in an FPU register return y; #else return tflite::TfLiteRound(x); #endif } enum class OutputTransformDetails { Default, IntegerOnly, }; /* * The `OutputTransform` struct describes what needs to be done to get from the * int32 accumulator value to the final result that is written back to memory. */ template <typename DstScalar, OutputTransformDetails = OutputTransformDetails::Default> struct OutputTransform {}; /* * ------------ * Float output * ------------ * * Conceptually, the float output transform is as follows: * 0. We start with an XOR-popcount accumulator value `accum`. It lies in the * range {0, ..., K}, where K := `kernel_height` * `kernel_width` * * `channels_in` is the maximum number of bits that can be set. * 1. Perform a 'back-transformation', which is a linear transformation that * maps {0, ..., K} onto {-K, ..., K}: * K - 2 * accum = -2 * accum + K * This yields the 'true output' of the binary convolution operation, in * the sense that it's the same value that you would get by running a * normal floating-point convolution with +1/-1 input and +1/-1 weights. * 2. Perform a clamp operation that represents a fused activation function. * 3. Convert to float and perform a linear transformation with a multiplier * and bias that represents a fused batch normalisation layer. * * Thus, the float output transform is: * float_cast(clamp(-2 * accum + K)) * mul + bias * * However, we can perform an equivalent, faster computation, by adjusting the * clamp values and fusing (part of) the back-transformation into the * multiplier/bias: * float_cast(clamp'(accum << 1)) * mul' + bias' * * Note that the left shift cannot be fused, because the left-shifted * accumulator value will either be always odd or always even, and we support * clamping to arbitrary integers. * * The parameters of the output transform are therefore two int32 clamp values * and float pointers to a multiplier and a bias. */ template <> struct OutputTransform<float, OutputTransformDetails::Default> { std::int32_t clamp_min = std::numeric_limits<std::int32_t>::lowest(); std::int32_t clamp_max = std::numeric_limits<std::int32_t>::max(); const float* multiplier = nullptr; const float* bias = nullptr; float Run(const std::int32_t accum, int out_channel) const { TFLITE_DCHECK(multiplier != nullptr); TFLITE_DCHECK(bias != nullptr); std::int32_t x = accum << 1; x = std::max<std::int32_t>(std::min<std::int32_t>(x, clamp_max), clamp_min); return static_cast<float>(x) * multiplier[out_channel] + bias[out_channel]; } }; /* * ----------- * Int8 output * ----------- * * For int8 output, there are two additional conceptual steps: * 4. Multiply by the reciprocal of the int8 output scale, and add the int8 * zero-point. * 5. Round to an integer and clamp to the int8 range. * * We can fuse step (4) into the existing multiplier/bias, and so the int8 * output transform is: * int8_cast(float_cast(clamp'(accum << 1)) * mul + bias) * * Thus, the int8 output transform parameters are the same as in the float case. */ template <> struct OutputTransform<std::int8_t, OutputTransformDetails::Default> { std::int32_t clamp_min = std::numeric_limits<std::int32_t>::lowest(); std::int32_t clamp_max = std::numeric_limits<std::int32_t>::max(); const float* multiplier = nullptr; const float* bias = nullptr; std::int8_t Run(const std::int32_t accum, int out_channel) const { TFLITE_DCHECK(multiplier != nullptr); TFLITE_DCHECK(bias != nullptr); // Clamping is done in int32 std::int32_t x = accum << 1; x = std::max<std::int32_t>(std::min<std::int32_t>(x, clamp_max), clamp_min); // The linear transformation is done in float float y = static_cast<float>(x) * multiplier[out_channel] + bias[out_channel]; // And then we round back to int32 and clamp to the int8 range return saturate(round(y)); } }; /* * ---------------- * Bitpacked output * ---------------- * * For writing bitpacked output, the output transform needs to yield a single * bit - the sign of the result of conceptual step (3). In fact, it's possible * to avoid having to do the clamping and the linear transformation first, and * instead compare the accumulator directly against a pre-computed threshold to * work out which bit to return. * * Thus, the bitpacked output transform parameters are a single pointer to an * array of pre-computed thresholds. */ template <> struct OutputTransform<TBitpacked, OutputTransformDetails::Default> { const std::int32_t* thresholds = nullptr; bool Run(const std::int32_t accum, int out_channel) const { TFLITE_DCHECK(thresholds != nullptr); return accum > thresholds[out_channel]; } }; } // namespace bconv2d } // namespace core } // namespace compute_engine #endif // COMPUTE_ENGINE_CORE_BCONV2D_OUTPUT_TRANSFORM_H_ <|start_filename|>larq_compute_engine/tflite/python/interpreter_wrapper_utils.h<|end_filename|> #ifndef COMPUTE_ENGINE_TFLITE_PYTHON_INTERPRETER_WRAPPER_UTILS_H_ #define COMPUTE_ENGINE_TFLITE_PYTHON_INTERPRETER_WRAPPER_UTILS_H_ #include <cstring> #include <sstream> #include "pybind11/numpy.h" #include "pybind11/pybind11.h" #include "pybind11/stl.h" #include "tensorflow/lite/c/common.h" #define PY_ERROR(x) \ { \ std::stringstream ss; \ ss << "ERROR at " << __FILE__ << ":" << __LINE__ << " : " << x \ << std::endl; \ throw std::runtime_error(ss.str()); \ } #define MINIMAL_CHECK(x) \ if (!(x)) { \ PY_ERROR("the following was false: " << #x) \ } template <typename InterpreterType> class InterpreterWrapperBase { public: InterpreterWrapperBase(){}; ~InterpreterWrapperBase(){}; // The python object `input` is a `List` of numpy arrays, // one numpy array for each model input. // // The result is a `List` of numpy arrays, one for each output pybind11::list predict(const pybind11::list& input_list); // List of numpy types pybind11::list get_input_types() { MINIMAL_CHECK(interpreter_); return get_types(interpreter_->inputs()); } pybind11::list get_output_types() { MINIMAL_CHECK(interpreter_); return get_types(interpreter_->outputs()); } // List of shape tuples pybind11::list get_input_shapes() { MINIMAL_CHECK(interpreter_); return get_shapes(interpreter_->inputs()); } pybind11::list get_output_shapes() { MINIMAL_CHECK(interpreter_); return get_shapes(interpreter_->outputs()); } // List of zero points, None for non-quantized tensors pybind11::list get_input_zero_points() { MINIMAL_CHECK(interpreter_); return get_zero_points(interpreter_->inputs()); } pybind11::list get_output_zero_points() { MINIMAL_CHECK(interpreter_); return get_zero_points(interpreter_->outputs()); } // List of quantization scales, None for non-quantized tensors pybind11::list get_input_scales() { MINIMAL_CHECK(interpreter_); return get_scales(interpreter_->inputs()); } pybind11::list get_output_scales() { MINIMAL_CHECK(interpreter_); return get_scales(interpreter_->outputs()); } protected: // Calls to MicroInterpreter::tensor allocate memory, so we must cache them TfLiteTensor* get_tensor(size_t index) { auto iter = tensors.find(index); if (iter != tensors.end()) return iter->second; TfLiteTensor* tensor = interpreter_->tensor(index); tensors[index] = tensor; return tensor; } std::unique_ptr<InterpreterType> interpreter_; std::map<int, TfLiteTensor*> tensors; template <typename TensorList> pybind11::list get_types(const TensorList& tensors); template <typename TensorList> pybind11::list get_shapes(const TensorList& tensors); template <typename TensorList> pybind11::list get_zero_points(const TensorList& tensors); template <typename TensorList> pybind11::list get_scales(const TensorList& tensors); }; TfLiteType TfLiteTypeFromPyType(pybind11::dtype py_type) { if (py_type.is(pybind11::dtype::of<float>())) return kTfLiteFloat32; if (py_type.is(pybind11::dtype::of<std::uint8_t>())) return kTfLiteUInt8; if (py_type.is(pybind11::dtype::of<std::int8_t>())) return kTfLiteInt8; if (py_type.is(pybind11::dtype::of<std::int16_t>())) return kTfLiteInt16; if (py_type.is(pybind11::dtype::of<std::int32_t>())) return kTfLiteInt32; if (py_type.is(pybind11::dtype::of<std::int64_t>())) return kTfLiteInt64; if (py_type.is(pybind11::dtype::of<bool>())) return kTfLiteBool; if (py_type.is(pybind11::dtype::of<char*>())) return kTfLiteString; return kTfLiteNoType; } pybind11::dtype PyTypeFromTfLiteType(TfLiteType type) { switch (type) { case kTfLiteFloat32: return pybind11::dtype::of<float>(); case kTfLiteUInt8: return pybind11::dtype::of<std::uint8_t>(); case kTfLiteInt8: return pybind11::dtype::of<std::int8_t>(); case kTfLiteInt16: return pybind11::dtype::of<std::int16_t>(); case kTfLiteInt32: return pybind11::dtype::of<std::int32_t>(); case kTfLiteInt64: return pybind11::dtype::of<std::int64_t>(); case kTfLiteBool: return pybind11::dtype::of<bool>(); case kTfLiteString: return pybind11::dtype::of<char*>(); case kTfLiteNoType: default: PY_ERROR("Model has invalid output type: " << type); return pybind11::dtype::of<float>(); }; } bool SetTensorFromNumpy(const TfLiteTensor* tensor, const pybind11::array& nparray) { TfLiteType type = TfLiteTypeFromPyType(nparray.dtype()); if (type != tensor->type) { PY_ERROR("Expected tensor type " << TfLiteTypeGetName(tensor->type) << " but got " << TfLiteTypeGetName(type) << " for tensor " << tensor->name); return false; } int ndim = nparray.ndim(); if (ndim != tensor->dims->size) { PY_ERROR("Expected tensor dimension " << tensor->dims->size << " but got " << ndim << " for tensor " << tensor->name); return false; } for (int j = 0; j < ndim; j++) { if (tensor->dims->data[j] != nparray.shape(j)) { PY_ERROR("Expected " << tensor->dims->data[j] << " for dimension " << j << " but found " << nparray.shape(j) << " for tensor " << tensor->name); return false; } } size_t size = nparray.nbytes(); if (size != tensor->bytes) { PY_ERROR("Expected " << tensor->bytes << " bytes but got " << size << " for tensor " << tensor->name); return false; } memcpy(tensor->data.raw, nparray.data(), size); return true; } template <typename InterpreterType> template <typename TensorList> pybind11::list InterpreterWrapperBase<InterpreterType>::get_types( const TensorList& tensors) { pybind11::list result; for (auto tensor_id : tensors) { const TfLiteTensor* tensor = get_tensor(tensor_id); result.append(PyTypeFromTfLiteType(tensor->type)); } return result; } template <typename InterpreterType> template <typename TensorList> pybind11::list InterpreterWrapperBase<InterpreterType>::get_shapes( const TensorList& tensors) { pybind11::list result; for (auto tensor_id : tensors) { const TfLiteTensor* tensor = get_tensor(tensor_id); pybind11::tuple shape(tensor->dims->size); for (int j = 0; j < tensor->dims->size; ++j) shape[j] = tensor->dims->data[j]; result.append(shape); } return result; } template <typename InterpreterType> template <typename TensorList> pybind11::list InterpreterWrapperBase<InterpreterType>::get_zero_points( const TensorList& tensors) { pybind11::list result; for (auto tensor_id : tensors) { const TfLiteTensor* tensor = get_tensor(tensor_id); if (tensor->quantization.type == kTfLiteAffineQuantization) { const int legacy_zero_point = tensor->params.zero_point; const auto* affine_quantization = reinterpret_cast<TfLiteAffineQuantization*>( tensor->quantization.params); MINIMAL_CHECK(affine_quantization); MINIMAL_CHECK(affine_quantization->zero_point); // For per-channel quantization, the zero point should be the same for // every channel for (int i = 0; i < affine_quantization->zero_point->size; ++i) MINIMAL_CHECK(affine_quantization->zero_point->data[i] == legacy_zero_point); result.append(pybind11::cast(legacy_zero_point)); } else { result.append(pybind11::cast<pybind11::none>(Py_None)); } } return result; } template <typename InterpreterType> template <typename TensorList> pybind11::list InterpreterWrapperBase<InterpreterType>::get_scales( const TensorList& tensors) { pybind11::list result; for (auto tensor_id : tensors) { const TfLiteTensor* tensor = get_tensor(tensor_id); if (tensor->quantization.type == kTfLiteAffineQuantization) { const float legacy_scale = tensor->params.scale; const auto* affine_quantization = reinterpret_cast<TfLiteAffineQuantization*>( tensor->quantization.params); MINIMAL_CHECK(affine_quantization); MINIMAL_CHECK(affine_quantization->scale); if (affine_quantization->scale->size == 1) { MINIMAL_CHECK(affine_quantization->scale->data[0] == legacy_scale); result.append(pybind11::cast(legacy_scale)); } else { std::vector<float> scales; for (int i = 0; i < affine_quantization->scale->size; ++i) scales.push_back(affine_quantization->scale->data[i]); result.append(pybind11::cast(scales)); } } else { result.append(pybind11::cast<pybind11::none>(Py_None)); } } return result; } template <typename InterpreterType> pybind11::list InterpreterWrapperBase<InterpreterType>::predict( const pybind11::list& input_list) { MINIMAL_CHECK(interpreter_); const size_t inputs_size = input_list.size(); if (inputs_size != interpreter_->inputs().size()) { PY_ERROR("Expected " << interpreter_->inputs().size() << " input tensors but got " << inputs_size << " tensors in dataset."); } for (size_t i = 0; i < inputs_size; ++i) { pybind11::array nparray = pybind11::array::ensure(input_list[i], pybind11::array::c_style); const TfLiteTensor* tensor = get_tensor(interpreter_->inputs()[i]); if (!SetTensorFromNumpy(tensor, nparray)) { PY_ERROR("Failed to set tensor data of input " << i); } } MINIMAL_CHECK(interpreter_->Invoke() == kTfLiteOk); pybind11::list result; for (auto output_id : interpreter_->outputs()) { TfLiteTensor* tensor = get_tensor(output_id); std::vector<int> shape(tensor->dims->data, tensor->dims->data + tensor->dims->size); pybind11::array nparray(PyTypeFromTfLiteType(tensor->type), shape, tensor->data.raw); result.append(nparray); } return result; } #endif <|start_filename|>larq_compute_engine/tflite/kernels/quantization.cc<|end_filename|> #include <type_traits> #include "larq_compute_engine/core/bitpacking/utils.h" #include "ruy/profiler/instrumentation.h" #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/kernels/internal/cppmath.h" #include "tensorflow/lite/kernels/internal/tensor.h" #include "tensorflow/lite/kernels/kernel_util.h" #include "tensorflow/lite/portable_type_to_tflitetype.h" using namespace tflite; namespace compute_engine { namespace tflite { using namespace core::bitpacking; using core::TBitpacked; TfLiteStatus QuantizePrepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input = GetInput(context, node, 0); TfLiteTensor* output = GetOutput(context, node, 0); TF_LITE_ENSURE(context, input->type == kTfLiteFloat32 || input->type == kTfLiteInt8 || input->type == kTfLiteBool); TF_LITE_ENSURE_EQ(context, output->type, kTfLiteInt32); int num_dims = NumDimensions(input); TF_LITE_ENSURE_EQ(context, num_dims, NumDimensions(output)); TfLiteIntArray* output_dims = TfLiteIntArrayCopy(input->dims); // The last dimension is bitpacked output_dims->data[num_dims - 1] = GetBitpackedSize(SizeOfDimension(input, num_dims - 1)); return context->ResizeTensor(context, output, output_dims); } TfLiteStatus DequantizePrepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input = GetInput(context, node, 0); TfLiteTensor* output = GetOutput(context, node, 0); TF_LITE_ENSURE_EQ(context, input->type, kTfLiteInt32); TF_LITE_ENSURE(context, output->type == kTfLiteFloat32 || output->type == kTfLiteInt8 || output->type == kTfLiteBool); int num_dims = NumDimensions(input); TF_LITE_ENSURE_EQ(context, num_dims, NumDimensions(output)); // The first n-1 dimensions are equal for (int i = 0; i < num_dims - 1; ++i) { TF_LITE_ENSURE_EQ(context, SizeOfDimension(output, i), SizeOfDimension(input, i)); } // The last dimension is bitpacked int packed_channels = SizeOfDimension(input, num_dims - 1); int unpacked_channels = SizeOfDimension(output, num_dims - 1); TF_LITE_ENSURE_EQ(context, packed_channels, GetBitpackedSize(unpacked_channels)); // We don't support resizing here, because we can not know the number of // output channels based on the number of input channels return kTfLiteOk; } TfLiteStatus QuantizeEval(TfLiteContext* context, TfLiteNode* node) { ruy::profiler::ScopeLabel label("Binary Quantize"); const TfLiteTensor* input = GetInput(context, node, 0); TfLiteTensor* output = GetOutput(context, node, 0); if (input->type == kTfLiteFloat32) { bitpack_tensor(GetTensorShape(input), GetTensorData<float>(input), 0, GetTensorData<TBitpacked>(output)); } else if (input->type == kTfLiteInt8) { bitpack_tensor(GetTensorShape(input), GetTensorData<std::int8_t>(input), input->params.zero_point, GetTensorData<TBitpacked>(output)); } else if (input->type == kTfLiteBool) { // The strategy here is to interpret the input data as an unsigned integer // (of the same width as the bool type for the target). We then call // bitpacking, with a 'zero point' of 1. This means that the value with all // zero bits will be bitpacked as bit 1, and all other values will be // bitpacked as bit 0. Assuming that `false` is represented by a value with // all zero bits, this gives the correct result of bitpacking `false` as bit // 1 and `true` as bit 0. static_assert(std::is_same<::tflite::TfLiteTypeToType<kTfLiteBool>::Type, bool>::value, ""); using BOOL_UINT = std::conditional< sizeof(bool) == 1, std::uint8_t, std::conditional<sizeof(bool) == 2, std::uint16_t, std::conditional<sizeof(bool) == 4, std::uint32_t, std::uint64_t>::type>::type>::type; static_assert(sizeof(bool) == sizeof(BOOL_UINT), ""); bitpack_tensor(GetTensorShape(input), GetTensorData<BOOL_UINT>(input), BOOL_UINT(1), GetTensorData<TBitpacked>(output)); } else { return kTfLiteError; } return kTfLiteOk; } TfLiteStatus DequantizeEval(TfLiteContext* context, TfLiteNode* node) { ruy::profiler::ScopeLabel label("Binary Dequantize"); const TfLiteTensor* input = GetInput(context, node, 0); TfLiteTensor* output = GetOutput(context, node, 0); auto out_shape = GetTensorShape(output); int dims = out_shape.DimensionsCount(); int num_rows = FlatSizeSkipDim(out_shape, dims - 1); int num_cols = out_shape.Dims(dims - 1); if (output->type == kTfLiteFloat32) { unpack_matrix(GetTensorData<TBitpacked>(input), num_rows, num_cols, GetTensorData<float>(output)); } else if (output->type == kTfLiteInt8) { int offset = TfLiteRound(1.0f / output->params.scale); std::int8_t zero_bit_result = std::min(127, output->params.zero_point + offset); std::int8_t one_bit_result = std::max(-128, output->params.zero_point - offset); unpack_matrix(GetTensorData<TBitpacked>(input), num_rows, num_cols, GetTensorData<std::int8_t>(output), zero_bit_result, one_bit_result); } else if (output->type == kTfLiteBool) { unpack_matrix(GetTensorData<TBitpacked>(input), num_rows, num_cols, GetTensorData<bool>(output), true, false); } else { return kTfLiteError; } return kTfLiteOk; } TfLiteRegistration* Register_QUANTIZE() { static TfLiteRegistration r = {nullptr, nullptr, QuantizePrepare, QuantizeEval}; return &r; } TfLiteRegistration* Register_DEQUANTIZE() { static TfLiteRegistration r = {nullptr, nullptr, DequantizePrepare, DequantizeEval}; return &r; } } // namespace tflite } // namespace compute_engine <|start_filename|>larq_compute_engine/core/bconv2d/optimized_bgemm.h<|end_filename|> #ifndef COMPUTE_ENGINE_CORE_BCONV2D_OPTIMIZED_BGEMM_H_ #define COMPUTE_ENGINE_CORE_BCONV2D_OPTIMIZED_BGEMM_H_ #include "larq_compute_engine/core/bconv2d/zero_padding_correction.h" #include "larq_compute_engine/core/bgemm/bgemm.h" #include "ruy/profiler/instrumentation.h" #include "tensorflow/lite/kernels/cpu_backend_context.h" #include "tensorflow/lite/kernels/cpu_backend_gemm_params.h" #include "tensorflow/lite/kernels/internal/optimized/im2col_utils.h" #include "tensorflow/lite/kernels/internal/types.h" #include "tensorflow/lite/kernels/padding.h" namespace compute_engine { namespace core { namespace bconv2d { using namespace tflite; inline void im2col(const ConvParams& params, const RuntimeShape& input_shape, const TBitpacked* input_data, const RuntimeShape& filter_shape, const RuntimeShape& output_shape, const RuntimeShape& im2col_shape, TBitpacked* im2col_data, RuntimeShape& result_shape, const TBitpacked** result_data) { const int stride_width = params.stride_width; const int stride_height = params.stride_height; const int dilation_width_factor = params.dilation_width_factor; const int dilation_height_factor = params.dilation_height_factor; // On bitpacked data, padding with `0` effectively pads with `+1.0` values. const std::uint8_t zero_byte = 0; const int filter_height = filter_shape.Dims(1); const int filter_width = filter_shape.Dims(2); const bool need_dilated_im2col = dilation_width_factor != 1 || dilation_height_factor != 1; const bool need_im2col = stride_width != 1 || stride_height != 1 || filter_width != 1 || filter_height != 1; const RuntimeShape* shape = nullptr; if (need_dilated_im2col) { TF_LITE_ASSERT(im2col_data); optimized_ops::DilatedIm2col<TBitpacked>(params, zero_byte, input_shape, input_data, filter_shape, output_shape, im2col_data); *result_data = im2col_data; shape = &im2col_shape; } else if (need_im2col) { TF_LITE_ASSERT(im2col_data); optimized_ops::Im2col<TBitpacked>(params, filter_height, filter_width, zero_byte, input_shape, input_data, im2col_shape, im2col_data); *result_data = im2col_data; shape = &im2col_shape; } else { TF_LITE_ASSERT(!im2col_data); *result_data = input_data; shape = &input_shape; } result_shape.ReplaceWith(shape->DimensionsCount(), shape->DimsData()); } template <typename AccumScalar, typename DstScalar> inline void BConv2DOptimizedBGEMM( const ConvParams& params, const RuntimeShape& input_shape, const TBitpacked* input_data, const RuntimeShape& filter_shape, const TBitpacked* packed_filter_data, const OutputTransform<DstScalar>& output_transform, const RuntimeShape& output_shape, DstScalar* output_data, const RuntimeShape& im2col_shape, TBitpacked* im2col_data, const float* padding_buffer, const int pad_value, CpuBackendContext* cpu_backend_context) { TF_LITE_ASSERT_EQ(input_shape.DimensionsCount(), 4); TF_LITE_ASSERT_EQ(filter_shape.DimensionsCount(), 4); TF_LITE_ASSERT_EQ(output_shape.DimensionsCount(), 4); ruy::profiler::ScopeLabel label("BConv2D (optimized)"); // m // ___________ // |1 7 | // |2 8 | // |3 9 | // k|. . inputs | // |. . | // k |___________| // ________ // |123.. | // |789.. | // | | k = filter_height * filter_width * channels_in / bitwidth // n| filter | m = output_height * output_width // | | n = output_channels // |________| // // Storage order is shown in the matrices // // inputs and filters are packed along the `channels_in` dimension. // const TBitpacked* lhs_data = packed_filter_data; const TBitpacked* rhs_data = nullptr; int n = filter_shape.Dims(0); int m = 0; int k = 0; RuntimeShape result_shape; im2col(params, input_shape, input_data, filter_shape, output_shape, im2col_shape, im2col_data, result_shape, &rhs_data); // If writing bitpacked output with a channel count that isn't a multiple of // 32 (i.e. where padding bits will be required in the output), fill the // output tensor with zeroes in advance so that the BGEMM doesn't have to // worry about doing the padding. if (std::is_same<DstScalar, TBitpacked>::value && output_shape.Dims(3) % bitpacking_bitwidth != 0) { std::fill( output_data, output_data + FlatSizeSkipDim(output_shape, 3) * bitpacking::GetBitpackedSize(output_shape.Dims(3)), TBitpacked(0)); } k = result_shape.Dims(3); m = FlatSizeSkipDim(result_shape, 3); // LHS (n, k/bitwidth) -> RowMajor -> (n, k/bitwidth) // RHS (m, k/bitwidth) -> ColMajor -> (k/bitwidth, m) // DST (n, m) -> ColMajor -> (m, n) cpu_backend_gemm::MatrixParams<TBitpacked> lhs_params; lhs_params.order = cpu_backend_gemm::Order::kRowMajor; lhs_params.rows = n; lhs_params.cols = k; // The LHS is the weights, which are static, so caching is prefered. lhs_params.cache_policy = cpu_backend_gemm::CachePolicy::kAlwaysCache; cpu_backend_gemm::MatrixParams<TBitpacked> rhs_params; rhs_params.order = cpu_backend_gemm::Order::kColMajor; rhs_params.rows = k; rhs_params.cols = m; // The RHS is the input activations, which change every inference, so there's // no advantage from caching. rhs_params.cache_policy = cpu_backend_gemm::CachePolicy::kNeverCache; cpu_backend_gemm::MatrixParams<DstScalar> dst_params; dst_params.order = cpu_backend_gemm::Order::kColMajor; dst_params.rows = n; dst_params.cols = m; bgemm::BGemm<AccumScalar>(lhs_params, lhs_data, rhs_params, rhs_data, dst_params, output_data, output_transform, cpu_backend_context); if (std::is_same<DstScalar, float>::value && params.padding_type == PaddingType::kSame && pad_value == 0) { ruy::profiler::ScopeLabel label("Zero padding correction"); const int stride_width = params.stride_width; const int stride_height = params.stride_height; const int dilation_width_factor = params.dilation_width_factor; const int dilation_height_factor = params.dilation_height_factor; const int batches = MatchingDim(input_shape, 0, output_shape, 0); const int input_depth = input_shape.Dims(3); const int input_width = input_shape.Dims(2); const int input_height = input_shape.Dims(1); const int filter_height = filter_shape.Dims(1); const int filter_width = filter_shape.Dims(2); const int output_depth = output_shape.Dims(3); const int output_width = output_shape.Dims(2); const int output_height = output_shape.Dims(1); zero_padding_correction::ApplyCorrection( batches, input_height, input_width, input_depth, filter_height, filter_width, output_depth, stride_height, stride_width, dilation_height_factor, dilation_width_factor, reinterpret_cast<float*>(output_data), output_height, output_width, padding_buffer); } } } // namespace bconv2d } // namespace core } // namespace compute_engine #endif // COMPUTE_ENGINE_CORE_BCONV2D_OPTIMIZED_BGEMM_H_ <|start_filename|>larq_compute_engine/tflite/build_make/Makefile<|end_filename|> # # This is based on # tensorflow/tensorflow/lite/tools/make/Makefile # # The makefile will always be run from the root of the compute engine repository # Make uses /bin/sh by default, which is incompatible with the bashisms seen # below. SHELL := /bin/bash TF_DIR := third_party/tensorflow TF_MAKEFILE_DIR := $(TF_DIR)/tensorflow/lite/tools/make ifeq ($(LCE_GEN_DIR),) $(error Please set LCE_GEN_DIR to specify an output dir) endif # Try to figure out the host system HOST_OS := ifeq ($(OS),Windows_NT) HOST_OS = windows else UNAME_S := $(shell uname -s) ifeq ($(UNAME_S),Linux) HOST_OS := linux endif ifeq ($(UNAME_S),Darwin) HOST_OS := osx endif endif HOST_ARCH := $(shell if uname -m | grep -q i[345678]86; then echo x86_32; else uname -m; fi) # Override these on the make command line to target a specific architecture. For example: # make -f tensorflow/lite/tools/make/Makefile TARGET=rpi TARGET_ARCH=armv7l TARGET := $(HOST_OS) TARGET_ARCH := $(HOST_ARCH) #LCE: Removed the following includes. It is unclear what they were for. #-I$(TF_MAKEFILE_DIR)/../../../../../ \ #-I$(TF_MAKEFILE_DIR)/../../../../../../ \ #-I$(OBJDIR) INCLUDES := \ -Ilarq_compute_engine/tflite/cc \ -I. \ -I$(TF_DIR) \ -I$(TF_MAKEFILE_DIR)/downloads/ \ -I$(TF_MAKEFILE_DIR)/downloads/eigen \ -I$(TF_MAKEFILE_DIR)/downloads/absl \ -I$(TF_MAKEFILE_DIR)/downloads/gemmlowp \ -I$(TF_MAKEFILE_DIR)/downloads/ruy \ -I$(TF_MAKEFILE_DIR)/downloads/neon_2_sse \ -I$(TF_MAKEFILE_DIR)/downloads/farmhash/src \ -I$(TF_MAKEFILE_DIR)/downloads/flatbuffers/include \ -I$(TF_MAKEFILE_DIR)/downloads/fp16/include # This is at the end so any globally-installed frameworks like protobuf don't # override local versions in the source tree. INCLUDES += -I/usr/local/include # These are the default libraries needed, but they can be added to or # overridden by the platform-specific settings in target makefiles. LIBS := \ -lstdc++ \ -lpthread \ -lm \ -lz \ -ldl # There are no rules for compiling objects for the host system (since we don't # generate things like the protobuf compiler that require that), so all of # these settings are for the target compiler. CFLAGS := -O3 -DNDEBUG -fPIC $(EXTRA_CFLAGS) CXXFLAGS := $(CFLAGS) --std=c++14 $(EXTRA_CXXFLAGS) LDOPTS := -L/usr/local/lib ARFLAGS := -r TARGET_TOOLCHAIN_PREFIX := CC_PREFIX := # Added by LCE: CXXFLAGS += -DTFLITE_WITH_RUY BUILD_WITH_RUY_PROFILER ?= false ifeq ($(BUILD_WITH_RUY_PROFILER),true) CXXFLAGS += -DRUY_PROFILER endif ifeq ($(HOST_OS),windows) CXXFLAGS += -fext-numeric-literals -D__LITTLE_ENDIAN__ endif # Auto-detect optimization opportunity if building natively. ifeq ($(HOST_OS),$(TARGET)) ifeq ($(HOST_ARCH),$(TARGET_ARCH)) ifeq ($(TARGET_ARCH),armv7l) ifneq ($(shell cat /proc/cpuinfo | grep Features | grep neon),) ifneq ($(shell cat /proc/cpuinfo | grep Features | grep vfpv4),) CXXFLAGS += -mfpu=neon-vfpv4 else CXXFLAGS += -mfpu=neon endif endif # ifeq ($(TARGET_ARCH),armv7l) endif # ifeq ($(HOST_ARCH),$(TARGET_ARCH)) endif # ifeq ($(HOST_OS),$(TARGET)) endif # This library is the main target for this makefile. It will contain a minimal # runtime that can be linked in to other programs. CORE_LIB_NAME := libtensorflow-lite.a BENCHMARK_LIB_NAME := benchmark-lib.a # What sources we want to compile, must be kept in sync with the main Bazel # build files. LCE_CORE_SRCS := $(wildcard larq_compute_engine/tflite/kernels/*.cc) LCE_EXAMPLE_SRCS := \ examples/lce_minimal.cc LCE_BENCHMARK_SRCS := \ larq_compute_engine/tflite/benchmark/lce_benchmark_main.cc # These target-specific makefiles should modify or replace options like # CXXFLAGS or LIBS to work for a specific targeted architecture. All logic # based on platforms or architectures should happen within these files, to # keep this main makefile focused on the sources and dependencies. include $(wildcard $(TF_MAKEFILE_DIR)/targets/*_makefile.inc) # Where compiled objects are stored. TARGET_OUT_DIR ?= $(TARGET)_$(TARGET_ARCH) GENDIR := $(TF_MAKEFILE_DIR)/gen/$(TARGET_OUT_DIR)/ OBJDIR := $(GENDIR)obj/ LIBDIR := $(GENDIR)lib/ BINDIR := $(LCE_GEN_DIR)/$(TARGET_OUT_DIR)/ CORE_LIB := $(LIBDIR)$(CORE_LIB_NAME) BENCHMARK_LIB := $(LIBDIR)$(BENCHMARK_LIB_NAME) LCE_EXAMPLE_BINARY := $(BINDIR)lce_minimal LCE_BENCHMARK_BINARY := $(BINDIR)lce_benchmark CXX := $(CC_PREFIX)${TARGET_TOOLCHAIN_PREFIX}g++ CC := $(CC_PREFIX)${TARGET_TOOLCHAIN_PREFIX}gcc AR := $(CC_PREFIX)${TARGET_TOOLCHAIN_PREFIX}ar LCE_CORE_OBJS := $(addprefix $(OBJDIR), \ $(patsubst %.cc,%.o,$(patsubst %.c,%.o,$(patsubst %.cpp,%.o,$(LCE_CORE_SRCS))))) LCE_EXAMPLE_OBJS := $(addprefix $(OBJDIR), \ $(patsubst %.cc,%.o,$(patsubst %.c,%.o,$(LCE_EXAMPLE_SRCS)))) LCE_BENCHMARK_OBJS := $(addprefix $(OBJDIR), \ $(patsubst %.cc,%.o,$(patsubst %.c,%.o,$(LCE_BENCHMARK_SRCS)))) # The target that's compiled if there's no command-line arguments. all: $(LCE_EXAMPLE_BINARY) $(LCE_BENCHMARK_BINARY) # For normal manually-created TensorFlow Lite C++ source files. $(OBJDIR)%.o: %.cpp @mkdir -p $(dir $@) $(CXX) $(CXXFLAGS) $(INCLUDES) -c $< -o $@ $(OBJDIR)%.o: %.cc @mkdir -p $(dir $@) $(CXX) $(CXXFLAGS) $(INCLUDES) -c $< -o $@ # For normal manually-created TensorFlow Lite C source files. $(OBJDIR)%.o: %.c @mkdir -p $(dir $@) $(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@ $(OBJDIR)%.o: %.cpp @mkdir -p $(dir $@) $(CXX) $(CXXFLAGS) $(INCLUDES) -c $< -o $@ $(LCE_EXAMPLE_BINARY): $(LCE_CORE_OBJS) $(LCE_EXAMPLE_OBJS) $(CORE_LIB) @mkdir -p $(dir $@) $(CXX) $(CXXFLAGS) $(INCLUDES) \ -o $(LCE_EXAMPLE_BINARY) $(LCE_CORE_OBJS) $(LCE_EXAMPLE_OBJS) \ $(LIBFLAGS) $(CORE_LIB) $(LDFLAGS) $(LIBS) $(LCE_BENCHMARK_BINARY): $(LCE_CORE_OBJS) $(LCE_BENCHMARK_OBJS) $(BENCHMARK_LIB) @mkdir -p $(dir $@) $(CXX) $(CXXFLAGS) $(INCLUDES) \ -o $(LCE_BENCHMARK_BINARY) $(LCE_CORE_OBJS) $(LCE_BENCHMARK_OBJS) \ $(LIBFLAGS) $(BENCHMARK_LIB) $(LDFLAGS) $(LIBS) # Gets rid of all generated files. clean: rm -rf $(TF_MAKEFILE_DIR)/gen # Gets rid of target files only, leaving the host alone. Also leaves the lib # directory untouched deliberately, so we can persist multiple architectures # across builds for iOS and Android. cleantarget: rm -rf $(OBJDIR) <|start_filename|>larq_compute_engine/mlir/python/graphdef_tfl_flatbuffer.cc<|end_filename|> #include <exception> #include "larq_compute_engine/mlir/tf_tfl_passes.h" #include "larq_compute_engine/mlir/tf_to_tfl_flatbuffer.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/ToolOutputFile.h" #include "mlir/IR/MLIRContext.h" #include "mlir/Pass/Pass.h" #include "mlir/Support/FileUtilities.h" #include "pybind11/pybind11.h" #include "pybind11/pytypes.h" #include "pybind11/stl.h" #include "tensorflow/compiler/mlir/lite/quantization/quantization_config.h" #include "tensorflow/compiler/mlir/lite/transforms/passes.h" #include "tensorflow/compiler/mlir/tensorflow/translate/import_model.h" #include "tensorflow/compiler/mlir/tensorflow/translate/mlir_roundtrip_flags.h" #include "tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.h" #include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h" #include "tensorflow/compiler/mlir/tensorflow/utils/import_utils.h" #include "tensorflow/core/framework/graph.pb.h" #include "tensorflow/core/framework/types.pb.h" #include "tensorflow/core/protobuf/graph_debug_info.pb.h" namespace tensorflow { pybind11::bytes ConvertGraphDefToTFLiteFlatBuffer( const pybind11::bytes& graphdef_bytes, const std::vector<string>& input_arrays, const std::vector<string>& input_dtypes, const std::vector<std::vector<int>>& input_shapes, const std::vector<string>& output_arrays, const bool should_quantize, const std::string& target_str, const pybind11::object& default_ranges, const bool experimental_enable_bitpacked_activations) { GraphDef graphdef; if (!tensorflow::LoadProtoFromBuffer(std::string(graphdef_bytes), &graphdef) .ok()) { throw std::runtime_error("Could not load GraphDef."); } LCETarget target; if (target_str == "arm") { target = LCETarget::ARM; } else if (target_str == "xcore") { target = LCETarget::XCORE; } else { throw std::runtime_error("Invalid target."); } // `ParseInputArrayInfo` requires a type that isn't pybind compatible, so // translate here. std::vector<llvm::Optional<std::vector<int>>> translated_input_shapes; for (auto x : input_shapes) { if (x.size() > 0) { translated_input_shapes.push_back(x); } else { translated_input_shapes.push_back(llvm::None); } } GraphImportConfig specs; specs.prune_unused_nodes = true; specs.convert_legacy_fed_inputs = true; specs.graph_as_function = false; specs.upgrade_legacy = true; if (!ParseInputArrayInfo(input_arrays, input_dtypes, translated_input_shapes, &specs.inputs) .ok()) { throw std::runtime_error("Could not parse input arrays."); } if (!ParseOutputArrayInfo(output_arrays, &specs.outputs).ok()) { throw std::runtime_error("Could not parse output arrays."); } mlir::MLIRContext context; GraphDebugInfo debug_info; mlir::StatusScopedDiagnosticHandler statusHandler(&context, /*propagate=*/true); auto module = ConvertGraphdefToMlir(graphdef, debug_info, specs, &context); if (!module.ok()) { throw std::runtime_error("Could not convert GraphDef."); } mlir::TFL::QuantizationSpecs quant_specs; if (should_quantize) { quant_specs.inference_type = tensorflow::DT_QINT8; for (auto input_array : input_arrays) { // Input inference type is DT_FLOAT, so set the default input ranges // to llvm::None. quant_specs.input_ranges.push_back({llvm::None, llvm::None}); } if (!default_ranges.is_none()) { quant_specs.default_ranges = default_ranges.cast<std::pair<double, double>>(); } } mlir::PassManager pm(&context, mlir::OpPassManager::Nesting::Implicit); tensorflow::SetCrashReproducer(pm); tensorflow::AddTFToLCETFLConversionPasses( quant_specs, &pm, target, experimental_enable_bitpacked_activations); // Convert back to outlined while format for export back to flatbuffer. pm.addPass(mlir::TFL::CreateWhileOutlinePass()); pm.addPass(mlir::TFL::CreateRuntimeVerifyPass()); std::string result; auto status = ConvertTFExecutorToFlatbuffer( module->get(), /*export_to_mlir=*/false, &result, &pm); if (!status.ok()) { throw std::runtime_error("Could not translate to flatbuffer."); } return pybind11::bytes(result); } } // namespace tensorflow
simonmaurer/compute-engine
<|start_filename|>test/dummy/app/assets/javascripts/app.js<|end_filename|> function sendData(url, content) { var xhr = new XMLHttpRequest(); xhr.onload = function () { // Process our return data if (xhr.status >= 200 && xhr.status < 300) { // What do when the request is successful console.log('success!', xhr); } else { // What do when the request fails console.log('The request failed!'); } // Code that should run regardless of the request status console.log('This always runs...'); }; xhr.open('PUT', url); xhr.setRequestHeader('X-CSRF-Token', document.querySelectorAll('meta[name="csrf-token"]')[0].content); data = new FormData(); data.set("content", content); xhr.send(data); } <|start_filename|>test/dummy/app/assets/javascripts/classic.js<|end_filename|> //= require new_ckeditor/classic/ckeditor.js <|start_filename|>test/dummy/app/assets/javascripts/balloon.js<|end_filename|> //= require new_ckeditor/balloon/ckeditor.js <|start_filename|>test/dummy/app/javascript/packs/application.js<|end_filename|> //= require rails-ujs //= require activestorage <|start_filename|>test/dummy/app/assets/javascripts/inline.js<|end_filename|> //= require new_ckeditor/inline/ckeditor.js
igorkasyanchuk/new_ckeditor
<|start_filename|>package.json<|end_filename|> { "name": "contentful-to-algolia", "version": "4.3.1", "description": "Transfer Contentful data to Algolia", "main": "index.js", "repository": "<EMAIL>:drublic/contentful-to-algolia.git", "author": "<NAME> <<EMAIL>>", "license": "MIT", "scripts": { "js:lint": "eslint {**/,}*.js" }, "dependencies": { "algoliasearch": "^3.33.0", "contentful": "^7.7.0", "eslint": "^5.16.0", "lodash": "^4.17.11" }, "cacheDirectories": [ "node_modules" ] }
drublic/contentful-to-algolia
<|start_filename|>test/__fixtures__/validate-ssl.js<|end_filename|> module.exports.validWildCardKey = `-----BEGIN PRIVATE KEY----- MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC6iTFLz75M9XxU TdX/xIh3mQSchRPQI5b3F6NbIfNxGCif8+cJznwMn54mMA+qeYFvyXUBIB8blU6O 3/xx3NpbplL6QWI+Ck07ZdCPZp33tPN65DZ/7SbWXVi4szzQlPZhlmFiIPCqlRU8 Lo/FcF/JXAHjk+1tJ61ZWhiqM3721h8L4/o3nkDjtVgr0rn1t1yr5fgGcB/HaB70 oNEOBh17cRB4yKBej5lnOH/U9cDXPsUBLZaWOJ2IQX4NZZwYnINfDa97xkLYrwC0 Z+e6EVxXyAgHMRM29KDfuwLoFGuOEj3xX0G8JlF9uYegy3u4y486B2/HA+NagtW0 wUflqwBPAgMBAAECggEAH8DC13jhmBAhvegSCZvW7yTpGAu/N6sXQ7COajD5U8Md Bz1pks3HaA6zySRdRlOwqOrONAbXxMZBvSh7vJYvxXImpdsDcjQmuXm3avG46jWv TLgUXuprtgnl1GsOayMwXaRPp3ib/y2pk7kJWD6sz4YN/ENuIyqh45fmovJpJnM6 Fk7QMQrVjh+VCeNBSfPPTe2DIMlX9L7ZfpY9d3jHJCv1wv7fyqbnJHelEGbBhMWr d6f6g+kxcKrc+BMz6/XpBnvckVZZ9WP3Dr4DKVoblgidGYpaOWFzF3S07acReBtP HhQwCZAsab/UTd7oQWhabkOkE+lUf+CIa9UszjBwYQKBgQDkHs/5giav9swujerK q6jKmgTedVVoa8YABubXBJ19SZcFfIVu+psDFccegfD6Ak0eiT8VpGDtZVmsDiuI yI+LliZ4ISC3n1IxiEdWy6kdTEHHuhGVzMGhdpjB36rBaKQWguZPBOMTIeyb+tqn +z3Qp7tOJIQSrJOVayL94pM06wKBgQDRVVR5I7prupWP1hMAs5bZQiRD67B/xw3U dGMklm/or7ceYHtNz2Dy8qcKrJvozfyRU5iKCMvoc8PNKBGwMxhTv5y0hunxZC8W hbBbKEwLo8xOYyo8ESvTykBaIQMoAhLXc4lr7d9U5QUMYL/yTIwYjnyK1d5wu2dl dCv/N+9ZLQKBgQCdKwF9VYeUGsTImmyW4Dg2BnGuV0bV39MWN6sZn4tmQ6pyVD2W ncDpGjsLMNm3VpiNnl/BaHSDex2SJl0mK5CCypuMjr585J77k3obOcw1bFGx6ues vtr1hMFwacq64H6VJ/DHpoVQrEHZoba+n6ISPU4WY6A/QXmZK6x7IXzsqwKBgGZT s+tTj7lBiAK7vqZFI6QoNNoOyERt5VDJY/1qnGG+I2FyAFRU3ytjekw5fC0dJC1W E+bFzgdfL4OF5r+e+nFV5SBKIumg83Oq/j5RQHsgIqrexrJ+IlJxN2vXX1ebS+KN 08syiE1TdlhKowmqaYFHhZHIYefxc+WgGDG2AgYxAoGACmN1Fc/I0zVCpD9trh2S fI9hdC4kp/cDNfPaiwrcC4bjEJgwCrCpOilAaQ81oQ7Y1S1e5BSbi37x4am1HFSH QKRxcbdxtsdjF3+YxI6r3FUvqQVNflILl+XORntuEV53jMnzPsqtcIhF3yeoAxBw UuByDE2vZ2EE7Scz2CHYL0E= -----END PRIVATE KEY-----`; module.exports.validWildCardCert = `-----BEGIN CER<KEY> -----END CERTIFICATE-----`; module.exports.validCert = `-----<KEY> -----END CERTIFICATE-----`; module.exports.badCert = `-----BEGIN CERTIFICATE----- <KEY> -----END CERTIFICATE-----`; module.exports.validKey = `-----<KEY>`; module.exports.badKey = `-----<KEY>`; module.exports.validBundle = `-----<KEY> -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- <KEY>IB<KEY> -----END CERTIFICATE-----`; module.exports.validBundleCert = `-----BEGIN CERTIFICATE----- MIIF+DCCA+CgAwIBAgIJAL0zsY8OwqGiMA0GCSqGSIb3DQ<KEY> -----END CERTIFICATE-----`; module.exports.nonMatchingKey = `-----BEGIN PRIVATE KEY----- <KEY> -----END PRIVATE KEY-----`;
SeptBlast/verify-valid-ssl
<|start_filename|>awwvision/src/main/java/com/google/cloud/servicebroker/samples/awwvision/data/RedditResponse.java<|end_filename|> /* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.cloud.servicebroker.samples.awwvision.data; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * JSON class structure for Reddit API. */ @JsonIgnoreProperties(ignoreUnknown = true) public class RedditResponse { public Data data; public RedditResponse() { } public RedditResponse(Data data) { this.data = data; } @JsonIgnoreProperties(ignoreUnknown = true) public static class Data { public Listing[] children; public Data() { } public Data(Listing[] children) { this.children = children; } } @JsonIgnoreProperties(ignoreUnknown = true) public static class Listing { public ListingData data; public Listing() { } public Listing(ListingData data) { this.data = data; } } @JsonIgnoreProperties(ignoreUnknown = true) public static class ListingData { public Preview preview; public String url; public ListingData() { } public ListingData(Preview preview) { this.preview = preview; } } @JsonIgnoreProperties(ignoreUnknown = true) public static class Preview { public Image[] images; public Preview() { } public Preview(Image[] images) { this.images = images; } } @JsonIgnoreProperties(ignoreUnknown = true) public static class Image { public Source source; public String id; public Image() { } public Image(Source source, String id) { this.source = source; this.id = id; } } @JsonIgnoreProperties(ignoreUnknown = true) public static class Source { public String url; public Source() { } public Source(String url) { this.url = url; } } } <|start_filename|>link-shortener/src/main/java/com/google/cloud/servicebroker/examples/linkshortener/domain/LinkInfo.java<|end_filename|> /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.servicebroker.examples.linkshortener.domain; import com.google.cloud.servicebroker.examples.linkshortener.enums.ThreatStatus; /** * LinkInfo holds augmented data for links. */ public class LinkInfo { private boolean local; private ThreatStatus threatStatus = ThreatStatus.UNKNOWN; public boolean isLocal() { return local; } public void setLocal(boolean local) { this.local = local; } public ThreatStatus getThreatStatus() { return threatStatus; } public void setThreatStatus(ThreatStatus threatStatus) { this.threatStatus = threatStatus; } } <|start_filename|>storelocator/src/test/java/com/google/cloud/servicebroker/samples/storelocator/service/StoreServiceTest.java<|end_filename|> /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.servicebroker.samples.storelocator.service; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.when; import com.google.cloud.servicebroker.samples.storelocator.data.LocationBounds; import com.google.cloud.servicebroker.samples.storelocator.data.Store; import com.google.cloud.servicebroker.samples.storelocator.repository.StoreRepository; import com.google.cloud.spanner.Statement; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.mock.mockito.SpyBean; import org.springframework.cloud.gcp.data.spanner.core.SpannerOperations; import org.springframework.test.context.junit4.SpringRunner; import java.util.Arrays; import java.util.Collections; import java.util.List; @RunWith(SpringRunner.class) public class StoreServiceTest { private static final Store store1 = new Store(0.0, 0.0, "1", "1", null, "6:00 AM", "6:00 PM", "(555) 555-5555"); private static final Store store2 = new Store(-1.0, -1.0, "1", "1", null, "6:00 AM", "6:00 PM", "(555) 555-5555"); private static final Store store3 = new Store(1.0, 1.0, "1", "1", null, "6:00 AM", "6:00 PM", "(555) 555-5555"); private static final Store store4 = new Store(-1.0, 1.0, "1", "1", null, "6:00 AM", "6:00 PM", "(555) 555-5555"); private static final Store store5 = new Store(1.0, -1.0, "1", "1", null, "6:00 AM", "6:00 PM", "(555) 555-5555"); private static final LocationBounds query1 = new LocationBounds(-1, -1, 1, 1); private static final LocationBounds query2 = new LocationBounds(-2, -2, 2, 2); private static final Statement statement1 = Statement.newBuilder("SELECT * FROM stores WHERE" + " latitude BETWEEN @lat1 AND @lat2 AND longitude BETWEEN @lng1 AND @lng2") .bind("lat1").to(-1.0) .bind("lat2").to(1.0) .bind("lng1").to(-1.0) .bind("lng2").to(1.0) .build(); private static final Statement statement2 = Statement.newBuilder("SELECT * FROM stores WHERE" + " latitude BETWEEN @lat1 AND @lat2 AND longitude BETWEEN @lng1 AND @lng2") .bind("lat1").to(-2.0) .bind("lat2").to(2.0) .bind("lng1").to(-2.0) .bind("lng2").to(2.0) .build(); private static final List<Store> result1 = Collections.singletonList(store1); private static final List<Store> result2 = Arrays.asList(store1, store2, store3, store4, store5); @MockBean StoreRepository storeRepository; @MockBean SpannerOperations spannerOperations; @SpyBean StoreService storeService; @Test public void testBuildStatement() { assertThat(storeService.buildStatement(query1)).isEqualTo(statement1); assertThat(storeService.buildStatement(query2)).isEqualTo(statement2); } @Test public void testFindWithinBounds() { assertThat(storeRepository).isNotNull(); when(storeRepository.getSpannerTemplate()).thenReturn(spannerOperations); given(spannerOperations.query(Store.class, statement1)).willReturn(result1); assertThat(storeService.findWithinBounds(query1)).isEqualTo(result1); given(spannerOperations.query(Store.class, statement2)).willReturn(result2); assertThat(storeService.findWithinBounds(query2)).isEqualTo(result2); } } <|start_filename|>awwvision/src/main/java/com/google/cloud/servicebroker/samples/awwvision/service/ImageLabelingService.java<|end_filename|> /* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.cloud.servicebroker.samples.awwvision.service; import com.google.api.services.vision.v1.Vision; import com.google.api.services.vision.v1.model.AnnotateImageRequest; import com.google.api.services.vision.v1.model.AnnotateImageResponse; import com.google.api.services.vision.v1.model.BatchAnnotateImagesRequest; import com.google.api.services.vision.v1.model.BatchAnnotateImagesResponse; import com.google.api.services.vision.v1.model.Feature; import com.google.api.services.vision.v1.model.Image; import com.google.common.collect.ImmutableList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.IOException; /** * Component which labels images using the Google Cloud Vision API. */ @Component public class ImageLabelingService { @Autowired private Vision vision; /** * Calls the Vision API to get a single label for the given image. * * @param bytes The image, in bytes * @return The label given to the image, or null if the request could not successfully label the * image */ public String labelImage(byte[] bytes) throws IOException { AnnotateImageRequest request = new AnnotateImageRequest().setImage(new Image().encodeContent(bytes)).setFeatures( ImmutableList.of(new Feature().setType("LABEL_DETECTION").setMaxResults(1))); return sendAndParseRequest(request); } private String sendAndParseRequest(AnnotateImageRequest request) throws IOException { AnnotateImageResponse response = sendRequest(request); if (response == null) { return null; } if (response.getLabelAnnotations() == null) { throw new IOException(response.getError() != null ? response.getError().getMessage() : "Unknown error getting image annotations"); } return response.getLabelAnnotations().get(0).getDescription(); } private AnnotateImageResponse sendRequest(AnnotateImageRequest request) throws IOException { Vision.Images.Annotate annotate = vision.images() .annotate(new BatchAnnotateImagesRequest().setRequests(ImmutableList.of(request))); BatchAnnotateImagesResponse batchResponse = annotate.execute(); if (batchResponse == null || batchResponse.getResponses() == null) { return null; } return batchResponse.getResponses().get(0); } } <|start_filename|>link-shortener/src/main/java/com/google/cloud/servicebroker/examples/linkshortener/domain/Link.java<|end_filename|> /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.servicebroker.examples.linkshortener.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; /** * Link holds a stub to URL mapping. */ @Entity @Table(name = "links") public class Link { @Id @Column(name = "stub") @Pattern(regexp = "^([a-zA-Z0-9]+(-[a-zA-Z0-9+])*)$") private String stub; @Column(name = "url") @NotBlank @Size(max = 1024) private String url; public String getStub() { return stub; } public void setStub(String stub) { this.stub = stub; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } } <|start_filename|>awwvision/src/main/java/com/google/cloud/servicebroker/samples/awwvision/controller/ViewImagesController.java<|end_filename|> /* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.cloud.servicebroker.samples.awwvision.controller; import com.google.api.services.storage.model.StorageObject; import com.google.cloud.servicebroker.samples.awwvision.service.CuteImageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * Provides request mappings for viewing cute images. */ @Controller public class ViewImagesController { @Autowired private CuteImageService cuteImageService; /** * Renders the home page. * * @param model The Model object. * @return The home page view name. * @throws IOException If the StorageApi cannot list objects. */ @RequestMapping("/") public String view(Model model) throws IOException { List<StorageObject> objects = cuteImageService.listAll(); List<Image> images = new ArrayList<>(); for (StorageObject obj : objects) { Image image = new Image(getPublicUrl(cuteImageService.getBucketName(), obj.getName()), obj.getMetadata().get("label")); images.add(image); } model.addAttribute("images", images); return "index"; } /** * Renders a specifc label's page. * * @param label The label. * @param model The Model object. * @return The view to render. * @throws IOException If the StorageApi cannot list objects. */ @RequestMapping("/label/{label}") public String viewLabel(@PathVariable("label") String label, Model model) throws IOException { List<StorageObject> objects = cuteImageService.listAll(); List<Image> images = new ArrayList<>(); for (StorageObject obj : objects) { Image image = new Image(getPublicUrl(cuteImageService.getBucketName(), obj.getName()), obj.getMetadata().get("label")); if (image.label.equals(label)) { images.add(image); } } model.addAttribute("images", images); return "index"; } static String getPublicUrl(String bucket, String object) { return String.format("http://storage.googleapis.com/%s/%s", bucket, object); } static class Image { private String url; private String label; public Image(String url, String label) { this.url = url; this.label = label; } public String getUrl() { return url; } public String getLabel() { return label; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } Image image = (Image) obj; return Objects.equals(url, image.url) && Objects.equals(label, image.label); } @Override public int hashCode() { return Objects.hash(url, label); } @Override public String toString() { return "Image{" + "url='" + url + '\'' + ", label='" + label + '\'' + '}'; } } } <|start_filename|>link-shortener/src/main/java/com/google/cloud/servicebroker/examples/linkshortener/services/SafebrowsingService.java<|end_filename|> /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.servicebroker.examples.linkshortener.services; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.safebrowsing.Safebrowsing; import com.google.api.services.safebrowsing.model.ClientInfo; import com.google.api.services.safebrowsing.model.FindThreatMatchesRequest; import com.google.api.services.safebrowsing.model.FindThreatMatchesResponse; import com.google.api.services.safebrowsing.model.ThreatEntry; import com.google.api.services.safebrowsing.model.ThreatInfo; import com.google.api.services.safebrowsing.model.ThreatMatch; import com.google.cloud.servicebroker.examples.linkshortener.enums.ThreatStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; /** * SafebrowsingService provides access to the Google Safebrowsing API which is what protects Chrome * users from going to malicious sites. */ @Service public class SafebrowsingService { private static final Logger LOG = LoggerFactory.getLogger(SafebrowsingService.class); private final String googleApiKey; private final Safebrowsing client; SafebrowsingService(@Value("${google.api.key}") String googleApiKey) throws GeneralSecurityException, IOException { Objects.requireNonNull(googleApiKey); this.googleApiKey = googleApiKey; client = new Safebrowsing.Builder( GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), null).build(); } /** * Returns a threat designator for a URL. A site is malicious if the Safebrowsing API returns * threats of any type for any platform. * * <p>This is NOT CACHED because threat information is always changing. * * @param url - the URL to check * @return a ThreatStatus for the URL, UNKNOWN if an exception occurred on lookup. */ public ThreatStatus threatStatus(final String url) { Objects.requireNonNull(url); LOG.debug("Looking up safebrowsing status of {}", url); try { // We construct a ThreatInfo instance which tells the service which kind of threats we're // looking for. final ThreatInfo ti = new ThreatInfo(); ti.setThreatTypes(Arrays.asList("MALWARE", "SOCIAL_ENGINEERING", "UNWANTED_SOFTWARE", "POTENTIALLY_HARMFUL_APPLICATION")); ti.setPlatformTypes(Collections.singletonList("ANY_PLATFORM")); final FindThreatMatchesRequest request = new FindThreatMatchesRequest(); request.setClient(new ClientInfo()); request.setThreatInfo(ti); final ThreatEntry te = new ThreatEntry(); te.setUrl(url); ti.setThreatEntries(Collections.singletonList(te)); final FindThreatMatchesResponse findThreatMatchesResponse = client .threatMatches() .find(request) .setKey(googleApiKey) .execute(); final List<ThreatMatch> threatMatches = findThreatMatchesResponse.getMatches(); if (threatMatches == null || threatMatches.size() == 0) { return ThreatStatus.BENIGN; } else { return ThreatStatus.MALICIOUS; } } catch (IOException ex) { LOG.error("couldn't get safebrowsing status", ex); return ThreatStatus.UNKNOWN; } } } <|start_filename|>link-shortener/src/main/java/com/google/cloud/servicebroker/examples/linkshortener/controllers/LinkController.java<|end_filename|> /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.servicebroker.examples.linkshortener.controllers; import com.google.cloud.servicebroker.examples.linkshortener.domain.Link; import com.google.cloud.servicebroker.examples.linkshortener.domain.LinkInfo; import com.google.cloud.servicebroker.examples.linkshortener.repositories.LinkRepository; import com.google.cloud.servicebroker.examples.linkshortener.services.LinkInfoService; import com.google.cloud.servicebroker.examples.linkshortener.services.ScreenshotService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; import java.util.Optional; import javax.servlet.http.HttpServletResponse; /** * Contains controller code for the links. */ @RestController @RequestMapping(value = "/api/v1/links", produces = MediaType.APPLICATION_JSON_VALUE) public class LinkController { @Autowired private LinkRepository linkRepository; @Autowired private LinkInfoService linkInfoService; @Autowired private ScreenshotService screenshotService; /** * Gets a link by a given short name. * * @param stub The short name of the link. * @return The link of one exists with the given stub. */ @GetMapping("/{stub}") public Optional<Link> getLink(@PathVariable String stub) { return linkRepository.findById(stub); } /** * Gets augmented data for a link with the given stub. * * @param stub The short name of the link. * @return Augmented info, if the link exists. */ @GetMapping("/{stub}/info") public Optional<LinkInfo> getInfo(@PathVariable String stub) { final Optional<Link> link = getLink(stub); if (link.isPresent()) { return Optional.of(linkInfoService.getLinkInfo(link.get())); } return Optional.empty(); } /** * Gets a JPEG preview of the link. * * @param stub The link to grab. * @param response The response to write the JSON back to. * @throws IOException If the user terminated the request before it could complete. */ @GetMapping("/{stub}/preview") public void getPreview(@PathVariable String stub, HttpServletResponse response) throws IOException { final Optional<Link> link = getLink(stub); if (!link.isPresent()) { response.sendError(404, "stub not found"); return; } response.setContentType(MediaType.IMAGE_JPEG_VALUE); response.getOutputStream().write(screenshotService.getScreenshot(link.get().getUrl())); } /** * Creates a link in the repository. * * @param link The link to create. * @return The created link. */ @PostMapping("/") public Link createLink(@RequestBody Link link) { return linkRepository.save(link); } /** * Deletes a link from the repository. * * @param stub The short name of the link. */ @DeleteMapping("/{stub}") public void deleteLink(@PathVariable String stub) { linkRepository.deleteById(stub); } } <|start_filename|>storelocator/src/main/java/com/google/cloud/servicebroker/samples/storelocator/config/GoogleMapProperties.java<|end_filename|> package com.google.cloud.servicebroker.samples.storelocator.config; /** * ConfigurationProperties for rendering the Google Map. */ public class GoogleMapProperties { private double lat; private double lng; // See https://developers.google.com/maps/documentation/javascript/tutorial#zoom-levels private int zoomLevel; private String key; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public double getLat() { return lat; } public void setLat(double lat) { this.lat = lat; } public double getLng() { return lng; } public void setLng(double lng) { this.lng = lng; } public int getZoomLevel() { return zoomLevel; } public void setZoomLevel(int zoomLevel) { this.zoomLevel = zoomLevel; } } <|start_filename|>awwvision/src/main/java/com/google/cloud/servicebroker/samples/awwvision/config/VisionConfig.java<|end_filename|> /* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.cloud.servicebroker.samples.awwvision.config; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.vision.v1.Vision; import com.google.api.services.vision.v1.VisionScopes; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.util.Base64; /** * Sets up connections to client libraries and other injectable beans. */ @Configuration public class VisionConfig { @Value("${gcp-application-name}") private String applicationName; @Bean JsonFactory jsonFactory() { return JacksonFactory.getDefaultInstance(); } @Bean HttpTransport transport() throws GeneralSecurityException, IOException { return GoogleNetHttpTransport.newTrustedTransport(); } @Bean GoogleCredential credential() throws IOException { String env = System.getenv("VCAP_SERVICES"); String privateKeyData = new JSONObject(env) .getJSONArray("google-storage") .getJSONObject(0) .getJSONObject("credentials") .getString("PrivateKeyData"); InputStream stream = new ByteArrayInputStream(Base64.getDecoder().decode(privateKeyData)); return GoogleCredential.fromStream(stream); } @Bean Vision vision(HttpTransport transport, JsonFactory jsonFactory, GoogleCredential credential) { if (credential.createScopedRequired()) { credential = credential.createScoped(VisionScopes.all()); } return new Vision.Builder(transport, jsonFactory, credential) .setApplicationName(applicationName).build(); } @Bean RestTemplate restTemplate() { return new RestTemplate(); } } <|start_filename|>link-shortener/src/main/java/com/google/cloud/servicebroker/examples/linkshortener/controllers/RouteController.java<|end_filename|> /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.servicebroker.examples.linkshortener.controllers; import com.google.cloud.servicebroker.examples.linkshortener.domain.Link; import com.google.cloud.servicebroker.examples.linkshortener.domain.LinkInfo; import com.google.cloud.servicebroker.examples.linkshortener.repositories.LinkRepository; import com.google.cloud.servicebroker.examples.linkshortener.services.LinkInfoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import java.util.Optional; /** * Contains the controller code for the main HTTP handlers. */ @Controller @RequestMapping("/") public class RouteController { @Autowired private LinkRepository linkRepo; @Autowired private LinkInfoService infoService; /** * Generates a redirect or a page displaying the short-url. If the page does not exist, the user * is asked to edit it. If the page is internal, the user is redirected. If the page is external * and malicious, the page is blocked. If the page is external and benign, a warning and preview * of the page is shown before the user goes there. * * @param stub The stub the user was linked to. * @param model The model of the page the link is added to if we need to render an interstitial. * @return A redirect or template to load. */ @GetMapping("/{stub}") public String lookupSite(@PathVariable("stub") String stub, Model model) { final Optional<Link> repo = linkRepo.findById(stub); if (!repo.isPresent()) { return "redirect:/?edit=" + stub; } final LinkInfo linkInfo = infoService.getLinkInfo(repo.get()); if (linkInfo.isLocal()) { return "redirect:" + repo.get().getUrl(); } model.addAttribute("link", repo.get()); switch (linkInfo.getThreatStatus()) { case MALICIOUS: return "blocked"; case BENIGN: return "block-external"; default: return "scanner-down"; } } /** * Get the index page for describing what the site is and how to create a new URL. * * @return the index page template name. */ @GetMapping("/") public String index() { return "index"; } } <|start_filename|>link-shortener/src/main/java/com/google/cloud/servicebroker/examples/linkshortener/services/ScreenshotService.java<|end_filename|> /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.servicebroker.examples.linkshortener.services; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.pagespeedonline.Pagespeedonline; import com.google.api.services.pagespeedonline.Pagespeedonline.Pagespeedapi.Runpagespeed; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Collections; import java.util.Objects; /** * ScreenshotServices uses Google's Pagespeed API to get a JPEG of a page. */ @Service public class ScreenshotService { private static final Logger LOG = LoggerFactory.getLogger(ScreenshotService.class); private final String googleApiKey; private final Pagespeedonline client; ScreenshotService(@Value("${google.api.key}") String googleApiKey) throws GeneralSecurityException, IOException { Objects.requireNonNull(googleApiKey); this.googleApiKey = googleApiKey; client = new Pagespeedonline.Builder( GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), null) .build(); } /** * Creates and caches a JPEG screenshot of a given URL. * @param url the URL. * @return A JPEG screenshot byte array. */ @Cacheable("screenshot-service") public byte[] getScreenshot(String url) { try { final Runpagespeed request = client.pagespeedapi().runpagespeed(url); request.setScreenshot(true); request.setRule(Collections.singletonList("MinifyHTML")); return request.execute().getScreenshot().decodeData(); } catch (IOException ex) { LOG.error("Couldn't get screenshot", ex); return new byte[]{}; } } } <|start_filename|>awwvision/src/test/java/com/google/cloud/servicebroker/samples/awwvision/controller/RedditScraperControllerTest.java<|end_filename|> /* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.cloud.servicebroker.samples.awwvision.controller; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.services.vision.v1.Vision; import com.google.api.services.vision.v1.model.AnnotateImageResponse; import com.google.api.services.vision.v1.model.BatchAnnotateImagesRequest; import com.google.api.services.vision.v1.model.BatchAnnotateImagesResponse; import com.google.api.services.vision.v1.model.EntityAnnotation; import com.google.cloud.servicebroker.samples.awwvision.data.RedditResponse; import com.google.cloud.servicebroker.samples.awwvision.data.RedditResponse.Data; import com.google.cloud.servicebroker.samples.awwvision.data.RedditResponse.Image; import com.google.cloud.servicebroker.samples.awwvision.data.RedditResponse.Listing; import com.google.cloud.servicebroker.samples.awwvision.data.RedditResponse.ListingData; import com.google.cloud.servicebroker.samples.awwvision.data.RedditResponse.Preview; import com.google.cloud.servicebroker.samples.awwvision.data.RedditResponse.Source; import com.google.cloud.servicebroker.samples.awwvision.service.CuteImageService; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.mock.mockito.SpyBean; import org.springframework.test.context.junit4.SpringRunner; import java.net.URL; @RunWith(SpringRunner.class) @AutoConfigureMockMvc @SpringBootTest(properties = {"gcp-storage-bucket=fake-bucket"}) public class RedditScraperControllerTest { @MockBean Vision vision; @MockBean CuteImageService cuteImageService; // Even though this is not used directly in the test, mock it out so the application doesn't try // to read environment variables to set the credential. @MockBean GoogleCredential googleCredential; @SpyBean RedditScraperController scraper; @Before public void setup() throws Exception { // Have the Vision API return "dog" for any request. Vision.Images images = Mockito.mock(Vision.Images.class); Vision.Images.Annotate annotate = Mockito.mock(Vision.Images.Annotate.class); when(vision.images()).thenReturn(images); when(images.annotate(ArgumentMatchers.any(BatchAnnotateImagesRequest.class))).thenReturn(annotate); when(annotate.execute()).thenReturn( new BatchAnnotateImagesResponse().setResponses(ImmutableList.of(new AnnotateImageResponse() .setLabelAnnotations(ImmutableList.of(new EntityAnnotation().setDescription("dog")))))); doReturn("".getBytes()).when(scraper).download(ArgumentMatchers.any(URL.class)); } @Test public void testScrape() throws Exception { Image img1 = new Image(new Source("http://url1.com"), "img1"); Image img2 = new Image(new Source("http://url2.com"), "img2"); RedditResponse redditResponse = new RedditResponse(new Data( new Listing[]{new Listing(new ListingData(new Preview(new Image[]{img1, img2})))})); redditResponse.data.children[0].data.url = "http://listing-url.com"; scraper.storeAndLabel(redditResponse); verify(cuteImageService).uploadJpeg("http://listing-url.com", new URL("http://listing-url.com"), ImmutableMap.of("label", "dog")); verify(cuteImageService).uploadJpeg("http://listing-url.com", new URL("http://listing-url.com"), ImmutableMap.of("label", "dog")); } } <|start_filename|>storelocator/src/main/java/com/google/cloud/servicebroker/samples/storelocator/service/StoreService.java<|end_filename|> /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.servicebroker.samples.storelocator.service; import static com.google.cloud.servicebroker.samples.storelocator.data.Store.TABLE_NAME; import static java.util.Objects.requireNonNull; import com.google.cloud.servicebroker.samples.storelocator.data.LocationBounds; import com.google.cloud.servicebroker.samples.storelocator.data.Store; import com.google.cloud.servicebroker.samples.storelocator.repository.StoreRepository; import com.google.cloud.spanner.Statement; import org.springframework.stereotype.Component; import java.util.List; @Component public class StoreService { private final StoreRepository storeRepository; public StoreService(StoreRepository storeRepository) { this.storeRepository = requireNonNull(storeRepository, "storeRepository"); } /** * Builds the {@link Statement} for performing a findWithinBounds query. * * @param bounds The bounds for the query. * @return A Spanner {@link Statement} for the query. */ Statement buildStatement(LocationBounds bounds) { return Statement .newBuilder("SELECT * FROM " + TABLE_NAME + " WHERE latitude BETWEEN @lat1 AND @lat2 AND longitude BETWEEN @lng1 AND @lng2") .bind("lat1").to(bounds.getLat1()) .bind("lat2").to(bounds.getLat2()) .bind("lng1").to(bounds.getLng1()) .bind("lng2").to(bounds.getLng2()) .build(); } public List<Store> findWithinBounds(LocationBounds bounds) { return storeRepository.getSpannerTemplate().query(Store.class, buildStatement(bounds)); } } <|start_filename|>awwvision/src/test/java/com/google/cloud/servicebroker/samples/awwvision/controller/ViewImagesControllerTest.java<|end_filename|> /* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.cloud.servicebroker.samples.awwvision.controller; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.empty; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.services.storage.Storage; import com.google.api.services.storage.model.StorageObject; import com.google.cloud.servicebroker.samples.awwvision.service.CuteImageService; import com.google.cloud.servicebroker.samples.awwvision.controller.ViewImagesController.Image; import com.google.common.collect.ImmutableMap; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import java.util.Arrays; @RunWith(SpringRunner.class) @AutoConfigureMockMvc @SpringBootTest(properties = {"gcp-storage-bucket=fake-bucket"}) public class ViewImagesControllerTest { @MockBean Storage storageService; // Even though this is not used directly in the test, mock it out so the application doesn't try // to read environment variables to set the credential. @MockBean GoogleCredential googleCredential; @MockBean CuteImageService cuteImageService; @Autowired private MockMvc mvc; private static final String BUCKET = "fake-bucket"; @Before public void setup() throws Exception { StorageObject obj1 = new StorageObject().setName("obj1").setMetadata(ImmutableMap.of("label", "dog")); StorageObject obj2 = new StorageObject().setName("obj2").setMetadata(ImmutableMap.of("label", "cat")); when(cuteImageService.listAll()).thenReturn(Arrays.asList(obj1, obj2)); when(cuteImageService.getBucketName()).thenReturn(BUCKET); } @Test public void testView() throws Exception { Image img1 = new Image(ViewImagesController.getPublicUrl(BUCKET, "obj1"), "dog"); Image img2 = new Image(ViewImagesController.getPublicUrl(BUCKET, "obj2"), "cat"); mvc.perform(get("/")).andExpect(model().attribute("images", containsInAnyOrder(img1, img2))); } @Test public void testViewLabel() throws Exception { Image dog = new Image(ViewImagesController.getPublicUrl(BUCKET, "obj1"), "dog"); mvc.perform(get("/label/dog")).andExpect(model().attribute("images", contains(dog))); } @Test public void testViewLabelEmpty() throws Exception { mvc.perform(get("/label/octopus")).andExpect(model().attribute("images", empty())); } } <|start_filename|>storelocator/src/test/java/com/google/cloud/servicebroker/samples/storelocator/data/StoreTest.java<|end_filename|> /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.servicebroker.samples.storelocator.data; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.json.JsonTest; import org.springframework.boot.test.json.JacksonTester; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @JsonTest public class StoreTest { @Autowired private JacksonTester<Store> json; private final Store jsonObject = new Store(123.4, -30.35, "store-name", "store-address", null, "open", "close", "num"); private final String jsonString = "{\"name\":\"store-name\",\"address\":\"store-address\"," + "\"latitude\":123.4,\"longitude\":-30.35,\"website\":null," + "\"openingTime\":\"open\",\"closingTime\":\"close\",\"phoneNumber\":\"num\"}"; @Test public void testSerialize() throws Exception { assertThat(this.json.write(this.jsonObject)).isEqualToJson(jsonString); } @Test public void testDeserialize() throws Exception { // Also tests equals method assertThat(this.json.parse(this.jsonString)).isEqualTo(jsonObject); } } <|start_filename|>storelocator/src/main/java/com/google/cloud/servicebroker/samples/storelocator/data/LocationBounds.java<|end_filename|> /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.servicebroker.samples.storelocator.data; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; /** * Two-dimensional bounding box for finding locations on a geographic coordinate system. */ public class LocationBounds { private final double lat1; private final double lng1; private final double lat2; private final double lng2; /** * Creates a LocationBox given two coordinate pairs. * * <p>The smaller latitude and longitude values will always be assigned to lat1 and lng1 * respectively. * * @param lat1 latitude of first coordinate pair. * @param lng1 longitude of first coordinate pair. * @param lat2 latitude of second coordinate pair. * @param lng2 longitude of second coordinate pair. */ @JsonCreator public LocationBounds( @JsonProperty("lat1") double lat1, @JsonProperty("lng1") double lng1, @JsonProperty("lat2") double lat2, @JsonProperty("lng2") double lng2) { this.lat1 = Math.min(lat1, lat2); this.lng1 = Math.min(lng1, lng2); this.lat2 = Math.max(lat1, lat2); this.lng2 = Math.max(lng1, lng2); } public double getLat1() { return lat1; } public double getLng1() { return lng1; } public double getLat2() { return lat2; } public double getLng2() { return lng2; } @Override public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } } <|start_filename|>storelocator/src/test/java/com/google/cloud/servicebroker/samples/storelocator/web/StoreControllerTest.java<|end_filename|> /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.servicebroker.samples.storelocator.web; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.google.api.gax.core.CredentialsProvider; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.servicebroker.samples.storelocator.data.LocationBounds; import com.google.cloud.servicebroker.samples.storelocator.data.Store; import com.google.cloud.servicebroker.samples.storelocator.service.StoreService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.mock.mockito.SpyBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; import java.util.Arrays; import java.util.Collections; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class StoreControllerTest { private static final Store store1 = new Store(0.0, 0.0, "1", "1", null, "6:00 AM", "6:00 PM", "(555) 555-5555"); private static final Store store2 = new Store(-1.0, -1.0, "1", "1", null, "6:00 AM", "6:00 PM", "(555) 555-5555"); private static final Store store3 = new Store(1.0, 1.0, "1", "1", null, "6:00 AM", "6:00 PM", "(555) 555-5555"); private static final Store store4 = new Store(-1.0, 1.0, "1", "1", null, "6:00 AM", "6:00 PM", "(555) 555-5555"); private static final Store store5 = new Store(1.0, -1.0, "1", "1", null, "6:00 AM", "6:00 PM", "(555) 555-5555"); private static final LocationBounds query1 = new LocationBounds(-1, -1, 1, 1); private static final LocationBounds query2 = new LocationBounds(-2, -2, 2, 2); private static final List<Store> result1 = Collections.singletonList(store1); private static final List<Store> result2 = Arrays.asList(store1, store2, store3, store4, store5); @Autowired MockMvc mockMvc; @MockBean StoreService storeService; // Creates a real instance even though we don't perform any spying. @SpyBean StoreController storeController; @MockBean GoogleCredentials googleCredentials; @Test public void testFindWithinBounds_1() throws Exception { when(storeService.findWithinBounds(query1)).thenReturn(result1); mockMvc.perform(get("/api/v1/stores") .content(MediaType.ALL_VALUE) .param("lat1", Double.toString(query1.getLat1())) .param("lng1", Double.toString(query1.getLng1())) .param("lat2", Double.toString(query1.getLat2())) .param("lng2", Double.toString(query1.getLng2())) ) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().json( "[{\"name\":\"1\",\"address\":\"1\",\"latitude\":0.0,\"longitude\":0.0}]")); ; } @Test public void testFindWithinBounds_2() throws Exception { when(storeService.findWithinBounds(query2)).thenReturn(result2); mockMvc.perform(get("/api/v1/stores") .content(MediaType.ALL_VALUE) .param("lat1", Double.toString(query2.getLat1())) .param("lng1", Double.toString(query2.getLng1())) .param("lat2", Double.toString(query2.getLat2())) .param("lng2", Double.toString(query2.getLng2())) ) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().json( "[{\"name\":\"1\",\"address\":\"1\",\"latitude\":0.0,\"longitude\":0.0}," + "{\"name\":\"1\",\"address\":\"1\",\"latitude\":-1.0,\"longitude\":-1.0}," + "{\"name\":\"1\",\"address\":\"1\",\"latitude\":1.0,\"longitude\":1.0}," + "{\"name\":\"1\",\"address\":\"1\",\"latitude\":-1.0,\"longitude\":1.0}," + "{\"name\":\"1\",\"address\":\"1\",\"latitude\":1.0,\"longitude\":-1.0}]")); ; } @Configuration static class Config { /** * Creates a CredentialsProvider using a mock credentials bean. * * <p>This allows the context to load. * * @param credentials mock credentials * @return a CredentialsProvider for the mock credentials. */ @Bean public CredentialsProvider spannerCredentialsProvider(GoogleCredentials credentials) { return () -> credentials; } /** * Creates a RequestMappingHandlerAdapter which supports JSON * * <p>When using AutoConfigureMockMvc, a reflective instance of a RequestMappingHandlerAdapter * is instantiated. This means it will only be configured to use its default message converters, * which do not support JSON. * * <p>This is contrary to an actual launch of the application. * Normally, the WebMvcConfigurationSupport's RequestMappingHandlerAdapter bean is used, which * support JSON. * * @return a RequestMappingHandlerAdapter which supports JSON. */ @Bean public RequestMappingHandlerAdapter requestMappingHandlerAdapter() { return new WebMvcConfigurationSupport().requestMappingHandlerAdapter(); } } } <|start_filename|>storelocator/src/main/java/com/google/cloud/servicebroker/samples/storelocator/config/StoreLocatorProperties.java<|end_filename|> /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.servicebroker.samples.storelocator.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; /** * Configuration for the store locator application. */ @Configuration @EnableConfigurationProperties @ConfigurationProperties(prefix = "store-locator") public class StoreLocatorProperties { private GoogleMapProperties googleMap; private boolean testDataEnabled; private int databaseInitTimeoutSeconds = 120; public GoogleMapProperties getGoogleMap() { return googleMap; } public void setGoogleMap(GoogleMapProperties googleMap) { this.googleMap = googleMap; } public boolean isTestDataEnabled() { return testDataEnabled; } public void setTestDataEnabled(boolean testDataEnabled) { this.testDataEnabled = testDataEnabled; } public int getDatabaseInitTimeoutSeconds() { return databaseInitTimeoutSeconds; } public void setDatabaseInitTimeoutSeconds(int databaseInitTimeoutSeconds) { this.databaseInitTimeoutSeconds = databaseInitTimeoutSeconds; } } <|start_filename|>awwvision/src/main/java/com/google/cloud/servicebroker/samples/awwvision/controller/RedditScraperController.java<|end_filename|> /* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.cloud.servicebroker.samples.awwvision.controller; import com.google.api.services.storage.model.StorageObject; import com.google.cloud.servicebroker.samples.awwvision.data.RedditResponse; import com.google.cloud.servicebroker.samples.awwvision.data.RedditResponse.Listing; import com.google.cloud.servicebroker.samples.awwvision.service.CuteImageService; import com.google.cloud.servicebroker.samples.awwvision.service.ImageLabelingService; import com.google.common.collect.ImmutableMap; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.net.URL; import java.util.Objects; /** * Provides a request mapping for scraping images from reddit, labeling them with the Vision API, * and storing them in Cloud Storage. */ @Controller public class RedditScraperController { private static final String REDDIT_URL = "https://www.reddit.com/r/aww/hot.json"; @Autowired private ImageLabelingService imageLabelingService; @Autowired private CuteImageService cuteImageService; private final Log logger = LogFactory.getLog(getClass()); @Value("${reddit-user-agent}") private String redditUserAgent; /** * Scrapes https://reddit.com/r/aww for cute pictures are stores them in a Storage bucket. * * @param restTemplate The RestTemplate. * @return The view to render. */ @RequestMapping("/reddit") public String getRedditUrls(RestTemplate restTemplate) { HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.USER_AGENT, redditUserAgent); RedditResponse response = restTemplate .exchange(REDDIT_URL, HttpMethod.GET, new HttpEntity<String>(headers), RedditResponse.class) .getBody(); storeAndLabel(response); return "reddit"; } void storeAndLabel(RedditResponse response) { for (Listing listing : response.data.children) { storeAndLabel(listing); // functional support? } } private void storeAndLabel(final Listing listing) { Objects.requireNonNull(listing, "listing must not be null"); if (listing.data.preview == null) { // is this a bug that should be listing.data.url? return; } final String dataUrl = listing.data.url; try { // Only label and upload the image if it does not already exist in storage. final StorageObject existing = cuteImageService.get(dataUrl); if (existing != null) { return; } final URL url = new URL(dataUrl); final byte[] raw = download(url); final String label = imageLabelingService.labelImage(raw); if (label != null) { cuteImageService.uploadJpeg(dataUrl, url, ImmutableMap.of("label", label)); } } catch (IOException ex) { logger.error("Issue with labeling or uploading image " + dataUrl, ex); } } byte[] download(URL url) throws IOException { return IOUtils.toByteArray(url.openStream()); } } <|start_filename|>storelocator/src/main/java/com/google/cloud/servicebroker/samples/storelocator/web/StoreController.java<|end_filename|> /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.servicebroker.samples.storelocator.web; import static java.util.Objects.requireNonNull; import com.google.cloud.servicebroker.samples.storelocator.data.LocationBounds; import com.google.cloud.servicebroker.samples.storelocator.data.Store; import com.google.cloud.servicebroker.samples.storelocator.service.StoreService; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * Provides a REST API for querying {@link Store} objects on a geographic coordinate system. */ @RestController @RequestMapping("/api/v1/stores") public class StoreController { private final StoreService storeService; public StoreController(StoreService storeService) { this.storeService = requireNonNull(storeService, "storeService"); } /** * Retrieves {@link Store} objects given a {@link LocationBounds}. * * @param bounds The bounding box to search for locations. * @return a {@link List} of locations inside the given bounding box. */ @GetMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public List<Store> locations(LocationBounds bounds) { return storeService.findWithinBounds(bounds); } } <|start_filename|>link-shortener/src/main/resources/templates/block-external.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <title>Going to the public Internet</title> <link rel="stylesheet" href="/webjars/bootstrap/dist/css/bootstrap.min.css"/> </head> <body class="container bg-info"> <br/> <br/> <div class="card"> <div class="card-body"> <h5 class="card-title">Leaving to the Internet</h5> <p class="card-text">This link leaves your organization and goes to a public Internet site.</p> <img th:src="@{${'/api/v1/links/' + link.stub + '/preview'}}" class="mx-auto d-block img-thumbnail"/> <a th:href="${link.url}" th:text="${link.url}" target="_blank" class="btn btn-primary"></a> </div> </div> </body> </html> <|start_filename|>storelocator/src/main/java/com/google/cloud/servicebroker/samples/storelocator/data/Store.java<|end_filename|> /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.servicebroker.samples.storelocator.data; import static com.google.cloud.servicebroker.samples.storelocator.data.Store.TABLE_NAME; import static java.util.Objects.requireNonNull; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.springframework.cloud.gcp.data.spanner.core.mapping.Column; import org.springframework.cloud.gcp.data.spanner.core.mapping.PrimaryKey; import org.springframework.cloud.gcp.data.spanner.core.mapping.Table; import java.net.URL; import java.util.Optional; /** * An entity object representing a simplified store location. * * <p>This object was heavily inspired by the Google Maps API Places resource. * See https://developers.google.com/maps/documentation/javascript/reference/places-service#PlaceResult * * <p>Only the latitude and longitude are used as the primary key. * This makes it trivial to create search queries using a coordinate bounding box. * * <p>For real use, this entity should be updated or replaced with a better defined and stronger * typed model. Many of the fields have been simplified for demonstration purposes. For example, the * openingTime and closingTime fields are a gross approximation of the model required to accurately * portray a business location's hour of operations. Many of the fields are simply typed to String, * such as phoneNumber. This is again for the simplicity of demonstration. * * @see LocationBounds */ @Table(name = TABLE_NAME) public class Store { public static final String TABLE_NAME = "stores"; @Column(name = "latitude") @PrimaryKey private final Double latitude; @Column(name = "longitude") @PrimaryKey(keyOrder = 2) private final Double longitude; @Column(name = "name") private final String name; @Column(name = "address") private final String address; @Column(name = "website") private final URL website; @Column(name = "openingTime") private final String openingTime; @Column(name = "closingTime") private final String closingTime; @Column(name = "phoneNumber") private final String phoneNumber; /** * Creates a Store. * * @param latitude the store's latitude. * @param longitude the store's longitude. * @param name the name of the store. Can be null. * @param address the address of the store. Can be null. * @param website The website URL of the store. Can be null. * @param openingTime The opening time of the store. Can be null. * @param closingTime The closing time of the store. Can be null. * @param phoneNumber The store's phone number. Can be null. */ @JsonCreator public Store( @JsonProperty("latitude") Double latitude, @JsonProperty("longitude") Double longitude, @JsonProperty("name") String name, @JsonProperty("address") String address, @JsonProperty("website") URL website, @JsonProperty("openingTime") String openingTime, @JsonProperty("closingTime") String closingTime, @JsonProperty("phoneNumber") String phoneNumber) { this.latitude = requireNonNull(latitude, "latitude"); this.longitude = requireNonNull(longitude, "longitude"); this.name = name; this.address = address; this.website = website; this.openingTime = openingTime; this.closingTime = closingTime; this.phoneNumber = phoneNumber; } public Double getLatitude() { return latitude; } public Double getLongitude() { return longitude; } public Optional<String> getName() { return Optional.ofNullable(name); } public Optional<String> getAddress() { return Optional.ofNullable(address); } public Optional<URL> getWebsite() { return Optional.ofNullable(website); } public Optional<String> getOpeningTime() { return Optional.ofNullable(openingTime); } public Optional<String> getClosingTime() { return Optional.ofNullable(closingTime); } public Optional<String> getPhoneNumber() { return Optional.ofNullable(phoneNumber); } @Override public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } } <|start_filename|>awwvision/src/main/java/com/google/cloud/servicebroker/samples/awwvision/VisionDemoApplication.java<|end_filename|> /* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.cloud.servicebroker.samples.awwvision; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Spring Boot Application that scrapes + classifies images from Reddit, and stores + loads them * from Google Cloud Storage. */ @SpringBootApplication public class VisionDemoApplication { public static void main(String[] args) { SpringApplication.run(VisionDemoApplication.class, args); } } <|start_filename|>link-shortener/src/main/java/com/google/cloud/servicebroker/examples/linkshortener/services/LinkInfoService.java<|end_filename|> /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.servicebroker.examples.linkshortener.services; import com.google.cloud.servicebroker.examples.linkshortener.domain.Link; import com.google.cloud.servicebroker.examples.linkshortener.domain.LinkInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.net.MalformedURLException; import java.net.URL; import java.util.Objects; /** * LinkInfoService gets basic information about a URL. */ @Service public class LinkInfoService { private static final Logger LOG = LoggerFactory.getLogger(LinkInfoService.class); @Value("${shortener.internal.domain}") private String allowedUrlSuffix; @Autowired private SafebrowsingService safebrowsingService; /** * Get information about the given link. * * @param link the link to get information for * @return data to augment the link, if the link is not local. */ public LinkInfo getLinkInfo(final Link link) { Objects.requireNonNull(link); final String url = link.getUrl(); final LinkInfo output = new LinkInfo(); output.setLocal(isLocal(url)); if (!output.isLocal()) { output.setThreatStatus(safebrowsingService.threatStatus(url)); } return output; } /** * isLocal determines if the given URL is local to the domain (ends with allowedUrlSuffix). * * @param url the URL to check. * @return true if the url ends with allowedUrlSuffix, false if the URL is bad or does not. */ private boolean isLocal(final String url) { Objects.requireNonNull(url); try { return new URL(url) .getHost() .endsWith(allowedUrlSuffix); } catch (MalformedURLException ex) { LOG.error("couldn't parse URL", ex); return false; // return false for safety } } } <|start_filename|>storelocator/src/main/java/com/google/cloud/servicebroker/samples/storelocator/web/MapController.java<|end_filename|> /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.servicebroker.samples.storelocator.web; import org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; /** * Provides a templated landing page for the store locator application. * * <p>HTML resources are Thymeleaf templates, relying on the {@link ThymeleafAutoConfiguration}. */ @Controller public class MapController { /** * Returns the index page, templated with Thymeleaf. * * @return the index page. */ @GetMapping(value = "/", produces = MediaType.TEXT_HTML_VALUE) public String index() { return "index"; } } <|start_filename|>storelocator/src/main/resources/static/js/main.js<|end_filename|> /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; let map; let placesService; let search; const resultsList = new Vue({ el: '#results-list', data: { items: [], markers: [], selected: -1, }, methods: { highlight: function (i) { selectLocation(i); }, }, }); const markerIcon = { url: '/pin.png', scaledSize: {width: 18, height: 28}, origin: {x: 0, y: 0}, anchor: {x: 9, y: 28}, }; // Callback function for the Google Maps script. function initMap() { // Attempt to get the user's location. if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function (position) { state.map.lat = position.coords.latitude; state.map.lng = position.coords.longitude; }); } map = new google.maps.Map(document.getElementById('map'), { center: {lat: state.map.lat, lng: state.map.lng}, zoom: state.map.zoomLevel, }); placesService = new google.maps.places.PlacesService(map); google.maps.event.addListener(map, 'bounds_changed', function () { getLocations(map.getBounds()) }); } // Calls the backend for location objects. function getLocations(bounds) { const url = "/api/v1/stores?lat1=" + bounds.getNorthEast().lat() + "&lat2=" + bounds.getSouthWest().lat() + "&lng1=" + bounds.getNorthEast().lng() + "&lng2=" + bounds.getSouthWest().lng(); // Query the backend to refresh results. $.getJSON(url, updateView); } // Updates the Vue data function updateView(results) { // Find which location is selected let selectedName; if (resultsList.selected !== -1 && resultsList.items.length > resultsList.selected) { selectedName = resultsList.items[resultsList.selected].name } else { selectedName = null; resultsList.selected = -1; } // If the location still exists, keep it selected for (let i = 0; i < results.length; i++) { if (selectedName === results[i].name) { resultsList.selected = i; break; } } const names = []; const newNames = []; for (let i = 0; i < resultsList.items.length; i++) { names[i] = resultsList.items[i].name; } // Update markers for (let i = 0; i < results.length; i++) { newNames.push(results[i].name); if (names.includes(results[i].name)) { continue; } // Add a marker const marker = new google.maps.Marker({ position: { lat: results[i].latitude, lng: results[i].longitude }, map: map, icon: markerIcon, }); marker.addListener('click', function () { selectLocation(i); }); resultsList.markers.push(marker); } for (let i = 0; i < resultsList.items.length; i++) { if (!newNames.includes(resultsList.items[i].name)) { resultsList.markers[i].setMap(null); } } for (let i = 0; i < resultsList.markers.length; i++) { let icon; if (i === resultsList.selected) { icon = null; } else { icon = markerIcon; } resultsList.markers[i].setIcon(icon); } resultsList.items = results; } function selectLocation(index) { resultsList.selected = index; updateView(resultsList.items); } <|start_filename|>storelocator/src/test/java/com/google/cloud/servicebroker/samples/storelocator/data/LocationBoundsTest.java<|end_filename|> /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.servicebroker.samples.storelocator.data; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.json.JsonTest; import org.springframework.boot.test.json.JacksonTester; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @JsonTest public class LocationBoundsTest { @Autowired private JacksonTester<LocationBounds> json; private final LocationBounds jsonObject = new LocationBounds(99.9, 88.8, 123.4, -30.35); // lng1 and lng2 flipped because the first coordinate pair is always the lesser one. private final String jsonString = "{\"lat1\":99.9,\"lng1\":-30.35,\"lat2\":123.4,\"lng2\":88.8}"; @Test public void testSerialize() throws Exception { assertThat(this.json.write(this.jsonObject)).isEqualToJson(jsonString); } @Test public void testDeserialize() throws Exception { // Also tests equals method assertThat(this.json.parse(this.jsonString)).isEqualTo(jsonObject); } } <|start_filename|>link-shortener/src/main/resources/templates/blocked.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <title>Link Blocked</title> <link rel="stylesheet" href="/webjars/bootstrap/dist/css/bootstrap.min.css"/> </head> <body class="container bg-dark"> <br/> <br/> <div class="card"> <div class="card-body bg-danger text-white"> <h5 class="card-title">Blocked</h5> <p class="card-text">The site this shortened url goes to is blocked for hosting malicious content.</p> <a th:href="@{/(edit,${link.stub})}" class="btn btn-light">Edit "<span th:text="${link.stub}"></span>"</a> </div> </div> </body> </html> <|start_filename|>storelocator/src/main/java/com/google/cloud/servicebroker/samples/storelocator/DatabaseInitializer.java<|end_filename|> /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.servicebroker.samples.storelocator; import static java.util.Objects.requireNonNull; import com.google.cloud.servicebroker.samples.storelocator.config.StoreLocatorProperties; import com.google.cloud.servicebroker.samples.storelocator.data.Store; import com.google.cloud.servicebroker.samples.storelocator.repository.StoreRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.cloud.gcp.data.spanner.core.admin.SpannerDatabaseAdminTemplate; import org.springframework.cloud.gcp.data.spanner.core.admin.SpannerSchemaUtils; import org.springframework.stereotype.Component; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Stream; /** * CommandLineRunner which creates the backing database and tables on startup. */ @Component public class DatabaseInitializer implements ApplicationRunner { private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseInitializer.class); private final SpannerSchemaUtils spannerSchemaUtils; private final SpannerDatabaseAdminTemplate spannerDatabaseAdminTemplate; private final StoreRepository storeRepository; private final StoreLocatorProperties storeLocatorProperties; DatabaseInitializer( SpannerSchemaUtils spannerSchemaUtils, SpannerDatabaseAdminTemplate spannerDatabaseAdminTemplate, StoreRepository storeRepository, StoreLocatorProperties storeLocatorProperties) { this.spannerSchemaUtils = requireNonNull(spannerSchemaUtils, "spannerSchemaUtils"); this.spannerDatabaseAdminTemplate = requireNonNull(spannerDatabaseAdminTemplate, "spannerDatabaseAdminTemplate"); this.storeRepository = requireNonNull(storeRepository, "storeRepository"); this.storeLocatorProperties = requireNonNull(storeLocatorProperties, "storeLocatorProperties"); } @Override public void run(ApplicationArguments arguments) { initializeDatabaseWithTimeout(); } private void initializeDatabaseWithTimeout() { LOGGER.info("Checking if Spanner tables exist..."); // In rare cases, Spanner operations will always fail with retryable error codes. // This can cause the Spring application to hang indefinitely. // An ExecutorService here gives more assurance that the app will gracefully fail on error. final ExecutorService executor = Executors.newCachedThreadPool(); final Future future = executor.submit(() -> { try { initializeDatabase(); } catch (MalformedURLException ex) { throw new RuntimeException("Test data included a malformed URL", ex); } }); try { future.get(storeLocatorProperties.getDatabaseInitTimeoutSeconds(), TimeUnit.SECONDS); } catch (TimeoutException ex) { LOGGER.error("Timeout initializing Spanner tables. Assuming they are unreachable."); LOGGER.error("Increase log level to check if retryable errors are incurring indefinitely."); throw new RuntimeException("Exception while initializing Spanner tables", ex); } catch (InterruptedException ignored) { // Ignore. Assume the application is already shutting down. } catch (ExecutionException ex) { throw new RuntimeException("Exception while initializing Spanner tables", ex); } finally { future.cancel(true); } LOGGER.info("Finished, Spanner tables exist."); } private void initializeDatabase() throws MalformedURLException { if (!spannerDatabaseAdminTemplate.tableExists(Store.TABLE_NAME)) { LOGGER.info("Creating database:table " + spannerDatabaseAdminTemplate.getDatabase() + ":" + Store.TABLE_NAME); spannerDatabaseAdminTemplate.executeDdlStrings( Collections.singletonList( spannerSchemaUtils.getCreateTableDDLString(Store.class)), true); if (storeLocatorProperties.isTestDataEnabled()) { addTestData(); } } } private void addTestData() throws MalformedURLException { LOGGER.info("Adding test data"); Stream.of( new Store(47.6419389, -122.3479717, "Matt's cool shop", "123 cool street drive", new URL("https://www.google.com"), "6:00 AM", "5:30 PM", "(555) - 555 - 5555)"), new Store(47.6519389, -122.5479717, "Super Sweet Cafe", "1826 SW green ave", new URL("https://www.google.com"), "8:00 AM", "8:00 PM", "(555) - 555 - 5555"), new Store(47.647011, -122.3450999, "A Google building", "192 West Google Drive", new URL("https://www.google.com"), "8:00 AM", "8:00 PM", "(555) - 555 - 5555") ).forEach(storeRepository::save); } }
isabella232/service-broker-samples
<|start_filename|>vocabulary_test.go<|end_filename|> package vocabulary_test import ( "testing" "reflect" "github.com/karan/vocabulary" e "github.com/karan/vocabulary/examples" ) // ----------------------------------------------------------------------------- func TestMeanings(t *testing.T) { c := &vocabulary.Config{BigHugeLabsApiKey: "", WordnikApiKey: ""} v, err := vocabulary.New(c) if err != nil { t.Errorf("Test failed: %s", err) } expected := []string{"A plastic blowing horn, typically 65 cm long, that produces a loud and monotone note."} actual, _ := v.Meanings("vuvuzela") if !reflect.DeepEqual(expected, actual) { t.Errorf("Test failed, expected: '%s', got: '%s'", expected, actual) } } func TestMeaningsInvalidWord(t *testing.T) { c := &vocabulary.Config{BigHugeLabsApiKey: "", WordnikApiKey: ""} v, err := vocabulary.New(c) if err != nil { t.Errorf("Test failed: %s", err) } expected := []string{} actual, _ := v.Meanings("asfbhsdjfhdsj") if !reflect.DeepEqual(expected, actual) { t.Errorf("Test failed, expected: '%s', got: '%s'", expected, actual) } } // ----------------------------------------------------------------------------- func TestSynonyms(t *testing.T) { c := &vocabulary.Config{BigHugeLabsApiKey: "", WordnikApiKey: ""} v, err := vocabulary.New(c) if err != nil { t.Errorf("Test failed: %s", err) } expected := []string{"lepatata"} actual, _ := v.Synonyms("vuvuzela") if !reflect.DeepEqual(expected, actual) { t.Errorf("Test failed, expected: '%s', got: '%s'", expected, actual) } } func TestSynonymsInvalidWord(t *testing.T) { c := &vocabulary.Config{BigHugeLabsApiKey: "", WordnikApiKey: ""} v, err := vocabulary.New(c) if err != nil { t.Errorf("Test failed: %s", err) } expected := []string{} actual, _ := v.Synonyms("asfbhsdjfhdsj") if !reflect.DeepEqual(expected, actual) { t.Errorf("Test failed, expected: '%s', got: '%s'", expected, actual) } } // ----------------------------------------------------------------------------- func TestAntonyms(t *testing.T) { c := &vocabulary.Config{BigHugeLabsApiKey: e.BigHugeLabsApiKey, WordnikApiKey: ""} v, err := vocabulary.New(c) if err != nil { t.Errorf("Test failed: %s", err) } expected := []string{"hate"} actual, _ := v.Antonyms("love") if !reflect.DeepEqual(expected, actual) { t.Errorf("Test failed, expected: '%s', got: '%s'", expected, actual) } } func TestAntonymsInvalidWord(t *testing.T) { c := &vocabulary.Config{BigHugeLabsApiKey: e.BigHugeLabsApiKey, WordnikApiKey: ""} v, err := vocabulary.New(c) if err != nil { t.Errorf("Test failed: %s", err) } expected := []string{} actual, _ := v.Antonyms("asfbhsdjfhdsj") if !reflect.DeepEqual(expected, actual) { t.Errorf("Test failed, expected: '%s', got: '%s'", expected, actual) } } // ----------------------------------------------------------------------------- func TestPartOfSpeech(t *testing.T) { c := &vocabulary.Config{BigHugeLabsApiKey: "", WordnikApiKey: e.WordnikApiKey} v, err := vocabulary.New(c) if err != nil { t.Errorf("Test failed: %s", err) } expected := vocabulary.PartOfSpeech{"adverb", "With speed; in a rapid manner."} actual, _ := v.PartOfSpeech("rapidly") if !reflect.DeepEqual(expected, actual[0]) { t.Errorf("Test failed, expected: '%s', got: '%s'", expected, actual) } } func TestPartOfSpeechInvalidWord(t *testing.T) { c := &vocabulary.Config{BigHugeLabsApiKey: "", WordnikApiKey: e.WordnikApiKey} v, err := vocabulary.New(c) if err != nil { t.Errorf("Test failed: %s", err) } expected := []vocabulary.PartOfSpeech{} actual, _ := v.PartOfSpeech("asfbhsdjfhdsj") if !reflect.DeepEqual(expected, actual) { t.Errorf("Test failed, expected: '%s', got: '%s'", expected, actual) } } // ----------------------------------------------------------------------------- func TestUsageExample(t *testing.T) { c := &vocabulary.Config{BigHugeLabsApiKey: "", WordnikApiKey: ""} v, err := vocabulary.New(c) if err != nil { t.Errorf("Test failed: %s", err) } expected := []string{"I went to the to of the hillock to look around."} actual, _ := v.UsageExample("hillock") if !reflect.DeepEqual(expected, actual) { t.Errorf("Test failed, expected: '%s', got: '%s'", expected, actual) } } func TestUsageExampleInvalidWord(t *testing.T) { c := &vocabulary.Config{BigHugeLabsApiKey: "", WordnikApiKey: ""} v, err := vocabulary.New(c) if err != nil { t.Errorf("Test failed: %s", err) } expected := []string{} actual, _ := v.UsageExample("asfbhsdjfhdsj") if !reflect.DeepEqual(expected, actual) { t.Errorf("Test failed, expected: '%s', got: '%s'", expected, actual) } } <|start_filename|>examples/example.go<|end_filename|> package main // Simple example usage of // github.com/karan/vocabulary import ( "fmt" "log" "github.com/karan/vocabulary" ) func main() { // Set the API keys // Some functions require API keys. Refer to docs. // If API keys are not required, simple set empty strings as config: c := &vocabulary.Config{BigHugeLabsApiKey: BigHugeLabsApiKey, WordnikApiKey: WordnikApiKey} // Instantiate a Vocabulary object with your config v, err := vocabulary.New(c) if err != nil { log.Fatal(err) } // Create a new vocabulary.Word object, and collects all possible information. word, err := v.Word("vuvuzela") if err != nil { log.Fatal(err) } fmt.Printf("word.Word = %s \n", word.Word) fmt.Printf("word.Meanings = %s \n", word.Meanings) fmt.Printf("word.Synonyms = %s \n", word.Synonyms) fmt.Printf("word.Antonyms = %s \n", word.Antonyms) fmt.Printf("word.PartOfSpeech = %s \n", word.PartOfSpeech) fmt.Printf("word.UsageExample = %s \n", word.UsageExample) // Get just the synonyms // synonyms, err := v.Synonyms("area") // if err != nil { // log.Fatal(err) // } // for _, s := range synonyms { // fmt.Println(s) // } // // Get just the antonyms // ants, err := v.Antonyms("love") // if err != nil { // log.Fatal(err) // } // for _, a := range ants { // fmt.Println(a) // } // Get just the part of speech // pos, err := v.PartOfSpeech("love") // if err != nil { // log.Fatal(err) // } // for _, a := range pos { // fmt.Println(a) // } // Can also use: // v.UsageExample(word) } <|start_filename|>vocabulary.go<|end_filename|> package vocabulary import ( "encoding/json" "fmt" "io/ioutil" "net/http" "strings" ) // ----------------------------------------------------------------------------- const meaningApiUrl string = "https://glosbe.com/gapi/translate?from=en&dest=en&format=json&pretty=true&phrase=%s" const synonymsApiUrl string = "https://glosbe.com/gapi/translate?from=en&dest=en&format=json&pretty=true&phrase=%s" const antonymsApiUrl string = "http://words.bighugelabs.com/api/2/%s/%s/text" const partOfSpeechApiUrl string = "http://api.wordnik.com/v4/word.json/%s/definitions?api_key=%s" const usageExampleApiUrl string = "http://api.urbandictionary.com/v0/define?term=%s" // ----------------------------------------------------------------------------- // Error represents an error. type Error string // Error implements the built-in error interface. func (e Error) Error() string { return string(e) } // ----------------------------------------------------------------------------- // Makes an http GET request and returns the byte array contents func makeReq(url string) ([]byte, error) { response, err := http.Get(url) if err != nil { fmt.Printf("%s", err) return nil, Error(fmt.Sprintf("%s", err)) } else { defer response.Body.Close() contents, err := ioutil.ReadAll(response.Body) if err != nil { fmt.Printf("%s", err) return nil, Error(fmt.Sprintf("%s", err)) } // fmt.Printf("%s\n", string(contents)) return contents, nil } } // Returns true if a is present in list func stringInSlice(a string, list []string) bool { for _, b := range list { if b == a { return true } } return false } // ----------------------------------------------------------------------------- // Config represents the configuration settings. type Config struct { BigHugeLabsApiKey string // API key from BigHugeLabs WordnikApiKey string // API key from Wordnik } // ----------------------------------------------------------------------------- // Represents the part of speech of a word type PartOfSpeech struct { POS string `json:"partOfSpeech"` // The part of speech for the word ExampleUsage string `json:"text"` // An example usage for the word in POS } // Represents a word with all its information type Word struct { Word string // The original word in the query Meanings []string // A list of meanings for this word Synonyms []string // A list of synonyms for this word Antonyms []string // A list of antonyms for this word PartOfSpeech []PartOfSpeech // A list of part of speech for this word UsageExample []string // A list of sentences showing usage example for the word } // ----------------------------------------------------------------------------- // Vocabulary object represents an instance of vocabulary type Vocabulary struct { c *Config } // Creates a new Word object collecting as much information as possible. // Requires having all API keys. func (v Vocabulary) Word(w string) (Word, error) { if w == "" { return Word{}, Error("word must be non-empty string") } if v.c.BigHugeLabsApiKey == "" { return Word{}, Error("BigHugeLabsApiKey required.") } if v.c.WordnikApiKey == "" { return Word{}, Error("WordnikApiKey required.") } meanings, err := v.Meanings(w) if err != nil { return Word{}, err } synonyms, err := v.Synonyms(w) if err != nil { return Word{}, err } antonyms, err := v.Antonyms(w) if err != nil { return Word{}, err } pos, err := v.PartOfSpeech(w) if err != nil { return Word{}, err } ue, err := v.UsageExample(w) if err != nil { return Word{}, err } return Word{ Word: w, Meanings: meanings, Synonyms: synonyms, Antonyms: antonyms, PartOfSpeech: pos, UsageExample: ue, }, nil } // Returns a list of strings representing the meanings of the given word. func (v Vocabulary) Meanings(w string) ([]string, error) { contents, err := makeReq(fmt.Sprintf(meaningApiUrl, w)) if err != nil { return []string{}, err } var glosbe Glosbe err = json.Unmarshal(contents, &glosbe) if err != nil || glosbe.Result != "ok" || len(glosbe.Tuc) == 0 { return []string{}, err } var meanings GlosbeMeanings err = json.Unmarshal(glosbe.Tuc[0], &meanings) if err != nil { return []string{}, err } var result []string for _, gt := range meanings.Things { result = append(result, gt.Text) } return result, nil } // Returns a list of strings representing the synonyms of the given word. func (v Vocabulary) Synonyms(w string) ([]string, error) { contents, err := makeReq(fmt.Sprintf(synonymsApiUrl, w)) if err != nil { return []string{}, err } var glosbe Glosbe err = json.Unmarshal(contents, &glosbe) if err != nil || glosbe.Result != "ok" || len(glosbe.Tuc) < 2 { return []string{}, err } var result []string for _, tuc_raw := range glosbe.Tuc[1:] { var gp GlosbePhrase err = json.Unmarshal(tuc_raw, &gp) if err != nil { return []string{}, err } if gp.Thing.Text != "" { result = append(result, gp.Thing.Text) } } return result, nil } // Returns a list of strings representing the antonyms of the given word. func (v Vocabulary) Antonyms(w string) ([]string, error) { if v.c.BigHugeLabsApiKey == "" { return []string{}, Error("BigHugeLabsApiKey required.") } contents, err := makeReq(fmt.Sprintf(antonymsApiUrl, v.c.BigHugeLabsApiKey, w)) if err != nil { return []string{}, err } if string(contents) == "" { return []string{}, nil } var result []string lines := strings.Split(string(contents), "\n") for _, line := range lines { b := strings.Split(line, "|") if len(b) == 3 && b[1] == "ant" && !stringInSlice(b[2], result) { result = append(result, b[2]) } } return result, nil } // Returns a list of PartOfSpeech structs representing the POS of the given word. func (v Vocabulary) PartOfSpeech(w string) ([]PartOfSpeech, error) { if v.c.WordnikApiKey == "" { return []PartOfSpeech{}, Error("WordnikApiKey required.") } contents, err := makeReq(fmt.Sprintf(partOfSpeechApiUrl, w, v.c.WordnikApiKey)) if err != nil { return []PartOfSpeech{}, err } var result []PartOfSpeech err = json.Unmarshal(contents, &result) if err != nil { return []PartOfSpeech{}, err } return result, nil } // Returns a list of strings representing usage examples of the given word. func (v Vocabulary) UsageExample(w string) ([]string, error) { contents, err := makeReq(fmt.Sprintf(usageExampleApiUrl, w)) if err != nil { return []string{}, err } var resp UrbanDictResp err = json.Unmarshal(contents, &resp) if err != nil { return []string{}, err } if len(resp.Things) == 0 { return []string{}, nil } var result []string for _, thing := range resp.Things { if thing.ThumbsUp > 2*thing.ThumbsDown { text := strings.Replace(thing.Example, "\r", " ", -1) text = strings.Replace(thing.Example, "\n", " ", -1) result = append(result, text) } } return result, nil } // ----------------------------------------------------------------------------- // New Instantiates a new instance of Vocabulary with the passed config. // func New(c *Config) (Vocabulary, error) { v := Vocabulary{c: c} return v, nil } <|start_filename|>api_types.go<|end_filename|> package vocabulary import ( "encoding/json" ) // ----------------------------------------------------------------------------- type GlosbeThing struct { Text string `json:"text"` } type GlosbeMeanings struct { Things []GlosbeThing `json:"meanings"` } type GlosbePhrase struct { Thing GlosbeThing `json:"phrase"` } type Glosbe struct { Result string `json:"result"` Tuc []json.RawMessage `json:"tuc"` } // ----------------------------------------------------------------------------- type UrbanDictThing struct { Example string `json:"example"` ThumbsUp int `json:"thumbs_up"` ThumbsDown int `json:"thumbs_down"` } type UrbanDictResp struct { Things []UrbanDictThing `json:"list"` }
karan/vocabulary
<|start_filename|>docs/sdotermpage.css<|end_filename|> .pln { color: #444; } /* plain text */ .tag { color: #515484; } /* div, span, a, etc */ .atn, .atv { color: #314B17; } /* href, datetime */ .new { color: #660003; } /* itemscope, itemtype, etc,. */ .curl { color: #080; } /* new url */ table.definition-table { border-spacing: 3px; border-collapse: separate; } #morecheck { outline: none; } #morecheck:checked + div { display: none; } .clipbutton { color: #202020 !important; border: 0; padding : 2px; } .example-head { display: block; padding-bottom: 5px; } /* example tab selection */ .ds-selector-tabs { padding-bottom: 2em; } .ds-selector-tabs .selectors { padding: 0; display: contents; width: auto; overflow-x: auto; border-bottom: 1px solid #ccc; height: 28px; } .ds-selector-tabs .selectors a { display: inline-block; min-width: 30px; text-align: center; font-size: 11px; font-weight: bold; height: 27px; padding: 0 8px; line-height: 27px; transition: all,0.218s; border-top-right-radius: 2px; border-top-left-radius: 2px; color: #666; border: 1px solid transparent; } .ds-selector-tabs .selectors a:first-child { margin-left: 2px; } .ds-selector-tabs .selectors a.selected { color: #202020 !important; border: 1px solid #ccc; border-bottom: 1px solid #fff !important; } #mainContent .ds-selector-tabs .selectors a:hover { background-color: transparent; color: #202020; cursor: pointer; } .ds-selector-tabs .ds-tab { display: none; } .ds-selector-tabs .ds-tab.selected { display: block; } .selectors code { padding-top: 0 !important; padding-bottom: 0 !important; } .ds-tab pre.ds-tab-content{ display: block; margin-top: 1px; } div.ds-tab-note{ display: block; padding-top: 5px; padding-bottom: 5px; font-style: italic; } a.ds-tab-note{ color: #3A4956; text-decoration: none; border-bottom: dotted 1px #3A4956; } a:visited.ds-tab-note{ color: #3A4956; text-decoration: none; border-bottom: dotted 1px #3A4956; } a:link.ds-tab-note{ color: #3A4956; text-decoration: none; border-bottom: dotted 1px #3A4956; } a:hover.ds-tab-note{ color: #3A4956; text-decoration: none; border-bottom: dotted 1px #3A4956; } .structureout { margin-left: 5px; } /*Effectively hide but can't use 'display: none;' as clip will not work if hidden*/ .structuretext { white-space: pre-wrap; opacity: .01; height:0; position:absolute; z-index: -1; } /* Tooltip container */ .tooltip { position: relative; display: inline-block; top: 4px; } /* Tooltip text */ .tooltip .tooltiptext { visibility: hidden; width: 100px; top: 100%; left: 50%; margin-left: -50px; /* Use half of the width (120/2 = 60), to center the tooltip */ background-color: black; color: #fff; text-align: center; padding: 5px 0; border-radius: 6px; /* Position the tooltip text - see examples below! */ position: absolute; z-index: 1; } .tooltip .tooltiptext::after { content: " "; position: absolute; bottom: 100%; /* At the top of the tooltip */ left: 50%; margin-left: -5px; border-width: 5px; border-style: solid; border-color: transparent transparent black transparent; } /* Show the tooltip text when you mouse over the tooltip container */ .tooltip .tooltiptext.show { visibility: visible; } <|start_filename|>docs/sdotermpage.js<|end_filename|> $(document).ready(function(){ prettyPrint(); setTimeout(function(){ $(".atn:contains(itemscope), .atn:contains(itemtype), .atn:contains(itemprop), .atn:contains(itemid), .atn:contains(time), .atn:contains(datetime), .atn:contains(datetime), .tag:contains(time) ").addClass('new'); $('.new + .pun + .atv').addClass('curl'); window.structured = []; $('.ds-tab.structure').on('loadstructuredview', async function(){ var $this = $(this); $key = $this.data('ex'); if(window.structured.indexOf($key) == -1) { window.structured.push($key); $jdata = $('.payload.' + $key).html(); const html1 = await prettyMarkupHtml($jdata); $('.structureout.' + $key).html( html1); var val = await prettyMarkupText($jdata); $('.structuretext.' + $key).html(val); } }); }, 500); setTimeout(function(){ $(".atn:contains(property), .atn:contains(typeof) ").addClass('new'); $('.new + .pun + .atv').addClass('curl'); }, 500); setTimeout(function() { $('.ds-selector-tabs .selectors a').click(function() { var $this = $(this); var $p = $this.parents('.ds-selector-tabs'); $('.selected', $p).removeClass('selected'); $this.addClass('selected'); $('.ds-tab.' + $this.data('selects'), $p).addClass('selected').trigger('loadstructuredview'); }); }, 0); clip = new ClipboardJS('.clip'); clip.on('success', function(e) { $but = e.trigger.className; $targ = $but.split(" ").pop(); var targsel = '.tooltiptext.' + $targ; var tip = $(targsel); tip.text('Copied!'); tip.addClass('show'); e.clearSelection(); setTimeout(function() { tip.removeClass('show'); }, 2500); }); clip.on('error', function(e) { var tip = $('.tooltip .tooltiptext'); tip.text(fallbackMessage('copy')); tip.addClass('show'); }); $('.tooltip .tooltiptext').mouseleave(function(){ $(this).removeClass('show'); }); }); <|start_filename|>docs/pretty-markup/layout.js<|end_filename|> /** * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var TYPE_URI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'; var NAME_URI = 'http://schema.org/name'; var defaultBase = 'http://example.org/'; var htmlIndentStep = 30; // one indentation step in HTML representation (in px) var textIndentStep = 4; // one indentation step in text representation (in spaces) /** * @param {string} text * @return {string} */ function replacePrefix(text) { text = text.split(/https?:\/\/schema.org\//g).join(''); text = text.split(/http:\/\/www.w3.org\/1999\/02\/22-rdf-syntax-ns#/g).join('@'); text = text.split(/http:\/\/www.w3.org\/2000\/01\/rdf-schema#/g).join('@'); return text; } /** * Does a random permutation of array elements * @param array */ function shuffleArray(array) { for (var i = array.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var temp = array[i]; array[i] = array[j]; array[j] = temp; } } /** * @param {Map<string, *>} shapes * @return {number[]} */ function makeColorSet(shapes) { var totalEntitiesCount = 0; var colors = []; var _iterator = _createForOfIteratorHelper(shapes.values()), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var store = _step.value; totalEntitiesCount += new Set(store.getSubjects().map(function (x) { return x.id; })).size; } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } for (var i = 0; i < totalEntitiesCount; i++) { colors.push(i / totalEntitiesCount * 360); } shuffleArray(colors); return colors; } /** * Makes a text layout for a single triple * @param {string} subject * @param {string} predicate * @param {string} object * @param {{ * indentLevel: number, * entityColorId: number, * isTarget: boolean * }} options * @return {string} */ function dataItemLayoutText(subject, predicate, object, options) { var indent = ' '.repeat(options.indentLevel * textIndentStep); return "".concat(indent).concat(replacePrefix(predicate), ": ").concat(replacePrefix(object)); } /** * Makes an html layout for a single triple * @param {string} subject * @param {string} predicate * @param {string} object * @param {{ * indentLevel: number, * entityColorId: number, * isTarget: boolean, * }} options * @return {*} */ function dataItemLayoutHtml(subject, predicate, object, options) { var indentBlock = document.createElement('div'); indentBlock.style.width = "".concat(options.indentLevel * htmlIndentStep, "px"); indentBlock.style.borderRight = "3px solid hsl(".concat(options.entityColorId, ", 60%, 70%)"); indentBlock.style.marginRight = '3px'; var predicateEl = document.createElement('div'); predicateEl.classList.add('predicate'); var predicateTextEl = document.createElement('div'); predicateTextEl.innerText = replacePrefix(predicate); predicateEl.appendChild(indentBlock); predicateEl.appendChild(predicateTextEl); var objectEl = document.createElement('div'); objectEl.classList.add('object'); objectEl.innerText = object; var tripleRow = document.createElement('div'); tripleRow.classList.add('triple-row'); tripleRow.style.background = options.isTarget ? '#f4f4f4' : '#fff'; tripleRow.appendChild(predicateEl); tripleRow.appendChild(objectEl); return tripleRow; } /** * Recursive level-based html generation * @param store - n3 store with quads * @param {string} id - current node identifier * @param {string[]} displayed * @param {number} indentLevel - current indentation level * @param {function} layoutGenerator * @param {{ * target?:{type: 'entity'|'property', uri: string}, * colorSet?: number[] * }|undefined} options * @return {HTMLElement[]} */ function markupLevel(store, id, displayed, indentLevel, layoutGenerator) { var _levelQuads, _levelQuads2; var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : undefined; if (displayed.includes(id)) return []; displayed.push(id); var levelQuads = store.getQuads(id, undefined, undefined); if (levelQuads.length === 0) return []; var tripleRows = []; // options for dataItemLayout building var layoutOptions = { indentLevel: indentLevel, entityColorId: options && options.colorSet ? options.colorSet.pop() : Math.random() * 360, isTarget: false }; // important properties (type & name) go first var typeQuad = store.getQuads(id, TYPE_URI, undefined); var nameQuad = store.getQuads(id, NAME_URI, undefined); levelQuads = levelQuads.filter(function (x) { return x.predicate.value !== TYPE_URI && x.predicate.value !== NAME_URI; }); (_levelQuads = levelQuads).push.apply(_levelQuads, _toConsumableArray(nameQuad)); (_levelQuads2 = levelQuads).push.apply(_levelQuads2, _toConsumableArray(typeQuad)); levelQuads.reverse(); // adding @id (it's not in quads) if (levelQuads.length > 0 && levelQuads[0].subject.termType === 'NamedNode') { tripleRows.push(layoutGenerator(id, '@id', id, layoutOptions)); } var _iterator2 = _createForOfIteratorHelper(levelQuads), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var quad = _step2.value; // used for highlighting target triples layoutOptions.isTarget = options && options.target && (options.target.type === 'entity' && typeQuad.length > 0 && typeQuad[0].object.value === options.target.uri || options.target.type === 'property' && quad.predicate.value === options.target.uri); var next_level = markupLevel(store, quad.object.id, displayed, indentLevel + 1, layoutGenerator, options); if (next_level.length > 0) { tripleRows.push(layoutGenerator(id, quad.predicate.value, '', layoutOptions)); tripleRows.push.apply(tripleRows, _toConsumableArray(next_level)); } else { var object = quad.object.termType === 'NamedNode' ? replacePrefix(quad.object.value) : quad.object.value; tripleRows.push(layoutGenerator(id, quad.predicate.value, object, layoutOptions)); } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return tripleRows; } /** * Get as close as possible base url that is still valid * @param {string} data - input markup * @return {string} */ function makeBaseUrl(data) { var dataObj; try { dataObj = JSON.parse(data); } catch (e) { // return default if can't be parsed as JSON return defaultBase; } if (dataObj.hasOwnProperty('@id')) { // if has an @id and @id has a full url prefix (e.g. https://, etc.), return it // else this is a relative url and we need to add the default base to it if (dataObj['@id'].match(/.*?:\/\/.*/g)) return dataObj['@id'];else return defaultBase + dataObj['@id']; } return defaultBase; } /** * Gets data from <script> tags * @param {string} data * @return {string|*} */ function removeScript(data) { try { JSON.parse(data); return data; } catch (e) { var domParser = new DOMParser(); var jsonld = [].slice.call(domParser.parseFromString(data, 'text/html').getElementsByTagName('script')).filter(function (x) { return x.type === 'application/ld+json'; }); // if there is exactly one json-ld, then parse it, else throw an exception // (I assume that only one json-ld can be in the example, but if not we still can // parse and display more than one) if (jsonld.length === 1) return jsonld[0].innerText;else if (jsonld.length > 1) throw 'not single json-ld in the example'; } } /** * Base function that will can be called for pretty markup generation * @param {string} data - json-ld markup * @param {{baseUrl?: string, target?: {type: 'entity'|'property', uri: string}}|undefined} options * - used for highlighting target entities/properties, e.g. startDate in the Event entity * @return {Promise<HTMLElement[]>} */ function prettyMarkupHtml(_x) { return _prettyMarkupHtml.apply(this, arguments); } /** * Base function that will can be called for pretty markup generation * @param {string} data - json-ld markup * @param {{baseUrl?: string, target?: {type: 'entity'|'property', uri: string}}|undefined} options * - used for highlighting target entities/properties, e.g. startDate in the Event entity * @return {Promise<string>} */ function _prettyMarkupHtml() { _prettyMarkupHtml = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(data) { var options, baseUrl, target, shapes, colorSet, tripleRows, _iterator3, _step3, _step3$value, id, shape, _args = arguments; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: options = _args.length > 1 && _args[1] !== undefined ? _args[1] : undefined; data = removeScript(data); // passed baseUrl is prioritised, but if not given, a close to the markup baseUrl will be used baseUrl = options && options.baseUrl ? options.baseUrl : makeBaseUrl(data); target = options && options.target ? options.target : undefined; _context.t0 = schemarama; _context.next = 7; return schemarama.stringToQuads(data, baseUrl); case 7: _context.t1 = _context.sent; shapes = _context.t0.quadsToShapes.call(_context.t0, _context.t1); colorSet = makeColorSet(shapes); tripleRows = []; _iterator3 = _createForOfIteratorHelper(shapes.entries()); try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { _step3$value = _slicedToArray(_step3.value, 2), id = _step3$value[0], shape = _step3$value[1]; tripleRows.push.apply(tripleRows, _toConsumableArray(markupLevel(shape, id, [], 0, dataItemLayoutHtml, { colorSet: colorSet, target: target }))); } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } return _context.abrupt("return", tripleRows); case 14: case "end": return _context.stop(); } } }, _callee); })); return _prettyMarkupHtml.apply(this, arguments); } function prettyMarkupText(_x2) { return _prettyMarkupText.apply(this, arguments); } function _prettyMarkupText() { _prettyMarkupText = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(data) { var options, baseUrl, target, shapes, colorSet, tripleRows, _iterator4, _step4, _step4$value, id, shape, _args2 = arguments; return regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: options = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : undefined; data = removeScript(data); // passed baseUrl is prioritised, but if not given, a close to the markup baseUrl will be used baseUrl = options && options.baseUrl ? options.baseUrl : makeBaseUrl(data); target = options && options.target ? options.target : undefined; _context2.t0 = schemarama; _context2.next = 7; return schemarama.stringToQuads(data, baseUrl); case 7: _context2.t1 = _context2.sent; shapes = _context2.t0.quadsToShapes.call(_context2.t0, _context2.t1); colorSet = makeColorSet(shapes); tripleRows = []; _iterator4 = _createForOfIteratorHelper(shapes.entries()); try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { _step4$value = _slicedToArray(_step4.value, 2), id = _step4$value[0], shape = _step4$value[1]; tripleRows.push(markupLevel(shape, id, [], 0, dataItemLayoutText, { colorSet: colorSet, target: target }).join('\n')); } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } return _context2.abrupt("return", tripleRows.join('\n\n')); case 14: case "end": return _context2.stop(); } } }, _callee2); })); return _prettyMarkupText.apply(this, arguments); } <|start_filename|>docs/cdc-covid.html<|end_filename|> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Schema.org - COVID Hospital data schema (US CDC)</title> <!-- #### Static Doc Insert Head goes here --> </head> <body> <!-- #### Static Doc Insert PageHead goes here --> <div id="mainContent"> <style> table { border-collapse:collapse; border:1px solid #ccc; } tbody, tr, td { border:inherit; border-collapse:inherit; } td { padding:5px; } .style0 { border-collapse:collapse; border:1px solid #000000 } .style1 { background-color:#fff2cc; } </style> <h2>Schema.org COVID-19: US CDC Data Table fields</h2> <dl> <dt><strong>Editor</strong>:</dt><dd> <NAME> &lt;<a href="mailto:<EMAIL>"><EMAIL></a>&gt;</dd> <dt><strong>Last Updated</strong>:</dt><dd>2020-04-02</dd> </dl> <p>This document specifies a Schema.org representation of the following US <a href="https://www.cdc.gov/">CDC</a> (Centers for Disease Control and Prevention) data format definition:</p> <ul> <li><b>Title</b>: Importing COVID-19 Patient Module Denominator data for Patient Safety Component (PSC)</li> <li><b>URL</b>: <a href="https://www.cdc.gov/nhsn/pdfs/covid19/import-covid19-data-508.pdf">https://www.cdc.gov/nhsn/pdfs/covid19/import-covid19-data-508.pdf</a> </li> </ul> <p>The representation defined here is intended to be 1:1 with the original representation and <a href="https://en.wikipedia.org/wiki/Round-trip_format_conversion">round-trippable</a>. The <a href="https://www.cdc.gov/">CDC</a> document defines several data fields in a tabular format. These are represented in Schema.org as properties of an object of type CDCPMDRecord.</p> <p id="cdc_authority"> For all formal matters of interpretation for the properties listed in the table below, please refer to the source CDC documentation for authoritative definitions and official updates. This document (and accompanying schemas) may be updated in the future to track changes from CDC, but we cannot guarantee to do this immediately. Implementors are cautioned to check the CDC site for updates and clarifications. We expect that some aspects of the CDC definitions may change. </p> <p> The purpose of this schema definition is to provide a standards-based representation that can be used to encode and exchange records that correspond to the CDC format. Depending on context, any of the formats and standards that work with Schema.org may be applicable, including the Microdata, RDFa and JSON-LD data formats, as well as related technologies such as W3C SPARQL for data query. JSON-LD is in most cases likely to be the most appropriate format. There is no assumption that data encoded using this schema should necessarily be published on the public Web, nor that it would be used by search engines. </p> <ul> <li><a href="https://www.cdc.gov/nhsn/acute-care-hospital/covid19/index.html">https://www.cdc.gov/nhsn/acute-care-hospital/covid19/index.html</a> <ul> <li>The above <a href="https://www.cdc.gov/nhsn/pdfs/covid19/import-covid19-data-508.pdf">source PDF</a> is linked under Resources section,</li> <li>"<a href="https://www.cdc.gov/nhsn/pdfs/covid19/import-covid19-data-508.pdf">How to import COVID-19 Summary Data [PDF – 200 KB]</a>, Alongside <a href="https://www.cdc.gov/nhsn/pdfs/covid19/covid19-test-csv-import.csv">CSV File Template [CSV – 250 B]</a></li> </ul></li> <li><a href="https://www.cms.gov/files/document/32920-hospital-letter-vice-president-pence.pdf">https://www.cms.gov/files/document/32920-hospital-letter-vice-president-pence.pdf</a></li> </ul> <h2>Schema.org vocabulary:</h2> <p>The following additions were made to Schema.org (in the Pending area, pending review and implementation feedback):</p> <ul> <li>1 new type: Thing &gt; Intangible &gt; StructuredValue &gt; <a href="/CDCPMDRecord">CDCPMDRecord</a></li> <li>14 new properties: <a href="/cvdCollectionDate">cvdCollectionDate</a>, <a href="/cvdNumBeds">cvdNumBeds</a>, <a href="/cvdNumTotBeds">cvdNumTotBeds</a>, <a href="/cvdNumBedsOcc">cvdNumBedsOcc</a>, <a href="/cvdNumICUBeds">cvdNumICUBeds</a>, <a href="/cvdNumICUBedsOcc">cvdNumICUBedsOcc</a>, <a href="/cvdNumVent">cvdNumVent</a>, <a href="/cvdNumVentUse">cvdNumVentUse</a>, <a href="/cvdNumC19HospPats">cvdNumC19HospPats</a>, <a href="/cvdNumC19MechVentPats">cvdNumC19MechVentPats</a>, <a href="/cvdNumC19HOPats">cvdNumC19HOPats</a>, <a href="/cvdNumC19OverflowPats">cvdNumC19OverflowPats</a>, <a href="/cvdNumC19OFMechVentPats">cvdNumC19OFMechVentPats</a>, <a href="/cvdNumC19Died">cvdNumC19Died</a>.</li> <li>In addition, a new <a href="/healthcareReportingData">healthcareReportingData</a> property can be used to relate a <a href="/Hospital">Hospital</a> to a <a href="/CDCPMDRecord">CDCPMDRecord</a>.</li> <li>The <a href="/datePosted">datePosted</a> property can also be used on a <a href="/CDCPMDRecord">CDCPMDRecord</a>.</li> <li><b>Use <a href="/cvdFacilityId">cvdFacilityId</a> to identify the NHSN facility, and (optionally)<a href="/cvdFacilityCounty">cvdFacilityCounty</a> for its county name.</b></li> </ul> <p>New properties: this adds several new properties (see "Schema.org name" column). Most are Number (with additional application-level constraints summarized in "Notes" column). </p> <p>The reason for prefixing each name with cvd is to avoid clashing with similar or identical names already in use at Schema.org. For example, <a href="https://schema.org/numberOfBeds">https://schema.org/numberOfBeds</a> already exists for describing hotel rooms, apartments etc.; for the COVID-19 case it is simplest to keep things relatively self-contained.</p> <p><br/></p> <table class="style0"> <thead> <tr> <td class="style1"><strong>CDC name</strong></td> <td class="style1"><strong>Schema.org name</strong></td> <td class="style1"><strong>Expected Value</strong></td> <td class="style1"><strong>Notes</strong><br/><br/> <strong>(see CDC for authoritative guidance)</strong></td> <td class="style1"><strong>Definition</strong></td> </tr> </thead> <tbody> <tr> <td>collectiondate</td> <td>cvdCollectionDate</td> <td>Text, mm/dd/yyyy <br/> <br/> [or ISO 8601 DateTime]</td> <td>CDC required.<br/> <br/> Original date format for collectiondate was mm/dd/yyyy, which can be ambiguous outside of a US context, so we provide the option of using ISO-8601 dates instead</td> <td>Date for which patient counts are reported.</td> </tr> <tr> <td>numbeds</td> <td>cvdNumBeds</td> <td>Number</td> <td>CDC required.<br/> <br/> 0 to 10000<br/> <br/> Must be a whole number<br/> <br/> Must be &lt;= numTotBeds </td> <td>HOSPITAL INPATIENT BEDS: Inpatient beds, including all staffed, licensed, and overflow (surge) beds used for inpatients.</td> </tr> <tr> <td>numtotbeds</td> <td>cvdNumTotBeds</td> <td>Number</td> <td>Must be a whole number<br/> <br/> 0 to 10000</td> <td>ALL HOSPITAL BEDS: Total number of all Inpatient and outpatient beds, including all staffed,ICU, licensed, and overflow (surge) beds used for inpatients or outpatients.</td> </tr> <tr> <td>numbedsocc</td> <td>cvdNumBedsOcc</td> <td>Number</td> <td>0 to 10000<br/> <br/> Must be a whole number <br/> <br/> Must be &lt;= numBeds </td> <td>HOSPITAL INPATIENT BED OCCUPANCY: Total number of staffed inpatient beds that are occupied.</td> </tr> <tr> <td>numicubeds</td> <td>cvdNumICUBeds</td> <td>Number</td> <td>0 to 10000<br/> <br/> Must be a whole number <br/> <br/> Must be &lt;= numBeds </td> <td>ICU BEDS: Total number of staffed inpatient intensive care unit (ICU) beds.</td> </tr> <tr> <td>numicubedsocc</td> <td>cvdNumICUBedsOcc</td> <td>Number</td> <td>0 to 10000<br/> <br/> Must be a whole number <br/> <br/> Must be &lt;= numICUBeds </td> <td>ICU BED OCCUPANCY: Total number of staffed inpatient ICU beds that are occupied.</td> </tr> <tr> <td>numvent</td> <td>cvdNumVent</td> <td>Number</td> <td>0 to 10000<br/> <br/> Must be a whole number <br/> <br/> Must be &lt;= numTotBeds or &lt;= 10,000 </td> <td>MECHANICAL VENTILATORS: Total number of ventilators available.</td> </tr> <tr> <td>numventuse</td> <td>cvdNumVentUse</td> <td>Number </td> <td>0 to 10000<br/> <br/> Must be a whole number <br/> <br/> Must be &lt;= numVent or &lt;= 10,000 </td> <td>MECHANICAL VENTILATORS IN USE: Total number of ventilators in use.</td> </tr> <tr> <td>numc19hosppats</td> <td>cvdNumC19HospPats</td> <td>Number</td> <td>0 to 10000<br/> <br/> Must be a whole number <br/> <br/> Must be &lt;= numBedsOcc </td> <td>HOSPITALIZED: Patients currently hospitalized in an inpatient care location who have suspected or confirmed COVID-19.</td> </tr> <tr> <td>numc19mechventpats</td> <td>cvdNumC19MechVentPats</td> <td>Number</td> <td>0 to 10000<br/> <br/> Must be a whole number <br/> <br/> Must be &lt;= numVentUse</td> <td>HOSPITALIZED and VENTILATED: Patients hospitalized in an NHSN inpatient care location who have suspected or confirmed COVID-19 and are on a mechanical ventilator.</td> </tr> <tr> <td>numc19hopats</td> <td>cvdNumC19HOPats</td> <td>Number</td> <td>0 to 10000<br/> <br/> Must be a whole number<br/> <br/> Must be &lt;= numBedsOcc </td> <td>HOSPITAL ONSET: Patients hospitalized in an NHSN inpatient care location with onset of suspected or confirmed COVID-19 14 or more days after hospitalization.</td> </tr> <tr> <td>numc19overflowpats</td> <td>cvdNumC19OverflowPats</td> <td>Number</td> <td>0 to 2000 <br/> <br/> Must be a whole number <br/> <br/> Must be &lt;=2000</td> <td>ED/OVERFLOW: Patients with suspected or confirmed COVID-19 who are in the ED or any overflow location awaiting an inpatient bed.</td> </tr> <tr> <td>numc19ofmechventpats</td> <td>cvdNumC19OFMechVentPats</td> <td>Number</td> <td>0 to 10000 <br/> <br/> Must be a whole number <br/> <br/> Must be &lt;= numVentUse </td> <td>ED/OVERFLOW and VENTILATED: Patients with suspected or confirmed COVID-19 who are in the ED or any overflow location awaiting an inpatient bed and on a mechanical ventilator.</td> </tr> <tr> <td>numc19died</td> <td>cvdNumC19Died </td> <td>Number</td> <td>0 to 1500 <br/> <br/> Must be a whole number <br/> <br/> Must be &lt;= 1500</td> <td>DEATHS: Patients with suspected or confirmed COVID-19 who died in the hospital, ED, or any overflow location.</td> </tr> </tbody> </table> <h2>Change Log</h2> <ul> <li>2020-04-02: Initial version.</li> </ul> </div> <!-- #### Static Doc Insert Footer here --> </body> </html> <|start_filename|>docs/debugwindow/viewconsole.js<|end_filename|> $(document).ready(function(){ setTimeout(function(){ var debugDiv = document.createElement('div'); debugDiv.id = "DebugDiv"; debugDiv.style.cssText = 'position:absolute;width:100%;height:500px;overflow:auto;z-index:100;text-align:left;color:yellow;background:#000;'; document.body.appendChild(debugDiv); $('#DebugDiv').animate({ scrollTop: $('#DebugDiv').get(0).scrollHeight }, 2000); window.DEBUG = {} let logger = document.getElementById("DebugDiv"); // Adding log method from our console object window.DEBUG.log = text => { let element = document.createElement("div"); let txt = document.createTextNode(text); element.appendChild(txt); logger.appendChild(element); } window.DEBUG.log("Debug output:"); }, 500); }); <|start_filename|>docs/schemaorg.css<|end_filename|> /* -- page structure -- */ #container { width: 100%; text-align: left; margin: 0; background: #fff; } #intro { position: relative; } #mainContent { border-bottom: solid 1px #CCCCCC; text-align: left; } #footer { text-align: right; font-size: x-small; } #mainContent, #footer, .wrapper { margin: 0 auto !important; padding: 0 0.5em; } /* -- general -- */ body { font-size: 1rem; font-weight: 400; line-height: 1.5; color: #212529; background: #FFF; font-family: Verdana, Tahoma, Arial, sans-serif; margin: 0; padding: 0; text-align: center; } code { font-family: Courier, monospace; } h1 { font: bold 24px Helvetica, Arial, sans-serif; color: #990000; letter-spacing: -1px; margin: 0.25em 0 0 0; } h2 { /* border-top: 1px solid #990000; */ padding-top: 5px; clear: both; color: #990000; font: normal 18px Helvetica, Arial, sans-serif; margin: 2em 0 0 0; } h3 { font-size: 12px; color: #660000; margin: 1em 0 0 0; position: relative; top: 8px; } h4 { font-size: 100%; margin: 0.5em 0 1em 0; position: relative; } */ hr { border: none; height: 1px; background: #ccc; margin: 2em 0 4em 0; } p { margin: 1em 0 0 0; } pre { font-family: Courier, monospace; font-size: 120%; background: #E1E1E1; width: auto; padding: 5px 5px 5px 10px; margin: 1em 0 0 0; text-align: left; overflow: auto; } pre.small{ font-size: 100%; } small { font-size: x-small; } #infohead { padding-bottom: 5px; } .superPaths{ padding-top:5px } /* -- main content -- */ #mainContent ul li { list-style: inherit; padding: 0 0 0 5px; margin: 0; } a:link { color: #660000; text-decoration: none; } a:visited { color: #990000; text-decoration: none; } a:hover { color: #660000; text-decoration: none; border-bottom: dotted 1px #660000; } #mainContent blockquote { padding: 0 0 0 15px; margin: 10px 0 10px 15px; width: auto; float: right; border-left: thin dotted #000; } #versioninfo { font-size: x-small; text-align: left; display: inline-block; float: left; color: #cccccc; } /* -- faq -- */ .faq p, .faq pre, .faq ul, .faq table, .faq { margin: .5em 0 0 50px; padding-top: 0px; padding-bottom: 2px; } .faq h1 { margin-bottom: 1em; } .faq ul, .faq ol { padding-left: 30px; margin-left: 50px; } #mainContent .question { font-weight: bold; margin: 1.5em 0 0 0; padding-top: 0px; padding-bottom: 2px; } /* -- types -- */ table.definition-table { margin: 1em 0 0 0; border: 1px solid #98A0A6; } .definition-table th { text-align: left; background: #C7CBCE; padding-left: 5px; } .definition-table td { padding: 0 5px 2px 5px; margin: 0; vertical-align: top; } .definition-table td p { padding: 0 0 .6em 0; margin: 0; } .definition-table td ul { padding-top: 0; margin-top: 0; } .definition-table tr.alt { background: #E9EAEB; } div.attrib { padding-bottom: 1em; } /* -- hierarchy -- */ table.h, .h tr, .h td { border: none; margin: 0; padding: 0; border-collapse: collapse } .h .space { width: 20px } .h .bar { background-color: #000; width: 1px } .h .tc { text-indent: -21px; padding-left: 21px } /* -- other -- */ .backtotop, .faq .backtotop { float: right; clear: both; padding: 3em 0 0 4em; padding: 0; font-size: 90%; } .date, .faq .date { color: #BFC3C7; text-align: right; font-size: x-small; clear: both; padding-top: 4em; } .version { color: #BFC3C7; text-align: right; font-size: x-small; clear: both; padding-top: 1em; } .ds-selector-tabs { padding-bottom: 2em; } .ds-selector-tabs .selectors { padding: 0; border-bottom: 1px solid #ccc; height: 28px; } .ds-selector-tabs .selectors a { display: inline-block; min-width: 30px; text-align: center; font-size: 11px; font-weight: bold; height: 27px; padding: 0 8px; line-height: 27px; transition: all,0.218s; border-top-right-radius: 2px; border-top-left-radius: 2px; color: #666; border: 1px solid transparent; } .ds-selector-tabs .selectors a:first-child { margin-left: 2px; } .ds-selector-tabs .selectors a.selected { color: #202020 !important; border: 1px solid #ccc; border-bottom: 1px solid #fff !important; } #mainContent .ds-selector-tabs .selectors a:hover { background-color: transparent; color: #202020; cursor: pointer; } .ds-selector-tabs .ds-tab { display: none; } .ds-selector-tabs .ds-tab.selected { display: block; } /* Clickable Anchor links */ a.clickableAnchor:link { color: #3A4956 !important; border-bottom: 0px !important; text-decoration: none; } a.clickableAnchor:visited { color: #3A4956 !important; border-bottom: 0px !important; text-decoration: none; } a.clickableAnchor:hover { color: #3A4956 !important; background-color: #3A4956 !important; text-decoration: none; } /* Core links */ a.core:link { color: #660000 !important; border-bottom: 0px !important; text-decoration: none; } a.core:visited { color: #660000 !important; border-bottom: 0px !important; text-decoration: none; } a.core:hover { color: #660000; text-decoration: none; border-bottom: dotted 1px #660000 !important; } /* Extension links */ a.ext:link { color: #0000aa !important; border-bottom-color:#0000aa !important; text-decoration: none; } a.ext:visited { color: #0000cc !important; border-bottom-color:#0000cc !important; text-decoration: none; } a.ext:hover { color: #0000cc; text-decoration: none; border-bottom: dotted 1px #0000cc; } /* External links */ a.externlink:link { color: #000 !important; border-bottom: dotted 1px #000 !important; text-decoration: none; } a.externlink:visited { color: #000 !important; border-bottom: dotted 1px #000 !important; text-decoration: none; } a.externlink:hover { color: #000; text-decoration: none; border-bottom: dotted 1px #000; } /* Attic extension links overriding default 'ext' values */ a.ext.ext-attic:link{ color: #888888 !important; border-bottom: dotted 1px #888888 !important; text-decoration: none; } a.ext.ext-attic:visited { color: #888888 !important; border-bottom: dotted 1px #888888 !important; text-decoration: none; } a.ext.ext-attic:hover { color: #fff !important; background-color: #bbbbbb; text-decoration: none; } .layerinfo { width: 100%; /* compatibility */ background-color: #990000; color: #fff; text-align: right; font-weight: bold; padding: 0.7em; } #lli a:link { text-decoration: underline; color : #fff; background-color: #990000; text-decoration: none; } #lli a:visited { text-decoration: underline; color : #fff; background-color: #990000; text-decoration: none; } /* Style overrides based on sitemode */ .testsite { color: black; background-color: #EEE; /* color: green; background-color: #DDFF00; background: #DDFF00; font-weight: 900; background-image: url(draft.jpg); background-repeat:repeat; */ } .needsreview { background-color: #FAEBD7; } .devnote { padding: 0.3em; font-size: 0.9rem; background-color:#d9edf7; color: #000; text-align: center; border: 1px solid #bce8f1; } .pendnote { padding: 0.7em; background-color:#fcf8e3; color: #000; border: 1px solid #faebcc; } .extlink { font-size: 85%; } .tag { color: #000; } /* div, span, etc */ .atn { color: #000; } /* href, datetime, */ .custom { color: #660003; } /* itemscope, itemtype, etc,. */ @media all and (max-width: 750px) { table.definition-table th, table.definition-table td { display: inline-block; } table.definition-table br { display: none; } } @media (min-width: 960px) { #mainContent, #footer, .wrapper { max-width: 960px; padding: 0 1em 1em 1em } } /*&&&&&&&&&&&&&&&&&&&&&&&&&&&&&*/ :root { --font-size: 1rem; --font-weight: 400; --line-height: 1.5; --color: #212529; --header-block-height: 120px; } #headerwrap { width: 100%; background-color: #990000; } #pagehead1 { display: block; font-size: 0; width: 100%; max-width: 960px; background-color: #990000; height: 80px; vertical-align: middle; margin-left: auto; margin-right: auto; } #pagehead1:before{ content: ''; display: inline-block; vertical-align: middle; height: 100%; } #pagehead-left{ width: 25%; font-size: 0; text-align: left; background-color: #990000; text-align:left; height: 80px; } #pagehead-mid{ width: 42%; text-align: right; background-color: #990000; height: 80px; } #pagehead-right{ width: 33%; text-align: right; background-color: #990000; height: 80px; } #sitename2 a:link, #sitename2 a:visited{ color: #fff; } .header-block { display: inline-block; vertical-align: middle; height: 100px; } .header-block:before{ content: ''; display: inline-block; vertical-align: middle; height: 100%; } .header-block-right { font-size: 1rem; text-align: right; } #sitename2 { max-width: 500px; min-width: auto; display: inline-block; color: #fff; margin: 0; padding: 25px; font: bold 1.5rem Helvetica, Arial, sans-serif; letter-spacing: -1px; text-shadow: 0 2px 0 #510000; } #selectionbar2 { display: inline-block; } #selectionbar2 ul { padding: 10px 0; margin: 0 auto; display: inline; color: #fff; } #selectionbar2 li { display: inline; list-style: none; } #selectionbar2 a:link, #selectionbar2 a:visited { color: #fff !important; display: inline; padding: 1px 9px 3px 6px; margin: 0 6px; opacity: 0.8; text-decoration: none !important; } #selectionbar2 a:hover { color: #fff !important; display: inline; opacity: 1; background-color: transparent; text-decoration: none !important; border-bottom: 0; cursor: pointer; } #cse-search-form2 { vertical-align: middle; display: inline-block; padding-left: 10px; } /* GSC Stuff */ #cse-search-form2 #___gcse_0 { width: 200px; padding-right: 25px; } #cse-search-form2 .gsib_a { padding: 3px 9px 3px 9px; } #cse-search-form2 .gsib_b { display: none; } #cse-search-form2 .gsc-input-box { border: none; } #cse-search-form2 form.gsc-search-box,#main-header table.gsc-search-box { margin-bottom: 0; font-size: 1rem; } #cse-search-form2 table.gsc-search-box td.gsc-input { padding-right: 0; font-size: 1rem; } #cse-search-form2 .gsc-search-button.gsc-search-button-v2 { background: rgba(255,255,255,.2) !important; border-radius: 0 10px 10px 0; border: none !important; margin: 0 0 1px 0; padding: 10px 10px 9px 8px; } #cse-search-form2 #gsc-iw-id1 { border-radius: 10px 0 0 10px; border: 1px solid #dee2e6; padding: 0; } #cse-search-form2 #gs_tti50 input { font-size: 1rem; background: none !important; } .devnote2 { display: none; } #navicon2 { display: none; } @media only screen and (max-width: 900px){ #sitename2 { float: left; } #navicon2 { display: inline-block; border: 1px solid #98A0A6; padding: 5px; margin-top: 15px; margin-right: 10px; float: right; } #pagehead1:before { display: none; } #pagehead1:not(.show) { height: 100px; } #pagehead1.show { height: 210px; } #pagehead-left { height: 75px; } #pagehead-left, #pagehead-mid, #pagehead-right { display: block; width: 100%; } #pagehead-mid:not(.show), #pagehead-right:not(.show) { display: none; } #pagehead-mid.show { height: 80px; text-align: right; } #pagehead-right.show { height: 55px; text-align: right; } #selectionbar2 { text-align: left; } #selectionbar2 li { display: list-item; line-height: 1.1rm; list-style: none; } } <|start_filename|>docs/schemaorg.js<|end_filename|> function navFunction() { var targets = document.getElementsByClassName("mobnav"); for(var i=0; i < targets.length;i++){ targets[i].classList.toggle("show"); } } (function() { var cx = '013516846811604855281:nj5laplixaa'; // Insert your own Custom Search engine ID here var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true; gcse.src = 'https://cse.google.com/cse.js?cx=' + cx; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s); })() <|start_filename|>SchemaTerms/example-code/protobufs/google/protobuf/pyext/map_container.h<|end_filename|> // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef GOOGLE_PROTOBUF_PYTHON_CPP_MAP_CONTAINER_H__ #define GOOGLE_PROTOBUF_PYTHON_CPP_MAP_CONTAINER_H__ #include <Python.h> #include <memory> #include <google/protobuf/descriptor.h> #include <google/protobuf/message.h> #include <google/protobuf/pyext/message.h> namespace google { namespace protobuf { class Message; namespace python { struct CMessageClass; // This struct is used directly for ScalarMap, and is the base class of // MessageMapContainer, which is used for MessageMap. struct MapContainer : public ContainerBase { // Use to get a mutable message when necessary. Message* GetMutableMessage(); // Cache some descriptors, used to convert keys and values. const FieldDescriptor* key_field_descriptor; const FieldDescriptor* value_field_descriptor; // We bump this whenever we perform a mutation, to invalidate existing // iterators. uint64 version; }; struct MessageMapContainer : public MapContainer { // The type used to create new child messages. CMessageClass* message_class; }; bool InitMapContainers(); extern PyTypeObject* MessageMapContainer_Type; extern PyTypeObject* ScalarMapContainer_Type; extern PyTypeObject MapIterator_Type; // Both map types use the same iterator. // Builds a MapContainer object, from a parent message and a // field descriptor. extern MapContainer* NewScalarMapContainer( CMessage* parent, const FieldDescriptor* parent_field_descriptor); // Builds a MessageMap object, from a parent message and a // field descriptor. extern MessageMapContainer* NewMessageMapContainer( CMessage* parent, const FieldDescriptor* parent_field_descriptor, CMessageClass* message_class); } // namespace python } // namespace protobuf } // namespace google #endif // GOOGLE_PROTOBUF_PYTHON_CPP_MAP_CONTAINER_H__ <|start_filename|>SchemaTerms/example-code/protobufs/google/protobuf/pyext/extension_dict.cc<|end_filename|> // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: <EMAIL> (<NAME>) // Author: <EMAIL> (<NAME>) #include <google/protobuf/pyext/extension_dict.h> #include <memory> #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/dynamic_message.h> #include <google/protobuf/message.h> #include <google/protobuf/descriptor.pb.h> #include <google/protobuf/pyext/descriptor.h> #include <google/protobuf/pyext/message.h> #include <google/protobuf/pyext/message_factory.h> #include <google/protobuf/pyext/repeated_composite_container.h> #include <google/protobuf/pyext/repeated_scalar_container.h> #include <google/protobuf/pyext/scoped_pyobject_ptr.h> #if PY_MAJOR_VERSION >= 3 #if PY_VERSION_HEX < 0x03030000 #error "Python 3.0 - 3.2 are not supported." #endif #define PyString_AsStringAndSize(ob, charpp, sizep) \ (PyUnicode_Check(ob) ? ((*(charpp) = const_cast<char*>( \ PyUnicode_AsUTF8AndSize(ob, (sizep)))) == NULL \ ? -1 \ : 0) \ : PyBytes_AsStringAndSize(ob, (charpp), (sizep))) #endif namespace google { namespace protobuf { namespace python { namespace extension_dict { static Py_ssize_t len(ExtensionDict* self) { Py_ssize_t size = 0; std::vector<const FieldDescriptor*> fields; self->parent->message->GetReflection()->ListFields(*self->parent->message, &fields); for (size_t i = 0; i < fields.size(); ++i) { if (fields[i]->is_extension()) { // With C++ descriptors, the field can always be retrieved, but for // unknown extensions which have not been imported in Python code, there // is no message class and we cannot retrieve the value. // ListFields() has the same behavior. if (fields[i]->message_type() != nullptr && message_factory::GetMessageClass( cmessage::GetFactoryForMessage(self->parent), fields[i]->message_type()) == nullptr) { PyErr_Clear(); continue; } ++size; } } return size; } struct ExtensionIterator { PyObject_HEAD; Py_ssize_t index; std::vector<const FieldDescriptor*> fields; // Owned reference, to keep the FieldDescriptors alive. ExtensionDict* extension_dict; }; PyObject* GetIter(PyObject* _self) { ExtensionDict* self = reinterpret_cast<ExtensionDict*>(_self); ScopedPyObjectPtr obj(PyType_GenericAlloc(&ExtensionIterator_Type, 0)); if (obj == nullptr) { return PyErr_Format(PyExc_MemoryError, "Could not allocate extension iterator"); } ExtensionIterator* iter = reinterpret_cast<ExtensionIterator*>(obj.get()); // Call "placement new" to initialize. So the constructor of // std::vector<...> fields will be called. new (iter) ExtensionIterator; self->parent->message->GetReflection()->ListFields(*self->parent->message, &iter->fields); iter->index = 0; Py_INCREF(self); iter->extension_dict = self; return obj.release(); } static void DeallocExtensionIterator(PyObject* _self) { ExtensionIterator* self = reinterpret_cast<ExtensionIterator*>(_self); self->fields.clear(); Py_XDECREF(self->extension_dict); self->~ExtensionIterator(); Py_TYPE(_self)->tp_free(_self); } PyObject* subscript(ExtensionDict* self, PyObject* key) { const FieldDescriptor* descriptor = cmessage::GetExtensionDescriptor(key); if (descriptor == NULL) { return NULL; } if (!CheckFieldBelongsToMessage(descriptor, self->parent->message)) { return NULL; } if (descriptor->label() != FieldDescriptor::LABEL_REPEATED && descriptor->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) { return cmessage::InternalGetScalar(self->parent->message, descriptor); } CMessage::CompositeFieldsMap::iterator iterator = self->parent->composite_fields->find(descriptor); if (iterator != self->parent->composite_fields->end()) { Py_INCREF(iterator->second); return iterator->second->AsPyObject(); } if (descriptor->label() != FieldDescriptor::LABEL_REPEATED && descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { // TODO(plabatut): consider building the class on the fly! ContainerBase* sub_message = cmessage::InternalGetSubMessage( self->parent, descriptor); if (sub_message == NULL) { return NULL; } (*self->parent->composite_fields)[descriptor] = sub_message; return sub_message->AsPyObject(); } if (descriptor->label() == FieldDescriptor::LABEL_REPEATED) { if (descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { // On the fly message class creation is needed to support the following // situation: // 1- add FileDescriptor to the pool that contains extensions of a message // defined by another proto file. Do not create any message classes. // 2- instantiate an extended message, and access the extension using // the field descriptor. // 3- the extension submessage fails to be returned, because no class has // been created. // It happens when deserializing text proto format, or when enumerating // fields of a deserialized message. CMessageClass* message_class = message_factory::GetOrCreateMessageClass( cmessage::GetFactoryForMessage(self->parent), descriptor->message_type()); ScopedPyObjectPtr message_class_handler( reinterpret_cast<PyObject*>(message_class)); if (message_class == NULL) { return NULL; } ContainerBase* py_container = repeated_composite_container::NewContainer( self->parent, descriptor, message_class); if (py_container == NULL) { return NULL; } (*self->parent->composite_fields)[descriptor] = py_container; return py_container->AsPyObject(); } else { ContainerBase* py_container = repeated_scalar_container::NewContainer( self->parent, descriptor); if (py_container == NULL) { return NULL; } (*self->parent->composite_fields)[descriptor] = py_container; return py_container->AsPyObject(); } } PyErr_SetString(PyExc_ValueError, "control reached unexpected line"); return NULL; } int ass_subscript(ExtensionDict* self, PyObject* key, PyObject* value) { const FieldDescriptor* descriptor = cmessage::GetExtensionDescriptor(key); if (descriptor == NULL) { return -1; } if (!CheckFieldBelongsToMessage(descriptor, self->parent->message)) { return -1; } if (value == nullptr) { return cmessage::ClearFieldByDescriptor(self->parent, descriptor); } if (descriptor->label() != FieldDescriptor::LABEL_OPTIONAL || descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { PyErr_SetString(PyExc_TypeError, "Extension is repeated and/or composite " "type"); return -1; } cmessage::AssureWritable(self->parent); if (cmessage::InternalSetScalar(self->parent, descriptor, value) < 0) { return -1; } return 0; } PyObject* _FindExtensionByName(ExtensionDict* self, PyObject* arg) { char* name; Py_ssize_t name_size; if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) { return NULL; } PyDescriptorPool* pool = cmessage::GetFactoryForMessage(self->parent)->pool; const FieldDescriptor* message_extension = pool->pool->FindExtensionByName(std::string(name, name_size)); if (message_extension == NULL) { // Is is the name of a message set extension? const Descriptor* message_descriptor = pool->pool->FindMessageTypeByName(std::string(name, name_size)); if (message_descriptor && message_descriptor->extension_count() > 0) { const FieldDescriptor* extension = message_descriptor->extension(0); if (extension->is_extension() && extension->containing_type()->options().message_set_wire_format() && extension->type() == FieldDescriptor::TYPE_MESSAGE && extension->label() == FieldDescriptor::LABEL_OPTIONAL) { message_extension = extension; } } } if (message_extension == NULL) { Py_RETURN_NONE; } return PyFieldDescriptor_FromDescriptor(message_extension); } PyObject* _FindExtensionByNumber(ExtensionDict* self, PyObject* arg) { int64 number = PyLong_AsLong(arg); if (number == -1 && PyErr_Occurred()) { return NULL; } PyDescriptorPool* pool = cmessage::GetFactoryForMessage(self->parent)->pool; const FieldDescriptor* message_extension = pool->pool->FindExtensionByNumber( self->parent->message->GetDescriptor(), number); if (message_extension == NULL) { Py_RETURN_NONE; } return PyFieldDescriptor_FromDescriptor(message_extension); } static int Contains(PyObject* _self, PyObject* key) { ExtensionDict* self = reinterpret_cast<ExtensionDict*>(_self); const FieldDescriptor* field_descriptor = cmessage::GetExtensionDescriptor(key); if (field_descriptor == nullptr) { return -1; } if (!field_descriptor->is_extension()) { PyErr_Format(PyExc_KeyError, "%s is not an extension", field_descriptor->full_name().c_str()); return -1; } const Message* message = self->parent->message; const Reflection* reflection = message->GetReflection(); if (field_descriptor->is_repeated()) { if (reflection->FieldSize(*message, field_descriptor) > 0) { return 1; } } else { if (reflection->HasField(*message, field_descriptor)) { return 1; } } return 0; } ExtensionDict* NewExtensionDict(CMessage *parent) { ExtensionDict* self = reinterpret_cast<ExtensionDict*>( PyType_GenericAlloc(&ExtensionDict_Type, 0)); if (self == NULL) { return NULL; } Py_INCREF(parent); self->parent = parent; return self; } void dealloc(PyObject* pself) { ExtensionDict* self = reinterpret_cast<ExtensionDict*>(pself); Py_CLEAR(self->parent); Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self)); } static PyObject* RichCompare(ExtensionDict* self, PyObject* other, int opid) { // Only equality comparisons are implemented. if (opid != Py_EQ && opid != Py_NE) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } bool equals = false; if (PyObject_TypeCheck(other, &ExtensionDict_Type)) { equals = self->parent == reinterpret_cast<ExtensionDict*>(other)->parent;; } if (equals ^ (opid == Py_EQ)) { Py_RETURN_FALSE; } else { Py_RETURN_TRUE; } } static PySequenceMethods SeqMethods = { (lenfunc)len, // sq_length 0, // sq_concat 0, // sq_repeat 0, // sq_item 0, // sq_slice 0, // sq_ass_item 0, // sq_ass_slice (objobjproc)Contains, // sq_contains }; static PyMappingMethods MpMethods = { (lenfunc)len, /* mp_length */ (binaryfunc)subscript, /* mp_subscript */ (objobjargproc)ass_subscript,/* mp_ass_subscript */ }; #define EDMETHOD(name, args, doc) { #name, (PyCFunction)name, args, doc } static PyMethodDef Methods[] = { EDMETHOD(_FindExtensionByName, METH_O, "Finds an extension by name."), EDMETHOD(_FindExtensionByNumber, METH_O, "Finds an extension by field number."), {NULL, NULL}, }; } // namespace extension_dict PyTypeObject ExtensionDict_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) // FULL_MODULE_NAME ".ExtensionDict", // tp_name sizeof(ExtensionDict), // tp_basicsize 0, // tp_itemsize (destructor)extension_dict::dealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number &extension_dict::SeqMethods, // tp_as_sequence &extension_dict::MpMethods, // tp_as_mapping PyObject_HashNotImplemented, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags "An extension dict", // tp_doc 0, // tp_traverse 0, // tp_clear (richcmpfunc)extension_dict::RichCompare, // tp_richcompare 0, // tp_weaklistoffset extension_dict::GetIter, // tp_iter 0, // tp_iternext extension_dict::Methods, // tp_methods 0, // tp_members 0, // tp_getset 0, // tp_base 0, // tp_dict 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset 0, // tp_init }; PyObject* IterNext(PyObject* _self) { extension_dict::ExtensionIterator* self = reinterpret_cast<extension_dict::ExtensionIterator*>(_self); Py_ssize_t total_size = self->fields.size(); Py_ssize_t index = self->index; while (self->index < total_size) { index = self->index; ++self->index; if (self->fields[index]->is_extension()) { // With C++ descriptors, the field can always be retrieved, but for // unknown extensions which have not been imported in Python code, there // is no message class and we cannot retrieve the value. // ListFields() has the same behavior. if (self->fields[index]->message_type() != nullptr && message_factory::GetMessageClass( cmessage::GetFactoryForMessage(self->extension_dict->parent), self->fields[index]->message_type()) == nullptr) { PyErr_Clear(); continue; } return PyFieldDescriptor_FromDescriptor(self->fields[index]); } } return nullptr; } PyTypeObject ExtensionIterator_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) // FULL_MODULE_NAME ".ExtensionIterator", // tp_name sizeof(extension_dict::ExtensionIterator), // tp_basicsize 0, // tp_itemsize extension_dict::DeallocExtensionIterator, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags "A scalar map iterator", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset PyObject_SelfIter, // tp_iter IterNext, // tp_iternext 0, // tp_methods 0, // tp_members 0, // tp_getset 0, // tp_base 0, // tp_dict 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset 0, // tp_init }; } // namespace python } // namespace protobuf } // namespace google
whiteslack/schemaorg
<|start_filename|>RCalendarPickerClass/ClockHelper.h<|end_filename|> // // ClockHelper.h // RCalendarPicker // // Created by roycms on 2016/11/23. // Copyright © 2016年 roycms. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface ClockHelper : NSObject /** 三个点A、B、C,计算ㄥABC @param pointA A CGPoint @param pointB B CGPoint @param pointC C CGPoint @return ㄥABC Angles */ + (CGFloat)getAnglesWithThreePoint:(CGPoint)pointA pointB:(CGPoint)pointB pointC:(CGPoint)pointC; /** 时间转角度 WithHour 整点 @param hours hours description @return return value description */ + (CGFloat)getAnglesWithHours:(CGFloat)hours; /** 时间转角度 WithHour 整点+ 分钟偏移 @param hours hours description @param minutes minutes description @return return value description */ + (CGFloat)getAnglesWithHoursAndMinutes:(CGFloat)hours minutes:(CGFloat)minutes; /** 时间转角度 WithMinutes @param minutes minutes description @return return value description */ + (CGFloat)getAnglesWithMinutes:(CGFloat)minutes; /** 根据角度换算成 小时时间 @param angle angle description @return return value description */ + (CGFloat)getHoursWithAngles:(CGFloat)angle; /** 根据角度换算成 分钟时间 @param angle angle description @return return value description */ + (CGFloat)getMinutesWithAngles:(CGFloat)angle; /** 根据点和角度 获取转动后的 点位置 @param center center description @param angel angel description @return return value description */ + (CGPoint)calculateTextPositonWithArcCenter:(CGPoint)center Angle:(CGFloat)angel; /** 返回 float 形式的 时间 格式例 12.05 @param hours hours description @param minutes minutes description @return return value description */ + (float)getFloatDate:(CGFloat)hours minutes:(CGFloat)minutes; /** 判断一个点是否在 一个view内 @param point 点 @param view view @return return value description */ + (BOOL)isPointInViewFor:(CGPoint)point view:(UIView *)view; @end <|start_filename|>index.html<|end_filename|> <!DOCTYPE html> <html lang="en-us"> <head> <meta charset="UTF-8"> <title>Rcalendarpicker by roycms</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="stylesheets/normalize.css" media="screen"> <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'> <link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen"> <link rel="stylesheet" type="text/css" href="stylesheets/github-light.css" media="screen"> </head> <body> <section class="page-header"> <h1 class="project-name">Rcalendarpicker</h1> <h2 class="project-tagline">RCalendarPicker 日历控件 ,日历选择控件,日历,日期选择</h2> <a href="https://github.com/roycms/RCalendarPicker" class="btn">View on GitHub</a> <a href="https://github.com/roycms/RCalendarPicker/zipball/master" class="btn">Download .zip</a> <a href="https://github.com/roycms/RCalendarPicker/tarball/master" class="btn">Download .tar.gz</a> </section> <section class="main-content"> <h1> <a id="rcalendarpicker" class="anchor" href="#rcalendarpicker" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>RCalendarPicker</h1> <p>RCalendarPicker Calendar calendar control, select control, calendar, date selection, the clock selection control. 日历控件 ,日历选择控件,日历,日期选择,时钟选择控件</p> <h1> <a id="preview" class="anchor" href="#preview" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Preview</h1> <p><img src="https://roycms.github.io/RCalendarPicker/RCalendarPicker/Resource/calendar.jpg" alt="预览1"> <img src="https://roycms.github.io/RCalendarPicker/RCalendarPicker/Resource/clock.jpg" alt="预览2"></p> <h1> <a id="cocoapods" class="anchor" href="#cocoapods" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>cocoapods</h1> <pre><code>pod 'RCalendarPicker' </code></pre> <h1> <a id="use" class="anchor" href="#use" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Use</h1> <p>default: MainScreenWidth = 360 MainScreenHeight = 960</p> <pre><code> RCalendarPickerView *calendarPicker = [[RCalendarPickerView alloc]initWithFrame:CGRectMake(0, 0, MainScreenWidth, MainScreenHeight)]; calendarPicker.today = [NSDate date]; //现在时间 calendarPicker.date = calendarPicker.today; //选择时间 calendarPicker.complete = ^(NSInteger day, NSInteger month, NSInteger year, NSDate *date){ NSLog(@"%d-%d-%d", (int)year,(int)month,(int)day); }; [self.view addSubview:calendarPicker]; </code></pre> <h1> <a id="the-lunar-calendar" class="anchor" href="#the-lunar-calendar" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>The lunar calendar</h1> <pre><code>RCalendarPickerView *calendarPicker = [[RCalendarPickerView alloc]initWithFrame:CGRectMake(0, 0, MainScreenWidth, MainScreenHeight)]; calendarPicker.isZn = YES; //开启农历 calendarPicker.today = [NSDate date]; //现在时间 calendarPicker.date = calendarPicker.today; //选择时间 calendarPicker.complete = ^(NSInteger day, NSInteger month, NSInteger year, NSDate *date){ NSLog(@"%d-%d-%d", (int)year,(int)month,(int)day); }; [self.view addSubview:calendarPicker]; </code></pre> <h1> <a id="a-clock-dial-effect" class="anchor" href="#a-clock-dial-effect" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>A clock dial effect</h1> <pre><code> RClockPickerView *rClockPickerView = [[RClockPickerView alloc]initWithFrame:CGRectMake(0, 0, MainScreenWidth, MainScreenHeight) clockRadius:140 clockCalibrationRadius:130]; rClockPickerView.date = [NSDate date]; rClockPickerView.complete = ^(NSInteger hours, NSInteger minutes, NSInteger noon){ NSLog(@"%d-%d-%d", (int)hours,(int)minutes,(int)noon); }; [self.view addSubview:rClockPickerView]; </code></pre> <h1> <a id="calendar--clock--use" class="anchor" href="#calendar--clock--use" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>calendar + clock use</h1> <pre><code>RCalendarPickerView *calendarPicker = [[RCalendarPickerView alloc]initWithFrame:CGRectMake(0, 0, MainScreenWidth, MainScreenHeight)]; calendarPicker.today = [NSDate date]; //现在时间 calendarPicker.date = calendarPicker.today; //选择时间 [self.view addSubview:calendarPicker]; calendarPicker.complete = ^(NSInteger day, NSInteger month, NSInteger year, NSDate *date){ NSLog(@"%d-%d-%d", (int)year,(int)month,(int)day); RClockPickerView *rClockPickerView = [[RClockPickerView alloc]initWithFrame:CGRectMake(0, 0, MainScreenWidth, MainScreenHeight) clockRadius:140 clockCalibrationRadius:130]; rClockPickerView.date = [NSDate date]; rClockPickerView.complete = ^(NSInteger hours, NSInteger minutes, NSInteger noon){ NSLog(@"%d-%d-%d", (int)hours,(int)minutes,(int)noon); NSDate *selectDate = [DateHelper dateInDate:date Hours:hours&gt;12?hours%12:hours minutes:minutes]; NSLog(@"selectDate: %@",selectDate); }; [self.view addSubview:rClockPickerView]; }; </code></pre> <h1> <a id="todo" class="anchor" href="#todo" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>TODO</h1> <ul> <li>增加上下午的判断和参数处理</li> <li>增加主题定义</li> <li>增加选择年月的切换形式</li> </ul> <footer class="site-footer"> <span class="site-footer-owner"><a href="https://github.com/roycms/RCalendarPicker">Rcalendarpicker</a> is maintained by <a href="https://github.com/roycms">roycms</a>.</span> <span class="site-footer-credits">This page was generated by <a href="https://pages.github.com">GitHub Pages</a> using the <a href="https://github.com/jasonlong/cayman-theme">Cayman theme</a> by <a href="https://twitter.com/jasonlong"><NAME></a>.</span> </footer> </section> </body> </html> <|start_filename|>RCalendarPickerClass/RClockPickerView.h<|end_filename|> // // RClockPickerView.h // RCalendarPicker // // Created by roycms on 2016/11/18. // Copyright © 2016年 roycms. All rights reserved. // #import <UIKit/UIKit.h> #import "RRGB.h" #import "Masonry.h" #import "DateHelper.h" #define LANGUAGE(LANValue) NSLocalizedStringFromTable(LANValue,@"RCalendarPickerLanguage", nil) #define MainScreenHeight ([UIScreen mainScreen].bounds.size.height) #define MainScreenWidth ([UIScreen mainScreen].bounds.size.width) @interface RClockPickerView : UIView /** 初始化 @param frame frame description @param clockRadius 表盘 圆圈的半径 @param clockCalibrationRadius 表盘刻度 圆圈的半径 @return return self */ - (instancetype)initWithFrame:(CGRect)frame clockRadius:(CGFloat)clockRadius clockCalibrationRadius:(CGFloat)clockCalibrationRadius; /** 设置当前钟表指针指向的时间 默认不设置是当前的时间 */ @property (nonatomic,assign)NSDate *date; /** 设置当前钟表指针指向的时间和上面的date一样只是格式不一样,两者重复设置后设置生效, 格式 12:01 或者 12.01 */ @property (nonatomic,strong)NSString *dateString; /** 主题 颜色 */ @property (nonatomic,assign) UIColor *thisTheme; /** 选择时间成功后 complete block */ @property (nonatomic,copy) void(^complete)(NSInteger hours, NSInteger minutes, NSInteger noon, float date); /** 取消按钮的block */ @property (nonatomic,copy) void(^cancel)(); /** 关闭 销毁 */ -(void)hide; @end <|start_filename|>RCalendarPickerClass/DateHelper.h<|end_filename|> // // DateHelper.h // RCalendarPicker // // Created by roycms on 2016/11/16. // Copyright © 2016年 roycms. All rights reserved. // #import <Foundation/Foundation.h> @interface DateHelper : NSObject /** 返回 day @param date nsdate @return 返回 day */ + (NSInteger)day:(NSDate *)date; /** 返回 月 @param date nsdate @return 返回 month */ + (NSInteger)month:(NSDate *)date; /** 返回 year @param date nsdate @return 返回 year */ + (NSInteger)year:(NSDate *)date; /** Description @param date date description @return return value description */ + (NSInteger)weekday:(NSDate *)date; /** hours @param date date description @return return value description */ + (NSInteger)hours:(NSDate *)date; /** minute @param date date description @return return value description */ + (NSInteger)minute:(NSDate *)date; /** Description @param date date description @return return value description */ + (NSInteger)firstWeekdayInThisMonth:(NSDate *)date; /** Description @param date date description @return return value description */ + (NSInteger)totaldaysInThisMonth:(NSDate *)date; /** Description @param date date description @return return value description */ + (NSInteger)totaldaysInMonth:(NSDate *)date; /** lastMonth @param date lastMonth @return lastMonth */ + (NSDate *)lastMonth:(NSDate *)date; /** nextMonth @param date date description @return nextMonth */ + (NSDate*)nextMonth:(NSDate *)date; /** 根据年月日 返回 NSDate @param year 年 @param month 月 @param day 日 @return 返回 NSDate */ + (NSDate *)dateInYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day; /** Description @param date date description @param hours hours description @param minutes minutes description @return return value description */ + (NSDate *)dateInDate:(NSDate *)date Hours:(NSInteger)hours minutes:(NSInteger)minutes; + (NSDate *)dateInDate:(NSDate *)date Hours:(NSInteger)hours minutes:(NSInteger)minutes second:(NSInteger)second; /** 返回农历的月 @param date date description @return return value description */ + (NSString*)getChineseCalendarMonthsWithDate:(NSDate *)date; /** 返回农历的天 @param date date description @return return value description */ + (NSString*)getChineseCalendarDaysWithDate:(NSDate *)date; /** 返回农历的年 @param date date description @return return value description */ + (NSString*)getChineseCalendarYearsWithDate:(NSDate *)date; /** 返回农历的全部 例子 甲子 十一月 初三 @param date date description @return return value description */ + (NSString*)getChineseCalendarWithDate:(NSDate *)date; /** 根据字符串返回 nsdate str⏬ dateFormat⏬ Tue May 31 18:20:45 +0800 2011 --->>>> EEE MMM dd HH:mm:ss ZZZZ yyyy 12/23/2015 12点08:03秒 --->>>> MM/dd/yyyy HH点mm:ss秒 2015-12-26 12:08:03 --->>>> yyyy-MM-dd HH:mm:ss 2015-12-26 --->>>> yyyy-MM-dd @param str str description @param dateFormat dateFormat description @return return value description */ + (NSDate *)getDateForString:(NSString *)str dateFormat:(NSString *)dateFormat; @end <|start_filename|>RCalendarPickerClass/RCollectionViewCell.h<|end_filename|> // // RCollectionViewCell.h // RCalendarPicker // // Created by roycms on 2016/11/16. // Copyright © 2016年 roycms. All rights reserved. // #import <UIKit/UIKit.h> #import "Masonry.h" #import "RRGB.h" @interface RCollectionViewCell : UICollectionViewCell /** 日 */ @property (nonatomic,strong)NSString *day; /** 农历 日 */ @property (nonatomic,strong)NSString *znDay; /** 是否选中 */ @property (nonatomic, assign)BOOL isSelected; /** 该天是否有绑定数据 */ @property (nonatomic, assign)BOOL isDataSource; /** 是否是今天 */ @property (nonatomic, assign)BOOL isToDay; /** day uicolor */ @property (nonatomic, assign)UIColor *dayLabelTextColor; /** 日期方格的背景颜色 */ @property (nonatomic, assign)UIColor *bgViewColor; @end <|start_filename|>RCalendarPickerClass/RCalendarPickerView.h<|end_filename|> // // RCalendarPickerView.h // RCalendarPicker // // Created by roycms on 2016/11/16. // Copyright © 2016年 roycms. All rights reserved. // #import <UIKit/UIKit.h> #import "Masonry.h" #import "RRGB.h" #import "DateHelper.h" #define LANGUAGE(LANValue) NSLocalizedStringFromTable(LANValue,@"RCalendarPickerLanguage", nil) #define MainScreenHeight ([UIScreen mainScreen].bounds.size.height) #define MainScreenWidth ([UIScreen mainScreen].bounds.size.width) @interface RCalendarPickerView : UIView<UICollectionViewDelegate , UICollectionViewDataSource,UIScrollViewDelegate> /** 选中时间 */ @property (nonatomic,strong) NSDate *selectDate; /** 绑定数据的数据源 */ @property (nonatomic,strong) NSArray *dataSource; /** 选择器的主题颜色 */ @property (nonatomic,assign) UIColor *thisTheme; /** 是否开启农历 */ @property (nonatomic,assign) BOOL isLunarCalendar; /** 选择日历时间成功后 complete block */ @property (nonatomic,copy) void(^complete)(NSInteger day, NSInteger month, NSInteger year ,NSDate *date); /** 取消按钮的block */ @property (nonatomic,copy) void(^cancel)(); /** 关闭 销毁日历 */ -(void)hide; @end <|start_filename|>params.json<|end_filename|> { "name": "Rcalendarpicker", "tagline": "RCalendarPicker 日历控件 ,日历选择控件,日历,日期选择", "body": "\r\n# RCalendarPicker\r\n\r\nRCalendarPicker Calendar calendar control, select control, calendar, date selection, the clock selection control. 日历控件 ,日历选择控件,日历,日期选择,时钟选择控件\r\n\r\n# Preview\r\n\r\n![预览1](https://roycms.github.io/RCalendarPicker/RCalendarPicker/Resource/calendar.jpg) \r\n![预览2](https://roycms.github.io/RCalendarPicker/RCalendarPicker/Resource/clock.jpg)\r\n\r\n# cocoapods\r\n\r\n```\r\npod 'RCalendarPicker'\r\n```\r\n\r\n# Use \r\n\r\ndefault: MainScreenWidth = 360 MainScreenHeight = 960\r\n```\r\n RCalendarPickerView *calendarPicker = [[RCalendarPickerView alloc]initWithFrame:CGRectMake(0, 0, MainScreenWidth, MainScreenHeight)];\r\n calendarPicker.today = [NSDate date]; //现在时间\r\n calendarPicker.date = calendarPicker.today; //选择时间\r\n calendarPicker.complete = ^(NSInteger day, NSInteger month, NSInteger year, NSDate *date){\r\n NSLog(@\"%d-%d-%d\", (int)year,(int)month,(int)day);\r\n };\r\n [self.view addSubview:calendarPicker];\r\n```\r\n\r\n# The lunar calendar \r\n```\r\nRCalendarPickerView *calendarPicker = [[RCalendarPickerView alloc]initWithFrame:CGRectMake(0, 0, MainScreenWidth, MainScreenHeight)];\r\n calendarPicker.isZn = YES; //开启农历\r\n calendarPicker.today = [NSDate date]; //现在时间\r\n calendarPicker.date = calendarPicker.today; //选择时间\r\n calendarPicker.complete = ^(NSInteger day, NSInteger month, NSInteger year, NSDate *date){\r\n NSLog(@\"%d-%d-%d\", (int)year,(int)month,(int)day);\r\n };\r\n [self.view addSubview:calendarPicker];\r\n```\r\n\r\n# A clock dial effect\r\n```\r\n RClockPickerView *rClockPickerView = [[RClockPickerView alloc]initWithFrame:CGRectMake(0, 0, MainScreenWidth, MainScreenHeight)\r\n clockRadius:140\r\n clockCalibrationRadius:130];\r\n rClockPickerView.date = [NSDate date];\r\n rClockPickerView.complete = ^(NSInteger hours, NSInteger minutes, NSInteger noon){\r\n NSLog(@\"%d-%d-%d\", (int)hours,(int)minutes,(int)noon);\r\n \r\n };\r\n [self.view addSubview:rClockPickerView];\r\n```\r\n\r\n# calendar + clock use\r\n```\r\nRCalendarPickerView *calendarPicker = [[RCalendarPickerView alloc]initWithFrame:CGRectMake(0, 0, MainScreenWidth, MainScreenHeight)];\r\n calendarPicker.today = [NSDate date]; //现在时间\r\n calendarPicker.date = calendarPicker.today; //选择时间\r\n [self.view addSubview:calendarPicker];\r\n \r\n calendarPicker.complete = ^(NSInteger day, NSInteger month, NSInteger year, NSDate *date){\r\n NSLog(@\"%d-%d-%d\", (int)year,(int)month,(int)day);\r\n \r\n RClockPickerView *rClockPickerView = [[RClockPickerView alloc]initWithFrame:CGRectMake(0, 0, MainScreenWidth, MainScreenHeight)\r\n clockRadius:140\r\n clockCalibrationRadius:130];\r\n rClockPickerView.date = [NSDate date];\r\n rClockPickerView.complete = ^(NSInteger hours, NSInteger minutes, NSInteger noon){\r\n NSLog(@\"%d-%d-%d\", (int)hours,(int)minutes,(int)noon);\r\n \r\n NSDate *selectDate = [DateHelper dateInDate:date Hours:hours>12?hours%12:hours minutes:minutes];\r\n \r\n NSLog(@\"selectDate: %@\",selectDate);\r\n \r\n };\r\n [self.view addSubview:rClockPickerView];\r\n };\r\n\r\n```\r\n\r\n# TODO\r\n\r\n* 增加上下午的判断和参数处理\r\n* 增加主题定义\r\n* 增加选择年月的切换形式\r\n\r\n", "note": "Don't delete this file! It's used internally to help with page regeneration." }
op1000/RCalendarPicker
<|start_filename|>www/scripts/util/build.js<|end_filename|> 'use strict'; var wrapHtml = require('./wrap-html'); var resolve = require('./content-resolver'); var toStr = require('stream-to-string'); var str = require('string-to-stream'); var codepenInjector = require('./codepen-injector'); var metaTagInjector = require('./meta-tag-injector'); var metadata = require('../../metadata'); module.exports = build; function build (htmlpath, opts, cb) { opts = opts || {}; resolve(htmlpath, {defaultCss: opts.defaultCss || 'index.css'}, function (err, streams, meta) { if (err) { return cb(err); } var content = {}; var cnt = 0; var total = 0; var streamNames = ['html', 'css', 'js']; for (var i = 0; i < streamNames.length; i++) { if (streams[streamNames[i]]) { (function(stream) { total++; toStr(streams[stream], function (err, data) { if (err) { return cb(err); } content[stream]= data; complete(stream, data); }); }(streamNames[i])); } } function complete (name, data) { if (++cnt === total) { var html = content.html ? str(content.html) : null; var js = content.js ? str(content.js) : null; //var css = content.css ? str(content.css) : null; var out = wrapHtml(html)({ entry: opts.entry || 'bundle.js', title: opts.title || meta.title, js: js, css: meta.csspath }) if (opts.codepen) { out = out.pipe(codepenInjector(content, opts.externalJS)) } out = out.pipe(metaTagInjector(metadata.metaTags)); cb(null, out, meta); } } }); } <|start_filename|>www/scripts/util/wrap-stream.js<|end_filename|> 'use strict'; var through2 = require('through2'); module.exports = wrapStream; function wrapStream(prefix, inputStream, suffix) { var wrotePrefix = false; return inputStream.pipe(through2(function (chunk, enc, callback) { if (!wrotePrefix) { this.push(prefix); wrotePrefix = true; } this.push(chunk); callback(); }, function (cb) { this.push(suffix); cb(); })); } <|start_filename|>www/scripts/util/content-resolver.js<|end_filename|> 'use strict'; module.exports = resolve; var fs = require('fs'); var path = require('path'); function resolve (htmlPath, options, cb) { var htmlname = path.resolve(htmlPath); var dirname = path.dirname(htmlname); var basename = path.basename(htmlname, path.extname(htmlname)); var jsname = path.resolve(dirname, basename + '.js'); var cssname = path.resolve(dirname, basename + '.css'); fs.access(cssname, fs.F_OK, function (err) { if (err) { cssname = options.defaultCss } doResolve(); }); function doResolve () { var data = { htmlname: htmlname, dirname: dirname, basename: basename, jsname: jsname, cssname: cssname, cssrel: path.basename(cssname, dirname), jsrel: path.basename(jsname, dirname) }; var streams = { html: fs.createReadStream(htmlname), js: fs.createReadStream(jsname), css: fs.createReadStream(cssname) }; var completeCnt = 0; function complete () { completeCnt++; if (completeCnt === Object.keys(streams).length) { cb(null, streams, data); } } for (var sstream in streams) { (function (stream) { streams[stream].on('error', function () { streams[stream] = null; complete(); }).on('open', complete); }(sstream)); } } } <|start_filename|>www/scripts/util/build-dist.js<|end_filename|> 'use strict'; var build = require('./build'); var glob = require('glob'); var path = require('path'); var fs = require('fs'); module.exports = buildDist; function buildDist (config, cb) { glob(config.pattern, function(err, files) { var i = 0; function next () { (function (file) { console.log('Processing input: "' + file + '"'); var opts = {}; opts.codepen = !!config.codepen; opts.defaultCss = config.defaultCss || 'styles.css'; if (config.externalJS) { opts.externalJS = config.externalJS; } build(file, opts, function(err, stream, meta) { if (err) { console.error(err); return; } stream.on('end', function () { if (i < files.length) { setImmediate(next); } else { cb && cb(null); } }); var pathname = path.resolve(process.cwd(), file); var localpath = path.basename(pathname, meta.dirname); var dest = path.resolve(config.destpath, localpath); console.log('Writing output: "' + dest + '"\n'); stream.pipe(fs.createWriteStream(dest)); }); }(files[i++])); } next(); }); } <|start_filename|>www/scripts/build-dist.js<|end_filename|> 'use strict'; var buildDist = require('./util/build-dist'); var argv = require('minimist')(process.argv.slice(2)); var xtend = require('xtend'); var awsConfig = require('./util/aws-config'); var awsCreds = require('../aws-credentials'); var path = require('path'); var meta = require('../metadata'); var opts = xtend(meta, { isSnapshot: !!argv.snapshot, bucket: argv.bucket, codepen: !!argv.codepen, }); meta.isSnapshot = !!argv.snapshot; meta.bucket = argv.bucket; var config = awsConfig(meta); buildDist({ pattern: argv.input || 'www/src/*.html', destpath: path.resolve(process.cwd(), argv.dest) }); <|start_filename|>www/scripts/util/html-stream.js<|end_filename|> 'use strict'; var hyperstream = require('hyperstream'); var html = require('simple-html-index'); var escape = require('escape-html'); module.exports = htmlStream; function htmlStream (opts) { opts = opts || {}; var h = html({ css: opts.css, entry: opts.entry, favicon: true, }); var head = { }; var meta = ''; if (opts.meta) { for (var name in opts.meta) { if (opts.meta.hasOwnProperty(name)) { var content = opts.meta[name]; meta += '<meta name="' + escape(name) + '" content="' + escape(content) + '" />'; } } } var content = { head: { _appendHtml: meta, }, }; if (opts.html) { content.body = {_appendHtml: opts.html} } var result = h.pipe(hyperstream(content)); if (opts.js) { result = result.pipe(hyperstream({ body: { _appendHtml: opts.js } })); } return result; }; <|start_filename|>www/scripts/util/wrap-html.js<|end_filename|> 'use strict'; var fs = require('fs'); var str = require('string-to-stream'); var htmlStream = require('./html-stream'); var wrapStream = require('./wrap-stream'); module.exports = wrapHtml; function wrapHtml (inputHtml) { return function (opts) { var jsStream; opts = opts || {}; if (opts.js) { if (typeof opts.js === 'string') { jsStream = str(opts.js); } else { jsStream = opts.js; } jsStream = wrapStream('<script>\nwindow.onload = function () {\n', jsStream, '\n};\n</script>'); } return htmlStream({ meta: { site: 'Your website name', title: opts.title, }, html: inputHtml, entry: opts.entry || 'static.js', css: opts.css || 'styles.css', js: jsStream }); }; }; <|start_filename|>www/scripts/util/meta-tag-injector.js<|end_filename|> 'use strict'; var hyperstream = require('hyperstream'); var escape = require('escape-html'); module.exports = metaTagInjector; function metaTagInjector (metaTags) { var metaTagHtml = ''; for (var name in metaTags) { if (metaTags.hasOwnProperty(name)) { metaTagHtml += '<meta name="' + escape(name) + '" content="' + escape(metaTags[name]) + '" />\n'; } } return hyperstream({ head: { _appendHtml: metaTagHtml } }); } <|start_filename|>www/scripts/util/aws-config.js<|end_filename|> 'use strict'; module.exports = awsConfig; function awsConfig (opts) { var config = {}; var appName = opts.appName; var prefix = appName + '/'; if (opts.isSnapshot) { prefix = 'snapshots/' + prefix + (+new Date()) + '/'; } if (opts.webHost) { var baseUrl = opts.webHost + prefix; } else { var baseUrl = 'http://' + opts.bucket + '.s3-website-us-east-1.amazonaws.com/' + prefix; } config.prefix = prefix; config.baseUrl = baseUrl; config.bucket = opts.bucket; config.isSnapshot = !!opts.isSnapshot; return config; }
rreusser/plotly-demos
<|start_filename|>synner-core/src/test/java/edu/nyu/dtl/synner/core/infer/InferTest.java<|end_filename|> package edu.nyu.dtl.synner.core.infer; import org.junit.*; import java.sql.SQLException; import java.util.Arrays; import java.util.List; public class InferTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } private void testTemplate(List<String> values, String id, String contains) throws SQLException { InferRequest request = new InferRequest(); request.setId(id); request.setValues(values); InferResponse response = Infer.infer(request); System.out.println(values); System.out.println(response.getInferredTypes()); } @Test @Ignore public void testInfer() throws SQLException { List<String> values = Arrays.asList("Miro", "Marco","Jonathan","Nicholas","Abdul"); testTemplate(values,"id1", "names/all"); values = Arrays.asList("Mumbai", "Delhi", "Florence", "Smith"); testTemplate(values,"id2", "cities/all"); values = Arrays.asList("Karko", "Mirx", "Jokn"); testTemplate(values,"id3", null); values = Arrays.asList("x", "s", "Mumbai"); testTemplate(values,"id4", null); } } <|start_filename|>synner-server/src/main/resources/static/js/directives/field-error-missings.js<|end_filename|> angular.module('Synner') .directive('fieldErrorMissings', ['$rootScope', '$timeout', 'Model', 'Functions', 'Parameters', function ($rootScope, $timeout, Model, Functions, Parameters) { return { templateUrl: 'fragments/field-error-missings.html', replace: true, restriction: 'E', scope: { field: '=' }, link: function ($scope, element, attrs) { function updateResult() { if (!$scope.inputRead) return; $scope.field.missingRows = $scope.fieldMissings; $scope.field.errorRows = $scope.fieldErrors; $scope.field.editingMissingError = false; $scope.inputRead = true; } function readResult() { if ($scope.inputRead) return; $scope.missingRows = $scope.field.missingRows === undefined ? 0 : $scope.field.missingRows; $scope.errorRows = $scope.field.errorRows === undefined ? 0 : $scope.field.errorRows; $scope.inputRead = true; } $scope.approveChanges = function () { updateResult(); }; $scope.discargeChanges = function () { Functions.clearFieldsHighlights(); $scope.fieldMissings = $scope.field.missingRows || 0; $scope.fieldErrors = $scope.field.errorRows || 0; $scope.field.editingMissingError = false; $scope.inputRead = true; }; $scope.missingNumberChange = function () { console.log('missing number change', $scope.missingRows); }; $scope.$watch('field.editingMissingError', function (editingMissingError) { if (editingMissingError) { $timeout(function () { element.find('input.field-errors-number').focus(); }); } else { $scope.discargeChanges(); $scope.$parent.selectField($scope.field); } }); $scope.$watchGroup(['fieldMissings', 'fieldErrors'], function () { }); $scope.$watchGroup(['field.fieldErrors', 'field.fieldMissings'], function () { $scope.inputRead = false; readResult(); }); } }; }]); <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/parser/RelationParser.java<|end_filename|> package edu.nyu.dtl.synner.core.parser; import com.fasterxml.jackson.databind.JsonNode; import edu.nyu.dtl.synner.core.datamodel.Field; import edu.nyu.dtl.synner.core.datamodel.ColumnType; import edu.nyu.dtl.synner.core.datamodel.Table; import edu.nyu.dtl.synner.core.generators.*; import java.util.*; import edu.nyu.dtl.synner.core.generators.VisualRelationshipGen.Approximation; import edu.nyu.dtl.synner.core.generators.domain.DomainGen; import edu.nyu.dtl.synner.core.generators.numerical.CustomGen; import edu.nyu.dtl.synner.core.generators.numerical.ExponentialGen; import edu.nyu.dtl.synner.core.generators.numerical.GaussianGen; import edu.nyu.dtl.synner.core.generators.numerical.UniformGen; import javax.script.ScriptException; import static edu.nyu.dtl.synner.core.parser.Commons.readValue; public class RelationParser { public RelationParser() { } public Table readModel(JsonNode rootNode) throws ScriptException { Map<String, Field> fields = new LinkedHashMap<>(); readFields(rootNode, fields); readRelationships(rootNode, fields); readGenerators(rootNode, fields); return new Table(fields.values()); } private void readFields(JsonNode rootNode, Map<String, Field> fields) throws ScriptException { Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields(); int pos = 0; while (fieldsIterator.hasNext()) { Map.Entry<String, JsonNode> fieldNode = fieldsIterator.next(); fields.put(fieldNode.getKey(), readField(pos++, fieldNode.getKey(), fieldNode.getValue())); } } private Field readField(int pos, String name, JsonNode jsonNode) throws ScriptException { if (jsonNode.has("pos")) pos = jsonNode.get("pos").asInt(); String filter = null; int errorRows = 0; int missingRows = 0; if (jsonNode.has("filter")) filter = jsonNode.get("filter").asText(); if (jsonNode.has("errorRows")) errorRows = jsonNode.get("errorRows").asInt(); if (jsonNode.has("missingRows")) missingRows = jsonNode.get("missingRows").asInt(); ColumnType type = jsonNode.has("type") ? ColumnType.fromReadableName(jsonNode.get("type").asText()) : null; return new Field(name, type, filter, missingRows, errorRows, pos); } private void readGenerators(JsonNode rootNode, Map<String, Field> fields) { Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields(); while (fieldsIterator.hasNext()) { Map.Entry<String, JsonNode> fieldNode = fieldsIterator.next(); Field field = fields.get(fieldNode.getKey()); field.setGenerator(readGenerator(fieldNode.getValue().get("generator"), field)); } } private void readRelationships(JsonNode rootNode, Map<String, Field> fields) { Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields(); while (fieldsIterator.hasNext()) { Map.Entry<String, JsonNode> fieldNode = fieldsIterator.next(); Field field = fields.get(fieldNode.getKey()); if (fieldNode.getValue().has("dependencies")) { Iterator<JsonNode> dependencies = fieldNode.getValue().get("dependencies").elements(); while (dependencies.hasNext()) { field.addDependency(fields.get(dependencies.next().asText())); } } } } private Generator readGenerator(JsonNode jsonNode, Field field) { if (jsonNode.has("value")) { return readConstant(jsonNode.get("value")); } else if (jsonNode.has("regexp")) { return readRegexp(jsonNode); } else if (jsonNode.has("domain")) { return readDomain(jsonNode, field); } else if (jsonNode.has("cases")) { return readCases(jsonNode); } else if (jsonNode.has("distribution")) { return readDistribution(jsonNode); } else if (jsonNode.has("function")) { return readFunction(jsonNode.get("function"), field); } else if (jsonNode.has("switch")) { return readSwitchMap(jsonNode.get("switch"), field); } else if (jsonNode.has("visrel")) { return readVisRel(jsonNode.get("visrel"), field); } else if (jsonNode.has("timerange")) { return readTimeRange(jsonNode.get("timerange"), field); } else if (jsonNode.has("daterange")) { return readDateRange(jsonNode.get("daterange"), field); } else { return new ConstantGen<>(null); } } private Generator readGenerator(JsonNode jsonNode) { return readGenerator(jsonNode, null); } private Generator<String> readDomain(JsonNode jsonNode, Field field) { int joinIdx = -1; if (jsonNode.has("join")) { String fieldName = jsonNode.get("join").asText(); List<Field> dependencies = field.getDependencies(); for (int i = 0; i < dependencies.size(); i++) { if (dependencies.get(i).getName().equals(fieldName)) { joinIdx = i; break; } } } JsonNode domain = jsonNode.get("domain"); if (domain.isTextual()) { return new DomainGen(domain.asText(), joinIdx); } else { DomainGen dg = new DomainGen(domain.get("name").asText(), joinIdx); if (domain.has("subcategory-name") && domain.has("subcategory-value") && !domain.get("subcategory-name").isNull() && !domain.get("subcategory-value").isNull()) { dg.setSubcategory(domain.get("subcategory-name").asText(), domain.get("subcategory-value").asText()); } return dg; } } private Generator<Double> readDistribution(JsonNode jsonNode) { JsonNode type = jsonNode.get("distribution"); switch (type.asText()) { case "uniform": double min = jsonNode.get("min").asDouble(); double max = jsonNode.get("max").asDouble(); return new UniformGen(min, max); case "gaussian": double mean = jsonNode.get("mean").asDouble(); double stdev = jsonNode.get("stdev").asDouble(); return new GaussianGen(mean, stdev); case "exponential": double rate = jsonNode.get("rate").asDouble(); return new ExponentialGen(rate); case "custom": Iterator<JsonNode> histogramIt = jsonNode.get("histogram").elements(); ArrayList<Double> histogramList = new ArrayList<>(); while (histogramIt.hasNext()) { histogramList.add(histogramIt.next().asDouble()); } Double[] histograms = new Double[histogramList.size()]; histograms = histogramList.toArray(histograms); double minCustom = jsonNode.get("min").asDouble(); double maxCustom = jsonNode.get("max").asDouble(); return new CustomGen(histograms, minCustom, maxCustom); default: throw new IllegalArgumentException("distribution type not recognised"); } } private Generator readCases(JsonNode jsonNode) { JsonNode casesNode = jsonNode.get("cases"); if (!casesNode.isArray()) throw new IllegalArgumentException("The 'cases' field must be an array"); Generator[] cases = readGeneratorsArray(casesNode); double ratioSum = 0; double[] ratios = null; if (jsonNode.has("ratios")) { JsonNode ratiosNode = jsonNode.get("ratios"); if (ratiosNode.size() != cases.length) throw new IllegalArgumentException("the 'ratios' array must have the same size of the 'cases' array"); ratios = new double[ratiosNode.size()]; Iterator<JsonNode> ratiosIt = ratiosNode.elements(); int i = 0; while (ratiosIt.hasNext()) { double val = ratiosIt.next().asDouble(); ratios[i++] = val; ratioSum += val; } } return ratioSum > 0 ? new CasesCustomDistGen(cases, ratios) : new CasesGen(cases); } private Generator readConstant(JsonNode jsonNode) { return new ConstantGen(readValue(jsonNode)); } private Generator readRegexp(JsonNode jsonNode) { return new StringGen(jsonNode.get("regexp").asText()); } private Generator readFunction(JsonNode jsonNode, Field field) { if (!jsonNode.isArray()) { try { return new FunctionGenerator(jsonNode.asText(), field.getDependencies()); } catch (ScriptException e) { throw new IllegalArgumentException("The defined function contains errors", e); } } try { Generator[] cases = new Generator[jsonNode.size()]; Iterator<JsonNode> elementsIt = jsonNode.elements(); double[] ratios = new double[jsonNode.size()]; int i = 0; while (elementsIt.hasNext()) { JsonNode el = elementsIt.next(); cases[i] = new FunctionGenerator(el.get("expression").asText(), field.getDependencies()); double val = el.get("freq").asDouble(); ratios[i] = val; i++; } return new CasesCustomDistGen(cases, ratios); } catch (ScriptException e) { throw new IllegalArgumentException("The defined function contains errors", e); } } private Generator readSwitchMap(JsonNode jsonNode, Field field) { try { Iterator<JsonNode> casesIt = jsonNode.elements(); SwitchGen<Comparable> cg = new SwitchGen<>(field.getDependencies()); while (casesIt.hasNext()) { JsonNode caseEl = casesIt.next(); if (caseEl.has("case")) { cg.addCondition(caseEl.get("case").asText(), readGenerator(caseEl.get("then"), field)); } else if (caseEl.has("default")) { cg.setElse(readGenerator(caseEl.get("default"), field)); } } return cg; } catch (ScriptException e) { throw new IllegalArgumentException("The defined conditional expression contains errors", e); } } private Generator readDateRange(JsonNode jsonNode, Field field) { int fromValue = jsonNode.get("from").intValue(); int toValue = jsonNode.get("to").intValue(); return new DateRangeGen(fromValue, toValue); } private Generator readTimeRange(JsonNode jsonNode, Field field) { int fromValue = jsonNode.get("from").intValue(); int toValue = jsonNode.get("to").intValue(); return new TimeRangeGen(fromValue, toValue); } private Generator readVisRel(JsonNode jsonNode, Field field) { double[] inValues = toDoubleArray(readValuesArray(jsonNode.get("in"))); double[] outValues = toDoubleArray(readValuesArray(jsonNode.get("out"))); if (inValues.length != outValues.length) throw new IllegalArgumentException("Visual relationship must have" + "the same number of elements in the in and out arrays"); int inputFieldIdx = -1; String inputFieldName = jsonNode.get("input-field").asText(); List<Field> dependencies = field.getDependencies(); for (int i = 0; i < dependencies.size(); i++) { if (dependencies.get(i).getName().equals(inputFieldName)) { inputFieldIdx = i; break; } } if (inputFieldIdx == -1) throw new IllegalArgumentException("Invalid input field for visual relationship"); double inMin = jsonNode.has("in-min") ? Double.valueOf(jsonNode.get("in-min").asText()) : 0; double inMax = jsonNode.has("in-max") ? Double.valueOf(jsonNode.get("in-max").asText()) : 1; double outMin = jsonNode.has("out-min") ? Double.valueOf(jsonNode.get("out-min").asText()) : 0; double outMax = jsonNode.has("out-max") ? Double.valueOf(jsonNode.get("out-max").asText()) : 1; double noises = jsonNode.has("noises") ? Double.valueOf(jsonNode.get("noises").asText()) : 0.05; if (noises <= 0.01) noises = 0.01; Approximation apprx = jsonNode.has("approximation") ? Approximation.valueOf(jsonNode.get("approximation").asText()) : Approximation.low; return new VisualRelationshipGen(inputFieldIdx, inValues, outValues, inMin, inMax, outMin, outMax, apprx, noises); } private Generator[] readGeneratorsArray(JsonNode elements) { if (!elements.isArray()) throw new IllegalArgumentException("expected array"); Generator[] res = new Generator[elements.size()]; Iterator<JsonNode> elementsIt = elements.elements(); int i = 0; while (elementsIt.hasNext()) res[i++] = readGenerator(elementsIt.next()); return res; } private double[] toDoubleArray(Comparable[] array) { double[] res = new double[array.length]; for (int i = 0; i < res.length; i++) res[i] = (double) array[i]; return res; } private Comparable[] readValuesArray(JsonNode elements) { if (!elements.isArray()) throw new IllegalArgumentException("expected array"); Comparable[] res = new Comparable[elements.size()]; Iterator<JsonNode> elementsIt = elements.elements(); int i = 0; while (elementsIt.hasNext()) res[i++] = readValue(elementsIt.next()); return res; } } <|start_filename|>synner-server/src/main/resources/static/js/directives/generator-function.js<|end_filename|> angular.module('Synner') .directive('generatorFunction', ['Model', 'Functions', '$rootScope', 'Parameters', function (Model, Functions, $rootScope, Parameters) { return { templateUrl: 'fragments/generator-function.html', replace: true, restriction: 'E', scope: { _result: '=result', // where we will put the result of generation specifications field: '=' }, link: function ($scope, element, attrs) { $scope.inputRead = false; $scope.cases = [ // {expression: '42', freq: 42}, ]; $scope.usedFieldsNotInDependencies = []; $scope.expressionError = null; function insertAtCursor(field, val) { if (field.selectionStart || field.selectionStart === '0') { field.value = field.value.substring(0, field.selectionStart) + val + field.value.substring(field.selectionEnd, field.value.length); } else { field.value += val; } $scope.selectedCase.expression = field.value; } $scope.selectInput = function (ecase, e) { $scope.selectedCase = ecase; $scope.selectedInput = e.target; }; $scope.add = function (exp) { insertAtCursor($scope.selectedInput, exp); }; $scope.increaseFreq = function (scase) { scase.freq++; }; $scope.decreaseFreq = function (scase) { scase.freq--; }; function functionExpressionUpdated() { $scope.usedFields = []; $scope.usedFieldsNotInDependencies = []; for (var idx = 0; idx < $scope.cases.length; idx++) { if ($scope.cases[idx].expression === null || $scope.cases[idx].expression.length === 0) continue; var expression = $scope.cases[idx].expression; try { var functionAvailableFields = []; for (var i = 0; i < Model.fields.length; i++) { // We check that the field in the model is in the field's dependencies var found = false; for (var dep of $scope.field.dependencies) { if (dep.id === Model.fields[i].id) { found = true; break; } } functionAvailableFields.push(Model.fields[i]); } var compiledFunction = Functions.compileFunction(expression, functionAvailableFields); // just so we check syntax errors compiledFunction.apply(null, Functions.createMockArguments(functionAvailableFields)); var usedFields = Functions.extractUsedFields(expression, $scope.field); var usedFieldsNotInDependencies = []; for (var usedField of usedFields) { var found = false; for (var field of $scope.field.dependencies) { if (field.id === usedField.id) { found = true; break; } } if (!found) usedFieldsNotInDependencies.push(usedField); } for (var uf of usedFields) { var found = false; for (var suf of $scope.usedFields) { if (suf.id === uf.id) { found = true; break; } } if (!found) $scope.usedFields.push(uf); } for (var uf of usedFieldsNotInDependencies) { var found = false; for (var suf of $scope.usedFieldsNotInDependencies) { if (suf.id === uf.id) { found = true; break; } } if (!found) $scope.usedFieldsNotInDependencies.push(uf); } if ($scope.usedFieldsNotInDependencies.length === 0) { updateResult(); } else { throw "ReferenceError: " + $scope.usedFieldsNotInDependencies[0].name + " is not defined"; } $scope.expressionError = null; } catch (e) { $scope.expressionError = e; } } } // Update the frequencies sum to calculate the probabilities function updateFreqSum () { $scope.freqSum = 0; for (var i = 0; i < $scope.cases.length - 1; i++) { if ($scope.cases[i].expression === null) continue; $scope.freqSum += $scope.cases[i].freq; } for (var i = 0; i < $scope.cases.length - 1; i++) { if ($scope.cases[i].expression === null || $scope.cases[i].expression === undefined || $scope.cases[i].expression.length === 0) continue; $scope.cases[i].prob = $scope.cases[i].freq / $scope.freqSum; } } function updateResult() { if (!$scope.inputRead) return; var generator = { 'function': [] }; var genCases = generator.function; for (var el of $scope.cases) { if (el.expression === null || el.expression === undefined || el.expression.length === 0) continue; genCases.push({ expression: el.expression, freq: el.freq }); } $scope._result.obj = generator; $scope.inputRead = true; } function readResult() { if ($scope.inputRead) return; var obj = $scope._result.obj; if (obj && Model.isFunction(obj)) { for (var idx = 0; idx < obj.function.length; idx++) { $scope.cases[idx] = { expression: obj.function[idx].expression, freq: obj.function[idx].freq }; } } else { $scope.cases[0] = { expression: $scope.field.type === 'string' ? "'A'" : '0', freq: 1 }; } $scope.inputRead = true; } $scope.$watch('cases', function () { if (!$scope.inputRead) return; // Check if there are void elements to delete for (var i = 0; i < $scope.cases.length - 1; i++) { if (($scope.cases[i].expression === null || $scope.cases[i].expression.length === 0) && $scope.cases.length > 2) $scope.cases.splice(i, 1); } // Check if the last element is full (so we can add a new empty element) if ($scope.cases.length === 0 || $scope.cases[$scope.cases.length - 1].expression !== null) { $scope.cases.push({expression: null, freq: 1}); } updateFreqSum(); functionExpressionUpdated(); }, true); $scope.$watchCollection('field.dependencies', function () { functionExpressionUpdated(); }); $scope.$watch('_result', function () { $scope.inputRead = false; $scope.cases = []; readResult(); }); } }; }]); <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/generators/domain/DomainsRelationship.java<|end_filename|> package edu.nyu.dtl.synner.core.generators.domain; import java.util.Objects; public class DomainsRelationship { String domainFrom; String domainTo; public DomainsRelationship(String domainFrom, String domainTo) { this.domainFrom = domainFrom; this.domainTo = domainTo; } public String getDomainFrom() { return domainFrom; } public void setDomainFrom(String domainFrom) { this.domainFrom = domainFrom; } public String getDomainTo() { return domainTo; } public void setDomainTo(String domainTo) { this.domainTo = domainTo; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DomainsRelationship that = (DomainsRelationship) o; return Objects.equals(domainFrom, that.domainFrom) && Objects.equals(domainTo, that.domainTo); } @Override public int hashCode() { return Objects.hash(domainFrom, domainTo); } } <|start_filename|>synner-server/src/main/resources/static/js/directives/visual-summary.js<|end_filename|> angular.module('Synner') .directive('visualSummary', ['$rootScope', '$timeout', 'Model', 'Parameters', function ($rootScope, $timeout, Model, Parameters) { return { templateUrl: 'fragments/visual-summary.html', replace: true, restriction: 'E', scope: { field: '=' }, link: function ($scope, element, attrs) { $scope.HIST_BARS = 20; $scope.MAX_STR_HIST_SIZE = 60; function updateResult() { updateGraphSummary(); updateSummary(); } function numericalValue(val, type) { if (type === 'date') { return Model.getIntFromDate(val); } else if (type === 'time') { return Model.getIntFromTime(val); } else if (type === 'string') { return parseFloat(val); } else { return val; } } function updateSummary() { var values = []; for (var j = 0; j < Model.data.length; j++) { var val = Model.data[j][$scope.field.id]; if (val === null) continue; values.push(numericalValue(val.v, $scope.field.type)); } $scope.textSummary = ' '; if ($scope.field.type === 'decimal' || $scope.field.type === 'integer') { if (values.length === 0) return; var mean = jStat.mean(values); var stdv = jStat.stdev(values); if (mean && stdv) { $scope.textSummary = 'Mean: ' + mean.toFixed(2) + ', Stdev: ' + stdv.toFixed(2); } } } function initHistogram() { $scope.svg = d3.select(element.find('svg')[0]); $scope.hist = $scope.svg.append('g'); updateHistogram(); } function updateHistogram() { $scope.histogramWidth = $scope.svg.node().getBoundingClientRect().width; $scope.histogramHeight = $scope.svg.node().getBoundingClientRect().height; $scope.barWidth = $scope.histogramWidth / $scope.values.length; $scope.x = d3.scale.ordinal() .domain($scope.values.map(function (d) { return d.id; })) .rangeBands([0, $scope.histogramWidth], 0, 0); $scope.y = d3.scale.linear() .range([$scope.histogramHeight, 0]) .domain([0, d3.max($scope.values, function (d) { return d.freq; })]); } function calculateFrequencies() { $scope.values = []; var valNum = 0, j, val; var missingVals = 0, errorVals = 0; if ($scope.field.type === 'string') { $scope.strMap = new Map(); var dataSize = Math.min($scope.MAX_STR_HIST_SIZE, Model.data.length); for (j = 0; j < dataSize; j++) { val = Model.data[j][$scope.field.id]; valNum++; if (val === null || val.v === null) { missingVals++; continue; } else if (val.s === 'error') { errorVals++; continue; } var num = $scope.strMap.get(val.v); $scope.strMap.set(val.v, num === undefined ? 1 : num + 1); } var i = 0; $scope.labels = Array.from($scope.strMap.keys()).sort(); for (var k of $scope.labels) { $scope.values.push({id: i, freq: valNum === 0 ? 0 : $scope.strMap.get(k) / valNum, s: null}); i++; } if (missingVals > 0) { $scope.values.push({ id: i++, freq: valNum === 0 ? 0 : missingVals / valNum, s: 'missing' }); } if (errorVals > 0) { $scope.values.push({ id: i, freq: valNum === 0 ? 0 : errorVals / valNum, s: 'error' }); } } else { var max = _.max(Model.data, function (r) { return r[$scope.field.id] === null ? null : r[$scope.field.id].v; }); if (max[$scope.field.id] == null) return; else max = numericalValue(max[$scope.field.id].v, $scope.field.type); var min = _.min(Model.data, function (r) { return r[$scope.field.id] === null ? null : r[$scope.field.id].v; }); if (min[$scope.field.id] == null) return; else min = numericalValue(min[$scope.field.id].v, $scope.field.type); var hist_bars = $scope.HIST_BARS; if ($scope.field.type === 'integer' && max - min + 1 < $scope.HIST_BARS) { hist_bars = max - min + 1; } for (j = 0; j < hist_bars; j++) $scope.values[j] = { id: j, freq: 0, bucketMin: min + (max - min) / hist_bars * j, bucketMax: min + (max - min) / hist_bars * (j + 1) }; for (j = 0; j < Model.data.length; j++) { val = Model.data[j][$scope.field.id]; if (!val || val.v === null) continue; valNum++; var val = $scope.values[Math.floor( ((numericalValue(val.v, $scope.field.type) - min) / (max - min)) * (hist_bars - 1) )]; if (val) val.freq++; } if (valNum > 0) { for (j = 0; j < hist_bars; j++) $scope.values[j].freq /= valNum; } } } function updateGraphSummary() { calculateFrequencies(); if ($scope.values.length === 0) return; if (!$scope.svg) { initHistogram(); } else { updateHistogram(); } var bar = $scope.hist.selectAll('.bar').data($scope.values); bar.enter().append('rect'); bar.exit().remove(); bar.attr('class', 'bar') .classed('missing', function (d) { return d.s === 'missing' }) .classed('error', function (d) { return d.s === 'error' }) .transition() .duration(1000) .attr('x', function (d) { return $scope.x(d.id); }) .attr('y', function (d) { return $scope.y(d.freq); }) .attr('width', $scope.x.rangeBand()) .attr('height', function (d) { return $scope.histogramHeight - $scope.y(d.freq); }); element.find('.visual-summary-tootip').remove(); var tooltip = d3.select('.visual-summary') .append('div') .attr('class', 'visual-summary-tootip') .style('position', 'absolute') .style('z-index', '10') .style('font-size', '12px') .style('font-weight', 'normal') .style('background', '#ddd') .style('padding', '4px') .style('visibility', 'hidden'); bar.on('mouseover', function (d, i) { var text; var freq = Math.round(d.freq * Model.data.length); if ($scope.values[i].s === 'missing') { text = 'Missing'; } else if ($scope.values[i].s === 'error') { text = 'Error'; } else if ($scope.field.type === 'string') { text = $scope.labels[d.id]; } else { var minBar = $scope.values[i].bucketMin; var maxBar = $scope.values[i].bucketMax; if ($scope.field.type === 'decimal' && minBar && maxBar) { text = minBar.toPrecision(3) + ' to ' + maxBar.toPrecision(3); } else if ($scope.field.type === 'integer') { text = Math.round(minBar) + ' to ' + Math.round(maxBar); } else if ($scope.field.type === 'time') { text = Model.strFormatTimeFromTime(Model.getTimeFromInt(minBar)) + ' to ' + Model.strFormatTimeFromTime(Model.getTimeFromInt(maxBar)); } else if ($scope.field.type === 'date') { text = Model.strFormatDateFromDate(Model.getDateFromInt(minBar)) + ' to ' + Model.strFormatDateFromDate(Model.getDateFromInt(maxBar)); } } return tooltip .html('<strong>' + text + '</strong>' + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(' + Math.round(d.freq * 100) + '%)') .style('top', (d3.event.pageY - 80) + 'px') .style('left', (d3.event.pageX + 10) + 'px') .style('visibility', 'visible'); }).on('mouseleave', function () { return tooltip.style('visibility', 'hidden'); }); } $scope.$watch(function () { var values = []; for (var f of Model.data) { values.push(f[$scope.field.id]); } return values; }, updateResult, true); } }; }]); <|start_filename|>synner-server/src/main/resources/static/js/directives/generator-visrel.js<|end_filename|> angular.module('Synner') .directive('generatorVisrel', ['Model', 'Functions', '$rootScope', '$timeout', 'Parameters', function (Model, Functions, $rootScope, $timeout, Parameters) { return { templateUrl: 'fragments/generator-visrel.html', replace: true, restriction: 'E', scope: { _result: '=result', // where we will put the result of generation specifications field: '=' }, link: function ($scope, element, attrs) { $scope.inputRead = false; $scope.paper = null; $scope.simplot = { MARGIN: {top: 5, right: 20, bottom: 25, left: 45} }; // everything about the simulation plot, svg, path, simulation arrays... $scope.selectedInputField = $scope.field.dependencies[0]; $scope.possibleInputFields = []; var GRAPH_PADDING = 0, LINE_X_POINTS = 10, LINE_WIDTH = 3, MAX_DATA_VOL = 500, MAIN_LINE_COLOR = '#1b6da8'; var $canvas = element.find('canvas'); var height = $canvas.height(); var width = $canvas.width(); $scope.sourceMin = null; $scope.sourceMax = null; $scope.targetMin = null; $scope.targetMax = null; $scope.noises = 1; $scope.path = undefined; $scope.visrelPoints = null; $scope.simSamples = []; $scope.simSamplesBoundaries = { min : null, max: null}; $scope.pathNoises = []; $scope.noisesTranslation = function (x, uiToRaw) { if (uiToRaw) return x * x / 40000; return Math.sqrt(x) * Math.sqrt(40000); }; $scope.noiseToNoisePerc = function (x) { // from the noise in the model ($scope.noise, which goes from 0 to 200) to [0,1] return x * x / 40000; }; $scope.noisePercToNoise = function (x) { // from the noise [0,1] to the noise in the model [0,200] return Math.sqrt(x) * Math.sqrt(40000); }; $scope.noisePercToDataRangeNoise = function (x) { // from the noise [0,1] to the noise in related to the current data range [$scope.targetMin, scope.targetMax] return x * 2 * ($scope.targetMax - $scope.targetMin); }; // Standard Normal variate using Box-Muller transform. function randn_bm() { var u = 0, v = 0; while (u === 0) u = Math.random(); //Converting [0,1) to (0,1) while (v === 0) v = Math.random(); return Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v); } function simulateGenerations() { var discretisation = 100; var discretisationBucketSize = 1 / discretisation; var visrelConf = $scope._result.obj.visrel; $scope.simSamplesBoundaries.min = $scope.targetMin; $scope.simSamplesBoundaries.max = $scope.targetMax; $scope.simSamples = []; $scope.simSamplesPosAreas = []; $scope.simSamplesNegAreas = []; if (visrelConf.in.length === 0) return; // empty sketch means no sim var dataVolume = Math.min(MAX_DATA_VOL, Model.dataVolume); var normalizedNoiseVal = $scope.noiseToNoisePerc($scope.noises); for (var i = 0; i < Model.experimentsNumber; i++) { var samples = []; var samplesPosAreas = [[0,0,0]]; var samplesNegAreas = [[0,0,0]]; var discretisationBucket = 0; var currentMaxPt = {ptx: 0, pty: 0, ptyn: 0}; var currentMinPt = {ptx: 0, pty: 0, ptyn: 0}; for (var xi = 0; xi < dataVolume; xi++) { var ptx = xi / dataVolume + (1 / dataVolume / Model.experimentsNumber) * i; var pty = 0; var found = false; for (var pos = 0; pos < visrelConf.in.length; pos++) { if (visrelConf.in[pos] >= ptx) { found = true; pty = visrelConf.out[pos]; break; } } if (!found) pty = visrelConf.out[visrelConf.out.length - 1]; var ptyn = pty + randn_bm() * normalizedNoiseVal; samples.push([ptx, ptyn]); if (ptx >= (discretisationBucket + 1) * discretisationBucketSize) { if (currentMaxPt !== null) samplesPosAreas.push([currentMaxPt.ptx, currentMaxPt.pty, currentMaxPt.ptyn]); if (currentMinPt !== null) samplesNegAreas.push([currentMinPt.ptx, currentMinPt.pty, currentMinPt.ptyn]); currentMaxPt = null; currentMinPt = null; discretisationBucket++; } // if (currentMinPt === null) currentMinPt = {ptx: ptx, pty: pty, ptyn: ptyn}; // if (currentMaxPt === null) currentMaxPt = {ptx: ptx, pty: pty, ptyn: ptyn}; if (ptyn < pty) { if (currentMinPt === null || currentMinPt.ptyn > ptyn) { currentMinPt = {ptx: ptx, pty: pty, ptyn: ptyn}; } //samplesNegAreas.push([ptx, pty, ptyn]); } else { if (currentMaxPt === null || currentMaxPt.ptyn < ptyn) { currentMaxPt = {ptx: ptx, pty: pty, ptyn: ptyn}; } //samplesPosAreas.push([ptx, pty, ptyn]); } var ptyVal = pty * ($scope.targetMax - $scope.targetMin) + $scope.targetMin; var ptynVal = ptyn * ($scope.targetMax - $scope.targetMin) + $scope.targetMin; if ($scope.simSamplesBoundaries.min > ptyVal) $scope.simSamplesBoundaries.min = ptyVal; if ($scope.simSamplesBoundaries.min > ptynVal) $scope.simSamplesBoundaries.min = ptynVal; if ($scope.simSamplesBoundaries.max < ptyVal) $scope.simSamplesBoundaries.max = ptyVal; if ($scope.simSamplesBoundaries.max < ptynVal) $scope.simSamplesBoundaries.max = ptynVal; } if (currentMaxPt !== null) samplesPosAreas.push([currentMaxPt.ptx, currentMaxPt.pty, currentMaxPt.ptyn]); if (currentMinPt !== null) samplesNegAreas.push([currentMinPt.ptx, currentMinPt.pty, currentMinPt.ptyn]); samplesNegAreas.push([1,1,1]); samplesPosAreas.push([1,1,1]); $scope.simSamples.push(samples); $scope.simSamplesPosAreas.push(samplesPosAreas); $scope.simSamplesNegAreas.push(samplesNegAreas); } } function updateResult() { if (!$scope.inputRead) return; // Prevent changes on the distribution parameters to change the input, even before reading it $scope.visrelPoints = extractPoints(); var generator = { 'visrel': { 'input-field': $scope.selectedInputField.name, 'in': [], 'out': [], 'noises': $scope.noiseToNoisePerc($scope.noises), 'in-min': $scope.sourceMin, 'in-max': $scope.sourceMax, 'out-min': $scope.targetMin, 'out-max': $scope.targetMax, 'approximation': 'interpolate' } }; if ($scope.visrelPoints !== null) { for (var i = 0; i < $scope.visrelPoints.length; i++) { generator['visrel']['in'].push($scope.visrelPoints[i][0]); generator['visrel']['out'].push($scope.visrelPoints[i][1]); } } $scope._result.obj = generator; $scope.inputRead = true; } function readResult() { if ($scope.inputRead) return; var generator = $scope._result.obj; if (generator && Model.isVisualRelationship(generator)) { $scope.cleanSketch(); var cm = generator['visrel']; var inVals = cm['in']; var outVals = cm['out']; var inputField = cm['input-field']; $scope.selectedInputField = null; for (var dep of $scope.field.dependencies) { if (dep.name === inputField) { $scope.selectedInputField = dep; break; } } $scope.sourceMin = cm['in-min']; $scope.sourceMax = cm['in-max']; $scope.targetMin = cm['out-min']; $scope.targetMax = cm['out-max']; $scope.noises = cm['noises'] ? $scope.noisePercToNoise(cm['noises']) : 0; paintCanvasPath(inVals, outVals); updateSimPlot(); } else { if ($scope.selectedInputField === null) { $scope.selectedInputField = Model.filterNumericFields($scope.field.dependencies)[0]; } inferArguments(); $scope.drawSketch('linear'); } $scope.inputRead = true; } function inferArguments() { var sourceSamples = Model.getSamples($scope.selectedInputField); var targetSamples = Model.getSamples($scope.field); if (targetSamples.length > 0) { $scope.targetMin = _.min(targetSamples); $scope.targetMax = _.max(targetSamples); } else { $scope.targetMin = 0; $scope.targetMax = 1; } if ($scope.targetMin === $scope.targetMax) { $scope.targetMin -= 5; $scope.targetMax += 5; } if (sourceSamples.length > 0) { $scope.sourceMin = _.min(sourceSamples); $scope.sourceMax = _.max(sourceSamples); } else { $scope.sourceMin = 0; $scope.sourceMax = 1; } if ($scope.sourceMin === $scope.sourceMax) { $scope.sourcMin -= 5; $scope.sourceMax += 5; } } //region CANVAS function paintCanvasPath(inVals, outVals) { if (inVals.length === 0 || outVals.length === 0) return; $scope.path = new $scope.paper.Path(); var h = height - 2 * GRAPH_PADDING, w = width - 2 * GRAPH_PADDING; for (var i = 0; i < inVals.length; i++) { var outValIdx = Math.floor((i / inVals.length) * outVals.length); $scope.path.add(new $scope.paper.Point(inVals[i] * w + GRAPH_PADDING, h - outVals[outValIdx] * h + GRAPH_PADDING)); } $scope.path.simplify(); $scope.path.opacity = 0; $canvas.hide(); } function extractPoints(granularityStep) { if ($scope.path === undefined || $scope.path.length === 0) return null; if (!granularityStep) granularityStep = 0.1; var points = [], px, p, i; px = $scope.path.getPointAt(0).x; var minX = Number.MAX_SAFE_INTEGER; var maxX = Number.MIN_SAFE_INTEGER; var minY = Number.MAX_SAFE_INTEGER; var maxY = Number.MIN_SAFE_INTEGER; for (i = 0; i <= $scope.path.length; i += granularityStep) { p = $scope.path.getPointAt(i); if (p.x > px) { if (p.x < minX) minX = p.x; if (p.x > maxX) maxX = p.x; if (p.y < minY) minY = p.y; if (p.y > maxY) maxY = p.y; } } for (i = 0; i <= $scope.path.length; i += granularityStep) { p = $scope.path.getPointAt(i); if (p.x > px) { points.push([ (p.x - minX) / (maxX - minX), 1 - ((p.y - minY) / (maxY - minY)) ]); px += 1; } } return points; } function checkPointCompatible(point) { var currentSegments = $scope.path.segments; if (currentSegments.length === 0) return true; return point.x >= currentSegments[currentSegments.length - 1].point.x; } /* UI callback */ $scope.drawSketch = function (type, xVals, yVals) { var i; $scope.cleanSketch(); $scope.paper.activate(); $scope.path = new $scope.paper.Path(); var h = height - 2 * GRAPH_PADDING, w = width - 2 * GRAPH_PADDING; switch (type) { case 'exp': for (i = 1; i < LINE_X_POINTS; i++) { $scope.path.add(new $scope.paper.Point(i / LINE_X_POINTS * w + GRAPH_PADDING, h - (i * i) / (LINE_X_POINTS * LINE_X_POINTS) * h + GRAPH_PADDING)); } break; case 'log': var maxv = Math.log(LINE_X_POINTS); for (i = 1; i < LINE_X_POINTS; i++) { $scope.path.add(new $scope.paper.Point(i / LINE_X_POINTS * w + GRAPH_PADDING, h - Math.log(i) / maxv * h + GRAPH_PADDING)); } break; case 'linear': for (i = 1; i < LINE_X_POINTS; i++) { $scope.path.add(new $scope.paper.Point(i / LINE_X_POINTS * w + GRAPH_PADDING, h - i / LINE_X_POINTS * h + GRAPH_PADDING)); } break; default: for (i = 1; xVals.length; i++) { $scope.path.add(new $scope.paper.Point(xVals[i] * w + GRAPH_PADDING, h - yVals[i] * h + GRAPH_PADDING)); } break; } $scope.path.opacity = 0; $canvas.hide(); updateResult(); }; $scope.cleanSketch = function () { $scope.paper.activate(); $scope.paper.project.clear(); $scope.paper.view.draw(); if ($scope.path) $scope.path.clear(); $canvas.show(); $scope.path = undefined; }; $scope.clean = function () { $scope.cleanSketch(); updateResult(); }; function initPaper() { $scope.paper = new paper.PaperScope(); for (var i = 0; i < $scope.paper.projects.length; i++) $scope.paper.projects[i].remove(); $scope.paper.remove(); $scope.paper.setup($canvas[0]); $scope.tool = new $scope.paper.Tool(); $scope.tool.onMouseDown = function (event) { $scope.cleanSketch(); render(true); $scope.path = new $scope.paper.Path(); $scope.path.strokeColor = MAIN_LINE_COLOR; $scope.path.strokeWidth = LINE_WIDTH; $scope.path.strokeCap = 'round'; $scope.path.strokeJoin = 'round'; }; $scope.tool.onMouseDrag = function (event) { if (!$scope.path) return; $scope.path.smooth(); if (!checkPointCompatible(event.point)) return; $scope.path.add(event.point); $scope.path.add(event.point); }; $scope.tool.onMouseUp = function (event) { if (!$scope.path) return; $scope.path.opacity = 0; $canvas.hide(); updateResult(); $scope.$apply(); }; $scope.cleanSketch(); } initPaper(); //endregion //region PLOT function updateSimPlot() { if (!$scope.simplot.svg) initGraph(); $scope.simplot.graphData = $scope.visrelPoints; simulateGenerations(); $timeout(render); } function initGraph() { var simplotc = $scope.simplot; simplotc.svg = d3.select(element.find('.visrel-simplot')[0]); // scales simplotc.x = d3.scale.linear(); simplotc.y = d3.scale.linear(); // axis simplotc.xAxis = d3.svg.axis().orient('bottom'); simplotc.yAxis = d3.svg.axis().orient('left'); simplotc.chartWrapper = simplotc.svg.append('g'); simplotc.chartWrapper.append('g').classed('x axis', true).style('font-size','9px'); simplotc.chartWrapper.append('g').classed('y axis', true).style('font-size','9px'); // Simulations simplotc.samplesPosAreas = []; simplotc.samplesNegAreas = []; var samplesAreasG = simplotc.chartWrapper.append('g').classed('samples-areas', true); for (var i = 0; i < Model.experimentsNumber; i++) { simplotc.samplesPosAreas.push(samplesAreasG.append('path').classed('sample-area', true).attr('exp-id', i)); simplotc.samplesNegAreas.push(samplesAreasG.append('path').classed('sample-area', true).attr('exp-id', i)); } simplotc.samplesScatterplot = simplotc.chartWrapper.append('g').classed('scatterplot', true); simplotc.path = simplotc.chartWrapper.append('path').classed('line', true); simplotc.d0ToX = function (d) { return simplotc.x(d[0] * ($scope.sourceMax - $scope.sourceMin) + $scope.sourceMin); }; simplotc.d1ToY = function (d) { return simplotc.y(d[1] * ($scope.targetMax - $scope.targetMin) + $scope.targetMin); }; simplotc.d2ToY = function (d) { return simplotc.y(d[2] * ($scope.targetMax - $scope.targetMin) + $scope.targetMin); }; addMouseOverInfo(); return true; } $scope.removeScatterplotTimeout = null; function addMouseOverInfo() { element .off('mouseover') .off('mouseout') .on('mouseover', '.sample-area', function () { if ($scope.removeScatterplotTimeout) { clearTimeout($scope.removeScatterplotTimeout); $scope.removeScatterplotTimeout = null; } var id = d3.select(this).attr('exp-id'); renderScatterplot(id); }) .on('mouseout', '.sample-area', function () { $scope.removeScatterplotTimeout = setTimeout(function () { element.find('.sample-area').removeClass('highlighted'); cleanScatterplot(); }, 2000); }); } function renderScatterplot(expNum) { var simplotc = $scope.simplot; cleanScatterplot(); var samplesAreas = element.find('.sample-area'); for (var i = 0; i < samplesAreas.length; i++) { var sa = samplesAreas.eq(i); var expId = sa.attr('exp-id'); if (expId == expNum) { sa.addClass('highlighted'); } else { sa.removeClass('highlighted'); } } var sp = $scope.simplot.samplesScatterplot.selectAll('.sample-dot').data($scope.simSamples[expNum]); sp.exit().remove(); sp.attr('cx', simplotc.d0ToX) .attr('cy', simplotc.d1ToY); sp.enter().append('circle') .attr('class', 'sample-dot') .attr('r', 1) .attr('cx', simplotc.d0ToX) .attr('cy', simplotc.d1ToY); } function cleanScatterplot() { element.find('.sample-area').removeClass('highlighted'); var sp = $scope.simplot.samplesScatterplot.selectAll('.sample-dot').data([]); sp.exit().remove(); } function render(dontConsiderNoises) { var simplotc = $scope.simplot; if (!simplotc.svg) return; //get dimensions var graphWidth = element.find('.visrel-simplot').width(); var graphHeight = element.find('.visrel-simplot').height(); simplotc.graphWidth = graphWidth - simplotc.MARGIN.left - simplotc.MARGIN.right; simplotc.graphHeight = graphHeight - simplotc.MARGIN.top - simplotc.MARGIN.bottom; //update x and y scales to new dimensions simplotc.svg .attr('width', simplotc.graphWidth + simplotc.MARGIN.right + simplotc.MARGIN.left) .attr('height', simplotc.graphHeight + simplotc.MARGIN.top + simplotc.MARGIN.bottom); simplotc.chartWrapper .attr('transform', 'translate(' + simplotc.MARGIN.left + ',' + simplotc.MARGIN.top + ')'); simplotc.x.range([0, simplotc.graphWidth]); simplotc.y.range([simplotc.graphHeight, 0]); simplotc.xAxis.scale(simplotc.x); simplotc.yAxis.scale(simplotc.y); simplotc.svg.select('.x.axis') .attr('transform', 'translate(0,' + simplotc.graphHeight + ')') .call(simplotc.xAxis); simplotc.svg.select('.y.axis') .call(simplotc.yAxis); simplotc.area = d3.svg.area() .x(simplotc.d0ToX) .y0(simplotc.d1ToY) .y1(simplotc.d2ToY); simplotc.area.interpolate('cardinal'); cleanScatterplot(); // Change data simplotc.x.domain([$scope.sourceMin, $scope.sourceMax]); if (dontConsiderNoises) { simplotc.y.domain([$scope.targetMin, $scope.targetMax]); } else { simplotc.y.domain([$scope.simSamplesBoundaries.min, $scope.simSamplesBoundaries.max]); } element.find('.target-max').css('top', simplotc.y($scope.targetMax)); element.find('.target-min').css('top', simplotc.y($scope.targetMin)).css('bottom', null); simplotc.xAxis.scale(simplotc.x); simplotc.yAxis.scale(simplotc.y); for (var i = 0; i < Model.experimentsNumber; i++) { simplotc.samplesPosAreas[i] .attr('d', simplotc.area($scope.simSamplesPosAreas[i] ? $scope.simSamplesPosAreas[i] : [])); simplotc.samplesNegAreas[i] .attr('d', simplotc.area($scope.simSamplesNegAreas[i] ? $scope.simSamplesNegAreas[i] : [])); } simplotc.line = d3.svg.line() .x(function (d) { return simplotc.x(d[0] * ($scope.sourceMax - $scope.sourceMin) + $scope.sourceMin); }) .y(function (d) { return simplotc.y(d[1] * ($scope.targetMax - $scope.targetMin) + $scope.targetMin); }); simplotc.line.interpolate('cardinal'); simplotc.path .classed('theoretical-line', true) .attr('d', simplotc.line($scope.visrelPoints === null ? [] : $scope.visrelPoints)); simplotc.svg.select('.x.axis').call(simplotc.xAxis); simplotc.svg.select('.y.axis').call(simplotc.yAxis); } initGraph(); //endregion $scope.$watchCollection(function () { return [$scope.sourceMin, $scope.sourceMax, $scope.targetMax, $scope.targetMin, $scope.noises, Model.dataVolume]; }, function () { updateResult(); }); $scope.$watch('_result.obj', function () { $scope.inputRead = false; readResult(); }); $scope.$watchCollection('field.dependencies', function () { $scope.possibleInputFields = Model.filterNumericFields($scope.field.dependencies); $scope.selectedInputField = $scope.possibleInputFields[0]; }); } }; }]); <|start_filename|>synner-server/src/main/resources/static/js/main.js<|end_filename|> var Synner = angular.module('Synner', ['ngResource', 'ngAnimate', 'rzModule', 'ui.ace', 'ngSanitize', 'angular.filter']); Synner.value('Parameters', { DEBUG: true, SERVER: { DEBUG: '', PRODUCTION: '' }, GENERATION_DELAY: 400, COMPLETE_PREVIEW_INIIAL_GENERATION_DELAY: 2000, COMPLETE_PREVIEW_GENERATION_DELAY: 100, INFER_DELAY: 200, AVAILABLE_DOMAINS: null, ROWS_TO_PROGRESSIVELY_ADD: 10, MAX_INTERFACE_DATA_VOLUME: 50 // Max allowed data to be loaded in the interface }); Synner.controller('MainCtrl', ['$rootScope', '$scope', '$timeout', '$window', '$anchorScroll', '$location', 'Model', 'API', 'Infer', 'Parameters', function ($rootScope, $scope, $timeout, $window, $anchorScroll, $location, Model, API, Infer, Parameters) { $scope._selectedField = {obj: null}; $scope.model = Model; API.getInfo(function (res) { Parameters.AVAILABLE_DOMAINS = res['available-domains']; }); $scope.addColumn = function (type) { var newField = Model.addNewColumn(type); $timeout(function () { $('#synner-data-table .field-name').eq(newField.id).focus().select(); $location.hash('end-of-table-placeholder'); $anchorScroll(); }, 10); $scope.selectField(newField); }; angular.element($window).bind('resize', function () { $rootScope.$broadcast('windowResize', $window.innerWidth); }); $scope.selectField = function (field) { $scope._selectedField.obj = field; $timeout(function () { $scope.updateHeight(); }); }; $rootScope.$on('selectField', function (e, field) { $scope.selectField(field); }); $scope.changeDataValue = function (dataValue, field) { dataValue.l = dataValue.v !== undefined && dataValue.v !== null; if ((typeof dataValue.v) === 'string' && dataValue.v.length === 0) dataValue.l = false; if (!field._generator.obj) Infer.inferFromData(field); $scope.requestNewDataGeneration(); }; $scope.selectInferCategory = function (req) { console.log(req); }; $scope.getInputPattern = function (f) { if (f.type === 'string') return ''; return "/^[0-9]{1,3}(\.\d{0,3})?/"; }; $scope.changeFieldType = function (fieldId) { Model.changeFieldType(fieldId); $scope.requestNewDataGeneration(); }; $scope.removeColumn = function (fieldId) { if ($scope._selectedField && $scope._selectedField.obj && $scope._selectedField.obj.id === fieldId) $scope._selectedField.obj = undefined; Model.removeColumn(fieldId); }; $scope.hideColumn = function (fieldId) { Model.hideColumn(fieldId); }; $scope.updateHeight = function () { $scope.mainPropertiesPanelHeight = $('body').height() - $('#synner-data-table').height() - $('.navbar').height(); }; // On resize window, so to maintain the correct layout window.onresize = function (event) { $scope.updateHeight(); }; $scope.requestNewDataGeneration = function () { Model.requestNewDataGeneration(); }; Model.dataGenerationReqTimeout = null; $scope.$watch(function () { var elements = []; for (var f of Model.fields) { if (!f._generator.obj) continue; elements.push(f._generator.obj); elements.push(f.filter); elements.push(f.errorRows); elements.push(f.missingRows); } return elements; }, $scope.requestNewDataGeneration, true); } ]); Synner.run(['$rootScope', function ($rootScope, $timeout) { $rootScope.$on('$includeContentLoaded', function () { }); $rootScope.$on('selectedFieldChanged', function () { }); }]); Synner.directive("limitCharsForFields", [function () { return { restrict: "A", link: function (scope, elem, attrs) { angular.element(elem).on("keypress", function (e) { if (e.key === " ") { $el = angular.element(elem); $el.val($el.val() + '_'); e.preventDefault(); } }); } } }]); Synner.directive("limitCharsForDataFields", [function () { return { restrict: "A", link: function (scope, elem, attrs) { angular.element(elem).on("keypress", function (e) { if (e.key === " ") { $(elem).val($(elem).val() + '_'); e.preventDefault(); } }); } } }]); Synner.directive("preventDropdownLooseFocus", [function () { return { restrict: "A", link: function (scope, elem, attrs) { angular.element(elem).on("click", function (e) { e.stopPropagation(); }); } } }]); Synner.filter('formatMd', function ($sce) { return function (input, query) { return $sce.trustAsHtml(input.replace(RegExp('\\*\\*(.*)\\*\\*', 'g'), '<strong>$1</strong>')); } }); Synner.directive('onEnterPress', function () { return function (scope, element, attrs) { element.bind("keydown keypress", function (event) { if (event.which === 13) { scope.$apply(function () { scope.$eval(attrs.onEnterPress); }); event.preventDefault(); } }); }; }); <|start_filename|>synner-server/src/main/resources/static/js/directives/generator-switch.js<|end_filename|> angular.module('Synner') .directive('generatorSwitch', ['Model', 'Functions', 'Parameters', '$timeout', function (Model, Functions, Parameters, $timeout) { return { templateUrl: 'fragments/generator-switch.html', replace: true, restriction: 'E', scope: { _result: '=result', field: '=', }, link: { pre: function preLink($scope, element, attrs) { var onChangeFirstTime = {}; // by editor id it says if it's the first time the on change is called $scope.aceEditorOnChange = function (e) { clearTimeout($scope.errorTimeout); var _session = e[1].session; if (onChangeFirstTime[e[1].id] === undefined) { onChangeFirstTime[e[1].id] = true; return; } var conditionalExpression = _session.getValue(); $scope.addSuggestions(_session.getValue()); if (conditionalExpression.length === 0) return; var $visibleLines = Functions.getVisibleLines(); var conditionFunction; var error = null; try { var functionAvailableFields = []; for (var i = 0; i < Model.fields.length; i++) { // We check that the field in the model is in the field's dependencies var found = false; for (var dep of $scope.field.dependencies) { if (dep.id === Model.fields[i].id) { found = true; break; } } functionAvailableFields.push(Model.fields[i]); } conditionFunction = Functions.compileFunction(conditionalExpression, functionAvailableFields); Model.haltGeneration = true; for (var i = 0; i < $visibleLines.length; i++) { Functions.evaluateConditionInLines(conditionFunction, $visibleLines[i], function () { Model.haltGeneration = false; Model.requestNewDataGeneration(); }); } } catch (e) { error = e; } if (error == null) { var c = $scope.getCaseByEditorElement(e[1].container); if (c) c.error = null; } else { $scope.errorTimeout = setTimeout(function () { var c = $scope.getCaseByEditorElement(e[1].container); if (c) c.error = error; $scope.$apply(); }, 1000); } }; $scope.getCaseByEditorElement = function (editorContainer) { var idx = parseInt(editorContainer.id.replace('cases-condition-', '')); if (idx === '') return null; // For the new case expression return $scope.cases[idx]; }; $scope.aceEditorLoaded = function (_editor) { var _session = _editor.getSession(); _editor.setOptions({ maxLines: 1, // make it 1 line autoScrollEditorIntoView: true, highlightActiveLine: false, printMargin: false, showGutter: false, fontSize: 12, mode: "ace/mode/javascript", theme: "ace/theme/crimson_editor" }); _editor.container.style.lineHeight = 1.8; _editor.renderer.updateFontSize(); _session.setUndoManager(new ace.UndoManager()); _editor.commands.bindKey("Enter|Shift-Enter", "null"); _editor.focus(); }; $scope.addSuggestions = function (expression) { $scope.expressionSuggestions = []; if (expression.length === 0) { for (var f of $scope.field.dependencies) $scope.expressionSuggestions.push(f.name); } else if (expression.match(/^[A-Za-z0-9\\_\s]+$/)) { $scope.expressionSuggestions.push('=='); $scope.expressionSuggestions.push('!='); $scope.expressionSuggestions.push('>'); $scope.expressionSuggestions.push('<'); $scope.expressionSuggestions.push('>='); $scope.expressionSuggestions.push('<='); } if ($scope.expressionSuggestions.length > 0) { $scope.dropdownAutosuggestions.css({opacity: 1}); return true; } else { $scope.removeSuggestions(); return false; } }; $scope.removeSuggestions = function () { $scope.dropdownAutosuggestions.css({opacity: 0}); $scope.expressionSuggestions = null; }; $scope.aceEditorOnFocus = function (e) { var _session = e[0].session; var suggestionsAdded = $scope.addSuggestions(_session.getValue()); $timeout(function () { $scope.currentFocusedEditor = e; document.currentFocusedEditor = e; var $focusedEditor = $($scope.currentFocusedEditor[0].container); var focEditorOffset = $focusedEditor.offset(); if (suggestionsAdded) { $scope.dropdownAutosuggestions.css({opacity: 1}).offset({ top: focEditorOffset.top + $focusedEditor.height(), left: focEditorOffset.left }); } }); }; $scope.aceEditorOnBlur = function () { $scope.dropdownAutosuggestions.css({opacity: 0}); }; $scope.addSuggestionToCurrentEditor = function (val) { if (!$scope.currentFocusedEditor) return; var currVal = $scope.currentFocusedEditor[0].env.editor.getValue(); $scope.currentFocusedEditor[0].env.editor.setValue(currVal + val, 1); $scope.currentFocusedEditor[0].env.editor.focus(); $scope.dropdownAutosuggestions.css({opacity: 0}); }; }, post: function postLink($scope, element, attrs) { $scope.dropdownAutosuggestions = element.find('.dropdown-autosuggestions'); $scope.cases = [ // {condition: 'Height > 10', error: null, _generator: {obj: {distribution: "uniform", min: -1, max: 1}}} ]; $scope._defaultCase = {obj: undefined}; $scope.compactViewDefaultCase = false; $scope.expressionSuggestions = null; document.switchScope = $scope; function updateResult() { if (!$scope.inputRead) return; // Prevent changes on the distribution parameters to change the input, even before reading it if (!$scope._result) return; // in case the directive is active without any result specified var generator = {'switch': []}; for (var c of $scope.cases) { generator['switch'].push({ 'pos': c.id, 'case': c.condition, 'then': c._generator.obj }); } generator['switch'].push({ 'default': $scope._defaultCase.obj }); $scope._result.obj = generator; $scope.inputRead = true; } function readResult() { if ($scope.inputRead) return; var obj = $scope._result.obj; if (obj) { $scope.cases = []; if (Model.isSwitch(obj)) { for (var c of obj['switch']) { if ('default' in c) { $scope._defaultCase.obj = c['default']; } else { $scope.cases.push({ id: c['pos'], condition: c['case'], error: null, _generator: {obj: c['then']} }); } } } else { $scope._defaultCase.obj = obj; } } $scope.inputRead = true; } $scope.addNewCondition = function () { $scope.cases.unshift({ id: $scope.cases.length, condition: '', erros: null, _generator: {obj: undefined} }); }; $scope.deleteCase = function (c) { $scope.cases.splice(c.id, 1); for (var i = 0; i < $scope.cases.length; i++) $scope.cases[i].id = i; }; $scope.$watch('field', function () { $scope.inputRead = false; readResult(); }); $scope.$watch('_defaultCase', function (defCase) { updateResult() }, true); $scope.$watch(function () { var cases = []; for (var c of $scope.cases) { if (!c.error) cases.push(c); } return cases; }, function (defCase) { updateResult() }, true); } } }; }]); <|start_filename|>synner-server/src/main/resources/static/js/directives/generator.js<|end_filename|> angular.module('Synner') .directive('generator', ['Model', 'Parameters', function (Model, Parameters) { return { templateUrl: 'fragments/generator.html', replace: true, restriction: 'E', scope: { _result: '=result', field: '=', compactView: '=' }, link: function ($scope, element, attrs) { $scope.inputRead = false; $scope.modality = null; $scope.modalities = []; function readResult() { var obj = $scope._result.obj; if (obj) { if (Model.isFunction(obj)) { $scope.modality = 'function'; } else if (Model.isCases(obj)) { $scope.modality = 'enumeration'; } else if (Model.isDomain(obj)) { $scope.modality = 'domain'; } else if (Model.isDistribution(obj)) { $scope.modality = 'distribution'; } else if (Model.isTimeRange(obj)) { $scope.modality = 'timerange'; } else if (Model.isDateRange(obj)) { $scope.modality = 'daterange'; } else if (Model.isVisualRelationship(obj) && Model.filterNumericFields($scope.field.dependencies).length > 0) { $scope.modality = 'visrel'; } } $scope.inputRead = true; } $scope.changeMod = function (m) { $scope.modality = m; }; $scope.getModalityDescription = function (mv) { for (var m of $scope.modalities) { if (m.v === mv) return m.descr; } return null; }; $scope.$watch('field', function() { $scope.modalities = Model.getFieldModalities($scope.field); $scope.modality = Model.getFieldGeneratorModality($scope.field); $scope.inputRead = false; }); $scope.$watchCollection('field.dependencies', function () { $scope.modalities = Model.getFieldModalities($scope.field); }); $scope.$watch('_result', function (res) { readResult(); }, true); $scope.$watch('field', function () { readResult(); }); } }; }]); <|start_filename|>synner-server/src/main/resources/static/js/directives/generator-domain.js<|end_filename|> angular.module('Synner') .directive('generatorDomain', ['Model', 'Parameters', 'filterFilter', '$anchorScroll', '$location', '$timeout', function (Model, Parameters, filterFilter, $anchorScroll, $location, $timeout) { return { templateUrl: 'fragments/generator-domain.html', replace: true, restriction: 'E', scope: { _result: '=result', // where we will put the result of generation specifications compactView: '=', field: '=' }, link: function ($scope, element, attrs) { $scope.AVAILABLE_DOMAINS = Parameters.AVAILABLE_DOMAINS; $scope.AVAILABLE_DOMAINS_AS_LIST = []; for (var d in $scope.AVAILABLE_DOMAINS) { $scope.AVAILABLE_DOMAINS_AS_LIST.push($scope.AVAILABLE_DOMAINS[d]); } $scope.AVAILABLE_DOMAINS_AS_TREE = {}; for (var d in $scope.AVAILABLE_DOMAINS) { if (!$scope.AVAILABLE_DOMAINS_AS_TREE[d.category]) { $scope.AVAILABLE_DOMAINS_AS_TREE[d.category] = [$scope.AVAILABLE_DOMAINS[d]]; } else { $scope.AVAILABLE_DOMAINS_AS_TREE[d.category].push($scope.AVAILABLE_DOMAINS[d]) } } $scope.filteredAvailableDomain = []; $scope.inputRead = false; $scope.selectedDomain = null; $scope.domainsListFiter = ''; $scope.selectedDependency = undefined; function getReachableDomain(rootDomain, domain, rdomains, depth) { if (rdomains === undefined) rdomains = {}; if (domain === undefined) domain = rootDomain; if (depth === undefined) depth = 0; depth += 1; for (var sd of $scope.AVAILABLE_DOMAINS[domain].subdomains) { if (rdomains[sd] === undefined && sd !== rootDomain) { rdomains[sd] = depth; getReachableDomain(rootDomain, sd, rdomains, depth); } } return rdomains; } element.find('.domains-list-search input').bind("keydown keypress", function (event) { if (event.which !== 13) return; $scope.filteredAvailableDomain = filterFilter($scope.AVAILABLE_DOMAINS_AS_LIST, {readableName: $scope.domainsListFiter}); $scope.changeDomain($scope.filteredAvailableDomain[0].name); $scope.domainsListFiter = ''; $scope.$apply(); event.preventDefault(); }); $timeout(function () { element.find('.domains-list-search input').focus(); }); function updateResult() { if (!$scope.inputRead) return; var generator = { 'domain': { name: $scope.selectedDomain.name } }; if ($scope.field.dependencies.length > 0) { if (!$scope.selectedDependency) { for (var dep of $scope.field.dependencies) { var depGen = Model.getGeneratorWithoutSwitch(dep); if (!Model.isDomain(depGen)) continue; var rdomains = getReachableDomain($scope.selectedDomain.name); for (var subDom in rdomains) { if (depGen.domain.name === subDom && (generator.join === undefined || rdomains[generator.join] > rdomains[subDom])) { $scope.selectedDependency = dep; } } } if (generator.join === undefined) { // if no dependencies are domains we just assign the first text column for (var dep of $scope.field.dependencies) { if (dep.type === 'string') { $scope.selectedDependency = dep; } } } } generator.join = $scope.selectedDependency.name; } $scope._result.obj = generator; } function readResult() { if ($scope.inputRead) return; var obj = $scope._result.obj; $scope.selectedDomain = null; if (obj && Model.isDomain(obj)) { for (var dname in $scope.AVAILABLE_DOMAINS) { if (dname === obj.domain.name) { $scope.selectedDomain = $scope.AVAILABLE_DOMAINS[dname]; } } $scope.selectedDependency = undefined; for (var dep of $scope.field.dependencies) { if (dep.name === obj.join) $scope.selectedDependency = dep; } } $scope.inputRead = true; $timeout(function () { $location.hash('domain-' + $scope.selectedDomain.name); $anchorScroll(); element.find('.domains-list-search input').focus(); }); } $scope.getReadableName = function (domainName) { return $scope.AVAILABLE_DOMAINS[domainName].readableName; }; $scope.changeDomain = function (domain) { if (!$scope.AVAILABLE_DOMAINS[domain].available) return; $scope.selectedDomain = $scope.AVAILABLE_DOMAINS[domain]; }; // We need to update the result when dependency changes, but this is also called if the field is changed // (from domain to another domain) and this could be called before the _result change callback $scope.$watch('field.dependencies', function (newVal, oldVal) { $scope.inputRead = false; readResult(); updateResult(); }, true); $scope.$watch('selectedDomain', function (newVal, oldVal) { updateResult(); }, true); $scope.$watch('selectedDependency', function (newVal, oldVal) { updateResult(); }, true); $scope.$watch('_result', function (newRes, oldRes) { $scope.inputRead = false; readResult(); }, true); } }; }]); <|start_filename|>synner-server/src/main/resources/static/js/infer.js<|end_filename|> Synner.service('Infer', ['Model', 'Parameters', 'API', '$timeout', function (Model, Parameters, API, $timeout) { // Infers the data type of a function based on user input this.inferDataType = function (field) { var noElements = true; for (let row = 0; row < Model.data.length; row++) { if (Model.data[row] === null || Model.data[row][field.id] === null || Model.data[row][field.id].l !== true) { continue; } else { noElements = false; } var val = Model.data[row][field.id].v; // First checks if it is a string if (isNaN(parseFloat(val))) { field.type = 'string'; return; } // Then checks if it is a decimal if (val.toString().indexOf('.') > -1) { field.type = 'decimal'; return; } } // Returns integer if the above 2 criteria are not met, but only if there is a value written by the user if (!noElements) field.type = 'integer'; }; this.inferFromData = function (field) { if (!field) return; var self = this; // this.inferDataType(field); if (field.inferReqTimeout) $timeout.cancel(field.inferReqTimeout); field.inferReqTimeout = $timeout(function () { var valuesToInfer = []; for (let row = 0; row < Model.data.length; row++) { if (Model.data[row] === null || Model.data[row][field.id] === null || Model.data[row][field.id].l !== true) continue; valuesToInfer.push(Model.data[row][field.id].v); } self.pushDefaultGenerator(valuesToInfer, field); if (valuesToInfer.length === 1 && typeof valuesToInfer[0] === 'string' && valuesToInfer[0].startsWith('=')) { field.inferOptions = []; field.inferOptions.push({ title: "Function", type: "function", generator: {function: {value: valuesToInfer[0].substr(1), variables: []}} }); } var req = [{ id: field.id, fieldname: field.name, type: field.type, values: valuesToInfer }]; API.infer(req, function (res) { let results = res[0]['inferred-types']; let examples = res[0]['examples']; field.inferOptions = []; for (let i = 0; i < results.length; i++) { field.inferOptions.push({ title: results[i].title, type: 'domain', description: examples[i], generator: { domain: {name: results[i].id} } }); } if (field.type === 'string') self.pushEnumerationCards(valuesToInfer, field.type, field); if (field.type === 'integer' || field.type === 'decimal') self.pushDistributionCards(valuesToInfer, field.inferOptions); if (field.type === 'time') self.pushTimeGeneratorsCards(valuesToInfer, field.inferOptions, field); if (field.type === 'date') self.pushDateGeneratorsCards(valuesToInfer, field.inferOptions, field); }); field.inferReqTimeout = undefined; }, Parameters.INFER_DELAY); }; this.pushDefaultGenerator = function (valuesToInfer, field) { var generator; if (field.type === 'string') { generator = {domain: {name:'NAME'}}; } else if (field.type === 'time') { generator = {timerange: {from: 0, to: 1439}}; } else if (field.type === 'date') { generator = {daterange: { from: (Date.now() - 100*24*60*60*1000) / (24*60*60*1000), to: Date.now() / (24*60*60*1000) }}; } else { if (valuesToInfer.length === 0) { valuesToInfer = ['0', '100']; } else if (valuesToInfer.length === 1) { valuesToInfer = [parseFloat(valuesToInfer[0] + 10), parseFloat(valuesToInfer[0]) - 10]; } var numbersList = this.strNumberListAsNumberList(valuesToInfer); generator = { distribution: "gaussian", mean: parseFloat(jStat.mean(numbersList).toFixed(2)), stdev: parseFloat(jStat.stdev(numbersList).toFixed(2)) }; } field.inferDefaultOption = generator; return generator; }; this.pushEnumerationCards = function (valuesToInfer, fieldType, field) { if (valuesToInfer.length === 0) { if (fieldType === 'string') valuesToInfer = ['M', 'F']; } let dict = {}; for (let k = 0; k < valuesToInfer.length; k++) { if (!(valuesToInfer[k] in dict)) dict[valuesToInfer[k]] = 0; dict[valuesToInfer[k]] += 1; } let dictKeys = Object.keys(dict); let details = []; let cases = []; let ratios = []; let len = Math.min(6, dictKeys.length); for (let j = 0; j < len; j++) { cases.push({value: dictKeys[j]}); ratios.push(dict[dictKeys[j]]); details.push(dictKeys[j] + " : " + Math.round(100 * dict[dictKeys[j]] / valuesToInfer.length) + "%"); } field.inferOptions.push({ title: "Enumeration", type: "enumeration", description: details, generator: {cases: cases, ratios: ratios} }); }; this.pushTimeGeneratorsCards = function (valuesToInfer, fieldType, field) { field.inferOptions.push({ title: "All Day", type: "time", description: ['15:08', '23:40', '08:12'], generator: {timerange: {from: 1, to: 1439}} }); field.inferOptions.push({ title: "Morning", type: "time", description: ['9:01', '11:43', '10:32'], generator: {timerange: {from: 1, to: 719}} }); field.inferOptions.push({ title: "Night", type: "time", description: ['19:08', '23:40', '16:34'], generator: {timerange: {from: 720, to: 1439}} }); }; this.pushDateGeneratorsCards = function (valuesToInfer, fieldType, field) { field.inferOptions.push({ title: "Last Year", type: "date", description: [ Model.strFormatDateFromDate(new Date(Date.now() - 200*24*60*60*1000)), Model.strFormatDateFromDate(new Date(Date.now() - 100*24*60*60*1000)), Model.strFormatDateFromDate(new Date(Date.now() - 250*24*60*60*1000)), Model.strFormatDateFromDate(new Date(Date.now() - 50*24*60*60*1000)) ], generator: {daterange: { from: (Date.now() - 365*24*60*60*1000) / (24*60*60*1000), to: Date.now() / (24*60*60*1000) }} }); field.inferOptions.push({ title: "Last 10 years", type: "date", description: [ Model.strFormatDateFromDate(new Date(Date.now() - 5*365*24*60*60*1000)), Model.strFormatDateFromDate(new Date(Date.now() - 3*300*24*60*60*1000)), Model.strFormatDateFromDate(new Date(Date.now() - 2*250*24*60*60*1000)), Model.strFormatDateFromDate(new Date(Date.now() - 4*50*24*60*60*1000)) ], generator: {daterange: { from: (Date.now() - 10*365*24*60*60*1000) / (24*60*60*1000), to: Date.now() / (24*60*60*1000) }} }); field.inferOptions.push({ title: "Last 50 years", type: "date", description: [ Model.strFormatDateFromDate(new Date(Date.now() - 10*365*24*60*60*1000)), Model.strFormatDateFromDate(new Date(Date.now() - 20*300*24*60*60*1000)), Model.strFormatDateFromDate(new Date(Date.now() - 30*250*24*60*60*1000)), Model.strFormatDateFromDate(new Date(Date.now() - 10*50*24*60*60*1000)) ], generator: {daterange: { from: (Date.now() - 50*365*24*60*60*1000) / (24*60*60*1000), to: Date.now() / (24*60*60*1000) }} }); }; this.pushDistributionCards = function (valuesToInfer, inferOptionsArray) { if (valuesToInfer.length === 0) { this.pushDistributionCards(['0', '100'], inferOptionsArray); return; } else if (valuesToInfer.length === 1) { this.pushDistributionCards([parseFloat(valuesToInfer[0] + 10), parseFloat(valuesToInfer[0]) - 10], inferOptionsArray); return; } let numbersList = this.strNumberListAsNumberList(valuesToInfer); // Uniform Distribution inferOptionsArray.push({ title: "Distribution: uniform", type: "distribution", description: [ "Minimum: " + Math.floor(Math.min(...numbersList)), "Maximum: " + Math.ceil(Math.max(...numbersList)) ], generator: { distribution: "uniform", min: Math.floor(Math.min(...numbersList)), max: Math.ceil(Math.max(...numbersList)) } }); var mean = parseFloat(jStat.mean(numbersList).toFixed(2)); var std = parseFloat(jStat.stdev(numbersList).toFixed(2)); // Gaussian Distribution inferOptionsArray.push({ title: "Distribution: gaussian", type: "distribution", description: [ "Mean: " + mean, "Std Dev: " + std ], generator: { distribution: "gaussian", mean: mean, stdev: std } }); // Exponential Distribution inferOptionsArray.push({ title: "Distribution: exponential", type: "distribution", description: [ "Rate: " + (mean > 0 ? parseFloat((1 / mean).toFixed(2)) : 1) ], generator: { distribution: "exponential", rate: mean > 0 ? parseFloat((1 / mean).toFixed(2)) : 1 } }); }; this.strNumberListAsNumberList = function (strNumList) { var numbersList = []; for (var i = 0; i < strNumList.length; i++) { numbersList.push(parseFloat(strNumList[i])); } return numbersList; }; this.inferDistribution = function (field) { var samples = Model.getSamples(field); if (samples.length > 0) { var stats = jStat(samples); return stats.stdev() > 0 ? stats : null; } return null; }; // Creating a new link the default link generator is a function. This analyses the current field generator and the // dependencies of the new link in order to suggest the best generator for this new link this.inferLinkGenerator = function (field) { var targetGenerator = field._generator.obj; if (field.dependencies.length === 1 && Model.isDomain(field.dependencies[0]._generator.obj) && Model.isDomain(targetGenerator)) { field._generator.obj = {'natural-join': targetGenerator}; } }; // analyse the field and if that is a domain it retrieves all the possible domain that can be linked to the field's domain this.getFieldSubdomains = function (field) { if (!field) return []; var gen = Model.getGeneratorWithoutSwitch(field); if(!Model.isDomain(gen)) return []; var domain = gen.domain.name; var res = []; for (var sd of Parameters.AVAILABLE_DOMAINS[domain].subdomains) { res.push({id: sd, domain: Parameters.AVAILABLE_DOMAINS[sd]}); } return res; } }]) ; <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/generators/numerical/UniformGen.java<|end_filename|> package edu.nyu.dtl.synner.core.generators.numerical; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import edu.nyu.dtl.synner.core.generators.Generator; @JsonPropertyOrder({"type", "min", "max"}) public class UniformGen implements Generator<Double> { @JsonProperty double min; double max; public UniformGen(double min, double max) { this.min = min; this.max = max; } @Override public Double generate(boolean errorMode, boolean previewMode) { double res = rnd.nextDouble() * (max - min) + min; if (errorMode) return res + 2 * (rnd.nextBoolean() ? 1 : - 1) * (max - min) ; return res; } @JsonProperty public String getType() { return "uniform"; } } <|start_filename|>synner-server/src/main/resources/static/expression-parser/ECMAScriptLexer.js<|end_filename|> // Generated from ECMAScript.g4 by ANTLR 4.7.1 // jshint ignore: start var antlr4 = require('antlr4/index'); var serializedATN = ["\u0003\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964", "\u0002i\u03b7\b\u0001\u0004\u0002\t\u0002\u0004\u0003\t\u0003\u0004", "\u0004\t\u0004\u0004\u0005\t\u0005\u0004\u0006\t\u0006\u0004\u0007\t", "\u0007\u0004\b\t\b\u0004\t\t\t\u0004\n\t\n\u0004\u000b\t\u000b\u0004", "\f\t\f\u0004\r\t\r\u0004\u000e\t\u000e\u0004\u000f\t\u000f\u0004\u0010", "\t\u0010\u0004\u0011\t\u0011\u0004\u0012\t\u0012\u0004\u0013\t\u0013", "\u0004\u0014\t\u0014\u0004\u0015\t\u0015\u0004\u0016\t\u0016\u0004\u0017", "\t\u0017\u0004\u0018\t\u0018\u0004\u0019\t\u0019\u0004\u001a\t\u001a", "\u0004\u001b\t\u001b\u0004\u001c\t\u001c\u0004\u001d\t\u001d\u0004\u001e", "\t\u001e\u0004\u001f\t\u001f\u0004 \t \u0004!\t!\u0004\"\t\"\u0004#", "\t#\u0004$\t$\u0004%\t%\u0004&\t&\u0004\'\t\'\u0004(\t(\u0004)\t)\u0004", "*\t*\u0004+\t+\u0004,\t,\u0004-\t-\u0004.\t.\u0004/\t/\u00040\t0\u0004", "1\t1\u00042\t2\u00043\t3\u00044\t4\u00045\t5\u00046\t6\u00047\t7\u0004", "8\t8\u00049\t9\u0004:\t:\u0004;\t;\u0004<\t<\u0004=\t=\u0004>\t>\u0004", "?\t?\u0004@\t@\u0004A\tA\u0004B\tB\u0004C\tC\u0004D\tD\u0004E\tE\u0004", "F\tF\u0004G\tG\u0004H\tH\u0004I\tI\u0004J\tJ\u0004K\tK\u0004L\tL\u0004", "M\tM\u0004N\tN\u0004O\tO\u0004P\tP\u0004Q\tQ\u0004R\tR\u0004S\tS\u0004", "T\tT\u0004U\tU\u0004V\tV\u0004W\tW\u0004X\tX\u0004Y\tY\u0004Z\tZ\u0004", "[\t[\u0004\\\t\\\u0004]\t]\u0004^\t^\u0004_\t_\u0004`\t`\u0004a\ta\u0004", "b\tb\u0004c\tc\u0004d\td\u0004e\te\u0004f\tf\u0004g\tg\u0004h\th\u0004", "i\ti\u0004j\tj\u0004k\tk\u0004l\tl\u0004m\tm\u0004n\tn\u0004o\to\u0004", "p\tp\u0004q\tq\u0004r\tr\u0004s\ts\u0004t\tt\u0004u\tu\u0004v\tv\u0004", "w\tw\u0004x\tx\u0004y\ty\u0004z\tz\u0004{\t{\u0004|\t|\u0004}\t}\u0004", "~\t~\u0004\u007f\t\u007f\u0004\u0080\t\u0080\u0004\u0081\t\u0081\u0004", "\u0082\t\u0082\u0004\u0083\t\u0083\u0004\u0084\t\u0084\u0004\u0085\t", "\u0085\u0004\u0086\t\u0086\u0004\u0087\t\u0087\u0004\u0088\t\u0088\u0003", "\u0002\u0003\u0002\u0003\u0002\u0003\u0002\u0003\u0002\u0003\u0002\u0003", "\u0003\u0003\u0003\u0003\u0003\u0003\u0003\u0003\u0004\u0003\u0004\u0003", "\u0005\u0003\u0005\u0003\u0006\u0003\u0006\u0003\u0007\u0003\u0007\u0003", "\b\u0003\b\u0003\t\u0003\t\u0003\n\u0003\n\u0003\u000b\u0003\u000b\u0003", "\f\u0003\f\u0003\r\u0003\r\u0003\u000e\u0003\u000e\u0003\u000f\u0003", "\u000f\u0003\u0010\u0003\u0010\u0003\u0010\u0003\u0011\u0003\u0011\u0003", "\u0011\u0003\u0012\u0003\u0012\u0003\u0013\u0003\u0013\u0003\u0014\u0003", "\u0014\u0003\u0015\u0003\u0015\u0003\u0016\u0003\u0016\u0003\u0017\u0003", "\u0017\u0003\u0018\u0003\u0018\u0003\u0019\u0003\u0019\u0003\u0019\u0003", "\u001a\u0003\u001a\u0003\u001a\u0003\u001b\u0003\u001b\u0003\u001b\u0003", "\u001b\u0003\u001c\u0003\u001c\u0003\u001d\u0003\u001d\u0003\u001e\u0003", "\u001e\u0003\u001e\u0003\u001f\u0003\u001f\u0003\u001f\u0003 \u0003", " \u0003 \u0003!\u0003!\u0003!\u0003\"\u0003\"\u0003\"\u0003\"\u0003", "#\u0003#\u0003#\u0003#\u0003$\u0003$\u0003%\u0003%\u0003&\u0003&\u0003", "\'\u0003\'\u0003\'\u0003(\u0003(\u0003(\u0003)\u0003)\u0003)\u0003*", "\u0003*\u0003*\u0003+\u0003+\u0003+\u0003,\u0003,\u0003,\u0003-\u0003", "-\u0003-\u0003.\u0003.\u0003.\u0003.\u0003/\u0003/\u0003/\u0003/\u0003", "0\u00030\u00030\u00030\u00030\u00031\u00031\u00031\u00032\u00032\u0003", "2\u00033\u00033\u00033\u00034\u00034\u00034\u00034\u00034\u00035\u0003", "5\u00035\u00035\u00035\u00035\u00035\u00035\u00035\u00055\u01a9\n5\u0003", "6\u00036\u00036\u00076\u01ae\n6\f6\u000e6\u01b1\u000b6\u00036\u0005", "6\u01b4\n6\u00036\u00036\u00066\u01b8\n6\r6\u000e6\u01b9\u00036\u0005", "6\u01bd\n6\u00036\u00036\u00056\u01c1\n6\u00056\u01c3\n6\u00037\u0003", "7\u00037\u00067\u01c8\n7\r7\u000e7\u01c9\u00038\u00038\u00038\u0006", "8\u01cf\n8\r8\u000e8\u01d0\u00039\u00039\u00039\u00039\u00039\u0003", "9\u0003:\u0003:\u0003:\u0003;\u0003;\u0003;\u0003;\u0003;\u0003;\u0003", ";\u0003;\u0003;\u0003;\u0003;\u0003<\u0003<\u0003<\u0003<\u0003<\u0003", "<\u0003<\u0003=\u0003=\u0003=\u0003=\u0003=\u0003>\u0003>\u0003>\u0003", ">\u0003>\u0003?\u0003?\u0003?\u0003?\u0003@\u0003@\u0003@\u0003@\u0003", "A\u0003A\u0003A\u0003A\u0003A\u0003A\u0003B\u0003B\u0003B\u0003B\u0003", "B\u0003B\u0003B\u0003B\u0003C\u0003C\u0003C\u0003C\u0003C\u0003C\u0003", "C\u0003D\u0003D\u0003D\u0003D\u0003D\u0003E\u0003E\u0003E\u0003E\u0003", "E\u0003E\u0003E\u0003E\u0003E\u0003F\u0003F\u0003F\u0003F\u0003G\u0003", "G\u0003G\u0003G\u0003G\u0003G\u0003G\u0003H\u0003H\u0003H\u0003H\u0003", "H\u0003H\u0003I\u0003I\u0003I\u0003I\u0003I\u0003I\u0003I\u0003I\u0003", "I\u0003J\u0003J\u0003J\u0003J\u0003J\u0003J\u0003J\u0003J\u0003J\u0003", "K\u0003K\u0003K\u0003K\u0003K\u0003L\u0003L\u0003L\u0003L\u0003L\u0003", "M\u0003M\u0003M\u0003M\u0003M\u0003M\u0003M\u0003M\u0003N\u0003N\u0003", "N\u0003O\u0003O\u0003O\u0003O\u0003O\u0003O\u0003P\u0003P\u0003P\u0003", "P\u0003P\u0003P\u0003P\u0003Q\u0003Q\u0003Q\u0003R\u0003R\u0003R\u0003", "R\u0003S\u0003S\u0003S\u0003S\u0003S\u0003S\u0003T\u0003T\u0003T\u0003", "T\u0003T\u0003U\u0003U\u0003U\u0003U\u0003U\u0003U\u0003U\u0003U\u0003", "V\u0003V\u0003V\u0003V\u0003V\u0003V\u0003W\u0003W\u0003W\u0003W\u0003", "W\u0003W\u0003X\u0003X\u0003X\u0003X\u0003X\u0003X\u0003X\u0003Y\u0003", "Y\u0003Y\u0003Y\u0003Y\u0003Y\u0003Y\u0003Z\u0003Z\u0003Z\u0003Z\u0003", "Z\u0003Z\u0003Z\u0003Z\u0003Z\u0003Z\u0003Z\u0003Z\u0003[\u0003[\u0003", "[\u0003[\u0003[\u0003\\\u0003\\\u0003\\\u0003\\\u0003\\\u0003\\\u0003", "\\\u0003\\\u0003\\\u0003]\u0003]\u0003]\u0003]\u0003]\u0003]\u0003]", "\u0003]\u0003^\u0003^\u0003^\u0003^\u0003^\u0003^\u0003^\u0003^\u0003", "^\u0003^\u0003^\u0003_\u0003_\u0003_\u0003_\u0003_\u0003_\u0003_\u0003", "_\u0003_\u0003`\u0003`\u0003`\u0003`\u0003`\u0003`\u0003`\u0003`\u0003", "`\u0003`\u0003`\u0003a\u0003a\u0003a\u0003a\u0003a\u0003a\u0003a\u0003", "a\u0003b\u0003b\u0003b\u0003b\u0003b\u0003b\u0003b\u0003c\u0003c\u0007", "c\u02ee\nc\fc\u000ec\u02f1\u000bc\u0003d\u0003d\u0007d\u02f5\nd\fd\u000e", "d\u02f8\u000bd\u0003d\u0003d\u0003d\u0007d\u02fd\nd\fd\u000ed\u0300", "\u000bd\u0003d\u0005d\u0303\nd\u0003e\u0006e\u0306\ne\re\u000ee\u0307", "\u0003e\u0003e\u0003f\u0003f\u0003f\u0003f\u0007f\u0310\nf\ff\u000e", "f\u0313\u000bf\u0003f\u0003f\u0003f\u0003f\u0003f\u0003g\u0003g\u0003", "g\u0003g\u0007g\u031e\ng\fg\u000eg\u0321\u000bg\u0003g\u0003g\u0003", "h\u0003h\u0003i\u0003i\u0003i\u0003i\u0005i\u032b\ni\u0003j\u0003j\u0003", "j\u0003j\u0005j\u0331\nj\u0003k\u0003k\u0003k\u0003k\u0005k\u0337\n", "k\u0003l\u0003l\u0005l\u033b\nl\u0003m\u0003m\u0003m\u0003m\u0003n\u0003", "n\u0003n\u0003n\u0003n\u0003n\u0003o\u0003o\u0003p\u0003p\u0003q\u0003", "q\u0003q\u0005q\u034e\nq\u0003r\u0003r\u0003r\u0003s\u0003s\u0003s\u0005", "s\u0356\ns\u0003t\u0003t\u0003u\u0003u\u0003v\u0003v\u0003w\u0003w\u0003", "w\u0007w\u0361\nw\fw\u000ew\u0364\u000bw\u0005w\u0366\nw\u0003x\u0003", "x\u0005x\u036a\nx\u0003x\u0006x\u036d\nx\rx\u000ex\u036e\u0003y\u0003", "y\u0003y\u0003y\u0005y\u0375\ny\u0003z\u0003z\u0003z\u0003z\u0003z\u0003", "z\u0005z\u037d\nz\u0003{\u0005{\u0380\n{\u0003|\u0005|\u0383\n|\u0003", "}\u0005}\u0386\n}\u0003~\u0005~\u0389\n~\u0003\u007f\u0003\u007f\u0003", "\u0080\u0003\u0080\u0003\u0081\u0003\u0081\u0007\u0081\u0391\n\u0081", "\f\u0081\u000e\u0081\u0394\u000b\u0081\u0003\u0082\u0007\u0082\u0397", "\n\u0082\f\u0082\u000e\u0082\u039a\u000b\u0082\u0003\u0083\u0003\u0083", "\u0003\u0083\u0005\u0083\u039f\n\u0083\u0003\u0084\u0003\u0084\u0003", "\u0084\u0005\u0084\u03a4\n\u0084\u0003\u0085\u0003\u0085\u0003\u0086", "\u0003\u0086\u0003\u0086\u0003\u0087\u0003\u0087\u0007\u0087\u03ad\n", "\u0087\f\u0087\u000e\u0087\u03b0\u000b\u0087\u0003\u0087\u0003\u0087", "\u0003\u0088\u0003\u0088\u0005\u0088\u03b6\n\u0088\u0003\u0311\u0002", "\u0089\u0003\u0003\u0005\u0004\u0007\u0005\t\u0006\u000b\u0007\r\b\u000f", "\t\u0011\n\u0013\u000b\u0015\f\u0017\r\u0019\u000e\u001b\u000f\u001d", "\u0010\u001f\u0011!\u0012#\u0013%\u0014\'\u0015)\u0016+\u0017-\u0018", "/\u00191\u001a3\u001b5\u001c7\u001d9\u001e;\u001f= ?!A\"C#E$G%I&K\'", "M(O)Q*S+U,W-Y.[/]0_1a2c3e4g5i6k7m8o9q:s;u<w=y>{?}@\u007fA\u0081B\u0083", "C\u0085D\u0087E\u0089F\u008bG\u008dH\u008fI\u0091J\u0093K\u0095L\u0097", "M\u0099N\u009bO\u009dP\u009fQ\u00a1R\u00a3S\u00a5T\u00a7U\u00a9V\u00ab", "W\u00adX\u00afY\u00b1Z\u00b3[\u00b5\\\u00b7]\u00b9^\u00bb_\u00bd`\u00bf", "a\u00c1b\u00c3c\u00c5d\u00c7e\u00c9f\u00cbg\u00cdh\u00cfi\u00d1\u0002", "\u00d3\u0002\u00d5\u0002\u00d7\u0002\u00d9\u0002\u00db\u0002\u00dd\u0002", "\u00df\u0002\u00e1\u0002\u00e3\u0002\u00e5\u0002\u00e7\u0002\u00e9\u0002", "\u00eb\u0002\u00ed\u0002\u00ef\u0002\u00f1\u0002\u00f3\u0002\u00f5\u0002", "\u00f7\u0002\u00f9\u0002\u00fb\u0002\u00fd\u0002\u00ff\u0002\u0101\u0002", "\u0103\u0002\u0105\u0002\u0107\u0002\u0109\u0002\u010b\u0002\u010d\u0002", "\u010f\u0002\u0003\u0002\u0018\u0005\u0002\f\f\u000f\u000f\u202a\u202b", "\u0004\u0002ZZzz\u0006\u0002\u000b\u000b\r\u000e\"\"\u00a2\u00a2\u0006", "\u0002\f\f\u000f\u000f$$^^\u0006\u0002\f\f\u000f\u000f))^^\u000b\u0002", "$$))^^ddhhppttvvxx\u000e\u0002\f\f\u000f\u000f$$))2;^^ddhhppttvxzz\u0004", "\u0002wwzz\u0003\u00022;\u0005\u00022;CHch\u0003\u000229\u0003\u0002", "3;\u0004\u0002GGgg\u0004\u0002--//\u0004\u0002&&aa\u0104\u0002C\\c|", "\u00ac\u00ac\u00b7\u00b7\u00bc\u00bc\u00c2\u00d8\u00da\u00f8\u00fa\u0221", "\u0224\u0235\u0252\u02af\u02b2\u02ba\u02bd\u02c3\u02d2\u02d3\u02e2\u02e6", "\u02f0\u02f0\u037c\u037c\u0388\u0388\u038a\u038c\u038e\u038e\u0390\u03a3", "\u03a5\u03d0\u03d2\u03d9\u03dc\u03f5\u0402\u0483\u048e\u04c6\u04c9\u04ca", "\u04cd\u04ce\u04d2\u04f7\u04fa\u04fb\u0533\u0558\u055b\u055b\u0563\u0589", "\u05d2\u05ec\u05f2\u05f4\u0623\u063c\u0642\u064c\u0673\u06d5\u06d7\u06d7", "\u06e7\u06e8\u06fc\u06fe\u0712\u0712\u0714\u072e\u0782\u07a7\u0907\u093b", "\u093f\u093f\u0952\u0952\u095a\u0963\u0987\u098e\u0991\u0992\u0995\u09aa", "\u09ac\u09b2\u09b4\u09b4\u09b8\u09bb\u09de\u09df\u09e1\u09e3\u09f2\u09f3", "\u0a07\u0a0c\u0a11\u0a12\u0a15\u0a2a\u0a2c\u0a32\u0a34\u0a35\u0a37\u0a38", "\u0a3a\u0a3b\u0a5b\u0a5e\u0a60\u0a60\u0a74\u0a76\u0a87\u0a8d\u0a8f\u0a8f", "\u0a91\u0a93\u0a95\u0aaa\u0aac\u0ab2\u0ab4\u0ab5\u0ab7\u0abb\u0abf\u0abf", "\u0ad2\u0ad2\u0ae2\u0ae2\u0b07\u0b0e\u0b11\u0b12\u0b15\u0b2a\u0b2c\u0b32", "\u0b34\u0b35\u0b38\u0b3b\u0b3f\u0b3f\u0b5e\u0b5f\u0b61\u0b63\u0b87\u0b8c", "\u0b90\u0b92\u0b94\u0b97\u0b9b\u0b9c\u0b9e\u0b9e\u0ba0\u0ba1\u0ba5\u0ba6", "\u0baa\u0bac\u0bb0\u0bb7\u0bb9\u0bbb\u0c07\u0c0e\u0c10\u0c12\u0c14\u0c2a", "\u0c2c\u0c35\u0c37\u0c3b\u0c62\u0c63\u0c87\u0c8e\u0c90\u0c92\u0c94\u0caa", "\u0cac\u0cb5\u0cb7\u0cbb\u0ce0\u0ce0\u0ce2\u0ce3\u0d07\u0d0e\u0d10\u0d12", "\u0d14\u0d2a\u0d2c\u0d3b\u0d62\u0d63\u0d87\u0d98\u0d9c\u0db3\u0db5\u0dbd", "\u0dbf\u0dbf\u0dc2\u0dc8\u0e03\u0e32\u0e34\u0e35\u0e42\u0e48\u0e83\u0e84", "\u0e86\u0e86\u0e89\u0e8a\u0e8c\u0e8c\u0e8f\u0e8f\u0e96\u0e99\u0e9b\u0ea1", "\u0ea3\u0ea5\u0ea7\u0ea7\u0ea9\u0ea9\u0eac\u0ead\u0eaf\u0eb2\u0eb4\u0eb5", "\u0ebf\u0ec6\u0ec8\u0ec8\u0ede\u0edf\u0f02\u0f02\u0f42\u0f6c\u0f8a\u0f8d", "\u1002\u1023\u1025\u1029\u102b\u102c\u1052\u1057\u10a2\u10c7\u10d2\u10f8", "\u1102\u115b\u1161\u11a4\u11aa\u11fb\u1202\u1208\u120a\u1248\u124a\u124a", "\u124c\u124f\u1252\u1258\u125a\u125a\u125c\u125f\u1262\u1288\u128a\u128a", "\u128c\u128f\u1292\u12b0\u12b2\u12b2\u12b4\u12b7\u12ba\u12c0\u12c2\u12c2", "\u12c4\u12c7\u12ca\u12d0\u12d2\u12d8\u12da\u12f0\u12f2\u1310\u1312\u1312", "\u1314\u1317\u131a\u1320\u1322\u1348\u134a\u135c\u13a2\u13f6\u1403\u1678", "\u1683\u169c\u16a2\u16ec\u1782\u17b5\u1822\u1879\u1882\u18aa\u1e02\u1e9d", "\u1ea2\u1efb\u1f02\u1f17\u1f1a\u1f1f\u1f22\u1f47\u1f4a\u1f4f\u1f52\u1f59", "\u1f5b\u1f5b\u1f5d\u1f5d\u1f5f\u1f5f\u1f61\u1f7f\u1f82\u1fb6\u1fb8\u1fbe", "\u1fc0\u1fc0\u1fc4\u1fc6\u1fc8\u1fce\u1fd2\u1fd5\u1fd8\u1fdd\u1fe2\u1fee", "\u1ff4\u1ff6\u1ff8\u1ffe\u2081\u2081\u2104\u2104\u2109\u2109\u210c\u2115", "\u2117\u2117\u211b\u211f\u2126\u2126\u2128\u2128\u212a\u212a\u212c\u212f", "\u2131\u2133\u2135\u213b\u2162\u2185\u3007\u3009\u3023\u302b\u3033\u3037", "\u303a\u303c\u3043\u3096\u309f\u30a0\u30a3\u30fc\u30fe\u3100\u3107\u312e", "\u3133\u3190\u31a2\u31b9\u3402\u3402\u4db7\u4db7\u4e02\u4e02\u9fa7\u9fa7", "\ua002\ua48e\uac02\uac02\ud7a5\ud7a5\uf902\ufa2f\ufb02\ufb08\ufb15\ufb19", "\ufb1f\ufb1f\ufb21\ufb2a\ufb2c\ufb38\ufb3a\ufb3e\ufb40\ufb40\ufb42\ufb43", "\ufb45\ufb46\ufb48\ufbb3\ufbd5\ufd3f\ufd52\ufd91\ufd94\ufdc9\ufdf2\ufdfd", "\ufe72\ufe74\ufe76\ufe76\ufe78\ufefe\uff23\uff3c\uff43\uff5c\uff68\uffc0", "\uffc4\uffc9\uffcc\uffd1\uffd4\uffd9\uffdc\uffdef\u0002\u0302\u0350", "\u0362\u0364\u0485\u0488\u0593\u05a3\u05a5\u05bb\u05bd\u05bf\u05c1\u05c1", "\u05c3\u05c4\u05c6\u05c6\u064d\u0657\u0672\u0672\u06d8\u06de\u06e1\u06e6", "\u06e9\u06ea\u06ec\u06ef\u0713\u0713\u0732\u074c\u07a8\u07b2\u0903\u0905", "\u093e\u093e\u0940\u094f\u0953\u0956\u0964\u0965\u0983\u0985\u09be\u09c6", "\u09c9\u09ca\u09cd\u09cf\u09d9\u09d9\u09e4\u09e5\u0a04\u0a04\u0a3e\u0a3e", "\u0a40\u0a44\u0a49\u0a4a\u0a4d\u0a4f\u0a72\u0a73\u0a83\u0a85\u0abe\u0abe", "\u0ac0\u0ac7\u0ac9\u0acb\u0acd\u0acf\u0b03\u0b05\u0b3e\u0b3e\u0b40\u0b45", "\u0b49\u0b4a\u0b4d\u0b4f\u0b58\u0b59\u0b84\u0b85\u0bc0\u0bc4\u0bc8\u0bca", "\u0bcc\u0bcf\u0bd9\u0bd9\u0c03\u0c05\u0c40\u0c46\u0c48\u0c4a\u0c4c\u0c4f", "\u0c57\u0c58\u0c84\u0c85\u0cc0\u0cc6\u0cc8\u0cca\u0ccc\u0ccf\u0cd7\u0cd8", "\u0d04\u0d05\u0d40\u0d45\u0d48\u0d4a\u0d4c\u0d4f\u0d59\u0d59\u0d84\u0d85", "\u0dcc\u0dcc\u0dd1\u0dd6\u0dd8\u0dd8\u0dda\u0de1\u0df4\u0df5\u0e33\u0e33", "\u0e36\u0e3c\u0e49\u0e50\u0eb3\u0eb3\u0eb6\u0ebb\u0ebd\u0ebe\u0eca\u0ecf", "\u0f1a\u0f1b\u0f37\u0f37\u0f39\u0f39\u0f3b\u0f3b\u0f40\u0f41\u0f73\u0f86", "\u0f88\u0f89\u0f92\u0f99\u0f9b\u0fbe\u0fc8\u0fc8\u102e\u1034\u1038\u103b", "\u1058\u105b\u17b6\u17d5\u18ab\u18ab\u20d2\u20de\u20e3\u20e3\u302c\u3031", "\u309b\u309c\ufb20\ufb20\ufe22\ufe25\u0016\u00022;\u0662\u066b\u06f2", "\u06fb\u0968\u0971\u09e8\u09f1\u0a68\u0a71\u0ae8\u0af1\u0b68\u0b71\u0be9", "\u0bf1\u0c68\u0c71\u0ce8\u0cf1\u0d68\u0d71\u0e52\u0e5b\u0ed2\u0edb\u0f22", "\u0f2b\u1042\u104b\u136b\u1373\u17e2\u17eb\u1812\u181b\uff12\uff1b\t", "\u0002aa\u2041\u2042\u30fd\u30fd\ufe35\ufe36\ufe4f\ufe51\uff41\uff41", "\uff67\uff67\b\u0002\f\f\u000f\u000f,,11]^\u202a\u202b\u0007\u0002\f", "\f\u000f\u000f11]^\u202a\u202b\u0006\u0002\f\f\u000f\u000f^_\u202a\u202b", "\u0002\u03c5\u0002\u0003\u0003\u0002\u0002\u0002\u0002\u0005\u0003\u0002", "\u0002\u0002\u0002\u0007\u0003\u0002\u0002\u0002\u0002\t\u0003\u0002", "\u0002\u0002\u0002\u000b\u0003\u0002\u0002\u0002\u0002\r\u0003\u0002", "\u0002\u0002\u0002\u000f\u0003\u0002\u0002\u0002\u0002\u0011\u0003\u0002", "\u0002\u0002\u0002\u0013\u0003\u0002\u0002\u0002\u0002\u0015\u0003\u0002", "\u0002\u0002\u0002\u0017\u0003\u0002\u0002\u0002\u0002\u0019\u0003\u0002", "\u0002\u0002\u0002\u001b\u0003\u0002\u0002\u0002\u0002\u001d\u0003\u0002", "\u0002\u0002\u0002\u001f\u0003\u0002\u0002\u0002\u0002!\u0003\u0002", "\u0002\u0002\u0002#\u0003\u0002\u0002\u0002\u0002%\u0003\u0002\u0002", "\u0002\u0002\'\u0003\u0002\u0002\u0002\u0002)\u0003\u0002\u0002\u0002", "\u0002+\u0003\u0002\u0002\u0002\u0002-\u0003\u0002\u0002\u0002\u0002", "/\u0003\u0002\u0002\u0002\u00021\u0003\u0002\u0002\u0002\u00023\u0003", "\u0002\u0002\u0002\u00025\u0003\u0002\u0002\u0002\u00027\u0003\u0002", "\u0002\u0002\u00029\u0003\u0002\u0002\u0002\u0002;\u0003\u0002\u0002", "\u0002\u0002=\u0003\u0002\u0002\u0002\u0002?\u0003\u0002\u0002\u0002", "\u0002A\u0003\u0002\u0002\u0002\u0002C\u0003\u0002\u0002\u0002\u0002", "E\u0003\u0002\u0002\u0002\u0002G\u0003\u0002\u0002\u0002\u0002I\u0003", "\u0002\u0002\u0002\u0002K\u0003\u0002\u0002\u0002\u0002M\u0003\u0002", "\u0002\u0002\u0002O\u0003\u0002\u0002\u0002\u0002Q\u0003\u0002\u0002", "\u0002\u0002S\u0003\u0002\u0002\u0002\u0002U\u0003\u0002\u0002\u0002", "\u0002W\u0003\u0002\u0002\u0002\u0002Y\u0003\u0002\u0002\u0002\u0002", "[\u0003\u0002\u0002\u0002\u0002]\u0003\u0002\u0002\u0002\u0002_\u0003", "\u0002\u0002\u0002\u0002a\u0003\u0002\u0002\u0002\u0002c\u0003\u0002", "\u0002\u0002\u0002e\u0003\u0002\u0002\u0002\u0002g\u0003\u0002\u0002", "\u0002\u0002i\u0003\u0002\u0002\u0002\u0002k\u0003\u0002\u0002\u0002", "\u0002m\u0003\u0002\u0002\u0002\u0002o\u0003\u0002\u0002\u0002\u0002", "q\u0003\u0002\u0002\u0002\u0002s\u0003\u0002\u0002\u0002\u0002u\u0003", "\u0002\u0002\u0002\u0002w\u0003\u0002\u0002\u0002\u0002y\u0003\u0002", "\u0002\u0002\u0002{\u0003\u0002\u0002\u0002\u0002}\u0003\u0002\u0002", "\u0002\u0002\u007f\u0003\u0002\u0002\u0002\u0002\u0081\u0003\u0002\u0002", "\u0002\u0002\u0083\u0003\u0002\u0002\u0002\u0002\u0085\u0003\u0002\u0002", "\u0002\u0002\u0087\u0003\u0002\u0002\u0002\u0002\u0089\u0003\u0002\u0002", "\u0002\u0002\u008b\u0003\u0002\u0002\u0002\u0002\u008d\u0003\u0002\u0002", "\u0002\u0002\u008f\u0003\u0002\u0002\u0002\u0002\u0091\u0003\u0002\u0002", "\u0002\u0002\u0093\u0003\u0002\u0002\u0002\u0002\u0095\u0003\u0002\u0002", "\u0002\u0002\u0097\u0003\u0002\u0002\u0002\u0002\u0099\u0003\u0002\u0002", "\u0002\u0002\u009b\u0003\u0002\u0002\u0002\u0002\u009d\u0003\u0002\u0002", "\u0002\u0002\u009f\u0003\u0002\u0002\u0002\u0002\u00a1\u0003\u0002\u0002", "\u0002\u0002\u00a3\u0003\u0002\u0002\u0002\u0002\u00a5\u0003\u0002\u0002", "\u0002\u0002\u00a7\u0003\u0002\u0002\u0002\u0002\u00a9\u0003\u0002\u0002", "\u0002\u0002\u00ab\u0003\u0002\u0002\u0002\u0002\u00ad\u0003\u0002\u0002", "\u0002\u0002\u00af\u0003\u0002\u0002\u0002\u0002\u00b1\u0003\u0002\u0002", "\u0002\u0002\u00b3\u0003\u0002\u0002\u0002\u0002\u00b5\u0003\u0002\u0002", "\u0002\u0002\u00b7\u0003\u0002\u0002\u0002\u0002\u00b9\u0003\u0002\u0002", "\u0002\u0002\u00bb\u0003\u0002\u0002\u0002\u0002\u00bd\u0003\u0002\u0002", "\u0002\u0002\u00bf\u0003\u0002\u0002\u0002\u0002\u00c1\u0003\u0002\u0002", "\u0002\u0002\u00c3\u0003\u0002\u0002\u0002\u0002\u00c5\u0003\u0002\u0002", "\u0002\u0002\u00c7\u0003\u0002\u0002\u0002\u0002\u00c9\u0003\u0002\u0002", "\u0002\u0002\u00cb\u0003\u0002\u0002\u0002\u0002\u00cd\u0003\u0002\u0002", "\u0002\u0002\u00cf\u0003\u0002\u0002\u0002\u0003\u0111\u0003\u0002\u0002", "\u0002\u0005\u0117\u0003\u0002\u0002\u0002\u0007\u011b\u0003\u0002\u0002", "\u0002\t\u011d\u0003\u0002\u0002\u0002\u000b\u011f\u0003\u0002\u0002", "\u0002\r\u0121\u0003\u0002\u0002\u0002\u000f\u0123\u0003\u0002\u0002", "\u0002\u0011\u0125\u0003\u0002\u0002\u0002\u0013\u0127\u0003\u0002\u0002", "\u0002\u0015\u0129\u0003\u0002\u0002\u0002\u0017\u012b\u0003\u0002\u0002", "\u0002\u0019\u012d\u0003\u0002\u0002\u0002\u001b\u012f\u0003\u0002\u0002", "\u0002\u001d\u0131\u0003\u0002\u0002\u0002\u001f\u0133\u0003\u0002\u0002", "\u0002!\u0136\u0003\u0002\u0002\u0002#\u0139\u0003\u0002\u0002\u0002", "%\u013b\u0003\u0002\u0002\u0002\'\u013d\u0003\u0002\u0002\u0002)\u013f", "\u0003\u0002\u0002\u0002+\u0141\u0003\u0002\u0002\u0002-\u0143\u0003", "\u0002\u0002\u0002/\u0145\u0003\u0002\u0002\u00021\u0147\u0003\u0002", "\u0002\u00023\u014a\u0003\u0002\u0002\u00025\u014d\u0003\u0002\u0002", "\u00027\u0151\u0003\u0002\u0002\u00029\u0153\u0003\u0002\u0002\u0002", ";\u0155\u0003\u0002\u0002\u0002=\u0158\u0003\u0002\u0002\u0002?\u015b", "\u0003\u0002\u0002\u0002A\u015e\u0003\u0002\u0002\u0002C\u0161\u0003", "\u0002\u0002\u0002E\u0165\u0003\u0002\u0002\u0002G\u0169\u0003\u0002", "\u0002\u0002I\u016b\u0003\u0002\u0002\u0002K\u016d\u0003\u0002\u0002", "\u0002M\u016f\u0003\u0002\u0002\u0002O\u0172\u0003\u0002\u0002\u0002", "Q\u0175\u0003\u0002\u0002\u0002S\u0178\u0003\u0002\u0002\u0002U\u017b", "\u0003\u0002\u0002\u0002W\u017e\u0003\u0002\u0002\u0002Y\u0181\u0003", "\u0002\u0002\u0002[\u0184\u0003\u0002\u0002\u0002]\u0188\u0003\u0002", "\u0002\u0002_\u018c\u0003\u0002\u0002\u0002a\u0191\u0003\u0002\u0002", "\u0002c\u0194\u0003\u0002\u0002\u0002e\u0197\u0003\u0002\u0002\u0002", "g\u019a\u0003\u0002\u0002\u0002i\u01a8\u0003\u0002\u0002\u0002k\u01c2", "\u0003\u0002\u0002\u0002m\u01c4\u0003\u0002\u0002\u0002o\u01cb\u0003", "\u0002\u0002\u0002q\u01d2\u0003\u0002\u0002\u0002s\u01d8\u0003\u0002", "\u0002\u0002u\u01db\u0003\u0002\u0002\u0002w\u01e6\u0003\u0002\u0002", "\u0002y\u01ed\u0003\u0002\u0002\u0002{\u01f2\u0003\u0002\u0002\u0002", "}\u01f7\u0003\u0002\u0002\u0002\u007f\u01fb\u0003\u0002\u0002\u0002", "\u0081\u01ff\u0003\u0002\u0002\u0002\u0083\u0205\u0003\u0002\u0002\u0002", "\u0085\u020d\u0003\u0002\u0002\u0002\u0087\u0214\u0003\u0002\u0002\u0002", "\u0089\u0219\u0003\u0002\u0002\u0002\u008b\u0222\u0003\u0002\u0002\u0002", "\u008d\u0226\u0003\u0002\u0002\u0002\u008f\u022d\u0003\u0002\u0002\u0002", "\u0091\u0233\u0003\u0002\u0002\u0002\u0093\u023c\u0003\u0002\u0002\u0002", "\u0095\u0245\u0003\u0002\u0002\u0002\u0097\u024a\u0003\u0002\u0002\u0002", "\u0099\u024f\u0003\u0002\u0002\u0002\u009b\u0257\u0003\u0002\u0002\u0002", "\u009d\u025a\u0003\u0002\u0002\u0002\u009f\u0260\u0003\u0002\u0002\u0002", "\u00a1\u0267\u0003\u0002\u0002\u0002\u00a3\u026a\u0003\u0002\u0002\u0002", "\u00a5\u026e\u0003\u0002\u0002\u0002\u00a7\u0274\u0003\u0002\u0002\u0002", "\u00a9\u0279\u0003\u0002\u0002\u0002\u00ab\u0281\u0003\u0002\u0002\u0002", "\u00ad\u0287\u0003\u0002\u0002\u0002\u00af\u028d\u0003\u0002\u0002\u0002", "\u00b1\u0294\u0003\u0002\u0002\u0002\u00b3\u029b\u0003\u0002\u0002\u0002", "\u00b5\u02a7\u0003\u0002\u0002\u0002\u00b7\u02ac\u0003\u0002\u0002\u0002", "\u00b9\u02b5\u0003\u0002\u0002\u0002\u00bb\u02bd\u0003\u0002\u0002\u0002", "\u00bd\u02c8\u0003\u0002\u0002\u0002\u00bf\u02d1\u0003\u0002\u0002\u0002", "\u00c1\u02dc\u0003\u0002\u0002\u0002\u00c3\u02e4\u0003\u0002\u0002\u0002", "\u00c5\u02eb\u0003\u0002\u0002\u0002\u00c7\u0302\u0003\u0002\u0002\u0002", "\u00c9\u0305\u0003\u0002\u0002\u0002\u00cb\u030b\u0003\u0002\u0002\u0002", "\u00cd\u0319\u0003\u0002\u0002\u0002\u00cf\u0324\u0003\u0002\u0002\u0002", "\u00d1\u032a\u0003\u0002\u0002\u0002\u00d3\u0330\u0003\u0002\u0002\u0002", "\u00d5\u0336\u0003\u0002\u0002\u0002\u00d7\u033a\u0003\u0002\u0002\u0002", "\u00d9\u033c\u0003\u0002\u0002\u0002\u00db\u0340\u0003\u0002\u0002\u0002", "\u00dd\u0346\u0003\u0002\u0002\u0002\u00df\u0348\u0003\u0002\u0002\u0002", "\u00e1\u034d\u0003\u0002\u0002\u0002\u00e3\u034f\u0003\u0002\u0002\u0002", "\u00e5\u0355\u0003\u0002\u0002\u0002\u00e7\u0357\u0003\u0002\u0002\u0002", "\u00e9\u0359\u0003\u0002\u0002\u0002\u00eb\u035b\u0003\u0002\u0002\u0002", "\u00ed\u0365\u0003\u0002\u0002\u0002\u00ef\u0367\u0003\u0002\u0002\u0002", "\u00f1\u0374\u0003\u0002\u0002\u0002\u00f3\u037c\u0003\u0002\u0002\u0002", "\u00f5\u037f\u0003\u0002\u0002\u0002\u00f7\u0382\u0003\u0002\u0002\u0002", "\u00f9\u0385\u0003\u0002\u0002\u0002\u00fb\u0388\u0003\u0002\u0002\u0002", "\u00fd\u038a\u0003\u0002\u0002\u0002\u00ff\u038c\u0003\u0002\u0002\u0002", "\u0101\u038e\u0003\u0002\u0002\u0002\u0103\u0398\u0003\u0002\u0002\u0002", "\u0105\u039e\u0003\u0002\u0002\u0002\u0107\u03a3\u0003\u0002\u0002\u0002", "\u0109\u03a5\u0003\u0002\u0002\u0002\u010b\u03a7\u0003\u0002\u0002\u0002", "\u010d\u03aa\u0003\u0002\u0002\u0002\u010f\u03b5\u0003\u0002\u0002\u0002", "\u0111\u0112\u0006\u0002\u0002\u0002\u0112\u0113\u00071\u0002\u0002", "\u0113\u0114\u0005\u0101\u0081\u0002\u0114\u0115\u00071\u0002\u0002", "\u0115\u0116\u0005\u0103\u0082\u0002\u0116\u0004\u0003\u0002\u0002\u0002", "\u0117\u0118\t\u0002\u0002\u0002\u0118\u0119\u0003\u0002\u0002\u0002", "\u0119\u011a\b\u0003\u0002\u0002\u011a\u0006\u0003\u0002\u0002\u0002", "\u011b\u011c\u0007]\u0002\u0002\u011c\b\u0003\u0002\u0002\u0002\u011d", "\u011e\u0007_\u0002\u0002\u011e\n\u0003\u0002\u0002\u0002\u011f\u0120", "\u0007*\u0002\u0002\u0120\f\u0003\u0002\u0002\u0002\u0121\u0122\u0007", "+\u0002\u0002\u0122\u000e\u0003\u0002\u0002\u0002\u0123\u0124\u0007", "}\u0002\u0002\u0124\u0010\u0003\u0002\u0002\u0002\u0125\u0126\u0007", "\u007f\u0002\u0002\u0126\u0012\u0003\u0002\u0002\u0002\u0127\u0128\u0007", "=\u0002\u0002\u0128\u0014\u0003\u0002\u0002\u0002\u0129\u012a\u0007", ".\u0002\u0002\u012a\u0016\u0003\u0002\u0002\u0002\u012b\u012c\u0007", "?\u0002\u0002\u012c\u0018\u0003\u0002\u0002\u0002\u012d\u012e\u0007", "A\u0002\u0002\u012e\u001a\u0003\u0002\u0002\u0002\u012f\u0130\u0007", "<\u0002\u0002\u0130\u001c\u0003\u0002\u0002\u0002\u0131\u0132\u0007", "0\u0002\u0002\u0132\u001e\u0003\u0002\u0002\u0002\u0133\u0134\u0007", "-\u0002\u0002\u0134\u0135\u0007-\u0002\u0002\u0135 \u0003\u0002\u0002", "\u0002\u0136\u0137\u0007/\u0002\u0002\u0137\u0138\u0007/\u0002\u0002", "\u0138\"\u0003\u0002\u0002\u0002\u0139\u013a\u0007-\u0002\u0002\u013a", "$\u0003\u0002\u0002\u0002\u013b\u013c\u0007/\u0002\u0002\u013c&\u0003", "\u0002\u0002\u0002\u013d\u013e\u0007\u0080\u0002\u0002\u013e(\u0003", "\u0002\u0002\u0002\u013f\u0140\u0007#\u0002\u0002\u0140*\u0003\u0002", "\u0002\u0002\u0141\u0142\u0007,\u0002\u0002\u0142,\u0003\u0002\u0002", "\u0002\u0143\u0144\u00071\u0002\u0002\u0144.\u0003\u0002\u0002\u0002", "\u0145\u0146\u0007\'\u0002\u0002\u01460\u0003\u0002\u0002\u0002\u0147", "\u0148\u0007@\u0002\u0002\u0148\u0149\u0007@\u0002\u0002\u01492\u0003", "\u0002\u0002\u0002\u014a\u014b\u0007>\u0002\u0002\u014b\u014c\u0007", ">\u0002\u0002\u014c4\u0003\u0002\u0002\u0002\u014d\u014e\u0007@\u0002", "\u0002\u014e\u014f\u0007@\u0002\u0002\u014f\u0150\u0007@\u0002\u0002", "\u01506\u0003\u0002\u0002\u0002\u0151\u0152\u0007>\u0002\u0002\u0152", "8\u0003\u0002\u0002\u0002\u0153\u0154\u0007@\u0002\u0002\u0154:\u0003", "\u0002\u0002\u0002\u0155\u0156\u0007>\u0002\u0002\u0156\u0157\u0007", "?\u0002\u0002\u0157<\u0003\u0002\u0002\u0002\u0158\u0159\u0007@\u0002", "\u0002\u0159\u015a\u0007?\u0002\u0002\u015a>\u0003\u0002\u0002\u0002", "\u015b\u015c\u0007?\u0002\u0002\u015c\u015d\u0007?\u0002\u0002\u015d", "@\u0003\u0002\u0002\u0002\u015e\u015f\u0007#\u0002\u0002\u015f\u0160", "\u0007?\u0002\u0002\u0160B\u0003\u0002\u0002\u0002\u0161\u0162\u0007", "?\u0002\u0002\u0162\u0163\u0007?\u0002\u0002\u0163\u0164\u0007?\u0002", "\u0002\u0164D\u0003\u0002\u0002\u0002\u0165\u0166\u0007#\u0002\u0002", "\u0166\u0167\u0007?\u0002\u0002\u0167\u0168\u0007?\u0002\u0002\u0168", "F\u0003\u0002\u0002\u0002\u0169\u016a\u0007(\u0002\u0002\u016aH\u0003", "\u0002\u0002\u0002\u016b\u016c\u0007`\u0002\u0002\u016cJ\u0003\u0002", "\u0002\u0002\u016d\u016e\u0007~\u0002\u0002\u016eL\u0003\u0002\u0002", "\u0002\u016f\u0170\u0007(\u0002\u0002\u0170\u0171\u0007(\u0002\u0002", "\u0171N\u0003\u0002\u0002\u0002\u0172\u0173\u0007~\u0002\u0002\u0173", "\u0174\u0007~\u0002\u0002\u0174P\u0003\u0002\u0002\u0002\u0175\u0176", "\u0007,\u0002\u0002\u0176\u0177\u0007?\u0002\u0002\u0177R\u0003\u0002", "\u0002\u0002\u0178\u0179\u00071\u0002\u0002\u0179\u017a\u0007?\u0002", "\u0002\u017aT\u0003\u0002\u0002\u0002\u017b\u017c\u0007\'\u0002\u0002", "\u017c\u017d\u0007?\u0002\u0002\u017dV\u0003\u0002\u0002\u0002\u017e", "\u017f\u0007-\u0002\u0002\u017f\u0180\u0007?\u0002\u0002\u0180X\u0003", "\u0002\u0002\u0002\u0181\u0182\u0007/\u0002\u0002\u0182\u0183\u0007", "?\u0002\u0002\u0183Z\u0003\u0002\u0002\u0002\u0184\u0185\u0007>\u0002", "\u0002\u0185\u0186\u0007>\u0002\u0002\u0186\u0187\u0007?\u0002\u0002", "\u0187\\\u0003\u0002\u0002\u0002\u0188\u0189\u0007@\u0002\u0002\u0189", "\u018a\u0007@\u0002\u0002\u018a\u018b\u0007?\u0002\u0002\u018b^\u0003", "\u0002\u0002\u0002\u018c\u018d\u0007@\u0002\u0002\u018d\u018e\u0007", "@\u0002\u0002\u018e\u018f\u0007@\u0002\u0002\u018f\u0190\u0007?\u0002", "\u0002\u0190`\u0003\u0002\u0002\u0002\u0191\u0192\u0007(\u0002\u0002", "\u0192\u0193\u0007?\u0002\u0002\u0193b\u0003\u0002\u0002\u0002\u0194", "\u0195\u0007`\u0002\u0002\u0195\u0196\u0007?\u0002\u0002\u0196d\u0003", "\u0002\u0002\u0002\u0197\u0198\u0007~\u0002\u0002\u0198\u0199\u0007", "?\u0002\u0002\u0199f\u0003\u0002\u0002\u0002\u019a\u019b\u0007p\u0002", "\u0002\u019b\u019c\u0007w\u0002\u0002\u019c\u019d\u0007n\u0002\u0002", "\u019d\u019e\u0007n\u0002\u0002\u019eh\u0003\u0002\u0002\u0002\u019f", "\u01a0\u0007v\u0002\u0002\u01a0\u01a1\u0007t\u0002\u0002\u01a1\u01a2", "\u0007w\u0002\u0002\u01a2\u01a9\u0007g\u0002\u0002\u01a3\u01a4\u0007", "h\u0002\u0002\u01a4\u01a5\u0007c\u0002\u0002\u01a5\u01a6\u0007n\u0002", "\u0002\u01a6\u01a7\u0007u\u0002\u0002\u01a7\u01a9\u0007g\u0002\u0002", "\u01a8\u019f\u0003\u0002\u0002\u0002\u01a8\u01a3\u0003\u0002\u0002\u0002", "\u01a9j\u0003\u0002\u0002\u0002\u01aa\u01ab\u0005\u00edw\u0002\u01ab", "\u01af\u00070\u0002\u0002\u01ac\u01ae\u0005\u00e7t\u0002\u01ad\u01ac", "\u0003\u0002\u0002\u0002\u01ae\u01b1\u0003\u0002\u0002\u0002\u01af\u01ad", "\u0003\u0002\u0002\u0002\u01af\u01b0\u0003\u0002\u0002\u0002\u01b0\u01b3", "\u0003\u0002\u0002\u0002\u01b1\u01af\u0003\u0002\u0002\u0002\u01b2\u01b4", "\u0005\u00efx\u0002\u01b3\u01b2\u0003\u0002\u0002\u0002\u01b3\u01b4", "\u0003\u0002\u0002\u0002\u01b4\u01c3\u0003\u0002\u0002\u0002\u01b5\u01b7", "\u00070\u0002\u0002\u01b6\u01b8\u0005\u00e7t\u0002\u01b7\u01b6\u0003", "\u0002\u0002\u0002\u01b8\u01b9\u0003\u0002\u0002\u0002\u01b9\u01b7\u0003", "\u0002\u0002\u0002\u01b9\u01ba\u0003\u0002\u0002\u0002\u01ba\u01bc\u0003", "\u0002\u0002\u0002\u01bb\u01bd\u0005\u00efx\u0002\u01bc\u01bb\u0003", "\u0002\u0002\u0002\u01bc\u01bd\u0003\u0002\u0002\u0002\u01bd\u01c3\u0003", "\u0002\u0002\u0002\u01be\u01c0\u0005\u00edw\u0002\u01bf\u01c1\u0005", "\u00efx\u0002\u01c0\u01bf\u0003\u0002\u0002\u0002\u01c0\u01c1\u0003", "\u0002\u0002\u0002\u01c1\u01c3\u0003\u0002\u0002\u0002\u01c2\u01aa\u0003", "\u0002\u0002\u0002\u01c2\u01b5\u0003\u0002\u0002\u0002\u01c2\u01be\u0003", "\u0002\u0002\u0002\u01c3l\u0003\u0002\u0002\u0002\u01c4\u01c5\u0007", "2\u0002\u0002\u01c5\u01c7\t\u0003\u0002\u0002\u01c6\u01c8\u0005\u00e9", "u\u0002\u01c7\u01c6\u0003\u0002\u0002\u0002\u01c8\u01c9\u0003\u0002", "\u0002\u0002\u01c9\u01c7\u0003\u0002\u0002\u0002\u01c9\u01ca\u0003\u0002", "\u0002\u0002\u01can\u0003\u0002\u0002\u0002\u01cb\u01cc\u00068\u0003", "\u0002\u01cc\u01ce\u00072\u0002\u0002\u01cd\u01cf\u0005\u00ebv\u0002", "\u01ce\u01cd\u0003\u0002\u0002\u0002\u01cf\u01d0\u0003\u0002\u0002\u0002", "\u01d0\u01ce\u0003\u0002\u0002\u0002\u01d0\u01d1\u0003\u0002\u0002\u0002", "\u01d1p\u0003\u0002\u0002\u0002\u01d2\u01d3\u0007d\u0002\u0002\u01d3", "\u01d4\u0007t\u0002\u0002\u01d4\u01d5\u0007g\u0002\u0002\u01d5\u01d6", "\u0007c\u0002\u0002\u01d6\u01d7\u0007m\u0002\u0002\u01d7r\u0003\u0002", "\u0002\u0002\u01d8\u01d9\u0007f\u0002\u0002\u01d9\u01da\u0007q\u0002", "\u0002\u01dat\u0003\u0002\u0002\u0002\u01db\u01dc\u0007k\u0002\u0002", "\u01dc\u01dd\u0007p\u0002\u0002\u01dd\u01de\u0007u\u0002\u0002\u01de", "\u01df\u0007v\u0002\u0002\u01df\u01e0\u0007c\u0002\u0002\u01e0\u01e1", "\u0007p\u0002\u0002\u01e1\u01e2\u0007e\u0002\u0002\u01e2\u01e3\u0007", "g\u0002\u0002\u01e3\u01e4\u0007q\u0002\u0002\u01e4\u01e5\u0007h\u0002", "\u0002\u01e5v\u0003\u0002\u0002\u0002\u01e6\u01e7\u0007v\u0002\u0002", "\u01e7\u01e8\u0007{\u0002\u0002\u01e8\u01e9\u0007r\u0002\u0002\u01e9", "\u01ea\u0007g\u0002\u0002\u01ea\u01eb\u0007q\u0002\u0002\u01eb\u01ec", "\u0007h\u0002\u0002\u01ecx\u0003\u0002\u0002\u0002\u01ed\u01ee\u0007", "e\u0002\u0002\u01ee\u01ef\u0007c\u0002\u0002\u01ef\u01f0\u0007u\u0002", "\u0002\u01f0\u01f1\u0007g\u0002\u0002\u01f1z\u0003\u0002\u0002\u0002", "\u01f2\u01f3\u0007g\u0002\u0002\u01f3\u01f4\u0007n\u0002\u0002\u01f4", "\u01f5\u0007u\u0002\u0002\u01f5\u01f6\u0007g\u0002\u0002\u01f6|\u0003", "\u0002\u0002\u0002\u01f7\u01f8\u0007p\u0002\u0002\u01f8\u01f9\u0007", "g\u0002\u0002\u01f9\u01fa\u0007y\u0002\u0002\u01fa~\u0003\u0002\u0002", "\u0002\u01fb\u01fc\u0007x\u0002\u0002\u01fc\u01fd\u0007c\u0002\u0002", "\u01fd\u01fe\u0007t\u0002\u0002\u01fe\u0080\u0003\u0002\u0002\u0002", "\u01ff\u0200\u0007e\u0002\u0002\u0200\u0201\u0007c\u0002\u0002\u0201", "\u0202\u0007v\u0002\u0002\u0202\u0203\u0007e\u0002\u0002\u0203\u0204", "\u0007j\u0002\u0002\u0204\u0082\u0003\u0002\u0002\u0002\u0205\u0206", "\u0007h\u0002\u0002\u0206\u0207\u0007k\u0002\u0002\u0207\u0208\u0007", "p\u0002\u0002\u0208\u0209\u0007c\u0002\u0002\u0209\u020a\u0007n\u0002", "\u0002\u020a\u020b\u0007n\u0002\u0002\u020b\u020c\u0007{\u0002\u0002", "\u020c\u0084\u0003\u0002\u0002\u0002\u020d\u020e\u0007t\u0002\u0002", "\u020e\u020f\u0007g\u0002\u0002\u020f\u0210\u0007v\u0002\u0002\u0210", "\u0211\u0007w\u0002\u0002\u0211\u0212\u0007t\u0002\u0002\u0212\u0213", "\u0007p\u0002\u0002\u0213\u0086\u0003\u0002\u0002\u0002\u0214\u0215", "\u0007x\u0002\u0002\u0215\u0216\u0007q\u0002\u0002\u0216\u0217\u0007", "k\u0002\u0002\u0217\u0218\u0007f\u0002\u0002\u0218\u0088\u0003\u0002", "\u0002\u0002\u0219\u021a\u0007e\u0002\u0002\u021a\u021b\u0007q\u0002", "\u0002\u021b\u021c\u0007p\u0002\u0002\u021c\u021d\u0007v\u0002\u0002", "\u021d\u021e\u0007k\u0002\u0002\u021e\u021f\u0007p\u0002\u0002\u021f", "\u0220\u0007w\u0002\u0002\u0220\u0221\u0007g\u0002\u0002\u0221\u008a", "\u0003\u0002\u0002\u0002\u0222\u0223\u0007h\u0002\u0002\u0223\u0224", "\u0007q\u0002\u0002\u0224\u0225\u0007t\u0002\u0002\u0225\u008c\u0003", "\u0002\u0002\u0002\u0226\u0227\u0007u\u0002\u0002\u0227\u0228\u0007", "y\u0002\u0002\u0228\u0229\u0007k\u0002\u0002\u0229\u022a\u0007v\u0002", "\u0002\u022a\u022b\u0007e\u0002\u0002\u022b\u022c\u0007j\u0002\u0002", "\u022c\u008e\u0003\u0002\u0002\u0002\u022d\u022e\u0007y\u0002\u0002", "\u022e\u022f\u0007j\u0002\u0002\u022f\u0230\u0007k\u0002\u0002\u0230", "\u0231\u0007n\u0002\u0002\u0231\u0232\u0007g\u0002\u0002\u0232\u0090", "\u0003\u0002\u0002\u0002\u0233\u0234\u0007f\u0002\u0002\u0234\u0235", "\u0007g\u0002\u0002\u0235\u0236\u0007d\u0002\u0002\u0236\u0237\u0007", "w\u0002\u0002\u0237\u0238\u0007i\u0002\u0002\u0238\u0239\u0007i\u0002", "\u0002\u0239\u023a\u0007g\u0002\u0002\u023a\u023b\u0007t\u0002\u0002", "\u023b\u0092\u0003\u0002\u0002\u0002\u023c\u023d\u0007h\u0002\u0002", "\u023d\u023e\u0007w\u0002\u0002\u023e\u023f\u0007p\u0002\u0002\u023f", "\u0240\u0007e\u0002\u0002\u0240\u0241\u0007v\u0002\u0002\u0241\u0242", "\u0007k\u0002\u0002\u0242\u0243\u0007q\u0002\u0002\u0243\u0244\u0007", "p\u0002\u0002\u0244\u0094\u0003\u0002\u0002\u0002\u0245\u0246\u0007", "v\u0002\u0002\u0246\u0247\u0007j\u0002\u0002\u0247\u0248\u0007k\u0002", "\u0002\u0248\u0249\u0007u\u0002\u0002\u0249\u0096\u0003\u0002\u0002", "\u0002\u024a\u024b\u0007y\u0002\u0002\u024b\u024c\u0007k\u0002\u0002", "\u024c\u024d\u0007v\u0002\u0002\u024d\u024e\u0007j\u0002\u0002\u024e", "\u0098\u0003\u0002\u0002\u0002\u024f\u0250\u0007f\u0002\u0002\u0250", "\u0251\u0007g\u0002\u0002\u0251\u0252\u0007h\u0002\u0002\u0252\u0253", "\u0007c\u0002\u0002\u0253\u0254\u0007w\u0002\u0002\u0254\u0255\u0007", "n\u0002\u0002\u0255\u0256\u0007v\u0002\u0002\u0256\u009a\u0003\u0002", "\u0002\u0002\u0257\u0258\u0007k\u0002\u0002\u0258\u0259\u0007h\u0002", "\u0002\u0259\u009c\u0003\u0002\u0002\u0002\u025a\u025b\u0007v\u0002", "\u0002\u025b\u025c\u0007j\u0002\u0002\u025c\u025d\u0007t\u0002\u0002", "\u025d\u025e\u0007q\u0002\u0002\u025e\u025f\u0007y\u0002\u0002\u025f", "\u009e\u0003\u0002\u0002\u0002\u0260\u0261\u0007f\u0002\u0002\u0261", "\u0262\u0007g\u0002\u0002\u0262\u0263\u0007n\u0002\u0002\u0263\u0264", "\u0007g\u0002\u0002\u0264\u0265\u0007v\u0002\u0002\u0265\u0266\u0007", "g\u0002\u0002\u0266\u00a0\u0003\u0002\u0002\u0002\u0267\u0268\u0007", "k\u0002\u0002\u0268\u0269\u0007p\u0002\u0002\u0269\u00a2\u0003\u0002", "\u0002\u0002\u026a\u026b\u0007v\u0002\u0002\u026b\u026c\u0007t\u0002", "\u0002\u026c\u026d\u0007{\u0002\u0002\u026d\u00a4\u0003\u0002\u0002", "\u0002\u026e\u026f\u0007e\u0002\u0002\u026f\u0270\u0007n\u0002\u0002", "\u0270\u0271\u0007c\u0002\u0002\u0271\u0272\u0007u\u0002\u0002\u0272", "\u0273\u0007u\u0002\u0002\u0273\u00a6\u0003\u0002\u0002\u0002\u0274", "\u0275\u0007g\u0002\u0002\u0275\u0276\u0007p\u0002\u0002\u0276\u0277", "\u0007w\u0002\u0002\u0277\u0278\u0007o\u0002\u0002\u0278\u00a8\u0003", "\u0002\u0002\u0002\u0279\u027a\u0007g\u0002\u0002\u027a\u027b\u0007", "z\u0002\u0002\u027b\u027c\u0007v\u0002\u0002\u027c\u027d\u0007g\u0002", "\u0002\u027d\u027e\u0007p\u0002\u0002\u027e\u027f\u0007f\u0002\u0002", "\u027f\u0280\u0007u\u0002\u0002\u0280\u00aa\u0003\u0002\u0002\u0002", "\u0281\u0282\u0007u\u0002\u0002\u0282\u0283\u0007w\u0002\u0002\u0283", "\u0284\u0007r\u0002\u0002\u0284\u0285\u0007g\u0002\u0002\u0285\u0286", "\u0007t\u0002\u0002\u0286\u00ac\u0003\u0002\u0002\u0002\u0287\u0288", "\u0007e\u0002\u0002\u0288\u0289\u0007q\u0002\u0002\u0289\u028a\u0007", "p\u0002\u0002\u028a\u028b\u0007u\u0002\u0002\u028b\u028c\u0007v\u0002", "\u0002\u028c\u00ae\u0003\u0002\u0002\u0002\u028d\u028e\u0007g\u0002", "\u0002\u028e\u028f\u0007z\u0002\u0002\u028f\u0290\u0007r\u0002\u0002", "\u0290\u0291\u0007q\u0002\u0002\u0291\u0292\u0007t\u0002\u0002\u0292", "\u0293\u0007v\u0002\u0002\u0293\u00b0\u0003\u0002\u0002\u0002\u0294", "\u0295\u0007k\u0002\u0002\u0295\u0296\u0007o\u0002\u0002\u0296\u0297", "\u0007r\u0002\u0002\u0297\u0298\u0007q\u0002\u0002\u0298\u0299\u0007", "t\u0002\u0002\u0299\u029a\u0007v\u0002\u0002\u029a\u00b2\u0003\u0002", "\u0002\u0002\u029b\u029c\u0006Z\u0004\u0002\u029c\u029d\u0007k\u0002", "\u0002\u029d\u029e\u0007o\u0002\u0002\u029e\u029f\u0007r\u0002\u0002", "\u029f\u02a0\u0007n\u0002\u0002\u02a0\u02a1\u0007g\u0002\u0002\u02a1", "\u02a2\u0007o\u0002\u0002\u02a2\u02a3\u0007g\u0002\u0002\u02a3\u02a4", "\u0007p\u0002\u0002\u02a4\u02a5\u0007v\u0002\u0002\u02a5\u02a6\u0007", "u\u0002\u0002\u02a6\u00b4\u0003\u0002\u0002\u0002\u02a7\u02a8\u0006", "[\u0005\u0002\u02a8\u02a9\u0007n\u0002\u0002\u02a9\u02aa\u0007g\u0002", "\u0002\u02aa\u02ab\u0007v\u0002\u0002\u02ab\u00b6\u0003\u0002\u0002", "\u0002\u02ac\u02ad\u0006\\\u0006\u0002\u02ad\u02ae\u0007r\u0002\u0002", "\u02ae\u02af\u0007t\u0002\u0002\u02af\u02b0\u0007k\u0002\u0002\u02b0", "\u02b1\u0007x\u0002\u0002\u02b1\u02b2\u0007c\u0002\u0002\u02b2\u02b3", "\u0007v\u0002\u0002\u02b3\u02b4\u0007g\u0002\u0002\u02b4\u00b8\u0003", "\u0002\u0002\u0002\u02b5\u02b6\u0006]\u0007\u0002\u02b6\u02b7\u0007", "r\u0002\u0002\u02b7\u02b8\u0007w\u0002\u0002\u02b8\u02b9\u0007d\u0002", "\u0002\u02b9\u02ba\u0007n\u0002\u0002\u02ba\u02bb\u0007k\u0002\u0002", "\u02bb\u02bc\u0007e\u0002\u0002\u02bc\u00ba\u0003\u0002\u0002\u0002", "\u02bd\u02be\u0006^\b\u0002\u02be\u02bf\u0007k\u0002\u0002\u02bf\u02c0", "\u0007p\u0002\u0002\u02c0\u02c1\u0007v\u0002\u0002\u02c1\u02c2\u0007", "g\u0002\u0002\u02c2\u02c3\u0007t\u0002\u0002\u02c3\u02c4\u0007h\u0002", "\u0002\u02c4\u02c5\u0007c\u0002\u0002\u02c5\u02c6\u0007e\u0002\u0002", "\u02c6\u02c7\u0007g\u0002\u0002\u02c7\u00bc\u0003\u0002\u0002\u0002", "\u02c8\u02c9\u0006_\t\u0002\u02c9\u02ca\u0007r\u0002\u0002\u02ca\u02cb", "\u0007c\u0002\u0002\u02cb\u02cc\u0007e\u0002\u0002\u02cc\u02cd\u0007", "m\u0002\u0002\u02cd\u02ce\u0007c\u0002\u0002\u02ce\u02cf\u0007i\u0002", "\u0002\u02cf\u02d0\u0007g\u0002\u0002\u02d0\u00be\u0003\u0002\u0002", "\u0002\u02d1\u02d2\u0006`\n\u0002\u02d2\u02d3\u0007r\u0002\u0002\u02d3", "\u02d4\u0007t\u0002\u0002\u02d4\u02d5\u0007q\u0002\u0002\u02d5\u02d6", "\u0007v\u0002\u0002\u02d6\u02d7\u0007g\u0002\u0002\u02d7\u02d8\u0007", "e\u0002\u0002\u02d8\u02d9\u0007v\u0002\u0002\u02d9\u02da\u0007g\u0002", "\u0002\u02da\u02db\u0007f\u0002\u0002\u02db\u00c0\u0003\u0002\u0002", "\u0002\u02dc\u02dd\u0006a\u000b\u0002\u02dd\u02de\u0007u\u0002\u0002", "\u02de\u02df\u0007v\u0002\u0002\u02df\u02e0\u0007c\u0002\u0002\u02e0", "\u02e1\u0007v\u0002\u0002\u02e1\u02e2\u0007k\u0002\u0002\u02e2\u02e3", "\u0007e\u0002\u0002\u02e3\u00c2\u0003\u0002\u0002\u0002\u02e4\u02e5", "\u0006b\f\u0002\u02e5\u02e6\u0007{\u0002\u0002\u02e6\u02e7\u0007k\u0002", "\u0002\u02e7\u02e8\u0007g\u0002\u0002\u02e8\u02e9\u0007n\u0002\u0002", "\u02e9\u02ea\u0007f\u0002\u0002\u02ea\u00c4\u0003\u0002\u0002\u0002", "\u02eb\u02ef\u0005\u00f1y\u0002\u02ec\u02ee\u0005\u00f3z\u0002\u02ed", "\u02ec\u0003\u0002\u0002\u0002\u02ee\u02f1\u0003\u0002\u0002\u0002\u02ef", "\u02ed\u0003\u0002\u0002\u0002\u02ef\u02f0\u0003\u0002\u0002\u0002\u02f0", "\u00c6\u0003\u0002\u0002\u0002\u02f1\u02ef\u0003\u0002\u0002\u0002\u02f2", "\u02f6\u0007$\u0002\u0002\u02f3\u02f5\u0005\u00d1i\u0002\u02f4\u02f3", "\u0003\u0002\u0002\u0002\u02f5\u02f8\u0003\u0002\u0002\u0002\u02f6\u02f4", "\u0003\u0002\u0002\u0002\u02f6\u02f7\u0003\u0002\u0002\u0002\u02f7\u02f9", "\u0003\u0002\u0002\u0002\u02f8\u02f6\u0003\u0002\u0002\u0002\u02f9\u0303", "\u0007$\u0002\u0002\u02fa\u02fe\u0007)\u0002\u0002\u02fb\u02fd\u0005", "\u00d3j\u0002\u02fc\u02fb\u0003\u0002\u0002\u0002\u02fd\u0300\u0003", "\u0002\u0002\u0002\u02fe\u02fc\u0003\u0002\u0002\u0002\u02fe\u02ff\u0003", "\u0002\u0002\u0002\u02ff\u0301\u0003\u0002\u0002\u0002\u0300\u02fe\u0003", "\u0002\u0002\u0002\u0301\u0303\u0007)\u0002\u0002\u0302\u02f2\u0003", "\u0002\u0002\u0002\u0302\u02fa\u0003\u0002\u0002\u0002\u0303\u00c8\u0003", "\u0002\u0002\u0002\u0304\u0306\t\u0004\u0002\u0002\u0305\u0304\u0003", "\u0002\u0002\u0002\u0306\u0307\u0003\u0002\u0002\u0002\u0307\u0305\u0003", "\u0002\u0002\u0002\u0307\u0308\u0003\u0002\u0002\u0002\u0308\u0309\u0003", "\u0002\u0002\u0002\u0309\u030a\be\u0002\u0002\u030a\u00ca\u0003\u0002", "\u0002\u0002\u030b\u030c\u00071\u0002\u0002\u030c\u030d\u0007,\u0002", "\u0002\u030d\u0311\u0003\u0002\u0002\u0002\u030e\u0310\u000b\u0002\u0002", "\u0002\u030f\u030e\u0003\u0002\u0002\u0002\u0310\u0313\u0003\u0002\u0002", "\u0002\u0311\u0312\u0003\u0002\u0002\u0002\u0311\u030f\u0003\u0002\u0002", "\u0002\u0312\u0314\u0003\u0002\u0002\u0002\u0313\u0311\u0003\u0002\u0002", "\u0002\u0314\u0315\u0007,\u0002\u0002\u0315\u0316\u00071\u0002\u0002", "\u0316\u0317\u0003\u0002\u0002\u0002\u0317\u0318\bf\u0002\u0002\u0318", "\u00cc\u0003\u0002\u0002\u0002\u0319\u031a\u00071\u0002\u0002\u031a", "\u031b\u00071\u0002\u0002\u031b\u031f\u0003\u0002\u0002\u0002\u031c", "\u031e\n\u0002\u0002\u0002\u031d\u031c\u0003\u0002\u0002\u0002\u031e", "\u0321\u0003\u0002\u0002\u0002\u031f\u031d\u0003\u0002\u0002\u0002\u031f", "\u0320\u0003\u0002\u0002\u0002\u0320\u0322\u0003\u0002\u0002\u0002\u0321", "\u031f\u0003\u0002\u0002\u0002\u0322\u0323\bg\u0002\u0002\u0323\u00ce", "\u0003\u0002\u0002\u0002\u0324\u0325\u000b\u0002\u0002\u0002\u0325\u00d0", "\u0003\u0002\u0002\u0002\u0326\u032b\n\u0005\u0002\u0002\u0327\u0328", "\u0007^\u0002\u0002\u0328\u032b\u0005\u00d5k\u0002\u0329\u032b\u0005", "\u00e3r\u0002\u032a\u0326\u0003\u0002\u0002\u0002\u032a\u0327\u0003", "\u0002\u0002\u0002\u032a\u0329\u0003\u0002\u0002\u0002\u032b\u00d2\u0003", "\u0002\u0002\u0002\u032c\u0331\n\u0006\u0002\u0002\u032d\u032e\u0007", "^\u0002\u0002\u032e\u0331\u0005\u00d5k\u0002\u032f\u0331\u0005\u00e3", "r\u0002\u0330\u032c\u0003\u0002\u0002\u0002\u0330\u032d\u0003\u0002", "\u0002\u0002\u0330\u032f\u0003\u0002\u0002\u0002\u0331\u00d4\u0003\u0002", "\u0002\u0002\u0332\u0337\u0005\u00d7l\u0002\u0333\u0337\u00072\u0002", "\u0002\u0334\u0337\u0005\u00d9m\u0002\u0335\u0337\u0005\u00dbn\u0002", "\u0336\u0332\u0003\u0002\u0002\u0002\u0336\u0333\u0003\u0002\u0002\u0002", "\u0336\u0334\u0003\u0002\u0002\u0002\u0336\u0335\u0003\u0002\u0002\u0002", "\u0337\u00d6\u0003\u0002\u0002\u0002\u0338\u033b\u0005\u00ddo\u0002", "\u0339\u033b\u0005\u00dfp\u0002\u033a\u0338\u0003\u0002\u0002\u0002", "\u033a\u0339\u0003\u0002\u0002\u0002\u033b\u00d8\u0003\u0002\u0002\u0002", "\u033c\u033d\u0007z\u0002\u0002\u033d\u033e\u0005\u00e9u\u0002\u033e", "\u033f\u0005\u00e9u\u0002\u033f\u00da\u0003\u0002\u0002\u0002\u0340", "\u0341\u0007w\u0002\u0002\u0341\u0342\u0005\u00e9u\u0002\u0342\u0343", "\u0005\u00e9u\u0002\u0343\u0344\u0005\u00e9u\u0002\u0344\u0345\u0005", "\u00e9u\u0002\u0345\u00dc\u0003\u0002\u0002\u0002\u0346\u0347\t\u0007", "\u0002\u0002\u0347\u00de\u0003\u0002\u0002\u0002\u0348\u0349\n\b\u0002", "\u0002\u0349\u00e0\u0003\u0002\u0002\u0002\u034a\u034e\u0005\u00ddo", "\u0002\u034b\u034e\u0005\u00e7t\u0002\u034c\u034e\t\t\u0002\u0002\u034d", "\u034a\u0003\u0002\u0002\u0002\u034d\u034b\u0003\u0002\u0002\u0002\u034d", "\u034c\u0003\u0002\u0002\u0002\u034e\u00e2\u0003\u0002\u0002\u0002\u034f", "\u0350\u0007^\u0002\u0002\u0350\u0351\u0005\u00e5s\u0002\u0351\u00e4", "\u0003\u0002\u0002\u0002\u0352\u0353\u0007\u000f\u0002\u0002\u0353\u0356", "\u0007\f\u0002\u0002\u0354\u0356\u0005\u0005\u0003\u0002\u0355\u0352", "\u0003\u0002\u0002\u0002\u0355\u0354\u0003\u0002\u0002\u0002\u0356\u00e6", "\u0003\u0002\u0002\u0002\u0357\u0358\t\n\u0002\u0002\u0358\u00e8\u0003", "\u0002\u0002\u0002\u0359\u035a\t\u000b\u0002\u0002\u035a\u00ea\u0003", "\u0002\u0002\u0002\u035b\u035c\t\f\u0002\u0002\u035c\u00ec\u0003\u0002", "\u0002\u0002\u035d\u0366\u00072\u0002\u0002\u035e\u0362\t\r\u0002\u0002", "\u035f\u0361\u0005\u00e7t\u0002\u0360\u035f\u0003\u0002\u0002\u0002", "\u0361\u0364\u0003\u0002\u0002\u0002\u0362\u0360\u0003\u0002\u0002\u0002", "\u0362\u0363\u0003\u0002\u0002\u0002\u0363\u0366\u0003\u0002\u0002\u0002", "\u0364\u0362\u0003\u0002\u0002\u0002\u0365\u035d\u0003\u0002\u0002\u0002", "\u0365\u035e\u0003\u0002\u0002\u0002\u0366\u00ee\u0003\u0002\u0002\u0002", "\u0367\u0369\t\u000e\u0002\u0002\u0368\u036a\t\u000f\u0002\u0002\u0369", "\u0368\u0003\u0002\u0002\u0002\u0369\u036a\u0003\u0002\u0002\u0002\u036a", "\u036c\u0003\u0002\u0002\u0002\u036b\u036d\u0005\u00e7t\u0002\u036c", "\u036b\u0003\u0002\u0002\u0002\u036d\u036e\u0003\u0002\u0002\u0002\u036e", "\u036c\u0003\u0002\u0002\u0002\u036e\u036f\u0003\u0002\u0002\u0002\u036f", "\u00f0\u0003\u0002\u0002\u0002\u0370\u0375\u0005\u00f5{\u0002\u0371", "\u0375\t\u0010\u0002\u0002\u0372\u0373\u0007^\u0002\u0002\u0373\u0375", "\u0005\u00dbn\u0002\u0374\u0370\u0003\u0002\u0002\u0002\u0374\u0371", "\u0003\u0002\u0002\u0002\u0374\u0372\u0003\u0002\u0002\u0002\u0375\u00f2", "\u0003\u0002\u0002\u0002\u0376\u037d\u0005\u00f1y\u0002\u0377\u037d", "\u0005\u00f7|\u0002\u0378\u037d\u0005\u00f9}\u0002\u0379\u037d\u0005", "\u00fb~\u0002\u037a\u037d\u0005\u00fd\u007f\u0002\u037b\u037d\u0005", "\u00ff\u0080\u0002\u037c\u0376\u0003\u0002\u0002\u0002\u037c\u0377\u0003", "\u0002\u0002\u0002\u037c\u0378\u0003\u0002\u0002\u0002\u037c\u0379\u0003", "\u0002\u0002\u0002\u037c\u037a\u0003\u0002\u0002\u0002\u037c\u037b\u0003", "\u0002\u0002\u0002\u037d\u00f4\u0003\u0002\u0002\u0002\u037e\u0380\t", "\u0011\u0002\u0002\u037f\u037e\u0003\u0002\u0002\u0002\u0380\u00f6\u0003", "\u0002\u0002\u0002\u0381\u0383\t\u0012\u0002\u0002\u0382\u0381\u0003", "\u0002\u0002\u0002\u0383\u00f8\u0003\u0002\u0002\u0002\u0384\u0386\t", "\u0013\u0002\u0002\u0385\u0384\u0003\u0002\u0002\u0002\u0386\u00fa\u0003", "\u0002\u0002\u0002\u0387\u0389\t\u0014\u0002\u0002\u0388\u0387\u0003", "\u0002\u0002\u0002\u0389\u00fc\u0003\u0002\u0002\u0002\u038a\u038b\u0007", "\u200e\u0002\u0002\u038b\u00fe\u0003\u0002\u0002\u0002\u038c\u038d\u0007", "\u200f\u0002\u0002\u038d\u0100\u0003\u0002\u0002\u0002\u038e\u0392\u0005", "\u0105\u0083\u0002\u038f\u0391\u0005\u0107\u0084\u0002\u0390\u038f\u0003", "\u0002\u0002\u0002\u0391\u0394\u0003\u0002\u0002\u0002\u0392\u0390\u0003", "\u0002\u0002\u0002\u0392\u0393\u0003\u0002\u0002\u0002\u0393\u0102\u0003", "\u0002\u0002\u0002\u0394\u0392\u0003\u0002\u0002\u0002\u0395\u0397\u0005", "\u00f3z\u0002\u0396\u0395\u0003\u0002\u0002\u0002\u0397\u039a\u0003", "\u0002\u0002\u0002\u0398\u0396\u0003\u0002\u0002\u0002\u0398\u0399\u0003", "\u0002\u0002\u0002\u0399\u0104\u0003\u0002\u0002\u0002\u039a\u0398\u0003", "\u0002\u0002\u0002\u039b\u039f\n\u0015\u0002\u0002\u039c\u039f\u0005", "\u010b\u0086\u0002\u039d\u039f\u0005\u010d\u0087\u0002\u039e\u039b\u0003", "\u0002\u0002\u0002\u039e\u039c\u0003\u0002\u0002\u0002\u039e\u039d\u0003", "\u0002\u0002\u0002\u039f\u0106\u0003\u0002\u0002\u0002\u03a0\u03a4\n", "\u0016\u0002\u0002\u03a1\u03a4\u0005\u010b\u0086\u0002\u03a2\u03a4\u0005", "\u010d\u0087\u0002\u03a3\u03a0\u0003\u0002\u0002\u0002\u03a3\u03a1\u0003", "\u0002\u0002\u0002\u03a3\u03a2\u0003\u0002\u0002\u0002\u03a4\u0108\u0003", "\u0002\u0002\u0002\u03a5\u03a6\n\u0002\u0002\u0002\u03a6\u010a\u0003", "\u0002\u0002\u0002\u03a7\u03a8\u0007^\u0002\u0002\u03a8\u03a9\u0005", "\u0109\u0085\u0002\u03a9\u010c\u0003\u0002\u0002\u0002\u03aa\u03ae\u0007", "]\u0002\u0002\u03ab\u03ad\u0005\u010f\u0088\u0002\u03ac\u03ab\u0003", "\u0002\u0002\u0002\u03ad\u03b0\u0003\u0002\u0002\u0002\u03ae\u03ac\u0003", "\u0002\u0002\u0002\u03ae\u03af\u0003\u0002\u0002\u0002\u03af\u03b1\u0003", "\u0002\u0002\u0002\u03b0\u03ae\u0003\u0002\u0002\u0002\u03b1\u03b2\u0007", "_\u0002\u0002\u03b2\u010e\u0003\u0002\u0002\u0002\u03b3\u03b6\n\u0017", "\u0002\u0002\u03b4\u03b6\u0005\u010b\u0086\u0002\u03b5\u03b3\u0003\u0002", "\u0002\u0002\u03b5\u03b4\u0003\u0002\u0002\u0002\u03b6\u0110\u0003\u0002", "\u0002\u0002)\u0002\u01a8\u01af\u01b3\u01b9\u01bc\u01c0\u01c2\u01c9", "\u01d0\u02ef\u02f6\u02fe\u0302\u0307\u0311\u031f\u032a\u0330\u0336\u033a", "\u034d\u0355\u0362\u0365\u0369\u036e\u0374\u037c\u037f\u0382\u0385\u0388", "\u0392\u0398\u039e\u03a3\u03ae\u03b5\u0003\u0002\u0003\u0002"].join(""); var atn = new antlr4.atn.ATNDeserializer().deserialize(serializedATN); var decisionsToDFA = atn.decisionToState.map( function(ds, index) { return new antlr4.dfa.DFA(ds, index); }); function ECMAScriptLexer(input) { antlr4.Lexer.call(this, input); this._interp = new antlr4.atn.LexerATNSimulator(this, atn, decisionsToDFA, new antlr4.PredictionContextCache()); return this; } ECMAScriptLexer.prototype = Object.create(antlr4.Lexer.prototype); ECMAScriptLexer.prototype.constructor = ECMAScriptLexer; Object.defineProperty(ECMAScriptLexer.prototype, "atn", { get : function() { return atn; } }); ECMAScriptLexer.EOF = antlr4.Token.EOF; ECMAScriptLexer.RegularExpressionLiteral = 1; ECMAScriptLexer.LineTerminator = 2; ECMAScriptLexer.OpenBracket = 3; ECMAScriptLexer.CloseBracket = 4; ECMAScriptLexer.OpenParen = 5; ECMAScriptLexer.CloseParen = 6; ECMAScriptLexer.OpenBrace = 7; ECMAScriptLexer.CloseBrace = 8; ECMAScriptLexer.SemiColon = 9; ECMAScriptLexer.Comma = 10; ECMAScriptLexer.Assign = 11; ECMAScriptLexer.QuestionMark = 12; ECMAScriptLexer.Colon = 13; ECMAScriptLexer.Dot = 14; ECMAScriptLexer.PlusPlus = 15; ECMAScriptLexer.MinusMinus = 16; ECMAScriptLexer.Plus = 17; ECMAScriptLexer.Minus = 18; ECMAScriptLexer.BitNot = 19; ECMAScriptLexer.Not = 20; ECMAScriptLexer.Multiply = 21; ECMAScriptLexer.Divide = 22; ECMAScriptLexer.Modulus = 23; ECMAScriptLexer.RightShiftArithmetic = 24; ECMAScriptLexer.LeftShiftArithmetic = 25; ECMAScriptLexer.RightShiftLogical = 26; ECMAScriptLexer.LessThan = 27; ECMAScriptLexer.MoreThan = 28; ECMAScriptLexer.LessThanEquals = 29; ECMAScriptLexer.GreaterThanEquals = 30; ECMAScriptLexer.Equals = 31; ECMAScriptLexer.NotEquals = 32; ECMAScriptLexer.IdentityEquals = 33; ECMAScriptLexer.IdentityNotEquals = 34; ECMAScriptLexer.BitAnd = 35; ECMAScriptLexer.BitXOr = 36; ECMAScriptLexer.BitOr = 37; ECMAScriptLexer.And = 38; ECMAScriptLexer.Or = 39; ECMAScriptLexer.MultiplyAssign = 40; ECMAScriptLexer.DivideAssign = 41; ECMAScriptLexer.ModulusAssign = 42; ECMAScriptLexer.PlusAssign = 43; ECMAScriptLexer.MinusAssign = 44; ECMAScriptLexer.LeftShiftArithmeticAssign = 45; ECMAScriptLexer.RightShiftArithmeticAssign = 46; ECMAScriptLexer.RightShiftLogicalAssign = 47; ECMAScriptLexer.BitAndAssign = 48; ECMAScriptLexer.BitXorAssign = 49; ECMAScriptLexer.BitOrAssign = 50; ECMAScriptLexer.NullLiteral = 51; ECMAScriptLexer.BooleanLiteral = 52; ECMAScriptLexer.DecimalLiteral = 53; ECMAScriptLexer.HexIntegerLiteral = 54; ECMAScriptLexer.OctalIntegerLiteral = 55; ECMAScriptLexer.Break = 56; ECMAScriptLexer.Do = 57; ECMAScriptLexer.Instanceof = 58; ECMAScriptLexer.Typeof = 59; ECMAScriptLexer.Case = 60; ECMAScriptLexer.Else = 61; ECMAScriptLexer.New = 62; ECMAScriptLexer.Var = 63; ECMAScriptLexer.Catch = 64; ECMAScriptLexer.Finally = 65; ECMAScriptLexer.Return = 66; ECMAScriptLexer.Void = 67; ECMAScriptLexer.Continue = 68; ECMAScriptLexer.For = 69; ECMAScriptLexer.Switch = 70; ECMAScriptLexer.While = 71; ECMAScriptLexer.Debugger = 72; ECMAScriptLexer.Function = 73; ECMAScriptLexer.This = 74; ECMAScriptLexer.With = 75; ECMAScriptLexer.Default = 76; ECMAScriptLexer.If = 77; ECMAScriptLexer.Throw = 78; ECMAScriptLexer.Delete = 79; ECMAScriptLexer.In = 80; ECMAScriptLexer.Try = 81; ECMAScriptLexer.Class = 82; ECMAScriptLexer.Enum = 83; ECMAScriptLexer.Extends = 84; ECMAScriptLexer.Super = 85; ECMAScriptLexer.Const = 86; ECMAScriptLexer.Export = 87; ECMAScriptLexer.Import = 88; ECMAScriptLexer.Implements = 89; ECMAScriptLexer.Let = 90; ECMAScriptLexer.Private = 91; ECMAScriptLexer.Public = 92; ECMAScriptLexer.Interface = 93; ECMAScriptLexer.Package = 94; ECMAScriptLexer.Protected = 95; ECMAScriptLexer.Static = 96; ECMAScriptLexer.Yield = 97; ECMAScriptLexer.Identifier = 98; ECMAScriptLexer.StringLiteral = 99; ECMAScriptLexer.WhiteSpaces = 100; ECMAScriptLexer.MultiLineComment = 101; ECMAScriptLexer.SingleLineComment = 102; ECMAScriptLexer.UnexpectedCharacter = 103; ECMAScriptLexer.prototype.channelNames = [ "DEFAULT_TOKEN_CHANNEL", "HIDDEN" ]; ECMAScriptLexer.prototype.modeNames = [ "DEFAULT_MODE" ]; ECMAScriptLexer.prototype.literalNames = [ null, null, null, "'['", "']'", "'('", "')'", "'{'", "'}'", "';'", "','", "'='", "'?'", "':'", "'.'", "'++'", "'--'", "'+'", "'-'", "'~'", "'!'", "'*'", "'/'", "'%'", "'>>'", "'<<'", "'>>>'", "'<'", "'>'", "'<='", "'>='", "'=='", "'!='", "'==='", "'!=='", "'&'", "'^'", "'|'", "'&&'", "'||'", "'*='", "'/='", "'%='", "'+='", "'-='", "'<<='", "'>>='", "'>>>='", "'&='", "'^='", "'|='", "'null'", null, null, null, null, "'break'", "'do'", "'instanceof'", "'typeof'", "'case'", "'else'", "'new'", "'var'", "'catch'", "'finally'", "'return'", "'void'", "'continue'", "'for'", "'switch'", "'while'", "'debugger'", "'function'", "'this'", "'with'", "'default'", "'if'", "'throw'", "'delete'", "'in'", "'try'", "'class'", "'enum'", "'extends'", "'super'", "'const'", "'export'", "'import'" ]; ECMAScriptLexer.prototype.symbolicNames = [ null, "RegularExpressionLiteral", "LineTerminator", "OpenBracket", "CloseBracket", "OpenParen", "CloseParen", "OpenBrace", "CloseBrace", "SemiColon", "Comma", "Assign", "QuestionMark", "Colon", "Dot", "PlusPlus", "MinusMinus", "Plus", "Minus", "BitNot", "Not", "Multiply", "Divide", "Modulus", "RightShiftArithmetic", "LeftShiftArithmetic", "RightShiftLogical", "LessThan", "MoreThan", "LessThanEquals", "GreaterThanEquals", "Equals", "NotEquals", "IdentityEquals", "IdentityNotEquals", "BitAnd", "BitXOr", "BitOr", "And", "Or", "MultiplyAssign", "DivideAssign", "ModulusAssign", "PlusAssign", "MinusAssign", "LeftShiftArithmeticAssign", "RightShiftArithmeticAssign", "RightShiftLogicalAssign", "BitAndAssign", "BitXorAssign", "BitOrAssign", "NullLiteral", "BooleanLiteral", "DecimalLiteral", "HexIntegerLiteral", "OctalIntegerLiteral", "Break", "Do", "Instanceof", "Typeof", "Case", "Else", "New", "Var", "Catch", "Finally", "Return", "Void", "Continue", "For", "Switch", "While", "Debugger", "Function", "This", "With", "Default", "If", "Throw", "Delete", "In", "Try", "Class", "Enum", "Extends", "Super", "Const", "Export", "Import", "Implements", "Let", "Private", "Public", "Interface", "Package", "Protected", "Static", "Yield", "Identifier", "StringLiteral", "WhiteSpaces", "MultiLineComment", "SingleLineComment", "UnexpectedCharacter" ]; ECMAScriptLexer.prototype.ruleNames = [ "RegularExpressionLiteral", "LineTerminator", "OpenBracket", "CloseBracket", "OpenParen", "CloseParen", "OpenBrace", "CloseBrace", "SemiColon", "Comma", "Assign", "QuestionMark", "Colon", "Dot", "PlusPlus", "MinusMinus", "Plus", "Minus", "BitNot", "Not", "Multiply", "Divide", "Modulus", "RightShiftArithmetic", "LeftShiftArithmetic", "RightShiftLogical", "LessThan", "MoreThan", "LessThanEquals", "GreaterThanEquals", "Equals", "NotEquals", "IdentityEquals", "IdentityNotEquals", "BitAnd", "BitXOr", "BitOr", "And", "Or", "MultiplyAssign", "DivideAssign", "ModulusAssign", "PlusAssign", "MinusAssign", "LeftShiftArithmeticAssign", "RightShiftArithmeticAssign", "RightShiftLogicalAssign", "BitAndAssign", "BitXorAssign", "BitOrAssign", "NullLiteral", "BooleanLiteral", "DecimalLiteral", "HexIntegerLiteral", "OctalIntegerLiteral", "Break", "Do", "Instanceof", "Typeof", "Case", "Else", "New", "Var", "Catch", "Finally", "Return", "Void", "Continue", "For", "Switch", "While", "Debugger", "Function", "This", "With", "Default", "If", "Throw", "Delete", "In", "Try", "Class", "Enum", "Extends", "Super", "Const", "Export", "Import", "Implements", "Let", "Private", "Public", "Interface", "Package", "Protected", "Static", "Yield", "Identifier", "StringLiteral", "WhiteSpaces", "MultiLineComment", "SingleLineComment", "UnexpectedCharacter", "DoubleStringCharacter", "SingleStringCharacter", "EscapeSequence", "CharacterEscapeSequence", "HexEscapeSequence", "UnicodeEscapeSequence", "SingleEscapeCharacter", "NonEscapeCharacter", "EscapeCharacter", "LineContinuation", "LineTerminatorSequence", "DecimalDigit", "HexDigit", "OctalDigit", "DecimalIntegerLiteral", "ExponentPart", "IdentifierStart", "IdentifierPart", "UnicodeLetter", "UnicodeCombiningMark", "UnicodeDigit", "UnicodeConnectorPunctuation", "ZWNJ", "ZWJ", "RegularExpressionBody", "RegularExpressionFlags", "RegularExpressionFirstChar", "RegularExpressionChar", "RegularExpressionNonTerminator", "RegularExpressionBackslashSequence", "RegularExpressionClass", "RegularExpressionClassChar" ]; ECMAScriptLexer.prototype.grammarFileName = "ECMAScript.g4"; ECMAScriptLexer.prototype.strictMode = true; ECMAScriptLexer.prototype.lastToken = null; /** * @returns {Boolean} Returns true if the lexer operates in strict mode. */ ECMAScriptLexer.prototype.getStrictMode = function() { return this.strictMode; }; /** * Sets whether the lexer operates in strict mode or not. * * @param strictMode {Boolean} The flag indicating the lexer operates in strict mode or not. */ ECMAScriptLexer.prototype.setStrictMode = function(strictMode) { this.strictMode = strictMode; }; /** * Return the next token from the character stream and records this last * token in case it resides on the default channel. This recorded token * is used to determine when the lexer could possibly match a regex * literal. * */ ECMAScriptLexer.prototype.nextToken = function() { var next = antlr4.Lexer.prototype.nextToken.call(this); if (next.channel == antlr4.Token.DEFAULT_CHANNEL) this.lastToken = next; return next; }; /** * @returns {Boolean} Returns true if the lexer can match a regex literal. */ ECMAScriptLexer.prototype.isRegexPossible = function() { if (this.lastToken == null) return true; switch (this.lastToken.type) { case ECMAScriptLexer.Identifier: return false; case ECMAScriptLexer.NullLiteral: return false; case ECMAScriptLexer.BooleanLiteral: return false; case ECMAScriptLexer.This: return false; case ECMAScriptLexer.CloseBracket: return false; case ECMAScriptLexer.CloseParen: return false; case ECMAScriptLexer.OctalIntegerLiteral: return false; case ECMAScriptLexer.DecimalLiteral: return false; case ECMAScriptLexer.HexIntegerLiteral: return false; case ECMAScriptLexer.StringLiteral: return false; case ECMAScriptLexer.PlusPlus: return false; case ECMAScriptLexer.MinusMinus: return false; default: return true; } }; ECMAScriptLexer.prototype.sempred = function(localctx, ruleIndex, predIndex) { switch (ruleIndex) { case 0: return this.RegularExpressionLiteral_sempred(localctx, predIndex); case 54: return this.OctalIntegerLiteral_sempred(localctx, predIndex); case 88: return this.Implements_sempred(localctx, predIndex); case 89: return this.Let_sempred(localctx, predIndex); case 90: return this.Private_sempred(localctx, predIndex); case 91: return this.Public_sempred(localctx, predIndex); case 92: return this.Interface_sempred(localctx, predIndex); case 93: return this.Package_sempred(localctx, predIndex); case 94: return this.Protected_sempred(localctx, predIndex); case 95: return this.Static_sempred(localctx, predIndex); case 96: return this.Yield_sempred(localctx, predIndex); default: throw "No registered predicate for:" + ruleIndex; } }; ECMAScriptLexer.prototype.RegularExpressionLiteral_sempred = function(localctx, predIndex) { switch(predIndex) { case 0: return this.isRegexPossible(); default: throw "No predicate with index:" + predIndex; } }; ECMAScriptLexer.prototype.OctalIntegerLiteral_sempred = function(localctx, predIndex) { switch(predIndex) { case 1: return !this.strictMode; default: throw "No predicate with index:" + predIndex; } }; ECMAScriptLexer.prototype.Implements_sempred = function(localctx, predIndex) { switch(predIndex) { case 2: return this.strictMode; default: throw "No predicate with index:" + predIndex; } }; ECMAScriptLexer.prototype.Let_sempred = function(localctx, predIndex) { switch(predIndex) { case 3: return this.strictMode; default: throw "No predicate with index:" + predIndex; } }; ECMAScriptLexer.prototype.Private_sempred = function(localctx, predIndex) { switch(predIndex) { case 4: return this.strictMode; default: throw "No predicate with index:" + predIndex; } }; ECMAScriptLexer.prototype.Public_sempred = function(localctx, predIndex) { switch(predIndex) { case 5: return this.strictMode; default: throw "No predicate with index:" + predIndex; } }; ECMAScriptLexer.prototype.Interface_sempred = function(localctx, predIndex) { switch(predIndex) { case 6: return this.strictMode; default: throw "No predicate with index:" + predIndex; } }; ECMAScriptLexer.prototype.Package_sempred = function(localctx, predIndex) { switch(predIndex) { case 7: return this.strictMode; default: throw "No predicate with index:" + predIndex; } }; ECMAScriptLexer.prototype.Protected_sempred = function(localctx, predIndex) { switch(predIndex) { case 8: return this.strictMode; default: throw "No predicate with index:" + predIndex; } }; ECMAScriptLexer.prototype.Static_sempred = function(localctx, predIndex) { switch(predIndex) { case 9: return this.strictMode; default: throw "No predicate with index:" + predIndex; } }; ECMAScriptLexer.prototype.Yield_sempred = function(localctx, predIndex) { switch(predIndex) { case 10: return this.strictMode; default: throw "No predicate with index:" + predIndex; } }; exports.ECMAScriptLexer = ECMAScriptLexer; <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/generators/SwitchGenCase.java<|end_filename|> package edu.nyu.dtl.synner.core.generators; import edu.nyu.dtl.synner.core.datamodel.Field; import jdk.nashorn.api.scripting.JSObject; import javax.script.*; import java.util.List; public class SwitchGenCase<T extends Comparable> { final List<Field> dependencies; final String expression; final Generator<T> generator; JSObject compiledExpression; private ScriptEngineManager factory; private ScriptEngine engine; public SwitchGenCase(String expression, List<Field> dependencies, Generator<T> generator) throws ScriptException { this.expression = expression; this.dependencies = dependencies; this.generator = generator; factory = new ScriptEngineManager(); engine = factory.getEngineByName("JavaScript"); ScriptContext sc = new SimpleScriptContext(); sc.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE); StringBuilder functionDefBldr = new StringBuilder("function conditionExpression("); if (dependencies != null) { for (int i = 0; i < dependencies.size(); i++) { functionDefBldr.append(dependencies.get(i).getName()); if (i < dependencies.size() - 1) functionDefBldr.append(","); } } functionDefBldr.append("){ return !!(").append(expression).append(");}"); engine.eval(functionDefBldr.toString(), sc); compiledExpression = (JSObject) sc.getAttribute("conditionExpression", ScriptContext.ENGINE_SCOPE); } public boolean satisfy(Comparable[] inputs) { return (boolean) compiledExpression.call(null, inputs); } public boolean satisfy() { return (boolean) compiledExpression.call(null); } } <|start_filename|>synner-server/src/main/resources/static/js/directives/dependencies-list.js<|end_filename|> // D3 initialization to display graph is inspired to https://bl.ocks.org/rkirsling/5001347 angular.module('Synner') .directive('dependenciesList', ['Parameters', 'Infer', 'Model', function (Parameters, Infer, Model) { return { restriction: 'E', replace: true, templateUrl: 'fragments/dependencies-list.html', scope: { field: '=' }, // in this way a change on the selected link and node can reflect up to the root link: function ($scope, element, attrs) { $scope.model = Model; $scope.newDependency = null; $scope._selectedField = $scope.$parent._selectedField; $scope.compatibleFields = []; $scope.possibleDependencies = []; function update() { updateCompatibleFields(); } // It adds a new dependency function addDependency() { if (!$scope.newDependency) return; if ($scope.newDependency.id.startsWith('field')) { Model.addDependency($scope.field.id, $scope.newDependency.item.id); Infer.inferLinkGenerator($scope.field); $scope.$parent.selectField($scope.field); } else { var newField = Model.addNewColumn('string'); newField.name = $scope.newDependency.name; newField._generator.obj = $scope.newDependency.item; $scope.field.dependencies.push(newField); var gen = Model.getGeneratorWithoutSwitch($scope.field); gen.join = newField.name; } $scope.newDependency = null; } function updateCompatibleFields() { var compatibleFields = Model.getCompatibleFields($scope.field); var possibleDependencies = []; for (var cf of compatibleFields) { possibleDependencies.push({ id: 'field@' + cf.name, name: cf.name, item: cf, group: 'Other columns' }); } if ($scope.field.dependencies.length === 0) { var subDomains = Infer.getFieldSubdomains($scope.field); for (var sd of subDomains) { var nameSuffix = ''; if (checkNameExisting(sd.domain.readableName)) { var i = 1; while (checkNameExisting(sd.domain.readableName + i)) i++; nameSuffix += i; } possibleDependencies.push({ id: '<EMAIL>, name: sd.domain.readableName + nameSuffix, item: {domain: {name: sd.domain.name}}, group: 'New field' }); } } $scope.possibleDependencies = possibleDependencies; } function checkNameExisting(name) { for (var f of Model.fields) { if (name === f.name) { return true; } } return false; } $scope.deleteDependency = function (dependency) { Model.removeDependencyFromField($scope.field.id, dependency.id); $scope.$parent.selectField($scope.field); }; $scope.$watch('_selectedField', update, true); $scope.$watch('newDependency', addDependency, true); $scope.$watch(function () { var elements = []; for (var f of Model.fields) { elements.push(f._generator.obj); } return elements; }, $scope.update, true); } }; }]); <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/parser/DataParser.java<|end_filename|> package edu.nyu.dtl.synner.core.parser; import com.fasterxml.jackson.databind.JsonNode; import edu.nyu.dtl.synner.core.datamodel.*; import static edu.nyu.dtl.synner.core.parser.Commons.readValue; public class DataParser { public DataParser() { } public GeneratedDataset readModel(Table table, JsonNode rootNode) { int toAdd = rootNode.has("to-add") ? rootNode.get("to-add").asInt() : 0; Comparable[][] tuples = readTuples(rootNode.get("tuples")); return new GeneratedDataset(table, tuples, toAdd); } private Comparable[][] readTuples(JsonNode jsonNode) { if (!jsonNode.isArray()) throw new IllegalArgumentException("the tuples field must be an array"); Comparable[][] tuples = new Comparable[jsonNode.size()][]; for (int i = 0; i < tuples.length; i++) { tuples[i] = readTuple(jsonNode.get(i)); } return tuples; } private Comparable[] readTuple(JsonNode jsonNode) { if (!jsonNode.isArray()) throw new IllegalArgumentException("each tuple must be an array"); Comparable[] tuple = new Comparable[jsonNode.size()]; for (int i = 0; i < tuple.length; i++) { tuple[i] = readValue(jsonNode.get(i)); } return tuple; } } <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/datamodel/Field.java<|end_filename|> package edu.nyu.dtl.synner.core.datamodel; import com.fasterxml.jackson.annotation.JsonProperty; import edu.nyu.dtl.synner.core.generators.Generator; import jdk.nashorn.api.scripting.JSObject; import javax.script.*; import java.util.ArrayList; import java.util.List; public class Field implements Comparable<Field> { @JsonProperty private final String name; @JsonProperty private final int pos; @JsonProperty private final List<Field> dependencies = new ArrayList<>(); @JsonProperty private String filter; @JsonProperty private int missingRows; @JsonProperty private int errorRows; @JsonProperty private String format; @JsonProperty private ColumnType type; @JsonProperty private Generator generator; // used as generator, or as fallback in case of relationships between columns JSObject compiledExpression; private ScriptEngineManager factory; private ScriptEngine engine; public Field(String name, ColumnType type, String filter, int missingRows, int errorRows, int pos) throws ScriptException { if (name == null || name.length() == 0) throw new IllegalArgumentException("Name should be a valid name"); this.name = name; this.type = type; this.pos = pos; this.setFilter(filter); this.missingRows = missingRows; this.errorRows = errorRows; } public String getName() { return name; } public void setGenerator(Generator generator) { this.generator = generator; } public Generator getGenerator() { return generator; } public ColumnType getType() { return type; } public void setType(ColumnType type) { this.type = type; } public int getPos() { return pos; } public List<Field> getDependencies() { return dependencies; } public void addDependency(Field field) { dependencies.add(field); } public void setFormat(String format) { this.format = format; } public String format(Comparable value) { if (format == null) return value.toString(); return String.format(format, value); } public void setFilter(String filter) throws ScriptException { this.filter = filter; if (filter == null || filter.length() == 0) return; factory = new ScriptEngineManager(); engine = factory.getEngineByName("JavaScript"); ScriptContext sc = new SimpleScriptContext(); sc.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE); engine.eval("function conditionExpression(" + this.name + "){ return !!(" + this.filter + ");}", sc); compiledExpression = (JSObject) sc.getAttribute("conditionExpression", ScriptContext.ENGINE_SCOPE); } public String getFilter() { return filter; } public int getMissingRows() { return missingRows; } public void setMissingRows(int missingRows) { this.missingRows = missingRows; } public int getErrorRows() { return errorRows; } public void setErrorRows(int errorRows) { this.errorRows = errorRows; } public boolean evaluateFilter(Object fieldValue) { if (compiledExpression == null) return true; return (boolean) compiledExpression.call(null, fieldValue); } @Override public boolean equals(Object o) { return this == o || !(o == null || getClass() != o.getClass()) && name.equals(((Field) o).name); } @Override public int hashCode() { return name.hashCode(); } @Override public String toString() { return name; } public String toString(boolean printDetails) { if (!printDetails) return toString(); return pos + " - " + name + "<" + type + "> { dependencies:" + dependencies.toString() + ", generator: " + generator + "}"; } @Override public int compareTo(Field o) { return Integer.compare(pos, o.pos); } } <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/generators/SwitchGen.java<|end_filename|> package edu.nyu.dtl.synner.core.generators; import edu.nyu.dtl.synner.core.datamodel.Field; import javax.script.ScriptException; import java.util.ArrayList; import java.util.List; public class SwitchGen<T extends Comparable> implements Generator<T> { List<SwitchGenCase<T>> cases = new ArrayList<>(); Generator<T> elseCase; List<Field> dependencies; public SwitchGen(List<Field> dependencies) { this.dependencies = dependencies; } @Override public T generate(boolean errorMode, boolean previewMode) throws Exception { for (SwitchGenCase<T> c : cases) { if (c.satisfy()) { return c.generator.generate(errorMode, previewMode); } } return elseCase.generate(errorMode, previewMode); } @Override public T generate(Comparable[] inputs, boolean errorMode, boolean previewMode) throws Exception { for (SwitchGenCase<T> c : cases) { if (c.satisfy(inputs)) { return c.generator.generate(inputs, errorMode, previewMode); } } return elseCase.generate(inputs, errorMode, previewMode); } public void addCondition(String expression, Generator<T> then) throws ScriptException { cases.add(new SwitchGenCase<>(expression, dependencies, then)); } public void setElse(Generator<T> elseCase) { this.elseCase = elseCase; } } <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/datamodel/Relationship.java<|end_filename|> package edu.nyu.dtl.synner.core.datamodel; import java.util.*; import java.util.logging.Logger; public class Relationship { private static Logger log = Logger.getLogger(Relationship.class.getName()); private Field from; private Field to; public Relationship(Field from, Field to) { if (from == null || to == null) throw new NullPointerException("the end points of a relationship cannot be null"); this.from = from; this.to = to; } public Field getFrom() { return from; } public void setFrom(Field from) { this.from = from; } public Field getTo() { return to; } public void setTo(Field to) { this.to = to; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Relationship that = (Relationship) o; return from.equals(that.from) && to.equals(that.to); } @Override public int hashCode() { return Objects.hash(from, to); } @Override public String toString() { return from + "->" + to; } /** * Kahn algorithm for topological sort * * <pre><code> L ← Empty list that will contain the sorted elements S ← Set of all nodes with no incoming edges while S is non-empty do remove a node n from S add n to tail of L for each node m with an edge e from n to m do remove edge e from the graph if m has no other incoming edges then insert m into S if graph has edges then return error (graph has at least one cycle) else return L (a topologically sorted order) * </code></pre> * */ public static List<Field> topologicalSort(final Collection<Field> fields) { List<Field> l = new ArrayList<>(); List<Relationship> edges = extractRelationships(fields); List<Field> s = getSetOfColumnsWithoutIncomingRelationships(fields, edges); while (!s.isEmpty()) { Field n = s.remove(0); l.add(n); ListIterator<Relationship> edgesIt = edges.listIterator(); while (edgesIt.hasNext()) { Relationship e = edgesIt.next(); if (!e.from.equals(n)) continue; edgesIt.remove(); if (incomingEdges(e.to, edges) == 0) s.add(e.to); } } if (!edges.isEmpty()) return null; return l; } private static List<Relationship> extractRelationships(final Collection<Field> fields) { List<Relationship> relationships = new ArrayList<>(); for (Field f : fields) { for (Field d : f.getDependencies()) { relationships.add(new Relationship(d, f)); } } return relationships; } public static int incomingEdges(final Field c, final Collection<Relationship> edges) { int incoming = 0; for (Relationship edge : edges) if (edge.to.equals(c)) incoming++; return incoming; } public static Relationship searchFirstDependency(final Field c, final Collection<Relationship> edges) { for (Relationship edge : edges) if (edge.to.equals(c)) return edge; return null; } /** Find if there are columns with multiple entering arcs. * @return null if no columns have multiple entering arcs. Returns the first columns * that have it. */ public static Field searchColumnWithMultipleEntriesArcs(final Collection<Relationship> relationships) { Set<Field> toCols = new HashSet<>(); for (Relationship relationship : relationships) { if (!toCols.add(relationship.to)) return relationship.to; } return null; } public static List<Relationship> extractHardRelationships(final Collection<Relationship> relationships) { List<Relationship> filteredRelationships = new ArrayList<>(); for (Relationship r : relationships) { filteredRelationships.add(r); } return filteredRelationships; } public static List<Field> getSetOfColumnsWithoutIncomingRelationships(final Collection<Field> fields, final Collection<Relationship> rels) { Set<Field> res = new HashSet<>(fields); for (Relationship r : rels) res.remove(r.to); return new ArrayList<>(res); } } <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/parser/Commons.java<|end_filename|> package edu.nyu.dtl.synner.core.parser; import com.fasterxml.jackson.databind.JsonNode; public class Commons { private Commons() {} public static Comparable readValue(JsonNode element) { if (element.isNumber()) { return element.asDouble(); } else if (element.isTextual()) { // we support only text return element.asText(); } else if (element.isNull()) { return null; } else { throw new IllegalArgumentException("type not supported for element: " + element); } } } <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/generators/TimeRangeGen.java<|end_filename|> package edu.nyu.dtl.synner.core.generators; import com.fasterxml.jackson.annotation.JsonProperty; public class TimeRangeGen implements Generator<Integer> { @JsonProperty private final int from; // minutes from midnight @JsonProperty private final int to; public TimeRangeGen(int from, int to) { this.from = from; this.to = to; } @Override public Integer generate(boolean errorMode, boolean previewMode) { int res = from; if (from < to) { res = rnd.nextInt(to - from) + from; } else if (from > to) { res = (rnd.nextInt(60*24 - from + to) + from) % (60*24); } if (errorMode) return (to + rnd.nextInt(60)) % (60*24); return res; } } <|start_filename|>synner-server/src/main/resources/static/js/directives/generator-distribution-custom.js<|end_filename|> angular.module('Synner') .directive('generatorDistributionCustom', ['$rootScope', '$timeout', 'Infer', 'Parameters', function ($rootScope, $timeout, Infer, Parameters) { return { templateUrl: 'fragments/generator-distribution-custom.html', replace: true, restriction: 'E', scope: { distribution: '=', // where we will put the result of generation specifications _result: '=result', // where we will put the result of generation specifications field: '=', compactView: '=' }, link: function ($scope, element, attrs) { var GRAPH_PADDING = 5.5, ARROW_SIZE = 4.5; var GRAPH_POINTS = 10; $scope.distParameters = { min: 0, // used for all the distributions that can start and end in a specific range max: 1, // used for all the distributions that can start and end in a specific range }; $scope.pathFinalized = false; $scope.histogram = null; document.getPath = function () { return $scope.path; }; $scope.inputRead = false; var $canvas = element.find('canvas'); function updateResult() { if (!$scope.inputRead) return; if (!$scope._result) return; // in case the directive is active without any result specified var generator = { distribution: 'custom', histogram: $scope.histogram, min: $scope.distParameters.min, max: $scope.distParameters.max }; $scope._result.obj = generator; } function inferDistParameters() { var stats = Infer.inferDistribution($scope.field); if (!stats) { $scope.distParameters.min = 0; $scope.distParameters.max = 1; } else { $scope.distParameters.min = stats.min(); $scope.distParameters.max = stats.max(); } } function readResult() { // Prevent reading if there is no need if ($scope.inputRead) return; var obj = $scope._result.obj; if (obj.distribution !== 'custom') return; if (obj.min === undefined || obj.max === undefined) { inferDistParameters(); } else { $scope.distParameters.min = obj.min; $scope.distParameters.max = obj.max; } $scope.histogram = !obj.histogram ? null : obj.histogram; $scope.inputRead = true; $timeout(initPlot); } function updatePoints() { var i, points = []; $scope.histogram = []; var px = $scope.path.getPointAt(0).x; var step = $scope.path.length / GRAPH_POINTS; for (i = 0; i <= $scope.path.length; i += step) { var p = $scope.path.getPointAt(i); if (p.x > px) { points.push({ x: p.x, y: p.y }); px += 1; } } var maxX = _.max(points, 'x').x, maxY = _.max(points, 'y').y; var minX = _.min(points, 'x').x, minY = _.min(points, 'y').y; var plotMinY = GRAPH_PADDING, plotMaxY = $scope.height - GRAPH_PADDING; var plotMinX = GRAPH_PADDING, plotMaxX = $scope.width - GRAPH_PADDING; var fx = (plotMaxX - plotMinX) / (maxX - minX); var fy = (plotMaxY - plotMinY) / (maxY - minY); var oldPath = $scope.path; $scope.path = new paper.Path(); var area = 0; for (i = 0; i < points.length; i++) { $scope.path.add(new paper.Point((points[i].x - minX) * fx + GRAPH_PADDING , (points[i].y - minY) * fy + GRAPH_PADDING)) ; points[i].x = (points[i].x - minX) / (maxX - minX); points[i].y = (maxY - points[i].y) / (maxY - minY); $scope.histogram.push(points[i].y); area += points[i].y; } $scope.maxY = 1/area; // Proof that the area of the resized histogram is 1 // var newArea = 0.0; // for (i = 0; i < points.length; i++) { // newArea += points[i].y * (1.0/area); // } // console.log('area = ', area, ' points = ', points.length, 'hf = ', 1/area, ' newarea = ', newArea ); $scope.path.strokeColor = '#e54c4c'; $scope.path.strokeWidth = 3; oldPath.replaceWith($scope.path); updateResult(); $scope.$apply(); } function drawHistogram() { if ($scope.histogram === null) { $scope.path = null; $scope.pathFinalized = false; return; } $scope.path = new paper.Path(); var area = 0; var xStep = ($scope.width - 2 * GRAPH_PADDING) / $scope.histogram.length; for (var i = 0; i < $scope.histogram.length; i++) { $scope.path.add(new paper.Point(i * xStep + GRAPH_PADDING , (1 - $scope.histogram[i]) * ($scope.height - 2 * GRAPH_PADDING) + GRAPH_PADDING)); area += $scope.histogram[i]; } $scope.maxY = 1/area; $scope.path.strokeColor = '#e54c4c'; $scope.path.strokeWidth = 3; $scope.pathFinalized = true; $scope.$apply(); } function checkPointCompatible(point) { var currentSegments = $scope.path.segments; if (currentSegments.length === 0) return true; return point.x >= currentSegments[currentSegments.length - 1].point.x; } function initPlot() { for (var i = 0; i < paper.projects.length; i++) paper.projects[i].remove(); for (var i = 0; i < paper.tools.length; i++) paper.tools[i].remove(); paper.setup($canvas[0]); $scope.tool = new paper.Tool(); $scope.tool.onMouseDown = function (event) { if ($scope.path) { console.log('path is not null with mouse down'); return; } $scope.path = new paper.Path(); $scope.path.strokeColor = '#e54c4c'; $scope.path.strokeWidth = 3; $scope.path.strokeCap = 'round'; $scope.path.strokeJoin = 'round'; }; $scope.tool.onMouseDrag = function (event) { if ($scope.pathFinalized) return; $scope.path.smooth(); if (!checkPointCompatible(event.point)) return; $scope.path.add(event.point); $scope.path.add(event.point); }; $scope.tool.onMouseUp = function (event) { if ($scope.pathFinalized) return; $scope.pathFinalized = true; $scope.path.simplify(); updatePoints(); updateResult(); }; drawPlot(); drawHistogram(); } function drawPlot() { $scope.height = $canvas.height(); $scope.width = $canvas.width(); var origin = new paper.Point(GRAPH_PADDING, $scope.height - GRAPH_PADDING); var axis = new paper.Group([ new paper.Path([ origin, new paper.Point(GRAPH_PADDING, GRAPH_PADDING) ]), new paper.Path([ new paper.Point(GRAPH_PADDING - ARROW_SIZE, GRAPH_PADDING), new paper.Point(GRAPH_PADDING, GRAPH_PADDING), ]), new paper.Path([ origin, new paper.Point($scope.width - GRAPH_PADDING, $scope.height - GRAPH_PADDING), ]), new paper.Path([ new paper.Point($scope.width - GRAPH_PADDING, $scope.height - GRAPH_PADDING + ARROW_SIZE), new paper.Point($scope.width - GRAPH_PADDING, $scope.height - GRAPH_PADDING) ]) ]); axis.strokeWidth = 1; axis.strokeColor = '#000000'; } $scope.cleanSketch = function () { paper.project.clear(); paper.view.draw(); $scope.path = null; $scope.pathFinalized = false; $scope.histogram = null; updateResult(); drawPlot(); }; $scope.$watch('distribution', updateResult); $scope.$watch('distParameters', updateResult, true); $scope.$watch('_result', function () { $scope.inputRead = false; readResult(); }, true); } }; }]); <|start_filename|>synner-server/src/main/resources/static/js/directives/generator-timerange.js<|end_filename|> angular.module('Synner') .directive('generatorTimerange', ['Model', function (Model) { return { templateUrl: 'fragments/generator-timerange.html', replace: true, restriction: 'E', scope: { _result: '=result', // where we will put the result of generation specifications field: '=' }, link: function ($scope, element, attrs) { $scope.inputRead = false; $scope.possibleHours = []; $scope.possibleMinutes = []; for (var i = 0; i < 24; i++) $scope.possibleHours.push(i); for (var i = 0; i < 60; i++) $scope.possibleMinutes.push(i); $scope.selectedFromHour = 0; $scope.selectedFromMinute = 0; $scope.selectedToHour = 0; $scope.selectedToMinute = 0; $scope.formatNum = function (n) { var strNum = n.toString(); if (strNum.length === 1) return '0' + n; return strNum; }; function updateResult() { if (!$scope.inputRead) return; var fromVal = timeToInt($scope.selectedFromHour, $scope.selectedFromMinute); var toVal = timeToInt($scope.selectedToHour, $scope.selectedToMinute); $scope._result.obj = { 'timerange': { from: fromVal, to: toVal } }; } function readResult() { if ($scope.inputRead) return; var obj = $scope._result.obj; if (obj && Model.isTimeRange(obj)) { var from = intToTime(obj.timerange.from); var to = intToTime(obj.timerange.to); $scope.selectedFromHour = from.hours; $scope.selectedFromMinute = from.minutes; $scope.selectedToHour = to.hours; $scope.selectedToMinute = to.minutes; } else { $scope.selectedFromHour = 0; $scope.selectedFromMinute = 0; $scope.selectedToHour = 0; $scope.selectedToMinute = 0; } $scope.inputRead = true; } function intToTime(t) { return { hours: Math.floor(t / 60), minutes: t - Math.floor(t / 60) * 60 }; } function timeToInt(hours, minutes) { return hours * 60 + minutes; } $scope.$watchCollection('[selectedFromHour, selectedFromMinute, selectedToHour, selectedToMinute]', updateResult); $scope.$watchCollection('[_result, _result.obj, field]', function () { $scope.inputRead = false; readResult(); }); } }; }]); <|start_filename|>synner-server/src/main/java/edu/nyu/dtl/synner/model/DownloadContact.java<|end_filename|> package edu.nyu.dtl.synner.model; import com.amazonaws.services.dynamodbv2.datamodeling.*; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Date; @DynamoDBTable(tableName="DownloadContacts") public class DownloadContact { public String id; public Date time; @JsonProperty public String name; @JsonProperty public String surname; @JsonProperty public String email; @JsonProperty public String organization; @JsonProperty public String comments; public DownloadContact() { this.time = new Date(); } public DownloadContact(String name, String surname, String email, String organization, String comments) { this.time = new Date(); this.name = name; this.surname = surname; this.email = email; this.organization = organization; this.comments = comments; } @DynamoDBHashKey(attributeName="ID") @DynamoDBAutoGeneratedKey public String getId() { return id; } public void setId(String id) { this.id = id; } @DynamoDBAttribute(attributeName="time") public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } @DynamoDBAttribute(attributeName="name") public String getName() { return name; } public void setName(String name) { this.name = name; } @DynamoDBAttribute(attributeName="surname") public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } @DynamoDBAttribute(attributeName="email") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @DynamoDBAttribute(attributeName="organization") public String getOrganization() { return organization; } public void setOrganization(String organization) { this.organization = organization; } @DynamoDBAttribute(attributeName="comments") public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } } <|start_filename|>synner-server/src/main/resources/static/js/directives/navbar.js<|end_filename|> angular.module('Synner') .directive('navbar', ['Parameters', 'API', 'Model', '$rootScope', function (Parameters, API, Model, $rootScope) { return { templateUrl: 'fragments/navbar.html', replace: true, restriction: 'E', scope: true, link: function ($scope, element, attrs) { $scope.model = Model; $scope.downloadModel = (function () { let a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; return function (object, fileName) { var blob = new Blob([JSON.stringify(object)], {type: "octet/stream"}); var url = window.URL.createObjectURL(blob); a.href = url; a.download = fileName; a.click(); window.URL.revokeObjectURL(url); }; }()); $scope.saveConfig = function () { var config = { fields: JSON.parse(JSON.stringify(Model.fields)), //fields deep copy dataVolume: Model.dataVolume }; $scope.filterNGHash(config); $scope.downloadModel(config, 'model-' + (new Date()).toISOString() + '.json'); }; $scope.filterNGHash = function (obj) { if ('$$hashKey' in obj) obj['$$hashKey'] = undefined; for (var p in obj) { if (typeof obj[p] === 'object') $scope.filterNGHash(obj[p]); } }; $scope.fileInput = document.getElementById("modeluploadfileinput"); $scope.fileInput.addEventListener("change", function () { if (this.files && this.files[0]) { var file = this.files[0]; var reader = new FileReader(); reader.addEventListener('load', function (e) { var obj = JSON.parse(e.target.result); Model.fields = obj.fields; Model.dataVolume = obj.dataVolume; Model.data = []; $scope.$apply(); $scope.fileInput.value = ''; }); reader.readAsBinaryString(file); } }); $scope.barpos = 0; $scope.progressBarDisplayInterval = null; $scope.$generationStatus = element.find('.generation-status'); $scope.$generationStatusProgressbar = element.find('.generation-status-progressbar'); $scope.progressBarSize = 0.2; $scope.pbopacity = 0; document.nb = $scope; $scope.updateMeasures = function () { $scope.generationStatusWidth = $scope.$generationStatus.width(); }; $scope.animateLoad = function () { if ($scope.pbopacity < 1) $scope.pbopacity += 0.2; else $scope.pbopacity = 1; $scope.$generationStatusProgressbar.css({ left: $scope.generationStatusWidth / 2 + ($scope.generationStatusWidth / 2) * Math.sin(($scope.barpos - 1) * Math.PI) - ($scope.generationStatusWidth * $scope.progressBarSize) / 2, opacity: $scope.pbopacity }); $scope.barpos = ($scope.barpos + 0.02) % 2; }; $scope.startLoadingDisplay = function () { $scope.updateMeasures(); $scope.pbopacity = 0; $scope.$generationStatusProgressbar.css({display:'initial', opacity: 0}); clearInterval($scope.progressBarDisplayInterval); $scope.progressBarDisplayInterval = setInterval($scope.animateLoad, 25); }; $scope.stopLoadingDisplay = function () { if ($scope.progressBarDisplayInterval == null) return; clearInterval($scope.progressBarDisplayInterval); $scope.progressBarDisplayInterval = null; $scope.$generationStatusProgressbar.css({display:'none', opacity: 0}); }; $rootScope.$on('DATA_UPDATE_START', $scope.startLoadingDisplay); $rootScope.$on('DATA_UPDATE_END', $scope.stopLoadingDisplay); } }; }]); <|start_filename|>synner-server/src/main/resources/static/expression-parser/antrl4-browserify-script.js<|end_filename|> var antlr4 = require('../node_modules/antlr4/index'); var ECMAScriptLexer = require('./ECMAScriptLexer'); var ECMAScriptParser = require('./ECMAScriptParser'); var ECMAScriptListener = require('./ECMAScriptListener'); var ECMAScriptVisitor = require('./ECMAScriptVisitor'); var listener = ECMAScriptListener(antlr4); var visitor = ECMAScriptVisitor(antlr4); exports.ExpressionParser = { ECMAScriptLexer: ECMAScriptLexer(antlr4), ECMAScriptParser: ECMAScriptParser(antlr4, listener, visitor), ECMAScriptVisitor: visitor, ECMAScriptListener: listener }; <|start_filename|>synner-server/src/main/resources/static/js/directives/generator-daterange.js<|end_filename|> angular.module('Synner') .directive('generatorDaterange', ['Model', function (Model) { return { templateUrl: 'fragments/generator-daterange.html', replace: true, restriction: 'E', scope: { _result: '=result', // where we will put the result of generation specifications field: '=' }, link: function ($scope, element, attrs) { $scope.inputRead = false; document.datetimecontroller = $scope; function updateResult() { if (!$scope.inputRead) return; var from = dateToDays($scope.selectedFromDate); var to = dateToDays($scope.selectedToDate); $scope._result.obj = { 'daterange': { from: from, to: to } }; } function readResult() { if ($scope.inputRead) return; var obj = $scope._result.obj; if (obj && Model.isDateRange(obj)) { if (!$scope.selectedFromDate || obj.daterange.from !== dateToDays($scope.selectedFromDate)) $scope.selectedFromDate = new Date(daysToMills(obj.daterange.from)); if (!$scope.selectedToDate || obj.daterange.to !== dateToDays($scope.selectedToDate)) $scope.selectedToDate = new Date(daysToMills(obj.daterange.to)); } else { $scope.selectedFromDate = new Date(Date.now() - 365*24*60*60*1000); $scope.selectedToDate = new Date(); } $scope.inputRead = true; } function dateToDays(date) { if (!date) return 0; return date.getTime() / (1000*60*60*24); } function daysToMills(days) { if (!days) return 0; return days * (1000*60*60*24); } $scope.$watchCollection('[selectedFromDate, selectedToDate]', updateResult); $scope.$watchCollection('[_result, _result.obj, field]', function () { $scope.inputRead = false; readResult(); }); } }; }]); <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/datamodel/Table.java<|end_filename|> package edu.nyu.dtl.synner.core.datamodel; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.*; import static edu.nyu.dtl.synner.core.datamodel.ColumnType.INT; import static edu.nyu.dtl.synner.core.datamodel.ColumnType.TIME; public class Table { public final static int FILTERED_GENERATIONS_TENTATIVES = 1000; @JsonProperty private final Set<Field> fields = new TreeSet<>(); private List<Field> generationOrder; public Table(Collection<Field> fields) { this.fields.addAll(fields); generationOrder = Relationship.topologicalSort(this.fields); } public Set<Field> getFields() { return Collections.unmodifiableSet(fields); } public int getColumnsNumber() { return fields.size(); } public Comparable finalizeINT(Comparable val) { if (val instanceof Double) { val = Math.round((Double) val); } else if (val instanceof String) { val = Math.round(Double.valueOf((String) val)); } else if (val instanceof StatusValue) { StatusValue sv = (StatusValue) val; sv.value = finalizeINT(sv.value); } return val; } public Comparable finalizeTIME(Comparable val) { if (val instanceof StatusValue) { StatusValue sv = (StatusValue) val; sv.value = finalizeTIME(sv.value); return sv; } else { long v; if (val instanceof Double) { v = ((Double) val).longValue(); } else if (val instanceof Long) { v = (long) val; } else { v = ((Integer) val).longValue(); } if (v < 0) v = 60*24 + v; v %= 60*24; return v; } } public void finalizeValue(Comparable[] tuple, Field c) { if (c.getType() == INT && tuple[c.getPos()] != null) { tuple[c.getPos()] = finalizeINT(tuple[c.getPos()]); } else if (c.getType() == TIME && tuple[c.getPos()] != null) { tuple[c.getPos()] = finalizeTIME(tuple[c.getPos()]); } } /** * Generate a tuple. * @param tuple the tuple to generate, which can be also pre-filled (not null values are not rewrited) * @return the tuple given as argument where null values have been replaced with generated ones */ public Comparable[] generateTuple(Comparable[] tuple, boolean previewMode) throws Exception { try { for (Field c : generationOrder) { if (tuple[c.getPos()] != null) continue; //TODO there should be a check of the type/generator List<Field> dependencies = c.getDependencies(); if (c.getMissingRows() > 0) { if (c.getGenerator().getRnd().nextInt(100) < c.getMissingRows()) { tuple[c.getPos()] = null; continue; } } boolean errorMode = false; if (c.getErrorRows() > 0) { if (c.getGenerator().getRnd().nextInt(100) < c.getErrorRows()) errorMode = true; } boolean filteredValue = true; int tentatives = FILTERED_GENERATIONS_TENTATIVES; while (tentatives >= 0 && filteredValue) { if (dependencies.isEmpty()) { if (errorMode) { tuple[c.getPos()] = new StatusValue(c.getGenerator().generate(true, previewMode), "error"); } else { tuple[c.getPos()] = c.getGenerator().generate(false, previewMode); } } else { Comparable[] dependencyVals = new Comparable[dependencies.size()]; for (int i = 0; i < dependencies.size(); i++) { dependencyVals[i] = tuple[dependencies.get(i).getPos()]; assert dependencyVals[i] != null; } if (errorMode) { tuple[c.getPos()] = new StatusValue(c.getGenerator().generate(dependencyVals, true, previewMode), "error"); } else { tuple[c.getPos()] = c.getGenerator().generate(dependencyVals, false, previewMode); } } filteredValue = !c.evaluateFilter(tuple[c.getPos()]); tentatives--; } if (tentatives < 0) throw new RuntimeException("Data cannot be generated with the current filter in field " + c.getName()); finalizeValue(tuple, c); } return tuple; } catch (Exception e) { e.printStackTrace(); throw e; } } /** * Generate a tuple. A new tuple to store the generated values is created and returned filled with generated values. */ public Comparable[] generateTuple(boolean previewMode) throws Exception { return generateTuple(new Comparable[fields.size()], previewMode); } } <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/generators/numerical/ExponentialGen.java<|end_filename|> package edu.nyu.dtl.synner.core.generators.numerical; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import edu.nyu.dtl.synner.core.generators.Generator; @JsonPropertyOrder({"type", "rate"}) public class ExponentialGen implements Generator<Double> { @JsonProperty double rate; public ExponentialGen(double rate) { this.rate = rate; } @Override public Double generate(boolean errorMode, boolean previewMode) { if (errorMode) return - rnd.nextDouble() * 100; return Math.log(1 - rnd.nextDouble()) / (-rate); } @JsonProperty public String getType() { return "exponential"; } } <|start_filename|>synner-server/src/main/java/edu/nyu/dtl/synner/api/APIController.java<|end_filename|> package edu.nyu.dtl.synner.api; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.regions.Regions; import com.amazonaws.auth.BasicSessionCredentials; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.model.*; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import edu.nyu.dtl.synner.core.datamodel.GeneratedDataset; import edu.nyu.dtl.synner.core.datamodel.Table; import edu.nyu.dtl.synner.core.GeneratorInfo; import edu.nyu.dtl.synner.core.generators.domain.DomainsManager; import edu.nyu.dtl.synner.core.parser.DataParser; import edu.nyu.dtl.synner.core.parser.RelationParser; import edu.nyu.dtl.synner.core.infer.*; import edu.nyu.dtl.synner.model.DownloadContact; import edu.nyu.dtl.synner.model.RequestResponseMessage; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.StringReader; import java.sql.Connection; import java.sql.SQLException; import java.util.*; @RestController @RequestMapping("/api") public class APIController { // synner-app user BasicAWSCredentials awsCreds = new BasicAWSCredentials( "AKIA2UC74TZPOBBLDN3A", "<KEY>"); final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.standard() .withRegion(Regions.US_EAST_2) .withCredentials(new AWSStaticCredentialsProvider(awsCreds)) .build(); @ExceptionHandler void handleIllegalArgumentException(IllegalArgumentException e, HttpServletResponse response) throws IOException { response.sendError(HttpStatus.BAD_REQUEST.value()); } @RequestMapping(value = "/generator", method = RequestMethod.POST) public @ResponseBody GeneratedDataset generator(@RequestBody String specifications, ServletRequest req, ServletResponse resp) throws Exception { StringReader strReader = new StringReader(specifications); ObjectMapper mapper = new ObjectMapper(new JsonFactory()); JsonNode rootNode = mapper.readTree(strReader); Table rel = new RelationParser().readModel(rootNode.get("model")); boolean previewMode = rootNode.has("preview-mode") ? rootNode.get("preview-mode").asBoolean() : false; GeneratedDataset gdata = new DataParser().readModel(rel, rootNode.get("data")); gdata.generate(previewMode); return gdata; } @RequestMapping(value = "/generator", produces = "application/json", method = RequestMethod.GET) public @ResponseBody GeneratorInfo generator() throws IOException, SQLException { GeneratorInfo gi = new GeneratorInfo(); Connection c = DomainsManager.getConnection(); gi.setAvailableDomains(DomainsManager.getDomains(c, false, null)); c.close(); return gi; } @RequestMapping(value = "/generator.csv", produces = "application/json", method = RequestMethod.GET) public @ResponseBody String generatorCSV() throws IOException { return "this is a CSV"; } @RequestMapping(value = "/generator.json", produces = "application/json", method = RequestMethod.GET) public @ResponseBody String generatorJSON() throws IOException { return "this is a JSON"; } @RequestMapping(value = "/infer", produces = "application/json", method = RequestMethod.POST) public @ResponseBody List<InferResponse> infer(@RequestBody List<InferRequest> inferRequests) throws IOException, SQLException { List<InferResponse> inferResponses = new ArrayList<>(); for (InferRequest infReq : inferRequests) { inferResponses.add(Infer.infer(infReq)); } return inferResponses; } @RequestMapping(value = "/downloadrequest", produces = "application/json", method = RequestMethod.POST) public @ResponseBody RequestResponseMessage downloadRequest(@RequestBody DownloadContact contactDetails) throws IOException, SQLException { DynamoDBMapper mapper = new DynamoDBMapper(ddb); mapper.save(contactDetails); return new RequestResponseMessage("ok", ""); } } <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/generators/numerical/GaussianGen.java<|end_filename|> package edu.nyu.dtl.synner.core.generators.numerical; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import edu.nyu.dtl.synner.core.generators.Generator; @JsonPropertyOrder({"type", "mean", "stddev"}) public class GaussianGen implements Generator<Double> { @JsonProperty double mean; @JsonProperty("stdev") double stdev; public GaussianGen(double mean, double stdev) { this.mean = mean; this.stdev = stdev; } @Override public Double generate(boolean errorMode, boolean previewMode) { double res = rnd.nextGaussian() * stdev + mean; if (errorMode) return res + (rnd.nextBoolean() ? 1 : - 1) * 4 * stdev; return res; } @JsonProperty public String getType() { return "gaussian"; } } <|start_filename|>synner-server/src/main/resources/static/js/directives/field-filter.js<|end_filename|> angular.module('Synner') .directive('fieldFilter', ['$rootScope', '$timeout', 'Model', 'Functions', 'Parameters', function ($rootScope, $timeout, Model, Functions, Parameters) { return { templateUrl: 'fragments/field-filter.html', replace: true, restriction: 'E', scope: { field: '=' }, link: function ($scope, element, attrs) { $scope.fieldFilter = ''; $scope.filterError = null; function checkFilter() { if ($scope.fieldFilter === null || $scope.fieldFilter === undefined || $scope.fieldFilter.length === 0) { Functions.clearFieldsHighlights(); $scope.filterError = null; return; } var $visibleLines = Functions.getVisibleLines(); $scope.filterError = null; var conditionFunction; try { conditionFunction = Functions.compileFunction($scope.fieldFilter, [$scope.field]); for (var i = 0; i < $visibleLines.length; i++) { if ($visibleLines[i].hasClass('add-rows-button-row')) continue; Functions.evaluateConditionInLines(conditionFunction, $visibleLines[i]); } } catch (e) { $scope.filterError = e; } } function updateResult() { if (!$scope.inputRead) return; if ($scope.filterError == null) { Functions.clearFieldsHighlights(); $scope.field.filter = $scope.fieldFilter; $scope.field.editingFilter = false; $scope.inputRead = true; } } function readResult() { if ($scope.inputRead) return; $scope.fieldFilter = $scope.field.filter; $scope.inputRead = true; } $scope.approveChanges = function () { checkFilter(); updateResult() }; $scope.discargeChanges = function () { Functions.clearFieldsHighlights(); $scope.fieldFilter = $scope.field.filter; $scope.filterError = null; $scope.field.editingFilter = false; $scope.inputRead = true; }; $scope.$watch('field.editingFilter', function (editingFilter) { if (editingFilter) { $timeout(function () { element.find('input.field-filter-text').focus(); }); } else { $scope.discargeChanges(); $scope.$parent.selectField($scope.field); } }); $scope.$watch('fieldFilter', checkFilter); $scope.$watch('field.filter', function () { $scope.inputRead = false; readResult(); }); } }; }]); <|start_filename|>synner-server/src/main/resources/static/js/directives/infer-panel.js<|end_filename|> angular.module('Synner') .directive('inferPanel', ['Parameters', 'Infer', 'Model', function (Parameters, Infer, Model) { return { templateUrl: 'fragments/infer-panel.html', replace: true, restriction: 'E', scope: { field: '=' }, link: function ($scope, element, attrs) { $scope.model = Model; $scope.modify = function (f, generator) { $scope.field._generator.obj = generator; Model.deleteFieldData($scope.field); }; $scope.$watchGroup(['field', 'field.type', 'field.name'], function () { Infer.inferFromData($scope.field); }); } }; }]); <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/generators/domain/FreqValue.java<|end_filename|> package edu.nyu.dtl.synner.core.generators.domain; public class FreqValue { private int freq; private String value; public FreqValue(int freq, String value) { this.freq = freq; this.value = value; } public int getFreq() { return freq; } public void setFreq(int freq) { this.freq = freq; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public String toString() { return freq + ", " + value; } } <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/GeneratorInfo.java<|end_filename|> package edu.nyu.dtl.synner.core; import com.fasterxml.jackson.annotation.JsonProperty; import edu.nyu.dtl.synner.core.generators.domain.DomainInfo; import java.util.Map; public class GeneratorInfo { @JsonProperty("available-domains") Map<String, DomainInfo> availableDomains; public Map<String, DomainInfo> getAvailableDomains() { return availableDomains; } public void setAvailableDomains(Map<String, DomainInfo> availableDomains) { this.availableDomains = availableDomains; } } <|start_filename|>synner-server/src/main/resources/static/js/directives/generator-distribution.js<|end_filename|> angular.module('Synner') .directive('generatorDistribution', ['$rootScope', '$timeout', 'Model', 'Infer', 'Parameters', function ($rootScope, $timeout, Model, Infer, Parameters) { return { templateUrl: 'fragments/generator-distribution.html', replace: true, restriction: 'E', scope: { distribution: '=', // where we will put the result of generation specifications _result: '=result', field: '=', enabled: '=', compactView: '=', labels: '=' }, link: function ($scope, element, attrs) { var INTERVALS = 50; $scope.dataVolume = Model.dataVolume; $scope.experimentsNumber = Model.experimentsNumber; // Plot contants $scope.GRAPH_HEIGHT = 250; $scope.GRAPH_WIDTH = 3 * $scope.GRAPH_HEIGHT; $scope.MARGIN = {top: 5, right: 5, bottom: 40, left: 50}; $scope.closeUpHeight = 30; $scope.model = Model; $scope.inputRead = false; $scope.marginTop = 40; $scope.dataGenerationReqTimeout = null; $scope.distrFunctions = { distribution: undefined, // the jstat object that represents the distribution sample: undefined, // function which will sample a value of the distribution pdf: undefined, // function which accepts a value and gives the pdf of that value cdf: undefined // function which accepts a value and gives the cdf of that value }; $scope.distParameters = { min: 0, // used for all the distributions that can start and end in a specific range max: 1, // used for all the distributions that can start and end in a specific range rate: 1, // used for exponential distribution 1.0251355942973368 borderline outstide 2 outside mean: 30, // used gaussian 30.779466958499995 borderline outstide 35 outside stdev: 5, // used for gaussian 5.138736292550285 borderline outside 7 outside shape: 3, // used for gamma (equivalent to k) 3.6084724011948155 borderline outstide 4 outside scale: 2 // used for gamma (equivalent to k)1.7550710765363955 borderline outstide 3 outside }; $scope.graphVisibility = 'hidden'; // Plot with and height $scope.graphWidth = 0; $scope.graphHeight = 0; // The entire available space width and height $scope.availableSpace = {width: 0, height: 0}; function inferDistParameters() { var stats = Infer.inferDistribution($scope.field); if (!stats) { $scope.distParameters.stdev = 1; $scope.distParameters.min = 0; $scope.distParameters.max = 1; $scope.distParameters.mean = 0; } else { $scope.distParameters.stdev = parseFloat(stats.stdev().toFixed(2)); $scope.distParameters.min = parseFloat(stats.min().toFixed(2)); $scope.distParameters.max = parseFloat(stats.max().toFixed(2)); $scope.distParameters.mean = parseFloat(stats.mean().toFixed(2)); } $scope.distParameters.rate = 1; } function readResult() { // Prevent reading if there is no need if ($scope.inputRead) return; var obj = $scope._result.obj; if (!obj) { inferDistParameters(); } else { switch ($scope.distribution) { case 'uniform': if (obj.min === undefined || obj.max === undefined) inferDistParameters(); else { $scope.distParameters.min = obj.min; $scope.distParameters.max = obj.max; } break; case 'gaussian': if (obj.mean === undefined || obj.stdev === undefined) inferDistParameters(); else { $scope.distParameters.mean = obj.mean; $scope.distParameters.stdev = obj.stdev; } break; case 'exponential': if (obj.rate === undefined) inferDistParameters(); else { $scope.distParameters.rate = obj.rate; } break; } } $scope.inputRead = true; if (!obj) updateGraph(); // update the result with the default values } function generatingResult() { var generator = { distribution: $scope.distribution }; switch ($scope.distribution) { case 'gaussian': generator.mean = $scope.distParameters.mean; generator.stdev = $scope.distParameters.stdev; break; case 'exponential': generator.rate = $scope.distParameters.rate; break; case 'uniform': generator.min = $scope.distParameters.min; generator.max = $scope.distParameters.max; } return generator; } function updateResult() { if (!$scope.inputRead) return; // Prevent changes on the distribution parameters to change the input, even before reading it if (!$scope._result) return; // in case the directive is active without any result specified $scope._result.obj = generatingResult(); updateGraph(); } function updateGraph() { if (!$scope.svg) initGraph(); $scope.dataVolume = Model.dataVolume; $scope.experimentsNumber = Model.experimentsNumber; $scope.distrFunctions = buildDistrFunctions($scope.distribution, $scope.distParameters); var distrRangeInfo = updateDistrRange($scope.distrFunctions, $scope.distParameters, $scope.rangeX); $scope.distrRange = distrRangeInfo.distrRange; $scope.distrRangeStep = distrRangeInfo.distrRangeStep; var thData = generateTheoreticalDistributionData($scope.distribution, $scope.distrFunctions, $scope.distrRange, $scope.distrRangeStep, $scope.distParameters); $scope.graphData = thData.data; updateParametersProbs($scope.distribution, thData.parametersProbs); $scope.samplesAvailable = true; for (var i = 0; i < $scope.experimentsNumber; i++) generateSampledDistributionData(i); $timeout(render); } function initGraph() { $scope.svg = d3.select(element.find('.distribution-plot')[0]); // scales $scope.x = d3.scale.linear(); $scope.y = d3.scale.linear(); // axis $scope.xAxis = d3.svg.axis().orient('bottom'); $scope.yAxis = d3.svg.axis().orient('left'); if ($scope.labels) { $scope.svg.append('text') .attr('class', 'x label') .text($scope.labels.x) .attr('text-anchor', 'middle'); $scope.svg.append('text') .attr('class', 'y label') .text($scope.labels.y) .attr('transform', 'rotate(-90)') .attr('text-anchor', 'middle'); } $scope.chartWrapper = $scope.svg.append('g'); $scope.chartWrapper.append('g').classed('x axis', true); $scope.chartWrapper.append('g').classed('y axis', true); $scope.chartWrapper.append('line').classed('left-std-dev', true); $scope.chartWrapper.append('line').classed('right-std-dev', true); $scope.chartWrapper.append('line').classed('mean', true); $scope.path = $scope.chartWrapper.append('path').classed('line', true); $scope.samples = []; $scope.samplesAvailable = false; for (var i = 0; i < $scope.experimentsNumber; i++) { $scope.samples.push({ id: i, path: undefined, area: undefined, x: d3.scale.linear(), y: d3.scale.linear(), }); } $scope.minMax = $scope.chartWrapper.append('path').classed('sample-area', true); $scope.areaSamplesContainer = $scope.chartWrapper.append('g').classed('area-samples', true); for (var i = 0; i < $scope.experimentsNumber; i++) { $scope.samples[i].area = $scope.areaSamplesContainer.append('path').classed('sample-area', true); } $scope.samplesContainer = $scope.chartWrapper.append('g').classed('samples', true); for (var i = 0; i < $scope.experimentsNumber; i++) { var samplePath = $scope.samplesContainer.append('path').classed('sample', true); samplePath.attr('exp-id', i); $scope.samples[i].path = samplePath; } $scope.histogram = $scope.chartWrapper.append('g').classed('histogram', true); $scope.meanCloseup = d3.select(element.find('.mean-closeup svg')[0]); $scope.meanCloseup.append('g').append('g').classed('samples', true); $scope.meanCloseup.attr('height', $scope.closeUpHeight); $scope.stdevCloseup = d3.select(element.find('.stdev-closeup svg')[0]); $scope.stdevCloseup.append('g').append('g').classed('samples', true); $scope.stdevCloseup.attr('height', $scope.closeUpHeight); $scope.rateCloseup = d3.select(element.find('.rate-closeup svg')[0]); $scope.rateCloseup.append('g').append('g').classed('samples', true); $scope.rateCloseup.attr('height', $scope.closeUpHeight); $scope.shapeCloseup = d3.select(element.find('.shape-closeup svg')[0]); $scope.shapeCloseup.append('g').append('g').classed('samples', true); $scope.shapeCloseup.attr('height', $scope.closeUpHeight); $scope.scaleCloseup = d3.select(element.find('.scale-closeup svg')[0]); $scope.scaleCloseup.append('g').append('g').classed('samples', true); $scope.scaleCloseup.attr('height', $scope.closeUpHeight); $scope.minCloseup = d3.select(element.find('.min-closeup svg')[0]); $scope.minCloseup.append('g').append('g').classed('samples', true); $scope.minCloseup.attr('height', $scope.closeUpHeight); $scope.maxCloseup = d3.select(element.find('.max-closeup svg')[0]); $scope.maxCloseup.append('g').append('g').classed('samples', true); $scope.maxCloseup.attr('height', $scope.closeUpHeight); return true; } function updateDimensions() { $scope.availableSpace.width = element.find('.distribution-plot-container').width(); $scope.availableSpace.height = element.find('.distribution-plot-container').height(); $scope.graphWidth = $scope.GRAPH_WIDTH - $scope.MARGIN.left - $scope.MARGIN.right; $scope.graphHeight = $scope.GRAPH_HEIGHT - $scope.MARGIN.top - $scope.MARGIN.bottom; } function render() { if (!$scope.svg || !$scope.graphData || !$scope.samplesAvailable) return; //get dimensions based on window size updateDimensions(); // d3.select('.generator-distribution').selectAll('.specs').remove(); //update x and y scales to new dimensions $scope.svg.attr('width', $scope.graphWidth + $scope.MARGIN.right + $scope.MARGIN.left) .attr('height', $scope.graphHeight + $scope.MARGIN.top + $scope.MARGIN.bottom); $scope.chartWrapper.attr('transform', 'translate(' + $scope.MARGIN.left + ',' + $scope.MARGIN.top + ')'); $scope.x.range([0, $scope.graphWidth]); $scope.y.range([$scope.graphHeight, 0]); $scope.xAxis.scale($scope.x); $scope.yAxis.scale($scope.y); $scope.svg.select('.x.axis') .attr('transform', 'translate(0,' + $scope.graphHeight + ')') .call($scope.xAxis); $scope.svg.select('.y.axis') .call($scope.yAxis); if ($scope.labels) { $scope.svg.select('.x.label') .attr('x', $scope.graphWidth / 2 + $scope.MARGIN.left) .attr('y', $scope.graphHeight + $scope.MARGIN.top + 30); $scope.svg.select('.y.label') .attr('x', - $scope.graphHeight / 2) .attr('y', 10) .text($scope.labels.y); } // Change data $scope.x.domain(d3.extent($scope.graphData, function (d) { return d.n; })); $scope.y.domain([0, d3.max($scope.graphData, function (d) { return d.p * ($scope.distribution === 'uniform' ? 2 : 1.5); })]); $scope.xAxis.scale($scope.x); $scope.yAxis.scale($scope.y); $scope.line = d3.svg.line() .x(function (d) { return $scope.x(d.n); }) .y(function (d) { return $scope.y(d.p); }); if ($scope.distribution === 'uniform') { $scope.line.interpolate('step-after'); } else { $scope.line.interpolate('cardinal'); } $scope.area = d3.svg.area() .x(function (d) { return $scope.x(d.n); }) .y0(function (d) { return $scope.y(d.pTheory); }) .y1(function (d) { return $scope.y(d.p); }); $scope.minMaxArea = d3.svg.area() .x(function (d) { return $scope.x(d.n); }) .y0(function (d) { return $scope.y(d.pMin); }) .y1(function (d) { return $scope.y(d.pMax); }); if ($scope.distribution === 'uniform') { $scope.area.interpolate('linear'); $scope.minMaxArea.interpolate('linear'); } else { $scope.area.interpolate('cardinal'); $scope.minMaxArea.interpolate('cardinal'); } var bins = $scope.histogram.selectAll('rect').data([]); bins.exit().transition().remove(); bins.enter().append('rect') .classed('highlighted-histogram', false) .classed('theoretical-area', true) .style('fill-opacity', '0.7') .attr('x', function (d) { return $scope.x(d.n - $scope.distrRangeStep / 2) + 1; }) .attr('y', function (d) { return $scope.y(d.p); }) .attr('width', $scope.x($scope.distrRangeStep) - $scope.x(0) - 2) .attr('height', function (d) { return Math.abs($scope.y(d.p) - $scope.y(0)); }); bins.transition() .duration(500) .style('fill-opacity', '0.7') .attr('x', function (d) { return $scope.x(d.n - $scope.distrRangeStep / 2) + 1; }) .attr('y', function (d) { return $scope.y(d.p); }) .attr('width', $scope.x($scope.distrRangeStep) - $scope.x(0) - 2) .attr('height', function (d) { return Math.abs($scope.y(d.p) - $scope.y(0)); }); $scope.path .classed('theoretical-line', true) .transition().duration(750) .attr('d', $scope.design === 'histogram' ? null : $scope.line($scope.graphData)); var expected = []; for (var i = 0; i < $scope.graphData.length; i++) expected.push($scope.graphData[i].p); for (var i = 0; i < $scope.experimentsNumber; i++) { $scope.samples[i].path .classed('hidden-sample', $scope.design !== 'sampleSketches') .transition() .duration(1000) .attr('d', $scope.line($scope.samples[i].data)); } for (var i = 0; i < $scope.experimentsNumber; i++) { var data = $scope.samples[i].data; if ($scope.distribution === 'uniform') { var newData = []; for (var j = 0; j < $scope.samples[i].data.length; j++) { var dt = $scope.samples[i].data[j]; if (dt.p === 0) continue; if (j === 0) { newData.push({ n: $scope.distrRange[0], p: dt.p, pTheory: dt.pTheory }); } else if (j === $scope.samples[i].data.length - 1) { newData.push({ n: $scope.distrRange[1], p: dt.p, pTheory: dt.pTheory }); } else { newData.push(dt); } } data = newData; } if ($scope.samples[i].bins) $scope.samples[i].bins.remove(); $scope.samples[i].area .classed('theoretical-area', true) .transition().duration(1000) .attr('d', $scope.area(data)); } var svgt = $scope.svg.transition(); svgt.select('.x.axis').call($scope.xAxis); svgt.select('.y.axis').call($scope.yAxis); drawDistributionSpecificAdditionalInfo(); $scope.graphVisibility = 'visible'; addMouseOverInfo(); } function updateBins(data) { var xShift = 0; if ($scope.distribution !== 'uniform') { xShift = - $scope.distrRangeStep / 2; } var bins = $scope.histogram.selectAll('rect').data(data); bins.exit().transition().style('fill-opacity', '0').remove(); bins.enter().append('rect') .classed('highlighted-histogram', true) .attr('x', function (d) { return $scope.x(d.n + xShift) + 1; }) .attr('y', function (d) { return $scope.y(d.p); }) .attr('width', $scope.x($scope.distrRangeStep) - $scope.x(0) - 2) .attr('height', function (d) { return Math.abs($scope.y(d.p) - $scope.y(0)); }); bins .transition() .duration(100) .style('fill-opacity', null) .attr('x', function (d) { return $scope.x(d.n + xShift) + 1; }) .attr('y', function (d) { return $scope.y(d.p); }) .attr('width', $scope.x($scope.distrRangeStep) - $scope.x(0) - 2) .attr('height', function (d) { return Math.abs($scope.y(d.p) - $scope.y(0)); }); } function highlightSample(id) { element.find('.sample').each(function () { var el = d3.select(this); if (el.attr('exp-id') === id) { el.classed('highlighted', true); } else { el.classed('highlighted', false); } }); } $scope.removeHistogramTimeout = null; function addMouseOverInfo() { element .off('mouseover') .off('mouseout') .on('mouseover', '.sample', function () { if ($scope.removeHistogramTimeout) { clearTimeout($scope.removeHistogramTimeout); $scope.removeHistogramTimeout = null; } var id = d3.select(this).attr('exp-id'); highlightSample(id); updateBins($scope.samples[id].data); }) .on('mouseout', '.sample', function () { $scope.removeHistogramTimeout = setTimeout(function () { updateBins([]); highlightSample(null); }, 1000); }); } function drawDistributionSpecificAdditionalInfo() { var distributionPropWidth = $($scope.meanCloseup[0][0]).closest('.distribution-property').width(); if ($scope.distribution === 'gaussian') { element.find('.left-std-dev').removeClass('hidden'); element.find('.right-std-dev').removeClass('hidden'); element.find('.mean').removeClass('hidden'); element.find('.stdev-closeup').removeClass('hidden'); element.find('.mean-closeup').removeClass('hidden'); $scope.gStDevLLine = $scope.svg.select('.left-std-dev') .attr('x1', $scope.x($scope.distParameters.mean - $scope.distParameters.stdev)) .attr('y1', $scope.y($scope.stdProb)) .attr('x2', $scope.x($scope.distParameters.mean - $scope.distParameters.stdev)) .attr('y2', $scope.y(0)) .classed('theoretical-stdev', true); $scope.gStDevRLine = $scope.svg.select('.right-std-dev') .attr('x1', $scope.x($scope.distParameters.mean + $scope.distParameters.stdev)) .attr('y1', $scope.y($scope.stdProb)) .attr('x2', $scope.x($scope.distParameters.mean + $scope.distParameters.stdev)) .attr('y2', $scope.y(0)) .classed('theoretical-stdev', true); $scope.meanLine = $scope.svg.select('.mean') .attr('x1', $scope.x($scope.distParameters.mean)) .attr('y1', $scope.y($scope.meanProb)) .attr('x2', $scope.x($scope.distParameters.mean)) .attr('y2', $scope.y(0)) .classed('theoretical-mean', true); // graphing the range of mean var meanMin = _.min($scope.samples, 'mean').mean; var meanMax = _.max($scope.samples, 'mean').mean; var meanCloseupX = d3.scale.linear() .domain([meanMin - 0.1 * (meanMax - meanMin), meanMax + 0.1 * (meanMax - meanMin)]) .range([0, distributionPropWidth]); var meanAxis = d3.svg.axis().scale(meanCloseupX) .tickValues([meanMin, $scope.distParameters.mean, meanMax]) .outerTickSize(0); $scope.meanCloseup .attr('width', distributionPropWidth) .select('g') .attr('transform', 'translate(0, 10)') .call(meanAxis); var data = []; for (var i = 0; i < $scope.experimentsNumber; i++) data.push({x: $scope.samples[i].mean, sample: true, id: i}); data.push({x: $scope.distParameters.mean, sample: false, id: -1}); $scope.meanCloseup.select('.samples').selectAll('line').data([]).exit().remove(); var rects = $scope.meanCloseup.select('.samples').selectAll('rect').data(data); rects.exit().remove(); rects.enter().append('rect') .attr('exp-id', function (d, i) { return i; }) .attr('x', function (d) { return Math.min(meanCloseupX($scope.distParameters.mean), meanCloseupX(d.x)); }) .attr('y', function (d) { return d.sample ? -5 : -7; }) .attr('width', function (d) { return d.sample ? Math.abs(meanCloseupX(d.x) - meanCloseupX($scope.distParameters.mean)) : 1; }) .attr('height', function (d) { return d.sample ? 10 : 14; }) .attr('class', function (d) { return d.sample ? 'sample layered' : 'theoretical-mean layered';}); rects.transition() .duration(500) .attr('exp-id', function (d, i) { return i; }) .attr('x', function (d) { return Math.min(meanCloseupX($scope.distParameters.mean), meanCloseupX(d.x)); }) .attr('y', function (d) { return d.sample ? -5 : -7; }) .attr('width', function (d) { return d.sample ? Math.abs(meanCloseupX(d.x) - meanCloseupX($scope.distParameters.mean)) : 1; }) .attr('height', function (d) { return d.sample ? 10 : 14; }) .attr('class', function (d) { return d.sample ? 'sample layered' : 'theoretical-mean layered';}); // graphing the range of standard deviation var stdMin = _.min($scope.samples, 'stdev').stdev; var stdMax = _.max($scope.samples, 'stdev').stdev; var stdevCloseupX = d3.scale.linear() .domain([stdMin - 0.1 * (stdMax - stdMin), stdMax + 0.1 * (stdMax - stdMin)]) .range([0, distributionPropWidth]); var stdAxis = d3.svg.axis().scale(stdevCloseupX) .tickValues([stdMin, $scope.distParameters.stdev, stdMax]) .outerTickSize(0); $scope.stdevCloseup .attr('width', distributionPropWidth) .select('g') .attr('transform', 'translate(0, 10)') .call(stdAxis); var data = []; for (var i = 0; i < $scope.experimentsNumber; i++) data.push({x: $scope.samples[i].stdev, sample: true, id: i}); data.push({x: $scope.distParameters.stdev, sample: false, id: -1}); $scope.stdevCloseup.select('.samples').selectAll('line').data([]).exit().remove(); var rects = $scope.stdevCloseup.select('.samples').selectAll('rect').data(data); rects.exit().remove(); rects.enter().append('rect') .attr('exp-id', function (d, i) { return i; }) .attr('x', function (d) { return Math.min(stdevCloseupX($scope.distParameters.stdev), stdevCloseupX(d.x)); }) .attr('y', function (d) { return d.sample ? -5 : -7; }) .attr('width', function (d) { return d.sample ? Math.abs(stdevCloseupX(d.x) - stdevCloseupX($scope.distParameters.stdev)) : 1; }) .attr('height', function (d) { return d.sample ? 10 : 14; }) .attr('class', function (d) { return d.sample ? 'sample layered' : 'theoretical-stdev layered';}); rects.transition() .duration(500) .attr('exp-id', function (d, i) { return i; }) .attr('x', function (d) { return Math.min(stdevCloseupX($scope.distParameters.stdev), stdevCloseupX(d.x)); }) .attr('y', function (d) { return d.sample ? -5 : -7; }) .attr('width', function (d) { return d.sample ? Math.abs(stdevCloseupX(d.x) - stdevCloseupX($scope.distParameters.stdev)) : 1; }) .attr('height', function (d) { return d.sample ? 10 : 14; }) .attr('class', function (d) { return d.sample ? 'sample layered' : 'theoretical-stdev layered';}); } else { element.find('.left-std-dev').addClass('hidden'); element.find('.right-std-dev').addClass('hidden'); element.find('.mean').addClass('hidden'); } if ($scope.distribution === 'exponential') { element.find('.rate-closeup').removeClass('hidden'); //graphing the range of rates var rateMin = _.min($scope.samples, 'rate').rate; var rateMax = _.max($scope.samples, 'rate').rate; var rateCloseupX = d3.scale.linear() .domain([rateMin - 0.1 * (rateMax - rateMin), rateMax + 0.1 * (rateMax - rateMin)]) .range([0, distributionPropWidth]); var rateAxis = d3.svg.axis().scale(rateCloseupX) .tickValues([rateMin, $scope.distParameters.rate, rateMax]) .outerTickSize(0); $scope.rateCloseup .attr('width', distributionPropWidth) .select('g') .attr('transform', 'translate(' + ($scope.graphWidth * 0.1) + ', 10)') .call(rateAxis); var data = []; for (var i = 0; i < $scope.experimentsNumber; i++) data.push({x: $scope.samples[i].rate, sample: true, id: i}); data.push({x: $scope.distParameters.rate, sample: false, id: -1}); $scope.rateCloseup.select('.samples').selectAll('line').data([]).exit().remove(); var rects = $scope.rateCloseup.select('.samples').selectAll('rect').data(data); rects.exit().remove(); rects.enter().append('rect') .attr('exp-id', function (d, i) { return i; }) .attr('x', function (d) { return Math.min(rateCloseupX($scope.distParameters.rate), rateCloseupX(d.x)); }) .attr('y', function (d) { return d.sample ? -5 : -7; }) .attr('width', function (d) { return d.sample ? Math.abs(rateCloseupX(d.x) - rateCloseupX($scope.distParameters.rate)) : 1; }) .attr('height', function (d) { return d.sample ? 10 : 14; }) .attr('class', function (d) { return d.sample ? 'sample layered' : 'theoretical-rate layered';}); rects.transition() .duration(500) .attr('exp-id', function (d, i) { return i; }) .attr('x', function (d) { return Math.min(rateCloseupX($scope.distParameters.rate), rateCloseupX(d.x)); }) .attr('y', function (d) { return d.sample ? -5 : -7; }) .attr('width', function (d) { return d.sample ? Math.abs(rateCloseupX(d.x) - rateCloseupX($scope.distParameters.rate)) : 1; }) .attr('height', function (d) { return d.sample ? 10 : 14; }) .attr('class', function (d) { return d.sample ? 'sample layered' : 'theoretical-rate layered';}); } if ($scope.distribution === 'gamma') { element.find('.scale-closeup').removeClass('hidden'); element.find('.shape-closeup').removeClass('hidden'); //graphing the range of shape var shapeMin = _.min($scope.samples, 'shape').shape; var shapeMax = _.max($scope.samples, 'shape').shape; var shapeCloseupX = d3.scale.linear() .domain([shapeMin - 0.1 * (shapeMax - shapeMin), shapeMax + 0.1 * (shapeMax - shapeMin)]) .range([0, distributionPropWidth]); var shapeAxis = d3.svg.axis().scale(shapeCloseupX) .tickValues([shapeMin, $scope.distParameters.shape, shapeMax]) .outerTickSize(0); $scope.shapeCloseup .attr('width', distributionPropWidth) .select('g') .attr('transform', 'translate(' + ($scope.graphWidth * 0.1) + ', 10)') .call(shapeAxis); var data = []; for (var i = 0; i < $scope.experimentsNumber; i++) data.push({x: $scope.samples[i].shape, sample: true, id: i}); data.push({x: $scope.distParameters.shape, sample: false, id: -1}); $scope.shapeCloseup.select('.samples').selectAll('line').data([]).exit().remove(); var lines = $scope.shapeCloseup.select('.samples').selectAll('rect').data(data); lines.exit().remove(); lines.enter().append('rect') .attr('exp-id', function (d, i) { return i; }) .attr('x', function (d) { return Math.min(shapeCloseupX($scope.distParameters.shape), shapeCloseupX(d.x)); }) .attr('y', function (d) { return d.sample ? -5 : -7; }) .attr('width', function (d) { return d.sample ? Math.abs(shapeCloseupX(d.x) - shapeCloseupX($scope.distParameters.shape)) : 1; }) .attr('height', function (d) { return d.sample ? 10 : 14; }) .attr('class', function (d) { return d.sample ? 'sample layered' : 'theoretical-shape layered';}); lines.transition() .duration(500) .attr('exp-id', function (d, i) { return i; }) .attr('x', function (d) { return Math.min(shapeCloseupX($scope.distParameters.shape), shapeCloseupX(d.x)); }) .attr('y', function (d) { return d.sample ? -5 : -7; }) .attr('width', function (d) { return d.sample ? Math.abs(shapeCloseupX(d.x) - shapeCloseupX($scope.distParameters.shape)) : 1; }) .attr('height', function (d) { return d.sample ? 10 : 14; }) .attr('class', function (d) { return d.sample ? 'sample layered' : 'theoretical-shape layered';}); // graphing the range of scale var scaleMin = _.min($scope.samples, 'scale').scale; var scaleMax = _.max($scope.samples, 'scale').scale; var scaleCloseupX = d3.scale.linear() .domain([scaleMin - 0.1 * (scaleMax - scaleMin), scaleMax + 0.1 * (scaleMax - scaleMin)]) .range([0, $scope.graphWidth * 0.25]); var stdAxis = d3.svg.axis().scale(scaleCloseupX) .tickValues([scaleMin, $scope.distParameters.scale, scaleMax]) .outerTickSize(0); $scope.scaleCloseup .attr('width', distributionPropWidth) .select('g') .attr('transform', 'translate(0, 10)') .call(stdAxis); var data = []; for (var i = 0; i < $scope.experimentsNumber; i++) data.push({x: $scope.samples[i].scale, sample: true, id: i}); data.push({x: $scope.distParameters.scale, sample: false, id: -1}); $scope.scaleCloseup.select('.samples').selectAll('line').data([]).exit().remove(); var rects = $scope.scaleCloseup.select('.samples').selectAll('rect').data(data); rects.exit().remove(); rects.enter().append('rect') .attr('exp-id', function (d, i) { return i; }) .attr('x', function (d) { return Math.min(scaleCloseupX($scope.distParameters.scale), scaleCloseupX(d.x)); }) .attr('y', function (d) { return d.sample ? -5 : -7; }) .attr('width', function (d) { return d.sample ? Math.abs(scaleCloseupX(d.x) - scaleCloseupX($scope.distParameters.scale)) : 1; }) .attr('height', function (d) { return d.sample ? 10 : 14; }) .attr('class', function (d) { return d.sample ? 'sample layered' : 'theoretical-scale layered';}); rects.transition() .duration(500) .attr('exp-id', function (d, i) { return i; }) .attr('x', function (d) { return Math.min(scaleCloseupX($scope.distParameters.scale), scaleCloseupX(d.x)); }) .attr('y', function (d) { return d.sample ? -5 : -7; }) .attr('width', function (d) { return d.sample ? Math.abs(scaleCloseupX(d.x) - scaleCloseupX($scope.distParameters.scale)) : 1; }) .attr('height', function (d) { return d.sample ? 10 : 14; }) .attr('class', function (d) { return d.sample ? 'sample layered' : 'theoretical-scale layered';}); } if ($scope.distribution === 'uniform') { var minMin = _.min($scope.samples, 'min').min; var minMax = _.max($scope.samples, 'min').min; var minCloseupX = d3.scale.linear() .domain([minMin - 0.1 * (minMax - minMin), minMax + 0.1 * (minMax - minMin)]) .range([0, $scope.graphWidth * 0.25]); var minAxis = d3.svg.axis().scale(minCloseupX) .tickValues([$scope.distParameters.min, minMax]) .outerTickSize(0); $scope.minCloseup .attr('width', $scope.graphWidth * 0.4) .select('g') .attr('transform', 'translate(' + ($scope.graphWidth * 0.05) + ', 10)') .call(minAxis); var data = []; for (var i = 0; i < $scope.experimentsNumber; i++) data.push({x: $scope.samples[i].min, sample: true, id: i}); data.push({x: $scope.distParameters.min, sample: false, id: -1}); $scope.minCloseup.select('.samples').selectAll('line').data([]).exit().remove(); var rects = $scope.minCloseup.select('.samples').selectAll('rect').data(data); rects.exit().remove(); rects.enter().append('rect') .attr('exp-id', function (d, i) { return i; }) .attr('x', function (d) { return Math.min(minCloseupX($scope.distParameters.min), minCloseupX(d.x)); }) .attr('y', function (d) { return d.sample ? -5 : -7; }) .attr('width', function (d) { return d.sample ? Math.abs(minCloseupX(d.x) - minCloseupX($scope.distParameters.min)) : 1; }) .attr('height', function (d) { return d.sample ? 10 : 14; }) .attr('class', function (d) { return d.sample ? 'sample layered' : 'theoretical-min layered';}); rects.transition() .duration(500) .attr('exp-id', function (d, i) { return i; }) .attr('x', function (d) { return Math.min(minCloseupX($scope.distParameters.min), minCloseupX(d.x)); }) .attr('y', function (d) { return d.sample ? -5 : -7; }) .attr('width', function (d) { return d.sample ? Math.abs(minCloseupX(d.x) - minCloseupX($scope.distParameters.min)) : 1; }) .attr('height', function (d) { return d.sample ? 10 : 14; }) .attr('class', function (d) { return d.sample ? 'sample layered' : 'theoretical-min layered';}); var maxMin = _.min($scope.samples, 'max').max; var maxMax = _.max($scope.samples, 'max').max; var maxCloseupX = d3.scale.linear() .domain([maxMin - 0.1 * (maxMax - maxMin), maxMax + 0.1 * (maxMax - maxMin)]) .range([0, $scope.graphWidth * 0.25]); var maxAxis = d3.svg.axis().scale(maxCloseupX) .tickValues([maxMin, $scope.distParameters.max]) .outerTickSize(0); $scope.maxCloseup .attr('width', $scope.graphWidth * 0.4) .select('g') .attr('transform', 'translate(' + ($scope.graphWidth * 0.05) + ', 10)') .call(maxAxis); var data = []; for (var i = 0; i < $scope.experimentsNumber; i++) data.push({x: $scope.samples[i].max, sample: true, id: i}); data.push({x: $scope.distParameters.max, sample: false, id: -1}); $scope.maxCloseup.select('.samples').selectAll('line').data([]).exit().remove(); var rects = $scope.maxCloseup.select('.samples').selectAll('rect').data(data); rects.exit().remove(); rects.enter().append('rect') .attr('exp-id', function (d, i) { return i; }) .attr('x', function (d) { return Math.min(maxCloseupX($scope.distParameters.max), maxCloseupX(d.x)); }) .attr('y', function (d) { return d.sample ? -5 : -7; }) .attr('width', function (d) { return d.sample ? Math.abs(maxCloseupX(d.x) - maxCloseupX($scope.distParameters.max)) : 1; }) .attr('height', function (d) { return d.sample ? 10 : 14; }) .attr('class', function (d) { return d.sample ? 'sample layered' : 'theoretical-max layered';}); rects.transition() .duration(500) .attr('exp-id', function (d, i) { return i; }) .attr('x', function (d) { return Math.min(maxCloseupX($scope.distParameters.max), maxCloseupX(d.x)); }) .attr('y', function (d) { return d.sample ? -5 : -7; }) .attr('width', function (d) { return d.sample ? Math.abs(maxCloseupX(d.x) - maxCloseupX($scope.distParameters.max)) : 1; }) .attr('height', function (d) { return d.sample ? 10 : 14; }) .attr('class', function (d) { return d.sample ? 'sample layered' : 'theoretical-max layered';}); $scope.minLeftCoor = $scope.maxRightCoor = 5; $scope.minBottomCoor = $scope.maxBottomCoor = 3; } } // Generate n samples using the distribution in $scope.distrFunctions function generateSamples(n, sort) { var data = []; for (var i = 0; i < n; i++) data.push($scope.distrFunctions.sample()); if (sort) { data.sort(function (p1, p2) { return p1 < p2 ? -1 : (p1 > p2 ? 1 : 0); }); } return data; } function updateDistrRange(distrFunctions, distParameters, rangeX) { var data, distrRange; if (rangeX) { distrRange = rangeX; } else { switch ($scope.distribution) { case 'gaussian': distrRange = [ distParameters.mean - 3 * distParameters.stdev, distParameters.mean + 3 * distParameters.stdev ]; break; case 'exponential': data = samplePDFValues(distrFunctions); distrRange = [0, _.max(data, 'n').n]; break; case 'gamma': data = samplePDFValues(distrFunctions); distrRange = [_.min(data, 'n').n, _.max(data, 'n').n]; break; case 'uniform': distrRange = [$scope.distParameters.min, $scope.distParameters.max]; } } return { distrRange: distrRange, distrRangeStep: (distrRange[1] - distrRange[0]) / INTERVALS } } // Generating samples this function will return an historgram of the samples function generateSampledDistributionData(i) { var vals = generateSamples($scope.dataVolume, true); var data = []; var samplesMean = jStat.mean(vals); var samplesStdDev = jStat.stdev(vals); var samplesVar = jStat.variance(vals); var samplesMin = jStat.min(vals); var samplesMax = jStat.max(vals); var samplesRate = 1 / samplesMean; var samplesScale = samplesVar / samplesMean; var samplesShape = samplesMean / samplesScale; $scope.samples[i].data = data; $scope.samples[i].rawData = vals; $scope.samples[i].mean = samplesMean; $scope.samples[i].stdev = samplesStdDev; $scope.samples[i].min = samplesMin; $scope.samples[i].max = samplesMax; $scope.samples[i].rate = samplesRate; $scope.samples[i].shape = samplesShape; $scope.samples[i].scale = samplesScale; if ($scope.distribution === 'gaussian') { var experimentHistogram = []; for (var hist_num = 0; hist_num < INTERVALS; hist_num++) { //initialize the actual dataset with a interval elements inside data[hist_num] = { n: $scope.distrRange[0] + $scope.distrRangeStep * (hist_num + 0.5), p: 0, pTheory: $scope.graphData[hist_num].p //$scope.graphData's p which is just the theoretical probability }; //keep count of how many points fall into each of the error bucket (1000 falls into 100) experimentHistogram[hist_num] = 0; } //populate and increase histogram count number for (var i = 0; i < $scope.dataVolume; i++) { var val = vals[i]; if (val < $scope.distrRange[0] || val > $scope.distrRange[1]) continue; var hist_index = Math.floor((val - $scope.distrRange[0]) / (($scope.distrRange[1] - $scope.distrRange[0]) / INTERVALS)); experimentHistogram[hist_index]++; } // calculate the prob of that histogram bar for (hist_num = 0; hist_num < INTERVALS; hist_num++) { data[hist_num].p = experimentHistogram[hist_num]; } } else if ($scope.distribution === 'uniform') { var experimentHistogram = []; for (var hist_num = 0; hist_num < INTERVALS; hist_num++) { //initialize the actual dataset with a interval elements inside data[hist_num] = { n: $scope.distParameters.min + $scope.distrRangeStep * (hist_num + 0.5) - $scope.distrRangeStep / 2, p: 0, pTheory: ($scope.dataVolume / INTERVALS) //$scope.graphData's p which is just the theoretical probability }; //keep count of how many points fall into each of the error bucket (1000 falls into 100) experimentHistogram[hist_num] = 0; } //populate and increase histogram count number for (var i = 0; i < $scope.dataVolume; i++) { var val = vals[i]; var hist_index = Math.floor((val - $scope.distParameters.min) / (($scope.distParameters.max - $scope.distParameters.min) / INTERVALS)); experimentHistogram[hist_index]++; } // calculate the prob of that histogram bar for (hist_num = 0; hist_num < INTERVALS; hist_num++) { data[hist_num].p = experimentHistogram[hist_num]; } } else if ($scope.distribution === 'exponential') { var experimentHistogram = []; for (var hist_num = 0; hist_num < INTERVALS; hist_num++) { //initialize the actual dataset with a interval elements inside data[hist_num] = { n: $scope.distrRange[0] + $scope.distrRangeStep * (hist_num + 0.5), p: 0, pTheory: $scope.graphData[hist_num].p //$scope.graphData's p which is just the theoretical probability }; //keep count of how many points fall into each of the error bucket (1000 falls into 100) experimentHistogram[hist_num] = 0; } //populate and increase histogram count number for (var i = 0; i < $scope.dataVolume; i++) { var val = vals[i]; if (val < $scope.distrRange[0] || val > $scope.distrRange[1]) continue; var hist_index = Math.floor((val - $scope.distrRange[0]) / (($scope.distrRange[1] - $scope.distrRange[0]) / INTERVALS)); experimentHistogram[hist_index]++; } // calculate the prob of that histogram bar for (hist_num = 0; hist_num < INTERVALS; hist_num++) { data[hist_num].p = experimentHistogram[hist_num]; } } else if ($scope.distribution === 'gamma') { var experimentHistogram = []; for (var hist_num = 0; hist_num < INTERVALS; hist_num++) { //initialize the actual dataset with a interval elements inside data[hist_num] = { n: $scope.distrRange[0] + $scope.distrRangeStep * (hist_num + 0.5), p: 0, pTheory: $scope.graphData[hist_num].p //$scope.graphData's p which is just the theoretical probability }; //keep count of how many points fall into each of the error bucket (1000 falls into 100) experimentHistogram[hist_num] = 0; } //populate and increase histogram count number for (var i = 0; i < $scope.dataVolume; i++) { var val = vals[i]; if (val < $scope.distrRange[0] || val > $scope.distrRange[1]) continue; var hist_index = Math.floor((val - $scope.distrRange[0]) / (($scope.distrRange[1] - $scope.distrRange[0]) / INTERVALS)); experimentHistogram[hist_index]++; } // calculate the prob of that histogram bar for (hist_num = 0; hist_num < INTERVALS; hist_num++) { experimentHistogram[hist_num] /= vals.length; data[hist_num].p = experimentHistogram[hist_num]; } } return data; } // Generate theoretical pdf values function samplePDFValues(distrFunctions) { var n, p, data = []; for (var i = 0; i < $scope.dataVolume; i++) { n = distrFunctions.sample(); p = distrFunctions.pdf(n); data.push({n: n, p: p}) } data.sort(function (p1, p2) { return p1.n < p2.n ? -1 : (p1.n > p2.n ? 1 : 0); }); return data; } function buildDistrFunctions(distribution, distParameters) { switch (distribution) { case 'gaussian': return { distribution: jStat.normal, sample: function () { return jStat.normal.sample(distParameters.mean, distParameters.stdev); }, pdf: function (n) { return jStat.normal.pdf(n, distParameters.mean, distParameters.stdev); }, cdf: function (n) { return jStat.normal.cdf(n, distParameters.mean, distParameters.stdev); } }; case 'exponential': return { distribution: jStat.exponential, sample: function () { return jStat.exponential.sample(distParameters.rate); }, pdf: function (n) { return jStat.exponential.pdf(n, distParameters.rate); }, cdf: function (n) { return jStat.exponential.cdf(n, distParameters.rate); } }; case 'gamma': return { distribution: jStat.gamma, sample: function () { return jStat.gamma.sample(distParameters.shape, distParameters.scale); }, pdf: function (n) { return jStat.gamma.pdf(n, distParameters.shape, distParameters.scale); }, cdf: function (n) { return jStat.gamma.cdf(n, distParameters.shape, distParameters.scale); } }; case 'uniform': return { distribution: jStat.uniform, sample: function () { return jStat.uniform.sample(distParameters.min, distParameters.max); }, pdf: function (n) { return jStat.uniform.pdf(n, distParameters.min, distParameters.max); }, cdf: function (n) { return jStat.uniform.cdf(n, distParameters.min, distParameters.max); } }; } } function generateTheoreticalDistributionData(distribution, distrFunctions, distrRange, distrRangeStep, distParameters) { var data = [], parametersProbs = {}; switch (distribution) { case 'gaussian': for (var i = 0; i < INTERVALS; i++) { var distrVal = distrFunctions.cdf(distrRange[0] + distrRangeStep * (i + 1)) - distrFunctions.cdf(distrRange[0] + distrRangeStep * i); distrVal *= $scope.dataVolume; // to frequencies instead of probability if (((distrRange[0] + distrRangeStep * INTERVALS / 2 - distParameters.stdev) > (distrRange[0] + distrRangeStep * i)) && ((distrRange[0] + distrRangeStep * INTERVALS / 2 - distParameters.stdev) < (distrRange[0] + distrRangeStep * (i + 1)))) { parametersProbs.stdProb = distrVal; } data.push({n: distrRange[0] + distrRangeStep * (i + 0.5), p: distrVal}); } parametersProbs.meanProb = data[INTERVALS / 2].p; break; case 'exponential': for (var i = 0; i < INTERVALS; i++) { var distrVal = distrFunctions.cdf(distrRange[0] + distrRangeStep * (i + 1)) - distrFunctions.cdf(distrRange[0] + distrRangeStep * i); distrVal *= $scope.dataVolume; // to frequencies instead of probability data.push({n: distrRange[0] + distrRangeStep * (i + 0.5), p: distrVal}); } break; case 'gamma': for (var i = 0; i < INTERVALS; i++) { var distrVal = distrFunctions.cdf(distrRange[0] + distrRangeStep * (i + 1)) - distrFunctions.cdf(distrRange[0] + distrRangeStep * i); distrVal *= $scope.dataVolume; // to frequencies instead of probability data.push({n: distrRange[0] + distrRangeStep * (i + 0.5), p: distrVal}); } break; case 'uniform': for (var i = -2; i < INTERVALS + 3; i++) { data.push({ n: distParameters.min + distrRangeStep * i, p: (i >= 0 && i < INTERVALS) ? ($scope.dataVolume / INTERVALS) : 0 }); } } return { data: data, parametersProbs: parametersProbs }; } function updateParametersProbs(distribution, parametersProbs) { switch (distribution) { case 'gaussian': $scope.stdProb = parametersProbs.stdProb; $scope.meanProb = parametersProbs.meanProb; break; } } $scope.$watch(function () { return [$scope.distribution, $scope.distParameters, $scope.enabled, Model.dataVolume, Model.experimentsNumber]; }, function () { if ($scope.enabled === false) return; if (!$scope.graphData) { updateResult(); return; } if ($scope.dataGenerationReqTimeout !== null) { $timeout.cancel($scope.dataGenerationReqTimeout); } $scope.dataGenerationReqTimeout = $timeout(function () { updateResult(); $scope.dataGenerationReqTimeout = null; }, 700); }, true); $scope.$watch('compactView', function () { $timeout(render); }); $scope.$watch('_result', function () { $scope.inputRead = false; readResult(); }, true); $rootScope.$on('windowResize', function () { $timeout(render); }); } }; }]); <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/generators/CasesGen.java<|end_filename|> package edu.nyu.dtl.synner.core.generators; import com.fasterxml.jackson.annotation.JsonProperty; public class CasesGen<T extends Comparable> implements Generator<T> { @JsonProperty Generator<T>[] generators; public CasesGen(Generator<T>... generators) { this.generators = generators; } @Override public T generate(boolean errorMode, boolean previewMode) throws Exception { return generators[rnd.nextInt(generators.length)].generate(errorMode, previewMode); } @Override public T generate(Comparable[] inputs, boolean errorMode, boolean previewMode) throws Exception { return generate(inputs, errorMode, previewMode); } } <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/generators/StringGen.java<|end_filename|> package edu.nyu.dtl.synner.core.generators; import com.fasterxml.jackson.annotation.JsonProperty; import com.mifmif.common.regex.Generex; public class StringGen implements Generator<String> { private final Generex generex; @JsonProperty private final String regexp; public StringGen(String regexp) { this.regexp = regexp; generex = new Generex(regexp); } @Override public String generate(boolean errorMode, boolean previewMode) { if (errorMode) { char[] str = new char[rnd.nextInt(10) + 4]; for (int i = 0; i < str.length; i++) str[i] = (char)(rnd.nextInt('z' - '0') + '0'); return new String(str); } return generex.random(); } } <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/datamodel/GeneratedDataset.java<|end_filename|> package edu.nyu.dtl.synner.core.datamodel; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; public class GeneratedDataset { private final Table table; private final Comparable[][] prefillData; private final int toAdd; private DataField[][] data; public GeneratedDataset(Table table, Comparable[][] prefillData, int toAdd) { if (toAdd < 0) throw new IllegalArgumentException("the number of tuples to add must be a positive number"); this.table = table; this.prefillData = prefillData; this.toAdd = toAdd; } public void generate(boolean previewMode) throws Exception { int colNum = table.getColumnsNumber(); data = new DataField[prefillData.length + toAdd][]; for (int rowIdx = 0; rowIdx < data.length; rowIdx++) { Comparable[] tuple = new Comparable[colNum]; if (rowIdx < prefillData.length) { for (int j = 0; j < prefillData[rowIdx].length; j++) tuple[j] = prefillData[rowIdx][j]; } table.generateTuple(tuple, previewMode); data[rowIdx] = new DataField[colNum]; for (int j = 0; j < colNum; j++) { boolean generated = rowIdx >= prefillData.length || prefillData[rowIdx][j] == null; if (tuple[j] instanceof StatusValue) { StatusValue sv = (StatusValue) tuple[j]; data[rowIdx][j] = new DataField(sv.getValue(), generated, sv.getStatus()); } else { data[rowIdx][j] = new DataField(tuple[j], generated); } } } } @JsonProperty public DataField[][] getData() { return data; } /** * Store a value, which can be generated or given as input. * It could also store other information in the future, such as path used to generate data, or errors notifications. */ public static class DataField { @JsonProperty("v") public final Comparable data; @JsonProperty("g") public final boolean generated; @JsonProperty("s") @JsonInclude(JsonInclude.Include.NON_NULL) public final String status; public DataField(Comparable data, boolean generated, String status) { this.data = data; this.generated = generated; this.status = status; } public DataField(Comparable data, boolean generated) { this(data, generated, null); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{v:"); sb.append(",g:"); sb.append(generated); if (this.status != null) { sb.append(",s:"); sb.append(this.status); } sb.append("}"); return sb.toString(); } } } <|start_filename|>synner-server/src/main/resources/static/css/main.css<|end_filename|> body, html { margin: 0; height: 100%; } body { overflow: hidden; } html ::-webkit-scrollbar { width: 5.2px; height: 5px; } html ::-webkit-scrollbar-button { display: none; } html ::-webkit-scrollbar-track-piece { background: #dadada; } html ::-webkit-scrollbar-thumb { background: #aaa; } select.form-control { height: initial; } input::-webkit-outer-spin-button, input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } .value-decoration { color: #999; } .properties-panel { max-height: 100%; margin: 0; overflow-y: scroll; border: none; border-left: 1px solid #cacaca; } .properties-panel .form-group { margin-bottom: 0; } .properties-panel .radio, .properties-panel .checkbox { margin-bottom: 0; } .error-message { padding: 5px; position: fixed; bottom: 0; background: #f34f4f73; width: 100%; border-top: black 1px solid; color: black; } .error-message .error-message-label { font-weight: bold; color: #333333; } .panel-title { width: 100%; margin: 0; padding: .3em .5em; background-color: #e7e7e7; } .panel-inline { display: inline-block; } .row-eq-height { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; } .list-group-item-action { cursor: pointer; } .input-group { display: inline-table; vertical-align: middle; } .input-group .input-group-addon, .input-group .input-group-btn, .input-group .form-control { width: auto !important; } .input-group .input-group-addon-blank { background: transparent; } .dropdown-menu { max-height: 200px; overflow-y: auto; } .dropdown-menu > li { padding: 0; } .dropdown-menu > li > a { padding: 8px 10px; } .dropdown-menu > li > a small { float: right; color: #999; } .dropdown-left-manual { right: 0; left: auto; padding-left: 1px; padding-right: 1px; } .form-control.form-control-inline { display: inline-block; } .btn-xxs, .btn-group-xxs > .btn { padding: 1px 6px; } .btn-xs, .btn-group-xs > .btn { padding: 4px 6px 5px 6px; } .btn-default-deselected, .btn-default-deselected:hover { background-color: #ffffff; } .ghost-editable, #main-properties-panel .main-panel-title > input, #main-properties-panel .main-panel-title > div, #synner-data-table .table tr th .field-properties-and-actions select.type-select, #synner-data-table input[type=text], #synner-data-table input[type=number], #synner-data-table input[type=time], #synner-data-table input[type=date] { border: none; display: inline; transition: width 0.3s; } .ghost-editable:focus, #main-properties-panel .main-panel-title > input:focus, #main-properties-panel .main-panel-title > div:focus, #synner-data-table .table tr th .field-properties-and-actions select.type-select:focus, #synner-data-table input[type=text]:focus, #synner-data-table input[type=number]:focus, #synner-data-table input[type=time]:focus, #synner-data-table input[type=date]:focus { outline: none; } .rzslider * { outline: none !important; } .rzslider .rz-pointer { top: -7px; z-index: 3; width: 16px; height: 16px; } .rzslider .rz-pointer:after { content: none; } .label { white-space: nowrap; } .select-container { border: 1px solid #ccc; background: #ddd; display: inline-block; } .select-container select { border: none; background: transparent; min-width: 80px; } .select-container select:focus { outline: none; } .modal { z-index: 1040 !important; } .modal-backdrop { z-index: 1035 !important; } #main-properties-panel { min-height: 300px; } #main-properties-panel .main-panel-title { display: inline-block; writing-mode: tb-rl; transform: rotate(-180deg); float: left; margin: 0.5em 0.3em 0.5em 0.3em; } #main-properties-panel .main-panel-title > input, #main-properties-panel .main-panel-title > div { line-height: 0.1rem; } .generator { position: relative; } .generator .generator-layout-table { height: 100%; } .generator .generator-layout-table .generator-content-td { width: 100%; border-left: 1px solid #ddd; } .generator .generator-layout-table > tbody > tr > td { vertical-align: top; } .generator > .panel { padding: 10px; height: 100%; } .generator > .panel .panel-body { padding: 0; } .generator .form-group { margin-bottom: 0; } .generator .form-group .list-group { max-height: 188px; overflow-y: auto; margin-bottom: 0; } .generator .generator-modalities { padding-right: 10px; float: left; } .generator .generator-modalities .list-group-item { white-space: nowrap; } .generator .generator-content { padding-left: 10px; } .generator.generator-compact-view .generator-modalities .form-group { margin-bottom: 0; } #synner-data-table { position: relative; margin-bottom: 0; border-bottom: 1px solid #333333; overflow-x: auto; } #synner-data-table ::-webkit-scrollbar { width: 4px; height: 5px; } #synner-data-table ::-webkit-scrollbar-button { display: none; } #synner-data-table ::-webkit-scrollbar-track-piece { background: #dadada; } #synner-data-table ::-webkit-scrollbar-thumb { background: #aaa; } #synner-data-table .table { width: auto; margin-bottom: 0; } #synner-data-table .table tbody { display: block; height: 200px; overflow-y: auto; } #synner-data-table .table thead, #synner-data-table .table tbody tr { display: table; table-layout: fixed; } #synner-data-table .table tr td { background-color: transparent; transition: all 0.5s ease; } #synner-data-table .table tr.highlighted td, #synner-data-table .table tr.highlighted:hover td { background-color: #fffdd4 !important; transition: all 0.5s ease; } #synner-data-table .table tr .selected { background-color: rgba(245, 245, 245, 0.8); } #synner-data-table .table tr .numerical-row { text-align: right; } #synner-data-table .table tr th { white-space: nowrap; border-right: 1px solid #ddd; padding-bottom: .45em; } #synner-data-table .table tr th .field-name { width: 129px; } #synner-data-table .table tr th .field-name.field-name-error { color: red; } #synner-data-table .table tr th .field-properties-and-actions { float: right; } #synner-data-table .table tr th .field-properties-and-actions select.type-select { margin-left: 5px; -webkit-appearance: none; text-overflow: ''; } #synner-data-table .table tr th .field-properties-and-actions .field-hide { margin-left: 5px; color: gray; } #synner-data-table .table tr th .field-properties-and-actions .field-remove { margin-left: 5px; color: gray; } #synner-data-table .table tr th .field-properties-and-actions .fa-exclamation-triangle { margin-left: 5px; color: gray; } #synner-data-table .table tr th .field-properties-and-actions .fa-filter { margin-left: 5px; color: gray; } #synner-data-table .table tr th.field-header { position: relative; } #synner-data-table .table tr th.field-header-dependencies { vertical-align: middle; } #synner-data-table .table tr th.field-header-dependencies ::-webkit-scrollbar { width: 4px; } #synner-data-table .table tr th.field-header-dependencies ::-webkit-scrollbar-button { display: none; } #synner-data-table .table tr th.field-header-dependencies ::-webkit-scrollbar-track-piece { background: #dadada; } #synner-data-table .table tr th.field-header-dependencies ::-webkit-scrollbar-thumb { background: #aaa; } #synner-data-table .table tr td, #synner-data-table .table tr th { width: 270px; min-width: 270px; } #synner-data-table .table .field-data { border-right: 1px solid #ddd; white-space: nowrap; } #synner-data-table .table .field-data .fa-lock { color: rgba(128, 128, 128, 0.35); } #synner-data-table .table .field-data .special-value { color: #ff5b5b; } #synner-data-table .table .field-data input[type=text], #synner-data-table .table .field-data input[type=number], #synner-data-table .table .field-data input[type=time], #synner-data-table .table .field-data input[type=date] { width: 90%; } #synner-data-table .table th.field-data-last-col, #synner-data-table .table td.field-data-last-col { width: 0px; min-width: 0px; max-width: 0px; padding: 0; border: none; } #synner-data-table .table .add-column-button { position: absolute; } #synner-data-table .table th.field-data-add-column, #synner-data-table .table td.field-data-add-column { width: 100%; border-right: none; padding: 0; vertical-align: middle; border-bottom: none; border-top: none; } #synner-data-table .table th.field-data-add-column .dropdown > button, #synner-data-table .table td.field-data-add-column .dropdown > button { border-left: none; font-weight: bold; background: transparent; } #synner-data-table .add-column-column { vertical-align: top; padding: 0; margin: 0; } #synner-data-table .add-column-column .add-column-button { margin-left: 0; margin-right: 0; margin-left: -5px; margin-top: 5px; } #synner-data-table input[type=text], #synner-data-table input[type=number], #synner-data-table input[type=time], #synner-data-table input[type=date] { background: transparent !important; } .generator-distribution-main .generator-distribution-main-layout-table { width: 100%; } .generator-distribution-main .generator-distribution-main-layout-table .distribution-container-td { width: 100%; } .generator-distribution-main .generator-distribution-main-layout-table > tbody > tr > td { vertical-align: top; } .generator-distribution-main .distribution-chooser { float: left; clear: left; margin-right: 10px; } .generator-distribution-main .distribution-chooser:focus { outline: -webkit-focus-ring-color auto 0; } .generator-distribution-main .generator-distribution { font-family: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif; width: 100%; table-layout: fixed; margin: auto; font-size: 12px; } .generator-distribution-main .generator-distribution .theoretical-line { stroke: #0085ff; } .generator-distribution-main .generator-distribution .theoretical-area { fill: #0085ff; fill-opacity: 0.1; } .generator-distribution-main .generator-distribution .highlighted-histogram { fill: #ffa24d; fill-opacity: 0.7; } .generator-distribution-main .generator-distribution .min-max-area { fill: #0085ff; fill-opacity: 0.4; } .generator-distribution-main .generator-distribution .theoretical-stdev { stroke-linecap: round; stroke-width: 3px; fill: #b7b7b7; stroke: #b7b7b7; } .generator-distribution-main .generator-distribution .theoretical-mean { stroke-width: 3px; fill: #ff7c7e; stroke: #ff7c7e; stroke-linecap: round; } .generator-distribution-main .generator-distribution .theoretical-rate { stroke-width: 3px; fill: #b7b7b7; stroke: #b7b7b7; stroke-linecap: round; } .generator-distribution-main .generator-distribution .theoretical-min { stroke-width: 3px; fill: #b7b7b7; stroke: #b7b7b7; stroke-linecap: round; } .generator-distribution-main .generator-distribution .theoretical-max { stroke-width: 3px; fill: #b7b7b7; stroke: #b7b7b7; stroke-linecap: round; } .generator-distribution-main .generator-distribution .theoretical-shape { stroke-width: 3px; fill: #b7b7b7; stroke: #b7b7b7; stroke-linecap: round; } .generator-distribution-main .generator-distribution .theoretical-scale { stroke-width: 3px; fill: #ff7c7e; stroke: #ff7c7e; stroke-linecap: round; } .generator-distribution-main .generator-distribution .distribution-bin { fill: rgba(173, 216, 230, 0.51); stroke: none; } .generator-distribution-main .generator-distribution .sample { stroke: #0085ff; stroke-opacity: 0.2; stroke-width: 1.5px; fill: none; } .generator-distribution-main .generator-distribution .sample.hidden-sample { stroke-opacity: 0; stroke-width: 3px; } .generator-distribution-main .generator-distribution .sample.highlighted { stroke-width: 1.5px; stroke: #0085ff; stroke-dasharray: 2; stroke-opacity: 0.7; } .generator-distribution-main .generator-distribution .specs { font-size: 12px; background: #ddd; padding: 4px; border-radius: 4px; display: none; } .generator-distribution-main .generator-distribution .distribution-property { padding: 10px 0 10px 0; max-width: 375px; text-align: center; } .generator-distribution-main .generator-distribution .distribution-property .control-label { font-size: 17px; margin-bottom: 10px; } .generator-distribution-main .generator-distribution .distribution-property .mean-closeup .ticks line, .generator-distribution-main .generator-distribution .distribution-property .stdev-closeup .ticks line, .generator-distribution-main .generator-distribution .distribution-property .rate-closeup .ticks line, .generator-distribution-main .generator-distribution .distribution-property .shape-closeup .ticks line, .generator-distribution-main .generator-distribution .distribution-property .scale-closeup .ticks line, .generator-distribution-main .generator-distribution .distribution-property .min-closeup .ticks line, .generator-distribution-main .generator-distribution .distribution-property .max-closeup .ticks line { fill: none; stroke: black; } .generator-distribution-main .generator-distribution .distribution-property .mean-closeup .domain, .generator-distribution-main .generator-distribution .distribution-property .stdev-closeup .domain, .generator-distribution-main .generator-distribution .distribution-property .rate-closeup .domain, .generator-distribution-main .generator-distribution .distribution-property .shape-closeup .domain, .generator-distribution-main .generator-distribution .distribution-property .scale-closeup .domain, .generator-distribution-main .generator-distribution .distribution-property .min-closeup .domain, .generator-distribution-main .generator-distribution .distribution-property .max-closeup .domain { fill: none; stroke: black; } .generator-distribution-main .generator-distribution .distribution-property .mean-closeup line.sample, .generator-distribution-main .generator-distribution .distribution-property .stdev-closeup line.sample, .generator-distribution-main .generator-distribution .distribution-property .rate-closeup line.sample, .generator-distribution-main .generator-distribution .distribution-property .shape-closeup line.sample, .generator-distribution-main .generator-distribution .distribution-property .scale-closeup line.sample, .generator-distribution-main .generator-distribution .distribution-property .min-closeup line.sample, .generator-distribution-main .generator-distribution .distribution-property .max-closeup line.sample { fill: none; stroke-opacity: 1; } .generator-distribution-main .generator-distribution .distribution-property .mean-closeup line.sample.highlighted, .generator-distribution-main .generator-distribution .distribution-property .stdev-closeup line.sample.highlighted, .generator-distribution-main .generator-distribution .distribution-property .rate-closeup line.sample.highlighted, .generator-distribution-main .generator-distribution .distribution-property .shape-closeup line.sample.highlighted, .generator-distribution-main .generator-distribution .distribution-property .scale-closeup line.sample.highlighted, .generator-distribution-main .generator-distribution .distribution-property .min-closeup line.sample.highlighted, .generator-distribution-main .generator-distribution .distribution-property .max-closeup line.sample.highlighted { stroke-width: 3px; stroke: #0085ff; } .generator-distribution-main .generator-distribution .distribution-property .mean-closeup rect.sample, .generator-distribution-main .generator-distribution .distribution-property .stdev-closeup rect.sample, .generator-distribution-main .generator-distribution .distribution-property .rate-closeup rect.sample, .generator-distribution-main .generator-distribution .distribution-property .shape-closeup rect.sample, .generator-distribution-main .generator-distribution .distribution-property .scale-closeup rect.sample, .generator-distribution-main .generator-distribution .distribution-property .min-closeup rect.sample, .generator-distribution-main .generator-distribution .distribution-property .max-closeup rect.sample { stroke: none; } .generator-distribution-main .generator-distribution .distribution-property .stdev-closeup line.sample { stroke: #b7b7b7; } .generator-distribution-main .generator-distribution .distribution-property .stdev-closeup rect.sample { fill: #b7b7b7; } .generator-distribution-main .generator-distribution .distribution-property .stdev-closeup rect.sample.layered { fill-opacity: 0.15; } .generator-distribution-main .generator-distribution .distribution-property .mean-closeup line.sample { stroke: #ff7c7e; } .generator-distribution-main .generator-distribution .distribution-property .mean-closeup rect.sample { fill: #ff7c7e; } .generator-distribution-main .generator-distribution .distribution-property .mean-closeup rect.sample.layered { fill-opacity: 0.15; } .generator-distribution-main .generator-distribution .distribution-property .rate-closeup line.sample { stroke: #b7b7b7; } .generator-distribution-main .generator-distribution .distribution-property .rate-closeup rect.sample { fill: #b7b7b7; } .generator-distribution-main .generator-distribution .distribution-property .rate-closeup rect.sample.layered { fill-opacity: 0.15; } .generator-distribution-main .generator-distribution .distribution-property .shape-closeup line.sample { stroke: #b7b7b7; } .generator-distribution-main .generator-distribution .distribution-property .shape-closeup rect.sample { fill: #b7b7b7; } .generator-distribution-main .generator-distribution .distribution-property .shape-closeup rect.sample.layered { fill-opacity: 0.15; } .generator-distribution-main .generator-distribution .distribution-property .scale-closeup line.sample { stroke: #ff7c7e; } .generator-distribution-main .generator-distribution .distribution-property .scale-closeup rect.sample { fill: #ff7c7e; } .generator-distribution-main .generator-distribution .distribution-property .scale-closeup rect.sample.layered { fill-opacity: 0.15; } .generator-distribution-main .generator-distribution .distribution-property .min-closeup line.sample, .generator-distribution-main .generator-distribution .distribution-property .max-closeup line.sample { stroke: #b7b7b7; } .generator-distribution-main .generator-distribution .distribution-property .min-closeup rect.sample, .generator-distribution-main .generator-distribution .distribution-property .max-closeup rect.sample { fill: #b7b7b7; } .generator-distribution-main .generator-distribution .distribution-property .min-closeup rect.sample.layered, .generator-distribution-main .generator-distribution .distribution-property .max-closeup rect.sample.layered { fill-opacity: 0.15; } .generator-distribution-main .generator-distribution .distribution-property input { width: 50px; padding: 2px; text-align: center; margin: auto; } .generator-distribution-main .generator-distribution .distribution-property input:focus { outline: none; } .generator-distribution-main .generator-distribution .distribution-property input::-webkit-outer-spin-button, .generator-distribution-main .generator-distribution .distribution-property input::-webkit-inner-spin-button { /* display: none; <- Crashes Chrome on hover */ -webkit-appearance: none; margin: 0; /* <-- Apparently some margin are still there even though it's hidden */ } .generator-distribution-main .generator-distribution .distribution-plot-container { vertical-align: top; text-align: center; width: 760px; } .generator-distribution-main .generator-distribution .distribution-plot-container svg { height: 250px; width: 750px; } .generator-distribution-main .generator-distribution .distribution-plot-container svg .axis path, .generator-distribution-main .generator-distribution .distribution-plot-container svg .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .generator-distribution-main .generator-distribution .distribution-plot-container svg .line { fill: none; stroke-width: 1px; } .generator-distribution-main .generator-distribution-custom { margin-left: 30px; } .generator-distribution-main .generator-distribution-custom table { max-width: 750px; } .generator-distribution-main .generator-distribution-custom table td { position: relative; } .generator-distribution-main .generator-distribution-custom table .td-canvas { padding: 11px 11px 0 4px; } .generator-distribution-main .generator-distribution-custom canvas { height: 220px; width: 750px; } .generator-distribution-main .generator-distribution-custom .control-buttons { vertical-align: bottom; padding: 20px; } .generator-distribution-main .generator-distribution-custom .clean-btn { position: absolute; top: 10px; right: 10px; padding: 4px 6px; } .generator-distribution-main .generator-distribution-custom .axish { text-align: center; margin-left: 10px 10px; margin-right: 10px; height: 20px; } .generator-distribution-main .generator-distribution-custom .axish .min-value { position: absolute; top: 0; width: 60px; left: -19px; text-align: center; } .generator-distribution-main .generator-distribution-custom .axish .max-value { position: absolute; top: 0; width: 60px; right: -13px; text-align: center; } .generator-distribution-main .generator-distribution-custom .axish-compact { float: left; text-align: center; margin-left: 10px 10px; margin-right: 10px; height: 20px; } .generator-distribution-main .generator-distribution-custom .axish-compact .min-value { display: inline-block; top: 0; width: 30px; left: -4px; text-align: center; } .generator-distribution-main .generator-distribution-custom .axish-compact .max-value { display: inline-block; top: 0; width: 60px; right: -13px; text-align: center; } .generator-distribution-main .generator-distribution-custom .axisv { margin-top: 10px; margin-bottom: 10px; width: 20px; } .generator-distribution-main .generator-distribution-custom .axisv .min-value { position: absolute; bottom: 10px; right: 0; } .generator-distribution-main .generator-distribution-custom .axisv .max-value { position: absolute; top: 10px; right: 0; } .generator-compact-view .generator-distribution-main .distribution-container .distribution-property { display: inline-block; position: initial; margin: 0; padding: 20px 0 0 0; } .generator-compact-view .generator-distribution-main .distribution-container .distribution-property .control-label { margin-bottom: 0; } .generator-compact-view .generator-distribution-main .distribution-container .distribution-property input { display: inline-block; width: 50px; border-color: transparent; } .generator-string-enum, .generator-number-enum { padding: 1px; } .generator-string-enum > table, .generator-number-enum > table { width: 100%; } .generator-string-enum > table th, .generator-number-enum > table th { padding-bottom: 5px; } .generator-string-enum > table th.cases-header-ratio, .generator-number-enum > table th.cases-header-ratio { text-align: center; } .generator-string-enum > table th.cases-header-freqpb, .generator-number-enum > table th.cases-header-freqpb { text-align: left; } .generator-string-enum > table tr.case-row, .generator-number-enum > table tr.case-row { height: 35px; } .generator-string-enum > table tr.case-row .case-value .input-group, .generator-number-enum > table tr.case-row .case-value .input-group { width: 100%; } .generator-string-enum > table tr.case-row .case-value .form-control, .generator-number-enum > table tr.case-row .case-value .form-control { height: 29px; width: 100% !important; } .generator-string-enum > table tr.case-row .case-value .void-input, .generator-number-enum > table tr.case-row .case-value .void-input { border: none; box-shadow: none; } .generator-string-enum > table tr.case-row .case-value .void-input:focus, .generator-number-enum > table tr.case-row .case-value .void-input:focus { outline: none; } .generator-string-enum > table tr.case-row .case-value .input-group-btn, .generator-number-enum > table tr.case-row .case-value .input-group-btn { width: 1% !important; } .generator-string-enum > table tr.case-row .case-hist-filler, .generator-number-enum > table tr.case-row .case-hist-filler { padding: 0; margin: 0; border-top: 1px solid #cccccc; height: 1px; } .generator-string-enum > table tr.case-row .case-freq-value, .generator-number-enum > table tr.case-row .case-freq-value { width: 18px; white-space: nowrap; } .generator-string-enum > table tr.case-row .case-freq-value .freq-value, .generator-number-enum > table tr.case-row .case-freq-value .freq-value { text-align: center; width: 18px; } .generator-string-enum > table tr.case-row .case-ratio, .generator-number-enum > table tr.case-row .case-ratio { width: 50px; vertical-align: middle; display: inline-block; text-align: center; } .generator-string-enum > table tr.case-row .case-ratio input, .generator-number-enum > table tr.case-row .case-ratio input { width: 4rem; text-align: center; border: 1px solid #ddd; } .generator-string-enum > table tr.case-row .case-freqpb, .generator-number-enum > table tr.case-row .case-freqpb { text-align: left; } .generator-string-enum > table tr.case-row .case-freqpb .progress, .generator-number-enum > table tr.case-row .case-freqpb .progress { border: none; display: inline-block; width: 150px; height: 34px; margin: 0 50px 0 0; padding: 0; overflow: visible; vertical-align: middle; position: relative; background: inherit; } .generator-string-enum > table tr.case-row .case-freqpb .progress .progress-bar, .generator-number-enum > table tr.case-row .case-freqpb .progress .progress-bar { background-color: #0053ba2e; box-shadow: none; border-right: 1px solid #002d88; transition: none; } .generator-string-enum > table tr.case-row .case-freqpb .progress.pg-hover .ratio-value, .generator-number-enum > table tr.case-row .case-freqpb .progress.pg-hover .ratio-value { display: none; } .generator-string-enum > table tr.case-row .case-freqpb .progress.pg-hover .freq-btn-decrease, .generator-string-enum > table tr.case-row .case-freqpb .progress.pg-hover .freq-btn-increase, .generator-number-enum > table tr.case-row .case-freqpb .progress.pg-hover .freq-btn-decrease, .generator-number-enum > table tr.case-row .case-freqpb .progress.pg-hover .freq-btn-increase { display: block; } .generator-string-enum > table tr.case-row .case-freqpb .progress .ratio-value, .generator-number-enum > table tr.case-row .case-freqpb .progress .ratio-value { display: block; position: absolute; top: 9px; width: 50px; text-align: left; padding: 2px; } .generator-string-enum > table tr.case-row .case-freqpb .progress .freq-btn-decrease, .generator-string-enum > table tr.case-row .case-freqpb .progress .freq-btn-increase, .generator-number-enum > table tr.case-row .case-freqpb .progress .freq-btn-decrease, .generator-number-enum > table tr.case-row .case-freqpb .progress .freq-btn-increase { display: none; position: absolute; top: 0; width: 20px; height: 34px; padding: 10px 0 0 0; width: 20px; text-align: center; padding: 10px 0 0 0; } .generator-string-enum > table tr.case-row .case-freqpb .progress .freq-btn-decrease:hover, .generator-string-enum > table tr.case-row .case-freqpb .progress .freq-btn-increase:hover, .generator-number-enum > table tr.case-row .case-freqpb .progress .freq-btn-decrease:hover, .generator-number-enum > table tr.case-row .case-freqpb .progress .freq-btn-increase:hover { background-color: #EBEBEB; cursor: pointer; } .generator-string-enum > table tr.case-row .case-freqpb .progress .freq-btn-decrease, .generator-number-enum > table tr.case-row .case-freqpb .progress .freq-btn-decrease { margin-left: -20px; } .generator-string-enum > table tr.case-row .case-freqpb .progress .simexperiments-container, .generator-number-enum > table tr.case-row .case-freqpb .progress .simexperiments-container { position: absolute; height: 29px; width: 100%; } .generator-string-enum > table tr.case-row .case-freqpb .progress .simexperiments-container .simres, .generator-number-enum > table tr.case-row .case-freqpb .progress .simexperiments-container .simres { position: absolute; opacity: 0.3; width: 10px; height: 34px; background-color: rgba(70, 130, 180, 0.5); } .visual-summary .textual-summary { font-weight: 400; font-size: 11px; height: 15px; } .visual-summary .chart { width: 100%; height: 40px; } .visual-summary .chart .odd { fill: #6D7993; } .visual-summary .chart .even { fill: steelblue; } .visual-summary .chart rect { fill: steelblue; } .visual-summary .chart rect.missing { fill: #b9b9b9; } .visual-summary .chart rect.error { fill: #d05b5b; } .visual-summary .chart text { fill: white; font: 10px sans-serif; text-anchor: end; } #synner-data-table .field-filter { position: absolute; top: 0; left: 0; width: 100%; background: white; border: 1px solid #ddd; border-right: none; border-left: none; } #synner-data-table .field-filter input[type=text].field-filter-text { display: block; margin: 5px; font-weight: normal; font-family: monospace; width: 224px; border: 1px solid #fff; } #synner-data-table .field-filter input[type=text].field-filter-text.has-error { border: 1px solid red; } #synner-data-table .field-filter .field-filter-error { margin: 5px; font-weight: normal; color: red; max-width: 224px; width: 224px; white-space: normal; } #synner-data-table .field-filter .confirm-dialog { width: 36px; height: 23px; text-align: center; vertical-align: middle; position: absolute; bottom: 0; right: 0; } #synner-data-table .field-filter .confirm-dialog .has-error { color: #ddd; } #synner-data-table .field-error-missings { position: absolute; top: 0; left: 0; width: 100%; background: white; border: 1px solid #ddd; border-right: none; border-left: none; padding: 5px; } #synner-data-table .field-error-missings input[type=range] { display: inline-block; margin: 0; width: 50px; } #synner-data-table .field-error-missings .input-label { font-weight: normal; position: relative; top: -3px; } #synner-data-table .field-error-missings .confirm-dialog { width: 36px; height: 23px; text-align: center; vertical-align: middle; position: absolute; bottom: 0; right: 0; } #synner-data-table .field-error-missings .confirm-dialog .has-error { color: #ddd; } .generator-switch { position: relative; height: 100%; margin-left: 4.2em; padding: 10px; border-left: 1px solid #ddd; overflow: auto; } .generator-switch .new-case-button { margin: 0 5px 10px 0; } .generator-switch > .panel > .panel-heading { padding: 5px 7px; } .generator-switch > .panel > .panel-heading .heading-label { display: inline-block; vertical-align: middle; } .generator-switch > .panel > .panel-heading .case-action-button { margin: 2px; float: right; padding-top: 3px; } .generator-switch > .panel > .panel-heading .ace_editor { height: 2em; } .generator-switch > .panel > .panel-heading .case-condition-container { display: inline-table; position: relative; } .generator-switch > .panel > .panel-heading .case-condition-container .expression-editor { border: 1px solid #ccc; width: 300px; } .generator-switch > .panel > .panel-heading .case-condition-container .dropdown-autosuggestions { opacity: 0; } .generator-switch > .panel > .panel-heading .condition-error { color: red; display: inline-block; margin-right: 4px; } .generator-domain .domains-list-search { margin-bottom: 10px; display: inline-block; } .generator-domain .domains-list-search .search-text-input { padding-left: 6px; width: auto; } .generator-domain .hr-separator { margin-bottom: 0; margin-top: 0; } .generator-domain .use-frequencies { margin-top: 10px; margin-bottom: 10px; display: inline-block; } .generator-domain .domain-join { display: inline-block; float: right; } .generator-domain .domain-join select { width: 200px; } .generator-domain .domains-list { max-height: 305px; overflow-y: auto; margin: 0; } .generator-domain .domains-list .domain-list-el { margin: 0px 10px 10px 0; border: 1px solid #ddd; display: inline-block; padding: 10px; } .generator-domain .domains-list .domain-list-el.notavailable { border-style: dashed; } .generator-domain .domains-list .domain-list-el .domain-title { font-size: 120%; margin-bottom: 5px; } .generator-domain .domains-list .domain-list-el .domain-examples { font-size: 80%; } .generator-domain .domains-list .domain-list-el:hover { background: #ececec; cursor: pointer; } .generator-domain .domains-list .domain-list-el.active { background: #b6b6b6; border: 1px solid #666; } .generator-domain .domain-dependencies { margin-top: 10px; } .generator-domain .subdomains-card { padding-left: 10px; } .generator-domain .input-group-addon { min-width: 45px; } .generator-function > table { width: 100%; } .generator-function > table th { padding-bottom: 5px; } .generator-function > table th.cases-header-ratio { text-align: center; } .generator-function > table th.cases-header-freqpb { text-align: left; } .generator-function > table tr.case-row { height: 35px; } .generator-function > table tr.case-row .case-value .input-group { width: 100%; } .generator-function > table tr.case-row .case-value .form-control { height: 29px; width: 100% !important; } .generator-function > table tr.case-row .case-value .void-input { border: none; box-shadow: none; } .generator-function > table tr.case-row .case-value .void-input:focus { outline: none; } .generator-function > table tr.case-row .case-value .input-group-btn { width: 1% !important; } .generator-function > table tr.case-row .case-hist-filler > div { padding: 0; margin: 0; border-top: 1px solid #cccccc; height: 1px; } .generator-function > table tr.case-row .case-ratio { width: 50px; vertical-align: middle; display: inline-block; text-align: center; } .generator-function > table tr.case-row .case-ratio input { width: 4rem; text-align: center; border: 1px solid #ddd; } .generator-function > table tr.case-row .case-freqpb { text-align: left; } .generator-function > table tr.case-row .case-freqpb .progress { border: none; display: inline-block; width: 150px; height: 34px; margin: 0 50px 0 0; padding: 0; overflow: visible; vertical-align: middle; position: relative; background: inherit; } .generator-function > table tr.case-row .case-freqpb .progress .progress-bar { background-color: rgba(70, 130, 180, 0.5); box-shadow: none; } .generator-function > table tr.case-row .case-freqpb .progress.pg-hover .ratio-value { display: none; } .generator-function > table tr.case-row .case-freqpb .progress.pg-hover .freq-btn-decrease, .generator-function > table tr.case-row .case-freqpb .progress.pg-hover .freq-btn-increase { display: block; } .generator-function > table tr.case-row .case-freqpb .progress .ratio-value { display: block; position: absolute; top: 9px; width: 50px; text-align: left; padding: 2px; -webkit-transition: left 0.6s ease; -o-transition: left 0.6s ease; transition: left 0.6s ease; } .generator-function > table tr.case-row .case-freqpb .progress .freq-btn-decrease, .generator-function > table tr.case-row .case-freqpb .progress .freq-btn-increase { display: none; position: absolute; top: 0; width: 20px; height: 34px; padding: 10px 0 0 0; width: 20px; text-align: center; padding: 10px 0 0 0; -webkit-transition: left 0.6s ease; -o-transition: left 0.6s ease; transition: left 0.6s ease; -webkit-transition: background-color 0.2s ease; -o-transition: background-color 0.2s ease; transition: background-color 0.2s ease; } .generator-function > table tr.case-row .case-freqpb .progress .freq-btn-decrease:hover, .generator-function > table tr.case-row .case-freqpb .progress .freq-btn-increase:hover { background-color: #EBEBEB; cursor: pointer; } .generator-function > table tr.case-row .case-freqpb .progress .freq-btn-decrease { margin-left: -20px; } .generator-function .function-expression label { display: block; } .generator-function .function-expression-errors { display: block; color: #ff5a49; } .generator-function .function-expression-suggestions { margin-top: 20px; } .generator-function .function-expression-suggestions table td { padding: 5px; } .generator-function .function-expression-suggestions table td code { cursor: pointer; } .generator-function .function-expression-suggestions .suggestion { margin: 5px; } .generator-function .used-field { margin-right: 0.4em; } .generator-visrel .visrel-canvas-simplot-container { position: relative; height: 250px; width: 625px; margin: 5px 10px 5px 0; } .generator-visrel .visrel-canvas-simplot-container .visrel-canvas { position: absolute; top: 5px; left: 45px; width: 560px; height: 220px; } .generator-visrel .visrel-canvas-simplot-container .visrel-simplot { position: absolute; top: 0; left: 0; height: 250px; width: 625px; } .generator-visrel .visrel-canvas-simplot-container .visrel-simplot .axis path, .generator-visrel .visrel-canvas-simplot-container .visrel-simplot .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .generator-visrel .visrel-canvas-simplot-container .visrel-simplot .sample-area { fill: #0085ff; opacity: 0.05; } .generator-visrel .visrel-canvas-simplot-container .visrel-simplot .highlighted { stroke: #176fbf; stroke-width: 1px; stroke-dasharray: 3; opacity: 0.2; fill-opacity: 0.5; } .generator-visrel .visrel-canvas-simplot-container .visrel-simplot .line { fill: none; stroke-width: 1px; stroke: #0085ff; } .generator-visrel .visrel-canvas-simplot-container .visrel-simplot .sample-dot { fill: #417bb7; } .generator-visrel .slider-table { margin-left: auto; margin-right: auto; } .generator-visrel .slider-table .rzslider { margin: 10px 5px 5px 5px; display: inline-block; width: 350px; } .generator-visrel .slider-table .rzslider .rz-tick { width: 1px; border-radius: 0; } .generator-visrel .slider-table .rzslider .rz-bubble { visibility: hidden !important; display: none !important; } .generator-visrel .slider-table .min-slider-tick { margin-top: -3px; float: left; width: 50px; text-align: center; margin-left: -20px; border: 0; padding: 0; } .generator-visrel .slider-table .max-slider-tick { margin-top: -3px; float: right; width: 50px; text-align: center; margin-right: -20px; } .generator-visrel .control-buttons { vertical-align: bottom; padding: 5px; } .generator-visrel .control-buttons .btn { margin: 2px; } .generator-visrel .axish { position: relative; text-align: center; margin-left: 10px 10px; margin-right: 10px; height: 30px; width: 560px; } .generator-visrel .axish .graph-tick-line { position: absolute; bottom: 0; left: 27.5px; width: 1px; height: 27px; background: black; } .generator-visrel .axish .source-max { position: absolute; right: 4px; top: 0; } .generator-visrel .axish .source-max input { position: relative; width: 55px; padding: 0; font-size: 10pt; text-align: center; margin-right: -6x; } .generator-visrel .axish .source-min { position: absolute; left: 16px; top: 0; } .generator-visrel .axish .source-min input { position: relative; width: 55px; padding: 0; font-size: 10pt; text-align: center; } .generator-visrel .axisv { position: relative; width: 60px; margin-top: 10px; margin-bottom: 10px; } .generator-visrel .axisv .graph-tick-line { position: absolute; top: 10px; left: 5px; height: 1px; background: black; width: 55px; } .generator-visrel .axisv .target-max { position: absolute; top: 0; } .generator-visrel .axisv .target-max input { position: relative; width: 55px; padding: 0; font-size: 10pt; text-align: center; } .generator-visrel .axisv .target-min { position: absolute; top: 0; } .generator-visrel .axisv .target-min input { position: relative; width: 55px; padding: 0; font-size: 10pt; text-align: center; } .generator-timerange label { margin-right: 10px; } .generator-timerange td { padding: 5px; } .generator-daterange label { margin-right: 10px; } .generator-daterange td { padding: 5px; } .dependencies-list { vertical-align: middle; } .dependencies-list .dependencies-label { display: block; float: left; padding-top: 2px; font-size: 80%; } .dependencies-list .fields { display: block; overflow-x: auto; overflow-y: hidden; } .dependencies-list .fields .dependency { cursor: pointer; margin-right: .2em; padding: 0.4em; border: 1px solid #ddd; } .dependencies-list .fields .dependency .fa { margin-left: 0.4em; } .dependencies-list .fields .dependency-selected { background-color: #bdbdbd; } .dependencies-list .fields .dependency-new { -webkit-appearance: none; text-overflow: ''; border: 1px solid #ddd; margin: 0; height: 17px; width: 2.8em; } .dependencies-list .fields .dependency-new:focus { outline: none; } .infer-panel > table { margin-top: 5px; } .infer-panel > table td { vertical-align: top; } .infer-panel .infer-panel-label { font-size: 120%; color: gray; padding-left: 10px; } .infer-panel .infer-default-panel-sep { background-color: #ddd; width: 1px; } .infer-panel .infer-suggestion-panel { float: left; margin: 10px 5px 10px 5px; } .infer-panel .infer-suggestion-panel .panel-heading { text-align: left; padding: 5px 7px; } .infer-panel .infer-suggestion-panel .panel-body { height: 180px; width: 150px; } .infer-panel .infer-suggestion-panel .panel-footer { text-align: right; } .infer-panel .infer-suggestion-panel .panel-footer .btn { padding: 2px 15px 2px 15px; } .infer-panel .infer-suggestion-panel .example { margin: 0 0 5px; } .infer-panel .infer-suggestion-panel .function { text-align: center; } .infer-panel .infer-suggestion-panel-default { margin-right: 10px; } .infer-panel .infer-suggestion-panel-option { margin-left: 10px; } .navbar-default { margin-bottom: 0 !important; } .navbar-default .load-save-model-dropdown { width: 37px; overflow: hidden; } .navbar-default .load-save-model-dropdown input[type="file"] { color: transparent; display: inline-block; } .navbar-default .navbar-caption { vertical-align: middle; color: white; } .navbar-default .btn { padding-top: 2px; padding-bottom: 1px; } .navbar-default .data-volume { margin-top: 11px; margin-right: 0 !important; } .navbar-default .data-volume input { color: black; width: 50px; height: 1.5rem; font-size: 13px; } .navbar-default .generation-status { position: absolute; height: 3px; bottom: 0; left: 0; right: 0; width: 100%; } .navbar-default .generation-status .generation-status-progressbar { background: #81b745; width: 20%; position: absolute; top: 0; bottom: 0; height: 100%; } /*# sourceMappingURL=main.css.map */ <|start_filename|>synner-server/src/main/resources/static/js/api.js<|end_filename|> var Synner = angular.module('Synner'); Synner.service('API', ['Parameters', '$resource', '$q', function (Parameters, $resource, $q) { this.apiRoot = Parameters.DEBUG ? Parameters.SERVER.DEBUG : Parameters.SERVER.PRODUCTION; this.generateReq = null; this.genRes = $resource('api/generator', null, { post: { method: 'POST', cancellable: true } }); this.generate = function (req, successCb, errorCb) { if (this.generateReq !== null) this.generateReq.$cancelRequest(); this.generateReq = this.genRes.post(req, successCb, errorCb); }; this.getInfo = function (successCb) { var res = $resource('api/generator', null, { get: { method: 'GET', } }); res.get(successCb); }; this.infer = function (req, successCb, errorCb) { var res = $resource('api/infer', null, { post: { isArray: true, method: 'POST', }, }); res.post(req, successCb, errorCb); }; this.downloadrequest = function (req, successCb, errorCb) { var res = $resource('api/downloadrequest', null, { post: { method: 'POST' } }); res.post(req, successCb, errorCb); }; }]); <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/generators/numerical/CustomGen.java<|end_filename|> package edu.nyu.dtl.synner.core.generators.numerical; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import edu.nyu.dtl.synner.core.generators.Generator; @JsonPropertyOrder({"type", "histogram", "min", "max"}) public class CustomGen implements Generator<Double> { @JsonProperty private Double[] normalizedHistogram; private Double[] minValues; private Double[] maxValues; private double min; private double max; public CustomGen(Double[] histogram, double min, double max) { if (max < min) throw new IllegalArgumentException("custom max less than min"); this.min = min; this.max = max; this.normalizedHistogram = new Double[histogram.length]; double sum = 0; for (Double histogramValue : histogram) { sum += histogramValue; } for (int i = 0; i < histogram.length; i++) { this.normalizedHistogram[i] = histogram[i] / sum; } this.minValues = new Double[this.normalizedHistogram.length]; this.maxValues = new Double[this.normalizedHistogram.length]; double binWidth = (max - min) / this.normalizedHistogram.length; for (int i = 0; i < this.normalizedHistogram.length; i++) this.minValues[i] = min + binWidth * i; for (int i = 0; i < this.normalizedHistogram.length; i++) this.maxValues[i] = min + binWidth * (i + 1); } @Override public Double generate(boolean errorMode, boolean previewMode) { double gen = rnd.nextDouble(); double cumulative = 0; double value = 0; if (errorMode) { if (rnd.nextBoolean()) { return this.min - gen * (this.max - this.min); } else { return this.max + gen * (this.max - this.min); } } for (int i = 0; i < this.normalizedHistogram.length; i++) { if (gen <= this.normalizedHistogram[i] + cumulative && gen > cumulative) { value = rnd.nextDouble() * (this.maxValues[i] - this.minValues[i]) + this.minValues[i]; return value; } cumulative += this.normalizedHistogram[i]; } return value; } @JsonProperty public String getType() { return "custom"; } } <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/infer/DomainDetail.java<|end_filename|> package edu.nyu.dtl.synner.core.infer; import java.util.List; public class DomainDetail implements Comparable<DomainDetail> { public String domain; public String domainReadableName; public List<String> examples; public int count; // number of times that an example value was found in the domain values public Double kNNscore; // kNN value between example and domain values DomainDetail(String domain, String readableName, int count, Double kNNscore, List<String> examples) { this.count = count; this.domain = domain; this.domainReadableName = readableName; this.kNNscore = kNNscore; this.examples = examples; } @Override public int compareTo(DomainDetail domainDetail) { int comp = Integer.compare(this.count, domainDetail.count); if (comp != 0) return comp; int kComp = Double.compare(domainDetail.kNNscore, this.kNNscore); return kComp; } public String toString() { return domain + " : " + count + " : " + kNNscore; } } <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/infer/InferRequest.java<|end_filename|> package edu.nyu.dtl.synner.core.infer; import com.fasterxml.jackson.annotation.JsonProperty; import edu.nyu.dtl.synner.core.datamodel.ColumnType; import java.util.List; public class InferRequest { @JsonProperty String id; @JsonProperty("fieldname") String fieldName; @JsonProperty List<String> values; @JsonProperty String type; // column type (i.e. "string", "decimal", or "integer") public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFieldName() { return id; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public List<String> getValues() { return values; } public void setValues(List<String> values) { this.values = values; } public String getType() { return type; } public void setType(String type) { this.type = type; } public ColumnType getTypeAsColumnType() { return ColumnType.fromReadableName(type); } @Override public String toString() { return "{id='" + id + "\', values=" + values + "}"; } } <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/infer/Infer.java<|end_filename|> package edu.nyu.dtl.synner.core.infer; import edu.nyu.dtl.synner.core.datamodel.ColumnType; import edu.nyu.dtl.synner.core.generators.domain.DomainInfo; import edu.nyu.dtl.synner.core.generators.domain.DomainsManager; import info.debatty.java.stringsimilarity.Levenshtein; import java.sql.Connection; import java.sql.SQLException; import java.util.*; public class Infer { private static final int RETURN_SIZE = 3; private static final int NUM_EXAMPLES = 5; private static final double DISTANCE_THRESHOLD = 0.5; /** * Infer the the values in the request. * * @param req the request contains the values to infer. * * @return the inferred types. Inferred types can be more than one, and sorted by importance * (the firsts better than the lasts). */ public static InferResponse infer(InferRequest req) throws SQLException { Connection c = DomainsManager.getConnection(); InferResponse res = new InferResponse(req); Map<String, DomainInfo> availableDomains = DomainsManager.getDomains(c); Random random = new Random(); if (req.getTypeAsColumnType() == ColumnType.STR) { List<DomainInfo> inferredByName = inferByName(availableDomains, req.fieldName); for (DomainInfo di : inferredByName) { res.inferredTypes.add(new InferType(di.getName(), di.getReadableName())); List<String> examples = new ArrayList<>(); List<String> words = DomainsManager.getValues(c, di.getName()); for (int q = 0; q < NUM_EXAMPLES; q++) { examples.add(words.get(random.nextInt(words.size()))); } res.examples.add(examples); } ArrayList<DomainDetail> domainDetailList = findMatchesInDomains(c, availableDomains, req, true, null); if (domainDetailList.size() < RETURN_SIZE - inferredByName.size()) { domainDetailList.addAll(kNearestNeighbors(c, availableDomains, req, domainDetailList)); } Collections.sort(domainDetailList); Collections.reverse(domainDetailList); Map<String, Integer> domainCount = new HashMap<>(); // Put all the inferred types back to the request for (DomainDetail item : domainDetailList) { if (!domainCount.containsKey(item.domain)) { domainCount.put(item.domain, 0); } int count = domainCount.get(item.domain); domainCount.replace(item.domain, count + 1); if (count >= 2) continue; if (!res.inferredTypes.contains(item.domain)) { res.inferredTypes.add(new InferType(item.domain, item.domainReadableName)); res.examples.add(item.examples); } if (res.inferredTypes.size() >= RETURN_SIZE - inferredByName.size()) break; } } c.close(); return res; } private static List<DomainInfo> inferByName(Map<String, DomainInfo> availableDomains, String fieldName) { List<DomainInfo> res = new ArrayList<>(); if (fieldName.isEmpty()) return res; fieldName = fieldName.toLowerCase(); for (DomainInfo domain : availableDomains.values()) { String domainName = domain.getName().toLowerCase(); if (domainName.contains(fieldName) || fieldName.contains(domainName)) { res.add(domain); } } return res; } /** * Helper function for infer * * @param availableDomains * @param exactMatch determines whether exact matches are found (if this is true) * or whether a string similarity measure (kNN) is used (if false) * @param exludeList */ private static ArrayList<DomainDetail> findMatchesInDomains(Connection c, Map<String, DomainInfo> availableDomains, InferRequest req, boolean exactMatch, ArrayList<DomainDetail> exludeList) throws SQLException { Random random = new Random(); ArrayList<DomainDetail> domainDetailList = new ArrayList<>(); l: for (DomainInfo domain : availableDomains.values()) { if (exludeList != null) { for (DomainDetail dd : exludeList) { if (dd.domain.equals(domain.getName())) continue l; } } List<String> words = DomainsManager.getValues(c, domain); List<String> examples = new ArrayList<>(); int count = 0; int userItemsAsExamples = 2; Double minScore = 1.0; if (exactMatch) { for (String item : req.getValues()) { if (!words.contains(item)) break; count = count + 1; if (userItemsAsExamples > 0) { examples.add(item); userItemsAsExamples--; } } if (count == 0) continue; } else { for (String item : req.getValues()) { for (String word : words) { Double score = computeDistance(item, word); if (score < minScore) minScore = score; } } if (minScore >= DISTANCE_THRESHOLD) continue; } int toinsert = NUM_EXAMPLES - examples.size(); for (int q = 0; q < toinsert; q++) { examples.add(words.get(random.nextInt(words.size()))); } domainDetailList.add(new DomainDetail(domain.getName(), domain.getReadableName(), count, minScore, examples)); } if (domainDetailList.isEmpty()) { Random rnd = new Random(); List<DomainInfo> domainsList = new ArrayList<>(availableDomains.values()); for (int i = 0; i < 3; i++) { int rndPos = rnd.nextInt(domainsList.size()); DomainInfo domain = domainsList.get(rndPos); domainsList.remove(rndPos); List<String> examples = new ArrayList<>(); for (int q = 0; q < NUM_EXAMPLES; q++) { examples.add(DomainsManager.getRandomValue(c, domain.getName(), rnd)); } domainDetailList.add(new DomainDetail(domain.getName(), domain.getReadableName(), 0, 0.0, examples)); } } return domainDetailList; } private static ArrayList<DomainDetail> kNearestNeighbors(Connection c, Map<String, DomainInfo> availableDomains, InferRequest req, ArrayList<DomainDetail> exludeList) throws SQLException { return findMatchesInDomains(c, availableDomains, req, false, exludeList); } private static double computeDistance(String item, String word) { Levenshtein l = new Levenshtein(); return l.distance(item, word) / (double) item.length(); } } <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/generators/domain/DomainsManager.java<|end_filename|> package edu.nyu.dtl.synner.core.generators.domain; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.opencsv.CSVReader; //import com.zaxxer.hikari.HikariConfig; //import com.zaxxer.hikari.HikariDataSource; import java.io.*; import java.sql.*; import java.util.*; import java.util.concurrent.TimeUnit; public class DomainsManager { // private static HikariConfig config = new HikariConfig(); // private static HikariDataSource ds; // // static { // config.setJdbcUrl("jdbc:sqlite:database.db"); // config.setMaximumPoolSize(10); // config.setMinimumIdle(0); // config.setIdleTimeout(1); // config.setConnectionTimeout(10000); // ds = new HikariDataSource(config); // } public static Connection getConnection() throws SQLException { return DriverManager.getConnection("jdbc:sqlite::resource:database.db"); // return ds.getConnection(); } public static void loadDataset(InputStream inputStream) throws SQLException { domainCachedList = null; Connection c = getConnection(); PreparedStatement existTableStm = c.prepareStatement("select exists(select 1 from sqlite_master where type = 'table' and tbl_name = ?)"); try { CSVReader reader = new CSVReader(new InputStreamReader(inputStream)); boolean relMode = true; String[] domains = reader.readNext(); for (int i = 0; i < domains.length; i++) { domains[i] = domains[i].toUpperCase(); if (domains[i].equals("FREQ") || domains[i].equals("ALIAS_1") || domains[i].equals("ALIAS_2") || domains[i].equals("ALIAS_3")) { relMode = false; continue; } // Create missing table if it doesn't exist existTableStm.setString(1, "Domain_" + domains[i]); if (existTableStm.executeQuery().getInt(1) == 0) { c.createStatement().execute("create table Domain_" + domains[i] + "(" + "val text primary key, " + "freq integer default 1, " + "alias_1 text, " + "alias_2 text, " + "alias_3 text);" ); } } if (relMode) { // Creating needed relationships. For example the input is NAME,GENDER,NATIONALITY then two // relationships are created: Rel_NAME-GENDER and Rel_NAME-NATIONALITY for (int i = 1; i < domains.length; i++) { existTableStm.setString(1, "Rel_" + domains[i - 1] + "_" + domains[i]); if (existTableStm.executeQuery().getInt(1) == 0) { c.createStatement().execute("create table Rel_" + domains[i - 1] + "_" + domains[i] + " (" + "val text not null references \" + domains[i - 1] + \", " + "valref text not null references " + domains[i] + "," + "primary key (val, valref))" ); c.createStatement().execute("create index IDX_VALREF_" + domains[i - 1] + "_" + domains[i] + " on Rel_" + domains[i - 1] + "_" + domains[i] + " (valref);"); } } String[] row; while ((row = reader.readNext()) != null) { // Inserting single values in Domain tables for (int i = 0; i < row.length; i++) { PreparedStatement ps = c.prepareStatement("insert or ignore into Domain_" + domains[i] + "(val) values (?);"); ps.setString(1, row[i]); ps.execute(); } // Populating relationships. for (int i = 1; i < row.length; i++) { PreparedStatement ps = c.prepareStatement("insert or ignore into Rel_" + domains[i - 1] + "_" + domains[i] + "(val, valref) values (?,?);"); ps.setString(1, row[0]); ps.setString(2, row[i]); ps.execute(); } } } else { int freqIdx = -1, alias1Idx = -1, alias2Idx = -1, alias3Idx = -1; for (int i = 0; i < domains.length; i++) { if (domains[i].equals("FREQ")) freqIdx = i; if (domains[i].equals("ALIAS_1")) alias1Idx = i; if (domains[i].equals("ALIAS_2")) alias2Idx = i; if (domains[i].equals("ALIAS_3")) alias3Idx = i; } PreparedStatement existValStm = c.prepareStatement("select exists(select 1 from Domain_" + domains[0] + " where val = ?)"); String[] row; while ((row = reader.readNext()) != null) { existValStm.setString(1, row[0]); if (existValStm.executeQuery().getInt(1) == 0) { PreparedStatement ps = c.prepareStatement("insert or ignore into Domain_" + domains[0] + "(val,freq,alias_1,alias_2,alias_3) values (?,?,?,?,?);"); ps.setString(1, row[0]); ps.setString(2, freqIdx > 0 ? row[freqIdx] : null); ps.setString(3, alias1Idx > 0 ? row[alias1Idx] : null); ps.setString(4, alias2Idx > 0 ? row[alias2Idx] : null); ps.setString(5, alias3Idx > 0 ? row[alias3Idx] : null); ps.execute(); } else { StringBuilder sb = new StringBuilder("update Domain_" + domains[0] + " set"); boolean first = true; if (freqIdx > 0 && freqIdx < row.length) { sb.append(" freq = ").append(row[freqIdx]); first = false; } if (alias1Idx > 0 && alias1Idx < row.length) { if (!first) sb.append(","); sb.append(" alias_1 = \"").append(row[alias1Idx]).append("\""); first = false; } if (alias2Idx > 0 && alias2Idx < row.length) { if (!first) sb.append(","); sb.append(" alias_2 = \"").append(row[alias2Idx]).append("\""); first = false; } if (alias3Idx > 0 && alias3Idx < row.length) { if (!first) sb.append(","); sb.append(" alias_3 = \"").append(row[alias3Idx]).append("\""); first = false; } sb.append(" where val = ?"); if (!first) { PreparedStatement ps = c.prepareStatement(sb.toString()); ps.setString(1, row[0]); ps.execute(); } } } } } catch (IOException e) { e.printStackTrace(); } c.close(); } public static void readDescriptionInput(InputStream inputStream) throws SQLException { domainCachedList = null; Connection c = getConnection(); try { CSVReader reader = new CSVReader(new InputStreamReader(inputStream)); String[] domains = reader.readNext(); if (!domains[0].equals("domain")) throw new IllegalArgumentException("domain should be he first column in the input"); if (!domains[1].equals("ordernum")) throw new IllegalArgumentException("ordernum should be he second column in the input"); if (!domains[2].equals("category")) throw new IllegalArgumentException("category should be the third column in the input"); if (!domains[3].equals("rname")) throw new IllegalArgumentException("rname should be the forth column in the input"); if (!domains[4].equals("description")) throw new IllegalArgumentException("description should be the fifth column in the input"); String[] row; while ((row = reader.readNext()) != null) { PreparedStatement existDescStm = c.prepareStatement("select count(*) from Domains_Info where domain = ?"); existDescStm.setString(1, "Domain_" + row[0].toUpperCase()); if (existDescStm.executeQuery().getInt(1) == 0) { // the description doesn't exist PreparedStatement ps = c.prepareStatement("insert or ignore into Domains_Info values (?,?,?,?,?);"); ps.setString(1, "Domain_" + row[0].toUpperCase()); ps.setString(2, row[1]); ps.setString(3, row[2]); ps.setString(4, row[3]); ps.setString(5, row[4]); ps.execute(); } else { PreparedStatement ps = c.prepareStatement("update Domains_Info set ordernum = ?, category = ?, readeable_name = ?, description = ? where domain = ?;"); ps.setString(1, row[1]); ps.setString(2, row[2]); ps.setString(3, row[3]); ps.setString(4, row[4]); ps.setString(5, "Domain_" + row[0].toUpperCase()); ps.execute(); } } } catch (IOException e) { e.printStackTrace(); } c.close(); } private static Map<String, DomainInfo> domainCachedList = null; private static Map<String, DomainInfo> domainAvailableCachedList = null; public static Map<String, DomainInfo> getDomains(Connection c) throws SQLException { return getDomains(c, true, null); } public static Map<String, DomainInfo> getDomains(Connection c, boolean getOnlyAvailable, String relateToDomain) throws SQLException { if (domainCachedList == null) { ResultSet rs = c.createStatement().executeQuery("select * from Domains_Info order by ordernum"); Map<String, DomainInfo> res = new LinkedHashMap<>(); while (rs.next()) { String domainName = rs.getString("domain").replace("Domain_", ""); DomainInfo domainInfo = new DomainInfo(domainName, rs.getString("category"), rs.getString("readeable_name"), rs.getString("description")); if (existDomain(c, domainName)) domainInfo.setAvailable(true); List<String> doms = getDirectReachableDomainsFromDomain(c, domainInfo.domainName); for (String dom : doms) { domainInfo.getSubdomains().add(dom); } res.put(domainName, domainInfo); } domainCachedList = res; } Map<String, DomainInfo> res = domainCachedList; if (getOnlyAvailable) { if (domainAvailableCachedList == null) { Map<String, DomainInfo> filteredRes = new LinkedHashMap<>(); for (Map.Entry<String, DomainInfo> e : domainCachedList.entrySet()) { if (e.getValue().isAvailable()) filteredRes.put(e.getKey(), e.getValue()); } domainAvailableCachedList = filteredRes; } res = domainAvailableCachedList; } if (relateToDomain != null) { Map<String, DomainInfo> filteredRes = new LinkedHashMap<>(); for (Map.Entry<String, DomainInfo> e : res.entrySet()) { List<String> path = findPath(c, relateToDomain, e.getValue().domainName, new ArrayList<>()); if (path != null && !path.isEmpty()) { filteredRes.put(e.getKey(), e.getValue()); } } res = filteredRes; } return res; } static Map<String, Integer> FREQ_SUM = new HashMap<>(); public synchronized static int getFreqSum(Connection c, String domain) throws SQLException { if (!FREQ_SUM.containsKey(domain)) { Statement st = c.createStatement(); ResultSet rs = st.executeQuery("select sum(freq) from Domain_" + domain.toUpperCase()); FREQ_SUM.put(domain, rs.getInt(1)); } return FREQ_SUM.get(domain); } static Map<String, List<FreqValue>> VALUES_CACHE = new HashMap<>(); public static String getRandomValue(Connection c, String domain, Random rnd) throws SQLException { int freqSum = getFreqSum(c, domain); int rIdx = rnd.nextInt(freqSum); if (!VALUES_CACHE.containsKey(domain)) { ResultSet rs = c.createStatement().executeQuery("select * from Domain_" + domain.toUpperCase() + " order by freq desc"); List<FreqValue> values = new ArrayList<>(); while (rs.next()) { values.add(new FreqValue(rs.getInt("freq"), rs.getString("val"))); } VALUES_CACHE.put(domain, values); } List<FreqValue> values = VALUES_CACHE.get(domain); int freqCumSum = 0; for (FreqValue v : values) { freqCumSum += v.getFreq(); if (rIdx < freqCumSum) return v.getValue(); } throw new IllegalArgumentException("frequency is not consistent"); } public static List<String> getValues(Connection c, String domain) throws SQLException { List<String> res = new ArrayList<>(); ResultSet rs = c.createStatement().executeQuery("select * from Domain_" + domain.toUpperCase()); while (rs.next()) { res.add(rs.getString("val")); } return res; } public static List<String> getValues(Connection c, DomainInfo domain) throws SQLException { return getValues(c, domain.getName()); } public static String findRootValue(Connection c, String value, String domain) throws SQLException { PreparedStatement st = c.prepareStatement("select exists(select 1 from " + "Domain_" + domain.toUpperCase() + " where lower(val) = ?)"); st.setString(1, value.toLowerCase()); ResultSet rs = st.executeQuery(); if (rs.getInt(1) == 1) { return value; } else { value = value.toLowerCase(); for (int i = 0; i < 3; i++) { st = c.prepareStatement("select val from Domain_" + domain.toUpperCase() + " where lower(alias_" + (i + 1) + ") = ?"); st.setString(1, value); rs = st.executeQuery(); if (!rs.isClosed()) return rs.getString("val"); } } return null; } private static List<DomainsRelationship> domainsRelationshipsCached = null; private static List<DomainsRelationship> getDirectRelations(Connection c) throws SQLException { if (domainsRelationshipsCached == null) { List<DomainsRelationship> res = new ArrayList<>(); ResultSet rs = c.createStatement().executeQuery("select tbl_name from sqlite_master where type = \"table\""); while (rs.next()) { String tbl_name = rs.getString("tbl_name"); if (!tbl_name.startsWith("Rel_")) continue; String[] s = tbl_name.split("_"); res.add(new DomainsRelationship(s[1], s[2])); } domainsRelationshipsCached = res; } return domainsRelationshipsCached; } private static Map<String, String> directRelCachedValues = new HashMap<>(); public static String existDirectRel(Connection c, String sourceDomain, String targetDomain) throws SQLException { String cacheKey = sourceDomain + targetDomain; String cacheKeyInverse = targetDomain + sourceDomain; if (directRelCachedValues.containsKey(cacheKey)) { return directRelCachedValues.get(cacheKey); } ResultSet rs = c.createStatement().executeQuery("select tbl_name from sqlite_master where type = \"table\" " + "and tbl_name like \"Rel_%\" " + "and tbl_name like \"%" + sourceDomain + "%\" " + "and tbl_name like \"%" + targetDomain + "%\""); if (!rs.next()) { directRelCachedValues.put(cacheKey, null); directRelCachedValues.put(cacheKeyInverse, null); return null; } String tblName = rs.getString("tbl_name"); directRelCachedValues.put(cacheKey, tblName); directRelCachedValues.put(cacheKeyInverse, tblName); return tblName; } public static boolean existDomain(Connection c, String domain) throws SQLException { ResultSet rs = c.createStatement().executeQuery("select tbl_name from sqlite_master where type = \"table\" and tbl_name = \"Domain_" + domain + "\""); return rs.next(); } public static List<String> getDirectReachableDomainsFromDomain(Connection c, String domain) throws SQLException { List<String> res = new ArrayList<>(); List<DomainsRelationship> rels = getDirectRelations(c); for (DomainsRelationship rel : rels) { if (rel.getDomainFrom().equals(domain)) { res.add(rel.getDomainTo()); } else if (rel.getDomainTo().equals(domain)) { res.add(rel.getDomainFrom()); } } return res; } // It finds the path between a relationship A and B. For example from CONTINENT to CITY as [CONTINENT,COUNTRY,CITY] public static List<String> findPath(Connection c, String sourceDomain, String targetDomain, List<String> visitedDomains) throws SQLException { visitedDomains.add(sourceDomain); // If the target node is reached then we return a path with just the target node if (targetDomain.equals(sourceDomain)) { List<String> res = new ArrayList<>(); res.add(targetDomain); visitedDomains.remove(sourceDomain); return res; } // Get list of reachable domains that have not been visited List<String> adjacentDomains = getDirectReachableDomainsFromDomain(c, sourceDomain); adjacentDomains.removeIf((s) -> visitedDomains.contains(s)); List<String> minPath = null; for (String adjacentDomain : adjacentDomains) { List<String> res = findPath(c, adjacentDomain, targetDomain, visitedDomains); if (res != null && (minPath == null || minPath.size() > res.size())) minPath = res; } if (minPath != null) minPath.add(0, sourceDomain); visitedDomains.remove(sourceDomain); return minPath; } private static Cache<String, List<String>> valuesFromRefValue = CacheBuilder.newBuilder() .maximumSize(50).expireAfterWrite(10, TimeUnit.MINUTES).build(); public static String generateValueFromRefValue(Connection c, String refValue, String refValueDomain, String targetDomain, Random rnd, boolean previewMode) throws SQLException { String rootValue = findRootValue(c, refValue, refValueDomain); if (rootValue == null) return null; // If the root value is found we try to see if there is a relationship di.domainName <-> targetDomain String relName = existDirectRel(c, refValueDomain, targetDomain); if (relName == null) { // Search for path and then call single steps List<String> path = findPath(c, refValueDomain, targetDomain, new ArrayList<>()); if (path == null) return null; String lastValue = refValue; for (int i = 1; i < path.size(); i++) { lastValue = generateValueFromRefValue(c, lastValue, path.get(i - 1), path.get(i), rnd, previewMode); if (lastValue == null) return null; } return lastValue; } else { PreparedStatement st; // Depending if rootValue is either as valref or val we need to look the relationship in the opposite way String vA = "valref", vB = "val"; if (relName.indexOf(refValueDomain) > relName.indexOf(targetDomain)) { vA = "val"; vB = "valref"; } if (previewMode) { String cacheKey = refValueDomain + "_" + refValue + "_" + targetDomain; List<String> vals = valuesFromRefValue.getIfPresent(cacheKey); if (vals == null) { st = c.prepareStatement("select a.val, a.valref, b.freq from " + relName + " a inner join Domain_" + targetDomain + " b on a." + vA + " = b.val where a." + vB + " = ?"); st.setString(1, rootValue); ResultSet rs = st.executeQuery(); vals = new ArrayList<>(); while (rs.next()) { vals.add(rs.getString(vA)); } valuesFromRefValue.put(cacheKey, vals); } if (vals.size() == 0) return null; return vals.get(rnd.nextInt(vals.size())); } else { // rootValue to be searched as valref in relName st = c.prepareStatement("select sum(freq) from " + relName + " a inner join Domain_" + targetDomain + " b on a." + vA + " = b.val where a." + vB + " = ?"); st.setString(1, rootValue); int freqSum = st.executeQuery().getInt(1); if (freqSum <= 0) return ""; st = c.prepareStatement("select a.val, a.valref, b.freq from " + relName + " a inner join Domain_" + targetDomain + " b on a." + vA + " = b.val where a." + vB + " = ?"); st.setString(1, rootValue); ResultSet rs = st.executeQuery(); int rIdx = rnd.nextInt(freqSum); int freqCumSum = 0; while (rs.next()) { freqCumSum += rs.getInt("freq"); if (rIdx < freqCumSum) return rs.getString(vA); } } } return null; } /* Once one sourceDomain is chosen temporarly, that contains refValue, the research proceed with that. For example Bristol is both a first name and a city. So if we don't know where that value comes, it could be that First Name is tried first, trying from First Name to find Continent. But that is not possible, so the next domain that contains Bristol is tried: "City", and from there we can find Continent. */ public static String generateValueFromRefValue(Connection c, String refValue, String targetDomain, Random rnd, boolean previewMode) throws SQLException { String rootValue; // Iterate through all domains Map<String, DomainInfo> availableDomains = getDomains(c, true, targetDomain); for (DomainInfo di : availableDomains.values()) { rootValue = findRootValue(c, refValue, di.domainName); if (rootValue == null) continue; // If the domain contains refValue, then we try to generate the targetDomain by using di.domainName as starting point String val = generateValueFromRefValue(c, refValue, di.domainName, targetDomain, rnd, previewMode); if (val != null) return val; } return null; } } <|start_filename|>synner-server/src/main/resources/static/js/directives/data-table.js<|end_filename|> angular.module('Synner') .directive('tableData', ['$timeout', 'Model', 'Parameters', '$anchorScroll', '$location', '$rootScope', function ($timeout, Model, Parameters, $anchorScroll, $location, $rootScope) { return { templateUrl: 'fragments/table.html', replace: true, restriction: 'E', scope: true, link: function ($scope, element, attrs) { $scope.addRows = function () { Model.addRows(); }; $scope.removeColumn = function (col) { $scope.$parent.removeColumn(col.id); }; $scope.editFilter = function (f) { f.editingFilter = !(f.editingFilter); }; $scope.editMissingError = function (f) { f.editingMissingError = !(f.editingMissingError); }; $scope.hideColumn = function (col) { $scope.$parent.hideColumn(col.id); }; $scope.model = Model; $scope.getInputTypeForField = function (f) { if (f.type === 'time') return 'time'; if (f.type === 'date') return 'date'; if (f.type === 'integer' || f.type === 'decimal') return 'number'; return 'text' }; $(window).scroll(function () { if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) { $scope.addRows(); } }); $rootScope.$on('DATA_RESET', function () { $location.hash('data-row-0'); $anchorScroll(); }); $scope.checkDuplicates = function (f) { for (var i = 0; i < Model.fields.length; i++) { Model.fields[i].hasFieldNameError = false; } for (var i = 0; i < Model.fields.length; i++) { for (var j = i + 1; j < Model.fields.length; j++) { if (Model.fields[j].name === Model.fields[i].name) { Model.fields[j].hasFieldNameError = true; Model.fields[i].hasFieldNameError = true; } } } }; } }; }]); <|start_filename|>synner-server/src/main/resources/static/js/functions.js<|end_filename|> Synner.service('Functions', ['Model', 'Parameters', '$timeout', function (Model, Parameters, $timeout) { this.extractUsedFields = function (functionExpression, field) { var usedFields = []; var compatibleFields = Model.getCompatibleFields(field); var parsedExpression = esprima.parse(functionExpression, {tokens: true}); for (var t of parsedExpression.tokens) { if (t.type === 'Identifier') { for (var f of Model.fields) { if (f.name === t.value) { usedFields.push(f); var found = false; for (var cf of compatibleFields) { if (cf.id === f.id) found = true; } } } } } return usedFields; }; // Get the visible lines in the table this.getVisibleLines = function () { var $tbody = $('#synner-data-table .table tbody'); var tbodyTop = $tbody.offset().top; var tbodyHeight = $tbody.height(); var lines = $tbody.find('tr'); var res = []; for (var i = 0; i < lines.length; i++) { var line = lines.eq(i); line.removeClass('highlighted'); var lineTop = line.offset().top; if (lineTop + line.height() > tbodyTop && lineTop < tbodyTop + tbodyHeight) { res.push(line); } } return res; }; this.resetHighlight = function (after) { var lines = $('#synner-data-table tbody').find('tr'); for (var i = 0; i < lines.length; i++) { lines.eq(i).removeClass('highlighted'); } if (after) after(); }; this.highlightTimeout = null; this.compileFunction = function (functionBodyText, fields) { try { var functionText = 'function domain() {}; '; // placeholder for functions that are defined in the backend functionText += '(function ('; for (var i = 0; i < Model.fields.length; i++) { // We check that the field in the model is in the field's dependencies // if not we include it but with an hidden name (e.g. Height would be __Height) var found = false; for (var f of fields) { if (f.id === Model.fields[i].id) { found = true; break; } } functionText += (found ? '' : '__') + Model.fields[i].name; functionText += ','; } functionText += ') { var random = 42; function uniform() {}; function normal() {}; return (' + functionBodyText + '); })'; return eval(functionText); } catch (e) { if (e.message === 'Unexpected token )') { throw 'Invalid or unexpected token'; } else { throw e.message; } } }; this.createMockArguments = function (fields) { var arguments = []; for (var f of fields) { if (f.type === 'integer') arguments.push(42); else if (f.type === 'decimal') arguments.push(42.24); else if (f.type === 'time') arguments.push(42); else if (f.type === 'date') arguments.push(42); else arguments.push('string_example'); } return arguments; }; this.evaluateConditionInLines = function (conditionFunction, $tableLine, afterFunction) { var conditionFunctionArguments = []; for (var i = 0; i < Model.fields.length; i++) { if (Model.fields[i].type === 'string') { conditionFunctionArguments.push($tableLine.find('td').eq(i).find('input').val()); } else { conditionFunctionArguments.push(parseFloat($tableLine.find('td').eq(i).find('input').val())); } } if (conditionFunction.apply(this, conditionFunctionArguments)) { $tableLine.addClass('highlighted'); } else { $tableLine.removeClass('highlighted'); } clearTimeout(this.highlightTimeout); var self = this; this.highlightTimeout = setTimeout(function () { self.resetHighlight(afterFunction); }, 700); }; this.clearFieldsHighlights = function () { clearTimeout(this.highlightTimeout); this.resetHighlight(); this.highlightTimeout = null; } }]); <|start_filename|>synner-core/src/test/java/edu/nyu/dtl/synner/core/generators/DomainGenTest.java<|end_filename|> package edu.nyu.dtl.synner.core.generators; import edu.nyu.dtl.synner.core.generators.domain.DomainGen; import edu.nyu.dtl.synner.core.generators.domain.DomainInfo; import edu.nyu.dtl.synner.core.generators.domain.DomainsManager; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Map; import java.util.Random; public class DomainGenTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test @Ignore public void loadData() throws SQLException { // DomainsManager.loadDataset(DomainGen.class.getClassLoader().getResourceAsStream("db_creation/cities.csv")); // DomainsManager.loadDataset(DomainGen.class.getClassLoader().getResourceAsStream("db_creation/continents.csv")); // DomainsManager.loadDataset(DomainGen.class.getClassLoader().getResourceAsStream("db_creation/continents-regions.csv")); // DomainsManager.loadDataset(DomainGen.class.getClassLoader().getResourceAsStream("db_creation/countries.csv")); // DomainsManager.loadDataset(DomainGen.class.getClassLoader().getResourceAsStream("db_creation/countries-cities.csv")); // DomainsManager.loadDataset(DomainGen.class.getClassLoader().getResourceAsStream("db_creation/regions.csv")); // DomainsManager.loadDataset(DomainGen.class.getClassLoader().getResourceAsStream("db_creation/regions-countries.csv")); // // DomainsManager.loadDataset(DomainGen.class.getClassLoader().getResourceAsStream("db_creation/female.csv")); // DomainsManager.loadDataset(DomainGen.class.getClassLoader().getResourceAsStream("db_creation/female-rel.csv")); // DomainsManager.loadDataset(DomainGen.class.getClassLoader().getResourceAsStream("db_creation/male.csv")); // DomainsManager.loadDataset(DomainGen.class.getClassLoader().getResourceAsStream("db_creation/male-rel.csv")); // // DomainsManager.loadDataset(DomainGen.class.getClassLoader().getResourceAsStream("db_creation/surname.csv")); // DomainsManager.loadDataset(DomainGen.class.getClassLoader().getResourceAsStream("db_creation/boolean.csv")); DomainsManager.readDescriptionInput(DomainGen.class.getClassLoader().getResourceAsStream("db_creation/descr.csv")); // DomainsManager.loadDataset(DomainGen.class.getClassLoader().getResourceAsStream("db_creation/0.csv")); // DomainsManager.loadDataset(DomainGen.class.getClassLoader().getResourceAsStream("predefined-domains/1.csv")); // DomainsManager.loadDataset(DomainGen.class.getClassLoader().getResourceAsStream("predefined-domains/2.csv")); // DomainsManager.loadDataset(DomainGen.class.getClassLoader().getResourceAsStream("predefined-domains/3.csv")); // DomainsManager.loadDataset(DomainGen.class.getClassLoader().getResourceAsStream("predefined-domains/4.csv")); // DomainsManager.loadDataset(DomainGen.class.getClassLoader().getResourceAsStream("predefined-domains/c1.csv")); // DomainsManager.loadDataset(DomainGen.class.getClassLoader().getResourceAsStream("predefined-domains/c2.csv")); // DomainsManager.loadDataset(DomainGen.class.getClassLoader().getResourceAsStream("predefined-domains/c3.csv")); // DomainsManager.readDescriptionInput(DomainGen.class.getClassLoader().getResourceAsStream("predefined-domains/desc.csv")); } @Test @Ignore public void produceRandomData() throws SQLException { Connection c = DomainsManager.getConnection(); Random rnd = new Random(); for (int i = 0; i < 1000000; i++) { System.out.println(DomainsManager.getRandomValue(c, "city", rnd) + " "); } // for (int i = 0; i < 10; i++) { // System.out.println(DomainsManager.generateValueFromRefValue(c, "Male", "NAME", new Random())); // } // // for (int i = 0; i < 10; i++) { // System.out.println(DomainsManager.generateValueFromRefValue(c, "Girl", "NAME", new Random())); // } // for (int i = 0; i < 10; i++) { // System.out.println(DomainsManager.generateValueFromRefValue(c, "Tai", "GENDER", new Random())); // } // System.out.println(DomainsManager.getDirectReachableDomainsFromDomain(c, "COUNTRY")); // System.out.println(DomainsManager.findPath(c,"CONTINENT","CITY",new ArrayList<>())); // System.out.println(DomainsManager.findPath(c,"REGION","CITY",new ArrayList<>())); // System.out.println(DomainsManager.findPath(c,"REGION","PROVINCE",new ArrayList<>())); // List<String> path = DomainsManager.findPath(c,"CONTINENT","PROVINCE",new ArrayList<>()); // String lastValue = DomainsManager.getRandomValue(c, path.get(0), DomainsManager.getFreqSum(c, path.get(0)), rnd); // for (int i = 1; i < path.size(); i++) { // lastValue = DomainsManager.generateValueFromRefValue(c, lastValue, path.get(i - 1), path.get(i), rnd); // System.out.println(path.get(i - 1) + " " + path.get(i) + " -> " + lastValue); // // } // // for (int i = 0; i < 10; i++) { // System.out.println(DomainsManager.generateValueFromRefValue(c, "Africa", "PROVINCE", rnd)); // } // // for (int i = 0; i < 10; i++) { // System.out.println(DomainsManager.generateValueFromRefValue(c, "Gauteng", "COUNTRY", rnd)); // } // System.out.println(DomainsManager.findPath(c,"PROVINCE","COUNTRY",new ArrayList<>())); c.close(); } @Test @Ignore public void getAvailableDomains() throws SQLException { Connection c = DomainsManager.getConnection(); Random rnd = new Random(); int freqSum = DomainsManager.getFreqSum(c, "NAME"); Map<String, DomainInfo> availableDomains = DomainsManager.getDomains(c, false, null); for (DomainInfo di : availableDomains.values()) { System.out.println("Domain: " + di.getName()); System.out.println("Subdomains: " + di.getSubdomains()); System.out.println("Reachable Domains: " + DomainsManager.getDomains(c, false, di.getName())); } c.close(); } } <|start_filename|>synner-server/src/main/resources/static/js/directives/generator-number-enum.js<|end_filename|> angular.module('Synner') .directive('generatorNumberEnum', ['Model', 'Parameters', function (Model, Parameters) { return { templateUrl: 'fragments/generator-number-enum.html', replace: true, restriction: 'E', scope: { _result: '=result', // where we will put the result of generation specifications field: '=' }, link: function ($scope, element, attrs) { $scope.MAX_INFERRED_CASES = 2; $scope.inputRead = false; $scope.cases = [ // {value: 21, freq: 42}, ]; function updateCdf() { $scope.cases[0].cdf = $scope.cases[0].prob / 100; for (var i = 1; i < $scope.cases.length - 1; i++) { $scope.cases[i].cdf = $scope.cases[i - 1].cdf + $scope.cases[i].prob / 100; } } function select() { var r = Math.random(); var sel = -1; for (var j = 0; j < $scope.cases.length - 1; j++) { if (r < $scope.cases[j].cdf) { sel = j; break; } } while ($scope.cases[sel].prob === 0) { sel--; if (sel < 0) sel = $scope.cases.length - 2; } return sel; } function simGenerations() { updateCdf(); for (var i = 0; i < $scope.cases.length - 1; i++) { $scope.cases[i].simulations = []; } for (var si = 0; si < Model.experimentsNumber; si++) { var hist = []; for (var i = 0; i < $scope.cases.length - 1; i++) hist.push(0); for (var i = 0; i < Model.dataVolume; i++) { hist[select()]++; } for (var i = 0; i < $scope.cases.length - 1; i++) { var freq = hist[i] / Model.dataVolume; var idealFreq = $scope.cases[i].freq / $scope.freqSum; var el = { }; if (freq < idealFreq) { el.initPerc = freq; el.width = idealFreq - freq; } else { el.initPerc = idealFreq; el.width = freq - idealFreq; } $scope.cases[i].simulations.push(el); } } } function updateResult() { if (!$scope.inputRead) return; var generator = { cases: [], ratios: [] }; for (var el of $scope.cases) { if (el.value === null || el.value === undefined || el.value.length === 0) continue; generator.cases.push({ value: el.value }); if ($scope.freqSum > 0) generator.ratios.push(el.freq); } $scope._result.obj = generator; $scope.inputRead = true; simGenerations(); } function readResult() { if ($scope.inputRead) return; $scope.cases.length = 0; // clean array var obj = $scope._result.obj; if (!obj || !Model.isCases(obj)) { // InferAPI the generator from the data var samples = new Set(Model.getSamples($scope.field)); for (var sample of samples.values()) { $scope.cases.push({value: sample, freq: 1}); if ($scope.cases.length >= $scope.MAX_INFERRED_CASES) break; } if ($scope.cases.length === 0) { $scope.cases.push({value: 0, freq: 1}); $scope.cases.push({value: 1, freq: 1}); } } else { // Read configuration from the generator if (Model.isCases(obj)) { for (var i = 0; i < obj.cases.length; i++) { // prob and values have the same length $scope.cases.push({ value: obj.cases[i].value, freq: obj.ratios[i] ? obj.ratios[i] : 0 }); } } else { $scope.cases.push({ value: obj.value, freq: 1 }); } } $scope.cases.push({value: null, freq: 1}); $scope.inputRead = true; } // Update the frequencies sum to calculate the probabilities function updateFreqSum () { $scope.freqSum = 0; for (var i = 0; i < $scope.cases.length - 1; i++) { if ($scope.cases[i].value === null) continue; $scope.freqSum += $scope.cases[i].freq; } for (var i = 0; i < $scope.cases.length - 1; i++) { if ($scope.cases[i].value === null || $scope.cases[i].value === undefined || $scope.cases[i].value.length === 0) continue; $scope.cases[i].prob = $scope.cases[i].freq / $scope.freqSum; } } $scope.increaseFreq = function (scase) { scase.freq++; }; $scope.decreaseFreq = function (scase) { scase.freq--; }; $scope.$watchCollection(function () { var vals = []; for (var i = 0; i < $scope.cases.length - 1; i++) vals.push($scope.cases[i].freq); return vals; }, function () { $scope.freqSum = 0; for (var i = 0; i < $scope.cases.length - 1; i++) { if ($scope.cases[i].value.length === 0) continue; $scope.freqSum += $scope.cases[i].freq; } for (var i = 0; i < $scope.cases.length - 1; i++) { if ($scope.cases[i].value.length === 0) continue; $scope.cases[i].prob = Math.round(($scope.cases[i].freq / $scope.freqSum) * 100); } updateResult(); }); $scope.$watchCollection(function () { var vals = []; for (var i = 0; i < $scope.cases.length - 1; i++) vals.push($scope.cases[i].value); return vals; }, function () { if (!$scope.inputRead) return; // Check if there are void elements to delete for (var i = 0; i < $scope.cases.length - 1; i++) { if (!$scope.cases[i].value) $scope.cases.splice(i, 1); } // Check if the last element is full (so we can add a new empty element) if ($scope.cases.length === 0 || $scope.cases[$scope.cases.length - 1].value.length > 0) { $scope.cases.push({value: '', freq: 1, isRegExp: false}); } updateResult(); }); $scope.$watchCollection(function () { var vals = []; for (var i = 0; i < $scope.cases.length - 1; i++) vals.push($scope.cases[i].isRegExp); return vals; }, updateResult); $scope.$watch('cases', function () { if (!$scope.inputRead) return; // Check if there are void elements to delete for (var i = 0; i < $scope.cases.length - 1; i++) { if ($scope.cases[i].value === null) $scope.cases.splice(i, 1); } // Check if the last element is full (so we can add a new empty element) if ($scope.cases.length === 0 || $scope.cases[$scope.cases.length - 1].value !== null) { $scope.cases.push({value: null, freq: 1}); } updateFreqSum(); updateResult(); }, true); $scope.$watch('_result', function () { $scope.inputRead = false; $scope.cases = []; readResult(); }); } }; }]); <|start_filename|>synner-core/src/test/java/edu/nyu/dtl/synner/core/generators/StringGenTest.java<|end_filename|> package edu.nyu.dtl.synner.core.generators; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.assertTrue; public class StringGenTest { int N = 1000; @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test @Ignore public void checkGeneratedValues() throws Exception { String regexp = "[0-3]([a-c]|[e-g]{1,2})"; StringGen strGen = new StringGen(regexp); for (int i = 0; i < N; i++) { String genStr = strGen.generate(false, false); assertTrue(genStr.matches(regexp)); } } } <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/generators/VisualRelationshipGen.java<|end_filename|> package edu.nyu.dtl.synner.core.generators; import com.fasterxml.jackson.annotation.JsonProperty; import java.math.BigDecimal; import java.util.Arrays; import java.util.Comparator; public class VisualRelationshipGen implements Generator<Comparable> { @JsonProperty private final int inputFieldIdx; @JsonProperty private double[] in = null; @JsonProperty private double[] out = null; @JsonProperty(value = "in-min") private double inMin; @JsonProperty(value = "in-max") private double inMax; @JsonProperty(value = "out-min") private double outMin; @JsonProperty(value = "out-max") private double outMax; @JsonProperty(value = "noises") private double noises; @JsonProperty private Approximation approximation; // called public VisualRelationshipGen(int inputFieldIdx, double[] in, double[] out, double inMin, double inMax, double outMin, double outMax, Approximation approximation, double noises) { this.inputFieldIdx = inputFieldIdx; this.in = in; this.out = out; this.inMin = inMin; this.inMax = inMax; this.outMin = outMin; this.outMax = outMax; this.approximation = approximation; this.noises = noises; } @Override public Comparable generate(boolean errorMode, boolean previewMode) { throw new RuntimeException("Method not implemented"); } private Comparable denormalizeOut(double value) { return value * (outMax - outMin) + outMin; } private double normalizeIn(double value) { return (value - inMin) / (inMax - inMin); } private double introduceNoises(double value) { return value + rnd.nextGaussian() * noises; } @Override public Comparable generate(Comparable[] inputs, boolean errorMode, boolean previewMode) { if (inputs == null || inputs[inputFieldIdx] == null) throw new NullPointerException(); if (!(inputs[inputFieldIdx] instanceof Number)) throw new IllegalArgumentException("interpolate is not possible without numeric values"); if (errorMode) { if (rnd.nextBoolean()) { return outMin - rnd.nextInt((int) (outMax - outMin)); } else { return outMax + rnd.nextInt((int) (outMax - outMin)); } } double input = normalizeIn(((Number) inputs[inputFieldIdx]).doubleValue()); int pos = Arrays.binarySearch(in, input); double normalizedRes; if (pos >= 0) normalizedRes = out[pos]; else { int lowPos = -pos - 2; int hiPos = -pos - 1; if (lowPos < 0) return outMin; if (hiPos >= in.length) return outMax; switch (approximation) { case interpolate: case nearer: double relPos = (input - in[lowPos]) / (in[hiPos] - in[lowPos]); if (approximation == Approximation.interpolate) { normalizedRes = (out[hiPos] - out[lowPos]) * relPos + out[lowPos]; } else { // nearer normalizedRes = out[lowPos + (int) Math.round(relPos)]; } break; case low: normalizedRes = out[lowPos]; break; case high: normalizedRes = out[hiPos]; break; default: throw new IllegalArgumentException("approximation constant not correctly defined"); } } double v = introduceNoises(normalizedRes); // if (v < 0) v = 0; // else if (v > 1) v = 1; return denormalizeOut(v); } public enum Approximation { interpolate, nearer, low, high } } <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/generators/domain/DomainGen.java<|end_filename|> package edu.nyu.dtl.synner.core.generators.domain; import com.fasterxml.jackson.annotation.JsonProperty; import edu.nyu.dtl.synner.core.generators.Generator; import java.sql.Connection; import java.sql.SQLException; import static edu.nyu.dtl.synner.core.generators.domain.DomainsManager.*; public class DomainGen implements Generator<String> { public static Connection CONNECTION = null; @JsonProperty private final String domainName; private String subcategoryDomainName = null; private String subcategoryDomainValue = null; private final int joinIndex; // -1 if there is no join public DomainGen(String domainName, int joinIndex) { this.domainName = domainName; this.joinIndex = joinIndex; } public DomainGen(String domain) { this(domain, -1); } public static synchronized Connection getConnection() throws SQLException { if (CONNECTION == null) { CONNECTION = DomainsManager.getConnection(); } return CONNECTION; } public void setSubcategory(String subcategoryDomainName, String subcategoryDomainValue) { this.subcategoryDomainName = subcategoryDomainName; this.subcategoryDomainValue = subcategoryDomainValue; } @Override public String generate(boolean errorMode, boolean previewMode) throws Exception { return generate(null, errorMode, previewMode); } @Override public synchronized String generate(Comparable[] inputs, boolean errorMode, boolean previewMode) throws SQLException { if (errorMode) { char[] str = new char[rnd.nextInt(10) + 4]; for (int i = 0; i < str.length; i++) str[i] = (char)(rnd.nextInt('z' - '0') + '0'); return new String(str); } Connection c = getConnection(); if (subcategoryDomainValue != null && subcategoryDomainName != null) { return generateValueFromRefValue(c, subcategoryDomainValue, subcategoryDomainName, domainName, rnd, previewMode); } else if (inputs != null && inputs.length > 0 && joinIndex >= 0) { Comparable joinInput = inputs[joinIndex]; return generateValueFromRefValue(c, joinInput.toString(), domainName, rnd, previewMode); } return getRandomValue(c, domainName, rnd); } } <|start_filename|>synner-server/src/main/resources/static/js/directives/download-form.js<|end_filename|> angular.module('Synner') .directive('downloadForm', ['Parameters', 'API', 'Model', '$rootScope', function (Parameters, API, Model, $rootScope) { return { templateUrl: 'fragments/download-form.html', replace: true, restriction: 'E', scope: true, link: function ($scope, element, attrs) { $scope.model = Model; $scope.dwFormMessage = ''; $scope.dwFormMessageColor = "#000000"; $scope.dwFormFirstName = ''; $scope.dwFormLastName = ''; $scope.dwFormEmail = ''; $scope.dwFormOrganization = ''; $scope.dwFormNotes = ''; $scope.processJSON = function (data) { let processed = []; for (let row of data) { let entry = {}; for (let i = 0; i < row.length; i++) { if ($scope.model.fields[i].hidden) continue; let key = $scope.model.fields[i].name; entry[key] = row[i].v; } processed.push(entry); } return processed; }; $scope.processCSV = function (data) { let processed = []; let header = []; for (let i = 0; i < data[0].length; i++) { if ($scope.model.fields[i].hidden) continue; header.push($scope.model.fields[i].name); } processed.push(header); for (let row of data) { let entry = []; for (let i = 0; i < row.length; i++) { if ($scope.model.fields[i].hidden) continue; entry.push(row[i].v); } processed.push(entry); } return processed; }; $scope.saveData = (function () { let a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; return function (data, fileName, type) { let blob, url; if (type === "json") { let json = JSON.stringify(data); blob = new Blob([json], {type: "octet/stream"}); url = window.URL.createObjectURL(blob); } else { let csvContent = "data:text/csv;charset=utf-8,"; let csvData = ""; data.forEach(function (rowArray) { let row = rowArray.join(","); csvData += row + "\r\n"; }); blob = new Blob([csvData], {type: csvContent}); url = window.URL.createObjectURL(blob); } a.href = url; a.download = fileName; a.click(); window.URL.revokeObjectURL(url); }; }()); function validateEmail(email) { var re = /\S+@\S+\.\S+/; return re.test(String(email).toLowerCase()); } $scope.download = function (type) { if ($scope.dwFormFirstName.length < 3) { $scope.dwFormMessage = "Please enter a valid first name"; $scope.dwFormMessageColor = "#ff0000"; return; } if ($scope.dwFormLastName.length < 3) { $scope.dwFormMessage = "Please enter a valid surname"; $scope.dwFormMessageColor = "#ff0000"; return; } if ($scope.dwFormEmail.length < 3 || !(validateEmail($scope.dwFormEmail))) { $scope.dwFormMessage = "Please enter a valid email"; $scope.dwFormMessageColor = "#ff0000"; return; } API.downloadrequest({ name: $scope.dwFormFirstName, surname: $scope.dwFormLastName, email: $scope.dwFormEmail, organization: $scope.dwFormOrganization, notes: $scope.dwFormNotes }, function (msg) { $scope.dwFormMessage = ""; $scope.dwFormMessageColor = "#000000"; if (!(type === "json") && !(type === "csv")) return; let fileName = "synner-data." + type; let numRows = $scope.model.dataVolume - $scope.model.dataRows; let req = $scope.model.getGenerationRequest(true, numRows); if (req !== null) { API.generate(req, function (res) { let processed = []; if (type === "json") processed = $scope.processJSON(res.data); else if (type === "csv") processed = $scope.processCSV(res.data); $scope.saveData(processed, fileName, type); }) } }, function (msg) { $scope.dwFormMessage = "An error occurred, it wasn't possible to download the data"; $scope.dwFormMessageColor = "#ff0000"; }); }; } }; }]); <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/generators/CasesCustomDistGen.java<|end_filename|> package edu.nyu.dtl.synner.core.generators; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Arrays; public class CasesCustomDistGen<T extends Comparable> extends CasesGen<T> { @JsonProperty private double[] ratios; // e.g. for categorical variable {M,F} [0.4, 0.6] means that 40% of the generated values will be M, and 60% will be F ) private double[] probabilities; private double[] cdf; public CasesCustomDistGen(Generator<T>[] values, double[] ratios) { super(values); this.ratios = ratios; generateProbabilities(); generateCdf(); } @Override public T generate(boolean errorMode, boolean previewMode) throws Exception { return generators[select()].generate(errorMode, previewMode); } @Override public T generate(Comparable[] inputs, boolean errorMode, boolean previewMode) throws Exception { return generators[select()].generate(inputs, errorMode, previewMode); } private void generateProbabilities() { double ratiosTot = 0; for (int i = 0; i < ratios.length; i++) ratiosTot += ratios[i]; double[] probabilities = new double[ratios.length]; for (int i = 0; i < ratios.length; i++) probabilities[i] = ratios[i] / ratiosTot; this.probabilities = probabilities; } private void generateCdf() { cdf = new double[probabilities.length]; cdf[0] = probabilities[0]; for (int i = 1; i < probabilities.length; i++) cdf[i] = cdf[i - 1] + probabilities[i]; } private int select() { double r = rnd.nextDouble(); int sel = Arrays.binarySearch(cdf, r); if (sel < 0) { // transform the negative insertion point to the index where it can be found sel = Math.abs(sel + 1); } while (probabilities[sel] == 0.0) { sel--; if (sel < 0) sel = probabilities.length - 1; } return sel; } } <|start_filename|>synner-core/src/test/java/edu/nyu/dtl/synner/core/generators/ConditionalGenTest.java<|end_filename|> package edu.nyu.dtl.synner.core.generators; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.*; public class ConditionalGenTest { private static final int N = 100; @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } public static <T extends Comparable> Generator<T> val(T val) { return new ConstantGen<>(val); } @Test @Ignore public void functionMap() throws Exception { Generator<String> gen = new FunctionGenerator<>("x / 2"); assertEquals(2d, gen.generate(new Comparable[]{4}, false, false)); } } <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/generators/Generator.java<|end_filename|> package edu.nyu.dtl.synner.core.generators; import java.util.Random; public interface Generator<O extends Comparable> { Random rnd = new Random(); O generate(boolean errorMode, boolean previewMode) throws Exception; default O generate(Comparable[] inputs, boolean errorMode, boolean previewMode) throws Exception { return generate(errorMode, previewMode); } default Random getRnd() { return rnd; } } <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/datamodel/StatusValue.java<|end_filename|> package edu.nyu.dtl.synner.core.datamodel; public class StatusValue implements Comparable<StatusValue> { Comparable value; String status; public StatusValue(Comparable value, String status) { this.value = value; this.status = status; } public Comparable getValue() { return value; } public void setValue(Comparable value) { this.value = value; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Override public int compareTo(StatusValue o) { return value.compareTo(o.value); } } <|start_filename|>synner-core/src/test/java/edu/nyu/dtl/synner/core/generators/CatGenTest.java<|end_filename|> package edu.nyu.dtl.synner.core.generators; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.*; public class CatGenTest { private static final double N = 10000; private static final Generator[] possibleValues1 = {val("A"), val("B"), val("C")}; @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } public static <T extends Comparable> Generator<T> val(T val) { return new ConstantGen<>(val); } @Test @Ignore public void checkCatGen() throws Exception { Generator<String> strGen = new CasesGen<>(possibleValues1); for (int i = 0; i < N; i++) { String genStr = strGen.generate(false, false); boolean found = false; for (Generator s : possibleValues1) { if (((ConstantGen)s).getConstant().equals(genStr)) found = true; } assertTrue(found); } } @Test @Ignore public void checkDistribution() throws Exception { double[] distribution = new double[] {0.2, 0.5, 0.3}; CasesCustomDistGen g = new CasesCustomDistGen(possibleValues1, distribution); Map<String, Integer> collect = new HashMap<>(); for (int i = 0; i < N; i++) { String val = (String) g.generate(false, false); if (collect.containsKey(val)) { int count = collect.get(val); collect.put(val, count + 1); } else { collect.put(val, 1); } } System.out.println(collect); for (int i = 0; i < possibleValues1.length; i++) { assertEquals(collect.get(possibleValues1[i]) / N, distribution[i], 0.01); } } } <|start_filename|>synner-server/src/main/resources/static/js/directives/generator-distribution-main.js<|end_filename|> angular.module('Synner') .directive('generatorDistributionMain', ['$rootScope', '$timeout', 'Model', 'Parameters', function ($rootScope, $timeout, Model, Parameters) { return { templateUrl: 'fragments/generator-distribution-main.html', replace: true, restriction: 'E', scope: { _result: '=result', // where we will put the result of generation specifications field: '=', compactView: '=' }, controller: function ($scope) { $scope.AVAILABLE_DISTRIBUTIONS = [ {id: 'uniform', desc: 'Uniform'}, {id: 'gaussian', desc: 'Gaussian'}, {id: 'gamma', desc: 'Gamma'}, {id: 'exponential', desc: 'Exponential'}, {id: 'custom', desc: 'Custom'} ]; $scope.inputRead = false; $scope.distributionId = null; $scope.labels = { x: $scope.field.name, y: 'Frequency' }; function readResult() { // Prevent reading if there is no need if ($scope.inputRead) return; var obj = $scope._result.obj; if (!obj || !Model.isDistribution(obj)) { $scope.distributionId = $scope.AVAILABLE_DISTRIBUTIONS[1].id; //gaussian as default } else { for (var d of $scope.AVAILABLE_DISTRIBUTIONS) { if (obj.distribution === d.id) { $scope.distributionId = d.id; break; } } } $scope.inputRead = true; } function updateResult() { if (!$scope.inputRead) return; // Prevent changes on the distribution parameters to change the input, even before reading it if (!$scope._result) return; // in case the directive is active without any result specified if ($scope.distributionId !== $scope._result.obj.distribution) { $scope._result.obj = { distribution: $scope.distributionId }; } } $scope.changeDistributionId = function (distributionId) { $scope.distributionId = distributionId; }; $scope.$watch('distributionId', updateResult, true); $scope.$watch('_result', function () { $scope.inputRead = false; readResult(); }, true); } }; }]); <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/generators/domain/DomainInfo.java<|end_filename|> package edu.nyu.dtl.synner.core.generators.domain; import java.util.ArrayList; import java.util.List; public class DomainInfo { String domainName; String category; String readableName; String description; boolean available = false; // We don't have all the data we should, so there are domain TODO that are not active List<String> subdomains = new ArrayList<>(); public DomainInfo (String domainName, String category, String readableName, String description) { this.domainName = domainName; this.category = category; this.readableName = readableName; this.description = description; } public String getName() { return domainName; } public void setName(String name) { this.domainName = name; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getReadableName() { return readableName; } public void setReadableName(String readableName) { this.readableName = readableName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<String> getSubdomains() { return subdomains; } public boolean isAvailable() { return available; } public void setAvailable(boolean available) { this.available = available; } @Override public String toString() { return "DomainInfo{" + "domainName='" + domainName + '\'' + ", readableName='" + readableName + '\'' + ", category='" + category + '\'' + ", description='" + description + '\'' + ", subdomains=" + subdomains + '}'; } } <|start_filename|>synner-core/src/test/java/edu/nyu/dtl/synner/core/generators/NumericalGenTest.java<|end_filename|> package edu.nyu.dtl.synner.core.generators; import edu.nyu.dtl.synner.core.generators.numerical.GaussianGen; import org.junit.*; public class NumericalGenTest { private static final int N = 10000; private static final int ISTOGRAM_BUCKETS = 1000; @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test @Ignore public void gaussianTest() throws Exception { int mean = 50; int std = 10; GaussianGen ngg = new GaussianGen(mean, std); int[] frequencies = new int[ISTOGRAM_BUCKETS + 1]; for (int i = 0; i < frequencies.length; i++) frequencies[i] = 0; double[] values = new double[N]; double max = Double.MIN_VALUE, min = Double.MAX_VALUE; for (int i = 0; i < N; i++) { values[i] = ngg.generate(false, false); if (values[i] > max) max = values[i]; if (values[i] < min) min = values[i]; } for (int i = 0; i < N; i++) { int pos = (int) (((values[i] - min) / (max - min)) * ISTOGRAM_BUCKETS); frequencies[pos]++; } int stdMinPos = (int) (((mean - std - min) / (max - min)) * ISTOGRAM_BUCKETS); int stdMaxPos = (int) (((mean + std - min) / (max - min)) * ISTOGRAM_BUCKETS); int sum = 0; for (int i = stdMinPos; i < stdMaxPos; i++) { sum += frequencies[i]; } Assert.assertEquals(0.34 * 2, sum / (double) N, 0.01); int std2MinPos = (int) (((mean - std * 2 - min) / (max - min)) * ISTOGRAM_BUCKETS); int std2MaxPos = (int) (((mean + std * 2 - min) / (max - min)) * ISTOGRAM_BUCKETS); sum = 0; for (int i = std2MinPos; i < std2MaxPos; i++) { sum += frequencies[i]; } Assert.assertEquals(0.34 * 2 + 0.14 * 2, sum / (double) N, 0.01); } } <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/Main.java<|end_filename|> package edu.nyu.dtl.synner.core; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import edu.nyu.dtl.synner.core.datamodel.Field; import edu.nyu.dtl.synner.core.datamodel.GeneratedDataset; import edu.nyu.dtl.synner.core.datamodel.Relationship; import edu.nyu.dtl.synner.core.datamodel.Table; import edu.nyu.dtl.synner.core.parser.DataParser; import edu.nyu.dtl.synner.core.parser.RelationParser; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Set; public class Main { public static void main(String[] args) throws Exception { File test1 = new File(args[0]); FileReader test1Reader = new FileReader(test1); ObjectMapper mapper = new ObjectMapper(new JsonFactory()); JsonNode rootNode = mapper.readTree(test1Reader); Table rel = new RelationParser().readModel(rootNode.get("model")); Set<Field> fields = rel.getFields(); System.out.println("Fields: " + fields); // Just to print it, but they are sorted in Table's constructor List<Field> topSort = Relationship.topologicalSort(fields); System.out.println("Topological sort: " + topSort); System.out.println("\nGeneration examples: "); GeneratedDataset gdata = new DataParser().readModel(rel, rootNode.get("data")); gdata.generate(false); GeneratedDataset.DataField[][] data = gdata.getData(); System.out.println(rel.getFields()); for (int i = 0; i < data.length; i++) { System.out.print("["); for (int j = 0; j < data[i].length; j++) { System.out.print(data[i][j].data); if (j < data[i].length - 1) System.out.print(", "); } System.out.println("]"); } } } <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/datamodel/ColumnType.java<|end_filename|> package edu.nyu.dtl.synner.core.datamodel; public enum ColumnType { INT("integer"), DEC("decimal"), STR("string"), DATE("date"), TIME("time"); private final String readableName; ColumnType(String readableName) { this.readableName = readableName; } @Override public String toString() { return readableName; } public static ColumnType fromReadableName(String readableName) { switch (readableName) { case "integer": return ColumnType.INT; case "decimal": return ColumnType.DEC; case "string": return ColumnType.STR; case "date": return ColumnType.DATE; case "time": return ColumnType.TIME; default: throw new IllegalArgumentException("given type is not recognized"); } } } <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/generators/ConstantGen.java<|end_filename|> package edu.nyu.dtl.synner.core.generators; import com.fasterxml.jackson.annotation.JsonProperty; import edu.nyu.dtl.synner.core.datamodel.ColumnType; public class ConstantGen<T extends Comparable> implements Generator<T> { @JsonProperty T constant; public ConstantGen(T value) { this.constant = value; } public T getConstant() { return constant; } @Override public T generate(boolean errorMode, boolean previewMode) { return constant; } } <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/infer/InferResponse.java<|end_filename|> package edu.nyu.dtl.synner.core.infer; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.ArrayList; import java.util.List; public class InferResponse { @JsonProperty String id; @JsonProperty List<String> values; @JsonProperty("inferred-types") List<InferType> inferredTypes = new ArrayList<>(); @JsonProperty("examples") List<List<String>> examples = new ArrayList<>(); public InferResponse(InferRequest req) { this.id = req.id; this.values = new ArrayList<>(req.values); } public String getId() { return id; } public void setId(String id) { this.id = id; } public List<String> getValues() { return values; } public void setValues(List<String> values) { this.values = values; } public List<InferType> getInferredTypes() { return inferredTypes; } public void setInferredTypes(List<InferType> inferredTypes) { this.inferredTypes = inferredTypes; } @Override public String toString() { return "{id='" + id + "\', values=" + values + ", inferredTypes=" + inferredTypes + ", examples=" + examples + "}"; } } <|start_filename|>synner-core/src/main/java/edu/nyu/dtl/synner/core/generators/FunctionGenerator.java<|end_filename|> package edu.nyu.dtl.synner.core.generators; import com.fasterxml.jackson.annotation.JsonProperty; import edu.nyu.dtl.synner.core.datamodel.Field; import edu.nyu.dtl.synner.core.generators.domain.DomainGen; import jdk.nashorn.api.scripting.JSObject; import javax.script.*; import java.util.List; import java.util.function.BiFunction; import java.util.function.Function; public class FunctionGenerator<T extends Comparable> implements Generator<T> { @JsonProperty String strFunction; JSObject function; private ScriptEngineManager factory; private ScriptEngine engine; private static String function_domain(String domain) throws Exception { DomainGen dGen = new DomainGen(domain); return dGen.generate(false, false); } public FunctionGenerator(String strFunction, List<Field> inputFields) throws ScriptException { this.strFunction = strFunction; factory = new ScriptEngineManager(); engine = factory.getEngineByName("JavaScript"); ScriptContext sc = new SimpleScriptContext(); sc.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE); Function<String, String> fDom = (String domain) -> { try { return function_domain(domain); } catch (Exception e) { return null; } }; sc.setAttribute("domain", fDom, ScriptContext.ENGINE_SCOPE); BiFunction<Number, Number, Number> fUniform = (Number min, Number max) -> { try { return rnd.nextDouble() * (max.doubleValue() - min.doubleValue()) + min.doubleValue(); } catch (Exception e) { return null; } }; sc.setAttribute("uniform", fUniform, ScriptContext.ENGINE_SCOPE); BiFunction<Number, Number, Number> fNormal = (Number mean, Number stdev) -> { try { return rnd.nextGaussian() * stdev.doubleValue() + mean.doubleValue(); } catch (Exception e) { return null; } }; sc.setAttribute("normal", fNormal, ScriptContext.ENGINE_SCOPE); StringBuilder functionDefBldr = new StringBuilder("function generatorFunction("); if (inputFields != null) { for (int i = 0; i < inputFields.size(); i++) { functionDefBldr.append(inputFields.get(i).getName()); functionDefBldr.append(","); } functionDefBldr.append("random"); } functionDefBldr.append("){ return (").append(strFunction).append(");}"); engine.eval(functionDefBldr.toString(), sc); function = (JSObject) sc.getAttribute("generatorFunction", ScriptContext.ENGINE_SCOPE); } public FunctionGenerator(String strFunction) throws ScriptException { this(strFunction, null); } @Override public T generate(boolean errorMode, boolean previewMode) { return (T) function.call(null, rnd.nextDouble()); } @Override public T generate(Comparable[] inputs, boolean errorMode, boolean previewMode) { Object[] inpts = new Object[inputs.length + 1]; for (int i = 0; i < inputs.length; i++) { inpts[i] = inputs[i]; } inpts[inputs.length] = rnd.nextDouble(); return (T) function.call(null, inpts); } } <|start_filename|>synner-server/src/main/resources/static/js/model.js<|end_filename|> Synner.service('Model', ['Parameters', 'API', '$timeout', '$rootScope', function (Parameters, API, $timeout, $rootScope) { document.model = this; this.fields = [ { id: 0, // used to have a way to identify the field (the name can be modified) name: 'Name', type: 'string', // the type of the field, which can be 'string', 'integer', 'decimal', or 'enum' dependencies: [], _generator: {obj: {switch: [{default: {domain: {name: "NAME"}, join: "Gender"}}]}} // contains the description of how to generate this field (in the field 'value') }, { id: 1, name: 'Surname', type: 'string', dependencies: [], _generator: {obj: {switch: [{default: {domain: {name: "SURNAME"}}}]} } }, { id: 2, name: 'Sex', type: 'string', dependencies: [], _generator: {obj: {switch: [{default: {domain: {name: "SEX"}}}]} } }, { id: 3, name: 'Age', type: 'integer', dependencies: [], _generator: {obj: {switch: [{default: {distribution: "uniform", min: 0, max: 42}}]}} }, { id: 4, name: 'Height', type: 'integer', dependencies: [], _generator: {obj: {switch: [{default: {distribution: "uniform", min: 0, max: 42}}]}} } // { // id: 0, // used to have a way to identify the field (the name can be modified) // name: 'Name', // type: 'string', // the type of the field, which can be 'string', 'integer', 'decimal', or 'enum' // dependencies: [], // _generator: {obj: {domain: "surnames/all"}} // contains the description of how to generate this field (in the field 'value') // }, // { // id: 1, // name: 'Age', // type: 'integer', // dependencies: [], // _generator: {obj: {distribution: "gaussian", mean: 27, stdev: 3}} // }, // { // id: 2, // name: 'Gender', // type: 'string', // dependencies: [], // _generator: {obj: {cases: [{value: "M"}, {value: "F"}], ratios: [1, 1]}} // }, // { // id: 3, // name: 'Height', // type: 'decimal', // dependencies: [], // _generator: {obj: {distribution: "gaussian", mean: 170, stdev: 10}} // }, // {id: 4, name: 'Country', type: 'string', dependencies: [], _generator: {obj: {domain: "countries/all"}}}, // {id: 5, name: 'City', type: 'string', dependencies: [], _generator: {obj: {domain: "cities/all"}}}, // { // id: 6, // name: 'Weight', // type: 'integer', // dependencies: [], // _generator: {obj: {distribution: "gaussian", mean: 70, stdev: 20}} // }, // { // id: 7, // name: 'BirthDate', // type: 'time', // dependencies: [], // _generator: {obj: {'function': '42'}} // } ]; this.fields[0].dependencies.push(this.fields[2]); this.fields[4].dependencies.push(this.fields[3]); this.dataVolume = 1000; // The amount of data to generate this.experimentsNumber = 20; // The amount of experiments to do in case of outcome prediction (e.g. distribution graph) // Number of rows to display in the interface as example this.defaultDataRows = 10; this.dataRows = 10; this.haltGeneration = false; this.data = [ // [{v: 'Miro', l: true}, null, {v: 'M', l: true}, {v: 179, l: true}, null, null, null, null], // [{v: 'Marco', l: true}, null, {v: 'M', l: true}, {v: 175, l: true}, null, null, null, null], // [null, null, {v: 'F', l: true}, {v: 156, l: true}, null, null, null, null], // [null, null, {v: 'F', l: true}, null, null, null, null, null] ]; this.getSamples = function (field) { var samples = []; for (var i = 0; i < this.data.length; i++) { var val = this.data[i][field.id]; if (val && val.v !== null) samples.push(val.v); } return samples; }; /* newData false if it is the first time generating data if newData is ture then the backend will only add new data on top of the model.data */ this.getGenerationRequest = function (newData, numRows) { var generationRequest = { model: {}, data: { 'to-add': 0, tuples: [] }, 'preview-mode': true, format: 'json' }; for (var field of this.fields) { var dependenciesNames = []; for (var dep of field.dependencies) { dependenciesNames.push(dep.name); } generationRequest.model[field.name] = { pos: field.id, type: field.type, filter: field.filter, errorRows: field.errorRows, missingRows: field.missingRows, dependencies: dependenciesNames, generator: field._generator.obj }; } if (newData) { // only generate new data, without caring about past values generationRequest.data['to-add'] = numRows; } else { var dl = Math.min(numRows, this.data.length); for (var tdx = 0; tdx < dl; tdx++) { var tuple = this.data[tdx], nonNullValue = false; var reqTuple = []; for (var idx = 0; idx < tuple.length; idx++) { var dt = tuple[idx]; var field = this.fields[idx]; if (dt === null || dt.l === false) { reqTuple.push(null); } else { nonNullValue = true; var v = dt.v; if (field.type === 'integer' || field.type === 'decimal') v = parseFloat(v); else if (field.type === 'time') v = this.getIntFromTime(v); else if (field.type === 'date') v = this.getIntFromDate(v); reqTuple.push(v); } } if (nonNullValue) { generationRequest.data.tuples.push(reqTuple); } } if (generationRequest.data.tuples.length < numRows) { generationRequest.data['to-add'] = numRows - generationRequest.data.tuples.length; } } return generationRequest; }; this.changeFieldType = function (fieldId) { this.fields[fieldId]._generator.obj = undefined; this.fields[fieldId].inferDefaultOption = undefined; this.fields[fieldId].inferOptions = []; this.clearValues(fieldId); }; var genSeq = 0, dataGenerationReqTimeout; this.requestNewDataGeneration = function () { var model = this; if (model.haltGeneration) return; genSeq = 0; if (dataGenerationReqTimeout !== null) { clearTimeout(dataGenerationReqTimeout); } dataGenerationReqTimeout = setTimeout(function () { dataGenerationReqTimeout = null; genSeq = 0; model.generateSamples(); }, Parameters.GENERATION_DELAY); }; this.generateSamples = function () { var model = this; $rootScope.$emit('DATA_UPDATE_START'); $rootScope.$emit('DATA_RESET'); var req = this.getGenerationRequest(false, this.defaultDataRows); if (req !== null) { API.generate(req, function (res) { model.generationError = null; model.updateData(res.data); $rootScope.$emit('DATA_UPDATE_END'); model.generateCompletePreview(); }, function (res) { model.generationError = res.data.message; $rootScope.$emit('DATA_UPDATE_END'); }) } }; this.addRows = function (num) { var rowsToAdd = !num ? Parameters.ROWS_TO_PROGRESSIVELY_ADD : num; var model = this; $rootScope.$emit('DATA_UPDATE_START'); var req = this.getGenerationRequest(true, rowsToAdd); if (req !== null) { API.generate(req, function (res) { model.updateData(res.data, model.data.length); $rootScope.$emit('DATA_UPDATE_END'); model.generateCompletePreview(); }) } }; // To add more data to the interface after updating the first rows to guarantee responsiveness this.generateCompletePreview = function () { var model = this; if (this.data.length < Parameters.MAX_INTERFACE_DATA_VOLUME) { var timeout = Parameters.COMPLETE_PREVIEW_INIIAL_GENERATION_DELAY; if (genSeq > 0) { // first time 1 sec, after proportional to genSeq timeout = genSeq * Parameters.COMPLETE_PREVIEW_GENERATION_DELAY; } genSeq++; if (dataGenerationReqTimeout) { clearTimeout(dataGenerationReqTimeout); } dataGenerationReqTimeout = setTimeout(function () { dataGenerationReqTimeout = null; model.addRows(Parameters.ROWS_TO_PROGRESSIVELY_ADD); }, timeout); } }; this.addNewColumn = function (type) { var newField = { id: this.fields.length, name: 'column' + (this.fields.length + 1), type: type, dependencies: [], _generator: {obj: null /* generator */} }; this.fields.push(newField); for (var row of this.data) row.push(null); return newField; }; this.hideColumn = function (id) { this.fields[id].hidden = !this.fields[id].hidden; }; this.removeColumn = function (id) { for (var f of this.fields) { for (var idx = f.dependencies.length - 1; idx >= 0; idx--) { if (f.dependencies[idx].id === id) { f.dependencies.splice(idx, 1); } } } for (var i = id + 1; i < this.fields.length; i++) { this.fields[i].id--; } this.fields.splice(id, 1); for (var i = 0; i < this.data.length; i++) { this.data[i].splice(id, 1); } if (this.fields.length === 0) { this.addNewColumn('string'); } }; this.getValueFromBackendValue = function (v, colType) { if (colType === 'decimal') { return v === null ? null : parseFloat((v).toFixed(2)); } else if (colType === 'time') { return this.getTimeFromInt(v); } else if (colType === 'date') { return this.getDateFromInt(v); } else { return v; } }; this.addDataTimeout = null; this.addData = function (newData) { // var self = this; // // if (this.addDataTimeout !== null) { // clearTimeout(this.addDataTimeout); // this.addDataTimeout = null; // } // // function addDataPartialAsync(newData, offset, length) { // var end = false; // // if (offset + length > newData.length) { // length = newData.length - offset; // end = true; // } // // for (var row_i = offset; row_i < offset + length; row_i++) { // var newRow = []; // for (var col_i = 0; col_i < newData[row_i].length; col_i++) { // newRow.push({ // l: false, // s: newData[row_i][col_i].s, // v: self.getValueFromBackendValue(newData[row_i][col_i].v, self.fields[col_i].type) // }); // } // self.data.push(newRow); // } // // if (!end) { // self.addDataTimeout = setTimeout(function () { // self.addDataTimeout = null; // addDataPartialAsync(newData, offset + length, 100); // $rootScope.$apply(); // }, 1); // } // } // // addDataPartialAsync(newData, 0, 100); // everything above is the async version that iteratively updates while doing yield of the code below for (var row_i = 0; row_i < newData.length; row_i++) { var newRow = []; for (var col_i = 0; col_i < newData[row_i].length; col_i++) { newRow.push({ l: false, s: newData[row_i][col_i].s, v:this.getValueFromBackendValue(newData[row_i][col_i].v, this.fields[col_i].type) }); } this.data.push(newRow); } }; this.updateData = function (results, offset) { if (offset === undefined) offset = 0; for (var row_i = 0; row_i < results.length; row_i++) { if (row_i + offset >= this.data.length) { break; // var newTuple = []; // for (var i = 0; i < results[row_i].length; i++) newTuple.push(null); // this.data.push(newTuple); } for (var col_i = 0; col_i < results[row_i].length; col_i++) { if (this.data[row_i + offset][col_i] === null) this.data[row_i + offset][col_i] = {l: false}; this.data[row_i + offset][col_i].s = results[row_i][col_i].s; this.data[row_i + offset][col_i].v = this.getValueFromBackendValue(results[row_i][col_i].v, this.fields[col_i].type); } } if (results.length + offset > this.data.length) { this.addData(results.splice(row_i)); } else if (this.data.length > results.length + offset) { this.data.splice(results.length); } }; this.getGeneratorWithoutSwitch = function (field) { var gen = field._generator.obj; if (this.isSwitch(gen) && gen.switch.length === 1 && gen.switch[0].default) { gen = gen.switch[0].default; } return gen; }; this.getCompatibleFields = function (field) { var compatibleFields = []; for (var f of this.fields) { // exclude link to the same node if (f.id === field.id) continue; // exclude duplicate links if (this.fieldHasDependency(field.id, f.id)) continue; compatibleFields.push(f); } return compatibleFields; }; this.clearValues = function (id) { for (var row of this.data) row[id] = null; }; this.isRegExp = function (generator) { return generator && 'regexp' in generator; }; this.isSingleValue = function (generator) { return generator && 'value' in generator; }; this.isCases = function (generator) { return generator && 'cases' in generator; }; this.isDistribution = function (generator) { return generator && 'distribution' in generator; }; this.isFunction = function (generator) { return generator && 'function' in generator; }; this.isTimeRange = function (generator) { return generator && 'timerange' in generator; }; this.isDateRange = function (generator) { return generator && 'daterange' in generator; }; this.isVisualRelationship = function (generator) { return generator && 'visrel' in generator; }; this.isSwitch = function (generator) { return generator && 'switch' in generator; }; this.isDomain = function (generator) { return generator && 'domain' in generator; }; // in Synner we store a time as integer, indicating the number of minutes after midnight this.getIntFromTime = function (date) { return date.getHours() * 60 + date.getMinutes(); }; this.getTimeFromInt = function (minutesFromMidnight) { var d = new Date(minutesFromMidnight * 60 * 1000); return new Date(minutesFromMidnight * 60 * 1000 + d.getTimezoneOffset() * 60000) }; this.strFormatTimeFromTime = function (date) { return date.getHours() + ':' + date.getMinutes(); }; this.getIntFromDate = function (date) { return date.getTime() / 60 / 60 / 24 / 1000; }; this.getDateFromInt = function (daysFromEpoch) { return new Date(daysFromEpoch * 24 * 60 * 60 * 1000) }; this.strFormatDateFromDate = function (date) { return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear(); }; this.getFieldModalities = function (field) { var modalities = []; if (field.type === 'string') { modalities = [ {v: 'enumeration', descr: 'Enumeration'}, {v: 'domain', descr: 'Domain'}, {v: 'function', descr: 'Expression'}, {v: 'sequence', descr: 'Sequence'} ]; } else if (field.type === 'decimal' || field.type === 'integer') { modalities = [ {v: 'distribution', descr: 'Distribution'}, {v: 'enumeration', descr: 'Enumeration'}, {v: 'function', descr: 'Expression'} ]; if (field.dependencies.length > 0) { for (var dep of field.dependencies) { if (dep.type === 'decimal' || dep.type === 'integer') { modalities.push({v: 'visrel', descr: 'Visual Relationship'}); break; } } } modalities.push({v: 'sequence', descr: 'Sequence'}); } else if (field.type === 'time') { modalities = [ {v: 'function', descr: 'Expression'}, {v: 'timerange', descr: 'Time Range'}, {v: 'sequence', descr: 'Sequence'} ]; } else if (field.type === 'date') { modalities = [ {v: 'function', descr: 'Expression'}, {v: 'daterange', descr: 'Date Range'}, {v: 'sequence', descr: 'Sequence'} ]; } return modalities; }; this.deleteFieldData = function (field) { for (var row_i = 0; row_i < this.data.length; row_i++) { this.data[row_i][field.id].l = false; this.data[row_i][field.id].v = null; } }; this.filterNumericFields = function (fields) { var numericFields = []; for (var dep of fields) { if (dep.type === 'integer' || dep.type === 'decimal') numericFields.push(dep); } return numericFields; }; this.getFieldGeneratorModality = function (field) { if (field.type === 'string') { if (this.isFunction(field._generator.obj)) return 'function'; if (this.isDomain(field._generator.obj)) return 'domain'; return 'enumeration'; } else if (field.type === 'decimal' || field.type === 'integer') { if (this.isFunction(field._generator.obj)) return 'function'; if (this.isCases(field._generator.obj)) return 'enumeration'; return 'distribution'; } }; // It creates a new link or use this.addDependency = function (fieldId, dependencyId) { var field = this.fields[fieldId]; if (!field) return false; var dependency = this.fields[dependencyId]; if (!this.fieldHasDependency(field.id, dependency.id)) { field.dependencies.push(dependency); } }; this.removeDependencyFromField = function (fieldId, dependencyId) { var field = this.fields[fieldId]; var dependency = this.fields[dependencyId]; for (var i = 0; i < field.dependencies.length; i++) { if (field.dependencies[i].id === dependency.id) { field.dependencies.splice(i, 1); break; } } // TODO Set the generator to null if incompatibile }; this.fieldHasDependency = function (fieldId, dependencyId) { var field = this.fields[fieldId]; var dependency = this.fields[dependencyId]; for (var i = 0; i < field.dependencies.length; i++) { if (field.dependencies[i].id === dependency.id) { return true; } } return false; }; }]); Synner.filter('numericFields', function () { return function (fields) { var filteredFields = []; for (var f of fields) { if (f.type === 'integer' || f.type === 'decimal') filteredFields.push(f); } return filteredFields; }; });
dtl-nyuad/synner
<|start_filename|>src/htmlContent/update-list.html<|end_filename|> {{#.}} <div> <h4>{{versionString}} {{releaseLifeCycle}} - {{dateString}} <!--(<a href="{{releaseNotesURLh3" title="{{releaseNotesURL}}">{{Strings.RELEASE_NOTES}}</a>)--></h4> <!--<h5><a href="{{sourceCode}}" title="{{Strings.UPDATE_GET_SOURCE_CODE}}">{{Strings.UPDATE_GET_SOURCE_CODE}}</a></h5>--> <ul> {{#changeLog}} <li><b>{{group}}</b></li> <ul> {{#features}} <li><i>{{name}}</i> - {{description}}</li> {{/features}} </ul> {{/changeLog}} </ul> </div> {{/.}}
arduino-org/ArduinoStudio
<|start_filename|>src/front/config/testnet/erc20matic.js<|end_filename|> export default { wbtc: { address: '0xeb8df6700e24802a5d435e5b0e4228065ca9e0f3', decimals: 8, fullName: 'Wrapped Bitcoin', canSwap: true, }, } <|start_filename|>src/front/config/mainnet/limitOrder.js<|end_filename|> export default { eth: '0x3ef51736315f52d568d6d2cf289419b9cfffe782', bnb: '0xe3456f4ee65e745a44ec3bcb83d0f2529d1b84eb', matic: '0xb707d89d29c189421163515c59e42147371d6857', }
T-Ph525/MultiCurrencyWallet
<|start_filename|>__tests__/actions/clear.spec.js<|end_filename|> import { CLEAR_COLLECTION, CLEAR_RESOURCE } from '../../src/types'; import { clearCollection, clearResource } from '../../src'; describe('clearing', () => { it('resource', () => { expect(clearResource({ resource: 'users', id: 234 })) .toEqual({ type: CLEAR_RESOURCE, id: 234, resource: 'users' }); }); it('collection', () => { expect(clearCollection({ resource: 'users', opts: { query: 'some&query' } })) .toEqual({ type: CLEAR_COLLECTION, resource: 'users', opts: { query: 'some&query' } }); }); }); <|start_filename|>__tests__/actions/asyncSideEffects.spec.js<|end_filename|> /* * Copyright 2018 American Express Travel Related Services Company, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ import { handleQueryPromiseRejection, waitAndDispatchFinished, } from '../../src/actions/asyncSideEffects'; import * as types from '../../src/types'; describe('async side effectsQuery', () => { describe('handleQueryPromiseRejection', () => { it('should catch the passed promise', async () => { expect.assertions(1); await expect(handleQueryPromiseRejection(Promise.reject())).resolves.toBeUndefined(); }); }); describe('waitAndDispatchFinished', () => { const dispatch = jest.fn(); it('should dispatch the passed action along with data that was successfully loaded', async () => { expect.assertions(1); const action = { type: 'LOAD_RESOURCE' }; const promise = Promise.resolve('async data'); const thunk = waitAndDispatchFinished(promise, action); await thunk(dispatch); expect(dispatch).toHaveBeenCalledWith({ type: types.LOAD_RESOURCE_FINISHED, data: 'async data' }); }); it('should dispatch the passed action along with the error when the load failed', async () => { expect.assertions(1); const action = { type: 'LOAD_RESOURCE' }; const error = new Error('async error'); const promise = Promise.reject(error); const thunk = waitAndDispatchFinished(promise, action); await thunk(dispatch); expect(dispatch).toHaveBeenCalledWith({ type: types.LOAD_RESOURCE_ERROR, data: error }); }); }); }); <|start_filename|>src/actions/clear.js<|end_filename|> import { CLEAR_COLLECTION, CLEAR_RESOURCE } from '../types'; export function clearResource({ resource, id }) { return { resource, id, type: CLEAR_RESOURCE }; } export function clearCollection({ resource, id, opts }) { return { resource, id, opts, type: CLEAR_COLLECTION, }; } <|start_filename|>src/actions/asyncSideEffects.js<|end_filename|> /* * Copyright 2018 American Express Travel Related Services Company, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ import * as types from '../types'; /** * Some actions which are asynchronous need to act on a promise, but also return the original * promise to achieve desired behavior. Moving these asynchronous side effects to their own * functions in a different file makes it easier to mock them and make sure they were called * with the correct inputs in one test script and test their behavior in another test script. */ /** * The promise in queryResource and queryCollection is exclusively used to wait on asynchronous * data before server-side rendering. The promise should reject if the load failed, so that iguazu * doesn't continue to load data that it does not need when it will just render an error state. On * the client, nothing waits on the promise via `.then` or `await`. Instead, a redux action is fired * when the async task is finished, which updates the store, which then triggers loadDataAsProps to * run. Whether the async task finished successfully or not will be made apparent by what is stored * in state. So it seems like the promise rejection is not being handled, but ultimately it is. This * is a simple catch to assure the browser that the promise has indeed been dealt with so it will * not emit a `unhandledrejection` event. */ export function handleQueryPromiseRejection(promise) { return promise.then(null, () => { /* Swallow */ }); } /** * The promise from executeFetch will be caught by the handleQueryPromiseRejection function above. * Its job is to catch if the network job failed, because nothing is broken if it did. It should * not catch any errors that happen as a result of the network call failing which is what happens * if the promise chain returned from executeFetch dispatches redux actions inside of it. The redux * actions can cause a rerender and a render error would be swallowed making it hard to debug what * went wrong. */ export function waitAndDispatchFinished(promise, action) { return async (dispatch) => { let data; try { data = await promise; dispatch({ ...action, type: types[`${action.type}_FINISHED`], data }); } catch (e) { data = e; dispatch({ ...action, type: types[`${action.type}_ERROR`], data }); } }; } <|start_filename|>__tests__/actions/query.spec.js<|end_filename|> /* * Copyright 2018 American Express Travel Related Services Company, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ import { queryResource, queryCollection } from '../../src/actions/query'; const mockLoadPromise = Promise.resolve('data'); jest.mock('../../src/actions/crud', () => ({ loadResource: jest.fn(() => mockLoadPromise), loadCollection: jest.fn(() => mockLoadPromise), })); jest.mock('../../src/selectors', () => ({ getResource: jest.fn(() => () => 'resource'), getCollection: jest.fn(() => () => 'collection'), resourceIsLoaded: jest.fn(), collectionIsLoaded: jest.fn(), })); jest.mock('../../src/actions/asyncSideEffects', () => ({ handleQueryPromiseRejection: jest.fn((promise) => promise.catch(() => { /* swallow */ })), })); const dispatch = jest.fn((input) => input); const getState = () => 'state'; const resource = 'users'; const id = '123'; const opts = 'opts'; const loadError = new Error('Async Load Error'); describe('iguazu query actions', () => { afterEach(() => { jest.clearAllMocks(); }); describe('queryResource', () => { it('should return a loading response if the resource is loading', () => { require('../../src/selectors').resourceIsLoaded.mockImplementationOnce(() => () => false); // eslint-disable-line global-require const thunk = queryResource({ resource, id, opts }); const loadResponse = thunk(dispatch, getState); expect(loadResponse.data).toEqual('resource'); expect(loadResponse.status).toEqual('loading'); expect(loadResponse.error).toBeFalsy(); expect(loadResponse.promise).toEqual(mockLoadPromise); }); it('should return a loaded response if the resource is loaded', () => { require('../../src/selectors').resourceIsLoaded.mockImplementationOnce(() => () => true); // eslint-disable-line global-require const thunk = queryResource({ resource, id, opts }); const loadResponse = thunk(dispatch, getState); expect(loadResponse.data).toEqual('resource'); expect(loadResponse.status).toEqual('complete'); expect(loadResponse.error).toBeFalsy(); expect(loadResponse.promise).toEqual(mockLoadPromise); }); it('should return a loading response if the resource is loaded, but forceFetch is specified', () => { require('../../src/selectors').resourceIsLoaded.mockImplementationOnce(() => () => true); // eslint-disable-line global-require const thunk = queryResource({ resource, id, opts, forceFetch: true, }); const loadResponse = thunk(dispatch, getState); expect(loadResponse.data).toEqual('resource'); expect(loadResponse.status).toEqual('loading'); expect(loadResponse.error).toBeFalsy(); expect(loadResponse.promise).toEqual(mockLoadPromise); }); it('should indicate an error occured if applicable', () => { require('../../src/selectors').resourceIsLoaded.mockImplementationOnce(() => () => true); // eslint-disable-line global-require require('../../src/selectors').getResource.mockImplementationOnce(() => () => loadError); // eslint-disable-line global-require const thunk = queryResource({ resource, id, opts }); const loadResponse = thunk(dispatch, getState); expect(loadResponse.error).toBe(loadError); }); it('should catch the promise if it rejects, but leave the uncaught promise for ssr', async () => { expect.assertions(2); const { handleQueryPromiseRejection } = require('../../src/actions/asyncSideEffects'); // eslint-disable-line global-require let promise; try { require('../../src/selectors').resourceIsLoaded.mockImplementationOnce(() => () => false); // eslint-disable-line global-require require('../../src/actions/crud').loadResource.mockImplementationOnce(() => Promise.reject(new Error('async error'))); // eslint-disable-line global-require const thunk = queryResource({ resource, id, opts }); const loadResponse = thunk(dispatch, getState); promise = loadResponse.promise; await promise; } catch (e) { expect(handleQueryPromiseRejection).toHaveBeenCalledWith(promise); expect(e.message).toBe('async error'); } }); }); describe('queryCollection', () => { it('should return a loading response if the collection is loading', () => { require('../../src/selectors').collectionIsLoaded.mockImplementationOnce(() => () => false); // eslint-disable-line global-require const thunk = queryCollection({ resource, id, opts }); const loadResponse = thunk(dispatch, getState); expect(loadResponse.data).toEqual('collection'); expect(loadResponse.status).toEqual('loading'); expect(loadResponse.promise).toEqual(mockLoadPromise); }); it('should return a loaded response if the collection is loaded', () => { require('../../src/selectors').collectionIsLoaded.mockImplementationOnce(() => () => true); // eslint-disable-line global-require const thunk = queryCollection({ resource, id, opts }); const loadResponse = thunk(dispatch, getState); expect(loadResponse.data).toEqual('collection'); expect(loadResponse.status).toEqual('complete'); expect(loadResponse.promise).toEqual(mockLoadPromise); }); it('should return a loading response if the collection is loaded, but forceFetch is specified', () => { require('../../src/selectors').collectionIsLoaded.mockImplementationOnce(() => () => true); // eslint-disable-line global-require const thunk = queryCollection({ resource, id, opts, forceFetch: true, }); const loadResponse = thunk(dispatch, getState); expect(loadResponse.data).toEqual('collection'); expect(loadResponse.status).toEqual('loading'); expect(loadResponse.promise).toEqual(mockLoadPromise); }); it('should indicate an error occured if applicable', () => { require('../../src/selectors').collectionIsLoaded.mockImplementationOnce(() => () => true); // eslint-disable-line global-require require('../../src/selectors').getCollection.mockImplementationOnce(() => () => loadError); // eslint-disable-line global-require const thunk = queryCollection({ resource, id, opts }); const loadResponse = thunk(dispatch, getState); expect(loadResponse.error).toBe(loadError); }); it('should catch the promise if it rejects, but leave the uncaught promise for ssr', async () => { expect.assertions(2); const { handleQueryPromiseRejection } = require('../../src/actions/asyncSideEffects'); // eslint-disable-line global-require let promise; try { require('../../src/selectors').collectionIsLoaded.mockImplementationOnce(() => () => false); // eslint-disable-line global-require require('../../src/actions/crud').loadCollection.mockImplementationOnce(() => Promise.reject(new Error('async error'))); // eslint-disable-line global-require const thunk = queryCollection({ resource, id, opts }); const loadResponse = thunk(dispatch, getState); promise = loadResponse.promise; await promise; } catch (e) { expect(handleQueryPromiseRejection).toHaveBeenCalledWith(promise); expect(e.message).toBe('async error'); } }); }); }); <|start_filename|>src/helpers/hash.js<|end_filename|> /* * Copyright 2018 American Express Travel Related Services Company, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ import hash from 'object-hash'; import { Map as iMap } from 'immutable'; import { ID_TYPE_ERROR } from '../errors'; function hashWithoutPrototypes(obj) { return hash(obj, { respectType: false }); } export function valuesAsStrings(obj) { return iMap(obj).map((v) => v.toString()).toJS(); } function getIdAsObject(id) { const idType = typeof id; if (idType === 'object' && id !== null) { return id; } if (idType === 'string' || idType === 'number') { return { id }; } throw new Error(ID_TYPE_ERROR); } export function convertId(originalId) { return valuesAsStrings(getIdAsObject(originalId)); } export function getResourceIdHash(originalId) { const idObj = convertId(originalId); return hashWithoutPrototypes(idObj); } export function getCollectionIdHash(id) { if (id) { const idObj = convertId(id); delete idObj.id; return hashWithoutPrototypes(idObj); } return hashWithoutPrototypes({}); } export function getQueryHash(opts = {}) { return hashWithoutPrototypes(opts.query || {}); } <|start_filename|>src/actions/query.js<|end_filename|> /* * Copyright 2018 American Express Travel Related Services Company, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ import { getResource, getCollection, resourceIsLoaded, collectionIsLoaded, } from '../selectors'; import { loadResource, loadCollection, } from './crud'; import { handleQueryPromiseRejection, } from './asyncSideEffects'; export function queryResource({ resource, id, opts, forceFetch, }) { return (dispatch, getState) => { const state = getState(); const data = getResource({ resource, id, opts })(state); const status = resourceIsLoaded({ resource, id, opts })(state) && !forceFetch ? 'complete' : 'loading'; const error = data instanceof Error && data; const promise = dispatch(loadResource({ resource, id, opts, forceFetch, })); handleQueryPromiseRejection(promise); return { data, status, error, promise, }; }; } export function queryCollection({ resource, id, opts, forceFetch, }) { return (dispatch, getState) => { const state = getState(); const data = getCollection({ resource, id, opts })(state); const status = collectionIsLoaded({ resource, id, opts })(state) && !forceFetch ? 'complete' : 'loading'; const error = data instanceof Error && data; const promise = dispatch(loadCollection({ resource, id, opts, forceFetch, })); handleQueryPromiseRejection(promise); return { data, status, error, promise, }; }; }
PatNeedham/iguazu-rest
<|start_filename|>examples/bench/django/templates/template.html<|end_filename|> {% extends "base.html" %} {% load bench %} <head> <title>${title|escape}</title> </head> {% block body %} <div>{% greeting user %}</div> <div>{% greeting "me" %}</div> <div>{% greeting "world" %}</div> <h2>Loop</h2> {% if items %} <ul> {% for item in items %} <li{% if forloop.last %} class="last"{% endif %}>{{ item }}</li> {% endfor %} </ul> {% endif %} {% endblock %} <|start_filename|>examples/bench/jinja2_inheritance/template.html<|end_filename|> {% extends "base.html" %} {% block body %} {{ greeting(user) }} {{ greeting('me') }} {{ greeting('world') }} <h2>Loop</h2> {%- if list_items %} <ul> {%- for list_item in list_items %} <li {{ "class='last'" if loop.last else ""}}>{{ list_item }}</li> {%- endfor %} </ul> {%- endif %} {% endblock body %} <|start_filename|>examples/bench/jinja2/template.html<|end_filename|> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en"> <head> <title>{{ title }}</title> </head> <body> {%- macro greeting(name) %} <p>hello {{ name }}</p> {%- endmacro %} {% include "header.html" %} {{ greeting(user) }} {{ greeting('me') }} {{ greeting('world') }} <h2>Loop</h2> {%- if list_items %} <ul> {%- for list_item in list_items %} <li {{ "class='last'" if loop.last else "" }}>{{ list_item }}</li> {%- endfor %} </ul> {%- endif %} {% include "footer.html" %} </body> </html> <|start_filename|>test/templates/unicode_code_py3k.html<|end_filename|> ## -*- coding: utf-8 -*- <% x = "drôle de petite voix m’a réveillé." %> % if x=="drôle de petite voix m’a réveillé.": hi, ${x} % endif <|start_filename|>examples/bench/mako_inheritance/template.html<|end_filename|> <%inherit file="base.html"/> ${parent.greeting(user)} ${parent.greeting('me')} ${parent.greeting('world')} <h2>Loop</h2> % if list_items: <ul> % for list_item in list_items: <li>${list_item}</li> % endfor </ul> % endif
LordAro/mako
<|start_filename|>src/test/java/org/elasticsearch/module/graphite/test/NodeTestHelper.java<|end_filename|> package org.elasticsearch.module.graphite.test; import org.elasticsearch.common.Strings; import org.elasticsearch.common.logging.log4j.LogConfigurator; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.node.Node; import org.elasticsearch.node.NodeBuilder; import java.io.IOException; public class NodeTestHelper { public static Node createNode(String clusterName, int graphitePort, String refreshInterval) throws IOException { return createNode(clusterName, graphitePort, refreshInterval, null, null, null); } public static Node createNode(String clusterName, int graphitePort, String refreshInterval, String includeRegex, String excludeRegex, String prefix) throws IOException { ImmutableSettings.Builder settingsBuilder = ImmutableSettings.settingsBuilder(); settingsBuilder.put("path.conf", NodeTestHelper.class.getResource("/").getFile()); settingsBuilder.put("gateway.type", "none"); settingsBuilder.put("cluster.name", clusterName); settingsBuilder.put("index.number_of_shards", 1); settingsBuilder.put("index.number_of_replicas", 1); settingsBuilder.put("metrics.graphite.host", "localhost"); settingsBuilder.put("metrics.graphite.port", graphitePort); settingsBuilder.put("metrics.graphite.every", refreshInterval); if (!Strings.isEmpty(prefix)) { settingsBuilder.put("metrics.graphite.prefix", prefix); } if (Strings.hasLength(includeRegex)) { settingsBuilder.put("metrics.graphite.include", includeRegex); } if (Strings.hasLength(excludeRegex)) { settingsBuilder.put("metrics.graphite.exclude", excludeRegex); } LogConfigurator.configure(settingsBuilder.build()); return NodeBuilder.nodeBuilder().settings(settingsBuilder.build()).node(); } }
TinLe/elasticsearch-graphite-plugin
<|start_filename|>lib/request.js<|end_filename|> 'use strict'; const jayson = require('jayson'); const pify = require('pify'); module.exports = (connection, path, params) => { if (typeof path === 'object') { params = path; path = '/web/dataset/call_kw'; } const config = { host: connection.host, port: connection.port, path: path || '', headers: { 'Content-Type': 'application/json', Accept: 'application/json', Cookie: `${connection.sid};` } }; const client = connection.protocol === 'https' ? jayson.client.https(config) : jayson.client.http(config); return pify(client.request.bind(client))('call', params || {}); };
rarar89/odoo-connect
<|start_filename|>examples/gd-field/Main.hs<|end_filename|> {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE RecordWildCards #-} -- In this example we draw the heatmap of the norm of gradient field -- of a given function f. module Main where import Data.Text (Text, pack) import Graphics.Vega.VegaLite import Torch.Autograd (grad, makeIndependent, toDependent) import qualified Torch.Functional as F import Torch.NN import Torch.Tensor (Tensor, asTensor, toDouble) f :: Tensor -> Tensor -> Tensor f x y = F.sin (2 * pit * r) where pit = asTensor (pi :: Double) r = F.sqrt (x * x + y * y) makeAxis :: [Double] -> [Double] -> [(Double, Double)] makeAxis axis1 axis2 = [(t, t') | t <- axis1, t' <- axis2] computeGd :: (Double, Double) -> IO (Double, Double, Double) computeGd (x, y) = do tx <- makeIndependent (asTensor x) ty <- makeIndependent (asTensor y) let fxy = f (toDependent tx) (toDependent ty) gd = grad fxy [tx, ty] gdx = toDouble $ gd !! 0 gdy = toDouble $ gd !! 1 gdr = sqrt (gdx * gdx + gdy * gdy) return (x, y, gdr) main :: IO () main = do let n = 30 b = 3 xs = (\x -> x / n) <$> [(- b * n :: Double) .. b * n] ys = (\x -> x / n) <$> [(- b * n :: Double) .. b * n] grid = makeAxis xs ys gds <- mapM computeGd grid let xs' = map (\(x, y, gdr) -> x) gds ys' = map (\(x, y, gdr) -> y) gds gdrs' = map (\(x, y, gdr) -> gdr) gds xDataValue = Numbers xs' yDataValue = Numbers ys' gdrDataValue = Numbers gdrs' xName = pack "x" yName = pack "y" gdrName = pack "gdr" figw = 800 figh = 800 dat = dataFromColumns [Parse [(xName, FoNumber), (yName, FoNumber), (gdrName, FoNumber)]] . dataColumn xName xDataValue . dataColumn yName yDataValue . dataColumn gdrName gdrDataValue enc = encoding . position X [PName xName, PmType Quantitative] . position Y [PName yName, PmType Quantitative] . color [MName gdrName, MmType Quantitative] vegaPlot = toVegaLite [mark Square [], dat [], enc [], width figw, height figh] toHtmlFile "gd-field.html" vegaPlot
saeedhadikhanloo/hasktorch
<|start_filename|>controllers/operator_metrics.go<|end_filename|> package controllers import ( "fmt" promcli "github.com/prometheus/client_golang/prometheus" "sigs.k8s.io/controller-runtime/pkg/metrics" ) // OperatorMetrics defines the Prometheus metrics exposed for the // operator status type OperatorMetrics struct { gpuNodesTotal promcli.Gauge reconciliationLastSuccess promcli.Gauge reconciliationStatus promcli.Gauge reconciliationTotal promcli.Counter reconciliationFailed promcli.Counter reconciliationHasNFDLabels promcli.Gauge } const ( reconciliationStatusSuccess = 1 reconciliationStatusNotReady = 0 reconciliationStatusClusterPolicyUnavailable = -1 reconciliationStatusClusterOperatorError = -2 ) func initOperatorMetrics(n *ClusterPolicyController) OperatorMetrics { m := OperatorMetrics{ gpuNodesTotal: promcli.NewGauge( promcli.GaugeOpts{ Name: "gpu_operator_gpu_nodes_total", Help: "Number of nodes with GPUs", }, ), reconciliationLastSuccess: promcli.NewGauge( promcli.GaugeOpts{ Name: "gpu_operator_reconciliation_last_success_ts_seconds", Help: "Timestamp (in seconds) of the last reconciliation loop success", }, ), reconciliationStatus: promcli.NewGauge( promcli.GaugeOpts{ Name: "gpu_operator_reconciliation_status", Help: fmt.Sprintf("%d if the reconciliation is currently successful, %d if the operands are not ready, %d if the cluster policy is unavailable, %d if an error occurred within the operator.", reconciliationStatusSuccess, reconciliationStatusNotReady, reconciliationStatusClusterPolicyUnavailable, reconciliationStatusClusterOperatorError), }, ), reconciliationTotal: promcli.NewCounter( promcli.CounterOpts{ Name: "gpu_operator_reconciliation_total", Help: "Total number of reconciliation", }, ), reconciliationFailed: promcli.NewCounter( promcli.CounterOpts{ Name: "gpu_operator_reconciliation_failed_total", Help: "Number of failed reconciliation", }, ), reconciliationHasNFDLabels: promcli.NewGauge( promcli.GaugeOpts{ Name: "gpu_operator_reconciliation_has_nfd_labels", Help: "1 if NFD mandatory kernel labels have been found, 0 otherwise", }, ), } metrics.Registry.MustRegister( m.gpuNodesTotal, m.reconciliationLastSuccess, m.reconciliationStatus, m.reconciliationTotal, m.reconciliationFailed, m.reconciliationHasNFDLabels, ) return m }
kralicky/gpu-operator
<|start_filename|>jx/src/main/java/javax/tools/ForwardingJavaFileObject.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.tools; import javax.lang.model.element.Modifier; import javax.lang.model.element.NestingKind; /** * Forwards calls to a given file object. Subclasses of this class * might override some of these methods and might also provide * additional fields and methods. * * @param <F> the kind of file object forwarded to by this object * * @author <NAME>; * @since 1.6 */ public class ForwardingJavaFileObject<F extends javax.tools.JavaFileObject> extends ForwardingFileObject<F> implements JavaFileObject { /** * Creates a new instance of ForwardingJavaFileObject. * * @param fileObject delegate to this file object */ protected ForwardingJavaFileObject(F fileObject) { super(fileObject); } public Kind getKind() { return fileObject.getKind(); } public boolean isNameCompatible(String simpleName, Kind kind) { return fileObject.isNameCompatible(simpleName, kind); } public NestingKind getNestingKind() { return fileObject.getNestingKind(); } public Modifier getAccessLevel() { return fileObject.getAccessLevel(); } } <|start_filename|>jx/src/main/java/javax/lang/model/type/UnknownTypeException.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.lang.model.type; import javax.lang.model.UnknownEntityException; /** * Indicates that an unknown kind of type was encountered. This can * occur if the language evolves and new kinds of types are added to * the {@code TypeMirror} hierarchy. May be thrown by a {@linkplain * javax.lang.model.type.TypeVisitor type visitor} to indicate that the visitor was created * for a prior version of the language. * * @author <NAME> * @author <NAME> * @author <NAME>; * @see javax.lang.model.type.TypeVisitor#visitUnknown * @since 1.6 */ public class UnknownTypeException extends UnknownEntityException { private static final long serialVersionUID = 269L; private final transient javax.lang.model.type.TypeMirror type; private final transient Object parameter; /** * Creates a new {@code UnknownTypeException}.The {@code p} * parameter may be used to pass in an additional argument with * information about the context in which the unknown type was * encountered; for example, the visit methods of {@link * TypeVisitor} may pass in their additional parameter. * * @param t the unknown type, may be {@code null} * @param p an additional parameter, may be {@code null} */ public UnknownTypeException(javax.lang.model.type.TypeMirror t, Object p) { super("Unknown type: " + t); type = t; this.parameter = p; } /** * Returns the unknown type. * The value may be unavailable if this exception has been * serialized and then read back in. * * @return the unknown type, or {@code null} if unavailable */ public TypeMirror getUnknownType() { return type; } /** * Returns the additional argument. * * @return the additional argument */ public Object getArgument() { return parameter; } } <|start_filename|>jx/src/main/java/javax/lang/model/element/AnnotationValue.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.lang.model.element; /** * Represents a value of an annotation type element. * A value is of one of the following types: * <ul><li> a wrapper class (such as {@link Integer}) for a primitive type * <li> {@code String} * <li> {@code TypeMirror} * <li> {@code VariableElement} (representing an enum constant) * <li> {@code AnnotationMirror} * <li> {@code List<? extends AnnotationValue>} * (representing the elements, in declared order, if the value is an array) * </ul> * * @author <NAME> * @author <NAME> * @author <NAME>&eacute; * @since 1.6 */ public interface AnnotationValue { /** * Returns the value. * * @return the value */ Object getValue(); /** * Returns a string representation of this value. * This is returned in a form suitable for representing this value * in the source code of an annotation. * * @return a string representation of this value */ String toString(); /** * Applies a visitor to this value. * * @param <R> the return type of the visitor's methods * @param <P> the type of the additional parameter to the visitor's methods * @param v the visitor operating on this value * @param p additional parameter to the visitor * * @return a visitor-specified result */ <R, P> R accept(AnnotationValueVisitor<R, P> v, P p); } <|start_filename|>jx/src/main/java/javax/annotation/processing/Completions.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.annotation.processing; /** * Utility class for assembling {@link Completion} objects. * * @author <NAME> * @author <NAME> * @author <NAME>&eacute; * @since 1.6 */ public class Completions { // No instances for you. private Completions() { } /** * Returns a completion of the value and message. * * @param value the text of the completion * @param message a message about the completion * * @return a completion of the provided value and message */ public static Completion of(String value, String message) { return new SimpleCompletion(value, message); } /** * Returns a completion of the value and an empty message * * @param value the text of the completion * * @return a completion of the value and an empty message */ public static Completion of(String value) { return new SimpleCompletion(value, ""); } private static class SimpleCompletion implements Completion { private final String value; private final String message; SimpleCompletion(String value, String message) { if (value == null || message == null) throw new NullPointerException("Null completion strings not accepted."); this.value = value; this.message = message; } public String getValue() { return value; } public String getMessage() { return message; } @Override public String toString() { return "[\"" + value + "\", \"" + message + "\"]"; } // Default equals and hashCode are fine. } } <|start_filename|>jx/src/main/java/javax/tools/ForwardingJavaFileManager.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.tools; import java.io.IOException; import java.util.Iterator; import java.util.Set; /** * Forwards calls to a given file manager. Subclasses of this class * might override some of these methods and might also provide * additional fields and methods. * * @param <M> the kind of file manager forwarded to by this object * * @author <NAME>&eacute; * @since 1.6 */ public class ForwardingJavaFileManager<M extends javax.tools.JavaFileManager> implements JavaFileManager { /** * The file manager which all methods are delegated to. */ protected final M fileManager; /** * Creates a new instance of ForwardingJavaFileManager. * * @param fileManager delegate to this file manager */ protected ForwardingJavaFileManager(M fileManager) { fileManager.getClass(); // null check this.fileManager = fileManager; } /** * @throws SecurityException {@inheritDoc} * @throws IllegalStateException {@inheritDoc} */ public ClassLoader getClassLoader(Location location) { return fileManager.getClassLoader(location); } /** * @throws IOException {@inheritDoc} * @throws IllegalStateException {@inheritDoc} */ public Iterable<javax.tools.JavaFileObject> list(Location location, String packageName, Set<javax.tools.JavaFileObject.Kind> kinds, boolean recurse) throws IOException { return fileManager.list(location, packageName, kinds, recurse); } /** * @throws IllegalStateException {@inheritDoc} */ public String inferBinaryName(Location location, javax.tools.JavaFileObject file) { return fileManager.inferBinaryName(location, file); } /** * @throws IllegalArgumentException {@inheritDoc} */ public boolean isSameFile(javax.tools.FileObject a, javax.tools.FileObject b) { return fileManager.isSameFile(a, b); } /** * @throws IllegalArgumentException {@inheritDoc} * @throws IllegalStateException {@inheritDoc} */ public boolean handleOption(String current, Iterator<String> remaining) { return fileManager.handleOption(current, remaining); } public boolean hasLocation(Location location) { return fileManager.hasLocation(location); } public int isSupportedOption(String option) { return fileManager.isSupportedOption(option); } /** * @throws IllegalArgumentException {@inheritDoc} * @throws IllegalStateException {@inheritDoc} */ public javax.tools.JavaFileObject getJavaFileForInput(Location location, String className, javax.tools.JavaFileObject.Kind kind) throws IOException { return fileManager.getJavaFileForInput(location, className, kind); } /** * @throws IllegalArgumentException {@inheritDoc} * @throws IllegalStateException {@inheritDoc} */ public javax.tools.JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, javax.tools.FileObject sibling) throws IOException { return fileManager.getJavaFileForOutput(location, className, kind, sibling); } /** * @throws IllegalArgumentException {@inheritDoc} * @throws IllegalStateException {@inheritDoc} */ public javax.tools.FileObject getFileForInput(Location location, String packageName, String relativeName) throws IOException { return fileManager.getFileForInput(location, packageName, relativeName); } /** * @throws IllegalArgumentException {@inheritDoc} * @throws IllegalStateException {@inheritDoc} */ public javax.tools.FileObject getFileForOutput(Location location, String packageName, String relativeName, FileObject sibling) throws IOException { return fileManager.getFileForOutput(location, packageName, relativeName, sibling); } public void flush() throws IOException { fileManager.flush(); } public void close() throws IOException { fileManager.close(); } } <|start_filename|>jx/src/main/java/javax/lang/model/type/MirroredTypeException.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.lang.model.type; import java.io.IOException; import java.io.ObjectInputStream; import javax.lang.model.element.Element; /** * Thrown when an application attempts to access the {@link Class} object * corresponding to a {@link TypeMirror}. * * @author <NAME> * @author <NAME> * @author <NAME>&eacute; * @see MirroredTypesException * @see Element#getAnnotation(Class) * @since 1.6 */ public class MirroredTypeException extends MirroredTypesException { private static final long serialVersionUID = 269; private transient TypeMirror type; // cannot be serialized /** * Constructs a new MirroredTypeException for the specified type. * * @param type the type being accessed */ public MirroredTypeException(TypeMirror type) { super("Attempt to access Class object for TypeMirror " + type.toString(), type); this.type = type; } /** * Returns the type mirror corresponding to the type being accessed. * The type mirror may be unavailable if this exception has been * serialized and then read back in. * * @return the type mirror, or {@code null} if unavailable */ public TypeMirror getTypeMirror() { return type; } /** * Explicitly set all transient fields. */ private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); type = null; types = null; } } <|start_filename|>jx/src/main/java/javax/lang/model/element/UnknownElementException.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.lang.model.element; import javax.lang.model.UnknownEntityException; /** * Indicates that an unknown kind of element was encountered. This * can occur if the language evolves and new kinds of elements are * added to the {@code Element} hierarchy. May be thrown by an * {@linkplain javax.lang.model.element.ElementVisitor element visitor} to indicate that the * visitor was created for a prior version of the language. * * @author <NAME> * @author <NAME> * @author <NAME>; * @see javax.lang.model.element.ElementVisitor#visitUnknown * @since 1.6 */ public class UnknownElementException extends UnknownEntityException { private static final long serialVersionUID = 269L; private final transient javax.lang.model.element.Element element; private final transient Object parameter; /** * Creates a new {@code UnknownElementException}. The {@code p} * parameter may be used to pass in an additional argument with * information about the context in which the unknown element was * encountered; for example, the visit methods of {@link * ElementVisitor} may pass in their additional parameter. * * @param e the unknown element, may be {@code null} * @param p an additional parameter, may be {@code null} */ public UnknownElementException(javax.lang.model.element.Element e, Object p) { super("Unknown element: " + e); element = e; this.parameter = p; } /** * Returns the unknown element. * The value may be unavailable if this exception has been * serialized and then read back in. * * @return the unknown element, or {@code null} if unavailable */ public Element getUnknownElement() { return element; } /** * Returns the additional argument. * * @return the additional argument */ public Object getArgument() { return parameter; } } <|start_filename|>jx/src/main/java/javax/tools/OptionChecker.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.tools; /** * Interface for recognizing options. * * @author <NAME>; * @since 1.6 */ public interface OptionChecker { /** * Determines if the given option is supported and if so, the * number of arguments the option takes. * * @param option an option * * @return the number of arguments the given option takes or -1 if * the option is not supported */ int isSupportedOption(String option); } <|start_filename|>jx/src/main/java/javax/lang/model/type/TypeMirror.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.lang.model.type; import javax.lang.model.AnnotatedConstruct; import javax.lang.model.element.Element; import javax.lang.model.util.Types; /** * Represents a type in the Java programming language. * Types include primitive types, declared types (class and interface types), * array types, type variables, and the null type. * Also represented are wildcard type arguments, * the signature and return types of executables, * and pseudo-types corresponding to packages and to the keyword {@code void}. * * <p> Types should be compared using the utility methods in {@link * javax.lang.model.util.Types}. There is no guarantee that any particular type will always * be represented by the same object. * * <p> To implement operations based on the class of an {@code * TypeMirror} object, either use a {@linkplain TypeVisitor visitor} * or use the result of the {@link #getKind} method. Using {@code * instanceof} is <em>not</em> necessarily a reliable idiom for * determining the effective class of an object in this modeling * hierarchy since an implementation may choose to have a single * object implement multiple {@code TypeMirror} subinterfaces. * * @author <NAME> * @author <NAME> * @author <NAME>&eacute; * @see Element * @see javax.lang.model.util.Types * @since 1.6 */ public interface TypeMirror extends AnnotatedConstruct { /** * Returns the {@code kind} of this type. * * @return the kind of this type */ TypeKind getKind(); /** * Obeys the general contract of {@link Object#equals Object.equals}. * This method does not, however, indicate whether two types represent * the same type. * Semantic comparisons of type equality should instead use * {@link Types#isSameType(TypeMirror, TypeMirror)}. * The results of {@code t1.equals(t2)} and * {@code Types.isSameType(t1, t2)} may differ. * * @param obj the object to be compared with this type * * @return {@code true} if the specified object is equal to this one */ boolean equals(Object obj); /** * Obeys the general contract of {@link Object#hashCode Object.hashCode}. * * @see #equals */ int hashCode(); /** * Returns an informative string representation of this type. If * possible, the string should be of a form suitable for * representing this type in source code. Any names embedded in * the result are qualified if possible. * * @return a string representation of this type */ String toString(); /** * Applies a visitor to this type. * * @param <R> the return type of the visitor's methods * @param <P> the type of the additional parameter to the visitor's methods * @param v the visitor operating on this type * @param p additional parameter to the visitor * * @return a visitor-specified result */ <R, P> R accept(TypeVisitor<R, P> v, P p); } <|start_filename|>jx/src/main/java/javax/lang/model/type/NoType.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.lang.model.type; import javax.lang.model.element.ExecutableElement; /** * A pseudo-type used where no actual type is appropriate. * The kinds of {@code NoType} are: * <ul> * <li>{@link TypeKind#VOID VOID} - corresponds to the keyword {@code void}. * <li>{@link TypeKind#PACKAGE PACKAGE} - the pseudo-type of a package element. * <li>{@link TypeKind#NONE NONE} - used in other cases * where no actual type is appropriate; for example, the superclass * of {@code java.lang.Object}. * </ul> * * @author <NAME> * @author <NAME> * @author <NAME>&eacute; * @see ExecutableElement#getReturnType() * @since 1.6 */ public interface NoType extends TypeMirror { } <|start_filename|>jx/src/main/java/javax/lang/model/element/PackageElement.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.lang.model.element; import javax.lang.model.util.Elements; import java.util.List; /** * Represents a package program element. Provides access to information * about the package and its members. * * @author <NAME> * @author <NAME> * @author <NAME>&eacute; * @see Elements#getPackageOf * @since 1.6 */ public interface PackageElement extends javax.lang.model.element.Element, QualifiedNameable { /** * Returns the fully qualified name of this package. * This is also known as the package's <i>canonical</i> name. * * @return the fully qualified name of this package, or an * empty name if this is an unnamed package */ javax.lang.model.element.Name getQualifiedName(); /** * Returns the simple name of this package. For an unnamed * package, an empty name is returned. * * @return the simple name of this package or an empty name if * this is an unnamed package */ @Override Name getSimpleName(); /** * Returns the {@linkplain NestingKind#TOP_LEVEL top-level} * classes and interfaces within this package. Note that * subpackages are <em>not</em> considered to be enclosed by a * package. * * @return the top-level classes and interfaces within this * package */ @Override List<? extends javax.lang.model.element.Element> getEnclosedElements(); /** * Returns {@code true} is this is an unnamed package and {@code * false} otherwise. * * @return {@code true} is this is an unnamed package and {@code * false} otherwise */ boolean isUnnamed(); /** * Returns {@code null} since a package is not enclosed by another * element. * * @return {@code null} */ @Override Element getEnclosingElement(); } <|start_filename|>jx/src/main/java/javax/lang/model/type/IntersectionType.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.lang.model.type; import java.util.List; import javax.lang.model.SourceVersion; /** * Represents an intersection type. * * <p>An intersection type can be either implicitly or explicitly * declared in a program. For example, the bound of the type parameter * {@code <T extends Number & Runnable>} is an (implicit) intersection * type. As of {@link javax.lang.model.SourceVersion#RELEASE_8 * RELEASE_8}, this is represented by an {@code IntersectionType} with * {@code Number} and {@code Runnable} as its bounds. * * in the * reference implementation an {@code IntersectionType} is used to * model the explicit target type of a cast expression. * @since 1.8 */ public interface IntersectionType extends TypeMirror { /** * Return the bounds comprising this intersection type. * * @return the bounds of this intersection types. */ List<? extends TypeMirror> getBounds(); } <|start_filename|>jx/src/main/java/javax/annotation/processing/FilerException.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.annotation.processing; import java.io.IOException; import javax.annotation.processing.Filer; /** * Indicates a {@link Filer} detected an attempt to open a file that * would violate the guarantees provided by the {@code Filer}. Those * guarantees include not creating the same file more than once, not * creating multiple files corresponding to the same type, and not * creating files for types with invalid names. * * @author <NAME> * @author <NAME> * @author <NAME>&eacute; * @since 1.6 */ public class FilerException extends IOException { static final long serialVersionUID = 8426423106453163293L; /** * Constructs an exception with the specified detail message. * * @param s the detail message, which should include the name of * the file attempting to be opened; may be {@code null} */ public FilerException(String s) { super(s); } } <|start_filename|>jx/src/main/java/javax/tools/ForwardingFileObject.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.tools; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.net.URI; /** * Forwards calls to a given file object. Subclasses of this class * might override some of these methods and might also provide * additional fields and methods. * * @param <F> the kind of file object forwarded to by this object * * @author <NAME>; * @since 1.6 */ public class ForwardingFileObject<F extends javax.tools.FileObject> implements FileObject { /** * The file object which all methods are delegated to. */ protected final F fileObject; /** * Creates a new instance of ForwardingFileObject. * * @param fileObject delegate to this file object */ protected ForwardingFileObject(F fileObject) { fileObject.getClass(); // null check this.fileObject = fileObject; } public URI toUri() { return fileObject.toUri(); } public String getName() { return fileObject.getName(); } /** * @throws IllegalStateException {@inheritDoc} * @throws UnsupportedOperationException {@inheritDoc} * @throws IOException {@inheritDoc} */ public InputStream openInputStream() throws IOException { return fileObject.openInputStream(); } /** * @throws IllegalStateException {@inheritDoc} * @throws UnsupportedOperationException {@inheritDoc} * @throws IOException {@inheritDoc} */ public OutputStream openOutputStream() throws IOException { return fileObject.openOutputStream(); } /** * @throws IllegalStateException {@inheritDoc} * @throws UnsupportedOperationException {@inheritDoc} * @throws IOException {@inheritDoc} */ public Reader openReader(boolean ignoreEncodingErrors) throws IOException { return fileObject.openReader(ignoreEncodingErrors); } /** * @throws IllegalStateException {@inheritDoc} * @throws UnsupportedOperationException {@inheritDoc} * @throws IOException {@inheritDoc} */ public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return fileObject.getCharContent(ignoreEncodingErrors); } /** * @throws IllegalStateException {@inheritDoc} * @throws UnsupportedOperationException {@inheritDoc} * @throws IOException {@inheritDoc} */ public Writer openWriter() throws IOException { return fileObject.openWriter(); } public long getLastModified() { return fileObject.getLastModified(); } public boolean delete() { return fileObject.delete(); } } <|start_filename|>jx/src/main/java/javax/annotation/processing/SupportedSourceVersion.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.annotation.processing; import javax.lang.model.SourceVersion; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * An annotation used to indicate the latest source version an * annotation processor supports. The {@link * Processor#getSupportedSourceVersion} method can construct its * result from the value of this annotation, as done by {@link * AbstractProcessor#getSupportedSourceVersion}. * * @author <NAME> * @author <NAME> * @author <NAME>&eacute; * @since 1.6 */ @Documented @Target(TYPE) @Retention(RUNTIME) public @interface SupportedSourceVersion { /** * Returns the latest supported source version. * * @return the latest supported source version */ SourceVersion value(); } <|start_filename|>jx/src/main/java/javax/lang/model/element/VariableElement.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.lang.model.element; import javax.lang.model.util.Elements; /** * Represents a field, {@code enum} constant, method or constructor * parameter, local variable, resource variable, or exception * parameter. * * @author <NAME> * @author <NAME> * @author <NAME>&eacute; * @since 1.6 */ public interface VariableElement extends javax.lang.model.element.Element { /** * Returns the value of this variable if this is a {@code final} * field initialized to a compile-time constant. Returns {@code * null} otherwise. The value will be of a primitive type or a * {@code String}. If the value is of a primitive type, it is * wrapped in the appropriate wrapper class (such as {@link * Integer}). * * <p>Note that not all {@code final} fields will have * constant values. In particular, {@code enum} constants are * <em>not</em> considered to be compile-time constants. To have a * constant value, a field's type must be either a primitive type * or {@code String}. * * @return the value of this variable if this is a {@code final} * field initialized to a compile-time constant, or {@code null} * otherwise * * @see Elements#getConstantExpression(Object) */ Object getConstantValue(); /** * Returns the simple name of this variable element. * * <p>For method and constructor parameters, the name of each * parameter must be distinct from the names of all other * parameters of the same executable. If the original source * names are not available, an implementation may synthesize names * subject to the distinctness requirement above. * * @return the simple name of this variable element */ @Override Name getSimpleName(); /** * Returns the enclosing element of this variable. * <p> * The enclosing element of a method or constructor parameter is * the executable declaring the parameter. * * @return the enclosing element of this variable */ @Override Element getEnclosingElement(); } <|start_filename|>jx/src/main/java/javax/lang/model/element/UnknownAnnotationValueException.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.lang.model.element; import javax.lang.model.UnknownEntityException; /** * Indicates that an unknown kind of annotation value was encountered. * This can occur if the language evolves and new kinds of annotation * values can be stored in an annotation. May be thrown by an * {@linkplain javax.lang.model.element.AnnotationValueVisitor annotation value visitor} to * indicate that the visitor was created for a prior version of the * language. * * @author <NAME> * @author <NAME> * @author <NAME>; * @see javax.lang.model.element.AnnotationValueVisitor#visitUnknown * @since 1.6 */ public class UnknownAnnotationValueException extends UnknownEntityException { private static final long serialVersionUID = 269L; private final transient javax.lang.model.element.AnnotationValue av; private final transient Object parameter; /** * Creates a new {@code UnknownAnnotationValueException}. The * {@code p} parameter may be used to pass in an additional * argument with information about the context in which the * unknown annotation value was encountered; for example, the * visit methods of {@link AnnotationValueVisitor} may pass in * their additional parameter. * * @param av the unknown annotation value, may be {@code null} * @param p an additional parameter, may be {@code null} */ public UnknownAnnotationValueException(javax.lang.model.element.AnnotationValue av, Object p) { super("Unknown annotation value: " + av); this.av = av; this.parameter = p; } /** * Returns the unknown annotation value. * The value may be unavailable if this exception has been * serialized and then read back in. * * @return the unknown element, or {@code null} if unavailable */ public AnnotationValue getUnknownAnnotationValue() { return av; } /** * Returns the additional argument. * * @return the additional argument */ public Object getArgument() { return parameter; } } <|start_filename|>jx/src/main/java/javax/lang/model/util/ElementFilter.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.lang.model.util; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; /** * Filters for selecting just the elements of interest from a * collection of elements. The returned sets and lists are new * collections and do use the argument as a backing store. The * methods in this class do not make any attempts to guard against * concurrent modifications of the arguments. The returned sets and * lists are mutable but unsafe for concurrent access. A returned set * has the same iteration order as the argument set to a method. * * <p>If iterables and sets containing {@code null} are passed as * arguments to methods in this class, a {@code NullPointerException} * will be thrown. * * <p>Note that a <i>static import</i> statement can make the text of * calls to the methods in this class more concise; for example: * * <blockquote><pre> * import static jx.lang.model.util.ElementFilter.*; * ... * {@code List<VariableElement>} fs = fieldsIn(someClass.getEnclosedElements()); * </pre></blockquote> * * @author <NAME> * @author <NAME> * @author <NAME>&eacute; * @author <NAME> * @since 1.6 */ public class ElementFilter { private static final Set<javax.lang.model.element.ElementKind> CONSTRUCTOR_KIND = Collections.unmodifiableSet(EnumSet.of(javax.lang.model.element.ElementKind.CONSTRUCTOR)); private static final Set<javax.lang.model.element.ElementKind> FIELD_KINDS = Collections.unmodifiableSet(EnumSet.of(javax.lang.model.element.ElementKind.FIELD, javax.lang.model.element.ElementKind.ENUM_CONSTANT)); private static final Set<javax.lang.model.element.ElementKind> METHOD_KIND = Collections.unmodifiableSet(EnumSet.of(javax.lang.model.element.ElementKind.METHOD)); private static final Set<javax.lang.model.element.ElementKind> PACKAGE_KIND = Collections.unmodifiableSet(EnumSet.of(javax.lang.model.element.ElementKind.PACKAGE)); private static final Set<javax.lang.model.element.ElementKind> TYPE_KINDS = Collections.unmodifiableSet(EnumSet.of(javax.lang.model.element.ElementKind.CLASS, javax.lang.model.element.ElementKind.ENUM, javax.lang.model.element.ElementKind.INTERFACE, javax.lang.model.element.ElementKind.ANNOTATION_TYPE)); private ElementFilter() { } // Do not instantiate. /** * Returns a list of fields in {@code elements}. * * @param elements the elements to filter * * @return a list of fields in {@code elements} */ public static List<javax.lang.model.element.VariableElement> fieldsIn(Iterable<? extends javax.lang.model.element.Element> elements) { return listFilter(elements, FIELD_KINDS, javax.lang.model.element.VariableElement.class); } /** * Returns a set of fields in {@code elements}. * * @param elements the elements to filter * * @return a set of fields in {@code elements} */ public static Set<javax.lang.model.element.VariableElement> fieldsIn(Set<? extends javax.lang.model.element.Element> elements) { return setFilter(elements, FIELD_KINDS, VariableElement.class); } /** * Returns a list of constructors in {@code elements}. * * @param elements the elements to filter * * @return a list of constructors in {@code elements} */ public static List<javax.lang.model.element.ExecutableElement> constructorsIn(Iterable<? extends javax.lang.model.element.Element> elements) { return listFilter(elements, CONSTRUCTOR_KIND, javax.lang.model.element.ExecutableElement.class); } /** * Returns a set of constructors in {@code elements}. * * @param elements the elements to filter * * @return a set of constructors in {@code elements} */ public static Set<javax.lang.model.element.ExecutableElement> constructorsIn(Set<? extends javax.lang.model.element.Element> elements) { return setFilter(elements, CONSTRUCTOR_KIND, javax.lang.model.element.ExecutableElement.class); } /** * Returns a list of methods in {@code elements}. * * @param elements the elements to filter * * @return a list of methods in {@code elements} */ public static List<javax.lang.model.element.ExecutableElement> methodsIn(Iterable<? extends javax.lang.model.element.Element> elements) { return listFilter(elements, METHOD_KIND, javax.lang.model.element.ExecutableElement.class); } /** * Returns a set of methods in {@code elements}. * * @param elements the elements to filter * * @return a set of methods in {@code elements} */ public static Set<javax.lang.model.element.ExecutableElement> methodsIn(Set<? extends javax.lang.model.element.Element> elements) { return setFilter(elements, METHOD_KIND, ExecutableElement.class); } /** * Returns a list of types in {@code elements}. * * @param elements the elements to filter * * @return a list of types in {@code elements} */ public static List<javax.lang.model.element.TypeElement> typesIn(Iterable<? extends javax.lang.model.element.Element> elements) { return listFilter(elements, TYPE_KINDS, javax.lang.model.element.TypeElement.class); } /** * Returns a set of types in {@code elements}. * * @param elements the elements to filter * * @return a set of types in {@code elements} */ public static Set<javax.lang.model.element.TypeElement> typesIn(Set<? extends javax.lang.model.element.Element> elements) { return setFilter(elements, TYPE_KINDS, TypeElement.class); } /** * Returns a list of packages in {@code elements}. * * @param elements the elements to filter * * @return a list of packages in {@code elements} */ public static List<javax.lang.model.element.PackageElement> packagesIn(Iterable<? extends javax.lang.model.element.Element> elements) { return listFilter(elements, PACKAGE_KIND, javax.lang.model.element.PackageElement.class); } /** * Returns a set of packages in {@code elements}. * * @param elements the elements to filter * * @return a set of packages in {@code elements} */ public static Set<javax.lang.model.element.PackageElement> packagesIn(Set<? extends javax.lang.model.element.Element> elements) { return setFilter(elements, PACKAGE_KIND, PackageElement.class); } // Assumes targetKinds and E are sensible. private static <E extends javax.lang.model.element.Element> List<E> listFilter(Iterable<? extends javax.lang.model.element.Element> elements, Set<javax.lang.model.element.ElementKind> targetKinds, Class<E> clazz) { List<E> list = new ArrayList<E>(); for (javax.lang.model.element.Element e : elements) { if (targetKinds.contains(e.getKind())) list.add(clazz.cast(e)); } return list; } // Assumes targetKinds and E are sensible. private static <E extends javax.lang.model.element.Element> Set<E> setFilter(Set<? extends javax.lang.model.element.Element> elements, Set<ElementKind> targetKinds, Class<E> clazz) { // Return set preserving iteration order of input set. Set<E> set = new LinkedHashSet<E>(); for (Element e : elements) { if (targetKinds.contains(e.getKind())) set.add(clazz.cast(e)); } return set; } } <|start_filename|>jx/src/main/java/javax/lang/model/element/Parameterizable.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.lang.model.element; import java.util.List; /** * A mixin interface for an element that has type parameters. * * @author <NAME> * @since 1.7 */ public interface Parameterizable extends Element { /** * Returns the formal type parameters of the type element in * declaration order. * * @return the formal type parameters, or an empty list * if there are none */ List<? extends TypeParameterElement> getTypeParameters(); } <|start_filename|>jx/src/main/java/javax/annotation/processing/Generated.java<|end_filename|> package javax.annotation.processing; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Retention(RetentionPolicy.SOURCE) @Target({ElementType.PACKAGE, ElementType.TYPE, ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.PARAMETER}) public @interface Generated { String[] value(); String date() default ""; String comments() default ""; } <|start_filename|>app/src/main/java/com/zeoflow/test/MainActivity.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zeoflow.test; import android.os.Bundle; import com.zeoflow.app.Activity; import com.zeoflow.jx.file.JavaFile; import com.zeoflow.jx.file.MethodSpec; import com.zeoflow.jx.file.TypeName; import com.zeoflow.jx.file.TypeSpec; import java.io.IOException; import javax.lang.model.element.Modifier; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String packageEx = "androidx.lifecycle.LiveData<java.util.List<java.lang.String>>"; log("" + TypeName.get(String.class).contains(String.class)); log("" + TypeName.get(packageEx).contains(String.class)); log("" + TypeName.get("androidx.lifecycle.Observer").contains(String.class)); log("" + TypeName.get(packageEx).disassemble().disassemble().disassemble().disassemble().toString()); log("" + TypeName.get(packageEx).assemble("java.lang.String").assemble(String.class).toString()); log("" + TypeName.get(String.class).assemble(Activity.class, true).toString()); log("" + TypeName.get(String.class).assemble(Activity.class, false).toString()); MethodSpec main = MethodSpec.methodBuilder("main") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(void.class) .addParameter(String[].class, "args") .addStatement("$T.out.println($S)", System.class, "Hello, JavaPoet!") .addStatement("String<T> name") .build(); MethodSpec main2 = MethodSpec.methodBuilder("getObs") .addModifiers(Modifier.PUBLIC) .returns(void.class) .addParameter(TypeName.get("com.Observable<T>"), "args") .addStatement("$T.out.println($S)", System.class, "Hello, JavaPoet!") .addStatement("String<T> name") .build(); TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld<Text, View>") .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addMethod(main) .addMethod(main2) .build(); JavaFile javaFile = JavaFile.builder("com.example.helloworld", helloWorld) .build(); try { javaFile.writeTo(System.out); } catch (IOException e) { e.printStackTrace(); } } } <|start_filename|>jx/src/main/java/javax/tools/Tool.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.tools; import javax.lang.model.SourceVersion; import java.io.InputStream; import java.io.OutputStream; import java.util.Set; /** * Common interface for tools that can be invoked from a program. * A tool is traditionally a command line program such as a compiler. * The set of tools available with a platform is defined by the * vendor. * * <p>Tools can be located using {@link * java.util.ServiceLoader#load(Class)}. * * @author <NAME> * @author <NAME>; * @author <NAME> * @since 1.6 */ public interface Tool { /** * Run the tool with the given I/O channels and arguments. By * convention a tool returns 0 for success and nonzero for errors. * Any diagnostics generated will be written to either {@code out} * or {@code err} in some unspecified format. * * @param in "standard" input; use System.in if null * @param out "standard" output; use System.out if null * @param err "standard" error; use System.err if null * @param arguments arguments to pass to the tool * * @return 0 for success; nonzero otherwise * * @throws NullPointerException if the array of arguments contains * any {@code null} elements. */ int run(InputStream in, OutputStream out, OutputStream err, String... arguments); /** * Gets the source versions of the Java&trade; programming language * supported by this tool. * * @return a set of supported source versions */ Set<SourceVersion> getSourceVersions(); } <|start_filename|>jx/src/main/java/javax/lang/model/type/TypeKind.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.lang.model.type; /** * The kind of a type mirror. * * <p>Note that it is possible additional type kinds will be added to * accommodate new, currently unknown, language structures added to * future versions of the Java&trade; programming language. * * @author <NAME> * @author <NAME> * @author <NAME>&eacute; * @see TypeMirror * @since 1.6 */ public enum TypeKind { /** * The primitive type {@code boolean}. */ BOOLEAN, /** * The primitive type {@code byte}. */ BYTE, /** * The primitive type {@code short}. */ SHORT, /** * The primitive type {@code int}. */ INT, /** * The primitive type {@code long}. */ LONG, /** * The primitive type {@code char}. */ CHAR, /** * The primitive type {@code float}. */ FLOAT, /** * The primitive type {@code double}. */ DOUBLE, /** * The pseudo-type corresponding to the keyword {@code void}. * * @see javax.lang.model.type.NoType */ VOID, /** * A pseudo-type used where no actual type is appropriate. * * @see javax.lang.model.type.NoType */ NONE, /** * The null type. */ NULL, /** * An array type. */ ARRAY, /** * A class or interface type. */ DECLARED, /** * A class or interface type that could not be resolved. */ ERROR, /** * A type variable. */ TYPEVAR, /** * A wildcard type argument. */ WILDCARD, /** * A pseudo-type corresponding to a package element. * * @see NoType */ PACKAGE, /** * A method, constructor, or initializer. */ EXECUTABLE, /** * An implementation-reserved type. * This is not the type you are looking for. */ OTHER, /** * A union type. * * @since 1.7 */ UNION, /** * An intersection type. * * @since 1.8 */ INTERSECTION; /** * Returns {@code true} if this kind corresponds to a primitive * type and {@code false} otherwise. * * @return {@code true} if this kind corresponds to a primitive type */ public boolean isPrimitive() { switch (this) { case BOOLEAN: case BYTE: case SHORT: case INT: case LONG: case CHAR: case FLOAT: case DOUBLE: return true; default: return false; } } } <|start_filename|>jx/src/main/java/javax/lang/model/UnknownEntityException.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.lang.model; import javax.lang.model.element.UnknownAnnotationValueException; import javax.lang.model.element.UnknownElementException; import javax.lang.model.type.UnknownTypeException; /** * Superclass of exceptions which indicate that an unknown kind of * entity was encountered. This situation can occur if the language * evolves and new kinds of constructs are introduced. Subclasses of * this exception may be thrown by visitors to indicate that the * visitor was created for a prior version of the language. * * <p>A common superclass for those exceptions allows a single catch * block to have code handling them uniformly. * * @author <NAME> * @see UnknownElementException * @see UnknownAnnotationValueException * @see UnknownTypeException * @since 1.7 */ public class UnknownEntityException extends RuntimeException { private static final long serialVersionUID = 269L; /** * Creates a new {@code UnknownEntityException} with the specified * detail message. * * @param message the detail message */ protected UnknownEntityException(String message) { super(message); } } <|start_filename|>jx/src/main/java/javax/annotation/processing/SupportedOptions.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.annotation.processing; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * An annotation used to indicate what options an annotation processor * supports. The {@link Processor#getSupportedOptions} method can * construct its result from the value of this annotation, as done by * {@link AbstractProcessor#getSupportedOptions}. Only {@linkplain * Processor#getSupportedOptions strings conforming to the * grammar} should be used as values. * * @author <NAME> * @author <NAME> * @author <NAME>&eacute; * @since 1.6 */ @Documented @Target(TYPE) @Retention(RUNTIME) public @interface SupportedOptions { /** * Returns the supported options. * * @return the supported options */ String[] value(); } <|start_filename|>jx/src/main/java/com/zeoflow/jx/file/ClassBean.java<|end_filename|> package com.zeoflow.jx.file; @SuppressWarnings({"unused", "RedundantSuppression"}) public class ClassBean { public String classPackage; public String className; public ClassBean(String classData) { int lastIndex = classData.lastIndexOf("."); if (lastIndex != -1) { this.classPackage = classData.substring(0, lastIndex); this.className = classData.substring(lastIndex + 1); } else { this.classPackage = classData; this.className = classData; } } public ClassBean(String classPackage, String className) { this.classPackage = classPackage; this.className = className; } } <|start_filename|>jx/src/main/java/javax/lang/model/element/TypeParameterElement.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.lang.model.element; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVariable; import java.util.List; /** * Represents a formal type parameter of a generic class, interface, method, * or constructor element. * A type parameter declares a {@link TypeVariable}. * * @author <NAME> * @author <NAME> * @author <NAME>&eacute; * @see TypeVariable * @since 1.6 */ public interface TypeParameterElement extends javax.lang.model.element.Element { /** * Returns the generic class, interface, method, or constructor that is * parameterized by this type parameter. * * @return the generic class, interface, method, or constructor that is * parameterized by this type parameter */ javax.lang.model.element.Element getGenericElement(); /** * Returns the bounds of this type parameter. * These are the types given by the {@code extends} clause * used to declare this type parameter. * If no explicit {@code extends} clause was used, * then {@code java.lang.Object} is considered to be the sole bound. * * @return the bounds of this type parameter, or an empty list if * there are none */ List<? extends TypeMirror> getBounds(); /** * Returns the {@linkplain TypeParameterElement#getGenericElement generic element} of this type parameter. * * @return the generic element of this type parameter */ @Override Element getEnclosingElement(); } <|start_filename|>jx/src/main/java/javax/tools/DiagnosticListener.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.tools; /** * Interface for receiving diagnostics from tools. * * @param <S> the type of source objects used by diagnostics received * by this listener * * @author <NAME> * @author <NAME>&eacute; * @since 1.6 */ public interface DiagnosticListener<S> { /** * Invoked when a problem is found. * * @param diagnostic a diagnostic representing the problem that * was found * * @throws NullPointerException if the diagnostic argument is * {@code null} and the implementation cannot handle {@code null} * arguments */ void report(Diagnostic<? extends S> diagnostic); } <|start_filename|>jx/src/main/java/javax/annotation/processing/Completion.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.annotation.processing; /** * A suggested {@linkplain Processor#getCompletions <em>completion</em>} for an * annotation. A completion is text meant to be inserted into a * program as part of an annotation. * * @author <NAME> * @author <NAME> * @author <NAME>&eacute; * @since 1.6 */ public interface Completion { /** * Returns the text of the suggested completion. * * @return the text of the suggested completion. */ String getValue(); /** * Returns an informative message about the completion. * * @return an informative message about the completion. */ String getMessage(); } <|start_filename|>jx/src/main/java/javax/lang/model/type/WildcardType.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.lang.model.type; /** * Represents a wildcard type argument. * Examples include: <pre><tt> * ? * ? extends Number * ? super T * </tt></pre> * * <p> A wildcard may have its upper bound explicitly set by an * {@code extends} clause, its lower bound explicitly set by a * {@code super} clause, or neither (but not both). * * @author <NAME> * @author <NAME> * @author <NAME>&eacute; * @since 1.6 */ public interface WildcardType extends TypeMirror { /** * Returns the upper bound of this wildcard. * If no upper bound is explicitly declared, * {@code null} is returned. * * @return the upper bound of this wildcard */ TypeMirror getExtendsBound(); /** * Returns the lower bound of this wildcard. * If no lower bound is explicitly declared, * {@code null} is returned. * * @return the lower bound of this wildcard */ TypeMirror getSuperBound(); } <|start_filename|>jx/src/main/java/javax/tools/JavaFileObject.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.tools; import javax.lang.model.element.Modifier; import javax.lang.model.element.NestingKind; /** * File abstraction for tools operating on Java&trade; programming language * source and class files. * * <p>All methods in this interface might throw a SecurityException if * a security exception occurs. * * <p>Unless explicitly allowed, all methods in this interface might * throw a NullPointerException if given a {@code null} argument. * * @author <NAME>&eacute; * @author <NAME> * @see JavaFileManager * @since 1.6 */ public interface JavaFileObject extends FileObject { /** * Gets the kind of this file object. * * @return the kind */ Kind getKind(); /** * Checks if this file object is compatible with the specified * simple name and kind. A simple name is a single identifier * (not qualified) as defined in * <cite>The Java&trade; Language Specification</cite>, * section 6.2 "Names and Identifiers". * * @param simpleName a simple name of a class * @param kind a kind * * @return {@code true} if this file object is compatible; false * otherwise */ boolean isNameCompatible(String simpleName, Kind kind); /** * Provides a hint about the nesting level of the class * represented by this file object. This method may return * {@link NestingKind#MEMBER} to mean * {@link NestingKind#LOCAL} or {@link NestingKind#ANONYMOUS}. * If the nesting level is not known or this file object does not * represent a class file this method returns {@code null}. * * @return the nesting kind, or {@code null} if the nesting kind * is not known */ NestingKind getNestingKind(); /** * Provides a hint about the access level of the class represented * by this file object. If the access level is not known or if * this file object does not represent a class file this method * returns {@code null}. * * @return the access level */ Modifier getAccessLevel(); /** * Kinds of JavaFileObjects. */ enum Kind { /** * Source files written in the Java programming language. For * example, regular files ending with {@code .java}. */ SOURCE(".java"), /** * Class files for the Java Virtual Machine. For example, * regular files ending with {@code .class}. */ CLASS(".class"), /** * HTML files. For example, regular files ending with {@code * .html}. */ HTML(".html"), /** * Any other kind. */ OTHER(""); /** * The extension which (by convention) is normally used for * this kind of file object. If no convention exists, the * empty string ({@code ""}) is used. */ public final String extension; Kind(String extension) { extension.getClass(); // null check this.extension = extension; } } } <|start_filename|>jx/src/main/java/javax/annotation/processing/RoundEnvironment.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.annotation.processing; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import java.lang.annotation.Annotation; import java.util.Set; /** * An annotation processing tool framework will {@linkplain * Processor#process provide an annotation processor with an object * implementing this interface} so that the processor can query for * information about a round of annotation processing. * * @author <NAME> * @author <NAME> * @author <NAME>; * @since 1.6 */ public interface RoundEnvironment { /** * Returns {@code true} if types generated by this round will not * be subject to a subsequent round of annotation processing; * returns {@code false} otherwise. * * @return {@code true} if types generated by this round will not * be subject to a subsequent round of annotation processing; * returns {@code false} otherwise */ boolean processingOver(); /** * Returns {@code true} if an error was raised in the prior round * of processing; returns {@code false} otherwise. * * @return {@code true} if an error was raised in the prior round * of processing; returns {@code false} otherwise */ boolean errorRaised(); /** * Returns the root elements for annotation processing generated * by the prior round. * * @return the root elements for annotation processing generated * by the prior round, or an empty set if there were none */ Set<? extends Element> getRootElements(); /** * Returns the elements annotated with the given annotation type. * The annotation may appear directly or be inherited. Only * package elements and type elements <i>included</i> in this * round of annotation processing, or declarations of members, * constructors, parameters, or type parameters declared within * those, are returned. Included type elements are {@linkplain * #getRootElements root types} and any member types nested within * them. Elements in a package are not considered included simply * because a {@code package-info} file for that package was * created. * * @param a annotation type being requested * * @return the elements annotated with the given annotation type, * or an empty set if there are none * * @throws IllegalArgumentException if the argument does not * represent an annotation type */ Set<? extends Element> getElementsAnnotatedWith(TypeElement a); /** * Returns the elements annotated with the given annotation type. * The annotation may appear directly or be inherited. Only * package elements and type elements <i>included</i> in this * round of annotation processing, or declarations of members, * constructors, parameters, or type parameters declared within * those, are returned. Included type elements are {@linkplain * #getRootElements root types} and any member types nested within * them. Elements in a package are not considered included simply * because a {@code package-info} file for that package was * created. * * @param a annotation type being requested * * @return the elements annotated with the given annotation type, * or an empty set if there are none * * @throws IllegalArgumentException if the argument does not * represent an annotation type */ Set<? extends Element> getElementsAnnotatedWith(Class<? extends Annotation> a); } <|start_filename|>jx/src/main/java/javax/lang/model/type/MirroredTypesException.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.lang.model.type; import java.io.IOException; import java.io.ObjectInputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.lang.model.element.Element; /** * Thrown when an application attempts to access a sequence of {@link * Class} objects each corresponding to a {@link TypeMirror}. * * @author <NAME> * @author <NAME> * @author <NAME>&eacute; * @see MirroredTypeException * @see Element#getAnnotation(Class) * @since 1.6 */ public class MirroredTypesException extends RuntimeException { private static final long serialVersionUID = 269; transient List<? extends TypeMirror> types; // cannot be serialized /* * Trusted constructor to be called by MirroredTypeException. */ MirroredTypesException(String message, TypeMirror type) { super(message); List<TypeMirror> tmp = (new ArrayList<TypeMirror>()); tmp.add(type); types = Collections.unmodifiableList(tmp); } /** * Constructs a new MirroredTypesException for the specified types. * * @param types the types being accessed */ public MirroredTypesException(List<? extends TypeMirror> types) { super("Attempt to access Class objects for TypeMirrors " + (types = // defensive copy new ArrayList<TypeMirror>(types)).toString()); this.types = Collections.unmodifiableList(types); } /** * Returns the type mirrors corresponding to the types being accessed. * The type mirrors may be unavailable if this exception has been * serialized and then read back in. * * @return the type mirrors in construction order, or {@code null} if unavailable */ public List<? extends TypeMirror> getTypeMirrors() { return types; } /** * Explicitly set all transient fields. */ private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); types = null; } } <|start_filename|>jx/src/main/java/javax/lang/model/element/Modifier.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.lang.model.element; /** * Represents a modifier on a program element such * as a class, method, or field. * * <p>Not all modifiers are applicable to all kinds of elements. * When two or more modifiers appear in the source code of an element * then it is customary, though not required, that they appear in the same * order as the constants listed in the detail section below. * * <p>Note that it is possible additional modifiers will be added in * future versions of the platform. * * @author <NAME> * @author <NAME> * @author <NAME>&eacute; * @since 1.6 */ public enum Modifier { // See JLS sections 8.1.1, 8.3.1, 8.4.3, 8.8.3, and 9.1.1. // java.lang.reflect.Modifier includes INTERFACE, but that's a VMism. /** * The modifier {@code public} */ PUBLIC, /** * The modifier {@code protected} */ PROTECTED, /** * The modifier {@code private} */ PRIVATE, /** * The modifier {@code abstract} */ ABSTRACT, /** * The modifier {@code default} * * @since 1.8 */ DEFAULT, /** * The modifier {@code static} */ STATIC, /** * The modifier {@code final} */ FINAL, /** * The modifier {@code transient} */ TRANSIENT, /** * The modifier {@code volatile} */ VOLATILE, /** * The modifier {@code synchronized} */ SYNCHRONIZED, /** * The modifier {@code native} */ NATIVE, /** * The modifier {@code strictfp} */ STRICTFP; /** * Returns this modifier's name in lowercase. */ public String toString() { return name().toLowerCase(java.util.Locale.US); } } <|start_filename|>jx/src/main/java/javax/lang/model/util/AbstractTypeVisitor6.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.lang.model.util; import javax.lang.model.SourceVersion; import javax.lang.model.type.IntersectionType; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVisitor; import javax.lang.model.type.UnionType; import javax.lang.model.type.UnknownTypeException; /** * A skeletal visitor of types with default behavior appropriate for * the {@link SourceVersion#RELEASE_6 RELEASE_6} * source version. * * <p> <b>WARNING:</b> The {@code TypeVisitor} interface implemented * by this class may have methods added to it in the future to * accommodate new, currently unknown, language structures added to * future versions of the Java&trade; programming language. * Therefore, methods whose names begin with {@code "visit"} may be * added to this class in the future; to avoid incompatibilities, * classes which extend this class should not declare any instance * methods with names beginning with {@code "visit"}. * * <p>When such a new visit method is added, the default * implementation in this class will be to call the {@link * #visitUnknown visitUnknown} method. A new abstract type visitor * class will also be introduced to correspond to the new language * level; this visitor will have different default behavior for the * visit method in question. When the new visitor is introduced, all * or portions of this visitor may be deprecated. * * <p>Note that adding a default implementation of a new visit method * in a visitor class will occur instead of adding a <em>default * method</em> directly in the visitor interface since a Java SE 8 * language feature cannot be used to this version of the API since * this version is required to be runnable on Java SE 7 * implementations. Future versions of the API that are only required * to run on Java SE 8 and later may take advantage of default methods * in this situation. * * @param <R> the return type of this visitor's methods. Use {@link * Void} for visitors that do not need to return results. * @param <P> the type of the additional parameter to this visitor's * methods. Use {@code Void} for visitors that do not need an * additional parameter. * * @author <NAME> * @author <NAME> * @author <NAME>&eacute; * @see AbstractTypeVisitor7 * @see AbstractTypeVisitor8 * @since 1.6 */ public abstract class AbstractTypeVisitor6<R, P> implements TypeVisitor<R, P> { /** * Constructor for concrete subclasses to call. */ protected AbstractTypeVisitor6() { } /** * Visits any type mirror as if by passing itself to that type * mirror's {@link javax.lang.model.type.TypeMirror#accept accept} method. The * invocation {@code v.visit(t, p)} is equivalent to {@code * t.accept(v, p)}. * * @param t the type to visit * @param p a visitor-specified parameter * * @return a visitor-specified result */ public final R visit(javax.lang.model.type.TypeMirror t, P p) { return t.accept(this, p); } /** * Visits any type mirror as if by passing itself to that type * mirror's {@link javax.lang.model.type.TypeMirror#accept accept} method and passing * {@code null} for the additional parameter. The invocation * {@code v.visit(t)} is equivalent to {@code t.accept(v, null)}. * * @param t the type to visit * * @return a visitor-specified result */ public final R visit(javax.lang.model.type.TypeMirror t) { return t.accept(this, null); } /** * Visits a {@code UnionType} element by calling {@code * visitUnknown}. * * @param t {@inheritDoc} * @param p {@inheritDoc} * * @return the result of {@code visitUnknown} * * @since 1.7 */ public R visitUnion(UnionType t, P p) { return visitUnknown(t, p); } /** * Visits an {@code IntersectionType} element by calling {@code * visitUnknown}. * * @param t {@inheritDoc} * @param p {@inheritDoc} * * @return the result of {@code visitUnknown} * * @since 1.8 */ public R visitIntersection(IntersectionType t, P p) { return visitUnknown(t, p); } /** * {@inheritDoc} * * <p> The default implementation of this method in {@code * AbstractTypeVisitor6} will always throw {@code * UnknownTypeException}. This behavior is not required of a * subclass. * * @param t the type to visit * * @return a visitor-specified result * * @throws javax.lang.model.type.UnknownTypeException a visitor implementation may optionally throw this exception */ public R visitUnknown(TypeMirror t, P p) { throw new UnknownTypeException(t, p); } } <|start_filename|>jx/src/main/java/javax/lang/model/type/UnionType.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.lang.model.type; import javax.lang.model.SourceVersion; import java.util.List; /** * Represents a union type. * <p> * As of the {@link SourceVersion#RELEASE_7 * RELEASE_7} source version, union types can appear as the type * of a multi-catch exception parameter. * * @since 1.7 */ public interface UnionType extends javax.lang.model.type.TypeMirror { /** * Return the alternatives comprising this union type. * * @return the alternatives comprising this union type. */ List<? extends TypeMirror> getAlternatives(); } <|start_filename|>jx/src/main/java/javax/tools/DiagnosticCollector.java<|end_filename|> /* * Copyright (C) 2021 ZeoFlow SRL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.tools; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Provides an easy way to collect diagnostics in a list. * * @param <S> the type of source objects used by diagnostics received * by this object * * @author <NAME>&eacute; * @since 1.6 */ public final class DiagnosticCollector<S> implements DiagnosticListener<S> { private final List<javax.tools.Diagnostic<? extends S>> diagnostics = Collections.synchronizedList(new ArrayList<javax.tools.Diagnostic<? extends S>>()); public void report(javax.tools.Diagnostic<? extends S> diagnostic) { diagnostic.getClass(); // null check diagnostics.add(diagnostic); } /** * Gets a list view of diagnostics collected by this object. * * @return a list view of diagnostics */ public List<Diagnostic<? extends S>> getDiagnostics() { return Collections.unmodifiableList(diagnostics); } }
pittayabuakhaw/jx
<|start_filename|>grepWinNP3/sktoolslib_mod/HotKeyCtrl.h<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012, 2020 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #pragma once #include <windows.h> // does not implement HKM_SETRULES class CHotKeyCtrl { public: CHotKeyCtrl(void); virtual ~CHotKeyCtrl(void); BOOL ConvertEditToHotKeyCtrl(HWND hwndCtl); BOOL ConvertEditToHotKeyCtrl(HWND hwndParent, UINT uiCtlId); void SetHotKey(WPARAM hk); WPARAM GetHotKey(); private: HWND m_hWnd; WNDPROC m_pfnOrigCtlProc; static LRESULT CALLBACK _HotKeyProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); HHOOK kb_hook; static LRESULT CALLBACK _KeyboardProc(int code, WPARAM wParam, LPARAM lParam); void SetHKText(WORD hk); bool controldown; bool shiftdown; bool menudown; bool lwindown; wchar_t controltext[MAX_PATH]; wchar_t shifttext[MAX_PATH]; wchar_t menutext[MAX_PATH]; wchar_t lwintext[MAX_PATH]; WORD hotkey; }; <|start_filename|>language/DoReverseMuiLoc.cmd<|end_filename|> @echo off setlocal rem for DLL generation: Project-Config: Linker: Manifest: Generate: NO (/MANIFEST:NO) rem en-US mkdir "$(TargetDir)..\en-US" ::"$(UCRTContentRoot)bin\$(WindowsTargetPlatformVersion)\x86\muirct.exe" -q "$(SolutionDir)language\DoReverseMuiLoc.rcconfig" -v 2 -x $(LangID) -g 0x0409 "$(TargetDir)$(TargetFileName)" "$(TargetDir)..\np3lng.dll" "$(TargetDir)..\en-US\np3lng.dll.mui" rem de-DE, fr-FR, es-ES, af-AF mkdir "$(TargetDir)..\de-DE" "$(UCRTContentRoot)bin\$(WindowsTargetPlatformVersion)\x86\muirct.exe" -q "$(SolutionDir)language\DoReverseMuiLoc.rcconfig" -v 2 -x $(LangID) -g 0x0409 "$(TargetDir)$(TargetFileName)" "$(TargetDir)$(TargetFileName).discard" "$(TargetDir)..\de-DE\np3lng.dll.mui" ::~~~for %%F in ($(TargetDir)*.dll.mui) do "$(UCRTContentRoot)bin\$(WindowsTargetPlatformVersion)\x86\muirct.exe" -c "$(TargetDir)np3lng.dll" -e "%%F" "$(UCRTContentRoot)bin\$(WindowsTargetPlatformVersion)\x86\muirct.exe" -c "$(TargetDir)np3lng.dll" -e "$(TargetDir)de-DE\np3lng.dll.mui" "$(UCRTContentRoot)bin\$(WindowsTargetPlatformVersion)\x86\muirct.exe" -c "$(TargetDir)np3lng.dll" -e "$(TargetDir)fr-FR\np3lng.dll.mui" "$(UCRTContentRoot)bin\$(WindowsTargetPlatformVersion)\x86\muirct.exe" -c "$(TargetDir)np3lng.dll" -e "$(TargetDir)es-ES\np3lng.dll.mui" "$(UCRTContentRoot)bin\$(WindowsTargetPlatformVersion)\x86\muirct.exe" -c "$(TargetDir)np3lng.dll" -e "$(TargetDir)af-AF\np3lng.dll.mui" :: --- OLD BATCH --- set MUIRCT_EXE=C:\Program Files (x86)\Windows Kits\10\bin\10.0.17134.0\x86\muirct.exe set COMPDIR=.\Bin\Debug_x64_v141 mkdir "%COMPDIR%\en-US" "%MUIRCT_EXE%" -q DoReverseMuiLoc.rcconfig -v 2 -x 0x0409 -g 0x0409 "%COMPDIR%\lng\np3_en_us.dll" "%COMPDIR%\np3lng.dll" "%COMPDIR%\en-US\np3lng.dll.mui" "%MUIRCT_EXE%" -c "%COMPDIR%\np3lng.dll" -e "%COMPDIR%\en-US\np3lng.dll.mui" mkdir "%COMPDIR%\de-DE" "%MUIRCT_EXE%" -q DoReverseMuiLoc.rcconfig -v 2 -x 0x0407 -g 0x0409 "%COMPDIR%\lng\np3_de_de.dll" "%COMPDIR%\lng\np3lng_de_discard.dll" "%COMPDIR%\de-DE\np3lng.dll.mui" "%MUIRCT_EXE%" -c "%COMPDIR%\np3lng.dll" -e "%COMPDIR%\de-DE\np3lng.dll.mui" mkdir "%COMPDIR%\es-ES" "%MUIRCT_EXE%" -q DoReverseMuiLoc.rcconfig -v 2 -x 0x0C0A -g 0x0409 "%COMPDIR%\lng\np3_es_es.dll" "%COMPDIR%\lng\np3lng_es_discard.dll" "%COMPDIR%\es-ES\np3lng.dll.mui" "%MUIRCT_EXE%" -c "%COMPDIR%\np3lng.dll" -e "%COMPDIR%\es-ES\np3lng.dll.mui" mkdir "%COMPDIR%\fr-FR" "%MUIRCT_EXE%" -q DoReverseMuiLoc.rcconfig -v 2 -x 0x040C -g 0x0409 "%COMPDIR%\lng\np3_fr_fr.dll" "%COMPDIR%\lng\np3lng_fr_discard.dll" "%COMPDIR%\fr-FR\np3lng.dll.mui" "%MUIRCT_EXE%" -c "%COMPDIR%\np3lng.dll" -e "%COMPDIR%\fr-FR\np3lng.dll.mui" endlocal pause <|start_filename|>grepWinNP3/sktoolslib_mod/JumpListHelpers.h<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2018, 2020 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #pragma once #include <wrl.h> #include <Shobjidl.h> /// Sets the application ID HRESULT SetAppID(LPCWSTR appID); /// creates an IShellLink object with the specified arguments /// note: the shell link is created for the current process exe path /// \param pszArguments the command line arguments to pass to this application /// \param pszTitle the title of the link which appears in the jump list /// \param iconIndex the index of the icon. Note this is NOT the icon ID but the number of the icon as it appears in the compiled resources /// \param asAdmin if true, the link is executed with "runas" HRESULT CreateShellLink(PCWSTR pszArguments, PCWSTR pszTitle, int iconIndex, bool asAdmin, Microsoft::WRL::ComPtr<IShellLink> *ppsl); /// creates an IShellLink that is a separator HRESULT CreateSeparatorLink(Microsoft::WRL::ComPtr<IShellLink> *ppsl); /// checks if an IShellItem is in an IObjectArray bool IsItemInArray(IShellItem *psi, IObjectArray *poaRemoved); /// removes the existing jump list HRESULT DeleteJumpList(LPCWSTR appID); /// sets the relaunch command for the specified window. /// use this to specify command line parameters for the default jump list command which starts the pinned application HRESULT SetRelaunchCommand(HWND hWnd, LPCWSTR appID, LPCWSTR commandLine, LPCWSTR dispName, LPCWSTR icon = nullptr); <|start_filename|>grepWinNP3/sktoolslib_mod/AeroControls.cpp<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012, 2014, 2017, 2020-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "AeroControls.h" #include <memory> #include <vssym32.h> enum ControlType { Static, Button, Progressbar }; #ifndef RECTWIDTH # define RECTWIDTH(rc) ((rc).right - (rc).left) #endif #ifndef RECTHEIGHT # define RECTHEIGHT(rc) ((rc).bottom - (rc).top) #endif using namespace Gdiplus; #pragma comment(lib, "gdiplus.lib") #pragma comment(lib, "comctl32.lib") AeroControlBase::AeroControlBase() { GdiplusStartupInput gdiplusStartupInput; m_dwm.Initialize(); m_theme.Initialize(); GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, nullptr); } AeroControlBase::~AeroControlBase() { for (std::map<HWND, UINT_PTR>::const_iterator it = subClassedControls.begin(); it != subClassedControls.end(); ++it) { RemoveWindowSubclass(it->first, SubclassProc, it->second); } GdiplusShutdown(gdiplusToken); } bool AeroControlBase::SubclassControl(HWND hControl) { bool bRet = false; if (!m_dwm.IsDwmCompositionEnabled()) return bRet; wchar_t szWndClassName[MAX_PATH]; if (GetClassName(hControl, szWndClassName, _countof(szWndClassName))) { if (!wcscmp(szWndClassName, WC_STATIC)) { bRet = !!SetWindowSubclass(hControl, SubclassProc, Static, reinterpret_cast<DWORD_PTR>(this)); subClassedControls[hControl] = Static; } if (!wcscmp(szWndClassName, WC_BUTTON)) { bRet = !!SetWindowSubclass(hControl, SubclassProc, Button, reinterpret_cast<DWORD_PTR>(this)); subClassedControls[hControl] = Button; } if (!wcscmp(szWndClassName, PROGRESS_CLASS)) { bRet = !!SetWindowSubclass(hControl, SubclassProc, Progressbar, reinterpret_cast<DWORD_PTR>(this)); subClassedControls[hControl] = Progressbar; } } return bRet; } LRESULT AeroControlBase::SubclassProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uidSubclass, DWORD_PTR dwRefData) { AeroControlBase* pThis = reinterpret_cast<AeroControlBase*>(dwRefData); if (pThis) { if (pThis->m_dwm.IsDwmCompositionEnabled()) { switch (uidSubclass) { case Static: return pThis->StaticWindowProc(hWnd, uMsg, wParam, lParam); case Button: return pThis->ButtonWindowProc(hWnd, uMsg, wParam, lParam); case Progressbar: return pThis->ProgressbarWindowProc(hWnd, uMsg, wParam, lParam); } } } return DefSubclassProc(hWnd, uMsg, wParam, lParam); } LRESULT AeroControlBase::StaticWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_SETTEXT: case WM_ENABLE: case WM_STYLECHANGED: { LRESULT res = DefSubclassProc(hWnd, uMsg, wParam, lParam); InvalidateRgn(hWnd, nullptr, FALSE); return res; } case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); if (hdc) { HDC hdcPaint = nullptr; RECT rcClient; GetClientRect(hWnd, &rcClient); LONG_PTR dwStyle = GetWindowLongPtr(hWnd, GWL_STYLE); LONG_PTR dwStyleEx = GetWindowLongPtr(hWnd, GWL_EXSTYLE); HTHEME hTheme = m_theme.OpenThemeData(nullptr, L"ControlPanelStyle"); if (hTheme) { HPAINTBUFFER hBufferedPaint = m_theme.BeginBufferedPaint(hdc, &rcClient, BPBF_TOPDOWNDIB, nullptr, &hdcPaint); if (hdcPaint) { PatBlt(hdcPaint, 0, 0, RECTWIDTH(rcClient), RECTHEIGHT(rcClient), BLACKNESS); m_theme.BufferedPaintSetAlpha(hBufferedPaint, &ps.rcPaint, 0x00); LONG_PTR dwStaticStyle = dwStyle & 0x1F; if (dwStaticStyle == SS_ICON || dwStaticStyle == SS_BITMAP) { bool bIcon = dwStaticStyle == SS_ICON; HANDLE hBmpIco = reinterpret_cast<HANDLE>(SendMessage(hWnd, STM_GETIMAGE, bIcon ? IMAGE_ICON : IMAGE_BITMAP, NULL)); if (hBmpIco) { std::unique_ptr<Bitmap> pBmp(bIcon ? new Bitmap(static_cast<HICON>(hBmpIco)) : new Bitmap(static_cast<HBITMAP>(hBmpIco), nullptr)); std::unique_ptr<Graphics> myGraphics(new Graphics(hdcPaint)); std::unique_ptr<CachedBitmap> pcbmp(new CachedBitmap(pBmp.get(), myGraphics.get())); myGraphics->DrawCachedBitmap(pcbmp.get(), 0, 0); } } else if (SS_BLACKRECT == dwStaticStyle || SS_GRAYRECT == dwStaticStyle || SS_WHITERECT == dwStaticStyle) { ARGB argb = 0L; switch (dwStaticStyle) { case SS_BLACKRECT: argb = 0xFF000000; break; case SS_GRAYRECT: argb = 0xFF808080; break; case SS_WHITERECT: argb = 0xFFFFFFFF; break; default: break; } Color clr(argb); FillRect(&rcClient, hdcPaint, clr); } else if (SS_BLACKFRAME == dwStaticStyle || SS_GRAYFRAME == dwStaticStyle || SS_WHITEFRAME == dwStaticStyle) { ARGB argb = 0L; switch (dwStaticStyle) { case SS_BLACKFRAME: argb = 0xFF000000; break; case SS_GRAYFRAME: argb = 0xFF808080; break; case SS_WHITEFRAME: argb = 0xFFFFFFFF; break; default: break; } Color clr(argb); DrawRect(&rcClient, hdcPaint, DashStyleSolid, clr, 1.0); } else { DTTOPTS dttOpts = {sizeof(DTTOPTS)}; dttOpts.dwFlags = DTT_COMPOSITED | DTT_GLOWSIZE; dttOpts.crText = RGB(255, 255, 255); dttOpts.iGlowSize = 12; // Default value m_theme.DetermineGlowSize(&dttOpts.iGlowSize); HFONT hFontOld = reinterpret_cast<HFONT>(SendMessage(hWnd, WM_GETFONT, 0L, 0L)); if (hFontOld) hFontOld = static_cast<HFONT>(SelectObject(hdcPaint, hFontOld)); int iLen = GetWindowTextLength(hWnd); if (iLen) { iLen += 5; // 1 for terminating zero, 4 for DT_MODIFYSTRING LPWSTR szText = static_cast<LPWSTR>(LocalAlloc(LPTR, sizeof(WCHAR) * iLen)); if (szText) { iLen = GetWindowTextW(hWnd, szText, iLen); if (iLen) { DWORD dwFlags = DT_WORDBREAK; switch (dwStaticStyle) { case SS_CENTER: dwFlags |= DT_CENTER; break; case SS_RIGHT: dwFlags |= DT_RIGHT; break; case SS_LEFTNOWORDWRAP: dwFlags &= ~DT_WORDBREAK; break; } if (dwStyle & SS_CENTERIMAGE) { dwFlags |= DT_VCENTER; dwFlags &= ~DT_WORDBREAK; } if (dwStyle & SS_ENDELLIPSIS) dwFlags |= DT_END_ELLIPSIS | DT_MODIFYSTRING; else if (dwStyle & SS_PATHELLIPSIS) dwFlags |= DT_PATH_ELLIPSIS | DT_MODIFYSTRING; else if (dwStyle & SS_WORDELLIPSIS) dwFlags |= DT_WORD_ELLIPSIS | DT_MODIFYSTRING; if (dwStyleEx & WS_EX_RIGHT) dwFlags |= DT_RIGHT; if (dwStyle & SS_NOPREFIX) dwFlags |= DT_NOPREFIX; m_theme.DrawThemeTextEx(hTheme, hdcPaint, 0, 0, szText, -1, dwFlags, &rcClient, &dttOpts); if (dwStyle & SS_SUNKEN || dwStyle & WS_BORDER) DrawRect(&rcClient, hdcPaint, DashStyleSolid, Color(0xFF, 0, 0, 0), 1.0); } LocalFree(szText); } } if (hFontOld) { SelectObject(hdcPaint, hFontOld); hFontOld = nullptr; } } m_theme.EndBufferedPaint(hBufferedPaint, TRUE); } m_theme.CloseThemeData(hTheme); } } EndPaint(hWnd, &ps); return 1; } case WM_NCDESTROY: case WM_DESTROY: RemoveWindowSubclass(hWnd, SubclassProc, Static); subClassedControls.erase(hWnd); break; } return DefSubclassProc(hWnd, uMsg, wParam, lParam); } LRESULT AeroControlBase::ButtonWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_SETTEXT: case WM_ENABLE: case WM_STYLECHANGED: { LRESULT res = DefSubclassProc(hWnd, uMsg, wParam, lParam); InvalidateRgn(hWnd, nullptr, FALSE); return res; } case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); if (hdc) { LONG_PTR dwStyle = GetWindowLongPtr(hWnd, GWL_STYLE); LONG_PTR dwButtonStyle = LOWORD(dwStyle); LONG_PTR dwButtonType = dwButtonStyle & 0xF; RECT rcClient; GetClientRect(hWnd, &rcClient); if ((dwButtonType & BS_GROUPBOX) == BS_GROUPBOX) { /// /// it must be a group box /// HTHEME hTheme = m_theme.OpenThemeData(hWnd, L"Button"); if (hTheme) { HDC hdcPaint = nullptr; BP_PAINTPARAMS params = {sizeof(BP_PAINTPARAMS)}; params.dwFlags = BPPF_ERASE; RECT rcExclusion = rcClient; params.prcExclude = &rcExclusion; /// /// We have to calculate the exclusion rect and therefore /// calculate the font height. We select the control's font /// into the DC and fake a drawing operation: /// HFONT hFontOld = reinterpret_cast<HFONT>(SendMessage(hWnd, WM_GETFONT, 0L, 0L)); if (hFontOld) hFontOld = static_cast<HFONT>(SelectObject(hdc, hFontOld)); RECT rcDraw = rcClient; DWORD dwFlags = DT_SINGLELINE; /// /// we use uppercase A to determine the height of text, so we /// can draw the upper line of the groupbox: /// DrawTextW(hdc, L"A", -1, &rcDraw, dwFlags | DT_CALCRECT); if (hFontOld) { SelectObject(hdc, hFontOld); hFontOld = nullptr; } InflateRect(&rcExclusion, -1, -1 * RECTHEIGHT(rcDraw)); HPAINTBUFFER hBufferedPaint = m_theme.BeginBufferedPaint(hdc, &rcClient, BPBF_TOPDOWNDIB, &params, &hdcPaint); if (hdcPaint) { /// /// now we again retrieve the font, but this time we select it into /// the buffered DC: /// hFontOld = reinterpret_cast<HFONT>(SendMessage(hWnd, WM_GETFONT, 0L, 0L)); if (hFontOld) hFontOld = static_cast<HFONT>(SelectObject(hdcPaint, hFontOld)); PatBlt(hdcPaint, 0, 0, RECTWIDTH(rcClient), RECTHEIGHT(rcClient), BLACKNESS); m_theme.BufferedPaintSetAlpha(hBufferedPaint, &ps.rcPaint, 0x00); int iPartId = BP_GROUPBOX; int iState = GetStateFromBtnState(dwStyle, FALSE, FALSE, 0L, iPartId, FALSE); DTTOPTS dttOpts = {sizeof(DTTOPTS)}; dttOpts.dwFlags = DTT_COMPOSITED | DTT_GLOWSIZE; dttOpts.crText = RGB(255, 255, 255); dttOpts.iGlowSize = 12; // Default value m_theme.DetermineGlowSize(&dttOpts.iGlowSize); COLORREF cr = RGB(0x00, 0x00, 0x00); GetEditBorderColor(hWnd, &cr); /// /// add the alpha value: /// cr |= 0xff000000; std::unique_ptr<Pen> myPen(new Pen(Color(cr), 1)); std::unique_ptr<Graphics> myGraphics(new Graphics(hdcPaint)); int iY = RECTHEIGHT(rcDraw) / 2; Rect rr = Rect(rcClient.left, rcClient.top + iY, RECTWIDTH(rcClient), RECTHEIGHT(rcClient) - iY - 1); GraphicsPath path; GetRoundRectPath(&path, rr, 10); myGraphics->DrawPath(myPen.get(), &path); //myGraphics->DrawRectangle(myPen, rcClient.left, rcClient.top + iY, // RECTWIDTH(rcClient)-1, RECTHEIGHT(rcClient) - iY-1); myGraphics.reset(); myPen.reset(); int iLen = GetWindowTextLength(hWnd); if (iLen) { iLen += 5; // 1 for terminating zero, 4 for DT_MODIFYSTRING LPWSTR szText = static_cast<LPWSTR>(LocalAlloc(LPTR, sizeof(WCHAR) * iLen)); if (szText) { iLen = GetWindowTextW(hWnd, szText, iLen); if (iLen) { int iX = RECTWIDTH(rcDraw); rcDraw = rcClient; rcDraw.left += iX; DrawTextW(hdcPaint, szText, -1, &rcDraw, dwFlags | DT_CALCRECT); PatBlt(hdcPaint, rcDraw.left, rcDraw.top, RECTWIDTH(rcDraw) + 3, RECTHEIGHT(rcDraw), BLACKNESS); rcDraw.left++; rcDraw.right++; m_theme.DrawThemeTextEx(hTheme, hdcPaint, iPartId, iState, szText, -1, dwFlags, &rcDraw, &dttOpts); } LocalFree(szText); } } if (hFontOld) { SelectObject(hdcPaint, hFontOld); hFontOld = nullptr; } m_theme.EndBufferedPaint(hBufferedPaint, TRUE); } m_theme.CloseThemeData(hTheme); } } else if (dwButtonType == BS_CHECKBOX || dwButtonType == BS_AUTOCHECKBOX || dwButtonType == BS_3STATE || dwButtonType == BS_AUTO3STATE || dwButtonType == BS_RADIOBUTTON || dwButtonType == BS_AUTORADIOBUTTON) { HTHEME hTheme = m_theme.OpenThemeData(hWnd, L"Button"); if (hTheme) { HDC hdcPaint = nullptr; BP_PAINTPARAMS params = {sizeof(BP_PAINTPARAMS)}; params.dwFlags = BPPF_ERASE; HPAINTBUFFER hBufferedPaint = m_theme.BeginBufferedPaint(hdc, &rcClient, BPBF_TOPDOWNDIB, &params, &hdcPaint); if (hdcPaint) { PatBlt(hdcPaint, 0, 0, RECTWIDTH(rcClient), RECTHEIGHT(rcClient), BLACKNESS); m_theme.BufferedPaintSetAlpha(hBufferedPaint, &ps.rcPaint, 0x00); int iState = CBS_UNCHECKEDNORMAL; LRESULT dwCheckState = SendMessage(hWnd, BM_GETCHECK, 0, 0L); POINT pt; RECT rc; GetWindowRect(hWnd, &rc); GetCursorPos(&pt); BOOL bHot = PtInRect(&rc, pt); BOOL bFocus = GetFocus() == hWnd; int iPartId = BP_CHECKBOX; if (dwButtonType == BS_RADIOBUTTON || dwButtonType == BS_AUTORADIOBUTTON) iPartId = BP_RADIOBUTTON; iState = GetStateFromBtnState(dwStyle, bHot, bFocus, dwCheckState, iPartId, FALSE); int bmWidth = static_cast<int>(ceil(13.0 * GetDeviceCaps(hdcPaint, LOGPIXELSX) / 96.0)); UINT uiHalfWidth = (RECTWIDTH(rcClient) - bmWidth) / 2; /// /// we have to use the whole client area, otherwise we get only partially /// drawn areas: /// RECT rcPaint = rcClient; if (dwButtonStyle & BS_LEFTTEXT) { rcPaint.left += uiHalfWidth; rcPaint.right += uiHalfWidth; } else { rcPaint.left -= uiHalfWidth; rcPaint.right -= uiHalfWidth; } /// /// we assume that bm.bmWidth is both the horizontal and the vertical /// dimension of the control bitmap and that it is square. bm.bmHeight /// seems to be the height of a striped bitmap because it is an absurdly /// high dimension value /// if ((dwButtonStyle & BS_VCENTER) == BS_VCENTER) /// BS_VCENTER is BS_TOP|BS_BOTTOM { int h = RECTHEIGHT(rcPaint); rcPaint.top = (h - bmWidth) / 2; rcPaint.bottom = rcPaint.top + bmWidth; } else if (dwButtonStyle & BS_TOP) { rcPaint.bottom = rcPaint.top + bmWidth; } else if (dwButtonStyle & BS_BOTTOM) { rcPaint.top = rcPaint.bottom - bmWidth; } else // default: center the checkbox/radiobutton vertically { int h = RECTHEIGHT(rcPaint); rcPaint.top = (h - bmWidth) / 2; rcPaint.bottom = rcPaint.top + bmWidth; } m_theme.DrawThemeBackground(hTheme, hdcPaint, iPartId, iState, &rcPaint, nullptr); rcPaint = rcClient; m_theme.GetThemeBackgroundContentRect(hTheme, hdcPaint, iPartId, iState, &rcPaint, &rc); if (dwButtonStyle & BS_LEFTTEXT) rc.right -= bmWidth + 2 * GetSystemMetrics(SM_CXEDGE); else rc.left += bmWidth + 2 * GetSystemMetrics(SM_CXEDGE); DTTOPTS dttOpts = {sizeof(DTTOPTS)}; dttOpts.dwFlags = DTT_COMPOSITED | DTT_GLOWSIZE; dttOpts.crText = RGB(255, 255, 255); dttOpts.iGlowSize = 12; // Default value m_theme.DetermineGlowSize(&dttOpts.iGlowSize); HFONT hFontOld = reinterpret_cast<HFONT>(SendMessage(hWnd, WM_GETFONT, 0L, 0L)); if (hFontOld) hFontOld = static_cast<HFONT>(SelectObject(hdcPaint, hFontOld)); int iLen = GetWindowTextLength(hWnd); if (iLen) { iLen += 5; // 1 for terminating zero, 4 for DT_MODIFYSTRING LPWSTR szText = static_cast<LPWSTR>(LocalAlloc(LPTR, sizeof(WCHAR) * iLen)); if (szText) { iLen = GetWindowTextW(hWnd, szText, iLen); if (iLen) { DWORD dwFlags = DT_SINGLELINE /*|DT_VCENTER*/; if (dwButtonStyle & BS_MULTILINE) { dwFlags |= DT_WORDBREAK; dwFlags &= ~(DT_SINGLELINE | DT_VCENTER); } if ((dwButtonStyle & BS_CENTER) == BS_CENTER) /// BS_CENTER is BS_LEFT|BS_RIGHT dwFlags |= DT_CENTER; else if (dwButtonStyle & BS_LEFT) dwFlags |= DT_LEFT; else if (dwButtonStyle & BS_RIGHT) dwFlags |= DT_RIGHT; if ((dwButtonStyle & BS_VCENTER) == BS_VCENTER) /// BS_VCENTER is BS_TOP|BS_BOTTOM dwFlags |= DT_VCENTER; else if (dwButtonStyle & BS_TOP) dwFlags |= DT_TOP; else if (dwButtonStyle & BS_BOTTOM) dwFlags |= DT_BOTTOM; else dwFlags |= DT_VCENTER; m_theme.DrawThemeTextEx(hTheme, hdcPaint, iPartId, iState, szText, -1, dwFlags, &rc, &dttOpts); /// /// if our control has the focus, we also have to draw the focus rectangle: /// if (bFocus) { /// /// now calculate the text size: /// RECT rcDraw = rc; /// /// we use GDI's good old DrawText, because it returns much more /// accurate data than DrawThemeTextEx, which takes the glow /// into account which we don't want: /// DrawTextW(hdcPaint, szText, -1, &rcDraw, dwFlags | DT_CALCRECT); if (dwFlags & DT_SINGLELINE) { dwFlags &= ~DT_VCENTER; RECT rcDrawTop; DrawTextW(hdcPaint, szText, -1, &rcDrawTop, dwFlags | DT_CALCRECT); rcDraw.top = rcDraw.bottom - RECTHEIGHT(rcDrawTop); } if (dwFlags & DT_RIGHT) { int iWidth = RECTWIDTH(rcDraw); rcDraw.right = rc.right; rcDraw.left = rcDraw.right - iWidth; } RECT rcFocus; IntersectRect(&rcFocus, &rc, &rcDraw); DrawFocusRect(&rcFocus, hdcPaint); } } LocalFree(szText); } } if (hFontOld) { SelectObject(hdcPaint, hFontOld); hFontOld = nullptr; } m_theme.EndBufferedPaint(hBufferedPaint, TRUE); } m_theme.CloseThemeData(hTheme); } } else if (BS_PUSHBUTTON == dwButtonType || BS_DEFPUSHBUTTON == dwButtonType) { /// /// it is a push button /// HTHEME hTheme = m_theme.OpenThemeData(hWnd, L"Button"); if (hTheme) { HDC hdcPaint = nullptr; BP_PAINTPARAMS params = {sizeof(BP_PAINTPARAMS)}; params.dwFlags = BPPF_ERASE; HPAINTBUFFER hBufferedPaint = m_theme.BeginBufferedPaint(hdc, &rcClient, BPBF_TOPDOWNDIB, &params, &hdcPaint); if (hdcPaint) { PatBlt(hdcPaint, 0, 0, RECTWIDTH(rcClient), RECTHEIGHT(rcClient), BLACKNESS); m_theme.BufferedPaintSetAlpha(hBufferedPaint, &ps.rcPaint, 0x00); int iState = CBS_UNCHECKEDNORMAL; LRESULT dwCheckState = SendMessage(hWnd, BM_GETCHECK, 0, 0L); POINT pt; RECT rc; GetWindowRect(hWnd, &rc); GetCursorPos(&pt); BOOL bHot = PtInRect(&rc, pt); BOOL bFocus = GetFocus() == hWnd; int iPartId = BP_PUSHBUTTON; if (dwButtonStyle == BS_RADIOBUTTON || dwButtonStyle == BS_AUTORADIOBUTTON) iPartId = BP_RADIOBUTTON; iState = GetStateFromBtnState(dwStyle, bHot, bFocus, dwCheckState, iPartId, GetCapture() == hWnd); /// /// we have to use the whole client area, otherwise we get only partially /// drawn areas: /// RECT rcPaint = rcClient; m_theme.DrawThemeBackground(hTheme, hdcPaint, iPartId, iState, &rcPaint, nullptr); m_theme.GetThemeBackgroundContentRect(hTheme, hdcPaint, iPartId, iState, &rcPaint, &rc); DTTOPTS dttOpts = {sizeof(DTTOPTS)}; dttOpts.dwFlags = DTT_COMPOSITED; dttOpts.crText = RGB(255, 255, 255); dttOpts.dwFlags |= DTT_GLOWSIZE; dttOpts.iGlowSize = 12; // Default value m_theme.DetermineGlowSize(&dttOpts.iGlowSize); HFONT hFontOld = reinterpret_cast<HFONT>(SendMessage(hWnd, WM_GETFONT, 0L, 0L)); if (hFontOld) hFontOld = static_cast<HFONT>(SelectObject(hdcPaint, hFontOld)); int iLen = GetWindowTextLength(hWnd); if (iLen) { iLen += 5; // 1 for terminating zero, 4 for DT_MODIFYSTRING LPWSTR szText = static_cast<LPWSTR>(LocalAlloc(LPTR, sizeof(WCHAR) * iLen)); if (szText) { iLen = GetWindowTextW(hWnd, szText, iLen); if (iLen) { DWORD dwFlags = DT_SINGLELINE | DT_CENTER | DT_VCENTER; m_theme.DrawThemeTextEx(hTheme, hdcPaint, iPartId, iState, szText, -1, dwFlags, &rc, &dttOpts); /// /// if our control has the focus, we also have to draw the focus rectangle: /// if (bFocus) { RECT rcDraw = rcClient; InflateRect(&rcDraw, -3, -3); DrawFocusRect(&rcDraw, hdcPaint); } } LocalFree(szText); } } if (hFontOld) { SelectObject(hdcPaint, hFontOld); hFontOld = nullptr; } m_theme.EndBufferedPaint(hBufferedPaint, TRUE); } m_theme.CloseThemeData(hTheme); } } else //PaintControl(hWnd, hdc, &ps.rcPaint, (m_dwFlags & WD_DRAW_BORDER) != 0); PaintControl(hWnd, hdc, &ps.rcPaint, false); } EndPaint(hWnd, &ps); return 0; } case WM_DESTROY: case WM_NCDESTROY: RemoveWindowSubclass(hWnd, SubclassProc, Button); subClassedControls.erase(hWnd); break; } return DefSubclassProc(hWnd, uMsg, wParam, lParam); } LRESULT AeroControlBase::ProgressbarWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_ENABLE: case WM_STYLECHANGED: { LRESULT res = DefSubclassProc(hWnd, uMsg, wParam, lParam); InvalidateRgn(hWnd, nullptr, FALSE); return res; } case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); RECT rc; GetWindowRect(hWnd, &rc); MapWindowPoints(nullptr, hWnd, reinterpret_cast<LPPOINT>(&rc), 2); if (hdc) { PaintControl(hWnd, hdc, &rc, false); BP_PAINTPARAMS params = {sizeof(BP_PAINTPARAMS)}; params.dwFlags = 0L; HDC hdcPaint = nullptr; HPAINTBUFFER hBufferedPaint = m_theme.BeginBufferedPaint(hdc, &rc, BPBF_TOPDOWNDIB, &params, &hdcPaint); if (hdcPaint) { COLORREF cr = RGB(0x00, 0x00, 0x00); SetPixel(hdcPaint, 0, 0, cr); SetPixel(hdcPaint, 0, RECTHEIGHT(rc) - 1, cr); SetPixel(hdcPaint, RECTWIDTH(rc) - 1, 0, cr); SetPixel(hdcPaint, RECTWIDTH(rc) - 1, RECTHEIGHT(rc) - 1, cr); m_theme.EndBufferedPaint(hBufferedPaint, TRUE); } } EndPaint(hWnd, &ps); return 1; } case WM_NCDESTROY: case WM_DESTROY: RemoveWindowSubclass(hWnd, SubclassProc, Static); subClassedControls.erase(hWnd); break; } return DefSubclassProc(hWnd, uMsg, wParam, lParam); } void AeroControlBase::FillRect(LPRECT prc, HDC hdcPaint, Color clr) const { auto pBrush = std::make_unique<SolidBrush>(clr); if (pBrush) { auto myGraphics = std::make_unique<Graphics>(hdcPaint); if (myGraphics) { myGraphics->FillRectangle(pBrush.get(), static_cast<INT>(prc->left), static_cast<INT>(prc->top), static_cast<INT>(prc->right - 1 - prc->left), static_cast<INT>(prc->bottom - 1 - prc->top)); } } } int AeroControlBase::GetStateFromBtnState(LONG_PTR dwStyle, BOOL bHot, BOOL bFocus, LRESULT dwCheckState, int iPartId, BOOL bHasMouseCapture) { int iState = 0; switch (iPartId) { case BP_PUSHBUTTON: iState = PBS_NORMAL; if (dwStyle & WS_DISABLED) iState = PBS_DISABLED; else { if (dwStyle & BS_DEFPUSHBUTTON) iState = PBS_DEFAULTED; if (bHasMouseCapture && bHot) iState = PBS_PRESSED; else if (bHasMouseCapture || bHot) iState = PBS_HOT; } break; case BP_GROUPBOX: iState = (dwStyle & WS_DISABLED) ? GBS_DISABLED : GBS_NORMAL; break; case BP_RADIOBUTTON: iState = RBS_UNCHECKEDNORMAL; switch (dwCheckState) { case BST_CHECKED: if (dwStyle & WS_DISABLED) iState = RBS_CHECKEDDISABLED; else if (bFocus) iState = RBS_CHECKEDPRESSED; else if (bHot) iState = RBS_CHECKEDHOT; else iState = RBS_CHECKEDNORMAL; break; case BST_UNCHECKED: if (dwStyle & WS_DISABLED) iState = RBS_UNCHECKEDDISABLED; else if (bFocus) iState = RBS_UNCHECKEDPRESSED; else if (bHot) iState = RBS_UNCHECKEDHOT; else iState = RBS_UNCHECKEDNORMAL; break; } break; case BP_CHECKBOX: switch (dwCheckState) { case BST_CHECKED: if (dwStyle & WS_DISABLED) iState = CBS_CHECKEDDISABLED; else if (bFocus) iState = CBS_CHECKEDPRESSED; else if (bHot) iState = CBS_CHECKEDHOT; else iState = CBS_CHECKEDNORMAL; break; case BST_INDETERMINATE: if (dwStyle & WS_DISABLED) iState = CBS_MIXEDDISABLED; else if (bFocus) iState = CBS_MIXEDPRESSED; else if (bHot) iState = CBS_MIXEDHOT; else iState = CBS_MIXEDNORMAL; break; case BST_UNCHECKED: if (dwStyle & WS_DISABLED) iState = CBS_UNCHECKEDDISABLED; else if (bFocus) iState = CBS_UNCHECKEDPRESSED; else if (bHot) iState = CBS_UNCHECKEDHOT; else iState = CBS_UNCHECKEDNORMAL; break; } break; default: break; } return iState; } void AeroControlBase::DrawRect(LPRECT prc, HDC hdcPaint, DashStyle dashStyle, Color clr, REAL width) const { auto myPen = std::make_unique<Pen>(clr, width); myPen->SetDashStyle(dashStyle); auto myGraphics = std::make_unique<Graphics>(hdcPaint); myGraphics->DrawRectangle(myPen.get(), static_cast<INT>(prc->left), static_cast<INT>(prc->top), static_cast<INT>(prc->right - 1 - prc->left), static_cast<INT>(prc->bottom - 1 - prc->top)); } void AeroControlBase::DrawFocusRect(LPRECT prcFocus, HDC hdcPaint) const { DrawRect(prcFocus, hdcPaint, DashStyleDot, Color(0xFF, 0, 0, 0), 1.0); }; void AeroControlBase::PaintControl(HWND hWnd, HDC hdc, RECT* prc, bool bDrawBorder) const { HDC hdcPaint = nullptr; if (bDrawBorder) InflateRect(prc, 1, 1); HPAINTBUFFER hBufferedPaint = m_theme.BeginBufferedPaint(hdc, prc, BPBF_TOPDOWNDIB, nullptr, &hdcPaint); if (hdcPaint) { RECT rc; GetWindowRect(hWnd, &rc); PatBlt(hdcPaint, 0, 0, RECTWIDTH(rc), RECTHEIGHT(rc), BLACKNESS); m_theme.BufferedPaintSetAlpha(hBufferedPaint, &rc, 0x00); /// /// first blit white so list ctrls don't look ugly: /// PatBlt(hdcPaint, 0, 0, RECTWIDTH(rc), RECTHEIGHT(rc), WHITENESS); if (bDrawBorder) InflateRect(prc, -1, -1); // Tell the control to paint itself in our memory buffer SendMessage(hWnd, WM_PRINTCLIENT, reinterpret_cast<WPARAM>(hdcPaint), PRF_CLIENT | PRF_ERASEBKGND | PRF_NONCLIENT | PRF_CHECKVISIBLE); if (bDrawBorder) { InflateRect(prc, 1, 1); FrameRect(hdcPaint, prc, static_cast<HBRUSH>(GetStockObject(BLACK_BRUSH))); } // Make every pixel opaque m_theme.BufferedPaintMakeOpaque_(hBufferedPaint, prc); m_theme.EndBufferedPaint(hBufferedPaint, TRUE); } } BOOL AeroControlBase::GetEditBorderColor(HWND hWnd, COLORREF* pClr) const { HTHEME hTheme = m_theme.OpenThemeData(hWnd, L"Edit"); if (hTheme) { m_theme.GetThemeColor(hTheme, EP_BACKGROUNDWITHBORDER, EBWBS_NORMAL, TMT_BORDERCOLOR, pClr); m_theme.CloseThemeData(hTheme); return TRUE; } return FALSE; } void AeroControlBase::DrawEditBorder(HWND hWnd) const { LONG_PTR dwStyleEx = GetWindowLongPtr(hWnd, GWL_EXSTYLE); if (!(dwStyleEx & WS_EX_CLIENTEDGE)) return; COLORREF cr = RGB(0x00, 0x00, 0x00); GetEditBorderColor(hWnd, &cr); Color clr; clr.SetFromCOLORREF(cr); DrawSolidWndRectOnParent(hWnd, clr); } void AeroControlBase::DrawSolidWndRectOnParent(HWND hWnd, Color clr) const { RECT rcWnd; GetWindowRect(hWnd, &rcWnd); HWND hParent = GetParent(hWnd); if (hParent) { ScreenToClient(hParent, &rcWnd); HDC hdc = GetDC(hParent); if (hdc) { DrawRect(&rcWnd, hdc, DashStyleSolid, clr, 1.0); ReleaseDC(hWnd, hdc); } } } void AeroControlBase::ScreenToClient(HWND hWnd, LPRECT lprc) { POINT pt; pt.x = lprc->left; pt.y = lprc->top; ::ScreenToClient(hWnd, &pt); lprc->left = pt.x; lprc->top = pt.y; pt.x = lprc->right; pt.y = lprc->bottom; ::ScreenToClient(hWnd, &pt); lprc->right = pt.x; lprc->bottom = pt.y; } void AeroControlBase::GetRoundRectPath(GraphicsPath* pPath, const Rect& r, int dia) { // diameter can't exceed width or height if (dia > r.Width) dia = r.Width; if (dia > r.Height) dia = r.Height; // define a corner Rect corner(r.X, r.Y, dia, dia); // begin path pPath->Reset(); pPath->StartFigure(); // top left pPath->AddArc(corner, 180, 90); // top right corner.X += (r.Width - dia - 1); pPath->AddArc(corner, 270, 90); // bottom right corner.Y += (r.Height - dia - 1); pPath->AddArc(corner, 0, 90); // bottom left corner.X -= (r.Width - dia - 1); pPath->AddArc(corner, 90, 90); // end path pPath->CloseFigure(); } <|start_filename|>src/ced/ced/util/encodings/encodings.pb.h<|end_filename|> // encoding: UTF-8 // Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// #ifndef UTIL_ENCODINGS_ENCODINGS_PB_H_ #define UTIL_ENCODINGS_ENCODINGS_PB_H_ enum Encoding { ISO_8859_1 = 0, // Teragram ASCII ISO_8859_2 = 1, // Teragram Latin2 ISO_8859_3 = 2, // in BasisTech but not in Teragram ISO_8859_4 = 3, // Teragram Latin4 ISO_8859_5 = 4, // Teragram ISO-8859-5 ISO_8859_6 = 5, // Teragram Arabic ISO_8859_7 = 6, // Teragram Greek ISO_8859_8 = 7, // Teragram Hebrew ISO_8859_9 = 8, // in BasisTech but not in Teragram ISO_8859_10 = 9, // in BasisTech but not in Teragram JAPANESE_EUC_JP = 10, // Teragram EUC_JP JAPANESE_SHIFT_JIS = 11, // Teragram SJS JAPANESE_JIS = 12, // Teragram JIS CHINESE_BIG5 = 13, // Teragram BIG5 CHINESE_GB = 14, // Teragram GB CHINESE_EUC_CN = 15, // Misnamed. Should be EUC_TW. Was Basis Tech // CNS11643EUC, before that Teragram EUC-CN(!) // See //i18n/basistech/basistech_encodings.h KOREAN_EUC_KR = 16, // Teragram KSC UNICODE = 17, // Teragram Unicode CHINESE_EUC_DEC = 18, // Misnamed. Should be EUC_TW. Was Basis Tech // CNS11643EUC, before that Teragram EUC. CHINESE_CNS = 19, // Misnamed. Should be EUC_TW. Was Basis Tech // CNS11643EUC, before that Teragram CNS. CHINESE_BIG5_CP950 = 20, // Teragram BIG5_CP950 JAPANESE_CP932 = 21, // Teragram CP932 UTF8 = 22, UNKNOWN_ENCODING = 23, ASCII_7BIT = 24, // ISO_8859_1 with all characters <= 127. // Should be present only in the crawler // and in the repository, // *never* as a result of Document::encoding(). RUSSIAN_KOI8_R = 25, // Teragram KOI8R RUSSIAN_CP1251 = 26, // Teragram CP1251 //---------------------------------------------------------- // These are _not_ output from teragram. Instead, they are as // detected in the headers of usenet articles. MSFT_CP1252 = 27, // 27: CP1252 aka MSFT euro ascii RUSSIAN_KOI8_RU = 28, // CP21866 aka KOI8-U, used for Ukrainian. // Misnamed, this is _not_ KOI8-RU but KOI8-U. // KOI8-U is used much more often than KOI8-RU. MSFT_CP1250 = 29, // CP1250 aka MSFT eastern european ISO_8859_15 = 30, // aka ISO_8859_0 aka ISO_8859_1 euroized //---------------------------------------------------------- //---------------------------------------------------------- // These are in BasisTech but not in Teragram. They are // needed for new interface languages. Now detected by // research langid MSFT_CP1254 = 31, // used for Turkish MSFT_CP1257 = 32, // used in Baltic countries //---------------------------------------------------------- //---------------------------------------------------------- //---------------------------------------------------------- // New encodings detected by Teragram ISO_8859_11 = 33, // aka TIS-620, used for Thai MSFT_CP874 = 34, // used for Thai MSFT_CP1256 = 35, // used for Arabic //---------------------------------------------------------- // Detected as ISO_8859_8 by Teragram, but can be found in META tags MSFT_CP1255 = 36, // Logical Hebrew Microsoft ISO_8859_8_I = 37, // Iso Hebrew Logical HEBREW_VISUAL = 38, // Iso Hebrew Visual //---------------------------------------------------------- //---------------------------------------------------------- // Detected by research langid CZECH_CP852 = 39, CZECH_CSN_369103 = 40, // aka ISO_IR_139 aka KOI8_CS MSFT_CP1253 = 41, // used for Greek RUSSIAN_CP866 = 42, //---------------------------------------------------------- //---------------------------------------------------------- // Handled by iconv in glibc ISO_8859_13 = 43, ISO_2022_KR = 44, GBK = 45, GB18030 = 46, BIG5_HKSCS = 47, ISO_2022_CN = 48, //----------------------------------------------------------- // Detected by xin liu's detector // Handled by transcoder // (Indic encodings) TSCII = 49, TAMIL_MONO = 50, TAMIL_BI = 51, JAGRAN = 52, MACINTOSH_ROMAN = 53, UTF7 = 54, BHASKAR = 55, // Indic encoding - Devanagari HTCHANAKYA = 56, // 56 Indic encoding - Devanagari //----------------------------------------------------------- // These allow a single place (inputconverter and outputconverter) // to do UTF-16 <==> UTF-8 bulk conversions and UTF-32 <==> UTF-8 // bulk conversions, with interchange-valid checking on input and // fallback if needed on ouput. UTF16BE = 57, // big-endian UTF-16 UTF16LE = 58, // little-endian UTF-16 UTF32BE = 59, // big-endian UTF-32 UTF32LE = 60, // little-endian UTF-32 //----------------------------------------------------------- //----------------------------------------------------------- // An encoding that means "This is not text, but it may have some // simple ASCII text embedded". Intended input conversion (not yet // implemented) is to keep strings of >=4 seven-bit ASCII characters // (follow each kept string with an ASCII space), delete the rest of // the bytes. This will pick up and allow indexing of e.g. captions // in JPEGs. No output conversion needed. BINARYENC = 61, //----------------------------------------------------------- //----------------------------------------------------------- // Some Web pages allow a mixture of HZ-GB and GB-2312 by using // ~{ ... ~} for 2-byte pairs, and the browsers support this. HZ_GB_2312 = 62, //----------------------------------------------------------- //----------------------------------------------------------- // Some external vendors make the common input error of // converting MSFT_CP1252 to UTF8 *twice*. No output conversion needed. UTF8UTF8 = 63, //----------------------------------------------------------- //----------------------------------------------------------- // Handled by transcoder for tamil language specific font // encodings without the support for detection at present. TAM_ELANGO = 64, // Elango - Tamil TAM_LTTMBARANI = 65, // Barani - Tamil TAM_SHREE = 66, // Shree - Tamil TAM_TBOOMIS = 67, // TBoomis - Tamil TAM_TMNEWS = 68, // TMNews - Tamil TAM_WEBTAMIL = 69, // Webtamil - Tamil //----------------------------------------------------------- //----------------------------------------------------------- // Shift_JIS variants used by Japanese cell phone carriers. KDDI_SHIFT_JIS = 70, DOCOMO_SHIFT_JIS = 71, SOFTBANK_SHIFT_JIS = 72, // ISO-2022-JP variants used by KDDI and SoftBank. KDDI_ISO_2022_JP = 73, SOFTBANK_ISO_2022_JP = 74, //----------------------------------------------------------- NUM_ENCODINGS = 75, // Always keep this at the end. It is not a // valid Encoding enum, it is only used to // indicate the total number of Encodings. }; #endif // UTIL_ENCODINGS_ENCODINGS_PB_H_ <|start_filename|>grepWinNP3/sktoolslib_mod/Pidl.cpp<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012, 2020 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "Pidl.h" LPITEMIDLIST CPidl::GetNextItemID(LPCITEMIDLIST pidl) { // Check for valid pidl. if (pidl == NULL) return NULL; // Get the size of the specified item identifier. int cb = pidl->mkid.cb; // If the size is zero, it is the end of the list. if (cb == 0) return NULL; // Add cb to pidl (casting to increment by bytes). pidl = (LPITEMIDLIST)(((LPBYTE)pidl) + cb); // Return NULL if it is null-terminating, or a pidl otherwise. return (pidl->mkid.cb == 0) ? NULL : (LPITEMIDLIST)pidl; } UINT CPidl::GetSize(LPCITEMIDLIST pidl) { UINT cbTotal = 0; if (pidl) { cbTotal += sizeof(pidl->mkid.cb); // Terminating null character while (pidl) { cbTotal += pidl->mkid.cb; pidl = GetNextItemID(pidl); } } return cbTotal; } LPITEMIDLIST CPidl::MakeCopy(LPCITEMIDLIST pidl) { UINT cb = 0; // Calculate size of list. cb = GetSize(pidl); LPITEMIDLIST pidlRet = (LPITEMIDLIST)CoTaskMemAlloc(cb); if (pidlRet) CopyMemory(pidlRet, pidl, cb); return pidlRet; } BOOL CPidl::GetParentID(LPITEMIDLIST pidl) { BOOL fRemoved = FALSE; // Make sure it's a valid PIDL. if (pidl == NULL) return (FALSE); if (pidl->mkid.cb) { LPITEMIDLIST pidlNext = pidl; while (pidlNext) { pidl = pidlNext; pidlNext = GetNextItemID(pidl); } // Remove the last one, insert terminating null character. pidl->mkid.cb = 0; fRemoved = TRUE; } return fRemoved; } LPITEMIDLIST CPidl::Append(LPITEMIDLIST pidlBase, LPCITEMIDLIST pidlAdd) { if (pidlBase == NULL) return NULL; if (pidlAdd == NULL) return pidlBase; LPITEMIDLIST pidlNew; UINT cb1 = GetSize(pidlBase) - sizeof(pidlBase->mkid.cb); UINT cb2 = GetSize(pidlAdd); pidlNew = (LPITEMIDLIST)CoTaskMemAlloc(cb1 + cb2); if (pidlNew) { CopyMemory(pidlNew, pidlBase, cb1); CopyMemory(((LPSTR)pidlNew) + cb1, pidlAdd, cb2); } return pidlNew; } <|start_filename|>src/StyleLexers/styleLexKotlin.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- //KEYWORDLIST KeyWords_Kotlin = EMPTY_KEYWORDLIST; KEYWORDLIST KeyWords_Kotlin = { // 0 keywords "abstract actual annotation as break by catch class companion const constructor continue crossinline " "data delegate do dynamic else enum expect external false field file final finally for fun get " "if import in infix init inline inner interface internal is it lateinit noinline null object open operator out override " "package param private property protected public receiver reified return sealed set setparam super suspend " "tailrec this throw true try typealias typeof val var vararg when where while " , // 1 class "AbstractCollection AbstractIterator AbstractList " "AbstractMap AbstractMutableCollection AbstractMutableList AbstractMutableMap AbstractMutableSet AbstractQueue " "AbstractSequentialList AbstractSet ActionBar Activity AdapterView AlertDialog Any Application " "Array ArrayAdapter ArrayBlockingQueue ArrayDeque ArrayList Arrays " "AtomicBoolean AtomicInteger AtomicLong AtomicReference AudioFormat AudioManager AudioRecord AudioTrack " "Base64 BaseAdapter BigDecimal BigInteger Binder BitSet Bitmap Boolean BooleanArray " "Buffer BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter Build Bundle Button " "Byte ByteArray ByteArrayInputStream ByteArrayOutputStream ByteBuffer ByteOrder " "Calendar Canvas Char CharArray CharArrayReader CharArrayWriter CharBuffer Character Charset CheckBox ChoiceFormat " "Class ClassLoader Collections Collectors Color " "ConcurrentHashMap ConcurrentLinkedDeque ConcurrentLinkedQueue Console Constructor Context ContextWrapper Copy " "CountDownLatch Currency " "DataInputStream DataOutputStream DatagramPacket DatagramSocket Date DateFormat DecimalFormat DeflaterOutputStream " "Dialog Dictionary Display Double DoubleArray DoubleBuffer Drawable " "EOFException EditText Enum EnumMap EnumSet Environment Error EventObject Exception " "Field File FileDescriptor FileInputStream FileOutputStream FilePermission FileReader FileSystem FileWriter " "FilterInputStream FilterOutputStream FilterReader FilterWriter Float FloatArray FloatBuffer Format Formatter " "GZIPInputStream GZIPOutputStream Gradle GregorianCalendar GridView " "Handler HashMap HashSet Hashtable HttpClient HttpCookie HttpRequest HttpURLConnection " "IOError IOException Image ImageButton ImageView IndexedValue Inet4Address Inet6Address InetAddress InetSocketAddress " "InflaterInputStream InputStream InputStreamReader Int IntArray IntBuffer Integer Intent IntentFilter " "JarEntry JarException JarFile JarInputStream JarOutputStream JavaCompile KeyEvent " "LayoutInflater LinearLayout LinkedHashMap LinkedHashSet LinkedList ListView Locale Long LongArray LongBuffer Looper " "MappedByteBuffer MatchGroup Matcher Math Matrix Message MessageFormat Method Modifier Module MotionEvent " "MulticastSocket " "Nothing Notification Number NumberFormat " "Object ObjectInputStream ObjectOutputStream Optional OutputStream OutputStreamWriter " "Package Paint Pair Parcel Pattern PendingIntent PhantomReference " "PipedInputStream PipedOutputStream PipedReader PipedWriter Point PointF " "PrintStream PrintWriter PriorityQueue Process ProcessBuilder ProgressBar Project Properties " "RadioButton RadioGroup Random " "Reader Record Rect RectF Reference ReferenceQueue Regex Region RelativeLayout RemoteException Result " "Runtime RuntimeException " "Scanner Script ScrollView SearchView SecurityManager SeekBar Semaphore ServerSocket Service ServiceLoader Settings " "Short ShortArray ShortBuffer SimpleDateFormat Socket SocketAddress SoftReference SourceSet Spinner " "Stack StackView String StringBuffer StringBuilder StringJoiner StringReader StringTokenizer StringWriter System " "TableLayout Task TextView Thread ThreadGroup ThreadLocal ThreadPoolExecutor Throwable TimeZone Timer TimerTask " "Toast ToggleButton TreeMap TreeSet Triple " "UByte UByteArray UInt UIntArray ULong ULongArray URI URL URLConnection URLDecoder URLEncoder UShort UShortArray UUID " "Unit " "Vector View ViewGroup Void WeakHashMap WeakReference Window Writer " "ZipEntry ZipException ZipFile ZipInputStream ZipOutputStream " , // 2 interface "Adapter Annotation Appendable AutoCloseable BaseStream BlockingDeque BlockingQueue ByteChannel " "Callable Channel CharSequence Cloneable Closeable Collection Collector Comparable Comparator ConcurrentMap Condition " "DataInput DataOutput Deque DoubleStream Enumeration EventListener Executor Flushable Formattable Function Future " "Grouping HttpResponse IBinder IInterface IntStream Iterable Iterator Lazy List ListAdapter ListIterator Lock LongStream " "Map MatchGroupCollection MatchResult Menu MenuItem " "MutableCollection MutableIterable MutableIterator MutableList MutableListIterator MutableMap MutableSet " "NavigableMap NavigableSet ObjectInput ObjectOutput OnClickListener Parcelable Path Predicate Queue " "RandomAccess ReadWriteLock Readable Runnable Serializable Set SortedMap SortedSet Spliterator Stream WebSocket " , // 3 enum "AnnotationRetention AnnotationTarget DeprecationLevel ElementType LazyThreadSafetyMode RegexOption RetentionPolicy " "TimeUnit " , // 4 annotation "Basic Column Delegate DelegatesTo Deprecated Documented Entity FunctionalInterface Generated Id Inherited " "ManagedBean Metadata MustBeDocumented Native NonEmpty NonNull OrderBy OrderColumn Override " "PostConstruct PreDestroy Priority Readonly Repeatable ReplaceWith Resource Resources Retention " "SafeVarargs Serial Suppress SuppressWarnings Table Target Transient Version " , // 5 function "assert check error print println readLine require " , // 6 KDoc "author constructor exception param property receiver return sample see since suppress throws " , NULL }; EDITLEXER lexKotlin = { SCLEX_KOTLIN, "Kotlin", IDS_LEX_KOTLIN_SRC, L"Kotlin Source Code", L"kt; kts; ktm", L"", &KeyWords_Kotlin, { { { STYLE_DEFAULT }, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_KOTLIN_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { { SCE_KOTLIN_WORD }, IDS_LEX_STR_63128, L"Keyword", L"fore:#0000FF", L"" }, { { SCE_KOTLIN_ANNOTATION }, IDS_LEX_STR_63370, L"Annotation", L"fore:#FF8000", L"" }, { { SCE_KOTLIN_CLASS }, IDS_LEX_STR_63258, L"Class", L"fore:#0080FF", L"" }, { { SCE_KOTLIN_INTERFACE }, IDS_LEX_STR_63369, L"Interface", L"bold; fore:#1E90FF", L"" }, { { SCE_KOTLIN_ENUM }, IDS_LEX_STR_63203, L"Enumeration", L"fore:#FF8000", L"" }, { { SCE_KOTLIN_FUNCTION }, IDS_LEX_STR_63277, L"Function", L"fore:#A46000", L"" }, { { MULTI_STYLE(SCE_KOTLIN_COMMENTBLOCK, SCE_KOTLIN_COMMENTLINE, 0, 0) }, IDS_LEX_STR_63127, L"Comment", L"fore:#608060", L"" }, { { MULTI_STYLE(SCE_KOTLIN_COMMENTBLOCKDOC, SCE_KOTLIN_COMMENTLINEDOC, 0, 0) }, IDS_LEX_STR_63259, L"Comment Doc", L"fore:#408080", L"" }, { { SCE_KOTLIN_COMMENTDOCWORD }, IDS_LEX_STR_63371, L"Comment Doc Word", L"fore:#408080", L"" }, { { SCE_KOTLIN_TASKMARKER }, IDS_LEX_STR_63373, L"Task Marker", L"bold; fore:#208080" }, { { MULTI_STYLE(SCE_KOTLIN_CHARACTER, SCE_KOTLIN_STRING, 0, 0) }, IDS_LEX_STR_63131, L"String", L"fore:#008000", L"" }, { { MULTI_STYLE(SCE_KOTLIN_RAWSTRING, SCE_KOTLIN_RAWSTRINGSTART, SCE_KOTLIN_RAWSTRINGEND, 0) }, IDS_LEX_STR_63134, L"Verbatim String", L"fore:#F08000", L"" }, { { SCE_KOTLIN_ESCAPECHAR }, IDS_LEX_STR_63366, L"ESC Sequence", L"fore:#0080C0", L"" }, { { SCE_KOTLIN_BACKTICKS }, IDS_LEX_STR_63221, L"Back Ticks", L"fore:#9E4D2A", L"" }, { { SCE_KOTLIN_LABEL }, IDS_LEX_STR_63235, L"Label", L"fore:#7C5AF3", L"" }, { { SCE_KOTLIN_NUMBER }, IDS_LEX_STR_63130, L"Number", L"fore:#FF0000", L"" }, { { SCE_KOTLIN_VARIABLE }, IDS_LEX_STR_63249, L"Variable", L"fore:#9E4D2A", L"" }, { { MULTI_STYLE(SCE_KOTLIN_OPERATOR, SCE_KOTLIN_OPERATOR2, 0, 0) }, IDS_LEX_STR_63132, L"Operator", L"fore:#B000B0", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>src/StyleLexers/styleLexMAK.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_MAK = EMPTY_KEYWORDLIST; EDITLEXER lexMAK = { SCLEX_MAKEFILE, "makefile", IDS_LEX_MAKEFILES, L"Makefiles", L"mak; make; mk; dsp; msc; msvc; am; pro; pri; gmk; ninja; dsw; \\^Makefile$; \\^Kbuild$", L"", &KeyWords_MAK, { { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_MAKE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {SCE_MAKE_COMMENT}, IDS_LEX_STR_63127, L"Comment", L"fore:#008000", L"" }, { {MULTI_STYLE(SCE_MAKE_IDENTIFIER,SCE_MAKE_IDEOL,0,0)}, IDS_LEX_STR_63129, L"Identifier", L"fore:#003CE6", L"" }, { {SCE_MAKE_OPERATOR}, IDS_LEX_STR_63132, L"Operator", L"", L"" }, { {SCE_MAKE_TARGET}, IDS_LEX_STR_63204, L"Target", L"fore:#003CE6; back:#FFC000", L"" }, { {SCE_MAKE_PREPROCESSOR}, IDS_LEX_STR_63133, L"Preprocessor", L"fore:#FF8000", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>minipath/language/mp_es_es/mp_es_es.cpp<|end_filename|> // encoding: UTF-8 // mp_es_es.cpp: Definiert die exportierten Funktionen für die DLL-Anwendung. // #include "stdafx.h" <|start_filename|>src/StyleLexers/styleLexPY.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_PY = { "False None True and as assert break class continue def del elif else except exec finally for from global if " "import in is lambda nonlocal not or pass print raise return try while with yield", NULL, }; EDITLEXER lexPY = { SCLEX_PYTHON, "python", IDS_LEX_PYTHON, L"Python Script", L"py; pyw; pyx; pxd; pxi; boo; empy; cobra; gs", L"", &KeyWords_PY, { { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_P_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {MULTI_STYLE(SCE_P_COMMENTLINE,SCE_P_COMMENTBLOCK,0,0)}, IDS_LEX_STR_63127, L"Comment", L"fore:#880000", L"" }, { {MULTI_STYLE(SCE_P_WORD,SCE_P_WORD2,0,0)}, IDS_LEX_STR_63128, L"Keyword", L"fore:#000088", L"" }, { {SCE_P_IDENTIFIER}, IDS_LEX_STR_63129, L"Identifier", L"", L"" }, { {MULTI_STYLE(SCE_P_CHARACTER,SCE_P_FCHARACTER,0,0)}, IDS_LEX_STR_63212, L"String Single Quoted", L"fore:#008800", L"" }, { {MULTI_STYLE(SCE_P_STRING,SCE_P_FSTRING,SCE_P_STRINGEOL,0)}, IDS_LEX_STR_63211, L"String Double Quoted", L"fore:#008800", L"" }, { {MULTI_STYLE(SCE_P_TRIPLE, SCE_P_FTRIPLE,0,0)}, IDS_LEX_STR_63245, L"String Triple Single Quotes", L"fore:#88B634", L"" }, { {MULTI_STYLE(SCE_P_TRIPLEDOUBLE,SCE_P_FTRIPLEDOUBLE,0,0)}, IDS_LEX_STR_63244, L"String Triple Double Quotes", L"fore:#88B634", L"" }, { {SCE_P_DECORATOR}, IDS_LEX_STR_63372, L"Decorator", L"fore:#F2B600", L"" }, { {SCE_P_NUMBER}, IDS_LEX_STR_63130, L"Number", L"fore:#FF4000", L"" }, { {SCE_P_OPERATOR}, IDS_LEX_STR_63132, L"Operator", L"bold; fore:#666600", L"" }, { {SCE_P_DEFNAME}, IDS_LEX_STR_63247, L"Function Name", L"fore:#660066", L"" }, { {SCE_P_CLASSNAME}, IDS_LEX_STR_63246, L"Class Name", L"fore:#660066", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>src/StyleLexers/styleLexJulia.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- //KEYWORDLIST KeyWords_Julia = EMPTY_KEYWORDLIST; KEYWORDLIST KeyWords_Julia = { // 0 Primary keywords and identifiers "abstract baremodule begin break catch const continue do else elseif end export finally for function global " "if import in isa let local macro module mutable primitive quote return struct try type using var where while " , // 1 Built in types "AbstractArray AbstractArrayStyle AbstractChannel AbstractChar AbstractDict AbstractDisplay AbstractFloat " "AbstractIrrational AbstractLock AbstractLogger AbstractMatrix AbstractRNG AbstractRange " "AbstractSet AbstractSparseArray AbstractSparseMatrix AbstractSparseVector AbstractString AbstractUnitRange " "AbstractVecOrMat AbstractVector AbstractWorkerPool Adjoint Anonymous Any ArgumentError Array ArrayStyle " "AssertionError AsyncCondition Atomic " "Base64DecodePipe Base64EncodePipe Bidiagonal BigFloat BigInt BitArray BitMatrix BitSet BitVector Bool BoundsError " "BroadcastStyle " "CFunction CapturedException CartesianIndex CartesianIndices Cchar Cdouble Cfloat Channel Char Cint Cintmax_t " "Clong Clonglong ClusterManager Cmd " "Colon Complex ComplexF16 ComplexF32 ComplexF64 CompositeException CompoundPeriod Condition ConsoleLogger Cptrdiff_t " "Cshort Csize_t Cssize_t Cstring Cuchar Cuint Cuintmax_t Culong Culonglong Cushort Cwchar_t Cwstring " "DataType Date DateFormat DateTime Day DefaultArrayStyle DenseArray DenseMatrix DenseVecOrMat DenseVector " "Diagonal Dict DimensionMismatch Dims DivideError DomainError " "EOFError Enum EnvDict ErrorException Event Exception ExponentialBackOff Expr Float16 Float32 Float64 Function Future " "Givens GlobalRef Hermitian Hour " "IO IOBuffer IOContext IOStream IPAddr IPv4 IPv6 IdDict ImmutableDict IndexCartesian IndexLinear IndexStyle InexactError " "InitError Instant Int Int128 Int16 Int32 Int64 Int8 Integer InterruptException InvalidStateException Irrational " "IteratorEltype IteratorSize " "KeyError LinRange LineNumberNode LinearIndices LoadError LogLevel LowerTriangular " "MIME Matrix MersenneTwister Method MethodError Microsecond Millisecond Minute Missing MissingException Module Month " "Mutex " "NTuple NamedTuple Nanosecond Nothing NullLogger Number OneTo OrdinalRange OutOfMemoryError OverflowError " "Pair Pairs PartialQuickSort Period PermutedDimsArray Pipe PipeBuffer PosDefException ProcessFailedException Ptr " "QR QRCompactWY QRPivoted QuoteNode " "Random RandomDevice Rational RawFD " "ReadOnlyMemoryError Real ReentrantLock Ref Regex RegexMatch RemoteChannel RemoteException RoundingMode " "Second SegmentationFault Semaphore Serialization Set SharedArray SharedMatrix SharedVector " "Signed SimpleLogger SingularException Some SparseMatrixCSC SparseVector SpinLock " "StackFrame StackOverflowError StackTrace Stateful StepRange StepRangeLen " "StridedArray StridedMatrix StridedVecOrMat StridedVector String StringIndexError SubArray SubString SubstitutionString " "SymTridiagonal Symbol Symmetric SystemError " "TCPSocket Task TextDisplay Time TimeType Timer TmStruct Transpose Tridiagonal Tuple Type TypeError TypeVar " "UDPSocket UInt UInt128 UInt16 UInt32 UInt64 UInt8 UTInstant " "UndefInitializer UndefKeywordError UndefRefError UndefVarError " "UniformScaling Union UnionAll UnitLowerTriangular UnitRange UnitUpperTriangular Unsigned UpperTriangular " "Val Vararg VecElement VecOrMat Vector VersionNumber WeakKeyDict WeakRef Week WorkerConfig WorkerPool Year " , // 2 Other keywords "allocated assert async boundscheck cfunction debug deprecate distributed dump " "elapsed enum error eval evalpoly everywhere fastmath fetch generated gensym goto " "inbounds inferred info inline isdefined label logmsg lower macroexpand macroexpand1 noinline nospecialize " "polly preserve printf profile propagate_inbounds pure show spawn spawnat specialize sprintf static sync " "task test test_broken test_deprecated test_logs test_nowarn test_skip test_throws test_warn testset threads " "time timed timev " "view views warn " , // 3 Raw string literals "raw " , NULL }; EDITLEXER lexJulia = { SCLEX_JULIA, "julia", IDS_LEX_JULIA_SCR, L"Julia Script", L"jl", L"", &KeyWords_Julia, { { { STYLE_DEFAULT }, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_JULIA_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { { SCE_JULIA_COMMENT }, IDS_LEX_STR_63127, L"Comment", L"fore:#608060", L"" }, { { SCE_JULIA_NUMBER }, IDS_LEX_STR_63130, L"Number", L"fore:#FF0000", L"" }, { { SCE_JULIA_KEYWORD1 }, IDS_LEX_STR_63128, L"Keyword", L"bold; fore:#0000FF", L"" }, { { MULTI_STYLE(SCE_JULIA_KEYWORD2, SCE_JULIA_KEYWORD3, SCE_JULIA_KEYWORD4, 0) }, IDS_LEX_STR_63260, L"Keyword 2nd", L"bold; fore:#8A008A", L"" }, { { MULTI_STYLE(SCE_JULIA_CHAR, SCE_JULIA_STRING, 0, 0) }, IDS_LEX_STR_63131, L"String", L"fore:#BB2F00", L"" }, { { MULTI_STYLE(SCE_JULIA_OPERATOR, SCE_JULIA_BRACKET, 0, 0) }, IDS_LEX_STR_63132, L"Operator", L"fore:#B53A00", L"" }, { { SCE_JULIA_TYPEOPERATOR }, IDS_LEX_STR_63375, L"Type Operator", L"fore:#950095", L"" }, { { SCE_JULIA_IDENTIFIER }, IDS_LEX_STR_63129, L"Identifier", L"fore:#00007B", L"" }, { { SCE_JULIA_SYMBOL }, IDS_LEX_STR_63293, L"Symbol", L"fore:#C0A030", L"" }, { { SCE_JULIA_MACRO }, IDS_LEX_STR_63280, L"Macro Def", L"fore:#0080FF", L"" }, { { SCE_JULIA_DOCSTRING }, IDS_LEX_STR_63259, L"Comment Doc", L"fore:#808080", L"" }, { { MULTI_STYLE(SCE_JULIA_STRINGINTERP, SCE_JULIA_STRINGLITERAL, 0, 0) }, IDS_LEX_STR_63301, L"Literal String", L"fore:#B000B0", L"" }, { { MULTI_STYLE(SCE_JULIA_COMMAND, SCE_JULIA_COMMANDLITERAL, 0, 0) }, IDS_LEX_STR_63236, L"Command", L"bold; fore:#0000DD", L"" }, { { SCE_JULIA_TYPEANNOT }, IDS_LEX_STR_63370, L"Annotation", L"fore:#FF8000", L"" }, { { SCE_JULIA_LEXERROR }, IDS_LEX_STR_63252, L"Parsing Error", L"fore:#FFFF00; back:#A00000; eolfilled", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>grepWinNP3/sktoolslib_mod/ProfilingInfo.h<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2014, 2020 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #pragma once ////////////////////////////////////////////////////////////////////// // required includes ////////////////////////////////////////////////////////////////////// #ifndef _DEBUG # ifndef __INTRIN_H_ # include <intrin.h> # endif #endif #ifndef _PSAPI_H_ # include <psapi.h> #endif #ifndef _STRING_ # include <string> #endif #ifndef _VECTOR_ # include <vector> #endif #ifndef _FSTREAM_ # include <fstream> #endif #ifndef _TIME_ # include <time.h> #endif #pragma comment(lib, "psapi.lib") /** * Collects the profiling info for a given profiled block / line. * Records execution count, min, max and accumulated execution time * in CPU clock ticks. */ class CProfilingRecord { public: /// collected profiling info struct CSpent { unsigned __int64 sum; unsigned __int64 minValue; unsigned __int64 maxValue; void Add(unsigned __int64 value) { sum += value; if (value < minValue) minValue = value; if (value > maxValue) maxValue = value; } /// First value add void Init(unsigned __int64 value) { sum = value; minValue = value; maxValue = value; } void Init() { sum = 0; minValue = ULLONG_MAX; /* -1 */ maxValue = 0; } }; /// construction CProfilingRecord(const char* name, const char* file, int line); /// record values void Add(unsigned __int64 valueRdtsc, unsigned __int64 valueWall, unsigned __int64 valueUser, unsigned __int64 valueKernel); /// modification void Reset(); /// data access const char* GetName() const { return name; } const char* GetFile() const { return file; } int GetLine() const { return line; } size_t GetCount() const { return count; } const CSpent& Get() const { return m_rdtsc; } const CSpent& GetU() const { return m_user; } const CSpent& GetK() const { return m_kernel; } const CSpent& GetW() const { return m_wall; } private: /// identification const char* name; const char* file; int line; CSpent m_rdtsc, m_user, m_kernel, m_wall; size_t count; }; /** * RAII class that encapsulates a single execution of a profiled * block / line. The result gets added to an existing profiling record. */ class CRecordProfileEvent { private: CProfilingRecord* record; /// the initial counter values unsigned __int64 m_rdtscStart; FILETIME m_kernelStart; FILETIME m_userStart; FILETIME m_wallStart; public: /// construction: start clock CRecordProfileEvent(CProfilingRecord* aRecord); /// destruction: time interval to profiling record, /// if Stop() had not been called before ~CRecordProfileEvent(); /// don't wait for destruction void Stop(); }; /// construction / destruction inline CRecordProfileEvent::CRecordProfileEvent(CProfilingRecord* aRecord) : record(aRecord) { // less precise first SYSTEMTIME st; GetSystemTime(&st); SystemTimeToFileTime(&st, &m_wallStart); FILETIME ftTemp; GetProcessTimes(GetCurrentProcess(), &ftTemp, &ftTemp, &m_kernelStart, &m_userStart); m_rdtscStart = __rdtsc(); } inline CRecordProfileEvent::~CRecordProfileEvent() { Stop(); } UINT64 inline DiffFiletime(FILETIME time1, FILETIME time2) { return *(UINT64*)&time1 - *(UINT64*)&time2; } /// stop counting inline void CRecordProfileEvent::Stop() { if (record) { // more precise first unsigned __int64 nTake = __rdtsc() - m_rdtscStart; FILETIME kernelEnd, userEnd, ftTemp; GetProcessTimes(GetCurrentProcess(), &ftTemp, &ftTemp, &kernelEnd, &userEnd); SYSTEMTIME st; GetSystemTime(&st); FILETIME oTime; SystemTimeToFileTime(&st, &oTime); record->Add(nTake, DiffFiletime(oTime, m_wallStart), DiffFiletime(userEnd, m_userStart), DiffFiletime(kernelEnd, m_kernelStart)); record = NULL; } } /** * Singleton class that acts as container for all profiling records. * You may reset its content as well as write it to disk. */ class CProfilingInfo { private: typedef std::vector<CProfilingRecord*> TRecords; TRecords records; /// construction / destruction CProfilingInfo(); ~CProfilingInfo(void); /// create report std::string GetReport() const; public: /// access to default instance static CProfilingInfo* GetInstance(); /// add a new record CProfilingRecord* Create(const char* name, const char* file, int line); /// write the current results to disk void DumpReport(); }; /** * Profiling macros */ #define PROFILE_CONCAT(a, b) PROFILE_CONCAT3(a, b) #define PROFILE_CONCAT3(a, b) a##b /// measures the time from the point of usage to the end of the respective block #define PROFILE_BLOCK \ static CProfilingRecord* PROFILE_CONCAT(record, __LINE__) = CProfilingInfo::GetInstance()->Create(__FUNCTION__, __FILE__, __LINE__); \ CRecordProfileEvent PROFILE_CONCAT(profileSection, __LINE__)(PROFILE_CONCAT(record, __LINE__)); /// measures the time taken to execute the respective code line #define PROFILE_LINE(line) \ static CProfilingRecord* PROFILE_CONCAT(record, __LINE__) = CProfilingInfo::GetInstance()->Create(__FUNCTION__, __FILE__, __LINE__); \ CRecordProfileEvent PROFILE_CONCAT(profileSection, __LINE__)(PROFILE_CONCAT(record, __LINE__)); \ line; \ PROFILE_CONCAT(profileSection, __LINE__).Stop(); ////////////////////////////////////////////////////////////////////// // construction / destruction ////////////////////////////////////////////////////////////////////// inline CProfilingRecord::CProfilingRecord(const char* name, const char* file, int line) : name(name) , file(file) , line(line) , count(0) { Reset(); } ////////////////////////////////////////////////////////////////////// // record values ////////////////////////////////////////////////////////////////////// void inline CProfilingRecord::Add(unsigned __int64 valueRdtsc, unsigned __int64 valueTime, unsigned __int64 valueUser, unsigned __int64 valueKernel) { if (!count++) { m_rdtsc.Init(valueRdtsc); m_user.Init(valueUser); m_kernel.Init(valueKernel); m_wall.Init(valueTime); } else { m_rdtsc.Add(valueRdtsc); m_user.Add(valueUser); m_kernel.Add(valueKernel); m_wall.Add(valueTime); } } ////////////////////////////////////////////////////////////////////// // modification ////////////////////////////////////////////////////////////////////// inline void CProfilingRecord::Reset() { count = 0; // we don't need to init other then count, to be save we do m_rdtsc.Init(); m_user.Init(); m_kernel.Init(); m_wall.Init(); } ////////////////////////////////////////////////////////////////////// // construction / destruction ////////////////////////////////////////////////////////////////////// inline CProfilingInfo::CProfilingInfo() { } inline CProfilingInfo::~CProfilingInfo(void) { DumpReport(); // free data for (size_t i = 0; i < records.size(); ++i) delete records[i]; } ////////////////////////////////////////////////////////////////////// // access to default instance ////////////////////////////////////////////////////////////////////// inline CProfilingInfo* CProfilingInfo::GetInstance() { static CProfilingInfo instance; return &instance; } inline void CProfilingInfo::DumpReport() { if (!records.empty()) { // write profile to file #ifdef _WIN32 char buffer[MAX_PATH]; if (GetModuleFileNameExA(GetCurrentProcess(), NULL, buffer, _countof(buffer)) > 0) #else const char* buffer = "application"; #endif try { char datebuf[MAX_PATH]; time_t rawtime; struct tm timeinfo; time(&rawtime); localtime_s(&timeinfo, &rawtime); strftime(datebuf, MAX_PATH, "-%y-%m-%d-%H-%M", &timeinfo); std::string fileName(buffer); fileName += datebuf; fileName += ".profile"; std::string report = GetInstance()->GetReport(); std::ofstream file; file.open(fileName.c_str(), std::ios::binary | std::ios::out); file.write(report.c_str(), report.size()); } catch (...) { // ignore all file errors etc. } } } ////////////////////////////////////////////////////////////////////// // create a report ////////////////////////////////////////////////////////////////////// inline static std::string IntToStr(unsigned __int64 value) { char buffer[100]; _ui64toa_s(value, buffer, _countof(buffer), 10); std::string result = buffer; for (size_t i = 3; i < result.length(); i += 4) result.insert(result.length() - i, 1, ','); return result; }; inline std::string CProfilingInfo::GetReport() const { enum { LINE_LENGTH = 600 }; char lineBuffer[LINE_LENGTH]; std::string result; result.reserve(LINE_LENGTH * records.size()); const char* const format = "%15s%17s%17s%17s%17s\n"; for (TRecords::const_iterator iter = records.begin(), end = records.end(); iter != end; ++iter) { size_t nCount = (*iter)->GetCount(); sprintf_s(lineBuffer, "%7sx %s\n%s:%s\n", IntToStr(nCount).c_str(), (*iter)->GetName(), (*iter)->GetFile(), IntToStr((*iter)->GetLine()).c_str()); result += lineBuffer; if (nCount == 0) continue; sprintf_s(lineBuffer, format, "type", "sum", "avg", "min", "max"); result += lineBuffer; sprintf_s(lineBuffer, format, "CPU Ticks", IntToStr((*iter)->Get().sum).c_str(), IntToStr((*iter)->Get().sum / nCount).c_str(), IntToStr((*iter)->Get().minValue).c_str(), IntToStr((*iter)->Get().maxValue).c_str()); result += lineBuffer; sprintf_s(lineBuffer, format, "UserMode[us]", IntToStr((*iter)->GetU().sum / 10).c_str(), IntToStr((*iter)->GetU().sum / 10 / nCount).c_str(), IntToStr((*iter)->GetU().minValue / 10).c_str(), IntToStr((*iter)->GetU().maxValue / 10).c_str()); result += lineBuffer; sprintf_s(lineBuffer, format, "KernelMode[us]", IntToStr((*iter)->GetK().sum / 10).c_str(), IntToStr((*iter)->GetK().sum / 10 / nCount).c_str(), IntToStr((*iter)->GetK().minValue / 10).c_str(), IntToStr((*iter)->GetK().maxValue / 10).c_str()); result += lineBuffer; sprintf_s(lineBuffer, format, "WallTime[us]", IntToStr((*iter)->GetW().sum / 10).c_str(), IntToStr((*iter)->GetW().sum / 10 / nCount).c_str(), IntToStr((*iter)->GetW().minValue / 10).c_str(), IntToStr((*iter)->GetW().maxValue / 10).c_str()); result += lineBuffer; result += "\n"; } // now print the processor speed read from the registry: the user may want to // convert the processor ticks to seconds HKEY hKey; // open the key where the proc speed is hidden: long lError = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &hKey); if (lError == ERROR_SUCCESS) { // query the key: DWORD BufSize = _MAX_PATH; DWORD dwMHz = 0; RegQueryValueExA(hKey, "~MHz", NULL, NULL, (LPBYTE)&dwMHz, &BufSize); RegCloseKey(hKey); sprintf_s(lineBuffer, "processor speed is %ld MHz\n", dwMHz); result += lineBuffer; } return result; } ////////////////////////////////////////////////////////////////////// // add a new record ////////////////////////////////////////////////////////////////////// inline CProfilingRecord* CProfilingInfo::Create(const char* name, const char* file, int line) { CProfilingRecord* record = new CProfilingRecord(name, file, line); records.push_back(record); return record; } <|start_filename|>scintilla/call/ScintillaCall.cxx<|end_filename|> // SciTE - Scintilla based Text Editor /** @file ScintillaCall.cxx ** Interface to calling a Scintilla instance. **/ // Copyright 1998-2019 by <NAME> <<EMAIL>> // The License.txt file describes the conditions under which this software may be distributed. /* Most of this file is automatically generated from the Scintilla.iface interface definition * file which contains any comments about the definitions. APIFacer.py does the generation. */ #include <cstdint> #include <string> #include <string_view> #include "ScintillaTypes.h" #include "ScintillaMessages.h" #include "ScintillaCall.h" namespace Scintilla { ScintillaCall::ScintillaCall() noexcept : fn(nullptr), ptr(0), statusLastCall(Status::Ok) { } void ScintillaCall::SetFnPtr(FunctionDirect fn_, intptr_t ptr_) noexcept { fn = fn_; ptr = ptr_; } bool ScintillaCall::IsValid() const noexcept { return fn && ptr; } intptr_t ScintillaCall::Call(Message msg, uintptr_t wParam, intptr_t lParam) { if (!fn) throw Failure(Status::Failure); int status = 0; const intptr_t retVal = fn(ptr, static_cast<unsigned int>(msg), wParam, lParam, &status); statusLastCall = static_cast<Scintilla::Status>(status); if (statusLastCall > Status::Ok && statusLastCall < Status::WarnStart) throw Failure(statusLastCall); return retVal; } intptr_t ScintillaCall::CallPointer(Message msg, uintptr_t wParam, void *s) { return Call(msg, wParam, reinterpret_cast<intptr_t>(s)); } intptr_t ScintillaCall::CallString(Message msg, uintptr_t wParam, const char *s) { return Call(msg, wParam, reinterpret_cast<intptr_t>(s)); } std::string ScintillaCall::CallReturnString(Message msg, uintptr_t wParam) { size_t len = CallPointer(msg, wParam, nullptr); if (len) { std::string value(len, '\0'); CallPointer(msg, wParam, value.data()); return value; } else { return std::string(); } } // Common APIs made more structured and type-safe Position ScintillaCall::LineStart(Line line) { return Call(Message::PositionFromLine, line); } Position ScintillaCall::LineEnd(Line line) { return Call(Message::GetLineEndPosition, line); } Span ScintillaCall::SelectionSpan() { return Span( Call(Message::GetSelectionStart), Call(Message::GetSelectionEnd)); } Span ScintillaCall::TargetSpan() { return Span( Call(Message::GetTargetStart), Call(Message::GetTargetEnd)); } void ScintillaCall::SetTarget(Span span) { Call(Message::SetTargetRange, span.start, span.end); } void ScintillaCall::ColouriseAll() { Colourise(0, -1); } char ScintillaCall::CharacterAt(Position position) { return static_cast<char>(Call(Message::GetCharAt, position)); } int ScintillaCall::UnsignedStyleAt(Position position) { // Returns signed value but easier to use as unsigned return static_cast<unsigned char>(Call(Message::GetStyleAt, position)); } std::string ScintillaCall::StringOfSpan(Span span) { if (span.Length() == 0) { return std::string(); } else { std::string text(span.Length(), '\0'); SetTarget(span); TargetText(text.data()); return text; } } Position ScintillaCall::ReplaceTarget(std::string_view text) { return ScintillaCall::CallString(Message::ReplaceTarget, text.length(), text.data()); } Position ScintillaCall::ReplaceTargetRE(std::string_view text) { return CallString(Message::ReplaceTargetRE, text.length(), text.data()); } Position ScintillaCall::SearchInTarget(std::string_view text) { return CallString(Message::SearchInTarget, text.length(), text.data()); } Span ScintillaCall::SpanSearchInTarget(std::string_view text) { const Position posFound = SearchInTarget(text); if (posFound >= 0) return Span(posFound, TargetEnd()); else return Span(posFound, 0); } // Generated methods // ScintillaCall requires automatically generated casts as it is converting // specific types to/from generic arguments and return values of 'Call'. // Suppress Visual C++ Code Analysis warnings for these casts and pointer returns. // 26472 = Don't use a static_cast for arithmetic conversions. // 26487 = Don't return a pointer '*' that may be invalid (lifetime.4). // 26490 = Don't use reinterpret_cast. #if defined(_MSC_VER) #pragma warning(disable: 26472 26487 26490) #endif //++Autogenerated -- start of section automatically generated from Scintilla.iface void ScintillaCall::AddText(Position length, const char *text) { CallString(Message::AddText, length, text); } void ScintillaCall::AddStyledText(Position length, const char *c) { CallString(Message::AddStyledText, length, c); } void ScintillaCall::InsertText(Position pos, const char *text) { CallString(Message::InsertText, pos, text); } void ScintillaCall::ChangeInsertion(Position length, const char *text) { CallString(Message::ChangeInsertion, length, text); } void ScintillaCall::ClearAll() { Call(Message::ClearAll); } void ScintillaCall::DeleteRange(Position start, Position lengthDelete) { Call(Message::DeleteRange, start, lengthDelete); } void ScintillaCall::ClearDocumentStyle() { Call(Message::ClearDocumentStyle); } Position ScintillaCall::Length() { return Call(Message::GetLength); } int ScintillaCall::CharAt(Position pos) { return static_cast<int>(Call(Message::GetCharAt, pos)); } Position ScintillaCall::CurrentPos() { return Call(Message::GetCurrentPos); } Position ScintillaCall::Anchor() { return Call(Message::GetAnchor); } int ScintillaCall::StyleAt(Position pos) { return static_cast<int>(Call(Message::GetStyleAt, pos)); } void ScintillaCall::Redo() { Call(Message::Redo); } void ScintillaCall::SetUndoCollection(bool collectUndo) { Call(Message::SetUndoCollection, collectUndo); } void ScintillaCall::SelectAll() { Call(Message::SelectAll); } void ScintillaCall::SetSavePoint() { Call(Message::SetSavePoint); } Position ScintillaCall::GetStyledText(void *tr) { return CallPointer(Message::GetStyledText, 0, tr); } bool ScintillaCall::CanRedo() { return Call(Message::CanRedo); } Line ScintillaCall::MarkerLineFromHandle(int markerHandle) { return Call(Message::MarkerLineFromHandle, markerHandle); } void ScintillaCall::MarkerDeleteHandle(int markerHandle) { Call(Message::MarkerDeleteHandle, markerHandle); } int ScintillaCall::MarkerHandleFromLine(Line line, int which) { return static_cast<int>(Call(Message::MarkerHandleFromLine, line, which)); } int ScintillaCall::MarkerNumberFromLine(Line line, int which) { return static_cast<int>(Call(Message::MarkerNumberFromLine, line, which)); } bool ScintillaCall::UndoCollection() { return Call(Message::GetUndoCollection); } WhiteSpace ScintillaCall::ViewWS() { return static_cast<Scintilla::WhiteSpace>(Call(Message::GetViewWS)); } void ScintillaCall::SetViewWS(Scintilla::WhiteSpace viewWS) { Call(Message::SetViewWS, static_cast<uintptr_t>(viewWS)); } TabDrawMode ScintillaCall::TabDrawMode() { return static_cast<Scintilla::TabDrawMode>(Call(Message::GetTabDrawMode)); } void ScintillaCall::SetTabDrawMode(Scintilla::TabDrawMode tabDrawMode) { Call(Message::SetTabDrawMode, static_cast<uintptr_t>(tabDrawMode)); } Position ScintillaCall::PositionFromPoint(int x, int y) { return Call(Message::PositionFromPoint, x, y); } Position ScintillaCall::PositionFromPointClose(int x, int y) { return Call(Message::PositionFromPointClose, x, y); } void ScintillaCall::GotoLine(Line line) { Call(Message::GotoLine, line); } void ScintillaCall::GotoPos(Position caret) { Call(Message::GotoPos, caret); } void ScintillaCall::SetAnchor(Position anchor) { Call(Message::SetAnchor, anchor); } Position ScintillaCall::GetCurLine(Position length, char *text) { return CallPointer(Message::GetCurLine, length, text); } std::string ScintillaCall::GetCurLine(Position length) { return CallReturnString(Message::GetCurLine, length); } Position ScintillaCall::EndStyled() { return Call(Message::GetEndStyled); } void ScintillaCall::ConvertEOLs(Scintilla::EndOfLine eolMode) { Call(Message::ConvertEOLs, static_cast<uintptr_t>(eolMode)); } EndOfLine ScintillaCall::EOLMode() { return static_cast<Scintilla::EndOfLine>(Call(Message::GetEOLMode)); } void ScintillaCall::SetEOLMode(Scintilla::EndOfLine eolMode) { Call(Message::SetEOLMode, static_cast<uintptr_t>(eolMode)); } void ScintillaCall::StartStyling(Position start, int unused) { Call(Message::StartStyling, start, unused); } void ScintillaCall::SetStyling(Position length, int style) { Call(Message::SetStyling, length, style); } bool ScintillaCall::BufferedDraw() { return Call(Message::GetBufferedDraw); } void ScintillaCall::SetBufferedDraw(bool buffered) { Call(Message::SetBufferedDraw, buffered); } void ScintillaCall::SetTabWidth(int tabWidth) { Call(Message::SetTabWidth, tabWidth); } int ScintillaCall::TabWidth() { return static_cast<int>(Call(Message::GetTabWidth)); } void ScintillaCall::SetTabMinimumWidth(int pixels) { Call(Message::SetTabMinimumWidth, pixels); } int ScintillaCall::TabMinimumWidth() { return static_cast<int>(Call(Message::GetTabMinimumWidth)); } void ScintillaCall::ClearTabStops(Line line) { Call(Message::ClearTabStops, line); } void ScintillaCall::AddTabStop(Line line, int x) { Call(Message::AddTabStop, line, x); } int ScintillaCall::GetNextTabStop(Line line, int x) { return static_cast<int>(Call(Message::GetNextTabStop, line, x)); } void ScintillaCall::SetCodePage(int codePage) { Call(Message::SetCodePage, codePage); } void ScintillaCall::SetFontLocale(const char *localeName) { CallString(Message::SetFontLocale, 0, localeName); } int ScintillaCall::FontLocale(char *localeName) { return static_cast<int>(CallPointer(Message::GetFontLocale, 0, localeName)); } std::string ScintillaCall::FontLocale() { return CallReturnString(Message::GetFontLocale, 0); } IMEInteraction ScintillaCall::IMEInteraction() { return static_cast<Scintilla::IMEInteraction>(Call(Message::GetIMEInteraction)); } void ScintillaCall::SetIMEInteraction(Scintilla::IMEInteraction imeInteraction) { Call(Message::SetIMEInteraction, static_cast<uintptr_t>(imeInteraction)); } bool ScintillaCall::IsIMEOpen() { return Call(Message::IsIMEOpen); } bool ScintillaCall::IsIMEModeCJK() { return Call(Message::IsIMEModeCJK); } void ScintillaCall::MarkerDefine(int markerNumber, Scintilla::MarkerSymbol markerSymbol) { Call(Message::MarkerDefine, markerNumber, static_cast<intptr_t>(markerSymbol)); } void ScintillaCall::MarkerSetFore(int markerNumber, Colour fore) { Call(Message::MarkerSetFore, markerNumber, fore); } void ScintillaCall::MarkerSetBack(int markerNumber, Colour back) { Call(Message::MarkerSetBack, markerNumber, back); } void ScintillaCall::MarkerSetBackSelected(int markerNumber, Colour back) { Call(Message::MarkerSetBackSelected, markerNumber, back); } void ScintillaCall::MarkerSetForeTranslucent(int markerNumber, ColourAlpha fore) { Call(Message::MarkerSetForeTranslucent, markerNumber, fore); } void ScintillaCall::MarkerSetBackTranslucent(int markerNumber, ColourAlpha back) { Call(Message::MarkerSetBackTranslucent, markerNumber, back); } void ScintillaCall::MarkerSetBackSelectedTranslucent(int markerNumber, ColourAlpha back) { Call(Message::MarkerSetBackSelectedTranslucent, markerNumber, back); } void ScintillaCall::MarkerSetStrokeWidth(int markerNumber, int hundredths) { Call(Message::MarkerSetStrokeWidth, markerNumber, hundredths); } void ScintillaCall::MarkerEnableHighlight(bool enabled) { Call(Message::MarkerEnableHighlight, enabled); } int ScintillaCall::MarkerAdd(Line line, int markerNumber) { return static_cast<int>(Call(Message::MarkerAdd, line, markerNumber)); } void ScintillaCall::MarkerDelete(Line line, int markerNumber) { Call(Message::MarkerDelete, line, markerNumber); } void ScintillaCall::MarkerDeleteAll(int markerNumber) { Call(Message::MarkerDeleteAll, markerNumber); } int ScintillaCall::MarkerGet(Line line) { return static_cast<int>(Call(Message::MarkerGet, line)); } Line ScintillaCall::MarkerNext(Line lineStart, int markerMask) { return Call(Message::MarkerNext, lineStart, markerMask); } Line ScintillaCall::MarkerPrevious(Line lineStart, int markerMask) { return Call(Message::MarkerPrevious, lineStart, markerMask); } void ScintillaCall::MarkerDefinePixmap(int markerNumber, const char *pixmap) { CallString(Message::MarkerDefinePixmap, markerNumber, pixmap); } void ScintillaCall::MarkerAddSet(Line line, int markerSet) { Call(Message::MarkerAddSet, line, markerSet); } void ScintillaCall::MarkerSetAlpha(int markerNumber, Scintilla::Alpha alpha) { Call(Message::MarkerSetAlpha, markerNumber, static_cast<intptr_t>(alpha)); } Layer ScintillaCall::MarkerGetLayer(int markerNumber) { return static_cast<Scintilla::Layer>(Call(Message::MarkerGetLayer, markerNumber)); } void ScintillaCall::MarkerSetLayer(int markerNumber, Scintilla::Layer layer) { Call(Message::MarkerSetLayer, markerNumber, static_cast<intptr_t>(layer)); } void ScintillaCall::SetMarginTypeN(int margin, Scintilla::MarginType marginType) { Call(Message::SetMarginTypeN, margin, static_cast<intptr_t>(marginType)); } MarginType ScintillaCall::MarginTypeN(int margin) { return static_cast<Scintilla::MarginType>(Call(Message::GetMarginTypeN, margin)); } void ScintillaCall::SetMarginWidthN(int margin, int pixelWidth) { Call(Message::SetMarginWidthN, margin, pixelWidth); } int ScintillaCall::MarginWidthN(int margin) { return static_cast<int>(Call(Message::GetMarginWidthN, margin)); } void ScintillaCall::SetMarginMaskN(int margin, int mask) { Call(Message::SetMarginMaskN, margin, mask); } int ScintillaCall::MarginMaskN(int margin) { return static_cast<int>(Call(Message::GetMarginMaskN, margin)); } void ScintillaCall::SetMarginSensitiveN(int margin, bool sensitive) { Call(Message::SetMarginSensitiveN, margin, sensitive); } bool ScintillaCall::MarginSensitiveN(int margin) { return Call(Message::GetMarginSensitiveN, margin); } void ScintillaCall::SetMarginCursorN(int margin, Scintilla::CursorShape cursor) { Call(Message::SetMarginCursorN, margin, static_cast<intptr_t>(cursor)); } CursorShape ScintillaCall::MarginCursorN(int margin) { return static_cast<Scintilla::CursorShape>(Call(Message::GetMarginCursorN, margin)); } void ScintillaCall::SetMarginBackN(int margin, Colour back) { Call(Message::SetMarginBackN, margin, back); } Colour ScintillaCall::MarginBackN(int margin) { return static_cast<Colour>(Call(Message::GetMarginBackN, margin)); } void ScintillaCall::SetMargins(int margins) { Call(Message::SetMargins, margins); } int ScintillaCall::Margins() { return static_cast<int>(Call(Message::GetMargins)); } void ScintillaCall::StyleClearAll() { Call(Message::StyleClearAll); } void ScintillaCall::StyleSetFore(int style, Colour fore) { Call(Message::StyleSetFore, style, fore); } void ScintillaCall::StyleSetBack(int style, Colour back) { Call(Message::StyleSetBack, style, back); } void ScintillaCall::StyleSetBold(int style, bool bold) { Call(Message::StyleSetBold, style, bold); } void ScintillaCall::StyleSetItalic(int style, bool italic) { Call(Message::StyleSetItalic, style, italic); } void ScintillaCall::StyleSetSize(int style, int sizePoints) { Call(Message::StyleSetSize, style, sizePoints); } void ScintillaCall::StyleSetFont(int style, const char *fontName) { CallString(Message::StyleSetFont, style, fontName); } void ScintillaCall::StyleSetEOLFilled(int style, bool eolFilled) { Call(Message::StyleSetEOLFilled, style, eolFilled); } void ScintillaCall::StyleResetDefault() { Call(Message::StyleResetDefault); } void ScintillaCall::StyleSetUnderline(int style, bool underline) { Call(Message::StyleSetUnderline, style, underline); } void ScintillaCall::StyleSetStrike(int style, bool strike) { Call(Message::StyleSetStrike, style, strike); } Colour ScintillaCall::StyleGetFore(int style) { return static_cast<Colour>(Call(Message::StyleGetFore, style)); } Colour ScintillaCall::StyleGetBack(int style) { return static_cast<Colour>(Call(Message::StyleGetBack, style)); } bool ScintillaCall::StyleGetBold(int style) { return Call(Message::StyleGetBold, style); } bool ScintillaCall::StyleGetItalic(int style) { return Call(Message::StyleGetItalic, style); } int ScintillaCall::StyleGetSize(int style) { return static_cast<int>(Call(Message::StyleGetSize, style)); } int ScintillaCall::StyleGetFont(int style, char *fontName) { return static_cast<int>(CallPointer(Message::StyleGetFont, style, fontName)); } std::string ScintillaCall::StyleGetFont(int style) { return CallReturnString(Message::StyleGetFont, style); } bool ScintillaCall::StyleGetEOLFilled(int style) { return Call(Message::StyleGetEOLFilled, style); } bool ScintillaCall::StyleGetUnderline(int style) { return Call(Message::StyleGetUnderline, style); } bool ScintillaCall::StyleGetStrike(int style) { return Call(Message::StyleGetStrike, style); } CaseVisible ScintillaCall::StyleGetCase(int style) { return static_cast<Scintilla::CaseVisible>(Call(Message::StyleGetCase, style)); } CharacterSet ScintillaCall::StyleGetCharacterSet(int style) { return static_cast<Scintilla::CharacterSet>(Call(Message::StyleGetCharacterSet, style)); } bool ScintillaCall::StyleGetVisible(int style) { return Call(Message::StyleGetVisible, style); } bool ScintillaCall::StyleGetChangeable(int style) { return Call(Message::StyleGetChangeable, style); } bool ScintillaCall::StyleGetHotSpot(int style) { return Call(Message::StyleGetHotSpot, style); } void ScintillaCall::StyleSetCase(int style, Scintilla::CaseVisible caseVisible) { Call(Message::StyleSetCase, style, static_cast<intptr_t>(caseVisible)); } void ScintillaCall::StyleSetSizeFractional(int style, int sizeHundredthPoints) { Call(Message::StyleSetSizeFractional, style, sizeHundredthPoints); } int ScintillaCall::StyleGetSizeFractional(int style) { return static_cast<int>(Call(Message::StyleGetSizeFractional, style)); } void ScintillaCall::StyleSetWeight(int style, Scintilla::FontWeight weight) { Call(Message::StyleSetWeight, style, static_cast<intptr_t>(weight)); } FontWeight ScintillaCall::StyleGetWeight(int style) { return static_cast<Scintilla::FontWeight>(Call(Message::StyleGetWeight, style)); } void ScintillaCall::StyleSetCharacterSet(int style, Scintilla::CharacterSet characterSet) { Call(Message::StyleSetCharacterSet, style, static_cast<intptr_t>(characterSet)); } void ScintillaCall::StyleSetHotSpot(int style, bool hotspot) { Call(Message::StyleSetHotSpot, style, hotspot); } void ScintillaCall::StyleSetCheckMonospaced(int style, bool checkMonospaced) { Call(Message::StyleSetCheckMonospaced, style, checkMonospaced); } bool ScintillaCall::StyleGetCheckMonospaced(int style) { return Call(Message::StyleGetCheckMonospaced, style); } void ScintillaCall::SetElementColour(Scintilla::Element element, ColourAlpha colourElement) { Call(Message::SetElementColour, static_cast<uintptr_t>(element), colourElement); } ColourAlpha ScintillaCall::ElementColour(Scintilla::Element element) { return static_cast<ColourAlpha>(Call(Message::GetElementColour, static_cast<uintptr_t>(element))); } void ScintillaCall::ResetElementColour(Scintilla::Element element) { Call(Message::ResetElementColour, static_cast<uintptr_t>(element)); } bool ScintillaCall::ElementIsSet(Scintilla::Element element) { return Call(Message::GetElementIsSet, static_cast<uintptr_t>(element)); } bool ScintillaCall::ElementAllowsTranslucent(Scintilla::Element element) { return Call(Message::GetElementAllowsTranslucent, static_cast<uintptr_t>(element)); } ColourAlpha ScintillaCall::ElementBaseColour(Scintilla::Element element) { return static_cast<ColourAlpha>(Call(Message::GetElementBaseColour, static_cast<uintptr_t>(element))); } void ScintillaCall::SetSelFore(bool useSetting, Colour fore) { Call(Message::SetSelFore, useSetting, fore); } void ScintillaCall::SetSelBack(bool useSetting, Colour back) { Call(Message::SetSelBack, useSetting, back); } Alpha ScintillaCall::SelAlpha() { return static_cast<Scintilla::Alpha>(Call(Message::GetSelAlpha)); } void ScintillaCall::SetSelAlpha(Scintilla::Alpha alpha) { Call(Message::SetSelAlpha, static_cast<uintptr_t>(alpha)); } bool ScintillaCall::SelEOLFilled() { return Call(Message::GetSelEOLFilled); } void ScintillaCall::SetSelEOLFilled(bool filled) { Call(Message::SetSelEOLFilled, filled); } Layer ScintillaCall::SelectionLayer() { return static_cast<Scintilla::Layer>(Call(Message::GetSelectionLayer)); } void ScintillaCall::SetSelectionLayer(Scintilla::Layer layer) { Call(Message::SetSelectionLayer, static_cast<uintptr_t>(layer)); } Layer ScintillaCall::CaretLineLayer() { return static_cast<Scintilla::Layer>(Call(Message::GetCaretLineLayer)); } void ScintillaCall::SetCaretLineLayer(Scintilla::Layer layer) { Call(Message::SetCaretLineLayer, static_cast<uintptr_t>(layer)); } bool ScintillaCall::CaretLineHighlightSubLine() { return Call(Message::GetCaretLineHighlightSubLine); } void ScintillaCall::SetCaretLineHighlightSubLine(bool subLine) { Call(Message::SetCaretLineHighlightSubLine, subLine); } void ScintillaCall::SetCaretFore(Colour fore) { Call(Message::SetCaretFore, fore); } void ScintillaCall::AssignCmdKey(int keyDefinition, int sciCommand) { Call(Message::AssignCmdKey, keyDefinition, sciCommand); } void ScintillaCall::ClearCmdKey(int keyDefinition) { Call(Message::ClearCmdKey, keyDefinition); } void ScintillaCall::ClearAllCmdKeys() { Call(Message::ClearAllCmdKeys); } void ScintillaCall::SetStylingEx(Position length, const char *styles) { CallString(Message::SetStylingEx, length, styles); } void ScintillaCall::StyleSetVisible(int style, bool visible) { Call(Message::StyleSetVisible, style, visible); } int ScintillaCall::CaretPeriod() { return static_cast<int>(Call(Message::GetCaretPeriod)); } void ScintillaCall::SetCaretPeriod(int periodMilliseconds) { Call(Message::SetCaretPeriod, periodMilliseconds); } void ScintillaCall::SetWordChars(const char *characters) { CallString(Message::SetWordChars, 0, characters); } int ScintillaCall::WordChars(char *characters) { return static_cast<int>(CallPointer(Message::GetWordChars, 0, characters)); } std::string ScintillaCall::WordChars() { return CallReturnString(Message::GetWordChars, 0); } void ScintillaCall::SetCharacterCategoryOptimization(int countCharacters) { Call(Message::SetCharacterCategoryOptimization, countCharacters); } int ScintillaCall::CharacterCategoryOptimization() { return static_cast<int>(Call(Message::GetCharacterCategoryOptimization)); } void ScintillaCall::BeginUndoAction() { Call(Message::BeginUndoAction); } void ScintillaCall::EndUndoAction() { Call(Message::EndUndoAction); } void ScintillaCall::IndicSetStyle(int indicator, Scintilla::IndicatorStyle indicatorStyle) { Call(Message::IndicSetStyle, indicator, static_cast<intptr_t>(indicatorStyle)); } IndicatorStyle ScintillaCall::IndicGetStyle(int indicator) { return static_cast<Scintilla::IndicatorStyle>(Call(Message::IndicGetStyle, indicator)); } void ScintillaCall::IndicSetFore(int indicator, Colour fore) { Call(Message::IndicSetFore, indicator, fore); } Colour ScintillaCall::IndicGetFore(int indicator) { return static_cast<Colour>(Call(Message::IndicGetFore, indicator)); } void ScintillaCall::IndicSetUnder(int indicator, bool under) { Call(Message::IndicSetUnder, indicator, under); } bool ScintillaCall::IndicGetUnder(int indicator) { return Call(Message::IndicGetUnder, indicator); } void ScintillaCall::IndicSetHoverStyle(int indicator, Scintilla::IndicatorStyle indicatorStyle) { Call(Message::IndicSetHoverStyle, indicator, static_cast<intptr_t>(indicatorStyle)); } IndicatorStyle ScintillaCall::IndicGetHoverStyle(int indicator) { return static_cast<Scintilla::IndicatorStyle>(Call(Message::IndicGetHoverStyle, indicator)); } void ScintillaCall::IndicSetHoverFore(int indicator, Colour fore) { Call(Message::IndicSetHoverFore, indicator, fore); } Colour ScintillaCall::IndicGetHoverFore(int indicator) { return static_cast<Colour>(Call(Message::IndicGetHoverFore, indicator)); } void ScintillaCall::IndicSetFlags(int indicator, Scintilla::IndicFlag flags) { Call(Message::IndicSetFlags, indicator, static_cast<intptr_t>(flags)); } IndicFlag ScintillaCall::IndicGetFlags(int indicator) { return static_cast<Scintilla::IndicFlag>(Call(Message::IndicGetFlags, indicator)); } void ScintillaCall::IndicSetStrokeWidth(int indicator, int hundredths) { Call(Message::IndicSetStrokeWidth, indicator, hundredths); } int ScintillaCall::IndicGetStrokeWidth(int indicator) { return static_cast<int>(Call(Message::IndicGetStrokeWidth, indicator)); } void ScintillaCall::SetWhitespaceFore(bool useSetting, Colour fore) { Call(Message::SetWhitespaceFore, useSetting, fore); } void ScintillaCall::SetWhitespaceBack(bool useSetting, Colour back) { Call(Message::SetWhitespaceBack, useSetting, back); } void ScintillaCall::SetWhitespaceSize(int size) { Call(Message::SetWhitespaceSize, size); } int ScintillaCall::WhitespaceSize() { return static_cast<int>(Call(Message::GetWhitespaceSize)); } void ScintillaCall::SetLineState(Line line, int state) { Call(Message::SetLineState, line, state); } int ScintillaCall::LineState(Line line) { return static_cast<int>(Call(Message::GetLineState, line)); } int ScintillaCall::MaxLineState() { return static_cast<int>(Call(Message::GetMaxLineState)); } bool ScintillaCall::CaretLineVisible() { return Call(Message::GetCaretLineVisible); } void ScintillaCall::SetCaretLineVisible(bool show) { Call(Message::SetCaretLineVisible, show); } Colour ScintillaCall::CaretLineBack() { return static_cast<Colour>(Call(Message::GetCaretLineBack)); } void ScintillaCall::SetCaretLineBack(Colour back) { Call(Message::SetCaretLineBack, back); } int ScintillaCall::CaretLineFrame() { return static_cast<int>(Call(Message::GetCaretLineFrame)); } void ScintillaCall::SetCaretLineFrame(int width) { Call(Message::SetCaretLineFrame, width); } void ScintillaCall::StyleSetChangeable(int style, bool changeable) { Call(Message::StyleSetChangeable, style, changeable); } void ScintillaCall::AutoCShow(Position lengthEntered, const char *itemList) { CallString(Message::AutoCShow, lengthEntered, itemList); } void ScintillaCall::AutoCCancel() { Call(Message::AutoCCancel); } bool ScintillaCall::AutoCActive() { return Call(Message::AutoCActive); } Position ScintillaCall::AutoCPosStart() { return Call(Message::AutoCPosStart); } void ScintillaCall::AutoCComplete() { Call(Message::AutoCComplete); } void ScintillaCall::AutoCStops(const char *characterSet) { CallString(Message::AutoCStops, 0, characterSet); } void ScintillaCall::AutoCSetSeparator(int separatorCharacter) { Call(Message::AutoCSetSeparator, separatorCharacter); } int ScintillaCall::AutoCGetSeparator() { return static_cast<int>(Call(Message::AutoCGetSeparator)); } void ScintillaCall::AutoCSelect(const char *select) { CallString(Message::AutoCSelect, 0, select); } void ScintillaCall::AutoCSetCancelAtStart(bool cancel) { Call(Message::AutoCSetCancelAtStart, cancel); } bool ScintillaCall::AutoCGetCancelAtStart() { return Call(Message::AutoCGetCancelAtStart); } void ScintillaCall::AutoCSetFillUps(const char *characterSet) { CallString(Message::AutoCSetFillUps, 0, characterSet); } void ScintillaCall::AutoCSetChooseSingle(bool chooseSingle) { Call(Message::AutoCSetChooseSingle, chooseSingle); } bool ScintillaCall::AutoCGetChooseSingle() { return Call(Message::AutoCGetChooseSingle); } void ScintillaCall::AutoCSetIgnoreCase(bool ignoreCase) { Call(Message::AutoCSetIgnoreCase, ignoreCase); } bool ScintillaCall::AutoCGetIgnoreCase() { return Call(Message::AutoCGetIgnoreCase); } void ScintillaCall::UserListShow(int listType, const char *itemList) { CallString(Message::UserListShow, listType, itemList); } void ScintillaCall::AutoCSetAutoHide(bool autoHide) { Call(Message::AutoCSetAutoHide, autoHide); } bool ScintillaCall::AutoCGetAutoHide() { return Call(Message::AutoCGetAutoHide); } void ScintillaCall::AutoCSetOptions(Scintilla::AutoCompleteOption options) { Call(Message::AutoCSetOptions, static_cast<uintptr_t>(options)); } AutoCompleteOption ScintillaCall::AutoCGetOptions() { return static_cast<Scintilla::AutoCompleteOption>(Call(Message::AutoCGetOptions)); } void ScintillaCall::AutoCSetDropRestOfWord(bool dropRestOfWord) { Call(Message::AutoCSetDropRestOfWord, dropRestOfWord); } bool ScintillaCall::AutoCGetDropRestOfWord() { return Call(Message::AutoCGetDropRestOfWord); } void ScintillaCall::RegisterImage(int type, const char *xpmData) { CallString(Message::RegisterImage, type, xpmData); } void ScintillaCall::ClearRegisteredImages() { Call(Message::ClearRegisteredImages); } int ScintillaCall::AutoCGetTypeSeparator() { return static_cast<int>(Call(Message::AutoCGetTypeSeparator)); } void ScintillaCall::AutoCSetTypeSeparator(int separatorCharacter) { Call(Message::AutoCSetTypeSeparator, separatorCharacter); } void ScintillaCall::AutoCSetMaxWidth(int characterCount) { Call(Message::AutoCSetMaxWidth, characterCount); } int ScintillaCall::AutoCGetMaxWidth() { return static_cast<int>(Call(Message::AutoCGetMaxWidth)); } void ScintillaCall::AutoCSetMaxHeight(int rowCount) { Call(Message::AutoCSetMaxHeight, rowCount); } int ScintillaCall::AutoCGetMaxHeight() { return static_cast<int>(Call(Message::AutoCGetMaxHeight)); } void ScintillaCall::SetIndent(int indentSize) { Call(Message::SetIndent, indentSize); } int ScintillaCall::Indent() { return static_cast<int>(Call(Message::GetIndent)); } void ScintillaCall::SetUseTabs(bool useTabs) { Call(Message::SetUseTabs, useTabs); } bool ScintillaCall::UseTabs() { return Call(Message::GetUseTabs); } void ScintillaCall::SetLineIndentation(Line line, int indentation) { Call(Message::SetLineIndentation, line, indentation); } int ScintillaCall::LineIndentation(Line line) { return static_cast<int>(Call(Message::GetLineIndentation, line)); } Position ScintillaCall::LineIndentPosition(Line line) { return Call(Message::GetLineIndentPosition, line); } Position ScintillaCall::Column(Position pos) { return Call(Message::GetColumn, pos); } Position ScintillaCall::CountCharacters(Position start, Position end) { return Call(Message::CountCharacters, start, end); } Position ScintillaCall::CountCodeUnits(Position start, Position end) { return Call(Message::CountCodeUnits, start, end); } void ScintillaCall::SetHScrollBar(bool visible) { Call(Message::SetHScrollBar, visible); } bool ScintillaCall::HScrollBar() { return Call(Message::GetHScrollBar); } void ScintillaCall::SetIndentationGuides(Scintilla::IndentView indentView) { Call(Message::SetIndentationGuides, static_cast<uintptr_t>(indentView)); } IndentView ScintillaCall::IndentationGuides() { return static_cast<Scintilla::IndentView>(Call(Message::GetIndentationGuides)); } void ScintillaCall::SetHighlightGuide(Position column) { Call(Message::SetHighlightGuide, column); } Position ScintillaCall::HighlightGuide() { return Call(Message::GetHighlightGuide); } Position ScintillaCall::LineEndPosition(Line line) { return Call(Message::GetLineEndPosition, line); } int ScintillaCall::CodePage() { return static_cast<int>(Call(Message::GetCodePage)); } Colour ScintillaCall::CaretFore() { return static_cast<Colour>(Call(Message::GetCaretFore)); } bool ScintillaCall::ReadOnly() { return Call(Message::GetReadOnly); } void ScintillaCall::SetCurrentPos(Position caret) { Call(Message::SetCurrentPos, caret); } void ScintillaCall::SetSelectionStart(Position anchor) { Call(Message::SetSelectionStart, anchor); } Position ScintillaCall::SelectionStart() { return Call(Message::GetSelectionStart); } void ScintillaCall::SetSelectionEnd(Position caret) { Call(Message::SetSelectionEnd, caret); } Position ScintillaCall::SelectionEnd() { return Call(Message::GetSelectionEnd); } void ScintillaCall::SetEmptySelection(Position caret) { Call(Message::SetEmptySelection, caret); } void ScintillaCall::SetPrintMagnification(int magnification) { Call(Message::SetPrintMagnification, magnification); } int ScintillaCall::PrintMagnification() { return static_cast<int>(Call(Message::GetPrintMagnification)); } void ScintillaCall::SetPrintColourMode(Scintilla::PrintOption mode) { Call(Message::SetPrintColourMode, static_cast<uintptr_t>(mode)); } PrintOption ScintillaCall::PrintColourMode() { return static_cast<Scintilla::PrintOption>(Call(Message::GetPrintColourMode)); } Position ScintillaCall::FindText(Scintilla::FindOption searchFlags, void *ft) { return CallPointer(Message::FindText, static_cast<uintptr_t>(searchFlags), ft); } Position ScintillaCall::FormatRange(bool draw, void *fr) { return CallPointer(Message::FormatRange, draw, fr); } Line ScintillaCall::FirstVisibleLine() { return Call(Message::GetFirstVisibleLine); } Position ScintillaCall::GetLine(Line line, char *text) { return CallPointer(Message::GetLine, line, text); } std::string ScintillaCall::GetLine(Line line) { return CallReturnString(Message::GetLine, line); } Line ScintillaCall::LineCount() { return Call(Message::GetLineCount); } void ScintillaCall::AllocateLines(Line lines) { Call(Message::AllocateLines, lines); } void ScintillaCall::SetMarginLeft(int pixelWidth) { Call(Message::SetMarginLeft, 0, pixelWidth); } int ScintillaCall::MarginLeft() { return static_cast<int>(Call(Message::GetMarginLeft)); } void ScintillaCall::SetMarginRight(int pixelWidth) { Call(Message::SetMarginRight, 0, pixelWidth); } int ScintillaCall::MarginRight() { return static_cast<int>(Call(Message::GetMarginRight)); } bool ScintillaCall::Modify() { return Call(Message::GetModify); } void ScintillaCall::SetSel(Position anchor, Position caret) { Call(Message::SetSel, anchor, caret); } Position ScintillaCall::GetSelText(char *text) { return CallPointer(Message::GetSelText, 0, text); } std::string ScintillaCall::GetSelText() { return CallReturnString(Message::GetSelText, 0); } Position ScintillaCall::GetTextRange(void *tr) { return CallPointer(Message::GetTextRange, 0, tr); } void ScintillaCall::HideSelection(bool hide) { Call(Message::HideSelection, hide); } int ScintillaCall::PointXFromPosition(Position pos) { return static_cast<int>(Call(Message::PointXFromPosition, 0, pos)); } int ScintillaCall::PointYFromPosition(Position pos) { return static_cast<int>(Call(Message::PointYFromPosition, 0, pos)); } Line ScintillaCall::LineFromPosition(Position pos) { return Call(Message::LineFromPosition, pos); } Position ScintillaCall::PositionFromLine(Line line) { return Call(Message::PositionFromLine, line); } void ScintillaCall::LineScroll(Position columns, Line lines) { Call(Message::LineScroll, columns, lines); } void ScintillaCall::ScrollCaret() { Call(Message::ScrollCaret); } void ScintillaCall::ScrollRange(Position secondary, Position primary) { Call(Message::ScrollRange, secondary, primary); } void ScintillaCall::ReplaceSel(const char *text) { CallString(Message::ReplaceSel, 0, text); } void ScintillaCall::SetReadOnly(bool readOnly) { Call(Message::SetReadOnly, readOnly); } void ScintillaCall::Null() { Call(Message::Null); } bool ScintillaCall::CanPaste() { return Call(Message::CanPaste); } bool ScintillaCall::CanUndo() { return Call(Message::CanUndo); } void ScintillaCall::EmptyUndoBuffer() { Call(Message::EmptyUndoBuffer); } void ScintillaCall::Undo() { Call(Message::Undo); } void ScintillaCall::Cut() { Call(Message::Cut); } void ScintillaCall::Copy() { Call(Message::Copy); } void ScintillaCall::Paste() { Call(Message::Paste); } void ScintillaCall::Clear() { Call(Message::Clear); } void ScintillaCall::SetText(const char *text) { CallString(Message::SetText, 0, text); } Position ScintillaCall::GetText(Position length, char *text) { return CallPointer(Message::GetText, length, text); } std::string ScintillaCall::GetText(Position length) { return CallReturnString(Message::GetText, length); } Position ScintillaCall::TextLength() { return Call(Message::GetTextLength); } void *ScintillaCall::DirectFunction() { return reinterpret_cast<void *>(Call(Message::GetDirectFunction)); } void *ScintillaCall::DirectStatusFunction() { return reinterpret_cast<void *>(Call(Message::GetDirectStatusFunction)); } void *ScintillaCall::DirectPointer() { return reinterpret_cast<void *>(Call(Message::GetDirectPointer)); } void ScintillaCall::SetOvertype(bool overType) { Call(Message::SetOvertype, overType); } bool ScintillaCall::Overtype() { return Call(Message::GetOvertype); } void ScintillaCall::SetCaretWidth(int pixelWidth) { Call(Message::SetCaretWidth, pixelWidth); } int ScintillaCall::CaretWidth() { return static_cast<int>(Call(Message::GetCaretWidth)); } void ScintillaCall::SetTargetStart(Position start) { Call(Message::SetTargetStart, start); } Position ScintillaCall::TargetStart() { return Call(Message::GetTargetStart); } void ScintillaCall::SetTargetStartVirtualSpace(Position space) { Call(Message::SetTargetStartVirtualSpace, space); } Position ScintillaCall::TargetStartVirtualSpace() { return Call(Message::GetTargetStartVirtualSpace); } void ScintillaCall::SetTargetEnd(Position end) { Call(Message::SetTargetEnd, end); } Position ScintillaCall::TargetEnd() { return Call(Message::GetTargetEnd); } void ScintillaCall::SetTargetEndVirtualSpace(Position space) { Call(Message::SetTargetEndVirtualSpace, space); } Position ScintillaCall::TargetEndVirtualSpace() { return Call(Message::GetTargetEndVirtualSpace); } void ScintillaCall::SetTargetRange(Position start, Position end) { Call(Message::SetTargetRange, start, end); } Position ScintillaCall::TargetText(char *text) { return CallPointer(Message::GetTargetText, 0, text); } std::string ScintillaCall::TargetText() { return CallReturnString(Message::GetTargetText, 0); } void ScintillaCall::TargetFromSelection() { Call(Message::TargetFromSelection); } void ScintillaCall::TargetWholeDocument() { Call(Message::TargetWholeDocument); } Position ScintillaCall::ReplaceTarget(Position length, const char *text) { return CallString(Message::ReplaceTarget, length, text); } Position ScintillaCall::ReplaceTargetRE(Position length, const char *text) { return CallString(Message::ReplaceTargetRE, length, text); } Position ScintillaCall::SearchInTarget(Position length, const char *text) { return CallString(Message::SearchInTarget, length, text); } void ScintillaCall::SetSearchFlags(Scintilla::FindOption searchFlags) { Call(Message::SetSearchFlags, static_cast<uintptr_t>(searchFlags)); } FindOption ScintillaCall::SearchFlags() { return static_cast<Scintilla::FindOption>(Call(Message::GetSearchFlags)); } void ScintillaCall::CallTipShow(Position pos, const char *definition) { CallString(Message::CallTipShow, pos, definition); } void ScintillaCall::CallTipCancel() { Call(Message::CallTipCancel); } bool ScintillaCall::CallTipActive() { return Call(Message::CallTipActive); } Position ScintillaCall::CallTipPosStart() { return Call(Message::CallTipPosStart); } void ScintillaCall::CallTipSetPosStart(Position posStart) { Call(Message::CallTipSetPosStart, posStart); } void ScintillaCall::CallTipSetHlt(Position highlightStart, Position highlightEnd) { Call(Message::CallTipSetHlt, highlightStart, highlightEnd); } void ScintillaCall::CallTipSetBack(Colour back) { Call(Message::CallTipSetBack, back); } void ScintillaCall::CallTipSetFore(Colour fore) { Call(Message::CallTipSetFore, fore); } void ScintillaCall::CallTipSetForeHlt(Colour fore) { Call(Message::CallTipSetForeHlt, fore); } void ScintillaCall::CallTipUseStyle(int tabSize) { Call(Message::CallTipUseStyle, tabSize); } void ScintillaCall::CallTipSetPosition(bool above) { Call(Message::CallTipSetPosition, above); } Line ScintillaCall::VisibleFromDocLine(Line docLine) { return Call(Message::VisibleFromDocLine, docLine); } Line ScintillaCall::DocLineFromVisible(Line displayLine) { return Call(Message::DocLineFromVisible, displayLine); } Line ScintillaCall::WrapCount(Line docLine) { return Call(Message::WrapCount, docLine); } void ScintillaCall::SetFoldLevel(Line line, Scintilla::FoldLevel level) { Call(Message::SetFoldLevel, line, static_cast<intptr_t>(level)); } FoldLevel ScintillaCall::FoldLevel(Line line) { return static_cast<Scintilla::FoldLevel>(Call(Message::GetFoldLevel, line)); } Line ScintillaCall::LastChild(Line line, Scintilla::FoldLevel level) { return Call(Message::GetLastChild, line, static_cast<intptr_t>(level)); } Line ScintillaCall::FoldParent(Line line) { return Call(Message::GetFoldParent, line); } void ScintillaCall::ShowLines(Line lineStart, Line lineEnd) { Call(Message::ShowLines, lineStart, lineEnd); } void ScintillaCall::HideLines(Line lineStart, Line lineEnd) { Call(Message::HideLines, lineStart, lineEnd); } bool ScintillaCall::LineVisible(Line line) { return Call(Message::GetLineVisible, line); } bool ScintillaCall::AllLinesVisible() { return Call(Message::GetAllLinesVisible); } void ScintillaCall::SetFoldExpanded(Line line, bool expanded) { Call(Message::SetFoldExpanded, line, expanded); } bool ScintillaCall::FoldExpanded(Line line) { return Call(Message::GetFoldExpanded, line); } void ScintillaCall::ToggleFold(Line line) { Call(Message::ToggleFold, line); } void ScintillaCall::ToggleFoldShowText(Line line, const char *text) { CallString(Message::ToggleFoldShowText, line, text); } void ScintillaCall::FoldDisplayTextSetStyle(Scintilla::FoldDisplayTextStyle style) { Call(Message::FoldDisplayTextSetStyle, static_cast<uintptr_t>(style)); } FoldDisplayTextStyle ScintillaCall::FoldDisplayTextGetStyle() { return static_cast<Scintilla::FoldDisplayTextStyle>(Call(Message::FoldDisplayTextGetStyle)); } void ScintillaCall::SetDefaultFoldDisplayText(const char *text) { CallString(Message::SetDefaultFoldDisplayText, 0, text); } int ScintillaCall::GetDefaultFoldDisplayText(char *text) { return static_cast<int>(CallPointer(Message::GetDefaultFoldDisplayText, 0, text)); } std::string ScintillaCall::GetDefaultFoldDisplayText() { return CallReturnString(Message::GetDefaultFoldDisplayText, 0); } void ScintillaCall::FoldLine(Line line, Scintilla::FoldAction action) { Call(Message::FoldLine, line, static_cast<intptr_t>(action)); } void ScintillaCall::FoldChildren(Line line, Scintilla::FoldAction action) { Call(Message::FoldChildren, line, static_cast<intptr_t>(action)); } void ScintillaCall::ExpandChildren(Line line, Scintilla::FoldLevel level) { Call(Message::ExpandChildren, line, static_cast<intptr_t>(level)); } void ScintillaCall::FoldAll(Scintilla::FoldAction action) { Call(Message::FoldAll, static_cast<uintptr_t>(action)); } void ScintillaCall::EnsureVisible(Line line) { Call(Message::EnsureVisible, line); } void ScintillaCall::SetAutomaticFold(Scintilla::AutomaticFold automaticFold) { Call(Message::SetAutomaticFold, static_cast<uintptr_t>(automaticFold)); } AutomaticFold ScintillaCall::AutomaticFold() { return static_cast<Scintilla::AutomaticFold>(Call(Message::GetAutomaticFold)); } void ScintillaCall::SetFoldFlags(Scintilla::FoldFlag flags) { Call(Message::SetFoldFlags, static_cast<uintptr_t>(flags)); } void ScintillaCall::EnsureVisibleEnforcePolicy(Line line) { Call(Message::EnsureVisibleEnforcePolicy, line); } void ScintillaCall::SetTabIndents(bool tabIndents) { Call(Message::SetTabIndents, tabIndents); } bool ScintillaCall::TabIndents() { return Call(Message::GetTabIndents); } void ScintillaCall::SetBackSpaceUnIndents(bool bsUnIndents) { Call(Message::SetBackSpaceUnIndents, bsUnIndents); } bool ScintillaCall::BackSpaceUnIndents() { return Call(Message::GetBackSpaceUnIndents); } void ScintillaCall::SetMouseDwellTime(int periodMilliseconds) { Call(Message::SetMouseDwellTime, periodMilliseconds); } int ScintillaCall::MouseDwellTime() { return static_cast<int>(Call(Message::GetMouseDwellTime)); } Position ScintillaCall::WordStartPosition(Position pos, bool onlyWordCharacters) { return Call(Message::WordStartPosition, pos, onlyWordCharacters); } Position ScintillaCall::WordEndPosition(Position pos, bool onlyWordCharacters) { return Call(Message::WordEndPosition, pos, onlyWordCharacters); } bool ScintillaCall::IsRangeWord(Position start, Position end) { return Call(Message::IsRangeWord, start, end); } void ScintillaCall::SetIdleStyling(Scintilla::IdleStyling idleStyling) { Call(Message::SetIdleStyling, static_cast<uintptr_t>(idleStyling)); } IdleStyling ScintillaCall::IdleStyling() { return static_cast<Scintilla::IdleStyling>(Call(Message::GetIdleStyling)); } void ScintillaCall::SetWrapMode(Scintilla::Wrap wrapMode) { Call(Message::SetWrapMode, static_cast<uintptr_t>(wrapMode)); } Wrap ScintillaCall::WrapMode() { return static_cast<Scintilla::Wrap>(Call(Message::GetWrapMode)); } void ScintillaCall::SetWrapVisualFlags(Scintilla::WrapVisualFlag wrapVisualFlags) { Call(Message::SetWrapVisualFlags, static_cast<uintptr_t>(wrapVisualFlags)); } WrapVisualFlag ScintillaCall::WrapVisualFlags() { return static_cast<Scintilla::WrapVisualFlag>(Call(Message::GetWrapVisualFlags)); } void ScintillaCall::SetWrapVisualFlagsLocation(Scintilla::WrapVisualLocation wrapVisualFlagsLocation) { Call(Message::SetWrapVisualFlagsLocation, static_cast<uintptr_t>(wrapVisualFlagsLocation)); } WrapVisualLocation ScintillaCall::WrapVisualFlagsLocation() { return static_cast<Scintilla::WrapVisualLocation>(Call(Message::GetWrapVisualFlagsLocation)); } void ScintillaCall::SetWrapStartIndent(int indent) { Call(Message::SetWrapStartIndent, indent); } int ScintillaCall::WrapStartIndent() { return static_cast<int>(Call(Message::GetWrapStartIndent)); } void ScintillaCall::SetWrapIndentMode(Scintilla::WrapIndentMode wrapIndentMode) { Call(Message::SetWrapIndentMode, static_cast<uintptr_t>(wrapIndentMode)); } WrapIndentMode ScintillaCall::WrapIndentMode() { return static_cast<Scintilla::WrapIndentMode>(Call(Message::GetWrapIndentMode)); } void ScintillaCall::SetLayoutCache(Scintilla::LineCache cacheMode) { Call(Message::SetLayoutCache, static_cast<uintptr_t>(cacheMode)); } LineCache ScintillaCall::LayoutCache() { return static_cast<Scintilla::LineCache>(Call(Message::GetLayoutCache)); } void ScintillaCall::SetScrollWidth(int pixelWidth) { Call(Message::SetScrollWidth, pixelWidth); } int ScintillaCall::ScrollWidth() { return static_cast<int>(Call(Message::GetScrollWidth)); } void ScintillaCall::SetScrollWidthTracking(bool tracking) { Call(Message::SetScrollWidthTracking, tracking); } bool ScintillaCall::ScrollWidthTracking() { return Call(Message::GetScrollWidthTracking); } int ScintillaCall::TextWidth(int style, const char *text) { return static_cast<int>(CallString(Message::TextWidth, style, text)); } void ScintillaCall::SetEndAtLastLine(bool endAtLastLine) { Call(Message::SetEndAtLastLine, endAtLastLine); } bool ScintillaCall::EndAtLastLine() { return Call(Message::GetEndAtLastLine); } int ScintillaCall::TextHeight(Line line) { return static_cast<int>(Call(Message::TextHeight, line)); } void ScintillaCall::SetVScrollBar(bool visible) { Call(Message::SetVScrollBar, visible); } bool ScintillaCall::VScrollBar() { return Call(Message::GetVScrollBar); } void ScintillaCall::AppendText(Position length, const char *text) { CallString(Message::AppendText, length, text); } PhasesDraw ScintillaCall::PhasesDraw() { return static_cast<Scintilla::PhasesDraw>(Call(Message::GetPhasesDraw)); } void ScintillaCall::SetPhasesDraw(Scintilla::PhasesDraw phases) { Call(Message::SetPhasesDraw, static_cast<uintptr_t>(phases)); } void ScintillaCall::SetFontQuality(Scintilla::FontQuality fontQuality) { Call(Message::SetFontQuality, static_cast<uintptr_t>(fontQuality)); } FontQuality ScintillaCall::FontQuality() { return static_cast<Scintilla::FontQuality>(Call(Message::GetFontQuality)); } void ScintillaCall::SetFirstVisibleLine(Line displayLine) { Call(Message::SetFirstVisibleLine, displayLine); } void ScintillaCall::SetMultiPaste(Scintilla::MultiPaste multiPaste) { Call(Message::SetMultiPaste, static_cast<uintptr_t>(multiPaste)); } MultiPaste ScintillaCall::MultiPaste() { return static_cast<Scintilla::MultiPaste>(Call(Message::GetMultiPaste)); } int ScintillaCall::Tag(int tagNumber, char *tagValue) { return static_cast<int>(CallPointer(Message::GetTag, tagNumber, tagValue)); } std::string ScintillaCall::Tag(int tagNumber) { return CallReturnString(Message::GetTag, tagNumber); } void ScintillaCall::LinesJoin() { Call(Message::LinesJoin); } void ScintillaCall::LinesSplit(int pixelWidth) { Call(Message::LinesSplit, pixelWidth); } void ScintillaCall::SetFoldMarginColour(bool useSetting, Colour back) { Call(Message::SetFoldMarginColour, useSetting, back); } void ScintillaCall::SetFoldMarginHiColour(bool useSetting, Colour fore) { Call(Message::SetFoldMarginHiColour, useSetting, fore); } void ScintillaCall::SetAccessibility(Scintilla::Accessibility accessibility) { Call(Message::SetAccessibility, static_cast<uintptr_t>(accessibility)); } Accessibility ScintillaCall::Accessibility() { return static_cast<Scintilla::Accessibility>(Call(Message::GetAccessibility)); } void ScintillaCall::LineDown() { Call(Message::LineDown); } void ScintillaCall::LineDownExtend() { Call(Message::LineDownExtend); } void ScintillaCall::LineUp() { Call(Message::LineUp); } void ScintillaCall::LineUpExtend() { Call(Message::LineUpExtend); } void ScintillaCall::CharLeft() { Call(Message::CharLeft); } void ScintillaCall::CharLeftExtend() { Call(Message::CharLeftExtend); } void ScintillaCall::CharRight() { Call(Message::CharRight); } void ScintillaCall::CharRightExtend() { Call(Message::CharRightExtend); } void ScintillaCall::WordLeft() { Call(Message::WordLeft); } void ScintillaCall::WordLeftExtend() { Call(Message::WordLeftExtend); } void ScintillaCall::WordRight() { Call(Message::WordRight); } void ScintillaCall::WordRightExtend() { Call(Message::WordRightExtend); } void ScintillaCall::Home() { Call(Message::Home); } void ScintillaCall::HomeExtend() { Call(Message::HomeExtend); } void ScintillaCall::LineEnd() { Call(Message::LineEnd); } void ScintillaCall::LineEndExtend() { Call(Message::LineEndExtend); } void ScintillaCall::DocumentStart() { Call(Message::DocumentStart); } void ScintillaCall::DocumentStartExtend() { Call(Message::DocumentStartExtend); } void ScintillaCall::DocumentEnd() { Call(Message::DocumentEnd); } void ScintillaCall::DocumentEndExtend() { Call(Message::DocumentEndExtend); } void ScintillaCall::PageUp() { Call(Message::PageUp); } void ScintillaCall::PageUpExtend() { Call(Message::PageUpExtend); } void ScintillaCall::PageDown() { Call(Message::PageDown); } void ScintillaCall::PageDownExtend() { Call(Message::PageDownExtend); } void ScintillaCall::EditToggleOvertype() { Call(Message::EditToggleOvertype); } void ScintillaCall::Cancel() { Call(Message::Cancel); } void ScintillaCall::DeleteBack() { Call(Message::DeleteBack); } void ScintillaCall::Tab() { Call(Message::Tab); } void ScintillaCall::BackTab() { Call(Message::BackTab); } void ScintillaCall::NewLine() { Call(Message::NewLine); } void ScintillaCall::FormFeed() { Call(Message::FormFeed); } void ScintillaCall::VCHome() { Call(Message::VCHome); } void ScintillaCall::VCHomeExtend() { Call(Message::VCHomeExtend); } void ScintillaCall::ZoomIn() { Call(Message::ZoomIn); } void ScintillaCall::ZoomOut() { Call(Message::ZoomOut); } void ScintillaCall::DelWordLeft() { Call(Message::DelWordLeft); } void ScintillaCall::DelWordRight() { Call(Message::DelWordRight); } void ScintillaCall::DelWordRightEnd() { Call(Message::DelWordRightEnd); } void ScintillaCall::LineCut() { Call(Message::LineCut); } void ScintillaCall::LineDelete() { Call(Message::LineDelete); } void ScintillaCall::LineTranspose() { Call(Message::LineTranspose); } void ScintillaCall::LineReverse() { Call(Message::LineReverse); } void ScintillaCall::LineDuplicate() { Call(Message::LineDuplicate); } void ScintillaCall::LowerCase() { Call(Message::LowerCase); } void ScintillaCall::UpperCase() { Call(Message::UpperCase); } void ScintillaCall::LineScrollDown() { Call(Message::LineScrollDown); } void ScintillaCall::LineScrollUp() { Call(Message::LineScrollUp); } void ScintillaCall::DeleteBackNotLine() { Call(Message::DeleteBackNotLine); } void ScintillaCall::HomeDisplay() { Call(Message::HomeDisplay); } void ScintillaCall::HomeDisplayExtend() { Call(Message::HomeDisplayExtend); } void ScintillaCall::LineEndDisplay() { Call(Message::LineEndDisplay); } void ScintillaCall::LineEndDisplayExtend() { Call(Message::LineEndDisplayExtend); } void ScintillaCall::HomeWrap() { Call(Message::HomeWrap); } void ScintillaCall::HomeWrapExtend() { Call(Message::HomeWrapExtend); } void ScintillaCall::LineEndWrap() { Call(Message::LineEndWrap); } void ScintillaCall::LineEndWrapExtend() { Call(Message::LineEndWrapExtend); } void ScintillaCall::VCHomeWrap() { Call(Message::VCHomeWrap); } void ScintillaCall::VCHomeWrapExtend() { Call(Message::VCHomeWrapExtend); } void ScintillaCall::LineCopy() { Call(Message::LineCopy); } void ScintillaCall::MoveCaretInsideView() { Call(Message::MoveCaretInsideView); } Position ScintillaCall::LineLength(Line line) { return Call(Message::LineLength, line); } void ScintillaCall::BraceHighlight(Position posA, Position posB) { Call(Message::BraceHighlight, posA, posB); } void ScintillaCall::BraceHighlightIndicator(bool useSetting, int indicator) { Call(Message::BraceHighlightIndicator, useSetting, indicator); } void ScintillaCall::BraceBadLight(Position pos) { Call(Message::BraceBadLight, pos); } void ScintillaCall::BraceBadLightIndicator(bool useSetting, int indicator) { Call(Message::BraceBadLightIndicator, useSetting, indicator); } Position ScintillaCall::BraceMatch(Position pos, int maxReStyle) { return Call(Message::BraceMatch, pos, maxReStyle); } Position ScintillaCall::BraceMatchNext(Position pos, Position startPos) { return Call(Message::BraceMatchNext, pos, startPos); } bool ScintillaCall::ViewEOL() { return Call(Message::GetViewEOL); } void ScintillaCall::SetViewEOL(bool visible) { Call(Message::SetViewEOL, visible); } void *ScintillaCall::DocPointer() { return reinterpret_cast<void *>(Call(Message::GetDocPointer)); } void ScintillaCall::SetDocPointer(void *doc) { CallPointer(Message::SetDocPointer, 0, doc); } void ScintillaCall::SetModEventMask(Scintilla::ModificationFlags eventMask) { Call(Message::SetModEventMask, static_cast<uintptr_t>(eventMask)); } Position ScintillaCall::EdgeColumn() { return Call(Message::GetEdgeColumn); } void ScintillaCall::SetEdgeColumn(Position column) { Call(Message::SetEdgeColumn, column); } EdgeVisualStyle ScintillaCall::EdgeMode() { return static_cast<Scintilla::EdgeVisualStyle>(Call(Message::GetEdgeMode)); } void ScintillaCall::SetEdgeMode(Scintilla::EdgeVisualStyle edgeMode) { Call(Message::SetEdgeMode, static_cast<uintptr_t>(edgeMode)); } Colour ScintillaCall::EdgeColour() { return static_cast<Colour>(Call(Message::GetEdgeColour)); } void ScintillaCall::SetEdgeColour(Colour edgeColour) { Call(Message::SetEdgeColour, edgeColour); } void ScintillaCall::MultiEdgeAddLine(Position column, Colour edgeColour) { Call(Message::MultiEdgeAddLine, column, edgeColour); } void ScintillaCall::MultiEdgeClearAll() { Call(Message::MultiEdgeClearAll); } Position ScintillaCall::MultiEdgeColumn(int which) { return Call(Message::GetMultiEdgeColumn, which); } void ScintillaCall::SearchAnchor() { Call(Message::SearchAnchor); } Position ScintillaCall::SearchNext(Scintilla::FindOption searchFlags, const char *text) { return CallString(Message::SearchNext, static_cast<uintptr_t>(searchFlags), text); } Position ScintillaCall::SearchPrev(Scintilla::FindOption searchFlags, const char *text) { return CallString(Message::SearchPrev, static_cast<uintptr_t>(searchFlags), text); } Line ScintillaCall::LinesOnScreen() { return Call(Message::LinesOnScreen); } void ScintillaCall::UsePopUp(Scintilla::PopUp popUpMode) { Call(Message::UsePopUp, static_cast<uintptr_t>(popUpMode)); } bool ScintillaCall::SelectionIsRectangle() { return Call(Message::SelectionIsRectangle); } void ScintillaCall::SetZoom(int zoomInPoints) { Call(Message::SetZoom, zoomInPoints); } int ScintillaCall::Zoom() { return static_cast<int>(Call(Message::GetZoom)); } void *ScintillaCall::CreateDocument(Position bytes, Scintilla::DocumentOption documentOptions) { return reinterpret_cast<void *>(Call(Message::CreateDocument, bytes, static_cast<intptr_t>(documentOptions))); } void ScintillaCall::AddRefDocument(void *doc) { CallPointer(Message::AddRefDocument, 0, doc); } void ScintillaCall::ReleaseDocument(void *doc) { CallPointer(Message::ReleaseDocument, 0, doc); } DocumentOption ScintillaCall::DocumentOptions() { return static_cast<Scintilla::DocumentOption>(Call(Message::GetDocumentOptions)); } ModificationFlags ScintillaCall::ModEventMask() { return static_cast<Scintilla::ModificationFlags>(Call(Message::GetModEventMask)); } void ScintillaCall::SetCommandEvents(bool commandEvents) { Call(Message::SetCommandEvents, commandEvents); } bool ScintillaCall::CommandEvents() { return Call(Message::GetCommandEvents); } void ScintillaCall::SetFocus(bool focus) { Call(Message::SetFocus, focus); } bool ScintillaCall::Focus() { return Call(Message::GetFocus); } void ScintillaCall::SetStatus(Scintilla::Status status) { Call(Message::SetStatus, static_cast<uintptr_t>(status)); } Status ScintillaCall::Status() { return static_cast<Scintilla::Status>(Call(Message::GetStatus)); } void ScintillaCall::SetMouseDownCaptures(bool captures) { Call(Message::SetMouseDownCaptures, captures); } bool ScintillaCall::MouseDownCaptures() { return Call(Message::GetMouseDownCaptures); } void ScintillaCall::SetMouseWheelCaptures(bool captures) { Call(Message::SetMouseWheelCaptures, captures); } bool ScintillaCall::MouseWheelCaptures() { return Call(Message::GetMouseWheelCaptures); } void ScintillaCall::SetCursor(Scintilla::CursorShape cursorType) { Call(Message::SetCursor, static_cast<uintptr_t>(cursorType)); } CursorShape ScintillaCall::Cursor() { return static_cast<Scintilla::CursorShape>(Call(Message::GetCursor)); } void ScintillaCall::SetControlCharSymbol(int symbol) { Call(Message::SetControlCharSymbol, symbol); } int ScintillaCall::ControlCharSymbol() { return static_cast<int>(Call(Message::GetControlCharSymbol)); } void ScintillaCall::WordPartLeft() { Call(Message::WordPartLeft); } void ScintillaCall::WordPartLeftExtend() { Call(Message::WordPartLeftExtend); } void ScintillaCall::WordPartRight() { Call(Message::WordPartRight); } void ScintillaCall::WordPartRightExtend() { Call(Message::WordPartRightExtend); } void ScintillaCall::SetVisiblePolicy(Scintilla::VisiblePolicy visiblePolicy, int visibleSlop) { Call(Message::SetVisiblePolicy, static_cast<uintptr_t>(visiblePolicy), visibleSlop); } void ScintillaCall::DelLineLeft() { Call(Message::DelLineLeft); } void ScintillaCall::DelLineRight() { Call(Message::DelLineRight); } void ScintillaCall::SetXOffset(int xOffset) { Call(Message::SetXOffset, xOffset); } int ScintillaCall::XOffset() { return static_cast<int>(Call(Message::GetXOffset)); } void ScintillaCall::ChooseCaretX() { Call(Message::ChooseCaretX); } void ScintillaCall::GrabFocus() { Call(Message::GrabFocus); } void ScintillaCall::SetXCaretPolicy(Scintilla::CaretPolicy caretPolicy, int caretSlop) { Call(Message::SetXCaretPolicy, static_cast<uintptr_t>(caretPolicy), caretSlop); } void ScintillaCall::SetYCaretPolicy(Scintilla::CaretPolicy caretPolicy, int caretSlop) { Call(Message::SetYCaretPolicy, static_cast<uintptr_t>(caretPolicy), caretSlop); } void ScintillaCall::SetPrintWrapMode(Scintilla::Wrap wrapMode) { Call(Message::SetPrintWrapMode, static_cast<uintptr_t>(wrapMode)); } Wrap ScintillaCall::PrintWrapMode() { return static_cast<Scintilla::Wrap>(Call(Message::GetPrintWrapMode)); } void ScintillaCall::SetHotspotActiveFore(bool useSetting, Colour fore) { Call(Message::SetHotspotActiveFore, useSetting, fore); } Colour ScintillaCall::HotspotActiveFore() { return static_cast<Colour>(Call(Message::GetHotspotActiveFore)); } void ScintillaCall::SetHotspotActiveBack(bool useSetting, Colour back) { Call(Message::SetHotspotActiveBack, useSetting, back); } Colour ScintillaCall::HotspotActiveBack() { return static_cast<Colour>(Call(Message::GetHotspotActiveBack)); } void ScintillaCall::SetHotspotActiveUnderline(bool underline) { Call(Message::SetHotspotActiveUnderline, underline); } bool ScintillaCall::HotspotActiveUnderline() { return Call(Message::GetHotspotActiveUnderline); } void ScintillaCall::SetHotspotSingleLine(bool singleLine) { Call(Message::SetHotspotSingleLine, singleLine); } bool ScintillaCall::HotspotSingleLine() { return Call(Message::GetHotspotSingleLine); } void ScintillaCall::ParaDown() { Call(Message::ParaDown); } void ScintillaCall::ParaDownExtend() { Call(Message::ParaDownExtend); } void ScintillaCall::ParaUp() { Call(Message::ParaUp); } void ScintillaCall::ParaUpExtend() { Call(Message::ParaUpExtend); } Position ScintillaCall::PositionBefore(Position pos) { return Call(Message::PositionBefore, pos); } Position ScintillaCall::PositionAfter(Position pos) { return Call(Message::PositionAfter, pos); } Position ScintillaCall::PositionRelative(Position pos, Position relative) { return Call(Message::PositionRelative, pos, relative); } Position ScintillaCall::PositionRelativeCodeUnits(Position pos, Position relative) { return Call(Message::PositionRelativeCodeUnits, pos, relative); } void ScintillaCall::CopyRange(Position start, Position end) { Call(Message::CopyRange, start, end); } void ScintillaCall::CopyText(Position length, const char *text) { CallString(Message::CopyText, length, text); } void ScintillaCall::SetSelectionMode(Scintilla::SelectionMode selectionMode) { Call(Message::SetSelectionMode, static_cast<uintptr_t>(selectionMode)); } SelectionMode ScintillaCall::SelectionMode() { return static_cast<Scintilla::SelectionMode>(Call(Message::GetSelectionMode)); } bool ScintillaCall::MoveExtendsSelection() { return Call(Message::GetMoveExtendsSelection); } Position ScintillaCall::GetLineSelStartPosition(Line line) { return Call(Message::GetLineSelStartPosition, line); } Position ScintillaCall::GetLineSelEndPosition(Line line) { return Call(Message::GetLineSelEndPosition, line); } void ScintillaCall::LineDownRectExtend() { Call(Message::LineDownRectExtend); } void ScintillaCall::LineUpRectExtend() { Call(Message::LineUpRectExtend); } void ScintillaCall::CharLeftRectExtend() { Call(Message::CharLeftRectExtend); } void ScintillaCall::CharRightRectExtend() { Call(Message::CharRightRectExtend); } void ScintillaCall::HomeRectExtend() { Call(Message::HomeRectExtend); } void ScintillaCall::VCHomeRectExtend() { Call(Message::VCHomeRectExtend); } void ScintillaCall::LineEndRectExtend() { Call(Message::LineEndRectExtend); } void ScintillaCall::PageUpRectExtend() { Call(Message::PageUpRectExtend); } void ScintillaCall::PageDownRectExtend() { Call(Message::PageDownRectExtend); } void ScintillaCall::StutteredPageUp() { Call(Message::StutteredPageUp); } void ScintillaCall::StutteredPageUpExtend() { Call(Message::StutteredPageUpExtend); } void ScintillaCall::StutteredPageDown() { Call(Message::StutteredPageDown); } void ScintillaCall::StutteredPageDownExtend() { Call(Message::StutteredPageDownExtend); } void ScintillaCall::WordLeftEnd() { Call(Message::WordLeftEnd); } void ScintillaCall::WordLeftEndExtend() { Call(Message::WordLeftEndExtend); } void ScintillaCall::WordRightEnd() { Call(Message::WordRightEnd); } void ScintillaCall::WordRightEndExtend() { Call(Message::WordRightEndExtend); } void ScintillaCall::SetWhitespaceChars(const char *characters) { CallString(Message::SetWhitespaceChars, 0, characters); } int ScintillaCall::WhitespaceChars(char *characters) { return static_cast<int>(CallPointer(Message::GetWhitespaceChars, 0, characters)); } std::string ScintillaCall::WhitespaceChars() { return CallReturnString(Message::GetWhitespaceChars, 0); } void ScintillaCall::SetPunctuationChars(const char *characters) { CallString(Message::SetPunctuationChars, 0, characters); } int ScintillaCall::PunctuationChars(char *characters) { return static_cast<int>(CallPointer(Message::GetPunctuationChars, 0, characters)); } std::string ScintillaCall::PunctuationChars() { return CallReturnString(Message::GetPunctuationChars, 0); } void ScintillaCall::SetCharsDefault() { Call(Message::SetCharsDefault); } int ScintillaCall::AutoCGetCurrent() { return static_cast<int>(Call(Message::AutoCGetCurrent)); } int ScintillaCall::AutoCGetCurrentText(char *text) { return static_cast<int>(CallPointer(Message::AutoCGetCurrentText, 0, text)); } std::string ScintillaCall::AutoCGetCurrentText() { return CallReturnString(Message::AutoCGetCurrentText, 0); } void ScintillaCall::AutoCSetCaseInsensitiveBehaviour(Scintilla::CaseInsensitiveBehaviour behaviour) { Call(Message::AutoCSetCaseInsensitiveBehaviour, static_cast<uintptr_t>(behaviour)); } CaseInsensitiveBehaviour ScintillaCall::AutoCGetCaseInsensitiveBehaviour() { return static_cast<Scintilla::CaseInsensitiveBehaviour>(Call(Message::AutoCGetCaseInsensitiveBehaviour)); } void ScintillaCall::AutoCSetMulti(Scintilla::MultiAutoComplete multi) { Call(Message::AutoCSetMulti, static_cast<uintptr_t>(multi)); } MultiAutoComplete ScintillaCall::AutoCGetMulti() { return static_cast<Scintilla::MultiAutoComplete>(Call(Message::AutoCGetMulti)); } void ScintillaCall::AutoCSetOrder(Scintilla::Ordering order) { Call(Message::AutoCSetOrder, static_cast<uintptr_t>(order)); } Ordering ScintillaCall::AutoCGetOrder() { return static_cast<Scintilla::Ordering>(Call(Message::AutoCGetOrder)); } void ScintillaCall::Allocate(Position bytes) { Call(Message::Allocate, bytes); } Position ScintillaCall::TargetAsUTF8(char *s) { return CallPointer(Message::TargetAsUTF8, 0, s); } std::string ScintillaCall::TargetAsUTF8() { return CallReturnString(Message::TargetAsUTF8, 0); } void ScintillaCall::SetLengthForEncode(Position bytes) { Call(Message::SetLengthForEncode, bytes); } Position ScintillaCall::EncodedFromUTF8(const char *utf8, char *encoded) { return CallPointer(Message::EncodedFromUTF8, reinterpret_cast<uintptr_t>(utf8), encoded); } std::string ScintillaCall::EncodedFromUTF8(const char *utf8) { return CallReturnString(Message::EncodedFromUTF8, reinterpret_cast<uintptr_t>(utf8)); } Position ScintillaCall::FindColumn(Line line, Position column) { return Call(Message::FindColumn, line, column); } CaretSticky ScintillaCall::CaretSticky() { return static_cast<Scintilla::CaretSticky>(Call(Message::GetCaretSticky)); } void ScintillaCall::SetCaretSticky(Scintilla::CaretSticky useCaretStickyBehaviour) { Call(Message::SetCaretSticky, static_cast<uintptr_t>(useCaretStickyBehaviour)); } void ScintillaCall::ToggleCaretSticky() { Call(Message::ToggleCaretSticky); } void ScintillaCall::SetPasteConvertEndings(bool convert) { Call(Message::SetPasteConvertEndings, convert); } bool ScintillaCall::PasteConvertEndings() { return Call(Message::GetPasteConvertEndings); } void ScintillaCall::ReplaceRectangular(Position length, const char *text) { CallString(Message::ReplaceRectangular, length, text); } void ScintillaCall::SelectionDuplicate() { Call(Message::SelectionDuplicate); } void ScintillaCall::SetCaretLineBackAlpha(Scintilla::Alpha alpha) { Call(Message::SetCaretLineBackAlpha, static_cast<uintptr_t>(alpha)); } Alpha ScintillaCall::CaretLineBackAlpha() { return static_cast<Scintilla::Alpha>(Call(Message::GetCaretLineBackAlpha)); } void ScintillaCall::SetCaretStyle(Scintilla::CaretStyle caretStyle) { Call(Message::SetCaretStyle, static_cast<uintptr_t>(caretStyle)); } CaretStyle ScintillaCall::CaretStyle() { return static_cast<Scintilla::CaretStyle>(Call(Message::GetCaretStyle)); } void ScintillaCall::SetIndicatorCurrent(int indicator) { Call(Message::SetIndicatorCurrent, indicator); } int ScintillaCall::IndicatorCurrent() { return static_cast<int>(Call(Message::GetIndicatorCurrent)); } void ScintillaCall::SetIndicatorValue(int value) { Call(Message::SetIndicatorValue, value); } int ScintillaCall::IndicatorValue() { return static_cast<int>(Call(Message::GetIndicatorValue)); } void ScintillaCall::IndicatorFillRange(Position start, Position lengthFill) { Call(Message::IndicatorFillRange, start, lengthFill); } void ScintillaCall::IndicatorClearRange(Position start, Position lengthClear) { Call(Message::IndicatorClearRange, start, lengthClear); } int ScintillaCall::IndicatorAllOnFor(Position pos) { return static_cast<int>(Call(Message::IndicatorAllOnFor, pos)); } int ScintillaCall::IndicatorValueAt(int indicator, Position pos) { return static_cast<int>(Call(Message::IndicatorValueAt, indicator, pos)); } Position ScintillaCall::IndicatorStart(int indicator, Position pos) { return Call(Message::IndicatorStart, indicator, pos); } Position ScintillaCall::IndicatorEnd(int indicator, Position pos) { return Call(Message::IndicatorEnd, indicator, pos); } void ScintillaCall::SetPositionCache(int size) { Call(Message::SetPositionCache, size); } int ScintillaCall::PositionCache() { return static_cast<int>(Call(Message::GetPositionCache)); } void ScintillaCall::CopyAllowLine() { Call(Message::CopyAllowLine); } void *ScintillaCall::CharacterPointer() { return reinterpret_cast<void *>(Call(Message::GetCharacterPointer)); } void *ScintillaCall::RangePointer(Position start, Position lengthRange) { return reinterpret_cast<void *>(Call(Message::GetRangePointer, start, lengthRange)); } Position ScintillaCall::GapPosition() { return Call(Message::GetGapPosition); } void ScintillaCall::IndicSetAlpha(int indicator, Scintilla::Alpha alpha) { Call(Message::IndicSetAlpha, indicator, static_cast<intptr_t>(alpha)); } Alpha ScintillaCall::IndicGetAlpha(int indicator) { return static_cast<Scintilla::Alpha>(Call(Message::IndicGetAlpha, indicator)); } void ScintillaCall::IndicSetOutlineAlpha(int indicator, Scintilla::Alpha alpha) { Call(Message::IndicSetOutlineAlpha, indicator, static_cast<intptr_t>(alpha)); } Alpha ScintillaCall::IndicGetOutlineAlpha(int indicator) { return static_cast<Scintilla::Alpha>(Call(Message::IndicGetOutlineAlpha, indicator)); } void ScintillaCall::SetExtraAscent(int extraAscent) { Call(Message::SetExtraAscent, extraAscent); } int ScintillaCall::ExtraAscent() { return static_cast<int>(Call(Message::GetExtraAscent)); } void ScintillaCall::SetExtraDescent(int extraDescent) { Call(Message::SetExtraDescent, extraDescent); } int ScintillaCall::ExtraDescent() { return static_cast<int>(Call(Message::GetExtraDescent)); } int ScintillaCall::MarkerSymbolDefined(int markerNumber) { return static_cast<int>(Call(Message::MarkerSymbolDefined, markerNumber)); } void ScintillaCall::MarginSetText(Line line, const char *text) { CallString(Message::MarginSetText, line, text); } int ScintillaCall::MarginGetText(Line line, char *text) { return static_cast<int>(CallPointer(Message::MarginGetText, line, text)); } std::string ScintillaCall::MarginGetText(Line line) { return CallReturnString(Message::MarginGetText, line); } void ScintillaCall::MarginSetStyle(Line line, int style) { Call(Message::MarginSetStyle, line, style); } int ScintillaCall::MarginGetStyle(Line line) { return static_cast<int>(Call(Message::MarginGetStyle, line)); } void ScintillaCall::MarginSetStyles(Line line, const char *styles) { CallString(Message::MarginSetStyles, line, styles); } int ScintillaCall::MarginGetStyles(Line line, char *styles) { return static_cast<int>(CallPointer(Message::MarginGetStyles, line, styles)); } std::string ScintillaCall::MarginGetStyles(Line line) { return CallReturnString(Message::MarginGetStyles, line); } void ScintillaCall::MarginTextClearAll() { Call(Message::MarginTextClearAll); } void ScintillaCall::MarginSetStyleOffset(int style) { Call(Message::MarginSetStyleOffset, style); } int ScintillaCall::MarginGetStyleOffset() { return static_cast<int>(Call(Message::MarginGetStyleOffset)); } void ScintillaCall::SetMarginOptions(Scintilla::MarginOption marginOptions) { Call(Message::SetMarginOptions, static_cast<uintptr_t>(marginOptions)); } MarginOption ScintillaCall::MarginOptions() { return static_cast<Scintilla::MarginOption>(Call(Message::GetMarginOptions)); } void ScintillaCall::AnnotationSetText(Line line, const char *text) { CallString(Message::AnnotationSetText, line, text); } int ScintillaCall::AnnotationGetText(Line line, char *text) { return static_cast<int>(CallPointer(Message::AnnotationGetText, line, text)); } std::string ScintillaCall::AnnotationGetText(Line line) { return CallReturnString(Message::AnnotationGetText, line); } void ScintillaCall::AnnotationSetStyle(Line line, int style) { Call(Message::AnnotationSetStyle, line, style); } int ScintillaCall::AnnotationGetStyle(Line line) { return static_cast<int>(Call(Message::AnnotationGetStyle, line)); } void ScintillaCall::AnnotationSetStyles(Line line, const char *styles) { CallString(Message::AnnotationSetStyles, line, styles); } int ScintillaCall::AnnotationGetStyles(Line line, char *styles) { return static_cast<int>(CallPointer(Message::AnnotationGetStyles, line, styles)); } std::string ScintillaCall::AnnotationGetStyles(Line line) { return CallReturnString(Message::AnnotationGetStyles, line); } int ScintillaCall::AnnotationGetLines(Line line) { return static_cast<int>(Call(Message::AnnotationGetLines, line)); } void ScintillaCall::AnnotationClearAll() { Call(Message::AnnotationClearAll); } void ScintillaCall::AnnotationSetVisible(Scintilla::AnnotationVisible visible) { Call(Message::AnnotationSetVisible, static_cast<uintptr_t>(visible)); } AnnotationVisible ScintillaCall::AnnotationGetVisible() { return static_cast<Scintilla::AnnotationVisible>(Call(Message::AnnotationGetVisible)); } void ScintillaCall::AnnotationSetStyleOffset(int style) { Call(Message::AnnotationSetStyleOffset, style); } int ScintillaCall::AnnotationGetStyleOffset() { return static_cast<int>(Call(Message::AnnotationGetStyleOffset)); } void ScintillaCall::ReleaseAllExtendedStyles() { Call(Message::ReleaseAllExtendedStyles); } int ScintillaCall::AllocateExtendedStyles(int numberStyles) { return static_cast<int>(Call(Message::AllocateExtendedStyles, numberStyles)); } void ScintillaCall::AddUndoAction(int token, Scintilla::UndoFlags flags) { Call(Message::AddUndoAction, token, static_cast<intptr_t>(flags)); } Position ScintillaCall::CharPositionFromPoint(int x, int y) { return Call(Message::CharPositionFromPoint, x, y); } Position ScintillaCall::CharPositionFromPointClose(int x, int y) { return Call(Message::CharPositionFromPointClose, x, y); } void ScintillaCall::SetMouseSelectionRectangularSwitch(bool mouseSelectionRectangularSwitch) { Call(Message::SetMouseSelectionRectangularSwitch, mouseSelectionRectangularSwitch); } bool ScintillaCall::MouseSelectionRectangularSwitch() { return Call(Message::GetMouseSelectionRectangularSwitch); } void ScintillaCall::SetMultipleSelection(bool multipleSelection) { Call(Message::SetMultipleSelection, multipleSelection); } bool ScintillaCall::MultipleSelection() { return Call(Message::GetMultipleSelection); } void ScintillaCall::SetAdditionalSelectionTyping(bool additionalSelectionTyping) { Call(Message::SetAdditionalSelectionTyping, additionalSelectionTyping); } bool ScintillaCall::AdditionalSelectionTyping() { return Call(Message::GetAdditionalSelectionTyping); } void ScintillaCall::SetAdditionalCaretsBlink(bool additionalCaretsBlink) { Call(Message::SetAdditionalCaretsBlink, additionalCaretsBlink); } bool ScintillaCall::AdditionalCaretsBlink() { return Call(Message::GetAdditionalCaretsBlink); } void ScintillaCall::SetAdditionalCaretsVisible(bool additionalCaretsVisible) { Call(Message::SetAdditionalCaretsVisible, additionalCaretsVisible); } bool ScintillaCall::AdditionalCaretsVisible() { return Call(Message::GetAdditionalCaretsVisible); } int ScintillaCall::Selections() { return static_cast<int>(Call(Message::GetSelections)); } bool ScintillaCall::SelectionEmpty() { return Call(Message::GetSelectionEmpty); } void ScintillaCall::ClearSelections() { Call(Message::ClearSelections); } void ScintillaCall::SetSelection(Position caret, Position anchor) { Call(Message::SetSelection, caret, anchor); } void ScintillaCall::AddSelection(Position caret, Position anchor) { Call(Message::AddSelection, caret, anchor); } void ScintillaCall::DropSelectionN(int selection) { Call(Message::DropSelectionN, selection); } void ScintillaCall::SetMainSelection(int selection) { Call(Message::SetMainSelection, selection); } int ScintillaCall::MainSelection() { return static_cast<int>(Call(Message::GetMainSelection)); } void ScintillaCall::SetSelectionNCaret(int selection, Position caret) { Call(Message::SetSelectionNCaret, selection, caret); } Position ScintillaCall::SelectionNCaret(int selection) { return Call(Message::GetSelectionNCaret, selection); } void ScintillaCall::SetSelectionNAnchor(int selection, Position anchor) { Call(Message::SetSelectionNAnchor, selection, anchor); } Position ScintillaCall::SelectionNAnchor(int selection) { return Call(Message::GetSelectionNAnchor, selection); } void ScintillaCall::SetSelectionNCaretVirtualSpace(int selection, Position space) { Call(Message::SetSelectionNCaretVirtualSpace, selection, space); } Position ScintillaCall::SelectionNCaretVirtualSpace(int selection) { return Call(Message::GetSelectionNCaretVirtualSpace, selection); } void ScintillaCall::SetSelectionNAnchorVirtualSpace(int selection, Position space) { Call(Message::SetSelectionNAnchorVirtualSpace, selection, space); } Position ScintillaCall::SelectionNAnchorVirtualSpace(int selection) { return Call(Message::GetSelectionNAnchorVirtualSpace, selection); } void ScintillaCall::SetSelectionNStart(int selection, Position anchor) { Call(Message::SetSelectionNStart, selection, anchor); } Position ScintillaCall::SelectionNStart(int selection) { return Call(Message::GetSelectionNStart, selection); } Position ScintillaCall::SelectionNStartVirtualSpace(int selection) { return Call(Message::GetSelectionNStartVirtualSpace, selection); } void ScintillaCall::SetSelectionNEnd(int selection, Position caret) { Call(Message::SetSelectionNEnd, selection, caret); } Position ScintillaCall::SelectionNEndVirtualSpace(int selection) { return Call(Message::GetSelectionNEndVirtualSpace, selection); } Position ScintillaCall::SelectionNEnd(int selection) { return Call(Message::GetSelectionNEnd, selection); } void ScintillaCall::SetRectangularSelectionCaret(Position caret) { Call(Message::SetRectangularSelectionCaret, caret); } Position ScintillaCall::RectangularSelectionCaret() { return Call(Message::GetRectangularSelectionCaret); } void ScintillaCall::SetRectangularSelectionAnchor(Position anchor) { Call(Message::SetRectangularSelectionAnchor, anchor); } Position ScintillaCall::RectangularSelectionAnchor() { return Call(Message::GetRectangularSelectionAnchor); } void ScintillaCall::SetRectangularSelectionCaretVirtualSpace(Position space) { Call(Message::SetRectangularSelectionCaretVirtualSpace, space); } Position ScintillaCall::RectangularSelectionCaretVirtualSpace() { return Call(Message::GetRectangularSelectionCaretVirtualSpace); } void ScintillaCall::SetRectangularSelectionAnchorVirtualSpace(Position space) { Call(Message::SetRectangularSelectionAnchorVirtualSpace, space); } Position ScintillaCall::RectangularSelectionAnchorVirtualSpace() { return Call(Message::GetRectangularSelectionAnchorVirtualSpace); } void ScintillaCall::SetVirtualSpaceOptions(Scintilla::VirtualSpace virtualSpaceOptions) { Call(Message::SetVirtualSpaceOptions, static_cast<uintptr_t>(virtualSpaceOptions)); } VirtualSpace ScintillaCall::VirtualSpaceOptions() { return static_cast<Scintilla::VirtualSpace>(Call(Message::GetVirtualSpaceOptions)); } void ScintillaCall::SetRectangularSelectionModifier(int modifier) { Call(Message::SetRectangularSelectionModifier, modifier); } int ScintillaCall::RectangularSelectionModifier() { return static_cast<int>(Call(Message::GetRectangularSelectionModifier)); } void ScintillaCall::SetAdditionalSelFore(Colour fore) { Call(Message::SetAdditionalSelFore, fore); } void ScintillaCall::SetAdditionalSelBack(Colour back) { Call(Message::SetAdditionalSelBack, back); } void ScintillaCall::SetAdditionalSelAlpha(Scintilla::Alpha alpha) { Call(Message::SetAdditionalSelAlpha, static_cast<uintptr_t>(alpha)); } Alpha ScintillaCall::AdditionalSelAlpha() { return static_cast<Scintilla::Alpha>(Call(Message::GetAdditionalSelAlpha)); } void ScintillaCall::SetAdditionalCaretFore(Colour fore) { Call(Message::SetAdditionalCaretFore, fore); } Colour ScintillaCall::AdditionalCaretFore() { return static_cast<Colour>(Call(Message::GetAdditionalCaretFore)); } void ScintillaCall::RotateSelection() { Call(Message::RotateSelection); } void ScintillaCall::SwapMainAnchorCaret() { Call(Message::SwapMainAnchorCaret); } void ScintillaCall::MultipleSelectAddNext() { Call(Message::MultipleSelectAddNext); } void ScintillaCall::MultipleSelectAddEach() { Call(Message::MultipleSelectAddEach); } int ScintillaCall::ChangeLexerState(Position start, Position end) { return static_cast<int>(Call(Message::ChangeLexerState, start, end)); } Line ScintillaCall::ContractedFoldNext(Line lineStart) { return Call(Message::ContractedFoldNext, lineStart); } void ScintillaCall::VerticalCentreCaret() { Call(Message::VerticalCentreCaret); } void ScintillaCall::MoveSelectedLinesUp() { Call(Message::MoveSelectedLinesUp); } void ScintillaCall::MoveSelectedLinesDown() { Call(Message::MoveSelectedLinesDown); } void ScintillaCall::SetIdentifier(int identifier) { Call(Message::SetIdentifier, identifier); } int ScintillaCall::Identifier() { return static_cast<int>(Call(Message::GetIdentifier)); } void ScintillaCall::RGBAImageSetWidth(int width) { Call(Message::RGBAImageSetWidth, width); } void ScintillaCall::RGBAImageSetHeight(int height) { Call(Message::RGBAImageSetHeight, height); } void ScintillaCall::RGBAImageSetScale(int scalePercent) { Call(Message::RGBAImageSetScale, scalePercent); } void ScintillaCall::MarkerDefineRGBAImage(int markerNumber, const char *pixels) { CallString(Message::MarkerDefineRGBAImage, markerNumber, pixels); } void ScintillaCall::RegisterRGBAImage(int type, const char *pixels) { CallString(Message::RegisterRGBAImage, type, pixels); } void ScintillaCall::ScrollToStart() { Call(Message::ScrollToStart); } void ScintillaCall::ScrollToEnd() { Call(Message::ScrollToEnd); } void ScintillaCall::SetTechnology(Scintilla::Technology technology) { Call(Message::SetTechnology, static_cast<uintptr_t>(technology)); } Technology ScintillaCall::Technology() { return static_cast<Scintilla::Technology>(Call(Message::GetTechnology)); } void *ScintillaCall::CreateLoader(Position bytes, Scintilla::DocumentOption documentOptions) { return reinterpret_cast<void *>(Call(Message::CreateLoader, bytes, static_cast<intptr_t>(documentOptions))); } void ScintillaCall::FindIndicatorShow(Position start, Position end) { Call(Message::FindIndicatorShow, start, end); } void ScintillaCall::FindIndicatorFlash(Position start, Position end) { Call(Message::FindIndicatorFlash, start, end); } void ScintillaCall::FindIndicatorHide() { Call(Message::FindIndicatorHide); } void ScintillaCall::VCHomeDisplay() { Call(Message::VCHomeDisplay); } void ScintillaCall::VCHomeDisplayExtend() { Call(Message::VCHomeDisplayExtend); } bool ScintillaCall::CaretLineVisibleAlways() { return Call(Message::GetCaretLineVisibleAlways); } void ScintillaCall::SetCaretLineVisibleAlways(bool alwaysVisible) { Call(Message::SetCaretLineVisibleAlways, alwaysVisible); } void ScintillaCall::SetLineEndTypesAllowed(Scintilla::LineEndType lineEndBitSet) { Call(Message::SetLineEndTypesAllowed, static_cast<uintptr_t>(lineEndBitSet)); } LineEndType ScintillaCall::LineEndTypesAllowed() { return static_cast<Scintilla::LineEndType>(Call(Message::GetLineEndTypesAllowed)); } LineEndType ScintillaCall::LineEndTypesActive() { return static_cast<Scintilla::LineEndType>(Call(Message::GetLineEndTypesActive)); } void ScintillaCall::SetRepresentation(const char *encodedCharacter, const char *representation) { CallString(Message::SetRepresentation, reinterpret_cast<uintptr_t>(encodedCharacter), representation); } int ScintillaCall::Representation(const char *encodedCharacter, char *representation) { return static_cast<int>(CallPointer(Message::GetRepresentation, reinterpret_cast<uintptr_t>(encodedCharacter), representation)); } std::string ScintillaCall::Representation(const char *encodedCharacter) { return CallReturnString(Message::GetRepresentation, reinterpret_cast<uintptr_t>(encodedCharacter)); } void ScintillaCall::ClearRepresentation(const char *encodedCharacter) { Call(Message::ClearRepresentation, reinterpret_cast<uintptr_t>(encodedCharacter)); } void ScintillaCall::ClearAllRepresentations() { Call(Message::ClearAllRepresentations); } void ScintillaCall::SetRepresentationAppearance(const char *encodedCharacter, Scintilla::RepresentationAppearance appearance) { Call(Message::SetRepresentationAppearance, reinterpret_cast<uintptr_t>(encodedCharacter), static_cast<intptr_t>(appearance)); } RepresentationAppearance ScintillaCall::RepresentationAppearance(const char *encodedCharacter) { return static_cast<Scintilla::RepresentationAppearance>(Call(Message::GetRepresentationAppearance, reinterpret_cast<uintptr_t>(encodedCharacter))); } void ScintillaCall::SetRepresentationColour(const char *encodedCharacter, ColourAlpha colour) { Call(Message::SetRepresentationColour, reinterpret_cast<uintptr_t>(encodedCharacter), colour); } ColourAlpha ScintillaCall::RepresentationColour(const char *encodedCharacter) { return static_cast<ColourAlpha>(Call(Message::GetRepresentationColour, reinterpret_cast<uintptr_t>(encodedCharacter))); } void ScintillaCall::EOLAnnotationSetText(Line line, const char *text) { CallString(Message::EOLAnnotationSetText, line, text); } int ScintillaCall::EOLAnnotationGetText(Line line, char *text) { return static_cast<int>(CallPointer(Message::EOLAnnotationGetText, line, text)); } std::string ScintillaCall::EOLAnnotationGetText(Line line) { return CallReturnString(Message::EOLAnnotationGetText, line); } void ScintillaCall::EOLAnnotationSetStyle(Line line, int style) { Call(Message::EOLAnnotationSetStyle, line, style); } int ScintillaCall::EOLAnnotationGetStyle(Line line) { return static_cast<int>(Call(Message::EOLAnnotationGetStyle, line)); } void ScintillaCall::EOLAnnotationClearAll() { Call(Message::EOLAnnotationClearAll); } void ScintillaCall::EOLAnnotationSetVisible(Scintilla::EOLAnnotationVisible visible) { Call(Message::EOLAnnotationSetVisible, static_cast<uintptr_t>(visible)); } EOLAnnotationVisible ScintillaCall::EOLAnnotationGetVisible() { return static_cast<Scintilla::EOLAnnotationVisible>(Call(Message::EOLAnnotationGetVisible)); } void ScintillaCall::EOLAnnotationSetStyleOffset(int style) { Call(Message::EOLAnnotationSetStyleOffset, style); } int ScintillaCall::EOLAnnotationGetStyleOffset() { return static_cast<int>(Call(Message::EOLAnnotationGetStyleOffset)); } bool ScintillaCall::SupportsFeature(Scintilla::Supports feature) { return Call(Message::SupportsFeature, static_cast<uintptr_t>(feature)); } LineCharacterIndexType ScintillaCall::LineCharacterIndex() { return static_cast<Scintilla::LineCharacterIndexType>(Call(Message::GetLineCharacterIndex)); } void ScintillaCall::AllocateLineCharacterIndex(Scintilla::LineCharacterIndexType lineCharacterIndex) { Call(Message::AllocateLineCharacterIndex, static_cast<uintptr_t>(lineCharacterIndex)); } void ScintillaCall::ReleaseLineCharacterIndex(Scintilla::LineCharacterIndexType lineCharacterIndex) { Call(Message::ReleaseLineCharacterIndex, static_cast<uintptr_t>(lineCharacterIndex)); } Line ScintillaCall::LineFromIndexPosition(Position pos, Scintilla::LineCharacterIndexType lineCharacterIndex) { return Call(Message::LineFromIndexPosition, pos, static_cast<intptr_t>(lineCharacterIndex)); } Position ScintillaCall::IndexPositionFromLine(Line line, Scintilla::LineCharacterIndexType lineCharacterIndex) { return Call(Message::IndexPositionFromLine, line, static_cast<intptr_t>(lineCharacterIndex)); } void ScintillaCall::StartRecord() { Call(Message::StartRecord); } void ScintillaCall::StopRecord() { Call(Message::StopRecord); } int ScintillaCall::Lexer() { return static_cast<int>(Call(Message::GetLexer)); } void ScintillaCall::Colourise(Position start, Position end) { Call(Message::Colourise, start, end); } void ScintillaCall::SetProperty(const char *key, const char *value) { CallString(Message::SetProperty, reinterpret_cast<uintptr_t>(key), value); } void ScintillaCall::SetKeyWords(int keyWordSet, const char *keyWords) { CallString(Message::SetKeyWords, keyWordSet, keyWords); } int ScintillaCall::Property(const char *key, char *value) { return static_cast<int>(CallPointer(Message::GetProperty, reinterpret_cast<uintptr_t>(key), value)); } std::string ScintillaCall::Property(const char *key) { return CallReturnString(Message::GetProperty, reinterpret_cast<uintptr_t>(key)); } int ScintillaCall::PropertyExpanded(const char *key, char *value) { return static_cast<int>(CallPointer(Message::GetPropertyExpanded, reinterpret_cast<uintptr_t>(key), value)); } std::string ScintillaCall::PropertyExpanded(const char *key) { return CallReturnString(Message::GetPropertyExpanded, reinterpret_cast<uintptr_t>(key)); } int ScintillaCall::PropertyInt(const char *key, int defaultValue) { return static_cast<int>(Call(Message::GetPropertyInt, reinterpret_cast<uintptr_t>(key), defaultValue)); } int ScintillaCall::LexerLanguage(char *language) { return static_cast<int>(CallPointer(Message::GetLexerLanguage, 0, language)); } std::string ScintillaCall::LexerLanguage() { return CallReturnString(Message::GetLexerLanguage, 0); } void *ScintillaCall::PrivateLexerCall(int operation, void *pointer) { return reinterpret_cast<void *>(CallPointer(Message::PrivateLexerCall, operation, pointer)); } int ScintillaCall::PropertyNames(char *names) { return static_cast<int>(CallPointer(Message::PropertyNames, 0, names)); } std::string ScintillaCall::PropertyNames() { return CallReturnString(Message::PropertyNames, 0); } TypeProperty ScintillaCall::PropertyType(const char *name) { return static_cast<Scintilla::TypeProperty>(Call(Message::PropertyType, reinterpret_cast<uintptr_t>(name))); } int ScintillaCall::DescribeProperty(const char *name, char *description) { return static_cast<int>(CallPointer(Message::DescribeProperty, reinterpret_cast<uintptr_t>(name), description)); } std::string ScintillaCall::DescribeProperty(const char *name) { return CallReturnString(Message::DescribeProperty, reinterpret_cast<uintptr_t>(name)); } int ScintillaCall::DescribeKeyWordSets(char *descriptions) { return static_cast<int>(CallPointer(Message::DescribeKeyWordSets, 0, descriptions)); } std::string ScintillaCall::DescribeKeyWordSets() { return CallReturnString(Message::DescribeKeyWordSets, 0); } LineEndType ScintillaCall::LineEndTypesSupported() { return static_cast<Scintilla::LineEndType>(Call(Message::GetLineEndTypesSupported)); } int ScintillaCall::AllocateSubStyles(int styleBase, int numberStyles) { return static_cast<int>(Call(Message::AllocateSubStyles, styleBase, numberStyles)); } int ScintillaCall::SubStylesStart(int styleBase) { return static_cast<int>(Call(Message::GetSubStylesStart, styleBase)); } int ScintillaCall::SubStylesLength(int styleBase) { return static_cast<int>(Call(Message::GetSubStylesLength, styleBase)); } int ScintillaCall::StyleFromSubStyle(int subStyle) { return static_cast<int>(Call(Message::GetStyleFromSubStyle, subStyle)); } int ScintillaCall::PrimaryStyleFromStyle(int style) { return static_cast<int>(Call(Message::GetPrimaryStyleFromStyle, style)); } void ScintillaCall::FreeSubStyles() { Call(Message::FreeSubStyles); } void ScintillaCall::SetIdentifiers(int style, const char *identifiers) { CallString(Message::SetIdentifiers, style, identifiers); } int ScintillaCall::DistanceToSecondaryStyles() { return static_cast<int>(Call(Message::DistanceToSecondaryStyles)); } int ScintillaCall::SubStyleBases(char *styles) { return static_cast<int>(CallPointer(Message::GetSubStyleBases, 0, styles)); } std::string ScintillaCall::SubStyleBases() { return CallReturnString(Message::GetSubStyleBases, 0); } int ScintillaCall::NamedStyles() { return static_cast<int>(Call(Message::GetNamedStyles)); } int ScintillaCall::NameOfStyle(int style, char *name) { return static_cast<int>(CallPointer(Message::NameOfStyle, style, name)); } std::string ScintillaCall::NameOfStyle(int style) { return CallReturnString(Message::NameOfStyle, style); } int ScintillaCall::TagsOfStyle(int style, char *tags) { return static_cast<int>(CallPointer(Message::TagsOfStyle, style, tags)); } std::string ScintillaCall::TagsOfStyle(int style) { return CallReturnString(Message::TagsOfStyle, style); } int ScintillaCall::DescriptionOfStyle(int style, char *description) { return static_cast<int>(CallPointer(Message::DescriptionOfStyle, style, description)); } std::string ScintillaCall::DescriptionOfStyle(int style) { return CallReturnString(Message::DescriptionOfStyle, style); } void ScintillaCall::SetILexer(void *ilexer) { CallPointer(Message::SetILexer, 0, ilexer); } Bidirectional ScintillaCall::Bidirectional() { return static_cast<Scintilla::Bidirectional>(Call(Message::GetBidirectional)); } void ScintillaCall::SetBidirectional(Scintilla::Bidirectional bidirectional) { Call(Message::SetBidirectional, static_cast<uintptr_t>(bidirectional)); } //--Autogenerated -- end of section automatically generated from Scintilla.iface */ } <|start_filename|>src/StyleLexers/styleLexINNO.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_INNO = { "_istool code components custommessages dirs files icons ini installdelete langoptions languages messages " "registry run setup tasks types uninstalldelete uninstallrun", "allowcancelduringinstall allownetworkdrive allownoicons allowrootdirectory allowuncpath alwaysrestart " "alwaysshowcomponentslist alwaysshowdironreadypage alwaysshowgrouponreadypage alwaysusepersonalgroup " "appcomments appcontact appcopyright appenddefaultdirname appenddefaultgroupname appid appmodifypath appmutex " "appname apppublisher apppublisherurl appreadmefile appsupportphone appsupporturl appupdatesurl appvername " "appversion architecturesallowed architecturesinstallin64bitmode aslrcompatible backcolor backcolor2 " "backcolordirection backsolid beveledlabel changesassociations changesenvironment closeapplications " "closeapplicationsfilter compression compressionthreads copyrightfontname copyrightfontsize createappdir " "createuninstallregkey defaultdialogfontname defaultdirname defaultgroupname defaultuserinfoname " "defaultuserinfoorg defaultuserinfoserial depcompatible dialogfontname dialogfontsize direxistswarning " "disabledirpage disablefinishedpage disableprogramgrouppage disablereadymemo disablereadypage " "disablestartupprompt disablewelcomepage diskclustersize diskslicesize diskspanning enabledirdoesntexistwarning " "encryption extradiskspacerequired flatcomponentslist iconindex infoafterfile infobeforefile " "internalcompresslevel languagecodepage languagedetectionmethod languageid languagename licensefile " "lzmaalgorithm lzmablocksize lzmadictionarysize lzmamatchfinder lzmanumblockthreads lzmanumfastbytes " "lzmauseseparateprocess mergeduplicatefiles minversion missingrunonceidswarning onlybelowversion output " "outputbasefilename outputdir outputmanifestfile password privilegesrequired privilegesrequiredoverridesallowed " "reservebytes restartapplications restartifneededbyrun righttoleft setupiconfile setuplogging setupmutex " "showcomponentsizes showlanguagedialog showtaskstreelines showundisplayablelanguages signeduninstaller " "signeduninstallerdir signtool signtoolminimumtimebetween signtoolretrycount signtoolretrydelay " "signtoolrunminimized slicesperdisk solidcompression sourcedir strongassemblyname terminalservicesaware " "timestamprounding timestampsinutc titlefontname titlefontsize touchdate touchtime uninstallable " "uninstalldisplayicon uninstalldisplayname uninstalldisplaysize uninstallfilesdir uninstalllogmode " "uninstallrestartcomputer updateuninstalllogappname useduserareaswarning usepreviousappdir usepreviousgroup " "usepreviouslanguage usepreviousprivigeles useprevioussetuptype useprevioustasks useprevioususerinfo " "userinfopage usesetupldr verb versioninfocompany versioninfocopyright versioninfodescription " "versioninfooriginalfilename versioninfoproductname versioninfoproducttextversion versioninfoproductversion " "versioninfotextversion versioninfoversion welcomefontname welcomefontsize windowresizable windowshowcaption " "windowstartmaximized windowvisible wizardimagealphaformat wizardimagefile wizardimagestretch wizardresizable " "wizardsizepercent wizardsmallimagefile wizardstyle", "afterinstall appusermodelid attribs beforeinstall check comment components copymode description destdir " "destname excludes extradiskspacerequired filename flags fontinstall groupdescription hotkey iconfilename " "iconindex infoafterfile infobeforefile key languages licensefile messagesfile minversion name " "onlybelowversion parameters permissions root runonceid section source statusmsg string subkey tasks " "terminalservicesaware type types valuedata valuename valuetype workingdir", "append define dim elif else emit endif endsub error expr file for if ifdef ifexist ifndef ifnexist include " "insert pragma sub undef", "and begin break case const continue do downto else end except finally for function if not of or procedure " "repeat then to try type until uses var while with", NULL, }; EDITLEXER lexINNO = { SCLEX_INNOSETUP, "inno", IDS_LEX_INNO, L"Inno Setup Script", L"iss; isl; islu", L"", &KeyWords_INNO, { { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_INNO_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {SCE_INNO_COMMENT}, IDS_LEX_STR_63127, L"Comment", L"fore:#008000", L"" }, { {SCE_INNO_KEYWORD}, IDS_LEX_STR_63128, L"Keyword", L"fore:#0000FF", L"" }, { {SCE_INNO_PARAMETER}, IDS_LEX_STR_63281, L"Parameter", L"fore:#0000FF", L"" }, { {SCE_INNO_SECTION}, IDS_LEX_STR_63232, L"Section", L"bold; fore:#000080", L"" }, { {SCE_INNO_PREPROC}, IDS_LEX_STR_63133, L"Preprocessor", L"fore:#CC0000", L"" }, { {SCE_INNO_INLINE_EXPANSION}, IDS_LEX_STR_63282, L"Inline Expansion", L"fore:#800080", L"" }, { {SCE_INNO_COMMENT_PASCAL}, IDS_LEX_STR_63283, L"Pascal Comment", L"fore:#008000", L"" }, { {SCE_INNO_KEYWORD_PASCAL}, IDS_LEX_STR_63284, L"Pascal Keyword", L"fore:#0000FF", L"" }, { {MULTI_STYLE(SCE_INNO_STRING_DOUBLE,SCE_INNO_STRING_SINGLE,0,0)}, IDS_LEX_STR_63131, L"String", L"", L"" }, //{ {SCE_INNO_IDENTIFIER}, IDS_LEX_STR_63129, L"Identifier", L"", L"" }, //{ {SCE_INNO_KEYWORD_USER}, L"User Defined", L"", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>src/uchardet/uchardet/src/LangModels/LangSloveneModel.cpp<|end_filename|> /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "../nsSBCharSetProber.h" /********* Language model for: Slovene *********/ /** * Generated by BuildLangModel.py * On: 2016-09-28 22:06:46.134717 **/ /* Character Mapping Table: * ILL: illegal character. * CTR: control character specific to the charset. * RET: carriage/return. * SYM: symbol (punctuation) that does not belong to word. * NUM: 0 - 9. * * Other characters are ordered by probabilities * (0 is the most common character in the language). * * Orders are generic to a language. So the codepoint with order X in * CHARSET1 maps to the same character as the codepoint with the same * order X in CHARSET2 for the same language. * As such, it is possible to get missing order. For instance the * ligature of 'o' and 'e' exists in ISO-8859-15 but not in ISO-8859-1 * even though they are both used for French. Same for the euro sign. */ static const unsigned char Iso_8859_2_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 0, 18, 19, 13, 1, 24, 17, 20, 2, 8, 12, 9, 14, 4, 3, /* 4X */ 11, 28, 5, 6, 7, 16, 10, 27, 25, 26, 15,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 0, 18, 19, 13, 1, 24, 17, 20, 2, 8, 12, 9, 14, 4, 3, /* 6X */ 11, 28, 5, 6, 7, 16, 10, 27, 25, 26, 15,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM, 41,SYM, 42,SYM, 43, 44,SYM,SYM, 22, 45, 46, 47,SYM, 23, 48, /* AX */ SYM, 49,SYM, 50,SYM, 51, 52,SYM,SYM, 22, 53, 54, 55,SYM, 23, 56, /* BX */ 57, 32, 58, 59, 60, 61, 37, 34, 21, 29, 62, 36, 63, 30, 64, 65, /* CX */ 66, 67, 68, 31, 35, 69, 70,SYM, 71, 72, 39, 73, 74, 40, 75, 76, /* DX */ 77, 32, 78, 79, 80, 81, 37, 34, 21, 29, 82, 36, 83, 30, 84, 85, /* EX */ 86, 87, 88, 31, 35, 89, 90,SYM, 91, 92, 39, 93, 94, 40, 95,SYM, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Iso_8859_16_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 0, 18, 19, 13, 1, 24, 17, 20, 2, 8, 12, 9, 14, 4, 3, /* 4X */ 11, 28, 5, 6, 7, 16, 10, 27, 25, 26, 15,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 0, 18, 19, 13, 1, 24, 17, 20, 2, 8, 12, 9, 14, 4, 3, /* 6X */ 11, 28, 5, 6, 7, 16, 10, 27, 25, 26, 15,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM, 96, 97, 98,SYM,SYM, 22,SYM, 22,SYM, 99,SYM,100,SYM,101,102, /* AX */ SYM,SYM, 21,103, 23,SYM,SYM,SYM, 23, 21,104,SYM,105,106,107,108, /* BX */ 109, 32,110,111,112, 37,113, 34,114, 29, 33, 36,115, 30,116,117, /* CX */ 118,119,120, 31, 35,121,122,123,124,125, 39,126,127,128,129,130, /* DX */ 131, 32,132,133,134, 37,135, 34,136, 29, 33, 36,137, 30,138,139, /* EX */ 140,141,142, 31, 35,143,144,145,146,147, 39,148,149,150,151,152, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Windows_1250_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 0, 18, 19, 13, 1, 24, 17, 20, 2, 8, 12, 9, 14, 4, 3, /* 4X */ 11, 28, 5, 6, 7, 16, 10, 27, 25, 26, 15,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 0, 18, 19, 13, 1, 24, 17, 20, 2, 8, 12, 9, 14, 4, 3, /* 6X */ 11, 28, 5, 6, 7, 16, 10, 27, 25, 26, 15,SYM,SYM,SYM,SYM,CTR, /* 7X */ SYM,ILL,SYM,ILL,SYM,SYM,SYM,SYM,ILL,SYM, 22,SYM,153,154, 23,155, /* 8X */ ILL,SYM,SYM,SYM,SYM,SYM,SYM,SYM,ILL,SYM, 22,SYM,156,157, 23,158, /* 9X */ SYM,SYM,SYM,159,SYM,160,SYM,SYM,SYM,SYM,161,SYM,SYM,SYM,SYM,162, /* AX */ SYM,SYM,SYM,163,SYM,SYM,SYM,SYM,SYM,164,165,SYM,166,SYM,167,168, /* BX */ 169, 32,170,171,172,173, 37, 34, 21, 29,174, 36,175, 30,176,177, /* CX */ 178,179,180, 31, 35,181,182,SYM,183,184, 39,185,186, 40,187,188, /* DX */ 189, 32,190,191,192,193, 37, 34, 21, 29,194, 36,195, 30,196,197, /* EX */ 198,199,200, 31, 35,201,202,SYM,203,204, 39,205,206, 40,207,SYM, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Maccentraleurope_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 0, 18, 19, 13, 1, 24, 17, 20, 2, 8, 12, 9, 14, 4, 3, /* 4X */ 11, 28, 5, 6, 7, 16, 10, 27, 25, 26, 15,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 0, 18, 19, 13, 1, 24, 17, 20, 2, 8, 12, 9, 14, 4, 3, /* 6X */ 11, 28, 5, 6, 7, 16, 10, 27, 25, 26, 15,SYM,SYM,SYM,SYM,CTR, /* 7X */ 208,209,210, 29,211,212,213, 32,214, 21,215, 21, 37, 37, 29,216, /* 8X */ 217,218, 30,219, 38, 38,220, 31,221, 35,222,223, 39,224,225,226, /* 9X */ SYM,SYM,227,SYM,SYM,SYM,SYM,228,SYM,SYM,SYM,229,SYM,SYM,230,231, /* AX */ 232,233,SYM,SYM,234,235,SYM,SYM,236,237,238,239,240,241,242,243, /* BX */ 244,245,SYM,SYM,246,247,SYM,SYM,SYM,SYM,SYM,248,249,249,249,249, /* CX */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,249,249,249,249,SYM,SYM,249,249, /* DX */ 249, 22,SYM,SYM, 22,249,249, 32,249,249, 30, 23, 23,249, 31, 35, /* EX */ 249,249, 39,249,249,249,249,249, 40, 40,249,249,249,249,249,SYM, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Ibm852_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 0, 18, 19, 13, 1, 24, 17, 20, 2, 8, 12, 9, 14, 4, 3, /* 4X */ 11, 28, 5, 6, 7, 16, 10, 27, 25, 26, 15,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 0, 18, 19, 13, 1, 24, 17, 20, 2, 8, 12, 9, 14, 4, 3, /* 6X */ 11, 28, 5, 6, 7, 16, 10, 27, 25, 26, 15,SYM,SYM,SYM,SYM,CTR, /* 7X */ 34,249, 29,249,249,249, 37, 34,249, 36,249,249,249,249,249, 37, /* 8X */ 29,249,249, 35,249,249,249,249,249,249,249,249,249,249,SYM, 21, /* 9X */ 32, 30, 31, 39,249,249, 23, 23,249,249,SYM,249, 21,249,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM,SYM, 32,249,249,249,SYM,SYM,SYM,SYM,249,249,SYM, /* BX */ SYM,SYM,SYM,SYM,SYM,SYM,249,249,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* CX */ 249,249,249, 36,249,249, 30,249,249,SYM,SYM,SYM,SYM,249,249,SYM, /* DX */ 31,249, 35,249,249,249, 22, 22,249, 39,249,249, 40, 40,249,SYM, /* EX */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,249,249,249,SYM,SYM, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ /* Model Table: * Total sequences: 727 * First 512 sequences: 0.9983524317161332 * Next 512 sequences (512-1024): 0.0016475682838668457 * Rest: -3.859759734048396e-17 * Negative sequences: TODO */ static const PRUint8 SloveneLangModel[] = { 2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,2,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,2,3,2,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,2,2, 3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,2,3,2,3,3,3,2,0,0,3,2,3,3,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,0,0,0,3,2,3,3,0, 3,3,3,3,3,2,3,3,0,0,3,3,3,3,3,2,3,2,3,3,3,2,3,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,2,3,2,3,3,2,3,2,0, 3,3,3,3,3,3,3,3,3,3,0,3,3,3,3,3,3,3,2,3,3,3,3,2,2,2,2,0,0, 3,3,3,3,3,3,3,3,2,3,0,3,3,3,2,2,3,3,3,3,3,2,2,0,0,0,3,2,2, 3,3,3,3,3,3,3,3,3,3,3,0,2,3,3,2,3,0,2,3,3,0,3,0,2,0,3,2,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,2,3,2,2,3,2,0, 3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,0,3,2,3,3,2,2,2,0,2,2,3,2,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,2,3,2,0,2,0,0,0, 3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,2,0,0, 3,3,3,3,3,3,3,2,0,3,3,3,2,2,2,0,3,2,3,2,3,0,0,0,2,2,2,2,0, 3,3,3,3,3,3,3,3,3,3,3,2,2,3,3,0,3,0,2,2,0,3,3,2,2,0,3,0,0, 3,3,3,3,3,3,3,3,0,3,2,3,3,3,2,2,3,2,2,3,3,0,0,0,2,2,3,2,2, 3,3,3,3,3,3,2,3,0,3,3,3,3,2,2,2,3,0,2,0,0,2,0,0,2,0,2,2,0, 3,3,3,3,3,3,0,0,3,3,2,2,3,2,0,0,3,0,2,2,0,0,2,0,0,0,0,0,0, 3,3,3,3,3,2,0,3,3,3,2,3,3,0,0,0,3,0,0,0,0,3,0,2,0,0,0,0,0, 3,3,3,2,3,2,0,2,3,3,2,0,3,0,0,0,3,2,3,2,0,0,0,2,0,0,0,0,0, 3,3,3,3,2,3,3,3,0,3,0,0,0,2,2,0,3,2,0,2,2,0,0,0,3,2,2,2,0, 3,3,3,3,2,2,2,3,0,0,2,3,0,2,2,0,3,2,3,3,2,0,0,0,2,2,2,2,0, 3,3,2,3,3,2,3,3,3,3,0,2,2,2,2,0,2,2,2,3,2,0,0,0,0,2,0,2,0, 3,3,3,3,3,0,3,0,0,2,0,0,0,0,2,0,2,2,2,0,2,0,0,0,2,0,2,3,0, 0,0,0,0,2,0,0,2,0,2,0,0,0,0,0,0,3,0,0,2,0,0,0,0,0,0,0,0,0, }; const SequenceModel Iso_8859_2SloveneModel = { Iso_8859_2_CharToOrderMap, SloveneLangModel, 29, (float)0.9983524317161332, PR_TRUE, "ISO-8859-2" }; const SequenceModel Iso_8859_16SloveneModel = { Iso_8859_16_CharToOrderMap, SloveneLangModel, 29, (float)0.9983524317161332, PR_TRUE, "ISO-8859-16" }; const SequenceModel Windows_1250SloveneModel = { Windows_1250_CharToOrderMap, SloveneLangModel, 29, (float)0.9983524317161332, PR_TRUE, "WINDOWS-1250" }; const SequenceModel MaccentraleuropeSloveneModel = { Maccentraleurope_CharToOrderMap, SloveneLangModel, 29, (float)0.9983524317161332, PR_TRUE, "MacCentralEurope" }; const SequenceModel Ibm852SloveneModel = { Ibm852_CharToOrderMap, SloveneLangModel, 29, (float)0.9983524317161332, PR_TRUE, "IBM852" }; <|start_filename|>grepWinNP3/sktoolslib_mod/DirFileEnum.h<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012, 2017-2018, 2020-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #pragma once #include <string> /** * Enumerates over a directory tree, non-recursively. * Advantages over CFileFind: * 1) Return values are not broken. An error return from * CFileFind::FindNext() indicates that the *next* * call to CFileFind::FindNext() will fail. * A failure from CSimpleFileFind means *that* call * failed, which is what I'd expect. * 2) Error handling. If you use CFileFind, you are * required to call ::GetLastError() yourself, there * is no abstraction. * 3) Support for ignoring the "." and ".." directories * automatically. * 4) No dynamic memory allocation. */ class CSimpleFileFind { private: /** * Windows FindFirstFile() handle. */ HANDLE m_hFindFile; /** * Windows error code - if all is well, ERROR_SUCCESS. * At end of directory, ERROR_NO_MORE_FILES. */ DWORD m_dError; /** * Flag indicating that FindNextFile() has not yet been * called. */ BOOL m_bFirst; /** * Flag indicating whether CSimpleFileFind was started for a file */ BOOL m_bFile; protected: /** * The prefix for files in this directory. * Ends with a "\", unless it's a drive letter only * ("C:" is different from "C:\", and "C:filename" is * legal anyway.) */ std::wstring m_sPathPrefix; /** * The file data returned by FindFirstFile()/FindNextFile(). */ WIN32_FIND_DATA m_findFileData; public: /** * Constructor. * * \param sPath The path to search in. * \param sPattern The filename pattern - default all files. */ CSimpleFileFind(const std::wstring& sPath, LPCWSTR pPattern = L"*.*", FINDEX_INFO_LEVELS infoLevel = FindExInfoBasic); ~CSimpleFileFind(); /** * Advance to the next file. * Note that the state of this object is undefined until * this method is called the first time. * * \return TRUE if a file was found, FALSE on error or * end-of-directory (use IsError() and IsPastEnd() to * disambiguate). */ bool FindNextFile(); /** * Advance to the next file, ignoring the "." and ".." * pseudo-directories (if seen). * * Behaves like FindNextFile(), apart from ignoring "." * and "..". * * \return TRUE if a file was found, FALSE on error or * end-of-directory. */ bool FindNextFileNoDots(DWORD attrToIgnore); /** * Advance to the next file, ignoring all directories. * * Behaves like FindNextFile(), apart from ignoring * directories. * * \return TRUE if a file was found, FALSE on error or * end-of-directory. */ bool FindNextFileNoDirectories(); /** * Get the Windows error code. * Only useful when IsError() returns true. * * \return Windows error code. */ inline DWORD GetError() const { return m_dError; } /** * Get the file/directory attributes. * * \return item attributes. */ inline DWORD GetAttributes() const { return m_findFileData.dwFileAttributes; } /** * Check if the current file data is valid. * (I.e. there has not been an error and we are not past * the end of the directory). * * \return TRUE iff the current file data is valid. */ inline bool IsValid() const { return (m_dError == ERROR_SUCCESS); } /** * Check if we have passed the end of the directory. * * \return TRUE iff we have passed the end of the directory. */ inline BOOL IsPastEnd() const { return (m_dError == ERROR_NO_MORE_FILES); } /** * Check if there has been an unexpected error - i.e. * any error other than passing the end of the directory. * * \return TRUE iff there has been an unexpected error. */ inline bool IsError() const { return (m_dError != ERROR_SUCCESS) && (m_dError != ERROR_NO_MORE_FILES); } /** * Check if the current file is a directory. * * \return TRUE iff the current file is a directory. */ inline bool IsDirectory() const { return !!(m_findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY); } /** * Get the current file name (excluding the path). * * \return the current file name. */ inline std::wstring GetFileName() const { return m_findFileData.cFileName; } const WIN32_FIND_DATA* GetFileFindData() const { return &m_findFileData; } /* * Get the current file name, including the path. * * \return the current file path. */ inline std::wstring GetFilePath() const { if (m_bFile) return m_sPathPrefix; return m_sPathPrefix + m_findFileData.cFileName; } /** * Get the last write time of the file * * \return the last write time */ FILETIME GetLastWriteTime() const { return m_findFileData.ftLastWriteTime; } /** * Get the creation time of the file * * \return the creation time */ FILETIME GetCreateTime() const { return m_findFileData.ftCreationTime; } /** * Check if the current file is the "." or ".." * pseudo-directory. * * \return TRUE iff the current file is the "." or ".." * pseudo-directory. */ inline bool IsDots() const { return IsDirectory() && m_findFileData.cFileName[0] == L'.' && ((m_findFileData.cFileName[1] == 0) || (m_findFileData.cFileName[1] == L'.' && m_findFileData.cFileName[2] == 0)); } }; /** * Enumerates over a directory tree, recursively. */ class CDirFileEnum { private: class CDirStackEntry : public CSimpleFileFind { public: CDirStackEntry(CDirStackEntry* seNext, const std::wstring& sDirName); ~CDirStackEntry(); CDirStackEntry* m_seNext; }; CDirStackEntry* m_seStack; bool m_bIsNew; DWORD m_attrToIgnore; inline void PopStack(); inline void PushStack(const std::wstring& sDirName); public: /** * Iterate through the specified directory and all subdirectories. * It does not matter whether or not the specified directory ends * with a slash. Both relative and absolute paths are allowed, * the results of this iterator will be consistent with the style * passed to this constructor. * * @param dirName The directory to search in. */ CDirFileEnum(const std::wstring& dirName); /** * Destructor. Frees all resources. */ ~CDirFileEnum(); /** * Get the next file from this iterator. * * \param result On successful return, holds the full path to the found * file. (If this function returns FALSE, the value of * result is unspecified). * \param pbIsDirectory Pointer to a bool variable which will hold * TRUE if the \c result path is a directory, FALSE * if it's a file. Pass nullptr if you don't need that information. * \param recurse true if recursing into subdirectories is requested. * \return TRUE iff a file was found, false at end of the iteration. */ bool NextFile(std::wstring& result, bool* pbIsDirectory, bool recurse = true); /** * Get the file info structure. * * \return The WIN32_FIND_DATA structure of the file or directory */ const WIN32_FIND_DATA* GetFileInfo() const { return m_seStack->GetFileFindData(); } /** * Set a mask of file attributes to ignore. Files or directories that * have any one of those attributes set won't be returned. * Useful if you want to ignore e.g. all system or hidden files: pass * FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN in that case. * * \param attr the file attribute mask */ void SetAttributesToIgnore(DWORD attr) { m_attrToIgnore = attr; } /** * Get the last write time of the file * * \return the last write time */ FILETIME GetLastWriteTime() const { if (m_seStack) return m_seStack->GetLastWriteTime(); FILETIME ft = {0}; return ft; } /** * Get the creation time of the file * * \return the creation time */ FILETIME GetCreateTime() const { if (m_seStack) return m_seStack->GetCreateTime(); FILETIME ft = {0}; return ft; } DWORD GetError() const { if (m_seStack) return m_seStack->GetError(); return 0; } }; <|start_filename|>lexilla/lexers_x/LexAHK.cxx<|end_filename|> // encoding: UTF-8 // Scintilla source code edit control /** @file LexAHK.cxx ** Lexer for AutoHotkey, simplified version ** Written by <NAME> (PhiLho) **/ // Copyright 1998-2006 by <NAME> <<EMAIL>> // The License.txt file describes the conditions under which this software may be distributed. /* notepad2-mod custom code for the AutoHotkey lexer */ #include <string> #include <assert.h> #include <map> // #include "ILexer.h" #include "Scintilla.h" #include "StringCopy.h" #include "PropSetSimple.h" #include "LexAccessor.h" #include "Accessor.h" #include "StyleContext.h" #include "LexerModule.h" #include "DefaultLexer.h" #include "OptionSet.h" #include "WordList.h" // #include "CharSetX.h" #include "SciXLexer.h" using namespace Lexilla; using namespace Scintilla; // Options used for LexerRust struct OptionsAHK { bool fold; bool foldComment; bool foldCompact; OptionsAHK() : fold(false) , foldComment(true) , foldCompact(true) { } }; static const char* const ahkWordLists[] = { "Flow of Control", "Commands", "Functions", "Directives", "Keys & Buttons", "Variables", "Special Parameters (keywords)", "User Defined", nullptr }; struct OptionSetAHK : public OptionSet<OptionsAHK> { OptionSetAHK() { DefineProperty("fold", &OptionsAHK::fold); DefineProperty("fold.comment", &OptionsAHK::foldComment); DefineProperty("fold.compact", &OptionsAHK::foldCompact); DefineWordListSets(ahkWordLists); } }; class LexerAHK : public DefaultLexer { OptionsAHK options; OptionSetAHK osAHK; WordList controlFlow; WordList commands; WordList functions; WordList directives; WordList keysButtons; WordList variables; WordList specialParams; WordList userDefined; CharacterSet WordChar; CharacterSet ExpOperator; public: LexerAHK() : DefaultLexer("AHK", SCLEX_AHK, nullptr, 0), //valLabel(CharacterSet::setAlphaNum, "@#$_~!^&*()+[]\';./\\<>?|{}-=\""), WordChar(CharacterSet::setAlphaNum, "@#$_[]?"), ExpOperator(CharacterSet::setNone, "+-*/!~&|^=<>.()") { } virtual ~LexerAHK() = default; void SCI_METHOD Release() override { delete this; } int SCI_METHOD Version() const override { return lvRelease5; } const char* SCI_METHOD PropertyNames() override { return osAHK.PropertyNames(); } int SCI_METHOD PropertyType(const char* name) override { return osAHK.PropertyType(name); } const char* SCI_METHOD PropertyGet(const char* name) override { return osAHK.PropertyGet(name); } const char* SCI_METHOD DescribeProperty(const char* name) override { return osAHK.DescribeProperty(name); } const char* SCI_METHOD DescribeWordListSets() override { return osAHK.DescribeWordListSets(); } void * SCI_METHOD PrivateCall(int, void *) override { return nullptr; } // -------------------------------------------------------------------------- Sci_Position SCI_METHOD PropertySet(const char* key, const char* val) override; Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override; void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument *pAccess) override; void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument *pAccess) override; static ILexer5 *LexerFactoryAHK() { return new LexerAHK(); } private: void HighlightKeyword(char currentWord[], StyleContext& sc); }; Sci_Position SCI_METHOD LexerAHK::PropertySet(const char* key, const char* val) { if (osAHK.PropertySet(&options, key, val)) { return 0; } return -1; } Sci_Position SCI_METHOD LexerAHK::WordListSet(int n, const char *wl) { WordList *wordListN = nullptr; switch (n) { case 0: wordListN = &controlFlow; break; case 1: wordListN = &commands; break; case 2: wordListN = &functions; break; case 3: wordListN = &directives; break; case 4: wordListN = &keysButtons; break; case 5: wordListN = &variables; break; case 6: wordListN = &specialParams; break; case 7: wordListN = &userDefined; break; } int firstModification = -1; if (wordListN) { WordList wlNew; wlNew.Set(wl); if (*wordListN != wlNew) { wordListN->Set(wl); firstModification = 0; } } return firstModification; } void LexerAHK::HighlightKeyword(char currentWord[], StyleContext& sc) { if (controlFlow.InList(currentWord)) { sc.ChangeState(SCE_AHK_WORD_CF); } else if (commands.InList(currentWord)) { sc.ChangeState(SCE_AHK_WORD_CMD); } else if (functions.InList(currentWord)) { sc.ChangeState(SCE_AHK_WORD_FN); } else if (currentWord[0] == '#' && directives.InList(currentWord + 1)) { sc.ChangeState(SCE_AHK_WORD_DIR); } else if (keysButtons.InList(currentWord)) { sc.ChangeState(SCE_AHK_WORD_KB); } else if (variables.InList(currentWord)) { sc.ChangeState(SCE_AHK_WORD_VAR); } else if (specialParams.InList(currentWord)) { sc.ChangeState(SCE_AHK_WORD_SP); } else if (userDefined.InList(currentWord)) { sc.ChangeState(SCE_AHK_WORD_UD); } else { sc.ChangeState(SCE_AHK_DEFAULT); } } void SCI_METHOD LexerAHK::Lex(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument *pAccess) { PropSetSimple props; Accessor styler(pAccess, &props); StyleContext sc(startPos, lengthDoc, initStyle, styler); // Do not leak onto next line if (initStyle != SCE_AHK_COMMENTBLOCK && initStyle != SCE_AHK_STRING) { initStyle = SCE_AHK_DEFAULT; } int currentState = initStyle; int nextState = -1; char currentWord[256]; /* The AutoHotkey syntax is heavily context-dependent. For example, for each command, the lexer knows if parameter #n is a string, a variable, a number, an expression, etc. I won't go this far, but I will try to handle most regular cases. */ // True if in a continuation section bool bContinuationSection = (initStyle == SCE_AHK_STRING); // Indicate if the lexer has seen only spaces since the start of the line bool bOnlySpaces = (!bContinuationSection); // Indicate if since the start of the line, lexer met only legal label chars bool bIsLabel = false; // Distinguish hotkeys from hotstring bool bIsHotkey = false; bool bIsHotstring = false; // In an expression bool bInExpression = false; // A quoted string in an expression (share state with continuation section string) bool bInExprString = false; // To accept A-F chars in a number bool bInHexNumber = false; for (; sc.More(); sc.Forward()) { if (nextState >= 0) { // I need to reset a state before checking new char sc.SetState(nextState); nextState = -1; } if (sc.state == SCE_AHK_SYNOPERATOR) { // Only one char (if two detected, we move Forward() anyway) sc.SetState(SCE_AHK_DEFAULT); } if (sc.atLineEnd && (bIsHotkey || bIsHotstring)) { // I make the hotkeys and hotstrings more visible // by changing the line end to LABEL style (if style uses eolfilled) bIsHotkey = bIsHotstring = false; sc.SetState(SCE_AHK_LABEL); } if (sc.atLineStart) { if (sc.state != SCE_AHK_COMMENTBLOCK && !bContinuationSection) { // Prevent some styles from leaking back to previous line sc.SetState(SCE_AHK_DEFAULT); } bOnlySpaces = true; bIsLabel = false; bInExpression = false; // I don't manage multiline expressions yet! bInHexNumber = false; } // Manage cases occuring in (almost) all states (not in comments) if (sc.state != SCE_AHK_COMMENTLINE && sc.state != SCE_AHK_COMMENTBLOCK && !IsASpace(sc.ch)) { if (sc.ch == '`') { // Backtick, escape sequence currentState = sc.state; sc.SetState(SCE_AHK_ESCAPE); sc.Forward(); nextState = currentState; continue; } if (sc.ch == '%' && !bIsHotstring && !bInExprString && sc.state != SCE_AHK_VARREF && sc.state != SCE_AHK_VARREFKW && sc.state != SCE_AHK_ERROR) { if (IsASpace(sc.chNext)) { if (sc.state == SCE_AHK_STRING) { // Illegal unquoted character! sc.SetState(SCE_AHK_ERROR); } else { // % followed by a space is expression start bInExpression = true; } } else { // Variable reference currentState = sc.state; sc.SetState(SCE_AHK_SYNOPERATOR); nextState = SCE_AHK_VARREF; continue; } } if (sc.state != SCE_AHK_STRING && !bInExpression) { // Management of labels, hotkeys, hotstrings and remapping // Check if the starting string is a label candidate if (bOnlySpaces && sc.ch != ',' && sc.ch != ';' && sc.ch != ':' && sc.ch != '%' && sc.ch != '`') { // A label cannot start with one of the above chars bIsLabel = true; } // The current state can be IDENTIFIER or DEFAULT, // depending if the label starts with a word char or not if (bIsLabel && sc.ch == ':' && (IsASpace(sc.chNext) || sc.atLineEnd)) { // ?l/a|b\e^l!: // Only ; comment should be allowed after sc.ChangeState(SCE_AHK_LABEL); sc.SetState(SCE_AHK_SYNOPERATOR); nextState = SCE_AHK_DEFAULT; continue; } else if (sc.Match(':', ':')) { if (bOnlySpaces) { // Hotstring ::aa::Foo bIsHotstring = true; sc.SetState(SCE_AHK_SYNOPERATOR); sc.Forward(); nextState = SCE_AHK_LABEL; continue; } // Hotkey F2:: or remapping a::b bIsHotkey = true; // Check if it is a known key sc.GetCurrentLowered(currentWord, sizeof(currentWord)); if (keysButtons.InList(currentWord)) { sc.ChangeState(SCE_AHK_WORD_KB); } sc.SetState(SCE_AHK_SYNOPERATOR); sc.Forward(); if (bIsHotstring) { nextState = SCE_AHK_STRING; } continue; } } } // Check if the current string is still a label candidate // Labels are much more permissive than regular identifiers... if (bIsLabel && (sc.ch == ',' || sc.ch == '%' || sc.ch == '`' || IsASpace(sc.ch))) { // Illegal character in a label bIsLabel = false; } // Determine if the current state should terminate. if (sc.state == SCE_AHK_COMMENTLINE) { if (sc.atLineEnd) { sc.SetState(SCE_AHK_DEFAULT); } } else if (sc.state == SCE_AHK_COMMENTBLOCK) { if (bOnlySpaces && sc.Match('*', '/')) { // End of comment at start of line (skipping white space) sc.Forward(); sc.ForwardSetState(SCE_AHK_DEFAULT); } } else if (sc.state == SCE_AHK_EXPOPERATOR) { if (!ExpOperator.Contains(sc.ch)) { sc.SetState(SCE_AHK_DEFAULT); } } else if (sc.state == SCE_AHK_STRING) { if (bContinuationSection) { if (bOnlySpaces && sc.ch == ')') { // End of continuation section bContinuationSection = false; sc.SetState(SCE_AHK_SYNOPERATOR); } } else if (bInExprString) { if (sc.ch == '\"') { if (sc.chNext == '\"') { // In expression string, double quotes are doubled to escape them sc.Forward(); // Skip it } else { bInExprString = false; sc.ForwardSetState(SCE_AHK_DEFAULT); } } else if (sc.atLineEnd) { sc.ChangeState(SCE_AHK_ERROR); } } else { if (sc.ch == ';' && IsASpace(sc.chPrev)) { // Line comments after code must be preceded by a space sc.SetState(SCE_AHK_COMMENTLINE); } } } else if (sc.state == SCE_AHK_NUMBER) { if (bInHexNumber) { if (!IsADigit(sc.ch, 16)) { bInHexNumber = false; sc.SetState(SCE_AHK_DEFAULT); } } else if (!(IsADigit(sc.ch) || sc.ch == '.')) { sc.SetState(SCE_AHK_DEFAULT); } } else if (sc.state == SCE_AHK_IDENTIFIER) { if (!WordChar.Contains(sc.ch)) { sc.GetCurrentLowered(currentWord, sizeof(currentWord)); HighlightKeyword(currentWord, sc); if (strcmp(currentWord, "if") == 0) { bInExpression = true; } sc.SetState(SCE_AHK_DEFAULT); } } else if (sc.state == SCE_AHK_VARREF) { if (sc.ch == '%') { // End of variable reference sc.GetCurrentLowered(currentWord, sizeof(currentWord)); if (variables.InList(currentWord)) { sc.ChangeState(SCE_AHK_VARREFKW); } sc.SetState(SCE_AHK_SYNOPERATOR); nextState = currentState; continue; } else if (!WordChar.Contains(sc.ch)) { // Oops! Probably no terminating % sc.ChangeState(SCE_AHK_ERROR); } } else if (sc.state == SCE_AHK_LABEL) { // Hotstring -- modifier or trigger string :*:aa::Foo or ::aa::Foo if (sc.ch == ':') { sc.SetState(SCE_AHK_SYNOPERATOR); if (sc.chNext == ':') { sc.Forward(); } nextState = SCE_AHK_LABEL; continue; } } // Determine if a new state should be entered if (sc.state == SCE_AHK_DEFAULT) { if (sc.ch == ';' && (bOnlySpaces || IsASpace(sc.chPrev))) { // Line comments are alone on the line or are preceded by a space sc.SetState(SCE_AHK_COMMENTLINE); } else if (bOnlySpaces && sc.Match('/', '*')) { // Comment at start of line (skipping white space) sc.SetState(SCE_AHK_COMMENTBLOCK); sc.Forward(); } else if (sc.ch == '{' || sc.ch == '}') { // Code block or special key {Enter} sc.SetState(SCE_AHK_SYNOPERATOR); } else if (bOnlySpaces && sc.ch == '(') { // Continuation section bContinuationSection = true; sc.SetState(SCE_AHK_SYNOPERATOR); nextState = SCE_AHK_STRING; // !!! Can be an expression! } else if (sc.Match(':', '=') || sc.Match('+', '=') || sc.Match('-', '=') || sc.Match('/', '=') || sc.Match('*', '=')) { // Expression assignment bInExpression = true; sc.SetState(SCE_AHK_SYNOPERATOR); sc.Forward(); nextState = SCE_AHK_DEFAULT; } else if (ExpOperator.Contains(sc.ch)) { sc.SetState(SCE_AHK_EXPOPERATOR); } else if (sc.ch == '\"') { bInExprString = true; sc.SetState(SCE_AHK_STRING); } else if (sc.ch == '0' && (sc.chNext == 'x' || sc.chNext == 'X')) { // Hexa, skip forward as we don't accept any other alpha char (beside A-F) inside bInHexNumber = true; sc.SetState(SCE_AHK_NUMBER); sc.Forward(2); } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_AHK_NUMBER); } else if (WordChar.Contains(sc.ch)) { sc.SetState(SCE_AHK_IDENTIFIER); } else if (sc.ch == ',') { sc.SetState(SCE_AHK_SYNOPERATOR); nextState = SCE_AHK_DEFAULT; } else if (sc.ch == ':') { if (bOnlySpaces) { // Start of hotstring :*:foo::Stuff or ::btw::Stuff bIsHotstring = true; sc.SetState(SCE_AHK_SYNOPERATOR); if (sc.chNext == ':') { sc.Forward(); } nextState = SCE_AHK_LABEL; } } else if (WordChar.Contains(sc.ch)) { sc.SetState(SCE_AHK_IDENTIFIER); } } if (!IsASpace(sc.ch)) { bOnlySpaces = false; } } // End of file: complete any pending changeState if (sc.state == SCE_AHK_IDENTIFIER) { sc.GetCurrentLowered(currentWord, sizeof(currentWord)); HighlightKeyword(currentWord, sc); } else if (sc.state == SCE_AHK_STRING && bInExprString) { sc.ChangeState(SCE_AHK_ERROR); } else if (sc.state == SCE_AHK_VARREF) { sc.ChangeState(SCE_AHK_ERROR); } sc.Complete(); } void SCI_METHOD LexerAHK::Fold(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, IDocument *pAccess) { if (!options.fold) { return; } PropSetSimple props; Accessor styler(pAccess, &props); bool const foldComment = options.foldComment; //props.GetInt("fold.comment") != 0; bool const foldCompact = options.foldCompact; //props.GetInt("fold.compact", 1) != 0; Sci_PositionU endPos = startPos + lengthDoc; bool bOnlySpaces = true; int lineCurrent = styler.GetLine(startPos); int levelCurrent = SC_FOLDLEVELBASE; if (lineCurrent > 0) { levelCurrent = styler.LevelAt(lineCurrent - 1) & SC_FOLDLEVELNUMBERMASK; } int levelNext = levelCurrent; char chNext = styler[startPos]; int styleNext = styler.StyleAt(startPos); int style = initStyle; for (Sci_PositionU i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int stylePrev = style; style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (foldComment && style == SCE_AHK_COMMENTBLOCK) { if (stylePrev != SCE_AHK_COMMENTBLOCK) { levelNext++; } else if ((styleNext != SCE_AHK_COMMENTBLOCK) && !atEOL) { // Comments don't end at end of line and the next character may be unstyled. levelNext--; } } if (style == SCE_AHK_SYNOPERATOR) { if (ch == '(' || ch == '{') { levelNext++; } else if (ch == ')' || ch == '}') { levelNext--; } } if (atEOL) { int level = levelCurrent; if (bOnlySpaces && foldCompact) { // Empty line level |= SC_FOLDLEVELWHITEFLAG; } if (!bOnlySpaces && levelNext > levelCurrent) { level |= SC_FOLDLEVELHEADERFLAG; } if (level != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, level); } lineCurrent++; levelCurrent = levelNext; bOnlySpaces = true; } if (!isspacechar(ch)) { bOnlySpaces = false; } } } LexerModule lmAHK(SCLEX_AHK, LexerAHK::LexerFactoryAHK, "ahk", ahkWordLists); <|start_filename|>test/test_files/StyleLexers/styleLexCPP/Notepad3.c<|end_filename|> /****************************************************************************** * * * Notepad3 * * * *******************************************************************************/ #include "Helpers.h" #include <commctrl.h> #include <uxtheme.h> #include <shlobj.h> #include <shlwapi.h> #include <shellapi.h> #include <commdlg.h> #include <stdio.h> #include <string.h> //#include <pathcch.h> #include <time.h> /****************************************************************************** * * Local and global Variables for Notepad3.c * */ CONSTANTS_T Constants; FLAGS_T Flags; FLAGS_T DefaultFlags; GLOBALS_T Globals; SETTINGS_T Settings; SETTINGS_T Defaults; SETTINGS2_T Settings2; SETTINGS2_T Defaults2; FOCUSEDVIEW_T FocusedView; FILEWATCHING_T FileWatching; WININFO s_WinInfo = INIT_WININFO; WININFO s_DefWinInfo = INIT_WININFO; COLORREF g_colorCustom[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; prefix_t s_mxSBPrefix[STATUS_SECTOR_COUNT]; prefix_t s_mxSBPostfix[STATUS_SECTOR_COUNT]; bool s_iStatusbarVisible[STATUS_SECTOR_COUNT] = SBS_INIT_ZERO; int s_iStatusbarWidthSpec[STATUS_SECTOR_COUNT] = SBS_INIT_ZERO; int s_vSBSOrder[STATUS_SECTOR_COUNT] = SBS_INIT_MINUS; WCHAR s_tchToolbarBitmap[MAX_PATH] = { L'\0' }; WCHAR s_tchToolbarBitmapHot[MAX_PATH] = { L'\0' }; WCHAR s_tchToolbarBitmapDisabled[MAX_PATH] = { L'\0' }; bool s_bEnableSaveSettings = true; int s_iToolBarTheme = -1; bool s_flagPosParam = false; int s_flagWindowPos = 0; int s_flagReuseWindow = 0; int s_flagSingleFileInstance = 0; int s_flagMultiFileArg = 0; int s_flagShellUseSystemMRU = 0; int s_flagPrintFileAndLeave = 0; // ------------------------------------ static WCHAR s_wchWndClass[16] = _W(SAPPNAME); static HWND s_hwndEditFrame = NULL; static HWND s_hwndNextCBChain = NULL; static HWND s_hwndReBar = NULL; static WCHAR s_wchTmpFilePath[MAX_PATH] = { L'\0' }; static WCHAR s_wchPrefixSelection[256] = { L'\0' }; static WCHAR s_wchAppendSelection[256] = { L'\0' }; static WCHAR s_wchPrefixLines[256] = { L'\0' }; static WCHAR s_wchAppendLines[256] = { L'\0' }; static int s_WinCurrentWidth = 0; #define FILE_LIST_SIZE 32 static LPWSTR s_lpFileList[FILE_LIST_SIZE] = { NULL }; static int s_cFileList = 0; static int s_cchiFileList = 0; static WCHAR* const _s_RecentFiles = L"Recent Files"; static WCHAR* const _s_RecentFind = L"Recent Find"; static WCHAR* const _s_RecentReplace = L"Recent Replace"; static WCHAR s_tchLastSaveCopyDir[MAX_PATH] = { L'\0' }; static bool s_bRunningWatch = false; static bool s_bFileReadOnly = false; static bool s_bIsElevated = false; static int s_iSortOptions = 0; static int s_iAlignMode = 0; static bool s_bIsAppThemed = true; static UINT s_msgTaskbarCreated = 0; static bool s_dwChangeNotifyTime = 0; static HANDLE s_hChangeHandle = NULL; static WCHAR s_wchTitleExcerpt[MIDSZ_BUFFER] = { L'\0' }; static UINT s_uidsAppTitle = IDS_MUI_APPTITLE; static DWORD s_dwLastCopyTime = 0; static bool s_bLastCopyFromMe = false; static bool s_bIndicMultiEdit = false; static int s_iInitialLine; static int s_iInitialColumn; static int s_iInitialLexer; static int s_cyReBar; static int s_cyReBarFrame; static int s_cxEditFrame; static int s_cyEditFrame; // for tiny expression calculation static double s_dExpression = 0.0; static int s_iExprError = -1; static WIN32_FIND_DATA s_fdCurFile; static HMODULE s_hRichEdit = INVALID_HANDLE_VALUE; static int const INISECTIONBUFCNT = 32; // .ini file load buffer in KB static TBBUTTON s_tbbMainWnd[] = { { 0,IDT_FILE_NEW,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 1,IDT_FILE_OPEN,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 3,IDT_FILE_SAVE,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 2,IDT_FILE_BROWSE,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 27,IDT_FILE_RECENT,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 0,0,0,BTNS_SEP,{0},0,0 }, { 4,IDT_EDIT_UNDO,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 5,IDT_EDIT_REDO,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 0,0,0,BTNS_SEP,{0},0,0 }, { 6,IDT_EDIT_CUT,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 7,IDT_EDIT_COPY,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 8,IDT_EDIT_PASTE,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 0,0,0,BTNS_SEP,{0},0,0 }, { 9,IDT_EDIT_FIND,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 10,IDT_EDIT_REPLACE,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 0,0,0,BTNS_SEP,{0},0,0 }, { 11,IDT_VIEW_WORDWRAP,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 0,0,0,BTNS_SEP,{0},0,0 }, { 23,IDT_VIEW_TOGGLEFOLDS,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 25,IDT_VIEW_TOGGLE_VIEW,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 0,0,0,BTNS_SEP,{0},0,0 }, { 21,IDT_FILE_OPENFAV,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 22,IDT_FILE_ADDTOFAV,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 0,0,0,BTNS_SEP,{0},0,0 }, { 12,IDT_VIEW_ZOOMIN,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 13,IDT_VIEW_ZOOMOUT,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 0,0,0,BTNS_SEP,{0},0,0 }, { 14,IDT_VIEW_SCHEME,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 0,0,0,BTNS_SEP,{0},0,0 }, { 24,IDT_FILE_LAUNCH,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 0,0,0,BTNS_SEP,{0},0,0 }, { 28,IDT_VIEW_PIN_ON_TOP,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 0,0,0,BTNS_SEP,{0},0,0 }, { 16,IDT_FILE_EXIT,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 0,0,0,BTNS_SEP,{0},0,0 }, { 15,IDT_VIEW_SCHEMECONFIG,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 17,IDT_FILE_SAVEAS,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 18,IDT_FILE_SAVECOPY,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 19,IDT_EDIT_CLEAR,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 20,IDT_FILE_PRINT,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, { 26,IDT_VIEW_CHASING_DOCTAIL,TBSTATE_ENABLED,BTNS_BUTTON,{0},0,0 }, }; static const int NUMTOOLBITMAPS = 29; // ---------------------------------------------------------------------------- const WCHAR* const TBBUTTON_DEFAULT_IDS_V1 = L"1 2 4 3 28 0 5 6 0 7 8 9 0 10 11 0 12 0 24 26 0 22 23 0 13 14 0 27 0 15 0 25 0 17"; const WCHAR* const TBBUTTON_DEFAULT_IDS_V2 = L"1 2 4 3 28 0 5 6 0 7 8 9 0 10 11 0 12 0 24 26 0 22 23 0 13 14 0 15 0 25 0 29 0 17"; //============================================================================= // some Mappings internal idx -> Scintilla values static int const s_DirectWriteTechnology[4] = { SC_TECHNOLOGY_DEFAULT , SC_TECHNOLOGY_DIRECTWRITE , SC_TECHNOLOGY_DIRECTWRITERETAIN , SC_TECHNOLOGY_DIRECTWRITEDC }; static int const s_SciBidirectional[3] = { SC_BIDIRECTIONAL_DISABLED , SC_BIDIRECTIONAL_L2R , SC_BIDIRECTIONAL_R2L }; int const g_FontQuality[4] = { SC_EFF_QUALITY_DEFAULT , SC_EFF_QUALITY_NON_ANTIALIASED , SC_EFF_QUALITY_ANTIALIASED , SC_EFF_QUALITY_LCD_OPTIMIZED }; //============================================================================= // static method declarations // undo / redo selections static UT_icd UndoRedoSelElement_icd = { sizeof(DocPos), NULL, NULL, NULL }; static void InitUndoRedoSelection(void* elt) { UndoRedoSelection_t* selection = (UndoRedoSelection_t*)elt; if (selection != NULL) { selection->selMode_undo = SC_SEL_STREAM; selection->anchorPos_undo = NULL; selection->curPos_undo = NULL; selection->anchorVS_undo = NULL; selection->curVS_undo = NULL; selection->selMode_redo = SC_SEL_STREAM; selection->anchorPos_redo = NULL; selection->curPos_redo = NULL; selection->anchorVS_redo = NULL; selection->curVS_redo = NULL; } } static void DelUndoRedoSelection(void* elt) { UndoRedoSelection_t* selection = (UndoRedoSelection_t*)elt; if (selection != NULL) { if (selection->anchorPos_undo != NULL) { utarray_clear(selection->anchorPos_undo); utarray_free(selection->anchorPos_undo); selection->anchorPos_undo = NULL; } if (selection->curPos_undo != NULL) { utarray_clear(selection->curPos_undo); utarray_free(selection->curPos_undo); selection->curPos_undo = NULL; } if (selection->anchorVS_undo != NULL) { utarray_clear(selection->anchorVS_undo); utarray_free(selection->anchorVS_undo); selection->anchorVS_undo = NULL; } if (selection->curVS_undo != NULL) { utarray_clear(selection->curVS_undo); utarray_free(selection->curVS_undo); selection->curVS_undo = NULL; } if (selection->anchorPos_redo != NULL) { utarray_clear(selection->anchorPos_redo); utarray_free(selection->anchorPos_redo); selection->anchorPos_redo = NULL; } if (selection->curPos_redo != NULL) { utarray_clear(selection->curPos_redo); utarray_free(selection->curPos_redo); selection->curPos_redo = NULL; } if (selection->anchorVS_redo != NULL) { utarray_clear(selection->anchorVS_redo); utarray_free(selection->anchorVS_redo); selection->anchorVS_redo = NULL; } if (selection->curVS_redo != NULL) { utarray_clear(selection->curVS_redo); utarray_free(selection->curVS_redo); selection->curVS_redo = NULL; } } } static void CopyUndoRedoSelection(void* dst, const void* src) { UndoRedoSelection_t* dst_sel = (UndoRedoSelection_t*)dst; const UndoRedoSelection_t* src_sel = (UndoRedoSelection_t*)src; DocPos* pPos = NULL; InitUndoRedoSelection(dst); dst_sel->selMode_undo = (src_sel) ? src_sel->selMode_undo : SC_SEL_STREAM; utarray_new(dst_sel->anchorPos_undo, &UndoRedoSelElement_icd); if (src_sel) { while ((pPos = (DocPos*)utarray_next(src_sel->anchorPos_undo, pPos)) != NULL) { utarray_push_back(dst_sel->anchorPos_undo, pPos); } } utarray_new(dst_sel->curPos_undo, &UndoRedoSelElement_icd); if (src_sel) { while ((pPos = (DocPos*)utarray_next(src_sel->curPos_undo, pPos)) != NULL) { utarray_push_back(dst_sel->curPos_undo, pPos); } } utarray_new(dst_sel->anchorVS_undo, &UndoRedoSelElement_icd); if (src_sel) { while ((pPos = (DocPos*)utarray_next(src_sel->anchorVS_undo, pPos)) != NULL) { utarray_push_back(dst_sel->anchorVS_undo, pPos); } } utarray_new(dst_sel->curVS_undo, &UndoRedoSelElement_icd); if (src_sel) { while ((pPos = (DocPos*)utarray_next(src_sel->curVS_undo, pPos)) != NULL) { utarray_push_back(dst_sel->curVS_undo, pPos); } } dst_sel->selMode_redo = (src_sel) ? src_sel->selMode_redo : SC_SEL_STREAM; utarray_new(dst_sel->anchorPos_redo, &UndoRedoSelElement_icd); if (src_sel) { while ((pPos = (DocPos*)utarray_next(src_sel->anchorPos_redo, pPos)) != NULL) { utarray_push_back(dst_sel->anchorPos_redo, pPos); } } utarray_new(dst_sel->curPos_redo, &UndoRedoSelElement_icd); if (src_sel) { while ((pPos = (DocPos*)utarray_next(src_sel->curPos_redo, pPos)) != NULL) { utarray_push_back(dst_sel->curPos_redo, pPos); } } utarray_new(dst_sel->anchorVS_redo, &UndoRedoSelElement_icd); if (src_sel) { while ((pPos = (DocPos*)utarray_next(src_sel->anchorVS_redo, pPos)) != NULL) { utarray_push_back(dst_sel->anchorVS_redo, pPos); } } utarray_new(dst_sel->curVS_redo, &UndoRedoSelElement_icd); if (src_sel) { while ((pPos = (DocPos*)utarray_next(src_sel->curVS_redo, pPos)) != NULL) { utarray_push_back(dst_sel->curVS_redo, pPos); } } } static UT_icd UndoRedoSelection_icd = { sizeof(UndoRedoSelection_t), InitUndoRedoSelection, CopyUndoRedoSelection, DelUndoRedoSelection }; static UT_array* UndoRedoSelectionUTArray = NULL; static bool _InUndoRedoTransaction(); static void _SaveRedoSelection(int token); static int _SaveUndoSelection(); static int _UndoRedoActionMap(int token, UndoRedoSelection_t** selection); // ---------------------------------------------------------------------------- static void _DelayClearZoomCallTip(int delay); #ifdef _EXTRA_DRAG_N_DROP_HANDLER_ static CLIPFORMAT cfDrpF = CF_HDROP; static POINTL ptDummy = { 0, 0 }; static PDROPTARGET pDropTarget = NULL; static DWORD DropFilesProc(CLIPFORMAT cf, HGLOBAL hData, HWND hWnd, DWORD dwKeyState, POINTL pt, void *pUserData); #endif //#define NP3_VIRTUAL_SPACE_ACCESS_OPTIONS (SCVS_RECTANGULARSELECTION | SCVS_NOWRAPLINESTART | SCVS_USERACCESSIBLE) #define NP3_VIRTUAL_SPACE_ACCESS_OPTIONS (SCVS_RECTANGULARSELECTION) //============================================================================= // // IgnoreNotifyChangeEvent(), ObserveNotifyChangeEvent(), CheckNotifyChangeEvent() // static volatile LONG iNotifyChangeStackCounter = 0L; static __forceinline bool CheckNotifyChangeEvent() { return (InterlockedOr(&iNotifyChangeStackCounter, 0L) == 0L); } void IgnoreNotifyChangeEvent() { InterlockedIncrement(&iNotifyChangeStackCounter); } void ObserveNotifyChangeEvent() { if (!CheckNotifyChangeEvent()) { InterlockedDecrement(&iNotifyChangeStackCounter); } if (CheckNotifyChangeEvent()) { UpdateVisibleHotspotIndicators(); UpdateAllBars(false); } } // SCN_UPDATEUI notification #define SC_UPDATE_NP3_INTERNAL_NOTIFY (SC_UPDATE_H_SCROLL << 1) //============================================================================= // // Delay Message Queue Handling (TODO: MultiThreading) // static CmdMessageQueue_t* MessageQueue = NULL; // ---------------------------------------------------------------------------- static int msgcmp(void* mqc1, void* mqc2) { CmdMessageQueue_t* const pMQC1 = (CmdMessageQueue_t*)mqc1; CmdMessageQueue_t* const pMQC2 = (CmdMessageQueue_t*)mqc2; if ((pMQC1->hwnd == pMQC2->hwnd) && (pMQC1->cmd == pMQC2->cmd) && (pMQC1->wparam == pMQC2->wparam) && (pMQC1->lparam == pMQC2->lparam)) { return 0; } return 1; } // ---------------------------------------------------------------------------- #define _MQ_ms(T) ((T) / USER_TIMER_MINIMUM) static void _MQ_AppendCmd(CmdMessageQueue_t* const pMsgQCmd, int cycles) { CmdMessageQueue_t* pmqc = NULL; DL_SEARCH(MessageQueue, pmqc, pMsgQCmd, msgcmp); if (!pmqc) { // NOT found pmqc = AllocMem(sizeof(CmdMessageQueue_t), HEAP_ZERO_MEMORY); pmqc->hwnd = pMsgQCmd->hwnd; pmqc->cmd = pMsgQCmd->cmd; pmqc->wparam = pMsgQCmd->wparam; pmqc->lparam = pMsgQCmd->lparam; pmqc->delay = cycles; DL_APPEND(MessageQueue, pmqc); } if (cycles < 2) { pmqc->delay = -1; // execute now (do not use PostMessage() here) SendMessage(pMsgQCmd->hwnd, pMsgQCmd->cmd, pMsgQCmd->wparam, pMsgQCmd->lparam); } else { pmqc->delay = (pmqc->delay + cycles) / 2; // increase delay } } // ---------------------------------------------------------------------------- /* UNUSED yet static void _MQ_RemoveCmd(CmdMessageQueue_t* const pMsgQCmd) { CmdMessageQueue_t* pmqc; DL_FOREACH(MessageQueue, pmqc) { if ((pMsgQCmd->hwnd == pmqc->hwnd) && (pMsgQCmd->cmd == pmqc->cmd) && (pMsgQCmd->wparam == pmqc->wparam)) { pmqc->delay = -1; } } } */ // ---------------------------------------------------------------------------- <|start_filename|>src/uchardet/uchardet/src/LangModels/LangItalianModel.cpp<|end_filename|> /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "../nsSBCharSetProber.h" /********* Language model for: Italian *********/ /** * Generated by BuildLangModel.py * On: 2016-09-21 18:46:08.841217 **/ /* Character Mapping Table: * ILL: illegal character. * CTR: control character specific to the charset. * RET: carriage/return. * SYM: symbol (punctuation) that does not belong to word. * NUM: 0 - 9. * * Other characters are ordered by probabilities * (0 is the most common character in the language). * * Orders are generic to a language. So the codepoint with order X in * CHARSET1 maps to the same character as the codepoint with the same * order X in CHARSET2 for the same language. * As such, it is possible to get missing order. For instance the * ligature of 'o' and 'e' exists in ISO-8859-15 but not in ISO-8859-1 * even though they are both used for French. Same for the euro sign. */ static const unsigned char Iso_8859_3_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 1, 16, 9, 10, 2, 17, 14, 19, 0, 27, 21, 5, 12, 4, 3, /* 4X */ 13, 20, 6, 8, 7, 11, 15, 25, 26, 23, 18,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 1, 16, 9, 10, 2, 17, 14, 19, 0, 27, 21, 5, 12, 4, 3, /* 6X */ 13, 20, 6, 8, 7, 11, 15, 25, 26, 23, 18,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM, 59,SYM,SYM,SYM,ILL, 60,SYM,SYM, 61, 48, 47, 62,SYM,ILL, 58, /* AX */ SYM, 63,SYM,SYM,SYM,SYM, 64,SYM,SYM, 46, 48, 47, 65,SYM,ILL, 58, /* BX */ 22, 32, 50,ILL, 39, 66, 67, 38, 24, 30, 55, 40, 31, 37, 42, 49, /* CX */ ILL, 44, 29, 33, 51, 68, 34,SYM, 69, 28, 45, 70, 36, 71, 72, 73, /* DX */ 22, 32, 50,ILL, 39, 74, 75, 38, 24, 30, 55, 40, 31, 37, 42, 49, /* EX */ ILL, 44, 29, 33, 51, 76, 34,SYM, 77, 28, 45, 78, 36, 79, 80,SYM, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Iso_8859_15_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 1, 16, 9, 10, 2, 17, 14, 19, 0, 27, 21, 5, 12, 4, 3, /* 4X */ 13, 20, 6, 8, 7, 11, 15, 25, 26, 23, 18,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 1, 16, 9, 10, 2, 17, 14, 19, 0, 27, 21, 5, 12, 4, 3, /* 6X */ 13, 20, 6, 8, 7, 11, 15, 25, 26, 23, 18,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM, 35,SYM, 35,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM, 41, 81,SYM,SYM, 41,SYM,SYM,SYM, 52, 52, 82,SYM, /* BX */ 22, 32, 50, 43, 39, 53, 54, 38, 24, 30, 55, 40, 31, 37, 42, 49, /* CX */ 56, 44, 29, 33, 51, 83, 34,SYM, 57, 28, 45, 84, 36, 85, 86, 87, /* DX */ 22, 32, 50, 43, 39, 53, 54, 38, 24, 30, 55, 40, 31, 37, 42, 49, /* EX */ 56, 44, 29, 33, 51, 88, 34,SYM, 57, 28, 45, 89, 36, 90, 91, 92, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Iso_8859_9_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 1, 16, 9, 10, 2, 17, 14, 19, 0, 27, 21, 5, 12, 4, 3, /* 4X */ 13, 20, 6, 8, 7, 11, 15, 25, 26, 23, 18,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 1, 16, 9, 10, 2, 17, 14, 19, 0, 27, 21, 5, 12, 4, 3, /* 6X */ 13, 20, 6, 8, 7, 11, 15, 25, 26, 23, 18,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM,SYM, 93,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* BX */ 22, 32, 50, 43, 39, 53, 54, 38, 24, 30, 55, 40, 31, 37, 42, 49, /* CX */ 47, 44, 29, 33, 51, 94, 34,SYM, 57, 28, 45, 95, 36, 96, 48, 97, /* DX */ 22, 32, 50, 43, 39, 53, 54, 38, 24, 30, 55, 40, 31, 37, 42, 49, /* EX */ 47, 44, 29, 33, 51, 98, 34,SYM, 57, 28, 45, 99, 36, 46, 48,100, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Iso_8859_1_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 1, 16, 9, 10, 2, 17, 14, 19, 0, 27, 21, 5, 12, 4, 3, /* 4X */ 13, 20, 6, 8, 7, 11, 15, 25, 26, 23, 18,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 1, 16, 9, 10, 2, 17, 14, 19, 0, 27, 21, 5, 12, 4, 3, /* 6X */ 13, 20, 6, 8, 7, 11, 15, 25, 26, 23, 18,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM,SYM,101,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* BX */ 22, 32, 50, 43, 39, 53, 54, 38, 24, 30, 55, 40, 31, 37, 42, 49, /* CX */ 56, 44, 29, 33, 51,102, 34,SYM, 57, 28, 45,103, 36,104,105,106, /* DX */ 22, 32, 50, 43, 39, 53, 54, 38, 24, 30, 55, 40, 31, 37, 42, 49, /* EX */ 56, 44, 29, 33, 51,107, 34,SYM, 57, 28, 45,108, 36,109,110,111, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Windows_1252_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 1, 16, 9, 10, 2, 17, 14, 19, 0, 27, 21, 5, 12, 4, 3, /* 4X */ 13, 20, 6, 8, 7, 11, 15, 25, 26, 23, 18,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 1, 16, 9, 10, 2, 17, 14, 19, 0, 27, 21, 5, 12, 4, 3, /* 6X */ 13, 20, 6, 8, 7, 11, 15, 25, 26, 23, 18,SYM,SYM,SYM,SYM,CTR, /* 7X */ SYM,ILL,SYM,112,SYM,SYM,SYM,SYM,SYM,SYM, 35,SYM, 52,ILL, 41,ILL, /* 8X */ ILL,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, 35,SYM, 52,ILL, 41,113, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM,SYM,114,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* BX */ 22, 32, 50, 43, 39, 53, 54, 38, 24, 30, 55, 40, 31, 37, 42, 49, /* CX */ 56, 44, 29, 33, 51,115, 34,SYM, 57, 28, 45,116, 36,117,118,119, /* DX */ 22, 32, 50, 43, 39, 53, 54, 38, 24, 30, 55, 40, 31, 37, 42, 49, /* EX */ 56, 44, 29, 33, 51,120, 34,SYM, 57, 28, 45,121, 36,122,123,124, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ /* Model Table: * Total sequences: 872 * First 512 sequences: 0.9989484485502651 * Next 512 sequences (512-1024): 0.0010515514497349433 * Rest: -4.336808689942018e-17 * Negative sequences: TODO */ static const PRUint8 ItalianLangModel[] = { 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,2,0,0,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,0,3,3,3,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,0,3,3,3,0,2,0,0,0,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,3,3,3,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,2,3,2,3,2,3,0,3,3,2,2,0, 3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,2,3,2,2,3,2,0,3,3,3,2,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,2, 3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,2,3,3,0,2,3,3,2,3,2,2,3,3,3,3,2,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,2,3,0,0,3,2,3,3,2,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,3,2,3,3,3,3,3,0,3,0,0,3,2,0,3,2,2,0,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,0,2,3,3,2,3,2,3,2,2,3,3,2,2, 3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,0,3,0,3,2,3,3,3,0,3,2,3,0,0, 3,3,3,3,3,3,2,3,3,3,3,3,3,3,2,3,3,0,0,2,0,0,0,3,0,2,3,0,0,3,2,2,2,2, 3,3,3,3,2,3,3,3,3,3,3,3,3,3,2,2,2,2,2,3,0,3,2,3,0,2,0,2,0,3,2,0,2,2, 3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,2,3,2,0,3,2,2,0,3,0,2,2,2,0,2,2,0,0,2, 3,3,3,3,2,3,3,0,2,2,2,3,2,2,2,3,2,0,0,2,0,2,2,3,2,0,0,0,0,2,2,2,2,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,3,0,2,3,0,2,0,3,0,3,0,2,2,2,2,3,2,0, 3,3,3,3,0,3,3,3,2,3,0,3,2,2,3,2,2,3,0,2,0,2,0,0,2,2,2,2,2,0,2,0,0,0, 3,3,3,3,3,2,2,2,2,0,2,3,0,2,3,0,3,2,3,3,0,3,0,3,0,2,0,2,0,3,2,0,2,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,0,2,0,2,0,3,0,3,0,3,0,2,0,0,3,0,3,0, 2,3,0,2,0,0,2,0,2,0,0,3,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,2,2,3,3,2,2,2,2,2,0,3,0,3,0,3,0,2,2,2,0,0,0,0,2,2, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,2,2,2,0,0,0,2,0,2,0,2,2,2,0,0,0,0,0,0, 2,0,0,0,2,0,3,0,2,0,0,0,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,2,3,2,0,2,0,2,0,0,2,2,0,3,0,0,0,2,0,3,0,0,0,0,0,0,0,0, 3,3,3,3,0,3,0,3,2,3,0,2,0,3,0,3,0,0,0,0,0,2,0,2,0,2,3,0,0,0,0,0,0,0, 3,3,3,3,2,2,2,2,0,2,2,3,2,0,0,0,0,0,0,2,0,3,0,2,0,2,0,2,0,0,0,0,0,2, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,3,2,2,3,3,2,3,2,3,0,2,2,0,2,3,0,2,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0, 0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,0,0,3,2,2,0,2,2,0,0,0,0,2,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,0,0,3,2,2,0,0,2,2,0,0,0,0,2,2,0,2,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0, }; const SequenceModel Iso_8859_3ItalianModel = { Iso_8859_3_CharToOrderMap, ItalianLangModel, 34, (float)0.9989484485502651, PR_TRUE, "ISO-8859-3" }; const SequenceModel Iso_8859_15ItalianModel = { Iso_8859_15_CharToOrderMap, ItalianLangModel, 34, (float)0.9989484485502651, PR_TRUE, "ISO-8859-15" }; const SequenceModel Iso_8859_9ItalianModel = { Iso_8859_9_CharToOrderMap, ItalianLangModel, 34, (float)0.9989484485502651, PR_TRUE, "ISO-8859-9" }; const SequenceModel Iso_8859_1ItalianModel = { Iso_8859_1_CharToOrderMap, ItalianLangModel, 34, (float)0.9989484485502651, PR_TRUE, "ISO-8859-1" }; const SequenceModel Windows_1252ItalianModel = { Windows_1252_CharToOrderMap, ItalianLangModel, 34, (float)0.9989484485502651, PR_TRUE, "WINDOWS-1252" }; <|start_filename|>grepWinNP3/sktoolslib_mod/GDIHelpers.cpp<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012-2013, 2017, 2020-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "GDIHelpers.h" #include <cassert> enum { AlphaShift = 24, RedShift = 16, GreenShift = 8, BlueShift = 0 }; COLORREF GDIHelpers::Darker(COLORREF crBase, float fFactor) { assert(fFactor <= 1.0f && fFactor > 0.0f); fFactor = min(fFactor, 1.0f); fFactor = max(fFactor, 0.0f); const BYTE bRed = GetRValue(crBase); const BYTE bBlue = GetBValue(crBase); const BYTE bGreen = GetGValue(crBase); const BYTE bRedShadow = static_cast<BYTE>(bRed * fFactor); const BYTE bBlueShadow = static_cast<BYTE>(bBlue * fFactor); const BYTE bGreenShadow = static_cast<BYTE>(bGreen * fFactor); return RGB(bRedShadow, bGreenShadow, bBlueShadow); } COLORREF GDIHelpers::Lighter(COLORREF crBase, float fFactor) { assert(fFactor > 1.0f); fFactor = max(fFactor, 1.0f); const BYTE bRed = GetRValue(crBase); const BYTE bBlue = GetBValue(crBase); const BYTE bGreen = GetGValue(crBase); const BYTE bRedHilite = static_cast<BYTE>(min((int)(bRed * fFactor), 255)); const BYTE bBlueHilite = static_cast<BYTE>(min((int)(bBlue * fFactor), 255)); const BYTE bGreenHilite = static_cast<BYTE>(min((int)(bGreen * fFactor), 255)); return RGB(bRedHilite, bGreenHilite, bBlueHilite); } void GDIHelpers::FillSolidRect(HDC hDC, int left, int top, int right, int bottom, COLORREF clr) { ::SetBkColor(hDC, clr); RECT rect; rect.left = left; rect.top = top; rect.right = right; rect.bottom = bottom; ::ExtTextOut(hDC, 0, 0, ETO_OPAQUE, &rect, nullptr, 0, nullptr); } void GDIHelpers::FillSolidRect(HDC hDC, const RECT* rc, COLORREF clr) { ::SetBkColor(hDC, clr); ::ExtTextOut(hDC, 0, 0, ETO_OPAQUE, rc, nullptr, 0, nullptr); } Gdiplus::ARGB GDIHelpers::MakeARGB(IN BYTE a, IN BYTE r, IN BYTE g, IN BYTE b) { return ((static_cast<Gdiplus::ARGB>(b) << BlueShift) | (static_cast<Gdiplus::ARGB>(g) << GreenShift) | (static_cast<Gdiplus::ARGB>(r) << RedShift) | (static_cast<Gdiplus::ARGB>(a) << AlphaShift)); } COLORREF GDIHelpers::InterpolateColors(COLORREF c1, COLORREF c2, double fraction) { assert(fraction >= 0.0 && fraction <= 1.0); int r1 = static_cast<int>(GetRValue(c1)); int g1 = static_cast<int>(GetGValue(c1)); int b1 = static_cast<int>(GetBValue(c1)); int r2 = static_cast<int>(GetRValue(c2)); int g2 = static_cast<int>(GetGValue(c2)); int b2 = static_cast<int>(GetBValue(c2)); auto clr = RGB((r2 - r1) * fraction + r1, (g2 - g1) * fraction + g1, (b2 - b1) * fraction + b1); return clr; } void GDIHelpers::RGBToHSB(COLORREF rgb, BYTE& hue, BYTE& saturation, BYTE& brightness) { BYTE r = GetRValue(rgb); BYTE g = GetGValue(rgb); BYTE b = GetBValue(rgb); BYTE minRGB = min(min(r, g), b); BYTE maxRGB = max(max(r, g), b); BYTE delta = maxRGB - minRGB; double l = maxRGB; double s = 0.0; double h = 0.0; if (maxRGB == 0) { hue = 0; saturation = 0; brightness = 0; return; } if (maxRGB) s = (255.0 * delta) / maxRGB; if (static_cast<BYTE>(s) != 0) { if (r == maxRGB) h = 0 + 43 * static_cast<double>(g - b) / delta; else if (g == maxRGB) h = 85 + 43 * static_cast<double>(b - r) / delta; else if (b == maxRGB) h = 171 + 43 * static_cast<double>(r - g) / delta; } else h = 0.0; hue = static_cast<BYTE>(h); saturation = static_cast<BYTE>(s); brightness = static_cast<BYTE>(l); } void GDIHelpers::RGBtoHSL(COLORREF color, float& h, float& s, float& l) { const float rPercent = static_cast<float>(GetRValue(color)) / 255; const float gPercent = static_cast<float>(GetGValue(color)) / 255; const float bPercent = static_cast<float>(GetBValue(color)) / 255; float maxColor = 0; if ((rPercent >= gPercent) && (rPercent >= bPercent)) maxColor = rPercent; else if ((gPercent >= rPercent) && (gPercent >= bPercent)) maxColor = gPercent; else if ((bPercent >= rPercent) && (bPercent >= gPercent)) maxColor = bPercent; float minColor = 0; if ((rPercent <= gPercent) && (rPercent <= bPercent)) minColor = rPercent; else if ((gPercent <= rPercent) && (gPercent <= bPercent)) minColor = gPercent; else if ((bPercent <= rPercent) && (bPercent <= gPercent)) minColor = bPercent; float L = 0, S = 0, H = 0; L = (maxColor + minColor) / 2; if (maxColor == minColor) { S = 0; H = 0; } else { auto d = maxColor - minColor; if (L < .50) S = d / (maxColor + minColor); else S = d / ((2.0f - maxColor) - minColor); if (maxColor == rPercent) H = (gPercent - bPercent) / d; else if (maxColor == gPercent) H = 2.0f + (bPercent - rPercent) / d; else if (maxColor == bPercent) H = 4.0f + (rPercent - gPercent) / d; } H = H * 60; if (H < 0) H += 360; s = S * 100; l = L * 100; h = H; } static float hsLtoRGBSubfunction(float temp1, float temp2, float temp3) { if ((temp3 * 6) < 1) return (temp2 + (temp1 - temp2) * 6 * temp3) * 100; else if ((temp3 * 2) < 1) return temp1 * 100; else if ((temp3 * 3) < 2) return (temp2 + (temp1 - temp2) * (.66666f - temp3) * 6) * 100; else return temp2 * 100; } COLORREF GDIHelpers::HSLtoRGB(float h, float s, float l) { if (s == 0) { BYTE t = static_cast<BYTE>(l / 100 * 255); return RGB(t, t, t); } const float L = l / 100; const float S = s / 100; const float H = h / 360; const float temp1 = (L < .50) ? L * (1 + S) : L + S - (L * S); const float temp2 = 2 * L - temp1; float temp3 = 0; temp3 = H + .33333f; if (temp3 > 1) temp3 -= 1; const float pcr = hsLtoRGBSubfunction(temp1, temp2, temp3); temp3 = H; const float pcg = hsLtoRGBSubfunction(temp1, temp2, temp3); temp3 = H - .33333f; if (temp3 < 0) temp3 += 1; const float pcb = hsLtoRGBSubfunction(temp1, temp2, temp3); BYTE r = static_cast<BYTE>(pcr / 100 * 255); BYTE g = static_cast<BYTE>(pcg / 100 * 255); BYTE b = static_cast<BYTE>(pcb / 100 * 255); return RGB(r, g, b); } bool GDIHelpers::ShortHexStringToCOLORREF(const std::string& s, COLORREF* clr) { if (s.length() != 3) return false; BYTE rgb[3]; // [0]=red, [1]=green, [2]=blue char dig[2]; dig[1] = '\0'; for (int i = 0; i < 3; ++i) { dig[0] = s[i]; BYTE& v = rgb[i]; char* ep = nullptr; errno = 0; // Must convert all digits of string. v = static_cast<BYTE>(strtoul(dig, &ep, 16)); if (errno == 0 && ep == &dig[1]) v = v * 16 + v; else { *clr = 0; return false; } } auto color = RGB(rgb[0], rgb[1], rgb[2]); *clr = color; return true; } bool GDIHelpers::HexStringToCOLORREF(const std::string& s, COLORREF* clr) { if ((s.length() != 6) && (s.length() != 8)) return false; char* ep = nullptr; errno = 0; unsigned long v = strtoul(s.c_str(), &ep, 16); // Must convert all digits of string. if (errno == 0 && ((ep == &s[6]) || (ep == &s[8]))) { BYTE r = (v >> 16) & 0xFF; BYTE g = (v >> 8) & 0xFF; BYTE b = v & 0xFF; *clr = RGB(r, g, b) | (v & 0xFF000000); return true; } *clr = RGB(0, 0, 0); return false; } bool GDIHelpers::LongHexStringToCOLORREF(const std::string& s, COLORREF* clr) { if (s.length() != 8) return false; char* ep = nullptr; errno = 0; unsigned long v = strtoul(s.c_str(), &ep, 16); // Must convert all digits of string. if (errno == 0 && ep == &s[8]) { BYTE b = (v >> 16) & 0xFF; BYTE g = (v >> 8) & 0xFF; BYTE r = v & 0xFF; *clr = RGB(r, g, b) | (v & 0xFF000000); return true; } *clr = RGB(0, 0, 0); return false; } bool GDIHelpers::HexStringToCOLORREF(const std::wstring& s, COLORREF* clr) { if (s.length() != 6) return false; wchar_t* ep = nullptr; errno = 0; unsigned long v = wcstoul(s.c_str(), &ep, 16); if (errno == 0 && ep == &s[6]) { BYTE r = (v >> 16) & 0xFF; BYTE g = (v >> 8) & 0xFF; BYTE b = v & 0xFF; *clr = RGB(r, g, b) | (v & 0xFF000000); return true; } *clr = RGB(0, 0, 0); return false; } <|start_filename|>test/test_files/encoding/UTF-8/Error Detection UTF-8 with tag (issue #1848).cmd<|end_filename|> @echo off :: encoding: UTF-8 exit setlocal enableextensions :: ==================================================================================================================== :: Build batch to create a PortableApps.com's (https://portableapps.com/development) :: :: Notepad3Portable :: :: -------------------------------------------------------------------------------------------------------------------- :: Based on PortableApps.com's Application_Template :: (https://downloads.sourceforge.net/portableapps/PortableApps.com_Application_Template_3.4.1.zip) :: -------------------------------------------------------------------------------------------------------------------- :: Prerequisites: (portable) intallation of: :: ----------------------------------------- :: + PortableApps.com App Compactor (https://portableapps.com/apps/utilities/appcompactor) :: :: + PortableApps.com Launcher (https://portableapps.com/apps/development/portableapps.com_launcher) :: (needed to create the Notepad3Portable.exe Launcher from the sources) :: :: + PortableApps.com Installer (https://portableapps.com/apps/development/portableapps.com_installer) :: :: ==================================================================================================================== ::more than 100 lines are suppressed :: ==================================================================================================================== goto :END :: REPLACE strg(%1) srcfile(%2) replstrg(%3) dstfile(%4) :REPLACE if exist "%~4" del /F /Q "%~4" type NUL > "%~4" for /f "tokens=1,* delims=¶" %%A in (%~2) do ( set string=%%A setlocal EnableDelayedExpansion set modified=!string:%~1=%~3! >> "%~4" echo(!modified! endlocal ) goto:EOF :: -------------------------------------------------------------------------------------------------------------------- :GETDATE for /f "tokens=2 delims==" %%a in (' wmic OS Get localdatetime /value ') do set "dt=%%a" set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%" set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%" ::set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%" ::set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%" ::echo datestamp: "%datestamp%" ::echo timestamp: "%timestamp%" ::echo fullstamp: "%fullstamp%" goto:EOF :: -------------------------------------------------------------------------------------------------------------------- :GETFILEVER set "file=%~1" if not defined file goto:EOF if not exist "%file%" goto:EOF set "FILEVER=" for /F "tokens=2 delims==" %%a in (' wmic datafile where name^="%file:\=\\%" Get Version /value ') do set "FILEVER=%%a" ::echo %file% = %FILEVER% goto:EOF :: -------------------------------------------------------------------------------------------------------------------- :GETBUILD set /p nxbuild=<%NP3_BUILD_VER% set /a BUILD = %nxbuild% - 1 set /p DEVNAME=<%NP3_BUILD_NAME% set DEVNAME=%DEVNAME:"=% goto:EOF :: -------------------------------------------------------------------------------------------------------------------- rem Resolve path to absolute. rem Param 1: Name of output variable. rem Param 2: Path to resolve. rem Return: Resolved absolute path. :RESOLVEPATH set %1=%~dpfn2 goto:EOF :: -------------------------------------------------------------------------------------------------------------------- :: ==================================================================================================================== :END endlocal ::pause ::exit :: ==================================================================================================================== <|start_filename|>test/test_files/StyleLexers/styleLexJS/environment.js<|end_filename|> // // Copyright (C) Microsoft. All rights reserved. // /// <disable>JS2085.EnableStrictMode</disable> "use strict"; var CloudExperienceHost; (function (CloudExperienceHost) { class Environment { static getTarget() { var retValue; var regValue = CloudExperienceHostAPI.Environment.target; switch (regValue) { case 0: retValue = CloudExperienceHost.TargetEnvironment.PROD; break; case 1: retValue = CloudExperienceHost.TargetEnvironment.INT; break; default: retValue = CloudExperienceHost.TargetEnvironment.PROD; break; } return retValue; } static hasInternetAccess() { let hasInternetAccess = false; let connectionProfile = Windows.Networking.Connectivity.NetworkInformation.getInternetConnectionProfile(); if (connectionProfile && (connectionProfile.getNetworkConnectivityLevel() === Windows.Networking.Connectivity.NetworkConnectivityLevel.internetAccess)) { if (connectionProfile.isWwanConnectionProfile && Environment._isOobeScenario() && !Environment.hasDataMartBeenChecked) { Environment.wwanConnectionIsDataMartSim = Environment.isDataMartSim(); Environment.hasDataMartBeenChecked = true; } hasInternetAccess = !Environment.wwanConnectionIsDataMartSim; } return hasInternetAccess; } static hasNetworkConnectivity() { let hasNetworkConnectivity = false; let ConnectionProfiles = Windows.Networking.Connectivity.NetworkInformation.getConnectionProfiles(); if (ConnectionProfiles.length !== 0) { for (var i = 0; i < ConnectionProfiles.length; i++) { if (ConnectionProfiles[i].getNetworkConnectivityLevel() > Windows.Networking.Connectivity.NetworkConnectivityLevel.none) { hasNetworkConnectivity = true; break; } } } return hasNetworkConnectivity; } static isDataMartSim() { let isDmSim = false; try { let modem = Windows.Networking.NetworkOperators.MobileBroadbandModem.getDefault(); if (modem) { let iccid = modem.deviceInformation.simIccId; isDmSim = CloudExperienceHostAPI.UtilStaticsCore.isDataMartSim(iccid); } } catch (exception) { } return isDmSim; } static getLicensingPoliciesAsync(namesJson) { return new WinJS.Promise(function (completeDispatch, errorDispatch, progressDispatch) { let names = JSON.parse(namesJson); let results = new Array(names.length); for (let i = 0; i < names.length; i++) { results[i] = CloudExperienceHostAPI.UtilStaticsCore.getLicensingPolicyValue(names[i]); } completeDispatch(JSON.stringify(results)); }); } static isNetworkRequiredAsync() { return new WinJS.Promise(function (completeDispatch, errorDispatch, progressDispatch) { let result = CloudExperienceHostAPI.UtilStaticsCore.isNetworkRequired; completeDispatch(result); }); } static GetWiFiHostedApplicationArguments() { let propertySet = new Windows.Foundation.Collections.PropertySet(); propertySet.insert("IsNetworkRequired", CloudExperienceHostAPI.UtilStaticsCore.isNetworkRequired); return propertySet; } static GetWiFiHostedApplicationArgumentsA() { let propertySet = Environment.GetWiFiHostedApplicationArguments(); propertySet.insert("NetworkUXMode", "Windows.Core"); return propertySet; } static GetWiFiHostedApplicationArgumentsHub() { let propertySet = new Windows.Foundation.Collections.PropertySet(); propertySet.insert("IsNetworkRequired", true); // Reference to NetworkUXMode enum defined in NetworkUX xaml app propertySet.insert("NetworkUXMode", "Desktop"); return propertySet; } static getMachineModel() { return CloudExperienceHostAPI.Environment.machineModel; } static getManufacturer() { return CloudExperienceHostAPI.Environment.manufacturer; } static getPlatform() { var retValue; var regValue = CloudExperienceHostAPI.Environment.platform; switch (regValue) { case 3: retValue = CloudExperienceHost.TargetPlatform.DESKTOP; break; case 5: retValue = CloudExperienceHost.TargetPlatform.XBOX; break; case 6: retValue = CloudExperienceHost.TargetPlatform.SURFACEHUB; break; case 10: retValue = CloudExperienceHost.TargetPlatform.HOLOGRAPHIC; break; default: // For non-legacy TargetPlatform values (any nturtl > 10) // getPlatform() should reflect the CloudExperienceHostAPI.Environment.platform value directly // Instead of looping back to a predefined CloudExperienceHost.TargetPlatform friendly name. // (core.ts may define a friendly name for an nturtl value if required for CXH app code) retValue = "CloudExperienceHost.Platform." + regValue; break; } return retValue; } static getEdition() { return CloudExperienceHostAPI.Environment.edition; } static isRemoteDesktopSession() { var isRemoteDesktopSession = false; var interactiveSession = Windows.System.RemoteDesktop.InteractiveSession; if (interactiveSession && interactiveSession.isRemote) { isRemoteDesktopSession = true; } return isRemoteDesktopSession; } static isSpeechDisabled() { let navMesh = CloudExperienceHost.getNavMesh(); return navMesh && navMesh.getSpeechDisabled(); } static _isOobeScenario() { let isOobe = false; try { if (Environment.getPlatform() == CloudExperienceHost.TargetPlatform.XBOX) { isOobe = !Windows.Xbox.System.Internal.XConfig.XConfigProperties.isOobeCompleted; } else { isOobe = CloudExperienceHost.getContext && CloudExperienceHost.getContext() && (CloudExperienceHost.getContext().host.toLowerCase() === "frx"); } } catch (e) { } return isOobe; } } Environment.hasDataMartBeenChecked = false; Environment.wwanConnectionIsDataMartSim = false; CloudExperienceHost.Environment = Environment; class PersonalizedWelcome { static getShouldSkipAsync() { return CloudExperienceHost.Policy.getAutoPilotPolicyDwordAsync("PersonalShowPersonalizedWelcome").then(showPolicy => { const skipPersonalizedWelcome = (showPolicy !== 1); if (skipPersonalizedWelcome) { CloudExperienceHost.Telemetry.logEvent("PersonalizedWelcome_Skip"); } return skipPersonalizedWelcome; }); } } CloudExperienceHost.PersonalizedWelcome = PersonalizedWelcome; class Wireless { static getShouldSkipAsync() { let skipNetworkConnectPage = CloudExperienceHostAPI.UtilStaticsCore.hideWireless; if (!skipNetworkConnectPage) { let connectionProfile = Windows.Networking.Connectivity.NetworkInformation.getInternetConnectionProfile(); if (connectionProfile) { skipNetworkConnectPage = (connectionProfile.getNetworkConnectivityLevel() === Windows.Networking.Connectivity.NetworkConnectivityLevel.internetAccess) && !connectionProfile.isWwanConnectionProfile; } } return WinJS.Promise.wrap(skipNetworkConnectPage); } } CloudExperienceHost.Wireless = Wireless; class WirelessCommercial { static getShouldSkipAsync() { let oobeResumeEnabled = CloudExperienceHost.Storage.SharableData.getValue("OOBEResumeEnabled"); // if device did not reboot and resume, then skip the page if (!oobeResumeEnabled) { return WinJS.Promise.wrap(true); } let skipNetworkConnectPage = CloudExperienceHostAPI.UtilStaticsCore.hideWirelessCommercial; CloudExperienceHost.Telemetry.logEvent("WirelessCommercial_HideWirelessCommercial", skipNetworkConnectPage); if (!skipNetworkConnectPage) { skipNetworkConnectPage = Environment.hasInternetAccess(); CloudExperienceHost.Telemetry.logEvent("WirelessCommercial_SkipNetworkConnectPage", skipNetworkConnectPage); } return WinJS.Promise.wrap(skipNetworkConnectPage); } } CloudExperienceHost.WirelessCommercial = WirelessCommercial; class Bookends { static getShouldSkipAsync() { let localAccountManager = new CloudExperienceHostBroker.Account.LocalAccountManager(); let isSpeechAllowedByPolicy = true; try { let speechController = AppObjectFactory.getInstance().getObjectFromString("CloudExperienceHostAPI.Speech.SpeechRecognitionController"); isSpeechAllowedByPolicy = speechController.isSpeechAllowedByPolicy(); } catch (exception) { CloudExperienceHost.Telemetry.logEvent("IsSpeechAllowedByPolicyError", CloudExperienceHost.GetJsonFromError(exception)); } let skipIntro = localAccountManager.unattendCreatedUser || !CloudExperienceHost.Cortana.isCortanaSupported() || !isSpeechAllowedByPolicy || CloudExperienceHost.Storage.SharableData.getValue("retailDemoEnabled"); if (!skipIntro) { // Check for Microphone access. Assumption is if there is a Microphone then there are speakers. try { let captureSettings = new Windows.Media.Capture.MediaCaptureInitializationSettings(); captureSettings.streamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.audio; captureSettings.mediaCategory = Windows.Media.Capture.MediaCategory.speech; let capture = new Windows.Media.Capture.MediaCapture(); let capturePromise = capture.initializeAsync(captureSettings).then(() => { // Successfully accessed the microphone, don't skip return WinJS.Promise.wrap(false); }, (error) => { // Failed to access microphone, skip bookends return WinJS.Promise.wrap(true); }); return capturePromise; } catch (exception) { // Return true to skip page if media capture initialization fails return WinJS.Promise.wrap(true); } } return WinJS.Promise.wrap(skipIntro); } } CloudExperienceHost.Bookends = Bookends; class AccountDisambiguation { static getShouldSkipAsync() { let allowedProviders = CloudExperienceHost.getAllowedIdentityProviders(); let onlineProviderAllowed = ((allowedProviders.indexOf(CloudExperienceHost.SignInIdentityProviders.MSA) != -1) || (allowedProviders.indexOf(CloudExperienceHost.SignInIdentityProviders.AAD) != -1)); // Skip (return success) if no online providers are allowed return WinJS.Promise.wrap(!onlineProviderAllowed); } } CloudExperienceHost.AccountDisambiguation = AccountDisambiguation; class AccountAndServices { // Unattend settings related to account creation and autologon are checked, and can cause us to skip most of // the Account and Services sections in CXH hosted OOBE. static shouldSkipAccountAndServices() { let localAccountManager = new CloudExperienceHostBroker.Account.LocalAccountManager(); return localAccountManager.unattendCreatedUser; } // Wraps the check above. Needed for the preload checks specified in the navigation JSON. static getShouldSkipAsync() { return WinJS.Promise.wrap(CloudExperienceHost.AccountAndServices.shouldSkipAccountAndServices()); } static getUserProfileEngagementAsync(items) { let promises = items.map((item) => { let itemStatus = "Ineligible"; let timeout = false; let userProfileEngagementPromise = CloudExperienceHostAPI.UserProfileEngagementCore.checkEngagementAsync(item).then((result) => { itemStatus = result; }); let timeoutPromise = WinJS.Promise.timeout(10000).then(() => { timeout = true; }); return WinJS.Promise.any([userProfileEngagementPromise, timeoutPromise]).then(() => { if (timeout) { CloudExperienceHost.Telemetry.logEvent("UserProfileEngagementItemTimeout", JSON.stringify({ item: item })); } else { CloudExperienceHost.Telemetry.logEvent("UserProfileEngagementItem", JSON.stringify({ item: item, result: itemStatus })); } return itemStatus; }); }); return WinJS.Promise.join(promises); } static isDomainAccount() { // Although we are calling into a ContentDeliveryManager specific WinRT object, note // that this is just a standard domain account check via LsaLookupUserAccountType(). return CloudExperienceHostAPI.ContentDeliveryManagerHelpers.isDomainAccount; } } CloudExperienceHost.AccountAndServices = AccountAndServices; class FeatureStaging { static isOobeFeatureEnabled(featureName) { return CloudExperienceHostAPI.FeatureStaging.isOobeFeatureEnabled(featureName); } } CloudExperienceHost.FeatureStaging = FeatureStaging; class FeatureUpdate { static getShouldSkipAsync() { let localAccountManager = new CloudExperienceHostBroker.Account.LocalAccountManager(); let zdpManager = AppObjectFactory.getInstance().getObjectFromString("CloudExperienceHostAPI.OobeZdpManagerStaticsCore"); let skipFeatureUpdate = localAccountManager.unattendCreatedUser || zdpManager.shouldSkip; if (!skipFeatureUpdate) { skipFeatureUpdate = true; try { let featureUpdateManager = AppObjectFactory.getInstance().getObjectFromString("CloudExperienceHostAPI.OobeFeatureUpdateManagerStatics"); skipFeatureUpdate = featureUpdateManager.shouldSkip; } catch (error) { } } return WinJS.Promise.wrap(skipFeatureUpdate); } } CloudExperienceHost.FeatureUpdate = FeatureUpdate; })(CloudExperienceHost || (CloudExperienceHost = {})); //# sourceMappingURL=environment.js.map <|start_filename|>grepWinNP3/sktoolslib_mod/Monitor.cpp<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2020-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "Monitor.h" #include <vector> #include <algorithm> static BOOL CALLBACK MonitorEnum(HMONITOR hMon, HDC /*hdc*/, LPRECT lprcMonitor, LPARAM pData) { MONITORINFOEX miEx{}; miEx.cbSize = sizeof(MONITORINFOEX); GetMonitorInfo(hMon, &miEx); if (miEx.dwFlags == DISPLAY_DEVICE_MIRRORING_DRIVER) { return TRUE; } std::vector<RECT>* pMonRects = reinterpret_cast<std::vector<RECT>*>(pData); pMonRects->push_back(*lprcMonitor); return TRUE; } std::wstring GetMonitorSetupHash() { std::vector<RECT> monRects; EnumDisplayMonitors(nullptr, nullptr, MonitorEnum, reinterpret_cast<LPARAM>(&monRects)); std::sort(monRects.begin(), monRects.end(), [](const RECT& a, const RECT& b) -> bool { if (a.left == b.left) return a.top < b.top; return a.left < b.left; }); return GetHashText(monRects.data(), monRects.size() * sizeof(RECT), HashType::HashMd5); } <|start_filename|>lexilla/lexlib/PropSetSimple.cxx<|end_filename|> // Scintilla source code edit control /** @file PropSetSimple.cxx ** A basic string to string map. **/ // Copyright 1998-2010 by <NAME> <<EMAIL>> // The License.txt file describes the conditions under which this software may be distributed. // Maintain a dictionary of properties #include <cstdlib> #include <cstring> #include <string> #include <string_view> #include <map> #include <functional> #include "PropSetSimple.h" using namespace Lexilla; namespace { typedef std::map<std::string, std::string, std::less<>> mapss; mapss *PropsFromPointer(void *impl) noexcept { return static_cast<mapss *>(impl); } } PropSetSimple::PropSetSimple() { mapss *props = new mapss; impl = static_cast<void *>(props); } PropSetSimple::~PropSetSimple() { mapss *props = PropsFromPointer(impl); delete props; impl = nullptr; } bool PropSetSimple::Set(std::string_view key, std::string_view val) { mapss *props = PropsFromPointer(impl); if (!props) return false; mapss::iterator it = props->find(key); if (it != props->end()) { if (val == it->second) return false; it->second = val; } else { props->emplace(key, val); } return true; } const char *PropSetSimple::Get(std::string_view key) const { mapss *props = PropsFromPointer(impl); if (props) { mapss::const_iterator keyPos = props->find(key); if (keyPos != props->end()) { return keyPos->second.c_str(); } } return ""; } int PropSetSimple::GetInt(std::string_view key, int defaultValue) const { const char *val = Get(key); if (*val) { return atoi(val); } return defaultValue; } <|start_filename|>scintilla/src/Decoration.h<|end_filename|> /** @file Decoration.h ** Visual elements added over text. **/ // Copyright 1998-2007 by <NAME> <<EMAIL>> // The License.txt file describes the conditions under which this software may be distributed. #ifndef DECORATION_H #define DECORATION_H namespace Scintilla::Internal { class IDecoration { public: virtual ~IDecoration() {} virtual bool Empty() const noexcept = 0; virtual int Indicator() const noexcept = 0; virtual Sci::Position Length() const noexcept = 0; virtual int ValueAt(Sci::Position position) const noexcept = 0; virtual Sci::Position StartRun(Sci::Position position) const noexcept = 0; virtual Sci::Position EndRun(Sci::Position position) const noexcept = 0; virtual void SetValueAt(Sci::Position position, int value) = 0; virtual void InsertSpace(Sci::Position position, Sci::Position insertLength) = 0; virtual Sci::Position Runs() const noexcept = 0; }; class IDecorationList { public: virtual ~IDecorationList() {} virtual const std::vector<const IDecoration*> &View() const noexcept = 0; virtual void SetCurrentIndicator(int indicator) = 0; virtual int GetCurrentIndicator() const noexcept = 0; virtual void SetCurrentValue(int value) = 0; virtual int GetCurrentValue() const noexcept = 0; // Returns with changed=true if some values may have changed virtual FillResult<Sci::Position> FillRange(Sci::Position position, int value, Sci::Position fillLength) = 0; virtual void InsertSpace(Sci::Position position, Sci::Position insertLength) = 0; virtual void DeleteRange(Sci::Position position, Sci::Position deleteLength) = 0; virtual void DeleteLexerDecorations() = 0; virtual int AllOnFor(Sci::Position position) const noexcept = 0; virtual int ValueAt(int indicator, Sci::Position position) noexcept = 0; virtual Sci::Position Start(int indicator, Sci::Position position) noexcept = 0; virtual Sci::Position End(int indicator, Sci::Position position) noexcept = 0; virtual bool ClickNotified() const noexcept = 0; virtual void SetClickNotified(bool notified) noexcept = 0; }; std::unique_ptr<IDecoration> DecorationCreate(bool largeDocument, int indicator); std::unique_ptr<IDecorationList> DecorationListCreate(bool largeDocument); } #endif <|start_filename|>scintilla/src/ContractionState.cxx<|end_filename|> // Scintilla source code edit control /** @file ContractionState.cxx ** Manages visibility of lines for folding and wrapping. **/ // Copyright 1998-2007 by <NAME> <<EMAIL>> // The License.txt file describes the conditions under which this software may be distributed. #include <cstddef> #include <cassert> #include <cstring> #include <stdexcept> #include <string_view> #include <vector> #include <optional> #include <algorithm> #include <memory> #include "Debugging.h" #include "Position.h" #include "UniqueString.h" #include "SplitVector.h" #include "Partitioning.h" #include "RunStyles.h" #include "SparseVector.h" #include "ContractionState.h" using namespace Scintilla::Internal; namespace { template <typename LINE> class ContractionState final : public IContractionState { // These contain 1 element for every document line. std::unique_ptr<RunStyles<LINE, char>> visible; std::unique_ptr<RunStyles<LINE, char>> expanded; std::unique_ptr<RunStyles<LINE, int>> heights; std::unique_ptr<SparseVector<UniqueString>> foldDisplayTexts; std::unique_ptr<Partitioning<LINE>> displayLines; LINE linesInDocument; void EnsureData(); bool OneToOne() const noexcept { // True when each document line is exactly one display line so need for // complex data structures. return visible == nullptr; } void InsertLine(Sci::Line lineDoc); void DeleteLine(Sci::Line lineDoc); public: ContractionState() noexcept; // Deleted so ContractionState objects can not be copied. ContractionState(const ContractionState &) = delete; void operator=(const ContractionState &) = delete; ContractionState(ContractionState &&) = delete; void operator=(ContractionState &&) = delete; ~ContractionState() override; void Clear() noexcept override; Sci::Line LinesInDoc() const noexcept override; Sci::Line LinesDisplayed() const noexcept override; Sci::Line DisplayFromDoc(Sci::Line lineDoc) const noexcept override; Sci::Line DisplayLastFromDoc(Sci::Line lineDoc) const noexcept override; Sci::Line DocFromDisplay(Sci::Line lineDisplay) const noexcept override; void InsertLines(Sci::Line lineDoc, Sci::Line lineCount) override; void DeleteLines(Sci::Line lineDoc, Sci::Line lineCount) override; bool GetVisible(Sci::Line lineDoc) const noexcept override; bool SetVisible(Sci::Line lineDocStart, Sci::Line lineDocEnd, bool isVisible) override; bool HiddenLines() const noexcept override; const char *GetFoldDisplayText(Sci::Line lineDoc) const noexcept override; bool SetFoldDisplayText(Sci::Line lineDoc, const char *text) override; bool GetExpanded(Sci::Line lineDoc) const noexcept override; bool SetExpanded(Sci::Line lineDoc, bool isExpanded) override; Sci::Line ContractedNext(Sci::Line lineDocStart) const noexcept override; int GetHeight(Sci::Line lineDoc) const noexcept override; bool SetHeight(Sci::Line lineDoc, int height) override; void ShowAll() noexcept override; void Check() const noexcept; }; template <typename LINE> ContractionState<LINE>::ContractionState() noexcept : linesInDocument(1) { } template <typename LINE> ContractionState<LINE>::~ContractionState() = default; template <typename LINE> void ContractionState<LINE>::EnsureData() { if (OneToOne()) { visible = std::make_unique<RunStyles<LINE, char>>(); expanded = std::make_unique<RunStyles<LINE, char>>(); heights = std::make_unique<RunStyles<LINE, int>>(); foldDisplayTexts = std::make_unique<SparseVector<UniqueString>>(); displayLines = std::make_unique<Partitioning<LINE>>(4); InsertLines(0, linesInDocument); } } template <typename LINE> void ContractionState<LINE>::InsertLine(Sci::Line lineDoc) { if (OneToOne()) { linesInDocument++; } else { const LINE lineDocCast = static_cast<LINE>(lineDoc); visible->InsertSpace(lineDocCast, 1); visible->SetValueAt(lineDocCast, 1); expanded->InsertSpace(lineDocCast, 1); expanded->SetValueAt(lineDocCast, 1); heights->InsertSpace(lineDocCast, 1); heights->SetValueAt(lineDocCast, 1); foldDisplayTexts->InsertSpace(lineDocCast, 1); foldDisplayTexts->SetValueAt(lineDocCast, nullptr); const Sci::Line lineDisplay = DisplayFromDoc(lineDoc); displayLines->InsertPartition(lineDocCast, static_cast<LINE>(lineDisplay)); displayLines->InsertText(lineDocCast, 1); } } template <typename LINE> void ContractionState<LINE>::DeleteLine(Sci::Line lineDoc) { if (OneToOne()) { linesInDocument--; } else { const LINE lineDocCast = static_cast<LINE>(lineDoc); if (GetVisible(lineDoc)) { displayLines->InsertText(lineDocCast, -heights->ValueAt(lineDocCast)); } displayLines->RemovePartition(lineDocCast); visible->DeleteRange(lineDocCast, 1); expanded->DeleteRange(lineDocCast, 1); heights->DeleteRange(lineDocCast, 1); foldDisplayTexts->DeletePosition(lineDocCast); } } template <typename LINE> void ContractionState<LINE>::Clear() noexcept { visible.reset(); expanded.reset(); heights.reset(); foldDisplayTexts.reset(); displayLines.reset(); linesInDocument = 1; } template <typename LINE> Sci::Line ContractionState<LINE>::LinesInDoc() const noexcept { if (OneToOne()) { return linesInDocument; } else { return displayLines->Partitions() - 1; } } template <typename LINE> Sci::Line ContractionState<LINE>::LinesDisplayed() const noexcept { if (OneToOne()) { return linesInDocument; } else { return displayLines->PositionFromPartition(static_cast<LINE>(LinesInDoc())); } } template <typename LINE> Sci::Line ContractionState<LINE>::DisplayFromDoc(Sci::Line lineDoc) const noexcept { if (OneToOne()) { return (lineDoc <= linesInDocument) ? lineDoc : linesInDocument; } else { if (lineDoc > displayLines->Partitions()) lineDoc = displayLines->Partitions(); return displayLines->PositionFromPartition(static_cast<LINE>(lineDoc)); } } template <typename LINE> Sci::Line ContractionState<LINE>::DisplayLastFromDoc(Sci::Line lineDoc) const noexcept { return DisplayFromDoc(lineDoc) + GetHeight(lineDoc) - 1; } template <typename LINE> Sci::Line ContractionState<LINE>::DocFromDisplay(Sci::Line lineDisplay) const noexcept { if (OneToOne()) { return lineDisplay; } else { if (lineDisplay < 0) { return 0; } if (lineDisplay > LinesDisplayed()) { return displayLines->PartitionFromPosition(static_cast<LINE>(LinesDisplayed())); } const Sci::Line lineDoc = displayLines->PartitionFromPosition(static_cast<LINE>(lineDisplay)); PLATFORM_ASSERT(GetVisible(lineDoc)); return lineDoc; } } template <typename LINE> void ContractionState<LINE>::InsertLines(Sci::Line lineDoc, Sci::Line lineCount) { if (OneToOne()) { linesInDocument += static_cast<LINE>(lineCount); } else { for (Sci::Line l = 0; l < lineCount; l++) { InsertLine(lineDoc + l); } } Check(); } template <typename LINE> void ContractionState<LINE>::DeleteLines(Sci::Line lineDoc, Sci::Line lineCount) { if (OneToOne()) { linesInDocument -= static_cast<LINE>(lineCount); } else { for (Sci::Line l = 0; l < lineCount; l++) { DeleteLine(lineDoc); } } Check(); } template <typename LINE> bool ContractionState<LINE>::GetVisible(Sci::Line lineDoc) const noexcept { if (OneToOne()) { return true; } else { if (lineDoc >= visible->Length()) return true; return visible->ValueAt(static_cast<LINE>(lineDoc)) == 1; } } template <typename LINE> bool ContractionState<LINE>::SetVisible(Sci::Line lineDocStart, Sci::Line lineDocEnd, bool isVisible) { if (OneToOne() && isVisible) { return false; } else { EnsureData(); Sci::Line delta = 0; Check(); if ((lineDocStart <= lineDocEnd) && (lineDocStart >= 0) && (lineDocEnd < LinesInDoc())) { for (Sci::Line line = lineDocStart; line <= lineDocEnd; line++) { if (GetVisible(line) != isVisible) { const int heightLine = heights->ValueAt(static_cast<LINE>(line)); const int difference = isVisible ? heightLine : -heightLine; visible->SetValueAt(static_cast<LINE>(line), isVisible ? 1 : 0); displayLines->InsertText(static_cast<LINE>(line), difference); delta += difference; } } } else { return false; } Check(); return delta != 0; } } template <typename LINE> bool ContractionState<LINE>::HiddenLines() const noexcept { if (OneToOne()) { return false; } else { return !visible->AllSameAs(1); } } template <typename LINE> const char *ContractionState<LINE>::GetFoldDisplayText(Sci::Line lineDoc) const noexcept { Check(); return foldDisplayTexts->ValueAt(lineDoc).get(); } template <typename LINE> bool ContractionState<LINE>::SetFoldDisplayText(Sci::Line lineDoc, const char *text) { EnsureData(); const char *foldText = foldDisplayTexts->ValueAt(lineDoc).get(); if (!foldText || !text || 0 != strcmp(text, foldText)) { UniqueString uns = IsNullOrEmpty(text) ? UniqueString() : UniqueStringCopy(text); foldDisplayTexts->SetValueAt(lineDoc, std::move(uns)); Check(); return true; } else { Check(); return false; } } template <typename LINE> bool ContractionState<LINE>::GetExpanded(Sci::Line lineDoc) const noexcept { if (OneToOne()) { return true; } else { Check(); return expanded->ValueAt(static_cast<LINE>(lineDoc)) == 1; } } template <typename LINE> bool ContractionState<LINE>::SetExpanded(Sci::Line lineDoc, bool isExpanded) { if (OneToOne() && isExpanded) { return false; } else { EnsureData(); if (isExpanded != (expanded->ValueAt(static_cast<LINE>(lineDoc)) == 1)) { expanded->SetValueAt(static_cast<LINE>(lineDoc), isExpanded ? 1 : 0); Check(); return true; } else { Check(); return false; } } } template <typename LINE> Sci::Line ContractionState<LINE>::ContractedNext(Sci::Line lineDocStart) const noexcept { if (OneToOne()) { return -1; } else { Check(); if (!expanded->ValueAt(static_cast<LINE>(lineDocStart))) { return lineDocStart; } else { const Sci::Line lineDocNextChange = expanded->EndRun(static_cast<LINE>(lineDocStart)); if (lineDocNextChange < LinesInDoc()) return lineDocNextChange; else return -1; } } } template <typename LINE> int ContractionState<LINE>::GetHeight(Sci::Line lineDoc) const noexcept { if (OneToOne()) { return 1; } else { return heights->ValueAt(static_cast<LINE>(lineDoc)); } } // Set the number of display lines needed for this line. // Return true if this is a change. template <typename LINE> bool ContractionState<LINE>::SetHeight(Sci::Line lineDoc, int height) { if (OneToOne() && (height == 1)) { return false; } else if (lineDoc < LinesInDoc()) { EnsureData(); if (GetHeight(lineDoc) != height) { if (GetVisible(lineDoc)) { displayLines->InsertText(static_cast<LINE>(lineDoc), height - GetHeight(lineDoc)); } heights->SetValueAt(static_cast<LINE>(lineDoc), height); Check(); return true; } else { Check(); return false; } } else { return false; } } template <typename LINE> void ContractionState<LINE>::ShowAll() noexcept { const LINE lines = static_cast<LINE>(LinesInDoc()); Clear(); linesInDocument = lines; } // Debugging checks template <typename LINE> void ContractionState<LINE>::Check() const noexcept { #ifdef CHECK_CORRECTNESS for (Sci::Line vline = 0; vline < LinesDisplayed(); vline++) { const Sci::Line lineDoc = DocFromDisplay(vline); PLATFORM_ASSERT(GetVisible(lineDoc)); } for (Sci::Line lineDoc = 0; lineDoc < LinesInDoc(); lineDoc++) { const Sci::Line displayThis = DisplayFromDoc(lineDoc); const Sci::Line displayNext = DisplayFromDoc(lineDoc + 1); const Sci::Line height = displayNext - displayThis; PLATFORM_ASSERT(height >= 0); if (GetVisible(lineDoc)) { PLATFORM_ASSERT(GetHeight(lineDoc) == height); } else { PLATFORM_ASSERT(0 == height); } } #endif } } namespace Scintilla::Internal { std::unique_ptr<IContractionState> ContractionStateCreate(bool largeDocument) { if (largeDocument) return std::make_unique<ContractionState<Sci::Line>>(); else return std::make_unique<ContractionState<int>>(); } } <|start_filename|>grepWinNP3/sktoolslib_mod/shelllink.cpp<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012, 2020 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "ShellLink.h" //////////////// Macros / Locals ///////////////////////////////////// #ifdef _DEBUG # define new DEBUG_NEW # undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif //////////////// Implementation ////////////////////////////////////// CShellLinkInfo::CShellLinkInfo() : m_pidl(NULL) , m_wHotkey(0) , m_nIconIndex(0) , m_nShowCmd(SW_SHOW) { } CShellLinkInfo::CShellLinkInfo(const CShellLinkInfo& sli) { *this = sli; } CShellLinkInfo::~CShellLinkInfo() { // Get the shell's allocator. IMalloc* pMalloc; HRESULT hRes = SHGetMalloc(&pMalloc); if (!SUCCEEDED(hRes)) { return; } //Free the pidl if (m_pidl) { pMalloc->Free(m_pidl); m_pidl = NULL; } // Release the pointer to IMalloc pMalloc->Release(); } CShellLinkInfo& CShellLinkInfo::operator=(const CShellLinkInfo& sli) { m_sTarget = sli.m_sTarget; m_pidl = sli.m_pidl; m_sArguments = sli.m_sArguments; m_sDescription = sli.m_sDescription; m_wHotkey = sli.m_wHotkey; m_sIconLocation = sli.m_sIconLocation; m_nIconIndex = sli.m_nIconIndex; m_nShowCmd = sli.m_nShowCmd; m_sWorkingDirectory = sli.m_sWorkingDirectory; return *this; } CShellLink::CShellLink() : m_psl(NULL) , m_ppf(NULL) , m_bAttemptedInitialise(FALSE) { } CShellLink::~CShellLink() { if (m_ppf) { m_ppf->Release(); m_ppf = NULL; } if (m_psl) { m_psl->Release(); m_psl = NULL; } } BOOL CShellLink::Initialise() { BOOL bSuccess = FALSE; if (m_bAttemptedInitialise) bSuccess = (m_psl != NULL); else { //Instantiate the COM class HRESULT hRes = ::CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&m_psl); if (SUCCEEDED(hRes)) { //Also get a pointer to IPersistFile hRes = m_psl->QueryInterface(IID_IPersistFile, (LPVOID*)&m_ppf); bSuccess = SUCCEEDED(hRes); } m_bAttemptedInitialise = TRUE; } return bSuccess; } BOOL CShellLink::Create(const CShellLinkInfo& sli) { if (!Initialise()) return FALSE; m_sli = sli; return TRUE; } BOOL CShellLink::Save(const std::wstring& sFilename) { if (!Initialise()) return FALSE; BOOL bSuccess = FALSE; HRESULT hRes; //Convert the path to a UNICODE string WCHAR wszPath[MAX_PATH]; wcscpy_s(wszPath, _countof(wszPath), sFilename.c_str()); //Set the various link values if (m_sli.m_pidl) { hRes = m_psl->SetIDList(m_sli.m_pidl); } else { hRes = m_psl->SetPath(m_sli.m_sTarget.c_str()); } hRes = m_psl->SetWorkingDirectory(m_sli.m_sWorkingDirectory.c_str()); hRes = m_psl->SetIconLocation(m_sli.m_sIconLocation.c_str(), m_sli.m_nIconIndex); hRes = m_psl->SetDescription(m_sli.m_sDescription.c_str()); hRes = m_psl->SetArguments(m_sli.m_sArguments.c_str()); hRes = m_psl->SetHotkey(m_sli.m_wHotkey); hRes = m_psl->SetShowCmd(m_sli.m_nShowCmd); //Save the link to file hRes = m_ppf->Save(wszPath, TRUE); if (SUCCEEDED(hRes)) bSuccess = TRUE; return bSuccess; } BOOL CShellLink::Load(const std::wstring& sFilename) { if (!Initialise()) return FALSE; BOOL bSuccess = FALSE; //Convert the path to a UNICODE string WCHAR wszPath[MAX_PATH]; wcscpy_s(wszPath, _countof(wszPath), sFilename.c_str()); //Load the link from file HRESULT hRes = m_ppf->Load(wszPath, STGM_READ); if (SUCCEEDED(hRes)) { //Get the various link values wchar_t szBuf[MAX_PATH]; WIN32_FIND_DATA fd; SecureZeroMemory(&fd, sizeof(fd)); hRes = m_psl->GetPath(szBuf, _countof(szBuf), &fd, SLGP_UNCPRIORITY); if (SUCCEEDED(hRes)) m_sli.m_sTarget = szBuf; hRes = m_psl->GetIDList(&m_sli.m_pidl); hRes = m_psl->GetWorkingDirectory(szBuf, _countof(szBuf)); if (SUCCEEDED(hRes)) m_sli.m_sWorkingDirectory = szBuf; hRes = m_psl->GetIconLocation(szBuf, _countof(szBuf), &m_sli.m_nIconIndex); if (SUCCEEDED(hRes)) m_sli.m_sIconLocation = szBuf; hRes = m_psl->GetDescription(szBuf, _countof(szBuf)); if (SUCCEEDED(hRes)) m_sli.m_sDescription = szBuf; hRes = m_psl->GetArguments(szBuf, _countof(szBuf)); if (SUCCEEDED(hRes)) m_sli.m_sArguments = szBuf; hRes = m_psl->GetHotkey(&m_sli.m_wHotkey); hRes = m_psl->GetShowCmd(&m_sli.m_nShowCmd); bSuccess = TRUE; } return bSuccess; } BOOL CShellLink::Resolve(HWND hParentWnd, DWORD dwFlags) { if (!Initialise()) return FALSE; BOOL bSuccess = FALSE; //Do the actual link resolve HRESULT hRes = m_psl->Resolve(hParentWnd, dwFlags); if (SUCCEEDED(hRes)) bSuccess = TRUE; return bSuccess; } std::wstring CShellLink::GetPath() const { return m_sli.m_sTarget; } std::wstring CShellLink::GetArguments() const { return m_sli.m_sArguments; } std::wstring CShellLink::GetDescription() const { return m_sli.m_sDescription; } WORD CShellLink::GetHotKey() const { return m_sli.m_wHotkey; } std::wstring CShellLink::GetIconLocation() const { return m_sli.m_sIconLocation; } int CShellLink::GetIconLocationIndex() const { return m_sli.m_nIconIndex; } LPITEMIDLIST CShellLink::GetPathIDList() const { return m_sli.m_pidl; } int CShellLink::GetShowCommand() const { return m_sli.m_nShowCmd; } std::wstring CShellLink::GetWorkingDirectory() const { return m_sli.m_sWorkingDirectory; } void CShellLink::SetPath(const std::wstring& sPath) { m_sli.m_sTarget = sPath; } void CShellLink::SetArguments(const std::wstring& sArguments) { m_sli.m_sArguments = sArguments; } void CShellLink::SetDescription(const std::wstring& sDescription) { m_sli.m_sDescription = sDescription; } void CShellLink::SetHotKey(WORD wHotkey) { m_sli.m_wHotkey = wHotkey; } void CShellLink::SetIconLocation(const std::wstring& sIconLocation) { m_sli.m_sIconLocation = sIconLocation; } void CShellLink::SetIconLocationIndex(int nIconIndex) { m_sli.m_nIconIndex = nIconIndex; } void CShellLink::SetPathIDList(LPITEMIDLIST pidl) { m_sli.m_pidl = pidl; } void CShellLink::SetShowCommand(int nShowCmd) { m_sli.m_nShowCmd = nShowCmd; } void CShellLink::SetWorkingDirectory(const std::wstring& sWorkingDirectory) { m_sli.m_sWorkingDirectory = sWorkingDirectory; } CUrlShellLink::CUrlShellLink() : m_pURL(NULL) { } BOOL CUrlShellLink::Create(const CShellLinkInfo& sli) { if (!Initialise()) return FALSE; m_sli = sli; return TRUE; } CUrlShellLink::~CUrlShellLink() { if (m_psl) { m_psl->Release(); m_psl = NULL; } if (m_ppf) { m_ppf->Release(); m_ppf = NULL; } if (m_pURL) { m_pURL->Release(); m_pURL = NULL; } } BOOL CUrlShellLink::Initialise() { BOOL bSuccess = FALSE; if (m_bAttemptedInitialise) bSuccess = (m_pURL != NULL); else { //Instantiate the COM class HRESULT hRes = ::CoCreateInstance(CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER, IID_IUniformResourceLocator, (LPVOID*)&m_pURL); if (SUCCEEDED(hRes)) { //Also get a pointer to IPersistFile hRes = m_pURL->QueryInterface(IID_IPersistFile, (LPVOID*)&m_ppf); if (SUCCEEDED(hRes)) { //Also get a pointer to IShellLink hRes = m_pURL->QueryInterface(IID_IShellLink, (LPVOID*)&m_psl); if (SUCCEEDED(hRes)) bSuccess = TRUE; } } m_bAttemptedInitialise = TRUE; } return bSuccess; } BOOL CUrlShellLink::Save(const std::wstring& sFilename) { if (!Initialise()) return FALSE; BOOL bSuccess = FALSE; //Convert the path to a UNICODE string WCHAR wszPath[MAX_PATH]; wcscpy_s(wszPath, _countof(wszPath), sFilename.c_str()); //Set the various arguments HRESULT hRes = m_pURL->SetURL(m_sli.m_sTarget.c_str(), 0); hRes = m_psl->SetIconLocation(m_sli.m_sIconLocation.c_str(), m_sli.m_nIconIndex); hRes = m_psl->SetDescription(m_sli.m_sDescription.c_str()); hRes = m_psl->SetHotkey(m_sli.m_wHotkey); //Save the link to file hRes = m_ppf->Save(wszPath, TRUE); if (SUCCEEDED(hRes)) bSuccess = TRUE; return bSuccess; } BOOL CUrlShellLink::Load(const std::wstring& sFilename) { if (!Initialise()) return FALSE; BOOL bSuccess = FALSE; //Convert the path to a UNICODE string WCHAR wszPath[MAX_PATH]; wcscpy_s(wszPath, _countof(wszPath), sFilename.c_str()); //Load the link from file HRESULT hRes = m_ppf->Load(wszPath, STGM_READ); if (SUCCEEDED(hRes)) { //Get the various link values LPWSTR lpTemp = NULL; hRes = m_pURL->GetURL(&lpTemp); if (lpTemp == NULL) return FALSE; if (SUCCEEDED(hRes)) { m_sli.m_sTarget = lpTemp; IMalloc* pMalloc; hRes = SHGetMalloc(&pMalloc); if (SUCCEEDED(hRes)) { pMalloc->Free(lpTemp); pMalloc->Release(); } } wchar_t szBuf[MAX_PATH]; hRes = m_psl->GetWorkingDirectory(szBuf, _countof(szBuf)); if (SUCCEEDED(hRes)) m_sli.m_sWorkingDirectory = szBuf; hRes = m_psl->GetIconLocation(szBuf, _countof(szBuf), &m_sli.m_nIconIndex); if (SUCCEEDED(hRes)) m_sli.m_sIconLocation = szBuf; //WINBUG: URL shortcuts always seem to return a description the same as the name of //file in which the shortcut is stored hRes = m_psl->GetDescription(szBuf, _countof(szBuf)); if (SUCCEEDED(hRes)) m_sli.m_sDescription = szBuf; hRes = m_psl->GetHotkey(&m_sli.m_wHotkey); hRes = m_psl->GetShowCmd(&m_sli.m_nShowCmd); bSuccess = TRUE; } return bSuccess; } BOOL CUrlShellLink::Invoke(HWND hParentWnd, DWORD dwFlags, const std::wstring& sVerb) { BOOL bSuccess = FALSE; URLINVOKECOMMANDINFO urlicmi; urlicmi.dwcbSize = sizeof(URLINVOKECOMMANDINFO); urlicmi.dwFlags = dwFlags; urlicmi.hwndParent = NULL; if (hParentWnd) urlicmi.hwndParent = hParentWnd; urlicmi.pcszVerb = sVerb.c_str(); //Invoke the verb on the URL HRESULT hRes = m_pURL->InvokeCommand(&urlicmi); if (SUCCEEDED(hRes)) bSuccess = TRUE; return bSuccess; } void CUrlShellLink::SetArguments(const std::wstring& /*sArguments*/) { //Arguments are not supported for Internet shortcuts } std::wstring CUrlShellLink::GetArguments() const { //Arguments are not supported for Internet shortcuts return std::wstring(); } LPITEMIDLIST CUrlShellLink::GetPathIDList() const { //pidls are not supported for Internet shortcuts return NULL; } void CUrlShellLink::SetPathIDList(LPITEMIDLIST /*pidl*/) { //pidls are not supported for Internet shortcuts } <|start_filename|>language/np3_it_it/stdafx.cpp<|end_filename|> // encoding: UTF-8 // stdafx.cpp : Quelldatei, die nur die Standard-Includes einbindet. // np3_it_it.pch ist der vorkompilierte Header. // stdafx.obj enthält die vorkompilierten Typinformationen. #include "stdafx.h" // TODO: Auf zusätzliche Header verweisen, die in STDAFX.H // und nicht in dieser Datei erforderlich sind. <|start_filename|>src/StyleLexers/styleLexVBS.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_VBS = { "alias and as attribute begin boolean byref byte byval call case class compare const continue currency date " "declare dim do double each else elseif empty end enum eqv erase error event exit explicit false for " "friend function get global gosub goto if imp implement in integer is let lib load long loop lset me mid " "mod module new next not nothing null object on option optional or preserve private property public " "raiseevent redim rem resume return rset select set single static stop string sub then to true type unload " "until variant wend while with withevents xor", NULL, }; EDITLEXER lexVBS = { SCLEX_VBSCRIPT, "vbscript", IDS_LEX_VB_SCR, L"VBScript", L"vbs; dsm", L"", &KeyWords_VBS, { { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_B_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {SCE_B_COMMENT}, IDS_LEX_STR_63127, L"Comment", L"fore:#808080", L"" }, { {SCE_B_KEYWORD}, IDS_LEX_STR_63128, L"Keyword", L"bold; fore:#B000B0", L"" }, { {SCE_B_IDENTIFIER}, IDS_LEX_STR_63129, L"Identifier", L"", L"" }, { {MULTI_STYLE(SCE_B_STRING,SCE_B_STRINGEOL,0,0)}, IDS_LEX_STR_63131, L"String", L"fore:#008000", L"" }, { {SCE_B_NUMBER}, IDS_LEX_STR_63130, L"Number", L"fore:#FF0000", L"" }, { {SCE_B_OPERATOR}, IDS_LEX_STR_63132, L"Operator", L"", L"" }, //{ {SCE_B_PREPROCESSOR}, IDS_LEX_STR_63133, L"Preprocessor", L"fore:#FF9C00", L"" }, //{ {SCE_B_CONSTANT}, L"Constant", L"", L"" }, //{ {SCE_B_DATE}, L"Date", L"", L"" }, //{ {SCE_B_KEYWORD2}, L"Keyword 2", L"", L"" }, //{ {SCE_B_KEYWORD3}, L"Keyword 3", L"", L"" }, //{ {SCE_B_KEYWORD4}, L"Keyword 4", L"", L"" }, //{ {SCE_B_ASM}, L"Inline Asm", L"fore:#FF8000", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>src/uchardet/uchardet/src/LangModels/LangRomanianModel.cpp<|end_filename|> /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "../nsSBCharSetProber.h" /********* Language model for: Romanian *********/ /** * Generated by BuildLangModel.py * On: 2016-09-28 18:58:13.757152 **/ /* Character Mapping Table: * ILL: illegal character. * CTR: control character specific to the charset. * RET: carriage/return. * SYM: symbol (punctuation) that does not belong to word. * NUM: 0 - 9. * * Other characters are ordered by probabilities * (0 is the most common character in the language). * * Orders are generic to a language. So the codepoint with order X in * CHARSET1 maps to the same character as the codepoint with the same * order X in CHARSET2 for the same language. * As such, it is possible to get missing order. For instance the * ligature of 'o' and 'e' exists in ISO-8859-15 but not in ISO-8859-1 * even though they are both used for French. Same for the euro sign. */ static const unsigned char Iso_8859_16_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 2, 17, 9, 11, 0, 16, 15, 23, 1, 26, 27, 6, 12, 4, 8, /* 4X */ 13, 32, 3, 10, 5, 7, 21, 29, 25, 28, 22,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 2, 17, 9, 11, 0, 16, 15, 23, 1, 26, 27, 6, 12, 4, 8, /* 6X */ 13, 32, 3, 10, 5, 7, 21, 29, 25, 28, 22,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM, 60, 61, 46,SYM,SYM, 38,SYM, 38,SYM, 19,SYM, 62,SYM, 63, 64, /* AX */ SYM,SYM, 41, 46, 40,SYM,SYM,SYM, 40, 41, 19,SYM, 65, 66, 67, 68, /* BX */ 69, 30, 24, 14, 33, 35, 53, 42, 45, 31, 58, 49, 70, 37, 20, 48, /* CX */ 43, 52, 59, 34, 71, 44, 36, 56, 50, 72, 47, 73, 39, 74, 18, 57, /* DX */ 75, 30, 24, 14, 33, 35, 53, 42, 45, 31, 58, 49, 76, 37, 20, 48, /* EX */ 43, 52, 59, 34, 77, 44, 36, 56, 50, 78, 47, 79, 39, 80, 18, 81, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Iso_8859_2_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 2, 17, 9, 11, 0, 16, 15, 23, 1, 26, 27, 6, 12, 4, 8, /* 4X */ 13, 32, 3, 10, 5, 7, 21, 29, 25, 28, 22,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 2, 17, 9, 11, 0, 16, 15, 23, 1, 26, 27, 6, 12, 4, 8, /* 6X */ 13, 32, 3, 10, 5, 7, 21, 29, 25, 28, 22,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM, 82,SYM, 46,SYM, 83, 56,SYM,SYM, 38, 84, 85, 86,SYM, 40, 87, /* AX */ SYM, 88,SYM, 46,SYM, 89, 56,SYM,SYM, 38, 90, 91, 92,SYM, 40, 93, /* BX */ 94, 30, 24, 14, 33, 95, 35, 42, 41, 31, 96, 49, 51, 37, 20, 97, /* CX */ 43, 52, 98, 34, 99, 44, 36,SYM, 55,100, 47, 50, 39, 54,101, 57, /* DX */ 102, 30, 24, 14, 33,103, 35, 42, 41, 31,104, 49, 51, 37, 20,105, /* EX */ 43, 52,106, 34,107, 44, 36,SYM, 55,108, 47, 50, 39, 54,109,SYM, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Windows_1250_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 2, 17, 9, 11, 0, 16, 15, 23, 1, 26, 27, 6, 12, 4, 8, /* 4X */ 13, 32, 3, 10, 5, 7, 21, 29, 25, 28, 22,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 2, 17, 9, 11, 0, 16, 15, 23, 1, 26, 27, 6, 12, 4, 8, /* 6X */ 13, 32, 3, 10, 5, 7, 21, 29, 25, 28, 22,SYM,SYM,SYM,SYM,CTR, /* 7X */ SYM,ILL,SYM,ILL,SYM,SYM,SYM,SYM,ILL,SYM, 38,SYM, 56,110, 40,111, /* 8X */ ILL,SYM,SYM,SYM,SYM,SYM,SYM,SYM,ILL,SYM, 38,SYM, 56,112, 40,113, /* 9X */ SYM,SYM,SYM, 46,SYM,114,SYM,SYM,SYM,SYM,115,SYM,SYM,SYM,SYM,116, /* AX */ SYM,SYM,SYM, 46,SYM,SYM,SYM,SYM,SYM,117,118,SYM,119,SYM,120,121, /* BX */ 122, 30, 24, 14, 33,123, 35, 42, 41, 31,124, 49, 51, 37, 20,125, /* CX */ 43, 52,126, 34,127, 44, 36,SYM, 55,128, 47, 50, 39, 54,129, 57, /* DX */ 130, 30, 24, 14, 33,131, 35, 42, 41, 31,132, 49, 51, 37, 20,133, /* EX */ 43, 52,134, 34,135, 44, 36,SYM, 55,136, 47, 50, 39, 54,137,SYM, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Ibm852_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 2, 17, 9, 11, 0, 16, 15, 23, 1, 26, 27, 6, 12, 4, 8, /* 4X */ 13, 32, 3, 10, 5, 7, 21, 29, 25, 28, 22,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 2, 17, 9, 11, 0, 16, 15, 23, 1, 26, 27, 6, 12, 4, 8, /* 6X */ 13, 32, 3, 10, 5, 7, 21, 29, 25, 28, 22,SYM,SYM,SYM,SYM,CTR, /* 7X */ 42, 39, 31, 24, 33,138, 35, 42, 46, 49, 44, 44, 20,139, 33, 35, /* 8X */ 31,140,141,142, 36,143,144, 56, 56, 36, 39,145,146, 46,SYM, 41, /* 9X */ 30, 37, 34, 47,147,148, 40, 40,149,150,SYM,151, 41,152,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM,SYM, 30, 24, 51,153,SYM,SYM,SYM,SYM,154,155,SYM, /* BX */ SYM,SYM,SYM,SYM,SYM,SYM, 14, 14,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* CX */ 43, 43,156, 49,157,158, 37, 20, 51,SYM,SYM,SYM,SYM,159,160,SYM, /* DX */ 34, 57,161, 52, 52,162, 38, 38,163, 47,164, 50, 54, 54,165,SYM, /* EX */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, 50, 55, 55,SYM,SYM, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ /* Model Table: * Total sequences: 981 * First 512 sequences: 0.997762564143313 * Next 512 sequences (512-1024): 0.002237435856687006 * Rest: 3.0357660829594124e-18 * Negative sequences: TODO */ static const PRUint8 RomanianLangModel[] = { 3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,0,3,3,3,3,3,2,0,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,3,3,3,0,3,3,3,2,3,3,3,2,2,0,0,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,3,3,3,0,3,3,3,0,3,3,3,3,3,0,2,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,2,2,3,3,2,2,2,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,0,3,3,3,3,2,3,3,3,3,2,2,2, 3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,2,3,3,0,2,2,3,3,3,3,0,2,2,3,3,2,3,0, 3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,3,2,2,3,0,3,3,3,2,2,2,0, 3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,3,3,3,3,3,2,2,0,2,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,3,3,3,0,3,3,3,0,3,2,3,3,3,2,0,2, 3,3,3,3,3,3,3,3,3,3,3,3,2,2,3,3,2,2,3,2,0,3,2,3,3,0,3,3,2,2,0,2,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,0,2,2,3,3,3,0,2,3,3,3,2,2,2, 3,3,3,3,3,2,3,3,3,2,3,3,3,2,3,3,2,3,0,0,0,3,2,3,3,0,2,2,3,3,3,2,0, 3,3,3,2,3,3,3,3,3,3,3,2,3,3,3,2,2,3,3,2,2,2,2,3,3,2,0,0,3,2,2,2,0, 3,3,3,3,3,3,3,3,3,3,3,2,2,3,3,0,0,2,3,0,2,0,2,3,3,0,2,2,3,0,2,2,0, 2,3,0,3,3,3,3,3,0,3,3,3,3,3,0,3,0,3,3,3,0,3,3,0,0,0,2,2,0,0,0,0,0, 3,3,3,3,3,2,3,3,3,0,2,3,3,2,3,3,2,3,0,0,2,3,2,3,3,0,2,0,3,2,2,2,0, 3,3,3,3,0,3,3,3,3,2,2,2,3,2,3,2,3,0,0,0,0,0,0,2,3,0,0,0,2,0,2,2,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,2,2,3,3,2,0,2,2,2,3,0,2,2,3,2,2,2,0, 3,3,3,0,0,0,0,3,2,2,2,0,0,0,3,0,0,0,0,0,2,2,0,0,2,0,0,2,0,0,0,0,0, 3,3,3,0,3,3,3,3,3,3,0,2,2,0,3,0,0,0,0,0,0,2,0,0,2,0,0,2,0,0,0,0,0, 0,3,0,2,3,0,3,0,0,0,0,0,3,0,0,0,0,0,2,3,0,0,2,2,0,0,0,2,0,0,0,0,0, 3,3,3,3,3,2,3,3,3,2,2,3,2,0,3,2,2,2,0,0,0,0,0,0,3,0,2,2,2,0,2,0,0, 3,3,3,2,2,2,2,3,3,0,2,3,2,2,3,2,0,3,0,0,0,3,3,2,3,0,0,2,2,0,2,2,0, 3,3,3,3,3,3,3,3,3,2,3,2,2,2,3,0,2,3,0,0,0,2,2,0,2,0,2,2,3,2,2,2,0, 0,3,0,3,3,3,3,3,0,2,2,2,3,0,0,0,0,0,2,3,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,2,0,3,0,3,3,3,2,0,0,3,3,0,3,0,0,0,0,3,0,2,2,3,0,0,3,0,0,0,0, 3,3,3,2,2,2,3,3,3,0,2,2,2,0,2,0,0,2,0,0,0,2,0,0,2,0,0,2,0,0,2,0,0, 3,3,3,3,2,3,3,3,3,2,3,2,3,2,2,2,2,2,2,2,2,2,0,3,0,0,0,2,3,2,2,2,0, 3,2,3,3,3,2,3,2,3,3,3,3,3,2,0,2,0,2,0,0,0,2,2,2,0,0,2,2,0,2,2,0,0, 3,3,3,2,3,2,2,2,3,2,3,2,2,2,0,0,2,2,0,0,0,0,0,3,0,0,0,0,2,3,0,0,0, 2,3,0,3,3,2,2,0,0,2,2,2,2,0,0,2,0,0,0,0,0,0,2,0,0,0,0,2,0,0,0,0,0, 0,3,2,2,2,2,2,0,0,2,2,2,2,2,0,2,0,2,0,0,0,2,2,0,0,0,2,2,0,0,0,0,0, 0,0,2,0,0,2,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2, }; const SequenceModel Iso_8859_16RomanianModel = { Iso_8859_16_CharToOrderMap, RomanianLangModel, 33, (float)0.997762564143313, PR_TRUE, "ISO-8859-16" }; const SequenceModel Iso_8859_2RomanianModel = { Iso_8859_2_CharToOrderMap, RomanianLangModel, 33, (float)0.997762564143313, PR_TRUE, "ISO-8859-2" }; const SequenceModel Windows_1250RomanianModel = { Windows_1250_CharToOrderMap, RomanianLangModel, 33, (float)0.997762564143313, PR_TRUE, "WINDOWS-1250" }; const SequenceModel Ibm852RomanianModel = { Ibm852_CharToOrderMap, RomanianLangModel, 33, (float)0.997762564143313, PR_TRUE, "IBM852" }; <|start_filename|>grepWinNP3/src/RegexReplaceFormatter.h<|end_filename|> // grepWin - regex search and replace for Windows // Copyright (C) 2011-2012, 2014-2015, 2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #pragma once #include <string> #include <stdio.h> #include <algorithm> #include <map> #pragma warning(push) #pragma warning(disable : 4996) // warning STL4010: Various members of std::allocator are deprecated in C++17 #include <boost/regex.hpp> #include <boost/spirit/include/classic_file_iterator.hpp> #include <boost/iostreams/device/mapped_file.hpp> #pragma warning(pop) class NumberReplacer { public: NumberReplacer() : leadZero(false) , padding(0) , start(1) , increment(1) { } bool leadZero; int padding; int start; int increment; std::wstring expression; }; class NumberReplacerA { public: NumberReplacerA() : leadZero(false) , padding(0) , start(1) , increment(1) { } bool leadZero; int padding; int start; int increment; std::string expression; }; extern std::vector<NumberReplacer> g_incVec; extern std::vector<NumberReplacerA> g_incVecA; class RegexReplaceFormatter { public: RegexReplaceFormatter(const std::wstring& sReplace) : m_sReplace(sReplace) { g_incVec.clear(); // parse for ${count0L}, ${count0L(n)}, ${count0L(n,m)}, where // ${count} // is replaced later with numbers starting from 1, incremented by 1 // ${count(n)} // is replaced with numbers starting from n, incremented by 1 // ${count(n,m)} // is replaced with numbers starting from n, incremented by m // 0 and L are optional and specify the size of the right-aligned // number string. If 0 is specified, zeros are used for padding, otherwise spaces. //boost::wregex expression = boost::wregex(L"(?<!\\\\)\\$\\{count(?<leadzero>0)?(?<length>\\d+)?(\\((?<startval>[-0-9]+)\\)||\\((?<startval>[-0-9]+),(?<increment>[-0-9]+)\\))?\\}", boost::regex::normal); boost::wregex expression = boost::wregex(L"\\$\\{count(?<leadzero>0)?(?<length>\\d+)?(\\((?<startval>[-0-9]+)\\)||\\((?<startval>[-0-9]+),(?<increment>[-0-9]+)\\))?\\}", boost::regex::normal); boost::match_results<std::wstring::const_iterator> whatc; std::wstring::const_iterator start = m_sReplace.begin(); std::wstring::const_iterator end = m_sReplace.end(); boost::match_flag_type flags = boost::match_default | boost::format_all; while (boost::regex_search(start, end, whatc, expression, flags)) { if (whatc[0].matched) { NumberReplacer nr; nr.leadZero = (static_cast<std::wstring>(whatc[L"leadzero"]) == L"0"); nr.padding = _wtoi(static_cast<std::wstring>(whatc[L"length"]).c_str()); std::wstring s = static_cast<std::wstring>(whatc[L"startval"]); if (!s.empty()) nr.start = _wtoi(s.c_str()); s = static_cast<std::wstring>(whatc[L"increment"]); if (!s.empty()) nr.increment = _wtoi(s.c_str()); if (nr.increment == 0) nr.increment = 1; nr.expression = static_cast<std::wstring>(whatc[0]); g_incVec.push_back(nr); } // update search position: if (start == whatc[0].second) { if (start == end) break; ++start; } else start = whatc[0].second; // update flags: flags |= boost::match_prev_avail; flags |= boost::match_not_bob; } } void SetReplacePair(const std::wstring& s1, const std::wstring& s2) { m_replaceMap[s1] = s2; } std::wstring operator()(boost::match_results<std::wstring::const_iterator> what) const { std::wstring sReplace = what.format(m_sReplace); if (!m_replaceMap.empty()) { for (auto it = m_replaceMap.cbegin(); it != m_replaceMap.cend(); ++it) { auto itBegin = std::search(sReplace.begin(), sReplace.end(), it->first.begin(), it->first.end()); while (itBegin != sReplace.end()) { if ((itBegin == sReplace.begin()) || ((*(itBegin - 1)) != '\\')) { auto itEnd = itBegin + it->first.size(); sReplace.replace(itBegin, itEnd, it->second); } else if ((*(itBegin - 1)) == '\\') { sReplace.erase(itBegin - 1); }; itBegin = std::search(sReplace.begin(), sReplace.end(), it->first.begin(), it->first.end()); } } } if (!g_incVec.empty()) { for (auto it = g_incVec.begin(); it != g_incVec.end(); ++it) { auto itBegin = std::search(sReplace.begin(), sReplace.end(), it->expression.begin(), it->expression.end()); if (itBegin != sReplace.end()) { if ((itBegin == sReplace.begin()) || ((*(itBegin - 1)) != '\\')) { auto itEnd = itBegin + it->expression.size(); wchar_t format[10] = {0}; if (it->padding) { if (it->leadZero) swprintf_s(format, _countof(format), L"%%0%dd", it->padding); else swprintf_s(format, _countof(format), L"%%%dd", it->padding); } else wcscpy_s(format, L"%d"); wchar_t buf[50] = {0}; swprintf_s(buf, _countof(buf), format, it->start); sReplace.replace(itBegin, itEnd, buf); it->start += it->increment; } else if ((*(itBegin - 1)) == '\\') { sReplace.erase(itBegin - 1); }; } } } //sReplace = boost::regex_replace(what[0].str(), sReplace, boost::match_default); return sReplace; } private: std::wstring m_sReplace; std::map<std::wstring, std::wstring> m_replaceMap; }; class RegexReplaceFormatterA { public: RegexReplaceFormatterA(const std::string& sReplace) : m_sReplace(sReplace) { g_incVec.clear(); // parse for ${count0L}, ${count0L(n)}, ${count0L(n,m)}, where // ${count} // is replaced later with numbers starting from 1, incremented by 1 // ${count(n)} // is replaced with numbers starting from n, incremented by 1 // ${count(n,m)} // is replaced with numbers starting from n, incremented by m // 0 and L are optional and specify the size of the right-aligned // number string. If 0 is specified, zeros are used for padding, otherwise spaces. //boost::wregex expression = boost::wregex(L"(?<!\\\\)\\$\\{count(?<leadzero>0)?(?<length>\\d+)?(\\((?<startval>[-0-9]+)\\)||\\((?<startval>[-0-9]+),(?<increment>[-0-9]+)\\))?\\}", boost::regex::normal); boost::regex expression = boost::regex("\\$\\{count(?<leadzero>0)?(?<length>\\d+)?(\\((?<startval>[-0-9]+)\\)||\\((?<startval>[-0-9]+),(?<increment>[-0-9]+)\\))?\\}", boost::regex::normal); boost::match_results<std::string::const_iterator> whatc; std::string::const_iterator start = m_sReplace.begin(); std::string::const_iterator end = m_sReplace.end(); boost::match_flag_type flags = boost::match_default | boost::format_all; while (boost::regex_search(start, end, whatc, expression, flags)) { if (whatc[0].matched) { NumberReplacerA nr; nr.leadZero = (static_cast<std::string>(whatc["leadzero"]) == "0"); nr.padding = atoi(static_cast<std::string>(whatc["length"]).c_str()); std::string s = static_cast<std::string>(whatc["startval"]); if (!s.empty()) nr.start = atoi(s.c_str()); s = static_cast<std::string>(whatc["increment"]); if (!s.empty()) nr.increment = atoi(s.c_str()); if (nr.increment == 0) nr.increment = 1; nr.expression = static_cast<std::string>(whatc[0]); g_incVecA.push_back(nr); } // update search position: if (start == whatc[0].second) { if (start == end) break; ++start; } else start = whatc[0].second; // update flags: flags |= boost::match_prev_avail; flags |= boost::match_not_bob; } } void SetReplacePair(const std::string& s1, const std::string& s2) { m_replaceMap[s1] = s2; } template <typename It> std::string operator()(boost::match_results<It> what) const { std::string sReplace = what.format(m_sReplace); if (!m_replaceMap.empty()) { for (auto it = m_replaceMap.cbegin(); it != m_replaceMap.cend(); ++it) { auto itBegin = std::search(sReplace.begin(), sReplace.end(), it->first.begin(), it->first.end()); while (itBegin != sReplace.end()) { if ((itBegin == sReplace.begin()) || ((*(itBegin - 1)) != '\\')) { auto itEnd = itBegin + it->first.size(); sReplace.replace(itBegin, itEnd, it->second); } else if ((*(itBegin - 1)) == '\\') { sReplace.erase(itBegin - 1); }; itBegin = std::search(sReplace.begin(), sReplace.end(), it->first.begin(), it->first.end()); } } } if (!g_incVec.empty()) { for (auto it = g_incVec.begin(); it != g_incVec.end(); ++it) { auto itBegin = std::search(sReplace.begin(), sReplace.end(), it->expression.begin(), it->expression.end()); if (itBegin != sReplace.end()) { if ((itBegin == sReplace.begin()) || ((*(itBegin - 1)) != '\\')) { auto itEnd = itBegin + it->expression.size(); char format[10] = {0}; if (it->padding) { if (it->leadZero) sprintf_s(format, _countof(format), "%%0%dd", it->padding); else sprintf_s(format, _countof(format), "%%%dd", it->padding); } else strcpy_s(format, "%d"); char buf[50] = {0}; sprintf_s(buf, _countof(buf), format, it->start); sReplace.replace(itBegin, itEnd, buf); it->start += it->increment; } else if ((*(itBegin - 1)) == '\\') { sReplace.erase(itBegin - 1); }; } } } return sReplace; } private: std::string m_sReplace; std::map<std::string, std::string> m_replaceMap; }; <|start_filename|>grepWinNP3/sktoolslib_mod/RegHistory.h<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012-2013, 2020-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #pragma once #include "SimpleIni.h" #include <string> #include <vector> /** * Maintains a list of X string items in the registry and provides methods * to add new items. The list can be used as a 'recently used' or 'recent items' list. */ class CRegHistory { public: CRegHistory(CSimpleIni* pIni = nullptr); virtual ~CRegHistory(); /// Loads the history /// \param lpszSection the section in the registry, e.g., "Software\\CompanyName\\History" /// \param lpszKeyPrefix the name of the registry values, e.g., "historyItem" /// \return the number of history items loaded int Load(LPCWSTR lpszSection, LPCWSTR lpszKeyPrefix); /// Saves the history. bool Save() const; /// Adds a new string to the history list. // ReSharper disable once CppHiddenFunction bool AddEntry(LPCWSTR szText); /// Removes the entry at index \c pos. void RemoveEntry(int pos); /// Removes the entry with text \c str void RemoveEntry(LPCWSTR str); /// Sets the maximum number of items in the history. Default is 25. void SetMaxHistoryItems(int nMax) { m_nMaxHistoryItems = nMax; } /// Returns the number of items in the history. size_t GetCount() const { return m_arEntries.size(); } /// Returns the entry at index \c pos LPCWSTR GetEntry(int pos) { return m_arEntries[pos].c_str(); } protected: std::wstring m_sSection; std::wstring m_sKeyPrefix; std::vector<std::wstring> m_arEntries; int m_nMaxHistoryItems; CSimpleIni* m_pIniFile; }; <|start_filename|>test/test_files/StyleLexers/styleLexJulia/x.jl<|end_filename|> # Comment here const bar = '\n' """ test_fun(a::Int) For test only """ function test_fun(a::Int, b::T) where T <: Number println(a) println("foo $(bar)") end @enum Unicode α=1 β=2 res = [√i for i in 1:10] #= Dummy function =# test_fun²(:sym, true, raw"test", `echo 1`) # function to calculate the volume of a sphere function sphere_vol(r) # julia allows Unicode names (in UTF-8 encoding) # so either "pi" or the symbol π can be used return 4/3*pi*r^3 end # functions can also be defined more succinctly quadratic(a, sqr_term, b) = (-b + sqr_term) / 2a # calculates x for 0 = a*x^2+b*x+c, arguments types can be defined in function definitions function quadratic2(a::Float64, b::Float64, c::Float64) # unlike other languages 2a is equivalent to 2*a # a^2 is used instead of a**2 or pow(a,2) sqr_term = sqrt(b^2-4a*c) r1 = quadratic(a, sqr_term, b) r2 = quadratic(a, -sqr_term, b) # multiple values can be returned from a function using tuples # if the return keyword is omitted, the last term is returned r1, r2 end vol = sphere_vol(3) # @printf allows number formatting but does not automatically append the \n to statements, see below using Printf @printf "volume = %0.3f\n" vol #> volume = 113.097 quad1, quad2 = quadratic2(2.0, -2.0, -12.0) println("result 1: ", quad1) #> result 1: 3.0 println("result 2: ", quad2) #> result 2: -2.0 s1 = "The quick brown fox jumps over the lazy dog α,β,γ" # search returns the first index of a char i = findfirst(isequal('b'), s1) println(i) #> 11 # the second argument is equivalent to the second argument of split, see below # or a range if called with another string r = findfirst("brown", s1) println(r) #> 11:15 # string replace is done thus: r = replace(s1, "brown" => "red") show(r); println() #> "The quick red fox jumps over the lazy dog α,β,γ" # search and replace can also take a regular expressions by preceding the string with 'r' r = findfirst(r"b[\w]*n", s1) println(r) #> 11:15 # again with a regular expression r = replace(s1, r"b[\w]*n" => "red") show(r); println() #> "The quick red fox jumps over the lazy dog α,β,γ" # there are also functions for regular expressions that return RegexMatch types # match scans left to right for the first match (specified starting index optional) r = match(r"b[\w]*n", s1) println(r) #> RegexMatch("brown") # RegexMatch types have a property match that holds the matched string show(r.match); println() #> "brown" # eachmatch returns an iterator over all the matches r = eachmatch(r"[\w]{4,}", s1) for i in r print("\"$(i.match)\" ") end #> "quick" "brown" "jumps" "over" "lazy" println() r = collect(m.match for m = eachmatch(r"[\w]{4,}", s1)) println(r) #> SubString{String}["quick", "brown", "jumps", "over", "lazy"] # a string can be repeated using the repeat function, # or more succinctly with the ^ syntax: r = "hello "^3 show(r); println() #> "hello hello hello " # the strip function works the same as python: # e.g., with one argument it strips the outer whitespace r = strip("hello ") show(r); println() #> "hello" # or with a second argument of an array of chars it strips any of them; r = strip("hello ", ['h', ' ']) show(r); println() #> "ello" # (note the array is of chars and not strings) # similarly split works in basically the same way as python: r = split("hello, there,bob", ',') show(r); println() #> SubString{String}["hello", " there", "bob"] r = split("hello, there,bob", ", ") show(r); println() #> SubString{String}["hello", "there,bob"] r = split("hello, there,bob", [',', ' '], limit=0, keepempty=false) show(r); println() #> SubString{String}["hello", "there", "bob"] # (the last two arguements are limit and include_empty, see docs) # the opposite of split: join is simply r = join(collect(1:10), ", ") println(r) #> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 function printsum(a) # summary generates a summary of an object println(summary(a), ": ", repr(a)) end # arrays can be initialised directly: a1 = [1,2,3] printsum(a1) #> 3-element Array{Int64,1}: [1, 2, 3] # or initialised empty: a2 = [] printsum(a2) #> 0-element Array{Any,1}: Any[] # since this array has no type, functions like push! (see below) don't work # instead arrays can be initialised with a type: a3 = Int64[] printsum(a3) #> 0-element Array{Int64,1}: Int64[] # ranges are different from arrays: a4 = 1:20 printsum(a4) #> 20-element UnitRange{Int64}: 1:20 # however they can be used to create arrays thus: a4 = collect(1:20) printsum(a4) #> 20-element Array{Int64,1}: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, #> 15, 16, 17, 18, 19, 20] # arrays can also be generated from comprehensions: a5 = [2^i for i = 1:10] printsum(a5) #> 10-element Array{Int64,1}: [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] # arrays can be any type, so arrays of arrays can be created: a6 = (Array{Int64, 1})[] printsum(a6) #> 0-element Array{Array{Int64,1},1}: Array{Int64,1}[] # (note this is a "jagged array" (i.e., an array of arrays), not a multidimensional array, # these are not covered here) # Julia provided a number of "Dequeue" functions, the most common # for appending to the end of arrays is push! # ! at the end of a function name indicates that the first argument is updated. push!(a1, 4) printsum(a1) #> 4-element Array{Int64,1}: [1, 2, 3, 4] # push!(a2, 1) would cause error: push!(a3, 1) printsum(a3) #> 1-element Array{Int64,1}: [1] #> 1-element Array{Int64,1}: [1] push!(a6, [1,2,3]) printsum(a6) #> 1-element Array{Array{Int64,1},1}: Array{Int64,1}[[1, 2, 3]] # using repeat() to create arrays # you must use the keywords "inner" and "outer" # all arguments must be arrays (not ranges) a7 = repeat(a1,inner=[2],outer=[1]) printsum(a7) #> 8-element Array{Int64,1}: [1, 1, 2, 2, 3, 3, 4, 4] a8 = repeat(collect(4:-1:1),inner=[1],outer=[2]) printsum(a8) #> 8-element Array{Int64,1}: [4, 3, 2, 1, 4, 3, 2, 1] # try, catch can be used to deal with errors as with many other languages try push!(a,1) catch err showerror(stdout, err, backtrace());println() end #> UndefVarError: a not defined #> Stacktrace: #> [1] top-level scope at C:\JuliaByExample\src\error_handling.jl:5 #> [2] include at .\boot.jl:317 [inlined] #> [3] include_relative(::Module, ::String) at .\loading.jl:1038 #> [4] include(::Module, ::String) at .\sysimg.jl:29 #> [5] exec_options(::Base.JLOptions) at .\client.jl:229 #> [6] _start() at .\client.jl:421 println("Continuing after error") #> Continuing after error # repeat can be useful to expand a grid # as in R's expand.grid() function: m1 = hcat(repeat([1,2],inner=[1],outer=[3*2]), repeat([1,2,3],inner=[2],outer=[2]), repeat([1,2,3,4],inner=[3],outer=[1])) printsum(m1) #> 12×3 Array{Int64,2}: [1 1 1; 2 1 1; 1 2 1; 2 2 2; 1 3 2; 2 3 2; 1 1 3; 2 1 3; #> 1 2 3; 2 2 4; 1 3 4; 2 3 4] # for simple repetitions of arrays, # use repeat m2 = repeat(m1,1,2) # replicate a9 once into dim1 and twice into dim2 println("size: ", size(m2)) #> size: (12, 6) m3 = repeat(m1,2,1) # replicate a9 twice into dim1 and once into dim2 println("size: ", size(m3)) #> size: (24, 3) # Julia comprehensions are another way to easily create # multidimensional arrays m4 = [i+j+k for i=1:2, j=1:3, k=1:2] # creates a 2x3x2 array of Int64 m5 = ["Hi Im # $(i+2*(j-1 + 3*(k-1)))" for i=1:2, j=1:3, k=1:2] # expressions are very flexible # you can specify the type of the array by just # placing it in front of the expression import LegacyStrings m5 = LegacyStrings.ASCIIString["Hi Im element # $(i+2*(j-1 + 3*(k-1)))" for i=1:2, j=1:3, k=1:2] printsum(m5) #> 2×3×2 Array{LegacyStrings.ASCIIString,3}: LegacyStrings.ASCIIString[ #> "Hi Im element # 1" "Hi Im element # 3" "Hi Im element # 5"; #> "Hi Im element # 2" "Hi Im element # 4" "Hi Im element # 6"] #> #> LegacyStrings.ASCIIString["Hi Im element # 7" "Hi Im element # 9" #> "Hi Im element # 11"; "Hi Im element # 8" "Hi Im element # 10" "Hi Im element # 12"] # Array reductions # many functions in Julia have an array method # to be applied to specific dimensions of an array: sum(m4, dims=3) # takes the sum over the third dimension sum(m4, dims=(1,3)) # sum over first and third dim maximum(m4, dims=2) # find the max elt along dim 2 findmax(m4, dims=3) # find the max elt and its index along dim 3 # (available only in very recent Julia versions) # Broadcasting # when you combine arrays of different sizes in an operation, # an attempt is made to "spread" or "broadcast" the smaller array # so that the sizes match up. broadcast operators are preceded by a dot: m4 .+ 3 # add 3 to all elements m4 .+ [1,2] # adds vector [1,2] to all elements along first dim # slices and views m4=m4[:,:,1] # holds dim 3 fixed m4[:,2,:] # that's a 2x1x2 array. not very intuititive to look at # get rid of dimensions with size 1: dropdims(m4[:,2,:], dims=2) # that's better # assign new values to a certain view m4[:,:,1] = rand(1:6,2,3) printsum(m4) #> 2×3 Array{Int64,2}: [3 5 3; 1 3 5] # (for more examples of try, catch see Error Handling above) try # this will cause an error, you have to assign the correct type m4[:,:,1] = rand(2,3) catch err println(err) end #> InexactError(:Int64, Int64, 0.7603891754678744) try # this will cause an error, you have to assign the right shape m4[:,:,1] = rand(1:6,3,2) catch err println(err) end #> DimensionMismatch("tried to assign 3×2 array to 2×3×1 destination") # dicts can be initialised directly: a1 = Dict(1=>"one", 2=>"two") printsum(a1) #> Dict{Int64,String} with 2 entries: Dict(2=>"two",1=>"one") # then added to: a1[3]="three" printsum(a1) #> Dict{Int64,String} with 3 entries: Dict(2=>"two",3=>"three",1=>"one") # (note dicts cannot be assumed to keep their original order) # dicts may also be created with the type explicitly set a2 = Dict{Int64, AbstractString}() a2[0]="zero" printsum(a2) #> Dict{Int64,AbstractString} with 1 entry: Dict{Int64,AbstractString}(0=>"zero") # dicts, like arrays, may also be created from comprehensions using Printf a3 = Dict([i => @sprintf("%d", i) for i = 1:10]) printsum(a3) #> Dict{Int64,String} with 10 entries: Dict(7=>"7",4=>"4",9=>"9",10=>"10", #> 2=>"2",3=>"3",5=>"5",8=>"8",6=>"6",1=>"1") # as you would expect, Julia comes with all the normal helper functions # for dicts, e.g., haskey println(haskey(a1,1)) #> true # which is equivalent to println(1 in keys(a1)) #> true # where keys creates an iterator over the keys of the dictionary # similar to keys, values get iterators over the dict's values: printsum(values(a1)) #> Base.ValueIterator for a Dict{Int64,String} with 3 entries: ["two", "three", "one"] # use collect to get an array: printsum(collect(values(a1))) #> 3-element Array{String,1}: ["two", "three", "one"] if true println("It's true!") else println("It's false!") end #> It's true! if false println("It's true!") else println("It's false!") end #> It's false! # Numbers can be compared with opperators like <, >, ==, != 1 == 1. #> true 1 > 2 #> false "foo" != "bar" #> true # and many functions return boolean values occursin("that", "this and that") #> true # More complex logical statments can be achieved with `elseif` function checktype(x) if x isa Int println("Look! An Int!") elseif x isa AbstractFloat println("Look! A Float!") elseif x isa Complex println("Whoa, that's complex!") else println("I have no idea what that is") end end checktype(2) #> Look! An Int! checktype(√2) #> Look! A Float! checktype(√Complex(-2)) #> Whoa, that's complex! checktype("who am I?") #> I have no idea what that is # For simple logical statements, one can be more terse using the "ternary operator", # which takes the form `predicate ? do_if_true : do_if_false` 1 > 2 ? println("that's true!") : println("that's false!") #> that's false! noisy_sqrt(x) = x ≥ 0 ? sqrt(x) : "That's negative!" noisy_sqrt(4) #> 2.0 noisy_sqrt(-4) #> That's negative! # "Short-circuit evaluation" offers another option for conditional statements. # The opperators `&&` for AND and `||` for OR only evaluate the right-hand # statement if necessary based on the predicate. # Logically, if I want to know if `42 == 0 AND x < y`, # it doesn't matter what `x` and `y` are, since the first statement is false. # This can be exploited to only evaluate a statement if something is true - # the second statement doesn't even have to be boolean! everything = 42 everything < 100 && println("that's true!") #> "that's true!" everything == 0 && println("that's true!") #> false √everything > 0 || println("that's false!") #> true √everything == everything || println("that's false!") #> that's false! <|start_filename|>grepWinNP3/sktoolslib_mod/DlgResizer.cpp<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012-2013, 2016, 2020-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "DlgResizer.h" #include <cassert> #include <commctrl.h> #ifndef ComboBox_GetEditSel # include <windowsx.h> #endif CDlgResizer::CDlgResizer() : m_hDlg(nullptr) , m_wndGrip(nullptr) , m_useSizeGrip(true) { m_controls.clear(); m_dlgRect = {}; m_dlgRectScreen = {}; m_sizeGrip = {}; } CDlgResizer::~CDlgResizer() { m_controls.clear(); } void CDlgResizer::Init(HWND hWndDlg) { m_hDlg = hWndDlg; GetClientRect(hWndDlg, &m_dlgRect); GetWindowRect(hWndDlg, &m_dlgRectScreen); OffsetRect(&m_dlgRectScreen, -m_dlgRectScreen.left, -m_dlgRectScreen.top); m_sizeGrip.cx = GetSystemMetrics(SM_CXVSCROLL); m_sizeGrip.cy = GetSystemMetrics(SM_CYHSCROLL); RECT rect = {0, 0, m_sizeGrip.cx, m_sizeGrip.cy}; m_wndGrip = ::CreateWindowEx(0, WC_SCROLLBAR, static_cast<LPCWSTR>(nullptr), WS_CHILD | WS_CLIPSIBLINGS | SBS_SIZEGRIP, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, m_hDlg, static_cast<HMENU>(nullptr), nullptr, nullptr); if (m_wndGrip) { HRGN rgn = ::CreateRectRgn(0, 0, 1, 1); HRGN rgnGrip = ::CreateRectRgnIndirect(&rect); for (int y = 0; y < m_sizeGrip.cy; y++) { ::SetRectRgn(rgn, 0, y, m_sizeGrip.cx - y, y + 1); ::CombineRgn(rgnGrip, rgnGrip, rgn, RGN_DIFF); } ::SetWindowRgn(m_wndGrip, rgnGrip, FALSE); if (m_useSizeGrip) { // update pos UpdateGripPos(); ShowSizeGrip(); } } } void CDlgResizer::AdjustMinMaxSize() { GetWindowRect(m_hDlg, &m_dlgRectScreen); OffsetRect(&m_dlgRectScreen, -m_dlgRectScreen.left, -m_dlgRectScreen.top); } void CDlgResizer::AddControl(HWND hWndDlg, UINT ctrlId, UINT resizeType) { ResizeCtrls ctrlInfo; ctrlInfo.hWnd = GetDlgItem(hWndDlg, ctrlId); if (!ctrlInfo.hWnd) { assert(false); return; } ctrlInfo.resizeType = resizeType; GetWindowRect(ctrlInfo.hWnd, &ctrlInfo.origSize); OffsetRect(&ctrlInfo.origSize, -ctrlInfo.origSize.left, -ctrlInfo.origSize.top); MapWindowPoints(ctrlInfo.hWnd, hWndDlg, reinterpret_cast<LPPOINT>(&ctrlInfo.origSize), 2); m_controls.push_back(ctrlInfo); } void CDlgResizer::DoResize(int width, int height) { UpdateGripPos(); if (m_controls.empty()) return; InvalidateRect(m_hDlg, nullptr, true); HDWP hDwp = BeginDeferWindowPos(static_cast<int>(m_controls.size())); std::vector<std::pair<size_t, DWORD>> savedSelections; for (size_t i = 0; i < m_controls.size(); ++i) { wchar_t className[257]; const auto& [hWnd, resizeType, origSize] = m_controls[i]; // Work around a bug in the standard combo box control that causes it to // incorrectly change the selection status after resizing. Without this // fix sometimes the combo box will show selected text after a WM_SIZE // resize type event even if there was no text selected before the size event. // The workaround is to save the current selection state before the resize and // to restore that state after the resize. int status = GetClassName(hWnd, className, static_cast<int>(std::size(className))); bool isComboBox = status > 0 && _wcsicmp(className, WC_COMBOBOX) == 0; if (isComboBox) { DWORD sel = ComboBox_GetEditSel(hWnd); savedSelections.push_back({i, sel}); } RECT newPos = origSize; switch (resizeType) { case RESIZER_TOPLEFT: break; // do nothing - the original position is fine case RESIZER_TOPRIGHT: newPos.left += (width - m_dlgRect.right); newPos.right += (width - m_dlgRect.right); break; case RESIZER_TOPLEFTRIGHT: newPos.right += (width - m_dlgRect.right); break; case RESIZER_TOPLEFTBOTTOMRIGHT: newPos.right += (width - m_dlgRect.right); newPos.bottom += (height - m_dlgRect.bottom); break; case RESIZER_BOTTOMLEFT: newPos.top += (height - m_dlgRect.bottom); newPos.bottom += (height - m_dlgRect.bottom); break; case RESIZER_BOTTOMRIGHT: newPos.top += (height - m_dlgRect.bottom); newPos.bottom += (height - m_dlgRect.bottom); newPos.left += (width - m_dlgRect.right); newPos.right += (width - m_dlgRect.right); break; case RESIZER_BOTTOMLEFTRIGHT: newPos.top += (height - m_dlgRect.bottom); newPos.bottom += (height - m_dlgRect.bottom); newPos.right += (width - m_dlgRect.right); break; case RESIZER_TOPLEFTBOTTOMLEFT: newPos.bottom += (height - m_dlgRect.bottom); break; case RESIZER_TOPRIGHTBOTTOMRIGHT: newPos.left += (width - m_dlgRect.right); newPos.right += (width - m_dlgRect.right); newPos.bottom += (height - m_dlgRect.bottom); break; } hDwp = DeferWindowPos(hDwp, hWnd, nullptr, newPos.left, newPos.top, newPos.right - newPos.left, newPos.bottom - newPos.top, SWP_NOZORDER | SWP_NOACTIVATE); } EndDeferWindowPos(hDwp); for (const auto& [index, sel] : savedSelections) { int startSel = LOWORD(sel); int endSel = HIWORD(sel); ComboBox_SetEditSel(m_controls[index].hWnd, startSel, endSel); } UpdateGripPos(); } void CDlgResizer::ShowSizeGrip(bool bShow) const { ::ShowWindow(m_wndGrip, (bShow && m_useSizeGrip) ? SW_SHOW : SW_HIDE); } void CDlgResizer::UpdateGripPos() const { RECT rect; ::GetClientRect(m_hDlg, &rect); rect.left = rect.right - m_sizeGrip.cx; rect.top = rect.bottom - m_sizeGrip.cy; // must stay below other children ::SetWindowPos(m_wndGrip, HWND_BOTTOM, rect.left, rect.top, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOREPOSITION); // maximized windows cannot be resized if (::IsZoomed(m_hDlg)) { ::EnableWindow(m_wndGrip, FALSE); ShowSizeGrip(false); } else { ::EnableWindow(m_wndGrip, TRUE); ShowSizeGrip(true); } } <|start_filename|>grepWinNP3/src/AboutDlg.cpp<|end_filename|> // grepWin - regex search and replace for Windows // Copyright (C) 2007-2013, 2018, 2020-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "resource.h" #include "AboutDlg.h" #include "version.h" #include "Theme.h" #include "DPIAware.h" #include <shellapi.h> #include <string> extern HICON g_hDlgIcon128; CAboutDlg::CAboutDlg(HWND hParent) : m_hParent(hParent) , m_themeCallbackId(0) { } CAboutDlg::~CAboutDlg() { } static LRESULT DrawGrepWinIcon(HWND hWnd) { if (g_hDlgIcon128) { PAINTSTRUCT ps; HDC const hDC = GetDC(hWnd); if (hDC) { BeginPaint(hWnd, &ps); int const dpiSized = CDPIAware::Instance().Scale(hWnd, 64); int const dpiLeft = CDPIAware::Instance().Scale(hWnd, 12); int const dpiTop = CDPIAware::Instance().Scale(hWnd, 12); HBRUSH const hBrush = (HBRUSH)GetSysColorBrush(COLOR_3DFACE); DrawIconEx(hDC, dpiLeft, dpiTop, g_hDlgIcon128, dpiSized, dpiSized, 0, hBrush, DI_NORMAL); ReleaseDC(hWnd, hDC); EndPaint(hWnd, &ps); } } return FALSE; } LRESULT CAboutDlg::DlgFunc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (uMsg) { case WM_INITDIALOG: { m_themeCallbackId = CTheme::Instance().RegisterThemeChangeCallback( [this]() { CTheme::Instance().SetThemeForDialog(*this, CTheme::Instance().IsDarkTheme()); CTheme::Instance().SetFontForDialog(*this, CTheme::Instance().GetDlgFontFaceName(), CTheme::Instance().GetDlgFontSize()); }); m_link.ConvertStaticToHyperlink(hwndDlg, IDC_WEBLINK, L"http://tools.stefankueng.com"); CTheme::Instance().SetThemeForDialog(*this, CTheme::Instance().IsDarkTheme()); CTheme::Instance().SetFontForDialog(*this, CTheme::Instance().GetDlgFontFaceName(), CTheme::Instance().GetDlgFontSize()); InitDialog(hwndDlg, IDI_GREPWIN); CLanguage::Instance().TranslateWindow(*this); wchar_t buf[MAX_PATH] = {0}; #if defined(_WIN64) swprintf_s(buf, _countof(buf), L"grepWinNP3 (x64) version %ld.%ld.%ld.%ld", GREPWIN_VERMAJOR, GREPWIN_VERMINOR, GREPWIN_VERMICRO, GREPWIN_VERBUILD); #else swprintf_s(buf, _countof(buf), L"grepWinNP3 (x86) version %ld.%ld.%ld.%ld", GREPWIN_VERMAJOR, GREPWIN_VERMINOR, GREPWIN_VERMICRO, GREPWIN_VERBUILD); #endif SetDlgItemText(*this, IDC_VERSIONINFO, buf); SetDlgItemText(*this, IDC_DATE, TEXT(GREPWIN_VERDATE)); } return TRUE; case WM_COMMAND: return DoCommand(LOWORD(wParam), HIWORD(wParam)); case WM_CLOSE: CTheme::Instance().RemoveRegisteredCallback(m_themeCallbackId); break; case WM_NOTIFY: { switch (wParam) { case IDC_WEBLINK: switch (reinterpret_cast<LPNMHDR>(lParam)->code) { case NM_CLICK: case NM_RETURN: { PNMLINK pNMLink = reinterpret_cast<PNMLINK>(lParam); LITEM item = pNMLink->item; if (item.iLink == 0) { ShellExecute(*this, L"open", item.szUrl, nullptr, nullptr, SW_SHOW); } break; } } break; default: break; } } break; default: return FALSE; case WM_PAINT: return DrawGrepWinIcon(*this); } return FALSE; } LRESULT CAboutDlg::DoCommand(int id, int /*msg*/) { switch (id) { case IDOK: // fall through case IDCANCEL: EndDialog(*this, id); break; default: break; } return 1; } <|start_filename|>src/StyleLexers/styleLexKiX.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- //KEYWORDLIST KeyWords_KiX = EMPTY_KEYWORDLIST; KEYWORDLIST KeyWords_KiX = { // keywords "beep big break call case cd cls color cookie1 copy debug del dim display do each else endif endselect exit " "flushkb for function get gets global go gosub goto if include loop md move next " "password play quit rd redim return run select set setl setm settime shell sleep small until use while", // functions "abs addkey addprinterconnection addprogramgroup addprogramitem asc ascan at backupeventlog box " "cdbl chr cin cleareventlog close comparefiletimes createobject cstr " "dectohex delkey delprinterconnection delprogramgroup delprogramitem deltree delvalue dir " "enumgroup enumipinfo enumkey enumlocalgroup enumvalue execute exist existkey expandenviromentvars " "fix formatnumber freefilehandle getdiskspace getfileattr getfilesize getfiletime getfileversion getobject " "iif ingroup instr instrrev int isdeclared join kbhit keyexist lcase left len loadhive loadkey logevent logoff ltrim " "memorysize messagebox open readline readprofilestring readtype readvalue redirectoutput right rnd round rtrim " "savekey sendkeys sendmessage setascii setconsole setdefaultprinter setfileattr setfocus setoption setsystemstate settitle showprogramgroup shutdown sidtoname srnd " "trim ubound ucase unloadhive val vartype vartypename writeline writeprofilestring writevalue", // macros "address build color comment cpu crlf csd curdir date day domain dos error fullname homedir homedrive homeshr hostname " "inwin ipaddress kix lanroot ldomain ldrive lm logonmode longhomedir lserver maxpwage mdayno mhz monthno month msecs " "onwow64 pid primarygroup priv productsuite producttype pwage ras result rserver " "scriptdir scriptexe scriptname serror sid site startdir syslang ticks time tssession userid userlang wdayno wksta wuserid ydayno year", NULL, }; EDITLEXER lexKiX = { SCLEX_KIX, "kix", IDS_LEX_KIX_SCR, L"KiXtart Script", L"kix", L"", &KeyWords_KiX, { { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_KIX_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {SCE_KIX_KEYWORD}, IDS_LEX_STR_63128, L"Keyword", L"bold; fore:#265CFF", L"" }, { {SCE_KIX_FUNCTIONS}, IDS_LEX_STR_63277, L"Function", L"fore:#9B009B", L"" }, { {SCE_KIX_MACRO}, IDS_LEX_STR_63280, L"Macro", L"fore:#FFC000", L"" }, { {MULTI_STYLE(SCE_KIX_COMMENT, SCE_KIX_COMMENTSTREAM,0,0)}, IDS_LEX_STR_63127, L"Comment", L"fore:#008000", L"" }, { {MULTI_STYLE(SCE_KIX_STRING1, SCE_KIX_STRING2,0,0)}, IDS_LEX_STR_63131, L"String", L"italic; fore:#8F8F8F", L"" }, { {SCE_KIX_OPERATOR}, IDS_LEX_STR_63132, L"Operator", L"fore:#C80000", L"" }, { {SCE_KIX_NUMBER}, IDS_LEX_STR_63130, L"Number", L"fore:#009797", L"" }, { {SCE_KIX_VAR}, IDS_LEX_STR_63249, L"Variable", L"fore:#9E4D2A", L"" }, { {SCE_KIX_IDENTIFIER}, IDS_LEX_STR_63129, L"Identifier", L"", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>grepWinNP3/sktoolslib_mod/ItemIDList.cpp<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012, 2020 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "ItemIDList.h" #include <Shobjidl.h> #include <Shlobj.h> #include <string> ItemIDList::ItemIDList(LPCITEMIDLIST item, LPCITEMIDLIST parent) : item_(item) , parent_(parent) , count_(-1) { } ItemIDList::~ItemIDList() { } int ItemIDList::size() const { if (count_ == -1) { count_ = 0; if (item_) { LPCSHITEMID ptr = &item_->mkid; while (ptr != 0 && ptr->cb != 0) { ++count_; LPBYTE byte = (LPBYTE)ptr; byte += ptr->cb; ptr = (LPCSHITEMID)byte; } } } return count_; } LPCSHITEMID ItemIDList::get(int index) const { int count = 0; if (item_ == NULL) return NULL; LPCSHITEMID ptr = &item_->mkid; if (ptr == NULL) return NULL; while (ptr->cb != 0) { if (count == index) break; ++count; LPBYTE byte = (LPBYTE)ptr; byte += ptr->cb; ptr = (LPCSHITEMID)byte; } return ptr; } std::wstring ItemIDList::toString() { IShellFolder *shellFolder = NULL; IShellFolder *parentFolder = NULL; STRRET name; wchar_t * szDisplayName = NULL; std::wstring ret; HRESULT hr; hr = ::SHGetDesktopFolder(&shellFolder); if (!SUCCEEDED(hr)) return ret; if (parent_) { hr = shellFolder->BindToObject(parent_, 0, IID_IShellFolder, (void **)&parentFolder); if (!SUCCEEDED(hr)) parentFolder = shellFolder; } else { parentFolder = shellFolder; } if ((parentFolder != 0) && (item_ != 0)) { hr = parentFolder->GetDisplayNameOf(item_, SHGDN_NORMAL | SHGDN_FORPARSING, &name); if (!SUCCEEDED(hr)) { parentFolder->Release(); return ret; } hr = StrRetToStr(&name, item_, &szDisplayName); CoTaskMemFree(name.pOleStr); if (!SUCCEEDED(hr)) return ret; } parentFolder->Release(); if (szDisplayName == NULL) { CoTaskMemFree(szDisplayName); return ret; //to avoid a crash! } ret = szDisplayName; CoTaskMemFree(szDisplayName); return ret; } LPCITEMIDLIST ItemIDList::operator&() { return item_; } <|start_filename|>test/test_files/StyleLexers/styleLexKotlin/ExampleCode.kt<|end_filename|> fun whenAssign(obj: Any): Any { val result = when (obj) { // 1 1 -> "one" // 2 "Hello" -> 1 // 3 is Long -> false // 4 else -> 42 // 5 } return result } fun printMessage(message: String): Unit { // 1 println(message) } fun printMessageWithPrefix(message: String, prefix: String = "Info") { // 2 println("[$prefix] $message") } fun sum(x: Int, y: Int): Int { // 3 return x + y } fun multiply(x: Int, y: Int) = x * y // 4 fun main() { printMessage("Hello") // 5 printMessageWithPrefix("Hello", "Log") // 6 printMessageWithPrefix("Hello") // 7 printMessageWithPrefix(prefix = "Log", message = "Hello") // 8 println(sum(1, 2)) // 9 println(multiply(2, 4)) // 10 } class MyClass var neverNull: String = "This can't be null" // 1 neverNull = null // 2 var nullable: String? = "You can keep a null here" // 3 nullable = null // 4 var inferredNonNull = "The compiler assumes non-null" // 5 inferredNonNull = null // 6 fun strLength(notNull: String): Int { // 7 return notNull.length } strLength(neverNull) // 8 strLength(nullable) // 9 val systemUsers: MutableList<Int> = mutableListOf(1, 2, 3) // 1 val sudoers: List<Int> = systemUsers // 2 fun addSudoer(newUser: Int) { // 3 systemUsers.add(newUser) } fun getSysSudoers(): List<Int> { // 4 return sudoers } fun main() { addSudoer(4) // 5 println("Tot sudoers: ${getSysSudoers().size}") // 6 getSysSudoers().forEach { // 7 i -> println("Some useful info on user $i") } // getSysSudoers().add(5) <- Error! // 8 } val empty = "test".let { // 1 customPrint(it) // 2 it.isEmpty() // 3 } println(" is empty: $empty") fun printNonNull(str: String?) { println("Printing \"$str\":") str?.let { // 4 print("\t") customPrint(it) println() } } printNonNull(null) printNonNull("my string") interface SoundBehavior { // 1 fun makeSound() } class ScreamBehavior(val n:String): SoundBehavior { // 2 override fun makeSound() = println("${n.toUpperCase()} !!!") } class RockAndRollBehavior(val n:String): SoundBehavior { // 2 override fun makeSound() = println("I'm The King of Rock 'N' Roll: $n") } // <NAME> is the "singer" of Slayer class TomAraya(n:String): SoundBehavior by ScreamBehavior(n) // 3 // You should know ;) class ElvisPresley(n:String): SoundBehavior by RockAndRollBehavior(n) // 3 fun main() { val tomAraya = TomAraya("<NAME>") tomAraya.makeSound() // 4 val elvisPresley = ElvisPresley("Dancin' to the Jailhouse Rock.") elvisPresley.makeSound() } <|start_filename|>grepWinNP3/sktoolslib_mod/ProgressDlg.cpp<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012, 2017, 2020-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "ProgressDlg.h" CProgressDlg::CProgressDlg() : m_pIDlg(nullptr) , m_bValid(false) //not valid by default , m_isVisible(false) , m_dwDlgFlags(PROGDLG_NORMAL) , m_hWndProgDlg(nullptr) { EnsureValid(); } CProgressDlg::~CProgressDlg() { if (m_bValid) { if (m_isVisible) //still visible, so stop first before destroying m_pIDlg->StopProgressDialog(); m_pIDlg->Release(); m_hWndProgDlg = nullptr; } } bool CProgressDlg::EnsureValid() { if (!m_bValid) { HRESULT hr = CoCreateInstance(CLSID_ProgressDialog, nullptr, CLSCTX_INPROC_SERVER, IID_IProgressDialog, reinterpret_cast<void**>(&m_pIDlg)); if (SUCCEEDED(hr)) m_bValid = true; //instance successfully created } return m_bValid; } void CProgressDlg::SetTitle(LPCWSTR szTitle) const { if (m_bValid) { m_pIDlg->SetTitle(szTitle); } } void CProgressDlg::SetLine(DWORD dwLine, LPCWSTR szText, bool bCompactPath /* = false */) const { if (m_bValid) { m_pIDlg->SetLine(dwLine, szText, bCompactPath, nullptr); } } #ifdef _MFC_VER void CProgressDlg::SetCancelMsg(UINT idMessage) { SetCancelMsg(CString(MAKEINTRESOURCE(idMessage))); } #endif // _MFC_VER void CProgressDlg::SetCancelMsg(LPCWSTR szMessage) const { if (m_bValid) { m_pIDlg->SetCancelMsg(szMessage, nullptr); } } void CProgressDlg::SetAnimation(HINSTANCE hinst, UINT uRsrcID) const { if (m_bValid) { m_pIDlg->SetAnimation(hinst, uRsrcID); } } #ifdef _MFC_VER void CProgressDlg::SetAnimation(UINT uRsrcID) { if (m_bValid) { m_pIDlg->SetAnimation(AfxGetResourceHandle(), uRsrcID); } } #endif void CProgressDlg::SetTime(bool bTime /* = true */) { m_dwDlgFlags &= ~(PROGDLG_NOTIME | PROGDLG_AUTOTIME); if (bTime) m_dwDlgFlags |= PROGDLG_AUTOTIME; else m_dwDlgFlags |= PROGDLG_NOTIME; } void CProgressDlg::SetShowProgressBar(bool bShow /* = true */) { if (bShow) m_dwDlgFlags &= ~PROGDLG_NOPROGRESSBAR; else m_dwDlgFlags |= PROGDLG_NOPROGRESSBAR; } #ifdef _MFC_VER HRESULT CProgressDlg::ShowModal(CWnd* pwndParent) { EnsureValid(); return ShowModal(pwndParent->GetSafeHwnd()); } HRESULT CProgressDlg::ShowModeless(CWnd* pwndParent) { EnsureValid(); return ShowModeless(pwndParent->GetSafeHwnd()); } void CProgressDlg::FormatPathLine(DWORD dwLine, UINT idFormatText, ...) { va_list args; va_start(args, idFormatText); CString sText; sText.FormatV(CString(MAKEINTRESOURCE(idFormatText)), args); SetLine(dwLine, sText, true); va_end(args); } void CProgressDlg::FormatNonPathLine(DWORD dwLine, UINT idFormatText, ...) { va_list args; va_start(args, idFormatText); CString sText; sText.FormatV(CString(MAKEINTRESOURCE(idFormatText)), args); SetLine(dwLine, sText, false); va_end(args); } #endif HRESULT CProgressDlg::ShowModal(HWND hWndParent) { EnsureValid(); if (m_bValid) { HRESULT hr = m_pIDlg->StartProgressDialog(hWndParent, nullptr, m_dwDlgFlags | PROGDLG_MODAL, nullptr); if (SUCCEEDED(hr)) { m_isVisible = true; } return hr; } return E_FAIL; } HRESULT CProgressDlg::ShowModeless(HWND hWndParent) { EnsureValid(); HRESULT hr = E_FAIL; m_hWndProgDlg = nullptr; if (m_bValid) { hr = m_pIDlg->StartProgressDialog(hWndParent, nullptr, m_dwDlgFlags, nullptr); if (SUCCEEDED(hr)) { m_isVisible = true; // The progress window can be remarkably slow to display, particularly // if its parent is blocked. // This process finds the hwnd for the progress window and gives it a kick... IOleWindow* pOleWindow; HRESULT hr2 = m_pIDlg->QueryInterface(IID_IOleWindow, reinterpret_cast<LPVOID*>(&pOleWindow)); if (SUCCEEDED(hr2)) { hr2 = pOleWindow->GetWindow(&m_hWndProgDlg); if (SUCCEEDED(hr2)) { ShowWindow(m_hWndProgDlg, SW_NORMAL); } pOleWindow->Release(); } } } return hr; } void CProgressDlg::SetProgress(DWORD dwProgress, DWORD dwMax) const { if (m_bValid) { m_pIDlg->SetProgress(dwProgress, dwMax); } } void CProgressDlg::SetProgress64(ULONGLONG u64Progress, ULONGLONG u64ProgressMax) const { if (m_bValid) { m_pIDlg->SetProgress64(u64Progress, u64ProgressMax); } } bool CProgressDlg::HasUserCancelled() const { if (m_bValid) { return (0 != m_pIDlg->HasUserCancelled()); } return FALSE; } void CProgressDlg::Stop() { if ((m_isVisible) && (m_bValid)) { m_pIDlg->StopProgressDialog(); // Sometimes the progress dialog sticks around after stopping it, // until the mouse pointer is moved over it or some other triggers. // We hide the window here immediately. if (m_hWndProgDlg) { ShowWindow(m_hWndProgDlg, SW_HIDE); } m_isVisible = false; m_pIDlg->Release(); m_bValid = false; m_hWndProgDlg = nullptr; } } void CProgressDlg::ResetTimer() const { if (m_bValid) { m_pIDlg->Timer(PDTIMER_RESET, nullptr); } } <|start_filename|>grepWinNP3/src/SearchInfo.cpp<|end_filename|> // grepWin - regex search and replace for Windows // Copyright (C) 2007-2008, 2012-2014, 2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "SearchInfo.h" CSearchInfo::CSearchInfo() : fileSize(0) , matchCount(0) , encoding(CTextFile::UnicodeType::AutoType) , readError(false) , folder(false) { modifiedTime.dwHighDateTime = 0; modifiedTime.dwLowDateTime = 0; } CSearchInfo::CSearchInfo(const std::wstring& path) : filePath(path) , fileSize(0) , matchCount(0) , encoding(CTextFile::UnicodeType::AutoType) , readError(false) , folder(false) { modifiedTime.dwHighDateTime = 0; modifiedTime.dwLowDateTime = 0; } CSearchInfo::~CSearchInfo() { } <|start_filename|>test/test_files/StyleLexers/styleLexASM/lowhelpr.asm<|end_filename|> ;*** ;lowhelpr.asm ; ; Copyright (C) Microsoft Corporation. All rights reserved. ; ;Purpose: ; Contains _CallSettingFrame(), which must be in asm for NLG purposes. ; ;Notes: ; ;******************************************************************************* title lowhelpr.asm .xlist include vcruntime.inc include exsup.inc .list EXTERN _NLG_Notify:NEAR EXTERN _NLG_Notify1:NEAR PUBLIC _CallSettingFrame PUBLIC _NLG_Return extern _NLG_Destination:_NLG_INFO CODESEG ;//////////////////////////////////////////////////////////////////////////// ;/ ;/ _CallSettingFrame - sets up EBP and calls the specified funclet. Restores ;/ EBP on return. ;/ ;/ Return value is return value of funclet (whatever is in EAX). ;/ public _CallSettingFrame _CallSettingFrame proc stdcall, funclet:IWORD, pRN:IWORD, dwInCode:DWORD ; FPO = 0 dwords locals allocated in prolog ; 3 dword parameters ; 8 bytes in prolog ; 4 registers saved (includes locals to work around debugger bug) ; 1 EBP is used ; 0 frame type = FPO .FPO (0,3,8,4,1,0) sub esp,4 push ebx push ecx mov eax,pRN add eax,0Ch ; sizeof(EHRegistrationNode) -- assumed to equal 0Ch mov dword ptr [ebp-4],eax mov eax,funclet push ebp ; Save our frame pointer push dwInCode mov ecx,dwInCode mov ebp,dword ptr [ebp-4] ; Load target frame pointer call _NLG_Notify1 ; Notify debugger push esi push edi call eax ; Call the funclet _NLG_Return:: pop edi pop esi mov ebx,ebp pop ebp mov ecx,dwInCode push ebp mov ebp,ebx cmp ecx, 0100h jne _NLG_Continue mov ecx, 02h _NLG_Continue: push ecx call _NLG_Notify1 ; Notify debugger yet again pop ebp ; Restore our frame pointer pop ecx pop ebx ret 0Ch _CallSettingFrame ENDP ; ; SafeSEH stubs, declared here, in assembler language, so that they may be ; added to the SafeSEH handler list (which cannot be done from native C). ; EXTERN _CatchGuardHandler:PROC EXTERN _TranslatorGuardHandler:PROC .SafeSEH _CatchGuardHandler .SafeSEH _TranslatorGuardHandler END <|start_filename|>src/StyleLexers/styleLexDIFF.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_DIFF = EMPTY_KEYWORDLIST; EDITLEXER lexDIFF = { SCLEX_DIFF, "diff", IDS_LEX_DIFF, L"Diff Files", L"diff; patch", L"", &KeyWords_DIFF, { { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_DIFF_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {SCE_DIFF_COMMENT}, IDS_LEX_STR_63127, L"Comment", L"fore:#008000", L"" }, { {SCE_DIFF_COMMAND}, IDS_LEX_STR_63236, L"Command", L"bold; fore:#0A246A", L"" }, { {SCE_DIFF_HEADER}, IDS_LEX_STR_63238, L"Source and Destination", L"fore:#C80000; back:#FFF1A8; eolfilled", L"" }, { {SCE_DIFF_POSITION}, IDS_LEX_STR_63239, L"Position Setting", L"fore:#0000FF", L"" }, { {MULTI_STYLE(SCE_DIFF_ADDED, SCE_DIFF_PATCH_ADD, SCE_DIFF_REMOVED_PATCH_ADD, 0)}, IDS_LEX_STR_63240, L"Line Addition", L"fore:#002000; back:#80FF80; eolfilled", L"" }, { {MULTI_STYLE(SCE_DIFF_DELETED, SCE_DIFF_PATCH_DELETE, SCE_DIFF_REMOVED_PATCH_DELETE, 0)}, IDS_LEX_STR_63241, L"Line Removal", L"fore:#200000; back:#FF8080; eolfilled", L"" }, { {SCE_DIFF_CHANGED}, IDS_LEX_STR_63242, L"Line Change", L"fore:#000020; back:#8080FF; eolfilled", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>src/ced/ced/util/case_insensitive_hash.h<|end_filename|> // encoding: UTF-8 // Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// #ifndef UTIL_CASE_INSENSITIVE_HASH_H_ #define UTIL_CASE_INSENSITIVE_HASH_H_ #include <ctype.h> #include <stddef.h> #ifndef _MSC_VER #include <strings.h> #endif #include <string> #include "util/basictypes.h" #include "util/string_util.h" // Functors for hashing c-strings with case-insensitive semantics. struct CStringCaseHash { size_t operator()(const char *str) const { unsigned long hash_val = 0; while (*str) { hash_val = 5*hash_val + tolower(*str); str++; } return (size_t)hash_val; } }; struct CStringCaseEqual { bool operator()(const char *str1, const char *str2) const { return !base::strcasecmp(str1, str2); } }; // These functors, in addition to being case-insensitive, ignore all // non-alphanumeric characters. This is useful when we want all variants of // a string -- where variants can differ in puncutation and whitespace -- to // map to the same value. struct CStringAlnumCaseHash { size_t operator()(const char *str) const { unsigned long hash_val = 0; while (*str) { if (isalnum(*str)) { hash_val = 5*hash_val + tolower(*str); } str++; } return (size_t)hash_val; } }; struct CStringAlnumCaseEqual { bool operator()(const char *str1, const char *str2) const { while (true) { // Skip until each pointer is pointing to an alphanumeric char or '\0' while (!isalnum(*str1) && (*str1 != '\0')) { str1++; } while (!isalnum(*str2) && (*str2 != '\0')) { str2++; } if (tolower(*str1) != tolower(*str2)) { return false; // mismatch on alphanumeric char or '\0' } if (*str1 == '\0') { // in which case *str2 must be '\0' as well return true; // reached '\0' in both strings without mismatch } str1++; str2++; } } }; #endif // UTIL_CASE_INSENSITIVE_HASH_H_ <|start_filename|>lexilla/lexlib/CharacterSet.h<|end_filename|> // Scintilla source code edit control /** @file CharacterSet.h ** Encapsulates a set of characters. Used to test if a character is within a set. **/ // Copyright 2007 by <NAME> <<EMAIL>> // The License.txt file describes the conditions under which this software may be distributed. #ifndef CHARACTERSET_H #define CHARACTERSET_H namespace Lexilla { template<int N> class CharacterSetArray { unsigned char bset[(N-1)/8 + 1] = {}; bool valueAfter = false; public: enum setBase { setNone=0, setLower=1, setUpper=2, setDigits=4, setAlpha=setLower|setUpper, setAlphaNum=setAlpha|setDigits }; CharacterSetArray(setBase base=setNone, const char *initialSet="", bool valueAfter_=false) noexcept { valueAfter = valueAfter_; AddString(initialSet); if (base & setLower) AddString("abcdefghijklmnopqrstuvwxyz"); if (base & setUpper) AddString("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); if (base & setDigits) AddString("0123456789"); } // For compatibility with previous version but should not be used in new code. CharacterSetArray(setBase base, const char *initialSet, [[maybe_unused]]int size_, bool valueAfter_=false) noexcept : CharacterSetArray(base, initialSet, valueAfter_) { assert(size_ == N); } void Add(int val) noexcept { assert(val >= 0); assert(val < N); bset[val >> 3] |= 1 << (val & 7); } void AddString(const char *setToAdd) noexcept { for (const char *cp=setToAdd; *cp; cp++) { const unsigned char uch = *cp; assert(uch < N); Add(uch); } } bool Contains(int val) const noexcept { assert(val >= 0); if (val < 0) return false; if (val >= N) return valueAfter; return bset[val >> 3] & (1 << (val & 7)); } bool Contains(char ch) const noexcept { // Overload char as char may be signed const unsigned char uch = ch; return Contains(uch); } }; using CharacterSet = CharacterSetArray<0x80>; // Functions for classifying characters template <typename T, typename... Args> constexpr bool AnyOf(T t, Args... args) noexcept { #if defined(__clang__) static_assert(__is_integral(T)); #endif return ((t == args) || ...); } // prevent pointer without <type_traits> template <typename T, typename... Args> constexpr void AnyOf([[maybe_unused]] T *t, [[maybe_unused]] Args... args) noexcept {} template <typename T, typename... Args> constexpr void AnyOf([[maybe_unused]] const T *t, [[maybe_unused]] Args... args) noexcept {} constexpr bool IsASpace(int ch) noexcept { return (ch == ' ') || ((ch >= 0x09) && (ch <= 0x0d)); } constexpr bool IsASpaceOrTab(int ch) noexcept { return (ch == ' ') || (ch == '\t'); } constexpr bool IsADigit(int ch) noexcept { return (ch >= '0') && (ch <= '9'); } constexpr bool IsADigit(int ch, int base) noexcept { if (base <= 10) { return (ch >= '0') && (ch < '0' + base); } else { return ((ch >= '0') && (ch <= '9')) || ((ch >= 'A') && (ch < 'A' + base - 10)) || ((ch >= 'a') && (ch < 'a' + base - 10)); } } constexpr bool IsASCII(int ch) noexcept { return (ch >= 0) && (ch < 0x80); } constexpr bool IsLowerCase(int ch) noexcept { return (ch >= 'a') && (ch <= 'z'); } constexpr bool IsUpperCase(int ch) noexcept { return (ch >= 'A') && (ch <= 'Z'); } constexpr bool IsUpperOrLowerCase(int ch) noexcept { return IsUpperCase(ch) || IsLowerCase(ch); } constexpr bool IsAlphaNumeric(int ch) noexcept { return ((ch >= '0') && (ch <= '9')) || ((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z')); } /** * Check if a character is a space. * This is ASCII specific but is safe with chars >= 0x80. */ constexpr bool isspacechar(int ch) noexcept { return (ch == ' ') || ((ch >= 0x09) && (ch <= 0x0d)); } constexpr bool iswordchar(int ch) noexcept { return IsAlphaNumeric(ch) || ch == '.' || ch == '_'; } constexpr bool iswordstart(int ch) noexcept { return IsAlphaNumeric(ch) || ch == '_'; } constexpr bool isoperator(int ch) noexcept { if (IsAlphaNumeric(ch)) return false; if (ch == '%' || ch == '^' || ch == '&' || ch == '*' || ch == '(' || ch == ')' || ch == '-' || ch == '+' || ch == '=' || ch == '|' || ch == '{' || ch == '}' || ch == '[' || ch == ']' || ch == ':' || ch == ';' || ch == '<' || ch == '>' || ch == ',' || ch == '/' || ch == '?' || ch == '!' || ch == '.' || ch == '~') return true; return false; } // Simple case functions for ASCII supersets. template <typename T> constexpr T MakeUpperCase(T ch) noexcept { if (ch < 'a' || ch > 'z') return ch; else return ch - 'a' + 'A'; } template <typename T> constexpr T MakeLowerCase(T ch) noexcept { if (ch < 'A' || ch > 'Z') return ch; else return ch - 'A' + 'a'; } int CompareCaseInsensitive(const char *a, const char *b) noexcept; int CompareNCaseInsensitive(const char *a, const char *b, size_t len) noexcept; } #endif <|start_filename|>grepWinNP3/src/ShellContextMenu.cpp<|end_filename|> // grepWin - regex search and replace for Windows // Copyright (C) 2007-2015, 2017, 2020-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "ShellContextMenu.h" #include <shellapi.h> #include "StringUtils.h" #include "Registry.h" #include "SearchInfo.h" #include "LineData.h" #include "ResString.h" #include "resource.h" #include <set> #include <algorithm> #define MIN_ID 6 #define MAX_ID 10000 IContextMenu2* g_iContext2 = nullptr; IContextMenu3* g_iContext3 = nullptr; WNDPROC g_oldWndProc = nullptr; struct ICompare { bool operator()(const std::wstring& lhs, const std::wstring& rhs) const { return _wcsicmp(lhs.c_str(), rhs.c_str()) < 0; } }; CShellContextMenu::CShellContextMenu() : m_nItems(0) , bDelete(FALSE) , m_menu(nullptr) , m_psfFolder(nullptr) , m_pidlArray(nullptr) , m_pidlArrayItems(0) , m_pFolderHook(nullptr) { } CShellContextMenu::~CShellContextMenu() { // free all allocated data delete m_pFolderHook; if (m_psfFolder && bDelete) m_psfFolder->Release(); m_psfFolder = nullptr; FreePIDLArray(m_pidlArray, m_pidlArrayItems); m_pidlArray = nullptr; m_pidlArrayItems = 0; if (m_menu) DestroyMenu(m_menu); } // this functions determines which version of IContextMenu is available for those objects (always the highest one) // and returns that interface BOOL CShellContextMenu::GetContextMenu(HWND hWnd, void** ppContextMenu, int& iMenuType) { *ppContextMenu = nullptr; if (m_pFolderHook) return FALSE; if (m_psfFolder == nullptr) return FALSE; if (m_strVector.empty()) return FALSE; HKEY ahkeys[16]; SecureZeroMemory(ahkeys, _countof(ahkeys) * sizeof(HKEY)); int numkeys = 0; if (RegOpenKey(HKEY_CLASSES_ROOT, L"*", &ahkeys[numkeys++]) != ERROR_SUCCESS) numkeys--; if (RegOpenKey(HKEY_CLASSES_ROOT, L"AllFileSystemObjects", &ahkeys[numkeys++]) != ERROR_SUCCESS) numkeys--; if (PathIsDirectory(m_strVector[0].filePath.c_str())) { if (RegOpenKey(HKEY_CLASSES_ROOT, L"Folder", &ahkeys[numkeys++]) != ERROR_SUCCESS) numkeys--; if (RegOpenKey(HKEY_CLASSES_ROOT, L"Directory", &ahkeys[numkeys++]) != ERROR_SUCCESS) numkeys--; } // find extension size_t dotPos = m_strVector[0].filePath.find_last_of('.'); std::wstring ext; if (dotPos != std::string::npos) { ext = m_strVector[0].filePath.substr(dotPos); if (RegOpenKey(HKEY_CLASSES_ROOT, ext.c_str(), &ahkeys[numkeys++]) == ERROR_SUCCESS) { WCHAR buf[MAX_PATH] = {0}; DWORD dwSize = MAX_PATH; if (RegQueryValueEx(ahkeys[numkeys - 1], L"", nullptr, nullptr, reinterpret_cast<LPBYTE>(buf), &dwSize) == ERROR_SUCCESS) { if (RegOpenKey(HKEY_CLASSES_ROOT, buf, &ahkeys[numkeys++]) != ERROR_SUCCESS) numkeys--; } } } delete m_pFolderHook; m_pFolderHook = new CIShellFolderHook(m_psfFolder, this); LPCONTEXTMENU icm1 = nullptr; if (FAILED(CDefFolderMenu_Create2(NULL, hWnd, static_cast<UINT>(m_pidlArrayItems), const_cast<LPCITEMIDLIST*>(m_pidlArray), m_pFolderHook, dfmCallback, numkeys, ahkeys, &icm1))) return FALSE; for (int i = 0; i < numkeys; ++i) RegCloseKey(ahkeys[i]); if (icm1) { // since we got an IContextMenu interface we can now obtain the higher version interfaces via that if (icm1->QueryInterface(IID_IContextMenu3, ppContextMenu) == S_OK) iMenuType = 3; else if (icm1->QueryInterface(IID_IContextMenu2, ppContextMenu) == S_OK) iMenuType = 2; if (*ppContextMenu) icm1->Release(); // we can now release version 1 interface, cause we got a higher one else { // since no higher versions were found // redirect ppContextMenu to version 1 interface iMenuType = 1; *ppContextMenu = icm1; } } else return FALSE; return TRUE; } LRESULT CALLBACK CShellContextMenu::HookWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_MENUCHAR: // only supported by IContextMenu3 if (g_iContext3) { LRESULT lResult = 0; g_iContext3->HandleMenuMsg2(message, wParam, lParam, &lResult); return (lResult); } break; case WM_DRAWITEM: [[fallthrough]]; case WM_MEASUREITEM: if (wParam) break; // if wParam != 0 then the message is not menu-related case WM_INITMENU: [[fallthrough]]; case WM_INITMENUPOPUP: if (g_iContext3) { LRESULT lResult = 0; g_iContext3->HandleMenuMsg2(message, wParam, lParam, &lResult); return (lResult); } else if (g_iContext2) g_iContext2->HandleMenuMsg(message, wParam, lParam); return TRUE; default: break; } // call original WndProc of window to prevent undefined behavior of window return ::CallWindowProc(g_oldWndProc, hWnd, message, wParam, lParam); } UINT CShellContextMenu::ShowContextMenu(HWND hWnd, POINT pt) { int iMenuType = 0; // to know which version of IContextMenu is supported LPCONTEXTMENU pContextMenu; // common pointer to IContextMenu and higher version interface if (GetWindowLongPtr(hWnd, GWLP_WNDPROC) == reinterpret_cast<LONG_PTR>(HookWndProc)) return 0; if (!GetContextMenu(hWnd, reinterpret_cast<void**>(&pContextMenu), iMenuType)) return 0; if (!m_menu) { DestroyMenu(m_menu); m_menu = CreatePopupMenu(); } CRegStdString regEditorCmd(L"Software\\grepWin\\editorcmd"); std::wstring editorCmd = regEditorCmd; if (bPortable) editorCmd = g_iniFile.GetValue(L"global", L"editorcmd", L""); if (m_strVector.size() == 1) { if (!editorCmd.empty()) { ::InsertMenu(m_menu, 1, MF_BYPOSITION | MF_STRING, 5, TranslatedString(g_hInst, IDS_OPENWITHEDITOR).c_str()); ::InsertMenu(m_menu, 5, MF_SEPARATOR | MF_BYPOSITION, 0, nullptr); } ::InsertMenu(m_menu, 1, MF_BYPOSITION | MF_STRING, 1, TranslatedString(g_hInst, IDS_OPENCONTAININGFOLDER).c_str()); ::InsertMenu(m_menu, 2, MF_BYPOSITION | MF_STRING, 2, TranslatedString(g_hInst, IDS_COPYPATH).c_str()); ::InsertMenu(m_menu, 3, MF_BYPOSITION | MF_STRING, 3, TranslatedString(g_hInst, IDS_COPYFILENAME).c_str()); if (!m_lineVector.empty()) ::InsertMenu(m_menu, 4, MF_BYPOSITION | MF_STRING, 4, TranslatedString(g_hInst, IDS_COPYRESULT).c_str()); ::InsertMenu(m_menu, 5, MF_SEPARATOR | MF_BYPOSITION, 0, nullptr); } else if (m_strVector.size() > 1) { if (!editorCmd.empty()) { ::InsertMenu(m_menu, 1, MF_BYPOSITION | MF_STRING, 5, TranslatedString(g_hInst, IDS_OPENWITHEDITOR).c_str()); ::InsertMenu(m_menu, 5, MF_SEPARATOR | MF_BYPOSITION, 0, nullptr); } ::InsertMenu(m_menu, 2, MF_BYPOSITION | MF_STRING, 2, TranslatedString(g_hInst, IDS_COPYPATHS).c_str()); ::InsertMenu(m_menu, 3, MF_BYPOSITION | MF_STRING, 3, TranslatedString(g_hInst, IDS_COPYFILENAMES).c_str()); if (!m_lineVector.empty()) ::InsertMenu(m_menu, 4, MF_BYPOSITION | MF_STRING, 4, TranslatedString(g_hInst, IDS_COPYRESULTS).c_str()); ::InsertMenu(m_menu, 5, MF_SEPARATOR | MF_BYPOSITION, 0, nullptr); } // lets fill the our popup menu pContextMenu->QueryContextMenu(m_menu, GetMenuItemCount(m_menu), MIN_ID, MAX_ID, CMF_NORMAL | CMF_EXPLORE); // subclass window to handle menu related messages in CShellContextMenu if (iMenuType > 1) // only subclass if its version 2 or 3 { if (GetWindowLongPtr(hWnd, GWLP_WNDPROC) != reinterpret_cast<LONG_PTR>(HookWndProc)) g_oldWndProc = reinterpret_cast<WNDPROC>(SetWindowLongPtr(hWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(HookWndProc))); if (iMenuType == 2) g_iContext2 = static_cast<LPCONTEXTMENU2>(pContextMenu); else // version 3 g_iContext3 = static_cast<LPCONTEXTMENU3>(pContextMenu); } else g_oldWndProc = nullptr; UINT idCommand = TrackPopupMenu(m_menu, TPM_RETURNCMD | TPM_LEFTALIGN, pt.x, pt.y, 0, hWnd, nullptr); if (g_oldWndProc) // un-subclass SetWindowLongPtr(hWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(g_oldWndProc)); if (idCommand >= MIN_ID && idCommand <= MAX_ID) // see if returned idCommand belongs to shell menu entries { InvokeCommand(pContextMenu, idCommand - MIN_ID); // execute related command idCommand = 0; } else { switch (idCommand) { case 1: { // This is the command line for explorer which tells it to select the given file std::wstring sFolder = L"/Select,\"" + m_strVector[0].filePath + L"\""; // Prepare shell execution params SHELLEXECUTEINFO shExecInfo = {0}; shExecInfo.cbSize = sizeof(shExecInfo); shExecInfo.lpFile = L"explorer.exe"; shExecInfo.lpParameters = sFolder.c_str(); shExecInfo.nShow = SW_SHOWNORMAL; shExecInfo.lpVerb = L"open"; // Context menu item shExecInfo.fMask = SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI; // Select file in explorer ShellExecuteEx(&shExecInfo); } break; case 2: { std::wstring pathNames; for (auto it = m_strVector.begin(); it != m_strVector.end(); ++it) { if (!pathNames.empty()) pathNames += L"\r\n"; pathNames += it->filePath; } WriteAsciiStringToClipboard(pathNames.c_str(), hWnd); } break; case 3: { std::wstring pathNames; for (auto it = m_strVector.begin(); it != m_strVector.end(); ++it) { if (!pathNames.empty()) pathNames += L"\r\n"; std::wstring p = it->filePath; p = p.substr(p.find_last_of('\\') + 1); pathNames += p; } WriteAsciiStringToClipboard(pathNames.c_str(), hWnd); } break; case 4: { std::wstring lines; for (auto it = m_lineVector.begin(); it != m_lineVector.end(); ++it) { if (!lines.empty()) lines += L"\r\n"; for (auto it2 = it->lines.cbegin(); it2 != it->lines.cend(); ++it2) { std::wstring l = it2->text; CStringUtils::trim(l, L"\r\n"); std::replace(l.begin(), l.end(), '\n', ' '); std::replace(l.begin(), l.end(), '\r', ' '); lines += l; } } WriteAsciiStringToClipboard(lines.c_str(), hWnd); } break; case 5: { if (!m_lineVector.empty()) { for (auto it = m_lineVector.cbegin(); it != m_lineVector.cend(); ++it) { for (auto it2 = it->lines.cbegin(); it2 != it->lines.cend(); ++it2) { std::wstring cmd = editorCmd; SearchReplace(cmd, L"%path%", it->path.c_str()); wchar_t buf[40] = {0}; swprintf_s(buf, L"%ld", it2->number); SearchReplace(cmd, L"%line%", buf); STARTUPINFO startupInfo; PROCESS_INFORMATION processInfo; SecureZeroMemory(&startupInfo, sizeof(startupInfo)); startupInfo.cb = sizeof(STARTUPINFO); SecureZeroMemory(&processInfo, sizeof(processInfo)); CreateProcess(nullptr, const_cast<wchar_t*>(cmd.c_str()), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startupInfo, &processInfo); CloseHandle(processInfo.hThread); CloseHandle(processInfo.hProcess); } } } else { for (auto it = m_strVector.begin(); it != m_strVector.end(); ++it) { std::wstring cmd = editorCmd; SearchReplace(cmd, L"%path%", it->filePath.c_str()); if (!it->matchLinesNumbers.empty()) { wchar_t buf[40] = {0}; swprintf_s(buf, L"%ld", it->matchLinesNumbers[0]); SearchReplace(cmd, L"%line%", buf); } else SearchReplace(cmd, L"%line%", L"0"); STARTUPINFO startupInfo; PROCESS_INFORMATION processInfo; SecureZeroMemory(&startupInfo, sizeof(startupInfo)); startupInfo.cb = sizeof(STARTUPINFO); SecureZeroMemory(&processInfo, sizeof(processInfo)); CreateProcess(nullptr, const_cast<wchar_t*>(cmd.c_str()), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startupInfo, &processInfo); CloseHandle(processInfo.hThread); CloseHandle(processInfo.hProcess); } } } break; } } pContextMenu->Release(); g_iContext2 = nullptr; g_iContext3 = nullptr; delete m_pFolderHook; m_pFolderHook = nullptr; return (idCommand); } void CShellContextMenu::InvokeCommand(LPCONTEXTMENU pContextMenu, UINT idCommand) { CMINVOKECOMMANDINFO cmi = {0}; cmi.cbSize = sizeof(CMINVOKECOMMANDINFO); cmi.lpVerb = reinterpret_cast<LPSTR>(MAKEINTRESOURCE(idCommand)); cmi.nShow = SW_SHOWNORMAL; pContextMenu->InvokeCommand(&cmi); } void CShellContextMenu::SetObjects(const std::vector<CSearchInfo>& strVector, const std::vector<LineData>& lineVector) { // free all allocated data if (m_psfFolder && bDelete) m_psfFolder->Release(); m_psfFolder = nullptr; FreePIDLArray(m_pidlArray, m_pidlArrayItems); m_pidlArray = nullptr; // get IShellFolder interface of Desktop (root of shell namespace) SHGetDesktopFolder(&m_psfFolder); // needed to obtain full qualified pidl // ParseDisplayName creates a PIDL from a file system path relative to the IShellFolder interface // but since we use the Desktop as our interface and the Desktop is the namespace root // that means that it's a fully qualified PIDL, which is what we need m_nItems = strVector.size(); m_pidlArray = static_cast<LPITEMIDLIST*>(CoTaskMemAlloc((m_nItems + 10) * sizeof(LPITEMIDLIST))); SecureZeroMemory(m_pidlArray, (m_nItems + 10) * sizeof(LPITEMIDLIST)); m_pidlArrayItems = 0; int succeededItems = 0; LPITEMIDLIST pidl = nullptr; m_strVector.clear(); m_lineVector.clear(); m_strVector.reserve(m_nItems); m_lineVector.reserve(m_nItems); size_t bufSize = 1024; auto filePath = std::make_unique<WCHAR[]>(bufSize); for (size_t i = 0; i < m_nItems; i++) { if (bufSize < strVector[i].filePath.size()) { bufSize = strVector[i].filePath.size() + 3; filePath = std::make_unique<WCHAR[]>(bufSize); } wcscpy_s(filePath.get(), bufSize, strVector[i].filePath.c_str()); if (SUCCEEDED(m_psfFolder->ParseDisplayName(NULL, nullptr, filePath.get(), NULL, &pidl, NULL))) { m_pidlArray[succeededItems++] = pidl; // copy pidl to pidlArray m_strVector.push_back(strVector[i]); if (lineVector.size() > static_cast<size_t>(i)) m_lineVector.push_back(lineVector[i]); } } m_pidlArrayItems = succeededItems; bDelete = TRUE; // indicates that m_psfFolder should be deleted by CShellContextMenu } void CShellContextMenu::FreePIDLArray(LPITEMIDLIST* pidlArray, int nItems) { if (!pidlArray) return; for (int i = 0; i < nItems; i++) { CoTaskMemFree(pidlArray[i]); } CoTaskMemFree(pidlArray); } HRESULT CShellContextMenu::dfmCallback(IShellFolder* /*psf*/, HWND /*hwnd*/, IDataObject* /*pdtobj*/, UINT uMsg, WPARAM /*wParam*/, LPARAM /*lParam*/) { switch (uMsg) { case DFM_MERGECONTEXTMENU: return S_OK; case DFM_INVOKECOMMAND: case DFM_INVOKECOMMANDEX: case DFM_GETDEFSTATICID: // Required for Windows 7 to pick a default return S_FALSE; } return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CIShellFolderHook::GetUIObjectOf(HWND hwndOwner, UINT cidl, LPCITEMIDLIST* apidl, REFIID riid, UINT* rgfReserved, void** ppv) { if (InlineIsEqualGUID(riid, IID_IDataObject)) { HRESULT hRes = m_iSf->GetUIObjectOf(hwndOwner, cidl, apidl, IID_IDataObject, nullptr, ppv); if (FAILED(hRes)) return hRes; IDataObject* iData = static_cast<LPDATAOBJECT>(*ppv); // the IDataObject returned here doesn't have a HDROP, so we create one ourselves and add it to the IDataObject // the HDROP is necessary for most context menu handlers // it seems the paths in the HDROP need to be sorted, otherwise // it might not work properly or even crash. // to get the items sorted, we just add them to a set - that way we g std::set<std::wstring, ICompare> sortedPaths; for (auto it = m_pShellContextMenu->m_strVector.cbegin(); it != m_pShellContextMenu->m_strVector.cend(); ++it) sortedPaths.insert(it->filePath); int nLength = 0; for (auto it = sortedPaths.cbegin(); it != sortedPaths.cend(); ++it) { nLength += static_cast<int>(it->size()); nLength += 1; // '\0' separator } int nBufferSize = sizeof(DROPFILES) + ((nLength + 5) * sizeof(wchar_t)); auto pBuffer = std::make_unique<char[]>(nBufferSize); SecureZeroMemory(pBuffer.get(), nBufferSize); DROPFILES* df = reinterpret_cast<DROPFILES*>(pBuffer.get()); df->pFiles = sizeof(DROPFILES); df->fWide = 1; wchar_t* pFileNames = reinterpret_cast<wchar_t*>(reinterpret_cast<BYTE*>(pBuffer.get()) + sizeof(DROPFILES)); wchar_t* pCurrentFilename = pFileNames; for (auto it = sortedPaths.cbegin(); it != sortedPaths.cend(); ++it) { wcscpy_s(pCurrentFilename, it->size() + 1, it->c_str()); pCurrentFilename += it->size(); *pCurrentFilename = '\0'; // separator between file names pCurrentFilename++; } *pCurrentFilename = '\0'; // terminate array pCurrentFilename++; *pCurrentFilename = '\0'; // terminate array STGMEDIUM medium = {0}; medium.tymed = TYMED_HGLOBAL; medium.hGlobal = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE, nBufferSize + 20); if (medium.hGlobal) { LPVOID pMem = ::GlobalLock(medium.hGlobal); if (pMem) { memcpy(pMem, pBuffer.get(), nBufferSize); GlobalUnlock(medium.hGlobal); FORMATETC formatEtc = {0}; formatEtc.cfFormat = CF_HDROP; formatEtc.dwAspect = DVASPECT_CONTENT; formatEtc.lindex = -1; formatEtc.tymed = TYMED_HGLOBAL; medium.pUnkForRelease = nullptr; hRes = iData->SetData(&formatEtc, &medium, TRUE); return hRes; } } return E_OUTOFMEMORY; } else { // just pass it on to the base object return m_iSf->GetUIObjectOf(hwndOwner, cidl, apidl, riid, rgfReserved, ppv); } } <|start_filename|>src/ChooseFont/GdiTextRenderer.cpp<|end_filename|> // encoding: UTF-8 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved // //---------------------------------------------------------------------------- #include "ChooseFont.h" #include "GdiTextRenderer.h" /****************************************************************** * * * GdiTextRenderer::GdiTextRenderer * * * * Destruct the object. * * * ******************************************************************/ GdiTextRenderer::~GdiTextRenderer() { SafeRelease(&m_renderTarget); SafeRelease(&m_renderingParams); } /****************************************************************** * * * GdiTextRenderer::GetDC * * * * Return a DC with the DIB surface selected into it. The client * * can use this to initialize the background before drawing and to * * get the result after drawing. * * * * The DC should not be released or deleted. Ownership is * * retained by the GdiTextRenderer object. * * * ******************************************************************/ HDC GdiTextRenderer::GetDC() { return m_renderTarget->GetMemoryDC(); } /****************************************************************** * * * GdiTextRenderer::Initialize * * * * Create a bitmap (DIB) render target and setup default rendering * * parameters. * * * ******************************************************************/ HRESULT GdiTextRenderer::Initialize(HWND referenceHwnd, HDC referenceDC, UINT width, UINT height) { HRESULT hr; IDWriteGdiInterop* gdiInterop = nullptr; hr = g_dwrite->GetGdiInterop(&gdiInterop); if (SUCCEEDED(hr)) { hr = gdiInterop->CreateBitmapRenderTarget(referenceDC, width, height, &m_renderTarget); } if (SUCCEEDED(hr)) { hr = g_dwrite->CreateMonitorRenderingParams( MonitorFromWindow(referenceHwnd, MONITOR_DEFAULTTONULL), &m_renderingParams); } SafeRelease(&gdiInterop); return hr; } /****************************************************************** * * * GdiTextRenderer::DrawGlyphRun * * * * Defer to IDWriteBitmapRenderTarget to draw a series of glyphs. * * * ******************************************************************/ HRESULT STDMETHODCALLTYPE GdiTextRenderer::DrawGlyphRun( void* /* clientDrawingContext */, FLOAT baselineOriginX, FLOAT baselineOriginY, DWRITE_MEASURING_MODE measuringMode, DWRITE_GLYPH_RUN const* glyphRun, DWRITE_GLYPH_RUN_DESCRIPTION const* /* glyphRunDescription */, IUnknown* /* clientDrawingEffect */) { m_renderTarget->DrawGlyphRun( baselineOriginX, baselineOriginY, measuringMode, glyphRun, m_renderingParams, GetSysColor(COLOR_BTNTEXT)); return S_OK; } /****************************************************************** * * * GdiTextRenderer::DrawUnderline * * * * This sample does not draw underlines. * * * ******************************************************************/ HRESULT STDMETHODCALLTYPE GdiTextRenderer::DrawUnderline( void* /* clientDrawingContext */, FLOAT /* baselineOriginX */, FLOAT /* baselineOriginY */, DWRITE_UNDERLINE const* /* underline */, IUnknown* /* clientDrawingEffect */) { return S_OK; } /****************************************************************** * * * GdiTextRenderer::DrawStrikethrough * * * * This sample does not draw strikethroughs * * * ******************************************************************/ HRESULT STDMETHODCALLTYPE GdiTextRenderer::DrawStrikethrough( void* /* clientDrawingContext */, FLOAT /* baselineOriginX */, FLOAT /* baselineOriginY */, DWRITE_STRIKETHROUGH const* /* strikethrough */, IUnknown* /* clientDrawingEffect */) { return S_OK; } /****************************************************************** * * * GdiTextRenderer::DrawInlineObject * * * * This sample does not use inline objects. * * * ******************************************************************/ HRESULT STDMETHODCALLTYPE GdiTextRenderer::DrawInlineObject( void* /* clientDrawingContext */, FLOAT /* originX */, FLOAT /* originY */, IDWriteInlineObject* /* inlineObject */, BOOL /* isSideways */, BOOL /* isRightToLeft */, IUnknown* /* clientDrawingEffect */) { return S_OK; } /****************************************************************** * * * GdiTextRenderer::IsPixelSnapped * * * * Leave pixel snapping on. * * * ******************************************************************/ HRESULT STDMETHODCALLTYPE GdiTextRenderer::IsPixelSnappingDisabled( void* /* clientDrawingContext */, BOOL* isDisabled) { *isDisabled = false; return S_OK; } /****************************************************************** * * * GdiTextRenderer::GetCurrentTransform * * * * This sample does not draw scaled and/or rotated text. * * * ******************************************************************/ HRESULT STDMETHODCALLTYPE GdiTextRenderer::GetCurrentTransform( void* /* clientDrawingContext */, DWRITE_MATRIX* transform) { static const DWRITE_MATRIX identity = {1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }; *transform = identity; return S_OK; } /****************************************************************** * * * GdiTextRenderer::GetPixelsPerDip * * * * Adjust the font size for the underlying DPI of the reference DC * * * ******************************************************************/ HRESULT STDMETHODCALLTYPE GdiTextRenderer::GetPixelsPerDip( void* /* clientDrawingContext */, FLOAT* pixelsPerDip) { *pixelsPerDip = m_renderTarget->GetPixelsPerDip(); return S_OK; } /****************************************************************** * * * GdiTextRenderer::QueryInterface * * * * COM boilerplate * * * ******************************************************************/ HRESULT STDMETHODCALLTYPE GdiTextRenderer::QueryInterface( REFIID riid, void **ppvObject) { *ppvObject = nullptr; if (riid == __uuidof(IDWriteTextRenderer) || riid == __uuidof(IUnknown)) { AddRef(); *ppvObject = this; return S_OK; } return E_NOINTERFACE; } /****************************************************************** * * * GdiTextRenderer::AddRef * * * * COM boilerplate * * ******************************************************************/ ULONG STDMETHODCALLTYPE GdiTextRenderer::AddRef() { return InterlockedIncrement(&m_refs); } /****************************************************************** * * * GdiTextRenderer::Release * * * * COM boilerplate * * * ******************************************************************/ ULONG STDMETHODCALLTYPE GdiTextRenderer::Release() { LONG refs = InterlockedDecrement(&m_refs); if (refs == 0) { delete this; } return refs; } <|start_filename|>scintilla/src/CharacterType.h<|end_filename|> // Scintilla source code edit control /** @file CharacterType.h ** Tests for character type and case-insensitive comparisons. **/ // Copyright 2007 by <NAME> <<EMAIL>> // The License.txt file describes the conditions under which this software may be distributed. #ifndef CHARACTERTYPE_H #define CHARACTERTYPE_H namespace Scintilla::Internal { // Functions for classifying characters /** * Check if a character is a space. * This is ASCII specific but is safe with chars >= 0x80. */ constexpr bool IsASpace(int ch) noexcept { return (ch == ' ') || ((ch >= 0x09) && (ch <= 0x0d)); } constexpr bool IsSpaceOrTab(int ch) noexcept { return (ch == ' ') || (ch == '\t'); } constexpr bool IsControl(int ch) noexcept { return ((ch >= 0) && (ch <= 0x1F)) || (ch == 0x7F); } constexpr bool IsEOLCharacter(int ch) noexcept { return ch == '\r' || ch == '\n'; } constexpr bool IsBreakSpace(int ch) noexcept { // used for text breaking, treat C0 control character as space. // by default C0 control character is handled as special representation, // so not appears in normal text. 0x7F DEL is omitted to simplify the code. return ch >= 0 && ch <= ' '; } constexpr bool IsADigit(int ch) noexcept { return (ch >= '0') && (ch <= '9'); } constexpr bool IsADigit(int ch, int base) noexcept { if (base <= 10) { return (ch >= '0') && (ch < '0' + base); } else { return ((ch >= '0') && (ch <= '9')) || ((ch >= 'A') && (ch < 'A' + base - 10)) || ((ch >= 'a') && (ch < 'a' + base - 10)); } } constexpr bool IsASCII(int ch) noexcept { return (ch >= 0) && (ch < 0x80); } constexpr bool IsLowerCase(int ch) noexcept { return (ch >= 'a') && (ch <= 'z'); } constexpr bool IsUpperCase(int ch) noexcept { return (ch >= 'A') && (ch <= 'Z'); } constexpr bool IsUpperOrLowerCase(int ch) noexcept { return IsUpperCase(ch) || IsLowerCase(ch); } constexpr bool IsAlphaNumeric(int ch) noexcept { return ((ch >= '0') && (ch <= '9')) || ((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z')); } constexpr bool IsPunctuation(int ch) noexcept { switch (ch) { case '!': case '"': case '#': case '$': case '%': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case '[': case '\\': case ']': case '^': case '_': case '`': case '{': case '|': case '}': case '~': return true; default: return false; } } // Simple case functions for ASCII supersets. template <typename T> constexpr T MakeUpperCase(T ch) noexcept { if (ch < 'a' || ch > 'z') return ch; else return ch - 'a' + 'A'; } template <typename T> constexpr T MakeLowerCase(T ch) noexcept { if (ch < 'A' || ch > 'Z') return ch; else return ch - 'A' + 'a'; } int CompareCaseInsensitive(const char *a, const char *b) noexcept; int CompareNCaseInsensitive(const char *a, const char *b, size_t len) noexcept; } #endif <|start_filename|>grepWinNP3/sktoolslib_mod/Registry.cpp<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012, 2017, 2020-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "registry.h" ////////////////////////////////////////////////////////////////////////////////////////////// #ifdef __CSTRINGT_H__ CRegBase::CRegBase() { } CRegBase::CRegBase(const CString& key, bool force, HKEY base, REGSAM sam) : CRegBaseCommon<CString>(key, force, base, sam) { m_key.TrimLeft(L"\\"); int backslashpos = m_key.ReverseFind('\\'); m_path = m_key.Left(backslashpos); m_path.TrimRight(L"\\"); m_key = m_key.Mid(backslashpos); m_key.Trim(L"\\"); } #endif ////////////////////////////////////////////////////////////////////////////////////////////// CRegStdBase::CRegStdBase() { } CRegStdBase::CRegStdBase(const std::wstring& key, bool force, HKEY base, REGSAM sam) : CRegBaseCommon<std::wstring>(key, force, base, sam) { std::wstring::size_type pos = key.find_last_of(L'\\'); m_path = key.substr(0, pos); m_key = key.substr(pos + 1); } ////////////////////////////////////////////////////////////////////////////////////////////// #ifdef __ATLTYPES_H__ // defines CRect CRegRect::CRegRect(void) : CRegTypedBase<CRect, CRegBase>(CRect(0, 0, 0, 0)) { } CRegRect::CRegRect(const CString& key, const CRect& def, bool force, HKEY base, REGSAM sam) : CRegTypedBase<CRect, CRegBase>(key, def, force, base, sam) { read(); } void CRegRect::InternalRead(HKEY hKey, CRect& value) { DWORD size = 0; DWORD type = 0; m_lastError = RegQueryValueEx(hKey, m_key, NULL, &type, nullptr, (LPDWORD)&size); if (m_lastError == ERROR_SUCCESS) { auto buffer = std::make_unique<char[]>(size); if ((m_lastError = RegQueryValueEx(hKey, m_key, nullptr, &type, (BYTE*)buffer.get(), &size)) == ERROR_SUCCESS) { ASSERT(type == REG_BINARY); value = CRect((LPRECT)buffer.get()); } } } void CRegRect::InternalWrite(HKEY hKey, const CRect& value) { m_lastError = RegSetValueEx(hKey, m_key, 0, REG_BINARY, (BYTE*)(LPCRECT)value, sizeof(value)); } #endif ////////////////////////////////////////////////////////////////////////////////////////////// #ifdef __ATLTYPES_H__ // defines CPoint CRegPoint::CRegPoint(void) : CRegTypedBase<CPoint, CRegBase>(CPoint(0, 0)) { } CRegPoint::CRegPoint(const CString& key, const CPoint& def, bool force, HKEY base, REGSAM sam) : CRegTypedBase<CPoint, CRegBase>(key, def, force, base, sam) { read(); } void CRegPoint::InternalRead(HKEY hKey, CPoint& value) { DWORD size = 0; DWORD type = 0; m_lastError = RegQueryValueEx(hKey, m_key, nullptr, &type, nullptr, (LPDWORD)&size); if (m_lastError == ERROR_SUCCESS) { auto buffer = std::make_unique<char[]>(size); if ((m_lastError = RegQueryValueEx(hKey, m_key, nullptr, &type, (BYTE*)buffer.get(), &size)) == ERROR_SUCCESS) { ASSERT(type == REG_BINARY); value = CPoint(*(POINT*)buffer.get()); } } } void CRegPoint::InternalWrite(HKEY hKey, const CPoint& value) { m_lastError = RegSetValueEx(hKey, m_key, 0, REG_BINARY, (BYTE*)&value, sizeof(value)); } #endif ///////////////////////////////////////////////////////////////////// #ifdef __AFXCOLL_H__ // defines CStringList CRegistryKey::CRegistryKey(const CString& key, HKEY base, REGSAM sam) { m_base = base; m_hKey = nullptr; m_sam = sam; m_path = key; m_path.TrimLeft(L"\\"); } CRegistryKey::~CRegistryKey() { if (m_hKey) RegCloseKey(m_hKey); } DWORD CRegistryKey::createKey() { DWORD disp; DWORD rc = RegCreateKeyEx(m_base, m_path, 0, L"", REG_OPTION_NON_VOLATILE, KEY_WRITE | m_sam, nullptr, &m_hKey, &disp); if (rc != ERROR_SUCCESS) { return rc; } return RegCloseKey(m_hKey); } DWORD CRegistryKey::removeKey() { RegOpenKeyEx(m_base, m_path, 0, KEY_WRITE | m_sam, &m_hKey); return SHDeleteKey(m_base, (LPCWSTR)m_path); } bool CRegistryKey::getValues(CStringList& values) { values.RemoveAll(); if (RegOpenKeyEx(m_base, m_path, 0, KEY_EXECUTE | m_sam, &m_hKey) == ERROR_SUCCESS) { for (int i = 0, rc = ERROR_SUCCESS; rc == ERROR_SUCCESS; i++) { wchar_t value[255]; DWORD size = _countof(value); rc = RegEnumValue(m_hKey, i, value, &size, nullptr, nullptr, nullptr, nullptr); if (rc == ERROR_SUCCESS) { values.AddTail(value); } } } return values.GetCount() > 0; } bool CRegistryKey::getSubKeys(CStringList& subkeys) { subkeys.RemoveAll(); if (RegOpenKeyEx(m_base, m_path, 0, KEY_EXECUTE | m_sam, &m_hKey) == ERROR_SUCCESS) { for (int i = 0, rc = ERROR_SUCCESS; rc == ERROR_SUCCESS; i++) { wchar_t value[1024]; DWORD size = _countof(value); FILETIME last_write_time; rc = RegEnumKeyEx(m_hKey, i, value, &size, nullptr, nullptr, nullptr, &last_write_time); if (rc == ERROR_SUCCESS) { subkeys.AddTail(value); } } } return subkeys.GetCount() > 0; } #endif <|start_filename|>grepWinNP3/src/ShellContextMenu.h<|end_filename|> // grepWin - regex search and replace for Windows // Copyright (C) 2007-2008, 2011-2015, 2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #pragma once #include <vector> #include <shobjidl.h> #include <shlobj.h> // ReSharper disable once CppInconsistentNaming class CIShellFolderHook; class CSearchInfo; struct LineData; class CShellContextMenu { public: void SetObjects(const std::vector<CSearchInfo> &strVector, const std::vector<LineData> &lineVector); UINT ShowContextMenu(HWND hWnd, POINT pt); CShellContextMenu(); virtual ~CShellContextMenu(); private: size_t m_nItems; BOOL bDelete; HMENU m_menu; IShellFolder * m_psfFolder; LPITEMIDLIST * m_pidlArray; int m_pidlArrayItems; std::vector<CSearchInfo> m_strVector; std::vector<LineData> m_lineVector; static void InvokeCommand(LPCONTEXTMENU pContextMenu, UINT idCommand); BOOL GetContextMenu(HWND hWnd, void **ppContextMenu, int &iMenuType); static LRESULT CALLBACK HookWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); static void FreePIDLArray(LPITEMIDLIST *pidlArray, int nItems); static HRESULT CALLBACK dfmCallback(IShellFolder *psf, HWND hwnd, IDataObject *pdtobj, UINT uMsg, WPARAM wParam, LPARAM lParam); CIShellFolderHook *m_pFolderHook; friend class CIShellFolderHook; }; // ReSharper disable once CppInconsistentNaming class CIShellFolderHook : public IShellFolder { public: CIShellFolderHook(LPSHELLFOLDER sf, CShellContextMenu *pShellContextMenu) { sf->AddRef(); m_iSf = sf; m_pShellContextMenu = pShellContextMenu; } virtual ~CIShellFolderHook() { m_iSf->Release(); } // IUnknown methods -------- HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, __RPC__deref_out void **ppvObject) override { return m_iSf->QueryInterface(riid, ppvObject); } ULONG STDMETHODCALLTYPE AddRef() override { return m_iSf->AddRef(); } ULONG STDMETHODCALLTYPE Release() override { return m_iSf->Release(); } // IShellFolder methods ---- HRESULT STDMETHODCALLTYPE GetUIObjectOf(HWND hwndOwner, UINT cidl, LPCITEMIDLIST *apidl, REFIID riid, UINT *rgfReserved, void **ppv) override; HRESULT STDMETHODCALLTYPE CompareIDs(LPARAM lParam, __RPC__in PCUIDLIST_RELATIVE pidl1, __RPC__in PCUIDLIST_RELATIVE pidl2) override { return m_iSf->CompareIDs(lParam, pidl1, pidl2); } HRESULT STDMETHODCALLTYPE GetDisplayNameOf(__RPC__in_opt PCUITEMID_CHILD pidl, SHGDNF uFlags, __RPC__out STRRET *pName) override { return m_iSf->GetDisplayNameOf(pidl, uFlags, pName); } HRESULT STDMETHODCALLTYPE CreateViewObject(__RPC__in_opt HWND hwndOwner, __RPC__in REFIID riid, __RPC__deref_out_opt void **ppv) override { return m_iSf->CreateViewObject(hwndOwner, riid, ppv); } HRESULT STDMETHODCALLTYPE EnumObjects(__RPC__in_opt HWND hwndOwner, SHCONTF grfFlags, __RPC__deref_out_opt IEnumIDList **ppenumIDList) override { return m_iSf->EnumObjects(hwndOwner, grfFlags, ppenumIDList); } HRESULT STDMETHODCALLTYPE BindToObject(__RPC__in PCUIDLIST_RELATIVE pidl, __RPC__in_opt IBindCtx *pbc, __RPC__in REFIID riid, __RPC__deref_out_opt void **ppv) override { return m_iSf->BindToObject(pidl, pbc, riid, ppv); } HRESULT STDMETHODCALLTYPE ParseDisplayName(__RPC__in_opt HWND hwnd, __RPC__in_opt IBindCtx *pbc, __RPC__in_string LPWSTR pszDisplayName, __reserved ULONG *pchEaten, __RPC__deref_out_opt PIDLIST_RELATIVE *ppidl, __RPC__inout_opt ULONG *pdwAttributes) override { return m_iSf->ParseDisplayName(hwnd, pbc, pszDisplayName, pchEaten, ppidl, pdwAttributes); } HRESULT STDMETHODCALLTYPE GetAttributesOf(UINT cidl, __RPC__in_ecount_full_opt(cidl) PCUITEMID_CHILD_ARRAY apidl, __RPC__inout SFGAOF *rgfInOut) override { return m_iSf->GetAttributesOf(cidl, apidl, rgfInOut); } HRESULT STDMETHODCALLTYPE BindToStorage(__RPC__in PCUIDLIST_RELATIVE pidl, __RPC__in_opt IBindCtx *pbc, __RPC__in REFIID riid, __RPC__deref_out_opt void **ppv) override { return m_iSf->BindToStorage(pidl, pbc, riid, ppv); } HRESULT STDMETHODCALLTYPE SetNameOf(__in_opt HWND hwnd, __in PCUITEMID_CHILD pidl, __in LPCWSTR pszName, __in SHGDNF uFlags, __deref_opt_out PITEMID_CHILD *ppidlOut) override { return m_iSf->SetNameOf(hwnd, pidl, pszName, uFlags, ppidlOut); } protected: LPSHELLFOLDER m_iSf; CShellContextMenu *m_pShellContextMenu; }; <|start_filename|>grepWinNP3/sktoolslib_mod/BaseWindow.cpp<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012-2013, 2015-2018, 2020-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "BaseWindow.h" #include <memory> #include <Shlwapi.h> #pragma comment(lib, "shlwapi.lib") bool CWindow::RegisterWindow(UINT style, HICON hIcon, HCURSOR hCursor, HBRUSH hbrBackground, LPCWSTR lpszMenuName, LPCWSTR lpszClassName, HICON hIconSm) { WNDCLASSEX wcx; // Fill in the window class structure with default parameters wcx.cbSize = sizeof(WNDCLASSEX); // size of structure wcx.style = style; // redraw if size changes wcx.lpfnWndProc = CWindow::stWinMsgHandler; // points to window procedure wcx.cbClsExtra = 0; // no extra class memory wcx.cbWndExtra = 0; // no extra window memory wcx.hInstance = hResource; // handle to instance wcx.hIcon = hIcon; // predefined app. icon wcx.hCursor = hCursor; // predefined arrow wcx.hbrBackground = hbrBackground; // white background brush wcx.lpszMenuName = lpszMenuName; // name of menu resource wcx.lpszClassName = lpszClassName; // name of window class wcx.hIconSm = hIconSm; // small class icon // Register the window class. return RegisterWindow(&wcx); } bool CWindow::RegisterWindow(CONST WNDCLASSEX* wcx) { // Register the window class. sClassName = std::wstring(wcx->lpszClassName); bRegisterWindowCalled = true; if (RegisterClassEx(wcx) == 0) { if (GetLastError() == ERROR_CLASS_ALREADY_EXISTS) return TRUE; return FALSE; } else return TRUE; } LRESULT CALLBACK CWindow::stWinMsgHandler(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { if (uMsg == WM_NCCREATE) { // get the pointer to the window from lpCreateParams which was set in CreateWindow SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(reinterpret_cast<LPCREATESTRUCT>(lParam)->lpCreateParams)); } // get the pointer to the window CWindow* pWnd = GetObjectFromWindow(hwnd); // if we have the pointer, go to the message handler of the window // else, use DefWindowProc if (pWnd) { switch (uMsg) { case WM_CREATE: if ((!pWnd->bWindowRestored) && (!pWnd->sRegistryPath.empty())) { WINDOWPLACEMENT wpl = {0}; DWORD size = sizeof(wpl); if (SHGetValue(HKEY_CURRENT_USER, pWnd->sRegistryPath.c_str(), pWnd->sRegistryValue.c_str(), REG_NONE, &wpl, &size) == ERROR_SUCCESS) SetWindowPlacement(hwnd, &wpl); else ShowWindow(hwnd, SW_SHOW); pWnd->bWindowRestored = true; } break; case WM_CLOSE: if (!pWnd->sRegistryPath.empty()) { WINDOWPLACEMENT wpl = {0}; wpl.length = sizeof(WINDOWPLACEMENT); GetWindowPlacement(hwnd, &wpl); SHSetValue(HKEY_CURRENT_USER, pWnd->sRegistryPath.c_str(), pWnd->sRegistryValue.c_str(), REG_NONE, &wpl, sizeof(wpl)); } break; } return pWnd->WinMsgHandler(hwnd, uMsg, wParam, lParam); } else return DefWindowProc(hwnd, uMsg, wParam, lParam); } bool CWindow::Create() { // Create the window RECT rect; rect.top = 0; rect.left = 0; rect.right = 600; rect.bottom = 400; return Create(WS_OVERLAPPEDWINDOW | WS_VISIBLE, nullptr, &rect); } bool CWindow::Create(DWORD dwStyles, HWND hParent /* = nullptr */, RECT* rect /* = nullptr */) { return CreateEx(0, dwStyles, hParent, rect); } bool CWindow::CreateEx(DWORD dwExStyles, DWORD dwStyles, HWND hParent /* = nullptr */, RECT* rect /* = nullptr */, LPCWSTR classname /* = nullptr */, HMENU hMenu /* = nullptr */) { // send the this pointer as the window creation parameter if (rect == nullptr) m_hwnd = CreateWindowEx(dwExStyles, classname ? classname : sClassName.c_str(), sWindowTitle.c_str(), dwStyles, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, hParent, hMenu, hResource, static_cast<void*>(this)); else { m_hwnd = CreateWindowEx(dwExStyles, classname ? classname : sClassName.c_str(), sWindowTitle.c_str(), dwStyles, rect->left, rect->top, rect->right - rect->left, rect->bottom - rect->top, hParent, hMenu, hResource, static_cast<void*>(this)); } m_hParent = hParent; if (!bRegisterWindowCalled) { ::SetWindowLongPtr(m_hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this)); prevWndProc = reinterpret_cast<WNDPROC>(GetWindowLongPtr(m_hwnd, GWLP_WNDPROC)); ::SetWindowLongPtr(m_hwnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(stWinMsgHandler)); } return (m_hwnd != nullptr); } void CWindow::SetTransparency(BYTE alpha, COLORREF color /* = 0xFF000000 */) { if (alpha == 255) { LONG_PTR exStyle = GetWindowLongPtr(*this, GWL_EXSTYLE); exStyle &= ~WS_EX_LAYERED; SetWindowLongPtr(*this, GWL_EXSTYLE, exStyle); } else { LONG_PTR exStyle = GetWindowLongPtr(*this, GWL_EXSTYLE); exStyle |= WS_EX_LAYERED; SetWindowLongPtr(*this, GWL_EXSTYLE, exStyle); } COLORREF col = color; DWORD flags = LWA_ALPHA; if (col & 0xFF000000) { col = RGB(255, 255, 255); flags = LWA_ALPHA; } else { flags = LWA_COLORKEY; } SetLayeredWindowAttributes(*this, col, alpha, flags); } <|start_filename|>src/StyleLexers/styleLexYAML.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_YAML = { "false n no off on true y yes", NULL, }; EDITLEXER lexYAML = { SCLEX_YAML, "yaml", IDS_LEX_YAML, L"YAML", L"yaml; yml", L"", &KeyWords_YAML, { { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_YAML_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {SCE_YAML_COMMENT}, IDS_LEX_STR_63127, L"Comment", L"fore:#008800", L"" }, { {SCE_YAML_IDENTIFIER}, IDS_LEX_STR_63129, L"Identifier", L"bold; fore:#0A246A", L"" }, { {SCE_YAML_KEYWORD}, IDS_LEX_STR_63128, L"Keyword", L"fore:#880088", L"" }, { {SCE_YAML_NUMBER}, IDS_LEX_STR_63130, L"Number", L"fore:#FF8000", L"" }, { {SCE_YAML_REFERENCE}, IDS_LEX_STR_63333, L"Reference", L"fore:#008888", L"" }, { {SCE_YAML_DOCUMENT}, IDS_LEX_STR_63334, L"Document", L"bold; fore:#FFFFFF; back:#000088; eolfilled", L"" }, { {SCE_YAML_TEXT}, IDS_LEX_STR_63335, L"Text", L"fore:#404040", L"" }, { {SCE_YAML_ERROR}, IDS_LEX_STR_63261, L"Error", L"bold; italic; fore:#FFFFFF; back:#FF0000; eolfilled", L"" }, { {SCE_YAML_OPERATOR}, IDS_LEX_STR_63132, L"Operator", L"fore:#333366", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>grepWinNP3/sktoolslib_mod/Language.cpp<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2013, 2017-2018, 2020-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "Language.h" #include "StringUtils.h" #include "UnicodeUtils.h" #include <Commctrl.h> #include <Shlwapi.h> #include <fstream> #include <vector> #include <algorithm> #include <cctype> #include <memory> #include <functional> #define MAX_STRING_LENGTH (64 * 1024) bool CLanguage::LoadFile(const std::wstring& path) { static std::wstring lastLangPath; // revert to original language if (_wcsicmp(lastLangPath.c_str(), path.c_str())) { std::map<std::wstring, std::wstring> langMap2; for (auto it = langmap.cbegin(); it != langmap.cend(); ++it) { langMap2[it->second] = it->first; } langmap = langMap2; } if (!PathFileExists(path.c_str())) return false; lastLangPath = path; // since stream classes still expect the filepath in char and not wchar_t // we need to convert the filepath to multibyte first std::ifstream file; try { } catch (std::ios_base::failure&) { return false; } file.open(path); if (!file.good()) { return false; } auto line = std::make_unique<char[]>(2 * MAX_STRING_LENGTH); std::vector<std::wstring> entry; do { file.getline(line.get(), 2 * MAX_STRING_LENGTH); if (line.get()[0] == 0) { //empty line means end of entry! std::wstring msgId; std::wstring msgStr; int type = 0; for (auto I = entry.begin(); I != entry.end(); ++I) { if (wcsncmp(I->c_str(), L"# ", 2) == 0) { //user comment type = 0; } if (wcsncmp(I->c_str(), L"#.", 2) == 0) { //automatic comments type = 0; } if (wcsncmp(I->c_str(), L"#,", 2) == 0) { //flag type = 0; } if (wcsncmp(I->c_str(), L"msgid", 5) == 0) { //message id msgId = I->c_str(); msgId = std::wstring(msgId.substr(7, msgId.size() - 8)); std::wstring s = msgId; s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](wint_t c) { return !iswspace(c); })); type = 1; } if (wcsncmp(I->c_str(), L"msgstr", 6) == 0) { //message string msgStr = I->c_str(); msgStr = msgStr.substr(8, msgStr.length() - 9); type = 2; } if (wcsncmp(I->c_str(), L"\"", 1) == 0) { if (type == 1) { std::wstring temp = I->c_str(); temp = temp.substr(1, temp.length() - 2); msgId += temp; } if (type == 2) { std::wstring temp = I->c_str(); temp = temp.substr(1, temp.length() - 2); msgStr += temp; } } } entry.clear(); SearchReplace(msgId, L"\\\"", L"\""); SearchReplace(msgId, L"\\n", L"\n"); SearchReplace(msgId, L"\\r", L"\r"); SearchReplace(msgId, L"\\\\", L"\\"); SearchReplace(msgStr, L"\\\"", L"\""); SearchReplace(msgStr, L"\\n", L"\n"); SearchReplace(msgStr, L"\\r", L"\r"); SearchReplace(msgStr, L"\\\\", L"\\"); if (!msgId.empty() && !msgStr.empty()) langmap[msgId] = msgStr; msgId.clear(); msgStr.clear(); } else { //~entry.push_back(CUnicodeUtils::StdGetUnicode(line.get())); entry.push_back(UTF8ToWide(line.get())); } } while (file.gcount() > 0); file.close(); return true; } std::wstring CLanguage::GetTranslatedString(const std::wstring& s) { return GetTranslatedString(s, &langmap); } std::wstring CLanguage::GetTranslatedString(const std::wstring& s, std::map<std::wstring, std::wstring>* pLangMap) { auto foundIt = pLangMap->find(s); if ((foundIt != pLangMap->end()) && (!foundIt->second.empty())) return foundIt->second; return s; } void CLanguage::TranslateWindow(HWND hWnd) { // iterate over all windows and replace their // texts with the translation TranslateWindowProc(hWnd, reinterpret_cast<LPARAM>(&langmap)); EnumChildWindows(hWnd, TranslateWindowProc, reinterpret_cast<LPARAM>(&langmap)); EnumThreadWindows(GetCurrentThreadId(), TranslateWindowProc, reinterpret_cast<LPARAM>(&langmap)); HMENU hSysMenu = GetSystemMenu(hWnd, FALSE); if (hSysMenu) { TranslateMenu(hSysMenu); } } void CLanguage::TranslateMenu(HMENU hMenu) { auto count = GetMenuItemCount(hMenu); for (int i = 0; i < count; ++i) { MENUITEMINFO mii = {0}; mii.cbSize = sizeof(MENUITEMINFO); mii.fMask = MIIM_STRING | MIIM_SUBMENU; mii.dwTypeData = nullptr; if (GetMenuItemInfo(hMenu, i, MF_BYPOSITION, &mii)) { if (mii.hSubMenu) TranslateMenu(mii.hSubMenu); if (mii.cch) { ++mii.cch; auto textBuf = std::make_unique<wchar_t[]>(mii.cch + 1); mii.dwTypeData = textBuf.get(); if (GetMenuItemInfo(hMenu, i, MF_BYPOSITION, &mii)) { auto translated = GetTranslatedString(textBuf.get()); mii.fMask = MIIM_STRING; mii.dwTypeData = const_cast<wchar_t*>(translated.c_str()); SetMenuItemInfo(hMenu, i, MF_BYPOSITION, &mii); } } } } } BOOL CALLBACK CLanguage::TranslateWindowProc(HWND hwnd, LPARAM lParam) { std::map<std::wstring, std::wstring>* pLangMap = reinterpret_cast<std::map<std::wstring, std::wstring>*>(lParam); int length = GetWindowTextLength(hwnd); auto text = std::make_unique<wchar_t[]>(length + 1); std::wstring translatedString; if (GetWindowText(hwnd, text.get(), length + 1)) { translatedString = GetTranslatedString(text.get(), pLangMap); SetWindowText(hwnd, translatedString.c_str()); } wchar_t className[1024] = {0}; if (GetClassName(hwnd, className, _countof(className))) { if ((wcscmp(className, WC_COMBOBOX) == 0) || (wcscmp(className, WC_COMBOBOXEX) == 0)) { // translate the items in the combobox int nSel = static_cast<int>(SendMessage(hwnd, CB_GETCURSEL, 0, 0)); int nCount = static_cast<int>(SendMessage(hwnd, CB_GETCOUNT, 0, 0)); for (int i = 0; i < nCount; ++i) { length = static_cast<int>(SendMessage(hwnd, CB_GETLBTEXTLEN, i, 0)); auto buf = std::make_unique<wchar_t[]>(length + 1); SendMessage(hwnd, CB_GETLBTEXT, i, reinterpret_cast<LPARAM>(buf.get())); std::wstring sTranslated = GetTranslatedString(buf.get(), pLangMap); SendMessage(hwnd, CB_INSERTSTRING, i, reinterpret_cast<LPARAM>(sTranslated.c_str())); SendMessage(hwnd, CB_DELETESTRING, i + 1, 0); } SendMessage(hwnd, CB_SETCURSEL, nSel, 0); } else if (wcscmp(className, WC_BUTTON) == 0) { LONG_PTR style = GetWindowLongPtr(hwnd, GWL_STYLE); if (((style & BS_GROUPBOX) == 0) && ((style & BS_CHECKBOX) || (style & BS_AUTORADIOBUTTON) || (style & BS_RADIOBUTTON))) { // adjust the width of checkbox and radio buttons HDC hDC = GetWindowDC(hwnd); RECT controlRect; RECT controlRectOrig; GetWindowRect(hwnd, &controlRect); ::MapWindowPoints(nullptr, GetParent(hwnd), reinterpret_cast<LPPOINT>(&controlRect), 2); controlRectOrig = controlRect; if (hDC) { HFONT hFont = GetWindowFont(hwnd); HGDIOBJ hOldFont = ::SelectObject(hDC, hFont); if (DrawText(hDC, translatedString.c_str(), -1, &controlRect, DT_WORDBREAK | DT_EDITCONTROL | DT_EXPANDTABS | DT_LEFT | DT_CALCRECT)) { // now we have the rectangle the control really needs if ((controlRectOrig.right - controlRectOrig.left) > (controlRect.right - controlRect.left)) { // we're dealing with radio buttons and check boxes, // which means we have to add a little space for the checkbox // the value of 3 pixels added here is necessary in case certain visual styles have // been disabled. Without this, the width is calculated too short. const int checkWidth = GetSystemMetrics(SM_CXMENUCHECK) + 2 * GetSystemMetrics(SM_CXEDGE) + 3; controlRectOrig.right = controlRectOrig.left + (controlRect.right - controlRect.left) + checkWidth; MoveWindow(hwnd, controlRectOrig.left, controlRectOrig.top, controlRectOrig.right - controlRectOrig.left, controlRectOrig.bottom - controlRectOrig.top, TRUE); } } SelectObject(hDC, hOldFont); ReleaseDC(hwnd, hDC); } } } else if (wcscmp(className, WC_HEADER) == 0) { // translate column headers in list and other controls int nCount = Header_GetItemCount(hwnd); auto buf = std::make_unique<wchar_t[]>(270); for (int i = 0; i < nCount; ++i) { HDITEM hdi = {0}; hdi.mask = HDI_TEXT; hdi.pszText = buf.get(); hdi.cchTextMax = 270; Header_GetItem(hwnd, i, &hdi); std::wstring sTranslated = GetTranslatedString(buf.get(), pLangMap); hdi.pszText = const_cast<LPWSTR>(sTranslated.c_str()); Header_SetItem(hwnd, i, &hdi); } } else if (wcscmp(className, WC_EDIT) == 0) { // translate hint texts in edit controls const int bufCount = 4096; auto buf = std::make_unique<wchar_t[]>(bufCount); SecureZeroMemory(buf.get(), bufCount * sizeof(wchar_t)); Edit_GetCueBannerText(hwnd, buf.get(), bufCount); auto sTranslated = GetTranslatedString(buf.get(), pLangMap); Edit_SetCueBannerText(hwnd, buf.get()); } else if (wcscmp(className, TOOLTIPS_CLASS) == 0) { const int bufCount = 4096; auto buf = std::make_unique<wchar_t[]>(bufCount); auto toolCount = static_cast<int>(SendMessage(hwnd, TTM_GETTOOLCOUNT, 0, 0)); for (int i = 0; i < toolCount; ++i) { SecureZeroMemory(buf.get(), bufCount * sizeof(wchar_t)); TOOLINFO tt = {0}; tt.cbSize = sizeof(TOOLINFO); tt.lpszText = buf.get(); SendMessage(hwnd, TTM_ENUMTOOLS, i, reinterpret_cast<LPARAM>(&tt)); auto sTranslated = GetTranslatedString(buf.get(), pLangMap); tt.lpszText = sTranslated.data(); if (tt.lpszText[0]) SendMessage(hwnd, TTM_SETTOOLINFO, 0, reinterpret_cast<LPARAM>(&tt)); } } } return TRUE; } CLanguage& CLanguage::Instance() { static CLanguage instance; return instance; } <|start_filename|>grepWinNP3/sktoolslib_mod/TextFile.cpp<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012, 2014, 2017-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "TextFile.h" #include "PathUtils.h" #include "maxpath.h" #include <memory> static wchar_t WideCharSwap(wchar_t nValue) { return (((nValue >> 8)) | (nValue << 8)); } static UINT64 WordSwapBytes(UINT64 nValue) { return ((nValue & 0xff00ff00ff00ff) << 8) | ((nValue >> 8) & 0xff00ff00ff00ff); // swap BYTESs in WORDs } CTextFile::CTextFile() : pFileBuf(nullptr) , fileLen(0) , encoding(AutoType) , hasBOM(false) , nullByteCount(2) { } CTextFile::~CTextFile() { pFileBuf = nullptr; } bool CTextFile::Save(LPCWSTR path) const { if (pFileBuf == nullptr) return false; HANDLE hFile = CreateFile(path, GENERIC_WRITE, FILE_SHARE_READ, nullptr, CREATE_ALWAYS, FILE_FLAG_SEQUENTIAL_SCAN, nullptr); if (hFile == INVALID_HANDLE_VALUE) return false; DWORD byteswritten; if (!WriteFile(hFile, pFileBuf.get(), fileLen, &byteswritten, nullptr)) { CloseHandle(hFile); return false; } CloseHandle(hFile); return true; } bool CTextFile::Load(LPCWSTR path, UnicodeType &type, bool bUTF8, volatile LONG *bCancelled) { encoding = AutoType; type = AutoType; LARGE_INTEGER lint; pFileBuf = nullptr; auto pathBuf = std::make_unique<wchar_t[]>(MAX_PATH_NEW); HANDLE hFile = INVALID_HANDLE_VALUE; int retryCounter = 0; if ((wcslen(path) > 2) && (path[0] == '\\') && (path[1] == '\\')) { // UNC path wcscpy_s(pathBuf.get(), MAX_PATH_NEW, L"\\\\?\\UNC"); wcscat_s(pathBuf.get(), MAX_PATH_NEW, &path[1]); } else { // 'normal' path wcscpy_s(pathBuf.get(), MAX_PATH_NEW, L"\\\\?\\"); wcscat_s(pathBuf.get(), MAX_PATH_NEW, path); } do { if (retryCounter) Sleep(20 + retryCounter * 50); hFile = CreateFile(pathBuf.get(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr); retryCounter++; } while (hFile == INVALID_HANDLE_VALUE && retryCounter < 5); if (hFile == INVALID_HANDLE_VALUE) return false; std::wstring wPath(path); size_t pos = wPath.find_last_of('\\'); filename = wPath.substr(pos + 1); if (!GetFileSizeEx(hFile, &lint)) { CloseHandle(hFile); return false; } MEMORYSTATUSEX memEx = {sizeof(MEMORYSTATUSEX)}; GlobalMemoryStatusEx(&memEx); DWORD bytesRead = 0; DWORD bytesToRead = min(lint.LowPart, DWORD(memEx.ullAvailPhys / 4UL)); if (lint.HighPart) bytesToRead = 500000; // read 50kb if the file is too big: we only // need to scan for the file type then. // if there isn't enough RAM available, only load a small part of the file // to do the encoding check. Then only load the full file in case // the encoding is UNICODE_LE since that's the only encoding we have // to convert first to do a proper search with. if (bytesToRead < lint.LowPart) { try { auto tempFileBuf = std::make_unique<BYTE[]>(bytesToRead + 1); if (!ReadFile(hFile, tempFileBuf.get(), bytesToRead, &bytesRead, nullptr)) { CloseHandle(hFile); return false; } encoding = CheckUnicodeType(tempFileBuf.get(), bytesRead); type = encoding; if (lint.HighPart) { CloseHandle(hFile); return false; } switch (encoding) { case Binary: case UTF8: case Ansi: CloseHandle(hFile); return false; default: pFileBuf = std::make_unique<BYTE[]>(lint.LowPart); if (pFileBuf) { for (unsigned long bc = 0; bc < bytesRead; ++bc) { pFileBuf[bc] = tempFileBuf[bc]; } } break; } } catch (const std::exception &) { return false; } } else { try { pFileBuf = std::make_unique<BYTE[]>(lint.LowPart); } catch (const std::exception &) { return false; } } if ((pFileBuf == nullptr) || (!ReadFile(hFile, pFileBuf.get(), lint.LowPart, &bytesRead, nullptr))) { pFileBuf = nullptr; CloseHandle(hFile); return false; } CloseHandle(hFile); fileLen = lint.LowPart; // we have the file read into memory, now we have to find out what // kind of text file we have here. if (encoding == AutoType) { encoding = CheckUnicodeType(pFileBuf.get(), bytesRead); if ((bUTF8) && (encoding != Binary)) encoding = UTF8; } if (encoding == Unicode_Le) { try { if ((bytesRead > 1) && (*static_cast<unsigned char *>(pFileBuf.get()) == 0xFF)) { // remove the BOM textContent.assign((reinterpret_cast<wchar_t *>(pFileBuf.get()) + 1), (bytesRead / sizeof(wchar_t)) - 1); hasBOM = true; } else textContent.assign(reinterpret_cast<wchar_t *>(pFileBuf.get()), bytesRead / sizeof(wchar_t)); } catch (const std::exception &) { return false; } } else if (encoding == Unicode_Be) { // make in place WORD BYTEs swap UINT64 *pQw = reinterpret_cast<UINT64 *>(pFileBuf.get()); int nQwords = bytesRead / 8; for (int nQword = 0; nQword < nQwords; nQword++) pQw[nQword] = WordSwapBytes(pQw[nQword]); wchar_t *pW = reinterpret_cast<wchar_t *>(pQw); int nWords = bytesRead / 2; for (int nWord = nQwords * 4; nWord < nWords; nWord++) pW[nWord] = WideCharSwap(pW[nWord]); try { if ((bytesRead > 1) && (*static_cast<unsigned char *>(pFileBuf.get()) == 0xFF)) { // remove the BOM textContent.assign((reinterpret_cast<wchar_t *>(pFileBuf.get()) + 1), (bytesRead / sizeof(wchar_t)) - 1); hasBOM = true; } else textContent.assign(reinterpret_cast<wchar_t *>(pFileBuf.get()), bytesRead / sizeof(wchar_t)); } catch (const std::exception &) { return false; } } else if ((encoding == UTF8) || ((encoding == Binary) && (bUTF8))) { try { int ret = MultiByteToWideChar(CP_UTF8, 0, reinterpret_cast<LPCSTR>(pFileBuf.get()), bytesRead, nullptr, 0); auto pWideBuf = std::make_unique<wchar_t[]>(ret + 1); int ret2 = MultiByteToWideChar(CP_UTF8, 0, reinterpret_cast<LPCSTR>(pFileBuf.get()), bytesRead, pWideBuf.get(), ret + 1); if (ret2 == ret) { if ((ret > 1) && (*pWideBuf.get() == 0xFEFF)) { // remove the BOM textContent.assign(pWideBuf.get() + 1, ret - 1); hasBOM = true; } else textContent.assign(pWideBuf.get(), ret); } } catch (const std::exception &) { return false; } } else //if (encoding == ANSI) { try { int ret = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, reinterpret_cast<LPCSTR>(pFileBuf.get()), bytesRead, nullptr, 0); auto pWideBuf = std::make_unique<wchar_t[]>(ret + 1); int ret2 = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, reinterpret_cast<LPCSTR>(pFileBuf.get()), bytesRead, pWideBuf.get(), ret + 1); if (ret2 == ret) textContent.assign(pWideBuf.get(), ret); } catch (const std::exception &) { return false; } } type = encoding; if (type == Binary) return true; return CalculateLines(bCancelled); } void CTextFile::SetFileContent(const std::wstring &content) { pFileBuf = nullptr; fileLen = 0; try { if (encoding == Unicode_Le) { if (hasBOM) { pFileBuf = std::make_unique<BYTE[]>((content.size() + 2) * sizeof(wchar_t)); if (pFileBuf) { memcpy(pFileBuf.get(), "\xFF\xFE", sizeof(wchar_t)); memcpy(pFileBuf.get() + 2, content.c_str(), content.size() * sizeof(wchar_t)); fileLen = (static_cast<int>(content.size()) + 1) * sizeof(wchar_t); } } else { pFileBuf = std::make_unique<BYTE[]>(content.size() * sizeof(wchar_t)); if (pFileBuf) { memcpy(pFileBuf.get(), content.c_str(), content.size() * sizeof(wchar_t)); fileLen = static_cast<int>(content.size()) * sizeof(wchar_t); } } } else if (encoding == Unicode_Be) { if (hasBOM) { pFileBuf = std::make_unique<BYTE[]>((content.size() + 2) * sizeof(wchar_t)); if (pFileBuf) { memcpy(pFileBuf.get(), "\xFF\xFE", sizeof(wchar_t)); memcpy(pFileBuf.get() + 2, content.c_str(), content.size() * sizeof(wchar_t)); fileLen = (static_cast<int>(content.size()) + 1) * sizeof(wchar_t); } } else { pFileBuf = std::make_unique<BYTE[]>(content.size() * sizeof(wchar_t)); if (pFileBuf) { memcpy(pFileBuf.get(), content.c_str(), content.size() * sizeof(wchar_t)); fileLen = static_cast<int>(content.size()) * sizeof(wchar_t); } } // make in place WORD BYTEs swap UINT64 *pQw = reinterpret_cast<UINT64 *>(pFileBuf.get()); int nQwords = fileLen / 8; for (int nQword = 0; nQword < nQwords; nQword++) pQw[nQword] = WordSwapBytes(pQw[nQword]); wchar_t *pW = reinterpret_cast<wchar_t *>(pQw); int nWords = fileLen / 2; for (int nWord = nQwords * 4; nWord < nWords; nWord++) pW[nWord] = WideCharSwap(pW[nWord]); } else if (encoding == UTF8) { if (hasBOM) { int ret = WideCharToMultiByte(CP_UTF8, 0, content.c_str(), -1, nullptr, 0, nullptr, nullptr); pFileBuf = std::make_unique<BYTE[]>(ret + 3); if (pFileBuf) { memcpy(pFileBuf.get(), "\xEF\xBB\xBF", 3); int ret2 = WideCharToMultiByte(CP_UTF8, 0, content.c_str(), -1, reinterpret_cast<LPSTR>(pFileBuf.get()) + 3, ret, nullptr, nullptr); fileLen = ret2 + 2; if (ret2 != ret) { pFileBuf = nullptr; fileLen = 0; } } } else { int ret = WideCharToMultiByte(CP_UTF8, 0, content.c_str(), -1, nullptr, 0, nullptr, nullptr); pFileBuf = std::make_unique<BYTE[]>(ret); if (pFileBuf) { int ret2 = WideCharToMultiByte(CP_UTF8, 0, content.c_str(), -1, reinterpret_cast<LPSTR>(pFileBuf.get()), ret, nullptr, nullptr); fileLen = ret2 - 1; if (ret2 != ret) { pFileBuf = nullptr; fileLen = 0; } } } } else if ((encoding == Ansi) || (encoding == Binary)) { int ret = WideCharToMultiByte(CP_ACP, 0, content.c_str(), static_cast<int>(content.size()) + 1, nullptr, 0, nullptr, nullptr); pFileBuf = std::make_unique<BYTE[]>(ret); if (pFileBuf) { int ret2 = WideCharToMultiByte(CP_ACP, 0, content.c_str(), static_cast<int>(content.size()) + 1, reinterpret_cast<LPSTR>(pFileBuf.get()), ret, nullptr, nullptr); fileLen = ret2 - 1; if (ret2 != ret) { pFileBuf = nullptr; fileLen = 0; } } } } catch (const std::exception &) { } if (pFileBuf) textContent = content; else textContent = L""; } bool CTextFile::ContentsModified(std::unique_ptr<BYTE[]> pBuf, DWORD newLen) { pFileBuf = std::move(pBuf); fileLen = newLen; return true; } CTextFile::UnicodeType CTextFile::CheckUnicodeType(BYTE *pBuffer, int cb) const { if (cb < 2) return Ansi; UINT16 *pVal16 = reinterpret_cast<UINT16 *>(pBuffer); UINT8 * pVal8 = reinterpret_cast<UINT8 *>(pVal16 + 1); // scan the whole buffer for a 0x0000 sequence // if found, we assume a binary file int nNull = 0; int nDblNull = 0; for (int i = 0; i < (cb - 2); i = i + 2) { if (0x0000 == *pVal16++) ++nDblNull; if (0x00 == *pVal8++) ++nNull; if (0x00 == *pVal8++) ++nNull; } if (nDblNull > nullByteCount) // configured value: allow double null chars to account for 'broken' text files return Binary; pVal16 = reinterpret_cast<UINT16 *>(pBuffer); pVal8 = reinterpret_cast<UINT8 *>(pVal16 + 1); if (*pVal16 == 0xFEFF) return Unicode_Le; if (*pVal16 == 0xFFFE) return Unicode_Be; if ((nNull > 3) && ((cb % 2) == 0)) // arbitrary value: allow three null chars to account for 'broken' ANSI/UTF8 text files, otherwise consider the file UTF16-LE return Unicode_Le; if (cb < 3) return Ansi; if (*pVal16 == 0xBBEF) { if (*pVal8 == 0xBF) return UTF8; } // check for illegal UTF8 chars pVal8 = static_cast<UINT8 *>(pBuffer); for (int i = 0; i < cb; ++i) { if ((*pVal8 == 0xC0) || (*pVal8 == 0xC1) || (*pVal8 >= 0xF5)) return Ansi; pVal8++; } pVal8 = static_cast<UINT8 *>(pBuffer); bool bUTF8 = false; for (int i = 0; i < (cb - 4); ++i) { if ((*pVal8 & 0xE0) == 0xC0) { pVal8++; i++; if ((*pVal8 & 0xC0) != 0x80) return Ansi; bUTF8 = true; } if ((*pVal8 & 0xF0) == 0xE0) { pVal8++; i++; if ((*pVal8 & 0xC0) != 0x80) return Ansi; pVal8++; i++; if ((*pVal8 & 0xC0) != 0x80) return Ansi; bUTF8 = true; } if ((*pVal8 & 0xF8) == 0xF0) { pVal8++; i++; if ((*pVal8 & 0xC0) != 0x80) return Ansi; pVal8++; i++; if ((*pVal8 & 0xC0) != 0x80) return Ansi; pVal8++; i++; if ((*pVal8 & 0xC0) != 0x80) return Ansi; bUTF8 = true; } pVal8++; } if (bUTF8) return UTF8; return Ansi; } bool CTextFile::CalculateLines(volatile LONG *bCancelled) { // fill an array with starting positions for every line in the loaded file if (pFileBuf == nullptr) return false; if (textContent.empty()) return true; linePositions.clear(); linePositions.reserve(textContent.size() / 10); size_t pos = 0; for (auto it = textContent.begin(); it != textContent.end() && ((bCancelled == nullptr) || !InterlockedExchangeAdd(bCancelled, 0)); ++it) { if (*it == '\r') { ++it; ++pos; if (it != textContent.end()) { if (*it == '\n') { // crlf lineending linePositions.push_back(pos); } else { // cr lineending linePositions.push_back(pos - 1); } } else break; } else if (*it == '\n') { // lf lineending linePositions.push_back(pos); } ++pos; } linePositions.push_back(pos); return true; } long CTextFile::LineFromPosition(long pos) const { auto lb = std::lower_bound(linePositions.begin(), linePositions.end(), static_cast<size_t>(pos)); auto lbLine = lb - linePositions.begin(); return static_cast<long>(lbLine + 1); } std::wstring CTextFile::GetLineString(long lineNumber) const { if ((lineNumber - 2) >= static_cast<long>(linePositions.size())) return std::wstring(); if (lineNumber <= 0) return std::wstring(); long startPos = 0; if (lineNumber > 1) startPos = static_cast<long>(linePositions[lineNumber - 2]) + 1; std::wstring endChars(L"\n\0", 2); size_t endPos = textContent.find_first_of(endChars, startPos); std::wstring line; if (endPos != std::wstring::npos) line = std::wstring(textContent.begin() + startPos, textContent.begin() + endPos); else line = std::wstring(textContent.begin() + startPos, textContent.end()); return line; } std::wstring CTextFile::GetFileNameWithoutExtension() const { return CPathUtils::GetFileNameWithoutExtension(filename); } std::wstring CTextFile::GetFileNameExtension() const { return CPathUtils::GetFileExtension(filename); } <|start_filename|>src/uchardet/uchardet/src/LangModels/LangTurkishModel.cpp<|end_filename|> /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "../nsSBCharSetProber.h" /********* Language model for: Turkish *********/ /** * Generated by BuildLangModel.py * On: 2015-12-04 02:24:44.730727 **/ /* Character Mapping Table: * ILL: illegal character. * CTR: control character specific to the charset. * RET: carriage/return. * SYM: symbol (punctuation) that does not belong to word. * NUM: 0 - 9. * * Other characters are ordered by probabilities * (0 is the most common character in the language). * * Orders are generic to a language. So the codepoint with order X in * CHARSET1 maps to the same character as the codepoint with the same * order X in CHARSET2 for the same language. * As such, it is possible to get missing order. For instance the * ligature of 'o' and 'e' exists in ISO-8859-15 but not in ISO-8859-1 * even though they are both used for French. Same for the euro sign. */ static const unsigned char Iso_8859_3_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 0, 15, 21, 7, 1, 26, 22, 19, 6, 28, 9, 5, 11, 3, 14, /* 4X */ 23, 34, 4, 10, 8, 12, 20, 29, 32, 13, 18,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 0, 15, 21, 7, 1, 26, 22, 19, 2, 28, 9, 5, 11, 3, 14, /* 6X */ 23, 34, 4, 10, 8, 12, 20, 29, 32, 13, 18,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM, 48,SYM,SYM,SYM,ILL, 49,SYM,SYM, 2, 17, 25, 50,SYM,ILL, 51, /* AX */ SYM, 52,SYM,SYM,SYM,SYM, 53,SYM,SYM, 6, 17, 25, 54,SYM,ILL, 55, /* BX */ 41, 36, 30,ILL, 39, 56, 57, 24, 42, 33, 58, 45, 59, 37, 31, 60, /* CX */ ILL, 47, 61, 38, 62, 63, 27,SYM, 64, 65, 40, 35, 16, 66, 67, 68, /* DX */ 41, 36, 30,ILL, 39, 69, 70, 24, 42, 33, 71, 45, 72, 37, 31, 73, /* EX */ ILL, 47, 74, 38, 75, 76, 27,SYM, 77, 78, 40, 35, 16, 79, 80,SYM, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Iso_8859_9_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 0, 15, 21, 7, 1, 26, 22, 19, 6, 28, 9, 5, 11, 3, 14, /* 4X */ 23, 34, 4, 10, 8, 12, 20, 29, 32, 13, 18,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 0, 15, 21, 7, 1, 26, 22, 19, 2, 28, 9, 5, 11, 3, 14, /* 6X */ 23, 34, 4, 10, 8, 12, 20, 29, 32, 13, 18,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM,SYM, 81,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* BX */ 41, 36, 30, 44, 39, 82, 46, 24, 42, 33, 83, 45, 84, 37, 31, 85, /* CX */ 25, 47, 86, 38, 87, 88, 27,SYM, 43, 89, 40, 35, 16, 2, 17, 90, /* DX */ 41, 36, 30, 44, 39, 91, 46, 24, 42, 33, 92, 45, 93, 37, 31, 94, /* EX */ 25, 47, 95, 38, 96, 97, 27,SYM, 43, 98, 40, 35, 16, 6, 17, 99, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ /* Model Table: * Total sequences: 935 * First 512 sequences: 0.991865243864388 * Next 512 sequences (512-1024): 0.008134756135611957 * Rest: 2.949029909160572e-17 * Negative sequences: TODO */ static const PRUint8 TurkishLangModel[] = { 3,2,3,3,3,3,2,3,3,3,3,3,3,3,2,3,0,3,3,3,3,3,3,3,3,3,3,0,3,3,0,2,2,2,2,0, 3,3,3,3,3,3,0,3,3,3,3,3,3,3,3,3,0,3,3,3,3,3,3,3,3,3,3,0,3,3,2,0,3,0,2,0, 3,3,3,3,3,3,0,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,0,2,2,2,0,2,0,2,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,2,3,0,3,2,2,2,2,2,2,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,2,3,2,2,2,2,2,2,2, 3,3,3,2,2,3,3,3,3,3,3,3,3,3,3,3,3,2,2,3,2,3,3,2,3,0,3,2,2,2,2,3,0,2,2,2, 3,2,0,3,3,3,3,3,3,3,3,3,2,3,2,3,0,3,3,2,3,3,2,3,2,3,2,0,0,0,0,0,2,0,0,0, 3,3,3,2,3,3,3,3,2,2,2,2,3,3,3,2,3,0,2,2,2,2,2,2,0,0,0,3,2,3,2,2,0,0,0,0, 3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,0,2,3,3,2,2,2,3,0,2,3,2,2,3,2,2,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,2,2,3,2,2,2,2,3,0,2,3,2,2,3,0,0,0,0,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,2,3,3,3,2,3,3,0,2,3,0,2,2,0,0,2,2,2, 3,3,3,2,3,3,3,3,2,2,3,3,3,3,3,3,3,2,3,3,0,3,2,3,2,0,2,2,0,2,3,2,2,2,2,2, 3,3,3,3,3,3,0,3,3,3,3,3,2,3,2,3,0,3,3,3,3,3,3,3,3,3,2,0,2,2,0,0,2,2,0,0, 3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,2,2,2,2,2,3,2,2,0,2,3,0,2,2,0,0,2,0,2, 3,3,3,3,3,3,0,3,3,3,3,3,3,3,3,3,0,3,3,3,3,3,3,3,3,3,3,0,3,3,0,2,2,2,0,0, 3,3,3,3,3,3,3,3,0,2,2,3,3,3,3,3,3,0,2,2,2,2,0,2,0,0,0,3,2,2,2,0,0,2,0,0, 2,2,2,3,3,3,0,3,3,3,3,3,0,3,2,3,0,3,3,3,3,3,2,3,3,3,3,0,2,0,0,0,0,0,0,0, 3,3,3,0,2,3,3,2,3,3,2,3,3,2,2,3,3,2,0,2,2,2,2,2,3,0,2,2,0,0,2,2,0,0,0,0, 3,3,3,2,2,3,3,3,2,2,0,3,3,3,3,2,3,0,2,2,0,3,3,0,0,0,0,2,0,0,2,2,0,0,0,0, 3,3,3,3,3,3,3,2,3,2,3,3,3,3,3,3,3,2,2,2,2,2,0,2,3,0,2,0,0,2,3,2,0,2,0,2, 3,3,3,2,3,3,2,2,0,2,3,2,3,3,3,2,2,2,2,2,3,2,2,0,0,0,2,0,0,0,2,2,0,0,0,0, 3,3,3,2,3,3,3,2,3,3,2,2,3,2,3,2,3,0,2,3,0,2,0,0,0,0,0,2,0,0,2,0,0,2,2,2, 3,3,3,2,3,3,3,2,2,2,2,0,3,2,3,0,3,0,2,3,2,0,2,2,0,0,2,3,2,2,2,0,0,2,0,0, 3,3,3,0,3,3,3,2,3,2,3,3,3,2,3,2,2,0,2,3,0,2,2,3,2,0,2,0,0,2,2,0,2,2,0,0, 3,3,3,0,2,3,3,2,3,2,0,3,3,2,3,2,3,2,0,0,0,0,2,2,0,0,0,3,0,0,0,0,0,0,0,0, 3,3,3,0,3,3,3,3,0,0,0,3,3,0,0,2,3,2,2,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,2,3,3,3,2,3,2,2,0,3,3,3,2,2,0,0,2,0,2,2,0,2,0,2,2,2,0,2,2,0,0,0,0, 0,0,0,3,3,3,0,3,3,3,3,3,0,3,0,2,0,2,3,2,2,0,0,2,3,3,2,0,2,0,0,0,0,0,0,0, 3,3,3,0,0,2,2,2,0,2,0,0,3,0,3,0,2,0,0,0,0,2,2,2,0,0,0,2,0,0,2,0,0,0,0,0, 3,3,3,2,2,2,0,0,0,2,2,2,2,2,3,2,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,2,0,0, 0,0,2,3,3,3,0,3,2,2,2,2,0,2,0,2,0,2,2,3,2,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0, 0,0,0,2,0,2,0,2,2,0,0,2,0,2,0,0,0,2,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0, 3,2,2,0,0,0,2,0,2,0,0,0,0,2,2,0,0,0,0,0,2,0,0,2,0,0,2,0,0,2,0,0,0,0,0,0, 2,0,2,2,2,2,0,2,2,0,2,2,2,0,0,2,0,0,2,0,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0, 2,0,2,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,2,2,0,2,0,0,2,2,0,0,0,2,0,0,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0, }; const SequenceModel Iso_8859_3TurkishModel = { Iso_8859_3_CharToOrderMap, TurkishLangModel, 36, (float)0.991865243864388, PR_FALSE, "ISO-8859-3" }; const SequenceModel Iso_8859_9TurkishModel = { Iso_8859_9_CharToOrderMap, TurkishLangModel, 36, (float)0.991865243864388, PR_FALSE, "ISO-8859-9" }; <|start_filename|>grepWinNP3/sktoolslib_mod/ThreadPool.h<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2020-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #pragma once #include <deque> #include <functional> #include <thread> #include <condition_variable> #include <mutex> #include <atomic> //thread pool class ThreadPool { public: ThreadPool(unsigned int n = std::thread::hardware_concurrency()); /// add a new task to the pool. /// the task is added to a queue and worked on as soon /// as there's a thread ready. template <class F> void enqueue(F&& f); /// add a new task to be worked on. /// this method waits until a thread in the pool /// is not busy anymore, so the queue will not /// grow bigger than the thread pool is. template <class F> void enqueueWait(F&& f); /// waits for all threads to be finished void waitFinished(); /// waits until the thread pool has at least /// one thread not busy void waitForFreeSlot(); ~ThreadPool(); unsigned int getProcessed() const { return m_processed; } private: std::vector<std::thread> m_workers; std::deque<std::function<void()>> m_tasks; std::mutex m_queueMutex; std::condition_variable m_cvTask; std::condition_variable m_cvFinished; std::atomic_uint m_processed; unsigned int m_busy; bool m_stop; void thread_proc(); }; inline ThreadPool::ThreadPool(unsigned int n) : m_processed(0) , m_busy(0) , m_stop(false) { for (unsigned int i = 0; i < n; ++i) m_workers.emplace_back(std::bind(&ThreadPool::thread_proc, this)); } inline ThreadPool::~ThreadPool() { // set stop-condition std::unique_lock<std::mutex> latch(m_queueMutex); m_stop = true; m_cvTask.notify_all(); latch.unlock(); // all threads terminate, then we're done. for (auto& t : m_workers) t.join(); } inline void ThreadPool::thread_proc() { while (true) { std::unique_lock<std::mutex> latch(m_queueMutex); m_cvTask.wait(latch, [this]() { return m_stop || !m_tasks.empty(); }); if (!m_tasks.empty()) { ++m_busy; auto fn = m_tasks.front(); m_tasks.pop_front(); // release lock. run async latch.unlock(); // run function outside context fn(); ++m_processed; // lock again latch.lock(); --m_busy; m_cvFinished.notify_one(); } else if (m_stop) { break; } } } template <class F> void ThreadPool::enqueue(F&& f) { std::unique_lock<std::mutex> lock(m_queueMutex); m_tasks.emplace_back(std::forward<F>(f)); m_cvTask.notify_one(); } template <class F> void ThreadPool::enqueueWait(F&& f) { waitForFreeSlot(); std::unique_lock<std::mutex> lock(m_queueMutex); m_tasks.emplace_back(std::forward<F>(f)); m_cvTask.notify_one(); } // waits until the queue is empty and all threads are idle. inline void ThreadPool::waitFinished() { std::unique_lock<std::mutex> lock(m_queueMutex); m_cvFinished.wait(lock, [this]() { return m_tasks.empty() && (m_busy == 0); }); } // waits until there's at least one thread free in the pool. inline void ThreadPool::waitForFreeSlot() { std::unique_lock<std::mutex> lock(m_queueMutex); if ((m_busy < m_workers.size()) && (m_tasks.size() < m_workers.size())) return; m_cvFinished.wait(lock, [this]() { return ((m_busy < m_workers.size()) && (m_tasks.size() < m_workers.size())); }); } <|start_filename|>src/uchardet/uchardet/src/nsCharSetProber.cpp<|end_filename|> /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- * vim: et sw=2 ts=2 fdm=marker */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Universal charset detector code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 2001 * the Initial Developer. All Rights Reserved. * * Contributor(s): * <NAME> <<EMAIL>> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "nsCharSetProber.h" #include "prmem.h" //This filter applies to all scripts which do not use English characters PRBool nsCharSetProber::FilterWithoutEnglishLetters(const char* aBuf, PRUint32 aLen, char** newBuf, PRUint32& newLen) { char *newptr; char *prevPtr, *curPtr; PRBool meetMSB = PR_FALSE; newptr = *newBuf = (char*)PR_Malloc(aLen); if (!newptr) return PR_FALSE; for (curPtr = prevPtr = (char*)aBuf; curPtr < aBuf+aLen; curPtr++) { if (*curPtr & 0x80) { meetMSB = PR_TRUE; } else if (*curPtr < 'A' || (*curPtr > 'Z' && *curPtr < 'a') || *curPtr > 'z') { //current char is a symbol, most likely a punctuation. we treat it as segment delimiter if (meetMSB && curPtr > prevPtr) //this segment contains more than single symbol, and it has upper ASCII, we need to keep it { while (prevPtr < curPtr) *newptr++ = *prevPtr++; prevPtr++; *newptr++ = ' '; meetMSB = PR_FALSE; } else //ignore current segment. (either because it is just a symbol or just an English word) prevPtr = curPtr+1; } } if (meetMSB && curPtr > prevPtr) while (prevPtr < curPtr) *newptr++ = *prevPtr++; newLen = static_cast<PRUint32>(newptr - *newBuf); return PR_TRUE; } //This filter applies to all scripts which contain both English characters and upper ASCII characters. PRBool nsCharSetProber::FilterWithEnglishLetters(const char* aBuf, PRUint32 aLen, char** newBuf, PRUint32& newLen) { //do filtering to reduce load to probers char *newptr; char *prevPtr, *curPtr; PRBool isInTag = PR_FALSE; newptr = *newBuf = (char*)PR_Malloc(aLen); if (!newptr) return PR_FALSE; for (curPtr = prevPtr = (char*)aBuf; curPtr < aBuf+aLen; curPtr++) { if (*curPtr == '>') isInTag = PR_FALSE; else if (*curPtr == '<') isInTag = PR_TRUE; if (!(*curPtr & 0x80) && (*curPtr < 'A' || (*curPtr > 'Z' && *curPtr < 'a') || *curPtr > 'z') ) { if (curPtr > prevPtr && !isInTag) // Current segment contains more than just a symbol // and it is not inside a tag, keep it. { while (prevPtr < curPtr) *newptr++ = *prevPtr++; prevPtr++; *newptr++ = ' '; } else prevPtr = curPtr+1; } } // If the current segment contains more than just a symbol // and it is not inside a tag then keep it. if (!isInTag) while (prevPtr < curPtr) *newptr++ = *prevPtr++; newLen = static_cast<PRUint32>(newptr - *newBuf); return PR_TRUE; } <|start_filename|>src/crypto/rijndael-api-fst.c<|end_filename|> // encoding: UTF-8 /** * rijndael-api-fst.c * * @version 2.9 (December 2000) * * Optimised ANSI C code for the Rijndael cipher (now AES) * * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * * This code is hereby placed in the public domain. * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''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 AUTHORS 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. * * Acknowledgements: * * We are deeply indebted to the following people for their bug reports, * fixes, and improvement suggestions to this implementation. Though we * tried to list all contributions, we apologise in advance for any * missing reference. * * <NAME> <<EMAIL>> * <NAME> <<EMAIL>> * <NAME> <<EMAIL>> */ /* @doc CRYPTO None of the functinality has been changed, but some names and definitions have been tweaked for compatibility with the local environment. */ #if !defined(WINVER) #define WINVER 0x601 /*_WIN32_WINNT_WIN7*/ #endif #if !defined(_WIN32_WINNT) #define _WIN32_WINNT 0x601 /*_WIN32_WINNT_WIN7*/ #endif #if !defined(NTDDI_VERSION) #define NTDDI_VERSION 0x06010000 /*NTDDI_WIN7*/ #endif #define VC_EXTRALEAN 1 #define WIN32_LEAN_AND_MEAN 1 #define NOMINMAX 1 #include <windows.h> //#include "helpers.h" //#include "appreg.h" //#include "resource.h" #include <stdio.h> #include "crypto.h" #include "sha-256.h" #include "rijndael-alg-fst.h" #include "rijndael-api-fst.h" // --------------------------------------------------------------------- // --- Disable/Enable some CodeAnalysis Warnings --- #pragma warning ( disable: 26451) //#pragma warning ( enable : 6001 ) // --------------------------------------------------------------------- /* @func Generate a 256 bit AES key from a passphrase, using reasonably acceptable procedures to obfustate the original passphrase. The resulting key can be used for AES encryption by <f AES_setup> <nl>Overview: <l Crypto Utilities> */ void AES_keygen(char *passphrase, //* @parm the ascii passphrase BYTE key[32]) //* @parm the result key { Sha256String(passphrase, key); } /* @func prepare an AES key for use. TheKey is a string of hex digits, keyLen is the length of the crypto key to generate, which ought to be 256 in normal circumstances. If the key is already available in binary form, call <f AES_bin_setup> <nl>Overview: <l Crypto Utilities> */ int AES_setup (AES_keyInstance *key, // @parm the <t AES_keyInstance> to be initialized AES_MODES direction, // @parm either <e AES_MODES.AES_DIR_ENCRYPT> or <e AES_MODES.AES_DIR_DECRYPT> int keyLen, // @parm the length of the key in bits (better be 256) char *TheKey) // @parm the key itself, a hex string { int i; char *keyMat; u8 cipherKey[MAXKB]; if (TheKey != NULL) { //strncpy(key->TheKey, TheKey, keyLen/4); memcpy_s(key->TheKey, AES_MAX_KEY_SIZE, TheKey, keyLen / 4); } /* initialize key schedule: */ keyMat = key->TheKey; for (i = 0; i < keyLen / 8; i++) { int t, v; t = *keyMat++; if ((t >= '0') && (t <= '9')) v = (t - '0') << 4; else if ((t >= 'a') && (t <= 'f')) v = (t - 'a' + 10) << 4; else if ((t >= 'A') && (t <= 'F')) v = (t - 'A' + 10) << 4; else return BAD_KEY_MAT; t = *keyMat++; if ((t >= '0') && (t <= '9')) v ^= (t - '0'); else if ((t >= 'a') && (t <= 'f')) v ^= (t - 'a' + 10); else if ((t >= 'A') && (t <= 'F')) v ^= (t - 'A' + 10); else return BAD_KEY_MAT; cipherKey[i] = (u8)v; } return(AES_bin_setup(key, direction, keyLen, cipherKey)); } /* @func lower level version of <f AES_setup> where the key is already converted to binary. */ int AES_bin_setup (AES_keyInstance *key, // @parm the <t AES_keyInstance> to be initialized AES_MODES direction, // @parm either <e AES_MODES.AES_DIR_ENCRYPT> or <e AES_MODES.AES_DIR_DECRYPT> int keyLen, // @parm the length of the key in bits (better be 256) BYTE *cipherKey) // @parm the key itself, keyLen/8 bytes { if (key == NULL) { return BAD_KEY_INSTANCE; } if ((direction == AES_DIR_ENCRYPT) || (direction == AES_DIR_DECRYPT)) { key->direction = direction; } else { return BAD_KEY_DIR; } if ((keyLen == 128) || (keyLen == 192) || (keyLen == 256)) { key->keyLen = keyLen; } else { return BAD_KEY_MAT; } if (direction == AES_DIR_ENCRYPT) { key->Nr = rijndaelKeySetupEnc(key->rk, cipherKey, keyLen); } else { key->Nr = rijndaelKeySetupDec(key->rk, cipherKey, keyLen); } rijndaelKeySetupEnc(key->ek, cipherKey, keyLen); return true; } /* @func Prepare a cipher object for use with one encyption steam. This sets the cypher mode and int initial vector. The initial vector can be any 16 bytes, and need not be kept secret. <nl>Overview: <l Crypto Utilities> */ int AES_bin_cipherInit (AES_cipherInstance *cipher, //@parm the <t AES_cipherInstance> to be set up AES_MODES mode, //@parm the <t AES_MODES> to use, <e AES_MODES.AES_MODE_CBC> is recommended BYTE *IV) //@parm the IV, any 16 bytes { if ((mode == AES_MODE_ECB) || (mode == AES_MODE_CBC) || (mode == AES_MODE_CFB1)) { cipher->mode = mode; } else { return BAD_CIPHER_MODE; } if (IV != NULL) { memcpy(cipher->IV, IV, AES_MAX_IV_SIZE); } else { memset(cipher->IV, 0, AES_MAX_IV_SIZE); } return true; } /* @func Prepare a cipher object for use with one encyption stream. This sets the cypher mode and int initial vector. The initial vector can be any 16 bytes, and need not be kept secret. <nl>Overview: <l Crypto Utilities> */ int AES_cipherInit (AES_cipherInstance *cipher, //@parm the <t AES_cipherInstance> to be set up AES_MODES mode, //@parm the <t AES_MODES> to use, <e AES_MODES.AES_MODE_CBC> is recommended char *IV) //@parm the IV, ascii hex to define 16 bytes { if ((mode == AES_MODE_ECB) || (mode == AES_MODE_CBC) || (mode == AES_MODE_CFB1)) { cipher->mode = mode; } else { return BAD_CIPHER_MODE; } if (IV != NULL) { int i; for (i = 0; i < AES_MAX_IV_SIZE; i++) { int t, j; t = IV[2 * i]; if ((t >= '0') && (t <= '9')) j = (t - '0') << 4; else if ((t >= 'a') && (t <= 'f')) j = (t - 'a' + 10) << 4; else if ((t >= 'A') && (t <= 'F')) j = (t - 'A' + 10) << 4; else return BAD_CIPHER_INSTANCE; t = IV[2 * i + 1]; if ((t >= '0') && (t <= '9')) j ^= (t - '0'); else if ((t >= 'a') && (t <= 'f')) j ^= (t - 'a' + 10); else if ((t >= 'A') && (t <= 'F')) j ^= (t - 'A' + 10); else return BAD_CIPHER_INSTANCE; cipher->IV[i] = (u8)j; } } else { memset(cipher->IV, 0, AES_MAX_IV_SIZE); } return true; } /* @func Encrypt a block of data, using the provided key and cipher. The block should be a multiple of 16 bytes long, The trailing bytes mod 16 to be ignored. In CBC mode, the cipher IV is updated to be ready to encrypt the next block. <nl>Overview: <l Crypto Utilities> @rdesc number of bytes encrypted */ ptrdiff_t AES_blockEncrypt (AES_cipherInstance *cipher, //@parm the current <t AES_cipherInstance> AES_keyInstance *key, //@parm the current <t AES_keyInstance> BYTE *input, // @parm the input data ptrdiff_t inputLen, // @parm the size of the input data BYTE *outBuffer) //@parm a buffer to receive the encrypted data { u8 block[16]; u8* iv; if (cipher == NULL || key == NULL || key->direction == AES_DIR_DECRYPT) { return BAD_CIPHER_STATE; } if (input == NULL || inputLen <= 0) { return 0; /* nothing to do */ } size_t const numBlocks = inputLen / 16; switch (cipher->mode) { case AES_MODE_ECB: for (size_t i = numBlocks; i > 0; i--) { rijndaelEncrypt(key->rk, key->Nr, input, outBuffer); input += 16; outBuffer += 16; } break; case AES_MODE_CBC: iv = cipher->IV; for (size_t i = numBlocks; i > 0; i--) { ((u32*)block)[0] = ((u32*)input)[0] ^ ((u32*)iv)[0]; ((u32*)block)[1] = ((u32*)input)[1] ^ ((u32*)iv)[1]; ((u32*)block)[2] = ((u32*)input)[2] ^ ((u32*)iv)[2]; ((u32*)block)[3] = ((u32*)input)[3] ^ ((u32*)iv)[3]; rijndaelEncrypt(key->rk, key->Nr, block, outBuffer); iv = outBuffer; input += 16; outBuffer += 16; } // copy the iv for proper chaining to the next block if (numBlocks > 0) memcpy(cipher->IV, outBuffer - AES_MAX_IV_SIZE, AES_MAX_IV_SIZE); break; case AES_MODE_CFB1: iv = cipher->IV; for (size_t i = numBlocks; i > 0; i--) { memcpy(outBuffer, input, 16); for (unsigned int k = 0; k < 128; k++) { rijndaelEncrypt(key->ek, key->Nr, iv, block); outBuffer[k >> 3] ^= (block[0] & 0x80U) >> (k & 7); for (unsigned int t = 0; t < 15; t++) { iv[t] = (iv[t] << 1) | (iv[t + 1] >> 7); } iv[15] = (iv[15] << 1) | ((outBuffer[k >> 3] >> (7 - (k & 7))) & 1); } outBuffer += 16; input += 16; } break; default: return BAD_CIPHER_STATE; } return 16 * numBlocks; } /* @func Encrypt data using the current key and cipher, using RFC 2040-like padding, which puts the count of "pad" bytes in each pad byte. If you are encoding multiple blocks, all but the last should be multiples of 16 in size and be encrypted using <f AES_encrypt>. This last block will be padded to fill out the block, or if the original was already a multiple of 16, a full 16 bytes of padding will be added. Conventional use is to always provide at least one pad byte. If the original file was a multiple of 16, supply a block of 16 pad bytes so the decrypted data can be exactly the size of the encrypted data. In CBC mode, the cipher IV is updated to be ready to encrypt the next block, even though there will normally not be a next block. <nl>Overview: <l Crypto Utilities> @rdesc length in octets (not bits) of the encrypted output buffer. */ ptrdiff_t AES_padEncrypt (AES_cipherInstance *cipher, //@parm the current <t AES_cipherInstance> AES_keyInstance *key, //@parm the current <t AES_keyInstance> BYTE *input, // @parm the input data ptrdiff_t inputOctets, // @parm the size of the input data BYTE *outBuffer) //@parm a buffer to receive the encrypted data { u8 block[16]; u8* iv; if (cipher == NULL || key == NULL || key->direction == AES_DIR_DECRYPT) { return BAD_CIPHER_STATE; } if (input == NULL || inputOctets < 0) { return 0; /* nothing to do */ } size_t const numBlocks = inputOctets / 16; switch (cipher->mode) { case AES_MODE_ECB: { for (size_t i = numBlocks; i > 0; i--) { rijndaelEncrypt(key->rk, key->Nr, input, outBuffer); input += 16; outBuffer += 16; } int const padLen = 16 - (int)(inputOctets - 16 * numBlocks); if ((padLen <= 0) || (padLen > 16)) { BUG1("Padding must be 1-16, is %d", padLen); return 16 * numBlocks; } memcpy(block, input, 16 - padLen); memset(block + 16 - padLen, padLen, padLen); rijndaelEncrypt(key->rk, key->Nr, block, outBuffer); } break; case AES_MODE_CBC: { iv = cipher->IV; for (size_t i = numBlocks; i > 0; i--) { ((u32*)block)[0] = ((u32*)input)[0] ^ ((u32*)iv)[0]; ((u32*)block)[1] = ((u32*)input)[1] ^ ((u32*)iv)[1]; ((u32*)block)[2] = ((u32*)input)[2] ^ ((u32*)iv)[2]; ((u32*)block)[3] = ((u32*)input)[3] ^ ((u32*)iv)[3]; rijndaelEncrypt(key->rk, key->Nr, block, outBuffer); iv = outBuffer; input += 16; outBuffer += 16; } size_t const padLen = 16 - (inputOctets - 16 * numBlocks); if ((padLen <= 0) || (padLen > 16)) { BUG1("Padding must be 1-16, is %d", padLen); return 16 * numBlocks; } for (unsigned int i = 0; i < 16 - padLen; i++) { block[i] = input[i] ^ iv[i]; } BYTE const plen = (BYTE)(padLen & 0xFF); for (size_t i = 16 - padLen; (i < 16); i++) { block[i] = plen ^ iv[i]; } rijndaelEncrypt(key->rk, key->Nr, block, outBuffer); // set for chaining to the next block, even though there will normally not be one memcpy(cipher->IV, outBuffer, AES_MAX_IV_SIZE); } break; default: return BAD_CIPHER_STATE; } return 16 * (numBlocks + 1); } /* @func Decrypt a block of data using the supplied key and cipher. The block should be a multiple of 16; the trailing bytes mod 16 are ignored. In CBC mode, the IV of the cypher is updated to be ready to decrypt the next block. <nl>Overview: <l Crypto Utilities> @rdesc the number of bytes decrypted */ ptrdiff_t AES_blockDecrypt (AES_cipherInstance *cipher, //@parm the current <t AES_cipherInstance> AES_keyInstance *key, //@parm the current <t AES_keyInstance> BYTE *input, //@parm the input encrypted data ptrdiff_t inputLen, //@parm the size of the input BYTE *outBuffer) //@parm a buffer to receive the decrypted buffer { //int lim = 32; u8 block[16]; u8* iv; if (cipher == NULL || key == NULL || cipher->mode != AES_MODE_CFB1 && key->direction == AES_DIR_ENCRYPT) { return BAD_CIPHER_STATE; } if (input == NULL || inputLen <= 0) { return 0; /* nothing to do */ } size_t const numBlocks = inputLen / 16; switch (cipher->mode) { case AES_MODE_ECB: for (size_t i = numBlocks; i > 0; i--) { rijndaelDecrypt(key->rk, key->Nr, input, outBuffer); input += 16; outBuffer += 16; } break; case AES_MODE_CBC: iv = cipher->IV; for (size_t i = numBlocks; i > 0; i--) { rijndaelDecrypt(key->rk, key->Nr, input, block); ((u32*)block)[0] ^= ((u32*)iv)[0]; ((u32*)block)[1] ^= ((u32*)iv)[1]; ((u32*)block)[2] ^= ((u32*)iv)[2]; ((u32*)block)[3] ^= ((u32*)iv)[3]; memcpy(cipher->IV, input, 16); memcpy(outBuffer, block, 16); input += 16; outBuffer += 16; } break; case AES_MODE_CFB1: iv = cipher->IV; for (size_t i = numBlocks; i > 0; i--) { memcpy(outBuffer, input, 16); for (unsigned int k = 0; k < 128; k++) { rijndaelEncrypt(key->ek, key->Nr, iv, block); for (unsigned int t = 0; t < 15; t++) { iv[t] = (iv[t] << 1) | (iv[t + 1] >> 7); } iv[15] = (iv[15] << 1) | ((input[k >> 3] >> (7 - (k & 7))) & 1); outBuffer[k >> 3] ^= (block[0] & 0x80U) >> (k & 7); } outBuffer += 16; input += 16; } break; default: return BAD_CIPHER_STATE; } return 16 * numBlocks; } /* @func Decrypt a block of data using the supplied key and cipher. The block must be a multiple of 16 bytes, and should be padded in the manner of <f AES_padEncrypt> the trailing bytes mod 16 are ignored. In CBC mode, the IV is updated to be ready to decrypt the next block, even thought there normally will not be any more blocks. <nl>Overview: <l Crypto Utilities> @rdesc the number of bytes decrypted */ ptrdiff_t AES_padDecrypt (AES_cipherInstance *cipher, //@parm the current <t AES_cipherInstance> AES_keyInstance *key, //@parm the current <t AES_keyInstance> BYTE *input, //@parm the input encrypted data ptrdiff_t inputOctets, //@parm the size of the input BYTE *outBuffer) //@parm a buffer to receive the decrypted buffer { u8 block[16]; unsigned int padLen; if (cipher == NULL || key == NULL || key->direction == AES_DIR_ENCRYPT) { return BAD_CIPHER_STATE; } if (input == NULL || inputOctets <= 0) { return 0; /* nothing to do */ } if (inputOctets % 16 != 0) { return BAD_DATA; } size_t const numBlocks = inputOctets / 16; switch (cipher->mode) { case AES_MODE_ECB: /* all blocks but last */ for (size_t i = numBlocks - 1; i > 0; i--) { rijndaelDecrypt(key->rk, key->Nr, input, outBuffer); input += 16; outBuffer += 16; } /* last block */ rijndaelDecrypt(key->rk, key->Nr, input, block); padLen = block[15]; if (padLen >= 16) { return BAD_DATA; } for (unsigned int i = 16 - padLen; i < 16; i++) { if (block[i] != padLen) { return BAD_DATA; } } memcpy(outBuffer, block, 16 - padLen); break; case AES_MODE_CBC: /* all blocks but last */ for (size_t i = numBlocks - 1; i > 0; i--) { rijndaelDecrypt(key->rk, key->Nr, input, block); ((u32*)block)[0] ^= ((u32*)cipher->IV)[0]; ((u32*)block)[1] ^= ((u32*)cipher->IV)[1]; ((u32*)block)[2] ^= ((u32*)cipher->IV)[2]; ((u32*)block)[3] ^= ((u32*)cipher->IV)[3]; memcpy(cipher->IV, input, 16); memcpy(outBuffer, block, 16); input += 16; outBuffer += 16; } /* last block */ rijndaelDecrypt(key->rk, key->Nr, input, block); ((u32*)block)[0] ^= ((u32*)cipher->IV)[0]; ((u32*)block)[1] ^= ((u32*)cipher->IV)[1]; ((u32*)block)[2] ^= ((u32*)cipher->IV)[2]; ((u32*)block)[3] ^= ((u32*)cipher->IV)[3]; memcpy(cipher->IV, input, 16); padLen = block[15]; if (padLen <= 0 || padLen > 16) { return BAD_DATA; } for (unsigned int i = 16 - padLen; i < 16; i++) { if (block[i] != padLen) { return BAD_DATA; } } memcpy(outBuffer, block, 16 - padLen); break; default: return BAD_CIPHER_STATE; } return (16 * numBlocks) - padLen; } #ifdef INTERMEDIATE_VALUE_KAT /** * cipherUpdateRounds: * * Encrypts/Decrypts exactly one full block a specified number of rounds. * Only used in the Intermediate Value Known Answer Test. * * Returns: * true - on success * BAD_CIPHER_STATE - cipher in bad state (e.g., not initialized) */ int cipherUpdateRounds(AES_cipherInstance *cipher, AES_keyInstance *key, BYTE *input, int inputLen, BYTE *outBuffer, int rounds) { u8 block[16]; if (cipher == NULL || key == NULL) { return BAD_CIPHER_STATE; } memcpy(block, input, 16); switch (key->direction) { case AES_DIR_ENCRYPT: rijndaelEncryptRound(key->rk, key->Nr, block, rounds); break; case AES_DIR_DECRYPT: rijndaelDecryptRound(key->rk, key->Nr, block, rounds); break; default: return BAD_KEY_DIR; } memcpy(outBuffer, block, 16); return true; } #endif /* INTERMEDIATE_VALUE_KAT */ <|start_filename|>src/uchardet/uchardet/src/LangModels/LangLithuanianModel.cpp<|end_filename|> /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "../nsSBCharSetProber.h" /********* Language model for: Lithuanian *********/ /** * Generated by BuildLangModel.py * On: 2016-09-21 00:25:34.775158 **/ /* Character Mapping Table: * ILL: illegal character. * CTR: control character specific to the charset. * RET: carriage/return. * SYM: symbol (punctuation) that does not belong to word. * NUM: 0 - 9. * * Other characters are ordered by probabilities * (0 is the most common character in the language). * * Orders are generic to a language. So the codepoint with order X in * CHARSET1 maps to the same character as the codepoint with the same * order X in CHARSET2 for the same language. * As such, it is possible to get missing order. For instance the * ligature of 'o' and 'e' exists in ISO-8859-15 but not in ISO-8859-1 * even though they are both used for French. Same for the euro sign. */ static const unsigned char Iso_8859_10_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 1, 18, 23, 12, 4, 25, 16, 26, 0, 14, 9, 10, 11, 6, 3, /* 4X */ 15, 37, 5, 2, 7, 8, 13, 33, 32, 19, 27,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 1, 18, 23, 12, 4, 25, 16, 26, 0, 14, 9, 10, 11, 6, 3, /* 6X */ 15, 37, 5, 2, 7, 8, 13, 33, 32, 19, 27,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM, 29, 50, 60, 47, 61, 62,SYM, 56, 55, 21, 63, 22,SYM, 28, 64, /* AX */ SYM, 29, 50, 65, 47, 66, 67,SYM, 56, 55, 21, 68, 22, 69, 28, 70, /* BX */ 41, 39, 71, 53, 38, 43, 72, 30, 24, 36, 31, 73, 17, 40, 74, 46, /* CX */ 75, 57, 34, 44, 59, 76, 35, 77, 48, 20, 54, 78, 45, 79, 80, 52, /* DX */ 41, 39, 81, 53, 38, 43, 82, 30, 24, 36, 31, 83, 17, 40, 84, 46, /* EX */ 85, 57, 34, 44, 59, 86, 35, 87, 48, 20, 54, 88, 45, 89, 90, 91, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Iso_8859_4_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 1, 18, 23, 12, 4, 25, 16, 26, 0, 14, 9, 10, 11, 6, 3, /* 4X */ 15, 37, 5, 2, 7, 8, 13, 33, 32, 19, 27,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 1, 18, 23, 12, 4, 25, 16, 26, 0, 14, 9, 10, 11, 6, 3, /* 6X */ 15, 37, 5, 2, 7, 8, 13, 33, 32, 19, 27,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM, 29, 92, 93,SYM, 94, 56,SYM,SYM, 21, 50, 95, 96,SYM, 22,SYM, /* AX */ SYM, 29,SYM, 97,SYM, 98, 56,SYM,SYM, 21, 50, 99,100,101, 22,102, /* BX */ 41, 39,103, 53, 38, 43,104, 30, 24, 36, 31,105, 17, 40,106, 47, /* CX */ 55, 57, 34,107, 59,108, 35,SYM, 48, 20, 54,109, 45,110, 28, 52, /* DX */ 41, 39,111, 53, 38, 43,112, 30, 24, 36, 31,113, 17, 40,114, 47, /* EX */ 55, 57, 34,115, 59,116, 35,SYM, 48, 20, 54,117, 45,118, 28,SYM, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Iso_8859_13_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 1, 18, 23, 12, 4, 25, 16, 26, 0, 14, 9, 10, 11, 6, 3, /* 4X */ 15, 37, 5, 2, 7, 8, 13, 33, 32, 19, 27,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 1, 18, 23, 12, 4, 25, 16, 26, 0, 14, 9, 10, 11, 6, 3, /* 6X */ 15, 37, 5, 2, 7, 8, 13, 33, 32, 19, 27,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, 48,SYM,119,SYM,SYM,SYM,SYM,120, /* AX */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, 48,SYM,121,SYM,SYM,SYM,SYM,122, /* BX */ 29, 30, 41, 49, 38, 43, 31, 50, 24, 36,123, 17,124,125, 47, 56, /* CX */ 21, 51, 57, 44, 34,126, 35,SYM, 20, 42, 58, 28, 45,127, 22, 52, /* DX */ 29, 30, 41, 49, 38, 43, 31, 50, 24, 36,128, 17,129,130, 47, 56, /* EX */ 21, 51, 57, 44, 34,131, 35,SYM, 20, 42, 58, 28, 45,132, 22,SYM, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ /* Model Table: * Total sequences: 1016 * First 512 sequences: 0.9928710196247589 * Next 512 sequences (512-1024): 0.0071289803752411715 * Rest: -4.85722573273506e-17 * Negative sequences: TODO */ static const PRUint8 LithuanianLangModel[] = { 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,2,3,3,3,3,3,3,3,3,3,3,0,2,3,2,2,2,0,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,0,3,3,3,3,3,3,3,0,0,0,0,2,2,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,2,0,3,3,2,3,2,3,3,2,3,0,2,2,2,2,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,0,3,3,3,2,3,3,3,0,0,0,0,2,3,0,0,0,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,0,3,3,3,3,3,2,3,0,0,2,0,2,3,0,0,0,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,2,2,2,3,3,3,3,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,3,3,2,2,3,3,2,2,3,3,3,3,3,2,3,3,3,3,3,3,2,3,3,3,2,2,2,0,2,0, 3,3,3,3,3,3,3,3,3,3,3,3,0,3,2,2,2,3,3,3,3,2,0,2,0,2,3,2,3,3,3,3,0,2,2,2,2,0, 3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,0,3,2,0,3,3,3,3,3,2,3,0,0,0,0,0,2,0,0,0,0, 3,3,3,3,3,3,3,3,3,2,3,3,3,3,2,2,2,3,2,3,3,3,0,3,2,2,3,2,3,3,2,3,0,2,2,0,2,0, 3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,3,3,2,3,3,3,3,0,2,0,2,2,0, 3,3,3,3,3,2,2,3,3,2,2,3,2,2,2,3,2,3,3,3,3,2,3,2,0,2,0,2,3,3,0,3,0,2,2,2,2,0, 3,3,3,3,3,3,2,2,3,3,2,3,2,3,2,2,2,3,2,3,3,2,3,2,0,2,2,2,2,3,2,3,0,2,2,2,2,2, 3,3,3,3,3,2,2,2,3,2,3,0,2,0,2,2,0,3,0,3,3,2,0,2,0,0,0,3,2,3,0,3,0,0,0,0,0,0, 3,3,2,3,3,2,2,2,3,2,0,0,0,0,0,2,2,3,0,2,3,0,0,0,0,0,0,0,3,3,3,3,0,0,2,2,0,0, 3,3,3,3,3,3,2,3,3,3,3,2,2,3,3,2,2,3,0,3,2,3,2,2,2,2,3,0,2,2,2,2,0,0,2,0,2,0, 3,3,3,3,3,3,3,3,3,2,3,3,3,3,2,3,2,3,2,3,3,2,2,2,0,0,3,3,3,3,2,2,0,2,2,2,0,0, 2,0,3,0,0,3,3,3,2,3,3,3,3,3,3,0,3,0,2,0,0,2,2,2,2,0,0,2,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,3,3,2,3,0,3,2,2,2,0,3,2,2,3,2,2,2,0,0,2,2,3,3,2,3,0,2,2,2,0,0, 2,3,3,2,2,3,3,3,2,3,3,3,3,3,3,3,3,0,3,2,0,2,2,2,3,2,0,3,2,0,0,0,0,0,2,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,2,2,3,0,3,2,3,2,3,2,2,2,2,3,2,0,0,2,2,2,2,0,0,2,0,0,0, 3,3,3,3,3,2,3,3,3,2,2,3,3,3,2,2,2,3,2,3,2,2,0,0,0,2,0,0,2,2,2,2,0,0,2,0,0,0, 3,3,2,3,3,2,0,2,3,3,3,2,2,2,0,0,2,2,2,2,0,0,0,2,0,2,3,2,3,2,0,0,0,0,0,0,2,2, 3,3,0,2,3,0,0,0,2,2,0,0,2,0,0,2,0,2,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,2,0,0,0, 3,3,2,3,3,3,0,2,3,2,3,2,0,0,2,0,2,2,2,2,2,0,0,2,0,2,0,0,2,2,0,0,0,0,0,2,0,0, 3,3,2,3,3,3,3,3,3,2,2,3,2,0,2,0,0,0,2,2,2,0,0,0,0,2,0,0,2,2,0,0,0,2,2,0,0,0, 3,3,2,3,3,2,2,2,3,2,3,3,3,2,0,2,2,2,2,3,3,0,0,2,0,0,2,2,2,2,0,2,0,2,2,0,2,0, 2,0,3,0,0,3,3,3,0,3,2,3,3,2,0,2,3,0,2,0,0,2,2,0,3,0,0,3,0,0,0,0,0,0,0,0,0,0, 0,0,3,0,0,2,0,0,0,2,2,2,0,2,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,3,0,0,3,0,3,0,3,3,2,2,3,2,3,3,2,0,0,0,2,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,2,0,0,2,2,0,2,2,0,0,0,0,3,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0, 3,3,2,2,3,2,2,0,2,0,2,0,0,0,0,0,2,0,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0,2,0,0,0,0, 2,0,2,0,2,0,2,0,0,2,0,2,2,0,0,0,2,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,2,0,0,2,2,2,0,2,2,2,2,0,0,0,2,0,0,0,0,0,0,2,0,2,0,2,0,0,0,0,0,0,0,0,0,0, 0,0,2,0,0,2,2,0,0,0,0,2,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,2,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; const SequenceModel Iso_8859_10LithuanianModel = { Iso_8859_10_CharToOrderMap, LithuanianLangModel, 38, (float)0.9928710196247589, PR_TRUE, "ISO-8859-10" }; const SequenceModel Iso_8859_4LithuanianModel = { Iso_8859_4_CharToOrderMap, LithuanianLangModel, 38, (float)0.9928710196247589, PR_TRUE, "ISO-8859-4" }; const SequenceModel Iso_8859_13LithuanianModel = { Iso_8859_13_CharToOrderMap, LithuanianLangModel, 38, (float)0.9928710196247589, PR_TRUE, "ISO-8859-13" }; <|start_filename|>src/StyleLexers/styleLexPS.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_PS = { "begin break catch continue data do dynamicparam else elseif end exit filter finally for foreach from " "function if in local param private process return switch throw trap try until where while", "add-computer add-content add-history add-member add-pssnapin add-type checkpoint-computer clear-content " "clear-eventlog clear-history clear-host clear-item clear-itemproperty clear-variable compare-object " "complete-transaction connect-wsman convert-path convertfrom-csv convertfrom-securestring " "convertfrom-stringdata convertto-csv convertto-html convertto-securestring convertto-xml copy-item " "copy-itemproperty debug-process disable-computerrestore disable-psbreakpoint disable-psremoting " "disable-pssessionconfiguration disable-wsmancredssp disconnect-wsman enable-computerrestore " "enable-psbreakpoint enable-psremoting enable-pssessionconfiguration enable-wsmancredssp enter-pssession " "exit-pssession export-alias export-clixml export-console export-counter export-csv export-formatdata " "export-modulemember export-pssession foreach-object format-custom format-list format-table format-wide " "get-acl get-alias get-authenticodesignature get-childitem get-command get-computerrestorepoint " "get-content get-counter get-credential get-culture get-date get-event get-eventlog get-eventsubscriber " "get-executionpolicy get-formatdata get-help get-history get-host get-hotfix get-item get-itemproperty " "get-job get-location get-member get-module get-pfxcertificate get-process get-psbreakpoint " "get-pscallstack get-psdrive get-psprovider get-pssession get-pssessionconfiguration get-pssnapin " "get-random get-service get-tracesource get-transaction get-uiculture get-unique get-variable get-verb " "get-winevent get-wmiobject get-wsmancredssp get-wsmaninstance group-object import-alias import-clixml " "import-counter import-csv import-localizeddata import-module import-pssession invoke-command " "invoke-expression invoke-history invoke-item invoke-restmethod invoke-webrequest invoke-wmimethod " "invoke-wsmanaction join-path limit-eventlog measure-command measure-object move-item move-itemproperty " "new-alias new-event new-eventlog new-item new-itemproperty new-module new-modulemanifest new-object " "new-psdrive new-pssession new-pssessionoption new-service new-timespan new-variable new-webserviceproxy " "new-wsmaninstance new-wsmansessionoption out-default out-file out-gridview out-host out-null out-printer " "out-string pop-location push-location read-host receive-job register-engineevent register-objectevent " "register-pssessionconfiguration register-wmievent remove-computer remove-event remove-eventlog " "remove-item remove-itemproperty remove-job remove-module remove-psbreakpoint remove-psdrive " "remove-pssession remove-pssnapin remove-variable remove-wmiobject remove-wsmaninstance rename-item " "rename-itemproperty reset-computermachinepassword resolve-path restart-computer restart-service " "restore-computer resume-service select-object select-string select-xml send-mailmessage set-acl set-alias " "set-authenticodesignature set-content set-date set-executionpolicy set-item set-itemproperty set-location " "set-psbreakpoint set-psdebug set-pssessionconfiguration set-service set-strictmode set-tracesource " "set-variable set-wmiinstance set-wsmaninstance set-wsmanquickconfig show-eventlog sort-object split-path " "start-job start-process start-service start-sleep start-transaction start-transcript stop-computer " "stop-job stop-process stop-service stop-transcript suspend-service tee-object test-computersecurechannel " "test-connection test-modulemanifest test-path test-wsman trace-command undo-transaction unregister-event " "unregister-pssessionconfiguration update-formatdata update-list update-typedata use-transaction " "wait-event wait-job wait-process where-object write-debug write-error write-eventlog write-host " "write-output write-progress write-verbose write-warning", "ac asnp cat cd chdir clc clear clhy cli clp cls clv compare copy cp cpi cpp cvpa dbp del diff dir ebp echo " "epal epcsv epsn erase etsn exsn fc fl foreach ft fw gal gbp gc gci gcm gcs gdr ghy gi gjb gl gm gmo gp " "gps group gsn gsnp gsv gu gv gwmi h help history icm iex ihy ii ipal ipcsv ipmo ipsn ise iwmi kill lp ls " "man md measure mi mkdir more mount move mp mv nal ndr ni nmo nsn nv ogv oh popd ps pushd pwd r rbp rcjb " "rd rdr ren ri rjb rm rmdir rmo rni rnp rp rsn rsnp rv rvpa rwmi sajb sal saps sasv sbp sc select set si " "sl sleep sort sp spjb spps spsv start sv swmi tee type where wjb write", "importsystemmodules prompt psedit tabexpansion", NULL, }; EDITLEXER lexPS = { SCLEX_POWERSHELL, "powershell", IDS_LEX_PWRSHELL, L"PowerShell Script", L"ps1; psd1; psm1; psc1", L"", &KeyWords_PS, { { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_POWERSHELL_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {MULTI_STYLE(SCE_POWERSHELL_COMMENT,SCE_POWERSHELL_COMMENTSTREAM,0,0)}, IDS_LEX_STR_63127, L"Comment", L"fore:#646464", L"" }, { {SCE_POWERSHELL_KEYWORD}, IDS_LEX_STR_63128, L"Keyword", L"bold; fore:#804000", L"" }, { {SCE_POWERSHELL_IDENTIFIER}, IDS_LEX_STR_63129, L"Identifier", L"", L"" }, { {MULTI_STYLE(SCE_POWERSHELL_STRING,SCE_POWERSHELL_CHARACTER,0,0)}, IDS_LEX_STR_63131, L"String", L"fore:#008000", L"" }, { {SCE_POWERSHELL_NUMBER}, IDS_LEX_STR_63130, L"Number", L"fore:#FF0000", L"" }, { {SCE_POWERSHELL_OPERATOR}, IDS_LEX_STR_63132, L"Operator", L"bold", L"" }, { {SCE_POWERSHELL_VARIABLE}, IDS_LEX_STR_63249, L"Variable", L"fore:#0A246A", L"" }, { {MULTI_STYLE(SCE_POWERSHELL_CMDLET,SCE_POWERSHELL_FUNCTION,0,0)}, IDS_LEX_STR_63250, L"Cmdlet", L"fore:#804000; back:#FFF1A8", L"" }, { {SCE_POWERSHELL_ALIAS}, IDS_LEX_STR_63251, L"Alias", L"bold; fore:#0A246A", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>src/StyleLexers/styleLexLaTex.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_LaTex = EMPTY_KEYWORDLIST; EDITLEXER lexLATEX = { SCLEX_LATEX, "latex", IDS_LEX_LATEX, L"LaTeX Files", L"tex; latex; sty; texi; texinfo; txi", L"", &KeyWords_LaTex, { { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_L_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {MULTI_STYLE(SCE_L_COMMAND,SCE_L_SHORTCMD,SCE_L_CMDOPT,0)}, IDS_LEX_STR_63236, L"Command", L"fore:#0000FF", L"" }, { {MULTI_STYLE(SCE_L_COMMENT,SCE_L_COMMENT2,0,0)}, IDS_LEX_STR_63127, L"Comment", L"fore:#008000", L"" }, { {MULTI_STYLE(SCE_L_MATH,SCE_L_MATH2,0,0)}, IDS_LEX_STR_63359, L"Math", L"fore:#FF0000", L"" }, { {SCE_L_SPECIAL}, IDS_LEX_STR_63306, L"Special Char", L"fore:#AAAA00", L"" }, { {MULTI_STYLE(SCE_L_TAG,SCE_L_TAG2,0,0)}, IDS_LEX_STR_63363, L"Tag", L"fore:#0000FF", L"" }, { {SCE_L_VERBATIM}, IDS_LEX_STR_63307, L"Verbatim Segment", L"fore:#666666", L"" }, { {SCE_L_ERROR}, IDS_LEX_STR_63261, L"Error", L"fore:#FFFF00; back:#A00000", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>grepWinNP3/sktoolslib_mod/HotKeyCtrl.cpp<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012, 2020 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "HotKeyCtrl.h" #include <CommCtrl.h> #define PROP_OBJECT_PTR MAKEINTATOM(ga.atom) #define PROP_ORIGINAL_PROC MAKEINTATOM(ga.atom) /* * typedefs */ class CGlobalAtom { public: CGlobalAtom(void) { atom = GlobalAddAtom(L"_HotKeyCtrl_Object_Pointer_" L"\\{07B14ED2-C35E-438a-9B39-F4BAFE4E59EB}"); } ~CGlobalAtom(void) { DeleteAtom(atom); } ATOM atom; }; /* * Local variables */ static CGlobalAtom ga; CHotKeyCtrl::CHotKeyCtrl(void) : m_hWnd(NULL) , m_pfnOrigCtlProc(NULL) , controldown(false) , shiftdown(false) , menudown(false) , lwindown(false) { } CHotKeyCtrl::~CHotKeyCtrl(void) { } BOOL CHotKeyCtrl::ConvertEditToHotKeyCtrl(HWND hwndCtl) { // Subclass the existing control. m_pfnOrigCtlProc = (WNDPROC)GetWindowLongPtr(hwndCtl, GWLP_WNDPROC); SetProp(hwndCtl, PROP_OBJECT_PTR, (HANDLE)this); SetWindowLongPtr(hwndCtl, GWLP_WNDPROC, (LONG_PTR)(WNDPROC)_HotKeyProc); kb_hook = SetWindowsHookEx(WH_KEYBOARD, _KeyboardProc, NULL, GetCurrentThreadId()); m_hWnd = hwndCtl; return TRUE; } BOOL CHotKeyCtrl::ConvertEditToHotKeyCtrl(HWND hwndParent, UINT uiCtlId) { return ConvertEditToHotKeyCtrl(GetDlgItem(hwndParent, uiCtlId)); } void CHotKeyCtrl::SetHKText(WORD hk) { wchar_t buf[MAX_PATH] = {0}; wchar_t result[MAX_PATH] = {0}; BYTE h = hk >> 8; if (h & HOTKEYF_CONTROL) { LONG sc = MapVirtualKey(VK_CONTROL, MAPVK_VK_TO_VSC); sc <<= 16; GetKeyNameText(sc, buf, _countof(buf)); wcscat_s(result, _countof(result), buf); } if (h & HOTKEYF_SHIFT) { if (result[0]) wcscat_s(result, _countof(result), L" + "); LONG sc = MapVirtualKey(VK_SHIFT, MAPVK_VK_TO_VSC); sc <<= 16; GetKeyNameText(sc, buf, _countof(buf)); wcscat_s(result, _countof(result), buf); } if (h & HOTKEYF_ALT) { if (result[0]) wcscat_s(result, _countof(result), L" + "); LONG sc = MapVirtualKey(VK_MENU, MAPVK_VK_TO_VSC); sc <<= 16; GetKeyNameText(sc, buf, _countof(buf)); wcscat_s(result, _countof(result), buf); } if (h & HOTKEYF_EXT) { if (result[0]) wcscat_s(result, _countof(result), L" + "); LONG sc = MapVirtualKey(VK_LWIN, MAPVK_VK_TO_VSC); sc |= 0x0100; sc <<= 16; GetKeyNameText(sc, buf, _countof(buf)); wcscat_s(result, _countof(result), buf); } if (result[0]) wcscat_s(result, _countof(result), L" + "); LONG nScanCode = MapVirtualKey(LOBYTE(hk), MAPVK_VK_TO_VSC); switch (LOBYTE(hk)) { // Keys which are "extended" (except for Return which is Numeric Enter as extended) case VK_INSERT: case VK_DELETE: case VK_HOME: case VK_END: case VK_NEXT: // Page down case VK_PRIOR: // Page up case VK_LEFT: case VK_RIGHT: case VK_UP: case VK_DOWN: case VK_SNAPSHOT: nScanCode |= 0x0100; // Add extended bit } nScanCode <<= 16; GetKeyNameText(nScanCode, buf, _countof(buf)); wcscat_s(result, _countof(result), buf); ::SetWindowText(m_hWnd, result); } LRESULT CALLBACK CHotKeyCtrl::_KeyboardProc(int code, WPARAM wParam, LPARAM lParam) { HWND hWndFocus = ::GetFocus(); if (hWndFocus) { CHotKeyCtrl *pHyperLink = (CHotKeyCtrl *)GetProp(hWndFocus, PROP_OBJECT_PTR); if ((pHyperLink) && (pHyperLink->m_hWnd == hWndFocus)) { if (lParam & 0x80000000) { // WM_KEYUP if (wParam == VK_CONTROL) { pHyperLink->controldown = false; } else if (wParam == VK_SHIFT) { pHyperLink->shiftdown = false; } else if (wParam == VK_MENU) { pHyperLink->menudown = false; } else if (wParam == VK_LWIN) { pHyperLink->lwindown = false; } else { WORD hk = 0; if (pHyperLink->controldown) { hk |= HOTKEYF_CONTROL; } if (pHyperLink->shiftdown) { hk |= HOTKEYF_SHIFT; } if (pHyperLink->menudown) { hk |= HOTKEYF_ALT; } if (pHyperLink->lwindown) { hk |= HOTKEYF_EXT; } pHyperLink->hotkey = MAKEWORD(wParam, hk); pHyperLink->SetHKText(pHyperLink->hotkey); return 1; //we processed it } } else { // WM_KEYDOWN if (wParam == VK_CONTROL) { pHyperLink->controldown = true; } else if (wParam == VK_SHIFT) { pHyperLink->shiftdown = true; } else if (wParam == VK_MENU) { pHyperLink->menudown = true; } else if (wParam == VK_LWIN) { pHyperLink->lwindown = true; } else { WORD hk = 0; if (pHyperLink->controldown) { hk |= HOTKEYF_CONTROL; } if (pHyperLink->shiftdown) { hk |= HOTKEYF_SHIFT; } if (pHyperLink->menudown) { hk |= HOTKEYF_ALT; } if (pHyperLink->lwindown) { hk |= HOTKEYF_EXT; } pHyperLink->hotkey = MAKEWORD(wParam, hk); pHyperLink->SetHKText(pHyperLink->hotkey); return 1; //we processed it } } return CallNextHookEx(pHyperLink->kb_hook, code, wParam, lParam); } } return 0; } LRESULT CALLBACK CHotKeyCtrl::_HotKeyProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { CHotKeyCtrl *pHyperLink = (CHotKeyCtrl *)GetProp(hwnd, PROP_OBJECT_PTR); switch (message) { case WM_SHOWWINDOW: pHyperLink->SetHKText(pHyperLink->hotkey); break; case WM_GETDLGCODE: return DLGC_WANTALLKEYS; case WM_SYSKEYDOWN: case WM_KEYDOWN: { return 0; } case WM_SYSKEYUP: case WM_KEYUP: { return 0; } case WM_CHAR: return 0; case WM_DESTROY: { SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR)pHyperLink->m_pfnOrigCtlProc); RemoveProp(hwnd, PROP_OBJECT_PTR); break; } } return CallWindowProc(pHyperLink->m_pfnOrigCtlProc, hwnd, message, wParam, lParam); } void CHotKeyCtrl::SetHotKey(WPARAM hk) { hotkey = (WORD)hk; SetHKText((WORD)hk); } WPARAM CHotKeyCtrl::GetHotKey() { return hotkey; } <|start_filename|>src/StyleLexers/styleLexCSV.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_CSV = EMPTY_KEYWORDLIST; EDITLEXER lexCSV = { SCLEX_CSV, "CSV", IDS_LEX_PRISM_CSV, L"CSV Prism", L"csv", L"", & KeyWords_CSV,{ //SCE_CSV_DEFAULT { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {STYLE_LINENUMBER}, IDS_LEX_STD_MARGIN, L"Margins and Line Numbers", L"", L"" }, { {SCI_SETEXTRAASCENT + SCI_SETEXTRADESCENT}, IDS_LEX_STD_X_SPC, L"Extra Line Spacing (Size)", L"size:-1", L"" }, { {SCE_CSV_COLUMN_0}, IDS_LEX_CSV_COL_0, L"Column 0", L"fore:#9400D3", L"" }, { {SCE_CSV_COLUMN_1}, IDS_LEX_CSV_COL_1, L"Column 1", L"fore:#1C01AF", L"" }, { {SCE_CSV_COLUMN_2}, IDS_LEX_CSV_COL_2, L"Column 2", L"fore:#0162F3", L"" }, { {SCE_CSV_COLUMN_3}, IDS_LEX_CSV_COL_3, L"Column 3", L"fore:#28A4FF", L"" }, { {SCE_CSV_COLUMN_4}, IDS_LEX_CSV_COL_4, L"Column 4", L"fore:#01C2C2", L"" }, { {SCE_CSV_COLUMN_5}, IDS_LEX_CSV_COL_5, L"Column 5", L"fore:#00D530", L"" }, { {SCE_CSV_COLUMN_6}, IDS_LEX_CSV_COL_6, L"Column 6", L"fore:#80D500", L"" }, { {SCE_CSV_COLUMN_7}, IDS_LEX_CSV_COL_7, L"Column 7", L"fore:#D3E401", L"" }, { {SCE_CSV_COLUMN_8}, IDS_LEX_CSV_COL_8, L"Column 8", L"fore:#FE9901", L"" }, { {SCE_CSV_COLUMN_9}, IDS_LEX_CSV_COL_9, L"Column 9", L"fore:#D90000", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>src/uthash/utringbuffer.h<|end_filename|> /* Copyright (c) 2015-2021, <NAME> http://troydhanson.github.com/uthash/ 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* a ring-buffer implementation using macros */ #ifndef UTRINGBUFFER_H #define UTRINGBUFFER_H #define UTRINGBUFFER_VERSION 2.3.0 #include <stdlib.h> #include <string.h> #include "utarray.h" // for "UT_icd" typedef struct { unsigned i; /* index of next available slot; wraps at n */ unsigned n; /* capacity */ unsigned char f; /* full */ UT_icd icd; /* initializer, copy and destructor functions */ char *d; /* n slots of size icd->sz */ } UT_ringbuffer; #define utringbuffer_init(a, _n, _icd) do { \ memset(a, 0, sizeof(UT_ringbuffer)); \ (a)->icd = *(_icd); \ (a)->n = (_n); \ if ((a)->n) { (a)->d = (char*)malloc((a)->n * (_icd)->sz); } \ } while(0) #define utringbuffer_clear(a) do { \ if ((a)->icd.dtor) { \ if ((a)->f) { \ unsigned _ut_i; \ for (_ut_i = 0; _ut_i < (a)->n; ++_ut_i) { \ (a)->icd.dtor(utringbuffer_eltptr(a, _ut_i)); \ } \ } else { \ unsigned _ut_i; \ for (_ut_i = 0; _ut_i < (a)->i; ++_ut_i) { \ (a)->icd.dtor(utringbuffer_eltptr(a, _ut_i)); \ } \ } \ } \ (a)->i = 0; \ (a)->f = 0; \ } while(0) #define utringbuffer_done(a) do { \ utringbuffer_clear(a); \ free((a)->d); (a)->d = NULL; \ (a)->n = 0; \ } while(0) #define utringbuffer_new(a,n,_icd) do { \ a = (UT_ringbuffer*)malloc(sizeof(UT_ringbuffer)); \ utringbuffer_init(a, n, _icd); \ } while(0) #define utringbuffer_free(a) do { \ utringbuffer_done(a); \ free(a); \ } while(0) #define utringbuffer_push_back(a,p) do { \ if ((a)->icd.dtor && (a)->f) { (a)->icd.dtor(_utringbuffer_internalptr(a,(a)->i)); } \ if ((a)->icd.copy) { (a)->icd.copy( _utringbuffer_internalptr(a,(a)->i), p); } \ else { memcpy(_utringbuffer_internalptr(a,(a)->i), p, (a)->icd.sz); }; \ if (++(a)->i == (a)->n) { (a)->i = 0; (a)->f = 1; } \ } while(0) #define utringbuffer_len(a) ((a)->f ? (a)->n : (a)->i) #define utringbuffer_empty(a) ((a)->i == 0 && !(a)->f) #define utringbuffer_full(a) ((a)->f != 0) #define _utringbuffer_real_idx(a,j) ((a)->f ? ((j) + (a)->i) % (a)->n : (j)) #define _utringbuffer_internalptr(a,j) ((void*)((a)->d + ((a)->icd.sz * (j)))) #define utringbuffer_eltptr(a,j) ((0 <= (j) && (j) < utringbuffer_len(a)) ? _utringbuffer_internalptr(a,_utringbuffer_real_idx(a,j)) : NULL) #define _utringbuffer_fake_idx(a,j) ((a)->f ? ((j) + (a)->n - (a)->i) % (a)->n : (j)) #define _utringbuffer_internalidx(a,e) (((char*)(e) >= (a)->d) ? (((char*)(e) - (a)->d)/(a)->icd.sz) : -1) #define utringbuffer_eltidx(a,e) _utringbuffer_fake_idx(a, _utringbuffer_internalidx(a,e)) #define utringbuffer_front(a) utringbuffer_eltptr(a,0) #define utringbuffer_next(a,e) ((e)==NULL ? utringbuffer_front(a) : utringbuffer_eltptr(a, utringbuffer_eltidx(a,e)+1)) #define utringbuffer_prev(a,e) ((e)==NULL ? utringbuffer_back(a) : utringbuffer_eltptr(a, utringbuffer_eltidx(a,e)-1)) #define utringbuffer_back(a) (utringbuffer_empty(a) ? NULL : utringbuffer_eltptr(a, utringbuffer_len(a) - 1)) #endif /* UTRINGBUFFER_H */ <|start_filename|>grepWinNP3/sktoolslib_mod/shelllink.h<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012, 2020 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #pragma once #include <Shlobj.h> #include <IntShCut.h> #include <string> //Class which contains all the parameters related to shortcut class CShellLinkInfo { public: //Constructors / Destructors CShellLinkInfo(); CShellLinkInfo(const CShellLinkInfo& sli); ~CShellLinkInfo(); //Methods CShellLinkInfo& operator=(const CShellLinkInfo& sli); //Variables std::wstring m_sTarget; LPITEMIDLIST m_pidl; std::wstring m_sArguments; std::wstring m_sDescription; WORD m_wHotkey; std::wstring m_sIconLocation; int m_nIconIndex; int m_nShowCmd; std::wstring m_sWorkingDirectory; }; //Class which wraps standard shortcuts i.e. IShellLink class CShellLink { public: //Constructors / Destructors CShellLink(); virtual ~CShellLink(); //Methods BOOL Create(const CShellLinkInfo& sli); BOOL Load(const std::wstring& sFilename); BOOL Save(const std::wstring& sFilename); BOOL Resolve(HWND hParentWnd, DWORD dwFlags); //Accessors std::wstring GetPath() const; LPITEMIDLIST GetPathIDList() const; std::wstring GetArguments() const; std::wstring GetDescription() const; WORD GetHotKey() const; std::wstring GetIconLocation() const; int GetIconLocationIndex() const; int GetShowCommand() const; std::wstring GetWorkingDirectory() const; //Mutators void SetPath(const std::wstring& sPath); void SetPathIDList(LPITEMIDLIST pidl); void SetArguments(const std::wstring& sArguments); void SetDescription(const std::wstring& sDescription); void SetHotKey(WORD wHotkey); void SetIconLocation(const std::wstring& sIconLocation); void SetIconLocationIndex(int nIconIndex); void SetShowCommand(int nShowCmd); void SetWorkingDirectory(const std::wstring& sWorkingDirectory); protected: BOOL Initialise(); CShellLinkInfo m_sli; IShellLink* m_psl; IPersistFile* m_ppf; BOOL m_bAttemptedInitialise; }; //Class which wraps internet shortcuts i.e. IUniformResourceLocator class CUrlShellLink : public CShellLink { public: //Constructors / Destructors CUrlShellLink(); virtual ~CUrlShellLink(); //Methods BOOL Create(const CShellLinkInfo& sli); BOOL Load(const std::wstring& sFilename); BOOL Save(const std::wstring& sFilename); BOOL Invoke(HWND hParentWnd, DWORD dwFlags, const std::wstring& sVerb); //Following 4 functions just ASSERT if called std::wstring GetArguments() const; LPITEMIDLIST GetPathIDList() const; void SetArguments(const std::wstring& sArguments); void SetPathIDList(LPITEMIDLIST pidl); protected: BOOL Initialise(); IUniformResourceLocator* m_pURL; }; <|start_filename|>lexilla/scripts/RunTest.bat<|end_filename|> rem Test lexers rem build lexilla.dll and TestLexers.exe then run TestLexers.exe cd ../src make DEBUG=1 cd ../test make DEBUG=1 make test <|start_filename|>Version_rel.cmd<|end_filename|> :: Batch file for RELEASE version (without the separator "_" before ".paf" in Notepad3Portable) @echo off setlocal set _VERPATCH_= echo."%_VERPATCH_%">.\np3portableapp\_buildname.txt Version -VerPatch "%_VERPATCH_%" endlocal <|start_filename|>grepWinNP3/sktoolslib_mod/checkyear.js<|end_filename|> /* This script is a local pre-commit hook script. * It's used to check whether the copyright year of modified files has been * bumped up to the current year. * * Only *.cpp, *.h and *.idl files are checked * * Set the local hook scripts like this (pre-commit hook): * WScript path/to/this/script/file.js * and set "Wait for the script to finish" */ var forReading = 1; var objArgs = WScript.Arguments; var num = objArgs.length; if (num !== 4 && num !== 3) { WScript.Echo("Usage: [CScript | WScript] checkyear.js path/to/pathsfile depth path/to/messagefile path/to/CWD"); WScript.Quit(1); } var currentyear = new Date().getFullYear(); var re = new RegExp('^(\\\/\\\/|#) Copyright.+(' + currentyear + ')(.*)'); var basere = /^\/\/ Copyright(.*)/; var filere = /(\.cpp$)|(\.h$)|(\.idl$)/; // readFileLines function readPaths(path) { var retPaths = []; var fileSystem = new ActiveXObject("Scripting.FileSystemObject"); if (fileSystem.FileExists(path)) { var textFile = fileSystem.OpenTextFile(path, forReading); while (!textFile.AtEndOfStream) { var line = textFile.ReadLine(); retPaths.push(line); } textFile.Close(); } return retPaths; } var found = true; var files = readPaths(objArgs(0)); var fileIndex = files.length; var errorMessage = ""; while (fileIndex--) { var f = files[fileIndex]; var fso = new ActiveXObject("Scripting.FileSystemObject"); if (f.match(filere) !== null) { if (fso.FileExists(f)) { var a = fso.OpenTextFile(f, forReading, false); var copyrightFound = false; var yearFound = false; while (!a.AtEndOfStream && !yearFound) { var r = a.ReadLine(); var rv = r.match(basere); if (rv !== null) { rv = r.match(re); if (rv !== null) { yearFound = true; } copyrightFound = true; } } a.Close(); if (copyrightFound && !yearFound) { if (errorMessage !== "") { errorMessage += "\n"; } errorMessage += f; found = false; } } } } if (found === false) { errorMessage = "the file(s):\n" + errorMessage + "\nhave not the correct copyright year!"; WScript.stderr.writeLine(errorMessage); } WScript.Quit(!found); <|start_filename|>grepWinNP3/sktoolslib_mod/Callback.cpp<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012, 2020 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "Callback.h" #include <urlmon.h> #include <Shlwapi.h> // for StrFormatByteSize() #ifdef _DEBUG # undef THIS_FILE static char THIS_FILE[] = __FILE__; # define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CCallback::CCallback() : m_cRef(0) { } CCallback::~CCallback() { } STDMETHODIMP CCallback::Authenticate(HWND* phwnd, LPWSTR* pszUsername, LPWSTR* pszPassword) { *phwnd = NULL; *pszUsername = (LPWSTR)CoTaskMemAlloc((m_username.size() + 1) * 2); wcscpy_s(*pszUsername, m_username.size() + 1, m_username.c_str()); *pszPassword = (LPWSTR)CoTaskMemAlloc((m_password.size() + 1) * 2); wcscpy_s(*pszPassword, m_password.size() + 1, m_password.c_str()); return S_OK; } <|start_filename|>src/StyleLexers/styleLexJS.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- // JavaScript keywords (sync with lexHTML::KeyWords_HTML for embedded JS) KEYWORDLIST KeyWords_JS = { // Primary keywords NP3_LEXER_JS_KEYWORD_LIST, // Secondary keywords "", // Documentation comment keywords "addindex addtogroup anchor arg attention author b brief bug c class code copyright date def defgroup deprecated dontinclude " "e em endcode endhtmlonly endif endlatexonly endlink endverbatim enum example exception f$ f[f] file" "hideinitializer htmlinclude htmlonly if image include ingroup internal invariant interface latexonly li line link " "mainpage name namespace nosubgrouping note overload p page par param param[in] param[out] post pre " "ref relates remarks return retval sa section see showinitializer since skip skipline struct subsection " "test throw throws todo typedef union until var verbatim verbinclude version warning weakgroup", // Global classes and typedefs "", // Preprocessor definitions "", // Task marker and error marker keywords "BUG FIXME HACK NOTE TBD TODO UNDONE XXX @@@", NULL, }; EDITLEXER lexJS = { SCLEX_CPP, "cpp", IDS_LEX_J_SCR, L"JavaScript", L"js; jse; jsm; as; mjs; qs", L"", &KeyWords_JS, { { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_C_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {SCE_C_IDENTIFIER}, IDS_LEX_STR_63129, L"Identifier", L"", L"" }, { {MULTI_STYLE(SCE_C_COMMENT,SCE_C_COMMENTLINE,0,0)}, IDS_LEX_STR_63127, L"Comment", L"fore:#646464", L"" }, { {SCE_C_WORD}, IDS_LEX_STR_63128, L"Keyword", L"bold; fore:#A46000", L"" }, //{ {SCE_C_WORD2}, IDS_LEX_STR_63260, L"Keyword 2nd", L"bold; fore:#A46000", L"" }, { {SCE_C_STRING}, IDS_LEX_STR_63131, L"String", L"fore:#008000", L"" }, { {SCE_C_REGEX}, IDS_LEX_STR_63135, L"Regex", L"fore:#006633; back:#FFF1A8", L"" }, { {SCE_C_NUMBER}, IDS_LEX_STR_63130, L"Number", L"fore:#FF0000", L"" }, { {SCE_C_OPERATOR}, IDS_LEX_STR_63132, L"Operator", L"fore:#B000B0", L"" }, //{ {MULTI_STYLE(SCE_C_PREPROCESSOR,SCE_C_PREPROCESSORCOMMENT,SCE_C_PREPROCESSORCOMMENTDOC,0)}, IDS_LEX_STR_63133, L"Preprocessor", L"fore:#FF8000", L"" }, //{ {MULTI_STYLE(SCE_C_VERBATIM, SCE_C_TRIPLEVERBATIM,0,0)}, IDS_LEX_STR_63134, L"Verbatim", L"fore:#B000B0", L"" }, { {MULTI_STYLE(SCE_C_COMMENTDOC,SCE_C_COMMENTLINEDOC,0,0)}, IDS_LEX_STR_63259, L"Comment Doc", L"fore:#808080", L"" }, { {SCE_C_COMMENTDOCKEYWORD}, IDS_LEX_STR_63371, L"Comment Doc Word", L"bold; fore:#808080", L"" }, { {SCE_C_COMMENTDOCKEYWORDERROR}, IDS_LEX_STR_63374, L"Comment Doc Error", L"italic; fore:#800000", L"" }, { {SCE_C_TASKMARKER}, IDS_LEX_STR_63373, L"Task Marker", L"bold; fore:#208080", L"" }, //{ {SCE_C_UUID}, L"UUID", L"", L"" }, //{ {SCE_C_GLOBALCLASS}, L"Global Class", L"", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>src/tinyexpr/benchmark.c<|end_filename|> // encoding: UTF-8 /* * TINYEXPR - Tiny recursive descent parser and evaluation engine in C * * Copyright (c) 2015, 2016 <NAME> * * http://CodePlea.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgement in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include <stdio.h> #include <time.h> #include <math.h> #include "tinyexpr.h" #define loops 10000 typedef double (*function1)(double); void bench(const char *expr, function1 func) { int i, j; volatile double d; double tmp; clock_t start; te_variable lk = {"a", &tmp}; printf("Expression: %s\n", expr); printf("native "); start = clock(); d = 0; for (j = 0; j < loops; ++j) for (i = 0; i < loops; ++i) { tmp = i; d += func(tmp); } const int nelapsed = (clock() - start) * 1000 / CLOCKS_PER_SEC; /*Million floats per second input.*/ printf(" %.5g", d); if (nelapsed) printf("\t%5dms\t%5dmfps\n", nelapsed, loops * loops / nelapsed / 1000); else printf("\tinf\n"); printf("interp "); te_expr *n = te_compile(expr, &lk, 1, 0); start = clock(); d = 0; for (j = 0; j < loops; ++j) for (i = 0; i < loops; ++i) { tmp = i; d += te_eval(n); } const int eelapsed = (clock() - start) * 1000 / CLOCKS_PER_SEC; te_free(n); /*Million floats per second input.*/ printf(" %.5g", d); if (eelapsed) printf("\t%5dms\t%5dmfps\n", eelapsed, loops * loops / eelapsed / 1000); else printf("\tinf\n"); printf("%.2f%% longer\n", (((double)eelapsed / nelapsed) - 1.0) * 100.0); printf("\n"); } double a5(double a) { return a+5; } double a52(double a) { return (a+5)*2; } double a10(double a) { return a+(5*2); } double as(double a) { return sqrt(pow(a, 1.5) + pow(a, 2.5)); } double al(double a) { return (1/(a+1)+2/(a+2)+3/(a+3)); } int main(int argc, char *argv[]) { bench("sqrt(a^1.5+a^2.5)", as); bench("a+5", a5); bench("a+(5*2)", a10); bench("(a+5)*2", a52); bench("(1/(a+1)+2/(a+2)+3/(a+3))", al); return 0; } <|start_filename|>grepWinNP3/sktoolslib_mod/ReaderWriterLock.h<|end_filename|> /********************************************************************* CReaderWriterLock: A simple and fast reader-writer lock class in C++ has characters of .NET ReaderWriterLock class Copyright (C) 2006 <NAME> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. 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. Email questions, comments or suggestions to <EMAIL> *********************************************************************/ /********************************************************************* Introduction: This implementation is inspired by System.Threading.ReaderWriterLock in .NET framework. Following are some important statements I excerpted (with some words modified) from .NET document. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemThreadingReaderWriterLockClassTopic.asp "ReaderWriterLock is used to synchronize access to a resource. At any given time, it allows either concurrent read access for multiple threads, or write access for a single thread. In a situation where a resource is changed infrequently, a ReaderWriterLock provides better throughput than a simple one-at-a-time lock, such as CriticalSection or Mutex. This library works best where most accesses are reads, while writes are infrequent and of short duration. While a writer is waiting for active reader locks to be released, threads requesting new reader locks will have to wait in the reader queue. Their requests are not granted, even though they could share concurrent access with existing reader-lock holders; this helps protect writers against indefinite blockage by readers..." *********************************************************************/ #pragma once #include <windows.h> #include <map> #if (_WIN32_WINNT >= 0x0403) ////////////////////////////////////////////////////////////////// // On multiprocessor systems, this value define number of times // that a thread tries to spin before actually performing a wait // operation (see InitializeCriticalSectionAndSpinCount API) # ifndef READER_WRITER_SPIN_COUNT # define READER_WRITER_SPIN_COUNT 400 # endif // READER_WRITER_SPIN_COUNT #endif // _WIN32_WINNT // Forward reference class CReaderWriterLock; ////////////////////////////////////////////////////////////////// // CReaderWriterLockNonReentrance class // NOTE: This class doesn't support reentrance & lock escalation. // May be deadlock in one of following situations: // 1) Call AcquireReaderLock twice (reentrance) // --> Revise execution flow. // 2) Call AcquireWriterLock twice (reentrance) // --> Revise execution flow. // 3) Call AcquireReaderLock then AcquireWriterLock (lock escalation) // --> Use ReleaseReaderAndAcquireWriterLock method // 4) Call AcquireWriterLock then AcquireReaderLock (lock deescalation) // --> Use DowngradeFromWriterLock method class CReaderWriterLockNonReentrance { public: CReaderWriterLockNonReentrance(); ~CReaderWriterLockNonReentrance(); bool AcquireReaderLock(DWORD dwTimeout = INFINITE); void ReleaseReaderLock(); bool AcquireWriterLock(DWORD dwTimeout = INFINITE); void ReleaseWriterLock(); bool TryAcquireReaderLock(); bool TryAcquireWriterLock(); void DowngradeFromWriterLock(); // When a thread calls UpgradeToWriterLock, the reader lock is released, // and the thread goes to the end of the writer queue. Thus, other threads // might write to resources before this method returns bool UpgradeToWriterLock(DWORD dwTimeout = INFINITE); protected: // A critical section to guard all the other members mutable CRITICAL_SECTION m_cs; // Auto-reset event, will be dynamically created/destroyed on demand volatile HANDLE m_hSafeToWriteEvent; // Manual-reset event, will be dynamically created/destroyed on demand volatile HANDLE m_hSafeToReadEvent; // Total number of writers on this object volatile INT m_iNumOfWriter; // Total number of readers have already owned this object volatile INT m_iNumOfReaderEntered; // Total number of readers are waiting to be owners of this object volatile INT m_iNumOfReaderWaiting; // Internal/Real implementation void EnterCS() const; void LeaveCS() const; bool _ReaderWait(DWORD dwTimeout); bool _WriterWaitAndLeaveCSIfSuccess(DWORD dwTimeout); bool _UpgradeToWriterLockAndLeaveCS(DWORD dwTimeout); void _ReaderRelease(); void _WriterRelease(bool blDowngrade); friend CReaderWriterLock; }; ////////////////////////////////////////////////////////////////// // CReaderWriterLock class // This class supports reentrance & lock escalation class CReaderWriterLock { public: CReaderWriterLock(); ~CReaderWriterLock(); bool AcquireReaderLock(DWORD dwTimeout = INFINITE); void ReleaseReaderLock(); // If current thread was already a reader // it will be upgraded to be writer automatically. // BE CAREFUL! Other threads might write to the resource // before current thread is successfully upgraded. bool AcquireWriterLock(DWORD dwTimeout = INFINITE); void ReleaseWriterLock(); // Regardless of how many times current thread acquired reader // or writer locks, a call to this method will release all locks. // After that, any call to ReleaseWriterLock or ReleaseReaderLock // will raise exception in DEBUG mode. void ReleaseAllLocks(); // Query thread's status DWORD GetCurrentThreadStatus() const; void GetCurrentThreadStatus(DWORD* lpdwReaderLockCounter, DWORD* lpdwWriterLockCounter) const; protected: CReaderWriterLockNonReentrance m_impl; typedef std::map<DWORD, DWORD> CMapThreadToState; CMapThreadToState m_map; }; ////////////////////////////////////////////////////////////////// // CAutoReadLockT & CAutoWriteLockT classes // Couple of template helper classes which would let one acquire a lock // in a body of code and not have to worry about explicitly releasing // that lock if an exception is encountered in that piece of code or // if there are multiple return points out of that piece. template <typename T> class CAutoReadLockT { public: CAutoReadLockT(T& objLock) : m_lock(objLock) { m_lock.AcquireReaderLock(); } ~CAutoReadLockT() { m_lock.ReleaseReaderLock(); } protected: T& m_lock; private: CAutoReadLockT& operator=(const CAutoReadLockT&) = delete; }; template <typename T> class CAutoWriteLockT { public: CAutoWriteLockT(T& objLock) : m_lock(objLock) { m_lock.AcquireWriterLock(); } ~CAutoWriteLockT() { m_lock.ReleaseWriterLock(); } protected: T& m_lock; private: CAutoWriteLockT& operator=(const CAutoWriteLockT&) = delete; }; template <typename T> class CAutoReadWeakLockT { public: CAutoReadWeakLockT(T& objLock, DWORD timeout = 1) : m_lock(objLock) { isAcquired = m_lock.AcquireReaderLock(timeout); } ~CAutoReadWeakLockT() { if (isAcquired) m_lock.ReleaseReaderLock(); } bool IsAcquired() const { return isAcquired; } protected: T& m_lock; bool isAcquired; }; template <typename T> class CAutoWriteWeakLockT { public: CAutoWriteWeakLockT(T& objLock, DWORD timeout = 1) : m_lock(objLock) { isAcquired = m_lock.AcquireWriterLock(timeout); } ~CAutoWriteWeakLockT() { release(); } void Release() { release(); } bool IsAcquired() const { return isAcquired; } protected: T& m_lock; bool isAcquired; void release() { if (isAcquired) { m_lock.ReleaseWriterLock(); isAcquired = false; } } }; ////////////////////////////////////////////////////////////////// // Instances of above template helper classes typedef CAutoReadLockT<CReaderWriterLock> CAutoReadLock; typedef CAutoWriteLockT<CReaderWriterLock> CAutoWriteLock; typedef CAutoReadWeakLockT<CReaderWriterLock> CAutoReadWeakLock; typedef CAutoWriteWeakLockT<CReaderWriterLock> CAutoWriteWeakLock; ////////////////////////////////////////////////////////////////// // Inline methods __forceinline void CReaderWriterLockNonReentrance::EnterCS() const { ::EnterCriticalSection(&m_cs); } __forceinline void CReaderWriterLockNonReentrance::LeaveCS() const { ::LeaveCriticalSection(&m_cs); } <|start_filename|>test/test_files/StyleLexers/styleLexCPP/Test_Replace (issue #1901).cxx<|end_filename|> namespace Scintilla { // Byte ranges... const unsigned char uch = ch; switch (codePage) { %Armadura: Ra = 4.18; La = 6.44 / 1000); %Mecanica: Kb = 0..75; Kt = 0.075; Bm = (125.33 / (1000*1000)); Jm = (14.25 / (1000*1000)); %Externos: n = 30; A = 100; } } <|start_filename|>grepWinNP3/sktoolslib_mod/PreserveChdir.cpp<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2013, 2020 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "PreserveChdir.h" #include "PathUtils.h" PreserveChdir::PreserveChdir() : m_originalDir(CPathUtils::GetCWD()) { } PreserveChdir::~PreserveChdir() { if (m_originalDir.empty()) // Nothing to do if failed to get the original dir. return; // _tchdir is an expensive function - don't call it unless we really have to. std::wstring currentDir = CPathUtils::GetCWD(); // Restore the current directory if it doesn't match the original directory // or if we failed to get the current directory. if (currentDir.empty() || _wcsicmp(m_originalDir.c_str(), currentDir.c_str()) != 0) SetCurrentDirectory(m_originalDir.c_str()); } <|start_filename|>src/StyleLexers/styleLexRust.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_Rust = { // Primary keywords and identifiers "as be break const continue crate else enum extern false fn for if impl in let loop match mod mut once pub " "ref return self static struct super trait true type unsafe use while", // Built in types "bool char f32 f64 i16 i32 i64 i8 int str u16 u32 u64 u8 uint", // Other keywords "abstract alignof become box do final macro offsetof override priv proc pure sizeof typeof unsized " "virtual yield", // Keywords 4 "", // Keywords 5 "", // Keywords 6 "", // Keywords 7 "", NULL, }; EDITLEXER lexRust = { SCLEX_RUST, "rust", IDS_LEX_RUST_SRC, L"Rust Source Code", L"rs; rust", L"", &KeyWords_Rust,{ { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_RUST_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {SCE_RUST_IDENTIFIER}, IDS_LEX_STR_63129, L"Identifier", L"", L"" }, { {SCE_RUST_WORD}, IDS_LEX_STR_63128, L"Keyword", L"bold; fore:#248112", L"" }, { {SCE_RUST_WORD2}, IDS_LEX_STR_63343, L"Build-In Type", L"fore:#A9003D", L"" }, { {SCE_RUST_WORD3}, IDS_LEX_STR_63345, L"Other Keyword", L"italic; fore:#248112", L"" }, //{ {SCE_RUST_WORD4}, IDS_LEX_STR_63128, L"Keyword 4", L"bold; fore:#0A246A", L"" }, //{ {SCE_RUST_WORD5}, IDS_LEX_STR_63128, L"Keyword 5", L"bold; fore:#0A246A", L"" }, //{ {SCE_RUST_WORD6}, IDS_LEX_STR_63128, L"Keyword 6", L"bold; fore:#0A246A", L"" }, //{ {SCE_RUST_WORD}, IDS_LEX_STR_63128, L"Keyword 7", L"bold; fore:#0A246A", L"" }, { {SCE_RUST_NUMBER}, IDS_LEX_STR_63130, L"Number", L"fore:#666666", L"" }, { {MULTI_STYLE(SCE_RUST_COMMENTBLOCK,SCE_RUST_COMMENTLINE,SCE_RUST_COMMENTBLOCKDOC,SCE_RUST_COMMENTLINEDOC)}, IDS_LEX_STR_63127, L"Comment", L"italic; fore:#488080", L"" }, { {MULTI_STYLE(SCE_RUST_STRING,SCE_RUST_STRINGR,SCE_RUST_CHARACTER,0)}, IDS_LEX_STR_63131, L"String", L"fore:#B31C1B", L"" }, { {SCE_RUST_OPERATOR}, IDS_LEX_STR_63132, L"Operator", L"fore:#666666", L"" }, { {SCE_RUST_MACRO}, IDS_LEX_STR_63280, L"Macro Definition", L"fore:#0A246A", L"" }, { {SCE_RUST_LIFETIME}, IDS_LEX_STR_63346, L"Rust Lifetime", L"fore:#B000B0", L"" }, { {SCE_RUST_LEXERROR}, IDS_LEX_STR_63252, L"Parsing Error", L"fore:#F0F0F0; back:#F00000", L"" }, { {MULTI_STYLE(SCE_RUST_BYTESTRING,SCE_RUST_BYTESTRINGR,SCE_RUST_BYTECHARACTER,0)}, IDS_LEX_STR_63344, L"Byte String", L"fore:#C0C0C0", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>test/test_files/StyleLexers/styleLexJS/test_script.js<|end_filename|> var x; const y; let z; for (let el of arr) { console.log(el); } <|start_filename|>src/StyleLexers/styleLexDart.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- //KEYWORDLIST KeyWords_Dart = EMPTY_KEYWORDLIST; KEYWORDLIST KeyWords_Dart = { // 0 keywords "abstract as assert async await break case catch class const continue covariant default deferred do " "else enum export extends extension external factory false final finally for get hide " "if implements import in interface is late library mixin native new null of on operator part required rethrow return " "set show static super switch sync this throw true try typedef var while with yield " , // 1 keywords2 "" , // 2 types "Function bool double dynamic int num void " , // 3 class "BidirectionalIterator BigInt Comparable Comparator Completer " "DateTime Deprecated Directory DoubleLinkedQueue DoubleLinkedQueueEntry Duration Error Exception Expando " "File FileStat FileSystemEntity FileSystemEvent Future FutureOr HasNextIterator HashMap HashSet " "IOException Invocation Iterable IterableBase IterableMixin Iterator " "LinkedHashMap LinkedHashSet LinkedList LinkedListEntry List ListBase ListMixin ListQueue " "Map MapBase MapEntry MapMixin MapView Match Null OSError Object Pattern Platform Point Process Queue " "Random RawSocket RawSocketEvent Rectangle RegExp RegExpMatch RuneIterator Runes " "ServerSocket Set SetBase SetMixin Sink Socket SocketException SplayTreeMap SplayTreeSet " "StackTrace Stopwatch Stream String StringBuffer StringSink Symbol SystemHash " "Timer Type Uri UriData " , // 4 enum "" , // 5 metadata "Deprecated Since deprecated override patch pragma " , // 6 function "identical identityHashCode main print " , NULL }; EDITLEXER lexDart = { SCLEX_DART, "Dart", IDS_LEX_DART_SRC, L"Dart Source Code", L"dart", L"", &KeyWords_Dart,{ { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_DART_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {SCE_DART_WORD}, IDS_LEX_STR_63128, L"Keyword", L"fore:#0000FF", L"" }, { {SCE_DART_WORD2}, IDS_LEX_STR_63260, L"Keyword 2nd", L"fore:#0000FF", L"" }, { {SCE_DART_METADATA}, IDS_LEX_STR_63203, L"Meta-Data", L"fore:#FF8000", L"" }, { {SCE_DART_CLASS}, IDS_LEX_STR_63258, L"Class", L"fore:#0080FF", L"" }, { {SCE_DART_ENUM}, IDS_LEX_STR_63203, L"Enumeration", L"fore:#FF8000", L"" }, { {SCE_DART_FUNCTION}, IDS_LEX_STR_63277, L"Function", L"fore:#A46000", L"" }, { {MULTI_STYLE(SCE_DART_COMMENTBLOCK, SCE_DART_COMMENTLINE, 0, 0)}, IDS_LEX_STR_63127, L"Comment", L"fore:#608060", L"" }, { {MULTI_STYLE(SCE_DART_COMMENTBLOCKDOC, SCE_DART_COMMENTLINEDOC, 0, 0)}, IDS_LEX_STR_63259, L"Comment Doc", L"fore:#408040", L"" }, { {SCE_DART_TASKMARKER}, IDS_LEX_STR_63373, L"Task Marker", L"bold; fore:#408080" }, { {MULTI_STYLE(SCE_DART_STRING_SQ, SCE_DART_STRING_DQ, 0, 0)}, IDS_LEX_STR_63131, L"String", L"fore:#008000", L"" }, { {MULTI_STYLE(SCE_DART_TRIPLE_STRING_SQ, SCE_DART_TRIPLE_STRING_DQ, SCE_DART_TRIPLE_STRINGSTART, SCE_DART_TRIPLE_STRINGEND)}, IDS_LEX_STR_63131, L"TriQ-String", L"fore:#F08000", L"" }, { {MULTI_STYLE(SCE_DART_RAWSTRING_SQ, SCE_DART_RAWSTRING_DQ, SCE_DART_TRIPLE_RAWSTRING_SQ, SCE_DART_TRIPLE_RAWSTRING_DQ)}, IDS_LEX_STR_63134, L"Verbatim String", L"fore:#F08000", L"" }, { {SCE_DART_ESCAPECHAR}, IDS_LEX_STR_63366, L"ESC Sequence", L"fore:#0080C0", L"" }, { {SCE_DART_LABEL}, IDS_LEX_STR_63235, L"Label", L"fore:#7C5AF3", L"" }, { {SCE_DART_NUMBER}, IDS_LEX_STR_63130, L"Number", L"fore:#FF0000", L"" }, { {SCE_DART_VARIABLE}, IDS_LEX_STR_63249, L"Variable", L"fore:#9E4D2A", L"" }, { {MULTI_STYLE(SCE_DART_SYMBOL_OPERATOR, SCE_DART_SYMBOL_IDENTIFIER, 0, 0)}, IDS_LEX_STR_63132, L"Operator", L"fore:#7C5AF3", L"" }, { {MULTI_STYLE(SCE_DART_OPERATOR, SCE_DART_OPERATOR2, 0, 0)}, IDS_LEX_STR_63132, L"Operator2", L"fore:#B000B0", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>grepWinNP3/sktoolslib_mod/FormatMessageWrapper.h<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012, 2017, 2020-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #pragma once /** * A wrapper class for calling the FormatMessage() Win32 function and controlling * the lifetime of the allocated error message buffer. */ class CFormatMessageWrapper { private: LPWSTR buffer; DWORD result; void release(); void obtainMessage() { obtainMessage(::GetLastError()); } void obtainMessage(DWORD errorCode); public: CFormatMessageWrapper() : buffer(nullptr) , result(0) { obtainMessage(); } CFormatMessageWrapper(DWORD lastError) : buffer(nullptr) , result(0) { obtainMessage(lastError); } ~CFormatMessageWrapper() { release(); } operator LPCWSTR() const { return buffer; } operator bool() const { return result != 0; } bool operator!() const { return result == 0; } LPCWSTR c_str() const { return buffer; } }; inline void CFormatMessageWrapper::obtainMessage(DWORD errorCode) { // First of all release the buffer to make it possible to call this // method more than once on the same object. release(); result = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, errorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language reinterpret_cast<LPWSTR>(&buffer), 0, nullptr); } inline void CFormatMessageWrapper::release() { if (buffer != nullptr) { LocalFree(buffer); buffer = nullptr; } result = 0; } <|start_filename|>grepWinNP3/sktoolslib_mod/BaseWindowD2D.h<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2020 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #pragma once #include "BaseWindow.h" #include <stdlib.h> #include <malloc.h> #include <memory.h> #include <math.h> #include <d2d1.h> #include <d2d1effects.h> #include <d2d1helper.h> #include <dwrite.h> #include <wincodec.h> #include <dxgi1_3.h> #include <d3d11_2.h> #include <d2d1_2.h> #include <d2d1_2helper.h> #include <dcomp.h> #include <wrl.h> using namespace Microsoft::WRL; struct ComException { HRESULT result; ComException(HRESULT const value) : result(value) { } }; void HR(HRESULT const result); /** * \ingroup Utils * A base window class with Direct2D support. */ class CWindowD2D : public CWindow { public: virtual bool Create() override; virtual bool Create(DWORD dwStyles, HWND hParent = nullptr, RECT* rect = nullptr) override; virtual bool CreateEx(DWORD dwExStyles, DWORD dwStyles, HWND hParent = nullptr, RECT* rect = nullptr, LPCWSTR classname = nullptr, HMENU hMenu = nullptr) override; protected: //constructor CWindowD2D(HINSTANCE hInst, CONST WNDCLASSEX* wcx = nullptr) : CWindow(hInst, wcx) , m_window_width(0) , m_window_height(0) { } virtual ~CWindowD2D() { } virtual LRESULT CALLBACK WinMsgProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) = 0; virtual HRESULT OnRender(ID2D1DeviceContext* dc) = 0; virtual HRESULT CreateDeviceResources() = 0; virtual HRESULT DiscardDeviceResources() = 0; protected: ComPtr<ID3D11Device> m_direct3dDevice; ComPtr<IDXGIDevice> m_dxgiDevice; ComPtr<IDXGIFactory2> m_dxFactory; ComPtr<IDWriteFactory> m_writeFactory; ComPtr<IDXGISwapChain1> m_swapChain; ComPtr<ID2D1Factory2> m_d2Factory; ComPtr<ID2D1Device1> m_d2Device; ComPtr<ID2D1DeviceContext> m_dc; ComPtr<IDXGISurface2> m_surface; ComPtr<IDCompositionDevice> m_compositionDevice; ComPtr<IDCompositionTarget> m_compositionTarget; ComPtr<IDCompositionVisual> m_compositionVisual; ComPtr<ID2D1Bitmap1> m_d2dBitmap; UINT m_window_width, m_window_height; private: LRESULT CALLBACK WinMsgHandler(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) override; void Resize(UINT width, UINT height); }; <|start_filename|>grepWinNP3/sktoolslib_mod/ReaderWriterLock.cpp<|end_filename|> /********************************************************************* CReaderWriterLock: A simple and fast reader-writer lock class in C++ has characters of .NET ReaderWriterLock class Copyright (C) 2006 <NAME> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. 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. Email questions, comments or suggestions to <EMAIL> *********************************************************************/ #include "stdafx.h" #include <crtdbg.h> #include "ReaderWriterLock.h" ///////////////////////////////////////////////////////////////// // Following macros make this file can be used in non-MFC project #ifndef ASSERT // Define ASSERT macro # define ASSERT _ASSERT // Define VERIFY macro # ifdef _DEBUG # define VERIFY ASSERT # define DEBUG_ONLY(f) ((void)(f)) # else # define VERIFY(f) ((void)(f)) # define DEBUG_ONLY(f) # endif #endif /////////////////////////////////////////////////////// // CReaderWriterLockNonReentrance implementation CReaderWriterLockNonReentrance::CReaderWriterLockNonReentrance() { SecureZeroMemory(this, sizeof(*this)); #if (_WIN32_WINNT >= 0x0403) InitializeCriticalSectionAndSpinCount(&m_cs, READER_WRITER_SPIN_COUNT); #else InitializeCriticalSection(&m_cs); #endif } CReaderWriterLockNonReentrance::~CReaderWriterLockNonReentrance() { _ASSERT((NULL == m_hSafeToReadEvent) && (NULL == m_hSafeToWriteEvent)); DeleteCriticalSection(&m_cs); } bool CReaderWriterLockNonReentrance::_ReaderWait(DWORD dwTimeout) { bool blCanRead; ++m_iNumOfReaderWaiting; if (nullptr == m_hSafeToReadEvent) { m_hSafeToReadEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr); } if (INFINITE == dwTimeout) // INFINITE is a special value { do { LeaveCS(); WaitForSingleObject(m_hSafeToReadEvent, INFINITE); // There might be one or more Writers entered, that's // why we need DO-WHILE loop here EnterCS(); } while (0 != m_iNumOfWriter); ++m_iNumOfReaderEntered; blCanRead = TRUE; } else { LeaveCS(); DWORD const dwBeginTime = GetTickCount(); DWORD dwConsumedTime = 0; for (;;) { blCanRead = (WAIT_OBJECT_0 == WaitForSingleObject(m_hSafeToReadEvent, dwTimeout - dwConsumedTime)); EnterCS(); if (0 == m_iNumOfWriter) { // Regardless timeout or not, there is no Writer // So it's safe to be Reader right now ++m_iNumOfReaderEntered; blCanRead = TRUE; break; } if (FALSE == blCanRead) { // Timeout after waiting break; } // There are some Writers have just entered // So leave CS and prepare to try again LeaveCS(); dwConsumedTime = GetTickCount() - dwBeginTime; if (dwConsumedTime > dwTimeout) { // Don't worry why the code here looks stupid // Because this case rarely happens, it's better // to optimize code for the usual case blCanRead = FALSE; EnterCS(); break; } } } if (0 == --m_iNumOfReaderWaiting) { CloseHandle(m_hSafeToReadEvent); m_hSafeToReadEvent = nullptr; } return blCanRead; } void CReaderWriterLockNonReentrance::_ReaderRelease() { INT iNumOfReaderEntered = --m_iNumOfReaderEntered; _ASSERT(0 <= iNumOfReaderEntered); if ((0 == iNumOfReaderEntered) && (nullptr != m_hSafeToWriteEvent)) { SetEvent(m_hSafeToWriteEvent); } } bool CReaderWriterLockNonReentrance::_WriterWaitAndLeaveCSIfSuccess(DWORD dwTimeout) { //EnterCS(); _ASSERT(0 != dwTimeout); // Increase Writer-counter & reset Reader-event if necessary INT iNumOfWriter = ++m_iNumOfWriter; if ((1 == iNumOfWriter) && (nullptr != m_hSafeToReadEvent)) { ResetEvent(m_hSafeToReadEvent); } if (nullptr == m_hSafeToWriteEvent) { m_hSafeToWriteEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); } LeaveCS(); bool blCanWrite = (WAIT_OBJECT_0 == WaitForSingleObject(m_hSafeToWriteEvent, dwTimeout)); if (FALSE == blCanWrite) { // Undo what we changed after timeout EnterCS(); if (0 == --m_iNumOfWriter) { CloseHandle(m_hSafeToWriteEvent); m_hSafeToWriteEvent = nullptr; if (0 == m_iNumOfReaderEntered) { // Although it was timeout, it's still safe to be writer now ++m_iNumOfWriter; LeaveCS(); blCanWrite = TRUE; } else if (m_hSafeToReadEvent) { SetEvent(m_hSafeToReadEvent); } } } return blCanWrite; } bool CReaderWriterLockNonReentrance::_UpgradeToWriterLockAndLeaveCS(DWORD dwTimeout) { _ASSERT(m_iNumOfReaderEntered > 0); if (0 == dwTimeout) { LeaveCS(); return FALSE; } --m_iNumOfReaderEntered; bool blCanWrite = _WriterWaitAndLeaveCSIfSuccess(dwTimeout); if (FALSE == blCanWrite) { // Now analyze why it was failed to have suitable action if (0 == m_iNumOfWriter) { _ASSERT(0 < m_iNumOfReaderEntered); // There are some readers still owning the lock // It's safe to be a reader again after failure ++m_iNumOfReaderEntered; } else { // Reach to here, it's NOT safe to be a reader immediately _ReaderWait(INFINITE); if (1 == m_iNumOfReaderEntered) { // After wait, now it's safe to be writer _ASSERT(0 == m_iNumOfWriter); m_iNumOfReaderEntered = 0; m_iNumOfWriter = 1; blCanWrite = TRUE; } } LeaveCS(); } return blCanWrite; } void CReaderWriterLockNonReentrance::_WriterRelease(bool blDowngrade) { _ASSERT(0 == m_iNumOfReaderEntered); if (blDowngrade) { ++m_iNumOfReaderEntered; } if (0 == --m_iNumOfWriter) { if (nullptr != m_hSafeToWriteEvent) { CloseHandle(m_hSafeToWriteEvent); m_hSafeToWriteEvent = nullptr; } if (m_hSafeToReadEvent) { SetEvent(m_hSafeToReadEvent); } } else { ////////////////////////////////////////////////////////////////////////// // Some WRITERs are queued _ASSERT((0 < m_iNumOfWriter) && (NULL != m_hSafeToWriteEvent)); if (FALSE == blDowngrade) { SetEvent(m_hSafeToWriteEvent); } } } bool CReaderWriterLockNonReentrance::AcquireReaderLock(DWORD dwTimeout) { bool blCanRead; EnterCS(); if (0 == m_iNumOfWriter) { // Enter successful without wait ++m_iNumOfReaderEntered; blCanRead = TRUE; } else { blCanRead = (dwTimeout) ? _ReaderWait(dwTimeout) : FALSE; } LeaveCS(); return blCanRead; } void CReaderWriterLockNonReentrance::ReleaseReaderLock() { EnterCS(); _ReaderRelease(); LeaveCS(); } bool CReaderWriterLockNonReentrance::AcquireWriterLock(DWORD dwTimeout) { bool blCanWrite; EnterCS(); if (0 == (m_iNumOfWriter | m_iNumOfReaderEntered)) { ++m_iNumOfWriter; blCanWrite = TRUE; } else if (0 == dwTimeout) { blCanWrite = FALSE; } else { blCanWrite = _WriterWaitAndLeaveCSIfSuccess(dwTimeout); if (blCanWrite) { return TRUE; } } LeaveCS(); return blCanWrite; } void CReaderWriterLockNonReentrance::ReleaseWriterLock() { EnterCS(); _WriterRelease(FALSE); LeaveCS(); } void CReaderWriterLockNonReentrance::DowngradeFromWriterLock() { EnterCS(); _WriterRelease(TRUE); LeaveCS(); } bool CReaderWriterLockNonReentrance::UpgradeToWriterLock(DWORD dwTimeout) { EnterCS(); return _UpgradeToWriterLockAndLeaveCS(dwTimeout); } // END CReaderWriterLockNonReentrance implementation /////////////////////////////////////////////////////// /////////////////////////////////////////////////////// // CReaderWriterLock implementation #define READER_RECURRENCE_UNIT 0x00000001 #define READER_RECURRENCE_MASK 0x0000FFFF #define WRITER_RECURRENCE_UNIT 0x00010000 CReaderWriterLock::CReaderWriterLock() { } CReaderWriterLock::~CReaderWriterLock() { } bool CReaderWriterLock::AcquireReaderLock(DWORD dwTimeout) { const DWORD dwCurrentThreadId = GetCurrentThreadId(); m_impl.EnterCS(); CMapThreadToState::iterator ite = m_map.find(dwCurrentThreadId); if (ite != m_map.end()) { ////////////////////////////////////////////////////////////////////////// // Current thread was already a WRITER or READER _ASSERT(0 < ite->second); ite->second += READER_RECURRENCE_UNIT; m_impl.LeaveCS(); return TRUE; } if (0 == m_impl.m_iNumOfWriter) { // There is NO WRITER on this RW object // Current thread is going to be a READER ++m_impl.m_iNumOfReaderEntered; m_map.insert(std::make_pair(dwCurrentThreadId, READER_RECURRENCE_UNIT)); m_impl.LeaveCS(); return TRUE; } if (0 == dwTimeout) { m_impl.LeaveCS(); return FALSE; } bool blCanRead = m_impl._ReaderWait(dwTimeout); if (blCanRead) { m_map.insert(std::make_pair(dwCurrentThreadId, READER_RECURRENCE_UNIT)); } m_impl.LeaveCS(); return blCanRead; } void CReaderWriterLock::ReleaseReaderLock() { const DWORD dwCurrentThreadId = GetCurrentThreadId(); m_impl.EnterCS(); CMapThreadToState::iterator ite = m_map.find(dwCurrentThreadId); _ASSERT((ite != m_map.end()) && (READER_RECURRENCE_MASK & ite->second)); const DWORD dwThreadState = (ite->second -= READER_RECURRENCE_UNIT); if (0 == dwThreadState) { m_map.erase(ite); m_impl._ReaderRelease(); } m_impl.LeaveCS(); } bool CReaderWriterLock::AcquireWriterLock(DWORD dwTimeout) { const DWORD dwCurrentThreadId = GetCurrentThreadId(); bool blCanWrite; m_impl.EnterCS(); CMapThreadToState::iterator ite = m_map.find(dwCurrentThreadId); if (ite != m_map.end()) { _ASSERT(0 < ite->second); if (ite->second >= WRITER_RECURRENCE_UNIT) { // Current thread was already a WRITER ite->second += WRITER_RECURRENCE_UNIT; m_impl.LeaveCS(); return TRUE; } // Current thread was already a READER _ASSERT(1 <= m_impl.m_iNumOfReaderEntered); if (1 == m_impl.m_iNumOfReaderEntered) { // This object is owned by ONLY current thread for READ // There might be some threads queued to be WRITERs // but for effectiveness (higher throughput), we allow current // thread upgrading to be WRITER right now m_impl.m_iNumOfReaderEntered = 0; ++m_impl.m_iNumOfWriter; ite->second += WRITER_RECURRENCE_UNIT; m_impl.LeaveCS(); return TRUE; } // Try upgrading from reader to writer blCanWrite = m_impl._UpgradeToWriterLockAndLeaveCS(dwTimeout); if (blCanWrite) { m_impl.EnterCS(); ite = m_map.find(dwCurrentThreadId); ite->second += WRITER_RECURRENCE_UNIT; m_impl.LeaveCS(); } } else { if (0 == (m_impl.m_iNumOfWriter | m_impl.m_iNumOfReaderEntered)) { // This RW object is not owned by any thread // --> it's safe to make this thread to be WRITER ++m_impl.m_iNumOfWriter; m_map.insert(std::make_pair(dwCurrentThreadId, WRITER_RECURRENCE_UNIT)); m_impl.LeaveCS(); return TRUE; } if (0 == dwTimeout) { m_impl.LeaveCS(); return FALSE; } blCanWrite = m_impl._WriterWaitAndLeaveCSIfSuccess(dwTimeout); if (blCanWrite) { m_impl.EnterCS(); m_map.insert(std::make_pair(dwCurrentThreadId, WRITER_RECURRENCE_UNIT)); } m_impl.LeaveCS(); } return blCanWrite; } void CReaderWriterLock::ReleaseWriterLock() { const DWORD dwCurrentThreadId = GetCurrentThreadId(); m_impl.EnterCS(); CMapThreadToState::iterator ite = m_map.find(dwCurrentThreadId); _ASSERT((ite != m_map.end()) && (WRITER_RECURRENCE_UNIT <= ite->second)); const DWORD dwThreadState = (ite->second -= WRITER_RECURRENCE_UNIT); if (0 == dwThreadState) { m_map.erase(ite); m_impl._WriterRelease(FALSE); } else if (WRITER_RECURRENCE_UNIT > dwThreadState) { // Down-grading from writer to reader m_impl._WriterRelease(TRUE); } m_impl.LeaveCS(); } void CReaderWriterLock::ReleaseAllLocks() { const DWORD dwCurrentThreadId = GetCurrentThreadId(); m_impl.EnterCS(); CMapThreadToState::iterator ite = m_map.find(dwCurrentThreadId); if (ite != m_map.end()) { const DWORD dwThreadState = ite->second; m_map.erase(ite); if (WRITER_RECURRENCE_UNIT <= dwThreadState) { m_impl._WriterRelease(FALSE); } else { _ASSERT(0 < dwThreadState); m_impl._ReaderRelease(); } } m_impl.LeaveCS(); } DWORD CReaderWriterLock::GetCurrentThreadStatus() const { DWORD dwThreadState; const DWORD dwCurrentThreadId = GetCurrentThreadId(); m_impl.EnterCS(); CMapThreadToState::const_iterator ite = m_map.find(dwCurrentThreadId); if (ite != m_map.end()) { dwThreadState = ite->second; m_impl.LeaveCS(); _ASSERT(dwThreadState > 0); } else { dwThreadState = 0; m_impl.LeaveCS(); } return dwThreadState; } void CReaderWriterLock::GetCurrentThreadStatus(DWORD* lpdwReaderLockCounter, DWORD* lpdwWriterLockCounter) const { const DWORD dwThreadState = GetCurrentThreadStatus(); if (nullptr != lpdwReaderLockCounter) { *lpdwReaderLockCounter = (dwThreadState & READER_RECURRENCE_MASK); } if (nullptr != lpdwWriterLockCounter) { *lpdwWriterLockCounter = (dwThreadState / WRITER_RECURRENCE_UNIT); } } <|start_filename|>src/StyleLexers/styleLexCPP.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_CPP = { // Primary keywords "alignas alignof asm audit auto axiom bitand bitor bool break case catch char class compl concept " "const const_cast consteval constexpr continue co_await co_return co_yield " "decltype default defined delete do double dynamic_cast else enum explicit export extern false final float for " "friend goto if import inline int long module mutable naked namespace new noexcept not not_eq noreturn nullptr " "operator or or_eq override private protected public " "register reinterpret_cast requires restrict return " "short signed sizeof static static_assert static_cast struct switch " "template this thread_local throw true try typedef typeid typename " "union unsigned using virtual void volatile while xor xor_eq", // Secondary keywords "_Alignas _Alignof _Atomic _Bool _Complex _Generic _Imaginary _Noreturn _Static_assert _Thread_local " "_Pragma __DATE__ __FILE__ __LINE__ __STDCPP_DEFAULT_NEW_ALIGNMENT__ __STDCPP_STRICT_POINTER_SAFETY__ " "__STDCPP_THREADS__ __STDC_HOSTED__ __STDC_ISO_10646__ __STDC_MB_MIGHT_NEQ_WC__ __STDC_UTF_16__ " "__STDC_UTF_32__ __STDC_VERSION__ __STDC__ __TIME__ __VA_ARGS__ __VA_OPT__ __abstract __alignof __asm " "__assume __based __box __cdecl __cplusplus __declspec __delegate __event __except __except__try " "__fastcall __finally __gc __has_include __hook __identifier __if_exists __if_not_exists __inline " "__interface __leave __multiple_inheritance __nogc __noop __pin __property __raise __sealed " "__single_inheritance __stdcall __super __try __try_cast __unhook __uuidof __value __virtual_inheritance", // Documentation comment keywords "addindex addtogroup anchor arg attention author b brief bug c class code copyright date def defgroup deprecated dontinclude " "e em endcode endhtmlonly endif endlatexonly endlink endverbatim enum example exception f$ f[f] file" "hideinitializer htmlinclude htmlonly if image include ingroup internal invariant interface latexonly li line link " "mainpage name namespace nosubgrouping note overload p page par param param[in] param[out] post pre " "ref relates remarks return retval sa section see showinitializer since skip skipline struct subsection " "test throw throws todo typedef union until var verbatim verbinclude version warning weakgroup", // Global classes and typedefs "__int16 __int32 __int64 __int8 __m128 __m128d __m128i __m64 __wchar_t char16_t char32_t complex imaginary int16_t int32_t " "int64_t int8_t intmax_t intptr_t ptrdiff_t size_t uint16_t uint32_t uint64_t uint8_t uintmax_t uintptr_t wchar_t", // Preprocessor definitions "DEBUG NDEBUG UNICODE _DEBUG _MSC_VER _UNICODE", // Task marker and error marker keywords "BUG FIXME HACK NOTE TBD TODO UNDONE XXX @@@", NULL, }; EDITLEXER lexCPP = { SCLEX_CPP, "cpp", IDS_LEX_CPP_SRC, L"C/C++ Source Code", L"c; cpp; cxx; cc; h; hpp; hxx; hh; mm; idl; midl; inl; odl; xpm; pch", L"", &KeyWords_CPP, { { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_C_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {SCE_C_IDENTIFIER}, IDS_LEX_STR_63129, L"Identifier", L"", L"" }, { {MULTI_STYLE(SCE_C_COMMENT,SCE_C_COMMENTLINE,0,0)}, IDS_LEX_STR_63127, L"Comment", L"fore:#008000", L"" }, { {SCE_C_WORD}, IDS_LEX_STR_63128, L"Keyword", L"bold; fore:#0A246A", L"" }, { {SCE_C_WORD2}, IDS_LEX_STR_63260, L"Keyword 2nd", L"bold; italic; fore:#3C6CDD", L"" }, { {SCE_C_GLOBALCLASS}, IDS_LEX_STR_63258, L"Typedefs/Classes", L"bold; italic; fore:#800000", L"" }, { {SCE_C_STRING}, IDS_LEX_STR_63131, L"String", L"fore:#008000", L"" }, //{ {SCE_C_REGEX}, IDS_LEX_STR_63135, L"Regex", L"fore:#006633; back:#FFF1A8", L"" }, { {SCE_C_NUMBER}, IDS_LEX_STR_63130, L"Number", L"fore:#FF0000", L"" }, { {SCE_C_OPERATOR}, IDS_LEX_STR_63132, L"Operator", L"fore:#B000B0", L"" }, { {MULTI_STYLE(SCE_C_PREPROCESSOR,SCE_C_PREPROCESSORCOMMENT,SCE_C_PREPROCESSORCOMMENTDOC,0)}, IDS_LEX_STR_63133, L"Preprocessor", L"fore:#FF8000", L"" }, { {MULTI_STYLE(SCE_C_VERBATIM,SCE_C_TRIPLEVERBATIM,0,0)}, IDS_LEX_STR_63134, L"Verbatim", L"fore:#B000B0", L"" }, { {MULTI_STYLE(SCE_C_COMMENTDOC,SCE_C_COMMENTLINEDOC,0,0)}, IDS_LEX_STR_63259, L"Comment Doc", L"fore:#808080", L"" }, { {SCE_C_COMMENTDOCKEYWORD}, IDS_LEX_STR_63371, L"Comment Doc Word", L"bold; fore:#808080", L"" }, { {SCE_C_COMMENTDOCKEYWORDERROR}, IDS_LEX_STR_63374, L"Comment Doc Error", L"italic; fore:#800000", L"" }, { {SCE_C_TASKMARKER}, IDS_LEX_STR_63373, L"Task Marker", L"bold; fore:#208080", L"" }, //{ {SCE_C_UUID}, L"UUID", L"", L"" }, //{ {SCE_C_USERLITERAL}, L"User Literal", L"", L"" }, //{ {SCE_C_ESCAPESEQUENCE}, L"Esc Seq", L"", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>grepWinNP3/sktoolslib_mod/ResourceFile.h<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012, 2020 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #pragma once class CResourceFile { public: CResourceFile(); CResourceFile(const CResourceFile &); virtual ~CResourceFile(); BYTE * GetByteBuffer() { return m_pBytes; } size_t GetLength() { return m_nBufLen; } size_t GetPosition() { return m_nPosition; } BOOL IsAtEOF() { return m_nPosition >= GetLength(); } BOOL IsOpen() { return m_bIsOpen; } public: virtual void Close(); virtual BYTE * DetachByteBuffer(); virtual BYTE * DuplicateByteBuffer(); virtual BOOL Open(HINSTANCE hInstance, LPCWSTR lpszResId, LPCWSTR lpszResType); virtual size_t Read(BYTE *buf, size_t nBufLen); virtual size_t Seek(size_t offset, size_t origin); virtual size_t SeekToBegin(); virtual size_t SeekToEnd(); virtual void SetByteBuffer(BYTE *buf, DWORD len); protected: BYTE * m_pBytes; // binary buffer size_t m_nBufLen; // size of m_pszResource: TCHARs for text, // bytes for binary size_t m_nPosition; // buffer position: TCHARs for text, // bytes for binary BOOL m_bText; // TRUE = text, FALSE = binary BOOL m_bIsOpen; // TRUE = text file resource is open BOOL m_bDoNotDeleteBuffer; // TRUE = buffer allocated externally // or detached; do not delete }; <|start_filename|>test/test_files/StyleLexers/styleLexBAT/CMD_01.cmd<|end_filename|> @ECHO Off EXIT :strt0 IF EXIST %temp%\badst_tmp.txt DEL /F /Q %temp%\badst_tmp.txt >NUL IF EXIST %temp%\disk_tmp.txt DEL /F /Q %temp%\disk_tmp.txt >NUL IF EXIST %temp%\exst_tmp.txt DEL /F /Q %temp%\exst_tmp.txt >NUL IF EXIST %temp%\intro_tmp.txt DEL /F /Q %temp%\intro_tmp.txt >NUL IF EXIST %temp%\scssf_tmp.txt DEL /F /Q %temp%\scssf_tmp.txt >NUL IF EXIST %temp%\wmic_tmp.txt DEL /F /Q %temp%\wmic_tmp.txt >NUL WMIC logicaldisk get caption,description,name,volumename >%temp%\wmic_tmp.txt :start SET slct= CLS ECHO. >%temp%\intro_tmp.txt ECHO. CAUTION: Use this Batch File ONLY with a REMOVABLE Disk (eg: USB Memory Stick) >>%temp%\intro_tmp.txt ECHO. >>%temp%\intro_tmp.txt ECHO List of All Disk : >>%temp%\intro_tmp.txt ECHO. >>%temp%\intro_tmp.txt TYPE %temp%\intro_tmp.txt TYPE %temp%\wmic_tmp.txt ECHO. ECHO Type E for Disk (E:) ECHO Type F for Disk (F:) ECHO Type G for Disk (G:) ECHO Type H for Disk (H:) ECHO Type I for Disk (I:) ECHO Type J for Disk (J:) ECHO Type K for Disk (K:) ECHO Type L for Disk (L:) ECHO Type M for Disk (M:) ECHO Type N for Disk (N:) ECHO Type O for Disk (O:) ECHO Type P for Disk (P:) ECHO Type Q for Disk (Q:) ECHO Type R for Disk (R:) ECHO Type S for Disk (S:) ECHO. ECHO Type X To Quit this Batch File IF NOT '%badslct%'=='' ECHO. IF NOT '%badslct%'=='' ECHO The selected Letter %badslct% is NOT Valid ! ! ! Choose an other selection . . . . SET badslct= ECHO. IF NOT '%badslct1%'=='' ECHO. IF NOT '%badslct1%'=='' ECHO. The Disk " (%ldisk%:) " NOT Exists ! ! ! Choose an other selection . . . . IF NOT '%badslct1%'=='' ECHO. IF NOT '%badslct1%'=='' ECHO. SET badslct1= SET /P slct= Type Here Your Choice and Press Enter: CALL :set_up IF '%slct%'=='E' GOTO :rdisk IF '%slct%'=='F' GOTO :rdisk IF '%slct%'=='G' GOTO :rdisk IF '%slct%'=='H' GOTO :rdisk IF '%slct%'=='I' GOTO :rdisk IF '%slct%'=='J' GOTO :rdisk IF '%slct%'=='K' GOTO :rdisk IF '%slct%'=='L' GOTO :rdisk IF '%slct%'=='M' GOTO :rdisk IF '%slct%'=='N' GOTO :rdisk IF '%slct%'=='O' GOTO :rdisk IF '%slct%'=='P' GOTO :rdisk IF '%slct%'=='Q' GOTO :rdisk IF '%slct%'=='R' GOTO :rdisk IF '%slct%'=='S' GOTO :rdisk IF '%slct%'=='X' GOTO :end SET badslct=" %slct% " GOTO :start :rdisk CLS SET ldisk=%slct% IF NOT EXIST %ldisk%:\. SET badslct1=" %slct% " IF NOT EXIST %ldisk%:\. GOTO :start ECHO. >%temp%\disk_tmp.txt ECHO. >>%temp%\disk_tmp.txt IF EXIST %ldisk%:\. WMIC logicaldisk where deviceid="%ldisk%:" get drivetype | FINDSTR /C:"2" >NUL IF %errorlevel%==0 ( SET CHKRM=and is WELL ) else ( SET CHKRM=but is NOT ) IF EXIST %ldisk%:\. ECHO The Disk " (%ldisk%:) " Exists, %CHKRM% a REMOVABLE Disk ! ! ! Choose a selection . . . . >>%temp%\disk_tmp.txt ECHO. >>%temp%\disk_tmp.txt ECHO. >>%temp%\disk_tmp.txt TYPE %temp%\intro_tmp.txt TYPE %temp%\wmic_tmp.txt TYPE %temp%\disk_tmp.txt IF EXIST %ldisk%:\. GOTO :disk1 :start1 CLS IF NOT '%badslct%'=='' ECHO The selected Letter %badslct% is NOT Valid ! ! ! Choose an other selection . . . . >%temp%\badst_tmp.txt SET badslct= ECHO. >>%temp%\badst_tmp.txt TYPE %temp%\intro_tmp.txt TYPE %temp%\wmic_tmp.txt TYPE %temp%\disk_tmp.txt TYPE %temp%\badst_tmp.txt :disk1 SET slct= ECHO Type C To Continue this process ECHO Type M To Return to the Main Menu ECHO Type X To Quit this Batch File SET badslct= ECHO. SET /P slct= Type Here Your Choice and Press Enter: CALL :set_up IF '%slct%'=='C' GOTO :disk2 IF '%slct%'=='M' GOTO :strt0 IF '%slct%'=='X' GOTO :end SET badslct=" %slct% " GOTO :start1 :disk2 ECHO. ECHO. IF EXIST %ldisk%:\autorun.inf\. GOTO :exst IF EXIST %ldisk%:\autorun.inf ATTRIB -h -s -r %ldisk%:\autorun.inf IF EXIST %ldisk%:\autorun.inf DEL /F /Q %ldisk%:\autorun.inf >NUL :exst IF NOT EXIST %ldisk%:\autorun.inf\. MKDIR %ldisk%:\autorun.inf IF EXIST %ldisk%:\autorun.inf\. ECHO %ldisk%:\autorun.inf >%temp%\exst_tmp.txt IF NOT EXIST %ldisk%:\autorun.inf\con\. MKDIR \\.\\%ldisk%:\autorun.inf\con IF EXIST %ldisk%:\autorun.inf\con\. ECHO %ldisk%:\autorun.inf\con >>%temp%\exst_tmp.txt IF NOT EXIST %ldisk%:\autorun.inf\con\aux\. MKDIR \\.\\%ldisk%:\autorun.inf\con\aux IF EXIST %ldisk%:\autorun.inf\con\aux\. ECHO %ldisk%:\autorun.inf\con\aux >>%temp%\exst_tmp.txt IF NOT EXIST %ldisk%:\autorun.inf\con\aux\nul\. MKDIR \\.\\%ldisk%:\autorun.inf\con\aux\nul IF EXIST %ldisk%:\autorun.inf\con\aux\nul\. ECHO %ldisk%:\autorun.inf\con\aux\nul >>%temp%\exst_tmp.txt IF EXIST %ldisk%:\autorun.inf\. ATTRIB +h +s +r %ldisk%:\autorun.inf IF EXIST %ldisk%:\autorun.inf\. TYPE %temp%\exst_tmp.txt IF NOT EXIST %ldisk%:\autorun.inf\. ECHO Access is denied. >%temp%\exst_tmp.txt IF NOT EXIST %ldisk%:\autorun.inf\. ECHO Access is denied. >>%temp%\exst_tmp.txt IF NOT EXIST %ldisk%:\autorun.inf\. ECHO Access is denied. >>%temp%\exst_tmp.txt IF NOT EXIST %ldisk%:\autorun.inf\. ECHO Access is denied. >>%temp%\exst_tmp.txt IF EXIST %ldisk%:\autorun.inf\. ECHO. >%temp%\scssf_tmp.txt IF EXIST %ldisk%:\autorun.inf\. ECHO. >>%temp%\scssf_tmp.txt IF EXIST %ldisk%:\autorun.inf\. ECHO Bacht Job Successful ! ! ! The Disk " (%ldisk%:) " is Protected to " AUTORUN.INF " . . . . >>%temp%\scssf_tmp.txt IF NOT EXIST %ldisk%:\autorun.inf\. ECHO. >%temp%\scssf_tmp.txt IF NOT EXIST %ldisk%:\autorun.inf\. ECHO. >>%temp%\scssf_tmp.txt IF NOT EXIST %ldisk%:\autorun.inf\. ECHO Bacht Job NOT Successful ! ! ! The Disk " (%ldisk%:) " is NOT Protected to " AUTORUN.INF " . . . . >>%temp%\scssf_tmp.txt ECHO. >>%temp%\scssf_tmp.txt ECHO. >>%temp%\scssf_tmp.txt TYPE %temp%\scssf_tmp.txt IF EXIST %ldisk%:\. GOTO :disk3 :start2 CLS IF NOT '%badslct%'=='' ECHO The selected Letter %badslct% is NOT Valid ! ! ! Choose an other selection . . . . >%temp%\badst_tmp.txt ECHO. >>%temp%\badst_tmp.txt SET badslct= TYPE %temp%\intro_tmp.txt TYPE %temp%\wmic_tmp.txt TYPE %temp%\disk_tmp.txt TYPE %temp%\exst_tmp.txt TYPE %temp%\scssf_tmp.txt TYPE %temp%\badst_tmp.txt :disk3 SET slct= ECHO Type M To Return to the Main Menu ECHO Type X To Quit this Batch File SET badslct= ECHO. SET /P slct= Type Here Your Choice and Press Enter: CALL :set_up IF '%slct%'=='M' GOTO :strt0 IF '%slct%'=='X' GOTO :end SET badslct=" %slct% " ECHO. GOTO :start2 :end IF EXIST %temp%\badst_tmp.txt DEL /F /Q %temp%\badst_tmp.txt >NUL IF EXIST %temp%\disk_tmp.txt DEL /F /Q %temp%\disk_tmp.txt >NUL IF EXIST %temp%\exst_tmp.txt DEL /F /Q %temp%\exst_tmp.txt >NUL IF EXIST %temp%\intro_tmp.txt DEL /F /Q %temp%\intro_tmp.txt >NUL IF EXIST %temp%\scssf_tmp.txt DEL /F /Q %temp%\scssf_tmp.txt >NUL IF EXIST %temp%\wmic_tmp.txt DEL /F /Q %temp%\wmic_tmp.txt >NUL GOTO :eof :set_up IF '%slct%'=='a' SET slct=A IF '%slct%'=='b' SET slct=B IF '%slct%'=='c' SET slct=C IF '%slct%'=='d' SET slct=D IF '%slct%'=='e' SET slct=E IF '%slct%'=='f' SET slct=F IF '%slct%'=='g' SET slct=G IF '%slct%'=='h' SET slct=H IF '%slct%'=='i' SET slct=I IF '%slct%'=='j' SET slct=J IF '%slct%'=='k' SET slct=K IF '%slct%'=='l' SET slct=L IF '%slct%'=='m' SET slct=M IF '%slct%'=='n' SET slct=N IF '%slct%'=='o' SET slct=O IF '%slct%'=='p' SET slct=P IF '%slct%'=='q' SET slct=Q IF '%slct%'=='r' SET slct=R IF '%slct%'=='s' SET slct=S IF '%slct%'=='t' SET slct=T IF '%slct%'=='u' SET slct=U IF '%slct%'=='v' SET slct=V IF '%slct%'=='w' SET slct=W IF '%slct%'=='x' SET slct=X IF '%slct%'=='y' SET slct=Y IF '%slct%'=='z' SET slct=Z :eof <|start_filename|>grepWinNP3/src/resource.h<|end_filename|> //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by Notepad3\grepWinNP3\src\Resources\grepWin.rc // encoding: CP-1252 #define IDS_APP_TITLE 103 #define IDS_NAME 104 #define IDS_SEARCHSTRING 105 #define IDS_REPLACESTRING 106 #define IDI_GREPWIN 107 #define IDS_NOTESTTEXTAVAILABLE 107 #define IDS_SEARCHSTRINGEMPTY 108 #define IDC_GREPWIN 109 #define IDS_NOREPLACETEXT 110 #define IDS_NOMATCH 111 #define IDS_PATTERN_TT 112 #define IDS_EXCLUDEDIR_TT 113 #define IDS_SEARCHPATH_TT 114 #define IDS_DOTMATCHNEWLINE_TT 115 #define IDS_SEARCHTEXT_TT 116 #define IDS_ONLYONE_TT 117 #define IDS_EDITMULTILINE_TT 118 #define IDS_ABOUT 119 #define IDS_LESSTHAN 120 #define IDS_EQUALTO 121 #define IDS_GREATERTHAN 122 #define IDS_SEARCH 123 #define IDS_REPLACECONFIRM 124 #define IDS_ANEMPTYSTRING 125 #define IDS_STOP 126 #define IDS_SELECTPATHTOSEARCH 127 #define IDS_INFOLABEL 128 #define IDD_SEARCHDLG 129 #define IDS_READERROR 129 #define IDD_REGEXTEST 130 #define IDS_BINARY 130 #define IDD_NAME 131 #define IDS_REGEXOK 131 #define IDD_BOOKMARKS 132 #define IDS_REGEXINVALID 132 #define IDC_BKPOPUP 133 #define IDS_SIZE 133 #define IDS_LINE 134 #define IDD_ABOUT 135 #define IDS_MATCHES 135 #define IDR_SEARCHDLG 136 #define IDS_TEXT 136 #define IDD_MULTILINEEDIT 137 #define IDS_PATH 137 #define IDD_SETTINGS 138 #define IDS_ENCODING 138 #define IDS_DATEMODIFIED 139 #define IDR_RTF1 139 #define IDR_INFODLG 139 #define IDS_SELECTEDITOR 140 #define IDS_OPENWITHEDITOR 141 #define IDS_OPENCONTAININGFOLDER 142 #define IDS_COPYPATH 143 #define IDS_COPYPATHS 144 #define IDS_COPYFILENAME 145 #define IDS_COPYFILENAMES 146 #define IDS_COPYRESULT 147 #define IDS_COPYRESULTS 148 #define IDS_XMOREMATCHES 149 #define IDS_CONTEXTLINE 150 #define IDS_INFOLABELFILE 151 #define IDS_ERR_RELATIVEPATH 152 #define IDS_ERR_INVALID_PATH 153 #define IDS_PROGRAMS 154 #define IDS_ALLFILES 155 #define IDS_BACKUPINFOLDER_TT 156 #define IDS_SHIFT_NOTSEARCH 157 #define IDS_FILEEXT 158 #define IDS_DARKMODE_TT 159 #define IDS_ERR_PATHNOTEXIST 160 #define IDS_INVERSESEARCH 161 #define IDS_SEARCHINFOUNDFILES 162 #define IDS_EXPORT_TT 163 #define IDS_EXPORTTITLE 164 #define IDS_EXPORTPATHS 165 #define IDS_EXPORTMATCHLINENUMBER 166 #define IDS_EXPORTMATCHLINECONTENT 167 #define IDS_UPDATEAVAILABLE 168 #define IDS_CAPTURESEARCH 169 #define IDS_CLONE 170 #define IDS_NEWINSTANCE_TT 171 #define IDS_REPLACEUTF8 172 #define IDS_INFOLABELSEL 173 #define IDC_SEARCHTEXT 1000 #define IDC_REGEXRADIO 1001 #define IDC_TEXTRADIO 1002 #define IDC_WHOLEWORDS 1003 #define IDC_REGEXOKLABEL 1004 #define IDC_ALLSIZERADIO 1005 #define IDC_SIZERADIO 1006 #define IDC_SIZECOMBO 1007 #define IDC_SIZEEDIT 1008 #define IDC_INCLUDESYSTEM 1009 #define IDC_INCLUDEHIDDEN 1010 #define IDC_INCLUDESUBFOLDERS 1011 #define IDC_SEARCHPATH 1012 #define IDC_SEARCHPATHBROWSE 1013 #define IDC_RESULTLIST 1014 #define IDC_GROUPSEARCHIN 1015 #define IDC_GROUPSEARCHFOR 1016 #define IDC_GROUPLIMITSEARCH 1017 #define IDC_GROUPSEARCHRESULTS 1018 #define IDC_KBTEXT 1019 #define IDC_SEARCHINFOLABEL 1020 #define IDC_ADDTOBOOKMARKS 1021 #define IDC_BOOKMARKS 1022 #define IDC_REPLACETEXT 1023 #define IDC_NEWINSTANCE 1024 #define IDC_SEARCHFORLABEL 1026 #define IDC_REPLACEWITHLABEL 1027 #define IDC_TESTREGEX 1028 #define IDC_CREATEBACKUP 1029 #define IDC_TEXTCONTENT 1030 #define IDC_REGEXMATCH 1031 #define IDC_REGEXREPLACED 1032 #define IDC_NAME 1037 #define IDC_PATTERNLABEL 1039 #define IDC_PATTERN 1040 #define IDC_EXCLUDE_DIRS_PATTERNLABEL 1041 #define IDC_CASE_SENSITIVE 1042 #define IDC_VERSIONINFO 1043 #define IDC_EXCLUDEDIRSPATTERN 1043 #define IDC_DATE 1044 #define IDC_WEBLINK 1045 #define IDC_FILEPATTERNREGEX 1046 #define IDC_FILEPATTERNTEXT 1048 #define IDC_REPLACE 1049 #define IDC_INCLUDEBINARY 1050 #define IDC_DOTMATCHNEWLINE 1051 #define IDC_ABOUTLINK 1052 #define IDC_UTF8 1053 #define IDC_UTF9 1054 #define IDC_BINARY 1054 #define IDC_ABOUTLINK2 1055 #define IDC_INFOLABEL 1056 #define IDC_RESULTFILES 1059 #define IDC_RADIO2 1060 #define IDC_RESULTCONTENT 1060 #define IDC_BUTTON1 1061 #define IDC_HELPBUTTON 1061 #define IDC_EDITMULTILINE1 1061 #define IDC_CHECK1 1062 #define IDC_ESCKEY 1062 #define IDC_INCLUDEPATH 1062 #define IDC_EDITMULTILINE2 1063 #define IDC_ONLYONE 1063 #define IDC_PATHMRU 1064 #define IDC_DARKMODE 1064 #define IDC_HELPLABEL 1065 #define IDC_EXCLUDEDIRMRU 1066 #define IDC_EDITORCMD 1066 #define IDC_PATTERNMRU 1067 #define IDC_EDITORGROUP 1067 #define IDC_STATIC1 1068 #define IDC_STATIC2 1069 #define IDC_SETTINGSBUTTON 1071 #define IDC_PROGRESS 1072 #define IDC_LANGUAGE 1073 #define IDC_STATIC3 1074 #define IDC_STATIC4 1075 #define IDC_DWM 1076 #define IDC_BACKUPINFOLDER 1077 #define IDC_RADIO_DATE_ALL 1078 #define IDC_BACKUPINFOLDER2 1078 #define IDC_NOWARNINGIFNOBACKUP 1078 #define IDC_RADIO_DATE_NEWER 1079 #define IDC_RADIO_DATE_OLDER 1080 #define IDC_RADIO_DATE_BETWEEN 1081 #define IDC_DATEPICK1 1082 #define IDC_DATEPICK2 1083 #define IDC_DARKMODEINFO 1083 #define IDC_INVERSESEARCH 1084 #define IDC_SEARCHINFOUNDFILES 1085 #define IDC_EXPORT 1086 #define IDC_UPDATELINK 1087 #define IDC_DOUPDATECHECKS 1088 #define IDC_CAPTURESEARCH 1089 #define IDC_EDIT1 1090 #define IDC_NUMNULL 1090 #define IDC_SYSLINK1 1091 #define IDC_RESETDEFAULT 3000 #define IDC_NP3_DISCLAIMER 3001 #define IDC_SPIN_MAXWORKER 3002 #define IDC_MAXNUMWORKER 3003 #define IDC_TEXT_NUMOFWORKER 3004 #define IDC_ENTRYCONTEXTMENU 3005 #define IDS_STAY_ON_TOP 3006 #define ID_REMOVEBOOKMARK 32771 #define ID_DUMMY_RENAMEPRESET 32774 #define ID_RENAMEBOOKMARK 32775 #define IDC_STATIC -1 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NO_MFC 1 #define _APS_NEXT_RESOURCE_VALUE 140 #define _APS_NEXT_COMMAND_VALUE 32776 #define _APS_NEXT_CONTROL_VALUE 1092 #define _APS_NEXT_SYMED_VALUE 110 #endif #endif <|start_filename|>src/uchardet/uchardet/src/LangModels/LangBelarusianModel.cpp<|end_filename|> /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "../nsSBCharSetProber.h" /********* Language model for: Belarusian *********/ /** * Generated by BuildLangModel.py * On: 2019-03-05 18:36:38.571630 **/ /* Character Mapping Table: * ILL: illegal character. * CTR: control character specific to the charset. * RET: carriage/return. * SYM: symbol (punctuation) that does not belong to word. * NUM: 0 - 9. * * Other characters are ordered by probabilities * (0 is the most common character in the language). * * Orders are generic to a language. So the codepoint with order X in * CHARSET1 maps to the same character as the codepoint with the same * order X in CHARSET2 for the same language. * As such, it is possible to get missing order. For instance the * ligature of 'o' and 'e' exists in ISO-8859-15 but not in ISO-8859-1 * even though they are both used for French. Same for the euro sign. */ static const unsigned char Windows_1251_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 35, 48, 44, 47, 34, 56, 51, 54, 31, 57, 50, 42, 46, 38, 37, /* 4X */ 49, 60, 40, 36, 39, 43, 45, 52, 41, 53, 55,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 35, 48, 44, 47, 34, 56, 51, 54, 31, 57, 50, 42, 46, 38, 37, /* 6X */ 49, 60, 40, 36, 39, 43, 45, 52, 41, 53, 55,SYM,SYM,SYM,SYM,CTR, /* 7X */ SYM, 64,SYM, 65,SYM,SYM,SYM,SYM,SYM,SYM, 66,SYM, 67, 68, 69, 70, /* 8X */ 71,SYM,SYM,SYM,SYM,SYM,SYM,SYM,ILL,SYM, 72,SYM, 73, 74, 75, 76, /* 9X */ CTR, 20, 20, 77,SYM, 62,SYM,SYM, 32,SYM, 63,SYM,SYM,CTR,SYM, 61, /* AX */ SYM,SYM, 2, 2, 62, 78,SYM,SYM, 32,SYM, 63,SYM, 79, 80, 81, 61, /* BX */ 0, 21, 13, 19, 11, 8, 28, 17, 33, 24, 6, 7, 14, 1, 12, 16, /* CX */ 3, 4, 9, 15, 30, 25, 18, 22, 27, 59, 58, 5, 26, 23, 29, 10, /* DX */ 0, 21, 13, 19, 11, 8, 28, 17, 33, 24, 6, 7, 14, 1, 12, 16, /* EX */ 3, 4, 9, 15, 30, 25, 18, 22, 27, 59, 58, 5, 26, 23, 29, 10, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ /* Model Table: * Total sequences: 1419 * First 512 sequences: 0.9748335015136226 * Next 512 sequences (512-1024): 0.023605173837262638 * Rest: 0.0015613246491147821 * Negative sequences: TODO */ static const PRUint8 BelarusianLangModel[] = { 3,3,3,3,3,0,3,3,3,3,3,3,2,3,3,2,3,3,3,3,3,3,3,3,3,3,0,3,3,3, 3,1,3,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,2,3,3,3,2,3,3,3,3,3,2,1,3,2,2,3,3,0,2,3,2,0,2,3,3,2,3, 3,2,3,3,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,3,3,3,3,0,3,3,3,3,3,3,2,3,3,2,3,3,3,3,3,3,3,1,3,3,0,3,3,3, 3,1,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,2,2,3,3,3,3,3,3,1,3,3,3,3,3,2,2,3,3,0,3,3,3,0,3,2,3,3,1, 2,0,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, 3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,1,3,1,0,2,2,3,0,3,3,2,0,2, 3,2,3,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0, 2,3,3,3,3,0,3,3,3,3,3,3,1,3,3,2,3,3,3,3,3,3,3,1,3,3,0,3,3,3, 2,1,3,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,3,3,3,3,1,2,3,3,3,0,1,3,3,3,3,2,2,3,2,0,1,0,2,1,2,1,2,0,1, 1,2,2,3,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0, 3,2,3,2,2,3,3,2,3,2,3,2,3,2,2,3,1,2,2,2,0,1,2,2,0,1,3,1,2,3, 2,2,3,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,0,3,3,2,3,3,3,2,3,3,2,3,3,3,3,3,3,3,2,3,2,0,3,3,2, 2,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,3,2,3,2,3,3,3,3,1,1,1,3,3,2,3,2,2,2,2,0,2,3,3,0,2,2,1,0,1, 2,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,1,3,3,0,3,3,3,3,3,3,2,3,3,1,3,3,3,3,3,3,3,1,3,3,0,3,3,3, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,3,1,3,3,3,3,3,2,2,1,3,3,3,3,3,3,3,2,2,0,3,3,3,0,2,1,2,3,1, 1,0,1,2,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,3,2,3,3,0,3,3,3,3,2,3,1,3,3,1,3,3,3,3,3,3,3,1,3,3,0,3,3,2, 2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,2,3,2,2,3,3,2,3,2,3,2,3,1,2,3,2,1,0,1,0,0,1,2,0,1,1,1,0,2, 0,2,3,2,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,2,3,3,3,3,3,2,3,2,3,2,2,3,3,1,2,2,1,3,1,2,0,1,0,1,1,1, 2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,2,3,3,0,3,3,3,3,2,3,2,3,3,1,3,3,3,3,2,3,3,2,3,3,0,3,3,3, 2,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,3,3,3,3,1,3,1,1,3,2,1,2,1,0,1,2,2,0,1,1,2,0,0, 0,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,2,3,3,3,3,1,3,3,3,3,3,3,1,1,0,3,0,3,2,2,0,0,3,2,1,2, 0,1,3,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,2,3,1,1,3,3,2,3,3,3,0,3,3,2,3,0,0,3,1,0,2,0,3,0,0,3,1,0,3, 0,1,3,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, 3,3,3,3,2,1,2,3,3,1,1,2,3,2,3,3,1,1,0,2,0,1,2,3,0,1,0,1,0,1, 0,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,3,2,3,3,0,3,3,2,3,2,3,0,3,2,0,3,3,3,3,0,2,3,2,0,2,0,3,3,0, 1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,3,3,2,3,2,3,2,2,3,1,1,2,1,0,0,2,2,0,2,0,2,2,2, 1,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0, 3,3,0,0,0,3,3,2,2,1,0,0,3,3,2,3,1,1,1,0,0,1,2,3,0,0,0,0,1,1, 0,0,1,2,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,2,3,3,0,3,3,2,3,2,3,3,3,3,0,3,3,3,3,3,3,3,1,3,3,0,2,2,1, 3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,0,1,3,0,2,3,0,3,0,3,1,2,3,1,2,2,3,2,0,3,2,0,0,1,0,3,0,0, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,2,0,2,2,2,3,0,0,3,3,2,3,2,0,2,1,0,1,1,1,0,2,1,0,0,1, 0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,1,1,3,0,3,1,2,3,2,2,1,3,3,0,2,2,3,2,0,3,2,1,0,1,0,3,1,2, 2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,0,2,2,3,3,3,2,3,0,0,3,2,3,3,2,0,2,1,0,0,3,3,0,0,0,2,0,1, 0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,1,1,2,3,2,1,2,0,0,2,3,2,1,3,2,1,2,1,0,2,2,3,0,0,0,0,2,0, 0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,2,1,3,2,0,2,2,2,3,0,3,0,2,2,0,0,3,3,0,0,3,3,0,0,2,0,2,1,2, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0, 3,2,3,3,2,1,1,2,3,3,2,0,3,0,0,3,0,0,2,1,0,0,0,1,0,0,0,0,0,1, 1,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,0,1,2,0,0,1,0,1,1,0,0,1,1,0,1,0,1,1,1,0,1,0,1,1,0,0,1,0, 0,3,0,0,2,3,3,2,3,2,2,2,2,2,3,2,2,2,2,2,2,2,1,0,1,2,1,1,0,0,1, 0,3,0,3,3,0,2,3,0,2,0,2,0,3,3,0,2,2,1,2,3,0,0,1,3,1,0,1,2,2, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,0,2,2,0,2,2,2,2,2,2,2,2,2,1,2,2,2,2,0,2,2,1,2,2,0,2,0,1, 1,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,0,0,2,2,2,2,3,2,3,2,2,2,2,1,2,3,2,2,2,2,2,1,1,1,2,2,0,0,0, 0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,0,0,2,1,2,0,3,2,3,1,2,2,2,1,2,2,2,2,2,2,2,2,1,2,1,1,0,0,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,0,0,2,2,2,2,1,3,1,0,2,2,2,1,1,1,3,2,2,0,0,2,2,2,1,1,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,1,0,0,1,1,2,2,3,2,3,1,2,2,2,2,2,2,2,2,2,2,2,1,1,1,2,2,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,0,0,2,2,2,2,2,2,1,0,1,2,2,1,1,2,1,0,1,2,0,1,1,1,2,1,0,0,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,0,0,3,2,2,2,1,2,2,0,0,2,2,1,2,0,2,1,2,0,2,2,2,1,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,0,0,3,3,2,2,2,2,2,0,2,2,2,2,2,2,2,1,2,2,1,2,0,2,0,1,0,0,0, 0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,0,0,0,1,0,0,0,0,0,2,1,1,1,3,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,0,0,2,2,2,2,2,2,1,0,2,2,2,1,0,2,1,1,2,1,1,1,1,0,1,1,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,1,0,0,2,2,3,1,2,3,2,1,2,0,2,1,2,2,2,2,1,2,0,0,1,1,1,0,0,0,0, 0,0,1,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0, 0,2,0,0,2,2,1,2,0,2,2,0,2,2,1,0,0,1,0,0,2,0,0,2,2,2,0,1,0,0,0, 0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,0,0,2,2,0,2,0,0,1,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,0,0,2,3,2,2,1,1,0,0,1,2,1,0,2,1,2,1,0,0,0,2,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,0,0,2,2,1,2,1,1,2,0,1,2,0,1,0,1,1,0,0,1,1,1,0,2,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,0,0,2,2,1,2,3,0,2,0,2,2,1,0,0,1,1,0,0,0,0,2,1,0,0,0,0,0,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0, 0,2,0,0,2,2,2,2,1,1,2,0,2,2,0,0,1,1,0,1,0,1,1,1,2,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,0,0,2,2,1,2,1,0,2,0,1,2,1,0,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,0,0,2,2,1,2,2,0,2,0,2,2,0,0,1,0,1,1,0,1,0,1,2,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,0,0,2,2,2,2,2,0,0,0,1,0,0,1,0,0,0,1,1,0,2,2,0,1,0,0,0,0,0, 0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,1,0,0,1,1,2,1,2,2,1,0,1,0,2,0,1,2,1,1,1,1,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,0,0,2,2,0,2,1,2,1,0,1,2,0,0,0,0,0,1,0,1,1,1,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,0,0,2,2,0,1,2,0,1,0,0,1,1,0,1,0,2,1,0,1,0,2,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,0,0,2,2,0,2,0,2,2,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,2,2,1,2,1,0,1,0,0,1,0,0,1,0,1,0,0,1,0,0,0,0,1,0,0,0,0, 0,0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0, }; const SequenceModel Windows_1251BelarusianModel = { Windows_1251_CharToOrderMap, BelarusianLangModel, 61, (float)0.9748335015136226, PR_TRUE, "WINDOWS-1251" }; <|start_filename|>grepWinNP3/sktoolslib_mod/BaseDialog.cpp<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012-2013, 2015-2017, 2020-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "BaseDialog.h" #include <CommCtrl.h> #include <WindowsX.h> static HWND g_hDlgCurrent = nullptr; INT_PTR CDialog::DoModal(HINSTANCE hInstance, int resID, HWND hWndParent) { m_bPseudoModal = false; hResource = hInstance; return DialogBoxParam(hInstance, MAKEINTRESOURCE(resID), hWndParent, &CDialog::stDlgFunc, reinterpret_cast<LPARAM>(this)); } INT_PTR CDialog::DoModal(HINSTANCE hInstance, LPCDLGTEMPLATE pDlgTemplate, HWND hWndParent) { m_bPseudoModal = false; hResource = hInstance; return DialogBoxIndirectParam(hInstance, pDlgTemplate, hWndParent, &CDialog::stDlgFunc, reinterpret_cast<LPARAM>(this)); } INT_PTR CDialog::DoModal(HINSTANCE hInstance, int resID, HWND hWndParent, UINT idAccel) { m_bPseudoModal = true; m_bPseudoEnded = false; hResource = hInstance; m_hwnd = CreateDialogParam(hInstance, MAKEINTRESOURCE(resID), hWndParent, &CDialog::stDlgFunc, reinterpret_cast<LPARAM>(this)); // deactivate the parent window if (hWndParent) ::EnableWindow(hWndParent, FALSE); ShowWindow(m_hwnd, SW_SHOW); ::BringWindowToTop(m_hwnd); ::SetForegroundWindow(m_hwnd); // Main message loop: MSG msg = {nullptr}; HACCEL hAccelTable = LoadAccelerators(hResource, MAKEINTRESOURCE(idAccel)); BOOL bRet = TRUE; while (!m_bPseudoEnded && ((bRet = GetMessage(&msg, nullptr, 0, 0)) != 0)) { if (bRet == -1) { // handle the error and possibly exit break; } else { if (!PreTranslateMessage(&msg)) { if (!TranslateAccelerator(m_hwnd, hAccelTable, &msg) && !::IsDialogMessage(m_hwnd, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } } } if (msg.message == WM_QUIT) PostQuitMessage(static_cast<int>(msg.wParam)); // re-enable the parent window if (hWndParent) ::EnableWindow(hWndParent, TRUE); DestroyWindow(m_hwnd); if (m_bPseudoModal) return m_iPseudoRet; return msg.wParam; } BOOL CDialog::EndDialog(HWND hDlg, INT_PTR nResult) { if (m_bPseudoModal) { m_bPseudoEnded = true; m_iPseudoRet = nResult; } return ::EndDialog(hDlg, nResult); } HWND CDialog::Create(HINSTANCE hInstance, int resID, HWND hWndParent) { m_bPseudoModal = true; hResource = hInstance; m_hwnd = CreateDialogParam(hInstance, MAKEINTRESOURCE(resID), hWndParent, &CDialog::stDlgFunc, reinterpret_cast<LPARAM>(this)); return m_hwnd; } void CDialog::ShowModeless(HINSTANCE hInstance, int resID, HWND hWndParent, bool show /* = true*/) { if (m_hwnd == nullptr) { hResource = hInstance; m_hwnd = CreateDialogParam(hInstance, MAKEINTRESOURCE(resID), hWndParent, &CDialog::stDlgFunc, reinterpret_cast<LPARAM>(this)); } if (show) { ShowWindow(m_hwnd, SW_SHOW); SetFocus(m_hwnd); } } void CDialog::ShowModeless(HINSTANCE hInstance, LPCDLGTEMPLATE pDlgTemplate, HWND hWndParent, bool show /* = true*/) { if (m_hwnd == nullptr) { hResource = hInstance; m_hwnd = CreateDialogIndirectParam(hInstance, pDlgTemplate, hWndParent, &CDialog::stDlgFunc, reinterpret_cast<LPARAM>(this)); } if (show) { ShowWindow(m_hwnd, SW_SHOW); SetFocus(m_hwnd); } } void CDialog::InitDialog(HWND hwndDlg, UINT iconID, bool bPosition /* = true*/) { RECT rc, rcDlg, rcOwner; WINDOWPLACEMENT placement; placement.length = sizeof(WINDOWPLACEMENT); HWND hwndOwner = ::GetParent(hwndDlg); GetWindowPlacement(hwndOwner, &placement); if ((hwndOwner == nullptr) || (placement.showCmd == SW_SHOWMINIMIZED) || (placement.showCmd == SW_SHOWMINNOACTIVE)) hwndOwner = ::GetDesktopWindow(); GetWindowRect(hwndOwner, &rcOwner); GetWindowRect(hwndDlg, &rcDlg); CopyRect(&rc, &rcOwner); OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top); OffsetRect(&rc, -rc.left, -rc.top); OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom); if (bPosition) SetWindowPos(hwndDlg, HWND_TOP, rcOwner.left + (rc.right / 2), rcOwner.top + (rc.bottom / 2), 0, 0, SWP_NOSIZE | SWP_SHOWWINDOW); HICON hIcon = static_cast<HICON>(::LoadImage(hResource, MAKEINTRESOURCE(iconID), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE | LR_SHARED)); ::SendMessage(hwndDlg, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(hIcon)); ::SendMessage(hwndDlg, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(hIcon)); m_dwm.Initialize(); m_margins.cxLeftWidth = 0; m_margins.cxRightWidth = 0; m_margins.cyBottomHeight = 0; m_margins.cyTopHeight = 0; } void CDialog::AddToolTip(UINT ctrlID, LPCWSTR text) { TOOLINFO tt; tt.cbSize = sizeof(TOOLINFO); tt.uFlags = TTF_IDISHWND | TTF_SUBCLASS; tt.hwnd = text == LPSTR_TEXTCALLBACK ? *this : GetDlgItem(*this, ctrlID); tt.uId = reinterpret_cast<UINT_PTR>(GetDlgItem(*this, ctrlID)); tt.lpszText = const_cast<LPWSTR>(text); SendMessage(m_hToolTips, TTM_ADDTOOL, 0, reinterpret_cast<LPARAM>(&tt)); } void CDialog::AddToolTip(HWND hWnd, LPCWSTR text) const { TOOLINFO tt; tt.cbSize = sizeof(TOOLINFO); tt.uFlags = TTF_IDISHWND | TTF_SUBCLASS; tt.hwnd = hWnd; tt.uId = reinterpret_cast<UINT_PTR>(hWnd); tt.lpszText = const_cast<LPWSTR>(text); SendMessage(m_hToolTips, TTM_ADDTOOL, 0, reinterpret_cast<LPARAM>(&tt)); } INT_PTR CALLBACK CDialog::stDlgFunc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { static bool bInDlgProc = false; if (bInDlgProc) return FALSE; CDialog* pWnd; switch (uMsg) { case WM_INITDIALOG: { // get the pointer to the window from lpCreateParams SetWindowLongPtr(hwndDlg, GWLP_USERDATA, lParam); pWnd = reinterpret_cast<CDialog*>(lParam); pWnd->m_hwnd = hwndDlg; // create the tooltip control pWnd->m_hToolTips = CreateWindowEx(0, TOOLTIPS_CLASS, nullptr, WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, hwndDlg, nullptr, pWnd->hResource, nullptr); SetWindowPos(pWnd->m_hToolTips, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); SendMessage(pWnd->m_hToolTips, TTM_SETMAXTIPWIDTH, 0, 600); SendMessage(pWnd->m_hToolTips, TTM_ACTIVATE, TRUE, 0); } break; } // get the pointer to the window pWnd = GetObjectFromWindow(hwndDlg); // if we have the pointer, go to the message handler of the window if (pWnd) { LRESULT lRes = pWnd->DlgFunc(hwndDlg, uMsg, wParam, lParam); switch (uMsg) { case WM_DWMCOMPOSITIONCHANGED: pWnd->OnCompositionChanged(); break; case WM_ERASEBKGND: { if (pWnd->m_dwm.IsDwmCompositionEnabled()) { bInDlgProc = true; DefDlgProc(hwndDlg, uMsg, wParam, lParam); bInDlgProc = false; HDC hdc = reinterpret_cast<HDC>(wParam); // draw the frame margins in black RECT rc; GetClientRect(hwndDlg, &rc); if (pWnd->m_margins.cxLeftWidth < 0) { SetBkColor(hdc, RGB(0, 0, 0)); ::ExtTextOut(hdc, 0, 0, ETO_OPAQUE, &rc, nullptr, 0, nullptr); } else { SetBkColor(hdc, RGB(0, 0, 0)); RECT rect; rect.left = rc.left; rect.top = rc.top; rect.right = rc.left + pWnd->m_margins.cxLeftWidth; rect.bottom = rc.bottom; ::ExtTextOut(hdc, 0, 0, ETO_OPAQUE, &rect, nullptr, 0, nullptr); rect.left = rc.left; rect.top = rc.top; rect.right = rc.right; rect.bottom = rc.top + pWnd->m_margins.cyTopHeight; ::ExtTextOut(hdc, 0, 0, ETO_OPAQUE, &rect, nullptr, 0, nullptr); rect.left = rc.right - pWnd->m_margins.cxRightWidth; rect.top = rc.top; rect.right = rc.right; rect.bottom = rc.bottom; ::ExtTextOut(hdc, 0, 0, ETO_OPAQUE, &rect, nullptr, 0, nullptr); rect.left = rc.left; rect.top = rc.bottom - pWnd->m_margins.cyBottomHeight; rect.right = rc.right; rect.bottom = rc.bottom; ::ExtTextOut(hdc, 0, 0, ETO_OPAQUE, &rect, nullptr, 0, nullptr); } lRes = TRUE; } } break; case WM_NCHITTEST: { if (pWnd->m_dwm.IsDwmCompositionEnabled()) { POINTS pts = MAKEPOINTS(lParam); POINT pt; pt.x = pts.x; pt.y = pts.y; RECT rc; GetClientRect(hwndDlg, &rc); MapWindowPoints(hwndDlg, nullptr, reinterpret_cast<LPPOINT>(&rc), 2); if (pWnd->m_margins.cxLeftWidth < 0) { lRes = PtInRect(&rc, pt) ? HTCAPTION : FALSE; } else { RECT m = rc; m.left += pWnd->m_margins.cxLeftWidth; m.top += pWnd->m_margins.cyTopHeight; m.right -= pWnd->m_margins.cxRightWidth; m.bottom -= pWnd->m_margins.cyBottomHeight; lRes = (PtInRect(&rc, pt) && !PtInRect(&m, pt)) ? HTCAPTION : FALSE; } } } break; case WM_ACTIVATE: if (0 == wParam) // becoming inactive g_hDlgCurrent = nullptr; else // becoming active g_hDlgCurrent = hwndDlg; break; default: break; } SetWindowLongPtr(hwndDlg, DWLP_MSGRESULT, lRes); return lRes; } else return 0; } bool CDialog::PreTranslateMessage(MSG* /*pMsg*/) { return false; } bool CDialog::IsCursorOverWindowBorder() { RECT wrc, crc; GetWindowRect(*this, &wrc); GetClientRect(*this, &crc); MapWindowPoints(*this, nullptr, reinterpret_cast<LPPOINT>(&crc), 2); DWORD pos = GetMessagePos(); POINT pt; pt.x = GET_X_LPARAM(pos); pt.y = GET_Y_LPARAM(pos); return (PtInRect(&wrc, pt) && !PtInRect(&crc, pt)); } /** * Wrapper around the CWnd::EnableWindow() method, but * makes sure that a control that has the focus is not disabled * before the focus is passed on to the next control. */ bool CDialog::DialogEnableWindow(UINT nID, bool bEnable) { HWND hwndDlgItem = GetDlgItem(*this, nID); if (hwndDlgItem == nullptr) return false; if (bEnable) return !!EnableWindow(hwndDlgItem, bEnable); if (GetFocus() == hwndDlgItem) { SendMessage(*this, WM_NEXTDLGCTL, 0, false); } return !!EnableWindow(hwndDlgItem, bEnable); } void CDialog::OnCompositionChanged() { if (m_dwm.IsDwmCompositionEnabled()) { m_dwm.DwmExtendFrameIntoClientArea(*this, &m_margins); } } void CDialog::ExtendFrameIntoClientArea(UINT leftControl, UINT topControl, UINT rightControl, UINT botomControl) { if (!m_dwm.IsDwmCompositionEnabled()) return; RECT rc, rc2; GetWindowRect(*this, &rc); GetClientRect(*this, &rc2); MapWindowPoints(*this, nullptr, reinterpret_cast<LPPOINT>(&rc2), 2); RECT rcControl; if (leftControl && leftControl != -1) { HWND hw = GetDlgItem(*this, leftControl); if (hw == nullptr) return; ::GetWindowRect(hw, &rcControl); m_margins.cxLeftWidth = rcControl.left - rc.left; m_margins.cxLeftWidth -= (rc2.left - rc.left); } else m_margins.cxLeftWidth = 0; if (topControl && topControl != -1) { HWND hw = GetDlgItem(*this, topControl); if (hw == nullptr) return; ::GetWindowRect(hw, &rcControl); m_margins.cyTopHeight = rcControl.top - rc.top; m_margins.cyTopHeight -= (rc2.top - rc.top); } else m_margins.cyTopHeight = 0; if (rightControl && rightControl != -1) { HWND hw = GetDlgItem(*this, rightControl); if (hw == nullptr) return; ::GetWindowRect(hw, &rcControl); m_margins.cxRightWidth = rc.right - rcControl.right; m_margins.cxRightWidth -= (rc.right - rc2.right); } else m_margins.cxRightWidth = 0; if (botomControl && botomControl != -1) { HWND hw = GetDlgItem(*this, botomControl); if (hw == nullptr) return; ::GetWindowRect(hw, &rcControl); m_margins.cyBottomHeight = rc.bottom - rcControl.bottom; m_margins.cyBottomHeight -= (rc.bottom - rc2.bottom); } else m_margins.cyBottomHeight = 0; if ((m_margins.cxLeftWidth == 0) && (m_margins.cyTopHeight == 0) && (m_margins.cxRightWidth == 0) && (m_margins.cyBottomHeight == 0)) { m_margins.cxLeftWidth = -1; m_margins.cyTopHeight = -1; m_margins.cxRightWidth = -1; m_margins.cyBottomHeight = -1; } if (m_dwm.IsDwmCompositionEnabled()) { m_dwm.DwmExtendFrameIntoClientArea(*this, &m_margins); } } int CDialog::GetDlgItemTextLength(UINT nId) { HWND hWnd = GetDlgItem(*this, nId); return GetWindowTextLength(hWnd); } std::unique_ptr<wchar_t[]> CDialog::GetDlgItemText(UINT nId) { int len = GetDlgItemTextLength(nId); len++; auto buf = std::make_unique<wchar_t[]>(len); ::GetDlgItemText(*this, nId, buf.get(), len); return buf; } void CDialog::RefreshCursor() { POINT pt; GetCursorPos(&pt); SetCursorPos(pt.x, pt.y); } void CDialog::ShowEditBalloon(UINT nId, LPCWSTR title, LPCWSTR text, int icon /*= TTI_ERROR*/) { EDITBALLOONTIP ebt = {0}; ebt.cbStruct = sizeof(EDITBALLOONTIP); ebt.pszTitle = title; ebt.pszText = text; ebt.ttiIcon = icon; if (!::SendMessage(GetDlgItem(*this, nId), EM_SHOWBALLOONTIP, 0, reinterpret_cast<LPARAM>(&ebt))) { UINT uType = MB_ICONERROR; switch (icon) { case TTI_ERROR: case TTI_ERROR_LARGE: uType = MB_ICONERROR; break; case TTI_WARNING: case TTI_WARNING_LARGE: uType = MB_ICONWARNING; break; case TTI_INFO: case TTI_INFO_LARGE: uType = MB_ICONINFORMATION; break; case TTI_NONE: uType = 0; break; } ::MessageBox(*this, text, title, uType); } } void CDialog::SetTransparency(BYTE alpha, COLORREF color /*= 0xFF000000*/) { if (alpha == 255) { LONG_PTR exStyle = GetWindowLongPtr(*this, GWL_EXSTYLE); exStyle &= ~WS_EX_LAYERED; SetWindowLongPtr(*this, GWL_EXSTYLE, exStyle); } else { LONG_PTR exStyle = GetWindowLongPtr(*this, GWL_EXSTYLE); exStyle |= WS_EX_LAYERED; SetWindowLongPtr(*this, GWL_EXSTYLE, exStyle); } COLORREF col = color; DWORD flags = LWA_ALPHA; if (col & 0xFF000000) { col = RGB(255, 255, 255); flags = LWA_ALPHA; } else { flags = LWA_COLORKEY; } SetLayeredWindowAttributes(*this, col, alpha, flags); } BOOL CDialog::IsDialogMessage(LPMSG lpMsg) { if (g_hDlgCurrent) { return ::IsDialogMessage(g_hDlgCurrent, lpMsg); } return FALSE; } RECT CDialog::AdjustControlSize(UINT nID) { HWND hwndDlgItem = GetDlgItem(*this, nID); // adjust the size of the control to fit its content auto sControlText = GetDlgItemText(nID); // next step: find the rectangle the control text needs to // be displayed HDC hDC = GetWindowDC(*this); RECT controlRect; GetWindowRect(hwndDlgItem, &controlRect); ::MapWindowPoints(nullptr, *this, reinterpret_cast<LPPOINT>(&controlRect), 2); RECT controlRectOrig = controlRect; if (hDC) { HFONT hFont = GetWindowFont(hwndDlgItem); HFONT hOldFont = static_cast<HFONT>(SelectObject(hDC, hFont)); if (DrawText(hDC, sControlText.get(), -1, &controlRect, DT_WORDBREAK | DT_EDITCONTROL | DT_EXPANDTABS | DT_LEFT | DT_CALCRECT)) { // now we have the rectangle the control really needs if ((controlRectOrig.right - controlRectOrig.left) > (controlRect.right - controlRect.left)) { // we're dealing with radio buttons and check boxes, // which means we have to add a little space for the checkbox const int checkWidth = GetSystemMetrics(SM_CXMENUCHECK) + 2 * GetSystemMetrics(SM_CXEDGE) + 3; controlRectOrig.right = controlRectOrig.left + (controlRect.right - controlRect.left) + checkWidth; MoveWindow(hwndDlgItem, controlRectOrig.left, controlRectOrig.top, controlRectOrig.right - controlRectOrig.left, controlRectOrig.bottom - controlRectOrig.top, TRUE); } } SelectObject(hDC, hOldFont); ReleaseDC(*this, hDC); } return controlRectOrig; } <|start_filename|>scintilla/src/SplitVector.h<|end_filename|> // Scintilla source code edit control /** @file SplitVector.h ** Main data structure for holding arrays that handle insertions ** and deletions efficiently. **/ // Copyright 1998-2007 by <NAME> <<EMAIL>> // The License.txt file describes the conditions under which this software may be distributed. #ifndef SPLITVECTOR_H #define SPLITVECTOR_H namespace Scintilla::Internal { template <typename T> class SplitVector { protected: std::vector<T> body; T empty; /// Returned as the result of out-of-bounds access. ptrdiff_t lengthBody; ptrdiff_t part1Length; ptrdiff_t gapLength; /// invariant: gapLength == body.size() - lengthBody ptrdiff_t growSize; /// Move the gap to a particular position so that insertion and /// deletion at that point will not require much copying and /// hence be fast. void GapTo(ptrdiff_t position) noexcept { if (position != part1Length) { try { if (gapLength > 0) { // If gap to move // This can never fail but std::move and std::move_backward are not noexcept. if (position < part1Length) { // Moving the gap towards start so moving elements towards end std::move_backward( body.data() + position, body.data() + part1Length, body.data() + gapLength + part1Length); } else { // position > part1Length // Moving the gap towards end so moving elements towards start std::move( body.data() + part1Length + gapLength, body.data() + gapLength + position, body.data() + part1Length); } } part1Length = position; } catch (...) { // Ignore any exception } } } /// Check that there is room in the buffer for an insertion, /// reallocating if more space needed. void RoomFor(ptrdiff_t insertionLength) { if (gapLength < insertionLength) { while (growSize < static_cast<ptrdiff_t>(body.size() / 6)) growSize *= 2; ReAllocate(body.size() + insertionLength + growSize); } } void Init() { body.clear(); body.shrink_to_fit(); lengthBody = 0; part1Length = 0; gapLength = 0; growSize = 8; } public: /// Construct a split buffer. SplitVector() : empty(), lengthBody(0), part1Length(0), gapLength(0), growSize(8) { } // Deleted so SplitVector objects can not be copied. SplitVector(const SplitVector &) = delete; SplitVector(SplitVector &&) = delete; void operator=(const SplitVector &) = delete; void operator=(SplitVector &&) = delete; ~SplitVector() { } ptrdiff_t GetGrowSize() const noexcept { return growSize; } void SetGrowSize(ptrdiff_t growSize_) noexcept { growSize = growSize_; } /// Reallocate the storage for the buffer to be newSize and /// copy existing contents to the new buffer. /// Must not be used to decrease the size of the buffer. void ReAllocate(ptrdiff_t newSize) { if (newSize < 0) throw std::runtime_error("SplitVector::ReAllocate: negative size."); if (newSize > static_cast<ptrdiff_t>(body.size())) { // Move the gap to the end GapTo(lengthBody); gapLength += newSize - static_cast<ptrdiff_t>(body.size()); // RoomFor implements a growth strategy but so does vector::resize so // ensure vector::resize allocates exactly the amount wanted by // calling reserve first. body.reserve(newSize); body.resize(newSize); } } /// Retrieve the element at a particular position. /// Retrieving positions outside the range of the buffer returns empty or 0. const T& ValueAt(ptrdiff_t position) const noexcept { if (position < part1Length) { if (position < 0) { return empty; } else { return body[position]; } } else { if (position >= lengthBody) { return empty; } else { return body[gapLength + position]; } } } /// Set the element at a particular position. /// Setting positions outside the range of the buffer performs no assignment /// but asserts in debug builds. template <typename ParamType> void SetValueAt(ptrdiff_t position, ParamType&& v) noexcept { if (position < part1Length) { PLATFORM_ASSERT(position >= 0); if (position < 0) { ; } else { body[position] = std::forward<ParamType>(v); } } else { PLATFORM_ASSERT(position < lengthBody); if (position >= lengthBody) { ; } else { body[gapLength + position] = std::forward<ParamType>(v); } } } /// Retrieve the element at a particular position. /// The position must be within bounds or an assertion is triggered. const T &operator[](ptrdiff_t position) const noexcept { PLATFORM_ASSERT(position >= 0 && position < lengthBody); if (position < part1Length) { return body[position]; } else { return body[gapLength + position]; } } /// Retrieve reference to the element at a particular position. /// This, instead of the const variant, can be used to mutate in-place. /// The position must be within bounds or an assertion is triggered. T &operator[](ptrdiff_t position) noexcept { PLATFORM_ASSERT(position >= 0 && position < lengthBody); if (position < part1Length) { return body[position]; } else { return body[gapLength + position]; } } /// Retrieve the length of the buffer. ptrdiff_t Length() const noexcept { return lengthBody; } /// Insert a single value into the buffer. /// Inserting at positions outside the current range fails. void Insert(ptrdiff_t position, T v) { PLATFORM_ASSERT((position >= 0) && (position <= lengthBody)); if ((position < 0) || (position > lengthBody)) { return; } RoomFor(1); GapTo(position); body[part1Length] = std::move(v); lengthBody++; part1Length++; gapLength--; } /// Insert a number of elements into the buffer setting their value. /// Inserting at positions outside the current range fails. void InsertValue(ptrdiff_t position, ptrdiff_t insertLength, T v) { PLATFORM_ASSERT((position >= 0) && (position <= lengthBody)); if (insertLength > 0) { if ((position < 0) || (position > lengthBody)) { return; } RoomFor(insertLength); GapTo(position); std::fill(body.data() + part1Length, body.data() + part1Length + insertLength, v); lengthBody += insertLength; part1Length += insertLength; gapLength -= insertLength; } } /// Add some new empty elements. /// InsertValue is good for value objects but not for unique_ptr objects /// since they can only be moved from once. /// Callers can write to the returned pointer to transform inputs without copies. T *InsertEmpty(ptrdiff_t position, ptrdiff_t insertLength) { PLATFORM_ASSERT((position >= 0) && (position <= lengthBody)); if (insertLength > 0) { if ((position < 0) || (position > lengthBody)) { return nullptr; } RoomFor(insertLength); GapTo(position); for (ptrdiff_t elem = part1Length; elem < part1Length + insertLength; elem++) { T emptyOne = {}; body[elem] = std::move(emptyOne); } lengthBody += insertLength; part1Length += insertLength; gapLength -= insertLength; } return body.data() + position; } /// Ensure at least length elements allocated, /// appending zero valued elements if needed. void EnsureLength(ptrdiff_t wantedLength) { if (Length() < wantedLength) { InsertEmpty(Length(), wantedLength - Length()); } } /// Insert text into the buffer from an array. void InsertFromArray(ptrdiff_t positionToInsert, const T s[], ptrdiff_t positionFrom, ptrdiff_t insertLength) { PLATFORM_ASSERT((positionToInsert >= 0) && (positionToInsert <= lengthBody)); if (insertLength > 0) { if ((positionToInsert < 0) || (positionToInsert > lengthBody)) { return; } RoomFor(insertLength); GapTo(positionToInsert); std::copy(s + positionFrom, s + positionFrom + insertLength, body.data() + part1Length); lengthBody += insertLength; part1Length += insertLength; gapLength -= insertLength; } } /// Delete one element from the buffer. void Delete(ptrdiff_t position) { PLATFORM_ASSERT((position >= 0) && (position < lengthBody)); DeleteRange(position, 1); } /// Delete a range from the buffer. /// Deleting positions outside the current range fails. /// Cannot be noexcept as vector::shrink_to_fit may be called and it may throw. void DeleteRange(ptrdiff_t position, ptrdiff_t deleteLength) { PLATFORM_ASSERT((position >= 0) && (position + deleteLength <= lengthBody)); if ((position < 0) || ((position + deleteLength) > lengthBody)) { return; } if ((position == 0) && (deleteLength == lengthBody)) { // Full deallocation returns storage and is faster Init(); } else if (deleteLength > 0) { GapTo(position); lengthBody -= deleteLength; gapLength += deleteLength; } } /// Delete all the buffer contents. void DeleteAll() { DeleteRange(0, lengthBody); } /// Retrieve a range of elements into an array void GetRange(T *buffer, ptrdiff_t position, ptrdiff_t retrieveLength) const { // Split into up to 2 ranges, before and after the split then use memcpy on each. ptrdiff_t range1Length = 0; if (position < part1Length) { const ptrdiff_t part1AfterPosition = part1Length - position; range1Length = retrieveLength; if (range1Length > part1AfterPosition) range1Length = part1AfterPosition; } std::copy(body.data() + position, body.data() + position + range1Length, buffer); buffer += range1Length; position = position + range1Length + gapLength; const ptrdiff_t range2Length = retrieveLength - range1Length; std::copy(body.data() + position, body.data() + position + range2Length, buffer); } /// Compact the buffer and return a pointer to the first element. /// Also ensures there is an empty element beyond logical end in case its /// passed to a function expecting a NUL terminated string. T *BufferPointer() { RoomFor(1); GapTo(lengthBody); T emptyOne = {}; body[lengthBody] = std::move(emptyOne); return body.data(); } /// Return a pointer to a range of elements, first rearranging the buffer if /// needed to make that range contiguous. T *RangePointer(ptrdiff_t position, ptrdiff_t rangeLength) noexcept { if (position < part1Length) { if ((position + rangeLength) > part1Length) { // Range overlaps gap, so move gap to start of range. GapTo(position); return body.data() + position + gapLength; } else { return body.data() + position; } } else { return body.data() + position + gapLength; } } /// Return a pointer to a single element. /// Does not rearrange the buffer. const T *ElementPointer(ptrdiff_t position) const noexcept { if (position < part1Length) { return body.data() + position; } else { return body.data() + position + gapLength; } } /// Return the position of the gap within the buffer. ptrdiff_t GapPosition() const noexcept { return part1Length; } }; } #endif <|start_filename|>lexilla/access/LexillaAccess.cxx<|end_filename|> // SciTE - Scintilla based Text Editor /** @file LexillaAccess.cxx ** Interface to loadable lexers. ** Maintains a list of lexer library paths and CreateLexer functions. ** If list changes then load all the lexer libraries and find the functions. ** When asked to create a lexer, call each function until one succeeds. **/ // Copyright 2019 by <NAME> <<EMAIL>> // The License.txt file describes the conditions under which this software may be distributed. #include <cstring> #include <string> #include <string_view> #include <vector> #include <set> #if !_WIN32 #include <dlfcn.h> #else #include <windows.h> #endif #include "ILexer.h" #include "Lexilla.h" #include "LexillaAccess.h" namespace { #if _WIN32 typedef FARPROC Function; typedef HMODULE Module; constexpr const char *pathSeparator = "\\"; #else typedef void *Function; typedef void *Module; constexpr const char *pathSeparator = "/"; #endif /// Generic function to convert from a Function(void* or FARPROC) to a function pointer. /// This avoids undefined and conditionally defined behaviour. template<typename T> T FunctionPointer(Function function) noexcept { static_assert(sizeof(T) == sizeof(function)); T fp {}; memcpy(&fp, &function, sizeof(T)); return fp; } #if _WIN32 std::wstring WideStringFromUTF8(std::string_view sv) { const int sLength = static_cast<int>(sv.length()); const int cchWide = ::MultiByteToWideChar(CP_UTF8, 0, sv.data(), sLength, nullptr, 0); std::wstring sWide(cchWide, 0); ::MultiByteToWideChar(CP_UTF8, 0, sv.data(), sLength, &sWide[0], cchWide); return sWide; } #endif // Turn off deprecation checks as LexillaAccess deprecates its wrapper over // the deprecated LexerNameFromID. Thus use within LexillaAccess is intentional. #if defined(__GNUC__) || defined(__clang__) #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #else #pragma warning(disable: 4996) #endif std::string directoryLoadDefault; std::string lastLoaded; struct LexLibrary { Lexilla::CreateLexerFn fnCL; Lexilla::LexerNameFromIDFn fnLNFI; Lexilla::GetLibraryPropertyNamesFn fnGLPN; Lexilla::SetLibraryPropertyFn fnSLP; std::string nameSpace; }; std::vector<LexLibrary> libraries; std::vector<std::string> lexers; std::vector<std::string> libraryProperties; Function FindSymbol(Module m, const char *symbol) noexcept { #if _WIN32 return ::GetProcAddress(m, symbol); #else return dlsym(m, symbol); #endif } Lexilla::CreateLexerFn pCreateLexerDefault = nullptr; bool NameContainsDot(std::string_view path) noexcept { for (std::string_view::const_reverse_iterator it = path.crbegin(); it != path.crend(); ++it) { if (*it == '.') return true; if (*it == '/' || *it == '\\') return false; } return false; } constexpr bool HasPrefix(std::string_view s, std::string_view prefix) noexcept { return (s.size() >= prefix.size()) && (prefix == s.substr(0, prefix.size())); } } void Lexilla::SetDefault(CreateLexerFn pCreate) noexcept { pCreateLexerDefault = pCreate; } void Lexilla::SetDefaultDirectory(std::string_view directory) { directoryLoadDefault = directory; } bool Lexilla::Load(std::string_view sharedLibraryPaths) { if (sharedLibraryPaths == lastLoaded) { return !libraries.empty(); } std::string_view paths = sharedLibraryPaths; lexers.clear(); libraries.clear(); while (!paths.empty()) { const size_t separator = paths.find_first_of(';'); std::string path(paths.substr(0, separator)); if (separator == std::string::npos) { paths.remove_prefix(paths.size()); } else { paths.remove_prefix(separator + 1); } if (path == ".") { if (directoryLoadDefault.empty()) { path = ""; } else { path = directoryLoadDefault; path += pathSeparator; } path += LEXILLA_LIB; } if (!NameContainsDot(path)) { // No '.' in name so add extension path.append(LEXILLA_EXTENSION); } #if _WIN32 // Convert from UTF-8 to wide characters std::wstring wsPath = WideStringFromUTF8(path); Module lexillaDL = ::LoadLibraryW(wsPath.c_str()); #else Module lexillaDL = dlopen(path.c_str(), RTLD_LAZY); #endif if (lexillaDL) { GetLexerCountFn fnLexerCount = FunctionPointer<GetLexerCountFn>( FindSymbol(lexillaDL, LEXILLA_GETLEXERCOUNT)); GetLexerNameFn fnLexerName = FunctionPointer<GetLexerNameFn>( FindSymbol(lexillaDL, LEXILLA_GETLEXERNAME)); if (fnLexerCount && fnLexerName) { const int nLexers = fnLexerCount(); for (int i = 0; i < nLexers; i++) { char name[100] = ""; fnLexerName(i, name, sizeof(name)); lexers.push_back(name); } } CreateLexerFn fnCL = FunctionPointer<CreateLexerFn>( FindSymbol(lexillaDL, LEXILLA_CREATELEXER)); LexerNameFromIDFn fnLNFI = FunctionPointer<LexerNameFromIDFn>( FindSymbol(lexillaDL, LEXILLA_LEXERNAMEFROMID)); GetLibraryPropertyNamesFn fnGLPN = FunctionPointer<GetLibraryPropertyNamesFn>( FindSymbol(lexillaDL, LEXILLA_GETLIBRARYPROPERTYNAMES)); SetLibraryPropertyFn fnSLP = FunctionPointer<SetLibraryPropertyFn>( FindSymbol(lexillaDL, LEXILLA_SETLIBRARYPROPERTY)); GetNameSpaceFn fnGNS = FunctionPointer<GetNameSpaceFn>( FindSymbol(lexillaDL, LEXILLA_GETNAMESPACE)); std::string nameSpace; if (fnGNS) { nameSpace = fnGNS(); nameSpace += LEXILLA_NAMESPACE_SEPARATOR; } LexLibrary lexLib { fnCL, fnLNFI, fnGLPN, fnSLP, nameSpace }; libraries.push_back(lexLib); } } lastLoaded = sharedLibraryPaths; std::set<std::string> nameSet; for (const LexLibrary &lexLib : libraries) { if (lexLib.fnGLPN) { const char *cpNames = lexLib.fnGLPN(); if (cpNames) { std::string_view names = cpNames; while (!names.empty()) { const size_t separator = names.find_first_of('\n'); std::string name(names.substr(0, separator)); nameSet.insert(name); if (separator == std::string::npos) { names.remove_prefix(names.size()); } else { names.remove_prefix(separator + 1); } } } } } // Standard Lexilla does not have any properties so can't be added to set. libraryProperties = std::vector<std::string>(nameSet.begin(), nameSet.end()); return !libraries.empty(); } Scintilla::ILexer5 *Lexilla::MakeLexer(std::string_view languageName) { std::string sLanguageName(languageName); // Ensure NUL-termination // First, try to match namespace then name suffix for (const LexLibrary &lexLib : libraries) { if (lexLib.fnCL && !lexLib.nameSpace.empty()) { if (HasPrefix(languageName, lexLib.nameSpace)) { Scintilla::ILexer5 *pLexer = lexLib.fnCL(sLanguageName.substr(lexLib.nameSpace.size()).c_str()); if (pLexer) { return pLexer; } } } } // If no match with namespace, try to just match name for (const LexLibrary &lexLib : libraries) { if (lexLib.fnCL) { Scintilla::ILexer5 *pLexer = lexLib.fnCL(sLanguageName.c_str()); if (pLexer) { return pLexer; } } } if (pCreateLexerDefault) { return pCreateLexerDefault(sLanguageName.c_str()); } #ifdef LEXILLA_STATIC Scintilla::ILexer5 *pLexer = CreateLexer(sLanguageName.c_str()); if (pLexer) { return pLexer; } #endif return nullptr; } std::vector<std::string> Lexilla::Lexers() { return lexers; } std::string Lexilla::NameFromID(int identifier) { for (const LexLibrary &lexLib : libraries) { if (lexLib.fnLNFI) { const char *name = lexLib.fnLNFI(identifier); if (name) { return name; } } } return std::string(); } std::vector<std::string> Lexilla::LibraryProperties() { return libraryProperties; } void Lexilla::SetProperty(const char *key, const char *value) { for (const LexLibrary &lexLib : libraries) { if (lexLib.fnSLP) { lexLib.fnSLP(key, value); } } // Standard Lexilla does not have any properties so don't set. } <|start_filename|>scintilla/src/RESearch.h<|end_filename|> // Scintilla source code edit control /** @file RESearch.h ** Interface to the regular expression search library. **/ // Written by <NAME> <<EMAIL>> // Based on the work of <NAME>. // This file is in the public domain. #ifndef RESEARCH_H #define RESEARCH_H namespace Scintilla::Internal { class CharacterIndexer { public: virtual char CharAt(Sci::Position index) const=0; virtual ~CharacterIndexer() { } }; class RESearch { public: explicit RESearch(CharClassify *charClassTable); // No dynamic allocation so default copy constructor and assignment operator are OK. void Clear() noexcept; void GrabMatches(const CharacterIndexer &ci); const char *Compile(const char *pattern, Sci::Position length, bool caseSensitive, bool posix) noexcept; int Execute(const CharacterIndexer &ci, Sci::Position lp, Sci::Position endp); static constexpr int MAXTAG = 10; static constexpr int NOTFOUND = -1; Sci::Position bopat[MAXTAG]; Sci::Position eopat[MAXTAG]; std::string pat[MAXTAG]; private: static constexpr int MAXNFA = 4096; // The following constants are not meant to be changeable. // They are for readability only. static constexpr int MAXCHR = 256; static constexpr int CHRBIT = 8; static constexpr int BITBLK = MAXCHR / CHRBIT; void ChSet(unsigned char c) noexcept; void ChSetWithCase(unsigned char c, bool caseSensitive) noexcept; int GetBackslashExpression(const char *pattern, int &incr) noexcept; Sci::Position PMatch(const CharacterIndexer &ci, Sci::Position lp, Sci::Position endp, char *ap); Sci::Position bol; Sci::Position tagstk[MAXTAG]; /* subpat tag stack */ char nfa[MAXNFA]; /* automaton */ int sta; unsigned char bittab[BITBLK]; /* bit table for CCL pre-set bits */ int failure; CharClassify *charClass; bool iswordc(unsigned char x) const noexcept { return charClass->IsWord(x); } }; } #endif <|start_filename|>grepWinNP3/sktoolslib_mod/AeroGlass.h<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012, 2017, 2020-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #pragma once #define TMSCHEMA_H // this excludes the deprecated tmschema.h without dependency on _WIN32_WINNT macro #include <windows.h> #include <Uxtheme.h> class CDwmApiImpl { private: HINSTANCE m_hDwmApiLib; BOOL IsInitialized() const; public: CDwmApiImpl(); ~CDwmApiImpl(); BOOL Initialize(); HRESULT DwmExtendFrameIntoClientArea(HWND hWnd, const MARGINS* pMarInset) const; BOOL IsDwmCompositionEnabled() const; HRESULT DwmEnableComposition(UINT uCompositionAction) const; }; class CUxThemeAeroImpl { private: HINSTANCE m_hUxThemeLib; BOOL IsInitialized() const; public: CUxThemeAeroImpl(); BOOL Initialize(); ~CUxThemeAeroImpl(); HRESULT BufferedPaintInit() const; HRESULT BufferedPaintUnInit() const; HTHEME OpenThemeData(HWND hwnd, LPCWSTR pszClassList) const; BOOL DetermineGlowSize(int* piSize, LPCWSTR pszClassIdList = nullptr) const; HRESULT CloseThemeData(HTHEME hTheme) const; HPAINTBUFFER BeginBufferedPaint(HDC hdcTarget, const RECT* prcTarget, BP_BUFFERFORMAT dwFormat, BP_PAINTPARAMS* pPaintParams, HDC* phdc) const; HRESULT EndBufferedPaint(HPAINTBUFFER hBufferedPaint, BOOL fUpdateTarget) const; HRESULT DrawThemeTextEx(HTHEME hTheme, HDC hdc, int iPartId, int iStateId, LPCWSTR pszText, int cchText, DWORD dwTextFlags, LPRECT pRect, const DTTOPTS* pOptions) const; HRESULT GetThemeInt(HTHEME hTheme, int iPartId, int iStateId, int iPropId, int* piVal) const; HRESULT GetThemeSysFont(HTHEME hTheme, int iFontId, LOGFONTW* plf) const; HRESULT BufferedPaintSetAlpha(HPAINTBUFFER hBufferedPaint, const RECT* prc, BYTE alpha) const; HRESULT BufferedPaintMakeOpaque_(HPAINTBUFFER hBufferedPaint, const RECT* prc) const; HRESULT DrawThemeBackground(HTHEME hTheme, HDC hdc, int iPartId, int iStateId, const RECT* pRect, const RECT* pClipRect) const; HRESULT GetThemeBackgroundContentRect(HTHEME hTheme, HDC hdc, int iPartId, int iStateId, LPCRECT pBoundingRect, LPRECT pContentRect) const; HRESULT GetThemeBackgroundExtent(HTHEME hTheme, HDC hdc, int iPartId, int iStateId, LPCRECT pContentRect, LPRECT pExtentRect) const; HRESULT GetThemeBitmap(HTHEME hTheme, int iPartId, int iStateId, int iPropId, ULONG dwFlags, HBITMAP* phBitmap) const; HRESULT DrawThemeParentBackground(HWND hwnd, HDC hdc, const RECT* prc) const; BOOL IsThemeBackgroundPartiallyTransparent(HTHEME hTheme, int iPartId, int iStateId) const; HRESULT DrawThemeText(HTHEME hTheme, HDC hdc, int iPartId, int iStateId, LPCWSTR pszText, int iCharCount, DWORD dwTextFlags, DWORD dwTextFlags2, LPCRECT pRect) const; HRESULT GetThemeColor(HTHEME hTheme, int iPartId, int iStateId, int iPropId, COLORREF* pColor) const; HRESULT GetThemePartSize(HTHEME hTheme, HDC hdc, int iPartId, int iStateId, LPCRECT prc, THEMESIZE eSize, SIZE* psz) const; HRESULT GetThemePosition(HTHEME hTheme, int iPartId, int iStateId, int iPropId, POINT* pPoint) const; HRESULT GetThemeMargins(HTHEME hTheme, HDC hdc, int iPartId, int iStateId, int iPropId, LPRECT prc, MARGINS* pMargins) const; HRESULT GetThemeMetric(HTHEME hTheme, HDC hdc, int iPartId, int iStateId, int iPropId, int* piVal) const; HRESULT GetThemeRect(HTHEME hTheme, int iPartId, int iStateId, int iPropId, LPRECT pRect) const; }; <|start_filename|>src/uchardet/uchardet/src/LangModels/LangFrenchModel.cpp<|end_filename|> /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "../nsSBCharSetProber.h" /********* Language model for: French *********/ /** * Generated by BuildLangModel.py * On: 2015-12-03 21:10:27.685575 **/ /* Character Mapping Table: * ILL: illegal character. * CTR: control character specific to the charset. * RET: carriage/return. * SYM: symbol (punctuation) that does not belong to word. * NUM: 0 - 9. * * Other characters are ordered by probabilities * (0 is the most common character in the language). * * Orders are generic to a language. So the codepoint with order X in * CHARSET1 maps to the same character as the codepoint with the same * order X in CHARSET2 for the same language. * As such, it is possible to get missing order. For instance the * ligature of 'o' and 'e' exists in ISO-8859-15 but not in ISO-8859-1 * even though they are both used for French. Same for the euro sign. */ static const unsigned char Windows_1252_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 2, 18, 11, 10, 0, 17, 15, 19, 4, 25, 26, 7, 13, 3, 8, /* 4X */ 12, 20, 5, 1, 6, 9, 16, 30, 21, 22, 29,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 2, 18, 11, 10, 0, 17, 15, 19, 4, 25, 26, 7, 13, 3, 8, /* 6X */ 12, 20, 5, 1, 6, 9, 16, 30, 21, 22, 29,SYM,SYM,SYM,SYM,CTR, /* 7X */ SYM,ILL,SYM, 56,SYM,SYM,SYM,SYM,SYM,SYM, 51,SYM, 35,ILL, 57,ILL, /* 8X */ ILL,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, 51,SYM, 35,ILL, 58, 59, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM,SYM, 60,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* BX */ 24, 38, 32, 46, 49, 61, 47, 27, 23, 14, 28, 41, 62, 39, 33, 36, /* CX */ 48, 45, 54, 40, 31, 55, 42,SYM, 52, 37, 43, 34, 44, 53, 50, 63, /* DX */ 24, 38, 32, 46, 49, 64, 47, 27, 23, 14, 28, 41, 65, 39, 33, 36, /* EX */ 48, 45, 54, 40, 31, 55, 42,SYM, 52, 37, 43, 34, 44, 53, 50, 66, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Iso_8859_1_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 2, 18, 11, 10, 0, 17, 15, 19, 4, 25, 26, 7, 13, 3, 8, /* 4X */ 12, 20, 5, 1, 6, 9, 16, 30, 21, 22, 29,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 2, 18, 11, 10, 0, 17, 15, 19, 4, 25, 26, 7, 13, 3, 8, /* 6X */ 12, 20, 5, 1, 6, 9, 16, 30, 21, 22, 29,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM,SYM, 67,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* BX */ 24, 38, 32, 46, 49, 68, 47, 27, 23, 14, 28, 41, 69, 39, 33, 36, /* CX */ 48, 45, 54, 40, 31, 55, 42,SYM, 52, 37, 43, 34, 44, 53, 50, 70, /* DX */ 24, 38, 32, 46, 49, 71, 47, 27, 23, 14, 28, 41, 72, 39, 33, 36, /* EX */ 48, 45, 54, 40, 31, 55, 42,SYM, 52, 37, 43, 34, 44, 53, 50, 73, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Iso_8859_15_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 2, 18, 11, 10, 0, 17, 15, 19, 4, 25, 26, 7, 13, 3, 8, /* 4X */ 12, 20, 5, 1, 6, 9, 16, 30, 21, 22, 29,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 2, 18, 11, 10, 0, 17, 15, 19, 4, 25, 26, 7, 13, 3, 8, /* 6X */ 12, 20, 5, 1, 6, 9, 16, 30, 21, 22, 29,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM, 51,SYM, 51,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM, 74, 75,SYM,SYM, 76,SYM,SYM,SYM, 35, 35, 77,SYM, /* BX */ 24, 38, 32, 46, 49, 78, 47, 27, 23, 14, 28, 41, 79, 39, 33, 36, /* CX */ 48, 45, 54, 40, 31, 55, 42,SYM, 52, 37, 43, 34, 44, 53, 50, 80, /* DX */ 24, 38, 32, 46, 49, 81, 47, 27, 23, 14, 28, 41, 82, 39, 33, 36, /* EX */ 48, 45, 54, 40, 31, 55, 42,SYM, 52, 37, 43, 34, 44, 53, 50, 83, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ /* Model Table: * Total sequences: 914 * First 512 sequences: 0.997057879992383 * Next 512 sequences (512-1024): 0.002942120007616917 * Rest: 3.8163916471489756e-17 * Negative sequences: TODO */ static const PRUint8 FrenchLangModel[] = { 3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,3,3,3,3,3,3,0,0,3,3,3,0,3,3,0,0,0,2,0,2,0, 3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,2,2,3,3,3,3,0,3,3,0,0,3,0,0,2,3,0,0,0,2,2,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,0,3,3,3,0,3,3,2,2,3,0,0,3,0, 3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,2,3,3,0,3,3,3,2,3,2,0,2,2,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,0,2,3,0,2,3,2,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,0,2,3,3,3,2,3,3,3,0,2,0,0,0, 3,3,3,2,3,3,3,3,3,3,2,3,3,3,3,2,2,2,3,3,2,2,3,3,2,0,2,0,3,3,2,3,2,0,0,0,0,0, 3,3,3,2,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,0,3,3,3,2,3,0,0,2,2,2,2,0,2,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,0,3,3,0,0,3,3,0,0,2,3,0,3,3, 3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,2,3,3,2,0,3,3,2,3,3,2,0,0,0,0,0,2,0, 3,3,3,2,3,3,3,2,3,3,3,2,2,3,3,3,2,2,2,3,0,0,3,3,0,3,0,0,2,2,3,2,2,2,3,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,2,2,3,2,2,2,2,3,3,0,3,3,0,0,3,0,2,2,2,3,2,0,0,2,0,0, 3,3,3,2,3,3,3,3,3,3,2,2,3,2,3,0,0,2,2,3,0,0,3,3,0,0,2,2,3,2,2,3,2,0,0,0,0,0, 3,3,3,3,3,2,3,2,3,3,2,3,3,3,3,2,0,2,3,2,0,0,3,3,0,2,2,0,3,0,2,2,3,0,2,2,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,0,0,0,3,2,2,0,3,0,0,2,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,2,2,2,3,3,3,2,2,3,3,0,2,3,3,0,0,0,0,2,0,2,0,2,0,0,0,0,0, 3,2,3,2,3,3,0,2,3,3,0,0,0,2,3,0,2,2,0,0,0,0,2,3,0,0,2,0,3,0,0,0,0,0,0,2,0,0, 3,3,3,2,3,3,3,3,3,3,2,2,2,3,3,2,0,3,0,0,0,0,0,3,0,2,0,0,3,0,0,0,0,0,2,2,0,0, 3,3,3,3,3,3,3,3,3,3,3,2,2,2,3,2,2,0,3,2,0,0,3,2,0,3,0,0,0,0,0,0,3,2,0,2,0,0, 3,3,3,3,3,3,3,3,3,3,0,2,0,3,3,0,0,2,2,0,0,0,3,3,0,2,2,0,2,2,2,3,3,0,0,2,0,0, 0,0,2,0,0,0,0,2,2,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,3,0,3,0,3,2,3,2,2,3,3,2,3,0,3,2,2,2,2,3,2,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0, 3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,0,2,2,2,0,3,2,0,0,2,2,0,0,0,0,0,0,0, 0,3,0,3,0,3,3,3,0,0,3,3,2,3,0,3,3,2,3,0,3,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,2,3,2,3,2,2,2,3,3,2,2,2,2,3,0,0,0,0,0,0,0,0,0,3,2,0,0,0,0,0,0,2,0,0,0,0,0, 3,3,3,2,3,3,2,3,3,3,0,0,2,3,2,2,2,2,2,3,0,0,3,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0, 0,0,3,0,0,0,0,0,3,3,0,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,2,0,0,3,2,0,0,0,3,0,3,0,0,2,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,3,2,3,2,0,2,3,3,0,2,0,2,2,2,0,0,2,2,2,0,3,0,0,0,2,0,0,3,2,0,0,0,0,0,0,0, 3,2,3,2,3,2,2,2,3,2,0,2,0,0,2,0,0,2,2,2,0,0,2,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0, 0,2,0,3,0,0,3,3,0,0,0,0,2,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,0,2,2,0,3,3,0,0,0,3,2,2,0,3,0,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,3,0,0,3,3,0,0,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,2,3,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,0,0,2,0,2,2,0,3,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,2,2,0,2,2,3,0,0,2,2,0,2,0,2,0,2,2,0,2,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; const SequenceModel Windows_1252FrenchModel = { Windows_1252_CharToOrderMap, FrenchLangModel, 38, (float)0.997057879992383, PR_TRUE, "WINDOWS-1252" }; const SequenceModel Iso_8859_1FrenchModel = { Iso_8859_1_CharToOrderMap, FrenchLangModel, 38, (float)0.997057879992383, PR_TRUE, "ISO-8859-1" }; const SequenceModel Iso_8859_15FrenchModel = { Iso_8859_15_CharToOrderMap, FrenchLangModel, 38, (float)0.997057879992383, PR_TRUE, "ISO-8859-15" }; <|start_filename|>test/TestAhkNotepad3.cmd<|end_filename|> @echo off setlocal enableextensions set SCRIPTDRV=%~d0 set SCRIPTDIR=%~dp0 set CWD=%CD% set TEST_DIR=%SCRIPTDIR%_TESTDIR\ set TEST_LOG=test.log set NP3_CONFIG_DIR=%SCRIPT_DIR%config\ set NP3_WIN32_DIR=%SCRIPT_DIR%..\Bin\Release_x86_v143\ set NP3_X64_DIR=%SCRIPT_DIR%..\Bin\Release_x64_v143\ set AHK_EXE=%ProgramW6432%/AutoHotkey/AutoHotkeyU32.exe set AHK_EXE32=%ProgramFiles(x86)%/AutoHotkey/AutoHotkeyU32.exe set AHK_EXE64=%ProgramFiles%/AutoHotkey/AutoHotkeyU32.exe if not exist "%AHK_EXE%" set AHK_EXE=%AHK_EXE32% if not exist "%AHK_EXE%" set AHK_EXE=%AHK_EXE64% :: -------------------------------------------------------------------------------------------------------------------- :: prepare tests if not exist "%TEST_DIR%" mkdir "%TEST_DIR%" if not exist "%TEST_DIR%Favorites\" mkdir "%TEST_DIR%Favorites\" copy "%NP3_CONFIG_DIR%Notepad3_distrib.ini" "%TEST_DIR%Notepad3.ini" /Y /V if exist "%NP3_WIN32_DIR%Notepad3.exe" copy /B "%NP3_WIN32_DIR%Notepad3.exe" /B "%TEST_DIR%Notepad3.exe" /Y /V if exist "%NP3_X64_DIR%Notepad3.exe" copy /B "%NP3_X64_DIR%Notepad3.exe" /B "%TEST_DIR%Notepad3.exe" /Y /V ::Loop over all ahk files in tests directory echo. > "%TEST_LOG%" set EXITCODE=0 ::for /r %%i in (*.ahk) do ( for %%i in (*.ahk) do ( echo - Run Testsuite %%~nxi echo +++ Run Testsuite %%~nxi +++ >> "%TEST_LOG%" start "testing" /B /Wait "%AHK_EXE%" /ErrorStdOut "%%~nxi" >> "%TEST_LOG%" 2>&1 if errorlevel 1 ( set EXITCODE=1 echo *** Testsuite %%~nxi failed! *** echo *** ERROR: Testsuite %%~nxi failed! *** >> "%TEST_LOG%" ) else ( echo +++ Testsuite %%~nxi succeeded. +++ >> "%TEST_LOG%" ) echo. >> "%TEST_LOG%" ) :: -------------------------------------------------------------------------------------------------------------------- :END type "%TEST_LOG%" :: - make EXITCODE survive 'endlocal' endlocal & set EXITCODE=%EXITCODE% ::echo.EXITCODE=%EXITCODE% ::pause if [%EXITCODE%] NEQ [0] exit /B %EXITCODE% :: ==================================================================================================================== <|start_filename|>src/uchardet/uchardet/src/LangModels/LangFinnishModel.cpp<|end_filename|> /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "../nsSBCharSetProber.h" /********* Language model for: Finnish *********/ /** * Generated by BuildLangModel.py * On: 2016-09-21 18:15:05.189948 **/ /* Character Mapping Table: * ILL: illegal character. * CTR: control character specific to the charset. * RET: carriage/return. * SYM: symbol (punctuation) that does not belong to word. * NUM: 0 - 9. * * Other characters are ordered by probabilities * (0 is the most common character in the language). * * Orders are generic to a language. So the codepoint with order X in * CHARSET1 maps to the same character as the codepoint with the same * order X in CHARSET2 for the same language. * As such, it is possible to get missing order. For instance the * ligature of 'o' and 'e' exists in ISO-8859-15 but not in ISO-8859-1 * even though they are both used for French. Same for the euro sign. */ static const unsigned char Iso_8859_15_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 0, 19, 21, 18, 4, 23, 20, 14, 1, 15, 9, 6, 12, 2, 7, /* 4X */ 16, 29, 10, 5, 3, 8, 13, 24, 26, 17, 25,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 0, 19, 21, 18, 4, 23, 20, 14, 1, 15, 9, 6, 12, 2, 7, /* 6X */ 16, 29, 10, 5, 3, 8, 13, 24, 26, 17, 25,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM, 27,SYM, 27,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM, 28, 61,SYM,SYM, 28,SYM,SYM,SYM, 62, 63, 64,SYM, /* BX */ 49, 35, 65, 46, 11, 56, 39, 37, 40, 30, 51, 31, 66, 36, 67, 57, /* CX */ 68, 58, 52, 33, 34, 59, 22,SYM, 69, 70, 38, 71, 32, 72, 73, 55, /* DX */ 49, 35, 74, 46, 11, 56, 39, 37, 40, 30, 51, 31, 75, 36, 76, 57, /* EX */ 77, 58, 52, 33, 34, 59, 22,SYM, 78, 79, 38, 80, 32, 81, 82, 83, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Windows_1252_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 0, 19, 21, 18, 4, 23, 20, 14, 1, 15, 9, 6, 12, 2, 7, /* 4X */ 16, 29, 10, 5, 3, 8, 13, 24, 26, 17, 25,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 0, 19, 21, 18, 4, 23, 20, 14, 1, 15, 9, 6, 12, 2, 7, /* 6X */ 16, 29, 10, 5, 3, 8, 13, 24, 26, 17, 25,SYM,SYM,SYM,SYM,CTR, /* 7X */ SYM,ILL,SYM, 84,SYM,SYM,SYM,SYM,SYM,SYM, 27,SYM, 85,ILL, 28,ILL, /* 8X */ ILL,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, 27,SYM, 86,ILL, 28, 87, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM,SYM, 88,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* BX */ 49, 35, 89, 46, 11, 56, 39, 37, 40, 30, 51, 31, 90, 36, 91, 57, /* CX */ 92, 58, 52, 33, 34, 59, 22,SYM, 93, 94, 38, 95, 32, 96, 97, 55, /* DX */ 49, 35, 98, 46, 11, 56, 39, 37, 40, 30, 51, 31, 99, 36,100, 57, /* EX */ 101, 58, 52, 33, 34, 59, 22,SYM,102,103, 38,104, 32,105,106,107, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Iso_8859_4_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 0, 19, 21, 18, 4, 23, 20, 14, 1, 15, 9, 6, 12, 2, 7, /* 4X */ 16, 29, 10, 5, 3, 8, 13, 24, 26, 17, 25,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 0, 19, 21, 18, 4, 23, 20, 14, 1, 15, 9, 6, 12, 2, 7, /* 6X */ 16, 29, 10, 5, 3, 8, 13, 24, 26, 17, 25,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM,108,109, 47,SYM,110,111,SYM,SYM, 27,112,113,114,SYM, 28,SYM, /* AX */ SYM,115,SYM, 47,SYM,116,117,SYM,SYM, 27,118,119,120, 45, 28, 45, /* BX */ 53, 35,121, 46, 11, 56, 39,122, 43, 30,123, 31,124, 36,125,126, /* CX */ 127, 54,128,129, 34, 59, 22,SYM,130,131, 38,132, 32,133,134, 55, /* DX */ 53, 35,135, 46, 11, 56, 39,136, 43, 30,137, 31,138, 36,139,140, /* EX */ 141, 54,142,143, 34, 59, 22,SYM,144,145, 38,146, 32,147,148,SYM, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Iso_8859_13_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 0, 19, 21, 18, 4, 23, 20, 14, 1, 15, 9, 6, 12, 2, 7, /* 4X */ 16, 29, 10, 5, 3, 8, 13, 24, 26, 17, 25,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 0, 19, 21, 18, 4, 23, 20, 14, 1, 15, 9, 6, 12, 2, 7, /* 6X */ 16, 29, 10, 5, 3, 8, 13, 24, 26, 17, 25,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,149,SYM, 47,SYM,SYM,SYM,SYM, 39, /* AX */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,150,SYM, 47,SYM,SYM,SYM,SYM, 39, /* BX */ 151,152, 53, 41, 11, 56,153,154, 43, 30,155,156,157,158,159,160, /* CX */ 27,161, 54, 33,162, 59, 22,SYM,163,164,165,166, 32, 60, 28, 55, /* DX */ 167,168, 53, 41, 11, 56,169,170, 43, 30,171,172,173,174,175,176, /* EX */ 27,177, 54, 33,178, 59, 22,SYM,179,180,181,182, 32, 60, 28,SYM, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Iso_8859_9_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 0, 19, 21, 18, 4, 23, 20, 14, 1, 15, 9, 6, 12, 2, 7, /* 4X */ 16, 29, 10, 5, 3, 8, 13, 24, 26, 17, 25,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 0, 19, 21, 18, 4, 23, 20, 14, 1, 15, 9, 6, 12, 2, 7, /* 6X */ 16, 29, 10, 5, 3, 8, 13, 24, 26, 17, 25,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM,SYM,183,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* BX */ 49, 35,184, 46, 11, 56, 39, 37, 40, 30, 51, 31,185, 36,186, 57, /* CX */ 50, 58, 52, 33, 34, 59, 22,SYM,187,188, 38,189, 32, 48, 42, 55, /* DX */ 49, 35,190, 46, 11, 56, 39, 37, 40, 30, 51, 31,191, 36,192, 57, /* EX */ 50, 58, 52, 33, 34, 59, 22,SYM,193,194, 38,195, 32, 44, 42,196, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Iso_8859_1_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 0, 19, 21, 18, 4, 23, 20, 14, 1, 15, 9, 6, 12, 2, 7, /* 4X */ 16, 29, 10, 5, 3, 8, 13, 24, 26, 17, 25,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 0, 19, 21, 18, 4, 23, 20, 14, 1, 15, 9, 6, 12, 2, 7, /* 6X */ 16, 29, 10, 5, 3, 8, 13, 24, 26, 17, 25,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM,SYM,197,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* BX */ 49, 35,198, 46, 11, 56, 39, 37, 40, 30, 51, 31,199, 36,200, 57, /* CX */ 201, 58, 52, 33, 34, 59, 22,SYM,202,203, 38,204, 32,205,206, 55, /* DX */ 49, 35,207, 46, 11, 56, 39, 37, 40, 30, 51, 31,208, 36,209, 57, /* EX */ 210, 58, 52, 33, 34, 59, 22,SYM,211,212, 38,213, 32,214,215,216, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ /* Model Table: * Total sequences: 919 * First 512 sequences: 0.9985378147555799 * Next 512 sequences (512-1024): 0.0014621852444200612 * Rest: 3.881443777498106e-17 * Negative sequences: TODO */ static const PRUint8 FinnishLangModel[] = { 3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,2,2,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,2,0,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,0,0,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,2,3,3,3,3,2,3,3,0,3,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,3,3,2,0,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,2,0,0,0,2, 3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,2,2,0,0, 3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,0,3,3,3,3,2,0,2, 3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,0,3,3,2,3,2,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,3,0,2,3,2,3,2,2,0,2,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,2, 3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,0,0,2,2,0,0,0,0,0,0,0, 3,3,2,2,3,3,2,3,3,2,3,3,3,2,2,2,3,3,2,3,3,3,3,2,2,2,2,0,0,0, 3,3,2,2,3,2,2,3,3,3,2,3,0,2,2,2,2,3,2,2,0,0,2,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,2,0,3,3,2,2,0,0,0,0,2, 3,3,3,2,3,2,2,3,3,2,2,3,2,0,2,0,2,3,0,2,0,0,3,2,0,0,0,0,0,0, 3,3,2,3,3,3,3,3,3,2,3,3,3,2,3,2,3,3,2,0,2,2,3,2,3,0,0,2,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,3,3,2,3,2,2,2,0,0, 3,3,3,3,3,3,3,3,3,0,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,0,0,3,2, 3,3,3,3,3,3,3,3,3,3,3,2,2,0,3,2,0,3,3,3,2,3,2,0,2,2,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,2,3,2,3,2,3,3,3,3,3,3,3,2,3,2,0,0,0,0, 3,3,2,3,3,3,3,3,3,3,3,0,2,0,3,0,2,3,3,2,2,3,0,0,0,2,0,0,0,2, 2,3,3,3,2,3,3,2,0,3,3,3,3,3,3,3,3,3,3,2,0,0,3,2,0,0,0,0,0,0, 3,3,2,3,3,3,3,3,3,2,3,2,0,2,0,2,2,3,0,2,2,2,0,3,0,2,0,0,0,0, 3,3,3,2,3,3,2,3,2,2,3,0,2,0,3,0,0,2,2,2,2,2,0,2,2,0,0,0,0,0, 3,3,3,2,3,2,2,3,2,2,2,2,2,2,2,0,2,3,2,2,2,0,0,2,2,3,0,0,0,0, 3,3,0,2,2,2,3,2,0,0,0,0,2,2,3,0,2,0,0,2,0,2,0,3,2,0,2,0,0,0, 3,3,2,2,3,0,0,2,2,2,2,0,2,2,0,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0, 3,2,0,0,2,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,0,0,0,2,0,0,3,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; const SequenceModel Iso_8859_15FinnishModel = { Iso_8859_15_CharToOrderMap, FinnishLangModel, 30, (float)0.9985378147555799, PR_TRUE, "ISO-8859-15" }; const SequenceModel Windows_1252FinnishModel = { Windows_1252_CharToOrderMap, FinnishLangModel, 30, (float)0.9985378147555799, PR_TRUE, "WINDOWS-1252" }; const SequenceModel Iso_8859_4FinnishModel = { Iso_8859_4_CharToOrderMap, FinnishLangModel, 30, (float)0.9985378147555799, PR_TRUE, "ISO-8859-4" }; const SequenceModel Iso_8859_13FinnishModel = { Iso_8859_13_CharToOrderMap, FinnishLangModel, 30, (float)0.9985378147555799, PR_TRUE, "ISO-8859-13" }; const SequenceModel Iso_8859_9FinnishModel = { Iso_8859_9_CharToOrderMap, FinnishLangModel, 30, (float)0.9985378147555799, PR_TRUE, "ISO-8859-9" }; const SequenceModel Iso_8859_1FinnishModel = { Iso_8859_1_CharToOrderMap, FinnishLangModel, 30, (float)0.9985378147555799, PR_TRUE, "ISO-8859-1" }; <|start_filename|>src/StyleLexers/styleLexNSIS.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_NSIS = { "!addincludedir !addplugindir !appendfile !cd !define !delfile !echo !else !endif !error !execute !finalize " "!getdllversion !if !ifdef !ifmacrodef !ifmacrondef !ifndef !include !insertmacro !macro !macroend " "!macroundef !makensis !packhdr !searchparse !searchreplace !system !tempfile !undef !verbose !warning " ".onguiend .onguiinit .oninit .oninstfailed .oninstsuccess .onmouseoversection .onrebootfailed " ".onselchange .onuserabort .onverifyinstdir abort addbrandingimage addsize allowrootdirinstall " "allowskipfiles autoclosewindow bannertrimpath bgfont bggradient brandingtext bringtofront call " "callinstdll caption changeui checkbitmap clearerrors completedtext componenttext copyfiles crccheck " "createdirectory createfont createshortcut delete deleteinisec deleteinistr deleteregkey deleteregvalue " "detailprint detailsbuttontext dirstate dirtext dirvar dirverify enablewindow enumregkey enumregvalue exch " "exec execshell execwait expandenvstrings file filebufsize fileclose fileerrortext fileexists fileopen " "fileread filereadbyte filereadutf16le filereadword fileseek filewrite filewritebyte filewriteutf16le " "filewriteword findclose findfirst findnext findproc findwindow flushini getcurinsttype getcurrentaddress " "getdlgitem getdllversion getdllversionlocal geterrorlevel getfiletime getfiletimelocal getfontname " "getfontnamelocal getfontversion getfontversionlocal getfullpathname getfunctionaddress getinstdirerror " "getlabeladdress gettempfilename goto hidewindow icon ifabort iferrors iffileexists ifrebootflag ifsilent " "initpluginsdir installbuttontext installcolors installdir installdirregkey instprogressflags insttype " "insttypegettext insttypesettext intcmp intcmpu intfmt intop iswindow langstring licensebkcolor " "licensedata licenseforceselection licenselangstring licensetext loadlanguagefile lockwindow logset " "logtext manifestsupportedos messagebox miscbuttontext name nop outfile page pagecallbacks pop push quit " "readenvstr readinistr readregdword readregstr reboot regdll rename requestexecutionlevel reservefile " "return rmdir searchpath sectiongetflags sectiongetinsttypes sectiongetsize sectiongettext sectionin " "sectionsetflags sectionsetinsttypes sectionsetsize sectionsettext sendmessage setautoclose " "setbrandingimage setcompress setcompressionlevel setcompressor setcompressordictsize setctlcolors " "setcurinsttype setdatablockoptimize setdatesave setdetailsprint setdetailsview seterrorlevel seterrors " "setfileattributes setfont setoutpath setoverwrite setpluginunload setrebootflag setregview " "setshellvarcontext setsilent showinstdetails showuninstdetails showwindow silentinstall silentuninstall " "sleep spacetexts strcmp strcmps strcpy strlen subcaption un.onguiend un.onguiinit un.oninit " "un.onrebootfailed un.onuninstfailed un.onuninstsuccess un.onuserabort unicode uninstallbuttontext " "uninstallcaption uninstallicon uninstallsubcaption uninstalltext uninstpage unregdll var viaddversionkey " "vifileversion viproductversion windowicon writeinistr writeregbin writeregdword writeregexpandstr " "writeregstr writeuninstaller xpstyle", "$0 $1 $2 $3 $4 $5 $6 $7 $8 $9 $admintools $appdata $cdburn_area $cmdline $commonfiles $commonfiles32 " "$commonfiles64 $cookies $desktop $documents $exedir $exefile $exepath $favorites $fonts $history " "$hwndparent $instdir $internet_cache $language $localappdata $music $nethood $outdir $pictures " "$pluginsdir $printhood $profile $programfiles $programfiles32 $programfiles64 $quicklaunch $r0 $r1 $r2 " "$r3 $r4 $r5 $r6 $r7 $r8 $r9 $recent $resources $resources_localized $sendto $smprograms $smstartup " "$startmenu $sysdir $temp $templates $videos $windir ${__date__} ${__file__} ${__function__} ${__global__} " "${__line__} ${__pageex__} ${__section__} ${__time__} ${__timestamp__} ${__uninstall__} ${nsisdir}", "32 64 admin all alt alwaysoff archive auto both bottom branding bzip2 charset colored components " "componentsonlyoncustom control cur current custom customstring date directory enablecancel end false " "file_attribute_archive file_attribute_hidden file_attribute_normal file_attribute_offline " "file_attribute_readonly file_attribute_system file_attribute_temporary filesonly final force global gray " "hidden hide highest hkcc hkcr hkcu hkdd hkey_classes_root hkey_current_config hkey_current_user " "hkey_dyn_data hkey_local_machine hkey_performance_data hkey_users hklm hkpd hku idabort idcancel idd_dir " "idd_inst idd_instfiles idd_license idd_selcom idd_uninst idd_verify idignore idno idok idretry idyes " "ifdiff ifempty ifnewer ignorecase imgid instfiles italic lang lastused leave left license listonly lzma " "manual mb_abortretryignore mb_defbutton1 mb_defbutton2 mb_defbutton3 mb_defbutton4 mb_iconexclamation " "mb_iconinformation mb_iconquestion mb_iconstop mb_ok mb_okcancel mb_retrycancel mb_right mb_rtlreading " "mb_setforeground mb_topmost mb_usericon mb_yesno mb_yesnocancel nevershow nocustom none nonfatal normal " "normal nounload noworkingdir off offline on oname plugin rawnl readonly rebootok resizetofit right sd " "shctx shell_context shift short show silent silentlog smooth solid strike sw_hide sw_showmaximized " "sw_showminimized sw_shownormal system temporary textonly timeout top trimcenter trimleft trimright true " "try underline uninstconfirm user utcdate win10 win7 win8 win8.1 windows winvista zlib", NULL, }; EDITLEXER lexNSIS = { SCLEX_NSIS, "nsis", IDS_LEX_NSIS, L"NSIS Script", L"nsi; nsh", L"", &KeyWords_NSIS, { { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //,{ {SCE_NSIS_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {MULTI_STYLE(SCE_NSIS_COMMENT,SCE_NSIS_COMMENTBOX,0,0)}, IDS_LEX_STR_63127, L"Comment", L"fore:#008000", L"" }, { {MULTI_STYLE(SCE_NSIS_STRINGDQ,SCE_NSIS_STRINGLQ,SCE_NSIS_STRINGRQ,0)}, IDS_LEX_STR_63131, L"String", L"fore:#666666; back:#EEEEEE", L"" }, { {SCE_NSIS_FUNCTION}, IDS_LEX_STR_63273, L"Function", L"fore:#0033CC", L"" }, { {SCE_NSIS_VARIABLE}, IDS_LEX_STR_63249, L"Variable", L"fore:#CC3300", L"" }, { {SCE_NSIS_STRINGVAR}, IDS_LEX_STR_63267, L"Variable within String", L"fore:#CC3300; back:#EEEEEE", L"" }, { {SCE_NSIS_NUMBER}, IDS_LEX_STR_63130, L"Number", L"fore:#FF0000", L"" }, { {SCE_NSIS_LABEL}, IDS_LEX_STR_63274, L"Constant", L"fore:#FF9900", L"" }, { {SCE_NSIS_SECTIONDEF}, IDS_LEX_STR_63232, L"Section", L"fore:#0033CC", L"" }, { {SCE_NSIS_SUBSECTIONDEF}, IDS_LEX_STR_63275, L"Sub Section", L"fore:#0033CC", L"" }, { {SCE_NSIS_SECTIONGROUP}, IDS_LEX_STR_63276, L"Section Group", L"fore:#0033CC", L"" }, { {SCE_NSIS_FUNCTIONDEF}, IDS_LEX_STR_63277, L"Function Definition", L"fore:#0033CC", L"" }, { {SCE_NSIS_PAGEEX}, IDS_LEX_STR_63278, L"PageEx", L"fore:#0033CC", L"" }, { {SCE_NSIS_IFDEFINEDEF}, IDS_LEX_STR_63279, L"If Definition", L"fore:#0033CC", L"" }, { {SCE_NSIS_MACRODEF}, IDS_LEX_STR_63280, L"Macro Definition", L"fore:#0033CC", L"" }, //{ {SCE_NSIS_USERDEFINED}, L"User Defined", L"", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>scintilla/src/PerLine.cxx<|end_filename|> // Scintilla source code edit control /** @file PerLine.cxx ** Manages data associated with each line of the document **/ // Copyright 1998-2009 by <NAME> <<EMAIL>> // The License.txt file describes the conditions under which this software may be distributed. #include <cstddef> #include <cassert> #include <cstring> #include <stdexcept> #include <string_view> #include <vector> #include <forward_list> #include <optional> #include <algorithm> #include <memory> #include "ScintillaTypes.h" #include "Debugging.h" #include "Geometry.h" #include "Platform.h" #include "Position.h" #include "SplitVector.h" #include "Partitioning.h" #include "CellBuffer.h" #include "PerLine.h" using namespace Scintilla::Internal; MarkerHandleSet::MarkerHandleSet() = default; MarkerHandleSet::~MarkerHandleSet() { mhList.clear(); } bool MarkerHandleSet::Empty() const noexcept { return mhList.empty(); } int MarkerHandleSet::MarkValue() const noexcept { unsigned int m = 0; for (const MarkerHandleNumber &mhn : mhList) { m |= (1 << mhn.number); } return m; } bool MarkerHandleSet::Contains(int handle) const noexcept { for (const MarkerHandleNumber &mhn : mhList) { if (mhn.handle == handle) { return true; } } return false; } MarkerHandleNumber const *MarkerHandleSet::GetMarkerHandleNumber(int which) const noexcept { for (const MarkerHandleNumber &mhn : mhList) { if (which == 0) return &mhn; which--; } return nullptr; } bool MarkerHandleSet::InsertHandle(int handle, int markerNum) { mhList.push_front(MarkerHandleNumber(handle, markerNum)); return true; } void MarkerHandleSet::RemoveHandle(int handle) { mhList.remove_if([handle](const MarkerHandleNumber &mhn) noexcept { return mhn.handle == handle; }); } bool MarkerHandleSet::RemoveNumber(int markerNum, bool all) { bool performedDeletion = false; mhList.remove_if([&](const MarkerHandleNumber &mhn) noexcept { if ((all || !performedDeletion) && (mhn.number == markerNum)) { performedDeletion = true; return true; } return false; }); return performedDeletion; } void MarkerHandleSet::CombineWith(MarkerHandleSet *other) noexcept { mhList.splice_after(mhList.before_begin(), other->mhList); } LineMarkers::~LineMarkers() = default; void LineMarkers::Init() { markers.DeleteAll(); } void LineMarkers::InsertLine(Sci::Line line) { if (markers.Length()) { markers.Insert(line, nullptr); } } void LineMarkers::InsertLines(Sci::Line line, Sci::Line lines) { if (markers.Length()) { markers.InsertEmpty(line, lines); } } void LineMarkers::RemoveLine(Sci::Line line) { // Retain the markers from the deleted line by oring them into the previous line if (markers.Length()) { if (line > 0) { MergeMarkers(line - 1); } markers.Delete(line); } } Sci::Line LineMarkers::LineFromHandle(int markerHandle) const noexcept { for (Sci::Line line = 0; line < markers.Length(); line++) { if (markers[line] && markers[line]->Contains(markerHandle)) { return line; } } return -1; } int LineMarkers::HandleFromLine(Sci::Line line, int which) const noexcept { if (markers.Length() && (line >= 0) && (line < markers.Length()) && markers[line]) { MarkerHandleNumber const *pnmh = markers[line]->GetMarkerHandleNumber(which); return pnmh ? pnmh->handle : -1; } return -1; } int LineMarkers::NumberFromLine(Sci::Line line, int which) const noexcept { if (markers.Length() && (line >= 0) && (line < markers.Length()) && markers[line]) { MarkerHandleNumber const *pnmh = markers[line]->GetMarkerHandleNumber(which); return pnmh ? pnmh->number : -1; } return -1; } void LineMarkers::MergeMarkers(Sci::Line line) { if (markers[line + 1]) { if (!markers[line]) markers[line] = std::make_unique<MarkerHandleSet>(); markers[line]->CombineWith(markers[line + 1].get()); markers[line + 1].reset(); } } int LineMarkers::MarkValue(Sci::Line line) const noexcept { if (markers.Length() && (line >= 0) && (line < markers.Length()) && markers[line]) return markers[line]->MarkValue(); else return 0; } Sci::Line LineMarkers::MarkerNext(Sci::Line lineStart, int mask) const noexcept { if (lineStart < 0) lineStart = 0; const Sci::Line length = markers.Length(); for (Sci::Line iLine = lineStart; iLine < length; iLine++) { const MarkerHandleSet *onLine = markers[iLine].get(); if (onLine && ((onLine->MarkValue() & mask) != 0)) return iLine; } return -1; } int LineMarkers::AddMark(Sci::Line line, int markerNum, Sci::Line lines) { handleCurrent++; if (!markers.Length()) { // No existing markers so allocate one element per line markers.InsertEmpty(0, lines); } if (line >= markers.Length()) { return -1; } if (!markers[line]) { // Need new structure to hold marker handle markers[line] = std::make_unique<MarkerHandleSet>(); } markers[line]->InsertHandle(handleCurrent, markerNum); return handleCurrent; } bool LineMarkers::DeleteMark(Sci::Line line, int markerNum, bool all) { bool someChanges = false; if (markers.Length() && (line >= 0) && (line < markers.Length()) && markers[line]) { if (markerNum == -1) { someChanges = true; markers[line].reset(); } else { someChanges = markers[line]->RemoveNumber(markerNum, all); if (markers[line]->Empty()) { markers[line].reset(); } } } return someChanges; } void LineMarkers::DeleteMarkFromHandle(int markerHandle) { const Sci::Line line = LineFromHandle(markerHandle); if (line >= 0) { markers[line]->RemoveHandle(markerHandle); if (markers[line]->Empty()) { markers[line].reset(); } } } LineLevels::~LineLevels() = default; void LineLevels::Init() { levels.DeleteAll(); } void LineLevels::InsertLine(Sci::Line line) { if (levels.Length()) { const int level = (line < levels.Length()) ? levels[line] : static_cast<int>(Scintilla::FoldLevel::Base); levels.Insert(line, level); } } void LineLevels::InsertLines(Sci::Line line, Sci::Line lines) { if (levels.Length()) { const int level = (line < levels.Length()) ? levels[line] : static_cast<int>(Scintilla::FoldLevel::Base); levels.InsertValue(line, lines, level); } } void LineLevels::RemoveLine(Sci::Line line) { if (levels.Length()) { // Move up following lines but merge header flag from this line // to line before to avoid a temporary disappearance causing expansion. int firstHeader = levels[line] & static_cast<int>(Scintilla::FoldLevel::HeaderFlag); levels.Delete(line); if (line == levels.Length()-1) // Last line loses the header flag levels[line-1] &= ~static_cast<int>(Scintilla::FoldLevel::HeaderFlag); else if (line > 0) levels[line-1] |= firstHeader; } } void LineLevels::ExpandLevels(Sci::Line sizeNew) { levels.InsertValue(levels.Length(), sizeNew - levels.Length(), static_cast<int>(Scintilla::FoldLevel::Base)); } void LineLevels::ClearLevels() { levels.DeleteAll(); } int LineLevels::SetLevel(Sci::Line line, int level, Sci::Line lines) { int prev = 0; if ((line >= 0) && (line < lines)) { if (!levels.Length()) { ExpandLevels(lines + 1); } prev = levels[line]; if (prev != level) { levels[line] = level; } } return prev; } int LineLevels::GetLevel(Sci::Line line) const noexcept { if (levels.Length() && (line >= 0) && (line < levels.Length())) { return levels[line]; } else { return static_cast<int>(Scintilla::FoldLevel::Base); } } LineState::~LineState() = default; void LineState::Init() { lineStates.DeleteAll(); } void LineState::InsertLine(Sci::Line line) { if (lineStates.Length()) { lineStates.EnsureLength(line); const int val = (line < lineStates.Length()) ? lineStates[line] : 0; lineStates.Insert(line, val); } } void LineState::InsertLines(Sci::Line line, Sci::Line lines) { if (lineStates.Length()) { lineStates.EnsureLength(line); const int val = (line < lineStates.Length()) ? lineStates[line] : 0; lineStates.InsertValue(line, lines, val); } } void LineState::RemoveLine(Sci::Line line) { if (lineStates.Length() > line) { lineStates.Delete(line); } } int LineState::SetLineState(Sci::Line line, int state) { lineStates.EnsureLength(line + 1); const int stateOld = lineStates[line]; lineStates[line] = state; return stateOld; } int LineState::GetLineState(Sci::Line line) { if (line < 0) return 0; lineStates.EnsureLength(line + 1); return lineStates[line]; } Sci::Line LineState::GetMaxLineState() const noexcept { return lineStates.Length(); } // Each allocated LineAnnotation is a char array which starts with an AnnotationHeader // and then has text and optional styles. struct AnnotationHeader { short style; // Style IndividualStyles implies array of styles short lines; int length; }; namespace { constexpr int IndividualStyles = 0x100; size_t NumberLines(std::string_view sv) { return std::count(sv.begin(), sv.end(), '\n') + 1; } std::unique_ptr<char[]>AllocateAnnotation(size_t length, int style) { const size_t len = sizeof(AnnotationHeader) + length + ((style == IndividualStyles) ? length : 0); return std::make_unique<char[]>(len); } } LineAnnotation::~LineAnnotation() = default; void LineAnnotation::Init() { ClearAll(); } void LineAnnotation::InsertLine(Sci::Line line) { if (annotations.Length()) { annotations.EnsureLength(line); annotations.Insert(line, std::unique_ptr<char []>()); } } void LineAnnotation::InsertLines(Sci::Line line, Sci::Line lines) { if (annotations.Length()) { annotations.EnsureLength(line); annotations.InsertEmpty(line, lines); } } void LineAnnotation::RemoveLine(Sci::Line line) { if (annotations.Length() && (line > 0) && (line <= annotations.Length())) { annotations[line-1].reset(); annotations.Delete(line-1); } } bool LineAnnotation::MultipleStyles(Sci::Line line) const noexcept { if (annotations.Length() && (line >= 0) && (line < annotations.Length()) && annotations[line]) return reinterpret_cast<AnnotationHeader *>(annotations[line].get())->style == IndividualStyles; else return false; } int LineAnnotation::Style(Sci::Line line) const noexcept { if (annotations.Length() && (line >= 0) && (line < annotations.Length()) && annotations[line]) return reinterpret_cast<AnnotationHeader *>(annotations[line].get())->style; else return 0; } const char *LineAnnotation::Text(Sci::Line line) const noexcept { if (annotations.Length() && (line >= 0) && (line < annotations.Length()) && annotations[line]) return annotations[line].get()+sizeof(AnnotationHeader); else return nullptr; } const unsigned char *LineAnnotation::Styles(Sci::Line line) const noexcept { if (annotations.Length() && (line >= 0) && (line < annotations.Length()) && annotations[line] && MultipleStyles(line)) return reinterpret_cast<unsigned char *>(annotations[line].get() + sizeof(AnnotationHeader) + Length(line)); else return nullptr; } void LineAnnotation::SetText(Sci::Line line, const char *text) { if (text && (line >= 0)) { annotations.EnsureLength(line+1); const int style = Style(line); annotations[line] = AllocateAnnotation(strlen(text), style); char *pa = annotations[line].get(); assert(pa); AnnotationHeader *pah = reinterpret_cast<AnnotationHeader *>(pa); pah->style = static_cast<short>(style); pah->length = static_cast<int>(strlen(text)); pah->lines = static_cast<short>(NumberLines(text)); memcpy(pa+sizeof(AnnotationHeader), text, pah->length); } else { if (annotations.Length() && (line >= 0) && (line < annotations.Length()) && annotations[line]) { annotations[line].reset(); } } } void LineAnnotation::ClearAll() { annotations.DeleteAll(); } void LineAnnotation::SetStyle(Sci::Line line, int style) { annotations.EnsureLength(line+1); if (!annotations[line]) { annotations[line] = AllocateAnnotation(0, style); } reinterpret_cast<AnnotationHeader *>(annotations[line].get())->style = static_cast<short>(style); } void LineAnnotation::SetStyles(Sci::Line line, const unsigned char *styles) { if (line >= 0) { annotations.EnsureLength(line+1); if (!annotations[line]) { annotations[line] = AllocateAnnotation(0, IndividualStyles); } else { const AnnotationHeader *pahSource = reinterpret_cast<AnnotationHeader *>(annotations[line].get()); if (pahSource->style != IndividualStyles) { std::unique_ptr<char[]>allocation = AllocateAnnotation(pahSource->length, IndividualStyles); AnnotationHeader *pahAlloc = reinterpret_cast<AnnotationHeader *>(allocation.get()); pahAlloc->length = pahSource->length; pahAlloc->lines = pahSource->lines; memcpy(allocation.get() + sizeof(AnnotationHeader), annotations[line].get() + sizeof(AnnotationHeader), pahSource->length); annotations[line] = std::move(allocation); } } AnnotationHeader *pah = reinterpret_cast<AnnotationHeader *>(annotations[line].get()); pah->style = IndividualStyles; memcpy(annotations[line].get() + sizeof(AnnotationHeader) + pah->length, styles, pah->length); } } int LineAnnotation::Length(Sci::Line line) const noexcept { if (annotations.Length() && (line >= 0) && (line < annotations.Length()) && annotations[line]) return reinterpret_cast<AnnotationHeader *>(annotations[line].get())->length; else return 0; } int LineAnnotation::Lines(Sci::Line line) const noexcept { if (annotations.Length() && (line >= 0) && (line < annotations.Length()) && annotations[line]) return reinterpret_cast<AnnotationHeader *>(annotations[line].get())->lines; else return 0; } LineTabstops::~LineTabstops() = default; void LineTabstops::Init() { tabstops.DeleteAll(); } void LineTabstops::InsertLine(Sci::Line line) { if (tabstops.Length()) { tabstops.EnsureLength(line); tabstops.Insert(line, nullptr); } } void LineTabstops::InsertLines(Sci::Line line, Sci::Line lines) { if (tabstops.Length()) { tabstops.EnsureLength(line); tabstops.InsertEmpty(line, lines); } } void LineTabstops::RemoveLine(Sci::Line line) { if (tabstops.Length() > line) { tabstops[line].reset(); tabstops.Delete(line); } } bool LineTabstops::ClearTabstops(Sci::Line line) noexcept { if (line < tabstops.Length()) { TabstopList *tl = tabstops[line].get(); if (tl) { tl->clear(); return true; } } return false; } bool LineTabstops::AddTabstop(Sci::Line line, int x) { tabstops.EnsureLength(line + 1); if (!tabstops[line]) { tabstops[line] = std::make_unique<TabstopList>(); } TabstopList *tl = tabstops[line].get(); if (tl) { // tabstop positions are kept in order - insert in the right place std::vector<int>::iterator it = std::lower_bound(tl->begin(), tl->end(), x); // don't insert duplicates if (it == tl->end() || *it != x) { tl->insert(it, x); return true; } } return false; } int LineTabstops::GetNextTabstop(Sci::Line line, int x) const noexcept { if (line < tabstops.Length()) { TabstopList *tl = tabstops[line].get(); if (tl) { for (const int i : *tl) { if (i > x) { return i; } } } } return 0; } <|start_filename|>src/StyleLexers/styleLexRUBY.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_RUBY = { "__FILE__ __LINE__ alias and begin break case class def defined? do else elsif end ensure false for if in " "module next nil not or redo rescue retry return self super then true undef unless until when while yield", NULL, }; EDITLEXER lexRUBY = { SCLEX_RUBY, "ruby", IDS_LEX_RUBY, L"Ruby Script", L"rb; ruby; rbw; rake; rjs; rakefile; gemspec; podspec; \\^Rakefile$; \\^Podfile$", L"", &KeyWords_RUBY, { { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_RB_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {MULTI_STYLE(SCE_RB_COMMENTLINE,SCE_P_COMMENTBLOCK,0,0)}, IDS_LEX_STR_63127, L"Comment", L"fore:#008000", L"" }, { {SCE_RB_WORD}, IDS_LEX_STR_63128, L"Keyword", L"fore:#00007F", L"" }, { {SCE_RB_IDENTIFIER}, IDS_LEX_STR_63129, L"Identifier", L"", L"" }, { {SCE_RB_NUMBER}, IDS_LEX_STR_63130, L"Number", L"fore:#008080", L"" }, { {SCE_RB_OPERATOR}, IDS_LEX_STR_63132, L"Operator", L"", L"" }, { {MULTI_STYLE(SCE_RB_STRING,SCE_RB_CHARACTER,SCE_P_STRINGEOL,0)}, IDS_LEX_STR_63131, L"String", L"fore:#FF8000", L"" }, { {SCE_RB_CLASSNAME}, IDS_LEX_STR_63246, L"Class Name", L"fore:#0000FF", L"" }, { {SCE_RB_DEFNAME}, IDS_LEX_STR_63247, L"Function Name", L"fore:#007F7F", L"" }, { {SCE_RB_POD}, IDS_LEX_STR_63292, L"POD", L"fore:#004000; back:#C0FFC0; eolfilled", L"" }, { {SCE_RB_REGEX}, IDS_LEX_STR_63135, L"Regex", L"fore:#000000; back:#A0FFA0", L"" }, { {SCE_RB_SYMBOL}, IDS_LEX_STR_63293, L"Symbol", L"fore:#C0A030", L"" }, { {SCE_RB_MODULE_NAME}, IDS_LEX_STR_63294, L"Module Name", L"fore:#A000A0", L"" }, { {SCE_RB_INSTANCE_VAR}, IDS_LEX_STR_63295, L"Instance Var", L"fore:#B00080", L"" }, { {SCE_RB_CLASS_VAR}, IDS_LEX_STR_63296, L"Class Var", L"fore:#8000B0", L"" }, { {SCE_RB_DATASECTION}, IDS_LEX_STR_63222, L"Data Section", L"fore:#600000; back:#FFF0D8; eolfilled", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>src/StyleLexers/styleLexJAVA.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_JAVA = { // Primary keywords "abstract assert boolean break byte case catch char class const " "continue default do double else enum extends final finally float for future generic goto if implements " "import inner instanceof int interface long native new null outer package private protected public rest " "return short static super switch synchronized this throw throws transient try var void volatile while", // Secondary keywords "@Deprecated @Documented @FlaskyTest @Inherited @JavascriptInterface @LargeTest @MediumTest @Override " "@Retention @SmallTest @Smoke @Supress @SupressLint @SupressWarnings @Target @TargetApi @TestTarget " "@TestTargetClass @UiThreadTest @interface", // Documentation comment keywords "addindex addtogroup anchor arg attention author b brief bug c class code copyright date def defgroup deprecated dontinclude " "e em endcode endhtmlonly endif endlatexonly endlink endverbatim enum example exception f$ f[f] file" "hideinitializer htmlinclude htmlonly if image include ingroup internal invariant interface latexonly li line link " "mainpage name namespace nosubgrouping note overload p page par param param[in] param[out] post pre " "ref relates remarks return retval sa section see showinitializer since skip skipline struct subsection " "test throw throws todo typedef union until var verbatim verbinclude version warning weakgroup", // Global classes and typedefs "", // Preprocessor definitions "", // Task marker and error marker keywords "BUG FIXME HACK NOTE TBD TODO UNDONE XXX @@@", NULL, }; EDITLEXER lexJAVA = { SCLEX_CPP, "cpp", IDS_LEX_JAVA_SRC, L"Java Source Code", L"java; jad; aidl; bsh", L"", &KeyWords_JAVA, { { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_C_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {SCE_C_IDENTIFIER}, IDS_LEX_STR_63129, L"Identifier", L"", L"" }, { {MULTI_STYLE(SCE_C_COMMENT,SCE_C_COMMENTLINE,0,0)}, IDS_LEX_STR_63127, L"Comment", L"fore:#646464", L"" }, { {SCE_C_WORD}, IDS_LEX_STR_63128, L"Keyword", L"bold; fore:#A46000", L"" }, { {SCE_C_WORD2}, IDS_LEX_STR_63260, L"Keyword 2nd", L"bold; fore:#A46000", L"" }, //{ {SCE_C_GLOBALCLASS}, IDS_LEX_STR_63258, L"Typedefs/Classes", L"bold; italic; fore:#800000", L"" }, { {SCE_C_STRING}, IDS_LEX_STR_63131, L"String", L"fore:#008000", L"" }, //{ {SCE_C_REGEX}, IDS_LEX_STR_63135, L"Regex", L"fore:#006633; back:#FFF1A8", L"" }, { {SCE_C_NUMBER}, IDS_LEX_STR_63130, L"Number", L"fore:#FF0000", L"" }, { {SCE_C_OPERATOR}, IDS_LEX_STR_63132, L"Operator", L"fore:#B000B0", L"" }, //{ {MULTI_STYLE(SCE_C_PREPROCESSOR,SCE_C_PREPROCESSORCOMMENT,SCE_C_PREPROCESSORCOMMENTDOC,0)}, IDS_LEX_STR_63133, L"Preprocessor", L"fore:#FF8000", L"" }, //{ {MULTI_STYLE(SCE_C_VERBATIM, SCE_C_TRIPLEVERBATIM,0,0)}, IDS_LEX_STR_63134, L"Verbatim", L"fore:#B000B0", L"" }, { {MULTI_STYLE(SCE_C_COMMENTDOC,SCE_C_COMMENTLINEDOC,0,0)}, IDS_LEX_STR_63259, L"Comment Doc", L"fore:#808080", L"" }, { {SCE_C_COMMENTDOCKEYWORD}, IDS_LEX_STR_63371, L"Comment Doc Word", L"bold; fore:#808080", L"" }, { {SCE_C_COMMENTDOCKEYWORDERROR}, IDS_LEX_STR_63374, L"Comment Doc Error", L"italic; fore:#800000", L"" }, { {SCE_C_TASKMARKER}, IDS_LEX_STR_63373, L"Task Marker", L"bold; fore:#208080", L"" }, //{ {SCE_C_UUID}, L"UUID", L"", L"" }, //{ {SCE_C_GLOBALCLASS}, L"Global Class", L"", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>grepWinNP3/sktoolslib_mod/BaseWindowD2D.cpp<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2020 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "BaseWindowD2D.h" #include <memory> #include <Shlwapi.h> #pragma comment(lib, "dxgi") #pragma comment(lib, "d3d11") #pragma comment(lib, "d2d1") #pragma comment(lib, "dcomp") #pragma comment(lib, "Dwrite") #pragma comment(lib, "dxguid") void HR(HRESULT const result) { if (S_OK != result) { throw ComException(result); } } bool CWindowD2D::Create() { // Create the window RECT rect; rect.top = 0; rect.left = 0; rect.right = 600; rect.bottom = 400; return CreateEx(WS_EX_NOREDIRECTIONBITMAP, WS_OVERLAPPEDWINDOW | WS_VISIBLE, nullptr, &rect); } bool CWindowD2D::Create(DWORD dwStyles, HWND hParent /* = nullptr */, RECT* rect /* = nullptr */) { return CreateEx(WS_EX_NOREDIRECTIONBITMAP, dwStyles, hParent, rect); } bool CWindowD2D::CreateEx(DWORD dwExStyles, DWORD dwStyles, HWND hParent, RECT* rect, LPCWSTR classname, HMENU hMenu) { auto ret = __super::CreateEx(dwExStyles, dwStyles, hParent, rect, classname, hMenu); if (ret) { D2D1_FACTORY_OPTIONS const options = {D2D1_DEBUG_LEVEL_NONE}; HR(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, options, m_d2Factory.GetAddressOf())); HR(DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(m_writeFactory), reinterpret_cast<IUnknown**>(m_writeFactory.GetAddressOf()))); m_dc = nullptr; m_d2Device = nullptr; m_dxFactory = nullptr; m_dxgiDevice = nullptr; m_direct3dDevice = nullptr; HR(D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, D3D11_CREATE_DEVICE_BGRA_SUPPORT, nullptr, 0, D3D11_SDK_VERSION, &m_direct3dDevice, nullptr, nullptr)); HR(m_direct3dDevice.As(&m_dxgiDevice)); HR(CreateDXGIFactory2(0, __uuidof(m_dxFactory), reinterpret_cast<void**>(m_dxFactory.GetAddressOf()))); HR(m_d2Factory->CreateDevice(m_dxgiDevice.Get(), m_d2Device.GetAddressOf())); HR(m_d2Device->CreateDeviceContext(D2D1_DEVICE_CONTEXT_OPTIONS_NONE, m_dc.GetAddressOf())); if (rect) Resize(rect->right - rect->left, rect->bottom - rect->top); } return ret; } LRESULT CALLBACK CWindowD2D::WinMsgHandler(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_CREATE: m_hwnd = hwnd; break; case WM_ERASEBKGND: return TRUE; case WM_SIZE: Resize((unsigned)lParam & 0xFFFF, (unsigned)lParam >> 16); [[fallthrough]]; case WM_PAINT: { if (!m_dc || !m_d2dBitmap) return 0; m_dc->BeginDraw(); m_dc->Clear(); OnRender(m_dc.Get()); HR(m_dc->EndDraw()); HR(m_swapChain->Present(1, 0)); HR(m_compositionDevice->Commit()); ValidateRect(*this, nullptr); return 0; } break; case WM_DISPLAYCHANGE: { InvalidateRect(hwnd, NULL, FALSE); return 0; } break; default: return WinMsgProc(hwnd, uMsg, wParam, lParam); } return WinMsgProc(hwnd, uMsg, wParam, lParam); } void CWindowD2D::Resize(UINT width, UINT height) { DiscardDeviceResources(); m_window_width = width; m_window_height = height; if (m_window_width == 0 || m_window_height == 0) { return; } DXGI_SWAP_CHAIN_DESC1 sc_description = {}; sc_description.Format = DXGI_FORMAT_B8G8R8A8_UNORM; sc_description.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sc_description.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; sc_description.BufferCount = 2; sc_description.SampleDesc.Count = 1; sc_description.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED; sc_description.Width = m_window_width; sc_description.Height = m_window_height; m_swapChain = nullptr; HR(m_dxFactory->CreateSwapChainForComposition(m_dxgiDevice.Get(), &sc_description, nullptr, m_swapChain.GetAddressOf())); m_compositionDevice = nullptr; HR(DCompositionCreateDevice(m_dxgiDevice.Get(), __uuidof(m_compositionDevice), reinterpret_cast<void**>(m_compositionDevice.GetAddressOf()))); m_compositionTarget = nullptr; HR(m_compositionDevice->CreateTargetForHwnd(*this, true, m_compositionTarget.GetAddressOf())); m_compositionVisual = nullptr; HR(m_compositionDevice->CreateVisual(m_compositionVisual.GetAddressOf())); HR(m_compositionVisual->SetContent(m_swapChain.Get())); HR(m_compositionTarget->SetRoot(m_compositionVisual.Get())); m_surface = nullptr; HR(m_swapChain->GetBuffer(0, __uuidof(m_surface), reinterpret_cast<void**>(m_surface.GetAddressOf()))); D2D1_BITMAP_PROPERTIES1 properties = {}; properties.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED; properties.pixelFormat.format = DXGI_FORMAT_B8G8R8A8_UNORM; properties.bitmapOptions = D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW; m_d2dBitmap = nullptr; HR(m_dc->CreateBitmapFromDxgiSurface(m_surface.Get(), properties, m_d2dBitmap.GetAddressOf())); m_dc->SetTarget(m_d2dBitmap.Get()); CreateDeviceResources(); }; <|start_filename|>src/DarkMode/uxtheme-stub/uxtheme-stub.cpp<|end_filename|> // ---------------------------------------------------------------------------- // Windows 10 1903, aka 18362, broke the API. // The function at ordinal 135 is AllowDarkModeForApp before, // and SetPreferredAppMode after 1903. It also broke ShouldAppsUseDarkMode, // which always return TRUE(actually, random runtime not zero) after 1903. // // Before 1903, BOOL __stdcall AllowDarkModeForApp(BOOL) only accepts TRUE or FALSE. // TRUE means dark mode is allowed and vice versa. // After 1903, PreferredMode __stdcall SetPreferredAppMode(PreferredMode) accepts // 4 valid value : Default, AllowDark, ForceDark, ForceLight. // extern "C" { // 1809 17763 void __stdcall ShouldAppsUseDarkMode() {} // ordinal 132 void __stdcall AllowDarkModeForWindow(int, int) {} // ordinal 133 void __stdcall AllowDarkModeForApp(int) {} // ordinal 135, in 1809 void __stdcall FlushMenuThemes() {} // ordinal 136 void __stdcall RefreshImmersiveColorPolicyState() {} // ordinal 104 void __stdcall IsDarkModeAllowedForWindow(int) {} // ordinal 137 void __stdcall GetIsImmersiveColorUsingHighContrast(int) {} // ordinal 106 void __stdcall OpenNcThemeData(int, int) {} // ordinal 49 // 1903 18362 void __stdcall ShouldSystemUseDarkMode() {} // ordinal 138 //void __stdcall SetPreferredAppMode(int) {} // ordinal 135, in 1903 void __stdcall IsDarkModeAllowedForApp() {} // ordinal 139 } <|start_filename|>grepWinNP3/sktoolslib_mod/hyperlink.h<|end_filename|> /* * Module ID: hyperlink.h * Title : CHyperLink Declaration. * * Author : <NAME> <<EMAIL>> * Date : November 15, 2005 * * To read the article describing this class, visit * http://www.olivierlanglois.net/hyperlinkdemo.htm * * Note: Strongly inspired by <NAME> code * Minor ideas come from <NAME> and <NAME> code * * Revision : * * 001 26-Nov-2005 - <NAME> * - Added changes to make CHyperLink compatible with UNICODE * - Use dynamic memory allocation for the URL string */ #pragma once #include <windows.h> #include <memory> class CHyperLink { public: CHyperLink(); virtual ~CHyperLink(); BOOL ConvertStaticToHyperlink(HWND hwndCtl, LPCWSTR strURL); BOOL ConvertStaticToHyperlink(HWND hwndParent, UINT uiCtlId, LPCWSTR strURL); BOOL setURL(LPCWSTR strURL); LPCWSTR getURL() const { return m_strURL.get(); } protected: /* * Override if you want to perform some action when the link has the focus * or when the cursor is over the link such as displaying the URL somewhere. */ virtual void OnSelect() {} virtual void OnDeselect() {} std::unique_ptr<wchar_t[]> m_strURL; // hyperlink URL private: static COLORREF m_gCrLinkColor, m_gCrVisitedColor; // Hyperlink colors static HCURSOR m_gHLinkCursor; // Cursor for hyperlink static HFONT m_gUnderlineFont; // Font for underline display static int m_gCounter; // Global resources user counter BOOL m_bOverControl; // cursor over control? BOOL m_bVisited; // Has it been visited? HFONT m_stdFont; // Standard font WNDPROC m_pfnOrigCtlProc; void createUnderlineFont() const; static void createLinkCursor(); void createGlobalResources() const { createUnderlineFont(); createLinkCursor(); } static void destroyGlobalResources() { /* * No need to call DestroyCursor() for cursors acquired through * LoadCursor(). */ m_gHLinkCursor = nullptr; DeleteObject(m_gUnderlineFont); m_gUnderlineFont = nullptr; } void Navigate(); static void DrawFocusRect(HWND hwnd); static LRESULT CALLBACK _HyperlinkParentProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK _HyperlinkProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); }; <|start_filename|>src/uchardet/uchardet/src/LangModels/LangEstonianModel.cpp<|end_filename|> /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "../nsSBCharSetProber.h" /********* Language model for: Estonian *********/ /** * Generated by BuildLangModel.py * On: 2016-09-26 23:47:54.476870 **/ /* Character Mapping Table: * ILL: illegal character. * CTR: control character specific to the charset. * RET: carriage/return. * SYM: symbol (punctuation) that does not belong to word. * NUM: 0 - 9. * * Other characters are ordered by probabilities * (0 is the most common character in the language). * * Orders are generic to a language. So the codepoint with order X in * CHARSET1 maps to the same character as the codepoint with the same * order X in CHARSET2 for the same language. * As such, it is possible to get missing order. For instance the * ligature of 'o' and 'e' exists in ISO-8859-15 but not in ISO-8859-1 * even though they are both used for French. Same for the euro sign. */ static const unsigned char Iso_8859_4_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 0, 19, 23, 10, 2, 22, 15, 16, 1, 17, 8, 5, 12, 7, 9, /* 4X */ 14, 28, 11, 3, 4, 6, 13, 27, 26, 25, 30,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 0, 19, 23, 10, 2, 22, 15, 16, 1, 17, 8, 5, 12, 7, 9, /* 6X */ 14, 28, 11, 3, 4, 6, 13, 27, 26, 25, 30,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM, 55, 56, 57,SYM, 58, 59,SYM,SYM, 29, 45, 60, 61,SYM, 32,SYM, /* AX */ SYM, 62,SYM, 63,SYM, 64, 65,SYM,SYM, 29, 45, 66, 67, 68, 32, 69, /* BX */ 37, 43, 70, 71, 18, 44, 47, 72, 73, 33, 74, 75, 76, 36, 77, 39, /* CX */ 78, 79, 31, 80, 81, 20, 24,SYM, 38, 82, 52, 83, 21, 84, 34, 85, /* DX */ 37, 43, 86, 87, 18, 44, 47, 88, 89, 33, 90, 91, 92, 36, 93, 39, /* EX */ 94, 95, 31, 96, 97, 20, 24,SYM, 38, 98, 52, 99, 21,100, 34,SYM, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Windows_1252_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 0, 19, 23, 10, 2, 22, 15, 16, 1, 17, 8, 5, 12, 7, 9, /* 4X */ 14, 28, 11, 3, 4, 6, 13, 27, 26, 25, 30,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 0, 19, 23, 10, 2, 22, 15, 16, 1, 17, 8, 5, 12, 7, 9, /* 6X */ 14, 28, 11, 3, 4, 6, 13, 27, 26, 25, 30,SYM,SYM,SYM,SYM,CTR, /* 7X */ SYM,ILL,SYM,101,SYM,SYM,SYM,SYM,SYM,SYM, 29,SYM,102,ILL, 32,ILL, /* 8X */ ILL,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, 29,SYM,103,ILL, 32,104, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM,SYM, 50,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* BX */ 40, 43,105,106, 18, 44, 47, 48, 41, 33,107,108, 35, 36,109,110, /* CX */ 46,111, 53, 42,112, 20, 24,SYM, 38, 54, 52,113, 21,114,115,116, /* DX */ 40, 43,117,118, 18, 44, 47, 48, 41, 33,119,120, 35, 36,121,122, /* EX */ 46,123, 53, 42,124, 20, 24,SYM, 38, 54, 52,125, 21,126,127,128, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Iso_8859_15_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 0, 19, 23, 10, 2, 22, 15, 16, 1, 17, 8, 5, 12, 7, 9, /* 4X */ 14, 28, 11, 3, 4, 6, 13, 27, 26, 25, 30,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 0, 19, 23, 10, 2, 22, 15, 16, 1, 17, 8, 5, 12, 7, 9, /* 6X */ 14, 28, 11, 3, 4, 6, 13, 27, 26, 25, 30,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM, 29,SYM, 29,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM, 32, 50,SYM,SYM, 32,SYM,SYM,SYM,129,130,131,SYM, /* BX */ 40, 43,132,133, 18, 44, 47, 48, 41, 33,134,135, 35, 36,136,137, /* CX */ 46,138, 53, 42,139, 20, 24,SYM, 38, 54, 52,140, 21,141,142,143, /* DX */ 40, 43,144,145, 18, 44, 47, 48, 41, 33,146,147, 35, 36,148,149, /* EX */ 46,150, 53, 42,151, 20, 24,SYM, 38, 54, 52,152, 21,153,154,155, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Iso_8859_13_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 0, 19, 23, 10, 2, 22, 15, 16, 1, 17, 8, 5, 12, 7, 9, /* 4X */ 14, 28, 11, 3, 4, 6, 13, 27, 26, 25, 30,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 0, 19, 23, 10, 2, 22, 15, 16, 1, 17, 8, 5, 12, 7, 9, /* 6X */ 14, 28, 11, 3, 4, 6, 13, 27, 26, 25, 30,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, 38,SYM,156,SYM,SYM,SYM,SYM, 47, /* AX */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, 38,SYM,157,SYM,SYM,SYM,SYM, 47, /* BX */ 158,159, 37,160, 18, 44,161, 45,162, 33,163,164,165,166, 39,167, /* CX */ 29,168,169, 42, 31, 20, 24,SYM,170, 51,171, 34, 21, 49, 32,172, /* DX */ 173,174, 37,175, 18, 44,176, 45,177, 33,178,179,180,181, 39,182, /* EX */ 29,183,184, 42, 31, 20, 24,SYM,185, 51,186, 34, 21, 49, 32,SYM, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Windows_1257_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 0, 19, 23, 10, 2, 22, 15, 16, 1, 17, 8, 5, 12, 7, 9, /* 4X */ 14, 28, 11, 3, 4, 6, 13, 27, 26, 25, 30,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 0, 19, 23, 10, 2, 22, 15, 16, 1, 17, 8, 5, 12, 7, 9, /* 6X */ 14, 28, 11, 3, 4, 6, 13, 27, 26, 25, 30,SYM,SYM,SYM,SYM,CTR, /* 7X */ SYM,ILL,SYM,ILL,SYM,SYM,SYM,SYM,ILL,SYM,ILL,SYM,ILL,SYM,SYM,SYM, /* 8X */ ILL,SYM,SYM,SYM,SYM,SYM,SYM,SYM,ILL,SYM,ILL,SYM,ILL,SYM,SYM,ILL, /* 9X */ SYM,ILL,SYM,SYM,SYM,ILL,SYM,SYM, 38,SYM,187,SYM,SYM,SYM,SYM, 47, /* AX */ SYM,SYM,SYM,SYM,SYM, 50,SYM,SYM, 38,SYM,188,SYM,SYM,SYM,SYM, 47, /* BX */ 189,190, 37,191, 18, 44,192, 45,193, 33,194,195,196,197, 39,198, /* CX */ 29,199,200, 42, 31, 20, 24,SYM,201, 51,202, 34, 21, 49, 32,203, /* DX */ 204,205, 37,206, 18, 44,207, 45,208, 33,209,210,211,212, 39,213, /* EX */ 29,214,215, 42, 31, 20, 24,SYM,216, 51,217, 34, 21, 49, 32,SYM, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ /* Model Table: * Total sequences: 853 * First 512 sequences: 0.9972721312183132 * Next 512 sequences (512-1024): 0.0027278687816868537 * Rest: -5.204170427930421e-18 * Negative sequences: TODO */ static const PRUint8 EstonianLangModel[] = { 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,2,2,3,3,0,3,3,3,3,2,2,0,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,2,3,3,2,2,3,3,2,2,2,0,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,2,2,3,3,0,3,3,3,2,0,2,0,2, 3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,2,2,2,0,2,2,0, 3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,2,3,3,3,0,3,3,2,3,3,3,2,2,0,3,2,2,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,3,0,0,0,2,2,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,2,2,3,3,0,0,2,2,2,2,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,2,2,3,2,3,3,3,3,2,3,3,3,3,2,3,3,0,2,2,2,0,2, 3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,0,3,3,2,2,3,3,0,2,0,0,0,2,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,0,2,3,3,0,3,3,3,2,2,2,0,0, 3,3,3,3,3,3,3,3,3,3,2,3,3,3,2,2,2,3,0,2,0,3,0,0,0,2,2,2,0,0,0,3,3, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,2,0,2,0,0,0, 3,3,3,3,3,3,3,3,3,3,2,2,3,2,3,3,3,2,3,3,3,3,3,2,3,3,0,2,0,2,2,0,0, 3,3,3,3,2,3,3,3,3,3,2,2,2,2,2,2,2,2,3,0,3,2,0,2,3,2,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,2,3,3,2,3,2,3,2,3,0,3,3,0,2,3,3,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,2,3,3,2,3,3,3,3,0,2,2,2,2,2,0,3,2,0,2,0,2,0,0, 3,3,3,3,3,3,3,3,3,3,0,3,3,3,0,0,3,3,3,0,3,3,3,2,0,3,0,2,0,0,0,2,0, 3,3,3,2,3,0,3,3,0,3,0,2,3,0,3,0,0,0,3,0,3,3,0,0,2,0,0,0,0,0,0,0,0, 2,3,3,3,3,3,0,3,3,3,3,3,3,3,3,3,3,0,3,3,0,0,0,0,0,0,2,0,0,0,0,0,0, 3,3,3,3,2,3,3,3,2,3,0,3,2,0,0,0,2,3,0,2,0,2,0,2,0,2,2,0,0,0,0,0,0, 0,3,3,3,3,3,3,3,2,0,3,3,3,3,3,3,3,3,0,3,3,0,0,0,0,0,0,0,0,0,2,0,0, 3,0,2,3,3,3,0,3,3,3,3,3,3,3,3,3,3,0,0,3,0,3,2,0,0,0,0,0,0,0,0,0,0, 3,3,3,2,3,3,3,2,0,3,2,3,0,0,0,2,0,2,2,0,0,3,3,3,2,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,2,3,3,2,2,2,3,0,0,2,0,0,2,3,0,3,0,0,2,0,0,0,0, 2,3,3,3,3,3,0,3,3,2,3,3,2,3,3,3,2,2,0,3,0,0,0,0,3,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,2,3,2,3,2,0,3,3,0,0,0,0,0,0,0,3,2,0,2,0,0,0,2,3,0, 3,3,2,2,2,2,2,2,2,2,0,0,0,0,0,0,0,2,0,0,0,0,0,2,0,2,0,0,0,0,0,0,0, 3,3,3,2,2,2,2,2,2,3,0,2,0,0,0,2,2,0,0,0,0,0,2,0,0,2,0,2,0,0,0,0,0, 3,3,2,0,0,0,3,0,0,2,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0, 2,3,3,0,0,2,3,2,2,2,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0, 2,3,2,2,0,2,2,2,2,3,2,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0, 0,0,0,2,2,2,2,2,2,0,0,0,2,0,0,2,2,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,3,0,0,0,0,3,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; const SequenceModel Iso_8859_4EstonianModel = { Iso_8859_4_CharToOrderMap, EstonianLangModel, 33, (float)0.9972721312183132, PR_TRUE, "ISO-8859-4" }; const SequenceModel Windows_1252EstonianModel = { Windows_1252_CharToOrderMap, EstonianLangModel, 33, (float)0.9972721312183132, PR_TRUE, "WINDOWS-1252" }; const SequenceModel Iso_8859_15EstonianModel = { Iso_8859_15_CharToOrderMap, EstonianLangModel, 33, (float)0.9972721312183132, PR_TRUE, "ISO-8859-15" }; const SequenceModel Iso_8859_13EstonianModel = { Iso_8859_13_CharToOrderMap, EstonianLangModel, 33, (float)0.9972721312183132, PR_TRUE, "ISO-8859-13" }; const SequenceModel Windows_1257EstonianModel = { Windows_1257_CharToOrderMap, EstonianLangModel, 33, (float)0.9972721312183132, PR_TRUE, "WINDOWS-1257" }; <|start_filename|>lexilla/lexlib/LexerModule.h<|end_filename|> // Scintilla source code edit control /** @file LexerModule.h ** Colourise for particular languages. **/ // Copyright 1998-2001 by <NAME> <<EMAIL>> // The License.txt file describes the conditions under which this software may be distributed. #ifndef LEXERMODULE_H #define LEXERMODULE_H namespace Lexilla { class Accessor; class WordList; struct LexicalClass; typedef void (*LexerFunction)(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, WordList *keywordlists[], Accessor &styler); typedef Scintilla::ILexer5 *(*LexerFactoryFunction)(); /** * A LexerModule is responsible for lexing and folding a particular language. * The Catalogue class maintains a list of LexerModules which can be searched to find a * module appropriate to a particular language. * The ExternalLexerModule subclass holds lexers loaded from DLLs or shared libraries. */ class LexerModule { protected: int language; LexerFunction fnLexer; LexerFunction fnFolder; LexerFactoryFunction fnFactory; const char * const * wordListDescriptions; const LexicalClass *lexClasses; size_t nClasses; public: const char *languageName; LexerModule( int language_, LexerFunction fnLexer_, const char *languageName_=nullptr, LexerFunction fnFolder_= nullptr, const char * const wordListDescriptions_[]=nullptr, const LexicalClass *lexClasses_=nullptr, size_t nClasses_=0) noexcept; LexerModule( int language_, LexerFactoryFunction fnFactory_, const char *languageName_, const char * const wordListDescriptions_[]=nullptr) noexcept; int GetLanguage() const noexcept; // -1 is returned if no WordList information is available int GetNumWordLists() const noexcept; const char *GetWordListDescription(int index) const noexcept; const LexicalClass *LexClasses() const noexcept; size_t NamedStyles() const noexcept; Scintilla::ILexer5 *Create() const; void Lex(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, WordList *keywordlists[], Accessor &styler) const; void Fold(Sci_PositionU startPos, Sci_Position lengthDoc, int initStyle, WordList *keywordlists[], Accessor &styler) const; friend class CatalogueModules; }; constexpr int Maximum(int a, int b) noexcept { return (a > b) ? a : b; } // Shut up annoying Visual C++ warnings: #ifdef _MSC_VER #pragma warning(disable: 4244 4456 4457) #endif // Turn off shadow warnings for lexers as may be maintained by others #if defined(__GNUC__) #pragma GCC diagnostic ignored "-Wshadow" #endif // Clang doesn't like omitting braces in array initialization but they just add // noise to LexicalClass arrays in lexers #if defined(__clang__) #pragma clang diagnostic ignored "-Wmissing-braces" #endif } #endif <|start_filename|>test/test_files/StyleLexers/styleLexKotlin/NetworkConnectionMonitor.kts<|end_filename|> package com.xdreamllc.ticktalk3.utils 1+2+3+4+5=12345 http://www.wki.org import android.app.Application import android.content.BroadcastReceiver import android.content.BroadcastReceiverimport android.content.BroadcastReceiver import android.content.BroadcastReceiverimport android.content.BroadcastReceiver import android.content.BroadcastReceiverimport android.content.BroadcastReceiver import android.content.BroadcastReceiverimport android.content.BroadcastReceiver import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.net.ConnectivityManager import android.net.Network import android.net.NetworkRequest import android.os.Build import android.os.Handler import android.os.Looper import android.os.Message import android.telephony.TelephonyManager /** * 网络连接变化监听器 *@author Carlos2927 *create at 2019/6/25 11:30 */ class NetworkConnectionMonitor { companion object{ private val TAG = "NetworkConnectionMonitor" private var mContext: Context = Application() private val listeners = mutableSetOf<NetworkWorkConnectChangedListener>() @JvmStatic private var isNetworkWell = false private val handler = object :Handler(Looper.getMainLooper()){ override fun handleMessage(msg: Message) { val oldState = isNetworkWell val isConnect = isNetworkConnected() val isNotify = oldState == !isConnect || msg.what == 3 MLog.w(TAG,"onConnectChanged isConnect ==> $isConnect isNotify $isNotify") if(isNotify){ listeners.iterator().let { while (it.hasNext()){ it.next().onConnectChanged(isConnect) } } } } } fun addNetworkWorkConnectChangedListener(mNetworkWorkConnectChangedListener:NetworkWorkConnectChangedListener){ listeners.add(mNetworkWorkConnectChangedListener) } fun removeNetworkWorkConnectChangedListener(mNetworkWorkConnectChangedListener:NetworkWorkConnectChangedListener){ listeners.remove(mNetworkWorkConnectChangedListener) } @JvmStatic fun checkNetwork(){ MLog.i(TAG,"checkNetwork() http ok,retry check!") handler.removeCallbacksAndMessages(null) handler.sendEmptyMessageDelayed(1,200) } @JvmStatic fun isNetworkWell():Boolean{ return isNetworkWell } fun init(context: Context){ mContext = context.applicationContext mContext.registerReceiver(object :BroadcastReceiver(){ override fun onReceive(context: Context?, intent: Intent?) { handler.removeCallbacksAndMessages(null) handler.sendEmptyMessageDelayed(1,1000) } }, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)) if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ val networkCallback = object :ConnectivityManager.NetworkCallback(){ override fun onAvailable(network: Network) { if(!handler.hasMessages(2)){ handler.removeCallbacksAndMessages(null) handler.sendEmptyMessageDelayed(1,1000) } } override fun onLost(network: Network) { handler.removeCallbacksAndMessages(null) handler.sendEmptyMessageDelayed(1,1000) } } (mContext.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager)?.let { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){ it.registerDefaultNetworkCallback(networkCallback) }else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ val builder = NetworkRequest.Builder() .addTransportType(android.net.NetworkCapabilities.TRANSPORT_CELLULAR) .addTransportType(android.net.NetworkCapabilities.TRANSPORT_ETHERNET) .addTransportType(android.net.NetworkCapabilities.TRANSPORT_VPN) .addTransportType(android.net.NetworkCapabilities.TRANSPORT_WIFI) it.registerNetworkCallback(builder.build(),networkCallback) } } } handler.sendEmptyMessageDelayed(2,1000) } fun isNetworkConnected(needNotifyChanged:Boolean = false):Boolean{ val oldState = isNetworkWell try { (mContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo?.let { val isAvailable = it.isAvailable val isConnected = it.isConnected isNetworkWell = isAvailable && isConnected if(!isNetworkWell){ MLog.i(TAG,"isNetworkConnected() isAvailable $isAvailable isConnected $isConnected") } }?:run { isNetworkWell = false MLog.i(TAG,"isNetworkConnected() no network") } }catch (e:Exception){ MLog.e(TAG,"isNetworkConnected() Error",e) } if(needNotifyChanged && oldState == !isNetworkWell){ handler.removeCallbacksAndMessages(null) handler.sendEmptyMessageDelayed(3,200) } return isNetworkWell } } interface NetworkWorkConnectChangedListener{ fun onConnectChanged(isConnected:Boolean) } } <|start_filename|>lexilla/lexers_x/LexCSV.cxx<|end_filename|> // encoding: UTF-8 // Scintilla source code edit control /** @file LexCSV.cxx ** Rainbow clouring for CSV files ** Written by RaiKoHoff **/ #include <string> #include <assert.h> #include <map> // #include "ILexer.h" #include "Scintilla.h" #include "StringCopy.h" #include "PropSetSimple.h" #include "LexAccessor.h" #include "Accessor.h" #include "StyleContext.h" #include "LexerModule.h" #include "DefaultLexer.h" #include "OptionSet.h" #include "WordList.h" // #include "CharSetX.h" #include "SciXLexer.h" using namespace Lexilla; using namespace Scintilla; namespace { // Use an unnamed namespace to protect the functions and classes from name conflicts enum delim : unsigned int { eComma = 0, eSemic, eTab, ePipe, eMax }; static int const DelimList[eMax] = { ',', ';', '\t', '|' }; // ================================================================================= struct OptionsCSV { bool fold; bool foldCompact; OptionsCSV() : fold(true) , foldCompact(true) { } }; static const char* const csvWordLists[] = { nullptr }; struct OptionSetCSV : public OptionSet<OptionsCSV> { OptionSetCSV() { DefineProperty("fold", &OptionsCSV::fold); DefineProperty("fold.compact", &OptionsCSV::foldCompact); DefineWordListSets(csvWordLists); } }; LexicalClass lexicalClasses[] = { // Lexer CSV SCLEX_CSV SCE_CSV_: 0, "SCE_CSV_DEFAULT", "default", "Default", 1, "SCE_CSV_COLUMN_0", "col_0", "Column 0", 2, "SCE_CSV_COLUMN_1", "col_1", "Column 1", 3, "SCE_CSV_COLUMN_2", "col_2", "Column 2", 4, "SCE_CSV_COLUMN_3", "col_3", "Column 3", 5, "SCE_CSV_COLUMN_4", "col_4", "Column 4", 6, "SCE_CSV_COLUMN_5", "col_5", "Column 5", 7, "SCE_CSV_COLUMN_6", "col_6", "Column 6", 8, "SCE_CSV_COLUMN_7", "col_7", "Column 7", 9, "SCE_CSV_COLUMN_8", "col_8", "Column 8", 10, "SCE_CSV_COLUMN_9", "col_9", "Column 9", }; } // end of namespace class LexerCSV : public DefaultLexer { WordList keywords; OptionsCSV options; OptionSetCSV osCSV; public: LexerCSV() : DefaultLexer("CSV", SCLEX_CSV, lexicalClasses, ELEMENTS(lexicalClasses)) { } virtual ~LexerCSV() { } void SCI_METHOD Release() override { delete this; } int SCI_METHOD Version() const override { return lvRelease5; } const char* SCI_METHOD PropertyNames() override { return osCSV.PropertyNames(); } int SCI_METHOD PropertyType(const char* name) override { return osCSV.PropertyType(name); } const char* SCI_METHOD PropertyGet(const char* name) override { return osCSV.PropertyGet(name); } const char* SCI_METHOD DescribeProperty(const char* name) override { return osCSV.DescribeProperty(name); } const char* SCI_METHOD DescribeWordListSets() override { return osCSV.DescribeWordListSets(); } void* SCI_METHOD PrivateCall(int, void*) override { return nullptr; } int SCI_METHOD LineEndTypesSupported() override { return SC_LINE_END_TYPE_DEFAULT; } int SCI_METHOD PrimaryStyleFromStyle(int style) override { return style; } static ILexer5* LexerFactoryCSV() { return new LexerCSV(); } // -------------------------------------------------------------------------- Sci_Position SCI_METHOD PropertySet(const char* key, const char* val) override; Sci_Position SCI_METHOD WordListSet(int n, const char* wl) override; void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument* pAccess) override; void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument* pAccess) override; }; Sci_Position SCI_METHOD LexerCSV::PropertySet(const char* key, const char* val) { if (osCSV.PropertySet(&options, key, val)) { return 0; } return -1; } Sci_Position SCI_METHOD LexerCSV::WordListSet(int n, const char* wl) { WordList* wordListN = nullptr; switch (n) { case 0: wordListN = &keywords; break; } Sci_Position firstModification = -1; if (wordListN) { WordList wlNew; wlNew.Set(wl); if (*wordListN != wlNew) { wordListN->Set(wl); firstModification = 0; } } return firstModification; } // ---------------------------------------------------------------------------- constexpr bool IsSingleQuoteChar(const int ch) noexcept { return (ch == '\''); } // ---------------------------------------------------------------------------- constexpr bool IsDoubleQuoteChar(const int ch) noexcept { return (ch == '"'); } // ---------------------------------------------------------------------------- constexpr unsigned int IsDelimiter(const int ch) noexcept { for (unsigned int i = 0; i < eMax; ++i) { if (DelimList[i] == ch) { return i; } } return eMax; } // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- constexpr int GetStateByColumn(const int col) noexcept { switch (col % 10) { case 0: return SCE_CSV_COLUMN_0; case 1: return SCE_CSV_COLUMN_1; case 2: return SCE_CSV_COLUMN_2; case 3: return SCE_CSV_COLUMN_3; case 4: return SCE_CSV_COLUMN_4; case 5: return SCE_CSV_COLUMN_5; case 6: return SCE_CSV_COLUMN_6; case 7: return SCE_CSV_COLUMN_7; case 8: return SCE_CSV_COLUMN_8; case 9: return SCE_CSV_COLUMN_9; default: break; } return SCE_CSV_COLUMN_0; } // ---------------------------------------------------------------------------- void SCI_METHOD LexerCSV::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument* pAccess) { PropSetSimple props; Accessor styler(pAccess, &props); // 2 passes: 1st pass: smart delimiter detection, 2nd pass: do styling Sci_PositionU delimCount[eMax] = { 0 }; Sci_PositionU countPerPrevLine[eMax] = { 0 }; //Sci_PositionU totalCount[eMax] = { 0 }; //Sci_PositionU lineCount[eMax] = { 0 }; Sci_PositionU smartDelimVote[eMax] = { 0 }; Sci_PositionU columnAvg = 0; // 1st PASS: bool isInSQString = false; bool isInDQString = false; StyleContext cnt(startPos, length, initStyle, styler); for (; cnt.More(); cnt.Forward()) { // reset column infos if (cnt.atLineStart) { isInSQString = false; isInDQString = false; for (unsigned int i = 0; i < eMax; ++i) { Sci_PositionU const dlm = delimCount[i]; if (dlm > 0) { smartDelimVote[i] += 1; if ((dlm == countPerPrevLine[i])) { smartDelimVote[i] += dlm; // bonus for column number } // e.g. delim=TAB, all columns decimal numbers with comma(,) as decimal-point => comma wins over TAB if (dlm == columnAvg) { smartDelimVote[i] += dlm; // correction for #delimiter = (#columns - 1); } columnAvg = (columnAvg == 0) ? dlm : (columnAvg + dlm - 1) >> 1; } countPerPrevLine[i] = dlm; delimCount[i] = 0; //totalCount[i] += dlm; //++lineCount[i]; } } // cnt.atLineStart if (IsSingleQuoteChar(cnt.ch)) { if (!isInDQString) { isInSQString = !isInSQString; // toggle } } else if (IsDoubleQuoteChar(cnt.ch)) { if (!isInSQString) { isInDQString = !isInDQString; // toggle } } else if (!isInSQString && !isInDQString) { unsigned int i = IsDelimiter(cnt.ch); if (i < eMax) { ++delimCount[i]; } } } cnt.Complete(); // -------------------------- // smar delimiter selection // -------------------------- int delim = DelimList[0]; Sci_PositionU maxVote = smartDelimVote[0]; for (unsigned int i = 1; i < eMax; ++i) { if (maxVote < smartDelimVote[i]) { delim = DelimList[i]; maxVote = smartDelimVote[i]; } } // -------------------------- int const delimiter = delim; // ------------------------------------------------------------------------------ // 2nd PASS // ------------------------------------------------------------------------------ int csvColumn = 0; isInSQString = false; isInDQString = false; StyleContext sc(startPos, length, initStyle, styler); for (; sc.More(); sc.Forward()) { // reset context infos if (sc.atLineStart) { csvColumn = 0; isInSQString = false; isInDQString = false; sc.SetState(GetStateByColumn(csvColumn)); } if (IsSingleQuoteChar(sc.ch)) { if (!isInDQString) { isInSQString = !isInSQString; // toggle } } else if (IsDoubleQuoteChar(sc.ch)) { if (!isInSQString) { isInDQString = !isInDQString; // toggle } } else if (delimiter == sc.ch) { if (!isInSQString && !isInDQString) { sc.SetState(GetStateByColumn(++csvColumn)); } } } sc.Complete(); } // ---------------------------------------------------------------------------- void SCI_METHOD LexerCSV::Fold(Sci_PositionU /*startPos*/, Sci_Position /*length*/, int, IDocument* /*pAccess*/) { return; } // ---------------------------------------------------------------------------- LexerModule lmCSV(SCLEX_CSV, LexerCSV::LexerFactoryCSV, "CSV", csvWordLists); // ---------------------------------------------------------------------------- <|start_filename|>scintilla/win32/ScintillaWin.h<|end_filename|> // Scintilla source code edit control /** @file ScintillaWin.h ** Define functions from ScintillaWin.cxx that can be called from ScintillaDLL.cxx. **/ // Copyright 1998-2018 by <NAME> <<EMAIL>> // The License.txt file describes the conditions under which this software may be distributed. #ifndef SCINTILLAWIN_H #define SCINTILLAWIN_H namespace Scintilla::Internal { class ScintillaWin; int ResourcesRelease(bool fromDllMain) noexcept; int RegisterClasses(void *hInstance) noexcept; Scintilla::sptr_t DirectFunction(ScintillaWin *sci, UINT iMessage, Scintilla::uptr_t wParam, Scintilla::sptr_t lParam); } #endif <|start_filename|>grepWinNP3/sktoolslib_mod/codecvt.cpp<|end_filename|> #include "stdafx.h" #include "codecvt.h" using namespace std; Ucs2Conversion::result Ucs2Conversion::do_in(mbstate_t&, const char* from, const char* fromEnd, const char*& fromNext, wchar_t* to, wchar_t* toLimit, wchar_t*& toNext) const { size_t maxInput = (fromEnd - from) & ~1; size_t maxOutput = (toLimit - to); size_t count = min(maxInput / 2, maxOutput); result res = ok; fromNext = from; toNext = to; for (; count--; fromNext += 2, ++toNext) { unsigned char c1 = *fromNext, c2 = *(fromNext + 1); *toNext = c1 | c2 << 8; } if (toNext == to && fromNext == fromEnd - 1) res = partial; return res; } Ucs2Conversion::result Ucs2Conversion::do_out(mbstate_t&, const wchar_t* from, const wchar_t* fromEnd, const wchar_t*& fromNext, char* to, char* toLimit, char*& toNext) const { size_t maxInput = (fromEnd - from); size_t maxOutput = (toLimit - to) & ~1; size_t count = min(maxInput, maxOutput / 2); fromNext = from; toNext = to; for (; count--; ++fromNext, toNext += 2) { *(toNext + 0) = static_cast<char>(*fromNext & 0xFF); *(toNext + 1) = static_cast<char>(*fromNext >> 8 & 0xFF); } return ok; } inline unsigned char take6Bits(unsigned value, size_t rightPosition) { return static_cast<unsigned char>((value >> rightPosition) & 63); } inline size_t mostSignifantBitPosition(unsigned value) { size_t result(0); size_t half = 16; for (; half > 0; half >>= 1) { if (1u << (result + half) <= value) result += half; } return result + 1; //return *lower_bound(range(0u, 31u), \x -> (1 << x <= value)); } UTF8Conversion::result UTF8Conversion::do_in(mbstate_t&, const char* from, const char* fromEnd, const char*& fromNext, wchar_t* to, wchar_t* toLimit, wchar_t*& toNext) const { fromNext = from; toNext = to; for (; toNext < toLimit && fromNext < fromEnd; ++toNext) { if (static_cast<unsigned char>(*fromNext) < 0x80) *toNext = static_cast<unsigned char>(*fromNext++); else { // 111zxxxx : z = 0 xxxx are data bits size_t zeroBitPos = mostSignifantBitPosition(~*fromNext); size_t extraBytes = 7 - zeroBitPos; if (static_cast<size_t>(fromEnd - fromNext) < extraBytes + 1) return partial; *toNext = static_cast<unsigned char>(*fromNext++) & static_cast<wchar_t>((1 << (zeroBitPos - 1)) - 1); for (; extraBytes--; ++fromNext) { *toNext = *toNext << 6 | static_cast<unsigned char>(*fromNext) & 63; } } } return ok; } UTF8Conversion::result UTF8Conversion::do_out(mbstate_t&, const wchar_t* from, const wchar_t* fromEnd, const wchar_t*& fromNext, char* to, char* toLimit, char*& toNext) const { fromNext = from; toNext = to; for (; fromNext < fromEnd; ++fromNext) { unsigned symbol = *fromNext; if (symbol < 0x7F) { if (toNext < toLimit) *toNext++ = static_cast<unsigned char>(symbol); else return ok; } else { size_t msbPos = mostSignifantBitPosition(symbol); size_t extraBytes = msbPos / 6; if (static_cast<size_t>(toLimit - toNext) >= extraBytes + 1) { *toNext = static_cast<unsigned char>(0xFF80 >> extraBytes); *toNext++ |= take6Bits(symbol, extraBytes * 6); for (; extraBytes--;) *toNext++ = 0x80 | take6Bits(symbol, extraBytes * 6); } else return ok; } } return ok; } <|start_filename|>test/test_files/StyleLexers/styleLexDart/ExampleCode.dart<|end_filename|> // This is a normal, one-line comment. /// This is a documentation comment, used to document libraries, /// classes, and their members. Tools like IDEs and dartdoc treat /// doc comments specially. /* Comments like these are also supported. */ // Importing core libraries import 'dart:math'; // Importing libraries from external packages import 'package:test/test.dart'; // Importing files import 'path/to/my_other_file.dart'; var name = '<NAME>'; var year = 1977; var antennaDiameter = 3.7; var flybyObjects = ['Jupiter', 'Saturn', 'Uranus', 'Neptune']; var image = { 'tags': ['saturn'], 'url': '//path/to/saturn.jpg' }; if (year >= 2001) { print('21st century'); } else if (year >= 1901) { print('20th century'); } for (var object in flybyObjects) { print(object); } for (int month = 1; month <= 12; month++) { print(month); } while (year < 2016) { year += 1; } int fibonacci(int n) { if (n == 0 || n == 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); } var result = fibonacci(20); class Spacecraft { String name; DateTime launchDate; // Constructor, with syntactic sugar for assignment to members. Spacecraft(this.name, this.launchDate) { // Initialization code goes here. } // Named constructor that forwards to the default one. Spacecraft.unlaunched(String name) : this(name, null); int get launchYear => launchDate?.year; // read-only non-final property // Method. void describe() { print('Spacecraft: $name'); if (launchDate != null) { int years = DateTime.now().difference(launchDate).inDays ~/ 365; print('Launched: $launchYear ($years years ago)'); } else { print('Unlaunched'); } } } var voyager = Spacecraft('Voyager I', DateTime(1977, 9, 5)); voyager.describe(); var voyager3 = Spacecraft.unlaunched('Voyager III'); voyager3.describe(); class Orbiter extends Spacecraft { double altitude; Orbiter(String name, DateTime launchDate, this.altitude) : super(name, launchDate); } class Piloted { int astronauts = 1; void describeCrew() { print('Number of astronauts: $astronauts'); } } abstract class Describable { void describe(); void describeWithEmphasis() { print('========='); describe(); print('========='); } } const oneSecond = Duration(seconds: 1); // ··· Future<void> printWithDelay(String message) async { await Future.delayed(oneSecond); print(message); } Future<void> printWithDelay(String message) { return Future.delayed(oneSecond).then((_) { print(message); }); } Future<void> createDescriptions(Iterable<String> objects) async { for (var object in objects) { try { var file = File('$object.txt'); if (await file.exists()) { var modified = await file.lastModified(); print( 'File for $object already exists. It was modified on $modified.'); continue; } await file.create(); await file.writeAsString('Start describing $object in this file.'); } on IOException catch (e) { print('Cannot create description for $object: $e'); } } } Stream<String> report(Spacecraft craft, Iterable<String> objects) async* { for (var object in objects) { await Future.delayed(oneSecond); yield '${craft.name} flies by $object'; } } if (astronauts == 0) { throw StateError('No astronauts.'); } try { for (var object in flybyObjects) { var description = await File('$object.txt').readAsString(); print(description); } } on IOException catch (e) { print('Could not describe object: $e'); } finally { flybyObjects.clear(); } <|start_filename|>grepWinNP3/sktoolslib_mod/InfoRtfDialog.cpp<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2020-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "InfoRtfDialog.h" #include "OnOutOfScope.h" #include <richedit.h> #include <shellapi.h> #pragma comment(lib, "Shell32.lib") CInfoRtfDialog::CInfoRtfDialog() : m_hParent(nullptr) , m_hwndRichEdit(nullptr) , m_rtfId(0) , m_iconId(0) { m_richEditLib = LoadLibrary(TEXT("Msftedit.dll")); } CInfoRtfDialog::~CInfoRtfDialog() { } INT_PTR CInfoRtfDialog::DoModal(HINSTANCE hInstance, HWND hParent, const std::string& dlgTitle, UINT rtfId, const std::wstring& resType, UINT iconId, int width, int height) { return DoModal(hInstance, hParent, dlgTitle, rtfId, resType, iconId, 10, 10, width, height); } INT_PTR CInfoRtfDialog::DoModal(HINSTANCE hInstance, HWND hParent, const std::string& dlgTitle, UINT rtfId, const std::wstring& resType, UINT iconId, int x, int y, int width, int height) { m_hParent = hParent; m_rtfId = rtfId; m_rtfResType = resType; m_iconId = iconId; auto hGbl = GlobalAlloc(GMEM_ZEROINIT, 1024); OnOutOfScope(GlobalFree(hGbl)); if (!hGbl) return -1; auto lpDt = static_cast<LPDLGTEMPLATE>(GlobalLock(hGbl)); // Define a dialog box. lpDt->style = WS_POPUP | WS_BORDER | WS_SYSMENU | DS_MODALFRAME | WS_CAPTION | WS_SIZEBOX; lpDt->cdit = 0; // Number of controls lpDt->x = static_cast<SHORT>(x); lpDt->y = static_cast<SHORT>(y); lpDt->cx = static_cast<short>(width); lpDt->cy = static_cast<short>(height); auto lpw = reinterpret_cast<LPWORD>(lpDt + 1); *lpw++ = 0; // No menu *lpw++ = 0; // Predefined dialog box class (by default) auto lpWsz = reinterpret_cast<LPWSTR>(lpw); auto nchar = 1 + MultiByteToWideChar(CP_UTF8, 0, dlgTitle.c_str(), -1, lpWsz, 50); lpw += nchar; GlobalUnlock(hGbl); return __super::DoModal(hInstance, lpDt, hParent); } void CInfoRtfDialog::ShowModeless(HINSTANCE hInstance, HWND hParent, const std::string& dlgTitle, UINT rtfId, const std::wstring& resType, UINT iconId, int width, int height) { m_hParent = hParent; m_rtfId = rtfId; m_rtfResType = resType; m_iconId = iconId; auto hGbl = GlobalAlloc(GMEM_ZEROINIT, 1024); OnOutOfScope(GlobalFree(hGbl)); if (!hGbl) return; auto lpDt = static_cast<LPDLGTEMPLATE>(GlobalLock(hGbl)); // Define a dialog box. lpDt->style = WS_POPUP | WS_BORDER | WS_SYSMENU | DS_MODALFRAME | WS_CAPTION | WS_SIZEBOX; lpDt->cdit = 0; // Number of controls lpDt->x = 10; lpDt->y = 10; lpDt->cx = static_cast<short>(width); lpDt->cy = static_cast<short>(height); auto lpw = reinterpret_cast<LPWORD>(lpDt + 1); *lpw++ = 0; // No menu *lpw++ = 0; // Predefined dialog box class (by default) auto lpWsz = reinterpret_cast<LPWSTR>(lpw); auto nchar = 1 + MultiByteToWideChar(CP_UTF8, 0, dlgTitle.c_str(), -1, lpWsz, 50); lpw += nchar; GlobalUnlock(hGbl); __super::ShowModeless(hInstance, lpDt, hParent); } LRESULT CInfoRtfDialog::DlgFunc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_INITDIALOG: { InitDialog(hwndDlg, m_iconId); RECT rc = {0}; GetClientRect(*this, &rc); m_hwndRichEdit = CreateWindowEx(0, MSFTEDIT_CLASS, L"", ES_MULTILINE | WS_VISIBLE | WS_CHILD | WS_BORDER | WS_VSCROLL | ES_NOOLEDRAGDROP | ES_SAVESEL | ES_READONLY, 0, 0, rc.right - rc.left, rc.bottom - rc.top, *this, nullptr, hResource, nullptr); auto hRes = FindResource(hResource, MAKEINTRESOURCE(m_rtfId), m_rtfResType.c_str()); if (hRes) { auto hResourceLoaded = LoadResource(hResource, hRes); if (hResourceLoaded) { auto lpResLock = static_cast<const char*>(LockResource(hResourceLoaded)); auto resLen = SizeofResource(hResource, hRes); if (resLen) { SETTEXTEX stt = {0}; stt.codepage = CP_UTF8; stt.flags = ST_DEFAULT | ST_NEWCHARS; SendMessage(m_hwndRichEdit, EM_SETTEXTEX, reinterpret_cast<WPARAM>(&stt), reinterpret_cast<LPARAM>(lpResLock)); SetFocus(m_hwndRichEdit); SendMessage(m_hwndRichEdit, EM_SETSEL, static_cast<WPARAM>(-1), static_cast<LPARAM>(0)); SendMessage(m_hwndRichEdit, EM_SETREADONLY, static_cast<WPARAM>(1), reinterpret_cast<LPARAM>(nullptr)); SendMessage(m_hwndRichEdit, EM_SETEVENTMASK, NULL, ENM_LINK | ENM_SCROLL); } } } return static_cast<INT_PTR>(TRUE); } case WM_SIZE: { UINT width = LOWORD(lParam); UINT height = HIWORD(lParam); MoveWindow(m_hwndRichEdit, 0, 0, width, height, TRUE); } break; case WM_DESTROY: CloseWindow(m_hwndRichEdit); DestroyWindow(m_hwndRichEdit); break; case WM_COMMAND: switch (LOWORD(wParam)) { case IDOK: case IDCANCEL: EndDialog(*this, LOWORD(wParam)); return static_cast<INT_PTR>(TRUE); default: break; } break; case WM_NOTIFY: { auto pHdr = reinterpret_cast<LPNMHDR>(lParam); if (pHdr) { if (pHdr->hwndFrom == m_hwndRichEdit) { switch (pHdr->code) { case EN_LINK: { auto pEnLink = reinterpret_cast<ENLINK*>(lParam); if ((pEnLink->msg != WM_LBUTTONUP) && (pEnLink->msg != WM_SETCURSOR)) break; auto buffer = std::make_unique<wchar_t[]>(pEnLink->chrg.cpMax - pEnLink->chrg.cpMin + 1); TEXTRANGE range{}; range.chrg = pEnLink->chrg; range.lpstrText = buffer.get(); SendMessage(m_hwndRichEdit, EM_GETTEXTRANGE, 0, reinterpret_cast<LPARAM>(&range)); auto url = std::wstring(buffer.get(), pEnLink->chrg.cpMax - pEnLink->chrg.cpMin); if (!url.empty()) { if (pEnLink->msg == WM_SETCURSOR) SetCursor(LoadCursor(nullptr, IDC_HAND)); else ShellExecute(hwndDlg, L"open", url.c_str(), nullptr, nullptr, SW_SHOWDEFAULT); } } break; } } } } break; } return static_cast<INT_PTR>(FALSE); } <|start_filename|>grepWinNP3/sktoolslib_mod/SysInfo.h<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012-2013, 2020-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #pragma once /** * \ingroup Utils * This singleton class handles system information */ #ifdef NTDDI_WINBLUE class SysInfo { private: SysInfo(); ~SysInfo(); public: static const SysInfo& Instance(); bool IsElevated() const { return m_isElevated; } bool IsUACEnabled() const { return m_isUacEnabled; } private: bool m_isElevated; bool m_isUacEnabled; }; #else class SysInfo { private: SysInfo(); ~SysInfo(); public: static const SysInfo& Instance(); DWORD GetFullVersion() const { return MAKEWORD(inf.dwMinorVersion, inf.dwMajorVersion); } bool IsXP() const { return (GetFullVersion() < 0x0600); } // cover Win5.1 and 5.2 alike bool IsVista() const { return (GetFullVersion() == 0x0600); } bool IsVistaOrLater() const { return (GetFullVersion() >= 0x0600); } bool IsWin7() const { return (GetFullVersion() == 0x0601); } bool IsWin7OrLater() const { return (GetFullVersion() >= 0x0601); } bool IsWin8() const { return (GetFullVersion() == 0x0602); } bool IsWin8OrLater() const { return (GetFullVersion() >= 0x0602); } bool IsElevated() const { return m_isElevated; } bool IsUACEnabled() const { return m_isUacEnabled; } private: OSVERSIONINFOEX inf; bool m_isElevated; bool m_isUacEnabled; }; #endif <|start_filename|>src/uchardet/uchardet/src/LangModels/LangSpanishModel.cpp<|end_filename|> /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "../nsSBCharSetProber.h" /********* Language model for: Spanish *********/ /** * Generated by BuildLangModel.py * On: 2015-12-12 18:39:02.290370 **/ /* Character Mapping Table: * ILL: illegal character. * CTR: control character specific to the charset. * RET: carriage/return. * SYM: symbol (punctuation) that does not belong to word. * NUM: 0 - 9. * * Other characters are ordered by probabilities * (0 is the most common character in the language). * * Orders are generic to a language. So the codepoint with order X in * CHARSET1 maps to the same character as the codepoint with the same * order X in CHARSET2 for the same language. * As such, it is possible to get missing order. For instance the * ligature of 'o' and 'e' exists in ISO-8859-15 but not in ISO-8859-1 * even though they are both used for French. Same for the euro sign. */ static const unsigned char Iso_8859_1_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 1, 14, 10, 8, 0, 16, 15, 20, 5, 23, 27, 7, 12, 3, 2, /* 4X */ 13, 21, 6, 4, 9, 11, 18, 31, 28, 17, 24,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 1, 14, 10, 8, 0, 16, 15, 20, 5, 23, 27, 7, 12, 3, 2, /* 6X */ 13, 21, 6, 4, 9, 11, 18, 31, 28, 17, 24,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM,SYM, 52,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* BX */ 33, 25, 39, 46, 37, 45, 47, 35, 36, 26, 48, 40, 53, 22, 41, 43, /* CX */ 49, 29, 38, 19, 50, 54, 34,SYM, 44, 51, 30, 55, 32, 42, 56, 57, /* DX */ 33, 25, 39, 46, 37, 45, 47, 35, 36, 26, 48, 40, 58, 22, 41, 43, /* EX */ 49, 29, 38, 19, 50, 59, 34,SYM, 44, 51, 30, 60, 32, 42, 61, 62, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Iso_8859_15_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 1, 14, 10, 8, 0, 16, 15, 20, 5, 23, 27, 7, 12, 3, 2, /* 4X */ 13, 21, 6, 4, 9, 11, 18, 31, 28, 17, 24,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 1, 14, 10, 8, 0, 16, 15, 20, 5, 23, 27, 7, 12, 3, 2, /* 6X */ 13, 21, 6, 4, 9, 11, 18, 31, 28, 17, 24,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM, 63,SYM, 64,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM, 65, 66,SYM,SYM, 67,SYM,SYM,SYM, 68, 69, 70,SYM, /* BX */ 33, 25, 39, 46, 37, 45, 47, 35, 36, 26, 48, 40, 71, 22, 41, 43, /* CX */ 49, 29, 38, 19, 50, 72, 34,SYM, 44, 51, 30, 73, 32, 42, 74, 75, /* DX */ 33, 25, 39, 46, 37, 45, 47, 35, 36, 26, 48, 40, 76, 22, 41, 43, /* EX */ 49, 29, 38, 19, 50, 77, 34,SYM, 44, 51, 30, 78, 32, 42, 79, 80, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Windows_1252_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 1, 14, 10, 8, 0, 16, 15, 20, 5, 23, 27, 7, 12, 3, 2, /* 4X */ 13, 21, 6, 4, 9, 11, 18, 31, 28, 17, 24,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 1, 14, 10, 8, 0, 16, 15, 20, 5, 23, 27, 7, 12, 3, 2, /* 6X */ 13, 21, 6, 4, 9, 11, 18, 31, 28, 17, 24,SYM,SYM,SYM,SYM,CTR, /* 7X */ SYM,ILL,SYM, 81,SYM,SYM,SYM,SYM,SYM,SYM, 82,SYM, 83,ILL, 84,ILL, /* 8X */ ILL,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, 85,SYM, 86,ILL, 87, 88, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM,SYM, 89,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* BX */ 33, 25, 39, 46, 37, 45, 47, 35, 36, 26, 48, 40, 90, 22, 41, 43, /* CX */ 49, 29, 38, 19, 50, 91, 34,SYM, 44, 51, 30, 92, 32, 42, 93, 94, /* DX */ 33, 25, 39, 46, 37, 45, 47, 35, 36, 26, 48, 40, 95, 22, 41, 43, /* EX */ 49, 29, 38, 19, 50, 96, 34,SYM, 44, 51, 30, 97, 32, 42, 98, 99, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ /* Model Table: * Total sequences: 897 * First 512 sequences: 0.9970385677528184 * Next 512 sequences (512-1024): 0.0029614322471815486 * Rest: 4.597017211338539e-17 * Negative sequences: TODO */ static const PRUint8 SpanishLangModel[] = { 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,0,3,3,3,2,3,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,2,3,3,3,3,3,3,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,2,3,3,2,2,3,3,2,2,3,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,0,3,2,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,0,2,3,3,3,0,0,2,2,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,2,3,3,3,3,2,0,3,2,2, 3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,2,2,3,3,2,2,0,2,2,0, 3,3,3,2,3,3,3,3,2,2,2,3,3,2,2,3,2,3,3,3,3,2,3,2,2,3,3,2,0,0,2,2,2, 3,3,3,3,3,3,3,3,2,3,3,3,2,2,3,2,2,3,2,3,3,0,3,2,2,3,3,0,0,0,2,2,2, 3,3,3,3,3,3,3,3,2,3,3,3,2,2,2,2,2,3,0,3,3,2,3,0,2,3,3,3,0,0,2,0,0, 3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,2,3,0,2,0, 3,3,3,3,3,3,2,2,2,2,2,3,3,3,3,2,2,3,0,3,2,0,3,2,0,3,3,2,2,0,3,2,2, 3,3,3,2,3,3,3,3,2,3,3,3,2,3,3,0,2,2,2,3,3,0,3,2,0,3,3,2,0,0,3,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,2,2,3,2,2,3,2,3,2,2,3,3,0,3,2,2,0,0,2,2,0, 3,3,3,3,3,3,3,3,3,3,0,3,3,0,2,2,2,2,2,3,3,0,3,2,2,2,3,2,0,0,3,2,3, 3,3,3,2,2,3,3,3,2,3,2,3,2,2,2,2,3,2,0,3,0,0,3,2,0,2,2,2,0,0,3,2,0, 3,3,3,3,3,3,3,3,2,2,2,3,2,2,2,2,2,2,0,3,2,0,0,2,2,2,2,2,0,0,2,2,0, 3,3,3,2,2,3,2,2,2,0,2,3,0,2,0,2,2,2,2,3,0,0,3,0,0,2,3,2,0,0,0,0,0, 0,0,0,3,3,0,3,3,3,3,3,0,3,3,2,3,2,0,3,0,0,0,0,0,0,0,0,0,2,0,0,0,0, 3,3,3,3,2,3,3,3,3,3,2,3,3,0,2,0,2,3,2,2,2,0,3,2,2,2,3,0,2,0,2,2,2, 2,3,2,0,2,2,0,2,2,2,0,3,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,0,2,2,3,3,3,2,3,2,3,3,3,0,2,0,0,2,0,2,2,0,0,0,0,0,0,0,0, 3,3,3,2,0,3,2,2,2,2,0,3,2,2,0,0,0,0,0,3,0,0,2,2,0,2,3,0,0,0,2,0,2, 3,3,3,2,0,3,2,0,2,2,2,3,2,2,2,3,0,2,0,3,2,3,2,0,3,3,2,2,0,0,2,0,0, 2,0,0,3,3,2,3,3,2,3,3,2,3,3,2,3,3,2,2,0,2,2,0,2,2,0,0,0,2,2,0,0,0, 2,3,2,3,3,2,3,3,3,3,3,2,2,3,2,3,2,2,2,0,0,0,0,2,0,0,0,0,3,0,0,0,0, 3,3,3,2,3,3,3,3,2,2,2,3,3,0,2,2,2,3,2,0,2,0,2,0,0,0,0,2,0,0,2,2,0, 3,3,3,2,2,3,2,2,2,3,3,3,2,3,2,0,2,2,3,2,2,2,0,2,0,2,2,2,3,0,0,2,0, 3,3,3,0,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,2,0,0,3,0,0,2,0,0,0,0,0,0,0, 2,3,2,3,3,0,2,3,2,3,2,0,3,2,3,0,2,0,0,0,0,0,0,2,2,0,0,0,0,2,0,0,0, 3,3,3,3,2,3,2,2,2,2,2,2,0,0,2,0,2,2,0,0,2,0,0,2,0,2,0,2,0,0,0,2,0, 3,0,0,2,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0, }; const SequenceModel Iso_8859_1SpanishModel = { Iso_8859_1_CharToOrderMap, SpanishLangModel, 33, (float)0.9970385677528184, PR_TRUE, "ISO-8859-1" }; const SequenceModel Iso_8859_15SpanishModel = { Iso_8859_15_CharToOrderMap, SpanishLangModel, 33, (float)0.9970385677528184, PR_TRUE, "ISO-8859-15" }; const SequenceModel Windows_1252SpanishModel = { Windows_1252_CharToOrderMap, SpanishLangModel, 33, (float)0.9970385677528184, PR_TRUE, "WINDOWS-1252" }; <|start_filename|>grepWinNP3/src/RegexTestDlg.cpp<|end_filename|> // grepWin - regex search and replace for Windows // Copyright (C) 2007-2008, 2011-2013, 2019-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "resource.h" #include "RegexTestDlg.h" #include "RegexReplaceFormatter.h" #include "Theme.h" #include "DarkModeHelper.h" #include "ResString.h" #include <string> #include <Richedit.h> #pragma warning(push) #pragma warning(disable : 4996) // warning STL4010: Various members of std::allocator are deprecated in C++17 #include <boost/regex.hpp> #pragma warning(pop) CRegexTestDlg::CRegexTestDlg(HWND hParent) : bDotMatchesNewline(false) , bCaseSensitive(false) , m_hParent(hParent) , m_themeCallbackId(0) { } CRegexTestDlg::~CRegexTestDlg() { } LRESULT CRegexTestDlg::DlgFunc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (uMsg) { case WM_INITDIALOG: { m_themeCallbackId = CTheme::Instance().RegisterThemeChangeCallback( [this]() { CTheme::Instance().SetThemeForDialog(*this, CTheme::Instance().IsDarkTheme()); CTheme::Instance().SetFontForDialog(*this, CTheme::Instance().GetDlgFontFaceName(), CTheme::Instance().GetDlgFontSize()); DarkModeHelper::Instance().AllowDarkModeForWindow(GetToolTipHWND(), CTheme::Instance().IsDarkTheme()); }); CTheme::Instance().SetThemeForDialog(*this, CTheme::Instance().IsDarkTheme()); CTheme::Instance().SetFontForDialog(*this, CTheme::Instance().GetDlgFontFaceName(), CTheme::Instance().GetDlgFontSize()); DarkModeHelper::Instance().AllowDarkModeForWindow(GetToolTipHWND(), CTheme::Instance().IsDarkTheme()); InitDialog(hwndDlg, IDI_GREPWIN); CLanguage::Instance().TranslateWindow(*this); // initialize the controls SetDlgItemText(hwndDlg, IDC_SEARCHTEXT, m_searchText.c_str()); SetDlgItemText(hwndDlg, IDC_REPLACETEXT, m_replaceText.c_str()); SetFocus(GetDlgItem(hwndDlg, IDC_SEARCHTEXT)); m_resizer.Init(hwndDlg); m_resizer.UseSizeGrip(!CTheme::Instance().IsDarkTheme()); m_resizer.AddControl(hwndDlg, IDC_TEXTCONTENT, RESIZER_TOPLEFTRIGHT); m_resizer.AddControl(hwndDlg, IDC_SEARCHTEXT, RESIZER_TOPLEFTRIGHT); m_resizer.AddControl(hwndDlg, IDC_REPLACETEXT, RESIZER_TOPLEFTRIGHT); m_resizer.AddControl(hwndDlg, IDC_REGEXMATCH, RESIZER_TOPLEFTRIGHT); m_resizer.AddControl(hwndDlg, IDC_REGEXREPLACED, RESIZER_TOPLEFTBOTTOMRIGHT); m_resizer.AddControl(hwndDlg, IDOK, RESIZER_BOTTOMRIGHT); m_resizer.AddControl(hwndDlg, IDCANCEL, RESIZER_BOTTOMRIGHT); SendMessage(GetDlgItem(*this, IDC_TEXTCONTENT), EM_SETEVENTMASK, 0, ENM_CHANGE); SendMessage(GetDlgItem(*this, IDC_TEXTCONTENT), EM_EXLIMITTEXT, 0, 200 * 1024); SendMessage(GetDlgItem(*this, IDC_REGEXREPLACED), EM_EXLIMITTEXT, 0, 200 * 1024); } return FALSE; case WM_COMMAND: return DoCommand(LOWORD(wParam), HIWORD(wParam)); case WM_SIZE: { m_resizer.DoResize(LOWORD(lParam), HIWORD(lParam)); } break; case WM_GETMINMAXINFO: { MINMAXINFO* mmi = reinterpret_cast<MINMAXINFO*>(lParam); mmi->ptMinTrackSize.x = m_resizer.GetDlgRect()->right; mmi->ptMinTrackSize.y = m_resizer.GetDlgRect()->bottom; return 0; } case WM_TIMER: { if (wParam == ID_REGEXTIMER) { KillTimer(*this, ID_REGEXTIMER); DoRegex(); } } break; case WM_CLOSE: CTheme::Instance().RemoveRegisteredCallback(m_themeCallbackId); break; default: return FALSE; } return FALSE; } LRESULT CRegexTestDlg::DoCommand(int id, int msg) { switch (id) { case IDOK: { auto buf = GetDlgItemText(IDC_SEARCHTEXT); m_searchText = buf.get(); buf = GetDlgItemText(IDC_REPLACETEXT); m_replaceText = buf.get(); } [[fallthrough]]; case IDCANCEL: EndDialog(*this, id); break; case IDC_TEXTCONTENT: { if (msg == EN_CHANGE) { auto buf = GetDlgItemText(IDC_TEXTCONTENT); m_textContent = std::wstring(buf.get()); SetTimer(*this, ID_REGEXTIMER, 300, nullptr); } } break; case IDC_SEARCHTEXT: { if (msg == EN_CHANGE) { auto buf = GetDlgItemText(IDC_SEARCHTEXT); m_searchText = buf.get(); SetTimer(*this, ID_REGEXTIMER, 300, nullptr); } } break; case IDC_REPLACETEXT: { if (msg == EN_CHANGE) { auto buf = GetDlgItemText(IDC_REPLACETEXT); m_replaceText = buf.get(); SetTimer(*this, ID_REGEXTIMER, 300, nullptr); } } break; default: break; } return 1; } void CRegexTestDlg::SetStrings(const std::wstring& search, const std::wstring& replace) { m_replaceText = replace; m_searchText = search; } void CRegexTestDlg::DoRegex() { if (m_textContent.empty()) { SetDlgItemText(*this, IDC_REGEXMATCH, TranslatedString(hResource, IDS_NOTESTTEXTAVAILABLE).c_str()); SetDlgItemText(*this, IDC_REGEXREPLACED, TranslatedString(hResource, IDS_NOTESTTEXTAVAILABLE).c_str()); } else if (m_searchText.empty()) { SetDlgItemText(*this, IDC_REGEXMATCH, TranslatedString(hResource, IDS_SEARCHSTRINGEMPTY).c_str()); SetDlgItemText(*this, IDC_REGEXREPLACED, TranslatedString(hResource, IDS_SEARCHSTRINGEMPTY).c_str()); } else if (m_replaceText.empty()) { SetDlgItemText(*this, IDC_REGEXREPLACED, TranslatedString(hResource, IDS_NOREPLACETEXT).c_str()); } if (!m_textContent.empty()) { std::wstring searchResult; std::wstring replaceResult; if (!m_searchText.empty()) { std::wstring::const_iterator start, end; start = m_textContent.begin(); end = m_textContent.end(); boost::match_results<std::wstring::const_iterator> what; try { int ft = boost::regex::normal; if (!bCaseSensitive) ft |= boost::regbase::icase; boost::wregex expression = boost::wregex(m_searchText, ft); boost::match_results<std::wstring::const_iterator> whatc; boost::match_flag_type flags = boost::match_default; if (!bDotMatchesNewline) flags |= boost::match_not_dot_newline; boost::match_flag_type rflags = boost::match_default | boost::format_all; if (!bDotMatchesNewline) rflags |= boost::match_not_dot_newline; RegexReplaceFormatter replaceFmt(m_replaceText); replaceFmt.SetReplacePair(L"${filepath}", L"c:\\grepwintest\\file.txt"); replaceFmt.SetReplacePair(L"${filename}", L"file"); replaceFmt.SetReplacePair(L"${fileext}", L"txt"); replaceResult = regex_replace(m_textContent, expression, replaceFmt, rflags); while (boost::regex_search(start, end, whatc, expression, flags)) { if (!searchResult.empty()) searchResult = searchResult + L"\r\n----------------------------\r\n"; std::wstring c(whatc[0].first, whatc[0].second); searchResult = searchResult + c; // update search position: if (start == whatc[0].second) { if (start == end) break; ++start; } else start = whatc[0].second; // update flags: flags |= boost::match_prev_avail; flags |= boost::match_not_bob; } } catch (const std::exception&) { } if (searchResult.empty()) SetDlgItemText(*this, IDC_REGEXMATCH, TranslatedString(hResource, IDS_NOMATCH).c_str()); else SetDlgItemText(*this, IDC_REGEXMATCH, searchResult.c_str()); } if (!searchResult.empty()) SetDlgItemText(*this, IDC_REGEXMATCH, searchResult.c_str()); if (!replaceResult.empty()) SetDlgItemText(*this, IDC_REGEXREPLACED, replaceResult.c_str()); } } <|start_filename|>grepWinNP3/sktoolslib_mod/Hash.cpp<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2020-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "Hash.h" #include <vector> #include <Wincrypt.h> std::wstring GetHashText(const void* data, size_t dataSize, HashType hashType) { HCRYPTPROV hProv = NULL; if (!CryptAcquireContext(&hProv, nullptr, nullptr, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) { return {}; } BOOL hashOk = FALSE; HCRYPTPROV hHash = NULL; switch (hashType) { case HashType::HashSha1: hashOk = CryptCreateHash(hProv, CALG_SHA1, 0, 0, &hHash); break; case HashType::HashMd5: hashOk = CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash); break; case HashType::HashSha256: hashOk = CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash); break; } if (!hashOk) { CryptReleaseContext(hProv, 0); return {}; } if (!CryptHashData(hHash, static_cast<const BYTE*>(data), static_cast<DWORD>(dataSize), 0)) { CryptDestroyHash(hHash); CryptReleaseContext(hProv, 0); return {}; } DWORD cbHashSize = 0, dwCount = sizeof(DWORD); if (!CryptGetHashParam(hHash, HP_HASHSIZE, reinterpret_cast<BYTE*>(&cbHashSize), &dwCount, 0)) { CryptDestroyHash(hHash); CryptReleaseContext(hProv, 0); return {}; } std::vector<BYTE> buffer(cbHashSize); if (!CryptGetHashParam(hHash, HP_HASHVAL, reinterpret_cast<BYTE*>(&buffer[0]), &cbHashSize, 0)) { CryptDestroyHash(hHash); CryptReleaseContext(hProv, 0); return {}; } std::wostringstream oss; oss.fill('0'); oss.width(2); for (const auto& b : buffer) { oss << std::hex << static_cast<const int>(b); } CryptDestroyHash(hHash); CryptReleaseContext(hProv, 0); return oss.str(); } <|start_filename|>grepWinNP3/sktoolslib_mod/Windows10Colors.h<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2018, 2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #pragma once /** * Functions to obtain Windows 10 accent colors and colors used to paint window frames. */ #include <Windows.h> #include <vector> #include <wrl.h> #include <windows.ui.viewmanagement.h> class Win10Colors { public: Win10Colors(); ~Win10Colors(); /** * RGBA color. Red is in the LSB, Alpha in the MSB. * You can use GetRValue() et al to access individual components. */ using RGBA = DWORD; /// Accent color shades struct AccentColor { /// foreground accent color RGBA foreground; /// background accent color RGBA background; /// Base accent color RGBA accent; /// Darkest shade. RGBA darkest; /// Darker shade. RGBA darker; /// Dark shade. RGBA dark; /// Light shade. RGBA light; /// Lighter shade. RGBA lighter; /// Lightest shade. RGBA lightest; }; static HRESULT GetAccentColor(AccentColor& color); /// Dynamically loaded WindowsCreateStringReference, if available static HRESULT WindowsCreateStringReference(PCWSTR sourceString, UINT32 length, HSTRING_HEADER* hstringHeader, HSTRING* string) { return instance.WindowsCreateStringReferenceImpl(sourceString, length, hstringHeader, string); } /// Dynamically loaded RoActivateInstance, if available static HRESULT RoActivateInstance(HSTRING activatableClassId, IInspectable** newInstance) { return instance.RoActivateInstanceImpl(activatableClassId, newInstance); } protected: /// Wrap WindowsCreateStringReference HRESULT WindowsCreateStringReferenceImpl(PCWSTR sourceString, UINT32 length, HSTRING_HEADER* hstringHeader, HSTRING* string) const { if (!pWindowsCreateStringReference) return E_NOTIMPL; return pWindowsCreateStringReference(sourceString, length, hstringHeader, string); } /// Wrap RoActivateInstance HRESULT RoActivateInstanceImpl(HSTRING activatableClassId, IInspectable** inst) const { if (!pRoActivateInstance) return E_NOTIMPL; return pRoActivateInstance(activatableClassId, inst); } static RGBA MakeRGBA(uint8_t r, uint8_t g, uint8_t b, uint8_t a) { return RGB(r, g, b) | (a << 24); } static RGBA ToRGBA(ABI::Windows::UI::Color color) { return MakeRGBA(color.R, color.G, color.B, color.A); } private: static Win10Colors instance; bool m_modulesLoaded = false; HMODULE winrt = nullptr; HMODULE m_winrtString = nullptr; using PfnWindowsCreateStringReference = HRESULT(STDAPICALLTYPE* )( PCWSTR sourceString, UINT32 length, HSTRING_HEADER* hStringHeader, HSTRING* string); PfnWindowsCreateStringReference pWindowsCreateStringReference = nullptr; using PfnRoActivateInstance = HRESULT(WINAPI* )(HSTRING activatableClassId, IInspectable** instance); PfnRoActivateInstance pRoActivateInstance = nullptr; }; <|start_filename|>scintilla/src/CharacterType.cxx<|end_filename|> // Scintilla source code edit control /** @file CharacterType.cxx ** Tests for character type and case-insensitive comparisons. **/ // Copyright 1998-2010 by <NAME> <<EMAIL>> // The License.txt file describes the conditions under which this software may be distributed. #include <cstdlib> #include <cassert> #include "CharacterType.h" using namespace Scintilla::Internal; namespace Scintilla::Internal { int CompareCaseInsensitive(const char *a, const char *b) noexcept { while (*a && *b) { if (*a != *b) { const char upperA = MakeUpperCase(*a); const char upperB = MakeUpperCase(*b); if (upperA != upperB) return upperA - upperB; } a++; b++; } // Either *a or *b is nul return *a - *b; } int CompareNCaseInsensitive(const char *a, const char *b, size_t len) noexcept { while (*a && *b && len) { if (*a != *b) { const char upperA = MakeUpperCase(*a); const char upperB = MakeUpperCase(*b); if (upperA != upperB) return upperA - upperB; } a++; b++; len--; } if (len == 0) return 0; else // Either *a or *b is nul return *a - *b; } } <|start_filename|>src/crypto/extras/np3encrypt.bat<|end_filename|> @echo off setlocal enableextensions set NP3ENCRYPTER=%~dp0np3encrypt.exe echo. Change directory to "%~1" pushd "%~1" echo. Iterating all files of "%CD%" for /r %%f in (*) do call :ENCRYPT "%%f" "%2" popd goto :END :: ---------------------------------------------------------------------------- :ENCRYPT set fn=%~nx1 set passphrase=<PASSWORD> echo. Encrypting file "%fn%" %NP3ENCRYPTER% ef "%fn%" "%fn%.enc" %passphrase% goto :eof :: ---------------------------------------------------------------------------- :END pause ::popd endlocal <|start_filename|>grepWinNP3/src/RegexReplaceFormatter.cpp<|end_filename|> // grepWin - regex search and replace for Windows // Copyright (C) 2011, 2015 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "RegexReplaceFormatter.h" std::vector<NumberReplacer> g_incVec; std::vector<NumberReplacerA> g_incVecA; <|start_filename|>src/StyleLexers/styleLexRC.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_RC = { // Primary keywords "ACCELERATORS ALT AUTO3STATE AUTOCHECKBOX AUTORADIOBUTTON BEGIN BITMAP BLOCK BUTTON CAPTION CHARACTERISTICS " "CHECKBOX CLASS COMBOBOX CONTROL CTEXT CURSOR DEFPUSHBUTTON DIALOG DIALOGEX DISCARDABLE EDITTEXT END " "EXSTYLE FONT GROUPBOX ICON LANGUAGE LISTBOX LTEXT MENU MENUEX MENUITEM MESSAGETABLE POPUP PUSHBUTTON " "RADIOBUTTON RCDATA RTEXT SCROLLBAR SEPARATOR SHIFT STATE3 STRINGTABLE STYLE TEXTINCLUDE VALUE VERSION " "VERSIONINFO VIRTKEY", // Secondary keywords "", // Documentation comment keywords "addindex addtogroup anchor arg attention author b brief bug c class code copyright date def defgroup deprecated dontinclude " "e em endcode endhtmlonly endif endlatexonly endlink endverbatim enum example exception f$ f[f] file" "hideinitializer htmlinclude htmlonly if image include ingroup internal invariant interface latexonly li line link " "mainpage name namespace nosubgrouping note overload p page par param param[in] param[out] post pre " "ref relates remarks return retval sa section see showinitializer since skip skipline struct subsection " "test throw throws todo typedef union until var verbatim verbinclude version warning weakgroup", // Global classes and typedefs "", // Preprocessor definitions "", // Task marker and error marker keywords "BUG FIXME HACK NOTE TBD TODO UNDONE XXX @@@", NULL, }; EDITLEXER lexRC = { SCLEX_CPP, "cpp", IDS_LEX_RESOURCE_SCR, L"Resource Script", L"rc; rc2; rct; rh; dlg; lang", L"", &KeyWords_RC, { { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_C_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {SCE_C_IDENTIFIER}, IDS_LEX_STR_63129, L"Identifier", L"", L"" }, { {MULTI_STYLE(SCE_C_COMMENT,SCE_C_COMMENTLINE,0,0)}, IDS_LEX_STR_63127, L"Comment", L"fore:#008000", L"" }, { {SCE_C_WORD}, IDS_LEX_STR_63128, L"Keyword", L"bold; fore:#0A246A", L"" }, //{ {SCE_C_WORD2}, IDS_LEX_STR_63260, L"Keyword 2nd", L"bold; fore:#A46000", L"" }, //{ {SCE_C_GLOBALCLASS}, IDS_LEX_STR_63258, L"Typedefs/Classes", L"bold; italic; fore:#800000", L"" }, { {SCE_C_STRING}, IDS_LEX_STR_63131, L"String", L"fore:#008000", L"" }, //{ {SCE_C_REGEX}, IDS_LEX_STR_63135, L"Regex", L"fore:#006633; back:#FFF1A8", L"" }, { {SCE_C_NUMBER}, IDS_LEX_STR_63130, L"Number", L"fore:#FF0000", L"" }, { {SCE_C_OPERATOR}, IDS_LEX_STR_63132, L"Operator", L"fore:#0A246A", L"" }, { {MULTI_STYLE(SCE_C_PREPROCESSOR,SCE_C_PREPROCESSORCOMMENT,SCE_C_PREPROCESSORCOMMENTDOC,0)}, IDS_LEX_STR_63133, L"Preprocessor", L"fore:#FF8000", L"" }, //{ {MULTI_STYLE(SCE_C_VERBATIM, SCE_C_TRIPLEVERBATIM,0,0)}, IDS_LEX_STR_63134, L"Verbatim", L"fore:#B000B0", L"" }, { {MULTI_STYLE(SCE_C_COMMENTDOC,SCE_C_COMMENTLINEDOC,0,0)}, IDS_LEX_STR_63259, L"Comment Doc", L"fore:#808080", L"" }, { {SCE_C_COMMENTDOCKEYWORD}, IDS_LEX_STR_63371, L"Comment Doc Word", L"bold; fore:#808080", L"" }, { {SCE_C_COMMENTDOCKEYWORDERROR}, IDS_LEX_STR_63374, L"Comment Doc Error", L"italic; fore:#800000", L"" }, { {SCE_C_TASKMARKER}, IDS_LEX_STR_63373, L"Task Marker", L"bold; fore:#208080", L"" }, //{ {SCE_C_UUID}, L"UUID", L"", L"" }, //{ {SCE_C_GLOBALCLASS}, L"Global Class", L"", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>grepWinNP3/sktoolslib_mod/CmdLineParser.cpp<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012, 2017, 2020-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "CmdLineParser.h" #include <locale> #include <algorithm> const wchar_t CCmdLineParser::m_sDelims[] = L"-/"; const wchar_t CCmdLineParser::m_sQuotes[] = L"\""; const wchar_t CCmdLineParser::m_sValueSep[] = L" :"; // don't forget space!! static void SearchReplace(std::wstring& str, const std::wstring& toreplace, const std::wstring& replacewith) { std::wstring result; std::wstring::size_type pos = 0; for (;;) { std::wstring::size_type next = str.find(toreplace, pos); result.append(str, pos, next - pos); if (next != std::wstring::npos) { result.append(replacewith); pos = next + toreplace.size(); } else { break; // exit loop } } str = std::move(result); } CCmdLineParser::CCmdLineParser(LPCWSTR sCmdLine) { if (sCmdLine) { Parse(sCmdLine); } } CCmdLineParser::~CCmdLineParser() { m_valueMap.clear(); } BOOL CCmdLineParser::Parse(LPCWSTR sCmdLine) { const std::wstring sEmpty = L""; // use this as a value if no actual value is given in commandline if (!sCmdLine) return false; m_valueMap.clear(); m_sCmdLine = sCmdLine; LPCWSTR sCurrent = sCmdLine; for (;;) { //format is -Key:"arg" if (sCurrent[0] == '\0') break; // no more data, leave loop LPCWSTR sArg = wcspbrk(sCurrent, m_sDelims); if (!sArg) break; // no (more) delimiters found sArg = sArg + 1; if (sArg[0] == '\0') break; // ends with delim LPCWSTR sVal = wcspbrk(sArg, m_sValueSep); if (sVal == nullptr) { std::wstring key(sArg); std::transform(key.begin(), key.end(), key.begin(), ::towlower); m_valueMap.insert(CValsMap::value_type(key, sEmpty)); break; } else if (sVal[0] == L' ' || wcslen(sVal) == 1) { // cmdline ends with /Key: or a key with no value std::wstring key(sArg, static_cast<int>(sVal - sArg)); if (!key.empty()) { std::transform(key.begin(), key.end(), key.begin(), ::towlower); m_valueMap.insert(CValsMap::value_type(key, sEmpty)); } sCurrent = sVal + 1; } else { // key has value std::wstring key(sArg, static_cast<int>(sVal - sArg)); std::transform(key.begin(), key.end(), key.begin(), ::towlower); sVal = sVal + 1; LPCWSTR sQuote = wcspbrk(sVal, m_sQuotes), sEndQuote(nullptr); bool hasEscapedQuotes = false; if (sQuote == sVal) { // string with quotes (defined in m_sQuotes, e.g. '") sQuote = sVal + 1; sEndQuote = wcspbrk(sQuote, m_sQuotes); while (sEndQuote && sEndQuote[-1] == '\\') { hasEscapedQuotes = true; sEndQuote = sEndQuote + 1; sEndQuote = wcspbrk(sEndQuote, m_sQuotes); } } else { sQuote = sVal; sEndQuote = wcschr(sQuote, L' '); while (sEndQuote && sEndQuote[-1] == '\\') { hasEscapedQuotes = true; sEndQuote = sEndQuote + 1; sEndQuote = wcspbrk(sEndQuote, m_sQuotes); } } if (sEndQuote == nullptr) { // no end quotes or terminating space, take the rest of the string to its end std::wstring csVal(sQuote); if (hasEscapedQuotes) SearchReplace(csVal, L"\\\"", L"\""); if (!key.empty()) { m_valueMap.insert(CValsMap::value_type(key, csVal)); } break; } else { // end quote if (!key.empty()) { std::wstring csVal(sQuote, static_cast<int>(sEndQuote - sQuote)); if (hasEscapedQuotes) SearchReplace(csVal, L"\\\"", L"\""); m_valueMap.insert(CValsMap::value_type(key, csVal)); } sCurrent = sEndQuote + 1; continue; } } } return TRUE; } CCmdLineParser::CValsMap::const_iterator CCmdLineParser::findKey(LPCWSTR sKey) const { std::wstring s(sKey); std::transform(s.begin(), s.end(), s.begin(), ::towlower); return m_valueMap.find(s); } BOOL CCmdLineParser::HasKey(LPCWSTR sKey) const { CValsMap::const_iterator it = findKey(sKey); if (it == m_valueMap.end()) return false; return true; } BOOL CCmdLineParser::HasVal(LPCWSTR sKey) const { CValsMap::const_iterator it = findKey(sKey); if (it == m_valueMap.end()) return false; if (it->second.empty()) return false; return true; } LPCWSTR CCmdLineParser::GetVal(LPCWSTR sKey) const { CValsMap::const_iterator it = findKey(sKey); if (it == m_valueMap.end()) return nullptr; return it->second.c_str(); } LONG CCmdLineParser::GetLongVal(LPCWSTR sKey) const { CValsMap::const_iterator it = findKey(sKey); if (it == m_valueMap.end()) return 0; return _wtol(it->second.c_str()); } __int64 CCmdLineParser::GetLongLongVal(LPCWSTR sKey) const { CValsMap::const_iterator it = findKey(sKey); if (it == m_valueMap.end()) return 0; return _wtoi64(it->second.c_str()); } CCmdLineParser::ITERPOS CCmdLineParser::begin() const { return m_valueMap.begin(); } CCmdLineParser::ITERPOS CCmdLineParser::getNext(ITERPOS& pos, std::wstring& sKey, std::wstring& sValue) const { if (m_valueMap.end() == pos) { sKey.clear(); return pos; } else { sKey = pos->first; sValue = pos->second; ++pos; return pos; } } BOOL CCmdLineParser::isLast(const ITERPOS& pos) const { return (pos == m_valueMap.end()); } <|start_filename|>grepWinNP3/sktoolslib_mod/IconBitmapUtils.h<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2013, 2020 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #pragma once #include <map> #pragma warning(push) #pragma warning(disable : 4458) // declaration of 'xx' hides class member #include <GdiPlus.h> #pragma warning(pop) #include <Uxtheme.h> /** * \ingroup utils * provides helper functions for converting icons to bitmaps */ class IconBitmapUtils { public: IconBitmapUtils(void); ~IconBitmapUtils(void); HBITMAP IconToBitmap(HINSTANCE hInst, UINT uIcon); HBITMAP IconToBitmapPARGB32(HICON hIcon); HBITMAP IconToBitmapPARGB32(HINSTANCE hInst, UINT uIcon); HRESULT Create32BitHBITMAP(HDC hdc, const SIZE* psize, __deref_opt_out void** ppvBits, __out HBITMAP* phBmp); HRESULT ConvertBufferToPARGB32(HPAINTBUFFER hPaintBuffer, HDC hdc, HICON hicon, SIZE& sizIcon); bool HasAlpha(__in Gdiplus::ARGB* pargb, SIZE& sizImage, int cxRow); HRESULT ConvertToPARGB32(HDC hdc, __inout Gdiplus::ARGB* pargb, HBITMAP hbmp, SIZE& sizImage, int cxRow); private: std::map<UINT, HBITMAP> bitmaps; }; <|start_filename|>scintilla/win32/ScintillaDLL.cxx<|end_filename|> // Scintilla source code edit control /** @file ScintillaDLL.cxx ** DLL entry point for Scintilla. **/ // Copyright 1998-2018 by <NAME> <<EMAIL>> // The License.txt file describes the conditions under which this software may be distributed. #undef _WIN32_WINNT #define _WIN32_WINNT 0x0500 #undef WINVER #define WINVER 0x0500 #include <windows.h> #include "ScintillaTypes.h" #include "ScintillaWin.h" using namespace Scintilla; extern "C" __declspec(dllexport) sptr_t APIENTRY Scintilla_DirectFunction( Internal::ScintillaWin *sci, UINT iMessage, uptr_t wParam, sptr_t lParam) { return Internal::DirectFunction(sci, iMessage, wParam, lParam); } extern "C" int APIENTRY DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpvReserved) { //Platform::DebugPrintf("Scintilla::DllMain %d %d\n", hInstance, dwReason); if (dwReason == DLL_PROCESS_ATTACH) { if (!Internal::RegisterClasses(hInstance)) return FALSE; } else if (dwReason == DLL_PROCESS_DETACH) { if (lpvReserved == NULL) { Internal::ResourcesRelease(true); } } return TRUE; } <|start_filename|>src/uchardet/uchardet/src/LangModels/LangThaiModel.cpp<|end_filename|> /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "../nsSBCharSetProber.h" /********* Language model for: Thai *********/ /** * Generated by BuildLangModel.py * On: 2015-12-04 03:05:06.182099 **/ /* Character Mapping Table: * ILL: illegal character. * CTR: control character specific to the charset. * RET: carriage/return. * SYM: symbol (punctuation) that does not belong to word. * NUM: 0 - 9. * * Other characters are ordered by probabilities * (0 is the most common character in the language). * * Orders are generic to a language. So the codepoint with order X in * CHARSET1 maps to the same character as the codepoint with the same * order X in CHARSET2 for the same language. * As such, it is possible to get missing order. For instance the * ligature of 'o' and 'e' exists in ISO-8859-15 but not in ISO-8859-1 * even though they are both used for French. Same for the euro sign. */ static const unsigned char Tis_620_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 66, 70, 67, 80, 78, 87, 85, 73, 79, 93, 88, 84, 68, 77, 81, /* 4X */ 75,101, 74, 61, 71, 86, 96, 90,103,100, 99,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 35, 64, 48, 52, 32, 60, 65, 54, 36, 97, 76, 46, 56, 41, 40, /* 6X */ 59,104, 43, 45, 44, 55, 72, 82, 94, 57, 92,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ ILL, 3, 23,105, 15,106, 89, 5, 21, 63, 26, 31,102, 42, 69, 58, /* AX */ 49, 91, 83, 34, 9, 17, 30, 12, 39, 1, 16, 19, 33, 62, 22, 47, /* BX */ 38, 7, 10, 2, 50, 11,107, 8, 28, 37, 13, 18, 98, 4, 53, 95, /* CX */ 14,SYM, 0, 29,SYM,SYM,SYM,SYM,SYM,SYM,SYM,ILL,ILL,ILL,ILL,SYM, /* DX */ 6, 20, 27, 24, 25,108, 51,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,109, /* EX */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,110,111,ILL,ILL,ILL,ILL, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Iso_8859_11_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 66, 70, 67, 80, 78, 87, 85, 73, 79, 93, 88, 84, 68, 77, 81, /* 4X */ 75,101, 74, 61, 71, 86, 96, 90,103,100, 99,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 35, 64, 48, 52, 32, 60, 65, 54, 36, 97, 76, 46, 56, 41, 40, /* 6X */ 59,104, 43, 45, 44, 55, 72, 82, 94, 57, 92,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM, 3, 23,112, 15,113, 89, 5, 21, 63, 26, 31,102, 42, 69, 58, /* AX */ 49, 91, 83, 34, 9, 17, 30, 12, 39, 1, 16, 19, 33, 62, 22, 47, /* BX */ 38, 7, 10, 2, 50, 11,114, 8, 28, 37, 13, 18, 98, 4, 53, 95, /* CX */ 14,SYM, 0, 29,SYM,SYM,SYM,SYM,SYM,SYM,SYM,ILL,ILL,ILL,ILL,SYM, /* DX */ 6, 20, 27, 24, 25,115, 51,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,116, /* EX */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,117,118,ILL,ILL,ILL,ILL, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ /* Model Table: * Total sequences: 2324 * First 512 sequences: 0.8815720594354438 * Next 512 sequences (512-1024): 0.0920860122682917 * Rest: 0.026341928296264486 * Negative sequences: TODO */ static const PRUint8 ThaiLangModel[] = { 0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,2,3, 0,2,3,0,0,3,2,3,0,0,2,0,0,0,0,2,0,1,1,1,0,2,0,0,0,0,1,0,0,0,1,1, 3,3,3,3,3,2,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3, 0,3,0,0,0,1,3,3,0,0,1,0,0,0,0,2,0,2,1,2,0,1,0,0,0,0,0,0,0,0,2,1, 3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,2,3,3,3,3,3,3,2,2,2,3,1,3,2, 0,2,3,0,0,2,2,1,0,0,0,0,0,0,0,1,0,1,1,0,0,1,0,0,0,0,0,0,0,0,2,1, 3,3,3,3,3,2,3,3,3,3,2,3,3,3,2,3,2,3,3,3,3,3,3,3,3,3,2,3,2,3,2,3, 0,2,1,0,0,3,2,1,0,0,0,0,0,0,0,1,0,3,3,1,0,1,0,0,0,0,3,0,0,0,1,1, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,2,2,2,2,3,3,2,2,1,2,2,2, 0,2,0,0,0,0,2,2,0,0,1,0,0,0,0,2,0,0,1,1,0,1,0,0,0,0,0,0,0,0,1,1, 3,3,3,3,3,2,3,3,3,3,3,3,3,3,1,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,2, 0,3,0,0,0,1,2,2,0,0,1,0,0,0,0,2,0,1,1,2,0,2,0,0,0,0,0,0,0,0,2,1, 0,3,3,3,3,2,0,3,3,3,3,3,3,3,0,3,3,3,3,3,0,3,3,3,0,0,3,0,3,0,1,3, 0,2,0,0,0,2,2,2,0,0,0,0,0,0,0,3,0,0,0,0,0,2,0,0,0,0,0,0,0,0,1,3, 3,3,3,3,3,2,3,3,3,3,2,3,3,3,2,3,3,3,3,3,3,2,3,3,3,3,2,2,1,0,2,1, 0,2,2,0,1,2,2,1,0,0,1,0,0,0,0,1,0,1,1,1,0,1,0,0,0,0,0,0,0,0,1,1, 3,3,3,3,3,3,3,3,2,3,3,3,3,2,2,2,3,2,2,2,3,3,3,2,2,2,2,2,2,0,2,2, 0,1,2,0,0,0,1,0,0,0,1,0,0,0,0,1,0,0,3,1,0,1,0,0,0,0,0,0,0,0,1,1, 3,3,3,3,3,3,3,2,3,2,3,3,3,3,0,3,2,3,2,2,3,2,2,3,3,3,2,2,1,3,2,1, 0,1,0,0,0,0,2,1,0,0,0,0,0,0,0,1,0,1,1,1,0,1,0,0,0,0,0,0,0,0,1,1, 3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,2,2,1,2,2, 0,2,0,0,0,0,3,1,0,0,1,0,0,0,0,1,0,1,1,1,0,1,0,0,0,0,0,0,0,0,1,1, 3,3,2,3,3,3,3,3,3,3,2,3,3,3,3,2,2,3,2,2,2,2,1,3,2,2,2,2,1,3,1,2, 0,1,0,0,0,0,1,1,0,0,1,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0,0,1,1, 3,3,3,1,2,1,2,1,2,3,3,1,1,2,2,3,2,1,2,1,1,1,2,1,1,1,1,1,3,3,0,1, 0,0,0,0,0,1,1,3,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,2,3,3,3,3,3,3,2,3,2,2,2,2,3,3,3,2,2,1,1,1,2,2,1,2,1,3,3,2, 0,1,0,0,0,0,2,2,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 0,3,3,3,3,1,3,3,3,3,3,2,3,3,0,3,3,3,3,3,3,3,3,2,3,3,3,3,2,0,2,2, 0,2,1,0,0,0,2,2,0,0,1,0,0,0,0,1,0,1,1,0,0,2,0,0,0,0,1,0,0,0,1,1, 3,3,3,1,3,2,2,3,3,2,2,3,1,1,2,2,1,2,1,2,1,3,1,1,1,1,1,2,0,3,0,1, 0,0,2,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,1,0, 3,3,3,3,3,1,3,2,3,3,2,3,3,3,1,3,3,3,3,3,3,2,2,2,3,3,2,2,2,2,2,2, 0,2,0,0,0,0,2,1,0,0,0,0,0,0,0,1,0,1,0,1,0,1,0,0,0,0,1,0,0,0,1,1, 3,3,3,3,3,1,2,1,2,1,3,2,2,2,3,1,2,2,1,1,2,1,1,2,2,1,1,2,1,3,3,1, 0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,3,3,1,2,1,0,3,3,1,2,3,1,1,1,0,0,3,1,1,0,0,1,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,2,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,2,3,3,3,1,2,1,2,2,2,3,2,2,2,1,1,2,1,2,2,2,1,1,2,2,1,1,1,0,2,1, 0,1,0,0,0,0,1,1,0,0,1,0,0,0,0,1,0,1,1,0,0,0,0,0,0,0,3,0,0,0,0,0, 0,3,3,3,3,1,0,3,2,2,2,3,3,3,0,3,3,3,3,3,0,1,2,2,0,0,1,0,0,0,3,3, 0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0, 3,3,3,3,3,1,3,2,2,2,1,1,2,2,3,2,1,2,1,1,2,3,3,2,2,2,1,2,0,3,1,2, 0,1,1,0,0,0,1,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 3,1,3,2,3,1,2,2,3,2,3,3,3,2,0,1,3,1,1,1,2,2,1,2,1,1,1,1,1,1,1,0, 0,1,1,0,0,0,1,1,0,0,1,0,0,0,0,1,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,1,1,3,0,1,1,2,1,2,1,2,1,0,1,1,2,1,1,1,1,1,1,1,1,1,1,0,1,1,1, 0,0,3,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,0,3,0,0,0,0,0,2,1,0,0,2,0,1,1,3,3,1,0,3,0,0,0,0,3,0,0,0,0,0, 0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,1,3,2,2,0,0,3,3,3,0,2,3,1,0,2,2,2,2,3,0,1,1,3,0,0,1,0,0,0,1,2, 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0, 3,3,1,2,3,1,2,2,2,1,2,2,2,2,1,1,2,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1, 0,0,0,0,0,1,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0, 0,3,3,2,3,0,0,2,1,3,2,3,3,1,0,3,2,3,1,2,0,2,2,1,0,0,1,0,1,0,1,2, 0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,2,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1, 3,3,2,2,2,0,2,2,2,1,2,1,2,2,0,1,1,2,1,1,2,2,1,2,2,2,1,1,1,0,1,1, 0,0,0,0,0,2,1,0,0,0,1,0,0,0,0,1,0,0,0,0,0,2,0,0,0,0,0,0,0,0,1,0, 0,3,3,3,2,2,3,2,2,2,1,3,2,2,0,3,2,2,3,1,3,1,2,2,3,2,1,2,1,0,2,1, 0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,0,0,0,0,0,1,0, 3,2,1,1,2,1,2,2,2,1,1,2,2,1,1,1,2,1,1,1,2,1,1,1,2,1,1,1,1,0,1,0, 0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,3,1,1,3,2,2,1,1,1,1,2,1,0,1,1,1,2,0,1,1,0,0,0,0,1,1,1,0,0,0,1, 0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0, 2,0,0,2,2,0,0,0,2,3,0,3,2,3,3,0,2,0,0,0,2,0,1,2,2,1,0,2,2,1,0,0, 1,2,0,1,0,1,1,1,1,1,2,3,0,1,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,1,2,2,1,1,1,1,1,1,1,1,2,2,3,1,1,1,2,1,1,1,1,1,1,1,1,1,1,0,1,1, 0,0,0,0,0,0,2,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,1,2,0,0,0,1,3,0,3,3,2,3,0,2,0,0,0,2,0,1,1,2,2,0,2,1,1,0,0, 0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,0,3,1,0,0,0,3,3,0,2,3,3,2,0,3,0,0,0,2,0,1,1,2,0,0,1,1,0,0,0, 3,1,1,2,1,0,1,1,1,1,2,0,2,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,0,1,1, 0,1,3,0,0,1,2,0,0,0,0,0,0,0,0,1,0,2,0,0,0,0,0,0,0,0,1,0,0,0,1,0, 3,0,2,1,1,0,0,1,0,0,1,0,2,1,0,1,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,1,3,1,2,1,1,2,1,1,1,0,1,1,0,1,1,1,1,1,1,0,0,1,1,1,0,1,1,1,0,0, 0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,0,1,1,0,0,0,1,3,0,3,2,2,2,0,2,0,0,0,2,0,1,2,2,1,0,2,3,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0, 3,0,0,2,2,0,0,0,2,2,0,1,3,2,1,0,2,0,0,0,3,0,1,1,1,1,0,0,1,0,0,0, 3,1,1,1,1,0,2,1,1,0,0,1,2,1,0,1,1,1,2,1,1,1,1,1,2,1,2,1,1,0,1,1, 0,0,0,0,0,0,1,0,0,0,3,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,0,3,3,0,0,0,2,2,0,2,2,2,1,0,2,0,0,0,2,0,1,1,1,2,0,1,1,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,0,2,3,0,0,0,2,1,0,2,2,2,1,0,1,0,0,0,1,0,3,2,1,2,0,1,1,0,0,0, 0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,0,1,2,0,0,0,2,1,0,1,3,2,1,0,2,0,0,0,1,0,2,1,1,1,0,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,0,2,2,0,0,0,2,2,0,0,1,1,2,0,1,0,0,0,1,0,1,1,1,1,0,1,1,0,0,0, 1,1,3,2,2,0,2,1,1,1,1,2,1,1,0,1,1,2,1,0,1,1,1,1,1,1,1,1,0,0,0,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,0,2,2,0,0,0,2,0,0,1,2,1,1,0,1,0,0,0,0,0,2,1,0,1,0,0,0,0,0,0, 3,1,1,1,2,0,1,2,1,0,0,0,1,2,0,1,2,1,1,1,1,0,0,0,1,1,0,1,1,0,0,1, 0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0, 0,0,0,3,0,0,0,0,0,2,0,0,1,0,0,1,0,2,2,0,0,1,0,0,0,0,0,0,2,0,1,0, 0,0,0,0,0,3,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,1,1,0,1,1,1,0,0,0,1,0,0,1,0,1,0,0,1,0,1,1,1,1,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,0,2,2,0,0,0,2,0,0,1,0,1,1,0,1,0,0,0,1,0,1,1,1,2,0,0,2,0,0,0, 2,1,1,0,2,0,2,1,1,1,1,2,1,1,1,0,0,1,0,1,0,0,0,0,0,0,1,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,0,2,2,0,0,0,2,1,0,1,1,1,1,0,1,0,0,0,0,0,0,1,0,1,0,0,1,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,1,1,0,0,0,0,2,0,2,2,2,2,0,2,0,0,0,2,0,1,0,1,1,0,1,1,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,0,2,2,0,0,0,2,1,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,2,0,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,1,1,0,0,0,1,1,0,0,1,2,1,0,1,0,0,0,1,0,0,0,0,1,0,1,0,0,0,0, 1,0,1,2,1,0,1,1,1,1,0,1,1,1,0,1,1,1,1,0,1,1,1,1,1,1,1,0,0,0,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,0,2,1,0,0,0,2,0,0,2,1,1,2,0,0,0,0,0,0,0,2,1,1,2,0,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,0,1,2,0,0,0,2,1,0,2,1,0,0,0,0,0,0,0,0,0,0,2,0,1,0,0,2,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,1,1,0,0,0,1,0,0,0,2,0,0,0,2,0,0,0,0,0,1,1,1,1,0,1,1,1,0,0, 0,1,2,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,1,1,0,0,0,0,1,1,1,1,2,0,0,1,0,1,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; const SequenceModel Tis_620ThaiModel = { Tis_620_CharToOrderMap, ThaiLangModel, 64, (float)0.8815720594354438, PR_FALSE, "TIS-620" }; const SequenceModel Iso_8859_11ThaiModel = { Iso_8859_11_CharToOrderMap, ThaiLangModel, 64, (float)0.8815720594354438, PR_FALSE, "ISO-8859-11" }; <|start_filename|>grepWinNP3/sktoolslib_mod/Windows10Colors.cpp<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2018, 2020-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "Windows10Colors.h" #pragma comment(lib, "dwmapi.lib") #pragma comment(lib, "ntdll.lib") using namespace Microsoft::WRL; namespace WindowsUI = ABI::Windows::UI; /// Wrapper class for WinRT string reference class HStringRef { HSTRING m_hStr; HSTRING_HEADER m_strHeader; public: HStringRef() : m_hStr(nullptr) , m_strHeader() { } // String ref doesn't need dtor template <size_t N> HRESULT Set(const wchar_t (&str)[N]) { return Win10Colors::WindowsCreateStringReference(str, N - 1, &m_strHeader, &m_hStr); } operator HSTRING() const { return m_hStr; } }; /// Call RoActivateInstance and query an interface template <typename If> static HRESULT ActivateInstance(HSTRING classId, ComPtr<If>& instance) { ComPtr<IInspectable> inspectable; auto hr = Win10Colors::RoActivateInstance(classId, &inspectable); if (FAILED(hr)) return hr; return inspectable.As(&instance); } Win10Colors Win10Colors::instance; Win10Colors::Win10Colors() { if (!m_modulesLoaded) { m_modulesLoaded = true; winrt = LoadLibraryW(L"api-ms-win-core-winrt-l1-1-0.dll"); if (winrt) { pRoActivateInstance = reinterpret_cast<PfnRoActivateInstance>( GetProcAddress(winrt, "RoActivateInstance")); } m_winrtString = LoadLibraryW(L"api-ms-win-core-winrt-string-l1-1-0.dll"); if (m_winrtString) { pWindowsCreateStringReference = reinterpret_cast<PfnWindowsCreateStringReference>( GetProcAddress(m_winrtString, "WindowsCreateStringReference")); } } } Win10Colors::~Win10Colors() { if (winrt) FreeLibrary(winrt); if (m_winrtString) FreeLibrary(m_winrtString); } HRESULT Win10Colors::GetAccentColor(AccentColor& color) { HStringRef classId; auto hr = classId.Set(L"Windows.UI.ViewManagement.UISettings"); if (FAILED(hr)) return hr; Microsoft::WRL::ComPtr<WindowsUI::ViewManagement::IUISettings> settings; hr = ActivateInstance(classId, settings); if (FAILED(hr)) return hr; ComPtr<WindowsUI::ViewManagement::IUISettings3> settings3; hr = settings.As(&settings3); if (!settings3) return E_FAIL; WindowsUI::Color uiColor; hr = settings3->GetColorValue(WindowsUI::ViewManagement::UIColorType_Foreground, &uiColor); if (FAILED(hr)) return hr; color.foreground = ToRGBA(uiColor); hr = settings3->GetColorValue(WindowsUI::ViewManagement::UIColorType_Background, &uiColor); if (FAILED(hr)) return hr; color.background = ToRGBA(uiColor); hr = settings3->GetColorValue(WindowsUI::ViewManagement::UIColorType_AccentDark3, &uiColor); if (FAILED(hr)) return hr; color.darkest = ToRGBA(uiColor); hr = settings3->GetColorValue(WindowsUI::ViewManagement::UIColorType_AccentDark2, &uiColor); if (FAILED(hr)) return hr; color.darker = ToRGBA(uiColor); hr = settings3->GetColorValue(WindowsUI::ViewManagement::UIColorType_AccentDark1, &uiColor); if (FAILED(hr)) return hr; color.dark = ToRGBA(uiColor); hr = settings3->GetColorValue(WindowsUI::ViewManagement::UIColorType_Accent, &uiColor); if (FAILED(hr)) return hr; color.accent = ToRGBA(uiColor); hr = settings3->GetColorValue(WindowsUI::ViewManagement::UIColorType_AccentLight1, &uiColor); if (FAILED(hr)) return hr; color.light = ToRGBA(uiColor); hr = settings3->GetColorValue(WindowsUI::ViewManagement::UIColorType_AccentLight2, &uiColor); if (FAILED(hr)) return hr; color.lighter = ToRGBA(uiColor); hr = settings3->GetColorValue(WindowsUI::ViewManagement::UIColorType_AccentLight3, &uiColor); if (FAILED(hr)) return hr; color.lightest = ToRGBA(uiColor); return S_OK; } <|start_filename|>lexilla/lexlib/PropSetSimple.h<|end_filename|> // Scintilla source code edit control /** @file PropSetSimple.h ** A basic string to string map. **/ // Copyright 1998-2009 by <NAME> <<EMAIL>> // The License.txt file describes the conditions under which this software may be distributed. #ifndef PROPSETSIMPLE_H #define PROPSETSIMPLE_H namespace Lexilla { class PropSetSimple { void *impl; public: PropSetSimple(); // Deleted so PropSetSimple objects can not be copied. PropSetSimple(const PropSetSimple&) = delete; PropSetSimple(PropSetSimple&&) = delete; PropSetSimple &operator=(const PropSetSimple&) = delete; PropSetSimple &operator=(PropSetSimple&&) = delete; virtual ~PropSetSimple(); bool Set(std::string_view key, std::string_view val); const char *Get(std::string_view key) const; int GetInt(std::string_view key, int defaultValue=0) const; }; } #endif <|start_filename|>src/StyleLexers/styleLexVB.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_VB = { NP3_LEXER_VB_KEYWORD_LIST, NULL, }; EDITLEXER lexVB = { SCLEX_VB, "vb", IDS_LEX_VIS_BAS, L"Visual Basic", L"vb; bas; frm; cls; ctl; pag; dsr; dob", L"", &KeyWords_VB, { { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_B_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {SCE_B_COMMENT}, IDS_LEX_STR_63127, L"Comment", L"fore:#808080", L"" }, { {SCE_B_KEYWORD}, IDS_LEX_STR_63128, L"Keyword", L"bold; fore:#B000B0", L"" }, { {SCE_B_IDENTIFIER}, IDS_LEX_STR_63129, L"Identifier", L"", L"" }, { {MULTI_STYLE(SCE_B_STRING,SCE_B_STRINGEOL,0,0)}, IDS_LEX_STR_63131, L"String", L"fore:#008000", L"" }, { {MULTI_STYLE(SCE_B_NUMBER,SCE_B_DATE,0,0)}, IDS_LEX_STR_63130, L"Number", L"fore:#FF0000", L"" }, { {SCE_B_OPERATOR}, IDS_LEX_STR_63132, L"Operator", L"", L"" }, { {SCE_B_PREPROCESSOR}, IDS_LEX_STR_63133, L"Preprocessor", L"fore:#FF9C00", L"" }, //{ {SCE_B_CONSTANT}, L"Constant", L"", L"" }, //{ {SCE_B_KEYWORD2}, L"Keyword 2", L"", L"" }, //{ {SCE_B_KEYWORD3}, L"Keyword 3", L"", L"" }, //{ {SCE_B_KEYWORD4}, L"Keyword 4", L"", L"" }, //{ {SCE_B_ASM}, L"Inline Asm", L"fore:#FF8000", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>src/StyleLexers/styleLexMATLAB.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_MATLAB = { "break case catch continue else elseif end for function global if otherwise persistent return " "switch try while", NULL, }; EDITLEXER lexMATLAB = { SCLEX_MATLAB, "matlab", IDS_LEX_MATLAB, L"MATLAB", L"matlab; m; sce; sci", L"", &KeyWords_MATLAB, { { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_MATLAB_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {SCE_MATLAB_COMMENT}, IDS_LEX_STR_63127, L"Comment", L"fore:#008000", L"" }, { {SCE_MATLAB_COMMAND}, IDS_LEX_STR_63236, L"Command", L"bold", L"" }, { {SCE_MATLAB_NUMBER}, IDS_LEX_STR_63130, L"Number", L"fore:#FF8000", L"" }, { {SCE_MATLAB_KEYWORD}, IDS_LEX_STR_63128, L"Keyword", L"bold; fore:#00007F", L"" }, { {MULTI_STYLE(SCE_MATLAB_STRING,SCE_MATLAB_DOUBLEQUOTESTRING,0,0)}, IDS_LEX_STR_63131, L"String", L"fore:#7F007F", L"" }, { {SCE_MATLAB_OPERATOR}, IDS_LEX_STR_63132, L"Operator", L"", L"" }, { {SCE_MATLAB_IDENTIFIER}, IDS_LEX_STR_63129, L"Identifier", L"", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>lexilla/lexers/LexMake.cxx<|end_filename|> // Scintilla source code edit control /** @file LexMake.cxx ** Lexer for make files. **/ // Copyright 1998-2001 by <NAME> <<EMAIL>> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdarg.h> #include <assert.h> #include <ctype.h> #include <string> #include <string_view> #include "ILexer.h" #include "Scintilla.h" #include "SciLexer.h" #include "WordList.h" #include "LexAccessor.h" #include "Accessor.h" #include "StyleContext.h" #include "CharacterSet.h" #include "LexerModule.h" using namespace Lexilla; static inline bool AtEOL(Accessor &styler, Sci_PositionU i) { return (styler[i] == '\n') || ((styler[i] == '\r') && (styler.SafeGetCharAt(i + 1) != '\n')); } static void ColouriseMakeLine( char *lineBuffer, Sci_PositionU lengthLine, Sci_PositionU startLine, Sci_PositionU endPos, Accessor &styler) { Sci_PositionU i = 0; Sci_Position lastNonSpace = -1; unsigned int state = SCE_MAKE_DEFAULT; bool bSpecial = false; // check for a tab character in column 0 indicating a command bool bCommand = false; if ((lengthLine > 0) && (lineBuffer[0] == '\t')) bCommand = true; // Skip initial spaces while ((i < lengthLine) && isspacechar(lineBuffer[i])) { i++; } if (i < lengthLine) { if (lineBuffer[i] == '#') { // Comment styler.ColourTo(endPos, SCE_MAKE_COMMENT); return; } if (lineBuffer[i] == '!') { // Special directive styler.ColourTo(endPos, SCE_MAKE_PREPROCESSOR); return; } } int varCount = 0; while (i < lengthLine) { if (((i + 1) < lengthLine) && (lineBuffer[i] == '$' && lineBuffer[i + 1] == '(')) { styler.ColourTo(startLine + i - 1, state); state = SCE_MAKE_IDENTIFIER; varCount++; } else if (state == SCE_MAKE_IDENTIFIER && lineBuffer[i] == ')') { if (--varCount == 0) { styler.ColourTo(startLine + i, state); state = SCE_MAKE_DEFAULT; } } // skip identifier and target styling if this is a command line if (!bSpecial && !bCommand) { if (lineBuffer[i] == ':') { if (((i + 1) < lengthLine) && (lineBuffer[i + 1] == '=')) { // it's a ':=', so style as an identifier if (lastNonSpace >= 0) styler.ColourTo(startLine + lastNonSpace, SCE_MAKE_IDENTIFIER); styler.ColourTo(startLine + i - 1, SCE_MAKE_DEFAULT); styler.ColourTo(startLine + i + 1, SCE_MAKE_OPERATOR); } else { // We should check that no colouring was made since the beginning of the line, // to avoid colouring stuff like /OUT:file if (lastNonSpace >= 0) styler.ColourTo(startLine + lastNonSpace, SCE_MAKE_TARGET); styler.ColourTo(startLine + i - 1, SCE_MAKE_DEFAULT); styler.ColourTo(startLine + i, SCE_MAKE_OPERATOR); } bSpecial = true; // Only react to the first ':' of the line state = SCE_MAKE_DEFAULT; } else if (lineBuffer[i] == '=') { if (lastNonSpace >= 0) styler.ColourTo(startLine + lastNonSpace, SCE_MAKE_IDENTIFIER); styler.ColourTo(startLine + i - 1, SCE_MAKE_DEFAULT); styler.ColourTo(startLine + i, SCE_MAKE_OPERATOR); bSpecial = true; // Only react to the first '=' of the line state = SCE_MAKE_DEFAULT; } } if (!isspacechar(lineBuffer[i])) { lastNonSpace = i; } i++; } if (state == SCE_MAKE_IDENTIFIER) { styler.ColourTo(endPos, SCE_MAKE_IDEOL); // Error, variable reference not ended } else { styler.ColourTo(endPos, SCE_MAKE_DEFAULT); } } static void ColouriseMakeDoc(Sci_PositionU startPos, Sci_Position length, int, WordList *[], Accessor &styler) { char lineBuffer[1024]; styler.StartAt(startPos); styler.StartSegment(startPos); Sci_PositionU linePos = 0; Sci_PositionU startLine = startPos; for (Sci_PositionU i = startPos; i < startPos + length; i++) { lineBuffer[linePos++] = styler[i]; if (AtEOL(styler, i) || (linePos >= sizeof(lineBuffer) - 1)) { // End of line (or of line buffer) met, colourise it lineBuffer[linePos] = '\0'; ColouriseMakeLine(lineBuffer, linePos, startLine, i, styler); linePos = 0; startLine = i + 1; } } if (linePos > 0) { // Last line does not have ending characters ColouriseMakeLine(lineBuffer, linePos, startLine, startPos + length - 1, styler); } } static const char *const emptyWordListDesc[] = { 0 }; LexerModule lmMake(SCLEX_MAKEFILE, ColouriseMakeDoc, "makefile", 0, emptyWordListDesc); <|start_filename|>grepWinNP3/src/stdafx.h<|end_filename|> // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #include <SDKDDKVer.h> #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include <windows.h> #include <windowsx.h> // C RunTime Header Files #include <stdlib.h> #include <malloc.h> #include <memory.h> #include <commctrl.h> #include <shlwapi.h> #include "Language.h" #include "SimpleIni.h" extern HINSTANCE g_hInst; extern bool bPortable; extern CSimpleIni g_iniFile; extern std::wstring g_iniPath; #define DEBUGOUTPUTREGPATH L"Software\\grepWinNP3\\DebugOutput" #pragma comment(linker, "\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='<KEY>' language='*'\"") <|start_filename|>scintilla/oniguruma/src/ascii.c<|end_filename|> /********************************************************************** ascii.c - Oniguruma (regular expression library) **********************************************************************/ /*- * Copyright (c) 2002-2019 K.Kosako * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. */ #include "regint.h" /* for USE_CALLOUT */ static int init(void) { #ifdef USE_CALLOUT int id; OnigEncoding enc; char* name; unsigned int args[4]; OnigValue opts[4]; enc = ONIG_ENCODING_ASCII; name = "FAIL"; BC0_P(name, fail); name = "MISMATCH"; BC0_P(name, mismatch); name = "MAX"; args[0] = ONIG_TYPE_TAG | ONIG_TYPE_LONG; args[1] = ONIG_TYPE_CHAR; opts[0].c = 'X'; BC_B_O(name, max, 2, args, 1, opts); name = "ERROR"; args[0] = ONIG_TYPE_LONG; opts[0].l = ONIG_ABORT; BC_P_O(name, error, 1, args, 1, opts); name = "COUNT"; args[0] = ONIG_TYPE_CHAR; opts[0].c = '>'; BC_B_O(name, count, 1, args, 1, opts); name = "TOTAL_COUNT"; args[0] = ONIG_TYPE_CHAR; opts[0].c = '>'; BC_B_O(name, total_count, 1, args, 1, opts); name = "CMP"; args[0] = ONIG_TYPE_TAG | ONIG_TYPE_LONG; args[1] = ONIG_TYPE_STRING; args[2] = ONIG_TYPE_TAG | ONIG_TYPE_LONG; BC_P(name, cmp, 3, args); #endif /* USE_CALLOUT */ return ONIG_NORMAL; } #if 0 static int is_initialized(void) { /* Don't use this function */ /* can't answer, because builtin callout entries removed in onig_end() */ return 0; } #endif static int ascii_is_code_ctype(OnigCodePoint code, unsigned int ctype) { if (code < 128) return ONIGENC_IS_ASCII_CODE_CTYPE(code, ctype); else return FALSE; } OnigEncodingType OnigEncodingASCII = { onigenc_single_byte_mbc_enc_len, "US-ASCII", /* name */ 1, /* max enc length */ 1, /* min enc length */ onigenc_is_mbc_newline_0x0a, onigenc_single_byte_mbc_to_code, onigenc_single_byte_code_to_mbclen, onigenc_single_byte_code_to_mbc, onigenc_ascii_mbc_case_fold, onigenc_ascii_apply_all_case_fold, onigenc_ascii_get_case_fold_codes_by_str, onigenc_minimum_property_name_to_ctype, ascii_is_code_ctype, onigenc_not_support_get_ctype_code_range, onigenc_single_byte_left_adjust_char_head, onigenc_always_true_is_allowed_reverse_match, init, 0, /* is_initialized */ onigenc_always_true_is_valid_mbc_string, ENC_FLAG_ASCII_COMPATIBLE|ENC_FLAG_SKIP_OFFSET_1, 0, 0 }; OnigEncodingType OnigEncodingASCII_CR = { onigenc_single_byte_mbc_enc_len, "US-ASCII", /* name */ 1, /* max enc length */ 1, /* min enc length */ onigenc_is_mbc_newline_0x0d, onigenc_single_byte_mbc_to_code, onigenc_single_byte_code_to_mbclen, onigenc_single_byte_code_to_mbc, onigenc_ascii_mbc_case_fold, onigenc_ascii_apply_all_case_fold, onigenc_ascii_get_case_fold_codes_by_str, onigenc_minimum_property_name_to_ctype, ascii_is_code_ctype, onigenc_not_support_get_ctype_code_range, onigenc_single_byte_left_adjust_char_head, onigenc_always_true_is_allowed_reverse_match, init, 0, /* is_initialized */ onigenc_always_true_is_valid_mbc_string, ENC_FLAG_ASCII_COMPATIBLE|ENC_FLAG_SKIP_OFFSET_1, 0, 0 }; OnigEncodingType OnigEncodingASCII_CRLF = { onigenc_single_byte_mbc_enc_len, "US-ASCII", /* name */ 1, /* max enc length */ 1, /* min enc length */ onigenc_is_mbc_newline_0x0d_0x0a, onigenc_single_byte_mbc_to_code, onigenc_single_byte_code_to_mbclen, onigenc_single_byte_code_to_mbc, onigenc_ascii_mbc_case_fold, onigenc_ascii_apply_all_case_fold, onigenc_ascii_get_case_fold_codes_by_str, onigenc_minimum_property_name_to_ctype, ascii_is_code_ctype, onigenc_not_support_get_ctype_code_range, onigenc_single_byte_left_adjust_char_head, onigenc_always_true_is_allowed_reverse_match, init, 0, /* is_initialized */ onigenc_always_true_is_valid_mbc_string, ENC_FLAG_ASCII_COMPATIBLE|ENC_FLAG_SKIP_OFFSET_1, 0, 0 }; <|start_filename|>src/StyleLexers/styleLexPAS.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_PAS = { "absolute abstract alias and array as asm assembler begin break case cdecl class const constructor continue " "cppdecl default destructor dispose div do downto else end end. except exit export exports external false " "far far16 file finalization finally for forward function goto if implementation in index inherited " "initialization inline interface is label library local message mod name near new nil nostackframe not " "object of oldfpccall on operator or out overload override packed pascal private procedure program " "property protected public published raise read record register reintroduce repeat resourcestring safecall " "self set shl shr softfloat stdcall stored string then threadvar to true try type unit until uses var " "virtual while with write xor", NULL, }; EDITLEXER lexPAS = { SCLEX_PASCAL, "pascal", IDS_LEX_PASCAL_SRC, L"Pascal Source Code", L"pas; dpr; dpk; dfm; pp; lfm; lpr; fpd", L"", &KeyWords_PAS, { { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_PAS_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {MULTI_STYLE(SCE_PAS_COMMENT,SCE_PAS_COMMENT2,SCE_PAS_COMMENTLINE,0)}, IDS_LEX_STR_63127, L"Comment", L"fore:#646464", L"" }, { {SCE_PAS_WORD}, IDS_LEX_STR_63128, L"Keyword", L"bold; fore:#800080", L"" }, { {SCE_PAS_IDENTIFIER}, IDS_LEX_STR_63129, L"Identifier", L"", L"" }, { {MULTI_STYLE(SCE_PAS_STRING,SCE_PAS_CHARACTER,SCE_PAS_STRINGEOL,0)}, IDS_LEX_STR_63131, L"String", L"fore:#008000", L"" }, { {MULTI_STYLE(SCE_PAS_NUMBER,SCE_PAS_HEXNUMBER,0,0)}, IDS_LEX_STR_63130, L"Number", L"fore:#FF0000", L"" }, { {SCE_PAS_OPERATOR}, IDS_LEX_STR_63132, L"Operator", L"bold", L"" }, { {SCE_PAS_ASM}, IDS_LEX_STR_63205, L"Inline Asm", L"fore:#0000FF", L"" }, { {MULTI_STYLE(SCE_PAS_PREPROCESSOR,SCE_PAS_PREPROCESSOR2,0,0)}, IDS_LEX_STR_63133, L"Preprocessor", L"fore:#FF00FF", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>Version_alpha.cmd<|end_filename|> :: Batch file for ALPHA and XPERIMENTAL version @echo off setlocal set _VERPATCH_=alpha echo."_%_VERPATCH_%">.\np3portableapp\_buildname.txt Version -VerPatch "%_VERPATCH_%" endlocal <|start_filename|>test/test_files/encoding/UTF-8/dl - (utf-8) Use as fallback on detection failure (issue #1815).js<|end_filename|> javascript:!function(){ var userName = location.href.split("/")[4]; var fileName = "Twilog-" + userName + ".html"; var fileNameForAll = "Twi " + userName + ".html"; $(document).ready(function(){ $("#loading").before('<a id="save" href="javascript:void(0);" title="adding">📃</a><a id="saveall" href="javascript:void(0);" style="margin-left:20px;">All(First)</a><input id="nest" style="margin-left:20px;" type="checkbox"><input type="text" id="newest" size="10">ネスト'); $('#save').css("size", "50px").click(function() { idSave(fileName) }); $('#saveall').css("size", "50px").click(function() { idSaveAll(fileNameForAll, userName) }); }); function idSaveAll(fName, id) { var text = conv( $("#results").html(), true ); if (text =="") return; var nest = "", LocalSaveFolder = "save", SaveFolderName = LocalSaveFolder; if ($('#nest').is(':checked')) var nest = "../../../", SaveFolderName = "FX" + "/" + LocalSaveFolder; var header = ['<!DOCTYPE html>', '<html>', '<meta charset="UTF-8">', '<title>old tweets:</title><base target="_blank" />', '<link rel="stylesheet" href="' + nest + SaveFolderName + '/default.css" />', '<script src="' + LocalSaveFolder + '/Twi ' + id + '.txt"></script>', '<script src="' + nest + SaveFolderName + '/jquery.min.js"></script>', '<script src="' + nest + SaveFolderName + '/default.js"></script>', '</head><body>', '<div id="nav"></div>', '<div id="results">'].join("\r\n"); var footer = '</div></body></html>'; // alert(fName + "\n" + text.slice(0,200)) saveFile(fName, [header, text, footer].join("\r\n")); } function idSave(fName) { var text = conv( $("#results").html() ); if (text =="") return; saveFile(fName, text); } function saveFile(fName, text) { var blob = new Blob([text], {type: "text/plain;charset=UTF-8"}); if (window.navigator.msSaveBlob) window.navigator.msSaveBlob(blob, fName); // IE else { // それ以外 var a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = fName; a.click(); } } function conv(s, isAll) { if (isAll != false && $("#newest").val() != "") { var targetId = $("#newest").val().split(":")[0]; if (location.href.indexOf(targetId) == -1) { alert("ユーザー名が一致しません。"); $('input[name="new_user_box"]').val(targetId); return ""; } var newest = $("#newest").val().split(":")[1]; var t = s.split(newest); if (t[1] == undefined) { alert("status id が見つかりません。Load 数が増えるのを待ってみてください。"); return ""; } var ind = t[0].lastIndexOf('</span>'); s = t[0].substring(0, ind) + '</span>'; } else { if (isAll == false) { alert("status id を入力してください。"); return ""; } } s = s.split("/span><br><span").join("/span><span"); var sp1 = "<span ", kugiri = "class=\"tweet\">", ume = sp1+kugiri, kara = ""; var b = s.split("<span rel=\""); var a = []; for (var i in b) { if (i == 0) a.push(b[i]); else { a.push(ume); var t = b[i].split(kugiri)[1]; a.push(t); } } a[a.length-1] = a[a.length-1].replace("</span><br>", "</span>"); s = a.join(kara); if (10 > s.length) { alert("更新がないようです。"); return ""; } return s; } }();void 0; <|start_filename|>src/DarkMode/user32-stub/user32-stub.cpp<|end_filename|> extern "C" void __stdcall SetWindowCompositionAttribute(int, int) {} <|start_filename|>src/StyleLexers/styleLexAHK.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_AHK = { // Flow of Control "break continue else exit exitapp gosub goto if ifequal ifexist ifgreater ifgreaterorequal " "ifinstring ifless iflessorequal ifmsgbox ifnotequal ifnotexist ifnotinstring ifwinactive " "ifwinexist ifwinnotactive ifwinnotexist loop onexit pause repeat return settimer sleep " "suspend static global local var byref while until for class try catch throw", // Commands "autotrim blockinput clipwait control controlclick controlfocus controlget controlgetfocus " "controlgetpos controlgettext controlmove controlsend controlsendraw controlsettext coordmode " "critical detecthiddentext detecthiddenwindows drive driveget drivespacefree edit endrepeat " "envadd envdiv envget envmult envset envsub envupdate fileappend filecopy filecopydir filecreatedir " "filecreateshortcut fileencoding filedelete filegetattrib filegetshortcut filegetsize filegettime filegetversion " "fileinstall filemove filemovedir fileread filereadline filerecycle filerecycleempty fileremovedir " "fileselectfile fileselectfolder filesetattrib filesettime formattime getkeystate groupactivate " "groupadd groupclose groupdeactivate gui guicontrol guicontrolget hideautoitwin hotkey imagesearch " "inidelete iniread iniwrite input inputbox keyhistory keywait listhotkeys listlines listvars menu " "mouseclick mouseclickdrag mousegetpos mousemove msgbox outputdebug pixelgetcolor pixelsearch " "postmessage process progress random regdelete regread regwrite reload run runas runwait send " "sendevent sendinput sendmessage sendmode sendplay sendraw setbatchlines setcapslockstate " "setcontroldelay setdefaultmousespeed setenv setformat setkeydelay setmousedelay setnumlockstate " "setscrolllockstate setstorecapslockmode settitlematchmode setwindelay setworkingdir shutdown sort " "soundbeep soundget soundgetwavevolume soundplay soundset soundsetwavevolume splashimage splashtextoff " "splashtexton splitpath statusbargettext statusbarwait stringcasesense stringgetpos stringleft stringlen " "stringlower stringmid stringreplace stringright stringsplit stringtrimleft stringtrimright stringupper " "sysget thread tooltip transform traytip urldownloadtofile winactivate winactivatebottom winclose winget " "wingetactivestats wingetactivetitle wingetclass wingetpos wingettext wingettitle winhide winkill " "winmaximize winmenuselectitem winminimize winminimizeall winminimizeallundo winmove winrestore winset " "winsettitle winshow winwait winwaitactive winwaitclose winwaitnotactive", // Functions "abs acos asc asin atan ceil chr cos dllcall exp fileexist floor getkeystate numget numput " "registercallback il_add il_create il_destroy instr islabel isfunc ln log lv_add lv_delete " "lv_deletecol lv_getcount lv_getnext lv_gettext lv_insert lv_insertcol lv_modify lv_modifycol " "lv_setimagelist mod onmessage round regexmatch regexreplace sb_seticon sb_setparts sb_settext " "sin sqrt strlen substr tan tv_add tv_delete tv_getchild tv_getcount tv_getnext tv_get tv_getparent " "tv_getprev tv_getselection tv_gettext tv_modify tv_setimagelist varsetcapacity winactive winexist " "trim ltrim rtrim fileopen strget strput object array isobject objinsert objremove objminindex " "objmaxindex objsetcapacity objgetcapacity objgetaddress objnewenum objaddref objrelease objhaskey " "objclone _insert _remove _minindex _maxindex _setcapacity _getcapacity _getaddress _newenum _addref " "_release _haskey _clone comobjcreate comobjget comobjconnect comobjerror comobjactive comobjenwrap " "comobjunwrap comobjparameter comobjmissing comobjtype comobjvalue comobjarray comobjquery comobjflags " "func getkeyname getkeyvk getkeysc isbyref exception", // Directives "allowsamelinecomments clipboardtimeout commentflag errorstdout escapechar hotkeyinterval " "hotkeymodifiertimeout hotstring if iftimeout ifwinactive ifwinexist include includeagain " "installkeybdhook installmousehook keyhistory ltrim maxhotkeysperinterval maxmem maxthreads " "maxthreadsbuffer maxthreadsperhotkey menumaskkey noenv notrayicon persistent singleinstance " "usehook warn winactivateforce", // Keys & Buttons "shift lshift rshift alt lalt ralt control lcontrol rcontrol ctrl lctrl rctrl lwin rwin appskey " "altdown altup shiftdown shiftup ctrldown ctrlup lwindown lwinup rwindown rwinup lbutton rbutton " "mbutton wheelup wheeldown xbutton1 xbutton2 joy1 joy2 joy3 joy4 joy5 joy6 joy7 joy8 joy9 joy10 " "joy11 joy12 joy13 joy14 joy15 joy16 joy17 joy18 joy19 joy20 joy21 joy22 joy23 joy24 joy25 joy26 " "joy27 joy28 joy29 joy30 joy31 joy32 joyx joyy joyz joyr joyu joyv joypov joyname joybuttons " "joyaxes joyinfo space tab enter escape esc backspace bs delete del insert ins pgup pgdn home end " "up down left right printscreen ctrlbreak pause scrolllock capslock numlock numpad0 numpad1 numpad2 " "numpad3 numpad4 numpad5 numpad6 numpad7 numpad8 numpad9 numpadmult numpadadd numpadsub numpaddiv " "numpaddot numpaddel numpadins numpadclear numpadup numpaddown numpadleft numpadright numpadhome " "numpadend numpadpgup numpadpgdn numpadenter f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 f11 f12 f13 f14 f15 " "f16 f17 f18 f19 f20 f21 f22 f23 f24 browser_back browser_forward browser_refresh browser_stop " "browser_search browser_favorites browser_home volume_mute volume_down volume_up media_next " "media_prev media_stop media_play_pause launch_mail launch_media launch_app1 launch_app2 blind " "click raw wheelleft wheelright", // Variables "a_ahkpath a_ahkversion a_appdata a_appdatacommon a_autotrim a_batchlines a_caretx a_carety " "a_computername a_controldelay a_cursor a_dd a_ddd a_dddd a_defaultmousespeed a_desktop " "a_desktopcommon a_detecthiddentext a_detecthiddenwindows a_endchar a_eventinfo a_exitreason " "a_formatfloat a_formatinteger a_gui a_guievent a_guicontrol a_guicontrolevent a_guiheight " "a_guiwidth a_guix a_guiy a_hour a_iconfile a_iconhidden a_iconnumber a_icontip a_index " "a_ipaddress1 a_ipaddress2 a_ipaddress3 a_ipaddress4 a_isadmin a_iscompiled a_issuspended " "a_keydelay a_language a_lasterror a_linefile a_linenumber a_loopfield a_loopfileattrib " "a_loopfiledir a_loopfileext a_loopfilefullpath a_loopfilelongpath a_loopfilename " "a_loopfileshortname a_loopfileshortpath a_loopfilesize a_loopfilesizekb a_loopfilesizemb " "a_loopfiletimeaccessed a_loopfiletimecreated a_loopfiletimemodified a_loopreadline a_loopregkey " "a_loopregname a_loopregsubkey a_loopregtimemodified a_loopregtype a_mday a_min a_mm a_mmm " "a_mmmm a_mon a_mousedelay a_msec a_mydocuments a_now a_nowutc a_numbatchlines a_ostype " "a_osversion a_priorhotkey a_programfiles a_programs a_programscommon a_screenheight " "a_screenwidth a_scriptdir a_scriptfullpath a_scriptname a_sec a_space a_startmenu " "a_startmenucommon a_startup a_startupcommon a_stringcasesense a_tab a_temp a_thishotkey " "a_thismenu a_thismenuitem a_thismenuitempos a_tickcount a_timeidle a_timeidlephysical " "a_timesincepriorhotkey a_timesincethishotkey a_titlematchmode a_titlematchmodespeed " "a_username a_wday a_windelay a_windir a_workingdir a_yday a_year a_yweek a_yyyy " "clipboard clipboardall comspec errorlevel programfiles true false a_thisfunc a_thislabel " "a_ispaused a_iscritical a_isunicode a_ptrsize a_scripthwnd a_priorkey", // Special Parameters (keywords) "ltrim rtrim join ahk_id ahk_pid ahk_class ahk_group ahk_exe processname processpath minmax " "controllist statuscd filesystem setlabel alwaysontop mainwindow nomainwindow useerrorlevel " "altsubmit hscroll vscroll imagelist wantctrla wantf2 vis visfirst wantreturn backgroundtrans " "minimizebox maximizebox sysmenu toolwindow exstyle check3 checkedgray readonly notab lastfound " "lastfoundexist alttab shiftalttab alttabmenu alttabandmenu alttabmenudismiss controllisthwnd " "hwnd deref pow bitnot bitand bitor bitxor bitshiftleft bitshiftright sendandmouse mousemove " "mousemoveoff hkey_local_machine hkey_users hkey_current_user hkey_classes_root hkey_current_config " "hklm hku hkcu hkcr hkcc reg_sz reg_expand_sz reg_multi_sz reg_dword reg_qword reg_binary reg_link " "reg_resource_list reg_full_resource_descriptor reg_resource_requirements_list reg_dword_big_endian " "regex pixel mouse screen relative rgb low belownormal normal abovenormal high realtime between " "contains in is integer float number digit xdigit integerfast floatfast alpha upper lower alnum " "time date not or and topmost top bottom transparent transcolor redraw region id idlast count " "list capacity eject lock unlock label serial type status seconds minutes hours days read parse " "logoff close error single shutdown menu exit reload tray add rename check uncheck togglecheck " "enable disable toggleenable default nodefault standard nostandard color delete deleteall icon " "noicon tip click show edit progress hotkey text picture pic groupbox button checkbox radio " "dropdownlist ddl combobox statusbar treeview listbox listview datetime monthcal updown slider " "tab tab2 activex iconsmall tile report sortdesc nosort nosorthdr grid hdr autosize range xm ym " "ys xs xp yp font resize owner submit nohide minimize maximize restore noactivate na cancel " "destroy center margin owndialogs guiescape guiclose guisize guicontextmenu guidropfiles tabstop " "section wrap border top bottom buttons expand first lines number uppercase lowercase limit " "password multi group background bold italic strike underline norm theme caption delimiter flash " "style checked password hidden left right center section move focus hide choose choosestring text " "pos enabled disabled visible notimers interrupt priority waitclose unicode tocodepage fromcodepage " "yes no ok cancel abort retry ignore force on off all send wanttab monitorcount monitorprimary " "monitorname monitorworkarea pid this base extends __get __set __call __delete __new new " "useunsetlocal useunsetglobal useenv localsameasglobal", // User Defined NULL, NULL }; EDITLEXER lexAHK = { SCLEX_AHK, "ahk", IDS_LEX_AHK, L"AutoHotkey Script", L"ahk; ahkl; ia; scriptlet", L"", &KeyWords_AHK, { { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ SCE_AHK_DEFAULT, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {MULTI_STYLE(SCE_AHK_COMMENTLINE,SCE_AHK_COMMENTBLOCK,0,0)}, IDS_LEX_STR_63127, L"Comment", L"fore:#008000", L"" }, { {SCE_AHK_ESCAPE}, IDS_LEX_STR_63306, L"Escape", L"fore:#FF8000", L"" }, { {SCE_AHK_SYNOPERATOR}, IDS_LEX_STR_63377, L"Syntax Operator", L"fore:#7F200F", L"" }, { {SCE_AHK_EXPOPERATOR}, IDS_LEX_STR_63308, L"Expression Operator", L"fore:#FF4F00", L"" }, { {SCE_AHK_STRING}, IDS_LEX_STR_63131, L"String", L"fore:#747474", L"" }, { {SCE_AHK_NUMBER}, IDS_LEX_STR_63130, L"Number", L"fore:#416CAD", L"" }, { {SCE_AHK_IDENTIFIER}, IDS_LEX_STR_63129, L"Identifier", L"fore:#CF2F0F", L"" }, { {SCE_AHK_VARREF}, IDS_LEX_STR_63309, L"Variable Dereferencing", L"fore:#CF2F0F; back:#E4FFE4", L"" }, { {SCE_AHK_LABEL}, IDS_LEX_STR_63235, L"Label", L"fore:#000000; back:#FFFFA1", L"" }, { {SCE_AHK_WORD_CF}, IDS_LEX_STR_63310, L"Flow of Control", L"bold; fore:#880088", L"" }, { {SCE_AHK_WORD_CMD}, IDS_LEX_STR_63236, L"Command", L"fore:#0036D9", L"" }, { {SCE_AHK_WORD_FN}, IDS_LEX_STR_63277, L"Function", L"italic; fore:#0F707F", L"" }, { {SCE_AHK_WORD_DIR}, IDS_LEX_STR_63203, L"Directive", L"italic; fore:#F04020", L"" }, { {SCE_AHK_WORD_KB}, IDS_LEX_STR_63311, L"Keys & Buttons", L"bold; fore:#FF00FF", L"" }, { {SCE_AHK_WORD_VAR}, IDS_LEX_STR_63312, L"Built-In Variables", L"italic; fore:#CF00CF", L"" }, { {SCE_AHK_WORD_SP}, IDS_LEX_STR_63376, L"Special", L"italic; fore:#BD8E00", L"" }, //{ {SCE_AHK_WORD_UD}, IDS_LEX_STR_63106, L"User Defined", L"fore:#800020", L"" }, { {SCE_AHK_VARREFKW}, IDS_LEX_STR_63313, L"Variable Keyword", L"italic; fore:#CF00CF; back:#F9F9FF", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>src/ced/ced/util/string_util.h<|end_filename|> // encoding: UTF-8 // Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// #ifndef UTIL_STRING_UTIL_H_ #define UTIL_STRING_UTIL_H_ #include <string.h> namespace base { #if defined(_WIN32) // Compare the two strings s1 and s2 without regard to case using // the current locale; returns 0 if they are equal, 1 if s1 > s2, and -1 if // s2 > s1 according to a lexicographic comparison. inline int strcasecmp(const char* s1, const char* s2) { return _stricmp(s1, s2); } inline int strncasecmp(const char* s1, const char* s2, size_t n) { return _strnicmp(s1, s2, n); } #else inline int strcasecmp(const char* s1, const char* s2) { return ::strcasecmp(s1, s2); } inline int strncasecmp(const char* s1, const char* s2, size_t n) { return ::strncasecmp(s1, s2, n); } #endif } #if !defined(__linux__) inline void* memrchr(const void* s, int c, size_t n) { const auto* p = (const unsigned char*) s; for (p += n; n > 0; n--) { if (*--p == c) return (void*) p; } return nullptr; } #endif #endif // UTIL_STRING_UTIL_H_ <|start_filename|>scintilla/src/KeyMap.h<|end_filename|> // Scintilla source code edit control /** @file KeyMap.h ** Defines a mapping between keystrokes and commands. **/ // Copyright 1998-2001 by <NAME> <<EMAIL>> // The License.txt file describes the conditions under which this software may be distributed. #ifndef KEYMAP_H #define KEYMAP_H namespace Scintilla::Internal { #define SCI_NORM KeyMod::Norm #define SCI_SHIFT KeyMod::Shift #define SCI_CTRL KeyMod::Ctrl #define SCI_ALT KeyMod::Alt #define SCI_META KeyMod::Meta #define SCI_SUPER KeyMod::Super #define SCI_CSHIFT (KeyMod::Ctrl | KeyMod::Shift) #define SCI_ASHIFT (KeyMod::Alt | KeyMod::Shift) /** */ class KeyModifiers { public: Scintilla::Keys key; Scintilla::KeyMod modifiers; KeyModifiers(Scintilla::Keys key_, Scintilla::KeyMod modifiers_) noexcept : key(key_), modifiers(modifiers_) { } bool operator<(const KeyModifiers &other) const noexcept { if (key == other.key) return modifiers < other.modifiers; else return key < other.key; } }; /** */ class KeyToCommand { public: Scintilla::Keys key; Scintilla::KeyMod modifiers; Scintilla::Message msg; }; /** */ class KeyMap { std::map<KeyModifiers, Scintilla::Message> kmap; static const KeyToCommand MapDefault[]; public: KeyMap(); void Clear() noexcept; void AssignCmdKey(Scintilla::Keys key, Scintilla::KeyMod modifiers, Scintilla::Message msg); Scintilla::Message Find(Scintilla::Keys key, Scintilla::KeyMod modifiers) const; // 0 returned on failure const std::map<KeyModifiers, Scintilla::Message> &GetKeyMap() const noexcept; }; } #endif <|start_filename|>scintilla/src/Indicator.h<|end_filename|> // Scintilla source code edit control /** @file Indicator.h ** Defines the style of indicators which are text decorations such as underlining. **/ // Copyright 1998-2001 by <NAME> <<EMAIL>> // The License.txt file describes the conditions under which this software may be distributed. #ifndef INDICATOR_H #define INDICATOR_H namespace Scintilla::Internal { struct StyleAndColour { Scintilla::IndicatorStyle style; ColourRGBA fore; StyleAndColour() noexcept : style(Scintilla::IndicatorStyle::Plain), fore(0, 0, 0) { } StyleAndColour(Scintilla::IndicatorStyle style_, ColourRGBA fore_ = ColourRGBA(0, 0, 0)) noexcept : style(style_), fore(fore_) { } bool operator==(const StyleAndColour &other) const noexcept { return (style == other.style) && (fore == other.fore); } }; /** */ class Indicator { public: enum class State { normal, hover }; StyleAndColour sacNormal; StyleAndColour sacHover; bool under; int fillAlpha; int outlineAlpha; Scintilla::IndicFlag attributes; XYPOSITION strokeWidth = 1.0f; Indicator() noexcept : under(false), fillAlpha(30), outlineAlpha(50), attributes(Scintilla::IndicFlag::None) { } Indicator(Scintilla::IndicatorStyle style_, ColourRGBA fore_= ColourRGBA(0,0,0), bool under_=false, int fillAlpha_=30, int outlineAlpha_=50) noexcept : sacNormal(style_, fore_), sacHover(style_, fore_), under(under_), fillAlpha(fillAlpha_), outlineAlpha(outlineAlpha_), attributes(Scintilla::IndicFlag::None) { } void Draw(Surface *surface, const PRectangle &rc, const PRectangle &rcLine, const PRectangle &rcCharacter, State drawState, int value) const; bool IsDynamic() const noexcept { return !(sacNormal == sacHover); } bool OverridesTextFore() const noexcept { return sacNormal.style == Scintilla::IndicatorStyle::TextFore || sacHover.style == Scintilla::IndicatorStyle::TextFore; } Scintilla::IndicFlag Flags() const noexcept { return attributes; } void SetFlags(Scintilla::IndicFlag attributes_) noexcept; }; } #endif <|start_filename|>test/test_files/StyleLexers/styleLexCPP/Config.cpp<|end_filename|> /****************************************************************************** * * * Config.cpp * * TODO: HACK * addindex *******************************************************************************/ #include <strsafe.h> #include <shlobj.h> // TODO: fkdlkldfdl // ---------------------------------------------------------------------------- extern "C" { #include "Version.h" #include "Helpers.h" #include "Styles.h" #include "Dialogs.h" #include "Encoding.h" #include "Notepad3.h" #include "resource.h" } extern "C" const int g_FontQuality[4]; extern "C" WININFO s_WinInfo; extern "C" WININFO s_DefWinInfo; extern "C" const WCHAR* const TBBUTTON_DEFAULT_IDS_V1; extern "C" const WCHAR* const TBBUTTON_DEFAULT_IDS_V2; extern "C" prefix_t s_mxSBPrefix[STATUS_SECTOR_COUNT]; extern "C" prefix_t s_mxSBPostfix[STATUS_SECTOR_COUNT]; extern "C" bool s_iStatusbarVisible[STATUS_SECTOR_COUNT]; extern "C" int s_iStatusbarWidthSpec[STATUS_SECTOR_COUNT]; extern "C" int s_vSBSOrder[STATUS_SECTOR_COUNT]; extern "C" WCHAR s_tchToolbarBitmap[MAX_PATH]; extern "C" WCHAR s_tchToolbarBitmapHot[MAX_PATH]; extern "C" WCHAR s_tchToolbarBitmapDisabled[MAX_PATH]; extern "C" bool s_bEnableSaveSettings; extern "C" int s_iToolBarTheme; extern "C" bool s_flagPosParam; extern "C" int s_flagWindowPos; extern "C" int s_flagReuseWindow; extern "C" int s_flagSingleFileInstance; extern "C" int s_flagMultiFileArg; extern "C" int s_flagShellUseSystemMRU; extern "C" int s_flagPrintFileAndLeave; // ---------------------------------------------------------------------------- #include "SimpleIni.h" #include "Config.h" // ============================================================================ static bool const s_bIsUTF8 = true; static bool const s_bUseMultiKey = false; static bool const s_bUseMultiLine = false; static bool const s_bSetSpaces = false; // ---------------------------------------------------------------------------- static int s_iStatusbarSections[STATUS_SECTOR_COUNT] = SBS_INIT_MINUS; // ---------------------------------------------------------------------------- #define SI_SUCCESS(RC) ((RC) >= SI_OK) // ============================================================================ static CSimpleIni s_INI(s_bIsUTF8, s_bUseMultiKey, s_bUseMultiLine); extern "C" bool LoadIniFile(LPCWSTR lpIniFilePath) { s_INI.Reset(); SI_Error const rc = s_INI.LoadFile(lpIniFilePath); return SI_SUCCESS(rc); } extern "C" bool SaveIniFile(LPCWSTR lpIniFilePath) { s_INI.SetSpaces(s_bSetSpaces); SI_Error const rc = s_INI.SaveFile(lpIniFilePath, true); if (SI_SUCCESS(rc)) { s_INI.Reset(); // done } return SI_SUCCESS(rc); } extern "C" void ReleaseIniFile() { s_INI.Reset(); } //============================================================================= // // Manipulation of (cached) ini file // //============================================================================= extern "C" size_t IniSectionGetString(LPCWSTR lpSectionName, LPCWSTR lpKeyName, LPCWSTR lpDefault, LPWSTR lpReturnedString, size_t cchReturnedString) { bool bHasMultiple = false; StringCchCopyW(lpReturnedString, cchReturnedString, s_INI.GetValue(lpSectionName, lpKeyName, lpDefault, &bHasMultiple)); //assert(!bHasMultiple); return StringCchLenW(lpReturnedString, cchReturnedString); } // ============================================================================ extern "C" int IniSectionGetInt(LPCWSTR lpSectionName, LPCWSTR lpKeyName, int iDefault) { bool bHasMultiple = false; int const iValue = (int)s_INI.GetLongValue(lpSectionName, lpKeyName, (long)iDefault, &bHasMultiple); //assert(!bHasMultiple); return iValue; } // ============================================================================ extern "C" double IniSectionGetDouble(LPCWSTR lpSectionName, LPCWSTR lpKeyName, double dDefault) { bool bHasMultiple = false; double const dValue = s_INI.GetDoubleValue(lpSectionName, lpKeyName, dDefault, &bHasMultiple); //assert(!bHasMultiple); return dValue; } // ============================================================================ extern "C" bool IniSectionGetBool(LPCWSTR lpSectionName, LPCWSTR lpKeyName, bool bDefault) { bool bHasMultiple = false; bool const bValue = s_INI.GetBoolValue(lpSectionName, lpKeyName, bDefault, &bHasMultiple); //assert(!bHasMultiple); return bValue; } // ============================================================================ extern "C" bool IniSectionSetString(LPCWSTR lpSectionName, LPCWSTR lpKeyName, LPCWSTR lpString) { SI_Error const rc = s_INI.SetValue(lpSectionName, lpKeyName, lpString, nullptr, !s_bUseMultiKey); return SI_SUCCESS(rc); } // ============================================================================ extern "C" bool IniSectionSetInt(LPCWSTR lpSectionName, LPCWSTR lpKeyName, int iValue) { SI_Error const rc = s_INI.SetLongValue(lpSectionName, lpKeyName, (long)iValue, nullptr, false, !s_bUseMultiKey); return SI_SUCCESS(rc); } extern "C" bool IniSectionSetHex(LPCWSTR lpSectionName, LPCWSTR lpKeyName, int iValue) { SI_Error const rc = s_INI.SetLongValue(lpSectionName, lpKeyName, (long)iValue, nullptr, true, !s_bUseMultiKey); return SI_SUCCESS(rc); } // ============================================================================ extern "C" bool IniSectionSetDouble(LPCWSTR lpSectionName, LPCWSTR lpKeyName, double dValue) { SI_Error const rc = s_INI.SetDoubleValue(lpSectionName, lpKeyName, dValue, nullptr, !s_bUseMultiKey); return SI_SUCCESS(rc); } // ============================================================================ extern "C" bool IniSectionSetBool(LPCWSTR lpSectionName, LPCWSTR lpKeyName, bool bValue) { SI_Error const rc = s_INI.SetBoolValue(lpSectionName, lpKeyName, bValue, nullptr, !s_bUseMultiKey); return SI_SUCCESS(rc); } // ============================================================================ extern "C" bool IniSectionDelete(LPCWSTR lpSectionName, LPCWSTR lpKeyName, bool bRemoveEmpty) { return s_INI.Delete(lpSectionName, lpKeyName, bRemoveEmpty); } // ============================================================================ extern "C" bool IniSectionClear(LPCWSTR lpSectionName, bool bRemoveEmpty) { bool const ok = s_INI.Delete(lpSectionName, nullptr, bRemoveEmpty); if (!bRemoveEmpty) { SI_Error const rc = s_INI.SetValue(lpSectionName, nullptr, nullptr); return SI_SUCCESS(rc); } return ok; } // ============================================================================ extern "C" bool IniClearAllSections(LPCWSTR lpPrefix, bool bRemoveEmpty) { size_t const len = StringCchLen(lpPrefix, 0); CSimpleIni::TNamesDepend Sections; s_INI.GetAllSections(Sections); for (const auto& section : Sections) { if (StringCchCompareNI(section.pItem, len, lpPrefix, len) == 0) { s_INI.Delete(section.pItem, nullptr, bRemoveEmpty); } } return true; } // ============================================================================ // ============================================================================ // ============================================================================ extern "C" size_t IniFileGetString(LPCWSTR lpFilePath, LPCWSTR lpSectionName, LPCWSTR lpKeyName, LPCWSTR lpDefault, LPWSTR lpReturnedString, size_t cchReturnedString) { CSimpleIni Ini(s_bIsUTF8, s_bUseMultiKey, s_bUseMultiLine); SI_Error const rc = Ini.LoadFile(lpFilePath); if (SI_SUCCESS(rc)) { bool bHasMultiple = false; StringCchCopyW(lpReturnedString, cchReturnedString, Ini.GetValue(lpSectionName, lpKeyName, lpDefault, &bHasMultiple)); //assert(!bHasMultiple); } return StringCchLenW(lpReturnedString, cchReturnedString); } // ============================================================================ extern "C" bool IniFileSetString(LPCWSTR lpFilePath, LPCWSTR lpSectionName, LPCWSTR lpKeyName, LPCWSTR lpString) { CSimpleIni Ini(s_bIsUTF8, s_bUseMultiKey, s_bUseMultiLine); SI_Error rc = Ini.LoadFile(lpFilePath); if (SI_SUCCESS(rc)) { SI_Error const res = Ini.SetValue(lpSectionName, lpKeyName, lpString, nullptr, !s_bUseMultiKey); rc = SI_SUCCESS(res) ? SI_OK : SI_FAIL; if (SI_SUCCESS(rc)) { Ini.SetSpaces(s_bSetSpaces); rc = Ini.SaveFile(Globals.IniFile, true); } } return SI_SUCCESS(rc); } // ============================================================================ extern "C" int IniFileGetInt(LPCWSTR lpFilePath, LPCWSTR lpSectionName, LPCWSTR lpKeyName, int iDefault) { CSimpleIni Ini(s_bIsUTF8, s_bUseMultiKey, s_bUseMultiLine); SI_Error const rc = Ini.LoadFile(lpFilePath); if (SI_SUCCESS(rc)) { bool bHasMultiple = false; int const iValue = Ini.GetLongValue(lpSectionName, lpKeyName, (long)iDefault, &bHasMultiple); //assert(!bHasMultiple); return iValue; } return iDefault; } // ============================================================================ extern "C" bool IniFileSetInt(LPCWSTR lpFilePath, LPCWSTR lpSectionName, LPCWSTR lpKeyName, int iValue) { CSimpleIni Ini(s_bIsUTF8, s_bUseMultiKey, s_bUseMultiLine); SI_Error rc = Ini.LoadFile(lpFilePath); if (SI_SUCCESS(rc)) { Ini.SetLongValue(lpSectionName, lpKeyName, (long)iValue, nullptr, false, !s_bUseMultiKey); Ini.SetSpaces(s_bSetSpaces); rc = Ini.SaveFile(Globals.IniFile, true); } return SI_SUCCESS(rc); } // ============================================================================ extern "C" bool IniFileGetBool(LPCWSTR lpFilePath, LPCWSTR lpSectionName, LPCWSTR lpKeyName, bool bDefault) { CSimpleIni Ini(s_bIsUTF8, s_bUseMultiKey, s_bUseMultiLine); SI_Error const rc = Ini.LoadFile(lpFilePath); if (SI_SUCCESS(rc)) { bool bHasMultiple = false; bool const bValue = Ini.GetBoolValue(lpSectionName, lpKeyName, bDefault, &bHasMultiple); //assert(!bHasMultiple); return bValue; } return bDefault; } // ============================================================================ extern "C" bool IniFileSetBool(LPCWSTR lpFilePath, LPCWSTR lpSectionName, LPCWSTR lpKeyName, bool bValue) { CSimpleIni Ini(s_bIsUTF8, s_bUseMultiKey, s_bUseMultiLine); SI_Error rc = Ini.LoadFile(lpFilePath); if (SI_SUCCESS(rc)) { Ini.SetBoolValue(lpSectionName, lpKeyName, bValue, nullptr, !s_bUseMultiKey); Ini.SetSpaces(s_bSetSpaces); rc = Ini.SaveFile(Globals.IniFile, true); } return SI_SUCCESS(rc); } // ============================================================================ extern "C" bool IniFileDelete(LPCWSTR lpFilePath, LPCWSTR lpSectionName, LPCWSTR lpKeyName, bool bRemoveEmpty) { CSimpleIni Ini(s_bIsUTF8, s_bUseMultiKey, s_bUseMultiLine); SI_Error rc = Ini.LoadFile(lpFilePath); if (SI_SUCCESS(rc)) { Ini.Delete(lpSectionName, lpKeyName, bRemoveEmpty); Ini.SetSpaces(s_bSetSpaces); rc = Ini.SaveFile(Globals.IniFile, true); } return SI_SUCCESS(rc); } // ============================================================================ //============================================================================= // // _CheckIniFile() // static bool _CheckIniFile(LPWSTR lpszFile, LPCWSTR lpszModule) { WCHAR tchFileExpanded[MAX_PATH] = { L'\0' }; ExpandEnvironmentStrings(lpszFile, tchFileExpanded, COUNTOF(tchFileExpanded)); if (PathIsRelative(tchFileExpanded)) { WCHAR tchBuild[MAX_PATH] = { L'\0' }; // program directory StringCchCopy(tchBuild, COUNTOF(tchBuild), lpszModule); StringCchCopy(PathFindFileName(tchBuild), COUNTOF(tchBuild), tchFileExpanded); if (PathFileExists(tchBuild)) { StringCchCopy(lpszFile, MAX_PATH, tchBuild); return true; } // sub directory (.\np3\) StringCchCopy(tchBuild, COUNTOF(tchBuild), lpszModule); PathCchRemoveFileSpec(tchBuild, COUNTOF(tchBuild)); StringCchCat(tchBuild, COUNTOF(tchBuild), L"\\np3\\"); StringCchCat(tchBuild, COUNTOF(tchBuild), tchFileExpanded); if (PathFileExists(tchBuild)) { StringCchCopy(lpszFile, MAX_PATH, tchBuild); return true; } // Application Data (%APPDATA%) if (GetKnownFolderPath(FOLDERID_RoamingAppData, tchBuild, COUNTOF(tchBuild))) { PathCchAppend(tchBuild, COUNTOF(tchBuild), tchFileExpanded); if (PathFileExists(tchBuild)) { StringCchCopy(lpszFile, MAX_PATH, tchBuild); return true; } } // Home (%HOMEPATH%) user's profile dir if (GetKnownFolderPath(FOLDERID_Profile, tchBuild, COUNTOF(tchBuild))) { PathCchAppend(tchBuild, COUNTOF(tchBuild), tchFileExpanded); if (PathFileExists(tchBuild)) { StringCchCopy(lpszFile, MAX_PATH, tchBuild); return true; } } //~// in general search path //~if (SearchPath(NULL,tchFileExpanded,L".ini",COUNTOF(tchBuild),tchBuild,NULL)) { //~ StringCchCopy(lpszFile,MAX_PATH,tchBuild); //~ return true; //~} } else if (PathFileExists(tchFileExpanded)) { StringCchCopy(lpszFile, MAX_PATH, tchFileExpanded); return true; } return false; } // ============================================================================ static bool _CheckIniFileRedirect(LPWSTR lpszAppName, LPWSTR lpszKeyName, LPWSTR lpszFile, LPCWSTR lpszModule) { WCHAR tch[MAX_PATH] = { L'\0' }; if (GetPrivateProfileString(lpszAppName, lpszKeyName, L"", tch, COUNTOF(tch), lpszFile)) { if (_CheckIniFile(tch, lpszModule)) { StringCchCopy(lpszFile, MAX_PATH, tch); return true; } WCHAR tchFileExpanded[MAX_PATH] = { L'\0' }; ExpandEnvironmentStrings(tch, tchFileExpanded, COUNTOF(tchFileExpanded)); if (PathIsRelative(tchFileExpanded)) { StringCchCopy(lpszFile, MAX_PATH, lpszModule); StringCchCopy(PathFindFileName(lpszFile), MAX_PATH, tchFileExpanded); return true; } StringCchCopy(lpszFile, MAX_PATH, tchFileExpanded); return true; } return false; } // ============================================================================ extern "C" bool FindIniFile() { bool bFound = false; WCHAR tchPath[MAX_PATH] = { L'\0' }; WCHAR tchModule[MAX_PATH] = { L'\0' }; GetModuleFileName(NULL, tchModule, COUNTOF(tchModule)); // set env path to module dir StringCchCopy(tchPath, COUNTOF(tchPath), tchModule); PathCchRemoveFileSpec(tchPath, COUNTOF(tchPath)); SetEnvironmentVariable(NOTEPAD3_MODULE_DIR_ENV_VAR, tchPath); if (StrIsNotEmpty(Globals.IniFile)) { if (StringCchCompareXI(Globals.IniFile, L"*?") == 0) { return bFound; } if (!_CheckIniFile(Globals.IniFile, tchModule)) { ExpandEnvironmentStringsEx(Globals.IniFile, COUNTOF(Globals.IniFile)); if (PathIsRelative(Globals.IniFile)) { StringCchCopy(tchPath, COUNTOF(tchPath), tchModule); PathCchRemoveFileSpec(tchPath, COUNTOF(tchPath)); PathCchAppend(tchPath, COUNTOF(tchPath), Globals.IniFile); StringCchCopy(Globals.IniFile, COUNTOF(Globals.IniFile), tchPath); } } } else { StringCchCopy(tchPath, COUNTOF(tchPath), PathFindFileName(tchModule)); PathCchRenameExtension(tchPath, COUNTOF(tchPath), L".ini"); bFound = _CheckIniFile(tchPath, tchModule); if (!bFound) { StringCchCopy(tchPath, COUNTOF(tchPath), L"Notepad3.ini"); bFound = _CheckIniFile(tchPath, tchModule); } if (bFound) { // allow two redirections: administrator -> user -> custom if (_CheckIniFileRedirect(_W(SAPPNAME), _W(SAPPNAME) L".ini", tchPath, tchModule)) { _CheckIniFileRedirect(_W(SAPPNAME), _W(SAPPNAME) L".ini", tchPath, tchModule); } StringCchCopy(Globals.IniFile, COUNTOF(Globals.IniFile), tchPath); } else { StringCchCopy(Globals.IniFile, COUNTOF(Globals.IniFile), tchModule); PathCchRenameExtension(Globals.IniFile, COUNTOF(Globals.IniFile), L".ini"); } } NormalizePathEx(Globals.IniFile, COUNTOF(Globals.IniFile), true, false); return bFound; } //============================================================================= <|start_filename|>src/uchardet/uchardet/src/LangModels/LangArabicModel.cpp<|end_filename|> /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "../nsSBCharSetProber.h" /********* Language model for: Arabic *********/ /** * Generated by BuildLangModel.py * On: 2015-12-13 18:33:58.848027 **/ /* Character Mapping Table: * ILL: illegal character. * CTR: control character specific to the charset. * RET: carriage/return. * SYM: symbol (punctuation) that does not belong to word. * NUM: 0 - 9. * * Other characters are ordered by probabilities * (0 is the most common character in the language). * * Orders are generic to a language. So the codepoint with order X in * CHARSET1 maps to the same character as the codepoint with the same * order X in CHARSET2 for the same language. * As such, it is possible to get missing order. For instance the * ligature of 'o' and 'e' exists in ISO-8859-15 but not in ISO-8859-1 * even though they are both used for French. Same for the euro sign. */ static const unsigned char Iso_8859_6_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 52, 72, 61, 68, 74, 69, 59, 78, 60, 90, 86, 67, 65, 71, 75, /* 4X */ 64, 85, 76, 55, 57, 79, 81, 70, 82, 87, 91,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 37, 58, 49, 47, 38, 54, 66, 46, 39, 88, 63, 45, 51, 43, 40, /* 6X */ 62, 89, 42, 44, 41, 50, 77, 73, 83, 56, 80,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM,ILL,ILL,ILL,SYM,ILL,ILL,ILL,ILL,ILL,ILL,ILL,SYM,SYM,ILL,ILL, /* AX */ ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,SYM,ILL,ILL,ILL,SYM, /* BX */ ILL, 32, 34, 15, 35, 22, 31, 0, 9, 8, 7, 27, 19, 18, 25, 11, /* CX */ 30, 5, 26, 12, 21, 23, 28,SYM, 33, 10, 29,ILL,ILL,ILL,ILL,ILL, /* DX */ 36, 13, 14, 17, 1, 3, 6, 16, 4, 24, 2,SYM,SYM,SYM,SYM,SYM, /* EX */ SYM,SYM,SYM,ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL,ILL, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Windows_1256_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 52, 72, 61, 68, 74, 69, 59, 78, 60, 90, 86, 67, 65, 71, 75, /* 4X */ 64, 85, 76, 55, 57, 79, 81, 70, 82, 87, 91,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 37, 58, 49, 47, 38, 54, 66, 46, 39, 88, 63, 45, 51, 43, 40, /* 6X */ 62, 89, 42, 44, 41, 50, 77, 73, 83, 56, 80,SYM,SYM,SYM,SYM,CTR, /* 7X */ SYM, 48,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, 95,SYM, 96, 92, 97, 98, /* 8X */ 53,SYM,SYM,SYM,SYM,SYM,SYM,SYM, 84,SYM, 99,SYM,100,SYM,SYM,101, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,102,SYM,SYM,SYM,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* BX */ 103, 32, 34, 15, 35, 22, 31, 0, 9, 8, 7, 27, 19, 18, 25, 11, /* CX */ 30, 5, 26, 12, 21, 23, 28,SYM, 20, 33, 10, 29, 36, 13, 14, 17, /* DX */ 104, 1, 93, 3, 6, 16, 4,105,106, 94,107,108, 24, 2,109,110, /* EX */ SYM,SYM,SYM,SYM,111,SYM,SYM,SYM,SYM,112,SYM,113,114,SYM,SYM,115, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ /* Model Table: * Total sequences: 1479 * First 512 sequences: 0.9696025116913417 * Next 512 sequences (512-1024): 0.029166911858880054 * Rest: 0.0012305764497782395 * Negative sequences: TODO */ static const PRUint8 ArabicLangModel[] = { 2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3,3,3,3,3,1,3,1,3,3,3,3,2,2,3, 3,2,1,2,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2, 1,2,3,2,2,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,0,3,1,3,3,3,3,2,2,3, 2,2,0,2,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,1,3,2,3,3,3,2,2,2,2, 0,2,1,3,1,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2, 2,2,2,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,1,2,3,2,3,2,3,3,2,3, 1,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0, 3,2,3,3,3,2,2,3,3,3,3,3,3,3,3,1,3,2,3,3,3,3,0,3,2,2,3,2,2,2,3,2, 0,3,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,3,3,2,3,3,2,2, 0,3,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,0,0,0,0,0,0,0,1,3,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,2,3,3,2,2,1,2,2,2,2,2,2,2, 1,2,2,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,2,3,3,2,3,0,3,2,0,2,2,3,0,3,2,0,3,3,3,0,2,0, 0,3,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,2,2,2,0,2,0,0,3,3,2,3,0,2,0,2, 2,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,2,3,3,2,2,3,3,2,3,3,1,0,0,2,2,0,1,0,1,0,1, 0,0,0,2,1,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0, 3,3,3,2,3,3,3,3,3,2,3,2,3,2,3,2,3,2,2,2,2,2,2,2,2,2,2,1,3,2,2,2, 1,3,0,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,0,2,0,2,1,3,2,0,3,2,0,2,0,3,0,2,0, 0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,3,3,3,3,2,3,3,3,3,3,3,0,3,3,3,3,3,3,0,3,2,3,2,3,2,3,2,2, 0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,2,3,3,1,3,2,1,2,0,2,2,0,3,2,2,0,0,2,0,2,1,2,0,3,0, 0,1,0,2,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,2,2,3,2,2,2,2,2,2,2,2,2,2,1,0,2,3,3,0,1,3,0, 0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,3,3,2,1,3,3,3,3,0,2,3,0,3,2,2,0,3,2,0,3,2,3,0,2,0, 0,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,2,2,0,2,3,1,2,1,0,1,0,0,1,0,3,2,0,2,2,2, 0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,2,3,3,3,2,3,3,2,2,3,2,3,2,2,0,2,1,2,1,1,0,2,1,0,0,0,1,0,2, 1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,2,3,3,3,3,2,3,2,3,3,2,1,2,2,2,3,3,2,2,2,0,0,0,2,3,1,0,0,2,1,2, 0,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,3,3,3,1,2,3,2,0,2,3,3,3,2,3,0,2,2,2,3,2,2,0,3,0,2,2,2,3,2,3,1, 0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,2,3,3,2,3,0,3,2,0,2,1,3,0,2,0,0,2,2,2,0,0,0,2,0,0, 0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,3,2,3,2,3,2,2,0,0,2,0,0,1,3,2,0,3,0,1,2,0,2,0,2,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,2,3,3,2,2,0,2,2,1,2,2,2,2,0,0,0,0,1,2,2,0,0,1,0,2, 2,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,2,3,2,2,1,1,2,3,1,2,2,0,0,0,0,0,0,1,0,0,2,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,2,3,2,3,2,0,2,0,1,2,0,2,1,2,0,0,0,2,2,0,0,0,2,0,2, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,2,3,2,1,2,2,2,0,0,2,0,0,2,2,1,0,2,1,0,2,0,2,0,2,0, 0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,2,2,2,2,2,2,2,0,0,0,2,2,0,3,3,0,2,0,0,0,0,2,2,0,0,0,0,0,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,2,3,2,2,3,2,2,2,2,2,2,0,2,2,2,2,2,2,0,1,0,1,2,0,1,1,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,1,1,1,0,0,2,2,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,2,2,3,2,2,1,2,3,2,0,0,0,2,0,0,3,0,0,0,1,0,0,0,2,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,3,2,2,2,3,2,2,0,2,0,2,2,2,2,0,1,2,1,1,0,2,0,1,0,3,1,2,0,1,2,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,2,2,3,2,1,2,1,1,0,2,2,0,2,0,2,2,0,0,0,2,0,0,2,2,1,2,0,0,0,0, 0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,1,0,1,1,1,0,1,0,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,1,0,0,0,0, 0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,2,2,1,2,2,2,2,2,1,2,0,2,1,2,0,0,1,0,1,0,1,0,0,0,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,2,2,1,1,2,2,2,2,2,0,2,0,2,1,2,0,0,1,0,0,0,2,0,0,0,1,2, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,2,2,1,2,2,2,2,2,2,0,2,0,2,1,2,0,0,1,0,0,0,1,0,0,0,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,1,0,1,2,2,2,2,2,1,1,2,0,2,2,2,0,0,2,0,0,0,1,0,0,0,2,2, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,2,2,2,2,2,2,1,2,2,2,1,0,1,1,1,0,0,0,0,2,0,2,0,0,0,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,2,2,2,2,2,1,2,2,2,0,1,0,2,1,2,0,0,0,0,2,0,1,0,0,0,0,2, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,2,2,2,2,2,0,1,2,1,1,2,0,2,1,0,0,0,1,0,1,0,0,0,0,0,0,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,2,2,2,1,2,0,0,2,1,2,0,0,1,1,0,0,0,0,0,1,0,0,0,0,0,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,2,2,2,2,1,0,0,1,2,0,2,0,0,1,0,0,0,1,1,1,0,1,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,2,2,2,2,2,2,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,2,2,2,1,1,1,1,1,0,1,1,0,0,1,1,0,0,0,0,1,0,0,0,0,0,0,0, 2,2,1,0,2,2,1,1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,2,2,2,2,2,1,0,0,1,2,0,0,1,2,0,0,0,0,0,1,0,0,0,0,0,0,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,1,1,1,0,2,2,2,2,1,0,2,0,1,0,2,0,0,0,0,0,0,2,0,0,0,0,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,2,2,2,2,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,2,0,0,0,0,0,1,0, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,2,2,2,1,1,0,0,0,1,0,0,0,0,0,0,0,1,1,0,1,0,0,1, 2,2,2,0,1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,1,2,1,0,1,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,2,1,0,2,2,0,0,0,0,0,0,0,1,0,0,2,0,0,0,0,1,0,0,1,2,2,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,1,0,1,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,1,2,1,0,1,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,2,0,1,1,0,1,0,1,1,0,1,0,0,1,0,0,0,0,0,0,0,1,0,0,0,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,2,0,0,2,0,2,0,0,1,0,0,0,0,1,0,0,0,0,1,0,1,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,1,0,2,1,1,0,0,0,0,0,0,1,0,0,2,0,1,0,2,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,1,0,1,1,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,2,1,0,1,0,0,0,0,1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,1,1,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0, }; const SequenceModel Iso_8859_6ArabicModel = { Iso_8859_6_CharToOrderMap, ArabicLangModel, 64, (float)0.9696025116913417, PR_FALSE, "ISO-8859-6" }; const SequenceModel Windows_1256ArabicModel = { Windows_1256_CharToOrderMap, ArabicLangModel, 64, (float)0.9696025116913417, PR_FALSE, "WINDOWS-1256" }; <|start_filename|>lexilla/lexers_x/orig/styleLexAHK.c<|end_filename|> // encoding: UTF-8 #include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_AHK = { "break continue else exit exitapp gosub goto if ifequal ifexist ifgreater ifgreaterorequal " "ifinstring ifless iflessorequal ifmsgbox ifnotequal ifnotexist ifnotinstring ifwinactive " "ifwinexist ifwinnotactive ifwinnotexist loop onexit pause repeat return settimer sleep " "suspend static global local var byref while until for class try catch throw", "autotrim blockinput clipwait control controlclick controlfocus controlget controlgetfocus " "controlgetpos controlgettext controlmove controlsend controlsendraw controlsettext coordmode " "critical detecthiddentext detecthiddenwindows drive driveget drivespacefree edit endrepeat " "envadd envdiv envget envmult envset envsub envupdate fileappend filecopy filecopydir filecreatedir " "filecreateshortcut filedelete filegetattrib filegetshortcut filegetsize filegettime filegetversion " "fileinstall filemove filemovedir fileread filereadline filerecycle filerecycleempty fileremovedir " "fileselectfile fileselectfolder filesetattrib filesettime formattime getkeystate groupactivate " "groupadd groupclose groupdeactivate gui guicontrol guicontrolget hideautoitwin hotkey imagesearch " "inidelete iniread iniwrite input inputbox keyhistory keywait listhotkeys listlines listvars menu " "mouseclick mouseclickdrag mousegetpos mousemove msgbox outputdebug pixelgetcolor pixelsearch " "postmessage process progress random regdelete regread regwrite reload run runas runwait send " "sendevent sendinput sendmessage sendmode sendplay sendraw setbatchlines setcapslockstate " "setcontroldelay setdefaultmousespeed setenv setformat setkeydelay setmousedelay setnumlockstate " "setscrolllockstate setstorecapslockmode settitlematchmode setwindelay setworkingdir shutdown sort " "soundbeep soundget soundgetwavevolume soundplay soundset soundsetwavevolume splashimage splashtextoff " "splashtexton splitpath statusbargettext statusbarwait stringcasesense stringgetpos stringleft stringlen " "stringlower stringmid stringreplace stringright stringsplit stringtrimleft stringtrimright stringupper " "sysget thread tooltip transform traytip urldownloadtofile winactivate winactivatebottom winclose winget " "wingetactivestats wingetactivetitle wingetclass wingetpos wingettext wingettitle winhide winkill " "winmaximize winmenuselectitem winminimize winminimizeall winminimizeallundo winmove winrestore winset " "winsettitle winshow winwait winwaitactive winwaitclose winwaitnotactive fileencoding", "abs acos asc asin atan ceil chr cos dllcall exp fileexist floor getkeystate numget numput " "registercallback il_add il_create il_destroy instr islabel isfunc ln log lv_add lv_delete " "lv_deletecol lv_getcount lv_getnext lv_gettext lv_insert lv_insertcol lv_modify lv_modifycol " "lv_setimagelist mod onmessage round regexmatch regexreplace sb_seticon sb_setparts sb_settext " "sin sqrt strlen substr tan tv_add tv_delete tv_getchild tv_getcount tv_getnext tv_get tv_getparent " "tv_getprev tv_getselection tv_gettext tv_modify tv_setimagelist varsetcapacity winactive winexist " "trim ltrim rtrim fileopen strget strput object array isobject objinsert objremove objminindex " "objmaxindex objsetcapacity objgetcapacity objgetaddress objnewenum objaddref objrelease objhaskey " "objclone _insert _remove _minindex _maxindex _setcapacity _getcapacity _getaddress _newenum _addref " "_release _haskey _clone comobjcreate comobjget comobjconnect comobjerror comobjactive comobjenwrap " "comobjunwrap comobjparameter comobjmissing comobjtype comobjvalue comobjarray comobjquery comobjflags " "func getkeyname getkeyvk getkeysc isbyref exception", "allowsamelinecomments clipboardtimeout commentflag errorstdout escapechar hotkeyinterval " "hotkeymodifiertimeout hotstring if iftimeout ifwinactive ifwinexist include includeagain " "installkeybdhook installmousehook keyhistory ltrim maxhotkeysperinterval maxmem maxthreads " "maxthreadsbuffer maxthreadsperhotkey menumaskkey noenv notrayicon persistent singleinstance " "usehook warn winactivateforce", "shift lshift rshift alt lalt ralt control lcontrol rcontrol ctrl lctrl rctrl lwin rwin appskey " "altdown altup shiftdown shiftup ctrldown ctrlup lwindown lwinup rwindown rwinup lbutton rbutton " "mbutton wheelup wheeldown xbutton1 xbutton2 joy1 joy2 joy3 joy4 joy5 joy6 joy7 joy8 joy9 joy10 " "joy11 joy12 joy13 joy14 joy15 joy16 joy17 joy18 joy19 joy20 joy21 joy22 joy23 joy24 joy25 joy26 " "joy27 joy28 joy29 joy30 joy31 joy32 joyx joyy joyz joyr joyu joyv joypov joyname joybuttons " "joyaxes joyinfo space tab enter escape esc backspace bs delete del insert ins pgup pgdn home end " "up down left right printscreen ctrlbreak pause scrolllock capslock numlock numpad0 numpad1 numpad2 " "numpad3 numpad4 numpad5 numpad6 numpad7 numpad8 numpad9 numpadmult numpadadd numpadsub numpaddiv " "numpaddot numpaddel numpadins numpadclear numpadup numpaddown numpadleft numpadright numpadhome " "numpadend numpadpgup numpadpgdn numpadenter f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 f11 f12 f13 f14 f15 " "f16 f17 f18 f19 f20 f21 f22 f23 f24 browser_back browser_forward browser_refresh browser_stop " "browser_search browser_favorites browser_home volume_mute volume_down volume_up media_next " "media_prev media_stop media_play_pause launch_mail launch_media launch_app1 launch_app2 blind " "click raw wheelleft wheelright", "a_ahkpath a_ahkversion a_appdata a_appdatacommon a_autotrim a_batchlines a_caretx a_carety " "a_computername a_controldelay a_cursor a_dd a_ddd a_dddd a_defaultmousespeed a_desktop " "a_desktopcommon a_detecthiddentext a_detecthiddenwindows a_endchar a_eventinfo a_exitreason " "a_formatfloat a_formatinteger a_gui a_guievent a_guicontrol a_guicontrolevent a_guiheight " "a_guiwidth a_guix a_guiy a_hour a_iconfile a_iconhidden a_iconnumber a_icontip a_index " "a_ipaddress1 a_ipaddress2 a_ipaddress3 a_ipaddress4 a_isadmin a_iscompiled a_issuspended " "a_keydelay a_language a_lasterror a_linefile a_linenumber a_loopfield a_loopfileattrib " "a_loopfiledir a_loopfileext a_loopfilefullpath a_loopfilelongpath a_loopfilename " "a_loopfileshortname a_loopfileshortpath a_loopfilesize a_loopfilesizekb a_loopfilesizemb " "a_loopfiletimeaccessed a_loopfiletimecreated a_loopfiletimemodified a_loopreadline a_loopregkey " "a_loopregname a_loopregsubkey a_loopregtimemodified a_loopregtype a_mday a_min a_mm a_mmm " "a_mmmm a_mon a_mousedelay a_msec a_mydocuments a_now a_nowutc a_numbatchlines a_ostype " "a_osversion a_priorhotkey a_programfiles a_programs a_programscommon a_screenheight " "a_screenwidth a_scriptdir a_scriptfullpath a_scriptname a_sec a_space a_startmenu " "a_startmenucommon a_startup a_startupcommon a_stringcasesense a_tab a_temp a_thishotkey " "a_thismenu a_thismenuitem a_thismenuitempos a_tickcount a_timeidle a_timeidlephysical " "a_timesincepriorhotkey a_timesincethishotkey a_titlematchmode a_titlematchmodespeed " "a_username a_wday a_windelay a_windir a_workingdir a_yday a_year a_yweek a_yyyy " "clipboard clipboardall comspec errorlevel programfiles true false a_thisfunc a_thislabel " "a_ispaused a_iscritical a_isunicode a_ptrsize a_scripthwnd a_priorkey", "ltrim rtrim join ahk_id ahk_pid ahk_class ahk_group ahk_exe processname processpath minmax " "controllist statuscd filesystem setlabel alwaysontop mainwindow nomainwindow useerrorlevel " "altsubmit hscroll vscroll imagelist wantctrla wantf2 vis visfirst wantreturn backgroundtrans " "minimizebox maximizebox sysmenu toolwindow exstyle check3 checkedgray readonly notab lastfound " "lastfoundexist alttab shiftalttab alttabmenu alttabandmenu alttabmenudismiss controllisthwnd " "hwnd deref pow bitnot bitand bitor bitxor bitshiftleft bitshiftright sendandmouse mousemove " "mousemoveoff hkey_local_machine hkey_users hkey_current_user hkey_classes_root hkey_current_config " "hklm hku hkcu hkcr hkcc reg_sz reg_expand_sz reg_multi_sz reg_dword reg_qword reg_binary reg_link " "reg_resource_list reg_full_resource_descriptor reg_resource_requirements_list reg_dword_big_endian " "regex pixel mouse screen relative rgb low belownormal normal abovenormal high realtime between " "contains in is integer float number digit xdigit integerfast floatfast alpha upper lower alnum " "time date not or and topmost top bottom transparent transcolor redraw region id idlast count " "list capacity eject lock unlock label serial type status seconds minutes hours days read parse " "logoff close error single shutdown menu exit reload tray add rename check uncheck togglecheck " "enable disable toggleenable default nodefault standard nostandard color delete deleteall icon " "noicon tip click show edit progress hotkey text picture pic groupbox button checkbox radio " "dropdownlist ddl combobox statusbar treeview listbox listview datetime monthcal updown slider " "tab tab2 activex iconsmall tile report sortdesc nosort nosorthdr grid hdr autosize range xm ym " "ys xs xp yp font resize owner submit nohide minimize maximize restore noactivate na cancel " "destroy center margin owndialogs guiescape guiclose guisize guicontextmenu guidropfiles tabstop " "section wrap border top bottom buttons expand first lines number uppercase lowercase limit " "password multi group background bold italic strike underline norm theme caption delimiter flash " "style checked password hidden left right center section move focus hide choose choosestring text " "pos enabled disabled visible notimers interrupt priority waitclose unicode tocodepage fromcodepage " "yes no ok cancel abort retry ignore force on off all send wanttab monitorcount monitorprimary " "monitorname monitorworkarea pid this base extends __get __set __call __delete __new new " "useunsetlocal useunsetglobal useenv localsameasglobal", "", "" }; // ---------------------------------------------------------------------------- EDITLEXER lexAHK = { SCLEX_AHK, IDS_LEX_AHK, L"AutoHotkey Script", L"", L"", &KeyWords_AHK, { { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ SCE_AHK_DEFAULT, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {MULTI_STYLE(SCE_AHK_COMMENTLINE,SCE_AHK_COMMENTBLOCK,0,0)}, IDS_LEX_STR_63127, L"Comment", L"fore:#008000", L"" }, { {SCE_AHK_ESCAPE}, IDS_LEX_STR_63306, L"Escape", L"fore:#FF8000", L"" }, { {SCE_AHK_SYNOPERATOR}, IDS_LEX_STR_63307, L"Syntax Operator", L"fore:#7F200F", L"" }, { {SCE_AHK_EXPOPERATOR}, IDS_LEX_STR_63308, L"Expression Operator", L"fore:#FF4F00", L"" }, { {SCE_AHK_STRING}, IDS_LEX_STR_63131, L"String", L"fore:#404040", L"" }, { {SCE_AHK_NUMBER}, IDS_LEX_STR_63130, L"Number", L"fore:#2F4F7F", L"" }, { {SCE_AHK_IDENTIFIER}, IDS_LEX_STR_63129, L"Identifier", L"fore:#CF2F0F", L"" }, { {SCE_AHK_VARREF}, IDS_LEX_STR_63309, L"Variable Dereferencing", L"fore:#CF2F0F; back:#E4FFE4", L"" }, { {SCE_AHK_LABEL}, IDS_LEX_STR_63235, L"Label", L"fore:#000000; back:#FFFFA1", L"" }, { {SCE_AHK_WORD_CF}, IDS_LEX_STR_63310, L"Flow of Control", L"bold; fore:#480048", L"" }, { {SCE_AHK_WORD_CMD}, IDS_LEX_STR_63236, L"Command", L"fore:#004080", L"" }, { {SCE_AHK_WORD_FN}, IDS_LEX_STR_63277, L"Function", L"italic; fore:#0F707F", L"" }, { {SCE_AHK_WORD_DIR}, IDS_LEX_STR_63203, L"Directive", L"italic; fore:#F04020", L"" }, { {SCE_AHK_WORD_KB}, IDS_LEX_STR_63311, L"Keys & Buttons", L"bold; fore:#FF00FF", L"" }, { {SCE_AHK_WORD_VAR}, IDS_LEX_STR_63312, L"Built-In Variables", L"italic; fore:#CF00CF", L"" }, { {SCE_AHK_WORD_SP}, IDS_LEX_STR_63280, L"Special", L"italic; fore:#0000FF", L"" }, //{ {SCE_AHK_WORD_UD}, IDS_LEX_STR_63106, L"User Defined", L"fore:#800020", L"" }, { {SCE_AHK_VARREFKW}, IDS_LEX_STR_63313, L"Variable Keyword", L"italic; fore:#CF00CF; back:#F9F9FF", L"" }, { {SCE_AHK_ERROR}, IDS_LEX_STR_63261, L"Error", L"back:#FFC0C0", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>scintilla/src/CharacterCategoryMap.h<|end_filename|> // Scintilla source code edit control /** @file CharacterCategoryMap.h ** Returns the Unicode general category of a character. ** Similar code to Lexilla's lexilla/lexlib/CharacterCategory.h but renamed ** to avoid problems with builds that statically include both Scintilla and Lexilla. **/ // Copyright 2013 by <NAME> <<EMAIL>> // The License.txt file describes the conditions under which this software may be distributed. #ifndef CHARACTERCATEGORYMAP_H #define CHARACTERCATEGORYMAP_H namespace Scintilla::Internal { enum CharacterCategory { ccLu, ccLl, ccLt, ccLm, ccLo, ccMn, ccMc, ccMe, ccNd, ccNl, ccNo, ccPc, ccPd, ccPs, ccPe, ccPi, ccPf, ccPo, ccSm, ccSc, ccSk, ccSo, ccZs, ccZl, ccZp, ccCc, ccCf, ccCs, ccCo, ccCn }; CharacterCategory CategoriseCharacter(int character); // Common definitions of allowable characters in identifiers from UAX #31. bool IsIdStart(int character); bool IsIdContinue(int character); bool IsXidStart(int character); bool IsXidContinue(int character); class CharacterCategoryMap { private: std::vector<unsigned char> dense; public: CharacterCategoryMap(); CharacterCategory CategoryFor(int character) const { if (static_cast<size_t>(character) < dense.size()) { return static_cast<CharacterCategory>(dense[character]); } else { // binary search through ranges return CategoriseCharacter(character); } } int Size() const noexcept; void Optimize(int countCharacters); }; } #endif <|start_filename|>Version.cmd<|end_filename|> :: - USAGE: do not wrap by 'call' "%~dpn0.cmd" (continue parent shell after exit /b 0) :: - Admin rights: :: PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%~dpn0.ps1""' -Verb RunAs}" @echo off setlocal enableextensions set SCRIPTNAME=%~dpn0.ps1 set ARGS=%* if ["%~1"] neq [""] call :ESCAPE_ARGS :POWERSHELL PowerShell.exe -NoProfile -NonInteractive -NoLogo -ExecutionPolicy Unrestricted -Command "& { $ErrorActionPreference = 'Stop'; & '%SCRIPTNAME%' @args; Exit $LastExitCode }" %ARGS% set EXITCODE=%ERRORLEVEL% ::ECHO ERRORLEVEL=%EXITCODE% :: Pause of 4 seconds to verify the "Notepad3 version number:" before exiting :: ============================================================================ ping -n 5 127.0.0.1>nul goto :END :ESCAPE_ARGS set ARGS=%ARGS:"=\"% set ARGS=%ARGS:`=``% set ARGS=%ARGS:'=`'% set ARGS=%ARGS:$=`$% set ARGS=%ARGS:{=`}% set ARGS=%ARGS:}=`}% set ARGS=%ARGS:(=`(% set ARGS=%ARGS:)=`)% set ARGS=%ARGS:,=`,% set ARGS=%ARGS:^%=% goto:eof :END :: - make EXITCODE survive 'endlocal' endlocal & set EXITCODE=%EXITCODE% :: -call exit only in case of if not [%EXITCODE%]==[0] exit /b %EXITCODE% <|start_filename|>src/StyleLexers/styleLexBASH.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_BASH = { "alias ar asa awk banner basename bash bc bdiff break bunzip2 bzip2 cal calendar case cat cc cd chgrp chmod " "chown chroot cksum clear cmp col comm compress continue cp cpio crypt csplit ctags cut date dc dd declare " "deroff dev df diff diff3 dir dircmp dircolors dirname do done du echo ed egrep elif else env esac eval ex " "exec exit expand export expr factor false fc fgrep fi file find fmt fold for function functions getconf " "getopt getopts grep gres groups hash head help history hostid iconv id if in install integer jobs join " "kill lc let line link ln local logname look ls m4 mail mailx make man md5sum mkdir mkfifo mknod more mt " "mv newgrp nice nl nm nohup ntps od pack paste patch pathchk pax pcat perl pg pinky pr print printenv " "printf ps ptx pwd read readlink readonly red return rev rm rmdir sed select seq set sh sha1sum shift " "shred size sleep sort spell split start stat stop strings strip stty su sum suspend sync tac tail tar tee " "test then time times touch tr trap true tsort tty type typeset ulimit umask unalias uname uncompress " "unexpand uniq unlink unpack unset until users uudecode uuencode vdir vi vim vpax wait wc whence which " "while who whoami wpaste wstart xargs yes zcat", NULL, }; EDITLEXER lexBASH = { SCLEX_BASH, "bash", IDS_LEX_SHELL_SCR, L"Shell Script", L"sh; csh; zsh; bash; tcsh; m4; in; \\^mozconfig$", L"", &KeyWords_BASH, { { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_SH_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {SCE_SH_ERROR}, IDS_LEX_STR_63261, L"Error", L"", L"" }, { {SCE_SH_COMMENTLINE}, IDS_LEX_STR_63127, L"Comment", L"fore:#008000", L"" }, { {SCE_SH_NUMBER}, IDS_LEX_STR_63130, L"Number", L"fore:#008080", L"" }, { {SCE_SH_WORD}, IDS_LEX_STR_63128, L"Keyword", L"fore:#0000FF", L"" }, { {SCE_SH_STRING}, IDS_LEX_STR_63211, L"String Double Quoted", L"fore:#008080", L"" }, { {SCE_SH_CHARACTER}, IDS_LEX_STR_63212, L"String Single Quoted", L"fore:#800080", L"" }, { {SCE_SH_OPERATOR}, IDS_LEX_STR_63132, L"Operator", L"", L"" }, { {SCE_SH_IDENTIFIER}, IDS_LEX_STR_63129, L"Identifier", L"", L"" }, { {SCE_SH_SCALAR}, IDS_LEX_STR_63360, L"Scalar", L"fore:#808000", L"" }, { {SCE_SH_PARAM}, IDS_LEX_STR_63281, L"Parameter Expansion", L"fore:#808000; back:#FFFF99", L"" }, { {SCE_SH_BACKTICKS}, IDS_LEX_STR_63221, L"Back Ticks", L"fore:#FF0080", L"" }, { {SCE_SH_HERE_DELIM}, IDS_LEX_STR_63223, L"Here-Doc (Delimiter)", L"", L"" }, { {SCE_SH_HERE_Q}, IDS_LEX_STR_63224, L"Here-Doc (Single Quoted, q)", L"fore:#008080", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>lexilla/lexers_x/LexerUtils.h<|end_filename|> #pragma once #include <vector> #include "CharSetX.h" namespace Lexilla { // TODO: change packed line state to NestedStateStack (convert lexer to class). template<int valueBit, int maxStateCount, int countBit, int baseStyle> int PackLineState(const std::vector<int>& states) noexcept { constexpr size_t countMask = (1 << countBit) - 1; size_t index = states.size(); int count = static_cast<int>(sci::min(index, countMask)); int lineState = count; lineState <<= countBit; count = sci::min(count, maxStateCount); while (count != 0) { --count; --index; int state = states[index]; if (state) { state -= baseStyle; } lineState = (lineState << valueBit) | state; } return lineState; } template<int valueBit, int maxStateCount, int countBit, int baseStyle> void UnpackLineState(int lineState, std::vector<int>& states) { constexpr int valueMask = (1 << valueBit) - 1; constexpr int countMask = (1 << countBit) - 1; int count = lineState & countMask; lineState >>= countBit; count = sci::min(count, maxStateCount); while (count != 0) { int state = lineState & valueMask; if (state) { state += baseStyle; } states.push_back(state); lineState >>= valueBit; --count; } } enum { DefaultNestedStateValueBit = 3, DefaultMaxNestedStateCount = 4, DefaultNestedStateCountBit = 3, DefaultNestedStateBaseStyle = 10, }; inline int PackLineState(const std::vector<int>& states) noexcept { return PackLineState<DefaultNestedStateValueBit, DefaultMaxNestedStateCount, DefaultNestedStateCountBit, DefaultNestedStateBaseStyle>(states); } inline void UnpackLineState(int lineState, std::vector<int>& states) { UnpackLineState<DefaultNestedStateValueBit, DefaultMaxNestedStateCount, DefaultNestedStateCountBit, DefaultNestedStateBaseStyle>(lineState, states); } inline int TryTakeAndPop(std::vector<int>& states, int value = 0) { if (!states.empty()) { value = states.back(); states.pop_back(); } return value; } inline int TakeAndPop(std::vector<int>& states) { const int value = states.back(); states.pop_back(); return value; } inline int TryPopAndPeek(std::vector<int>& states, int value = 0) { if (!states.empty()) { states.pop_back(); if (!states.empty()) { value = states.back(); } } return value; } inline int GetDocNextChar(LexAccessor& styler, const StyleContext& sc, bool ignoreCurrent = false) noexcept { if (!ignoreCurrent && !IsWhiteSpace(sc.ch)) { return sc.ch; } if (!IsWhiteSpace(sc.chNext)) { return sc.chNext; } Sci_Position pos = sc.currentPos + 2; do { const char ch = styler.SafeGetCharAt(pos); if (!IsWhiteSpace(ch)) { return ch; } ++pos; } while (true); } inline int GetLineNextChar(LexAccessor& styler, const StyleContext& sc, bool ignoreCurrent = false) noexcept { if (!ignoreCurrent && !IsWhiteSpace(sc.ch)) { return sc.ch; } if (sc.currentPos + 1 == static_cast<Sci_PositionU>(sc.lineStartNext)) { return '\0'; } if (!IsWhiteSpace(sc.chNext)) { return sc.chNext; } Sci_Position pos = sc.currentPos + 2; while (pos < sc.lineStartNext) { const char ch = styler.SafeGetCharAt(pos); if (!IsWhiteSpace(ch)) { return ch; } ++pos; } return '\0'; } void BacktrackToStart(const LexAccessor& styler, int stateMask, Sci_PositionU& startPos, Sci_Position& lengthDoc, int& initStyle) noexcept; void LookbackNonWhite(LexAccessor& styler, Sci_PositionU startPos, int maxSpaceStyle, int& chPrevNonWhite, int& stylePrevNonWhite); Sci_PositionU CheckBraceOnNextLine(LexAccessor& styler, Sci_Position line, int operatorStyle, int maxSpaceStyle, int ignoreStyle = 0) noexcept; bool HighlightTaskMarker(StyleContext& sc, int& visibleChars, int visibleCharsBefore, int markerStyle); #if 0 // nested state stack on each line using NestedStateStack = std::map<Sci_Line, std::vector<int>>; inline void GetNestedState(const NestedStateStack& stateStack, Sci_Line line, std::vector<int>& states) { const auto it = stateStack.find(line); if (it != stateStack.end()) { states = it->second; } } inline void SaveNestedState(NestedStateStack& stateStack, Sci_Line line, const std::vector<int>& states) { if (states.empty()) { auto it = stateStack.find(line); if (it != stateStack.end()) { stateStack.erase(it); } } else { stateStack[line] = states; } } #endif } <|start_filename|>src/StyleLexers/styleLexJSON.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_JSON = { "+Infinity -Infinity Infinity NaN false null true", "@base @container @context @direction @graph @id @import @included @index @json @language @list @nest @none " "@prefix @propagate @protected @reverse @set @type @value @version @vocab", NULL, }; EDITLEXER lexJSON = { SCLEX_JSON, "json", IDS_LEX_JSON, L"JSON", L"json; har; ipynb; wxcp; jshintrc; eslintrc; babelrc; prettierrc; stylelintrc; jsonld; jsonc; arcconfig; arclint; jscop", L"", &KeyWords_JSON, { { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_JSON_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {MULTI_STYLE(SCE_JSON_LINECOMMENT,SCE_JSON_BLOCKCOMMENT,0,0)}, IDS_LEX_STR_63127, L"Comment", L"fore:#646464", L"" }, { {SCE_JSON_KEYWORD}, IDS_LEX_STR_63128, L"Keyword", L"bold; fore:#957000", L"" }, { {SCE_JSON_LDKEYWORD}, IDS_LEX_STR_63365, L"LD Keyword", L"bold; fore:#A61D04", L"" }, { {MULTI_STYLE(SCE_JSON_STRING,SCE_JSON_STRINGEOL,0,0)}, IDS_LEX_STR_63131, L"String", L"fore:#008000", L"" }, //{ {SCE_C_REGEX}, IDS_LEX_STR_63135, L"Regex", L"fore:#006633; back:#FFF1A8", L"" }, { {SCE_JSON_NUMBER}, IDS_LEX_STR_63130, L"Number", L"fore:#FF0000", L"" }, { {SCE_JSON_OPERATOR}, IDS_LEX_STR_63132, L"Operator", L"fore:#B000B0", L"" }, { {SCE_JSON_PROPERTYNAME}, IDS_LEX_STR_63364, L"Property Name", L"fore:#002697", L"" }, { {SCE_JSON_ESCAPESEQUENCE}, IDS_LEX_STR_63366, L"ESC Sequence", L"fore:#0B982E", L"" }, { {SCE_JSON_ERROR}, IDS_LEX_STR_63252, L"Parsing Error", L"fore:#FFFF00; back:#A00000; eolfilled", L"" }, EDITLEXER_SENTINEL } }; /* # String style.json.2=fore:#7F0000 # Unclosed string SCE_JSON_STRINGEOL style.json.3=fore:#FFFFFF,back:#FF0000,eolfilled # Property name SCE_JSON_PROPERTYNAME style.json.4=fore:#880AE8 # Escape sequence SCE_JSON_ESCAPESEQUENCE style.json.5=fore:#0B982E # Line comment SCE_JSON_LINECOMMENT style.json.6=fore:#05BBAE,italic # Block comment SCE_JSON_BLOCKCOMMENT style.json.7=$(style.json.6) # Operator SCE_JSON_OPERATOR style.json.8=fore:#18644A # URL/IRI SCE_JSON_URI style.json.9=fore:#0000FF # JSON-LD compact IRI SCE_JSON_COMPACTIRI style.json.10=fore:#D137C1 # JSON keyword SCE_JSON_KEYWORD style.json.11=fore:#0BCEA7,bold # JSON-LD keyword SCE_JSON_LDKEYWORD style.json.12=fore:#EC2806 # Parsing error SCE_JSON_ERROR style.json.13=fore:#FFFFFF,back:#FF0000 */ <|start_filename|>test/test_files/StyleLexers/styleLexJAVA/DecryptNotepad3.java<|end_filename|> /* * Notepad3 format decrypter * * * This standalone program decrypts files that were encrypted in Notepad3's simple format. * * The intent of this program is to provide an independent, robust implementation for handling the file format, * in case Notepad3 (or that author's own small standalone decrypter) is inaccessible or has errors. * * Prerequisites: compiled class (javac DecryptNotepad3.java => DecryptNotepad3.class) * * Usage: java DecryptNotepad3 InputFile [-m] Passphrase * Options: * -m: Use master key (only applicable for files with master key) * Examples: * java DecryptNotepad3 myencryptedfile.bin <PASSWORD> * java DecryptNotepad3 myencryptedfile.bin -m masterPass<PASSWORD> * (Prints to standard output) * * * Copyright (c) 2017 Project Nayuki * All rights reserved. Contact Nayuki for licensing. * https://www.nayuki.io/page/notepadcrypt-format-decryptor-java * Old: http://nayuki.eigenstate.org/page/notepadcrypt-format-decryptor-java * * Adaption to Notepad3 by RaiKoHoff * * NotepadCrypt resources: * - http://www.andromeda.com/people/ddyer/notepad/NotepadCrypt.html * - http://www.andromeda.com/people/ddyer/notepad/NotepadCrypt-technotes.html * * Notepad3 resources: * - https://www.rizonesoft.com/downloads/notepad3/ * - https://www.rizonesoft.com/documents/notepad3/ * - https://github.com/rizonesoft/Notepad3 */ import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import static java.lang.Integer.rotateRight; public final class DecryptNotepad3 { /* Main functions */ public static void main(String[] args) throws IOException { // Get arguments File inputFile; String passphrase; boolean useMasterKey; if (args.length == 2) { useMasterKey = false; passphrase = args[1]; } else if (args.length == 3 && args[1].equals("-m")) { useMasterKey = true; passphrase = args[2]; } else { System.err.println("Usage: java DecryptNotepad3 InputFile [-m] Passphrase"); System.err.println(" -m: Use master key (only applicable for files with master key)"); System.exit(1); return; } inputFile = new File(args[0]); // Read file byte[] data = new byte[(int)inputFile.length()]; InputStream in = new FileInputStream(inputFile); try { if (data.length > 0 && in.read(data) < data.length) throw new IOException("Unexpected file size"); if (in.read(data) != -1) throw new IOException("Unexpected file size"); } finally { in.close(); } // Decrypt and write byte[] plaintext; try { plaintext = decryptFileData(data, passphrase.getBytes("US-ASCII"), useMasterKey); } catch (IllegalArgumentException e) { System.err.println("Error: " + e.getMessage()); System.exit(1); return; } System.out.write(plaintext); } static byte[] decryptFileData(byte[] fileData, byte[] passphrase, boolean useMasterKey) { if (fileData.length == 0) return fileData; // Notepad3 produces an empty file when trying to encrypt an empty text file // Parse file format boolean hasMasterKey; if (toInt32(fileData, 0) != 0x04030201) throw new IllegalArgumentException("Unsupported file format"); switch (toInt32(fileData, 4)) { case 0x01000000: hasMasterKey = false; break; case 0x02000000: hasMasterKey = true; break; default: throw new IllegalArgumentException("Unsupported encryption format"); } // Decrypt text byte[] cipherKey = getSha256Hash(passphrase); byte[] initVec = Arrays.copyOfRange(fileData, 8, 24); byte[] ciphertext = Arrays.copyOfRange(fileData, hasMasterKey ? 72 : 24, fileData.length); if (useMasterKey) { if (!hasMasterKey) throw new IllegalArgumentException("Master key mode requested on file data with no master key"); byte[] iv = Arrays.copyOfRange(fileData, 24, 40); byte[] fileKey = Arrays.copyOfRange(fileData, 40, 72); Aes.decryptCbcMode(fileKey, cipherKey, iv); cipherKey = fileKey; } return decryptWithPadding(ciphertext, cipherKey, initVec); } /* Utility functions */ private static byte[] decryptWithPadding(byte[] ciphertext, byte[] key, byte[] initVec) { // Decrypt message if (ciphertext.length % 16 != 0) throw new IllegalArgumentException("Invalid file length"); byte[] plaintext = ciphertext.clone(); Aes.decryptCbcMode(plaintext, key, initVec); // Check padding (rejections are always correct, but false acceptance has 1/255 chance) int padding = plaintext[plaintext.length - 1]; if (padding < 1 || padding > 16) throw new IllegalArgumentException("Incorrect key or corrupt data"); for (int i = 1; i <= padding; i++) { if (plaintext[plaintext.length - i] != padding) throw new IllegalArgumentException("Incorrect key or corrupt data"); } // Strip padding return Arrays.copyOfRange(plaintext, 0, plaintext.length - padding); } static int toInt32(byte[] b, int off) { // Big endian return (b[off + 0] & 0xFF) << 24 | (b[off + 1] & 0xFF) << 16 | (b[off + 2] & 0xFF) << 8 | (b[off + 3] & 0xFF) << 0; } /* Cryptography library functions */ private static byte[] getSha256Hash(byte[] msg) { if (msg.length > Integer.MAX_VALUE / 8) throw new IllegalArgumentException("Message too large for this implementation"); // Add 1 byte for termination, 8 bytes for length, then round up to multiple of block size (64) byte[] padded = Arrays.copyOf(msg, (msg.length + 1 + 8 + 63) / 64 * 64); padded[msg.length] = (byte)0x80; for (int i = 0; i < 4; i++) padded[padded.length - 1 - i] = (byte)((msg.length * 8) >>> (i * 8)); // Table of round constants final int[] K = { 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2, }; // Compress each block int[] state = {0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19}; for (int off = 0; off < padded.length; off += 64) { int[] schedule = new int[64]; for (int i = 0; i < 16; i++) schedule[i] = toInt32(padded, off + i * 4); for (int i = 16; i < 64; i++) { int x = schedule[i - 15]; int y = schedule[i - 2]; schedule[i] = schedule[i - 16] + schedule[i - 7] + (rotateRight(x, 7) ^ rotateRight(x, 18) ^ (x >>> 3)) + (rotateRight(y, 17) ^ rotateRight(y, 19) ^ (y >>> 10)); } int a = state[0], b = state[1], c = state[2], d = state[3]; int e = state[4], f = state[5], g = state[6], h = state[7]; for (int i = 0; i < 64; i++) { int t1 = h + (rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + schedule[i]; int t2 = (rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22)) + ((a & b) ^ (a & c) ^ (b & c)); h = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2; } state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; state[5] += f; state[6] += g; state[7] += h; } // Serialize state as result byte[] hash = new byte[state.length * 4]; for (int i = 0; i < hash.length; i++) hash[i] = (byte)(state[i / 4] >>> ((3 - i % 4) * 8)); return hash; } } final class Aes { private static final int BLOCK_LEN = 16; // Do not modify public static void decryptCbcMode(byte[] msg, byte[] key, byte[] initVec) { if (msg.length % BLOCK_LEN != 0 || initVec.length != BLOCK_LEN) throw new IllegalArgumentException("Message is not a multiple of block length"); Aes cipher = new Aes(key); byte[] prevCiphertextBlock = initVec; for (int off = 0; off < msg.length; off += BLOCK_LEN) { byte[] curCiphertextBlock = Arrays.copyOfRange(msg, off, off + BLOCK_LEN); cipher.decryptBlock(msg, off); for (int i = 0; i < BLOCK_LEN; i++) msg[off + i] ^= prevCiphertextBlock[i]; prevCiphertextBlock = curCiphertextBlock; } } private byte[][] keySchedule; public Aes(byte[] key) { if (key.length < 4 || key.length % 4 != 0) throw new IllegalArgumentException("Invalid key length"); // Expand key into key schedule int nk = key.length / 4; int rounds = Math.max(nk, 4) + 6; int[] w = new int[(rounds + 1) * 4]; // Key schedule for (int i = 0; i < nk; i++) w[i] = DecryptNotepad3.toInt32(key, i * 4); byte rcon = 1; for (int i = nk; i < w.length; i++) { // rcon = 2^(i/nk) mod 0x11B int tp = w[i - 1]; if (i % nk == 0) { tp = subInt32Bytes(rotateRight(tp, 24)) ^ (rcon << 24); rcon = multiply(rcon, (byte)0x02); } else if (nk > 6 && i % nk == 4) tp = subInt32Bytes(tp); w[i] = w[i - nk] ^ tp; } keySchedule = new byte[w.length / 4][BLOCK_LEN]; for (int i = 0; i < keySchedule.length; i++) { for (int j = 0; j < keySchedule[i].length; j++) keySchedule[i][j] = (byte)(w[i * 4 + j / 4] >>> ((3 - j % 4) * 8)); } } public void decryptBlock(byte[] msg, int off) { // Initial round byte[] temp0 = Arrays.copyOfRange(msg, off, off + BLOCK_LEN); addRoundKey(temp0, keySchedule[keySchedule.length - 1]); byte[] temp1 = new byte[BLOCK_LEN]; for (int i = 0; i < 4; i++) { // Shift rows inverse and sub bytes inverse for (int j = 0; j < 4; j++) temp1[i + j * 4] = SBOX_INVERSE[temp0[i + (j - i + 4) % 4 * 4] & 0xFF]; } // Middle rounds for (int k = keySchedule.length - 2; k >= 1; k--) { addRoundKey(temp1, keySchedule[k]); for (int i = 0; i < BLOCK_LEN; i += 4) { // Mix columns inverse for (int j = 0; j < 4; j++) { temp0[i + j] = (byte)( multiply(temp1[i + (j + 0) % 4], (byte)0x0E) ^ multiply(temp1[i + (j + 1) % 4], (byte)0x0B) ^ multiply(temp1[i + (j + 2) % 4], (byte)0x0D) ^ multiply(temp1[i + (j + 3) % 4], (byte)0x09)); } } for (int i = 0; i < 4; i++) { // Shift rows inverse and sub bytes inverse for (int j = 0; j < 4; j++) temp1[i + j * 4] = SBOX_INVERSE[temp0[i + (j - i + 4) % 4 * 4] & 0xFF]; } } // Final round addRoundKey(temp1, keySchedule[0]); System.arraycopy(temp1, 0, msg, off, temp1.length); } private static void addRoundKey(byte[] block, byte[] key) { for (int i = 0; i < BLOCK_LEN; i++) block[i] ^= key[i]; } /* Utilities */ private static byte[] SBOX = new byte[256]; private static byte[] SBOX_INVERSE = new byte[256]; // Initialize the S-box and inverse static { for (int i = 0; i < 256; i++) { byte tp = reciprocal((byte)i); byte s = (byte)(tp ^ rotateByteLeft(tp, 1) ^ rotateByteLeft(tp, 2) ^ rotateByteLeft(tp, 3) ^ rotateByteLeft(tp, 4) ^ 0x63); SBOX[i] = s; SBOX_INVERSE[s & 0xFF] = (byte)i; } } private static byte multiply(byte x, byte y) { // Russian peasant multiplication byte z = 0; for (int i = 0; i < 8; i++) { z ^= x * ((y >>> i) & 1); x = (byte)((x << 1) ^ (((x >>> 7) & 1) * 0x11B)); } return z; } private static byte reciprocal(byte x) { if (x == 0) return 0; else { for (byte y = 1; y != 0; y++) { if (multiply(x, y) == 1) return y; } throw new AssertionError(); } } private static byte rotateByteLeft(byte x, int y) { if (y < 0 || y >= 8) throw new IllegalArgumentException("Input out of range"); return (byte)((x << y) | ((x & 0xFF) >>> (8 - y))); } private static int subInt32Bytes(int x) { return (SBOX[x >>> 24 & 0xFF] & 0xFF) << 24 | (SBOX[x >>> 16 & 0xFF] & 0xFF) << 16 | (SBOX[x >>> 8 & 0xFF] & 0xFF) << 8 | (SBOX[x >>> 0 & 0xFF] & 0xFF) << 0; } } <|start_filename|>grepWinNP3/sktoolslib_mod/IconBitmapUtils.cpp<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2013, 2020 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "IconBitmapUtils.h" #pragma comment(lib, "uxtheme.lib") IconBitmapUtils::IconBitmapUtils() { } IconBitmapUtils::~IconBitmapUtils() { std::map<UINT, HBITMAP>::iterator it; for (it = bitmaps.begin(); it != bitmaps.end(); ++it) { ::DeleteObject(it->second); } bitmaps.clear(); } HBITMAP IconBitmapUtils::IconToBitmap(HINSTANCE hInst, UINT uIcon) { std::map<UINT, HBITMAP>::iterator bitmap_it = bitmaps.lower_bound(uIcon); if (bitmap_it != bitmaps.end() && bitmap_it->first == uIcon) return bitmap_it->second; HICON hIcon = (HICON)LoadImage(hInst, MAKEINTRESOURCE(uIcon), IMAGE_ICON, 12, 12, LR_DEFAULTCOLOR); if (!hIcon) return NULL; RECT rect; rect.right = ::GetSystemMetrics(SM_CXMENUCHECK); rect.bottom = ::GetSystemMetrics(SM_CYMENUCHECK); rect.left = rect.top = 0; HWND desktop = ::GetDesktopWindow(); if (desktop == NULL) { DestroyIcon(hIcon); return NULL; } HDC screen_dev = ::GetDC(desktop); if (screen_dev == NULL) { DestroyIcon(hIcon); return NULL; } // Create a compatible DC HDC dst_hdc = ::CreateCompatibleDC(screen_dev); if (dst_hdc == NULL) { DestroyIcon(hIcon); ::ReleaseDC(desktop, screen_dev); return NULL; } // Create a new bitmap of icon size HBITMAP bmp = ::CreateCompatibleBitmap(screen_dev, rect.right, rect.bottom); if (bmp == NULL) { DestroyIcon(hIcon); ::DeleteDC(dst_hdc); ::ReleaseDC(desktop, screen_dev); return NULL; } // Select it into the compatible DC HBITMAP old_dst_bmp = (HBITMAP)::SelectObject(dst_hdc, bmp); if (old_dst_bmp == NULL) { DestroyIcon(hIcon); ::DeleteDC(dst_hdc); ::ReleaseDC(desktop, screen_dev); return NULL; } // Fill the background of the compatible DC with the white color // that is taken by menu routines as transparent ::SetBkColor(dst_hdc, RGB(255, 255, 255)); ::ExtTextOut(dst_hdc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL); // Draw the icon into the compatible DC ::DrawIconEx(dst_hdc, 0, 0, hIcon, rect.right, rect.bottom, 0, NULL, DI_NORMAL); // Restore settings ::SelectObject(dst_hdc, old_dst_bmp); ::DeleteDC(dst_hdc); ::ReleaseDC(desktop, screen_dev); DestroyIcon(hIcon); if (bmp) bitmaps.insert(bitmap_it, std::make_pair(uIcon, bmp)); return bmp; } HBITMAP IconBitmapUtils::IconToBitmapPARGB32(HINSTANCE hInst, UINT uIcon) { std::map<UINT, HBITMAP>::iterator bitmap_it = bitmaps.lower_bound(uIcon); if (bitmap_it != bitmaps.end() && bitmap_it->first == uIcon) return bitmap_it->second; HICON hIcon = (HICON)LoadImage(hInst, MAKEINTRESOURCE(uIcon), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR); HBITMAP hBmp = IconToBitmapPARGB32(hIcon); DestroyIcon(hIcon); if (hBmp) bitmaps.insert(bitmap_it, std::make_pair(uIcon, hBmp)); return hBmp; } HBITMAP IconBitmapUtils::IconToBitmapPARGB32(HICON hIcon) { if (!hIcon) return NULL; SIZE sizIcon; sizIcon.cx = GetSystemMetrics(SM_CXSMICON); sizIcon.cy = GetSystemMetrics(SM_CYSMICON); RECT rcIcon; SetRect(&rcIcon, 0, 0, sizIcon.cx, sizIcon.cy); HBITMAP hBmp = NULL; HDC hdcDest = CreateCompatibleDC(NULL); if (hdcDest) { if (SUCCEEDED(Create32BitHBITMAP(hdcDest, &sizIcon, NULL, &hBmp))) { HBITMAP hbmpOld = (HBITMAP)SelectObject(hdcDest, hBmp); if (hbmpOld) { BLENDFUNCTION bfAlpha = {AC_SRC_OVER, 0, 255, AC_SRC_ALPHA}; BP_PAINTPARAMS paintParams = {0}; paintParams.cbSize = sizeof(paintParams); paintParams.dwFlags = BPPF_ERASE; paintParams.pBlendFunction = &bfAlpha; HDC hdcBuffer; HPAINTBUFFER hPaintBuffer = BeginBufferedPaint(hdcDest, &rcIcon, BPBF_DIB, &paintParams, &hdcBuffer); if (hPaintBuffer) { if (DrawIconEx(hdcBuffer, 0, 0, hIcon, sizIcon.cx, sizIcon.cy, 0, NULL, DI_NORMAL)) { // If icon did not have an alpha channel we need to convert buffer to PARGB ConvertBufferToPARGB32(hPaintBuffer, hdcDest, hIcon, sizIcon); } // This will write the buffer contents to the destination bitmap EndBufferedPaint(hPaintBuffer, TRUE); } SelectObject(hdcDest, hbmpOld); } } DeleteDC(hdcDest); } return hBmp; } HRESULT IconBitmapUtils::Create32BitHBITMAP(HDC hdc, const SIZE *psize, __deref_opt_out void **ppvBits, __out HBITMAP *phBmp) { if (psize == 0) return E_INVALIDARG; if (phBmp == 0) return E_POINTER; *phBmp = NULL; BITMAPINFO bmi; SecureZeroMemory(&bmi, sizeof(bmi)); bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biCompression = BI_RGB; bmi.bmiHeader.biWidth = psize->cx; bmi.bmiHeader.biHeight = psize->cy; bmi.bmiHeader.biBitCount = 32; HDC hdcUsed = hdc ? hdc : GetDC(NULL); if (hdcUsed) { *phBmp = CreateDIBSection(hdcUsed, &bmi, DIB_RGB_COLORS, ppvBits, NULL, 0); if (hdc != hdcUsed) { ReleaseDC(NULL, hdcUsed); } } return (NULL == *phBmp) ? E_OUTOFMEMORY : S_OK; } HRESULT IconBitmapUtils::ConvertBufferToPARGB32(HPAINTBUFFER hPaintBuffer, HDC hdc, HICON hicon, SIZE &sizIcon) { RGBQUAD *prgbQuad; int cxRow; HRESULT hr = GetBufferedPaintBits(hPaintBuffer, &prgbQuad, &cxRow); if (SUCCEEDED(hr)) { Gdiplus::ARGB *pargb = reinterpret_cast<Gdiplus::ARGB *>(prgbQuad); if (!HasAlpha(pargb, sizIcon, cxRow)) { ICONINFO info; if (GetIconInfo(hicon, &info)) { if (info.hbmMask) { hr = ConvertToPARGB32(hdc, pargb, info.hbmMask, sizIcon, cxRow); } DeleteObject(info.hbmColor); DeleteObject(info.hbmMask); } } } return hr; } bool IconBitmapUtils::HasAlpha(__in Gdiplus::ARGB *pargb, SIZE &sizImage, int cxRow) { ULONG cxDelta = cxRow - sizImage.cx; for (ULONG y = sizImage.cy; y; --y) { for (ULONG x = sizImage.cx; x; --x) { if (*pargb++ & 0xFF000000) { return true; } } pargb += cxDelta; } return false; } HRESULT IconBitmapUtils::ConvertToPARGB32(HDC hdc, __inout Gdiplus::ARGB *pargb, HBITMAP hbmp, SIZE &sizImage, int cxRow) { BITMAPINFO bmi; SecureZeroMemory(&bmi, sizeof(bmi)); bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biCompression = BI_RGB; bmi.bmiHeader.biWidth = sizImage.cx; bmi.bmiHeader.biHeight = sizImage.cy; bmi.bmiHeader.biBitCount = 32; HANDLE hHeap = GetProcessHeap(); void * pvBits = HeapAlloc(hHeap, 0, bmi.bmiHeader.biWidth * 4 * bmi.bmiHeader.biHeight); if (pvBits == 0) return E_OUTOFMEMORY; HRESULT hr = E_UNEXPECTED; if (GetDIBits(hdc, hbmp, 0, bmi.bmiHeader.biHeight, pvBits, &bmi, DIB_RGB_COLORS) == bmi.bmiHeader.biHeight) { ULONG cxDelta = cxRow - bmi.bmiHeader.biWidth; Gdiplus::ARGB *pargbMask = static_cast<Gdiplus::ARGB *>(pvBits); for (ULONG y = bmi.bmiHeader.biHeight; y; --y) { for (ULONG x = bmi.bmiHeader.biWidth; x; --x) { if (*pargbMask++) { // transparent pixel *pargb++ = 0; } else { // opaque pixel *pargb++ |= 0xFF000000; } } pargb += cxDelta; } hr = S_OK; } HeapFree(hHeap, 0, pvBits); return hr; } <|start_filename|>scintilla/src/RunStyles.h<|end_filename|> /** @file RunStyles.h ** Data structure used to store sparse styles. **/ // Copyright 1998-2007 by <NAME> <<EMAIL>> // The License.txt file describes the conditions under which this software may be distributed. /// Styling buffer using one element for each run rather than using /// a filled buffer. #ifndef RUNSTYLES_H #define RUNSTYLES_H namespace Scintilla::Internal { // Return for RunStyles::FillRange reports if anything was changed and the // range that was changed. This may be trimmed from the requested range // when some of the requested range already had the requested value. template <typename DISTANCE> struct FillResult { bool changed; DISTANCE position; DISTANCE fillLength; }; template <typename DISTANCE, typename STYLE> class RunStyles { private: std::unique_ptr<Partitioning<DISTANCE>> starts; std::unique_ptr<SplitVector<STYLE>> styles; DISTANCE RunFromPosition(DISTANCE position) const noexcept; DISTANCE SplitRun(DISTANCE position); void RemoveRun(DISTANCE run); void RemoveRunIfEmpty(DISTANCE run); void RemoveRunIfSameAsPrevious(DISTANCE run); public: RunStyles(); // Deleted so RunStyles objects can not be copied. RunStyles(const RunStyles &) = delete; RunStyles(RunStyles &&) = delete; void operator=(const RunStyles &) = delete; void operator=(RunStyles &&) = delete; ~RunStyles(); DISTANCE Length() const noexcept; STYLE ValueAt(DISTANCE position) const noexcept; DISTANCE FindNextChange(DISTANCE position, DISTANCE end) const noexcept; DISTANCE StartRun(DISTANCE position) const noexcept; DISTANCE EndRun(DISTANCE position) const noexcept; // Returns changed=true if some values may have changed FillResult<DISTANCE> FillRange(DISTANCE position, STYLE value, DISTANCE fillLength); void SetValueAt(DISTANCE position, STYLE value); void InsertSpace(DISTANCE position, DISTANCE insertLength); void DeleteAll(); void DeleteRange(DISTANCE position, DISTANCE deleteLength); DISTANCE Runs() const noexcept; bool AllSame() const noexcept; bool AllSameAs(STYLE value) const noexcept; DISTANCE Find(STYLE value, DISTANCE start) const noexcept; void Check() const; }; } #endif <|start_filename|>scintilla/src/ElapsedPeriod.h<|end_filename|> // Scintilla source code edit control /** @file ElapsedPeriod.h ** Encapsulate C++ <chrono> to simplify use. **/ // Copyright 2018 by <NAME> <<EMAIL>> // The License.txt file describes the conditions under which this software may be distributed. #ifndef ELAPSEDPERIOD_H #define ELAPSEDPERIOD_H namespace Scintilla::Internal { // Simplified access to high precision timing. class ElapsedPeriod { using ElapsedClock = std::chrono::steady_clock; ElapsedClock::time_point tp; public: /// Capture the moment ElapsedPeriod() noexcept : tp(ElapsedClock::now()) { } /// Return duration as floating point seconds double Duration(bool reset=false) noexcept { const ElapsedClock::time_point tpNow = ElapsedClock::now(); const std::chrono::duration<double> duration = std::chrono::duration_cast<std::chrono::duration<double>>(tpNow - tp); if (reset) { tp = tpNow; } return duration.count(); } }; } #endif <|start_filename|>test/test_files/encoding/UTF-8/Error Detection encoding_utf-8 with tag (issue #1831).json<|end_filename|> // encoding: UTF-8 { "manifest_version": 2, "name": "k view", "version": "0.5", "description": "テスト。", "browser_action": { "default_icon": { "19": "round-done-button.png" } }, } <|start_filename|>test/test_files/StyleLexers/styleLexGo/Go_goroutine_channel.go<|end_filename|> package main import ( "fmt" "math/rand" ) func main() { channels := make([]chan bool, 6) //创建一个类型为chan bool的切片,每一项是能发送bool值的通道 for i := range channels { //通过range初始化切片 channels[i] = make(chan bool) } go func() { //在其他goroutine中执行匿名函数 for { channels[rand.Intn(6)] <- true //read.Intn(n, int)的用途是产生一个不大于n的随机数 } // 发送数据到随机出现的通道 }() for i := 0; i < 36; i++ { var x int select { // select语句当监听到哪个分支的通道未阻塞时就跳转到哪个分支 case <-channels[0]: x = 1 case <-channels[1]: x = 2 case <-channels[2]: x = 3 case <-channels[3]: x = 4 case <-channels[4]: x = 5 case <-channels[5]: x = 6 } fmt.Printf("%d ", x) } fmt.Println() } <|start_filename|>src/StyleLexers/styleLexASM.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- KEYWORDLIST KeyWords_ASM = { "aaa aad aam aas adc add and arpl bound bsf bsr bswap bt btc btr bts call cbw cdq cflush clc cld cli clts " "cmc cmova cmovae cmovb cmovbe cmovc cmove cmovg cmovge cmovl cmovle cmovna cmovnae cmovnb cmovnbe cmovnc " "cmovne cmovng cmovnge cmovnl cmovnle cmovno cmovnp cmovns cmovnz cmovo cmovp cmovpe cmovpo cmovs cmovz " "cmp cmps cmpsb cmpsd cmpsq cmpsw cmpxchg cmpxchg486 cmpxchg8b cpuid cwd cwde daa das dec div emms enter " "esc femms hlt ibts icebp idiv imul in inc ins insb insd insw int int01 int03 int1 int3 into invd invlpg " "iret iretd iretdf iretf iretw ja jae jb jbe jc jcxz je jecxz jg jge jl jle jmp jna jnae jnb jnbe jnc jne " "jng jnge jnl jnle jno jnp jns jnz jo jp jpe jpo js jz lahf lar lds lea leave les lfs lgdt lgs lidt lldt " "lmsw loadall loadall286 lock lods lodsb lodsd lodsq lodsw loop loopd loope looped loopew loopne loopned " "loopnew loopnz loopnzd loopnzw loopw loopz loopzd loopzw lsl lss ltr mov movs movsb movsd movsq movsw " "movsx movsxd movzx mul neg nop not or out outs outsb outsd outsw pop popa popad popaw popf popfd popfw " "push pusha pushad pushaw pushd pushf pushfd pushfw pushw rcl rcr rdmsr rdpmc rdshr rdtsc rep repe repne " "repnz repz ret retf retn rol ror rsdc rsldt rsm rsts sahf sal salc sar sbb scas scasb scasd scasq scasw " "seta setae setb setbe setc sete setg setge setl setle setna setnae setnb setnbe setnc setne setng setnge " "setnl setnle setno setnp setns setnz seto setp setpe setpo sets setz sgdt shl shld shr shrd sidt sldt smi " "smint smintold smsw stc std sti stos stosb stosd stosq stosw str sub svdc svldt svts syscall sysenter " "sysexit sysret test ud0 ud1 ud2 umov verr verw wait wbinvd wrmsr wrshr xadd xbts xchg xlat xlatb xor", "f2xm1 fabs fadd faddp fbld fbstp fchs fclex fcmovb fcmovbe fcmove fcmovnb fcmovnbe fcmovne fcmovnu fcmovu " "fcom fcomi fcomip fcomp fcompp fcos fdecstp fdisi fdiv fdivp fdivr fdivrp feni ffree ffreep fiadd ficom " "ficomp fidiv fidivr fild fimul fincstp finit fist fistp fisub fisubr fld fld1 fldcw fldenv fldenvd " "fldenvw fldl2e fldl2t fldlg2 fldln2 fldpi fldz fmul fmulp fnclex fndisi fneni fninit fnop fnsave fnsaved " "fnsavew fnstcw fnstenv fnstenvd fnstenvw fnstsw fpatan fprem fprem1 fptan frndint frstor frstord frstorw " "fsave fsaved fsavew fscale fsetpm fsin fsincos fsqrt fst fstcw fstenv fstenvd fstenvw fstp fstsw fsub " "fsubp fsubr fsubrp ftst fucom fucomp fucompp fwait fxam fxch fxtract fyl2x fyl2xp1", "ah al ax bh bl bp bx ch cl cr0 cr2 cr3 cr4 cs cx dh di dl dr0 dr1 dr2 dr3 dr6 dr7 ds dx eax ebp ebx ecx edi " "edx eip es esi esp fs gs mm0 mm1 mm2 mm3 mm4 mm5 mm6 mm7 r10 r10b r10d r10w r11 r11b r11d r11w r12 r12b " "r12d r12w r13 r13b r13d r13w r14 r14b r14d r14w r15 r15b r15d r15w r8 r8b r8d r8w r9 r9b r9d r9w rax rbp " "rbx rcx rdi rdx rip rsi rsp si sp ss st st0 st1 st2 st3 st4 st5 st6 st7 tr3 tr4 tr5 tr6 tr7 xmm0 xmm1 " "xmm10 xmm11 xmm12 xmm13 xmm14 xmm15 xmm2 xmm3 xmm4 xmm5 xmm6 xmm7 xmm8 xmm9 ymm0 ymm1 ymm10 ymm11 ymm12 " "ymm13 ymm14 ymm15 ymm2 ymm3 ymm4 ymm5 ymm6 ymm7 ymm8 ymm9", "%arg %assign %define %elif %elifctk %elifdef %elifid %elifidn %elifidni %elifmacro %elifnctk %elifndef " "%elifnid %elifnidn %elifnidni %elifnmacro %elifnnum %elifnstr %elifnum %elifstr %else %endif %endmacro " "%endrep %error %exitrep %iassign %idefine %if %ifctk %ifdef %ifid %ifidn %ifidni %ifmacro %ifnctk %ifndef " "%ifnid %ifnidn %ifnidni %ifnmacro %ifnnum %ifnstr %ifnum %ifstr %imacro %include %line %local %macro %out " "%pop %push %rep %repl %rotate %stacksize %strlen %substr %undef %xdefine %xidefine .186 .286 .286c .286p " ".287 .386 .386c .386p .387 .486 .486p .8086 .8087 .alpha .break .code .const .continue .cref .data .data? " ".dosseg .else .elseif .endif .endw .err .err1 .err2 .errb .errdef .errdif .errdifi .erre .erridn .erridni " ".errnb .errndef .errnz .exit .fardata .fardata? .if .lall .lfcond .list .listall .listif .listmacro " ".listmacroall .model .msfloat .no87 .nocref .nolist .nolistif .nolistmacro .radix .repeat .sall .seq " ".sfcond .stack .startup .tfcond .type .until .untilcxz .while .xall .xcref .xlist absolute alias align " "alignb assume at bits catstr comm comment common cpu db dd df dosseg dq dt dup dw echo else elseif " "elseif1 elseif2 elseifb elseifdef elseifdif elseifdifi elseife elseifidn elseifidni elseifnb elseifndef " "end endif endm endp ends endstruc eq equ even exitm export extern externdef extrn for forc ge global goto " "group gt high highword iend if if1 if2 ifb ifdef ifdif ifdifi ife ifidn ifidni ifnb ifndef import incbin " "include includelib instr invoke irp irpc istruc label le length lengthof local low lowword lroffset lt " "macro mask mod name ne offset opattr option org page popcontext proc proto ptr public purge pushcontext " "record repeat rept resb resd resq rest resw section seg segment short size sizeof sizestr struc struct " "substr subtitle subttl textequ this times title type typedef union use16 use32 while width", "$ $$ %0 %1 %2 %3 %4 %5 %6 %7 %8 %9 .bss .data .text ? @b @f a16 a32 abs addr all assumes at basic byte c " "carry? casemap common compact cpu dotname dword emulator epilogue error export expr16 expr32 far far16 " "far32 farstack flat forceframe fortran fword huge language large listing ljmp loadds m510 medium memory " "near near16 near32 nearstack nodotname noemulator nokeyword noljmp nom510 none nonunique nooldmacros " "nooldstructs noreadonly noscoped nosignextend nosplit nothing notpublic o16 o32 oldmacros oldstructs " "os_dos overflow? para parity? pascal private prologue qword radix readonly real10 real4 real8 req sbyte " "scoped sdword seq setif2 sign? small smallstack stdcall sword syscall tbyte tiny use16 use32 uses vararg " "word wrt zero?", "addpd addps addsd addss andnpd andnps andpd andps blendpd blendps blendvpd blendvps cmpeqpd cmpeqps cmpeqsd " "cmpeqss cmplepd cmpleps cmplesd cmpless cmpltpd cmpltps cmpltsd cmpltss cmpnepd cmpneps cmpnesd cmpness " "cmpnlepd cmpnleps cmpnlesd cmpnless cmpnltpd cmpnltps cmpnltsd cmpnltss cmpordpd cmpordps cmpordsd " "cmpordss cmpunordpd cmpunordps cmpunordsd cmpunordss comisd comiss crc32 cvtdq2pd cvtdq2ps cvtpd2dq " "cvtpd2pi cvtpd2ps cvtpi2pd cvtpi2ps cvtps2dq cvtps2pd cvtps2pi cvtsd2si cvtsd2ss cvtsi2sd cvtsi2ss " "cvtss2sd cvtss2si cvttpd2dq cvttpd2pi cvttps2dq cvttps2pi cvttsd2si cvttss2si divpd divps divsd divss " "dppd dpps extractps fxrstor fxsave insertps ldmxscr lfence maskmovdq maskmovdqu maxpd maxps maxss mfence " "minpd minps minsd minss movapd movaps movd movdq2q movdqa movdqu movhlps movhpd movhps movlhps movlpd " "movlps movmskpd movmskps movntdq movntdqa movnti movntpd movntps movntq movq movq2dq movsd movss movupd " "movups mpsadbw mulpd mulps mulsd mulss orpd orps packssdw packsswb packusdw packuswb paddb paddd paddq " "paddsb paddsiw paddsw paddusb paddusw paddw pand pandn pause paveb pavgb pavgusb pavgw paxsd pblendvb " "pblendw pcmpeqb pcmpeqd pcmpeqq pcmpeqw pcmpestri pcmpestrm pcmpgtb pcmpgtd pcmpgtq pcmpgtw pcmpistri " "pcmpistrm pdistib pextrb pextrd pextrq pextrw pf2id pf2iw pfacc pfadd pfcmpeq pfcmpge pfcmpgt pfmax pfmin " "pfmul pfnacc pfpnacc pfrcp pfrcpit1 pfrcpit2 pfrsqit1 pfrsqrt pfsub pfsubr phminposuw pi2fd pinsrb pinsrd " "pinsrq pinsrw pmachriw pmaddwd pmagw pmaxsb pmaxsd pmaxsw pmaxub pmaxud pmaxuw pminsb pminsd pminsw " "pminub pminud pminuw pmovmskb pmovsxbd pmovsxbq pmovsxbw pmovsxdq pmovsxwd pmovsxwq pmovzxbd pmovzxbq " "pmovzxbw pmovzxdq pmovzxwd pmovzxwq pmuldq pmulhriw pmulhrwa pmulhrwc pmulhuw pmulhw pmulld pmullw " "pmuludq pmvgezb pmvlzb pmvnzb pmvzb popcnt por prefetch prefetchnta prefetcht0 prefetcht1 prefetcht2 " "prefetchw psadbw pshufd pshufhw pshuflw pshufw pslld pslldq psllq psllw psrad psraw psrld psrldq psrlq " "psrlw psubb psubd psubq psubsb psubsiw psubsw psubusb psubusw psubw pswapd ptest punpckhbw punpckhdq " "punpckhqdq punpckhwd punpcklbw punpckldq punpcklqdq punpcklwd pxor rcpps rcpss roundpd roundps roundsd " "roundss rsqrtps rsqrtss sfence shufpd shufps sqrtpd sqrtps sqrtsd sqrtss stmxcsr subpd subps subsd subss " "ucomisd ucomiss unpckhpd unpckhps unpcklpd unpcklps xorpd xorps", NULL, }; EDITLEXER lexASM = { SCLEX_ASM, "asm", IDS_LEX_ASM_SCR, L"Assembly Script", L"asm; s; sx; inc; a51", L"", &KeyWords_ASM, { { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_ASM_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {MULTI_STYLE(SCE_ASM_COMMENT,SCE_ASM_COMMENTBLOCK,0,0)}, IDS_LEX_STR_63127, L"Comment", L"fore:#008000", L"" }, { {SCE_ASM_IDENTIFIER}, IDS_LEX_STR_63129, L"Identifier", L"", L"" }, { {MULTI_STYLE(SCE_ASM_STRING,SCE_ASM_CHARACTER,SCE_ASM_STRINGEOL,0)}, IDS_LEX_STR_63131, L"String", L"fore:#008000", L"" }, { {SCE_ASM_NUMBER}, IDS_LEX_STR_63130, L"Number", L"fore:#FF0000", L"" }, { {SCE_ASM_OPERATOR}, IDS_LEX_STR_63132, L"Operator", L"fore:#0A246A", L"" }, { {SCE_ASM_CPUINSTRUCTION}, IDS_LEX_STR_63206, L"CPU Instruction", L"fore:#0A246A", L"" }, { {SCE_ASM_MATHINSTRUCTION}, IDS_LEX_STR_63207, L"FPU Instruction", L"fore:#0A246A", L"" }, { {SCE_ASM_EXTINSTRUCTION}, IDS_LEX_STR_63210, L"Extended Instruction", L"fore:#0A246A", L"" }, { {SCE_ASM_DIRECTIVE}, IDS_LEX_STR_63203, L"Directive", L"fore:#0A246A", L"" }, { {SCE_ASM_DIRECTIVEOPERAND}, IDS_LEX_STR_63209, L"Directive Operand", L"fore:#0A246A", L"" }, { {SCE_ASM_REGISTER}, IDS_LEX_STR_63208, L"Register", L"fore:#FF8000", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>grepWinNP3/sktoolslib_mod/InfoRtfDialog.h<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2020-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #pragma once #include "BaseDialog.h" #include "SmartHandle.h" #include <string> /** * bookmarks dialog. */ class CInfoRtfDialog : public CDialog { public: CInfoRtfDialog(); ~CInfoRtfDialog(); INT_PTR DoModal(HINSTANCE hInstance, HWND hParent, const std::string& dlgTitle, UINT rtfId, const std::wstring& resType, UINT iconId, int width, int height); INT_PTR DoModal(HINSTANCE hInstance, HWND hParent, const std::string& dlgTitle, UINT rtfId, const std::wstring& resType, UINT iconId, int x, int y, int width, int height); void ShowModeless(HINSTANCE hInstance, HWND hParent, const std::string& dlgTitle, UINT rtfId, const std::wstring& resType, UINT iconId, int width, int height); protected: LRESULT CALLBACK DlgFunc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) override; private: HWND m_hParent; HWND m_hwndRichEdit; UINT m_rtfId; std::wstring m_rtfResType; UINT m_iconId; CAutoLibrary m_richEditLib; }; <|start_filename|>grepWinNP3/sktoolslib_mod/ClipboardHelper.h<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012, 2020 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #pragma once class CClipboardHelper { public: CClipboardHelper() : bClipBoardOpen(false) { } ~CClipboardHelper(); bool Open(HWND hOwningWnd, bool retry = true); static HGLOBAL GlobalAlloc(SIZE_T dwBytes); private: bool bClipBoardOpen; }; inline CClipboardHelper::~CClipboardHelper() { if (bClipBoardOpen) CloseClipboard(); } inline bool CClipboardHelper::Open(HWND hOwningWnd, bool retry) { // OpenClipboard may fail if another application has opened the clipboard. // Try up to 8 times, with an initial delay of 1 ms and an exponential back off // for a maximum total delay of 127 ms (1+2+4+8+16+32+64). const int tries = retry ? 8 : 1; for (int attempt = 0; attempt < tries; ++attempt) { if (attempt > 0) { ::Sleep(1 << (attempt - 1)); } bClipBoardOpen = (OpenClipboard(hOwningWnd) != 0); if (bClipBoardOpen) { return true; } } return false; } inline HGLOBAL CClipboardHelper::GlobalAlloc(SIZE_T dwBytes) { return ::GlobalAlloc(GMEM_MOVEABLE, dwBytes); } <|start_filename|>minipath/src/VersionEx.h<|end_filename|> #define MNPTHNAME "MiniPath" #define VERSION_MAJOR 1 #define VERSION_MINOR 0 #define VERSION_REV 2 #define VERSION_BUILD 181 <|start_filename|>grepWinNP3/sktoolslib_mod/ResourceFile.cpp<|end_filename|> // sktoolslib - common files for SK tools // Copyright (C) 2012, 2020 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include <stdio.h> #include <malloc.h> #include <crtdbg.h> #include "ResourceFile.h" CResourceFile::CResourceFile() : m_pBytes(NULL) , m_bText(FALSE) , m_nBufLen(0) , m_nPosition(0) , m_bIsOpen(FALSE) , m_bDoNotDeleteBuffer(FALSE) { } CResourceFile::CResourceFile(const CResourceFile &rf) { if (rf.m_bDoNotDeleteBuffer) { // buffer is allocated externally or has been detached m_pBytes = rf.m_pBytes; } else { m_pBytes = new BYTE[rf.m_nBufLen + 2]; memset(m_pBytes, 0, rf.m_nBufLen + 2); memcpy(m_pBytes, rf.m_pBytes, rf.m_nBufLen); } m_nBufLen = rf.m_nBufLen; m_nPosition = 0; m_bIsOpen = rf.m_bIsOpen; m_bText = rf.m_bText; m_bDoNotDeleteBuffer = rf.m_bDoNotDeleteBuffer; } CResourceFile::~CResourceFile() { Close(); } BOOL CResourceFile::Open(HINSTANCE hInstance, LPCWSTR lpszResId, LPCWSTR lpszResType) { BOOL rc = FALSE; Close(); _ASSERTE(lpszResId); _ASSERTE(lpszResType); if (lpszResId && lpszResType) { wchar_t *pszRes = NULL; // is this a resource name string or an id? if (HIWORD(lpszResId) == 0) { // id pszRes = MAKEINTRESOURCE(LOWORD((UINT)(UINT_PTR)lpszResId)); } else { // string pszRes = (wchar_t *)lpszResId; } HRSRC hrsrc = FindResource(hInstance, pszRes, lpszResType); _ASSERTE(hrsrc); if (hrsrc) { DWORD dwSize = SizeofResource(hInstance, hrsrc); // in bytes HGLOBAL hglob = LoadResource(hInstance, hrsrc); _ASSERTE(hglob); if (hglob) { LPVOID lplock = LockResource(hglob); _ASSERTE(lplock); if (lplock) { // save resource as byte buffer m_pBytes = new BYTE[dwSize + 16]; memset(m_pBytes, 0, dwSize + 16); m_nBufLen = (int)dwSize; memcpy(m_pBytes, lplock, m_nBufLen); m_nPosition = 0; m_bIsOpen = TRUE; m_bDoNotDeleteBuffer = FALSE; // ok to delete the buffer rc = TRUE; } } } } return rc; } void CResourceFile::Close() { m_bIsOpen = FALSE; if (m_pBytes && !m_bDoNotDeleteBuffer) delete[] m_pBytes; m_pBytes = NULL; m_nBufLen = 0; m_nPosition = 0; } BYTE *CResourceFile::DetachByteBuffer() { BYTE *p = NULL; if (m_bIsOpen && !m_bText) { m_bDoNotDeleteBuffer = TRUE; p = m_pBytes; } return p; } BYTE *CResourceFile::DuplicateByteBuffer() { BYTE *dup = NULL; if (IsOpen() && !m_bText) { dup = (BYTE *)malloc(m_nBufLen + 2); memset(dup, 0, m_nBufLen + 2); memcpy(dup, m_pBytes, m_nBufLen); } return dup; } void CResourceFile::SetByteBuffer(BYTE *buf, DWORD len) { _ASSERTE(buf); _ASSERTE(len != 0); _ASSERTE(m_pBytes == NULL); if (buf && (len > 0)) { m_pBytes = buf; m_nBufLen = len; m_bText = FALSE; m_bDoNotDeleteBuffer = TRUE; // do not delete this buffer m_bIsOpen = TRUE; } } size_t CResourceFile::Read(BYTE *buf, size_t nBufLen) { size_t nOldPosition = m_nPosition; size_t nIndex = 0; if (buf) *buf = L'\0'; if (m_bIsOpen && m_pBytes && !m_bText) { while (!IsAtEOF()) { BYTE b = m_pBytes[m_nPosition++]; if (buf && (nIndex < nBufLen)) buf[nIndex] = b; nIndex++; } } // if we were just getting buffer size, restore position if (!buf) m_nPosition = nOldPosition; return nIndex; } size_t CResourceFile::SeekToBegin() { return Seek(0, SEEK_SET); } size_t CResourceFile::SeekToEnd() { return Seek(0, SEEK_END); } size_t CResourceFile::Seek(size_t offset, size_t origin) { size_t rc = (size_t)-1; if (IsOpen()) { switch (origin) { default: case SEEK_SET: // beginning of file if (offset <= m_nBufLen) { m_nPosition = offset; rc = m_nPosition; } break; case SEEK_CUR: // current position of file pointer if ((m_nPosition + offset) <= m_nBufLen) { m_nPosition += offset; rc = m_nPosition; } break; case SEEK_END: // end of file m_nPosition = m_nBufLen; rc = m_nPosition; break; } } return rc; } <|start_filename|>src/uchardet/uchardet/src/LangModels/LangAfricaansModel.cpp<|end_filename|> /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "../nsSBCharSetProber.h" /********* Language model for: Africaans *********/ /** * Generated by BuildLangModel.py * On: 2019-03-05 22:07:18.720938 **/ /* Character Mapping Table: * ILL: illegal character. * CTR: control character specific to the charset. * RET: carriage/return. * SYM: symbol (punctuation) that does not belong to word. * NUM: 0 - 9. * * Other characters are ordered by probabilities * (0 is the most common character in the language). * * Orders are generic to a language. So the codepoint with order X in * CHARSET1 maps to the same character as the codepoint with the same * order X in CHARSET2 for the same language. * As such, it is possible to get missing order. For instance the * ligature of 'o' and 'e' exists in ISO-8859-15 but not in ISO-8859-1 * even though they are both used for French. Same for the euro sign. */ static const unsigned char Windows_1252_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 3, 16, 21, 8, 0, 20, 10, 18, 1, 22, 11, 9, 14, 2, 6, /* 4X */ 17, 29, 5, 4, 7, 13, 12, 15, 27, 19, 25,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 3, 16, 21, 8, 0, 20, 10, 18, 1, 22, 11, 9, 14, 2, 6, /* 6X */ 17, 29, 5, 4, 7, 13, 12, 15, 27, 19, 25,SYM,SYM,SYM,SYM,CTR, /* 7X */ SYM,ILL,SYM, 53,SYM,SYM,SYM,SYM,SYM,SYM, 32,SYM, 54,ILL, 37,ILL, /* 8X */ ILL,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, 32,SYM, 55,ILL, 37, 56, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM,SYM, 57,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* BX */ 48, 28, 45, 44, 43, 51, 42, 39, 35, 26, 24, 23, 52, 38, 49, 30, /* CX */ 58, 59, 41, 31, 33, 60, 40,SYM, 36, 50, 61, 47, 34, 62, 63, 46, /* DX */ 48, 28, 45, 44, 43, 51, 42, 39, 35, 26, 24, 23, 52, 38, 49, 30, /* EX */ 64, 65, 41, 31, 33, 66, 40,SYM, 36, 50, 67, 47, 34, 68, 69, 70, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Iso_8859_1_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 3, 16, 21, 8, 0, 20, 10, 18, 1, 22, 11, 9, 14, 2, 6, /* 4X */ 17, 29, 5, 4, 7, 13, 12, 15, 27, 19, 25,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 3, 16, 21, 8, 0, 20, 10, 18, 1, 22, 11, 9, 14, 2, 6, /* 6X */ 17, 29, 5, 4, 7, 13, 12, 15, 27, 19, 25,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM,SYM, 88,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* BX */ 48, 28, 45, 44, 43, 51, 42, 39, 35, 26, 24, 23, 52, 38, 49, 30, /* CX */ 89, 90, 41, 31, 33, 91, 40,SYM, 36, 50, 92, 47, 34, 93, 94, 46, /* DX */ 48, 28, 45, 44, 43, 51, 42, 39, 35, 26, 24, 23, 52, 38, 49, 30, /* EX */ 95, 96, 41, 31, 33, 97, 40,SYM, 36, 50, 98, 47, 34, 99,100,101, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Iso_8859_9_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 3, 16, 21, 8, 0, 20, 10, 18, 1, 22, 11, 9, 14, 2, 6, /* 4X */ 17, 29, 5, 4, 7, 13, 12, 15, 27, 19, 25,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 3, 16, 21, 8, 0, 20, 10, 18, 1, 22, 11, 9, 14, 2, 6, /* 6X */ 17, 29, 5, 4, 7, 13, 12, 15, 27, 19, 25,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM,SYM,102,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* BX */ 48, 28, 45, 44, 43, 51, 42, 39, 35, 26, 24, 23, 52, 38, 49, 30, /* CX */ 103,104, 41, 31, 33,105, 40,SYM, 36, 50,106, 47, 34,107,108, 46, /* DX */ 48, 28, 45, 44, 43, 51, 42, 39, 35, 26, 24, 23, 52, 38, 49, 30, /* EX */ 109,110, 41, 31, 33,111, 40,SYM, 36, 50,112, 47, 34,113,114,115, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ static const unsigned char Iso_8859_15_CharToOrderMap[] = { CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,RET,CTR,CTR,RET,CTR,CTR, /* 0X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 1X */ SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* 2X */ NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,NUM,SYM,SYM,SYM,SYM,SYM,SYM, /* 3X */ SYM, 3, 16, 21, 8, 0, 20, 10, 18, 1, 22, 11, 9, 14, 2, 6, /* 4X */ 17, 29, 5, 4, 7, 13, 12, 15, 27, 19, 25,SYM,SYM,SYM,SYM,SYM, /* 5X */ SYM, 3, 16, 21, 8, 0, 20, 10, 18, 1, 22, 11, 9, 14, 2, 6, /* 6X */ 17, 29, 5, 4, 7, 13, 12, 15, 27, 19, 25,SYM,SYM,SYM,SYM,CTR, /* 7X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 8X */ CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR,CTR, /* 9X */ SYM,SYM,SYM,SYM,SYM,SYM, 32,SYM, 32,SYM,SYM,SYM,SYM,SYM,SYM,SYM, /* AX */ SYM,SYM,SYM,SYM, 37, 71,SYM,SYM, 37,SYM,SYM,SYM, 72, 73, 74,SYM, /* BX */ 48, 28, 45, 44, 43, 51, 42, 39, 35, 26, 24, 23, 52, 38, 49, 30, /* CX */ 75, 76, 41, 31, 33, 77, 40,SYM, 36, 50, 78, 47, 34, 79, 80, 46, /* DX */ 48, 28, 45, 44, 43, 51, 42, 39, 35, 26, 24, 23, 52, 38, 49, 30, /* EX */ 81, 82, 41, 31, 33, 83, 40,SYM, 36, 50, 84, 47, 34, 85, 86, 87, /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ /* Model Table: * Total sequences: 825 * First 512 sequences: 0.9986034713711631 * Next 512 sequences (512-1024): 0.0013965286288368912 * Rest: -1.1709383462843448e-17 * Negative sequences: TODO */ static const PRUint8 AfricaansLangModel[] = { 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0, 3,0,3,0,2,3,2,2,0,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,3,3,3, 3,3,3,0,3,2,0,2,0,0,2,0,0,0,0,0,0,0,0,0,0,2,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3, 3,3,2,3,2,0,2,0,0,0,2,0,0,0,2,0,2,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,0, 3,0,3,0,2,3,0,2,2,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3, 3,2,0,0,2,0,2,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,2, 3,3,2,2,2,0,2,2,0,2,2,3,0,2,0,0,0,0,2,2,0,0,2,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0, 3,2,3,0,2,2,0,0,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,0,3, 3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,2,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,0,3, 3,3,0,2,2,0,0,0,2,2,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3, 2,3,2,0,0,0,0,2,0,0,2,0,0,0,0,2,2,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,0,2, 2,2,0,0,0,0,2,0,0,2,2,0,0,0,0,2,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,0,0,0, 2,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,0,0, 3,3,3,3,3,3,3,0,2,3,0,3,0,3,2,0,0,3,0,3,2,0,0,0,2, 0,2,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,2,0,2, 2,3,3,0,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,0,3, 2,2,0,2,0,0,2,0,2,2,0,0,0,2,0,0,2,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,2,0,2,0,2,2,3,0,3,2,2,3,3,3,2,3,0,3, 0,2,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,2,3,2,2,0,3,2,3,3,3,2,3,2,3,2,0,0, 0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,2,2,0,2, 2,2,2,0,0,0,2,0,0,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0, 3,3,3,3,2,3,3,3,2,3,0,2,0,3,3,3,2,0,0,3,2,2,0,0,3, 0,2,0,2,2,0,0,0,2,2,0,0,0,0,0,0,0,0,2,0,2,0,0,0,0, 3,2,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,0,3,3,2,0,0, 2,0,0,0,0,0,0,0,0,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,0,0, 0,2,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,2,3,3,3,3,3,2,3,0,3,0,3,2,2,2,0,3,3,2,3,2,0,0, 3,0,0,0,3,0,2,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,2,3,0,2,3,2,2,2,0,2,0,3,3,2,2,2,2,2,0,2,0,0,0, 2,0,0,0,0,0,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,3,3,0,3,3,0,3,2,3,2,0,2,0,2,0,2,0,0,0,2,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,0,0,0,3,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,2,2,3,2,2,0,2,2,0,3,2,2,2,2,2,3,2,2,2,0,0, 2,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,2,3,2,2,2,2,2,2,3,2,0,2,2,2,0,3,3,0,0,0,2,0,0,0, 0,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,0,3,0,0,2,3,0,2,0,0,2,2,0,2,2,3,2,3,2,2,0,0,0, 0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,2,0,2,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0, 0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,0,2,0,0,2,0,0,0,0,0,2,3,0,2,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,3,0,3,2,0,2,2,2,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,2,0,0,2,0,0,2,2,2,0,0,0,2,2,0,0,0,0,2,0,0,0,0, 2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,0,2,0,2,0,3,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,2,0,0,2,0,3,0,0,0,0,0,0,2,0,0,2,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,2,0,2,2,0,2,2,2,2,0,0,0,0,0,0,0,2,0,0,2,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,2,0,2,2,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,0,0,0,0,0,0,2,0,0,2,2,0,0,0,0,0,0,2,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,2,2,0,2,2,2,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,2,2,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,2,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,2,0,0,0,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; const SequenceModel Windows_1252AfricaansModel = { Windows_1252_CharToOrderMap, AfricaansLangModel, 50, (float)0.9986034713711631, PR_TRUE, "WINDOWS-1252" }; const SequenceModel Iso_8859_1AfricaansModel = { Iso_8859_1_CharToOrderMap, AfricaansLangModel, 50, (float)0.9986034713711631, PR_TRUE, "ISO-8859-1" }; const SequenceModel Iso_8859_9AfricaansModel = { Iso_8859_9_CharToOrderMap, AfricaansLangModel, 50, (float)0.9986034713711631, PR_TRUE, "ISO-8859-9" }; const SequenceModel Iso_8859_15AfricaansModel = { Iso_8859_15_CharToOrderMap, AfricaansLangModel, 50, (float)0.9986034713711631, PR_TRUE, "ISO-8859-15" }; <|start_filename|>Version_beta.cmd<|end_filename|> :: Batch file for BETA version @echo off setlocal set _VERPATCH_=beta echo."_%_VERPATCH_%">.\np3portableapp\_buildname.txt Version -VerPatch "%_VERPATCH_%" endlocal <|start_filename|>grepWinNP3/src/Bookmarks.cpp<|end_filename|> // grepWin - regex search and replace for Windows // Copyright (C) 2007-2009, 2012-2013, 2017, 2020-2021 - <NAME> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // #include "stdafx.h" #include "Bookmarks.h" #include "maxpath.h" #include <shlobj.h> #include <memory> CBookmarks::CBookmarks() { SetUnicode(true); SetMultiLine(true); SetSpaces(false); } CBookmarks::~CBookmarks() { } void CBookmarks::Load() { auto path = std::make_unique<wchar_t[]>(MAX_PATH_NEW); GetModuleFileName(nullptr, path.get(), MAX_PATH_NEW); if (bPortable) { m_iniPath = path.get(); m_iniPath = m_iniPath.substr(0, m_iniPath.rfind('\\')); } else { SHGetFolderPath(nullptr, CSIDL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, path.get()); m_iniPath = path.get(); m_iniPath += L"\\grepWinNP3"; } CreateDirectory(m_iniPath.c_str(), nullptr); m_iniPath += L"\\bookmarks"; SetUnicode(); SetMultiLine(); SetSpaces(false); LoadFile(m_iniPath.c_str()); } void CBookmarks::Save() { auto path = std::make_unique<wchar_t[]>(MAX_PATH_NEW); GetModuleFileName(nullptr, path.get(), MAX_PATH_NEW); if (bPortable) { m_iniPath = path.get(); m_iniPath = m_iniPath.substr(0, m_iniPath.rfind('\\')); } else { SHGetFolderPath(nullptr, CSIDL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, path.get()); m_iniPath = path.get(); m_iniPath += L"\\grepWinNP3"; } CreateDirectory(m_iniPath.c_str(), nullptr); m_iniPath += L"\\bookmarks"; SaveFile(m_iniPath.c_str(), true); } void CBookmarks::AddBookmark(const Bookmark& bm) { std::wstring val = L"\""; val += bm.Search; val += L"\""; SetValue(bm.Name.c_str(), L"searchString", val.c_str()); val = L"\""; val += bm.Replace; val += L"\""; SetValue(bm.Name.c_str(), L"replaceString", val.c_str()); SetValue(bm.Name.c_str(), L"useregex", bm.UseRegex ? L"true" : L"false"); SetValue(bm.Name.c_str(), L"casesensitive", bm.CaseSensitive ? L"true" : L"false"); SetValue(bm.Name.c_str(), L"dotmatchesnewline", bm.DotMatchesNewline ? L"true" : L"false"); SetValue(bm.Name.c_str(), L"backup", bm.Backup ? L"true" : L"false"); SetValue(bm.Name.c_str(), L"wholewords", bm.WholeWords ? L"true" : L"false"); SetValue(bm.Name.c_str(), L"utf8", bm.Utf8 ? L"true" : L"false"); SetValue(bm.Name.c_str(), L"includesystem", bm.IncludeSystem ? L"true" : L"false"); SetValue(bm.Name.c_str(), L"includefolder", bm.IncludeFolder ? L"true" : L"false"); SetValue(bm.Name.c_str(), L"includehidden", bm.IncludeHidden ? L"true" : L"false"); SetValue(bm.Name.c_str(), L"includebinary", bm.IncludeBinary ? L"true" : L"false"); val = L"\""; val += bm.ExcludeDirs; val += L"\""; SetValue(bm.Name.c_str(), L"excludedirs", val.c_str()); val = L"\""; val += bm.FileMatch; val += L"\""; SetValue(bm.Name.c_str(), L"filematch", val.c_str()); SetValue(bm.Name.c_str(), L"filematchregex", bm.FileMatchRegex ? L"true" : L"false"); SetValue(bm.Name.c_str(), L"searchpath", bm.Path.c_str()); } void CBookmarks::RemoveBookmark(const std::wstring& name) { Delete(name.c_str(), L"searchString", true); Delete(name.c_str(), L"replaceString", true); Delete(name.c_str(), L"useregex", true); Delete(name.c_str(), L"casesensitive", true); Delete(name.c_str(), L"dotmatchesnewline", true); Delete(name.c_str(), L"backup", true); Delete(name.c_str(), L"wholewords", true); Delete(name.c_str(), L"utf8", true); Delete(name.c_str(), L"includesystem", true); Delete(name.c_str(), L"includefolder", true); Delete(name.c_str(), L"includehidden", true); Delete(name.c_str(), L"includebinary", true); Delete(name.c_str(), L"excludedirs", true); Delete(name.c_str(), L"filematch", true); Delete(name.c_str(), L"filematchregex", true); Delete(name.c_str(), L"searchpath", true); } Bookmark CBookmarks::GetBookmark(const std::wstring& name) const { Bookmark bk; if (GetSectionSize(name.c_str()) >= 0) { bk.Name = name; bk.Search = GetValue(name.c_str(), L"searchString", L""); bk.Replace = GetValue(name.c_str(), L"replaceString", L""); bk.UseRegex = wcscmp(GetValue(name.c_str(), L"useregex", L"false"), L"true") == 0; bk.CaseSensitive = wcscmp(GetValue(name.c_str(), L"casesensitive", L"false"), L"true") == 0; bk.DotMatchesNewline = wcscmp(GetValue(name.c_str(), L"dotmatchesnewline", L"false"), L"true") == 0; bk.Backup = wcscmp(GetValue(name.c_str(), L"backup", L"false"), L"true") == 0; bk.WholeWords = wcscmp(GetValue(name.c_str(), L"wholewords", L"false"), L"true") == 0; bk.Utf8 = wcscmp(GetValue(name.c_str(), L"utf8", L"false"), L"true") == 0; bk.IncludeSystem = wcscmp(GetValue(name.c_str(), L"includesystem", L"false"), L"true") == 0; bk.IncludeFolder = wcscmp(GetValue(name.c_str(), L"includefolder", L"false"), L"true") == 0; bk.IncludeHidden = wcscmp(GetValue(name.c_str(), L"includehidden", L"false"), L"true") == 0; bk.IncludeBinary = wcscmp(GetValue(name.c_str(), L"includebinary", L"false"), L"true") == 0; bk.ExcludeDirs = GetValue(name.c_str(), L"excludedirs", L""); bk.FileMatch = GetValue(name.c_str(), L"filematch", L""); bk.FileMatchRegex = wcscmp(GetValue(name.c_str(), L"filematchregex", L"false"), L"true") == 0; bk.Path = GetValue(name.c_str(), L"searchpath", L""); } return bk; } <|start_filename|>src/DarkMode/DarkMode.h<|end_filename|> #pragma once #include <Windows.h> #pragma comment(lib, "NtDll.lib") #pragma comment(lib, "Comctl32.lib") #pragma comment(lib, "Uxtheme.lib") #ifdef __cplusplus extern "C" { #else #include <stdbool.h> #endif void SetDarkMode(bool bEnableDarkMode); inline void InitDarkMode() { SetDarkMode(true); }; void ReleaseDarkMode(); void InitListView(HWND hListView); void InitTreeView(HWND hTreeView); //LRESULT OwnerDrawTextItem(HWND hwnd, WPARAM wParam, LPARAM lParam); DWORD GetWindowsBuildNumber(LPDWORD major, LPDWORD minor); #ifdef D_NP3_WIN10_DARK_MODE bool IsDarkModeSupported(); bool CheckDarkModeEnabled(); bool ShouldAppsUseDarkModeEx(); void AllowDarkModeForAppEx(bool allow); bool AllowDarkModeForWindowEx(HWND hWnd, bool allow); bool IsHighContrast(); void RefreshTitleBarThemeColor(HWND hWnd); bool IsColorSchemeChangeMessage(LPARAM lParam); bool IsColorSchemeChangeMessageMsg(UINT message, LPARAM lParam); #define CASE_WM_CTLCOLOR_SET \ case WM_CTLCOLORDLG: \ case WM_CTLCOLORBTN: \ case WM_CTLCOLOREDIT: \ case WM_CTLCOLORLISTBOX: \ case WM_CTLCOLORSTATIC #else inline bool IsDarkModeSupported() { return false; } inline bool CheckDarkModeEnabled() { return false; } #endif #define UseDarkMode() (IsDarkModeSupported() && CheckDarkModeEnabled()) #ifdef __cplusplus } #endif <|start_filename|>src/StyleLexers/styleLexTOML.c<|end_filename|> #include "StyleLexers.h" // ---------------------------------------------------------------------------- //KEYWORDLIST KeyWords_TOML = EMPTY_KEYWORDLIST; KEYWORDLIST KeyWords_TOML = { "+inf +nan -inf -nan false inf nan true", // Keyword NULL, }; EDITLEXER lexTOML = { SCLEX_TOML, "TOML", IDS_LEX_TOML_CFG, L"TOML Config", L"toml", L"", &KeyWords_TOML,{ { {STYLE_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, //{ {SCE_TOML_DEFAULT}, IDS_LEX_STR_63126, L"Default", L"", L"" }, { {SCE_TOML_KEYWORD}, IDS_LEX_STR_63128, L"Keyword", L"bold; fore:#FF0080", L"" }, { {SCE_TOML_COMMENT}, IDS_LEX_STR_63127, L"Comment", L"fore:#008000", L"" }, { {SCE_TOML_SECTION}, IDS_LEX_STR_63232, L"Section", L"bold; fore:#000000; back:#FFF1A8; eolfilled", L"" }, { {SCE_TOML_KEY}, IDS_LEX_STR_63348, L"Key", L"bold; fore:#5E608F", L"" }, { {SCE_TOML_ASSIGNMENT}, IDS_LEX_STR_63233, L"Assignment", L"bold; fore:#FF2020", L"" }, { {SCE_TOML_VALUE}, IDS_LEX_STR_63201, L"Value", L"fore:#202020", L"" }, { {SCE_TOML_NUMBER}, IDS_LEX_STR_63130, L"Number", L"fore:#0000E0", L"" }, { {SCE_TOML_DATETIME}, IDS_LEX_STR_63356, L"Date-Time", L"fore:#950095", L"" }, { {MULTI_STYLE(SCE_TOML_STR_BASIC, SCE_TOML_STR_LITERAL,0,0)}, IDS_LEX_STR_63131, L"String", L"italic; fore:#606060", L"" }, { {SCE_TOML_PARSINGERROR}, IDS_LEX_STR_63252, L"Parsing Error", L"fore:#FFFF00; back:#A00000; eolfilled", L"" }, EDITLEXER_SENTINEL } }; <|start_filename|>lexilla/lexlib/LexAccessor.cxx<|end_filename|> // Scintilla source code edit control /** @file LexAccessor.cxx ** Interfaces between Scintilla and lexers. **/ // Copyright 1998-2010 by <NAME> <<EMAIL>> // The License.txt file describes the conditions under which this software may be distributed. #include <cassert> #include <cstring> #include <string> #include <algorithm> #include "ILexer.h" #include "LexAccessor.h" #include "CharacterSet.h" using namespace Lexilla; namespace Lexilla { bool LexAccessor::MatchIgnoreCase(Sci_Position pos, const char *s) { for (; *s; s++, pos++) { if (*s != MakeLowerCase(SafeGetCharAt(pos))) { return false; } } return true; } void LexAccessor::GetRange(Sci_PositionU startPos_, Sci_PositionU endPos_, char *s, Sci_PositionU len) { assert(startPos_ <= endPos_ && len != 0 && s != nullptr); endPos_ = std::min(endPos_, startPos_ + len - 1); len = endPos_ - startPos_; if (startPos_ >= static_cast<Sci_PositionU>(startPos) && endPos_ <= static_cast<Sci_PositionU>(endPos)) { const char * const p = buf + (startPos_ - startPos); memcpy(s, p, len); } else { pAccess->GetCharRange(s, startPos_, len); } s[len] = '\0'; } void LexAccessor::GetRangeLowered(Sci_PositionU startPos_, Sci_PositionU endPos_, char *s, Sci_PositionU len) { GetRange(startPos_, endPos_, s, len); while (*s) { if (*s >= 'A' && *s <= 'Z') { *s += 'a' - 'A'; } ++s; } } std::string LexAccessor::GetRange(Sci_PositionU startPos_, Sci_PositionU endPos_) { assert(startPos_ < endPos_); const Sci_PositionU len = endPos_ - startPos_; std::string s(len, '\0'); GetRange(startPos_, endPos_, s.data(), len); return s; } std::string LexAccessor::GetRangeLowered(Sci_PositionU startPos_, Sci_PositionU endPos_) { assert(startPos_ < endPos_); const Sci_PositionU len = endPos_ - startPos_; std::string s(len, '\0'); GetRangeLowered(startPos_, endPos_, s.data(), len); return s; } }
X-EcutiOnner/Notepad3
<|start_filename|>index.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>The Grid</title> <link rel="stylesheet" href="css/master.css"> <!-- <link rel="stylesheet" href="css/the-grid.css"> --> <link rel="stylesheet" href="src/sass/the-grid.min.css"> <link href="https://fonts.googleapis.com/css?family=Lato:400,900" rel="stylesheet"> <link rel="stylesheet" href="js/highlightjs/styles/dracula.css"> </head> <body> <div class="head container column align-items-center justify-content-center"> <div class="head-box"> <h1><small>The</small>Grid</h1> <div class="hr"> <hr class="green"> </div> <p>Simple grid based in flexbox. Botstrap 4 compatible.</p> </div> </div> <div class="size margin"> <div class="example column container align-items-center justify-content-center"> <h1>Grid based on 12 columns <small>(Like a bootstrap 4)</small></h1> <div class="container column"> <div class="col-1 ">1</div> <div class="col-2 ">2</div> <div class="col-3 ">3</div> <div class="col-4 ">4</div> <div class="col-5 ">5</div> <div class="col-6 ">6</div> <div class="col-7 ">7</div> <div class="col-8 ">8</div> <div class="col-9 ">9</div> <div class="col-10 ">10</div> <div class="col-11 ">11</div> <div class="col-12 ">12</div> </div> <pre><code class="html"> &lt;div class=&quot;container column&quot;&gt; &lt;div class=&quot;col-1&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;col-2&quot;&gt;2&lt;/div&gt; &lt;div class=&quot;col-3&quot;&gt;3&lt;/div&gt; &lt;div class=&quot;col-4&quot;&gt;4&lt;/div&gt; &lt;div class=&quot;col-5&quot;&gt;5&lt;/div&gt; &lt;div class=&quot;col-6&quot;&gt;6&lt;/div&gt; &lt;div class=&quot;col-7&quot;&gt;7&lt;/div&gt; &lt;div class=&quot;col-8&quot;&gt;8&lt;/div&gt; &lt;div class=&quot;col-9&quot;&gt;9&lt;/div&gt; &lt;div class=&quot;col-10&quot;&gt;10&lt;/div&gt; &lt;div class=&quot;col-11&quot;&gt;11&lt;/div&gt; &lt;div class=&quot;col-12&quot;&gt;12&lt;/div&gt; &lt;/div&gt; </code></pre> <div class="container column"> <div class="col-1 col-sm-1 col-md-1 col-lg-1 col-xl-1">1</div> <div class="col-2 col-sm-2 col-md-2 col-lg-2 col-xl-2">2</div> <div class="col-3 col-sm-3 col-md-3 col-lg-3 col-xl-3">3</div> <div class="col-4 col-sm-4 col-md-4 col-lg-4 col-xl-4">4</div> <div class="col-5 col-sm-5 col-md-5 col-lg-5 col-xl-5">5</div> <div class="col-6 col-sm-6 col-md-6 col-lg-6 col-xl-6">6</div> <div class="col-7 col-sm-7 col-md-7 col-lg-7 col-xl-7">7</div> <div class="col-8 col-sm-8 col-md-8 col-lg-8 col-xl-8">8</div> <div class="col-9 col-sm-9 col-md-9 col-lg-9 col-xl-9">9</div> <div class="col-10 col-sm-10 col-md-10 col-lg-10 col-xl-10">10</div> <div class="col-11 col-sm-11 col-md-11 col-lg-11 col-xl-11">11</div> <div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12">12</div> </div> <pre><code class="html"> &lt;div class=&quot;container column&quot;&gt; &lt;div class=&quot;col-1 col-sm-1 col-md-1 col-lg-1 col-xl-1&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;col-2 col-sm-2 col-md-2 col-lg-2 col-xl-2&quot;&gt;2&lt;/div&gt; &lt;div class=&quot;col-3 col-sm-3 col-md-3 col-lg-3 col-xl-3&quot;&gt;3&lt;/div&gt; &lt;div class=&quot;col-4 col-sm-4 col-md-4 col-lg-4 col-xl-4&quot;&gt;4&lt;/div&gt; &lt;div class=&quot;col-5 col-sm-5 col-md-5 col-lg-5 col-xl-5&quot;&gt;5&lt;/div&gt; &lt;div class=&quot;col-6 col-sm-6 col-md-6 col-lg-6 col-xl-6&quot;&gt;6&lt;/div&gt; &lt;div class=&quot;col-7 col-sm-7 col-md-7 col-lg-7 col-xl-7&quot;&gt;7&lt;/div&gt; &lt;div class=&quot;col-8 col-sm-8 col-md-8 col-lg-8 col-xl-8&quot;&gt;8&lt;/div&gt; &lt;div class=&quot;col-9 col-sm-9 col-md-9 col-lg-9 col-xl-9&quot;&gt;9&lt;/div&gt; &lt;div class=&quot;col-10 col-sm-10 col-md-10 col-lg-10 col-xl-10&quot;&gt;10&lt;/div&gt; &lt;div class=&quot;col-11 col-sm-11 col-md-11 col-lg-11 col-xl-11&quot;&gt;11&lt;/div&gt; &lt;div class=&quot;col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12&quot;&gt;12&lt;/div&gt; &lt;/div&gt; </code></pre> <div class="container"> <div class="col-12 col-sm-6 col-md-6 col-lg-3 col-xl-3">1</div> </div> <pre><code class="html"> &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;col-12 col-sm-6 col-md-6 col-lg-3 col-xl-3&quot;&gt;1&lt;/div&gt; &lt;/div&gt; </code></pre> </div> <div class="example column container align-items-center justify-content-center"> <h1>Order control<small>(Resize screen)</small></h1> <div class="container column"> <div class="col-1 col-xl-1 order-xl-1 order-sm-12 order-12">1</div> <div class="col-2 col-xl-2 order-xl-2 order-sm-11 order-11">2</div> <div class="col-3 col-xl-3 order-xl-3 order-sm-10 order-10">3</div> <div class="col-4 col-xl-4 order-xl-4 order-sm-9 order-9">4</div> <div class="col-5 col-xl-5 order-xl-5 order-sm-8 order-8">5</div> <div class="col-6 col-xl-6 order-xl-6 order-sm-7 order-7">6</div> <div class="col-7 col-xl-7 order-xl-7 order-sm-6 order-6">7</div> <div class="col-8 col-xl-8 order-xl-8 order-sm-5 order-5">8</div> <div class="col-9 col-xl-9 order-xl-9 order-sm-4 order-4">9</div> <div class="col-10 col-xl-10 order-xl-10 order-sm-3 order-3">10</div> <div class="col-11 col-xl-11 order-xl-11 order-sm-2 order-2">11</div> <div class="col-12 col-xl-12 order-xl-12 order-sm-1 order-1">12</div> </div> <pre><code class="html"> &lt;div class=&quot;container column&quot;&gt; &lt;div class=&quot;col-1 col-xl-1 order-xl-1 order-sm-12 order-12&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;col-2 col-xl-2 order-xl-2 order-sm-11 order-11&quot;&gt;2&lt;/div&gt; &lt;div class=&quot;col-3 col-xl-3 order-xl-3 order-sm-10 order-10&quot;&gt;3&lt;/div&gt; &lt;div class=&quot;col-4 col-xl-4 order-xl-4 order-sm-9 order-9&quot;&gt;4&lt;/div&gt; &lt;div class=&quot;col-5 col-xl-5 order-xl-5 order-sm-8 order-8&quot;&gt;5&lt;/div&gt; &lt;div class=&quot;col-6 col-xl-6 order-xl-6 order-sm-7 order-7&quot;&gt;6&lt;/div&gt; &lt;div class=&quot;col-7 col-xl-7 order-xl-7 order-sm-6 order-6&quot;&gt;7&lt;/div&gt; &lt;div class=&quot;col-8 col-xl-8 order-xl-8 order-sm-5 order-5&quot;&gt;8&lt;/div&gt; &lt;div class=&quot;col-9 col-xl-9 order-xl-9 order-sm-4 order-4&quot;&gt;9&lt;/div&gt; &lt;div class=&quot;col-10 col-xl-10 order-xl-10 order-sm-3 order-3&quot;&gt;10&lt;/div&gt; &lt;div class=&quot;col-11 col-xl-11 order-xl-11 order-sm-2 order-2&quot;&gt;11&lt;/div&gt; &lt;div class=&quot;col-12 col-xl-12 order-xl-12 order-sm-1 order-1&quot;&gt;12&lt;/div&gt; &lt;/div&gt; </code></pre> </div> <div class="example column container align-items-center justify-content-center"> <h1>Container row</h1> <div class="container"> <div class="box">1</div> <div class="box">2</div> </div> <pre><code class="html"> &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;&quot;&gt;2&lt;/div&gt; &lt;/div&gt; </code></pre> </div> <div class="example column container align-items-center justify-content-center"> <h1>Container row-reverse</h1> <div class="container row-reverse"> <div class="box">1</div> <div class="box">2</div> </div> <pre><code class="html"> &lt;div class=&quot;container row-reverse&quot;&gt; &lt;div class=&quot;&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;&quot;&gt;2&lt;/div&gt; &lt;/div&gt; </code></pre> </div> <div class="example column container align-items-center justify-content-center container align-items-center justify-content-center"> <h1>Container column</h1> <div class="container column"> <div class="box">1</div> <div class="box">2</div> </div> <pre><code class="html"> &lt;div class=&quot;container column&quot;&gt; &lt;div class=&quot;&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;&quot;&gt;2&lt;/div&gt; &lt;/div&gt; </code></pre> </div> <div class="example column container align-items-center justify-content-center"> <h1>Container column-reverse</h1> <div class="container column-reverse"> <div class="box">1</div> <div class="box">2</div> </div> <pre><code class="html"> &lt;div class=&quot;container column-reverse&quot;&gt; &lt;div class=&quot;&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;&quot;&gt;2&lt;/div&gt; &lt;/div&gt; </code></pre> </div> <div class="example column container align-items-center justify-content-center"> <h1>Flex-wrap: wrap</h1> <div class="container wrap"> <div class="box">1</div> <div class="box">2</div> </div> <pre><code class="html"> &lt;div class=&quot;container wrap&quot;&gt; &lt;div class=&quot;&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;&quot;&gt;2&lt;/div&gt; &lt;/div&gt; </code></pre> </div> <div class="example column container align-items-center justify-content-center"> <h1>Flex-wrap: nowrap</h1> <div class="container no-wrap"> <div class="box">1</div> <div class="box">2</div> </div> <pre><code class="html"> &lt;div class=&quot;container no-wrap&quot;&gt; &lt;div class=&quot;&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;&quot;&gt;2&lt;/div&gt; &lt;/div&gt; </code></pre> </div> <div class="example column container align-items-center justify-content-center"> <h1>Justify-content</h1> <div class="container justify-content-start"> <div class="box">1</div> <div class="box">2</div> </div> <pre><code class="html"> &lt;div class=&quot;container justify-content-start&quot;&gt; &lt;div class=&quot;&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;&quot;&gt;2&lt;/div&gt; &lt;/div&gt; </code></pre> <div class="container justify-content-center"> <div class="box">1</div> <div class="box">2</div> </div> <pre><code class="html"> &lt;div class=&quot;container justify-content-center&quot;&gt; &lt;div class=&quot;&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;&quot;&gt;2&lt;/div&gt; &lt;/div&gt; </code></pre> <div class="container justify-content-end"> <div class="box">1</div> <div class="box">2</div> </div> <pre><code class="html"> &lt;div class=&quot;container justify-content-end&quot;&gt; &lt;div class=&quot;&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;&quot;&gt;2&lt;/div&gt; &lt;/div&gt; </code></pre> <div class="container justify-content-between"> <div class="box">1</div> <div class="box">2</div> </div> <pre><code class="html"> &lt;div class=&quot;container justify-content-between&quot;&gt; &lt;div class=&quot;&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;&quot;&gt;2&lt;/div&gt; &lt;/div&gt; </code></pre> <div class="container justify-content-around"> <div class="box">1</div> <div class="box">2</div> </div> <pre><code class="html"> &lt;div class=&quot;container justify-content-around&quot;&gt; &lt;div class=&quot;&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;&quot;&gt;2&lt;/div&gt; &lt;/div&gt; </code></pre> </div> <div class="example column container align-items-center justify-content-center"> <h1>Align-items</h1> <div class="container align-items-start"> <div class="box">1</div> <div class="box">2</div> </div> <pre><code class="html"> &lt;div class=&quot;container align-items-start&quot;&gt; &lt;div class=&quot;&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;&quot;&gt;2&lt;/div&gt; &lt;/div&gt; </code></pre> <div class="container align-items-center"> <div class="box">1</div> <div class="box">2</div> </div> <pre><code class="html"> &lt;div class=&quot;container align-items-center&quot;&gt; &lt;div class=&quot;&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;&quot;&gt;2&lt;/div&gt; &lt;/div&gt; </code></pre> <div class="container align-items-end"> <div class="box">1</div> <div class="box">2</div> </div> <pre><code class="html"> &lt;div class=&quot;container align-items-end&quot;&gt; &lt;div class=&quot;&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;&quot;&gt;2&lt;/div&gt; &lt;/div&gt; </code></pre> <div class="container align-items-baseline"> <div class="box">1</div> <div class="box">2</div> </div> <pre><code class="html"> &lt;div class=&quot;container align-items-baseline&quot;&gt; &lt;div class=&quot;&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;&quot;&gt;2&lt;/div&gt; &lt;/div&gt; </code></pre> <div class="container align-items-stretch"> <div class="box">1</div> <div class="box">2</div> </div> <pre><code class="html"> &lt;div class=&quot;container align-items-stretch&quot;&gt; &lt;div class=&quot;&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;&quot;&gt;2&lt;/div&gt; &lt;/div&gt; </code></pre> </div> <div class="example column container align-items-center justify-content-center"> <h1>Align-self</h1> <div class="container align-items-center wrap"> <div class="box">1</div> <div class="box align-self-start">3</div> <div class="box align-self-center">3</div> <div class="box align-self-end">2</div> <div class="box align-self-stretch">4</div> </div> <pre><code class="html"> &lt;div class=&quot;container align-items-center&quot;&gt; &lt;div class=&quot;&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;align-self-start&quot;&gt;2&lt;/div&gt; &lt;div class=&quot;align-self-center&quot;&gt;3&lt;/div&gt; &lt;div class=&quot;align-self-end&quot;&gt;4&lt;/div&gt; &lt;div class=&quot;align-self-stretch&quot;&gt;5&lt;/div&gt; &lt;/div&gt; </code></pre> </div> <div class="example column container align-items-center justify-content-center"> <h1>Flex-grow</h1> <div class="container"> <div class="box flex-grow-1">1</div> </div> <pre><code class="html"> &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;flex-grow-1&quot;&gt;1&lt;/div&gt; &lt;/div&gt; </code></pre> <div class="container"> <div class="box flex-grow-1">1</div> <div class="box flex-grow-1">2</div> </div> <pre><code class="html"> &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;flex-grow-1&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;flex-grow-1&quot;&gt;2&lt;/div&gt; &lt;/div&gt; </code></pre> <div class="container"> <div class="box flex-grow-1">1</div> <div class="box flex-grow-5">2</div> </div> <pre><code class="html"> &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;flex-grow-1&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;flex-grow-5&quot;&gt;2&lt;/div&gt; &lt;/div&gt; </code></pre> <div class="container wrap"> <div class="box flex-grow-1">1</div> <div class="box flex-grow-2">2</div> <div class="box flex-grow-3">3</div> <div class="box flex-grow-4">4</div> <div class="box flex-grow-5">5</div> </div> <pre><code class="html"> &lt;div class=&quot;container wrap&quot;&gt; &lt;div class=&quot;flex-grow-1&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;flex-grow-2&quot;&gt;2&lt;/div&gt; &lt;div class=&quot;flex-grow-3&quot;&gt;3&lt;/div&gt; &lt;div class=&quot;flex-grow-4&quot;&gt;4&lt;/div&gt; &lt;div class=&quot;flex-grow-5&quot;&gt;5&lt;/div&gt; &lt;/div&gt; </code></pre> </div> <div class="example column container align-items-center justify-content-center"> <h1>Flex-basis</h1> <div class="container wrap"> <div class="box flex-basis-100">1</div> <div class="box flex-basis-200">2</div> <div class="box flex-basis-300">3</div> </div> <pre><code class="html"> &lt;div class=&quot;container wrap&quot;&gt; &lt;div class=&quot;flex-basis-100&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;flex-basis-200&quot;&gt;2&lt;/div&gt; &lt;div class=&quot;flex-basis-300&quot;&gt;3&lt;/div&gt; &lt;/div&gt; </code></pre> <div class="container wrap"> <div class="box flex-basis-100">1</div> <div class="box flex-basis-200">2</div> <div class="box flex-grow-1">3</div> </div> <pre><code class="html"> &lt;div class=&quot;container wrap&quot;&gt; &lt;div class=&quot;flex-basis-100&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;flex-basis-200&quot;&gt;2&lt;/div&gt; &lt;div class=&quot;flex-basis-300 flex-grow-1&quot;&gt;3&lt;/div&gt; &lt;/div&gt; </code></pre> <div class="container column"> <div class="box flex-basis-100">1</div> <div class="box flex-basis-200">2</div> <div class="box flex-grow-1">3</div> </div> <pre><code class="html"> &lt;div class=&quot;container wrap column&quot;&gt; &lt;div class=&quot;flex-basis-100&quot;&gt;1&lt;/div&gt; &lt;div class=&quot;flex-basis-200&quot;&gt;2&lt;/div&gt; &lt;div class=&quot;flex-basis-300 flex-grow-1&quot;&gt;3&lt;/div&gt; &lt;/div&gt; </code></pre> <div class="container"> <div class="box flex-basis-100">1</div> </div> <div class="container"> <div class="box flex-basis-200">1</div> </div> <div class="container"> <div class="box flex-basis-300">1</div> </div> <div class="container"> <div class="box flex-basis-400">1</div> </div> <div class="container"> <div class="box flex-basis-500">1</div> </div> <div class="container"> <div class="box flex-basis-600">1</div> </div> <div class="container"> <div class="box flex-basis-700">1</div> </div> <div class="container"> <div class="box flex-basis-800">1</div> </div> <div class="container"> <div class="box flex-basis-900">1</div> </div> <div class="container"> <div class="box flex-basis-1000">1</div> </div> <div class="container"> <div class="box flex-basis-1100">1</div> </div> <div class="container"> <div class="box flex-basis-1200">1</div> </div> <pre><code class="html"> &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;flex-basis-100&quot;&gt;1&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;flex-basis-200&quot;&gt;2&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;flex-basis-300&quot;&gt;3&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;flex-basis-400&quot;&gt;4&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;flex-basis-500&quot;&gt;5&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;flex-basis-600&quot;&gt;6&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;flex-basis-700&quot;&gt;7&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;flex-basis-800&quot;&gt;8&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;flex-basis-900&quot;&gt;9&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;flex-basis-1000&quot;&gt;10&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;flex-basis-1100&quot;&gt;11&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;flex-basis-1200&quot;&gt;12&lt;/div&gt; &lt;/div&gt; </code></pre> </div> </div> <script src="http://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.4.0/highlight.min.js"></script> <script> hljs.initHighlightingOnLoad(); </script> </body> </html> <|start_filename|>package.json<|end_filename|> { "name": "the-grid-flexbox", "version": "2.0.1", "publishConfig": { "registry":"https://npm.pkg.github.com/" }, "description": "Atomic grid based in flexbox. Mobile first. Botstrap 4 compatible.", "keywords": [ "css", "flexbox", "sass", "mobile-first", "responsive", "front-end", "framework", "web" ], "scripts": { "dev": "gulp" }, "repository": { "type": "git", "url": "git+https://github.com/gustavoquinalha/the-grid.git" }, "author": "gustavoquinalha<<EMAIL>>", "license": "MIT", "bugs": { "url": "https://github.com/gustavoquinalha/the-grid/issues" }, "homepage": "https://github.com/gustavoquinalha/the-grid#readme", "dependencies": { "gulp": "^3.9.1", "gulp-sass": "^2.3.2" }, "devDependencies": { "breakpoint-sass": "^2.7.0", "browser-sync": "^2.18.2", "gulp": "^3.9.1", "gulp-autoprefixer": "^3.1.1", "gulp-clean-css": "^3.9.2", "gulp-rename": "^1.2.2", "gulp-sass": "^2.3.2", "gulp-sourcemaps": "^2.2.0" } } <|start_filename|>css/master.css<|end_filename|> * { margin: 0; padding: 0; font-family: 'Lato', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; /* color: #222 */ } *, *::before, *::after { box-sizing: inherit; } html, body { height: 100%; font-family: sans-serif; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; } html { box-sizing: border-box; -ms-overflow-style: scrollbar; } h1, h2, h3, h4, h5, h6 { margin-top: 0; margin-bottom: 0; padding-top: 0; padding-bottom: 0; } b, strong { font-weight: bolder; } p { margin-top: 0; margin-bottom: 0; } a { color: #007bff; text-decoration: none; background-color: transparent; -webkit-text-decoration-skip: objects; } a:hover { color: #0056b3; } input, button, select, optgroup, textarea { margin: 0; font-family: inherit; font-size: inherit; line-height: inherit; outline: none } img { vertical-align: middle; border-style: none; } svg:not(:root) { overflow: hidden; } pre, code { width: 100%; box-sizing: border-box; } [hidden] { display: none !important; } .hljs { background: #222!important } .head { min-height: 100vh!important; width: 100%; padding: 0!important; text-align: center; } .head-box { width: 400px; max-width: 90%; } .head h1 { font-size: 6em; color: #222 } .head p { font-size: 1.7em; color: rgba(34, 34, 34, 0.7) } .size { width: 1200px; max-width: 90%; } .example h1 { font-size: 2.5em!important; } .margin { margin: 0 auto } .example { min-height: 50vh; padding-top: 20vh; padding-bottom: 20vh; box-sizing: border-box } .example .container, .example .row { background: #222; margin-top: 10px; margin-bottom: 10px; width: 100%; } .container.column .box, .container.column-reverse .box {} .example .container.no-wrap .box, .example .container.wrap .box {} .example .container.no-wrap .box.flex-grow-1, .example .container.wrap .box.flex-grow-1, .example .container.no-wrap .box.flex-grow-2, .example .container.wrap .box.flex-grow-2, .example .container.no-wrap .box.flex-grow-3, .example .container.wrap .box.flex-grow-3, .example .container.no-wrap .box.flex-grow-4, .example .container.wrap .box.flex-grow-4, .example .container.no-wrap .box.flex-grow-5, .example .container.wrap .box.flex-grow-5, .example .container.no-wrap .box.flex-grow-6, .example .container.wrap .box.flex-grow-6, .example .container.no-wrap .box.flex-grow-7, .example .container.wrap .box.flex-grow-7, .example .container.no-wrap .box.flex-grow-8, .example .container.wrap .box.flex-grow-8, .example .container.no-wrap .box.flex-grow-9, .example .container.wrap .box.flex-grow-9, .example .container.no-wrap .box.flex-grow-10, .example .container.wrap .box.flex-grow-10, .example .container.no-wrap .box.flex-grow-11, .example .container.wrap .box.flex-grow-11, .example .container.no-wrap .box.flex-grow-12, .example .container.wrap .box.flex-grow-12 {} .align-items-stretch, .align-items-baseline, .align-items-start, .align-items-center, .align-items-end { min-height: 200px; } .hr { padding-top: 10px; padding-bottom: 10px; } .hr .green { width: 100px; height: 10px; border-radius: 20px; background: #50fa7b; border: none; margin: 0 auto } .box, [class*="basis-"], [class*="basis-"], [class*="col-"] { background: #50fa7b; margin: 10px; padding: 10px; border-radius: 20px; box-sizing: border-box; color: #fff; text-align: center; } @media screen and (max-width: 480px) { .head { min-height: 50vh!important; } .head h1 { font-size: 3em; } .head p { font-size: 1em; } .example h1 { font-size: 1.5em!important; } .box, [class*="basis-"], [class*="basis-"], [class*="col-"] { margin: 5px!important; padding: 5px!important; } }
gustavoquinalha/the-grid
<|start_filename|>Makefile<|end_filename|> all: bitflip bitflip: bitflip.c $(CC) -O3 -Wall -W -pedantic -std=c99 -o bitflip bitflip.c clean: rm bitflip <|start_filename|>bitflip.c<|end_filename|> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include <sys/mman.h> // https://stackoverflow.com/questions/9596945/how-to-get-appropriate-timestamp-in-c-for-logs char *timestamp() { time_t ltime; /* calendar time */ ltime = time(NULL); /* get current cal time */ return asctime(localtime(&ltime)); } int main() { size_t bytes = 1073741824; unsigned int tests = 0; unsigned char total = 0; printf("=== Bitflipped ===\n"); printf("==================\n"); printf("Allocating a gigabyte ...\n"); unsigned char *buffer = (unsigned char *)calloc(bytes, 1); // Ensure the buffer is actually resident in RAM mlock(buffer, bytes); memset(buffer, 0, bytes); printf("Run started: %s\n", timestamp()); fflush(stdout); while (total == 0) { // We aren't going to miss a bitflip by being slow sleep(30); // Naively walk through and tally all zero bytes for (size_t i = 0; i < bytes; ++i) { total += buffer[i]; } // Keep the user sane that it isn't frozen :) fprintf(stderr, "\rTest run #%d", tests); ++tests; } printf("--- !!! ---"); printf("Error detected: %s\n", timestamp()); printf("Result should be 0 but is %d\n", total); printf("Total tests run: %d\n", tests); fflush(stdout); }
Smerity/bitflipped
<|start_filename|>src/app/modules/about/pages/about/about.component.html<|end_filename|> <div class="about"> <mindmapp-header></mindmapp-header> <mindmapp-jumbotron></mindmapp-jumbotron> <section class="about-section" id="section-0"> <div class="container"> <h1> <fa-icon [icon]="faBrain" mat-card-avatar size="1x"></fa-icon> &nbsp;&nbsp;{{ 'PAGES.ABOUT.SECTIONS.0.TITLE' | translate }} </h1> <p>{{ 'PAGES.ABOUT.SECTIONS.0.SUBTITLE' | translate }}</p> <div class="cards"> <mat-card> <mat-card-header> <mat-card-title> {{ 'PAGES.ABOUT.SECTIONS.0.CARDS.0.TITLE' | translate }} </mat-card-title> </mat-card-header> <img alt="Solar system" mat-card-image src="/assets/images/solar-system.png"> <mat-card-content> <p>{{ 'PAGES.ABOUT.SECTIONS.0.CARDS.0.CONTENT' | translate }}</p> </mat-card-content> </mat-card> <mat-card> <mat-card-header> <mat-card-title> {{ 'PAGES.ABOUT.SECTIONS.0.CARDS.1.TITLE' | translate }} </mat-card-title> </mat-card-header> <img alt="Radial tree" mat-card-image src="/assets/images/radial-tree.png"> <mat-card-content> <p>{{ 'PAGES.ABOUT.SECTIONS.0.CARDS.1.CONTENT' | translate }}</p> </mat-card-content> </mat-card> <mat-card> <mat-card-header> <mat-card-title> {{ 'PAGES.ABOUT.SECTIONS.0.CARDS.2.TITLE' | translate }} </mat-card-title> </mat-card-header> <img alt="Business plan" mat-card-image src="/assets/images/business-plan.png"> <mat-card-content> <p>{{ 'PAGES.ABOUT.SECTIONS.0.CARDS.2.CONTENT' | translate }}</p> </mat-card-content> </mat-card> </div> </div> </section> <section class="about-section" id="section-1"> <div class="container"> <h1> <fa-icon [icon]="faRocket" mat-card-avatar size="1x"></fa-icon> &nbsp;&nbsp;{{ 'PAGES.ABOUT.SECTIONS.1.TITLE' | translate }} </h1> <p>{{ 'PAGES.ABOUT.SECTIONS.1.SUBTITLE' | translate }}</p> <div class="cards"> <mat-card> <mat-card-header> <fa-icon [icon]="faCheck" mat-card-avatar size="lg"></fa-icon> <mat-card-title> {{ 'PAGES.ABOUT.SECTIONS.1.CARDS.0.TITLE' | translate }} </mat-card-title> </mat-card-header> <mat-card-content> <p>{{ 'PAGES.ABOUT.SECTIONS.1.CARDS.0.CONTENT' | translate }}</p> </mat-card-content> </mat-card> <mat-card> <mat-card-header> <fa-icon [icon]="faChartLine" mat-card-avatar size="lg"></fa-icon> <mat-card-title> {{ 'PAGES.ABOUT.SECTIONS.1.CARDS.1.TITLE' | translate }} </mat-card-title> </mat-card-header> <mat-card-content> <p>{{ 'PAGES.ABOUT.SECTIONS.1.CARDS.1.CONTENT' | translate }}</p> </mat-card-content> </mat-card> <mat-card> <mat-card-header> <fa-icon [icon]="faCogs" mat-card-avatar size="lg"></fa-icon> <mat-card-title> {{ 'PAGES.ABOUT.SECTIONS.1.CARDS.2.TITLE' | translate }} </mat-card-title> </mat-card-header> <mat-card-content> <p>{{ 'PAGES.ABOUT.SECTIONS.1.CARDS.2.CONTENT' | translate }}</p> </mat-card-content> </mat-card> </div> </div> </section> <section class="about-section" id="section-2"> <div class="container"> <h1> <fa-icon [icon]="faHeart" mat-card-avatar size="1x"></fa-icon> &nbsp;&nbsp;{{ 'PAGES.ABOUT.SECTIONS.2.TITLE' | translate }} </h1> <p>{{ 'PAGES.ABOUT.SECTIONS.2.SUBTITLE' | translate }}</p> <mat-list role="list"> <mat-list-item role="listitem"> <mat-icon mat-list-icon>link</mat-icon> <a href="https://opencollective.com/mindmapp/contribute" target="_blank">Open Collective</a> </mat-list-item> <mat-list-item role="listitem"> <mat-icon mat-list-icon>link</mat-icon> <a href="https://paypal.me/Mindmapp" target="_blank">PayPal</a> </mat-list-item> </mat-list> </div> </section> <mindmapp-footer></mindmapp-footer> </div>
lele79/mindmapp
<|start_filename|>OpenSSL/ssl/ssl.h<|end_filename|> /* * ssl.h * * Copyright (C) <NAME> * See LICENSE for details. * * Export functions and exceptions from the SSL sub module. * See the file RATIONALE for a short explanation of why this module was written. * * Reviewed 2001-07-23 * */ #ifndef PyOpenSSL_SSL_H_ #define PyOpenSSL_SSL_H_ #include <Python.h> #include <pythread.h> #include "context.h" #include "session.h" #include "connection.h" #include "../util.h" #include "../crypto/crypto.h" extern PyObject *ssl_Error, /* Base class */ *ssl_ZeroReturnError, /* Used with SSL_get_erorr */ *ssl_WantReadError, /* ... */ *ssl_WantWriteError, /* ... */ *ssl_WantX509LookupError, /* ... */ *ssl_SysCallError; /* Uses (errno,errstr) */ #define ssl_Context_New_NUM 0 #define ssl_Context_New_RETURN ssl_ContextObj * #define ssl_Context_New_PROTO (int method) #define ssl_Connection_New_NUM 1 #define ssl_Connection_New_RETURN ssl_ConnectionObj * #define ssl_Connection_New_PROTO (ssl_ContextObj *ctx, PyObject *sock) #define ssl_API_pointers 2 #ifdef WITH_THREAD extern int _pyOpenSSL_tstate_key; #endif /* WITH_THREAD */ #ifdef SSL_MODULE extern ssl_Context_New_RETURN ssl_Context_New ssl_Context_New_PROTO; extern ssl_Connection_New_RETURN ssl_Connection_New ssl_Connection_New_PROTO; extern crypto_X509Obj* (*new_x509)(X509*, int); extern crypto_X509NameObj* (*new_x509name)(X509_NAME*, int); extern crypto_X509StoreObj* (*new_x509store)(X509_STORE*, int); #else /* SSL_MODULE */ extern void **ssl_API; #define ssl_Context_New \ (*(ssl_Context_New_RETURN (*)ssl_Context_New_PROTO) ssl_API[ssl_Context_New_NUM]) #define ssl_Connection_New \ (*(ssl_Connection_New_RETURN (*)ssl_Connection_New_PROTO) ssl_API[ssl_Connection_New_NUM]) #define import_SSL() \ { \ PyObject *module = PyImport_ImportModule("OpenSSL.SSL"); \ if (module != NULL) { \ PyObject *module_dict = PyModule_GetDict(module); \ PyObject *c_api_object = PyDict_GetItemString(module_dict, "_C_API"); \ if (PyCObject_Check(c_api_object)) { \ ssl_API = (void **)PyCObject_AsVoidPtr(c_api_object); \ } \ } \ } #endif /* SSL_MODULE */ #endif /* PyOpenSSL_SSL_H_ */ <|start_filename|>OpenSSL/rand/rand.c<|end_filename|> /* * rand.c * * Copyright (C) <NAME> * See LICENSE file for details. * * PRNG management routines, thin wrappers. * See the file RATIONALE for a short explanation of why this module was written. * */ #include <Python.h> /* * In order to get the RAND_screen definition from the rand.h * WIN32 or WINDOWS needs to be defined, otherwise we get a * warning. */ #ifdef MS_WINDOWS # ifndef WIN32 # define WIN32 # endif #endif #include <openssl/rand.h> #include "../util.h" PyObject *rand_Error; static char rand_doc[] = "\n\ PRNG management routines, thin wrappers.\n\ See the file RATIONALE for a short explanation of why this module was written.\n\ "; static char rand_add_doc[] = "\n\ Add data with a given entropy to the PRNG\n\ \n\ :param buffer: Buffer with random data\n\ :param entropy: The entropy (in bytes) measurement of the buffer\n\ :return: None\n\ "; static PyObject * rand_add(PyObject *spam, PyObject *args) { char *buf; int size; double entropy; if (!PyArg_ParseTuple(args, BYTESTRING_FMT "#d:add", &buf, &size, &entropy)) return NULL; RAND_add(buf, size, entropy); Py_INCREF(Py_None); return Py_None; } static char rand_seed_doc[] = "\n\ Alias for rand_add, with entropy equal to length\n\ \n\ :param buffer: Buffer with random data\n\ :return: None\n\ "; static PyObject * rand_seed(PyObject *spam, PyObject *args) { char *buf; int size; if (!PyArg_ParseTuple(args, BYTESTRING_FMT "#:seed", &buf, &size)) return NULL; RAND_seed(buf, size); Py_INCREF(Py_None); return Py_None; } static char rand_status_doc[] = "\n\ Retrieve the status of the PRNG\n\ \n\ :return: True if the PRNG is seeded enough, false otherwise\n\ "; static PyObject * rand_status(PyObject *spam, PyObject *args) { if (!PyArg_ParseTuple(args, ":status")) return NULL; return PyLong_FromLong((long)RAND_status()); } #ifdef MS_WINDOWS static char rand_screen_doc[] = "\n\ Add the current contents of the screen to the PRNG state. Availability:\n\ Windows.\n\ \n\ :return: None\n\ "; static PyObject * rand_screen(PyObject *spam, PyObject *args) { if (!PyArg_ParseTuple(args, ":screen")) return NULL; RAND_screen(); Py_INCREF(Py_None); return Py_None; } #endif static char rand_egd_doc[] = "\n\ Query an entropy gathering daemon (EGD) for random data and add it to the\n\ PRNG. I haven't found any problems when the socket is missing, the function\n\ just returns 0.\n\ \n\ :param path: The path to the EGD socket\n\ :param bytes: (optional) The number of bytes to read, default is 255\n\ :returns: The number of bytes read (NB: a value of 0 isn't necessarily an\n\ error, check rand.status())\n\ "; static PyObject * rand_egd(PyObject *spam, PyObject *args) { char *path; int bytes = 255; if (!PyArg_ParseTuple(args, "s|i:egd", &path, &bytes)) return NULL; return PyLong_FromLong((long)RAND_egd_bytes(path, bytes)); } static char rand_cleanup_doc[] = "\n\ Erase the memory used by the PRNG.\n\ \n\ :return: None\n\ "; static PyObject * rand_cleanup(PyObject *spam, PyObject *args) { if (!PyArg_ParseTuple(args, ":cleanup")) return NULL; RAND_cleanup(); Py_INCREF(Py_None); return Py_None; } static char rand_load_file_doc[] = "\n\ Seed the PRNG with data from a file\n\ \n\ :param filename: The file to read data from\n\ :param maxbytes: (optional) The number of bytes to read, default is\n\ to read the entire file\n\ :return: The number of bytes read\n\ "; static PyObject * rand_load_file(PyObject *spam, PyObject *args) { char *filename; int maxbytes = -1; if (!PyArg_ParseTuple(args, "s|i:load_file", &filename, &maxbytes)) return NULL; return PyLong_FromLong((long)RAND_load_file(filename, maxbytes)); } static char rand_write_file_doc[] = "\n\ Save PRNG state to a file\n\ \n\ :param filename: The file to write data to\n\ :return: The number of bytes written\n\ "; static PyObject * rand_write_file(PyObject *spam, PyObject *args) { char *filename; if (!PyArg_ParseTuple(args, "s:write_file", &filename)) return NULL; return PyLong_FromLong((long)RAND_write_file(filename)); } static char rand_bytes_doc[] = "\n\ Get some randomm bytes as a string.\n\ \n\ :param num_bytes: The number of bytes to fetch\n\ :return: A string of random bytes\n\ "; #if PY_VERSION_HEX < 0x02050000 #define Py_ssize_t int #define PY_SSIZE_FMT "i" #else #define PY_SSIZE_FMT "n" #endif static PyObject * rand_bytes(PyObject *spam, PyObject *args, PyObject *keywds) { Py_ssize_t num_bytes; static char *kwlist[] = {"num_bytes", NULL}; char *buf; unsigned int rc; PyObject *obj = NULL; if (!PyArg_ParseTupleAndKeywords( args, keywds, PY_SSIZE_FMT ":bytes", kwlist, &num_bytes)) { return NULL; } if(num_bytes < 0) { PyErr_SetString(PyExc_ValueError, "num_bytes must not be negative"); return NULL; } buf = malloc(num_bytes); if (buf == NULL) /* out of memory */ return NULL; rc = RAND_bytes((unsigned char *) buf, num_bytes); if(rc != 1) { /* if unsuccessful */ exception_from_error_queue(rand_Error); goto done; } obj = PyBytes_FromStringAndSize(buf, (unsigned) num_bytes); done: free(buf); return obj; } /* Methods in the OpenSSL.rand module */ static PyMethodDef rand_methods[] = { { "add", (PyCFunction)rand_add, METH_VARARGS, rand_add_doc }, { "seed", (PyCFunction)rand_seed, METH_VARARGS, rand_seed_doc }, { "status", (PyCFunction)rand_status, METH_VARARGS, rand_status_doc }, #ifdef MS_WINDOWS { "screen", (PyCFunction)rand_screen, METH_VARARGS, rand_screen_doc }, #endif { "egd", (PyCFunction)rand_egd, METH_VARARGS, rand_egd_doc }, { "cleanup", (PyCFunction)rand_cleanup, METH_VARARGS, rand_cleanup_doc }, { "load_file", (PyCFunction)rand_load_file, METH_VARARGS, rand_load_file_doc }, { "write_file",(PyCFunction)rand_write_file, METH_VARARGS, rand_write_file_doc }, { "bytes", (PyCFunction)rand_bytes, METH_VARARGS|METH_KEYWORDS, rand_bytes_doc }, { NULL, NULL } }; #ifdef PY3 static struct PyModuleDef randmodule = { PyModuleDef_HEAD_INIT, "rand", rand_doc, -1, rand_methods }; #endif /* * Initialize the rand sub module * * Arguments: None * Returns: None */ PyOpenSSL_MODINIT(rand) { PyObject *module; #ifdef PY3 module = PyModule_Create(&randmodule); #else module = Py_InitModule3("rand", rand_methods, rand_doc); #endif if (module == NULL) { PyOpenSSL_MODRETURN(NULL); } rand_Error = PyErr_NewException("OpenSSL.rand.Error", NULL, NULL); if (rand_Error == NULL) { goto error; } /* PyModule_AddObject steals a reference. */ Py_INCREF(rand_Error); if (PyModule_AddObject(module, "Error", rand_Error) != 0) { goto error; } ERR_load_RAND_strings(); PyOpenSSL_MODRETURN(module); error: PyOpenSSL_MODRETURN(NULL); ; } <|start_filename|>OpenSSL/ssl/session.c<|end_filename|> /* * session.c * * Copyright (C) <NAME> * Copyright (C) <NAME> * See LICENSE for details. * * SSL Session object data structures and functions. * */ #include <Python.h> #define SSL_MODULE #include "ssl.h" static char ssl_Session_doc[] = "\n\ Session() -> Session instance\n\ \n\ "; /* * Initialize an already-constructed Session instance with an OpenSSL session * structure (or NULL). A reference to the OpenSSL session structure is stolen. */ static ssl_SessionObj* ssl_Session_init(ssl_SessionObj *self, SSL_SESSION *native_session) { self->session = native_session; return self; } /* * Create a Session object */ static PyObject* ssl_Session_new(PyTypeObject *subtype, PyObject *args, PyObject *kwargs) { ssl_SessionObj *self; if (!PyArg_ParseTuple(args, ":Session")) { return NULL; } self = PyObject_New(ssl_SessionObj, &ssl_Session_Type); if (self == NULL) { return NULL; } return (PyObject *)ssl_Session_init(self, NULL); } /* * Create a Session object from an existing SSL_SESSION*. A reference to the * SSL_SESSION* is stolen. */ ssl_SessionObj* ssl_Session_from_SSL_SESSION(SSL_SESSION *native_session) { ssl_SessionObj *self; self = PyObject_New(ssl_SessionObj, &ssl_Session_Type); if (self == NULL) { return NULL; } return ssl_Session_init(self, native_session); } /* * Discard the reference to the OpenSSL session structure, if there is one, so * that it can be freed if it is no longer in use. Also release the memory for * the Python object. */ static void ssl_Session_dealloc(ssl_SessionObj *self) { if (self->session != NULL) { SSL_SESSION_free(self->session); self->session = NULL; } Py_TYPE(self)->tp_free((PyObject*)self); } /* * Member methods in the Session object * ADD_METHOD(name) expands to a correct PyMethodDef declaration * { 'name', (PyCFunction)ssl_Session_name, METH_VARARGS } * for convenience * ADD_ALIAS(name,real) creates an "alias" of the ssl_Session_real * function with the name 'name' */ #define ADD_METHOD(name) { #name, (PyCFunction)ssl_Session_##name, METH_VARARGS, ssl_Session_##name##_doc } static PyMethodDef ssl_Session_methods[] = { { NULL, NULL } }; #undef ADD_METHOD /* * The Python Session type definition. */ PyTypeObject ssl_Session_Type = { PyOpenSSL_HEAD_INIT(&PyType_Type, 0) "OpenSSL.SSL.Session", sizeof(ssl_SessionObj), 0, (destructor)ssl_Session_dealloc, /* tp_dealloc */ NULL, /* print */ NULL, /* tp_getattr */ NULL, /* setattr */ NULL, /* compare */ NULL, /* repr */ NULL, /* as_number */ NULL, /* as_sequence */ NULL, /* as_mapping */ NULL, /* hash */ NULL, /* call */ NULL, /* str */ NULL, /* getattro */ NULL, /* setattro */ NULL, /* as_buffer */ Py_TPFLAGS_DEFAULT, // Py_TPFLAGS_HAVE_GC, /* tp_flags */ ssl_Session_doc, /* tp_doc */ NULL, // (traverseproc)ssl_Session_traverse, /* tp_traverse */ NULL, // (inquiry)ssl_Session_clear, /* tp_clear */ NULL, /* tp_richcompare */ 0, /* tp_weaklistoffset */ NULL, /* tp_iter */ NULL, /* tp_iternext */ ssl_Session_methods, /* tp_methods */ NULL, /* tp_members */ NULL, /* tp_getset */ NULL, /* tp_base */ NULL, /* tp_dict */ NULL, /* tp_descr_get */ NULL, /* tp_descr_set */ 0, /* tp_dictoffset */ NULL, /* tp_init */ NULL, /* tp_alloc */ ssl_Session_new, /* tp_new */ }; /* * Initialize the Session part of the SSL sub module * * Arguments: dict - The OpenSSL.SSL module * Returns: 1 for success, 0 otherwise */ int init_ssl_session(PyObject *module) { if (PyType_Ready(&ssl_Session_Type) < 0) { return 0; } /* PyModule_AddObject steals a reference. */ Py_INCREF((PyObject *)&ssl_Session_Type); if (PyModule_AddObject(module, "Session", (PyObject *)&ssl_Session_Type) < 0) { return 0; } return 1; } <|start_filename|>OpenSSL/crypto/netscape_spki.c<|end_filename|> /* * netscape_spki.c * * Copyright (C) <NAME> * See LICENSE for details. * * Netscape SPKI handling, thin wrapper */ #include <Python.h> #define crypto_MODULE #include "crypto.h" /* * Constructor for Nestcape_SPKI, never called by Python code directly * * Arguments: name - A "real" NetscapeSPKI object * dealloc - Boolean value to specify whether the destructor should * free the "real" NetscapeSPKI object * Returns: The newly created NetscapeSPKI object */ crypto_NetscapeSPKIObj * crypto_NetscapeSPKI_New(NETSCAPE_SPKI *name, int dealloc) { crypto_NetscapeSPKIObj *self; self = PyObject_New(crypto_NetscapeSPKIObj, &crypto_NetscapeSPKI_Type); if (self == NULL) return NULL; self->netscape_spki = name; self->dealloc = dealloc; return self; } static char crypto_NetscapeSPKI_doc[] = "\n\ NetscapeSPKI([enc]) -> NetscapeSPKI instance\n\ \n\ :param enc: Base64 encoded NetscapeSPKI object.\n\ :type enc: :py:data:`str`\n\ :return: The NetscapeSPKI object\n\ "; static PyObject * crypto_NetscapeSPKI_new(PyTypeObject *subtype, PyObject *args, PyObject *kwargs) { char *enc = NULL; int enc_len = -1; NETSCAPE_SPKI *spki; if (!PyArg_ParseTuple(args, "|s#:NetscapeSPKI", &enc, &enc_len)) return NULL; if (enc_len >= 0) spki = NETSCAPE_SPKI_b64_decode(enc, enc_len); else spki = NETSCAPE_SPKI_new(); if (spki == NULL) { exception_from_error_queue(crypto_Error); return NULL; } return (PyObject *)crypto_NetscapeSPKI_New(spki, 1); } /* * Deallocate the memory used by the NetscapeSPKI object * * Arguments: self - The NetscapeSPKI object * Returns: None */ static void crypto_NetscapeSPKI_dealloc(crypto_NetscapeSPKIObj *self) { /* Sometimes we don't have to dealloc this */ if (self->dealloc) NETSCAPE_SPKI_free(self->netscape_spki); PyObject_Del(self); } static char crypto_NetscapeSPKI_sign_doc[] = "\n\ Sign the certificate request using the supplied key and digest\n\ \n\ :param pkey: The key to sign with\n\ :param digest: The message digest to use\n\ :return: None\n\ "; static PyObject * crypto_NetscapeSPKI_sign(crypto_NetscapeSPKIObj *self, PyObject *args) { crypto_PKeyObj *pkey; char *digest_name; const EVP_MD *digest; if (!PyArg_ParseTuple(args, "O!s:sign", &crypto_PKey_Type, &pkey, &digest_name)) return NULL; if (pkey->only_public) { PyErr_SetString(PyExc_ValueError, "Key has only public part"); return NULL; } if (!pkey->initialized) { PyErr_SetString(PyExc_ValueError, "Key is uninitialized"); return NULL; } if ((digest = EVP_get_digestbyname(digest_name)) == NULL) { PyErr_SetString(PyExc_ValueError, "No such digest method"); return NULL; } if (!NETSCAPE_SPKI_sign(self->netscape_spki, pkey->pkey, digest)) { exception_from_error_queue(crypto_Error); return NULL; } Py_INCREF(Py_None); return Py_None; } static char crypto_NetscapeSPKI_verify_doc[] = "\n\ Verifies a certificate request using the supplied public key\n\ \n\ :param key: a public key\n\ :return: True if the signature is correct.\n\ :raise OpenSSL.crypto.Error: If the signature is invalid or there is a\n\ problem verifying the signature.\n\ "; PyObject * crypto_NetscapeSPKI_verify(crypto_NetscapeSPKIObj *self, PyObject *args) { crypto_PKeyObj *pkey; int answer; if (!PyArg_ParseTuple(args, "O!:verify", &crypto_PKey_Type, &pkey)) { return NULL; } if ((answer = NETSCAPE_SPKI_verify(self->netscape_spki, pkey->pkey)) <= 0) { exception_from_error_queue(crypto_Error); return NULL; } return PyLong_FromLong((long)answer); } static char crypto_NetscapeSPKI_b64_encode_doc[] = "\n\ Generate a base64 encoded string from an SPKI\n\ \n\ :return: The base64 encoded string\n\ "; PyObject * crypto_NetscapeSPKI_b64_encode(crypto_NetscapeSPKIObj *self, PyObject *args) { char *str; if (!PyArg_ParseTuple(args, ":b64_encode")) return NULL; str = NETSCAPE_SPKI_b64_encode(self->netscape_spki); return PyBytes_FromString(str); } static char crypto_NetscapeSPKI_get_pubkey_doc[] = "\n\ Get the public key of the certificate\n\ \n\ :return: The public key\n\ "; static PyObject * crypto_NetscapeSPKI_get_pubkey(crypto_NetscapeSPKIObj *self, PyObject *args) { crypto_PKeyObj *crypto_PKey_New(EVP_PKEY *, int); EVP_PKEY *pkey; crypto_PKeyObj *py_pkey; if (!PyArg_ParseTuple(args, ":get_pubkey")) return NULL; if ((pkey = NETSCAPE_SPKI_get_pubkey(self->netscape_spki)) == NULL) { exception_from_error_queue(crypto_Error); return NULL; } py_pkey = crypto_PKey_New(pkey, 1); if (py_pkey != NULL) { py_pkey->only_public = 1; } return (PyObject *)py_pkey; } static char crypto_NetscapeSPKI_set_pubkey_doc[] = "\n\ Set the public key of the certificate\n\ \n\ :param pkey: The public key\n\ :return: None\n\ "; static PyObject * crypto_NetscapeSPKI_set_pubkey(crypto_NetscapeSPKIObj *self, PyObject *args) { crypto_PKeyObj *pkey; if (!PyArg_ParseTuple(args, "O!:set_pubkey", &crypto_PKey_Type, &pkey)) return NULL; if (!NETSCAPE_SPKI_set_pubkey(self->netscape_spki, pkey->pkey)) { exception_from_error_queue(crypto_Error); return NULL; } Py_INCREF(Py_None); return Py_None; } /* * ADD_METHOD(name) expands to a correct PyMethodDef declaration * { 'name', (PyCFunction)crypto_NetscapeSPKI_name, METH_VARARGS } * for convenience */ #define ADD_METHOD(name) \ { #name, (PyCFunction)crypto_NetscapeSPKI_##name, METH_VARARGS, crypto_NetscapeSPKI_##name##_doc } static PyMethodDef crypto_NetscapeSPKI_methods[] = { ADD_METHOD(get_pubkey), ADD_METHOD(set_pubkey), ADD_METHOD(b64_encode), ADD_METHOD(sign), ADD_METHOD(verify), { NULL, NULL } }; #undef ADD_METHOD PyTypeObject crypto_NetscapeSPKI_Type = { PyOpenSSL_HEAD_INIT(&PyType_Type, 0) "NetscapeSPKI", sizeof(crypto_NetscapeSPKIObj), 0, (destructor)crypto_NetscapeSPKI_dealloc, NULL, /* print */ NULL, /* getattr */ NULL, /* setattr */ NULL, /* compare */ NULL, /* repr */ NULL, /* as_number */ NULL, /* as_sequence */ NULL, /* as_mapping */ NULL, /* hash */ NULL, /* call */ NULL, /* str */ NULL, /* getattro */ NULL, /* setattro */ NULL, /* as_buffer */ Py_TPFLAGS_DEFAULT, crypto_NetscapeSPKI_doc, /* doc */ NULL, /* traverse */ NULL, /* clear */ NULL, /* tp_richcompare */ 0, /* tp_weaklistoffset */ NULL, /* tp_iter */ NULL, /* tp_iternext */ crypto_NetscapeSPKI_methods, /* tp_methods */ NULL, /* tp_members */ NULL, /* tp_getset */ NULL, /* tp_base */ NULL, /* tp_dict */ NULL, /* tp_descr_get */ NULL, /* tp_descr_set */ 0, /* tp_dictoffset */ NULL, /* tp_init */ NULL, /* tp_alloc */ crypto_NetscapeSPKI_new, /* tp_new */ }; /* * Initialize the X509Name part of the crypto module * * Arguments: module - The crypto module * Returns: None */ int init_crypto_netscape_spki(PyObject *module) { if (PyType_Ready(&crypto_NetscapeSPKI_Type) < 0) { return 0; } /* PyModule_AddObject steals a reference */ Py_INCREF((PyObject *)&crypto_NetscapeSPKI_Type); if (PyModule_AddObject(module, "NetscapeSPKI", (PyObject *)&crypto_NetscapeSPKI_Type) != 0) { return 0; } /* PyModule_AddObject steals a reference */ Py_INCREF((PyObject *)&crypto_NetscapeSPKI_Type); if (PyModule_AddObject(module, "NetscapeSPKIType", (PyObject *)&crypto_NetscapeSPKI_Type) != 0) { return 0; } return 1; } <|start_filename|>OpenSSL/ssl/session.h<|end_filename|> /* * session.h * Copyright (C) <NAME> * See LICENSE for details. * * Defined here is the Python type which represents an SSL session by wrapping * an OpenSSL SSL_SESSION*. * */ #ifndef PyOpenSSL_SSL_SESSION_H_ #define PyOpenSSL_SSL_SESSION_H_ #include <Python.h> #include <openssl/ssl.h> typedef struct { PyObject_HEAD SSL_SESSION *session; } ssl_SessionObj; extern PyTypeObject ssl_Session_Type; extern int init_ssl_session(PyObject *); extern ssl_SessionObj *ssl_Session_from_SSL_SESSION(SSL_SESSION *native_session); #endif <|start_filename|>OpenSSL/crypto/x509store.c<|end_filename|> /* * x509store.c * * Copyright (C) <NAME> * See LICENSE for details. * * X.509 Store handling, mostly thin wrapping. * See the file RATIONALE for a short explanation of why this module was written. */ #include <Python.h> #define crypto_MODULE #include "crypto.h" static char crypto_X509Store_add_cert_doc[] = "\n\ Add a certificate\n\ \n\ :param cert: The certificate to add\n\ :return: None\n\ "; static PyObject * crypto_X509Store_add_cert(crypto_X509StoreObj *self, PyObject *args) { crypto_X509Obj *cert; if (!PyArg_ParseTuple(args, "O!:add_cert", &crypto_X509_Type, &cert)) return NULL; if (!X509_STORE_add_cert(self->x509_store, cert->x509)) { exception_from_error_queue(crypto_Error); return NULL; } Py_INCREF(Py_None); return Py_None; } /* * ADD_METHOD(name) expands to a correct PyMethodDef declaration * { 'name', (PyCFunction)crypto_X509Store_name, METH_VARARGS } * for convenience */ #define ADD_METHOD(name) \ { #name, (PyCFunction)crypto_X509Store_##name, METH_VARARGS, crypto_X509Store_##name##_doc } static PyMethodDef crypto_X509Store_methods[] = { ADD_METHOD(add_cert), { NULL, NULL } }; #undef ADD_METHOD /* * Constructor for X509Store, never called by Python code directly * * Arguments: name - A "real" X509_STORE object * dealloc - Boolean value to specify whether the destructor should * free the "real" X509_STORE object * Returns: The newly created X509Store object */ crypto_X509StoreObj * crypto_X509Store_New(X509_STORE *store, int dealloc) { crypto_X509StoreObj *self; self = PyObject_New(crypto_X509StoreObj, &crypto_X509Store_Type); if (self == NULL) return NULL; self->x509_store = store; self->dealloc = dealloc; return self; } /* * Deallocate the memory used by the X509Store object * * Arguments: self - The X509Store object * Returns: None */ static void crypto_X509Store_dealloc(crypto_X509StoreObj *self) { /* Sometimes we don't have to dealloc this */ if (self->dealloc) X509_STORE_free(self->x509_store); PyObject_Del(self); } PyTypeObject crypto_X509Store_Type = { PyOpenSSL_HEAD_INIT(&PyType_Type, 0) "X509Store", sizeof(crypto_X509StoreObj), 0, (destructor)crypto_X509Store_dealloc, NULL, /* print */ NULL, /* getattr */ NULL, /* setattr */ NULL, /* compare */ NULL, /* repr */ NULL, /* as_number */ NULL, /* as_sequence */ NULL, /* as_mapping */ NULL, /* hash */ NULL, /* call */ NULL, /* str */ NULL, /* getattro */ NULL, /* setattro */ NULL, /* as_buffer */ Py_TPFLAGS_DEFAULT, NULL, /* doc */ NULL, /* traverse */ NULL, /* clear */ NULL, /* tp_richcompare */ 0, /* tp_weaklistoffset */ NULL, /* tp_iter */ NULL, /* tp_iternext */ crypto_X509Store_methods, /* tp_methods */ }; /* * Initialize the X509Store part of the crypto module * * Arguments: module - The crypto module * Returns: None */ int init_crypto_x509store(PyObject *module) { if (PyType_Ready(&crypto_X509Store_Type) < 0) { return 0; } /* PyModule_AddObject steals a reference. */ Py_INCREF((PyObject *)&crypto_X509Store_Type); if (PyModule_AddObject(module, "X509StoreType", (PyObject *)&crypto_X509Store_Type) != 0) { return 0; } return 1; }
harnesscloud/remyroy-pyopenssl-shutdown-fix
<|start_filename|>examples/misc/lib/library_tour/core/iterator.dart<|end_filename|> import 'dart:collection'; final Iterator<Process> _it = [Process(), Process(), Process()].iterator; // #docregion class Process { // Represents a process... // #enddocregion static int _nextId = 0; final int id = _nextId++; // #docregion } class ProcessIterator implements Iterator<Process> { @override Process get current => /*...*/ // #enddocregion _it.current; // #docregion @override bool moveNext() => /*...*/ // #enddocregion _it.moveNext(); // #docregion } // A mythical class that lets you iterate through all // processes. Extends a subclass of [Iterable]. class Processes extends IterableBase<Process> { @override final Iterator<Process> iterator = ProcessIterator(); } void main() { // Iterable objects can be used with for-in. for (final process in Processes()) { // Do something with the process. // #enddocregion print(process.id); // #docregion } } <|start_filename|>examples/misc/lib/library_tour/async/stream.dart<|end_filename|> // ignore_for_file: unused_element, unused_local_variable import 'dart:convert'; import 'dart:io'; void miscDeclAnalyzedButNotTested() { const recursive = 0, followLinks = 1; final searchPath = '.', searchTerms = ['']; Map<dynamic, bool> argResults = {}; void searchFile(FileSystemEntity e, List<String> terms) {} { // #docregion listen void main(List<String> arguments) { // ... FileSystemEntity.isDirectory(searchPath).then((isDir) { if (isDir) { final startingDir = Directory(searchPath); startingDir.list().listen((entity) { if (entity is File) { searchFile(entity, searchTerms); } }); } else { searchFile(File(searchPath), searchTerms); } }); } // #enddocregion listen } { // #docregion await-for Future<void> main(List<String> arguments) async { // ... if (await FileSystemEntity.isDirectory(searchPath)) { final startingDir = Directory(searchPath); await for (final entity in startingDir.list()) { if (entity is File) { searchFile(entity, searchTerms); } } } else { searchFile(File(searchPath), searchTerms); } } // #enddocregion await-for } { // #docregion readFileAwaitFor Future<void> readFileAwaitFor() async { var config = File('config.txt'); Stream<List<int>> inputStream = config.openRead(); // #docregion transform var lines = inputStream .transform(utf8.decoder) .transform(const LineSplitter()); // #enddocregion transform try { await for (final line in lines) { print('Got ${line.length} characters from stream'); } print('file is now closed'); } catch (e) { print(e); } } // #enddocregion readFileAwaitFor } { // #docregion onDone var config = File('config.txt'); Stream<List<int>> inputStream = config.openRead(); inputStream .transform(utf8.decoder) .transform(const LineSplitter()) .listen((String line) { print('Got ${line.length} characters from stream'); }, onDone: () { print('file is now closed'); }, onError: (e) { print(e); }); // #enddocregion onDone } }
lukepighetti/site-www
<|start_filename|>libmicroros/include/uxr/client/core/session/create_entities_bin.h<|end_filename|> // Copyright 2018 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef UXR_CLIENT_CORE_SESSION_CREATE_ENTITIES_BIN_H_ #define UXR_CLIENT_CORE_SESSION_CREATE_ENTITIES_BIN_H_ #ifdef __cplusplus extern "C" { #endif // ifdef __cplusplus #include <uxr/client/core/session/common_create_entities.h> #include <uxr/client/core/type/xrce_types.h> //================================================================== // PUBLIC //================================================================== /** * @brief Buffers into the stream identified by `stream_id` an XRCE CREATE submessage with an XRCE Participant payload. * The submessage will be sent when `uxr_flash_output_streams` or `uxr_run_session` function are called. * As a result of the reception of this submessage, the Agent will create an XRCE Participant according to * the binary provided in the CREATE submessage. * @param session A uxrSession structure previously initialized. * @param stream_id The output stream identifier where the CREATE submessage will be buffered. * @param object_id The identifier of the XRCE Participant. * @param domain_id The identifier of the Domain to which the XRCE Participant belongs. * @param participant_name The XRCE Participant name. Can be NULL. * @param mode The set of flags that determines the entity creation mode. * The Creation Mode Table describes the entities creation behaviour according to the * `UXR_REUSE` and `UXR_REPLACE` flags. * @return A `request_id` that identifies the request made by the Client. * This could be used in the `uxr_run_session_until_one_status` or `uxr_run_session_until_all_status` functions. */ UXRDLLAPI uint16_t uxr_buffer_create_participant_bin( uxrSession* session, uxrStreamId stream_id, uxrObjectId object_id, uint16_t domain_id, const char* participant_name, uint8_t mode); /** * @brief Buffers into the stream identified by `stream_id` an XRCE CREATE submessage with an XRCE Topic payload. * The submessage will be sent when `uxr_flash_output_streams` or `uxr_run_session` function are called. * As a result of the reception of this submessage, the Agent will create an XRCE Topic according to * the binary provided in the CREATE submessage. * @param session A uxrSession structure previously initialized. * @param stream_id The output stream identifier where the CREATE submessage will be buffered. * @param object_id The identifier of the XRCE Topic. * @param participant_id The identifier of the associated XRCE Participant. * @param topic_name The XRCE Topic name. * @param type_name The XRCE Topic type. * @param mode The set of flags that determines the entity creation mode. * The Creation Mode Table describes the entities creation behaviour according to the * `UXR_REUSE` and `UXR_REPLACE` flags. * @return A `request_id` that identifies the request made by the Client. * This could be used in the `uxr_run_session_until_one_status` or `uxr_run_session_until_all_status` functions. */ UXRDLLAPI uint16_t uxr_buffer_create_topic_bin( uxrSession* session, uxrStreamId stream_id, uxrObjectId object_id, uxrObjectId participant_id, const char* topic_name, const char* type_name, uint8_t mode); /** * @brief Buffers into the stream identified by `stream_id` an XRCE CREATE submessage with an XRCE Subscriber payload. * The submessage will be sent when `uxr_flash_output_streams` or `uxr_run_session` function are called. * As a result of the reception of this submessage, the Agent will create an XRCE Publisher according to * the binary provided in the CREATE submessage. * @param session A uxrSession structure previously initialized. * @param mode The set of flags that determines the entity creation mode. * The Creation Mode Table describes the entities creation behaviour according to the * `UXR_REUSE` and `UXR_REPLACE` flags. * @return A `request_id` that identifies the request made by the Client. * This could be used in the `uxr_run_session_until_one_status` or `uxr_run_session_until_all_status` functions. */ UXRDLLAPI uint16_t uxr_buffer_create_publisher_bin( uxrSession* session, uxrStreamId stream_id, uxrObjectId object_id, uxrObjectId participant_id, uint8_t mode); /** * @brief Buffers into the stream identified by `stream_id` an XRCE CREATE submessage with an XRCE Subscriber payload. * The submessage will be sent when `uxr_flash_output_streams` or `uxr_run_session` function are called. * As a result of the reception of this submessage, the Agent will create an XRCE Subscriber according to * the binary provided in the CREATE submessage. * @param session A uxrSession structure previously initialized. * @param stream_id The output stream identifier where the CREATE submessage will be buffered. * @param object_id The identifier of the XRCE Subscriber. * @param participant_id The identifier of the associated XRCE Participant. * @param mode The set of flags that determines the entity creation mode. * The Creation Mode Table describes the entities creation behaviour according to the * `UXR_REUSE` and `UXR_REPLACE` flags. * @return A `request_id` that identifies the request made by the Client. * This could be used in the `uxr_run_session_until_one_status` or `uxr_run_session_until_all_status` functions. */ UXRDLLAPI uint16_t uxr_buffer_create_subscriber_bin( uxrSession* session, uxrStreamId stream_id, uxrObjectId object_id, uxrObjectId participant_id, uint8_t mode); /** * The enum that identifies the durability of the QoS of the DDS entity. */ typedef enum uxrQoSDurability { UXR_DURABILITY_VOLATILE = 0, UXR_DURABILITY_TRANSIENT_LOCAL, UXR_DURABILITY_TRANSIENT, UXR_DURABILITY_PERSISTENT } uxrQoSDurability; /** * @brief Buffers into the stream identified by `stream_id` an XRCE CREATE submessage with an XRCE DataWriter payload. * The submessage will be sent when `uxr_flash_output_streams` or `uxr_run_session` function are called. * As a result of the reception of this submessage, the Agent will create an XRCE DataWriter according to * the binary provided in the CREATE submessage. * @param session A uxrSession structure previously initialized. * @param stream_id The output stream identifier where the CREATE submessage will be buffered. * @param object_id The identifier of the XRCE DataWriter. * @param publisher_id The identifier of the associated XRCE Publisher. * @param topic_id The identifier of the associated XRCE Topic. * @param reliable Reliability flag. * @param keep_last Keep last flag. * @param transient_local Transient local flag. * @param mode The set of flags that determines the entity creation mode. * The Creation Mode Table describes the entities creation behaviour according to the * `UXR_REUSE` and `UXR_REPLACE` flags. * @return A `request_id` that identifies the request made by the Client. * This could be used in the `uxr_run_session_until_one_status` or `uxr_run_session_until_all_status` functions. */ UXRDLLAPI uint16_t uxr_buffer_create_datawriter_bin( uxrSession* session, uxrStreamId stream_id, uxrObjectId object_id, uxrObjectId publisher_id, uxrObjectId topic_id, bool reliable, bool keep_last, uxrQoSDurability durability, uint8_t mode); /** * @brief Buffers into the stream identified by `stream_id` an XRCE CREATE submessage with an XRCE DataReader payload. * The submessage will be sent when `uxr_flash_output_streams` or `uxr_run_session` function are called. * As a result of the reception of this submessage, the Agent will create an XRCE DataReader according to * the binary provided in the CREATE submessage. * @param session A uxrSession structure previously initialized. * @param stream_id The output stream identifier where the CREATE submessage will be buffered. * @param object_id The identifier of the XRCE DataReader. * @param subscriber_id The identifier of the associated XRCE Subscriber. * @param topic_id The identifier of the associated XRCE Topic. * @param reliable Reliability flag. * @param keep_last Keep last flag. * @param transient_local Transient local flag. * @param mode The set of flags that determines the entity creation mode. * The Creation Mode Table describes the entities creation behaviour according to the * `UXR_REUSE` and `UXR_REPLACE` flags. * @return A `request_id` that identifies the request made by the Client. * This could be used in the `uxr_run_session_until_one_status` or `uxr_run_session_until_all_status` functions. */ UXRDLLAPI uint16_t uxr_buffer_create_datareader_bin( uxrSession* session, uxrStreamId stream_id, uxrObjectId object_id, uxrObjectId subscriber_id, uxrObjectId topic_id, bool reliable, bool keep_last, uxrQoSDurability durability, uint8_t mode); /** * @brief Buffers into the stream identified by `stream_id` an XRCE CREATE submessage with an XRCE Requester payload. * The submessage will be sent when `uxr_flag_output_streams` or `uxr_run_session` functions are called. * As a result of the reception of this submessage, the Agent will create an XRCE Requester according to * the binary provided in the CREATE submessage. * * @param session A uxrSession structure previously initialized. * @param stream_id The output stream identifier where the CREATE submessage will be buffered. * @param object_id The identifier of the XRCE Requester. * @param participant_id The identifier of the associated XRCE Participant. * @param service_name Requester service name. * @param request_type Requester request type. * @param reply_type Requester reply type. * @param request_topic_name Requester request topic name. * @param reply_topic_name Requester reply topic name. * @param mode The set of flags that determines the entitiy creation mode. * the Creation Mode Table describes the entities creation behaviour according to the * `UXR_REUSE` and `UXR_REPLACE` flags. * @return A `request_id` that identifies the request made by the Client. * This could be used in the `uxr_run_session_until_one_status` or `uxr_run_session_until_all_status` functions. */ UXRDLLAPI uint16_t uxr_buffer_create_requester_bin( uxrSession* session, uxrStreamId stream_id, uxrObjectId object_id, uxrObjectId participant_id, const char* service_name, const char* request_type, const char* reply_type, const char* request_topic_name, const char* reply_topic_name, uint8_t mode); /** * @brief Buffers into the stream identified by `stream_id` an XRCE CREATE submessage with an XRCE Replier payload. * The submessage will be sent when `uxr_flag_output_streams` or `uxr_run_session` functions are called. * As a result of the reception of this submessage, the Agent will create an XRCE Replier according to * the binary provided in the CREATE submessage. * * @param session A uxrSession structure previously initialized. * @param stream_id The output stream identifier where the CREATE submessage will be buffered. * @param object_id The identifier of the XRCE Requester. * @param participant_id The identifier of the associated XRCE Participant. * @param service_name Replier service name. * @param request_type Replier request type. * @param reply_type Replier reply type. * @param request_topic_name Replier request topic name. * @param reply_topic_name Replier reply topic name. * @param mode The set of flags that determines the entitiy creation mode. * the Creation Mode Table describes the entities creation behaviour according to the * `UXR_REUSE` and `UXR_REPLACE` flags. * @return A `request_id` that identifies the request made by the Client. * This could be used in the `uxr_run_session_until_one_status` or `uxr_run_session_until_all_status` functions. */ UXRDLLAPI uint16_t uxr_buffer_create_replier_bin( uxrSession* session, uxrStreamId stream_id, uxrObjectId object_id, uxrObjectId participant_id, const char* service_name, const char* request_type, const char* reply_type, const char* request_topic_name, const char* reply_topic_name, uint8_t mode); #ifdef __cplusplus } #endif // ifdef __cplusplus #endif // UXR_CLIENT_CORE_SESSION_CREATE_ENTITIES_BIN_H_ <|start_filename|>libmicroros/include/composition_interfaces/msg/rosidl_typesupport_microxrcedds_c__visibility_control.h<|end_filename|> // generated from // rosidl_typesupport_microxrcedds_c/resource/rosidl_typesupport_microxrcedds_c__visibility_control.h.in // generated code does not contain a copyright notice #ifndef COMPOSITION_INTERFACES__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ #define COMPOSITION_INTERFACES__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ #if __cplusplus extern "C" { #endif // This logic was borrowed (then namespaced) from the examples on the gcc wiki: // https://gcc.gnu.org/wiki/Visibility #if defined _WIN32 || defined __CYGWIN__ #ifdef __GNUC__ #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_composition_interfaces __attribute__ ((dllexport)) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_composition_interfaces __attribute__ ((dllimport)) #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_composition_interfaces __declspec(dllexport) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_composition_interfaces __declspec(dllimport) #endif #ifdef ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_BUILDING_DLL_composition_interfaces #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_composition_interfaces ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_composition_interfaces #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_composition_interfaces ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_composition_interfaces #endif #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_composition_interfaces __attribute__ ((visibility("default"))) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_composition_interfaces #if __GNUC__ >= 4 #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_composition_interfaces __attribute__ ((visibility("default"))) #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_composition_interfaces #endif #endif #if __cplusplus } #endif #endif // COMPOSITION_INTERFACES__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ <|start_filename|>libmicroros/include/geometry_msgs/msg/rosidl_typesupport_microxrcedds_c__visibility_control.h<|end_filename|> // generated from // rosidl_typesupport_microxrcedds_c/resource/rosidl_typesupport_microxrcedds_c__visibility_control.h.in // generated code does not contain a copyright notice #ifndef GEOMETRY_MSGS__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ #define GEOMETRY_MSGS__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ #if __cplusplus extern "C" { #endif // This logic was borrowed (then namespaced) from the examples on the gcc wiki: // https://gcc.gnu.org/wiki/Visibility #if defined _WIN32 || defined __CYGWIN__ #ifdef __GNUC__ #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_geometry_msgs __attribute__ ((dllexport)) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_geometry_msgs __attribute__ ((dllimport)) #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_geometry_msgs __declspec(dllexport) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_geometry_msgs __declspec(dllimport) #endif #ifdef ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_BUILDING_DLL_geometry_msgs #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_geometry_msgs ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_geometry_msgs #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_geometry_msgs ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_geometry_msgs #endif #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_geometry_msgs __attribute__ ((visibility("default"))) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_geometry_msgs #if __GNUC__ >= 4 #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_geometry_msgs __attribute__ ((visibility("default"))) #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_geometry_msgs #endif #endif #if __cplusplus } #endif #endif // GEOMETRY_MSGS__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ <|start_filename|>pico_uart_transports.h<|end_filename|> #ifndef MICRO_ROS_PICOSDK #define MICRO_ROS_PICOSDK #include <stdio.h> #include <stdint.h> #include <uxr/client/profile/transport/custom/custom_transport.h> bool pico_serial_transport_open(struct uxrCustomTransport * transport); bool pico_serial_transport_close(struct uxrCustomTransport * transport); size_t pico_serial_transport_write(struct uxrCustomTransport* transport, const uint8_t * buf, size_t len, uint8_t * err); size_t pico_serial_transport_read(struct uxrCustomTransport* transport, uint8_t* buf, size_t len, int timeout, uint8_t* err); #endif //MICRO_ROS_PICOSDK <|start_filename|>libmicroros/include/builtin_interfaces/msg/rosidl_typesupport_microxrcedds_c__visibility_control.h<|end_filename|> // generated from // rosidl_typesupport_microxrcedds_c/resource/rosidl_typesupport_microxrcedds_c__visibility_control.h.in // generated code does not contain a copyright notice #ifndef BUILTIN_INTERFACES__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ #define BUILTIN_INTERFACES__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ #if __cplusplus extern "C" { #endif // This logic was borrowed (then namespaced) from the examples on the gcc wiki: // https://gcc.gnu.org/wiki/Visibility #if defined _WIN32 || defined __CYGWIN__ #ifdef __GNUC__ #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_builtin_interfaces __attribute__ ((dllexport)) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_builtin_interfaces __attribute__ ((dllimport)) #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_builtin_interfaces __declspec(dllexport) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_builtin_interfaces __declspec(dllimport) #endif #ifdef ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_BUILDING_DLL_builtin_interfaces #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_builtin_interfaces ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_builtin_interfaces #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_builtin_interfaces ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_builtin_interfaces #endif #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_builtin_interfaces __attribute__ ((visibility("default"))) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_builtin_interfaces #if __GNUC__ >= 4 #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_builtin_interfaces __attribute__ ((visibility("default"))) #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_builtin_interfaces #endif #endif #if __cplusplus } #endif #endif // BUILTIN_INTERFACES__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ <|start_filename|>libmicroros/include/micro_ros_msgs/msg/rosidl_typesupport_microxrcedds_c__visibility_control.h<|end_filename|> // generated from // rosidl_typesupport_microxrcedds_c/resource/rosidl_typesupport_microxrcedds_c__visibility_control.h.in // generated code does not contain a copyright notice #ifndef MICRO_ROS_MSGS__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ #define MICRO_ROS_MSGS__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ #if __cplusplus extern "C" { #endif // This logic was borrowed (then namespaced) from the examples on the gcc wiki: // https://gcc.gnu.org/wiki/Visibility #if defined _WIN32 || defined __CYGWIN__ #ifdef __GNUC__ #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_micro_ros_msgs __attribute__ ((dllexport)) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_micro_ros_msgs __attribute__ ((dllimport)) #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_micro_ros_msgs __declspec(dllexport) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_micro_ros_msgs __declspec(dllimport) #endif #ifdef ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_BUILDING_DLL_micro_ros_msgs #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_micro_ros_msgs ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_micro_ros_msgs #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_micro_ros_msgs ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_micro_ros_msgs #endif #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_micro_ros_msgs __attribute__ ((visibility("default"))) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_micro_ros_msgs #if __GNUC__ >= 4 #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_micro_ros_msgs __attribute__ ((visibility("default"))) #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_micro_ros_msgs #endif #endif #if __cplusplus } #endif #endif // MICRO_ROS_MSGS__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ <|start_filename|>pico_uart_transport.c<|end_filename|> #include <stdio.h> #include "pico/stdlib.h" #include <uxr/client/profile/transport/custom/custom_transport.h> void usleep(uint64_t us) { sleep_us(us); } int clock_gettime(clockid_t unused, struct timespec *tp) { uint64_t m = time_us_64(); tp->tv_sec = m / 1000000; tp->tv_nsec = (m % 1000000) * 1000; return 0; } bool pico_serial_transport_open(struct uxrCustomTransport * transport) { stdio_init_all(); return true; } bool pico_serial_transport_close(struct uxrCustomTransport * transport) { return true; } size_t pico_serial_transport_write(struct uxrCustomTransport * transport, uint8_t *buf, size_t len, uint8_t *errcode) { for (size_t i = 0; i < len; i++) { if (buf[i] != putchar(buf[i])) { *errcode = 1; return i; } } return len; } size_t pico_serial_transport_read(struct uxrCustomTransport * transport, uint8_t *buf, size_t len, int timeout, uint8_t *errcode) { uint64_t start_time_us = time_us_64(); for (size_t i = 0; i < len; i++) { int64_t elapsed_time_us = timeout * 1000 - (time_us_64() - start_time_us); if (elapsed_time_us < 0) { *errcode = 1; return i; } int character = getchar_timeout_us(elapsed_time_us); if (character == PICO_ERROR_TIMEOUT) { *errcode = 1; return i; } buf[i] = character; } return len; } <|start_filename|>libmicroros/include/rmw_microros/ping.h<|end_filename|> // Copyright 2021 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @file */ #ifndef RMW_MICROROS__PING_H_ #define RMW_MICROROS__PING_H_ #include <rmw/rmw.h> #include <rmw/ret_types.h> #include <rmw/init_options.h> #include <rmw_microxrcedds_c/config.h> #include <ucdr/microcdr.h> #ifdef RMW_UXRCE_TRANSPORT_CUSTOM #include <uxr/client/profile/transport/custom/custom_transport.h> #endif // RMW_MICROROS__PING_H_ #if defined(__cplusplus) extern "C" { #endif // if defined(__cplusplus) /** \addtogroup rmw micro-ROS RMW API * @{ */ /** * \brief Check if micro-ROS Agent is up and running. * This function can be called even when the micro-ROS context has not yet been * initialized by the application logics. * \param[in] timeout_ms Timeout in ms (per attempt). * \param[in] attempts Number of tries before considering the ping as failed. * \return RMW_RET_OK If micro-ROS Agent is available. * \return RMW_RET_ERROR If micro-ROS Agent is not available. */ rmw_ret_t rmw_uros_ping_agent( const int timeout_ms, const uint8_t attempts); /** * \brief Check if micro-ROS Agent is up and running using the transport set on the given rmw options. * This function can be called even when the micro-ROS context has not yet been initialized. * The transport will be initialized and closed once during the ping process. * \param[in] timeout_ms Timeout in ms (per attempt). * \param[in] attempts Number of tries before considering the ping as failed. * \param[in] rmw_options rmw options with populated transport parameters. * \return RMW_RET_OK If micro-ROS Agent is available. * \return RMW_RET_ERROR If micro-ROS Agent is not available. */ rmw_ret_t rmw_uros_ping_agent_options( const int timeout_ms, const uint8_t attempts, rmw_init_options_t * rmw_options); /** @}*/ #if defined(__cplusplus) } #endif // if defined(__cplusplus) #endif // RMW_MICROROS__PING_H_ <|start_filename|>libmicroros/include/rmw_uros/options.h<|end_filename|> // Copyright 2019 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef RMW_UROS__OPTIONS_H_ #define RMW_UROS__OPTIONS_H_ #include <rmw/rmw.h> #include <rmw/ret_types.h> #include <rmw/init_options.h> #include <rmw_microxrcedds_c/config.h> #include <ucdr/microcdr.h> #ifdef RMW_UXRCE_TRANSPORT_CUSTOM #include <uxr/client/profile/transport/custom/custom_transport.h> #endif // RMW_UROS__OPTIONS_H_ #if defined(__cplusplus) extern "C" { #endif // if defined(__cplusplus) #ifdef RMW_UXRCE_TRANSPORT_IPV4 #define MAX_IP_LEN 16 #elif defined(RMW_UXRCE_TRANSPORT_IPV6) #define MAX_IP_LEN 39 #endif // ifdef RMW_UXRCE_TRANSPORT_IPV4 #define MAX_PORT_LEN 5 #define MAX_SERIAL_DEVICE 50 typedef struct rmw_uxrce_transport_params_t { #if defined(RMW_UXRCE_TRANSPORT_SERIAL) char serial_device[MAX_SERIAL_DEVICE]; #elif defined(RMW_UXRCE_TRANSPORT_UDP) char agent_address[MAX_IP_LEN]; char agent_port[MAX_PORT_LEN]; #elif defined(RMW_UXRCE_TRANSPORT_CUSTOM) bool framing; void* args; open_custom_func open_cb; close_custom_func close_cb; write_custom_func write_cb; read_custom_func read_cb; #endif // if defined(RMW_UXRCE_TRANSPORT_SERIAL) uint32_t client_key; } rmw_uxrce_transport_params_t; /** * \brief Returns the time synchronization state of the epoch time. * \return true if last time synchronization succeded and false otherwise */ bool rmw_uros_epoch_synchronized(); /** * \brief Returns the epoch time in milliseconds taking into account the offset computed during the time synchronization. * \return epoch time in milliseconds. * \return 0 if session is not initialized. */ int64_t rmw_uros_epoch_millis(); /** * \brief Returns the epoch time in nanoseconds taking into account the offset computed during the time synchronization. * \return epoch time in nanoseconds. * \return 0 if session is not initialized. */ int64_t rmw_uros_epoch_nanos(); /** * \brief Synchronizes the session time using the NTP protocol. * \param[in] timeout_ms The waiting time in milliseconds. * \return RMW_RET_OK when success. * \return RMW_RET_ERROR If no session is running or the synchronization fails. */ rmw_ret_t rmw_uros_sync_session( const int timeout_ms); /** * \brief Parses command line args and fills rmw implementation-specific options. * `rmw_init_options allocator` is used to allocate the specific rmw options. * * \param[in] argc Number of arguments. * \param[in] argv Arguments. * \param[in,out] rmw_options Updated options with rmw specifics. * \return RMW_RET_OK If arguments were valid and set in rmw_init_options. * \return RMW_RET_INVALID_ARGUMENT If rmw_init_options is not valid or unexpected arguments. */ rmw_ret_t rmw_uros_init_options( int argc, const char* const argv[], rmw_init_options_t* rmw_options); /** * \brief Fills rmw implementation-specific options with the given parameters. * * \param[in] dev Serial device. * \param[in,out] rmw_options Updated options with rmw specifics. * \return RMW_RET_OK If arguments were valid and set in rmw_init_options. * \return RMW_RET_INVALID_ARGUMENT If rmw_init_options is not valid or unexpected arguments. */ rmw_ret_t rmw_uros_options_set_serial_device( const char* dev, rmw_init_options_t* rmw_options); /** * \brief Fills rmw implementation-specific options with the given parameters. * * \param[in] ip Agent IP address. * \param[in] port Agent UDP port. * \param[in,out] rmw_options Updated options with rmw specifics. * \return RMW_RET_OK If arguments were valid and set in rmw_init_options. * \return RMW_RET_INVALID_ARGUMENT If rmw_init_options is not valid or unexpected arguments. */ rmw_ret_t rmw_uros_options_set_udp_address( const char* ip, const char* port, rmw_init_options_t* rmw_options); /** * \brief Fills rmw implementation-specific options with the autodicovered address of an micro-ROS Agent. * * \param[in,out] rmw_options Updated options with rmw specifics. * \return RMW_RET_OK If arguments were valid and set in rmw_init_options. * \return RMW_RET_TIMEOUT If micro-ROS agent autodiscovery is timeout. * \return RMW_RET_INVALID_ARGUMENT If rmw_init_options is not valid or unexpected arguments. */ rmw_ret_t rmw_uros_discover_agent( rmw_init_options_t* rmw_options); /** * \brief Fills rmw implementation-specific options with the given parameters. * * \param[in] client_key MicroXRCE-DDS client key. * \param[in,out] rmw_options Updated options with rmw specifics. * \return RMW_RET_OK If arguments were valid and set in rmw_init_options. * \return RMW_RET_INVALID_ARGUMENT If rmw_init_options is not valid or unexpected arguments. */ rmw_ret_t rmw_uros_options_set_client_key( uint32_t client_key, rmw_init_options_t* rmw_options); /** * \brief Check if micro-ROS Agent is up and running. * This function can be called even when the micro-ROS context has not yet been * initialized by the application logics. * \param[in] timeout_ms Timeout in ms (per attempt). * \param[in] attempts Number of tries before considering the ping as failed. * \return RMW_RET_OK If micro-ROS Agent is available. * \return RMW_RET_ERROR If micro-ROS Agent is not available. */ rmw_ret_t rmw_uros_ping_agent( const int timeout_ms, const uint8_t attempts); /** * \brief Sets the callback functions for continous serialization for a publisher * * \param[in] publisher publisher where continous serialization is being configured * \param[in] size_cb callback that should modify the total serialization size * \param[in] serialization_cb callback that should serialize the user part of the message */ typedef void (* rmw_uros_continous_serialization_size)( uint32_t* topic_length); typedef void (* rmw_uros_continous_serialization)( ucdrBuffer* ucdr); void rmw_uros_set_continous_serialization_callbacks( rmw_publisher_t* publisher, rmw_uros_continous_serialization_size size_cb, rmw_uros_continous_serialization serialization_cb); #ifdef RMW_UXRCE_TRANSPORT_CUSTOM extern rmw_uxrce_transport_params_t rmw_uxrce_transport_default_params; /** * \brief Check if micro-ROS Agent answers to micro-ROS client * * \param[in] framing Enable XRCE framing. * \param[in] args Arguments for open function. * \param[in] open_cb Open transport callback. * \param[in] close_cb Close transport callback. * \param[in] write_cb Write transport callback. * \param[in] read_cb Read transport callback. * \return RMW_RET_OK If correct. * \return RMW_RET_ERROR If invalid. */ rmw_ret_t rmw_uros_set_custom_transport( bool framing, void* args, open_custom_func open_cb, close_custom_func close_cb, write_custom_func write_cb, read_custom_func read_cb); #endif //RMW_UXRCE_TRANSPORT_CUSTOM #if defined(__cplusplus) } #endif // if defined(__cplusplus) #endif // RMW_UROS__OPTIONS_H_ <|start_filename|>libmicroros/include/visualization_msgs/msg/rosidl_typesupport_microxrcedds_c__visibility_control.h<|end_filename|> // generated from // rosidl_typesupport_microxrcedds_c/resource/rosidl_typesupport_microxrcedds_c__visibility_control.h.in // generated code does not contain a copyright notice #ifndef VISUALIZATION_MSGS__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ #define VISUALIZATION_MSGS__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ #if __cplusplus extern "C" { #endif // This logic was borrowed (then namespaced) from the examples on the gcc wiki: // https://gcc.gnu.org/wiki/Visibility #if defined _WIN32 || defined __CYGWIN__ #ifdef __GNUC__ #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_visualization_msgs __attribute__ ((dllexport)) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_visualization_msgs __attribute__ ((dllimport)) #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_visualization_msgs __declspec(dllexport) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_visualization_msgs __declspec(dllimport) #endif #ifdef ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_BUILDING_DLL_visualization_msgs #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_visualization_msgs ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_visualization_msgs #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_visualization_msgs ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_visualization_msgs #endif #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_visualization_msgs __attribute__ ((visibility("default"))) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_visualization_msgs #if __GNUC__ >= 4 #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_visualization_msgs __attribute__ ((visibility("default"))) #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_visualization_msgs #endif #endif #if __cplusplus } #endif #endif // VISUALIZATION_MSGS__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ <|start_filename|>libmicroros/include/unique_identifier_msgs/msg/rosidl_typesupport_microxrcedds_c__visibility_control.h<|end_filename|> // generated from // rosidl_typesupport_microxrcedds_c/resource/rosidl_typesupport_microxrcedds_c__visibility_control.h.in // generated code does not contain a copyright notice #ifndef UNIQUE_IDENTIFIER_MSGS__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ #define UNIQUE_IDENTIFIER_MSGS__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ #if __cplusplus extern "C" { #endif // This logic was borrowed (then namespaced) from the examples on the gcc wiki: // https://gcc.gnu.org/wiki/Visibility #if defined _WIN32 || defined __CYGWIN__ #ifdef __GNUC__ #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_unique_identifier_msgs __attribute__ ((dllexport)) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_unique_identifier_msgs __attribute__ ((dllimport)) #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_unique_identifier_msgs __declspec(dllexport) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_unique_identifier_msgs __declspec(dllimport) #endif #ifdef ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_BUILDING_DLL_unique_identifier_msgs #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_unique_identifier_msgs ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_unique_identifier_msgs #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_unique_identifier_msgs ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_unique_identifier_msgs #endif #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_unique_identifier_msgs __attribute__ ((visibility("default"))) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_unique_identifier_msgs #if __GNUC__ >= 4 #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_unique_identifier_msgs __attribute__ ((visibility("default"))) #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_unique_identifier_msgs #endif #endif #if __cplusplus } #endif #endif // UNIQUE_IDENTIFIER_MSGS__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ <|start_filename|>libmicroros/include/test_msgs/msg/rosidl_typesupport_microxrcedds_c__visibility_control.h<|end_filename|> // generated from // rosidl_typesupport_microxrcedds_c/resource/rosidl_typesupport_microxrcedds_c__visibility_control.h.in // generated code does not contain a copyright notice #ifndef TEST_MSGS__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ #define TEST_MSGS__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ #if __cplusplus extern "C" { #endif // This logic was borrowed (then namespaced) from the examples on the gcc wiki: // https://gcc.gnu.org/wiki/Visibility #if defined _WIN32 || defined __CYGWIN__ #ifdef __GNUC__ #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_test_msgs __attribute__ ((dllexport)) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_test_msgs __attribute__ ((dllimport)) #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_test_msgs __declspec(dllexport) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_test_msgs __declspec(dllimport) #endif #ifdef ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_BUILDING_DLL_test_msgs #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_test_msgs ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_test_msgs #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_test_msgs ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_test_msgs #endif #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_test_msgs __attribute__ ((visibility("default"))) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_test_msgs #if __GNUC__ >= 4 #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_test_msgs __attribute__ ((visibility("default"))) #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_test_msgs #endif #endif #if __cplusplus } #endif #endif // TEST_MSGS__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ <|start_filename|>microros_static_library/library_generation/toolchain.cmake<|end_filename|> include($ENV{PICO_SDK_PATH}/cmake/preload/toolchains/find_compiler.cmake) set(CMAKE_SYSTEM_NAME Generic) set(CMAKE_CROSSCOMPILING 1) set(CMAKE_SYSTEM_PROCESSOR cortex-m0plus) set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) if (NOT PICO_GCC_TRIPLE) if (DEFINED ENV{PICO_GCC_TRIPLE}) set(PICO_GCC_TRIPLE $ENV{PICO_GCC_TRIPLE}) message("PICO_GCC_TRIPLE set from environment: $ENV{PICO_GCC_TRIPLE}") else() set(PICO_GCC_TRIPLE arm-none-eabi) message("PICO_GCC_TRIPLE defaulted to arm-none-eabi") endif() endif() pico_find_compiler(PICO_COMPILER_CC ${PICO_GCC_TRIPLE}-gcc) pico_find_compiler(PICO_COMPILER_CXX ${PICO_GCC_TRIPLE}-g++) set(CMAKE_C_COMPILER ${PICO_COMPILER_CC} CACHE FILEPATH "C compiler") set(CMAKE_CXX_COMPILER ${PICO_COMPILER_CXX} CACHE FILEPATH "C++ compiler") SET(CMAKE_C_COMPILER_WORKS 1 CACHE INTERNAL "") SET(CMAKE_CXX_COMPILER_WORKS 1 CACHE INTERNAL "") set(FLAGS "-O2 -march=armv6-m -mcpu=cortex-m0plus -mthumb -ffunction-sections -fdata-sections -fno-exceptions -nostdlib -D'RCUTILS_LOG_MIN_SEVERITY=RCUTILS_LOG_MIN_SEVERITY_NONE'" CACHE STRING "" FORCE) set(CMAKE_C_FLAGS_INIT "-std=c11 ${FLAGS} -DCLOCK_MONOTONIC=0 -D'__attribute__(x)='" CACHE STRING "" FORCE) set(CMAKE_CXX_FLAGS_INIT "-std=c++14 ${FLAGS} -fno-rtti -DCLOCK_MONOTONIC=0 -D'__attribute__(x)='" CACHE STRING "" FORCE) <|start_filename|>libmicroros/include/std_srvs/msg/rosidl_typesupport_microxrcedds_c__visibility_control.h<|end_filename|> // generated from // rosidl_typesupport_microxrcedds_c/resource/rosidl_typesupport_microxrcedds_c__visibility_control.h.in // generated code does not contain a copyright notice #ifndef STD_SRVS__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ #define STD_SRVS__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ #if __cplusplus extern "C" { #endif // This logic was borrowed (then namespaced) from the examples on the gcc wiki: // https://gcc.gnu.org/wiki/Visibility #if defined _WIN32 || defined __CYGWIN__ #ifdef __GNUC__ #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_std_srvs __attribute__ ((dllexport)) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_std_srvs __attribute__ ((dllimport)) #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_std_srvs __declspec(dllexport) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_std_srvs __declspec(dllimport) #endif #ifdef ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_BUILDING_DLL_std_srvs #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_std_srvs ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_std_srvs #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_std_srvs ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_std_srvs #endif #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_std_srvs __attribute__ ((visibility("default"))) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_std_srvs #if __GNUC__ >= 4 #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_std_srvs __attribute__ ((visibility("default"))) #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_std_srvs #endif #endif #if __cplusplus } #endif #endif // STD_SRVS__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ <|start_filename|>libmicroros/include/shape_msgs/msg/rosidl_typesupport_microxrcedds_c__visibility_control.h<|end_filename|> // generated from // rosidl_typesupport_microxrcedds_c/resource/rosidl_typesupport_microxrcedds_c__visibility_control.h.in // generated code does not contain a copyright notice #ifndef SHAPE_MSGS__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ #define SHAPE_MSGS__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_ #if __cplusplus extern "C" { #endif // This logic was borrowed (then namespaced) from the examples on the gcc wiki: // https://gcc.gnu.org/wiki/Visibility #if defined _WIN32 || defined __CYGWIN__ #ifdef __GNUC__ #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_shape_msgs __attribute__ ((dllexport)) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_shape_msgs __attribute__ ((dllimport)) #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_shape_msgs __declspec(dllexport) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_shape_msgs __declspec(dllimport) #endif #ifdef ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_BUILDING_DLL_shape_msgs #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_shape_msgs ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_shape_msgs #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_shape_msgs ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_shape_msgs #endif #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_EXPORT_shape_msgs __attribute__ ((visibility("default"))) #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_IMPORT_shape_msgs #if __GNUC__ >= 4 #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_shape_msgs __attribute__ ((visibility("default"))) #else #define ROSIDL_TYPESUPPORT_MICROXRCEDDS_C_PUBLIC_shape_msgs #endif #endif #if __cplusplus } #endif #endif // SHAPE_MSGS__MSG__ROSIDL_TYPESUPPORT_MICROXRCEDDS_C__VISIBILITY_CONTROL_H_
EbbeFuglsang/micro_ros_raspberrypi_pico_sdk
<|start_filename|>pixel_renderer/src/shaders/shader.vert<|end_filename|> #version 450 layout(location = 1) out vec2 frag_tex_coord; void main() { // generate a triangle covering the entire screen along with the // appropriate texture coordinates using just gl_VertexIndex frag_tex_coord = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2); gl_Position = vec4(frag_tex_coord * 2.0f + -1.0f, 0.0f, 1.0f); } <|start_filename|>pixel_renderer/src/shaders/shader.frag<|end_filename|> #version 450 // no idea what this does #extension GL_ARB_separate_shader_objects : enable // output to framebuffer at index 0 layout(location = 0) out vec4 out_color; layout(location = 1) in vec2 frag_tex_coord; layout(binding = 0) uniform sampler2D tex_sampler; void main() { out_color = texture(tex_sampler, frag_tex_coord); }
devins2518/nees
<|start_filename|>RFU/version.cpp<|end_filename|> #include "rfu.h" #include <Windows.h> #pragma comment(lib, "WinInet.lib") #include <WinInet.h> #include <string> #include <regex> bool HttpRequest(const char* url, std::string& response) { if (auto* const internet = InternetOpenA("LewisTehMinerz/RFU", INTERNET_OPEN_TYPE_PRECONFIG, nullptr, nullptr, NULL)) { if (auto* const request = InternetOpenUrlA(internet, url, nullptr, 0, INTERNET_FLAG_NO_UI | INTERNET_FLAG_NO_CACHE_WRITE, NULL)) { char buffer[1024]; DWORD bytes_read; while (InternetReadFile(request, buffer, sizeof buffer, &bytes_read) && bytes_read > 0) { response.append(buffer, bytes_read); } InternetCloseHandle(internet); InternetCloseHandle(request); return true; } InternetCloseHandle(internet); return false; } return false; } bool CheckForUpdates() { std::string response; if (!HttpRequest("https://api.github.com/repos/" RFU_GITHUB_REPO "/releases/latest", response)) { MessageBoxA(nullptr, "Failed to connect to Github", "Update Check", MB_OK); return false; } std::smatch matches; std::regex_search(response, matches, std::regex(R"x("tag_name":\s*"v?([^"]+))x")); // "tag_name":\s*"v?(.+)" if (matches.size() <= 1) { printf("Response: %s\n", response.c_str()); MessageBoxA(nullptr, "Invalid response", "Update Check", MB_OK); return false; } const auto latest_version = matches[1].str(); if (latest_version != RFU_VERSION) { char buffer[256]; sprintf_s(buffer, "A new version of RFU is available.\n\nCurrent Version: %s\nLatest Version: %s\n\nVisit download page?", // ReSharper disable once CppPrintfExtraArg RFU_VERSION, latest_version.c_str()); if (MessageBoxA(nullptr, buffer, "Update Check", MB_YESNOCANCEL | MB_ICONEXCLAMATION) == IDYES) { ShellExecuteA(nullptr, "open", "https://github.com/" RFU_GITHUB_REPO "/releases", nullptr, nullptr, SW_SHOWNORMAL); return true; } } return false; } <|start_filename|>RFU/ui.cpp<|end_filename|> #include <Windows.h> #include <shellapi.h> #include <cstdio> #include "ui.h" #include <iostream> #include <string> #include "resource.h" #include "settings.h" #include "rfu.h" // ReSharper disable CppClangTidyCppcoreguidelinesMacroUsage #define RFU_TRAYICON (WM_APP + 1) #define RFU_TRAYMENU_APC (WM_APP + 2) #define RFU_TRAYMENU_CONSOLE (WM_APP + 3) #define RFU_TRAYMENU_EXIT (WM_APP + 4) //#define RFU_TRAYMENU_VSYNC (WM_APP + 5) #define RFU_TRAYMENU_LOADSET (WM_APP + 6) #define RFU_TRAYMENU_GITHUB (WM_APP + 7) #define RFU_TRAYMENU_STUDIO (WM_APP + 8) #define RFU_TRAYMENU_CFU (WM_APP + 9) #define RFU_TRAYMENU_ADV_NBE (WM_APP + 10) #define RFU_TRAYMENU_ADV_SE (WM_APP + 11) #define RFU_TRAYMENU_STARTUP (WM_APP + 12) #define RFU_TRAYMENU_CLIENT (WM_APP + 13) #define RFU_FCS_FIRST (WM_APP + 20) #define RFU_FCS_NONE RFU_FCS_FIRST // ReSharper enable CppClangTidyCppcoreguidelinesMacroUsage HWND UI::Window = nullptr; int UI::AttachedProcessesCount = 0; bool UI::IsConsoleOnly = false; bool UI::IsSilent = false; HANDLE WatchThread; NOTIFYICONDATA NotifyIconData; LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { if (uMsg == RFU_TRAYICON) { if (lParam == WM_RBUTTONDOWN || lParam == WM_LBUTTONDOWN) { POINT position; GetCursorPos(&position); auto* const popup = CreatePopupMenu(); std::wstring attachedProcsRaw = L"Attached Processes: "; attachedProcsRaw += std::to_wstring(UI::AttachedProcessesCount); auto* const attachedProcs = attachedProcsRaw.data(); AppendMenu(popup, MF_STRING | MF_GRAYED, RFU_TRAYMENU_APC, L"Version: " RFU_VERSION); AppendMenu(popup, MF_STRING | MF_GRAYED, RFU_TRAYMENU_APC, attachedProcs); AppendMenu(popup, MF_SEPARATOR, 0, nullptr); AppendMenu(popup, MF_STRING | (Settings::UnlockClient ? MF_CHECKED : 0), RFU_TRAYMENU_CLIENT, L"Unlock Client"); AppendMenu(popup, MF_STRING | (Settings::UnlockStudio ? MF_CHECKED : 0), RFU_TRAYMENU_STUDIO, L"Unlock Studio"); AppendMenu(popup, MF_STRING | (Settings::CheckForUpdates ? MF_CHECKED : 0), RFU_TRAYMENU_CFU, L"Check for Updates"); auto* submenu = CreatePopupMenu(); AppendMenu(submenu, MF_STRING, RFU_FCS_NONE, L"None"); for (size_t i = 0; i < Settings::FPSCapValues.size(); i++) { auto value = Settings::FPSCapValues[i]; WCHAR name[16] = { 0 }; if (static_cast<int>(value) == value) _snwprintf_s(name, sizeof(name), L"%d", static_cast<int>(value)); else _snwprintf_s(name, sizeof(name), L"%.2f", value); AppendMenu(submenu, MF_STRING, RFU_FCS_NONE + i + 1, name); } CheckMenuRadioItem(submenu, RFU_FCS_FIRST, RFU_FCS_FIRST + Settings::FPSCapValues.size(), RFU_FCS_FIRST + Settings::FPSCapSelection, MF_BYCOMMAND); AppendMenu(popup, MF_POPUP, reinterpret_cast<UINT_PTR>(submenu), L"FPS Cap"); auto* advanced = CreatePopupMenu(); AppendMenu(advanced, MF_STRING | (Settings::SilentErrors ? MF_CHECKED : 0), RFU_TRAYMENU_ADV_SE, L"Silent Errors"); AppendMenu(advanced, MF_STRING | (Settings::SilentErrors ? MF_GRAYED : 0) | ( Settings::NonBlockingErrors ? MF_CHECKED : 0), RFU_TRAYMENU_ADV_NBE, L"Use Console Errors"); AppendMenu(popup, MF_POPUP, reinterpret_cast<UINT_PTR>(advanced), L"Advanced"); AppendMenu(popup, MF_SEPARATOR, 0, nullptr); AppendMenu(popup, MF_STRING, RFU_TRAYMENU_LOADSET, L"Load Settings"); AppendMenu(popup, MF_STRING, RFU_TRAYMENU_CONSOLE, L"Toggle Console"); AppendMenu(popup, MF_STRING, RFU_TRAYMENU_GITHUB, L"Visit GitHub"); AppendMenu(popup, MF_STRING | (RunsOnStartup() ? MF_CHECKED : 0), RFU_TRAYMENU_STARTUP, L"Run on Startup"); AppendMenu(popup, MF_STRING, RFU_TRAYMENU_EXIT, L"Exit"); SetForegroundWindow(hwnd); // to allow "clicking away" const auto result = TrackPopupMenu(popup, TPM_RETURNCMD | TPM_TOPALIGN | TPM_LEFTALIGN, position.x, // NOLINT(misc-redundant-expression) position.y, 0, hwnd, nullptr); // clarity if (result != 0) { switch (result) { case RFU_TRAYMENU_EXIT: Shell_NotifyIcon(NIM_DELETE, &NotifyIconData); #pragma warning( push ) #pragma warning( disable : 6258 ) // app quits anyway, why do we care about improper thread termination? TerminateThread(WatchThread, 0); #pragma warning( pop ) FreeConsole(); PostQuitMessage(0); break; case RFU_TRAYMENU_CONSOLE: UI::ToggleConsole(); break; case RFU_TRAYMENU_GITHUB: ShellExecuteA(nullptr, "open", "https://github.com/" RFU_GITHUB_REPO, nullptr, nullptr, SW_SHOWNORMAL); break; case RFU_TRAYMENU_LOADSET: Settings::Load(); Settings::Update(); break; case RFU_TRAYMENU_CLIENT: Settings::UnlockClient = !Settings::UnlockClient; CheckMenuItem(popup, RFU_TRAYMENU_CLIENT, Settings::UnlockClient ? MF_CHECKED : MF_UNCHECKED); break; case RFU_TRAYMENU_STUDIO: Settings::UnlockStudio = !Settings::UnlockStudio; CheckMenuItem(popup, RFU_TRAYMENU_STUDIO, Settings::UnlockStudio ? MF_CHECKED : MF_UNCHECKED); break; case RFU_TRAYMENU_CFU: Settings::CheckForUpdates = !Settings::CheckForUpdates; CheckMenuItem(popup, RFU_TRAYMENU_CFU, Settings::CheckForUpdates ? MF_CHECKED : MF_UNCHECKED); break; case RFU_TRAYMENU_ADV_NBE: Settings::NonBlockingErrors = !Settings::NonBlockingErrors; CheckMenuItem(popup, RFU_TRAYMENU_ADV_NBE, Settings::NonBlockingErrors ? MF_CHECKED : MF_UNCHECKED); break; case RFU_TRAYMENU_ADV_SE: Settings::SilentErrors = !Settings::SilentErrors; CheckMenuItem(popup, RFU_TRAYMENU_ADV_SE, Settings::SilentErrors ? MF_CHECKED : MF_UNCHECKED); if (Settings::SilentErrors) CheckMenuItem(popup, RFU_TRAYMENU_ADV_NBE, MF_GRAYED); break; case RFU_TRAYMENU_STARTUP: // switch SetRunOnStartup(!RunsOnStartup()); break; default: if (result >= RFU_FCS_FIRST && result <= RFU_FCS_FIRST + Settings::FPSCapValues.size()) { Settings::FPSCapSelection = result - RFU_FCS_FIRST; // NOLINT(clang-diagnostic-implicit-int-conversion) Settings::FPSCap = Settings::FPSCapSelection == 0 ? 0.0 : Settings::FPSCapValues[Settings::FPSCapSelection - 1]; } } if (result != RFU_TRAYMENU_CONSOLE && result != RFU_TRAYMENU_LOADSET && result != RFU_TRAYMENU_GITHUB && result != RFU_TRAYMENU_STARTUP && result != RFU_TRAYMENU_EXIT) { Settings::Update(); Settings::Save(); } } return 1; } } else { return DefWindowProc(hwnd, uMsg, wParam, lParam); } return 0; } bool IsConsoleVisible = false; void UI::SetConsoleVisible(bool visible) { IsConsoleVisible = visible; ShowWindow(GetConsoleWindow(), visible ? SW_SHOWNORMAL : SW_HIDE); } void UI::CreateHiddenConsole() { AllocConsole(); const auto hIcon = reinterpret_cast<LPARAM>(GetIcon(GetModuleHandle(nullptr), IsAppDarkMode())); SendMessage(GetConsoleWindow(), WM_SETICON, ICON_BIG, hIcon); SendMessage(GetConsoleWindow(), WM_SETICON, ICON_SMALL, hIcon); FILE* pCout{}; FILE* pCin{}; freopen_s(&pCout, "CONOUT$", "w", stdout); freopen_s(&pCin, "CONIN$", "r", stdin); if (!IsConsoleOnly) { auto* const menu = GetSystemMenu(GetConsoleWindow(), FALSE); EnableMenuItem(menu, SC_CLOSE, MF_GRAYED); } #ifdef _WIN64 SetConsoleTitleA("RFU " RFU_VERSION " x64"); #else SetConsoleTitleA("RFU " RFU_VERSION " x86"); #endif SetConsoleVisible(false); } bool UI::ToggleConsole() { if (!GetConsoleWindow()) CreateHiddenConsole(); SetConsoleVisible(!IsConsoleVisible); return IsConsoleVisible; } int UI::Start(HINSTANCE instance, LPTHREAD_START_ROUTINE watchthread) { WNDCLASSEX wcex; wcex.cbSize = sizeof wcex; wcex.style = 0; wcex.lpfnWndProc = WindowProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = instance; wcex.hIcon = nullptr; wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)); wcex.lpszMenuName = nullptr; wcex.lpszClassName = L"RFUClass"; wcex.hIconSm = nullptr; RegisterClassEx(&wcex); Window = CreateWindow(L"RFUClass", L"RFU", 0, 0, 0, 0, 0, NULL, NULL, instance, NULL); if (!Window) return 0; NotifyIconData.cbSize = sizeof NotifyIconData; NotifyIconData.hWnd = Window; NotifyIconData.uID = ICON_LIGHT; NotifyIconData.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; NotifyIconData.uCallbackMessage = RFU_TRAYICON; NotifyIconData.hIcon = GetIcon(instance, IsSystemDarkMode()); wcscpy_s(NotifyIconData.szTip, L"RFU"); Shell_NotifyIcon(NIM_ADD, &NotifyIconData); WatchThread = CreateThread(nullptr, 0, watchthread, nullptr, NULL, nullptr); BOOL ret; MSG msg; while ((ret = GetMessage(&msg, nullptr, 0, 0)) != 0) { if (ret != -1) { TranslateMessage(&msg); DispatchMessage(&msg); } } return msg.wParam; // NOLINT(clang-diagnostic-shorten-64-to-32) } bool UI::IsSystemDarkMode() { HKEY hK; RegOpenKeyA(HKEY_CURRENT_USER, R"(Software\Microsoft\Windows\CurrentVersion\Themes\Personalize)", &hK); DWORD v = 0; DWORD dataSize = sizeof v; RegGetValueA(hK, nullptr, "SystemUseLightTheme", RRF_RT_REG_DWORD, nullptr, &v, &dataSize); RegCloseKey(hK); return v == 0; } bool UI::IsAppDarkMode() { HKEY hK; RegOpenKeyA(HKEY_CURRENT_USER, R"(Software\Microsoft\Windows\CurrentVersion\Themes\Personalize)", &hK); DWORD v = 0; DWORD dataSize = sizeof v; RegGetValueA(hK, nullptr, "AppsUseLightTheme", RRF_RT_REG_DWORD, nullptr, &v, &dataSize); RegCloseKey(hK); return v == 0; } HICON UI::GetIcon(HINSTANCE instance, const bool dark) { if (dark) return LoadIcon(instance, MAKEINTRESOURCE(ICON_LIGHT)); return LoadIcon(instance, MAKEINTRESOURCE(ICON_DARK)); } <|start_filename|>RFU/procutil.cpp<|end_filename|> #include "procutil.h" #include <TlHelp32.h> #include "sigscan.h" constexpr auto READ_LIMIT = 1024 * 1024 * 2; // 2 MB; std::vector<HANDLE> ProcUtil::GetProcessesByImageName(LPCWSTR image_name, size_t limit, DWORD access) { std::vector<HANDLE> result; PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); auto* const snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); size_t count = 0; if (Process32First(snapshot, &entry) == TRUE) { while (count < limit && Process32Next(snapshot, &entry) == TRUE) { if (_wcsicmp(entry.szExeFile, image_name) == 0) { if (auto* process = OpenProcess(access, FALSE, entry.th32ProcessID)) { result.push_back(process); count++; } else { printf("OpenProcess failed, maybe try running as administrator? GetLastError() = %lu\n", GetLastError()); } } } } CloseHandle(snapshot); return result; } HANDLE ProcUtil::GetProcessByImageName(LPWSTR image_name) { auto processes = GetProcessesByImageName(image_name, 1); return !processes.empty() ? processes[0] : nullptr; } std::vector<HMODULE> ProcUtil::GetProcessModules(HANDLE process) { std::vector<HMODULE> result; DWORD last = 0; DWORD needed = 0; while (true) { if (!EnumProcessModulesEx(process, result.data(), last, &needed, LIST_MODULES_ALL)) throw WindowsException("unable to enum modules"); result.resize(needed / sizeof(HMODULE)); if (needed <= last) return result; last = needed; } } ProcUtil::ModuleInfo ProcUtil::GetModuleInfo(HANDLE process, HMODULE hmodule) { ModuleInfo result; if (hmodule == nullptr) { /* GetModuleInformation works with hModule set to NULL with the caveat that lpBaseOfDll will be NULL aswell: https://doxygen.reactos.org/de/d86/dll_2win32_2psapi_2psapi_8c_source.html#l01102 Solutions: 1) Enumerate modules in the process and compare file names 2) Use NtQueryInformationProcess with ProcessBasicInformation to find the base address (as done here: https://doxygen.reactos.org/de/d86/dll_2win32_2psapi_2psapi_8c_source.html#l00142) */ // can't use unicode here, must use ansi char buffer[MAX_PATH]; DWORD size = sizeof buffer; if (!QueryFullProcessImageNameA(process, 0, buffer, &size)) // Requires at least PROCESS_QUERY_LIMITED_INFORMATION throw WindowsException("unable to query process image name"); bool found; printf("ProcUtil::GetModuleInfo: buffer = %s\n", buffer); try { found = FindModuleInfo(process, buffer, result); } catch (WindowsException& e) { printf("[%p] ProcUtil::GetModuleInfo failed: %s (%lX)\n", process, e.what(), e.GetLastError()); found = false; } if (!found) // Couldn't enum modules or GetModuleFileNameEx/GetModuleInformation failed { result.path = buffer; result.base = nullptr; result.size = 0; result.entry_point = nullptr; } } else { char buffer[MAX_PATH]; if (!GetModuleFileNameExA(process, hmodule, buffer, sizeof buffer)) // Requires PROCESS_QUERY_INFORMATION | PROCESS_VM_READ throw WindowsException("unable to get module file name"); MODULEINFO mi; if (!GetModuleInformation(process, hmodule, &mi, sizeof mi)) // Requires PROCESS_QUERY_INFORMATION | PROCESS_VM_READ throw WindowsException("unable to get module information"); result.path = buffer; result.base = mi.lpBaseOfDll; result.size = mi.SizeOfImage; result.entry_point = mi.EntryPoint; } return result; } bool ProcUtil::FindModuleInfo(HANDLE process, const std::filesystem::path& path, ModuleInfo& out) { printf("ProcUtil::FindModuleInfo: path = %s\n", path.string().c_str()); for (auto* hmodule : GetProcessModules(process)) { try { auto info = GetModuleInfo(process, hmodule); printf("ProcUtil::FindModuleInfo: info.path = %s\n", path.string().c_str()); if (equivalent(info.path, path)) { out = info; return true; } } catch ([[maybe_unused]] std::filesystem::filesystem_error& e) { // ignored } } return false; } void* ScanRegion(HANDLE process, const char* aob, const char* mask, const uint8_t* base, size_t size) { std::vector<uint8_t> buffer; buffer.resize(READ_LIMIT); const auto aob_len = strlen(mask); while (size >= aob_len) { size_t bytes_read = 0; if (ReadProcessMemory(process, base, buffer.data(), size < buffer.size() ? size : buffer.size(), reinterpret_cast<SIZE_T*>(&bytes_read)) && bytes_read >= aob_len) { if (auto* const result = sigscan::scan(aob, mask, reinterpret_cast<uintptr_t>(buffer.data()), reinterpret_cast<uintptr_t>(buffer.data()) + bytes_read)) { return const_cast<uint8_t*>(base) + (result - buffer.data()); } } if (bytes_read > aob_len) bytes_read -= aob_len; size -= bytes_read; base += bytes_read; } return nullptr; } void* ProcUtil::ScanProcess(HANDLE process, const char* aob, const char* mask, const uint8_t* start, const uint8_t* end) { const auto* i = start; while (i < end) { MEMORY_BASIC_INFORMATION mbi; if (!VirtualQueryEx(process, i, &mbi, sizeof mbi)) { return nullptr; } auto size = mbi.RegionSize - (i - static_cast<const uint8_t*>(mbi.BaseAddress)); if (i + size >= end) size = end - i; if (mbi.State & MEM_COMMIT && mbi.Protect & PAGE_READABLE && !(mbi.Protect & PAGE_GUARD)) { if (auto* result = ScanRegion(process, aob, mask, i, size)) { return result; } } i += size; } return nullptr; } bool ProcUtil::IsOS64Bit() { #ifdef _WIN64 return true; #else SYSTEM_INFO info; GetNativeSystemInfo(&info); return info.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 || info.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_ARM64; // lol arm #endif } bool ProcUtil::IsProcess64Bit(HANDLE process) { if (IsOS64Bit()) { auto result = 0; if (!IsWow64Process(process, &result)) throw WindowsException("unable to check process wow64"); return result == 0; } return false; } <|start_filename|>RFU/settings.cpp<|end_filename|> #include "settings.h" #include "mapping.h" #include <string> #include <fstream> #include <vector> #include "rfu.h" FileMapping ipc; // NOLINT(clang-diagnostic-exit-time-destructors) const char* advance(const char* ptr) { while (isspace(*ptr)) ptr++; return ptr; } // scuffed array parse. e.g. [1, 2, 3, 4, 5] std::vector<double> ParseDoubleArray(const std::string& value, size_t max_elements = 0) { std::vector<double> result; auto ptr = advance(value.c_str()); if (*ptr != '[') throw std::invalid_argument("unexpected character"); while (++ptr < value.c_str() + value.size()) { ptr = advance(ptr); if (*ptr == ']') break; errno = 0; char* end_ptr; double element = std::strtod(ptr, &end_ptr); if (errno != 0) throw std::invalid_argument("conversion error"); if (std::isnan(element)) throw std::invalid_argument("element is nan"); if (std::isinf(element)) throw std::invalid_argument("element is infinite"); if (max_elements == 0 || result.size() < max_elements) result.push_back(element); ptr = advance(end_ptr); if (*ptr == ']') break; if (*ptr != ',') throw std::invalid_argument("unexpected character"); } return result; } bool ParseBool(const std::string& value) { if (_stricmp(value.c_str(), "true") == 0) return true; if (_stricmp(value.c_str(), "false") == 0) return false; return std::stoi(value) != 0; } std::string BoolToString(bool value) { return value ? "true" : "false"; } std::string DoubleArrayToString(const std::vector<double>& array) { std::string buffer = "["; for (size_t i = 0; i < array.size(); i++) { if (i > 0) buffer += ", "; buffer += std::to_string(array[i]); } buffer += "]"; return buffer; } namespace Settings { bool VSyncEnabled = false; std::vector<double> FPSCapValues = { 30, 60, 75, 120, 144, 165, 240, 360 }; uint32_t FPSCapSelection = 0; double FPSCap = 0.0; bool UnlockClient = true; bool UnlockStudio = false; bool CheckForUpdates = true; bool NonBlockingErrors = true; bool SilentErrors = false; bool Init() { if (!Load()) Save(); Update(); return true; } // very basic settings parser/writer bool Load() { std::ifstream file("settings"); if (!file.is_open()) return false; printf("Loading settings from file...\n"); std::string line; while (std::getline(file, line)) { const auto eq = line.find('='); if (eq != std::string::npos) { auto key = line.substr(0, eq); auto value = line.substr(eq + 1); try { if (key == "VSyncEnabled") VSyncEnabled = ParseBool(value); else if (key == "FPSCapValues") FPSCapValues = ParseDoubleArray(value, 100); else if (key == "FPSCapSelection") FPSCapSelection = std::stoul(value); else if (key == "FPSCap") FPSCap = std::stod(value); else if (key == "UnlockClient") UnlockClient = ParseBool(value); else if (key == "UnlockStudio") UnlockStudio = ParseBool(value); else if (key == "CheckForUpdates") CheckForUpdates = ParseBool(value); else if (key == "NonBlockingErrors") NonBlockingErrors = ParseBool(value); else if (key == "SilentErrors") SilentErrors = ParseBool(value); } catch ([[maybe_unused]] std::exception& e) { // catch string conversion errors } } } if (FPSCapSelection > 0 && FPSCapSelection > FPSCapValues.size()) { FPSCapSelection = 0; } for (auto& value : FPSCapValues) { value = std::fmin(std::fmax(value, -2147483648.0), 2147483647.0); } FPSCap = FPSCapSelection == 0 ? 0.0 : FPSCapValues[FPSCapSelection - 1]; Update(); return true; } bool Save() { std::ofstream file("settings"); if (!file.is_open()) return false; printf("Saving settings to file...\n"); file << "UnlockClient=" << BoolToString(UnlockClient) << std::endl; file << "UnlockStudio=" << BoolToString(UnlockStudio) << std::endl; file << "FPSCapValues=" << DoubleArrayToString(FPSCapValues) << std::endl; file << "FPSCapSelection=" << std::to_string(FPSCapSelection) << std::endl; file << "FPSCap=" << std::to_string(FPSCap) << std::endl; file << "CheckForUpdates=" << BoolToString(CheckForUpdates) << std::endl; file << "NonBlockingErrors=" << BoolToString(NonBlockingErrors) << std::endl; file << "SilentErrors=" << BoolToString(SilentErrors) << std::endl; return true; } bool Update() { SetFPSCapExternal(FPSCap); return true; } } <|start_filename|>RFU/mapping.h<|end_filename|> #pragma once #include <Windows.h> class FileMapping // NOLINT(cppcoreguidelines-special-member-functions) { HANDLE file = nullptr; HANDLE mapping = nullptr; LPVOID view = nullptr; public: LPVOID Open(const char* file_name, const char* map_name, size_t size = 1024) { if (view) return nullptr; if (file_name) { file = CreateFileA(file_name, GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (file == INVALID_HANDLE_VALUE) return nullptr; } mapping = CreateFileMappingA(file ? file : INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, size, map_name); // NOLINT(clang-diagnostic-shorten-64-to-32) if (mapping == nullptr) { Close(); return nullptr; } view = MapViewOfFile(mapping, FILE_MAP_ALL_ACCESS, 0, 0, size); if (view == nullptr) { Close(); return nullptr; } return view; } LPVOID Open(const char* map_name, size_t size = 1024) { if (view) return nullptr; mapping = OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, map_name); if (mapping == nullptr) return nullptr; view = MapViewOfFile(mapping, FILE_MAP_ALL_ACCESS, 0, 0, size); if (view == nullptr) { Close(); return nullptr; } return view; } void Close() { if (view) UnmapViewOfFile(view); if (mapping) CloseHandle(mapping); if (file) CloseHandle(file); file = nullptr; mapping = nullptr; view = nullptr; } template <typename T> T Get() { return static_cast<T>(view); } [[nodiscard]] bool IsOpen() const { return view != nullptr; } ~FileMapping() { Close(); } }; <|start_filename|>RFU/procutil.h<|end_filename|> // ReSharper disable CppFunctionalStyleCast #pragma once #include <Windows.h> #include <Psapi.h> #include <vector> #include <string> #include <filesystem> #include <stdexcept> #define PAGE_READABLE (PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_READONLY | PAGE_READWRITE) // NOLINT(cppcoreguidelines-macro-usage) namespace ProcUtil { // Problem: Calling GetLastError() in a catch block is sketchy/unreliable as Windows' internal exception handling _may_ call WinAPI functions beforehand that change the error. Better safe than sorry. // Solution: This class class WindowsException : public std::runtime_error { public: WindowsException(const char* message) : std::runtime_error(init(message)), last_error(0) { } [[nodiscard]] DWORD GetLastError() const { return last_error; } private: const char* init(const char* message) { last_error = ::GetLastError(); return message; } DWORD last_error; }; struct ModuleInfo; struct ProcessInfo; std::vector<HANDLE> GetProcessesByImageName(LPCWSTR image_name, size_t limit = -1, DWORD access = PROCESS_ALL_ACCESS); HANDLE GetProcessByImageName(LPWSTR image_name); std::vector<HMODULE> GetProcessModules(HANDLE process); ModuleInfo GetModuleInfo(HANDLE process, HMODULE hmodule); bool FindModuleInfo(HANDLE process, const std::filesystem::path& path, ModuleInfo& out); void* ScanProcess(HANDLE process, const char* aob, const char* mask, const uint8_t* start = nullptr, const uint8_t* end = reinterpret_cast<const uint8_t*>(UINTPTR_MAX)); bool IsOS64Bit(); bool IsProcess64Bit(HANDLE process); template <typename T> bool Read(HANDLE process, const void* location, T* buffer, size_t size = 1) noexcept { return ReadProcessMemory(process, location, buffer, size * sizeof(T), nullptr) != 0; } template <typename T> T Read(HANDLE process, const void* location) { T value; if (!ReadProcessMemory(process, location, static_cast<LPVOID>(&value), sizeof(T), nullptr)) throw WindowsException("unable to read process memory"); return value; } inline const void* ReadPointer(HANDLE process, const void* location) { #ifdef _WIN64 return IsProcess64Bit(process) ? reinterpret_cast<const void*>(Read<uint64_t>(process, location)) : reinterpret_cast<const void*>(Read<uint32_t>(process, location)); #else return Read<const void*>(process, location); #endif } template <typename T> void Write(HANDLE process, const void* location, const T& value) { if (!WriteProcessMemory(process, const_cast<LPVOID>(location), static_cast<LPCVOID>(&value), sizeof(T), nullptr)) throw WindowsException("unable to write process memory"); } template <size_t N, typename T> bool ExecuteStub(HANDLE process, const uint8_t(&code)[N], T& arg) { if (auto alloc = static_cast<const uint8_t*>(VirtualAllocEx(process, nullptr, sizeof(T) + sizeof(code), MEM_COMMIT, PAGE_EXECUTE_READWRITE))) { Write(process, alloc, arg); Write(process, alloc + sizeof(T), code); if (const auto thread = CreateRemoteThread(process, nullptr, 0, LPTHREAD_START_ROUTINE(alloc + sizeof(T)), LPVOID(alloc), NULL, nullptr)) { WaitForSingleObject(thread, INFINITE); arg = Read<T>(process, alloc); VirtualFreeEx(process, LPVOID(alloc), 0, MEM_RELEASE); return true; } } return false; } struct ModuleInfo { std::filesystem::path path; void* base = nullptr; size_t size = 0; void* entry_point = nullptr; [[nodiscard]] HMODULE GetHandle() const { return static_cast<HMODULE>(base); } }; struct ProcessInfo { HANDLE handle = nullptr; ModuleInfo hmodule; DWORD id = 0; std::string name; HWND window = nullptr; std::string window_title; bool FindMainWindow() // a.k.a. find first window associated with the process that is visible { window = nullptr; EnumWindows([](HWND window, LPARAM param) -> BOOL // NOLINT(clang-diagnostic-shadow) { auto* info = reinterpret_cast<ProcessInfo*>(param); DWORD process_id; GetWindowThreadProcessId(window, &process_id); if (IsWindowVisible(window) && process_id == info->id) { char title[256] = { 0 }; GetWindowTextA(window, title, sizeof title); info->window = window; info->window_title = title; return FALSE; } return TRUE; }, reinterpret_cast<LPARAM>(this)); return window != nullptr; } ProcessInfo() = default; ProcessInfo(HANDLE handle, bool find_window = false) : handle(handle) { id = GetProcessId(handle); printf("[%p] Got ID %lu\n", handle, id); hmodule = GetModuleInfo(handle, nullptr); printf("[%p] Got ModuleInfo\n", handle); name = hmodule.path.filename().string(); printf("[%p] Got module name\n", handle); if (find_window) FindMainWindow(); } }; } <|start_filename|>RFU/sigscan.cpp<|end_filename|> #include "sigscan.h" #include <cstdio> #include <Windows.h> #include <Psapi.h> #pragma comment(lib, "Psapi.lib") namespace sigscan { bool compare(const char* location, const char* aob, const char* mask) { for (; *mask; ++aob, ++mask, ++location) { if (*mask == 'x' && *location != *aob) { return false; } } return true; } bool compare_reverse(const char* location, const char* aob, const char* mask) { const auto* mask_iter = mask + strlen(mask) - 1; for (; mask_iter >= mask; --aob, --mask_iter, --location) { if (*mask_iter == 'x' && *location != *aob) { return false; } } return true; } uint8_t* scan(const char* aob, const char* mask, uintptr_t start, uintptr_t end) { if (start <= end) { for (; start < end - strlen(mask); ++start) { if (compare(reinterpret_cast<char*>(start), const_cast<char*>(aob), mask)) { return reinterpret_cast<uint8_t*>(start); } } } else { for (; start >= end; --start) { if (compare_reverse(reinterpret_cast<char*>(start), const_cast<char*>(aob), mask)) { return reinterpret_cast<uint8_t*>(start) - strlen(mask) - 1; } } } return nullptr; }; uint8_t* scan(LPCWSTR hmodule, const char* aob, const char* mask) { MODULEINFO info; if (GetModuleInformation(GetCurrentProcess(), GetModuleHandleW(hmodule), &info, sizeof info)) { printf("scan(): got module info\n"); return scan(aob, mask, reinterpret_cast<unsigned>(info.lpBaseOfDll), // NOLINT(clang-diagnostic-void-pointer-to-int-cast) reinterpret_cast<uintptr_t>(&info.lpBaseOfDll + info.SizeOfImage)); } printf("scan(): failed\n"); return nullptr; } } <|start_filename|>RFU/sigscan.h<|end_filename|> #pragma once #include <cstdint> #include <Shlwapi.h> namespace sigscan { bool compare(const char* location, const char* aob, const char* mask); bool compare_reverse(const char* location, const char* aob, const char* mask); uint8_t* scan(const char* aob, const char* mask, uintptr_t start, uintptr_t end); uint8_t* scan(LPCWSTR hmodule, const char* aob, const char* mask); } <|start_filename|>RFU/ui.h<|end_filename|> #pragma once #include <Windows.h> namespace UI { void CreateHiddenConsole(); void SetConsoleVisible(bool visible); bool ToggleConsole(); int Start(HINSTANCE instance, LPTHREAD_START_ROUTINE watchthread); bool IsSystemDarkMode(); bool IsAppDarkMode(); HICON GetIcon(HINSTANCE instance, bool dark); extern HWND Window; extern int AttachedProcessesCount; extern bool IsConsoleOnly; extern bool IsSilent; } <|start_filename|>RFU/rfu.h<|end_filename|> #pragma once // ReSharper disable CppClangTidyCppcoreguidelinesMacroUsage #define RFU_VERSION "5.4.1" #define RFU_GITHUB_REPO "LewisTehMinerz/RFU" #define RFU_REGKEY "RFU" // ReSharper enable CppClangTidyCppcoreguidelinesMacroUsage bool CheckForUpdates(); bool RunsOnStartup(); void SetRunOnStartup(bool shouldRun); void SetFPSCapExternal(double value);
LewisTehMinerz/RFU
<|start_filename|>core/src/test/kotlin/net/corda/core/internal/utilities/ZipBombDetectorTest.kt<|end_filename|> package net.corda.core.internal.utilities import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @RunWith(Parameterized::class) class ZipBombDetectorTest(private val case : TestCase) { enum class TestCase( val description : String, val zipResource : String, val maxUncompressedSize : Long, val maxCompressionRatio : Float, val expectedOutcome : Boolean ) { LEGIT_JAR("This project's jar file", "zip/core.jar", 128_000, 10f, false), // This is not detected as a zip bomb as ZipInputStream is unable to read all of its entries // (https://stackoverflow.com/questions/69286786/zipinputstream-cannot-parse-a-281-tb-zip-bomb), // so the total uncompressed size doesn't exceed maxUncompressedSize SMALL_BOMB( "A large (5.5 GB) zip archive", "zip/zbsm.zip", 64_000_000, 10f, false), // Decreasing maxUncompressedSize leads to a successful detection SMALL_BOMB2( "A large (5.5 GB) zip archive, with 1MB maxUncompressedSize", "zip/zbsm.zip", 1_000_000, 10f, true), // ZipInputStream is also unable to read all entries of zblg.zip, but since the first one is already bigger than 4GB, // that is enough to exceed maxUncompressedSize LARGE_BOMB( "A huge (281 TB) Zip bomb, this is the biggest possible non-recursive non-Zip64 archive", "zip/zblg.zip", 64_000_000, 10f, true), //Same for this, but its entries are 22GB each EXTRA_LARGE_BOMB( "A humongous (4.5 PB) Zip64 bomb", "zip/zbxl.zip", 64_000_000, 10f, true), //This is a jar file containing a single 10GB manifest BIG_MANIFEST( "A jar file with a huge manifest", "zip/big-manifest.jar", 64_000_000, 10f, true); override fun toString() = description } companion object { @JvmStatic @Parameterized.Parameters(name = "{0}") fun primeNumbers(): Collection<*> { return TestCase.values().toList() } } @Test(timeout=10_000) fun test() { (javaClass.classLoader.getResourceAsStream(case.zipResource) ?: throw IllegalStateException("Missing test resource file ${case.zipResource}")).let { Assert.assertEquals(case.expectedOutcome, ZipBombDetector.scanZip(it, case.maxUncompressedSize, case.maxCompressionRatio)) } } }
rayniel95/corda
<|start_filename|>SXSpeechRecognitionTwoWays/SXSpeechRecognitionTwoWays/NavViewController.h<|end_filename|> // // NavViewController.h // SXSpeechRecognitionTwoWays // // Created by dongshangxian on 2016/12/15. // Copyright © 2016年 Sankuai. All rights reserved. // #import <UIKit/UIKit.h> @interface NavViewController : UINavigationController @end <|start_filename|>SXSpeechRecognitionTwoWays/SXSpeechRecognitionTwoWays/ViewController2.h<|end_filename|> // // ViewController2.h // SXSpeechRecognitionTwoWays // // Created by dongshangxian on 2016/12/19. // Copyright © 2016年 Sankuai. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController2 : UIViewController @end <|start_filename|>SXSpeechRecognitionTwoWays/SXSpeechRecognitionTwoWays/AVAudioManager.h<|end_filename|> // // AVAudioManager.h // SXSpeechRecognitionTwoWays // // Created by dongshangxian on 2016/12/15. // Copyright © 2016年 Sankuai. All rights reserved. // #import <Foundation/Foundation.h> @interface AVAudioManager : NSObject + (instancetype)shareManager; - (void)start; - (void)stop; @end
dsxNiubility/SXSpeechRecognizerTwoWays
<|start_filename|>examples/reverse-img-search/Makefile<|end_filename|> prepare: @cargo run --release prepare-intermediate-vectors make-lsh: @cargo run --release make-lsh 5000 <|start_filename|>examples/neural-network/Makefile<|end_filename|> build: @cargo build --bin neural-network
bwindsor22/lsh-rs
<|start_filename|>src/sync3xlexpand.hpp<|end_filename|> #pragma once struct Sync3XLExpand { float out1; float out2; float out3; float mix; }; <|start_filename|>src/via-params.hpp<|end_filename|> #pragma once #include "starling-rack-ui.hpp" // Custom Quantities template<int NUM_MODES> struct ViaButtonQuantity : ParamQuantity { std::string modes[NUM_MODES]; virtual int getModeEnumeration(void) {return 0;} virtual void setMode(int mode) {} float getDisplayValue() override { if (!module) return Quantity::getDisplayValue(); return getModeEnumeration(); } std::string getDisplayValueString() override { if (!module) return Quantity::getDisplayValueString(); int mode = getDisplayValue(); return modes[mode] + " (" + std::to_string(mode + 1) + ")"; } void setDisplayValueString(std::string s) override { if (!module) return; for (int i = 0; i < NUM_MODES; i++) { if (s == modes[i] || s == std::to_string(i + 1)) { setMode(i); } } } }; struct ViaComplexButtonQuantity : ParamQuantity { std::string * modes; int numModes = 0; virtual int getModeEnumeration(void) {return 0;} virtual void getModeArray(void) {} virtual void setMode(int mode) {} float getDisplayValue() override { if (!module) return Quantity::getDisplayValue(); return getModeEnumeration(); } std::string getDisplayValueString() override { if (!module) return Quantity::getDisplayValueString(); int mode = getDisplayValue(); getModeArray(); return modes[mode] + " (" + std::to_string(mode + 1) + ")"; } void setDisplayValueString(std::string s) override { if (!module) return; for (int i = 0; i < numModes; i++) { if (s == modes[i] || s == std::to_string(i + 1)) { setMode(i); } } } }; struct ViaKnobQuantity : ParamQuantity { std::string stripScientificNotation(std::string s) { return s.substr(0, s.size() - 4); } virtual float translateParameter(float value) {return 0;} virtual float translateInput(float userInput) {return 0;} virtual void setLabel(void) {}; float getDisplayValue() override { if (!module) return Quantity::getDisplayValue(); setLabel(); return translateParameter(getSmoothValue()); } int getDisplayPrecision() override { return 3; } void setDisplayValue(float v) override { if (!module) return; setValue(translateInput(v)); } std::string getDisplayValueString(void) override { std::string displayValueRaw = string::f("%.*g", getDisplayPrecision(), math::normalizeZero(getDisplayValue())); if (displayValueRaw.size() > 4) { if (string::endsWith(displayValueRaw, "e+03")) { return stripScientificNotation(displayValueRaw) + "k"; } else if (string::startsWith(displayValueRaw.c_str(), "0.")) { return string::f("%.*g", getDisplayPrecision(), std::stof(displayValueRaw) * 1000.0) + "m"; } else { return displayValueRaw; } } else if (displayValueRaw.size() > 2) { if (string::startsWith(displayValueRaw, "0.")) { return string::f("%.*g", getDisplayPrecision(), std::stof(displayValueRaw) * 1000.0) + "m"; } else { return displayValueRaw; } } else { return displayValueRaw; } } }; <|start_filename|>src/sync3xllevels.cpp<|end_filename|> #include "starling.hpp" #include "via-params.hpp" #include "sync3xlexpand.hpp" struct Sync3XLLevels : Module { enum ParamId { LVL1KNOB_PARAM, LVL2KNOB_PARAM, LVL3KNOB_PARAM, LVLMIXKNOB_PARAM, PARAMS_LEN }; enum InputId { LVL1CV_INPUT, LVL2CV_INPUT, LVL3CV_INPUT, LVLMIXCV_INPUT, INPUTS_LEN }; enum OutputId { OUTPUTS_LEN }; enum LightId { LVL1LED_LIGHT, LVL2LED_LIGHT, LVL3LED_LIGHT, LVLMIXLED_LIGHT, LVL1LED__LIGHT, LVL2LED__LIGHT, LVL3LED__LIGHT, LVLMIXLED__LIGHT, LIGHTS_LEN }; Sync3XLLevels() { config(PARAMS_LEN, INPUTS_LEN, OUTPUTS_LEN, LIGHTS_LEN); configParam(LVL1KNOB_PARAM, 0.f, 1.f, 0.f, "Out 1 level"); configParam(LVL2KNOB_PARAM, 0.f, 1.f, 0.f, "Out 2 level"); configParam(LVL3KNOB_PARAM, 0.f, 1.f, 0.f, "Out 3 level"); configParam(LVLMIXKNOB_PARAM, 0.f, 1.f, 0.f, "Mix level"); configInput(LVL1CV_INPUT, "Out 1 level"); configInput(LVL2CV_INPUT, "Out 2 level"); configInput(LVL3CV_INPUT, "Out 3 level"); configInput(LVLMIXCV_INPUT, "Mix level"); leftExpander.producerMessage = new Sync3XLExpand; leftExpander.consumerMessage = new Sync3XLExpand; } ~Sync3XLLevels() { free(leftExpander.producerMessage); free(leftExpander.consumerMessage); } bool expanderAttached = false; void process(const ProcessArgs& args) override { float voltage1 = inputs[LVL1CV_INPUT].getVoltage() + params[LVL1KNOB_PARAM].getValue() * 5.f; voltage1 = clamp(voltage1, 0.f, 10.f); voltage1 *= 0.2f; float voltage2 = inputs[LVL2CV_INPUT].getVoltage() + params[LVL2KNOB_PARAM].getValue() * 5.f; voltage2 = clamp(voltage2, 0.f, 10.f); voltage2 *= 0.2f; float voltage3 = inputs[LVL3CV_INPUT].getVoltage() + params[LVL3KNOB_PARAM].getValue() * 5.f; voltage3 = clamp(voltage3, 0.f, 10.f); voltage3 *= 0.2f; float voltageMix = inputs[LVLMIXCV_INPUT].getVoltage() + params[LVLMIXKNOB_PARAM].getValue() * 5.f; voltageMix = clamp(voltageMix, 0.f, 10.f); voltageMix *= 0.2f; if (expanderAttached && leftExpander.module) { Sync3XLExpand* from_host = (Sync3XLExpand*) leftExpander.consumerMessage; Sync3XLExpand* to_host = (Sync3XLExpand*) leftExpander.module->rightExpander.producerMessage; voltage1 *= from_host->out1; voltage2 *= from_host->out2; voltage3 *= from_host->out3; voltageMix *= from_host->mix; to_host->out1 = voltage1; to_host->out2 = voltage2; to_host->out3 = voltage3; to_host->mix = voltageMix; leftExpander.module->rightExpander.messageFlipRequested = true; }; lights[LVL1LED_LIGHT].setSmoothBrightness(clamp(voltage1, 0.f, 5.f)/5.f, args.sampleTime); lights[LVL2LED_LIGHT].setSmoothBrightness(clamp(voltage2, 0.f, 5.f)/5.f, args.sampleTime); lights[LVL3LED_LIGHT].setSmoothBrightness(clamp(voltage3, 0.f, 5.f)/5.f, args.sampleTime); lights[LVLMIXLED_LIGHT].setSmoothBrightness(clamp(voltageMix, 0.f, 5.f)/5.f, args.sampleTime); lights[LVL1LED__LIGHT].setSmoothBrightness(-clamp(voltage1, -5.f, 0.f)/5.f, args.sampleTime); lights[LVL2LED__LIGHT].setSmoothBrightness(-clamp(voltage2, -5.f, 0.f)/5.f, args.sampleTime); lights[LVL3LED__LIGHT].setSmoothBrightness(-clamp(voltage3, -5.f, 0.f)/5.f, args.sampleTime); lights[LVLMIXLED__LIGHT].setSmoothBrightness(-clamp(voltageMix, -5.f, 0.f)/5.f, args.sampleTime); } void onExpanderChange(const ExpanderChangeEvent& e) override { if (leftExpander.module && (leftExpander.module->model == modelSync3XL)) { expanderAttached = true; } else { expanderAttached = false; } } }; struct Sync3XLLevelsWidget : ModuleWidget { Sync3XLLevelsWidget(Sync3XLLevels* module) { setModule(module); setPanel(createPanel(asset::plugin(pluginInstance, "res/sync3xllevels.svg"))); addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, 0))); addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0))); addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); addParam(createParamCentered<SifamGrey>(mm2px(Vec(30.513, 19.562)), module, Sync3XLLevels::LVL1KNOB_PARAM)); addParam(createParamCentered<SifamGrey>(mm2px(Vec(30.513, 47.062)), module, Sync3XLLevels::LVL2KNOB_PARAM)); addParam(createParamCentered<SifamGrey>(mm2px(Vec(30.513, 74.562)), module, Sync3XLLevels::LVL3KNOB_PARAM)); addParam(createParamCentered<SifamGrey>(mm2px(Vec(30.513, 102.062)), module, Sync3XLLevels::LVLMIXKNOB_PARAM)); addInput(createInputCentered<HexJack>(mm2px(Vec(16.762, 26.438)), module, Sync3XLLevels::LVL1CV_INPUT)); addInput(createInputCentered<HexJack>(mm2px(Vec(16.762, 53.938)), module, Sync3XLLevels::LVL2CV_INPUT)); addInput(createInputCentered<HexJack>(mm2px(Vec(16.762, 81.438)), module, Sync3XLLevels::LVL3CV_INPUT)); addInput(createInputCentered<HexJack>(mm2px(Vec(16.762, 108.938)), module, Sync3XLLevels::LVLMIXCV_INPUT)); addChild(createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(6.45, 26.438)), module, Sync3XLLevels::LVL1LED_LIGHT)); addChild(createLightCentered<MediumLight<RedLight>>(mm2px(Vec(6.45, 26.438)), module, Sync3XLLevels::LVL1LED__LIGHT)); addChild(createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(6.45, 53.938)), module, Sync3XLLevels::LVL2LED_LIGHT)); addChild(createLightCentered<MediumLight<RedLight>>(mm2px(Vec(6.45, 53.938)), module, Sync3XLLevels::LVL2LED__LIGHT)); addChild(createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(6.45, 81.438)), module, Sync3XLLevels::LVL3LED_LIGHT)); addChild(createLightCentered<MediumLight<RedLight>>(mm2px(Vec(6.45, 81.438)), module, Sync3XLLevels::LVL3LED__LIGHT)); addChild(createLightCentered<MediumLight<GreenLight>>(mm2px(Vec(6.45, 108.938)), module, Sync3XLLevels::LVLMIXLED_LIGHT)); addChild(createLightCentered<MediumLight<RedLight>>(mm2px(Vec(6.45, 108.938)), module, Sync3XLLevels::LVLMIXLED__LIGHT)); } }; Model* modelSync3XLLevels = createModel<Sync3XLLevels, Sync3XLLevelsWidget>("SYNC3XLLEVELS"); <|start_filename|>plugin.json<|end_filename|> { "slug": "Starling_Via", "name": "<NAME>", "author": "Starling", "license": "MIT", "version": "2.0.0", "pluginUrl": "https://starling.space/via", "authorUrl": "https://starling.space", "authorEmail": "<EMAIL>", "manualUrl": "https://starling.space/via/platform-info#rack", "sourceUrl": "https://github.com/starlingcode/Via-for-Rack.git", "donateUrl": "https://paypal.me/ssttaarrlliinngg", "changelogUrl": "https://github.com/starlingcode/Via-for-Rack/blob/v2/CHANGELOG.md", "modules": [ { "slug": "META", "name": "META", "description": "flexible contour generator", "modularGridUrl": "https://www.modulargrid.net/e/starling-via-meta", "tags": [ "Function Generator", "Drum", "Hardware" ] }, { "slug": "SYNC", "name": "SYNC", "description": "clock-synced signal source", "modularGridUrl": "https://www.modulargrid.net/e/starling-via-sync", "tags": [ "Oscillator", "Clock Modulator", "Hardware" ] }, { "slug": "SCANNER", "name": "SCANNER", "description": "multi-channel waveshaper", "modularGridUrl": "https://www.modulargrid.net/e/starling-via-scanner", "tags": [ "Waveshaper", "Distortion", "Hardware" ] }, { "slug": "GATESEQ", "name": "GATESEQ", "description": "rhythm engine", "modularGridUrl": "https://www.modulargrid.net/e/starling-via-gateseq", "tags": [ "Sequencer", "Sample and Hold", "Hardware" ] }, { "slug": "ATSR", "name": "ATSR", "description": "crossfading envelope", "modularGridUrl": "https://www.modulargrid.net/e/starling-via-atsr-", "tags": [ "Envelope Generator", "LFO", "Hardware" ] }, { "slug": "OSC3", "name": "OSC3", "description": "musical oscillator trio", "modularGridUrl": "https://www.modulargrid.net/e/starling-via-osc3-", "tags": [ "VCO", "Hardware" ] }, { "slug": "SYNC3", "name": "SYNC3", "description": "frequency synthesizer", "modularGridUrl": "https://www.modulargrid.net/e/starling-via-sync3-", "tags": [ "Oscillator", "Clock Modulator", "Hardware" ] }, { "slug": "SYNC3XL", "name": "SYNC3XL", "description": "3 voice frequency synthesizer", "tags": [ "Oscillator", "Clock Modulator", "Hardware" ] }, { "slug": "SYNC3XLLEVELS", "name": "Sync3XL Levels", "description": "SYNC3XL VCA expander", "tags": [ "Expander" ] } ] } <|start_filename|>src/starling.cpp<|end_filename|> #include "starling.hpp" Plugin *pluginInstance; void init(rack::Plugin *p) { pluginInstance = p; p->addModel(modelMeta); p->addModel(modelGateseq); p->addModel(modelScanner); p->addModel(modelSync); p->addModel(modelAtsr); p->addModel(modelOsc3); p->addModel(modelSync3); p->addModel(modelSync3XL); p->addModel(modelSync3XLLevels); }
liquidcitymotors/Via-for-Rack
<|start_filename|>threadcontainer.go<|end_filename|> package jwz // NoThreadableError indicates that the container was not in a valid state when a utility function was called // against it // type NoThreadableError struct { } func (e NoThreadableError) Error() string { return "Container is not a root (has parent), but contains no Threadable element" } // threadContainer is used to encapsulate a Threadable implementation. It holds some intermediate state used while // threading. This is private to the module and is used while performing the threading operation, then discarded. // type threadContainer struct { // threadable contains the base of the threadable items in this instance of the struct // threadable Threadable // parent shows which threadable item is the parent of this container, which can be nil for a root node // parent *threadContainer // child shows which threadable is the child of this container // child *threadContainer // child shows which threadable is the child of this container // next *threadContainer // forID holds the message id that this container is holding. This is only useful for // when we don't ever see the actual email (it is referenced by one email, but we don't // have the email as we are parsing a partial set) // forID string } // flush copies the ThreadContainer tree structure down into the underlying // Threadable elements. I.E. make the IThreadable tree look like // the ThreadContainer tree. // func (tc *threadContainer) flush() error { // Only a root node can have no threadable element - if we have a parent, then // we are not a root node. // if tc.parent != nil && tc.threadable == nil { return NoThreadableError{} } tc.parent = nil if tc.threadable != nil { if tc.child == nil { tc.threadable.SetChild(nil) } else { tc.threadable.SetChild(tc.child.threadable) } } if tc.child != nil { _ = tc.child.flush() tc.child = nil } if tc.threadable != nil { if tc.next == nil { tc.threadable.SetNext(nil) } else { tc.threadable.SetNext(tc.next.threadable) } } if tc.next != nil { _ = tc.next.flush() tc.next = nil } tc.threadable = nil return nil } // findChild returns true if child is under self's tree. This is used for detecting circularities in the references header. // func (tc *threadContainer) findChild(target *threadContainer) bool { if tc.child == nil { return false } else if tc.child == target { return true } else { return tc.child.findChild(target) } } // reverseChildren does what it implies and reverses the order of the child elements // func (tc *threadContainer) reverseChildren() { if tc.child != nil { var kid, prev, rest *threadContainer // Reverse the children of this one // prev = nil kid = tc.child rest = kid.next for kid != nil { kid.next = prev prev = kid kid = rest if rest != nil { rest = rest.next } } tc.child = prev // Now reverse the children of this one's children // for kid = tc.child; kid != nil; kid = kid.next { kid.reverseChildren() } } } func (tc *threadContainer) fillDummy(t Threadable) { // Only a root node can have no threadable element - if we have a message id, then // we are not a root node. // if tc.threadable == nil && tc.forID != "" { tc.threadable = t.MakeDummy(tc.forID) } // Depth first, but it does not matter // if tc.child != nil { tc.child.fillDummy(t) } // Simple walk this one, no need to save stack space by following the next chain here // if tc.next != nil { tc.next.fillDummy(t) } } <|start_filename|>examples/visualize/main.go<|end_filename|> package main import ( "flag" "fmt" "github.com/gatherstars-com/jwz" "github.com/gdamore/tcell/v2" "github.com/rivo/tview" "log" "os" "sort" "strings" ) func main() { var testData string var sizeHint int flag.StringVar(&testData, "emldir", "./eml", "base directory beneath which the test can find .eml files") flag.IntVar(&sizeHint, "sizehint", 3000, "supply a rough number of the emails you are scanning, if you have a clue") flag.Parse() // Use the enmime package to build all the emails we find under the given directory // threadables, err := buildEnvelopes(testData, sizeHint) if err != nil { log.Printf("Unable to walk the eml directory: %#v", err) os.Exit(1) } // Now we have a big slice of all the emails, lets use our jwz algorithm to place them in to a thread tree // threader := jwz.NewThreader() sliceRoot, err := threader.ThreadSlice(threadables) if err != nil { log.Fatalf("Email threading operation return fatal error: %#v", err) } // Sort it Rodney! // x := jwz.Sort(sliceRoot, byDate) // And create a tree visualization in the console. Note that TERM must be set and your terminfo // stuff should be good. I don't know if this works on Windows - perhaps someone can tell me. // visualize(x) } // visualize a neat-ish ASCII tree representation of the threads, so we can do a human based check of whether // things are working. // // Also, The colors will sometimes look wonky on a custom configuration of OSX console. Try a standard one and // make sure your TERM and terminfo database are good if you have issues. // func visualize(threads jwz.Threadable) { root := tview.NewTreeNode("Threads"). SetColor(tcell.ColorGreen) buildVisual(root, threads) tree := tview.NewTreeView(). SetRoot(root). SetCurrentNode(root) sideBar := tview.NewTextView(). SetTextAlign(tview.AlignLeft). SetText("Email Text") headers := tview.NewTextView(). SetTextAlign(tview.AlignLeft). SetText("Email Headers"). SetToggleHighlights(false) // There is only selected (mouse click or <enter>, not a tree.SetSelectedFunc(func(node *tview.TreeNode) { reference := node.GetReference() if reference == nil { sideBar.SetText("No email in this node") } else { thr := reference.(*Email) if thr.dummy { sideBar.SetText("Placeholders manufactured by the Threader don't contain email text") } else { sideBar.SetText(thr.email.Text) sideBar.ScrollToBeginning() headers.Clear() // Print each header in sorted order // hk := thr.email.GetHeaderKeys() sort.Strings(hk) for _, k := range hk { v := thr.email.GetHeader(k) if !strings.HasPrefix(k, "From ") { _, _ = headers.Write([]byte(fmt.Sprintf("%-30s: %s\n", k, v))) headers.ScrollToBeginning() } } } } }) grid := tview.NewGrid(). SetRows(-3, 0). SetColumns(-0, -2). SetBorders(true). AddItem(headers, 1, 0, 1, 2, 0, 0, false) grid.AddItem(tree, 0, 0, 1, 1, 5, 50, true). AddItem(sideBar, 0, 1, 1, 1, 0, 50, false) flex := tview.NewFlex().SetDirection(tview.FlexRow) flex.AddItem(tree, 0, 2, true) text := tview.NewBox().SetBorder(false) flex.AddItem(text, 0, 3, false) info := tview.NewBox().SetBorder(true) flex.AddItem(info, 7, 1, false) app := tview.NewApplication().SetRoot(grid, true).EnableMouse(true) if err := app.Run(); err != nil { panic(err) } } // This function is called when an email node is selected in the tree // // buildVisual creates a visual node for the given treeNode and makes it a child of the // given target node. // func buildVisual(target *tview.TreeNode, treeNode jwz.Threadable) { if treeNode == nil { // We have descended far enough in this part of the tree // return } // We need a new visual node for this part of the tree // n := tview.NewTreeNode(tview.Escape(treeNode.Subject())). SetReference(treeNode) // And select a colour // colorMe(n, treeNode) // Which we add to the target node // target.AddChild(n) // Then we add the child of this node to newly create visual entry as a child. This recursive call will make sure we // descend the children of every node correctly as we trace the next pointers at the same level after this // buildVisual(n, treeNode.GetChild()) // But all the next links in the chain from this node are children of our current visual // for next := treeNode.GetNext(); next != nil; next = next.GetNext() { // So we create a visual node for this next email // nn := tview.NewTreeNode(next.Subject()). SetReference(next) // Select a color // colorMe(nn, next) // And it becomes a child of the target too // target.AddChild(nn) // And in turn, we need to add its children // buildVisual(nn, next.GetChild()) } } // colorMe decides what color a visualized node should be, based on whether it has child and/or next // func colorMe(n *tview.TreeNode, treeNode jwz.Threadable) { hasNext := treeNode.GetNext() != nil hasChild := treeNode.GetChild() != nil // Color according to taste - not that the background color of your terminal and whether you have bothered // to set TERM and terminfo up correctly may make these color selections look strange or even not work // switch { case hasNext && hasChild: // With a next and a child, it is part of a thread, but also the start of a sub thread // n.SetColor(tcell.ColorLightGreen) case hasNext: // With a next and no child, it is a reply by some boring old gammon // n.SetColor(tcell.ColorLightBlue) case hasChild: // With a child and no next then it is the start of a sub-thread // n.SetColor(tcell.ColorLightGreen) default: // With no child and no next, then it is the haggard old spinster of the email world // and either resides on its own, or has the last word on a thread. Or something. // n.SetColor(tcell.ColorLightYellow) } } <|start_filename|>threadable.go<|end_filename|> package jwz import "time" // ThreadableRoot is an interface that supports traversing a set of Threadables in some arbitrary // way - for instance if they are in some kind of tree structure, the traversal can be // hidden behind the interface // // JI - Although it might be useful to support incoming tree structures, all the // Next and Get are doing is keeping a pointer if the input is a []Threadable. So we also // have a function that just accepts that as input as well as one that accepts a ThreadableRoot // type ThreadableRoot interface { // Next causes an internal iterator over your internal representation of Threadable // elements to either be created and pointing to the next element, or to simply // advance to the next element if there is one. It returns true if another element // is available and false if there are no more beans. // Next() bool // Get returns the next available Threadable from your internal storage. // Note that this func should not be called without a prior call to Next and your // implementation can assume that. // Get() Threadable } // Threadable is an interface which can be implemented by any go type, which will then // allow it to be threaded. // type Threadable interface { // MessageThreadID returns a string identifying this message. // Generally this will be a representation of the contents of the // Message-ID header. // MessageThreadID() string // MessageThreadReferences returns the IDs of the set of messages referenced by this one. // This list should be ordered from oldest-ancestor to youngest-ancestor. However, the returned // tree can be sorted however you like. // MessageThreadReferences() []string // Subject returns the subject line of the threadable with no manipulation of Re: Re: etc. // Subject() string // SimplifiedSubject - provides a threadable subject string. // // When no references are present, subjects will be used to thread together // messages. This method should return a threadable subject: two messages // with the same simplifiedSubject will be considered to belong to the same // thread. This string should not have `Re:' on the front, and may have // been simplified in whatever other ways seem appropriate. // // This is a String of Unicode characters, and should have had any encodings - // such as RFC 2047 charset encodings - removed first. // // If you aren't interested in threading by subject at all, return "". // SimplifiedSubject() string // SubjectIsReply indicates whether the original subject was one that appeared to be a reply // I.E. it had a `Re:' or some other indicator that lets you determine that. When threading by subject, // this property is used to tell whether two messages appear to be siblings, // or in a parent/child relationship. // SubjectIsReply() bool // SetNext is called after the proper thread order has been computed, // and will be called on each Threadable in the chain, to set up the proper tree // structure. // SetNext(next Threadable) // SetChild is called after the proper thread order has been computed, // and will be called on each Threadable in the chain, to set up the proper tree // structure. // SetChild(kid Threadable) // SetParent is not called by the jwz algorithm and if you do not need the pointer in your // implementation, then you can implement it as a null function. It can be useful when using // the Walk utility method though // SetParent(parent Threadable) // GetNext just makes it easier to navigate through the threads after they are built, // but you don't have to use this if you have a better way // GetNext() Threadable // GetChild just makes it easier to navigate through the threads after they are built, // but you don't have to use this if you have a better way // GetChild() Threadable // GetParent just makes it easier to navigate through the threads after they are built, // but you don't have to use this if you have no need for it // GetParent() Threadable // GetDate is not used by the threading algorithm, but implementing this function may make // your own tree walking routines and sorting methods easier to implement. // It should return the Date associated with the Threadable // GetDate() time.Time // MakeDummy creates a dummy parent object. // // With some set of messages, the only way to achieve proper threading is // to introduce an element into the tree which represents messages which are // not present in the set: for example, when two messages share a common // ancestor, but that ancestor is not in the set. This method is used to // make a placeholder for those sorts of ancestors. It should return // a Threadable type. The SetNext() and SetChild() funcs // will be used on this placeholder, as either the object or the argument, // just as for other elements of the tree. // MakeDummy(forID string) Threadable // IsDummy should return true of dummy messages, false otherwise. // It is legal to pass dummy messages within your input; // the isDummy() method is the mechanism by which they are noted and ignored. // IsDummy() bool } <|start_filename|>utils.go<|end_filename|> package jwz import "sort" // ThreadLess specifies the signature of a function that compares two Threadables in some way you define, // such as comparing dates in the emails they contain. Note your function should be able to handle Dummy // Threadables in some sensible way, such as using the child of the Dummy for the sort parameters. // // ThreadLess reports whether the Threadable t1 must sort before the Threadable t2. // // If both ThreadLess(t1, t2) and ThreadLess(t2, t1) are false, then t1 and t2 are considered equal. // Sort may place equal elements in any order in the final result. // // ThreadLess must describe a transitive ordering: // // - if both ThreadLess(t1, t2) and ThreadLess(t2, t3) are true, then ThreadLess(t1, t3) must be true as well. // - if both ThreadLess(t1, t2) and ThreadLess(t2, t3) are false, then ThreadLess(t1, t3) must be false as well. // type ThreadLess func(t1 Threadable, t2 Threadable) bool // WalkFunction specifies the signature of a function that can be called by the generic Walk utility function. // As well as being passed the current Threadable in the walk, the function will be passed an interface of your // choosing, which is passed in to the walk function and then propagated to each call of this function. T // // The Walk will not interact with the interface{}, just keep it accessible to your walk function, hence you // can pass nil if you do not need it. // // If your searcher function returns true, then the tree walk will end where it is // type WalkFunction func(t Threadable, u interface{}) (bool, error) // Count will traverse the supplied Threadable and store the count of Threadables contained within it in the // given counter location. // // Note that any Dummy placeholder nodes are excluded from the count. // func Count(root Threadable, counter *int) { if root == nil { return } for node := root; node != nil; node = node.GetNext() { if c := node.GetChild(); c != nil { // Count children of the current one first then // Count(c, counter) } // Only count this one if it is not a dummy placeholder // if !node.IsDummy() { *counter++ } } } // Sort will create order from the chaos created by threading a set of emails, that even if given as input // in a specific order, will be threaded in whatever order the go data structures happen to spit out - which // will usually be a different order each time. // // Note that Sort will not change the embedded nature of the Threads. As in, while the child of a particular // Threadable can, and usually will, be changed, the new child will belong to the set of next Threadables that // its original child pointer belonged to. If sorting by date for instance, the set of reply threads/emails // will be ordered such that the replies are in date order, which is what you want. However, the set of replies // will remain the same, as the song goes. // // Note that you should use the returned Threadable as the new root of your threads, as your old one is // very likely to have been moved halfway down the top level chain that you passed in. That will confuse the // BeJesus out of you. I know it did me for a minute. // // So, all the chains will be sorted by asking your supplied ThreadLess function whether the first Threadable // it gives you should sort before the second one it gives you. This makes the sort trivial for you to sort // the Threadable set and avoids you having to get your head around following the chain of pointers etc. // func Sort(threads Threadable, by ThreadLess) Threadable { // Guard against stupidity // if threads == nil { return nil } // If this node has no next pointers, then it is the only element in this current chain, so it is // sorted by default // if threads.GetNext() == nil { return threads } // Now we sort the chain of current pointers. The easiest way is to convert to a slice then // sort the slice. This is because after sorting, the child of the node above should become the // first element of the sorted slice // var s = make([]Threadable, 0, 42) for current := threads; current != nil; current = current.GetNext() { // If the current node we are inspecting has a child, then sort that first // if c := current.GetChild(); c != nil { current.SetChild(Sort(c, by)) } s = append(s, current) } // We can now sort the slice of next pointers at this level. Note that the child of this node // will already have been sorted, so if it is used to get the date or something like that // - because this node is a Dummy - then it will be OK to use it as it will be in the correct // order already // sort.Slice(s, func(i, j int) bool { return by(s[i], s[j]) }) // And we now rebuild the chain from the slice // l := len(s) - 1 for i := 0; i < l; i++ { s[i].SetNext(s[i+1]) } // Last element in the slice no longer has a current of course // s[l].SetNext(nil) // And the new child of the node above is the first of the newly sorted (or at the top level the new root) // newChild := s[0] s = nil // And return the new child for the node above us // return newChild } // Walk allows the caller to execute some function against each node in the tree, while avoiding dealing with the // internal structure of the Threadable tree. It is easy to get tree walk code wrong, and while this generic walk // will probably not do everything that everyone wants - such as cause Leeds United to beat Manchester United - it // is likely to work for most cases. // // Walk will call your WalkFunction for each node in the tree and will supply the node, and an interface value // (which can be nil) that you can supply for your own tracking if simple walk is not enough for you. // // The walker will perform depth first search if asked, by passing parameter isDepth=true // func Walk(isDepth bool, tree Threadable, f WalkFunction, u interface{}) error { // Guard against stupidity // if tree == nil { return nil } // A depth first search means we descend in to the children until there aren't any, then traverse the // next pointers. A breadth first search means we traverse all the next pointers then descend in to the children // if isDepth { for current := tree; current != nil; current = current.GetNext() { // If the current node we are inspecting has a child, then call with that first // if c := current.GetChild(); c != nil { if err := Walk(isDepth, c, f, u); err != nil { return err } } // Now call the user function on this current node, which of course means we eventually call them all // stop, err := f(current, u) if err != nil || stop { return err } } } else { // This is breadth first, which means we call the function with all the Threadables in the next // chain, then we call their children if they have any // for current := tree; current != nil; current = current.GetNext() { // Call the function on each next in turn // stop, err := f(current, u) if err != nil || stop { return err } } for current := tree; current != nil; current = current.GetNext() { // If the current node we are inspecting has a child, then walk it breadth wise // if c := current.GetChild(); c != nil { if err := Walk(isDepth, c, f, u); err != nil { return err } } } } // We are finished with this bit // return nil } <|start_filename|>jwz.go<|end_filename|> // Package jwz is an implementation of the email threading algorithm created by <NAME> and explained by him // at: https://www.jwz.org/doc/threading.html // // This package was created by cribbing from the code at: // https://www.jwz.org/doc/threading.html#:~:text=grendel-1999-05-14.tar.gz // from the Java source code in view/Threader.java - it contains no ham and cheese sandwiches. // // The code, interface etc. was obviously adapted in to Go form, though where possible, the code reflects the // original Java if it is not too ungolike. // // Author: <NAME> - <EMAIL> / <EMAIL> // // See the LICENSE file, sit down, have a scone. // package jwz import ( "errors" "fmt" ) // Threader arranges a set of messages into a thread hierarchy, by references. // type Threader struct { rootNode *threadContainer idTable map[string]*threadContainer bogusIDCount int } // NewThreader returns an instance of the Threader struct, that is ready to attack // your Threadable // //goland:noinspection GoUnusedExportedFunction func NewThreader() *Threader { t := &Threader{ idTable: make(map[string]*threadContainer), } return t } // Thread will create a threadable organized so that the root node // is the original reference, creating dummy placeholders for the emails // we don't have yet // func (t *Threader) Thread(threadable Threadable) (Threadable, error) { if threadable == nil { return nil, nil } // Build a thread container from this single email // if !threadable.IsDummy() { if err := t.buildContainer(threadable); err != nil { return nil, err } } else { return nil, errors.New("cannot thread a single email with a dummy root") } var err error // Organize the root set from what we have // t.rootNode, err = t.findRootSet() if err != nil { return nil, err } // We no longer need the map - probably no real need to blank it here, but the original Java code did that, // and it won't harm to let the GC reclaim this in case our caller keeps the *Threader around for some reason // t.idTable = nil // We do this to avoid flipping the input order each time through. // t.rootNode.reverseChildren() // There should not be a next in the root of a conversation thread // if t.rootNode.next != nil { return nil, fmt.Errorf("root node contains a next and should not: %#v", t.rootNode) } // Because the result of this function is a tree that does actually contain dummies for missing references // we need to add a dummy threadable for any node that does not yet have one. Then we can flush the chain // of containers in to the threadable // t.rootNode.fillDummy(threadable) var result Threadable if t.rootNode.child != nil { result = t.rootNode.child.threadable } // Flush the tree structure of each element of the root set down into // their underlying Threadables // _ = t.rootNode.flush() t.rootNode = nil return result, nil } // ThreadSlice will thread the set of messages contained within threadableSlice. // The Threadable returned is the new first element of the root set. // func (t *Threader) ThreadSlice(threadableSlice []Threadable) (Threadable, error) { if threadableSlice == nil || len(threadableSlice) == 0 { return nil, nil } // Iterate all the Threadable represented by the root and build the // threadContainer from them // for _, nt := range threadableSlice { if !nt.IsDummy() { if err := t.buildContainer(nt); err != nil { return nil, err } } } return t.threadRoot() } // ThreadRoot will thread the set of messages provided by ThreadableRoot. // The Threadable returned is the new first element of the root set. // func (t *Threader) ThreadRoot(threadableRoot ThreadableRoot) (Threadable, error) { if threadableRoot == nil { return nil, nil } // Iterate all the Threadable represented by the root and build the // threadContainer from them // for threadableRoot.Next() == true { nt := threadableRoot.Get() if !nt.IsDummy() { if err := t.buildContainer(nt); err != nil { return nil, err } } } return t.threadRoot() } func (t *Threader) threadRoot() (Threadable, error) { var err error // Organize the root set from what we have // t.rootNode, err = t.findRootSet() if err != nil { return nil, err } // We no longer need the map - probably no real need to blank it here, but the original Java code did that, // and it won't harm to let the GC reclaim this in case our caller keeps the *Threader around for some reason // t.idTable = nil // Get rid of any empty containers. They should no longer needed // t.pruneEmptyContainers(t.rootNode) // We do this so to avoid flipping the input order each time through. // t.rootNode.reverseChildren() // We might need to sort on subjects, so let's process them // t.gatherSubjects() // There should not be a next in the root of a conversation thread // if t.rootNode.next != nil { return nil, fmt.Errorf("root node contains a next and should not: %#v", t.rootNode) } for r := t.rootNode.child; r != nil; r = r.next { // If this direct child of the root node has no threadable in it, // manufacture a dummy container to bind its children together. // Note that these dummies can only ever occur as elements of // the root set. // if r.threadable == nil { r.threadable = r.child.threadable.MakeDummy(r.forID) } } var result Threadable if t.rootNode.child != nil { result = t.rootNode.child.threadable } // Flush the tree structure of each element of the root set down into // their underlying Threadables // _ = t.rootNode.flush() t.rootNode = nil return result, nil } // buildContainer() does three things: // // - It walks the tree of Threadable, and wraps each in a // threadContainer object. // - It indexes each threadContainer object in the idTable, under // the message ID of the contained Threadable. // - For each of the references within Threadable, it ensures that there // is a threadContainer in the table (an empty one, if necessary.) // func (t *Threader) buildContainer(threadable Threadable) error { var present bool // See if we already have a container for this threadable // id := threadable.MessageThreadID() tid := id c, present := t.idTable[id] if present { // There is already a ThreadContainer in the table for this ID. // Under normal circumstances, there will be no IThreadable in it // (since it was a forward reference from a References field.) // // If there is already a threadable in it, then that means there // are two IThreadables with the same ID. Generate a new ID for // this one, sigh... This ID is only used to cause the two entries // in the hash table to not stomp each other. // if c.threadable != nil { id = fmt.Sprintf("<Bogus-id:%d>", t.bogusIDCount) t.bogusIDCount++ c = nil } else { c.threadable = threadable } } // Create a ThreadContainer for this Threadable, and store it in // the map // if c == nil { c = &threadContainer{forID: tid} c.threadable = threadable c.forID = tid t.idTable[id] = c } // Create ThreadContainers for each of the references which don't // have them. Link each of the referenced messages together in the // order implied by the references field, unless they are already // linked. // var parentRef, ref *threadContainer // Iterate through the references field of the threadable and see if we // already have a reference to them in our map. Create one if not // refs := threadable.MessageThreadReferences() for _, refString := range refs { ref, present = t.idTable[refString] if !present { ref = &threadContainer{forID: refString} t.idTable[refString] = ref } // If we have references A B C D, make D be a child of C, etc., // except if they have parents already. // if parentRef != nil && // there is a parent ref.parent == nil && // don't have a parent already parentRef != ref && // not a tight loop !parentRef.findChild(ref) { // not a wide loop // Ok, link it into the parent's child list. // ref.parent = parentRef ref.next = parentRef.child parentRef.child = ref } parentRef = ref } // At this point `parentRef' is set to the container of the last element // in the references field. Make that be the parent of this container, // unless doing so would introduce a circularity. // if parentRef != nil && (parentRef == c || c.findChild(parentRef)) { parentRef = nil } if c.parent != nil { // If it has a parent already, that's there because we saw this message // in a references field, and presumed a parent based on the other // entries in that field. Now that we have the actual message, we can // be more definitive, so throw away the old parent and use this new one. // Find this container in the parent's child-list, and unlink it. // // Note that this could cause this message to now have no parent, if it // has no references field, but some message referred to it as the // non-first element of its references. (Which would have been some // kind of lie...) // var rest, prev *threadContainer for prev, rest = nil, c.parent.child; rest != nil; { if rest == c { break } prev = rest rest = rest.next } if rest == nil { return fmt.Errorf("didn't find %#v in parent %#v", c, c.parent) } if prev == nil { c.parent.child = c.next } else { prev.next = c.next } c.next = nil c.parent = nil } // If we have a parent, link c into the parent's child list. // if parentRef != nil { c.parent = parentRef c.next = parentRef.child parentRef.child = c } // No error // return nil } // findRootSet finds the root set of the threadContainers, and returns a root node. // // NB: A container is in the root set if it has no parents. // func (t *Threader) findRootSet() (*threadContainer, error) { root := &threadContainer{} for _, c := range t.idTable { if c.parent == nil { if c.next != nil { return nil, fmt.Errorf("container has no parent, but has a next value: %#v", c.next) } c.next = root.child root.child = c } } return root, nil } // Walk through the threads and discard any empty container objects. // After calling this, there will only be any empty container objects // at depth 0, and those will all have at least two kids. // func (t *Threader) pruneEmptyContainers(parent *threadContainer) { var prev *threadContainer var container = parent.child var next *threadContainer if container != nil { next = container.next } for container != nil { if container.threadable == nil && container.child == nil { // This is an empty container with no kids. Nuke it. // // Normally such containers won't occur, but they can show up when // two messages have References lines that disagree. For example, // assuming A and B are messages, and 1, 2, and 3 are references for // messages we haven't seen: // // A has refs: 1 2 3 // B has refs: 1 3 // // There is ambiguity whether 3 is a child of 1 or 2. So, // depending on the processing order, we might end up with either // // -- 1 // |-- 2 // |-- 3 // |-- A // |-- B // or // -- 1 // |-- 2 <--- non-root childless container // |-- 3 // |-- A // |-- B // if prev == nil { parent.child = container.next } else { prev.next = container.next } // Set container to prev so that prev keeps its same value // the next time through the loop. // container = prev } else if container.threadable == nil && // expired, and container.child != nil && // has kids, and (container.parent != nil || // not at root, or container.child.next == nil) { // only one kid // Expired message with kids. Promote the kids to this level. // Don't do this if we would be promoting them to the root level, // unless there is only one kid. // var tail *threadContainer var kids = container.child // Remove this container from the list, replacing it with `kids' // if prev == nil { parent.child = kids } else { prev.next = kids } // Make each child's parent be this level's parent. // Make the last child's next be this container's next // - splicing `kids' into the list in place of `container' // for tail = kids; tail.next != nil; tail = tail.next { tail.parent = container.parent } tail.parent = container.parent tail.next = container.next // Since we've inserted items in the chain, `next' currently points // to the item after them (tail.next); reset that so that we process // the newly promoted items the very next time around. // next = kids // Set container to prev so that prev keeps its same value // the next time through the loop. // container = prev } else if container.child != nil { // A real message with kids. // Iterate over its children, and try to strip out the junk. // t.pruneEmptyContainers(container) } // Set up for the next iteration // prev = container container = next if container == nil { next = nil } else { next = container.next } } } // If any two members of the root set have the same subject, merge them. // This is so that messages which don't have References headers at all // still get threaded (to the extent possible, at least.) // func (t *Threader) gatherSubjects() { var count int subjTable := make(map[string]*threadContainer) for c := t.rootNode.child; c != nil; c = c.next { threadable := c.threadable // If there is no threadable, this is a dummy node in the root set. // Only root set members may be dummies, and they always have at least // two kids. Take the first kid as representative of the subject. // if threadable == nil { threadable = c.child.threadable } subj := threadable.SimplifiedSubject() if subj == "" { continue } old := subjTable[subj] // Add this container to the table if: // - There is no container in the table with this subject, or // - This one is a dummy container and the old one is not: the dummy // one is more interesting as a root, so put it in the table instead. // - The container in the table has a "Re:" version of this subject, // and this container has a non-"Re:" version of this subject. // The non-re version is the more interesting of the two. // if old == nil || (c.threadable == nil && old.threadable != nil) || (old.threadable != nil && old.threadable.SubjectIsReply() && c.threadable != nil && !c.threadable.SubjectIsReply()) { subjTable[subj] = c count++ } } // We are done if the table is empty // if count == 0 { return } // The subj_table is now populated with one entry for each subject which // occurs in the root set. Now iterate over the root set, and gather // together the difference. // var prev, c, rest *threadContainer prev = nil c = t.rootNode.child rest = c.next for c != nil { threadable := c.threadable // might be a dummy -- see above // if threadable == nil { threadable = c.child.threadable } subj := threadable.SimplifiedSubject() // Don't thread together all subject-less messages; let them dangle. // if subj != "" { old := subjTable[subj] if old != c { // Avoid processing ourselves // Ok, so now we have found another container in the root set with // the same subject. There are a few possibilities: // // - If both are dummies, append one's children to the other, and remove // the now-empty container. // // - If one container is a dummy and the other is not, make the non-dummy // one be a child of the dummy, and a sibling of the other "real" // messages with the same subject (the dummy's children.) // // - If that container is a non-dummy, and that message's subject does // not begin with "Re:", but *this* message's subject does, then // make this be a child of the other. // // - If that container is a non-dummy, and that message's subject begins // with "Re:", but *this* message's subject does *not*, then make that // be a child of this one -- they were mis-ordered. (This happens // somewhat implicitly, since if there are two messages, one with Re: // and one without, the one without will be in the hash table, // regardless of the order in which they were seen.) // // - Otherwise, make a new dummy container and make both messages be a // child of it. This catches the both-are-replies and neither-are- // replies cases, and makes them be siblings instead of asserting a // hierarchical relationship which might not be true. // // (People who reply to a message without using "Re:" and without using // a References line will break this slightly. Those people suck.) // // (It has occurred to me that taking the date or message number into // account would be one way of resolving some ambiguous cases, // but that's not altogether straightforward either.) // JI: You cannot rely on the clock settings being correct on a server/client that sent a message // // Remove the "second" message from the root set. if prev == nil { t.rootNode.child = c.next } else { prev.next = c.next } c.next = nil if old.threadable == nil && c.threadable == nil { // They're both dummies; merge them. // var tail *threadContainer for tail = old.child; tail != nil && tail.next != nil; tail = tail.next { } tail.next = c.child for tail = c.child; tail != nil; tail = tail.next { tail.parent = old } c.child = nil } else if old.threadable == nil || // old is empty, or (c.threadable != nil && c.threadable.SubjectIsReply() && // c has Re, and !old.threadable.SubjectIsReply()) { // old does not. // Make this message be a child of the other. c.parent = old c.next = old.child old.child = c } else { // Make the old and new messages be children of a new dummy container. // We do this by creating a new container object for old->msg and // transforming the old container into a dummy (by merely emptying it), // so that the table still points to the one that is at depth 0 // instead of depth 1. // newC := &threadContainer{} newC.threadable = old.threadable newC.child = old.child for tail := newC.child; tail != nil; tail = tail.next { tail.parent = newC } old.threadable = nil old.child = nil c.parent = old newC.parent = old // old is now a dummy; make it have exactly two kids, c and newC. // old.child = c c.next = newC } // we've done a merge, so keep the same `prev' next time around. // c = prev } } prev = c c = rest if rest != nil { rest = rest.next } } } <|start_filename|>examples/visualize/handlers.go<|end_filename|> package main import ( "fmt" "github.com/gatherstars-com/jwz" "github.com/jhillyerd/enmime" "io/fs" "log" "net/mail" "os" "path/filepath" "regexp" "strings" "time" ) // buildEnvelopes finds all email files beneath the given emlDir (files starting with .eml), parses them // and returns a slice full of all the envelopes that we parsed in to existence // func buildEnvelopes(emlDir string, sizeHint int) ([]jwz.Threadable, error) { duprem := make(map[string]string) // Where we are going to store the emails. We know that the test data is of a fair size, so we tell the slice that // in advance // var emails = make([]jwz.Threadable, 0, sizeHint) var ignored int _ = filepath.WalkDir(emlDir, func(path string, d fs.DirEntry, err error) error { if err != nil { log.Printf("cannot process file %s because: %s", path, err) os.Exit(1) } if d.IsDir() { // Skip any directory entries, including the base test data dir // return nil } // We only look at files that have an eml extension // if !strings.HasSuffix(path, ".eml") { return nil } f, e := os.Open(path) if e != nil { return err } envelope, e1 := enmime.ReadEnvelope(f) _ = f.Close() if e1 != nil { log.Printf("cannot parse email file error = %v", e1) return nil } // See if the parser thinks that there are errors - the error recording in the package // is unfortunately a little hokey in that we just get some strings and will have to do // lots of processing if it is left that way. I would prefer to contribute some code that // processes errors like the AWS SDK, so we can check the types of error/warning etc. // if len(envelope.Errors) > 0 { for _, ee := range envelope.Errors { if !ee.Severe { log.Printf("enmime shows a non-fatal error. File '%s', error: %#v", path, ee) } else { log.Printf("enmime parse yields severe error. File: '%s', error: %#v", path, ee) return nil } } } // All is good, so let's accumulate the email, unless it's a duplicate, which sometimes happens // with spammers and test email sets from Kaggle. We will keep duplicates in the input directory but ignore // them for processing in this example. The actual unit test processes all the emails in testdata so that // dealing with garbage input is tested, but here we are creating a visual, so let's just remove the // Manchester United. // thisID := envelope.GetHeader("Message-Id") ent, present := duprem[thisID] if present { log.Printf("Duplicate message id(%s) in file '%s' ignored in favor of file '%s'", thisID, path, ent) ignored++ } else { duprem[thisID] = path email := NewEmail(envelope) emails = append(emails, email) } return nil }) log.Printf("Parsed %d email, with %d ignored for a total of %d", len(emails), ignored, len(emails)+ignored) return emails, nil } // Email implements the Threadable interface - see the interface documentation for the function docs. // This is what a user of this package needs to provide to thread their messages, though you don't have to use // enmime of course. // // You can put anything in here as only next and child are required, though you need some sort of // reference to the email, or at least a few parts of it, such as the Subject, Message-Id, and References // headers. // // You could also add a prev field if you need doubly linked next lists, which can make some things easier // etc. Or use a container or something. This is the simplest example - you should get the idea, big nose. // type Email struct { email *enmime.Envelope next jwz.Threadable parent jwz.Threadable child jwz.Threadable dummy bool forID string } // GetNext the next Threadable in the chain, if any // func (e *Email) GetNext() jwz.Threadable { return e.next } // GetChild the child Threadable of this node, if any // func (e *Email) GetChild() jwz.Threadable { return e.child } // GetParent the parent Threadable of this node, if any // func (e *Email) GetParent() jwz.Threadable { return e.parent } // GetDate extracts the timestamp from the enmime envelope contained in the supplied Threadable // func (e *Email) GetDate() time.Time { // We can have dummies because we are likely to have parsed a set of emails with incomplete threads, // where the start of the thread or sub thread was referenced, but we did not get to parse it, at least yet. // This means it will be a placeholder as the root for the thread, so we can use the time of the child as the // time of this email. // if e.IsDummy() { if e.GetChild() != nil { return e.GetChild().GetDate() } // Protect against having nothing in the children that knows what time it is. So, back to the // beginning of time according to Unix // return time.Unix(0, 0) } emailDateStr := e.email.GetHeader("Date") d, err := mail.ParseDate(emailDateStr) if err != nil { return time.Unix(0, 0) } return d } var idre = regexp.MustCompile("<.*?>") // MessageThreadID the id of this email message // func (e *Email) MessageThreadID() string { if e.dummy { return e.forID } ref := e.email.GetHeader("Message-Id") refs := idre.FindAllString(ref, -1) if len(refs) > 0 { return refs[0] } return "<bogus-id-in-email>" } func (e *Email) MessageThreadReferences() []string { if e.dummy { return nil } // This should be a nicely formatted field that has unique IDs enclosed within <>, and each of those should be // space separated. However, it isn't as simple as this because all sorts of garbage mail clients have been programmed // over the years by people who did not understand what the References field was (I'm looking at you // Comcast, for instance). We can get things like: // // 1) References: Your message of Friday... <actual-ID> (Some garbage the programmer thought might be useful) // 2) References: <EMAIL> (This isn't even a reference, it is the sender's email) // 3) References: <ref-1><ref-2><ref-3> (Either a pure bug, or they misread the spec) // // Further to this, we also need to filter out the following: // // 4) References: <this message-id> (The client author places this email as the first in the // reference chain) // 5) References: <ref-1><ref-2><ref-1> A pure bug somewhere in the chain repeats a reference // // The RFC has now been cleaned up to exactly specify this field, but we have to assume there are still // 20 year old email clients out there and cater for them. Especially when we are testing with ancient // public email bodies. // ref := e.email.GetHeader("References") // Find all the correctly delimited references, which takes care of 1) and 3) // rawRefs := idre.FindAllString(ref, -1) // Find the message Id, so we can take care of 4) // m := e.MessageThreadID() // Find the From address, so we can deal with 2). Even though ignoring this would be harmless in that we would just // think it is an email we never saw, it is wrong not to deal with here. We can avoid the clutter in the database // by filtering them out. // fa, _ := e.email.AddressList("From") // Make a set, so we can remove duplicates and deal with 5) // set := make(map[string]interface{}) // This will be our final return set, after de-fucking the references // var refs = make([]string, 0, len(rawRefs)) // Now we range through the references that the email has given us and make sure that the reference does // not run afoul of 2), 4) or 5) // for _, r := range rawRefs { // 2) and 5) // if _, repeated := set[r]; r != m && !repeated { set[r] = nil // Technically, From: can have more than one sender (back in the day before email lists // got sorted), we will never see this in practice, but, in for a pound, in for a penny // var found bool = false for _, f := range fa { if r == "<"+f.Address+">" { found = true break } } if !found { // If we got thorough all of those checks, then Phew! Made it! // refs = append(refs, r) } } } return refs } var re = regexp.MustCompile("[Rr][Ee][ \t]*:[ \t]*") // SimplifiedSubject the email subject without any Re: prefixes. If this // Threadable is a dummy, but it has a child, we try to use the subject in the // child, if it has one. Note that this is only used for threading if there are // no references etc // func (e *Email) SimplifiedSubject() string { if e.dummy { return "" } subj := e.email.GetHeader("Subject") subj = re.ReplaceAllString(subj, "") return strings.Trim(subj, " ") } // Subject the subject as defined in the email, plus a few adornments so that humans can see that // the threading is correct and see the sort order // func (e *Email) Subject() string { if e.dummy { if e.child != nil { return e.child.Subject() + " :: node synthesized by https://gatherstars.com/" } return fmt.Sprintf("Placeholder %s - manufactured by https://gatherstars.com/", e.MessageThreadID()) } // Add in the date for a bit of extra information // var sb strings.Builder t := e.GetDate() sb.WriteString(t.UTC().String()) sb.WriteString(" : ") sb.WriteString(strings.Trim(e.email.GetHeader("Subject"), " ")) return sb.String() } // SubjectIsReply true if the Subject header of this email appears to indicate it is a reply to something. // This is only used if there are no references in the Threadables that otherwise show that relationship func (e *Email) SubjectIsReply() bool { if e.dummy { return false } subj := e.email.GetHeader("Subject") return re.MatchString(subj) } // SetNext allows us to change or add a pointer to the next Threadable in a set of emails // func (e *Email) SetNext(next jwz.Threadable) { e.next = next } // SetChild allows us to add or change the child Threadable of this node // func (e *Email) SetChild(kid jwz.Threadable) { e.child = kid if kid != nil { kid.SetParent(e) } } // SetParent allows us to add or change the parent Threadable of this node // func (e *Email) SetParent(parent jwz.Threadable) { e.parent = parent } // MakeDummy manufactures a placeholder Threadable that other Threadables can become children of. See // interface documentation for more details - note that this may be subject to change to also supply the // MessageID that this dummy is placeholder for, if we have it // func (e *Email) MakeDummy(forID string) jwz.Threadable { return &Email{ dummy: true, forID: forID, } } // IsDummy true if this Threadable is a Manchester United supporter // func (e *Email) IsDummy() bool { return e.dummy } // NewEmail creates a new structure that implements the jwz.Threadable interface. it should be obvious that // your struct can contain whatever you want it to, so long as it obeys the jwz.Threadable contract. Here, // we use it to pass around a pointer to the enmime envelope that we have parsed an email into. // func NewEmail(envelope *enmime.Envelope) jwz.Threadable { e := &Email{ email: envelope, dummy: false, } return e } // byDate is a sort comparison function that is used to call in to the Threadable Sort utility function and // sort the threads by Date // func byDate(t1 jwz.Threadable, t2 jwz.Threadable) bool { return t1.GetDate().Before(t2.GetDate()) } <|start_filename|>utils_test.go<|end_filename|> package jwz import ( "fmt" ) func ExampleSort() { // Emails := loadEmails() - your function to load emails into a slice // // Create a threader and thread using the slice of Threadable in the slice called Emails // threader := NewThreader() sliceRoot, err := threader.ThreadSlice(Emails) if err != nil { fmt.Printf("func ThreadSlice() error = %#v", err) } // Count with no dummies // var n, ns int Count(sliceRoot, &n) // Sort it Rodney! // x := Sort(sliceRoot, func(t1 Threadable, t2 Threadable) bool { // Sort by date, inline function // return t1.GetDate().Before(t2.GetDate()) }) Count(x, &ns) if n != ns { fmt.Printf("Count before sort: %d, Count after sort: %d\n", n, ns) } fmt.Printf("First node subject: %s\n", x.Subject()) // Output: First node subject: 1970-01-01 00:00:00 +0000 UTC : Re: My source: RE: A biblical digression :: node synthesized by https://gatherstars.com/ } func ExampleWalk_depth() { // Emails := loadEmails() - your function to load emails into a slice // // Create a threader and thread using the slice of Threadable in the slice called Emails // threader := NewThreader() sliceRoot, err := threader.ThreadSlice(Emails) if err != nil { fmt.Printf("func ThreadSlice() error = %#v", err) } var c int _ = Walk(true, sliceRoot, func(t Threadable, u interface{}) (bool, error) { c := u.(*int) if !t.IsDummy() { *c++ } return false, nil }, &c) fmt.Printf("Walker walked %d depth first\n", c) // Output: Walker walked 2379 depth first } func ExampleWalk_breadth() { // Emails := loadEmails() - your function to load emails into a slice // // Create a threader and thread using the slice of Threadable in the slice called Emails // threader := NewThreader() sliceRoot, err := threader.ThreadSlice(Emails) if err != nil { fmt.Printf("func ThreadSlice() error = %#v", err) } var c int // Walk the tree breadth first and call our anonymous function on each Threadable // _ = Walk(false, sliceRoot, func(t Threadable, u interface{}) (bool, error) { c := u.(*int) if !t.IsDummy() { *c++ } return false, nil }, &c) fmt.Printf("Walker walked %d depth first\n", c) // Output: Walker walked 2379 depth first } type searcher struct { messageID string e Threadable } func ExampleWalk_search() { // Emails := loadEmails() - your function to load emails into a slice // // Create a threader and thread using the slice of Threadable in the slice called Emails // threader := NewThreader() sliceRoot, err := threader.ThreadSlice(Emails) if err != nil { fmt.Printf("func ThreadSlice() error = %#v", err) } // Construct our search // var param = &searcher{ messageID: "<008701c24a16$e3443830$0200a8c0@JMHALL>", } // Walk the tree breadth first and call our anonymous function on each Threadable // _ = Walk(false, sliceRoot, func(t Threadable, u interface{}) (bool, error) { params := u.(*searcher) if !t.IsDummy() { if t.MessageThreadID() == params.messageID { // We found the email we wanted, so we can stop here // params.e = t return true, nil } } return false, nil }, param) fmt.Printf("Walker found the email %s with subject %s\n", param.messageID, param.e.Subject()) // Walker found the email <008701c24a16$e3443830$0200a8c0@JMHALL> with subject 2002-08-22 20:02:45 +0000 UTC : Property rights in the 3rd World (De Soto's Mystery of Capital) } func ExampleCount() { // Emails := loadEmails() - your function to load emails into a slice // // Create a threader and thread using the slice of Threadable in the slice called Emails // threader := NewThreader() sliceRoot, err := threader.ThreadSlice(Emails) if err != nil { fmt.Printf("func ThreadSlice() error = %#v", err) return } // Find out how many non dummy Threadables are in the tree - in other words, how many // actual emails are there in the tree? // var nc int Count(sliceRoot, &nc) fmt.Printf("There are %d test emails", nc) // Output: There are 2379 test emails } <|start_filename|>jwz_test.go<|end_filename|> package jwz import ( "fmt" "github.com/jhillyerd/enmime" "io/fs" "log" "net/mail" "os" "path/filepath" "regexp" "strings" "testing" "time" ) // Where we are going to store the emails. We know that the test data is of a fair size, so we tell the slice that // in advance // var Emails = make([]Threadable, 0, 3000) // TestMain sets up everything for the other test(s). It essentially parses a largish set of publicly available // Emails in to a structure that can then be used to perform email threading testing. To perform the parsing, we // use the enmime package at https://github.com/jhillyerd/enmime // func TestMain(m *testing.M) { // Parse all the emails in the test directory // loadEmails() // OK, we have a fairly large email set all parsed, so now we can let the real tests run // os.Exit(m.Run()) } func loadEmails() { _ = filepath.WalkDir("test/testdata", func(path string, d fs.DirEntry, err error) error { if err != nil { log.Printf("cannot process directory/file %s because: %#v", path, err) os.Exit(1) } if d.IsDir() { // Skip any directory entries, including the base test data dir // return nil } // We only look at files that have an eml extension // if !strings.HasSuffix(path, ".eml") { return nil } f, e := os.Open(path) if e != nil { return err } envelope, e1 := enmime.ReadEnvelope(f) _ = f.Close() if e1 != nil { log.Printf("cannot parse email file error = %v", e1) return nil } // See if the parser thinks that there are errors - the error recording in the package // is unfortunately a little hokey in that we just get some strings and will have to do // lots of processing if it is left that way. I would prefer to contribute some code that // processes errors like the AWS SDK, so we can check the types of error/warning etc. // if len(envelope.Errors) > 0 { for _, ee := range envelope.Errors { if ee.Severe { log.Printf("enmime parse yields severe error. File '%s', error: %#v", path, ee) return nil } log.Printf("enmime shows a non-fatal error. File '%s'm error: %#v", path, ee) } } // All is good, so let's accumulate the email // email := NewEmail(envelope) Emails = append(Emails, email) return nil }) } // EmailRoot is a structure that implements the ThreadableRoot interface. I have not used ThreadableRoot // here, but this is what it needs to look like if your input structure is not just a slice of Threadable // type EmailRoot struct { // This is some structure of the emails you want to thread, that you know how to traverse // emails []Threadable // You need some sort of position holder, which in this silly example is an index in the struct // position int } // Next sets the internal cursor to the next available Threadable // func (e *EmailRoot) Next() bool { e.position = e.position + 1 if e.position < len(e.emails) { return true } return false } // Get returns the Threadable at the current internal cursor position // func (e *EmailRoot) Get() Threadable { return e.emails[e.position] } // NewThreadableRoot returns a struct instance that can be traversed using the ThreadableRoot interface // func NewThreadableRoot(emails []Threadable) ThreadableRoot { tr := &EmailRoot{ emails: emails, position: -1, } return tr } // Email is structure that implements the Threadable interface - this is what a user of this // package needs to do. // type Email struct { email *enmime.Envelope next Threadable parent Threadable child Threadable dummy bool forID string } func (e *Email) GetNext() Threadable { return e.next } func (e *Email) GetChild() Threadable { return e.child } // GetParent the parent Threadable of this node, if any // func (e *Email) GetParent() Threadable { return e.parent } // GetDate extracts the timestamp from the enmime envelope contained in the supplied Threadable // func (e *Email) GetDate() time.Time { // We can have dummies because we are likely to have parsed a set of emails with incomplete threads, // where the start of the thread or sub thread was referenced, but we did not get to parse it, at least yet. // This means it will be a placeholder as the root for the thread, so we can use the time of the child as the // time of this email. // if e.IsDummy() { if e.GetChild() != nil { return e.GetChild().GetDate() } // Protect against having nothing in the children that knows what time it is. So, back to the // beginning of time according to Unix // return time.Unix(0, 0) } emailDateStr := e.email.GetHeader("Date") d, err := mail.ParseDate(emailDateStr) if err != nil { return time.Unix(0, 0) } return d } var idre = regexp.MustCompile("<.*?>") func (e *Email) MessageThreadID() string { if e.dummy { return e.forID } ref := e.email.GetHeader("Message-Id") refs := idre.FindAllString(ref, -1) if len(refs) > 0 { return refs[0] } return "<bogus-id-in-email>" } func (e *Email) MessageThreadReferences() []string { if e.dummy { return nil } // This should be a nicely formatted field that has unique IDs enclosed within <>, and each of those should be // space separated. However, it isn't as simple as this because all sorts of garbage mail clients have been programmed // over the years by people who did not understand what the References field was (I'm looking at you // Comcast, for instance). We can get things like: // // 1) References: Your message of Friday... <actual-ID> (Some garbage the programmer thought might be useful) // 2) References: <EMAIL> (This isn't even a reference, it is the sender's email) // 3) References: <ref-1><ref-2><ref-3> (Either a pure bug, or they misread the spec) // // Further to this, we also need to filter out the following: // // 4) References: <this message-id> (The client author places this email as the first in the // reference chain) // 5) References: <ref-1><ref-2><ref-1> A pure bug somewhere in the chain repeats a reference // // The RFC has now been cleaned up to exactly specify this field, but we have to assume there are still // 20 year old email clients out there and cater for them. Especially when we are testing with ancient // public email bodies. // ref := e.email.GetHeader("References") // Find all the correctly delimited references, which takes care of 1) and 3) // rawRefs := idre.FindAllString(ref, -1) // Find the message Id, so we can take care of 4) // m := e.MessageThreadID() // Find the From address, so we can deal with 2). Even though ignoring this would be harmless in that we would just // think it is an email we never saw, it is wrong not to deal with here. We can avoid the clutter in the database // by filtering them out. // fa, _ := e.email.AddressList("From") // Make a set, so we can remove duplicates and deal with 5) // set := make(map[string]interface{}) // This will be our final return set, after de-fucking the references // var refs = make([]string, 0, len(rawRefs)) // Now we range through the references that the email has given us and make sure that the reference does // not run afoul of 2), 4) or 5) // for _, r := range rawRefs { // 2) and 5) // if _, repeated := set[r]; r != m && !repeated { set[r] = nil // Technically, From: can have more than one sender (back in the day before email lists // got sorted), we will never see this in practice, but, in for a pound, in for a penny // var found bool = false for _, f := range fa { if r == "<"+f.Address+">" { found = true break } } if !found { // If we got thorough all of those checks, then Phew! Made it! // refs = append(refs, r) } } } return refs } var re = regexp.MustCompile("[Rr][Ee][ \t]*:[ \t]*") func (e *Email) SimplifiedSubject() string { if e.dummy { return "" } subj := e.email.GetHeader("Subject") subj = re.ReplaceAllString(subj, "") return subj } func (e *Email) Subject() string { if e.dummy { if e.child != nil { return e.child.Subject() + " :: node synthesized by https://gatherstars.com/" } return fmt.Sprintf("Placeholder %s - manufactured by https://gatherstars.com/", e.forID) } // Add in the date for a bit of extra information // var sb strings.Builder t := e.GetDate() sb.WriteString(t.UTC().String()) sb.WriteString(" : ") sb.WriteString(strings.Trim(e.email.GetHeader("Subject"), " ")) return sb.String() } func (e *Email) SubjectIsReply() bool { subj := e.email.GetHeader("Subject") return re.MatchString(subj) } func (e *Email) SetNext(next Threadable) { e.next = next } func (e *Email) SetChild(kid Threadable) { e.child = kid if kid != nil { kid.SetParent(e) } } // SetParent allows us to add or change the parent Threadable of this node // func (e *Email) SetParent(parent Threadable) { e.parent = parent } func (e *Email) MakeDummy(forID string) Threadable { return &Email{ dummy: true, forID: forID, } } func (e *Email) IsDummy() bool { return e.dummy } func NewEmail(envelope *enmime.Envelope) Threadable { e := &Email{ email: envelope, dummy: false, } return e } func ExampleThreader_ThreadSlice() { // Emails := loadEmails() - your function to load emails into a slice // // Create a threader and thread using the slice of Threadable in the slice called Emails // threader := NewThreader() sliceRoot, err := threader.ThreadSlice(Emails) if err != nil { fmt.Printf("func ThreadSlice() error = %#v", err) return } // Make sure that number we got back, not including dummies, is the same as we sent in // var nc int Count(sliceRoot, &nc) if nc != 2379 { fmt.Printf("expected %d emails after threading, but got %d back", 2379, nc) } else { fmt.Printf("There are %d test emails", nc) } // Output: There are 2379 test emails } func TestThreader_ThreadSlice(t1 *testing.T) { // Emails := loadEmails() - your function to load emails into a slice // // Create a threader and thread using the slice of Threadable in the slice called Emails // threader := NewThreader() sliceRoot, err := threader.ThreadSlice(Emails) if err != nil { t1.Errorf("func ThreadSlice() error = %#v", err) } // Make sure that number we got back, not including dummies, is the same as we sent in // var nc int Count(sliceRoot, &nc) if nc != 2379 { t1.Errorf("expected %d emails after threading, but got %d back", 2379, nc) } } func ExampleThreader_ThreadRoot() { // Emails := loadEmails() - your function to load emails into a slice // // Create a threader and thread using the slice of Threadable in the slice called Emails // tr := NewThreadableRoot(Emails) threader := NewThreader() treeRoot, err := threader.ThreadRoot(tr) if err != nil { fmt.Printf("func ThreadRoot() error = %#v", err) } if treeRoot == nil { fmt.Printf("received no output from the threading algorithm") } // Make sure that number we got back, not including dummies, is the same as we sent in // var nc int Count(treeRoot, &nc) if nc != 2379 { fmt.Printf("expected %d emails afer threading, but got %d back", 2379, nc) } else { fmt.Printf("There are %d test emails", nc) } // Output: There are 2379 test emails } func TestThreader_ThreadRoot(t1 *testing.T) { // Emails := loadEmails() - your function to load emails into a slice // // Create a threader and thread using the ThreadableRootInterface to traverse the emails // tr := NewThreadableRoot(Emails) threader := NewThreader() treeRoot, err := threader.ThreadRoot(tr) if err != nil { t1.Errorf("ThreadRoot() error = %#v", err) } if treeRoot == nil { t1.Errorf("received no output from the threading algorithm") } // Make sure that number we got back, not including dummies, is the same as we sent in // var nc int Count(treeRoot, &nc) if nc != 2379 { t1.Errorf("expected %d emails after threading, but got %d back", 2379, nc) } }
gatherstars-com/jwz
<|start_filename|>scripts/spotify.scpt<|end_filename|> set currentlyPlayingTrack to getCurrentlyPlayingTrack() on getCurrentlyPlayingTrack() if application "Spotify" is running then tell application "Spotify" set currentArtist to artist of current track as string set currentTrack to name of current track as string return currentArtist & "<<|asn|>>" & currentTrack end tell end if end getCurrentlyPlayingTrack <|start_filename|>scripts/itunes.scpt<|end_filename|> set currentlyPlayingTrack to getCurrentlyPlayingTrack() on getCurrentlyPlayingTrack() if application "iTunes" is running then tell application "iTunes" set currentArtist to the artist of the current track set currentTitle to the name of the current track return currentArtist & "<<|asn|>>" & currentTitle end tell end if end getCurrentlyPlayingTrack
vas3k/valyrics
<|start_filename|>buildkonfig-compiler/src/main/kotlin/com/codingfeline/buildkonfig/compiler/Constants.kt<|end_filename|> package com.codingfeline.buildkonfig.compiler const val DEFAULT_KONFIG_OBJECT_NAME = "BuildKonfig" typealias Logger = (String) -> Unit <|start_filename|>buildkonfig-gradle-plugin/src/main/kotlin/com/codingfeline/buildkonfig/gradle/TargetConfigDsl.kt<|end_filename|> package com.codingfeline.buildkonfig.gradle import com.codingfeline.buildkonfig.compiler.FieldSpec import com.codingfeline.buildkonfig.compiler.TargetConfig import org.gradle.api.logging.Logger import java.io.Serializable import javax.inject.Inject open class TargetConfigDsl @Inject constructor( name: String, private val logger: Logger ) : TargetConfig(name), Serializable { companion object { const val serialVersionUID = 1L } @Suppress("unused") fun buildConfigField( type: FieldSpec.Type, name: String, value: String ) { val alreadyPresent = fieldSpecs[name] if (alreadyPresent != null) { logger.info("TargetConfig: buildConfigField '$name' is being replaced: ${alreadyPresent.value} -> $value") } fieldSpecs[name] = FieldSpec(type, name, value) } @Suppress("unused") fun buildConfigNullableField( type: FieldSpec.Type, name: String, value: String? ) { val alreadyPresent = fieldSpecs[name] if (alreadyPresent != null) { logger.info("TargetConfig: buildConfigField '$name' is being replaced: ${alreadyPresent.value} -> $value") } fieldSpecs[name] = FieldSpec(type, name, value, nullable = true) } fun toTargetConfig(): TargetConfig { return TargetConfig(name) .also { it.flavor = flavor it.fieldSpecs.putAll(fieldSpecs) } } } <|start_filename|>buildkonfig-compiler/src/main/kotlin/com/codingfeline/buildkonfig/compiler/FieldSpec.kt<|end_filename|> package com.codingfeline.buildkonfig.compiler import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.asTypeName import java.io.Serializable data class FieldSpec( private val type: Type, val name: String, val value: String?, val isTargetSpecific: Boolean = false, val nullable: Boolean = false ) : Serializable { enum class Type(val _typeName: TypeName, val _template: String = "%L") { STRING(String::class.asTypeName(), "%S"), INT(Int::class.asTypeName()), FLOAT(Float::class.asTypeName()), LONG(Long::class.asTypeName()), BOOLEAN(Boolean::class.asTypeName()); } val typeName: TypeName get() = with(type) { if (nullable) _typeName.copy(nullable = true) else _typeName.copy() } val template: String get() = with(type) { if (nullable && value == null) "%L" else _template } } <|start_filename|>buildkonfig-compiler/src/main/kotlin/com/codingfeline/buildkonfig/compiler/TargetName.kt<|end_filename|> package com.codingfeline.buildkonfig.compiler import java.io.Serializable data class TargetName( val name: String, val platformType: PlatformType ) : Serializable /** * see org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType */ enum class PlatformType { common, jvm, js, androidJvm, native; } <|start_filename|>buildkonfig-gradle-plugin/src/main/kotlin/com/codingfeline/buildkonfig/gradle/TargetConfigFactory.kt<|end_filename|> package com.codingfeline.buildkonfig.gradle import org.gradle.api.NamedDomainObjectFactory import org.gradle.api.logging.Logger import org.gradle.api.model.ObjectFactory class TargetConfigFactory( private val objectFactory: ObjectFactory, private val logger: Logger ) : NamedDomainObjectFactory<TargetConfigDsl> { override fun create(name: String): TargetConfigDsl { return objectFactory.newInstance(TargetConfigDsl::class.java, name, logger) } } <|start_filename|>buildkonfig-compiler/src/main/kotlin/com/codingfeline/buildkonfig/compiler/BuildKonfigEnvironment.kt<|end_filename|> package com.codingfeline.buildkonfig.compiler import com.codingfeline.buildkonfig.compiler.generator.BuildKonfigCompiler import com.codingfeline.buildkonfig.compiler.generator.FileAppender import java.io.File class BuildKonfigEnvironment( private val data: BuildKonfigData ) { sealed class CompilationStatus { object Success : CompilationStatus() class Failure(val errors: List<String>) : CompilationStatus() } fun generateConfigs(logger: Logger): CompilationStatus { val errors = ArrayList<String>() val writer = writer@{ fileName: String -> val file = File(fileName) if (!file.exists()) { file.parentFile.mkdirs() file.createNewFile() } return@writer file.writer() } if (data.hasTargetSpecificConfigs) { compileExpectActual(data, writer, logger) } else { compileCommonObject(data, writer, logger) } return if (errors.isEmpty()) { CompilationStatus.Success } else { CompilationStatus.Failure(errors) } } private fun compileCommonObject(data: BuildKonfigData, writer: FileAppender, logger: Logger): List<String> { val errors = mutableListOf<String>() try { BuildKonfigCompiler.compileCommonObject( data.packageName, data.objectName, data.exposeObject, data.commonConfig, data.hasJsTarget, writer, logger ) } catch (e: Throwable) { e.message?.let { errors.add(it) } } return errors } private fun compileExpectActual(data: BuildKonfigData, writer: FileAppender, logger: Logger): List<String> { val errors = mutableListOf<String>() try { BuildKonfigCompiler.compileCommon( data.packageName, data.objectName, data.exposeObject, data.commonConfig, writer, logger ) } catch (e: Throwable) { e.message?.let { errors.add(it) } } data.targetConfigs.filter { it.config != null } .forEach { config -> try { BuildKonfigCompiler.compileTarget( data.packageName, data.objectName, data.exposeObject, config, writer, logger ) } catch (e: Throwable) { e.message?.let { errors.add(it) } } } return errors } }
Coronel-B/BuildKonfig
<|start_filename|>app/src/main/java/chat/rocket/android/server/infraestructure/SharedPrefsConnectingServerRepository.kt<|end_filename|> package chat.rocket.android.server.infraestructure import android.content.SharedPreferences import chat.rocket.android.server.domain.CurrentServerRepository class SharedPrefsConnectingServerRepository(private val preferences: SharedPreferences) : CurrentServerRepository { override fun save(url: String) { preferences.edit().putString(CONNECTING_SERVER_KEY, url).apply() } override fun get(): String? { return preferences.getString(CONNECTING_SERVER_KEY, null) } companion object { private const val CONNECTING_SERVER_KEY = "connecting_server" } override fun clear() { preferences.edit().remove(CONNECTING_SERVER_KEY).apply() } } <|start_filename|>app/src/main/java/chat/rocket/android/chatroom/domain/UriInteractor.kt<|end_filename|> package chat.rocket.android.chatroom.domain import android.content.Context import android.net.Uri import chat.rocket.android.util.extensions.* import javax.inject.Inject class UriInteractor @Inject constructor(private val context: Context) { /** * Returns the file name from the [Uri]. */ fun getFileName(uri: Uri): String? = uri.getFileName(context) /** * Returns the MimeType from the [Uri]. */ fun getMimeType(uri: Uri): String = uri.getMimeType(context) /** * Returns the file size from the [Uri]. */ fun getFileSize(uri: Uri) = uri.getFileSize(context) /** * Returns the InputStream from the [Uri]. */ fun getInputStream(uri: Uri) = uri.getInputStream(context) /** * Returns the Bitmap from the [Uri]. * * Note: It should be an image. */ fun getBitmap(uri: Uri) = uri.getBitmpap(context) } <|start_filename|>app/src/play/java/chat/rocket/android/push/di/FirebaseMessagingServiceProvider.kt<|end_filename|> package chat.rocket.android.push.di import chat.rocket.android.dagger.module.AppModule import chat.rocket.android.push.FirebaseMessagingService import dagger.Module import dagger.android.ContributesAndroidInjector @Module abstract class FirebaseMessagingServiceProvider { @ContributesAndroidInjector(modules = [AppModule::class]) abstract fun provideFirebaseMessagingService(): FirebaseMessagingService } <|start_filename|>app/src/main/java/chat/rocket/android/server/infraestructure/MemoryUsersRepository.kt<|end_filename|> package chat.rocket.android.server.infraestructure import chat.rocket.android.server.domain.UsersRepository import chat.rocket.android.server.domain.UsersRepository.Query import chat.rocket.common.model.User import java.util.concurrent.CopyOnWriteArrayList class MemoryUsersRepository : UsersRepository { private val users = CopyOnWriteArrayList<User>() override fun getAll(): List<User> { return users.toList() } override fun get(query: Query.() -> Unit): List<User> { val q = Query().apply(query) return users.filter { with(q) { if (name != null && it.name?.contains(name!!.toRegex()) == true) return@filter false if (username != null && it.username?.contains(username!!.toRegex()) == true) return@filter false if (id != null && id == it.id) return@filter false if (status != null && status == it.status) return@filter false return@filter true } } } override fun save(user: User) { users.addIfAbsent(user) } override fun saveAll(userList: List<User>) { users.addAllAbsent(userList) } override fun clear() { this.users.clear() } } <|start_filename|>app/src/main/java/chat/rocket/android/main/adapter/AccountsAdapter.kt<|end_filename|> package chat.rocket.android.main.adapter import androidx.recyclerview.widget.RecyclerView import android.view.ViewGroup import chat.rocket.android.R import chat.rocket.android.server.domain.model.Account import chat.rocket.android.util.extensions.inflate import chat.rocket.common.model.UserStatus private const val VIEW_TYPE_CHANGE_STATUS = 0 private const val VIEW_TYPE_ACCOUNT = 1 private const val VIEW_TYPE_ADD_ACCOUNT = 2 class AccountsAdapter( private val accounts: List<Account>, private val selector: Selector ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return when (viewType) { VIEW_TYPE_CHANGE_STATUS -> StatusViewHolder(parent.inflate(R.layout.item_change_status)) VIEW_TYPE_ACCOUNT -> AccountViewHolder(parent.inflate(R.layout.item_account)) else -> AddAccountViewHolder(parent.inflate(R.layout.item_add_account)) } } override fun getItemCount() = accounts.size + 2 override fun getItemViewType(position: Int): Int { return when { position == 0 -> VIEW_TYPE_CHANGE_STATUS position <= accounts.size -> VIEW_TYPE_ACCOUNT else -> VIEW_TYPE_ADD_ACCOUNT } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (holder) { is StatusViewHolder -> bindStatusViewHolder(holder) is AccountViewHolder -> bindAccountViewHolder(holder, position) is AddAccountViewHolder -> bindAddAccountViewHolder(holder) } } private fun bindStatusViewHolder(holder: StatusViewHolder) { holder.bind { userStatus -> selector.onStatusSelected(userStatus) } } private fun bindAccountViewHolder(holder: AccountViewHolder, position: Int) { val account = accounts[position - 1] holder.bind(account) holder.itemView.setOnClickListener { selector.onAccountSelected(account.serverUrl) } } private fun bindAddAccountViewHolder(holder: AddAccountViewHolder) { holder.itemView.setOnClickListener { selector.onAddedAccountSelected() } } } interface Selector { fun onStatusSelected(userStatus: UserStatus) fun onAccountSelected(serverUrl: String) fun onAddedAccountSelected() } <|start_filename|>app/src/main/java/chat/rocket/android/settings/presentation/SettingsView.kt<|end_filename|> package chat.rocket.android.settings.presentation interface SettingsView
luckcoolla/Rocket.Chat.Android
<|start_filename|>.storybook/webpack.config.js<|end_filename|> const path = require("path"); const include = [ path.resolve(__dirname, '../stories'), path.resolve(__dirname, '../lib/') ]; module.exports = { resolve: { extensions: [".ts", ".tsx", ".js"] }, module: { rules: [ { test: /\.tsx?/, loader: 'babel-loader!awesome-typescript-loader', exclude: /node_modules/, include } ] } }; <|start_filename|>.storybook/config.js<|end_filename|> import { configure, addDecorator } from '@storybook/react'; import { schemaString, mocks } from '../graphql-mock'; import apolloStorybookDecorator from 'apollo-storybook-react'; import '@storybook/addon-console'; const req = require.context('../stories', true, /\.tsx?$/) addDecorator( apolloStorybookDecorator({ typeDefs: schemaString, mocks }) ); function loadStories() { req.keys().forEach((filename) => req(filename)) } configure(loadStories, module);
mikejmets/react-apollo-form