repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
tinyos-io/tinyos-3.x-contrib
berkeley/quanto/tools/quanto/labjack/ue9.h
//Author: LabJack //Aug. 8, 2008 //Header for UE9 example helper functions. // //History //-(10/11/2005) added structure for storing calibration info //-(10/11/2005) added the following functions: // binaryToCalibratedAnalogVoltage // binaryToCalibratedAnalogTemperature // analogToCalibratedBinaryVoltage // binaryToUncalibratedAnalogVoltage // analogToUncalibratedBinaryVoltage // FPuint8ArrayToFPDouble // getCalibrationInfo //-(10/11/2005) removed the following functions: // translateCalibratedVoltage // translateUncalibratedVoltage // getAnalogCalibrationInfo // fpArrayTofpDouble (now FPuint8ArrayToFPDouble) //-(01/11/2006) changed header include order in ue9.h so that code compiles under MAC OS X. //-(12/19/2006) added calibrations for hi-res mode for the UE9 Pro //-(12/19/2006) added resolution parameter for binaryToCalibratedAnalogVoltage(ue9CalibrationInfo //-(12/19/2006) changed the name of CALIBRATION_INFORMATION struct to UE9_CALIBRATION_INFORMATION //-(10/04/2007) added the following functions: // getLJTDACCalibrationInfo // isCalibrationInfoValid // isLJTDACCalibrationInfoValid // LJTDACAnalogToCalibratedBinaryVoltage // binaryToUncalibratedAnalogTemperature // I2C // eAIN // eDAC // eDI // eDO // eTCConfig // eTCValues // ehSingleIO // ehDIO_Feedback // ehTimerCounter //-(10/04/2007) added constants for easy functions //-(10/04/2007) fixed misplaced bracket in getTickCount function //-(10/04/2007) changed server parameter name to ipAddress in openTCPConnection function //-(10/04/2007) added more documentation to ue9.h //-(08/08/2008) fixed a bug in ehDIO_Feedback where CIO and MIO states were only being set #ifndef _UE9_H #define _UE9_H #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <math.h> #ifdef WIN32 #include <winsock.h> #include <windows.h> #else #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/time.h> #endif typedef unsigned char uint8; typedef unsigned short uint16; typedef unsigned int uint32; //Structure for storing calibration constants struct UE9_CALIBRATION_INFORMATION{ uint8 prodID; double unipolarSlope[4]; double unipolarOffset[4]; double bipolarSlope; double bipolarOffset; double DACSlope[2]; double DACOffset[2]; double tempSlope; double tempSlopeLow; double calTemp; double Vref; double VrefDiv2; double VsSlope; double hiResUnipolarSlope; double hiResUnipolarOffset; double hiResBipolarSlope; double hiResBipolarOffset; }; typedef struct UE9_CALIBRATION_INFORMATION ue9CalibrationInfo; //Structure for storing LJTDAC calibration constants struct UE9_LJTDAC_CALIBRATION_INFORMATION{ uint8 prodID; double DACSlopeA; double DACOffsetA; double DACSlopeB; double DACOffsetB; }; typedef struct UE9_LJTDAC_CALIBRATION_INFORMATION ue9LJTDACCalibrationInfo; /* Functions */ void normalChecksum( uint8 *b, int n); //Adds checksum to a data packet for normal command format. //b = data packet for normal command //n = size of data packet void extendedChecksum( uint8 *b, int n); //Adds checksum to a data packet for extended command format. //b = data packet for extended command //n = size of data packet uint8 normalChecksum8( uint8 *b, int n); //Returns the Checksum8 for a normal command data packet. //b = data packet for normal command //n = size of data packet uint16 extendedChecksum16( uint8 *b, int n); //Returns the Checksum16 for a extended command data packet. //b = data packet for extended command //n = size of data packet uint8 extendedChecksum8( uint8 *b); //Returns the Checksum8 for a extended command data packet. //b = data packet for extended command int openTCPConnection( char *ipAddress, int port); //Opens a TCP connection to a UE9 at the specific ipAddress and port. //Returns a value < 0 on failure, or a socket file descriptor on success. int closeTCPConnection( int fd); //Closes the TCP connection specified by the socket file descriptor. Returns -1 //on failure, or 0 on success. long getTickCount(); //Returns the number of milliseconds that has elasped since the system was //started. long getCalibrationInfo( int sd, ue9CalibrationInfo *caliInfo); //Gets calibration information from memory blocks 0-3 of a UE9. Returns the //calibration information in a calibrationInfo structure. //sd = socket descriptor to a UE9 device //caliInfo = structure where calibration information will be stored long getLJTDACCalibrationInfo( int sd, ue9LJTDACCalibrationInfo *caliInfo, uint8 DIOAPinNum); //Gets calibration information from the EEPROM of a LJTick-DAC (LJTDAC). //Returns the calibration information in a LJTDACCalibrationInfo structure. //fd = socket descriptor to a UE9 device //caliInfo = structure where LJTDAC calibration information will be stored //DIOAPinNum = The UE9 digital IO line where the LJTDAC DIOA pin is connected. // The DIOB pin is assumed to be the next digital IO line. double FPuint8ArrayToFPDouble( uint8 *buffer, int startIndex); //Converts a fixed point byte array (starting a startIndex) to a floating point //double value. This function is used primarily by getCalibrationInfo. long isCalibrationInfoValid( ue9CalibrationInfo *caliInfo); //Performs a simple check to determine if the caliInfo struct was set up by //getCalibrationInfo. Returns 0 if caliInfo is not valid, or 1 if it is. //caliInfo = structure where calibrarion information is stored long isLJTDACCalibrationInfoValid( ue9LJTDACCalibrationInfo *caliInfo); //Performs a simple check to determine if the caliInfo struct was set up by //getLJTDACCalibrationInfo. Returns 0 if caliInfo is not valid, or 1 if it is. //caliInfo = structure where LJTDAC calibration information is stored long binaryToCalibratedAnalogVoltage( ue9CalibrationInfo *caliInfo, uint8 gainBip, uint8 resolution, uint16 bytesVoltage, double *analogVoltage); //Translates the binary analog input bytes read from the UE9, to a voltage value //(calibrated). Call getCalibrationInfo first to set up caliInfo. Returns -1 //on error, 0 on success. //caliInfo = structure where calibrarion information is stored //gainBip = the gain option and bipolar setting. The high bit of the byte is the // bipolar setting and the lower 3 bits is the gain option. See the // Feedback function in Section 5.3.3 of the UE9 User's Guide for a table // of BipGain values that can be passed. //resolution = the resolution of the analog reading //bytesVoltage = the 2 byte voltage that will be converted to a analog value //analogVoltage = the converted analog voltage long analogToCalibratedBinaryVoltage( ue9CalibrationInfo *caliInfo, int DACNumber, double analogVoltage, uint16 *bytesVoltage); //Translates a voltage value to binary analog input bytes (calibrated) that can //be sent to a UE9. Call getCalibrationInfo first to set up caliInfo. Returns //-1 on error, 0 on success. //caliInfo = structure where calibrarion information is stored //DACNumber - channel number of the DAC //analogVoltage = the analog voltage that will be converted to a 2 byte value //bytesVoltage = the converted 2 byte voltage long LJTDACAnalogToCalibratedBinaryVoltage( ue9LJTDACCalibrationInfo *caliInfo, int DACNumber, double analogVoltage, uint16 *bytesVoltage); //Translates a voltage value to binary analog input bytes (calibrated) that can //be sent to a LJTick-DAC (LJTDAC). Call getLJTDACCalibrationInfo first to set //up caliInfo. Returns -1 on error, 0 on success. //caliInfo = structure where LJTDAC calibrarion information is stored //DACNumber - channel number of the DAC (0 = DACA, 1 = DACB) //analogVoltage = the analog voltage that will be converted to a 2 byte value //bytesVoltage = the converted 2 byte voltage long binaryToCalibratedAnalogTemperature( ue9CalibrationInfo *caliInfo, int powerLevel, uint16 bytesTemperature, double *analogTemperature); //Translates the binary analog bytes read from the UE9, to a Kelvin temperature //value (calibrated). Call getCalibrationInfo first to set up caliInfo. //Returns -1 on error, 0 on success. //caliInfo = structure where calibrarion information is stored //powerLevel = the power level the UE9 is set at. // (0x00: Fixed high, system clock = 48 MHz // 0x01: Fixed low, system clock = 6 MHz) //bytesTemperature = the 2 byte temperature that will be converted to an analog value //analogTemperature = the converted analog temperature long binaryToUncalibratedAnalogVoltage( uint8 gainBip, uint8 resolution, uint16 bytesVoltage, double *analogVoltage); //Translates the binary analog input bytes read from the UE9, to a voltage value //(uncalibrated). Returns -1 on error, 0 on success. //gainBip = the gain option and bipolar setting. The high bit of the byte is the // bipolar setting and the lower 3 bits is the gain option. See the // Feedback function in Section 5.3.3 of the UE9 User's Guide for a table // of BipGain values that can be passed. //resolution = the resolution of the analog reading //bytesVoltage = the 2 byte voltage that will be converted to a analog value //analogVoltage = the converted analog voltage long analogToUncalibratedBinaryVoltage( double analogVoltage, uint16 *bytesVoltage); //Translates a voltage value to binary analog input bytes (uncalibrated) that //can be sent to a UE9. //analogVoltage = the analog voltage that will be converted to a 2 byte value //bytesVoltage = the converted 2 byte voltage long binaryToUncalibratedAnalogTemperature( uint16 bytesTemperature, double *analogTemperature); //Translates the binary analog bytes read from the UE9, to a Kelvin temperature //value (uncalibrated). //bytesTemperature = the 2 byte temperature that will be converted to an analog value //analogTemperature = the converted analog temperature long I2C( int fd, uint8 I2COptions, uint8 SpeedAdjust, uint8 SDAPinNum, uint8 SCLPinNum, uint8 AddressByte, uint8 NumI2CBytesToSend, uint8 NumI2CBytesToReceive, uint8 *I2CBytesCommand, uint8 *Errorcode, uint8 *AckArray, uint8 *I2CBytesResponse); //This function will perform the I2C low-level function call. Please refer to section //5.3.20 of the UE9 User's Guide for parameter documentation. Returns -1 on error, 0 //on success. //fd = socket file descriptor to a UE9 device //I2COptions = byte 6 of the command //SpeedAdjust = byte 7 of the command //SDAPinNum = byte 8 of the command //SCLPinNum = byte 9 of the command //AddressByte = byte 10 of the command //NumI2CBytesToSend = byte 12 of the command //NumI2CBytesToReceive = byte 13 of the command //*I2CBytesCommand = Array that holds bytes 14 and above of the command. Needs to be at // least NumI2CBytesToSend elements in size. //*Errorcode = returns byte 6 of the response //*AckArray = Array that returns bytes 8 - 11 of the response. Needs to be at least 4 // elements in size. //*I2CBytesResponse = Array that returns bytes 12 and above of the response. Needs to be at // least NumI2CBytesToReceive elements in size. /* Easy Functions (Similar to the easy functions in the UD driver for Windows) */ long eAIN( int fd, ue9CalibrationInfo *CalibrationInfo, long ChannelP, long ChannelN, double *Voltage, long Range, long Resolution, long Settling, long Binary, long Reserved1, long Reserved2); //An "easy" function that returns a reading from one analog input. Returns 0 for //no error, or -1 or >0 value (low-level errorcode) on error. //fd = socket file descriptor to a UE9 device. //CalibrationInfo = Structure where calibration information is stored. //ChannelP = The positive AIN channel to acquire. //ChannelN = For the UE9, this parameter is ignored. //Voltage = Returns the analog input reading, which is generally a voltage. //Range = Pass a constant specifying the voltage range. //Resolution = Pass 12-17 to specify the resolution of the analog input reading, and 18 // for a high-res reading from UE9-Pro. 0-11 coresponds to 12-bit. //Settling = Pass 0 for default settling. This parameter adds extra settling before the // ADC conversion of about Settling times 5 microseconds. //Binary = If this is nonzero (True), the Voltage parameter will return the raw binary // value. //Reserved (1&2) = Pass 0. long eDAC( int fd, ue9CalibrationInfo *CalibrationInfo, long Channel, double Voltage, long Binary, long Reserved1, long Reserved2); //An "easy" function that writes a value to one analog output. Returns 0 for //no error, or -1 or >0 value (low-level errorcode) on error. //fd = socket file descriptor to a UE9 device. //CalibrationInfo = structure where calibrarion information is stored //Channel = The analog output channel to write to. //Voltage = The voltage to write to the analog output. //Binary = If this is nonzero (True), the value passed for Voltage should be binary. //Reserved (1&2) = Pass 0. long eDI( int fd, long Channel, long *State); //An "easy" function that reads the state of one digital input. This function does //not automatically configure the specified channel as digital, unless ConfigIO is //set as True. Returns 0 for no error, or -1 or >0 value (low-level errorcode) on error. //fd = socket file descriptor to a UE9 device. //Channel = The channel to read. 0-22 corresponds to FIO0-MIO2. //State = Returns the state of the digital input. 0=False=Low and 1=True=High. long eDO( int fd, long Channel, long State); //An "easy" function that writes the state of one digital output. Returns 0 for //no error, or -1 or >0 value (low-level errorcode) on error. //fd = socket file descriptor to a UE9 device. //Channel = The channel to write to. 0-19 corresponds to FIO0-MIO2. //State = The state to write to the digital output. 0=False=Low and 1=True=High. long eTCConfig( int fd, long *aEnableTimers, long *aEnableCounters, long TCPinOffset, long TimerClockBaseIndex, long TimerClockDivisor, long *aTimerModes, double *aTimerValues, long Reserved1, long Reserved2); //An "easy" function that configures and initializes all the timers and counters. Returns //0 for no error, or -1 or >0 value (low-level errorcode) on error. //fd = socket file descriptor to a UE9 device. //aEnableTimers = An array where each element specifies whether that timer is enabled. // Timers must be enabled in order starting from 0, so for instance, // Timer1 cannot be enabled without enabling Timer 0 also. A nonzero // for an array element specifies to enable that timer. For the UE9, // this array must always have at least 6 elements. //aEnableCounters = An array where each element specifies whether that counter is enabled. // Counters do not have to be enabled in order starting from 0, so // Counter1 can be enabled when Counter0 is disabled. A nonzero value // for an array element specifies to enable that counter. For the UE9, // this array must always have at least 2 elements. //TCPinOffset = Ignored with the UE9. //TimerClockBaseIndex = Pass a constant to set the timer base clock. The default is // LJ_tc750KHZ. //TimerClockDivisor = Pass a divisor from 0-255 where 0 is a divisor of 256. //aTimerModes = An array where each element is a constant specifying the mode for that // timer. For the UE9, this array must always have at least 6 elements. //aTimerValues = An array where each element specifies the initial value for that // timer. For the UE9, this array must always have at least 6 elements. //Reserved (1&2) = Pass 0. long eTCValues( int fd, long *aReadTimers, long *aUpdateResetTimers, long *aReadCounters, long *aResetCounters, double *aTimerValues, double *aCounterValues, long Reserved1, long Reserved2); //An "easy" function that updates and reads all the timers and counters. Returns 0 for //no error, or -1 or >0 value (low-level errorcode) on error. //fd = socket file descriptor to a UE9 device. //aReadTimers = An array where each element specifies whether to read that timer. A // nonzero value for an array element specifies to read that timer. For // the UE9, this array must always have at least 6 elements. //aUpdateResetTimers = An array where each element specifies whether to update/reset // that timers. A nonzero value for an array element specifies to // update/reset that timer. For the UE9, this array must always // have at least 6 elements. //aReadCounters = An array where each element specifies whether to read that counter. // A nonzero value for an array element specifies to read that counter. // For the UE9, this array must always have at least 2 elements. //aResetCounters = An array where each element specifies whether to reset that counter. // A nonzero value for an array element specifies to reset that counter. // For the UE9, this array must always have at least 2 elements. //aTimerValues = Input: An array where each element is the new value for that timer. Each // value is only updated if the appropriate element is set in the // aUpdateResetTimers array. // Output: An array where each element is the value read from that timer if // the appropriate element is set in the aReadTimers array. If the timer // mode set for the timer is Quadrature Input, the value needs to be converted // from an unsigned 32-bit integer to a signed 32-bit integer (2’s complement). // For the UE9, this array must always have at least 6 elements. //aCounterValues = An array where each element is the value read from that counter if the // appropriate element is set in the aReadTimers array. For the UE9, this // array must always have at least 2 elements. //Reserved (1&2) = Pass 0. /* Easy Function Helpers */ long ehSingleIO( int fd, uint8 inIOType, uint8 inChannel, uint8 inDirBipGainDACL, uint8 inStateResDACH, uint8 inSettlingTime, uint8 *outIOType, uint8 *outChannel, uint8 *outDirAINL, uint8 *outStateAINM, uint8 *outAINH); //Used by the eAIN and eDAC easy functions. This function takes the SingleIO low-level command //and response bytes (not including checksum and command bytes) as its parameter and performs a //SingleIO call with the UE9. Returns -1 on error, 0 on success. long ehDIO_Feedback( int fd, uint8 channel, uint8 direction, uint8 *state); //Used by the eDI and eDO easy funtions. This function takes the same parameters as eDI and //eDO (as bytes), with the additional parameter of channel, and will perform the Feedback //low-level function call. Returns -1 on error, 0 on success. long ehTimerCounter( int fd, uint8 inTimerClockDivisor, uint8 inEnableMask, uint8 inTimerClockBase, uint8 inUpdateReset, uint8 *inTimerMode, uint16 *inTimerValue, uint8 *inCounterMode, uint32 *outTimer, uint32 *outCounter); //Used by the eTCConfig and eTCValues easy functions. This function takes the TimerCounter //low-level command and response bytes (not including checksum and command bytes) as its parameter //and performs a TimerCounter call with the UE9. Returns -1 or errorcode (>1 value) on error, 0 //on success. /* Easy Functions Constants */ /* Ranges */ // -5V to +5V #define LJ_rgBIP5V 3 // 0V to +5V #define LJ_rgUNI5V 103 // 0V to +2.5V #define LJ_rgUNI2P5V 105 // 0V to +1.25Vz #define LJ_rgUNI1P25V 107 // 0V to +0.625V #define LJ_rgUNIP625V 109 /* timer clocks: */ // 750 khz #define LJ_tc750KHZ 0 // system clock #define LJ_tcSYS 1 /* timer modes */ // 16 bit PWM #define LJ_tmPWM16 0 // 8 bit PWM #define LJ_tmPWM8 1 // 32-bit rising to rising edge measurement #define LJ_tmRISINGEDGES32 2 // 32-bit falling to falling edge measurement #define LJ_tmFALLINGEDGES32 3 // duty cycle measurement #define LJ_tmDUTYCYCLE 4 // firmware based rising edge counter #define LJ_tmFIRMCOUNTER 5 // firmware counter with debounce #define LJ_tmFIRMCOUNTERDEBOUNCE 6 // frequency output #define LJ_tmFREQOUT 7 // Quadrature #define LJ_tmQUAD 8 // stops another timer after n pulses #define LJ_tmTIMERSTOP 9 // read lower 32-bits of system timer #define LJ_tmSYSTIMERLOW 10 // read upper 32-bits of system timer #define LJ_tmSYSTIMERHIGH 11 // 16-bit rising to rising edge measurement #define LJ_tmRISINGEDGES16 12 // 16-bit falling to falling edge measurement #define LJ_tmFALLINGEDGES16 13 #endif
tinyos-io/tinyos-3.x-contrib
nxtmote/misc/src/libusb-win32/libusb-win32-src-0.1.12.1/src/windows.c
/* LIBUSB-WIN32, Generic Windows USB Library * Copyright (c) 2002-2005 <NAME> <<EMAIL>> * Copyright (c) 2000-2005 <NAME> <<EMAIL>> * * 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 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. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stdlib.h> #include <string.h> #include <stdio.h> #include <errno.h> #include <ctype.h> #include <windows.h> #include <winioctl.h> #include <setupapi.h> #include "usb.h" #include "error.h" #include "usbi.h" #include "driver_api.h" #include "registry.h" #define LIBUSB_DEFAULT_TIMEOUT 5000 #define LIBUSB_DEVICE_NAME "\\\\.\\libusb0-" #define LIBUSB_BUS_NAME "bus-0" #define LIBUSB_MAX_DEVICES 256 extern int __usb_debug; typedef struct { usb_dev_handle *dev; libusb_request req; char *bytes; int size; DWORD control_code; OVERLAPPED ol; } usb_context_t; static struct usb_version _usb_version = { { VERSION_MAJOR, VERSION_MINOR, VERSION_MICRO, VERSION_NANO }, { -1, -1, -1, -1 } }; static int _usb_setup_async(usb_dev_handle *dev, void **context, DWORD control_code, unsigned char ep, int pktsize); static int _usb_transfer_sync(usb_dev_handle *dev, int control_code, int ep, int pktsize, char *bytes, int size, int timeout); /* static int usb_get_configuration(usb_dev_handle *dev); */ static int _usb_cancel_io(usb_context_t *context); static int _usb_abort_ep(usb_dev_handle *dev, unsigned int ep); static int _usb_io_sync(HANDLE dev, unsigned int code, void *in, int in_size, void *out, int out_size, int *ret); static int _usb_reap_async(void *context, int timeout, int cancel); static int _usb_add_virtual_hub(struct usb_bus *bus); static void _usb_free_bus_list(struct usb_bus *bus); static void _usb_free_dev_list(struct usb_device *dev); static void _usb_deinit(void); /* DLL main entry point */ BOOL WINAPI DllMain(HANDLE module, DWORD reason, LPVOID reserved) { switch(reason) { case DLL_PROCESS_ATTACH: break; case DLL_PROCESS_DETACH: _usb_deinit(); break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; default: break; } return TRUE; } /* static int usb_get_configuration(usb_dev_handle *dev) */ /* { */ /* int ret; */ /* char config; */ /* ret = usb_control_msg(dev, USB_RECIP_DEVICE | USB_ENDPOINT_IN, */ /* USB_REQ_GET_CONFIGURATION, 0, 0, &config, 1, */ /* LIBUSB_DEFAULT_TIMEOUT); */ /* if(ret >= 0) */ /* { */ /* return config; */ /* } */ /* return ret; */ /* } */ int usb_os_open(usb_dev_handle *dev) { char dev_name[LIBUSB_PATH_MAX]; char *p; /* int config; */ if(!dev) { usb_error("usb_os_open: invalid device handle %p", dev); return -EINVAL; } dev->impl_info = INVALID_HANDLE_VALUE; dev->config = 0; dev->interface = -1; dev->altsetting = -1; if(!dev->device->filename) { usb_error("usb_os_open: invalid file name"); return -ENOENT; } /* build the Windows file name from the unique device name */ strcpy(dev_name, dev->device->filename); p = strstr(dev_name, "--"); if(!p) { usb_error("usb_os_open: invalid file name %s", dev->device->filename); return -ENOENT; } *p = 0; dev->impl_info = CreateFile(dev_name, 0, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if(dev->impl_info == INVALID_HANDLE_VALUE) { usb_error("usb_os_open: failed to open %s: win error: %s", dev->device->filename, usb_win_error_to_string()); return -ENOENT; } /* now, retrieve the device's current configuration, except from hubs */ /* if(dev->device->config && dev->device->config->interface */ /* && dev->device->config->interface[0].altsetting */ /* && dev->device->config->interface[0].altsetting[0].bInterfaceClass */ /* != USB_CLASS_HUB) */ /* { */ /* config = usb_get_configuration(dev); */ /* if(config > 0) */ /* { */ /* dev->config = config; */ /* } */ /* } */ return 0; } int usb_os_close(usb_dev_handle *dev) { if(dev->impl_info != INVALID_HANDLE_VALUE) { if(dev->interface >= 0) { usb_release_interface(dev, dev->interface); } CloseHandle(dev->impl_info); dev->impl_info = INVALID_HANDLE_VALUE; dev->interface = -1; dev->altsetting = -1; } return 0; } int usb_set_configuration(usb_dev_handle *dev, int configuration) { libusb_request req; if(dev->impl_info == INVALID_HANDLE_VALUE) { usb_error("usb_set_configuration: error: device not open"); return -EINVAL; } if(dev->config == configuration) { return 0; } if(dev->interface >= 0) { usb_error("usb_set_configuration: can't change configuration, " "an interface is still in use (claimed)"); return -EINVAL; } req.configuration.configuration = configuration; req.timeout = LIBUSB_DEFAULT_TIMEOUT; if(!_usb_io_sync(dev->impl_info, LIBUSB_IOCTL_SET_CONFIGURATION, &req, sizeof(libusb_request), NULL, 0, NULL)) { usb_error("usb_set_configuration: could not set config %d: " "win error: %s", configuration, usb_win_error_to_string()); return -usb_win_error_to_errno(); } dev->config = configuration; dev->interface = -1; dev->altsetting = -1; return 0; } int usb_claim_interface(usb_dev_handle *dev, int interface) { libusb_request req; if(dev->impl_info == INVALID_HANDLE_VALUE) { usb_error("usb_claim_interface: device not open"); return -EINVAL; } if(!dev->config) { usb_error("usb_claim_interface: could not claim interface %d, invalid " "configuration %d", interface, dev->config); return -EINVAL; } if(dev->interface == interface) { return 0; } req.interface.interface = interface; if(!_usb_io_sync(dev->impl_info, LIBUSB_IOCTL_CLAIM_INTERFACE, &req, sizeof(libusb_request), NULL, 0, NULL)) { usb_error("usb_claim_interface: could not claim interface %d, " "win error: %s", interface, usb_win_error_to_string()); return -usb_win_error_to_errno(); } else { dev->interface = interface; dev->altsetting = 0; return 0; } } int usb_release_interface(usb_dev_handle *dev, int interface) { libusb_request req; if(dev->impl_info == INVALID_HANDLE_VALUE) { usb_error("usb_release_interface: device not open"); return -EINVAL; } if(!dev->config) { usb_error("usb_release_interface: could not release interface %d, " "invalid configuration %d", interface, dev->config); return -EINVAL; } req.interface.interface = interface; if(!_usb_io_sync(dev->impl_info, LIBUSB_IOCTL_RELEASE_INTERFACE, &req, sizeof(libusb_request), NULL, 0, NULL)) { usb_error("usb_release_interface: could not release interface %d, " "win error: %s", interface, usb_win_error_to_string()); return -usb_win_error_to_errno(); } else { dev->interface = -1; dev->altsetting = -1; return 0; } } int usb_set_altinterface(usb_dev_handle *dev, int alternate) { libusb_request req; if(dev->impl_info == INVALID_HANDLE_VALUE) { usb_error("usb_set_altinterface: device not open"); return -EINVAL; } if(dev->config <= 0) { usb_error("usb_set_altinterface: could not set alt interface %d: " "invalid configuration %d", alternate, dev->config); return -EINVAL; } if(dev->interface < 0) { usb_error("usb_set_altinterface: could not set alt interface %d: " "no interface claimed", alternate); return -EINVAL; } req.interface.interface = dev->interface; req.interface.altsetting = alternate; req.timeout = LIBUSB_DEFAULT_TIMEOUT; if(!_usb_io_sync(dev->impl_info, LIBUSB_IOCTL_SET_INTERFACE, &req, sizeof(libusb_request), NULL, 0, NULL)) { usb_error("usb_set_altinterface: could not set alt interface " "%d/%d: win error: %s", dev->interface, alternate, usb_win_error_to_string()); return -usb_win_error_to_errno(); } dev->altsetting = alternate; return 0; } static int _usb_setup_async(usb_dev_handle *dev, void **context, DWORD control_code, unsigned char ep, int pktsize) { usb_context_t **c = (usb_context_t **)context; if(((control_code == LIBUSB_IOCTL_INTERRUPT_OR_BULK_WRITE) || (control_code == LIBUSB_IOCTL_ISOCHRONOUS_WRITE)) && (ep & USB_ENDPOINT_IN)) { usb_error("_usb_setup_async: invalid endpoint 0x%02x", ep); return -EINVAL; } if(((control_code == LIBUSB_IOCTL_INTERRUPT_OR_BULK_READ) || (control_code == LIBUSB_IOCTL_ISOCHRONOUS_READ)) && !(ep & USB_ENDPOINT_IN)) { usb_error("_usb_setup_async: invalid endpoint 0x%02x", ep); return -EINVAL; } *c = malloc(sizeof(usb_context_t)); if(!*c) { usb_error("_usb_setup_async: memory allocation error"); return -ENOMEM; } memset(*c, 0, sizeof(usb_context_t)); (*c)->dev = dev; (*c)->req.endpoint.endpoint = ep; (*c)->req.endpoint.packet_size = pktsize; (*c)->control_code = control_code; (*c)->ol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if(!(*c)->ol.hEvent) { free(*c); *c = NULL; usb_error("_usb_setup_async: creating event failed: win error: %s", usb_win_error_to_string()); return -usb_win_error_to_errno(); } return 0; } int usb_submit_async(void *context, char *bytes, int size) { usb_context_t *c = (usb_context_t *)context; if(!c) { usb_error("usb_submit_async: invalid context"); return -EINVAL; } if(c->dev->impl_info == INVALID_HANDLE_VALUE) { usb_error("usb_submit_async: device not open"); return -EINVAL; } if(c->dev->config <= 0) { usb_error("usb_submit_async: invalid configuration %d", c->dev->config); return -EINVAL; } if(c->dev->interface < 0) { usb_error("usb_submit_async: invalid interface %d", c->dev->interface); return -EINVAL; } c->ol.Offset = 0; c->ol.OffsetHigh = 0; c->bytes = bytes; c->size = size; ResetEvent(c->ol.hEvent); if(!DeviceIoControl(c->dev->impl_info, c->control_code, &c->req, sizeof(libusb_request), c->bytes, c->size, NULL, &c->ol)) { if(GetLastError() != ERROR_IO_PENDING) { usb_error("usb_submit_async: submitting request failed, " "win error: %s", usb_win_error_to_string()); return -usb_win_error_to_errno(); } } return 0; } static int _usb_reap_async(void *context, int timeout, int cancel) { usb_context_t *c = (usb_context_t *)context; ULONG ret = 0; if(!c) { usb_error("usb_reap: invalid context"); return -EINVAL; } if(WaitForSingleObject(c->ol.hEvent, timeout) == WAIT_TIMEOUT) { /* request timed out */ if(cancel) { _usb_cancel_io(c); } usb_error("usb_reap: timeout error"); return -ETIMEDOUT; } if(!GetOverlappedResult(c->dev->impl_info, &c->ol, &ret, TRUE)) { usb_error("usb_reap: reaping request failed, win error: %s", usb_win_error_to_string()); return -usb_win_error_to_errno(); } return ret; } int usb_reap_async(void *context, int timeout) { return _usb_reap_async(context, timeout, TRUE); } int usb_reap_async_nocancel(void *context, int timeout) { return _usb_reap_async(context, timeout, FALSE); } int usb_cancel_async(void *context) { /* NOTE that this function will cancel all pending URBs */ /* on the same endpoint as this particular context, or even */ /* all pending URBs for this particular device. */ usb_context_t *c = (usb_context_t *)context; if(!c) { usb_error("usb_cancel_async: invalid context"); return -EINVAL; } if(c->dev->impl_info == INVALID_HANDLE_VALUE) { usb_error("usb_cancel_async: device not open"); return -EINVAL; } _usb_cancel_io(c); return 0; } int usb_free_async(void **context) { usb_context_t **c = (usb_context_t **)context; if(!*c) { usb_error("usb_free_async: invalid context"); return -EINVAL; } CloseHandle((*c)->ol.hEvent); free(*c); *c = NULL; return 0; } static int _usb_transfer_sync(usb_dev_handle *dev, int control_code, int ep, int pktsize, char *bytes, int size, int timeout) { void *context = NULL; int transmitted = 0; int ret; int requested; ret = _usb_setup_async(dev, &context, control_code, (unsigned char )ep, pktsize); if(ret < 0) { return ret; } do { requested = size > LIBUSB_MAX_READ_WRITE ? LIBUSB_MAX_READ_WRITE : size; ret = usb_submit_async(context, bytes, requested); if(ret < 0) { transmitted = ret; break; } ret = usb_reap_async(context, timeout); if(ret < 0) { transmitted = ret; break; } transmitted += ret; bytes += ret; size -= ret; } while(size > 0 && ret == requested); usb_free_async(&context); return transmitted; } int usb_bulk_write(usb_dev_handle *dev, int ep, char *bytes, int size, int timeout) { return _usb_transfer_sync(dev, LIBUSB_IOCTL_INTERRUPT_OR_BULK_WRITE, ep, 0, bytes, size, timeout); } int usb_bulk_read(usb_dev_handle *dev, int ep, char *bytes, int size, int timeout) { return _usb_transfer_sync(dev, LIBUSB_IOCTL_INTERRUPT_OR_BULK_READ, ep, 0, bytes, size, timeout); } int usb_interrupt_write(usb_dev_handle *dev, int ep, char *bytes, int size, int timeout) { return _usb_transfer_sync(dev, LIBUSB_IOCTL_INTERRUPT_OR_BULK_WRITE, ep, 0, bytes, size, timeout); } int usb_interrupt_read(usb_dev_handle *dev, int ep, char *bytes, int size, int timeout) { return _usb_transfer_sync(dev, LIBUSB_IOCTL_INTERRUPT_OR_BULK_READ, ep, 0, bytes, size, timeout); } int usb_isochronous_setup_async(usb_dev_handle *dev, void **context, unsigned char ep, int pktsize) { if(ep & 0x80) return _usb_setup_async(dev, context, LIBUSB_IOCTL_ISOCHRONOUS_READ, ep, pktsize); else return _usb_setup_async(dev, context, LIBUSB_IOCTL_ISOCHRONOUS_WRITE, ep, pktsize); } int usb_bulk_setup_async(usb_dev_handle *dev, void **context, unsigned char ep) { if(ep & 0x80) return _usb_setup_async(dev, context, LIBUSB_IOCTL_INTERRUPT_OR_BULK_READ, ep, 0); else return _usb_setup_async(dev, context, LIBUSB_IOCTL_INTERRUPT_OR_BULK_WRITE, ep, 0); } int usb_interrupt_setup_async(usb_dev_handle *dev, void **context, unsigned char ep) { if(ep & 0x80) return _usb_setup_async(dev, context, LIBUSB_IOCTL_INTERRUPT_OR_BULK_READ, ep, 0); else return _usb_setup_async(dev, context, LIBUSB_IOCTL_INTERRUPT_OR_BULK_WRITE, ep, 0); } int usb_control_msg(usb_dev_handle *dev, int requesttype, int request, int value, int index, char *bytes, int size, int timeout) { int read = 0; libusb_request req; void *out = &req; int out_size = sizeof(libusb_request); void *in = bytes; int in_size = size; int code; if(dev->impl_info == INVALID_HANDLE_VALUE) { usb_error("usb_control_msg: device not open"); return -EINVAL; } req.timeout = timeout; /* windows doesn't support generic control messages, so it needs to be */ /* split up */ switch(requesttype & (0x03 << 5)) { case USB_TYPE_STANDARD: switch(request) { case USB_REQ_GET_STATUS: req.status.recipient = requesttype & 0x1F; req.status.index = index; code = LIBUSB_IOCTL_GET_STATUS; break; case USB_REQ_CLEAR_FEATURE: req.feature.recipient = requesttype & 0x1F; req.feature.feature = value; req.feature.index = index; code = LIBUSB_IOCTL_CLEAR_FEATURE; break; case USB_REQ_SET_FEATURE: req.feature.recipient = requesttype & 0x1F; req.feature.feature = value; req.feature.index = index; code = LIBUSB_IOCTL_SET_FEATURE; break; case USB_REQ_GET_DESCRIPTOR: req.descriptor.recipient = requesttype & 0x1F; req.descriptor.type = (value >> 8) & 0xFF; req.descriptor.index = value & 0xFF; req.descriptor.language_id = index; code = LIBUSB_IOCTL_GET_DESCRIPTOR; break; case USB_REQ_SET_DESCRIPTOR: req.descriptor.recipient = requesttype & 0x1F; req.descriptor.type = (value >> 8) & 0xFF; req.descriptor.index = value & 0xFF; req.descriptor.language_id = index; code = LIBUSB_IOCTL_SET_DESCRIPTOR; break; case USB_REQ_GET_CONFIGURATION: code = LIBUSB_IOCTL_GET_CONFIGURATION; break; case USB_REQ_SET_CONFIGURATION: req.configuration.configuration = value; code = LIBUSB_IOCTL_SET_CONFIGURATION; break; case USB_REQ_GET_INTERFACE: req.interface.interface = index; code = LIBUSB_IOCTL_GET_INTERFACE; break; case USB_REQ_SET_INTERFACE: req.interface.interface = index; req.interface.altsetting = value; code = LIBUSB_IOCTL_SET_INTERFACE; break; default: usb_error("usb_control_msg: invalid request 0x%x", request); return -EINVAL; } break; case USB_TYPE_VENDOR: case USB_TYPE_CLASS: req.vendor.type = (requesttype >> 5) & 0x03; req.vendor.recipient = requesttype & 0x1F; req.vendor.request = request; req.vendor.value = value; req.vendor.index = index; if(requesttype & 0x80) code = LIBUSB_IOCTL_VENDOR_READ; else code = LIBUSB_IOCTL_VENDOR_WRITE; break; case USB_TYPE_RESERVED: default: usb_error("usb_control_msg: invalid or unsupported request type: %x", requesttype); return -EINVAL; } /* out request? */ if(!(requesttype & USB_ENDPOINT_IN)) { if(!(out = malloc(sizeof(libusb_request) + size))) { usb_error("usb_control_msg: memory allocation failed"); return -ENOMEM; } memcpy(out, &req, sizeof(libusb_request)); memcpy((char *)out + sizeof(libusb_request), bytes, size); out_size = sizeof(libusb_request) + size; in = NULL; in_size = 0; } if(!_usb_io_sync(dev->impl_info, code, out, out_size, in, in_size, &read)) { usb_error("usb_control_msg: sending control message failed, " "win error: %s", usb_win_error_to_string()); if(!(requesttype & USB_ENDPOINT_IN)) { free(out); } return -usb_win_error_to_errno(); } /* out request? */ if(!(requesttype & USB_ENDPOINT_IN)) { free(out); return size; } else return read; } int usb_os_find_busses(struct usb_bus **busses) { struct usb_bus *bus = NULL; /* create one 'virtual' bus */ bus = malloc(sizeof(struct usb_bus)); if(!bus) { usb_error("usb_os_find_busses: memory allocation failed"); return -ENOMEM; } memset(bus, 0, sizeof(*bus)); strcpy(bus->dirname, LIBUSB_BUS_NAME); usb_message("usb_os_find_busses: found %s", bus->dirname); *busses = bus; return 0; } int usb_os_find_devices(struct usb_bus *bus, struct usb_device **devices) { int i; struct usb_device *dev, *fdev = NULL; char dev_name[LIBUSB_PATH_MAX]; int ret; HANDLE handle; libusb_request req; for(i = 1; i < LIBUSB_MAX_DEVICES; i++) { ret = 0; _snprintf(dev_name, sizeof(dev_name) - 1,"%s%04d", LIBUSB_DEVICE_NAME, i); if(!(dev = malloc(sizeof(*dev)))) { usb_error("usb_os_find_devices: memory allocation failed"); return -ENOMEM; } memset(dev, 0, sizeof(*dev)); dev->bus = bus; dev->devnum = (unsigned char)i; handle = CreateFile(dev_name, 0, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if(handle == INVALID_HANDLE_VALUE) { free(dev); continue; } /* retrieve device descriptor */ req.descriptor.type = USB_DT_DEVICE; req.descriptor.recipient = USB_RECIP_DEVICE; req.descriptor.index = 0; req.descriptor.language_id = 0; req.timeout = LIBUSB_DEFAULT_TIMEOUT; _usb_io_sync(handle, LIBUSB_IOCTL_GET_DESCRIPTOR, &req, sizeof(libusb_request), &dev->descriptor, USB_DT_DEVICE_SIZE, &ret); if(ret < USB_DT_DEVICE_SIZE) { usb_error("usb_os_find_devices: couldn't read device descriptor"); free(dev); CloseHandle(handle); continue; } _snprintf(dev->filename, LIBUSB_PATH_MAX - 1, "%s--0x%04x-0x%04x", dev_name, dev->descriptor.idVendor, dev->descriptor.idProduct); CloseHandle(handle); LIST_ADD(fdev, dev); usb_message("usb_os_find_devices: found %s on %s", dev->filename, bus->dirname); } *devices = fdev; return 0; } void usb_os_init(void) { HANDLE dev; libusb_request req; int i; int ret; char dev_name[LIBUSB_PATH_MAX]; usb_message("usb_os_init: dll version: %d.%d.%d.%d", VERSION_MAJOR, VERSION_MINOR, VERSION_MICRO, VERSION_NANO); for(i = 1; i < LIBUSB_MAX_DEVICES; i++) { /* build the Windows file name */ _snprintf(dev_name, sizeof(dev_name) - 1,"%s%04d", LIBUSB_DEVICE_NAME, i); dev = CreateFile(dev_name, 0, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if(dev == INVALID_HANDLE_VALUE) { continue; } if(!_usb_io_sync(dev, LIBUSB_IOCTL_GET_VERSION, &req, sizeof(libusb_request), &req, sizeof(libusb_request), &ret) || (ret < sizeof(libusb_request))) { usb_error("usb_os_init: getting driver version failed"); CloseHandle(dev); continue; } else { _usb_version.driver.major = req.version.major; _usb_version.driver.minor = req.version.minor; _usb_version.driver.micro = req.version.micro; _usb_version.driver.nano = req.version.nano; usb_message("usb_os_init: driver version: %d.%d.%d.%d", req.version.major, req.version.minor, req.version.micro, req.version.nano); /* set debug level */ req.timeout = 0; req.debug.level = __usb_debug; if(!_usb_io_sync(dev, LIBUSB_IOCTL_SET_DEBUG_LEVEL, &req, sizeof(libusb_request), NULL, 0, NULL)) { usb_error("usb_os_init: setting debug level failed"); } CloseHandle(dev); break; } } } int usb_resetep(usb_dev_handle *dev, unsigned int ep) { libusb_request req; if(dev->impl_info == INVALID_HANDLE_VALUE) { usb_error("usb_resetep: device not open"); return -EINVAL; } req.endpoint.endpoint = (int)ep; req.timeout = LIBUSB_DEFAULT_TIMEOUT; if(!_usb_io_sync(dev->impl_info, LIBUSB_IOCTL_ABORT_ENDPOINT, &req, sizeof(libusb_request), NULL, 0, NULL)) { usb_error("usb_resetep: could not abort ep 0x%02x, win error: %s", ep, usb_win_error_to_string()); return -usb_win_error_to_errno(); } if(!_usb_io_sync(dev->impl_info, LIBUSB_IOCTL_RESET_ENDPOINT, &req, sizeof(libusb_request), NULL, 0, NULL)) { usb_error("usb_resetep: could not reset ep 0x%02x, win error: %s", ep, usb_win_error_to_string()); return -usb_win_error_to_errno(); } return 0; } int usb_clear_halt(usb_dev_handle *dev, unsigned int ep) { libusb_request req; if(dev->impl_info == INVALID_HANDLE_VALUE) { usb_error("usb_clear_halt: device not open"); return -EINVAL; } req.endpoint.endpoint = (int)ep; req.timeout = LIBUSB_DEFAULT_TIMEOUT; if(!_usb_io_sync(dev->impl_info, LIBUSB_IOCTL_RESET_ENDPOINT, &req, sizeof(libusb_request), NULL, 0, NULL)) { usb_error("usb_clear_halt: could not clear halt, ep 0x%02x, " "win error: %s", ep, usb_win_error_to_string()); return -usb_win_error_to_errno(); } return 0; } int usb_reset(usb_dev_handle *dev) { libusb_request req; if(dev->impl_info == INVALID_HANDLE_VALUE) { usb_error("usb_reset: device not open"); return -EINVAL; } req.timeout = LIBUSB_DEFAULT_TIMEOUT; if(!_usb_io_sync(dev->impl_info, LIBUSB_IOCTL_RESET_DEVICE, &req, sizeof(libusb_request), NULL, 0, NULL)) { usb_error("usb_reset: could not reset device, win error: %s", usb_win_error_to_string()); return -usb_win_error_to_errno(); } return 0; } const struct usb_version *usb_get_version(void) { return &_usb_version; } void usb_set_debug(int level) { HANDLE dev; libusb_request req; int i; char dev_name[LIBUSB_PATH_MAX]; if(__usb_debug || level) { usb_message("usb_set_debug: setting debugging level to %d (%s)\n", level, level ? "on" : "off"); } __usb_debug = level; /* find a valid device */ for(i = 1; i < LIBUSB_MAX_DEVICES; i++) { /* build the Windows file name */ _snprintf(dev_name, sizeof(dev_name) - 1,"%s%04d", LIBUSB_DEVICE_NAME, i); dev = CreateFile(dev_name, 0, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if(dev == INVALID_HANDLE_VALUE) { continue; } /* set debug level */ req.timeout = 0; req.debug.level = __usb_debug; if(!_usb_io_sync(dev, LIBUSB_IOCTL_SET_DEBUG_LEVEL, &req, sizeof(libusb_request), NULL, 0, NULL)) { usb_error("usb_os_init: setting debug level failed"); } CloseHandle(dev); break; } } int usb_os_determine_children(struct usb_bus *bus) { struct usb_device *dev; int i = 0; /* add a virtual hub to the bus to emulate this feature */ if(_usb_add_virtual_hub(bus)) { if(bus->root_dev->children) { free(bus->root_dev->children); } bus->root_dev->num_children = 0; for(dev = bus->devices; dev; dev = dev->next) bus->root_dev->num_children++; bus->root_dev->children = malloc(sizeof(struct usb_device *) * bus->root_dev->num_children); for(dev = bus->devices; dev; dev = dev->next) bus->root_dev->children[i++] = dev; } return 0; } static int _usb_cancel_io(usb_context_t *context) { int ret; ret = _usb_abort_ep(context->dev, context->req.endpoint.endpoint); WaitForSingleObject(context->ol.hEvent, 0); return ret; } static int _usb_abort_ep(usb_dev_handle *dev, unsigned int ep) { libusb_request req; if(dev->impl_info == INVALID_HANDLE_VALUE) { usb_error("_usb_abort_ep: device not open"); return -EINVAL; } req.endpoint.endpoint = (int)ep; req.timeout = LIBUSB_DEFAULT_TIMEOUT; if(!_usb_io_sync(dev->impl_info, LIBUSB_IOCTL_ABORT_ENDPOINT, &req, sizeof(libusb_request), NULL, 0, NULL)) { usb_error("_usb_abort_ep: could not abort ep 0x%02x, win error: %s", ep, usb_win_error_to_string()); return -usb_win_error_to_errno(); } return 0; } static int _usb_io_sync(HANDLE dev, unsigned int code, void *out, int out_size, void *in, int in_size, int *ret) { OVERLAPPED ol; DWORD _ret; memset(&ol, 0, sizeof(ol)); if(ret) *ret = 0; ol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if(!ol.hEvent) return FALSE; if(!DeviceIoControl(dev, code, out, out_size, in, in_size, NULL, &ol)) { if(GetLastError() != ERROR_IO_PENDING) { CloseHandle(ol.hEvent); return FALSE; } } if(GetOverlappedResult(dev, &ol, &_ret, TRUE)) { if(ret) *ret = (int)_ret; CloseHandle(ol.hEvent); return TRUE; } CloseHandle(ol.hEvent); return FALSE; } static int _usb_add_virtual_hub(struct usb_bus *bus) { struct usb_device *dev; if(!bus->root_dev) { if(!(dev = malloc(sizeof(*dev)))) return FALSE; memset(dev, 0, sizeof(*dev)); strcpy(dev->filename, "virtual-hub"); dev->bus = bus; dev->descriptor.bLength = USB_DT_DEVICE_SIZE; dev->descriptor.bDescriptorType = USB_DT_DEVICE; dev->descriptor.bcdUSB = 0x0200; dev->descriptor.bDeviceClass = USB_CLASS_HUB; dev->descriptor.bDeviceSubClass = 0; dev->descriptor.bDeviceProtocol = 0; dev->descriptor.bMaxPacketSize0 = 64; dev->descriptor.idVendor = 0; dev->descriptor.idProduct = 0; dev->descriptor.bcdDevice = 0x100; dev->descriptor.iManufacturer = 0; dev->descriptor.iProduct = 0; dev->descriptor.iSerialNumber = 0; dev->descriptor.bNumConfigurations = 0; bus->root_dev = dev; } return TRUE; } static void _usb_free_bus_list(struct usb_bus *bus) { if(bus) { _usb_free_bus_list(bus->next); if(bus->root_dev) usb_free_dev(bus->root_dev); _usb_free_dev_list(bus->devices); usb_free_bus(bus); } } static void _usb_free_dev_list(struct usb_device *dev) { if(dev) { _usb_free_dev_list(dev->next); usb_free_dev(dev); } } static void _usb_deinit(void) { _usb_free_bus_list(usb_get_busses()); }
tinyos-io/tinyos-3.x-contrib
eon/eon/src/runtime/linuxsim/rt_main.c
<gh_stars>1-10 #include "../mImpl.h" #include <sys/types.h> #include <unistd.h> #include <signal.h> extern uint8_t minPathState[NUMPATHS]; //int curstate = STATE_BASE; //float curgrade = 0.0; int main(int argc, char **argv) { int fd; int err; init(argc,argv); printf("starting sources...\n"); err = start_sources(fd); while(TRUE) { sim_sleep(10); } return 0; }
tinyos-io/tinyos-3.x-contrib
eon/eon/src/runtime/stargate/rt_main.c
#include "../mImpl.h" #include "rt_intercomm.h" #include "sfaccess/telossource.h" #include <sys/types.h> #include <unistd.h> #include <signal.h> extern const uint8_t minPathState[NUMPATHS]; int curstate = STATE_BASE; float curgrade = 0.0; //#define LOCALDBG enum { AM_STATUS_MSG = 0xd1, AM_SLEEP_MSG = 0xd3, }; #define STATUSMSGSIZE 3 int asfpid = 0; int startasf() { int err; printf("startasf...\n"); pid_t pID = fork(); printf("forked(%i)\n",pID); if (pID == 0) { //child process #ifdef LOCALDBG err = execlp("./sf","sf","9000","/dev/ttyUSB0","115200","telos",(char*) 0); #else err = execlp("/root/asf","asf","9000","/dev/tts/1","19200","mica2dot",(char*) 0); #endif if (err) { printf("execlp failed!\n"); exit(1); } printf("Hrmmm....should not have reached this point.\n"); } else if (pID < 0) { printf("fork failed\n"); return pID; } else { return pID; } return pID; } int stopasf() { int err; err = kill(asfpid, SIGTERM); if (err) { printf("error: could not send SIGTERM to proc %i\n",asfpid); } err = waitpid(asfpid, NULL, 0); printf("asf stopped...\n"); if (err <= 0) { return err; } return 0; } int closedown() { int err; err = stopasf(); if (err) { printf("stopasf failed (err=%i)\n",err); return err; } err = intercomm_stop(); if (err) { printf("intercomm_stop failed (err=%i)\n",err); return err; } printf("closedown done\n"); //usleep(100000); return err; } int firststartup(const char* host, short port) { int err=0; asfpid = startasf(); if (asfpid <= 0) { printf("Error starting asf (err=%i)\n",err); return asfpid; } printf("asf started (err=%i)\n",err); usleep(500000); return err; } int startup(const char* host, short port) { int err=0; asfpid = startasf(); if (asfpid <= 0) { printf("Error starting asf (err=%i)\n",err); return asfpid; } printf("asf started (err=%i)\n",err); usleep(300000); err = intercomm_start(port); if (err) { printf("Error in startup (err=%i)\n",err); return err; } printf("Startup succeeded...\n"); return err; } int sendStatusPacket(int fd, bool sleepy, uint16_t load) { telospacket packet; uint8_t data[STATUSMSGSIZE]; int err; packet.length = STATUSMSGSIZE; packet.addr = TOS_BCAST_ADDR; packet.type = AM_STATUS_MSG; packet.data = data; data[0] = sleepy; hton_uint16(data+1, load); err = write_telos_packet(fd, &packet); if (err) { printf("AAAH! Could not send status packet.\n"); return -1; } return 0; } int sendSleepPacket(int fd) { telospacket packet; uint8_t data[1]; int err; packet.length = 1; packet.addr = TOS_BCAST_ADDR; packet.type = AM_SLEEP_MSG; packet.data = data; data[0] = 1; err = write_telos_packet(fd, &packet); if (err) { printf("AAAH! Could not send sleep packet.\n"); return -1; } return 0; } /*int main(int argc, char **argv) { int fd; int err; int sleepy = FALSE; telospacket *packet; init(argc,argv); printf("Starting\n"); sleep(1); #ifndef LOCALDBG system("modprobe usbserial"); system("modprobe ftdi_sio"); sleep(1); firststartup("localhost",9000); sleep(1); fd = open_telos_source("localhost", 9000); if (fd <= 0) { printf("o_t_s failed! (fd=%i)\n",fd); return 1; } sendStatusPacket(fd, 1, 0); sleep(1); //usleep(100000); //sendStatusPacket(fd, 1, 0); //usleep(100000); close(fd); usleep(500000); //sleep(1); printf("...going to sleep.\n"); err = stopasf(); if (err) { printf("stopasf failed (err=%i)\n",err); return err; } usleep(10000); system("modprobe -r ftdi_sio"); system("modprobe -r usbserial"); system("/sbin/sys_suspend"); #endif while(TRUE) { //wait for device to wake #ifndef LOCALDBG //sleep(2); system("modprobe usbserial"); system("modprobe ftdi_sio"); #endif sleep(1); err = startup("localhost",9000); if (err) { printf("Startup failed...\n"); return 1; } fd = open_telos_source("localhost", 9000); if (fd <= 0) { printf("o_t_s failed! (fd=%i)\n",fd); return 1; } printf("startup succeeded...\n"); //wait for sleep msg and send status while (!sleepy) { packet = read_telos_packet(fd); if (packet && packet->type == AM_SLEEP_MSG) { sleepy = TRUE; printf("Sleep Msg!"); sleep(1); } else { printf("."); } free_telos_packet(&packet); packet = NULL; } sleepy = FALSE; sleep(1); //send I'm sleeping packet sendStatusPacket(fd, 1, 0); usleep(10000); close(fd); err = closedown(); if (err) { printf("closedown failed...\n"); } else { printf("Going to sleep\n"); #ifdef LOCALDBG sleep(5); #else system("modprobe -r ftdi_sio"); system("modprobe -r usbserial"); system("/sbin/sys_suspend"); #endif } sleep(1);///hrmmm } return 0; }*/ int main(int argc, char **argv) { int fd; int err; int sleepy = FALSE; bool connection = FALSE; FILE *connfile; bool firsttime = TRUE; telospacket *packet; init(argc,argv); printf("Starting Server\n"); sleep(1); sleep(1); firststartup("localhost",9000); fd = open_telos_source("localhost", 9000); err = start_sources(fd); while(TRUE) { if (!firsttime) { printf("Waiting for packet\n"); packet = read_telos_packet(fd); } else { printf("First time...don't wait.\n"); packet = NULL; firsttime = FALSE; } if (packet) { int igrade; curstate = packet->data[0]; igrade = packet->data[1]; curgrade = igrade; curgrade = curgrade / 100.0; free_telos_packet(&packet); } packet = NULL; sleep(9); printf("Time to sleep...if not connected.\n"); do { system("./check_wlan"); connfile = fopen("./connected","r"); if (connfile == NULL) { printf("not connected\n"); connection = FALSE; } else { fclose(connfile); connection = TRUE; sleep(1); printf("connected\n"); } } while(connection); printf("Sending packet.\n"); sendSleepPacket(fd); sleep(1); printf("Zzzzzz.....\n"); system("echo 1>/proc/sys/pm/suspend"); sleep(1); } return 0; }
tinyos-io/tinyos-3.x-contrib
wustl/upma/system/SenderDispatcher.h
<filename>wustl/upma/system/SenderDispatcher.h #ifndef SENDER_DISPATHCHER_H #define SENDER_DISPATHCHER_H enum { TDMA_SLOT = 0, CSMA_SLOT = 1, BEACON_SLOT = 2, NO_SLOT = 0xff, }; #endif
tinyos-io/tinyos-3.x-contrib
eon/tos/lib/tossim/sim_energy.c
<reponame>tinyos-io/tinyos-3.x-contrib #include <stdio.h> #include <tos.h> #include <sim_energy.h> int g_init = 0; sim_battery_t node_battery[TOSSIM_MAX_NODES]; void sim_energy_init_all() { int i; //printf("Initializing node_power variables to zero\n"); for (i=0; i< TOSSIM_MAX_NODES; i++) { sim_energy_init(i); } } void sim_energy_init(int nodeId) { if (g_init == 0) { g_init = 1; sim_energy_init_all(); } node_battery[nodeId].in_mJ=0.0; node_battery[nodeId].out_mJ=0.0; node_battery[nodeId].size=0.0; node_battery[nodeId].energy=0.0; node_battery[nodeId].waste=0.0; } double sim_node_energy(int nodeId) { return node_battery[nodeId].energy; } double sim_node_energy_in(int nodeId) { return node_battery[nodeId].in_mJ; } double sim_node_energy_out(int nodeId) { return node_battery[nodeId].out_mJ; } double sim_node_batt_size(int nodeId) { return node_battery[nodeId].size; } double sim_node_waste(int nodeId) { return node_battery[nodeId].waste; } void set_sim_node_energy(int nodeId, double mJ) { node_battery[nodeId].energy = mJ; } void sim_harvest_energy(int nodeId, double mJ) { node_battery[nodeId].in_mJ += mJ; node_battery[nodeId].energy += mJ; if (node_battery[nodeId].energy > node_battery[nodeId].size) { node_battery[nodeId].waste += node_battery[nodeId].energy - node_battery[nodeId].size; node_battery[nodeId].energy= node_battery[nodeId].size; } } bool sim_consume_energy(int nodeId, double mJ) { node_battery[nodeId].out_mJ += mJ; node_battery[nodeId].energy -= mJ; if (node_battery[nodeId].energy < 0) { node_battery[nodeId].energy= 0; //maybe do some signalling cuz we're dead return FALSE; } return TRUE; } bool sim_consume_profile(int nodeId, int path) { //TODO: need to add code for this. return TRUE; } void set_sim_node_batt_size(int nodeId, double mJ) { node_battery[nodeId].size = mJ; }
tinyos-io/tinyos-3.x-contrib
gems/ttsp/tinyos/tos/lib/ttsp/TimeSyncMsg.h
#ifndef TIMESYNC_MSG_H #define TIMESYNC_MSG_H typedef nx_struct TtspMsg { nx_uint16_t rootID; // rootId nx_uint16_t nodeID; // nodeId nx_uint8_t seqNum; // sequence number for the root nx_uint32_t globalTime; nx_uint32_t localTime; nx_uint32_t syncPeriod; } TtspMsg; enum { TIMESYNCMSG_LEN = sizeof(TtspMsg) - sizeof(nx_uint32_t), AM_TTSPMSG = 133 }; #endif
tinyos-io/tinyos-3.x-contrib
eon/eon/src/runtime/linuxsim/simworld/simworld.c
<filename>eon/eon/src/runtime/linuxsim/simworld/simworld.c<gh_stars>1-10 #include <pthread.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <values.h> #include <stdarg.h> #include <string.h> #include "simworld.h" //#define __USE_GNU //#include "/usr/include/dlfcn.h" //#include <dlfcn.h> void __attribute__ ((constructor)) myinit(void); typedef void *(*__threadfunc) (void *); typedef struct thread_struct { __threadfunc func; void *arg; } thread_struct_t; #define MAX_TDS 15 #define IDLE_POWER 1000 //uW #define GPS_POWER 300000 //uW #define FLASH_POWER 30000 //uW #define RADIO_LST_POWER 1000 //uW #define RADIO_RX_POWER 18000 //uW #define RADIO_TX_POWER 27000 //uW #define GPS_MIN_TIME 30 //seconds #define GPS_MAX_TIME 200 //seconds #define RADIO_RX_TIME 3000 //us #define RADIO_TX_TIME 3000 //us #define FLASH_MIN_TIME 1000 //us #define FLASH_MAX_TIME 3000 //us /********DEFINED ACTIONS*************************/ #define ACTION_SENSOR 11 #define ACTION_RADIORX 12 #define ACTION_RADIOTX 13 #define ACTION_RADIOLSTN 14 #define ACTION_ENERGYIN 15 #define ACTION_ENERGYOUT 16 #define ACTION_ENERGYBATT 17 #define ACTION_SETCALLBACK 18 #define ACTION_FLASHREAD 19 #define ACTION_FLASHWRITE 20 #define ACTION_POWERFAULT 21 #define ACTION_ERROR 22 #define ACTION_USER 10 #define NUM_ACTIONS 23 int __action_count[NUM_ACTIONS]; /********END DEFINED ACTIONS*********************/ typedef struct td_entry { int valid; pthread_t id; int asleep; unsigned int waketime; pthread_cond_t cond; } td_entry; pthread_mutex_t __td_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t __log_mutex = PTHREAD_MUTEX_INITIALIZER; td_entry __tds[MAX_TDS]; unsigned int __current_time; //in hundredths of a second unsigned int __scale_factor; unsigned int __time_limit; int __scale=0; __energyfunc the_energyfunc = NULL; pthread_t energy_tid; //LOG FILE FILE* __log_file = NULL; char __log_file_name[512]; int __uselog = 0; int __log_sys_evts = 0; int __log_level; /********************************** Energy accounting variables ***********************************/ unsigned int __battery_uJ; unsigned int __capacity_uJ; int __outuW; int __inuW; int __outuJ; int __inuJ; pthread_t maint_tid; int lastgpstime = GPS_MIN_TIME; unsigned int __deadtime=0; unsigned int __wastedenergy=0; unsigned int __solar_trace[400]; int solarcount = 360; unsigned int solar_hours[24]; int current_hour = 0; /********************************** Network Variables *********************************/ typedef struct net_req_t { int wait_hs; int request; } net_req_t; net_req_t __requests[50]; int __numrequests; //MESSAGING VARS int __inbox_full=0; int __inbox_value; //FLASH VARS int __simflash[100]; /************************************* Prototypes ***************************************/ void read_solar_trace(); void read_network_trace(); void up_power(int uW); void down_power(int uW); /************************************* API Here are the functions the user can call *************************************/ unsigned int predict_src_energy(unsigned int hours) { unsigned int sumenergy =0; int i; for (i=0; i < hours; i++) { sumenergy += solar_hours[(current_hour + i)%24]; } return sumenergy; } unsigned int get_battery_size() { return __capacity_uJ; } unsigned int get_current_time() { return __current_time; } void log_output(int action, const char *template, ...) { static int first =0; va_list ap; if (first ==0) { __log_file = fopen(__log_file_name, "a"); first = 1; } if (__log_sys_evts == 0 && action > __log_level) { //don't log system events return; } pthread_mutex_lock(&__log_mutex); //if (__battery_uJ > 0) { __action_count[action]++; } va_start(ap,template); if (__uselog) { fprintf(__log_file,"@@:%d:%u:",action, __current_time); vfprintf(__log_file, template, ap); fprintf(__log_file, "\n"); //fclose(__log_file); } else { printf("@@:%d:%u:",action, __current_time); vprintf(template, ap); printf("\n"); } va_end(ap); pthread_mutex_unlock(&__log_mutex); return; } int set_energy_callback(__energyfunc func) { log_output(ACTION_SETCALLBACK,"%d", (int)func); the_energyfunc = func; return 0; } int get_sensor_reading() { static int __reading = 0; int sleeptime; if (__battery_uJ <= 0) return -1; pthread_mutex_lock(&__td_mutex); up_power(GPS_POWER); pthread_mutex_unlock(&__td_mutex); __reading++; sleeptime = ((rand() >> 4) % (GPS_MAX_TIME - GPS_MIN_TIME)) + GPS_MIN_TIME; sim_sleep(sleeptime); log_output(ACTION_SENSOR,"%d",__reading); pthread_mutex_lock(&__td_mutex); down_power(GPS_POWER); pthread_mutex_unlock(&__td_mutex); return __reading; } int read_flash_int(int addr) { int sleeptime; int result; if (__battery_uJ <= 0) return -1; if (addr < 0 || addr >= 100) { log_output(ACTION_ERROR,"Flash read: Out of bounds"); return -1; } pthread_mutex_lock(&__td_mutex); up_power(FLASH_POWER); pthread_mutex_unlock(&__td_mutex); sleeptime = ((rand() >> 4) % (FLASH_MAX_TIME - FLASH_MIN_TIME)) + FLASH_MIN_TIME; sim_usleep(sleeptime); result = __simflash[addr]; log_output(ACTION_FLASHREAD,"%d:%d",addr,result); pthread_mutex_lock(&__td_mutex); down_power(FLASH_POWER); pthread_mutex_unlock(&__td_mutex); return result; } int write_flash_int(int addr, int value) { int sleeptime; if (__battery_uJ <= 0) return 0; if (addr < 0 || addr >= 100) { log_output(ACTION_ERROR,"Flash write: Out of bounds"); return 1; } pthread_mutex_lock(&__td_mutex); up_power(FLASH_POWER); pthread_mutex_unlock(&__td_mutex); sleeptime = ((rand() >> 4) % (FLASH_MAX_TIME - FLASH_MIN_TIME)) + FLASH_MIN_TIME; sim_usleep(sleeptime); __simflash[addr] = value; log_output(ACTION_FLASHWRITE,"%d:%d",addr,value); pthread_mutex_lock(&__td_mutex); down_power(FLASH_POWER); pthread_mutex_unlock(&__td_mutex); return 0; } int recv_network_int(unsigned int to_seconds, int *timedout) { unsigned int time_so_far = to_seconds; int rxval = -1; int rxed = 0; int limit = 0; if (__battery_uJ <= 0) { if (timedout != NULL) { *timedout = 1; } return -1; } if (to_seconds > 0) { limit = to_seconds; } pthread_mutex_lock(&__td_mutex); up_power(RADIO_LST_POWER); pthread_mutex_unlock(&__td_mutex); log_output(ACTION_RADIOLSTN,"%d:%u",to_seconds,(int)timedout); while (!limit || time_so_far > 0) { if (__inbox_full && __battery_uJ > 0) { rxval = __inbox_value; rxed = 1; pthread_mutex_lock(&__td_mutex); up_power(RADIO_RX_POWER); pthread_mutex_unlock(&__td_mutex); sim_usleep(RADIO_RX_TIME); log_output(ACTION_RADIORX,"%d",rxval); __inbox_full = 0; pthread_mutex_lock(&__td_mutex); down_power(RADIO_RX_POWER); pthread_mutex_unlock(&__td_mutex); break; } sim_sleep(3); if (limit) { time_so_far -= 3; } } pthread_mutex_lock(&__td_mutex); down_power(RADIO_LST_POWER); pthread_mutex_unlock(&__td_mutex); if (!rxed && timedout != NULL) { *timedout = 1; } if (rxed && timedout != NULL) { *timedout = 0; } return rxval; } void send_network_int(int value) { if (__battery_uJ <= 0) return; pthread_mutex_lock(&__td_mutex); up_power(RADIO_TX_POWER); pthread_mutex_unlock(&__td_mutex); sim_usleep(RADIO_TX_TIME); log_output(ACTION_RADIOTX, "%d",value); pthread_mutex_lock(&__td_mutex); down_power(RADIO_TX_POWER); pthread_mutex_unlock(&__td_mutex); } /**************************************** End API Calls ******************************************/ void up_power(int uW) { __outuW += uW; } void down_power(int uW) { if (uW >= __outuW) { log_output(ACTION_POWERFAULT,"%u >= %u",uW,__outuW); __outuW = 0; } else { __outuW -= uW; } } unsigned int consume_energy(unsigned int __uJ) { //printf("consume_energy(%u) -> (%u, %u)\n", __uJ, __outuJ, __battery_uJ); __outuJ += __uJ; if (__uJ <= __battery_uJ) { __battery_uJ -= __uJ; } else { __battery_uJ = 0; } return __battery_uJ; } int __doewma(int oldv, int newv, int num, int den) { int retval; retval = ((oldv * (den-num)) + (newv * num))/den; return retval; } unsigned int harvest_energy() { static int last_hr; unsigned int hr; unsigned int hrs_elapsed; unsigned int __uJ; hrs_elapsed = __current_time / (100 * 60 * 60); hr = hrs_elapsed % (24*14); current_hour = hr; if (hr != last_hr) { //new hour int hr24 = last_hr % 24; solar_hours[hr24] = __doewma(solar_hours[hr24], __solar_trace[last_hr], 4, 10); } __uJ = __solar_trace[hr] / ((60 * 60)/ENERGY_TIME); //uJ/hr -> uJ/ENERGY_TIME __inuJ += __uJ; __battery_uJ += __uJ; if (__battery_uJ > __capacity_uJ) { __wastedenergy += __battery_uJ - __capacity_uJ; __battery_uJ = __capacity_uJ; } return __battery_uJ; } int getnextentry(pthread_t tid) { int i; int theindex = -1; pthread_mutex_lock(&__td_mutex); for (i=0; i < MAX_TDS; i++) { if (__tds[i].valid == 0 && theindex == -1) { __tds[i].valid = 1; __tds[i].id = tid; __tds[i].asleep = 0; __tds[i].waketime = 0; pthread_cond_init(&__tds[i].cond, NULL); theindex = i; break; } } pthread_mutex_unlock(&__td_mutex); return theindex; } void removeentry(pthread_t tid) { int i; pthread_mutex_lock(&__td_mutex); for (i=0; i < MAX_TDS; i++) { if (__tds[i].valid == 1 && pthread_equal(__tds[i].id, tid) != 0) { __tds[i].valid = 0; pthread_cond_destroy(&__tds[i].cond); } } pthread_mutex_unlock(&__td_mutex); } int lookupentry(pthread_t tid) { int theindex = -1; int i; for (i=0; i < MAX_TDS; i++) { if (__tds[i].valid == 1 && pthread_equal(__tds[i].id, tid) != 0) { theindex = i; break; } } return theindex; } void clearentries() { int i; pthread_mutex_lock(&__td_mutex); for (i=0; i < MAX_TDS; i++) { __tds[i].valid = 0; } pthread_mutex_unlock(&__td_mutex); } int sleepy() { int imsleepy = 1; int i; pthread_mutex_lock(&__td_mutex); for (i=0; i < MAX_TDS; i++) { if (__tds[i].valid == 1 && __tds[i].asleep == 0) { imsleepy = 0; } } pthread_mutex_unlock(&__td_mutex); return imsleepy; } unsigned int getnexttime() { int i; unsigned int ntime = UINT_MAX; pthread_mutex_lock(&__td_mutex); //printf("getnexttime\n"); for (i=0; i < MAX_TDS; i++) { if (__tds[i].valid == 1 && __tds[i].waketime < ntime && __tds[i].waketime >= __current_time) { ntime = __tds[i].waketime; } } pthread_mutex_unlock(&__td_mutex); return ntime; } void checknetwork(unsigned int delta) { static unsigned int last_msg = 0; static int msg_count = 0; unsigned int msg_time; if (__numrequests <= 0) { return; } msg_time = last_msg + __requests[msg_count].wait_hs; if (msg_time <= (__current_time + delta)) { //send next message if (__inbox_full == 0) { __inbox_full = 1; __inbox_value = __requests[msg_count].request; } last_msg = msg_time; //printf("@@:13------>%d,%d<----pre\n",msg_count, __numrequests); msg_count = (msg_count+1) % __numrequests; //printf("@@:13------>%d<----post\n",msg_count); } } int realsleep(unsigned int waketime) { unsigned int delta; unsigned int realdelta; int i; delta = waketime - __current_time; //actual time to sleep realdelta = (delta * 100)/__scale_factor; //printf("realdelta = %u\n",realdelta); checknetwork(delta); pthread_mutex_lock(&__td_mutex); for (i=0; i < MAX_TDS; i++) { if (__tds[i].valid == 1 && __tds[i].waketime == waketime) { __tds[i].asleep = 0; pthread_cond_signal(&__tds[i].cond); } } consume_energy((__outuW * delta) / 100); if (__battery_uJ == 0) { __deadtime += delta; } if (__scale) { if (realdelta < 1000) { //from hs to us usleep(realdelta * 10000); } else { sleep(realdelta / 100); } } if (waketime == UINT_MAX) { __current_time =0; } else { __current_time = waketime; } pthread_mutex_unlock(&__td_mutex); return realdelta; } void *__m_thread_routine (void *arg) { unsigned int nexttime; unsigned int delta; while (1) { //check to see if all threads are asleep if (sleepy()) { nexttime = getnexttime(); //printf("sleepy-post(%u)\n",nexttime); delta = realsleep(nexttime); } //usleep(100); pthread_yield(); } return NULL; } void *__energy_thread_routine (void *arg) { //printf("energy thread!\n"); while (1) { //printf("energy thread! sleeping!\n"); sim_sleep(ENERGY_TIME); harvest_energy(); if (__current_time > __time_limit) { printf("Simulation done\n"); int i; for (i=0; i < NUM_ACTIONS; i++) { printf("Action %d : %d times\n", i, __action_count[i]); } printf("Dead time: %u seconds\n",__deadtime / 100); printf("Wasted Energy: %u uJoules\n",__wastedenergy); exit(1); } //printf("__outuJ = %u (%u)\n", __outuJ, __battery_uJ); log_output(ACTION_ENERGYIN,"%d",__inuJ); log_output(ACTION_ENERGYOUT,"%d",__outuJ); log_output(ACTION_ENERGYBATT,"%u",__battery_uJ); if (the_energyfunc != NULL) { //printf("calling func\n"); //add noise int innoise; int outnoise; unsigned int battnoise; innoise = ((rand() >> 4) % 600) - 300; //+/- 60uW accuracy outnoise = ((rand() >> 4) % 600) - 300; battnoise = (rand() >> 4) & 0x0000000f; the_energyfunc(__inuJ+innoise, __outuJ+outnoise, (__battery_uJ & 0xFFFFFFF0) | battnoise); } __inuJ = 0; __outuJ = 0; } return NULL; } void myinit(void) { int ret; pthread_t self = pthread_self(); int entry; clearentries(); entry = getnextentry(self); __current_time= 0; __outuW = IDLE_POWER; memset(&__action_count, 0, sizeof(__action_count)); //READ IN ENVIRONMENT VARIABLES read_solar_trace(); read_network_trace(); char *str_factor = getenv("SIM_TIME_FACTOR"); if (str_factor == NULL) { __scale_factor = 100; __scale = 0; } else { __scale = 1; __scale_factor = atoi(str_factor); } char *str_limit = getenv("SIM_TIME_LIMIT"); if (str_limit == NULL) { __time_limit = 0; } else { __time_limit = atol(str_limit) * 100; } char *str_bsize = getenv("SIM_BATTERY_SIZE"); if (str_bsize == NULL) { __capacity_uJ = 10000000L; } else { __capacity_uJ= atol(str_bsize); } __battery_uJ = __capacity_uJ / 2; char *str_fname = getenv("SIM_LOG_FILE"); if (str_fname == NULL) { __log_file = NULL; printf("Logging to stdout\n"); } else { strncpy(__log_file_name, str_fname, 500); __log_file = fopen(str_fname,"w"); if (__log_file != NULL) { __uselog = 1; } fclose(__log_file); printf("Logging to file:%s(%d)\n",__log_file_name, __uselog); } char *str_ll = getenv("SIM_LOG_LEVEL"); if (str_ll == NULL) { __log_level = ACTION_USER; } else { __log_level = atoi(str_ll); } printf("Log Level=%d\n", __log_level); //END OF READING ENVINRONMENT VARIABLES ret = pthread_create(&maint_tid, NULL, __m_thread_routine, NULL); sim_pthread_create(&energy_tid, NULL, __energy_thread_routine, NULL); printf("libsimworld init! (entry=%d, scale=%u)\n", entry, __scale_factor); } void *__thread_routine (void *arg) { void *ret; thread_struct_t *tst = (thread_struct_t*)arg; if (getnextentry(pthread_self()) == -1) { //could not find a free slot printf("TOO MANY THREADS! Killing this one.\n"); sim_pthread_exit(NULL); } ret = tst->func(tst->arg); sim_pthread_exit(ret); } int sim_pthread_create (pthread_t *__restrict __threadp, __const pthread_attr_t *__restrict __attr, void *(*__start_routine) (void *), void *__restrict __arg) { int ret; thread_struct_t *tst = malloc(sizeof(thread_struct_t)); //printf ("shim: called pthread_create()\n"); tst->func = __start_routine; tst->arg = __arg; ret = pthread_create(__threadp, __attr, __thread_routine, (void*)tst); return ret; } void __attribute__((noreturn)) sim_pthread_exit(void *value_ptr) { //clean up monitoring data here //printf ("shim: called pthread_exit()\n"); removeentry(pthread_self()); pthread_exit(value_ptr); //never reached, but necessary to convince GCC that it won't return; exit(1); } unsigned int sim_sleep (unsigned int __seconds) { unsigned int realdelta; int idx; //printf ("shim: called sleep(%u)\n", __seconds); //log_output (1,"sleep() : %u",__outuW); pthread_mutex_lock(&__td_mutex); realdelta = __seconds * 100; idx = lookupentry(pthread_self()); if (idx == -1) { printf("AAAH. I have no record of this thread...BUG!\n"); exit(1); } __tds[idx].waketime = __current_time + realdelta; __tds[idx].asleep = 1; //printf ("pre-wait\n"); pthread_cond_wait(&__tds[idx].cond, &__td_mutex); //printf ("post-wait\n"); //printf ("shim: sleep returned(%u, %u)\n", __tds[idx].waketime, __current_time); pthread_mutex_unlock(&__td_mutex); return __seconds; } int sim_usleep (__useconds_t __useconds) { unsigned int realdelta; int idx; //log_output (1,"usleep() : %u",__outuW); pthread_mutex_lock(&__td_mutex); realdelta = __useconds / 10000; idx = lookupentry(pthread_self()); if (idx == -1) { printf("AAAH. I have no record of this thread...BUG!\n"); exit(1); } __tds[idx].waketime = __current_time + realdelta; __tds[idx].asleep = 1; pthread_cond_wait(&__tds[idx].cond, &__td_mutex); pthread_mutex_unlock(&__td_mutex); return 0; } void read_solar_trace() { char *str_fname = getenv("SIM_SOLAR_TRACE"); FILE *thefile; int i, ret; if (str_fname == NULL) { printf("No solar trace specified!\n"); exit(-1); } thefile = fopen(str_fname, "r"); for (i=0; i < 365; i++) { ret = fscanf(thefile,"%u",&__solar_trace[i]); //printf("%u\n",__solar_trace[i]); } } void read_network_trace() { char *str_fname = getenv("SIM_NETWORK_TRACE"); FILE *thefile; int i, ret; if (str_fname == NULL) { printf("No network trace specified!\n"); __numrequests = 0; return; } thefile = fopen(str_fname, "r"); i=0; while (!feof(thefile) && i < 50) { ret = fscanf(thefile,"%u %u",&__requests[i].wait_hs, &__requests[i].request); //printf("%u -> %u\n",__requests[i].wait_hs, __requests[i].request); if (!feof(thefile)) { i++; } else { break; } } fclose(thefile); __numrequests = i; printf("i=%d\n",i); }
tinyos-io/tinyos-3.x-contrib
stanford-sing/libs/fwp/sim/TossimRadioMsg.h
#ifndef TOSSIM_RADIO_MSG_H #define TOSSIM_RADIO_MSG_H #include "AM.h" typedef nx_struct tossim_header { nx_am_addr_t dest; nx_am_addr_t src; nx_uint8_t length; nx_am_id_t type; nx_uint8_t quiet; // added for FWP } tossim_header_t; typedef nx_struct tossim_footer { nxle_uint16_t crc; } tossim_footer_t; typedef nx_struct tossim_metadata { nx_uint16_t strength; nx_uint8_t ack; nx_uint16_t time; } tossim_metadata_t; #endif
tinyos-io/tinyos-3.x-contrib
berkeley/apps/AIIT_tutorials/8_RadioToCount/Counter.h
#ifndef PRINT_SERIAL_H #define PRINT_SERIAL_H #include "message.h" typedef nx_struct counter_msg { nx_uint16_t nodeid; nx_uint16_t counter; } counter_msg_t; enum { AM_COUNTER_MSG = 0x10, }; #endif
tinyos-io/tinyos-3.x-contrib
nxtmote/tos/platforms/nxtmote/interrupt_timer.h
<gh_stars>1-10 /** * Adapted for nxtmote. * @author <NAME> */ #ifndef INTERRUPT_TIMER_H #define INTERRUPT_TIMER_H void timer_init ( void ); extern volatile int count_timer0_interrupt; extern volatile int count_timer1_interrupt; #endif
tinyos-io/tinyos-3.x-contrib
eon/tos/lib/tossim/sim_energy.h
#ifndef _SIM_ENERGY_H_ #define _SIM_ENERGY_H_ #ifdef __cplusplus extern "C" { #endif typedef struct sim_battery_t { double in_mJ; double out_mJ; double size; double energy; double waste; } sim_battery_t; void sim_energy_init_all(); void sim_energy_init(int nodeId); double sim_node_energy(int nodeId); double sim_node_energy_in(int nodeId); double sim_node_energy_out(int nodeId); double sim_node_batt_size(int nodeId); double sim_node_waste(int nodeId); void set_sim_node_energy(int nodeId, double mJ); void sim_harvest_energy(int nodeId, double mJ); bool sim_consume_energy(int nodeId, double mJ); bool sim_consume_profile(int nodeId, int path); void set_sim_node_batt_size(int nodeId, double mJ); #ifdef __cplusplus } #endif #endif
tinyos-io/tinyos-3.x-contrib
intelmote2/tools/platforms/intelmote2/jflashmm/src/Compile_switches.h
<reponame>tinyos-io/tinyos-3.x-contrib<gh_stars>1-10 /****************************************************************************** ** ** COPYRIGHT (C) 2000, 2001, 2002 Intel Corporation. ** ** The information in this file is furnished for informational use ** only, is subject to change without notice, and should not be construed as ** a commitment by Intel Corporation. Intel Corporation assumes no ** responsibility or liability for any errors or inaccuracies that may appear ** in this document or any software that may be provided in association with ** this document. ** ** FILENAME: Compile_switches.h ** ** PURPOSE: collects the optional switches for this program. ** ** LAST MODIFIED: $Modtime: 10/04/02 11:09a $ ******************************************************************************/ //#define DEBUG #define K3_BUGFIX
tinyos-io/tinyos-3.x-contrib
diku/mcs51/tos/chips/mcs51/byteorder.h
/** * Keil byte order * uint16_t big endian (MSB first) * sfr16 little endian (LSB first) * * Keil stores multi-byte-values as big endian (MSB first, at the * lowest address). This means for uint16_t values the high order byte * (MSB) must be selected as the address for uint16_t values. * * sfr16 values the are stored as little endian as such the LSB must * be selected as the address of the sfr16 register * * It might be worth ignoring the sfr16 definition altogether to avoid * confusion, or at least use the following macros to illustrate what * is going on - possibly in a compiler agnostic way. * * http://www.keil.com/support/man/docs/c51/c51_xe.htm * http://www.keil.com/support/man/docs/c51/c51_le_sfr16.htm * */ /** * SDCC byte order * * SDCC apparently stores multibyte values as little endian, it is * unclear whether this is the case for sfr16 registers or not. * * Hopefully someone remembers to chech before compiling with sdcc =]. * * http://sdcc.sourceforge.net/doc/sdccman.pdf */ #ifndef _H_BYTEORDER_H_ #define _H_BYTEORDER_H_ #define BIG_ENDIAN /* #ifdef __KEIL__ */ /* #else */ /* #define LITTLE_ENDIAN */ /* #endif */ //#define _BSWAP_UINT16(word) (((uint8_t*)&word)[0]<<8 | ((uint8_t*)&word)[1]) #define _BSWAP_UINT16(w) ( ((0x00FFu&w)<<8) | ((0xFF00u&w)>>8)) #define _BSWAP_UINT32(l) ( ((0x000000FFul&l)<<24) |\ ((0x0000FF00ul&l)<<8) |\ ((0x00FF0000ul&l)>>8) |\ ((0xFF000000ul&l)>>24)) #ifdef BIG_ENDIAN #define letohs (uint16_t) _BSWAP_UINT16 #define letohl (uint32_t) _BSWAP_UINT32 #define SFR16_TO_UINT16 (uint16_t) _BSWAP_UINT16 #define UINT16_TO_SFR16 (sfr16) _BSWAP_UINT16 #else /* This warning shows up in Nesc - so maybe it should be defined in the makefile or something #warning "This code probably will not work without the Keil Compiler." */ #define letohs(w) w #define letohl(w) w #define SFR16_TO_UINT16(w) w #define UINT16_TO_SFR16(w) w #endif #endif //_H_BYTEORDER_H_
johann8384/udpbalancer
misc.h
<reponame>johann8384/udpbalancer /* * misc.h, 2005.07.18, SJ */ void drop_root(); long tvdiff(struct timeval a, struct timeval b); char *_extract(char *row, int ch, char *s, int size); unsigned long resolve_host(char *h); int readudppacket(int sd, char *buf, int size, int timeout, struct sockaddr *client_addr);
johann8384/udpbalancer
config.h
/* * config.h, 2005.07.18, SJ */ #define PROGNAME "udpbalancer" #define VERSION "0.1" #define LISTEN_ADDR "0.0.0.0" #define GGID 98 #define UUID 99 #define LOG_OPTION LOG_DEBUG #define LOG_FACILITY LOG_LOCAL4 #define TIMEOUT 1 #define MAX_LOST_PACKET 5 #define PACKETLEN 4096 #define TMPLEN 64 #define MAXHOSTS 4 #define IPADDRLEN 16 #define BONUS 4 #define REFRESH_INTERVAL 300 #define M_ROUNDROBIN 0 #define M_LOADBALANCE 1 #define M_VOLUMEBALANCE 2 #define M_DEFAULT M_ROUNDROBIN #define FORMAT1 "%s\n" #define FORMAT2 "%s: %d\n" #define FORMAT3 "%s: %s\n" struct onehost { char host[IPADDRLEN]; unsigned short int avail; unsigned long rtt; unsigned long bogomips; unsigned long counter; unsigned long lost; unsigned long s_addr; };
johann8384/udpbalancer
misc.c
<gh_stars>1-10 /* * misc.c, 2005.07.18, SJ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <netdb.h> #include "config.h" void drop_root(){ setgid(GGID); setuid(UUID); } long tvdiff(struct timeval a, struct timeval b){ double res; res = (a.tv_sec * 1000000 + a.tv_usec) - (b.tv_sec * 1000000 + b.tv_usec); return (long) res; } char *_extract(char *row, int ch, char *s, int size){ char *r; int len; if(row == NULL) return NULL; if((r = strchr(row,ch)) == NULL) return NULL; if(s != NULL){ len = strlen(row) - strlen(r); if(len > size) len = size; strncpy(s, row, len); s[len] = '\0'; } return r; } unsigned long resolve_host(char *h){ struct hostent *host; struct in_addr addr; if((addr.s_addr = inet_addr(h)) == -1){ if((host = gethostbyname(h)) == NULL){ return 0; } else return *(unsigned long*)host->h_addr; } else return addr.s_addr; } int readudppacket(int sd, char *buf, int size, int timeout, struct sockaddr *client_addr){ struct timeval tv; fd_set rfds; int retval, n, size_of; size_of = sizeof(struct sockaddr); FD_ZERO(&rfds); FD_SET(sd, &rfds); tv.tv_sec = timeout; tv.tv_usec = 0; retval = select(sd+1, &rfds, NULL, NULL, &tv); /* 0: timeout, -1: error */ if(retval <= 0) return 0; n = recvfrom(sd, buf, size, 0, (struct sockaddr *)&client_addr, &size_of); return n; }
johann8384/udpbalancer
udpbalancer.c
<gh_stars>1-10 /* * udpbalancer.c, 2005.07.18, SJ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> #include <netinet/in.h> #include <arpa/inet.h> #include <time.h> #include <unistd.h> #include <syslog.h> #include <signal.h> #include <stdarg.h> #include "misc.h" #include "config.h" #define USAGE "usage: " PROGNAME " -l <listen address> -m <method> -p <port>, -x <host1:bogo1,host2:bogo2,..,hostN:bogoN>, ..." #if defined (__FreeBSD__) #define INT_MAX 2147483647 #endif extern char *optarg; extern int optind; int sd, lsd, v=0, timeout=TIMEOUT, hostnum=0; unsigned long counter; struct timezone tz; struct timeval senttime, now; struct onehost hosts[MAXHOSTS]; int bogomips[MAXHOSTS]; int fatal(const char *fmt, ...){ va_list ap; va_start(ap, fmt); vprintf(fmt, ap); va_end(ap); #ifdef USESYSLOG vsyslog(LOG_OPTION, fmt, ap); #endif exit(1); } void clean_exit(){ close(sd); close(lsd); #ifdef USESYSLOG syslog(LOG_OPTION, "terminated"); #endif exit(1); } int choose_round_robin_host(int chost){ int i; if(chost > hostnum) i=0; for(i=chost; i<hostnum; i++){ if(hosts[i].avail == 1) return i; } for(i=0; i<chost; i++){ if(hosts[i].avail == 1) return i; } return -1; } int choose_volume_host(){ int i, x=0, maxbogo=0; // determine max. bogomips value for(i=0; i<hostnum; i++){ if(hosts[i].avail == 1 && bogomips[i] > maxbogo) maxbogo = bogomips[i]; } // choose random number x = rand() % maxbogo + 1; //fprintf(stderr, "rand: %d ** ", x); // choose one for(i=0; i<hostnum; i++){ if(hosts[i].avail == 1 && bogomips[i] >= x) return i; } return -1; } int choose_balance_host(){ int i, x, ix=-1, minrtt=timeout*1E6, maxbogo=0, cbogo; // determine which host respondes the fastest for(i=0; i<hostnum; i++){ if(hosts[i].avail == 1 && hosts[i].rtt > 0 && hosts[i].rtt / hosts[i].counter < minrtt){ minrtt = hosts[i].rtt / hosts[i].counter; ix = i; } } // determine max. bogomips value for(i=0; i<hostnum; i++){ cbogo = bogomips[i]; if(i == ix) cbogo += BONUS; // bonus weight for the fastest if(hosts[i].avail == 1 && cbogo > maxbogo) maxbogo = cbogo; } // choose random number x = rand() % maxbogo + 1; //fprintf(stderr, "rand: %d fastest: %s ** ", x, hosts[ix].host); // choose one for(i=0; i<hostnum; i++){ cbogo = bogomips[i]; if(i == ix) cbogo += BONUS; if(hosts[i].avail == 1 && cbogo >= x) return i; } return -1; } void refresh(){ int i; for(i=0; i<hostnum; i++){ hosts[i].rtt = 0; hosts[i].counter = 1; hosts[i].avail = 1; hosts[i].bogomips = 0; hosts[i].lost = 0; } alarm(REFRESH_INTERVAL); //fprintf(stderr, "FLUSHED\n"); } int main(int argc, char **argv){ int i, n, nexthost, port=0, method=M_DEFAULT, addr_len; char *p, *pl, *pl2, *listen_addr=LISTEN_ADDR, tmpbuf[TMPLEN]; unsigned char packet[PACKETLEN]; unsigned long listenhost; struct sockaddr_in my_addr, send_addr, client_addr; while((i = getopt(argc, argv, "x:l:m:p:v")) > 0){ switch(i){ case 'x' : pl = optarg; do{ memset((char *)&hosts[hostnum], 0, sizeof(struct onehost)); p = _extract(pl, ',', &tmpbuf[0], TMPLEN-1); if(p){ p++; pl = p; } else { strncpy(&tmpbuf[0], pl, TMPLEN-1); } pl2 = strchr(tmpbuf, ':'); if(pl2){ *pl2 = '\0'; pl2++; bogomips[hostnum] = atoi(pl2); if(bogomips[hostnum] == 0) fatal(FORMAT2, "bogomips value must be >= 1", bogomips[hostnum]); } else { bogomips[hostnum] = 0; } strncpy((char *)&hosts[hostnum].host[0], &tmpbuf[0], IPADDRLEN-1); hosts[hostnum].s_addr = resolve_host(hosts[hostnum].host); if(hosts[hostnum].s_addr == 0) fatal(FORMAT3, "invalid host", hosts[hostnum].host); hostnum++; if(hostnum > MAXHOSTS) fatal(FORMAT2, "too many host. max:", MAXHOSTS); } while(p); break; case 'l' : listen_addr = optarg; break; case 'm' : if(!strcmp(optarg, "roundrobin")) method = M_ROUNDROBIN; if(!strcmp(optarg, "loadbalance")) method = M_LOADBALANCE; if(!strcmp(optarg, "volumebalance")) method = M_VOLUMEBALANCE; break; case 'p' : port = atoi(optarg); if(port == 0 || port > 65535) fatal(FORMAT2, "invalid port", port); break; case 'v' : v++; break; default : fatal(FORMAT1, USAGE); break; } } if(port == 0) fatal(FORMAT2, "invalid port", port); listenhost = resolve_host(listen_addr); #ifdef USESYSLOG (void) openlog(PROGNAME, LOG_PID, LOG_FACILITY); syslog(LOG_OPTION, "%s %s is starting on %s:%d", PROGNAME, VERSION, listen_addr, port); #endif signal(SIGINT, clean_exit); signal(SIGQUIT, clean_exit); signal(SIGKILL, clean_exit); signal(SIGTERM, clean_exit); signal(SIGALRM, refresh); /* create listener socket */ if((lsd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) fatal(FORMAT1, "cannot open listener socket"); my_addr.sin_family = AF_INET; my_addr.sin_port = htons(port); my_addr.sin_addr.s_addr = listenhost; bzero(&(my_addr.sin_zero), 8); if(bind(lsd, (struct sockaddr*)&my_addr, sizeof(struct sockaddr)) == -1) fatal(FORMAT2, "cannot bind to port:", port); /* drop root privs if we have */ if(getuid() == 0 || geteuid() == 0){ fprintf(stderr, "dropped\n"); drop_root(); } /* create sender socket */ if((sd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) fatal(FORMAT1, "cannot open socket"); bzero((char *)&send_addr, sizeof(struct sockaddr)); send_addr.sin_family = AF_INET; send_addr.sin_port = htons(port); nexthost = -1; addr_len = sizeof(struct sockaddr); srand(getpid()); refresh(); for(;;){ /* read request from clients */ if((n = recvfrom(lsd, &packet[0], PACKETLEN, 0, (struct sockaddr*)&client_addr, &addr_len)) > 0){ //fprintf(stderr, "%d %s\n", n, inet_ntoa(client_addr.sin_addr)); /* determine next host to forward request */ switch(method){ case M_ROUNDROBIN: nexthost++; nexthost = choose_round_robin_host(nexthost); break; case M_VOLUMEBALANCE: nexthost = choose_volume_host(); break; case M_LOADBALANCE: nexthost = choose_balance_host(); break; } if(nexthost < 0){ #ifdef USESYSLOG syslog(LOG_OPTION, "no available hosts! Refreshing."); #endif fprintf(stderr, "no available hosts! Refreshing.\n"); refresh(); continue; } /* send request to selected host */ send_addr.sin_addr.s_addr = hosts[nexthost].s_addr; gettimeofday(&senttime, &tz); sendto(sd, (char *)&packet, n, 0, (struct sockaddr *)&send_addr, sizeof(struct sockaddr)); /* * read answer * we do not retry instead let the client repeat the request */ n = readudppacket(sd, &packet[0], PACKETLEN, timeout, (struct sockaddr*)&client_addr); gettimeofday(&now, &tz); if(n > 0){ hosts[nexthost].counter++; hosts[nexthost].rtt += tvdiff(now, senttime); if(hosts[nexthost].rtt < 0) hosts[nexthost].rtt = INT_MAX - 100; // print debug info if(v > 2) fprintf(stderr, "%s => %s:%d - %d bytes in %ld [usec]\n", inet_ntoa(client_addr.sin_addr), hosts[nexthost].host, port, n, tvdiff(now, senttime)); } else { /* one lost packet should not discard our next node */ hosts[nexthost].lost++; if(hosts[nexthost].lost > MAX_LOST_PACKET){ hosts[nexthost].avail = 0; #ifdef USESYSLOG syslog(LOG_OPTION, "%s-(%d) been discarded", hosts[nexthost].host, port); #endif if(v >= 1) fprintf(stderr, "%s-(%d) been discarded\n", hosts[nexthost].host, port); } } /* send response back to your client */ sendto(lsd, (char *)&packet, n, 0, (struct sockaddr *)&client_addr, sizeof(struct sockaddr)); } } return 0; }
amrayn/residue-java
samples/jni/src/residue-jni.h
<gh_stars>0 // // Part of residue native binding for java // // Copyright (C) 2017-present Amrayn Web Services // // https://muflihun.com // https://amrayn.com // https://github.com/amrayn/residue-java // // Author: @abumusamq // #include <jni.h> #ifndef Residue_JNI_H #define Residue_JNI_H #ifdef __cplusplus extern "C" { #endif JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void*); /* * Method: connect */ JNIEXPORT void JNICALL Java_com_muflihun_residue_Residue_connect(JNIEnv *, jobject, jstring); /* * Method: disconnect */ JNIEXPORT void JNICALL Java_com_muflihun_residue_Residue_disconnect(JNIEnv *, jobject); /** * Residue.write(String loggerId, String file, int lineNumber, String func, String msg, int level, int vl, jstring threadId) * * Sends log */ JNIEXPORT void JNICALL Java_com_muflihun_residue_Residue_write(JNIEnv *, jobject, jstring, jstring, jint, jstring, jstring, jint, jint, jstring); #ifdef __cplusplus } #endif #endif
ksk-/yqueue
src/YQueue/Queue.h
<reponame>ksk-/yqueue #pragma once #include <condition_variable> #include <functional> #include <optional> #include <boost/fiber/all.hpp> #include <boost/noncopyable.hpp> #include <YQueue/Defines.h> #include <YQueue/TypeTraits.h> namespace YQueue { /** * @class Queue * @brief Simple concurrent queue class. * @tparam T value type * @tparam Capacity the capacity of the queue * @tparam Concurrency the concurrency model to synchronize queue operations * @tparam Container the underlying container type */ template< typename T, typename Container = std::deque<T>, Concurrency Concurrency = Concurrency::Threads, size_t Capacity = YQUEUE_QUEUE_CAPACITY, REQUIRES(std::is_copy_constructible_v<T>) > class Queue final : private boost::noncopyable { using Mutex = std::conditional_t<Concurrency == Concurrency::Threads, std::mutex, boost::fibers::mutex >; using ConditionVariable = std::conditional_t<Concurrency == Concurrency::Threads, std::condition_variable, boost::fibers::condition_variable >; public: /** * @brief The concurrency model to synchronize queue operations. */ static constexpr YQueue::Concurrency concurrency = Concurrency; public: Queue() : waiting_(false) { if constexpr (type_traits::has_set_capacity_v<Container>) { container_.set_capacity(Capacity); } } /** * @brief Invokes the given callable to consume all available values from the queue. * @param callable the consumer callable * @return number of dequeued values */ template<typename Callable, REQUIRES(std::is_invocable_v<Callable, T>)> size_t consumeAll(Callable&& callable) { std::vector<T> dequeued; { std::unique_lock lock(mutex_); if (waiting_) { cv_.wait(lock, [this] { return !isEmpty() || !waiting_; }); } const size_t size = container_.size(); dequeued.reserve(size); if constexpr (std::is_nothrow_move_constructible_v<T>) { std::move(container_.begin(), container_.end(), std::back_inserter(dequeued)); } else { std::copy(container_.begin(), container_.end(), std::back_inserter(dequeued)); } container_.clear(); } std::for_each(dequeued.cbegin(), dequeued.cend(), std::forward<Callable>(callable)); return dequeued.size(); } /** * @brief Invokes the given callable to consume one available value from the queue. * @param callable the consumer callable * @return true if the value was dequeued successfully, false - otherwise */ template<typename Callable, REQUIRES(std::is_invocable_v<Callable, T>)> bool consumeOne(Callable&& callable) { std::optional<T> dequeued; { std::unique_lock lock(mutex_); if (waiting_) { cv_.wait(lock, [this] { return !isEmpty() || !waiting_; }); } if (!isEmpty()) { dequeued = pop(); } } if (!dequeued.has_value()) { return false; } std::invoke(std::forward<Callable>(callable), dequeued.value()); return true; } /** * @brief Dequeues a value from the queue. * @return a valued optional if the value was dequeued successfully, std::nullopt - otherwise */ std::optional<T> dequeue() { std::lock_guard lock(mutex_); return isEmpty() ? std::nullopt : std::optional(pop()); } /** * @brief Disables waiting for enqueued values for all consumers. */ void disableWaiting() { std::lock_guard lock(mutex_); waiting_ = false; cv_.notify_all(); } /** * @brief Enables waiting for enqueued values in consume methods. */ void enableWaiting() { std::lock_guard lock(mutex_); waiting_ = true; } /** * @brief Enqueues the given value into the queue. * @param value the value * @return true if the value was enqueued successfully, false if the queue is full */ template<typename U, REQUIRES(std::is_convertible_v<U, T>)> bool enqueue(U&& value) { { std::lock_guard lock(mutex_); if (isFull()) { return false; } container_.push_back(std::forward<U>(value)); } if (waiting_) { cv_.notify_one(); } return true; } private: bool isEmpty() const { return container_.empty(); } bool isFull() const { return container_.size() == Capacity; } T pop() { T value = std::move_if_noexcept(container_.front()); container_.pop_front(); return value; } private: bool waiting_; Container container_; Mutex mutex_; ConditionVariable cv_; }; }
ksk-/yqueue
src/YQueue/HashMap.h
<reponame>ksk-/yqueue #pragma once #include <algorithm> #include <forward_list> #include <optional> #include <shared_mutex> #include <thread> #include <vector> #include <boost/noncopyable.hpp> #include <YQueue/TypeTraits.h> namespace YQueue { /** * @class HashMap * @brief Simple thread-safe hashmap class. * @tparam Key key type * @tparam Value value type * @tparam Hash hash-function * @note The Hash should be a stateless functional object. * @tparam KeyEqual equality comparison predicate * @note The KeyEqual callable should be a stateless functional object. */ template< typename Key, typename Value, typename Hash = std::hash<Key>, typename KeyEqual = std::equal_to<Key>, REQUIRES(std::is_copy_constructible_v<Key>), REQUIRES(std::is_copy_constructible_v<Value>), REQUIRES(type_traits::is_stateless_callable_r_v<size_t, Hash, Key>), REQUIRES(type_traits::is_stateless_callable_r_v<bool, KeyEqual, Key, Key>) > class HashMap final : private boost::noncopyable { class Bucket final : private boost::noncopyable { public: std::optional<Value> find(const Key& key) const { std::shared_lock lock(mutex_); const auto it = findValue(key); return (it != data_.cend()) ? std::optional(it->second) : std::nullopt; } template<typename T, REQUIRES(std::is_convertible_v<T, Value>)> std::pair<Value, bool> getOrInsert(const Key& key, T&& value) { std::lock_guard lock(mutex_); auto it = findValue(key); if (it == data_.end()) { data_.emplace_front(key, std::forward<T>(value)); return { data_.begin()->second, true }; } return { it->second, false }; } void remove(const Key& key) { std::lock_guard lock(mutex_); data_.remove_if([&key](const auto& pair) { return std::invoke(KeyEqual(), pair.first, key); }); } private: auto findValue(const Key& key) const { return std::find_if(data_.begin(), data_.end(), [&key](const auto& pair) { return std::invoke(KeyEqual(), pair.first, key); }); } private: mutable std::shared_mutex mutex_; std::forward_list<std::pair<Key, Value>> data_; }; public: /** * @brief Constructor. * @param bucketCount the number of the buckets containing the data of the map * @warning The bucketCount is fixed and there aren't rehashing. */ explicit HashMap(size_t bucketCount = YQUEUE_HASHMAP_BUCKETS) : buckets_(bucketCount > 0 ? bucketCount : std::thread::hardware_concurrency()) {} /** * @brief Returns the requested value or inserts it if the value isn't found. * @param key the key * @param value the inserted value * @return [value, true] if the value was inserted or [value, false] if it was found in the map * @warning The return value is a copy of the value in the map. */ template<typename T, REQUIRES(std::is_convertible_v<T, Value>)> std::pair<Value, bool> getOrInsert(const Key& key, T&& value) { return bucket(key).getOrInsert(key, std::forward<T>(value)); } /** * @brief Looks for a value by the given key. * @param key the key * @return value if it exists or std::nullopt otherwise * @warning The return value is a copy of the value in the map. */ std::optional<Value> find(const Key& key) const { return bucket(key).find(key); } /** * @brief Removes the value if the given key exists. */ void remove(const Key& key) { bucket(key).remove(key); } private: Bucket& bucket(const Key& key) { return buckets_[std::invoke(Hash(), key) % buckets_.size()];; } const Bucket& bucket(const Key& key) const { return buckets_[std::invoke(Hash(), key) % buckets_.size()]; } private: std::vector<Bucket> buckets_; }; }
ksk-/yqueue
src/YQueue/Defines.h
<gh_stars>0 #pragma once namespace YQueue { /** * @enum Concurrency * @brief Defines concurrency models. */ enum class Concurrency : uint8_t { Threads = 0, /*!< thread-based concurrency */ Fibers = 1, /*!< fiber-based concurrency (see the Boost.Fiber library) */ }; }
ksk-/yqueue
src/YQueue/TypeTraits.h
#pragma once #include <type_traits> #define REQUIRES(...) typename = std::enable_if_t<__VA_ARGS__> #define EXISTS(type, expression) std::enable_if_t<std::is_same_v<type, decltype(expression)>> namespace YQueue::type_traits { /** * @brief Determines if the Callable is a stateless functional object that can be invoked with the given arguments. */ template<typename Callable, typename... Ts> struct is_stateless_callable : std::bool_constant< std::is_invocable_v<Callable, Ts...> && std::is_nothrow_default_constructible_v<Callable> && std::is_empty_v<Callable> > {}; template<typename Callable, typename... Ts> constexpr bool is_stateless_callable_v = is_stateless_callable<Callable, Ts...>::value; /** * @brief Determines if the Callable is a stateless functional object with the given signature. */ template<typename R, typename Callable, typename... Ts> struct is_stateless_callable_r : std::bool_constant< std::is_invocable_r_v<R, Callable, Ts...> && std::is_nothrow_default_constructible_v<Callable> && std::is_empty_v<Callable> > {}; template<typename R, typename Callable, typename... Ts> constexpr bool is_stateless_callable_r_v = is_stateless_callable_r<R, Callable, Ts...>::value; /** * @brief Determines if the Class has the set_capacity() method. */ template<typename Class, typename = void> struct has_set_capacity : std::false_type {}; template<typename Class> struct has_set_capacity< Class, std::void_t< EXISTS(void, std::declval<Class>().set_capacity(std::declval<typename Class::capacity_type>())) > > : std::true_type {}; template<typename T> constexpr bool has_set_capacity_v = has_set_capacity<T>::value; }
ksk-/yqueue
src/YQueue/FConsumer.h
#pragma once #include <functional> #include <YQueue/IConsumer.h> #include <YQueue/TypeTraits.h> namespace YQueue { /** * @class FConsumer * @brief Functional implementation of IConsumer. */ template<typename Key, typename Value> class FConsumer final : public IConsumer<Key, Value> { public: /** * @brief Constructor. * @param callable the consumer callable */ template<typename Callable, REQUIRES(std::is_invocable_v<Callable, Key, Value>)> FConsumer(Callable&& callable) : callable_(std::forward<Callable>(callable)) {} void consume(const Key& key, const Value& value) override { std::invoke(callable_, key, value); } void consume(const Key& key, Value&& value) override { std::invoke(callable_, key, std::move(value)); } private: std::function<void(const Key&, Value)> callable_; }; }
ksk-/yqueue
tests/Testing.h
#pragma once #include <thread> #include <boost/noncopyable.hpp> #include <boost/test/included/unit_test.hpp> // NOTE: This is a requirement of Boost.Test. namespace std { template<typename Key, typename Value> inline std::ostream& operator<<(std::ostream& out, const std::pair<Key, Value>& pair) { return out << "[ " << pair.first << " , " << pair.second << " ]"; } } namespace Testing { using Action = std::function<void(size_t)>; class ThreadSafetyTest final : private boost::noncopyable { public: ThreadSafetyTest& runAction(size_t threadCount, Action action) { for (size_t index = 0; index < threadCount; ++index) { threads_.emplace_back(action, index); } return *this; } void wait() { std::for_each(threads_.begin(), threads_.end(), std::mem_fn(&std::thread::join)); } private: std::vector<std::thread> threads_; }; template<bool expression> void checkExpression() { BOOST_CHECK(expression); } template<typename C1, typename C2> void checkEqualCollections(const C1& expected, const C2& actual) { BOOST_CHECK_EQUAL_COLLECTIONS( std::cbegin(expected), std::cend(expected), std::cbegin(actual), std::cend(actual) ); } }
ksk-/yqueue
src/YQueue/Processor.h
<reponame>ksk-/yqueue<gh_stars>0 #pragma once #include <boost/asio/post.hpp> #include <boost/asio/thread_pool.hpp> #include <boost/circular_buffer.hpp> #include <boost/fiber/all.hpp> #include <boost/noncopyable.hpp> #include <boost/signals2.hpp> #include <YQueue/HashMap.h> #include <YQueue/IConsumer.h> #include <YQueue/TypeTraits.h> #include <YQueue/Queue.h> #include <YQueue/Utils.h> namespace YQueue { template< typename Key, typename Value, typename QueueType = Queue<Value, boost::circular_buffer<Value>, Concurrency::Fibers>, REQUIRES(std::is_copy_constructible_v<Key>), REQUIRES(std::is_copy_constructible_v<Value>), REQUIRES(QueueType::concurrency == Concurrency::Fibers) > /** * @class Processor * @brief The queues processor * @tparam Key queue identifier type (key) * @tparam Value queued values type * @tparam Capacity the capacity of the queues */ class Processor final : boost::noncopyable { public: /** * @brief Constructor. * @param threadCount number of processing threads * @note If the threadCount equal to 0 will be use thr number of concurrent threads supported on the platform. */ explicit Processor(size_t threadCount = YQUEUE_PROCESSOR_THREADS) : isRunning_(false) , maxThreadCount_(threadCount > 0 ? threadCount : std::thread::hardware_concurrency()) {} /** * @brief Destructor. * @note The processing will be stopped before the destruction. */ ~Processor() { stop(); } /** * @brief Dequeues a value from the given queue. * @param key the key of the queue * @note The queue will be created if it isn't exists. * @return a valued optional if the value was dequeued successfully, std::nullopt - otherwise */ std::optional<Value> dequeue(const Key& key) { auto queue = queues_.find(key); return queue.has_value() ? queue.value()->dequeue() : std::nullopt; } /** * @brief Enqueues the given value into the given queue. * @param key the key of the queue * @param value the value * @note The queue will be created if it isn't exists. * @return true if the value was enqueued successfully, false - otherwise */ template<typename T, REQUIRES(std::is_convertible_v<T, Value>)> bool enqueue(const Key& key, T&& value) { auto&& [queue, _] = queues_.getOrInsert(key, std::make_shared<QueueType>()); return queue->enqueue(std::forward<T>(value)); } /** * @brief Starts the processing. */ void start() { std::lock_guard lock(mutex_); if (!isRunning_) { start_p(); } } /** * @brief Stops the processing. */ void stop() { std::lock_guard lock(mutex_); if (isRunning_) { stop_p(); } } /** * @brief Subscribes the given consumer to the given queue. * @param key the key of the queue * @param consumer the consumer * @note The queue will be created if it isn't exists. * @warning Only one consumer can be subscribed to the queue. * @return true if the consumer was subscribed successfully, false - otherwise */ bool subscribe(const Key& key, std::shared_ptr<IConsumer<Key, Value>> consumer) { bool inserted = false; std::lock_guard lock(mutex_); if (!Utils::contains(consumers_, key)) { if (isRunning_) { stop_p(); std::tie(std::ignore, inserted) = consumers_.try_emplace(key, std::move(consumer)); start_p(); } else { std::tie(std::ignore, inserted) = consumers_.try_emplace(key, std::move(consumer)); } if (inserted) { auto&& [queue, _] = queues_.getOrInsert(key, std::make_shared<QueueType>()); onStopped_.connect([queue] { queue->disableWaiting(); }); queue->enableWaiting(); } } return inserted; } /** * @brief Unsubscribes the consumer from the given queue. * @param key the key of the queue * @return true if the consumer was unsubscribed successfully, false if there wasn't any subscriber */ bool unsubscribe(const Key& key) { bool removed = false; std::lock_guard lock(mutex_); if (isRunning_) { stop_p(); removed = consumers_.erase(key) > 0; start_p(); } else { removed = consumers_.erase(key) > 0; } return removed; } private: template<typename Consumers> void runConsumers(const Consumers& consumers) { std::vector<boost::fibers::fiber> fibers; for (auto&& [key, consumer] : consumers) { fibers.emplace_back([&key, consumer, this] { auto&& [queue, _] = queues_.getOrInsert(key, std::make_shared<QueueType>()); while (isRunning_) { boost::this_fiber::yield(); queue->consumeAll([&](auto&& value) { consumer->consume(key, std::forward<decltype(value)>(value)); }); } }); } std::for_each(fibers.begin(), fibers.end(), std::mem_fn(&boost::fibers::fiber::join)); } void start_p() { isRunning_ = true; const size_t threadCount = std::min(maxThreadCount_, consumers_.size()); threadPool_.emplace(threadCount); auto consumers = Utils::splitToChunks(consumers_.cbegin(), consumers_.cend(), threadCount); for (size_t i = 0; i < threadCount; ++i) { boost::asio::post(threadPool_.value(), [this, consumers = std::move(consumers[i])] { runConsumers(consumers); }); } } void stop_p() { isRunning_ = false; std::invoke(onStopped_); threadPool_->wait(); threadPool_.reset(); } private: bool isRunning_; boost::signals2::signal<void()> onStopped_; size_t maxThreadCount_; std::optional<boost::asio::thread_pool> threadPool_; HashMap<Key, std::shared_ptr<QueueType>> queues_; std::mutex mutex_; std::unordered_map<Key, std::shared_ptr<IConsumer<Key, Value>>> consumers_; }; }
ksk-/yqueue
src/YQueue/Utils.h
<filename>src/YQueue/Utils.h #pragma once #include <algorithm> #include <vector> #include <YQueue/TypeTraits.h> namespace YQueue::Utils { /** * @brief Checks if the map contains an element with the given key. * @tparam Map the map type * @tparam Key the key type */ template<typename Map, typename Key, REQUIRES(std::is_convertible_v<Key, typename Map::key_type>)> bool contains(const Map& map, const Key& key) { return map.find(key) != map.cend(); } /** * @brief Splits the sequence into chunks. * @warning All elements of the sequence will be copied into chunks. * @tparam InputIterator sequence iterator type * @param first an iterator that points to the beginning of the sequence * @param last an iterator pointing to the end of the sequence * @param count number of chunks * @return vector of the chunks */ template<typename InputIterator> auto splitToChunks(InputIterator first, InputIterator last, size_t count) { using value_type = typename std::iterator_traits<InputIterator>::value_type; std::vector<std::vector<value_type>> chunks(count); std::for_each(first, last, [&chunks, count, index = 0](const value_type& value) mutable { chunks[index % count].emplace_back(value); ++index; }); return chunks; } }
ksk-/yqueue
src/YQueue/IConsumer.h
#pragma once namespace YQueue { /** * @interface IConsumer * @brief The interface of queue consumers. * @tparam Key queue identifier type (key) * @tparam Value consumed values type */ template<typename Key, typename Value> struct IConsumer { virtual ~IConsumer() = default; /** * @brief Consumes the value from the given queue. * @param key the key of the queue * @param value the consumed value (lvalue reference) */ virtual void consume(const Key& key, const Value& value) = 0; /** * @brief Consumes the value from the given queue. * @param key the key of the queue * @param value the consumed value (rvalue reference) */ virtual void consume(const Key& key, Value&& value) = 0; }; }
SYY-Robot/kubot_ros
tools/libfreenect2/tools/streamer_recorder/include/streamer.h
/* * This file is part of the OpenKinect Project. http://www.openkinect.org * * Copyright (c) 2017 individual OpenKinect contributors. See the CONTRIB file * for details. * * This code is licensed to you under the terms of the Apache License, version * 2.0, or, at your option, the terms of the GNU General Public License, * version 2.0. See the APACHE20 and GPL2 files for the text of the licenses, * or the following URLs: * http://www.apache.org/licenses/LICENSE-2.0 * http://www.gnu.org/licenses/gpl-2.0.txt * * If you redistribute this file in source form, modified or unmodified, you * may: * 1) Leave this header intact and distribute it under the same terms, * accompanying it with the APACHE20 and GPL20 files, or * 2) Delete the Apache 2.0 clause and accompany it with the GPL2 file, or * 3) Delete the GPL v2 clause and accompany it with the APACHE20 file * In all cases you must keep the copyright notice intact and include a copy * of the CONTRIB file. * * Binary distributions must follow the binary distribution requirements of * either License. */ #ifndef STREAMER_H #define STREAMER_H #include <libfreenect2/frame_listener.hpp> #include "PracticalSocket.h" #include <opencv2/opencv.hpp> #include "config.h" class Streamer { public: // methods void initialize(); void stream(libfreenect2::Frame* frame); private: // frame related parameters int jpegqual; // Compression Parameter vector<int> compression_params; vector<unsigned char> encoded; int total_pack; int ibuf[1]; // udp related parameters string servAddress; // Server IP adress unsigned short servPort; // Server port UDPSocket sock; }; #endif
SYY-Robot/kubot_ros
tools/libfreenect2/platform/android/libfreenect2/config.h
#ifndef LIBFREENECT2_CONFIG_H #define LIBFREENECT2_CONFIG_H #define LIBFREENECT2_VERSION "0.2.0" #define LIBFREENECT2_API_VERSION ((0 << 16) | 2) #define LIBFREENECT2_PACK( __Declaration__ ) __Declaration__ __attribute__((__packed__)) #define LIBFREENECT2_API __attribute__((visibility("default"))) #define LIBFREENECT2_WITH_TURBOJPEG_SUPPORT #define LIBFREENECT2_THREADING_STDLIB #define LIBFREENECT2_WITH_CXX11_SUPPORT #endif // LIBFREENECT2_CONFIG_H
SYY-Robot/kubot_ros
tools/libfreenect2/include/libfreenect2/led_settings.h
/* * This file is part of the OpenKinect Project. http://www.openkinect.org * * Copyright (c) 2011 individual OpenKinect contributors. See the CONTRIB file * for details. * * This code is licensed to you under the terms of the Apache License, version * 2.0, or, at your option, the terms of the GNU General Public License, * version 2.0. See the APACHE20 and GPL2 files for the text of the licenses, * or the following URLs: * http://www.apache.org/licenses/LICENSE-2.0 * http://www.gnu.org/licenses/gpl-2.0.txt * * If you redistribute this file in source form, modified or unmodified, you * may: * 1) Leave this header intact and distribute it under the same terms, * accompanying it with the APACHE20 and GPL20 files, or * 2) Delete the Apache 2.0 clause and accompany it with the GPL2 file, or * 3) Delete the GPL v2 clause and accompany it with the APACHE20 file * In all cases you must keep the copyright notice intact and include a copy * of the CONTRIB file. * * Binary distributions must follow the binary distribution requirements of * either License. */ #ifndef LED_SETTINGS_H_ #define LED_SETTINGS_H_ namespace libfreenect2 { // The following information was found by using the library released by Microsoft under MIT license, // https://github.com/Microsoft/MixedRealityCompanionKit/tree/master/KinectIPD/NuiSensor // Debugging the library assembly shows the original struct name was _PETRA_LED_STATE. struct LedSettings { uint16_t LedId; // LED index [0, 1] uint16_t Mode; // 0 = constant, 1 = blink between StartLevel, StopLevel every IntervalInMs ms uint16_t StartLevel; // LED intensity [0, 1000] uint16_t StopLevel; // LED intensity [0, 1000] uint32_t IntervalInMs; // Blink interval for Mode=1 in milliseconds uint32_t Reserved; // 0 }; } /* namespace libfreenect2 */ #endif /* LED_SETTINGS_H_ */
SYY-Robot/kubot_ros
tools/libfreenect2/include/libfreenect2/color_settings.h
<gh_stars>1-10 /* * This file is part of the OpenKinect Project. http://www.openkinect.org * * Copyright (c) 2011 individual OpenKinect contributors. See the CONTRIB file * for details. * * This code is licensed to you under the terms of the Apache License, version * 2.0, or, at your option, the terms of the GNU General Public License, * version 2.0. See the APACHE20 and GPL2 files for the text of the licenses, * or the following URLs: * http://www.apache.org/licenses/LICENSE-2.0 * http://www.gnu.org/licenses/gpl-2.0.txt * * If you redistribute this file in source form, modified or unmodified, you * may: * 1) Leave this header intact and distribute it under the same terms, * accompanying it with the APACHE20 and GPL20 files, or * 2) Delete the Apache 2.0 clause and accompany it with the GPL2 file, or * 3) Delete the GPL v2 clause and accompany it with the APACHE20 file * In all cases you must keep the copyright notice intact and include a copy * of the CONTRIB file. * * Binary distributions must follow the binary distribution requirements of * either License. */ #ifndef COLOR_SETTINGS_H_ #define COLOR_SETTINGS_H_ namespace libfreenect2 { // The following information was found by using the library released by Microsoft under MIT license, // https://github.com/Microsoft/MixedRealityCompanionKit/tree/master/KinectIPD/NuiSensor enum ColorSettingCommandType { COLOR_SETTING_SET_EXPOSURE_MODE = 0, COLOR_SETTING_SET_INTEGRATION_TIME = 1, COLOR_SETTING_GET_INTEGRATION_TIME = 2, COLOR_SETTING_SET_WHITE_BALANCE_MODE = 10, COLOR_SETTING_SET_RED_CHANNEL_GAIN = 11, COLOR_SETTING_SET_GREEN_CHANNEL_GAIN = 12, COLOR_SETTING_SET_BLUE_CHANNEL_GAIN = 13, COLOR_SETTING_GET_RED_CHANNEL_GAIN = 14, COLOR_SETTING_GET_GREEN_CHANNEL_GAIN = 15, COLOR_SETTING_GET_BLUE_CHANNEL_GAIN = 16, COLOR_SETTING_SET_EXPOSURE_TIME_MS = 17, COLOR_SETTING_GET_EXPOSURE_TIME_MS = 18, COLOR_SETTING_SET_DIGITAL_GAIN = 19, COLOR_SETTING_GET_DIGITAL_GAIN = 20, COLOR_SETTING_SET_ANALOG_GAIN = 21, COLOR_SETTING_GET_ANALOG_GAIN = 22, COLOR_SETTING_SET_EXPOSURE_COMPENSATION = 23, COLOR_SETTING_GET_EXPOSURE_COMPENSATION = 24, COLOR_SETTING_SET_ACS = 25, COLOR_SETTING_GET_ACS = 26, COLOR_SETTING_SET_EXPOSURE_METERING_MODE = 27, COLOR_SETTING_SET_EXPOSURE_METERING_ZONES = 28, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_0_WEIGHT = 29, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_1_WEIGHT = 30, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_2_WEIGHT = 31, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_3_WEIGHT = 32, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_4_WEIGHT = 33, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_5_WEIGHT = 34, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_6_WEIGHT = 35, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_7_WEIGHT = 36, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_8_WEIGHT = 37, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_9_WEIGHT = 38, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_10_WEIGHT = 39, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_11_WEIGHT = 40, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_12_WEIGHT = 41, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_13_WEIGHT = 42, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_14_WEIGHT = 43, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_15_WEIGHT = 44, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_16_WEIGHT = 45, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_17_WEIGHT = 46, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_18_WEIGHT = 47, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_19_WEIGHT = 48, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_20_WEIGHT = 49, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_21_WEIGHT = 50, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_22_WEIGHT = 51, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_23_WEIGHT = 52, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_24_WEIGHT = 53, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_25_WEIGHT = 54, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_26_WEIGHT = 55, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_27_WEIGHT = 56, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_28_WEIGHT = 57, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_29_WEIGHT = 58, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_30_WEIGHT = 59, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_31_WEIGHT = 60, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_32_WEIGHT = 61, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_33_WEIGHT = 62, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_34_WEIGHT = 63, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_35_WEIGHT = 64, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_36_WEIGHT = 65, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_37_WEIGHT = 66, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_38_WEIGHT = 67, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_39_WEIGHT = 68, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_40_WEIGHT = 69, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_41_WEIGHT = 70, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_42_WEIGHT = 71, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_43_WEIGHT = 72, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_44_WEIGHT = 73, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_45_WEIGHT = 74, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_46_WEIGHT = 75, COLOR_SETTING_SET_EXPOSURE_METERING_ZONE_47_WEIGHT = 76, COLOR_SETTING_SET_MAX_ANALOG_GAIN_CAP = 77, COLOR_SETTING_SET_MAX_DIGITAL_GAIN_CAP = 78, COLOR_SETTING_SET_FLICKER_FREE_FREQUENCY = 79, COLOR_SETTING_GET_EXPOSURE_MODE = 80, COLOR_SETTING_GET_WHITE_BALANCE_MODE = 81, COLOR_SETTING_SET_FRAME_RATE = 82, COLOR_SETTING_GET_FRAME_RATE = 83, }; } /* namespace libfreenect2 */ #endif /* COLOR_SETTINGS_H_ */
SYY-Robot/kubot_ros
tools/libfreenect2/tools/streamer_recorder/include/recorder.h
/* * This file is part of the OpenKinect Project. http://www.openkinect.org * * Copyright (c) 2017 individual OpenKinect contributors. See the CONTRIB file * for details. * * This code is licensed to you under the terms of the Apache License, version * 2.0, or, at your option, the terms of the GNU General Public License, * version 2.0. See the APACHE20 and GPL2 files for the text of the licenses, * or the following URLs: * http://www.apache.org/licenses/LICENSE-2.0 * http://www.gnu.org/licenses/gpl-2.0.txt * * If you redistribute this file in source form, modified or unmodified, you * may: * 1) Leave this header intact and distribute it under the same terms, * accompanying it with the APACHE20 and GPL20 files, or * 2) Delete the Apache 2.0 clause and accompany it with the GPL2 file, or * 3) Delete the GPL v2 clause and accompany it with the APACHE20 file * In all cases you must keep the copyright notice intact and include a copy * of the CONTRIB file. * * Binary distributions must follow the binary distribution requirements of * either License. */ #ifndef RECORDER_H #define RECORDER_H #include <libfreenect2/frame_listener.hpp> #include <opencv2/opencv.hpp> #include "config.h" #include <iomanip> #include <sstream> #include <string> #include <vector> #include <fstream> // file input/output functions #include <cstdlib> // time stamp #include <sys/timeb.h> // time stamp class Recorder { public: // methods Recorder(); void initialize(); void record(libfreenect2::Frame* frame, const std::string& frame_type); void stream(libfreenect2::Frame* frame); void saveTimeStamp(); void registTimeStamp(); private: /////// RECORD VIDEO, NOT READY YET (RECORD IMAGE FOR NOW) /////// // cv::VideoWriter out_capture; ///////////////////////////////////////////////////////////////// cv::Mat cvMat_frame; // SAVE IMAGE //cv::vector<int> img_comp_param; //vector that stores the compression parameters of the image std::vector<int> img_comp_param; //vector that stores the compression parameters of the image int frameID; // int maxFrameID; // 16.6min max at 30 FPS (max frame ID sort of hardcoded in image naming too, see below) // static int timeStamps [MAX_FRAME_ID]; std::vector<int> timeStamps; int t_start; int t_now; std::ostringstream oss_recordPath; std::string recordPath; // ----------------- // Timer timeb tb; int nSpan; int getMilliSpan(int nTimeStart); int getMilliCount(); }; #endif
SYY-Robot/kubot_ros
tools/libfreenect2/include/internal/libfreenect2/protocol/command.h
/* * This file is part of the OpenKinect Project. http://www.openkinect.org * * Copyright (c) 2011 individual OpenKinect contributors. See the CONTRIB file * for details. * * This code is licensed to you under the terms of the Apache License, version * 2.0, or, at your option, the terms of the GNU General Public License, * version 2.0. See the APACHE20 and GPL2 files for the text of the licenses, * or the following URLs: * http://www.apache.org/licenses/LICENSE-2.0 * http://www.gnu.org/licenses/gpl-2.0.txt * * If you redistribute this file in source form, modified or unmodified, you * may: * 1) Leave this header intact and distribute it under the same terms, * accompanying it with the APACHE20 and GPL20 files, or * 2) Delete the Apache 2.0 clause and accompany it with the GPL2 file, or * 3) Delete the GPL v2 clause and accompany it with the APACHE20 file * In all cases you must keep the copyright notice intact and include a copy * of the CONTRIB file. * * Binary distributions must follow the binary distribution requirements of * either License. */ #ifndef COMMAND_H_ #define COMMAND_H_ #include <stdint.h> #include <cstring> #include "libfreenect2/protocol/response.h" #include "libfreenect2/led_settings.h" #define KCMD_READ_FIRMWARE_VERSIONS 0x02 #define KCMD_INIT_STREAMS 0x09 #define KCMD_READ_HARDWARE_INFO 0x14 #define KCMD_READ_STATUS 0x16 #define KCMD_READ_DATA_PAGE 0x22 #define KCMD_READ_DATA_0x26 0x26 #define KCMD_SET_STREAMING 0x2B #define KCMD_SET_MODE 0x4B #define KCMD_RGB_SETTING 0x3E // Command value for color camera settings #define KCMD_LED_SETTING 0x4B #define KCMD_0x46 0x46 #define KCMD_0x47 0x47 // observed in sensor stop/shutdown sequence #define KCMD_STOP 0x0A #define KCMD_SHUTDOWN 0x00 namespace libfreenect2 { namespace protocol { template<int NParam> struct CommandData { uint32_t magic; uint32_t sequence; uint32_t max_response_length; uint32_t command; uint32_t reserved0; uint32_t parameters[NParam]; CommandData() { for(int i = 0; i < NParam; ++i) parameters[i] = 0; } }; template<> struct CommandData<0> { uint32_t magic; uint32_t sequence; uint32_t max_response_length; uint32_t command; uint32_t reserved0; }; struct CommandBase { virtual ~CommandBase() {} virtual uint32_t sequence() const = 0; virtual uint32_t maxResponseLength() const = 0; virtual uint32_t minResponseLength() const = 0; virtual const uint8_t *data() const = 0; virtual uint32_t size() const = 0; }; template<uint32_t CommandId, uint32_t MaxResponseLength, uint32_t MinResponseLength, uint32_t NParam> class Command : public CommandBase { public: typedef CommandData<NParam> Data; static const uint32_t MagicNumber = 0x06022009; static const uint32_t Size = sizeof(Data); uint32_t min_response_length; Command(uint32_t seq) { data_.magic = MagicNumber; data_.sequence = seq; data_.max_response_length = MaxResponseLength; data_.command = CommandId; data_.reserved0 = 0; min_response_length = MinResponseLength; } virtual ~Command() { } virtual uint32_t sequence() const { return data_.sequence; } virtual uint32_t maxResponseLength() const { return data_.max_response_length; } virtual uint32_t minResponseLength() const { return min_response_length; } virtual const uint8_t *data() const { return reinterpret_cast<const uint8_t *>(&data_); } virtual uint32_t size() const { return Size; } protected: Data data_; }; template<uint32_t CommandId, uint32_t MaxResponseLength> struct CommandWith0Params : public Command<CommandId, MaxResponseLength, MaxResponseLength, 0> { CommandWith0Params(uint32_t seq) : Command<CommandId, MaxResponseLength, MaxResponseLength, 0>(seq) { } }; template<uint32_t CommandId, uint32_t MaxResponseLength, uint32_t Param1> struct CommandWith1Param : public Command<CommandId, MaxResponseLength, MaxResponseLength, 1> { CommandWith1Param(uint32_t seq) : Command<CommandId, MaxResponseLength, MaxResponseLength, 1>(seq) { this->data_.parameters[0] = Param1; } }; template<uint32_t CommandId, uint32_t MaxResponseLength, uint32_t MinResponseLength, uint32_t Param1> struct CommandWith1ParamLarge : public Command<CommandId, MaxResponseLength, MinResponseLength, 1> { CommandWith1ParamLarge(uint32_t seq) : Command<CommandId, MaxResponseLength, MinResponseLength, 1>(seq) { this->data_.parameters[0] = Param1; } }; template<uint32_t CommandId, uint32_t MaxResponseLength, uint32_t Param1, uint32_t Param2 = 0, uint32_t Param3 = 0, uint32_t Param4 = 0> struct CommandWith4Params : public Command<CommandId, MaxResponseLength, MaxResponseLength, 4> { CommandWith4Params(uint32_t seq) : Command<CommandId, MaxResponseLength, MaxResponseLength, 4>(seq) { this->data_.parameters[0] = Param1; this->data_.parameters[1] = Param2; this->data_.parameters[2] = Param3; this->data_.parameters[3] = Param4; } }; typedef CommandWith0Params<0x02, 0x200> ReadFirmwareVersionsCommand; typedef CommandWith0Params<KCMD_READ_HARDWARE_INFO, 0x5C> ReadHardwareInfoCommand; typedef CommandWith0Params<KCMD_INIT_STREAMS, 0x00> InitStreamsCommand; typedef CommandWith1Param<KCMD_READ_DATA_PAGE, 0x80, 0x01> ReadSerialNumberCommand; typedef CommandWith1ParamLarge<KCMD_READ_DATA_PAGE, 0x1C0000, sizeof(P0TablesResponse), 0x02> ReadP0TablesCommand; typedef CommandWith1ParamLarge<KCMD_READ_DATA_PAGE, 0x1C0000, sizeof(DepthCameraParamsResponse), 0x03> ReadDepthCameraParametersCommand; typedef CommandWith1ParamLarge<KCMD_READ_DATA_PAGE, 0x1C0000, sizeof(RgbCameraParamsResponse), 0x04> ReadRgbCameraParametersCommand; typedef CommandWith1Param<KCMD_READ_STATUS, 0x04, 0x090000> ReadStatus0x090000Command; typedef CommandWith1Param<KCMD_READ_STATUS, 0x04, 0x100007> ReadStatus0x100007Command; // TODO: are they ever used?! typedef CommandWith1Param<KCMD_READ_STATUS, 0x04, 0x02006F> ReadStatus0x02006FCommand; typedef CommandWith1Param<KCMD_READ_STATUS, 0x04, 0x020070> ReadStatus0x020070Command; // TODO: is the following actually correct? typedef CommandWith0Params<KCMD_READ_DATA_0x26, 0x10> ReadData0x26Command; //typedef CommandWith1Param<KCMD_READ_DATA_0x26, 0x10, 0x00> ReadData0x26_0x00Command; typedef CommandWith1Param<KCMD_SET_STREAMING, 0x00, 0x00> SetStreamDisabledCommand; typedef CommandWith1Param<KCMD_SET_STREAMING, 0x00, 0x01> SetStreamEnabledCommand; // TODO: are they ever used?! typedef CommandWith4Params<KCMD_0x46, 0x00, 0x00, 0x00003840, 0x00000037, 0x00> Unknown0x46Command; typedef CommandWith0Params<KCMD_0x47, 0x10> Unknown0x47Command; typedef CommandWith0Params<KCMD_STOP, 0x00> StopCommand; typedef CommandWith0Params<KCMD_SHUTDOWN, 0x00> ShutdownCommand; typedef CommandWith4Params<KCMD_SET_MODE, 0x00, 0x00> SetModeDisabledCommand; typedef CommandWith4Params<KCMD_SET_MODE, 0x00, 0x01> SetModeEnabledCommand; typedef CommandWith4Params<KCMD_SET_MODE, 0x00, 0x01, 0x00640064> SetModeEnabledWith0x00640064Command; typedef CommandWith4Params<KCMD_SET_MODE, 0x00, 0x01, 0x00500050> SetModeEnabledWith0x00500050Command; // The following information was found by using the library released by Microsoft under MIT license, // https://github.com/Microsoft/MixedRealityCompanionKit/tree/master/KinectIPD/NuiSensor // Command values come from headers, packet CommandId from stepping through assembly in NuiSensorLib.lib #define ColorSettingResponseSize sizeof(ColorSettingResponse) struct ColorSettingCommand : public Command<KCMD_RGB_SETTING, ColorSettingResponseSize, ColorSettingResponseSize, 4> { ColorSettingCommand(ColorSettingCommandType cmd, uint32_t value = 0) : Command<KCMD_RGB_SETTING, ColorSettingResponseSize, ColorSettingResponseSize, 4>(0) // seq always zero { // Data parameters are elements of struct NUISENSOR_RGB_CHANGE_STREAM_SETTING // which supports multiple settings for a single call. this->data_.parameters[0] = 1; // NumCommands = 1 for single command this->data_.parameters[1] = 0; // SequenceId = 0 for RGB commands this->data_.parameters[2] = (uint32_t)cmd; // Cmd with a value from NUISENSOR_RGB_COMMAND_* this->data_.parameters[3] = value; // Arg is int or float depending on Cmd, zero for GET_* } // Could overload ctor to ease usage for float-valued settings. ColorSettingCommand(ColorSettingCommandType cmd, float value) : Command<KCMD_RGB_SETTING, ColorSettingResponseSize, ColorSettingResponseSize, 4>(0) { this->data_.parameters[0] = 1; this->data_.parameters[1] = 0; this->data_.parameters[2] = (uint32_t)cmd; uint32_t value2; memcpy(&value2, &value, sizeof(value2)); this->data_.parameters[3] = value2; } }; #define LedSettingResponseSize 0 struct LedSettingCommand : public libfreenect2::protocol::Command<KCMD_LED_SETTING, LedSettingResponseSize, LedSettingResponseSize, 4> { LedSettingCommand(LedSettings led) : Command<KCMD_LED_SETTING, LedSettingResponseSize, LedSettingResponseSize, 4>(0) // seq always zero { memcpy(this->data_.parameters, &led, sizeof(led)); } }; } /* namespace protocol */ } /* namespace libfreenect2 */ #endif /* COMMAND_H_ */
rixo/tree-sitter-svelte-atom
src/parser.c
#include <tree_sitter/parser.h> #if defined(__GNUC__) || defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmissing-field-initializers" #endif #define LANGUAGE_VERSION 12 #define STATE_COUNT 276 #define LARGE_STATE_COUNT 2 #define SYMBOL_COUNT 86 #define ALIAS_COUNT 1 #define TOKEN_COUNT 41 #define EXTERNAL_TOKEN_COUNT 12 #define FIELD_COUNT 0 #define MAX_ALIAS_SEQUENCE_LENGTH 7 enum { anon_sym_LT = 1, anon_sym_GT = 2, anon_sym_SLASH_GT = 3, anon_sym_LT_SLASH = 4, anon_sym_EQ = 5, aux_sym_attribute_name_token1 = 6, anon_sym_SQUOTE = 7, aux_sym_quoted_attribute_value_token1 = 8, anon_sym_DQUOTE = 9, aux_sym_quoted_attribute_value_token2 = 10, aux_sym__text_token1 = 11, anon_sym_LBRACE_RBRACE = 12, anon_sym_LBRACE = 13, anon_sym_RBRACE = 14, anon_sym_AT = 15, anon_sym_html = 16, anon_sym_debug = 17, anon_sym_const = 18, anon_sym_POUND = 19, anon_sym_if = 20, anon_sym_COLON = 21, anon_sym_else = 22, anon_sym_SLASH = 23, anon_sym_each = 24, anon_sym_as = 25, anon_sym_await = 26, anon_sym_then = 27, anon_sym_catch = 28, anon_sym_key = 29, sym__start_tag_name = 30, sym__script_start_tag_name = 31, sym__style_start_tag_name = 32, sym__end_tag_name = 33, sym_erroneous_end_tag_name = 34, sym__implicit_end_tag = 35, sym_raw_text = 36, sym_raw_text_expr = 37, sym_raw_text_await = 38, sym_raw_text_each = 39, sym_comment = 40, sym_document = 41, sym__node = 42, sym__statement = 43, sym_element = 44, sym_start_tag = 45, sym_self_closing_tag = 46, sym_end_tag = 47, sym_script_element = 48, sym_script_start_tag = 49, sym_style_element = 50, sym_style_start_tag = 51, sym_attribute = 52, sym_attribute_name = 53, sym_attribute_value = 54, sym_expr_attribute_value = 55, sym_quoted_attribute_value = 56, sym__text = 57, sym__expression = 58, sym_expression = 59, sym_html_expr = 60, sym_debug_expr = 61, sym_const_expr = 62, sym_if_statement = 63, sym_else_if_statement = 64, sym_else_statement = 65, sym_if_start_expr = 66, sym_else_expr = 67, sym_else_if_expr = 68, sym_if_end_expr = 69, sym_each_statement = 70, sym_each_start_expr = 71, sym_else_each_statement = 72, sym_each_end_expr = 73, sym_await_statement = 74, sym_then_statement = 75, sym_catch_statement = 76, sym_await_start_expr = 77, sym_then_expr = 78, sym_catch_expr = 79, sym_await_end_expr = 80, sym_key_statement = 81, sym_key_start_expr = 82, sym_key_end_expr = 83, aux_sym_document_repeat1 = 84, aux_sym_start_tag_repeat1 = 85, alias_sym_then = 86, }; static const char *ts_symbol_names[] = { [ts_builtin_sym_end] = "end", [anon_sym_LT] = "<", [anon_sym_GT] = ">", [anon_sym_SLASH_GT] = "/>", [anon_sym_LT_SLASH] = "</", [anon_sym_EQ] = "=", [aux_sym_attribute_name_token1] = "attribute_name_token1", [anon_sym_SQUOTE] = "'", [aux_sym_quoted_attribute_value_token1] = "attribute_value", [anon_sym_DQUOTE] = "\"", [aux_sym_quoted_attribute_value_token2] = "attribute_value", [aux_sym__text_token1] = "text", [anon_sym_LBRACE_RBRACE] = "expression", [anon_sym_LBRACE] = "{", [anon_sym_RBRACE] = "}", [anon_sym_AT] = "@", [anon_sym_html] = "special_block_keyword", [anon_sym_debug] = "special_block_keyword", [anon_sym_const] = "special_block_keyword", [anon_sym_POUND] = "#", [anon_sym_if] = "special_block_keyword", [anon_sym_COLON] = ":", [anon_sym_else] = "special_block_keyword", [anon_sym_SLASH] = "/", [anon_sym_each] = "special_block_keyword", [anon_sym_as] = "as", [anon_sym_await] = "special_block_keyword", [anon_sym_then] = "special_block_keyword", [anon_sym_catch] = "special_block_keyword", [anon_sym_key] = "special_block_keyword", [sym__start_tag_name] = "tag_name", [sym__script_start_tag_name] = "tag_name", [sym__style_start_tag_name] = "tag_name", [sym__end_tag_name] = "tag_name", [sym_erroneous_end_tag_name] = "erroneous_end_tag_name", [sym__implicit_end_tag] = "_implicit_end_tag", [sym_raw_text] = "raw_text", [sym_raw_text_expr] = "raw_text_expr", [sym_raw_text_await] = "raw_text_await", [sym_raw_text_each] = "raw_text_each", [sym_comment] = "comment", [sym_document] = "document", [sym__node] = "_node", [sym__statement] = "_statement", [sym_element] = "element", [sym_start_tag] = "start_tag", [sym_self_closing_tag] = "self_closing_tag", [sym_end_tag] = "end_tag", [sym_script_element] = "script_element", [sym_script_start_tag] = "start_tag", [sym_style_element] = "style_element", [sym_style_start_tag] = "start_tag", [sym_attribute] = "attribute", [sym_attribute_name] = "attribute_name", [sym_attribute_value] = "attribute_value", [sym_expr_attribute_value] = "expr_attribute_value", [sym_quoted_attribute_value] = "quoted_attribute_value", [sym__text] = "_text", [sym__expression] = "_expression", [sym_expression] = "expression", [sym_html_expr] = "html_expr", [sym_debug_expr] = "debug_expr", [sym_const_expr] = "const_expr", [sym_if_statement] = "if_statement", [sym_else_if_statement] = "else_if_statement", [sym_else_statement] = "else_statement", [sym_if_start_expr] = "if_start_expr", [sym_else_expr] = "else_expr", [sym_else_if_expr] = "else_if_expr", [sym_if_end_expr] = "if_end_expr", [sym_each_statement] = "each_statement", [sym_each_start_expr] = "each_start_expr", [sym_else_each_statement] = "else_each_statement", [sym_each_end_expr] = "each_end_expr", [sym_await_statement] = "await_statement", [sym_then_statement] = "then_statement", [sym_catch_statement] = "catch_statement", [sym_await_start_expr] = "await_start_expr", [sym_then_expr] = "then_expr", [sym_catch_expr] = "catch_expr", [sym_await_end_expr] = "await_end_expr", [sym_key_statement] = "key_statement", [sym_key_start_expr] = "key_start_expr", [sym_key_end_expr] = "key_end_expr", [aux_sym_document_repeat1] = "document_repeat1", [aux_sym_start_tag_repeat1] = "start_tag_repeat1", [alias_sym_then] = "then", }; static TSSymbol ts_symbol_map[] = { [ts_builtin_sym_end] = ts_builtin_sym_end, [anon_sym_LT] = anon_sym_LT, [anon_sym_GT] = anon_sym_GT, [anon_sym_SLASH_GT] = anon_sym_SLASH_GT, [anon_sym_LT_SLASH] = anon_sym_LT_SLASH, [anon_sym_EQ] = anon_sym_EQ, [aux_sym_attribute_name_token1] = aux_sym_attribute_name_token1, [anon_sym_SQUOTE] = anon_sym_SQUOTE, [aux_sym_quoted_attribute_value_token1] = sym_attribute_value, [anon_sym_DQUOTE] = anon_sym_DQUOTE, [aux_sym_quoted_attribute_value_token2] = sym_attribute_value, [aux_sym__text_token1] = aux_sym__text_token1, [anon_sym_LBRACE_RBRACE] = sym_expression, [anon_sym_LBRACE] = anon_sym_LBRACE, [anon_sym_RBRACE] = anon_sym_RBRACE, [anon_sym_AT] = anon_sym_AT, [anon_sym_html] = anon_sym_html, [anon_sym_debug] = anon_sym_html, [anon_sym_const] = anon_sym_html, [anon_sym_POUND] = anon_sym_POUND, [anon_sym_if] = anon_sym_html, [anon_sym_COLON] = anon_sym_COLON, [anon_sym_else] = anon_sym_html, [anon_sym_SLASH] = anon_sym_SLASH, [anon_sym_each] = anon_sym_html, [anon_sym_as] = anon_sym_as, [anon_sym_await] = anon_sym_html, [anon_sym_then] = anon_sym_html, [anon_sym_catch] = anon_sym_html, [anon_sym_key] = anon_sym_html, [sym__start_tag_name] = sym__start_tag_name, [sym__script_start_tag_name] = sym__start_tag_name, [sym__style_start_tag_name] = sym__start_tag_name, [sym__end_tag_name] = sym__start_tag_name, [sym_erroneous_end_tag_name] = sym_erroneous_end_tag_name, [sym__implicit_end_tag] = sym__implicit_end_tag, [sym_raw_text] = sym_raw_text, [sym_raw_text_expr] = sym_raw_text_expr, [sym_raw_text_await] = sym_raw_text_await, [sym_raw_text_each] = sym_raw_text_each, [sym_comment] = sym_comment, [sym_document] = sym_document, [sym__node] = sym__node, [sym__statement] = sym__statement, [sym_element] = sym_element, [sym_start_tag] = sym_start_tag, [sym_self_closing_tag] = sym_self_closing_tag, [sym_end_tag] = sym_end_tag, [sym_script_element] = sym_script_element, [sym_script_start_tag] = sym_start_tag, [sym_style_element] = sym_style_element, [sym_style_start_tag] = sym_start_tag, [sym_attribute] = sym_attribute, [sym_attribute_name] = sym_attribute_name, [sym_attribute_value] = sym_attribute_value, [sym_expr_attribute_value] = sym_expr_attribute_value, [sym_quoted_attribute_value] = sym_quoted_attribute_value, [sym__text] = sym__text, [sym__expression] = sym__expression, [sym_expression] = sym_expression, [sym_html_expr] = sym_html_expr, [sym_debug_expr] = sym_debug_expr, [sym_const_expr] = sym_const_expr, [sym_if_statement] = sym_if_statement, [sym_else_if_statement] = sym_else_if_statement, [sym_else_statement] = sym_else_statement, [sym_if_start_expr] = sym_if_start_expr, [sym_else_expr] = sym_else_expr, [sym_else_if_expr] = sym_else_if_expr, [sym_if_end_expr] = sym_if_end_expr, [sym_each_statement] = sym_each_statement, [sym_each_start_expr] = sym_each_start_expr, [sym_else_each_statement] = sym_else_each_statement, [sym_each_end_expr] = sym_each_end_expr, [sym_await_statement] = sym_await_statement, [sym_then_statement] = sym_then_statement, [sym_catch_statement] = sym_catch_statement, [sym_await_start_expr] = sym_await_start_expr, [sym_then_expr] = sym_then_expr, [sym_catch_expr] = sym_catch_expr, [sym_await_end_expr] = sym_await_end_expr, [sym_key_statement] = sym_key_statement, [sym_key_start_expr] = sym_key_start_expr, [sym_key_end_expr] = sym_key_end_expr, [aux_sym_document_repeat1] = aux_sym_document_repeat1, [aux_sym_start_tag_repeat1] = aux_sym_start_tag_repeat1, [alias_sym_then] = alias_sym_then, }; static const TSSymbolMetadata ts_symbol_metadata[] = { [ts_builtin_sym_end] = { .visible = false, .named = true, }, [anon_sym_LT] = { .visible = true, .named = false, }, [anon_sym_GT] = { .visible = true, .named = false, }, [anon_sym_SLASH_GT] = { .visible = true, .named = false, }, [anon_sym_LT_SLASH] = { .visible = true, .named = false, }, [anon_sym_EQ] = { .visible = true, .named = false, }, [aux_sym_attribute_name_token1] = { .visible = false, .named = false, }, [anon_sym_SQUOTE] = { .visible = true, .named = false, }, [aux_sym_quoted_attribute_value_token1] = { .visible = true, .named = true, }, [anon_sym_DQUOTE] = { .visible = true, .named = false, }, [aux_sym_quoted_attribute_value_token2] = { .visible = true, .named = true, }, [aux_sym__text_token1] = { .visible = true, .named = true, }, [anon_sym_LBRACE_RBRACE] = { .visible = true, .named = true, }, [anon_sym_LBRACE] = { .visible = true, .named = false, }, [anon_sym_RBRACE] = { .visible = true, .named = false, }, [anon_sym_AT] = { .visible = true, .named = false, }, [anon_sym_html] = { .visible = true, .named = true, }, [anon_sym_debug] = { .visible = true, .named = true, }, [anon_sym_const] = { .visible = true, .named = true, }, [anon_sym_POUND] = { .visible = true, .named = false, }, [anon_sym_if] = { .visible = true, .named = true, }, [anon_sym_COLON] = { .visible = true, .named = false, }, [anon_sym_else] = { .visible = true, .named = true, }, [anon_sym_SLASH] = { .visible = true, .named = false, }, [anon_sym_each] = { .visible = true, .named = true, }, [anon_sym_as] = { .visible = true, .named = true, }, [anon_sym_await] = { .visible = true, .named = true, }, [anon_sym_then] = { .visible = true, .named = true, }, [anon_sym_catch] = { .visible = true, .named = true, }, [anon_sym_key] = { .visible = true, .named = true, }, [sym__start_tag_name] = { .visible = true, .named = true, }, [sym__script_start_tag_name] = { .visible = true, .named = true, }, [sym__style_start_tag_name] = { .visible = true, .named = true, }, [sym__end_tag_name] = { .visible = true, .named = true, }, [sym_erroneous_end_tag_name] = { .visible = true, .named = true, }, [sym__implicit_end_tag] = { .visible = false, .named = true, }, [sym_raw_text] = { .visible = true, .named = true, }, [sym_raw_text_expr] = { .visible = true, .named = true, }, [sym_raw_text_await] = { .visible = true, .named = true, }, [sym_raw_text_each] = { .visible = true, .named = true, }, [sym_comment] = { .visible = true, .named = true, }, [sym_document] = { .visible = true, .named = true, }, [sym__node] = { .visible = false, .named = true, }, [sym__statement] = { .visible = false, .named = true, }, [sym_element] = { .visible = true, .named = true, }, [sym_start_tag] = { .visible = true, .named = true, }, [sym_self_closing_tag] = { .visible = true, .named = true, }, [sym_end_tag] = { .visible = true, .named = true, }, [sym_script_element] = { .visible = true, .named = true, }, [sym_script_start_tag] = { .visible = true, .named = true, }, [sym_style_element] = { .visible = true, .named = true, }, [sym_style_start_tag] = { .visible = true, .named = true, }, [sym_attribute] = { .visible = true, .named = true, }, [sym_attribute_name] = { .visible = true, .named = true, }, [sym_attribute_value] = { .visible = true, .named = true, }, [sym_expr_attribute_value] = { .visible = true, .named = true, }, [sym_quoted_attribute_value] = { .visible = true, .named = true, }, [sym__text] = { .visible = false, .named = true, }, [sym__expression] = { .visible = false, .named = true, }, [sym_expression] = { .visible = true, .named = true, }, [sym_html_expr] = { .visible = true, .named = true, }, [sym_debug_expr] = { .visible = true, .named = true, }, [sym_const_expr] = { .visible = true, .named = true, }, [sym_if_statement] = { .visible = true, .named = true, }, [sym_else_if_statement] = { .visible = true, .named = true, }, [sym_else_statement] = { .visible = true, .named = true, }, [sym_if_start_expr] = { .visible = true, .named = true, }, [sym_else_expr] = { .visible = true, .named = true, }, [sym_else_if_expr] = { .visible = true, .named = true, }, [sym_if_end_expr] = { .visible = true, .named = true, }, [sym_each_statement] = { .visible = true, .named = true, }, [sym_each_start_expr] = { .visible = true, .named = true, }, [sym_else_each_statement] = { .visible = true, .named = true, }, [sym_each_end_expr] = { .visible = true, .named = true, }, [sym_await_statement] = { .visible = true, .named = true, }, [sym_then_statement] = { .visible = true, .named = true, }, [sym_catch_statement] = { .visible = true, .named = true, }, [sym_await_start_expr] = { .visible = true, .named = true, }, [sym_then_expr] = { .visible = true, .named = true, }, [sym_catch_expr] = { .visible = true, .named = true, }, [sym_await_end_expr] = { .visible = true, .named = true, }, [sym_key_statement] = { .visible = true, .named = true, }, [sym_key_start_expr] = { .visible = true, .named = true, }, [sym_key_end_expr] = { .visible = true, .named = true, }, [aux_sym_document_repeat1] = { .visible = false, .named = false, }, [aux_sym_start_tag_repeat1] = { .visible = false, .named = false, }, [alias_sym_then] = { .visible = true, .named = true, }, }; static TSSymbol ts_alias_sequences[3][MAX_ALIAS_SEQUENCE_LENGTH] = { [0] = {0}, [1] = { [0] = sym_attribute_name, }, [2] = { [4] = alias_sym_then, }, }; static uint16_t ts_non_terminal_alias_map[] = { sym_expression, 2, sym_expression, sym_attribute_name, 0, }; static bool ts_lex(TSLexer *lexer, TSStateId state) { START_LEXER(); eof = lexer->eof(lexer); switch (state) { case 0: if (eof) ADVANCE(37); if (lookahead == '"') ADVANCE(47); if (lookahead == '#') ADVANCE(59); if (lookahead == '\'') ADVANCE(44); if (lookahead == '/') ADVANCE(64); if (lookahead == ':') ADVANCE(61); if (lookahead == '<') ADVANCE(38); if (lookahead == '=') ADVANCE(42); if (lookahead == '>') ADVANCE(39); if (lookahead == '@') ADVANCE(55); if (lookahead == 'a') ADVANCE(26); if (lookahead == 'c') ADVANCE(8); if (lookahead == 'd') ADVANCE(12); if (lookahead == 'e') ADVANCE(6); if (lookahead == 'h') ADVANCE(29); if (lookahead == 'i') ADVANCE(16); if (lookahead == 'k') ADVANCE(13); if (lookahead == 't') ADVANCE(20); if (lookahead == '{') ADVANCE(53); if (lookahead == '}') ADVANCE(54); if (lookahead == '\t' || lookahead == '\n' || lookahead == '\r' || lookahead == ' ') SKIP(0) END_STATE(); case 1: if (lookahead == '"') ADVANCE(47); if (lookahead == '\'') ADVANCE(44); if (lookahead == '/') ADVANCE(5); if (lookahead == '=') ADVANCE(42); if (lookahead == '>') ADVANCE(39); if (lookahead == '{') ADVANCE(52); if (lookahead == '\t' || lookahead == '\n' || lookahead == '\r' || lookahead == ' ') SKIP(1) if (lookahead != 0 && lookahead != '<' && lookahead != '}') ADVANCE(43); END_STATE(); case 2: if (lookahead == '"') ADVANCE(47); if (lookahead == '\t' || lookahead == '\n' || lookahead == '\r' || lookahead == ' ') ADVANCE(48); if (lookahead != 0) ADVANCE(49); END_STATE(); case 3: if (lookahead == '#') ADVANCE(59); if (lookahead == '/') ADVANCE(63); if (lookahead == ':') ADVANCE(61); if (lookahead == '@') ADVANCE(55); if (lookahead == '\t' || lookahead == '\n' || lookahead == '\r' || lookahead == ' ') SKIP(3) END_STATE(); case 4: if (lookahead == '\'') ADVANCE(44); if (lookahead == '\t' || lookahead == '\n' || lookahead == '\r' || lookahead == ' ') ADVANCE(45); if (lookahead != 0) ADVANCE(46); END_STATE(); case 5: if (lookahead == '>') ADVANCE(40); END_STATE(); case 6: if (lookahead == 'a') ADVANCE(10); if (lookahead == 'l') ADVANCE(27); END_STATE(); case 7: if (lookahead == 'a') ADVANCE(21); END_STATE(); case 8: if (lookahead == 'a') ADVANCE(32); if (lookahead == 'o') ADVANCE(25); END_STATE(); case 9: if (lookahead == 'b') ADVANCE(33); END_STATE(); case 10: if (lookahead == 'c') ADVANCE(18); END_STATE(); case 11: if (lookahead == 'c') ADVANCE(19); END_STATE(); case 12: if (lookahead == 'e') ADVANCE(9); END_STATE(); case 13: if (lookahead == 'e') ADVANCE(34); END_STATE(); case 14: if (lookahead == 'e') ADVANCE(62); END_STATE(); case 15: if (lookahead == 'e') ADVANCE(24); END_STATE(); case 16: if (lookahead == 'f') ADVANCE(60); END_STATE(); case 17: if (lookahead == 'g') ADVANCE(57); END_STATE(); case 18: if (lookahead == 'h') ADVANCE(65); END_STATE(); case 19: if (lookahead == 'h') ADVANCE(69); END_STATE(); case 20: if (lookahead == 'h') ADVANCE(15); END_STATE(); case 21: if (lookahead == 'i') ADVANCE(30); END_STATE(); case 22: if (lookahead == 'l') ADVANCE(56); END_STATE(); case 23: if (lookahead == 'm') ADVANCE(22); END_STATE(); case 24: if (lookahead == 'n') ADVANCE(68); END_STATE(); case 25: if (lookahead == 'n') ADVANCE(28); END_STATE(); case 26: if (lookahead == 's') ADVANCE(66); if (lookahead == 'w') ADVANCE(7); END_STATE(); case 27: if (lookahead == 's') ADVANCE(14); END_STATE(); case 28: if (lookahead == 's') ADVANCE(31); END_STATE(); case 29: if (lookahead == 't') ADVANCE(23); END_STATE(); case 30: if (lookahead == 't') ADVANCE(67); END_STATE(); case 31: if (lookahead == 't') ADVANCE(58); END_STATE(); case 32: if (lookahead == 't') ADVANCE(11); END_STATE(); case 33: if (lookahead == 'u') ADVANCE(17); END_STATE(); case 34: if (lookahead == 'y') ADVANCE(70); END_STATE(); case 35: if (lookahead == '\t' || lookahead == '\n' || lookahead == '\r' || lookahead == ' ') ADVANCE(35); if (lookahead != 0 && lookahead != '<' && lookahead != '>' && lookahead != '{' && lookahead != '}') ADVANCE(50); END_STATE(); case 36: if (eof) ADVANCE(37); if (lookahead == '<') ADVANCE(38); if (lookahead == '{') ADVANCE(53); if (lookahead == '\t' || lookahead == '\n' || lookahead == '\r' || lookahead == ' ') SKIP(36) if (lookahead != 0 && lookahead != '>' && lookahead != '}') ADVANCE(50); END_STATE(); case 37: ACCEPT_TOKEN(ts_builtin_sym_end); END_STATE(); case 38: ACCEPT_TOKEN(anon_sym_LT); if (lookahead == '/') ADVANCE(41); END_STATE(); case 39: ACCEPT_TOKEN(anon_sym_GT); END_STATE(); case 40: ACCEPT_TOKEN(anon_sym_SLASH_GT); END_STATE(); case 41: ACCEPT_TOKEN(anon_sym_LT_SLASH); END_STATE(); case 42: ACCEPT_TOKEN(anon_sym_EQ); END_STATE(); case 43: ACCEPT_TOKEN(aux_sym_attribute_name_token1); if (lookahead != 0 && lookahead != '\t' && lookahead != '\n' && lookahead != '\r' && lookahead != ' ' && lookahead != '"' && lookahead != '\'' && lookahead != '/' && (lookahead < '<' || '>' < lookahead) && lookahead != '{' && lookahead != '}') ADVANCE(43); END_STATE(); case 44: ACCEPT_TOKEN(anon_sym_SQUOTE); END_STATE(); case 45: ACCEPT_TOKEN(aux_sym_quoted_attribute_value_token1); if (lookahead == '\t' || lookahead == '\n' || lookahead == '\r' || lookahead == ' ') ADVANCE(45); if (lookahead != 0 && lookahead != '\'') ADVANCE(46); END_STATE(); case 46: ACCEPT_TOKEN(aux_sym_quoted_attribute_value_token1); if (lookahead != 0 && lookahead != '\'') ADVANCE(46); END_STATE(); case 47: ACCEPT_TOKEN(anon_sym_DQUOTE); END_STATE(); case 48: ACCEPT_TOKEN(aux_sym_quoted_attribute_value_token2); if (lookahead == '\t' || lookahead == '\n' || lookahead == '\r' || lookahead == ' ') ADVANCE(48); if (lookahead != 0 && lookahead != '"') ADVANCE(49); END_STATE(); case 49: ACCEPT_TOKEN(aux_sym_quoted_attribute_value_token2); if (lookahead != 0 && lookahead != '"') ADVANCE(49); END_STATE(); case 50: ACCEPT_TOKEN(aux_sym__text_token1); if (lookahead == '\t' || lookahead == '\n' || lookahead == '\r' || lookahead == ' ') ADVANCE(35); if (lookahead != 0 && lookahead != '<' && lookahead != '>' && lookahead != '{' && lookahead != '}') ADVANCE(50); END_STATE(); case 51: ACCEPT_TOKEN(anon_sym_LBRACE_RBRACE); END_STATE(); case 52: ACCEPT_TOKEN(anon_sym_LBRACE); END_STATE(); case 53: ACCEPT_TOKEN(anon_sym_LBRACE); if (lookahead == '}') ADVANCE(51); END_STATE(); case 54: ACCEPT_TOKEN(anon_sym_RBRACE); END_STATE(); case 55: ACCEPT_TOKEN(anon_sym_AT); END_STATE(); case 56: ACCEPT_TOKEN(anon_sym_html); END_STATE(); case 57: ACCEPT_TOKEN(anon_sym_debug); END_STATE(); case 58: ACCEPT_TOKEN(anon_sym_const); END_STATE(); case 59: ACCEPT_TOKEN(anon_sym_POUND); END_STATE(); case 60: ACCEPT_TOKEN(anon_sym_if); END_STATE(); case 61: ACCEPT_TOKEN(anon_sym_COLON); END_STATE(); case 62: ACCEPT_TOKEN(anon_sym_else); END_STATE(); case 63: ACCEPT_TOKEN(anon_sym_SLASH); END_STATE(); case 64: ACCEPT_TOKEN(anon_sym_SLASH); if (lookahead == '>') ADVANCE(40); END_STATE(); case 65: ACCEPT_TOKEN(anon_sym_each); END_STATE(); case 66: ACCEPT_TOKEN(anon_sym_as); END_STATE(); case 67: ACCEPT_TOKEN(anon_sym_await); END_STATE(); case 68: ACCEPT_TOKEN(anon_sym_then); END_STATE(); case 69: ACCEPT_TOKEN(anon_sym_catch); END_STATE(); case 70: ACCEPT_TOKEN(anon_sym_key); END_STATE(); default: return false; } } static TSLexMode ts_lex_modes[STATE_COUNT] = { [0] = {.lex_state = 0, .external_lex_state = 1}, [1] = {.lex_state = 36, .external_lex_state = 2}, [2] = {.lex_state = 36, .external_lex_state = 2}, [3] = {.lex_state = 36, .external_lex_state = 2}, [4] = {.lex_state = 36, .external_lex_state = 2}, [5] = {.lex_state = 36, .external_lex_state = 2}, [6] = {.lex_state = 36, .external_lex_state = 2}, [7] = {.lex_state = 36, .external_lex_state = 2}, [8] = {.lex_state = 36, .external_lex_state = 2}, [9] = {.lex_state = 36, .external_lex_state = 2}, [10] = {.lex_state = 36, .external_lex_state = 2}, [11] = {.lex_state = 36, .external_lex_state = 2}, [12] = {.lex_state = 36, .external_lex_state = 2}, [13] = {.lex_state = 36, .external_lex_state = 2}, [14] = {.lex_state = 36, .external_lex_state = 2}, [15] = {.lex_state = 36, .external_lex_state = 2}, [16] = {.lex_state = 36, .external_lex_state = 3}, [17] = {.lex_state = 36, .external_lex_state = 2}, [18] = {.lex_state = 36, .external_lex_state = 3}, [19] = {.lex_state = 36, .external_lex_state = 2}, [20] = {.lex_state = 36, .external_lex_state = 3}, [21] = {.lex_state = 36, .external_lex_state = 3}, [22] = {.lex_state = 36, .external_lex_state = 2}, [23] = {.lex_state = 36, .external_lex_state = 2}, [24] = {.lex_state = 36, .external_lex_state = 2}, [25] = {.lex_state = 36, .external_lex_state = 2}, [26] = {.lex_state = 36, .external_lex_state = 3}, [27] = {.lex_state = 36, .external_lex_state = 2}, [28] = {.lex_state = 36, .external_lex_state = 2}, [29] = {.lex_state = 36, .external_lex_state = 2}, [30] = {.lex_state = 36, .external_lex_state = 2}, [31] = {.lex_state = 36, .external_lex_state = 2}, [32] = {.lex_state = 36, .external_lex_state = 2}, [33] = {.lex_state = 36, .external_lex_state = 2}, [34] = {.lex_state = 36, .external_lex_state = 2}, [35] = {.lex_state = 36, .external_lex_state = 2}, [36] = {.lex_state = 36, .external_lex_state = 2}, [37] = {.lex_state = 36, .external_lex_state = 2}, [38] = {.lex_state = 36, .external_lex_state = 2}, [39] = {.lex_state = 36, .external_lex_state = 2}, [40] = {.lex_state = 36, .external_lex_state = 2}, [41] = {.lex_state = 36, .external_lex_state = 2}, [42] = {.lex_state = 36, .external_lex_state = 2}, [43] = {.lex_state = 36, .external_lex_state = 2}, [44] = {.lex_state = 36, .external_lex_state = 2}, [45] = {.lex_state = 1, .external_lex_state = 4}, [46] = {.lex_state = 1}, [47] = {.lex_state = 1, .external_lex_state = 4}, [48] = {.lex_state = 1, .external_lex_state = 4}, [49] = {.lex_state = 1, .external_lex_state = 4}, [50] = {.lex_state = 1}, [51] = {.lex_state = 1, .external_lex_state = 4}, [52] = {.lex_state = 36, .external_lex_state = 3}, [53] = {.lex_state = 36, .external_lex_state = 3}, [54] = {.lex_state = 36, .external_lex_state = 3}, [55] = {.lex_state = 36, .external_lex_state = 3}, [56] = {.lex_state = 1}, [57] = {.lex_state = 1}, [58] = {.lex_state = 36, .external_lex_state = 3}, [59] = {.lex_state = 36, .external_lex_state = 3}, [60] = {.lex_state = 36, .external_lex_state = 3}, [61] = {.lex_state = 36, .external_lex_state = 3}, [62] = {.lex_state = 36, .external_lex_state = 3}, [63] = {.lex_state = 36, .external_lex_state = 3}, [64] = {.lex_state = 36, .external_lex_state = 3}, [65] = {.lex_state = 36, .external_lex_state = 3}, [66] = {.lex_state = 36, .external_lex_state = 3}, [67] = {.lex_state = 1}, [68] = {.lex_state = 36, .external_lex_state = 3}, [69] = {.lex_state = 36, .external_lex_state = 3}, [70] = {.lex_state = 36, .external_lex_state = 3}, [71] = {.lex_state = 36, .external_lex_state = 3}, [72] = {.lex_state = 36, .external_lex_state = 3}, [73] = {.lex_state = 36, .external_lex_state = 3}, [74] = {.lex_state = 1}, [75] = {.lex_state = 36, .external_lex_state = 3}, [76] = {.lex_state = 36, .external_lex_state = 3}, [77] = {.lex_state = 36, .external_lex_state = 3}, [78] = {.lex_state = 36, .external_lex_state = 3}, [79] = {.lex_state = 36, .external_lex_state = 3}, [80] = {.lex_state = 36, .external_lex_state = 3}, [81] = {.lex_state = 36, .external_lex_state = 3}, [82] = {.lex_state = 36, .external_lex_state = 3}, [83] = {.lex_state = 36, .external_lex_state = 3}, [84] = {.lex_state = 36, .external_lex_state = 3}, [85] = {.lex_state = 36, .external_lex_state = 3}, [86] = {.lex_state = 36, .external_lex_state = 3}, [87] = {.lex_state = 36, .external_lex_state = 3}, [88] = {.lex_state = 36, .external_lex_state = 3}, [89] = {.lex_state = 36, .external_lex_state = 3}, [90] = {.lex_state = 36, .external_lex_state = 3}, [91] = {.lex_state = 1}, [92] = {.lex_state = 36, .external_lex_state = 3}, [93] = {.lex_state = 36, .external_lex_state = 3}, [94] = {.lex_state = 36, .external_lex_state = 3}, [95] = {.lex_state = 36, .external_lex_state = 3}, [96] = {.lex_state = 36, .external_lex_state = 3}, [97] = {.lex_state = 36, .external_lex_state = 3}, [98] = {.lex_state = 36, .external_lex_state = 2}, [99] = {.lex_state = 36, .external_lex_state = 2}, [100] = {.lex_state = 36, .external_lex_state = 2}, [101] = {.lex_state = 36, .external_lex_state = 2}, [102] = {.lex_state = 36, .external_lex_state = 2}, [103] = {.lex_state = 36, .external_lex_state = 2}, [104] = {.lex_state = 36, .external_lex_state = 2}, [105] = {.lex_state = 36, .external_lex_state = 2}, [106] = {.lex_state = 36, .external_lex_state = 2}, [107] = {.lex_state = 36, .external_lex_state = 2}, [108] = {.lex_state = 36, .external_lex_state = 2}, [109] = {.lex_state = 36, .external_lex_state = 2}, [110] = {.lex_state = 36, .external_lex_state = 2}, [111] = {.lex_state = 36, .external_lex_state = 2}, [112] = {.lex_state = 36, .external_lex_state = 2}, [113] = {.lex_state = 36, .external_lex_state = 2}, [114] = {.lex_state = 36, .external_lex_state = 2}, [115] = {.lex_state = 36, .external_lex_state = 2}, [116] = {.lex_state = 36, .external_lex_state = 2}, [117] = {.lex_state = 36, .external_lex_state = 2}, [118] = {.lex_state = 36, .external_lex_state = 2}, [119] = {.lex_state = 36, .external_lex_state = 2}, [120] = {.lex_state = 36, .external_lex_state = 2}, [121] = {.lex_state = 36, .external_lex_state = 2}, [122] = {.lex_state = 36, .external_lex_state = 2}, [123] = {.lex_state = 36, .external_lex_state = 2}, [124] = {.lex_state = 36, .external_lex_state = 2}, [125] = {.lex_state = 36, .external_lex_state = 2}, [126] = {.lex_state = 36, .external_lex_state = 2}, [127] = {.lex_state = 36, .external_lex_state = 2}, [128] = {.lex_state = 36, .external_lex_state = 2}, [129] = {.lex_state = 36, .external_lex_state = 2}, [130] = {.lex_state = 36, .external_lex_state = 2}, [131] = {.lex_state = 36, .external_lex_state = 2}, [132] = {.lex_state = 36, .external_lex_state = 2}, [133] = {.lex_state = 36, .external_lex_state = 2}, [134] = {.lex_state = 36, .external_lex_state = 2}, [135] = {.lex_state = 36, .external_lex_state = 2}, [136] = {.lex_state = 36, .external_lex_state = 2}, [137] = {.lex_state = 36, .external_lex_state = 2}, [138] = {.lex_state = 36, .external_lex_state = 2}, [139] = {.lex_state = 1, .external_lex_state = 4}, [140] = {.lex_state = 36, .external_lex_state = 2}, [141] = {.lex_state = 1, .external_lex_state = 4}, [142] = {.lex_state = 3, .external_lex_state = 5}, [143] = {.lex_state = 3, .external_lex_state = 5}, [144] = {.lex_state = 3, .external_lex_state = 5}, [145] = {.lex_state = 36, .external_lex_state = 2}, [146] = {.lex_state = 3, .external_lex_state = 5}, [147] = {.lex_state = 36, .external_lex_state = 2}, [148] = {.lex_state = 3, .external_lex_state = 5}, [149] = {.lex_state = 3, .external_lex_state = 5}, [150] = {.lex_state = 36, .external_lex_state = 2}, [151] = {.lex_state = 3, .external_lex_state = 5}, [152] = {.lex_state = 36, .external_lex_state = 2}, [153] = {.lex_state = 3, .external_lex_state = 5}, [154] = {.lex_state = 36, .external_lex_state = 2}, [155] = {.lex_state = 36, .external_lex_state = 2}, [156] = {.lex_state = 36, .external_lex_state = 2}, [157] = {.lex_state = 36, .external_lex_state = 2}, [158] = {.lex_state = 36, .external_lex_state = 2}, [159] = {.lex_state = 36, .external_lex_state = 2}, [160] = {.lex_state = 3, .external_lex_state = 5}, [161] = {.lex_state = 0}, [162] = {.lex_state = 3, .external_lex_state = 5}, [163] = {.lex_state = 3, .external_lex_state = 5}, [164] = {.lex_state = 3, .external_lex_state = 5}, [165] = {.lex_state = 1, .external_lex_state = 4}, [166] = {.lex_state = 1, .external_lex_state = 4}, [167] = {.lex_state = 1, .external_lex_state = 4}, [168] = {.lex_state = 1, .external_lex_state = 4}, [169] = {.lex_state = 1, .external_lex_state = 4}, [170] = {.lex_state = 3, .external_lex_state = 5}, [171] = {.lex_state = 1, .external_lex_state = 4}, [172] = {.lex_state = 3, .external_lex_state = 5}, [173] = {.lex_state = 1}, [174] = {.lex_state = 1}, [175] = {.lex_state = 3, .external_lex_state = 5}, [176] = {.lex_state = 1, .external_lex_state = 4}, [177] = {.lex_state = 3, .external_lex_state = 5}, [178] = {.lex_state = 1}, [179] = {.lex_state = 1}, [180] = {.lex_state = 0, .external_lex_state = 6}, [181] = {.lex_state = 0, .external_lex_state = 6}, [182] = {.lex_state = 0, .external_lex_state = 6}, [183] = {.lex_state = 0}, [184] = {.lex_state = 0, .external_lex_state = 6}, [185] = {.lex_state = 1}, [186] = {.lex_state = 0}, [187] = {.lex_state = 1}, [188] = {.lex_state = 1}, [189] = {.lex_state = 0, .external_lex_state = 5}, [190] = {.lex_state = 0, .external_lex_state = 7}, [191] = {.lex_state = 0, .external_lex_state = 5}, [192] = {.lex_state = 0, .external_lex_state = 7}, [193] = {.lex_state = 1}, [194] = {.lex_state = 1}, [195] = {.lex_state = 0, .external_lex_state = 6}, [196] = {.lex_state = 0, .external_lex_state = 8}, [197] = {.lex_state = 0, .external_lex_state = 5}, [198] = {.lex_state = 0, .external_lex_state = 6}, [199] = {.lex_state = 0, .external_lex_state = 5}, [200] = {.lex_state = 0}, [201] = {.lex_state = 2}, [202] = {.lex_state = 4}, [203] = {.lex_state = 4}, [204] = {.lex_state = 0}, [205] = {.lex_state = 0}, [206] = {.lex_state = 0, .external_lex_state = 5}, [207] = {.lex_state = 0, .external_lex_state = 9}, [208] = {.lex_state = 0}, [209] = {.lex_state = 2}, [210] = {.lex_state = 0, .external_lex_state = 6}, [211] = {.lex_state = 0}, [212] = {.lex_state = 0}, [213] = {.lex_state = 0, .external_lex_state = 5}, [214] = {.lex_state = 0, .external_lex_state = 5}, [215] = {.lex_state = 0, .external_lex_state = 5}, [216] = {.lex_state = 0, .external_lex_state = 5}, [217] = {.lex_state = 0, .external_lex_state = 5}, [218] = {.lex_state = 0, .external_lex_state = 5}, [219] = {.lex_state = 0, .external_lex_state = 6}, [220] = {.lex_state = 0}, [221] = {.lex_state = 0}, [222] = {.lex_state = 0}, [223] = {.lex_state = 0, .external_lex_state = 5}, [224] = {.lex_state = 0, .external_lex_state = 5}, [225] = {.lex_state = 0, .external_lex_state = 5}, [226] = {.lex_state = 0, .external_lex_state = 5}, [227] = {.lex_state = 0}, [228] = {.lex_state = 0}, [229] = {.lex_state = 0}, [230] = {.lex_state = 0}, [231] = {.lex_state = 0}, [232] = {.lex_state = 0}, [233] = {.lex_state = 0}, [234] = {.lex_state = 0, .external_lex_state = 10}, [235] = {.lex_state = 0}, [236] = {.lex_state = 0}, [237] = {.lex_state = 0}, [238] = {.lex_state = 0}, [239] = {.lex_state = 0}, [240] = {.lex_state = 0}, [241] = {.lex_state = 0}, [242] = {.lex_state = 0}, [243] = {.lex_state = 0}, [244] = {.lex_state = 0}, [245] = {.lex_state = 0}, [246] = {.lex_state = 0}, [247] = {.lex_state = 0}, [248] = {.lex_state = 0}, [249] = {.lex_state = 0}, [250] = {.lex_state = 0}, [251] = {.lex_state = 0}, [252] = {.lex_state = 0}, [253] = {.lex_state = 0}, [254] = {.lex_state = 0}, [255] = {.lex_state = 0}, [256] = {.lex_state = 0}, [257] = {.lex_state = 0}, [258] = {.lex_state = 0}, [259] = {.lex_state = 0}, [260] = {.lex_state = 0}, [261] = {.lex_state = 0}, [262] = {.lex_state = 0, .external_lex_state = 10}, [263] = {.lex_state = 0, .external_lex_state = 5}, [264] = {.lex_state = 0}, [265] = {.lex_state = 0, .external_lex_state = 5}, [266] = {.lex_state = 0}, [267] = {.lex_state = 0}, [268] = {.lex_state = 0}, [269] = {.lex_state = 0}, [270] = {.lex_state = 0}, [271] = {.lex_state = 0}, [272] = {.lex_state = 0}, [273] = {.lex_state = 0}, [274] = {.lex_state = 0}, [275] = {.lex_state = 0}, }; enum { ts_external_token__start_tag_name = 0, ts_external_token__script_start_tag_name = 1, ts_external_token__style_start_tag_name = 2, ts_external_token__end_tag_name = 3, ts_external_token_erroneous_end_tag_name = 4, ts_external_token_SLASH_GT = 5, ts_external_token__implicit_end_tag = 6, ts_external_token_raw_text = 7, ts_external_token_raw_text_expr = 8, ts_external_token_raw_text_await = 9, ts_external_token_raw_text_each = 10, ts_external_token_comment = 11, }; static TSSymbol ts_external_scanner_symbol_map[EXTERNAL_TOKEN_COUNT] = { [ts_external_token__start_tag_name] = sym__start_tag_name, [ts_external_token__script_start_tag_name] = sym__script_start_tag_name, [ts_external_token__style_start_tag_name] = sym__style_start_tag_name, [ts_external_token__end_tag_name] = sym__end_tag_name, [ts_external_token_erroneous_end_tag_name] = sym_erroneous_end_tag_name, [ts_external_token_SLASH_GT] = anon_sym_SLASH_GT, [ts_external_token__implicit_end_tag] = sym__implicit_end_tag, [ts_external_token_raw_text] = sym_raw_text, [ts_external_token_raw_text_expr] = sym_raw_text_expr, [ts_external_token_raw_text_await] = sym_raw_text_await, [ts_external_token_raw_text_each] = sym_raw_text_each, [ts_external_token_comment] = sym_comment, }; static bool ts_external_scanner_states[11][EXTERNAL_TOKEN_COUNT] = { [1] = { [ts_external_token__start_tag_name] = true, [ts_external_token__script_start_tag_name] = true, [ts_external_token__style_start_tag_name] = true, [ts_external_token__end_tag_name] = true, [ts_external_token_erroneous_end_tag_name] = true, [ts_external_token_SLASH_GT] = true, [ts_external_token__implicit_end_tag] = true, [ts_external_token_raw_text] = true, [ts_external_token_raw_text_expr] = true, [ts_external_token_raw_text_await] = true, [ts_external_token_raw_text_each] = true, [ts_external_token_comment] = true, }, [2] = { [ts_external_token_comment] = true, }, [3] = { [ts_external_token__implicit_end_tag] = true, [ts_external_token_comment] = true, }, [4] = { [ts_external_token_SLASH_GT] = true, }, [5] = { [ts_external_token_raw_text_expr] = true, }, [6] = { [ts_external_token_raw_text] = true, }, [7] = { [ts_external_token__start_tag_name] = true, [ts_external_token__script_start_tag_name] = true, [ts_external_token__style_start_tag_name] = true, }, [8] = { [ts_external_token_raw_text_expr] = true, [ts_external_token_raw_text_each] = true, }, [9] = { [ts_external_token_raw_text_expr] = true, [ts_external_token_raw_text_await] = true, }, [10] = { [ts_external_token__end_tag_name] = true, }, }; static uint16_t ts_parse_table[LARGE_STATE_COUNT][SYMBOL_COUNT] = { [0] = { [ts_builtin_sym_end] = ACTIONS(1), [anon_sym_LT] = ACTIONS(1), [anon_sym_GT] = ACTIONS(1), [anon_sym_SLASH_GT] = ACTIONS(1), [anon_sym_LT_SLASH] = ACTIONS(1), [anon_sym_EQ] = ACTIONS(1), [anon_sym_SQUOTE] = ACTIONS(1), [anon_sym_DQUOTE] = ACTIONS(1), [anon_sym_LBRACE_RBRACE] = ACTIONS(1), [anon_sym_LBRACE] = ACTIONS(1), [anon_sym_RBRACE] = ACTIONS(1), [anon_sym_AT] = ACTIONS(1), [anon_sym_html] = ACTIONS(1), [anon_sym_debug] = ACTIONS(1), [anon_sym_const] = ACTIONS(1), [anon_sym_POUND] = ACTIONS(1), [anon_sym_if] = ACTIONS(1), [anon_sym_COLON] = ACTIONS(1), [anon_sym_else] = ACTIONS(1), [anon_sym_SLASH] = ACTIONS(1), [anon_sym_each] = ACTIONS(1), [anon_sym_as] = ACTIONS(1), [anon_sym_await] = ACTIONS(1), [anon_sym_then] = ACTIONS(1), [anon_sym_catch] = ACTIONS(1), [anon_sym_key] = ACTIONS(1), [sym__start_tag_name] = ACTIONS(1), [sym__script_start_tag_name] = ACTIONS(1), [sym__style_start_tag_name] = ACTIONS(1), [sym__end_tag_name] = ACTIONS(1), [sym_erroneous_end_tag_name] = ACTIONS(1), [sym__implicit_end_tag] = ACTIONS(1), [sym_raw_text] = ACTIONS(1), [sym_raw_text_expr] = ACTIONS(1), [sym_raw_text_await] = ACTIONS(1), [sym_raw_text_each] = ACTIONS(1), [sym_comment] = ACTIONS(1), }, [1] = { [sym_document] = STATE(244), [sym__node] = STATE(31), [sym__statement] = STATE(31), [sym_element] = STATE(31), [sym_start_tag] = STATE(20), [sym_self_closing_tag] = STATE(122), [sym_script_element] = STATE(31), [sym_script_start_tag] = STATE(181), [sym_style_element] = STATE(31), [sym_style_start_tag] = STATE(182), [sym__text] = STATE(31), [sym__expression] = STATE(31), [sym_expression] = STATE(31), [sym_html_expr] = STATE(31), [sym_debug_expr] = STATE(31), [sym_const_expr] = STATE(31), [sym_if_statement] = STATE(31), [sym_if_start_expr] = STATE(9), [sym_each_statement] = STATE(31), [sym_each_start_expr] = STATE(22), [sym_await_statement] = STATE(31), [sym_await_start_expr] = STATE(11), [sym_key_statement] = STATE(31), [sym_key_start_expr] = STATE(34), [aux_sym_document_repeat1] = STATE(31), [ts_builtin_sym_end] = ACTIONS(3), [anon_sym_LT] = ACTIONS(5), [aux_sym__text_token1] = ACTIONS(7), [anon_sym_LBRACE_RBRACE] = ACTIONS(7), [anon_sym_LBRACE] = ACTIONS(9), [sym_comment] = ACTIONS(7), }, }; static uint16_t ts_small_parse_table[] = { [0] = 15, ACTIONS(5), 1, anon_sym_LT, ACTIONS(13), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(24), 1, sym_then_expr, STATE(28), 1, sym_catch_expr, STATE(34), 1, sym_key_start_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(11), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(75), 3, sym_then_statement, sym_catch_statement, sym_await_end_expr, STATE(44), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [65] = 15, ACTIONS(5), 1, anon_sym_LT, ACTIONS(17), 1, anon_sym_LBRACE, STATE(4), 1, sym_else_if_expr, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(36), 1, sym_else_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(15), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(69), 3, sym_else_if_statement, sym_else_statement, sym_if_end_expr, STATE(7), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [130] = 15, ACTIONS(5), 1, anon_sym_LT, ACTIONS(17), 1, anon_sym_LBRACE, STATE(4), 1, sym_else_if_expr, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(36), 1, sym_else_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(19), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(88), 3, sym_else_if_statement, sym_else_statement, sym_if_end_expr, STATE(8), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [195] = 15, ACTIONS(5), 1, anon_sym_LT, ACTIONS(21), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(14), 1, sym_then_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(39), 1, sym_catch_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(11), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(107), 3, sym_then_statement, sym_catch_statement, sym_await_end_expr, STATE(44), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [260] = 15, ACTIONS(5), 1, anon_sym_LT, ACTIONS(13), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(24), 1, sym_then_expr, STATE(28), 1, sym_catch_expr, STATE(34), 1, sym_key_start_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(23), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(72), 3, sym_then_statement, sym_catch_statement, sym_await_end_expr, STATE(2), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [325] = 15, ACTIONS(5), 1, anon_sym_LT, ACTIONS(17), 1, anon_sym_LBRACE, STATE(4), 1, sym_else_if_expr, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(36), 1, sym_else_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(11), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(89), 3, sym_else_if_statement, sym_else_statement, sym_if_end_expr, STATE(44), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [390] = 15, ACTIONS(5), 1, anon_sym_LT, ACTIONS(17), 1, anon_sym_LBRACE, STATE(4), 1, sym_else_if_expr, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(36), 1, sym_else_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(11), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(77), 3, sym_else_if_statement, sym_else_statement, sym_if_end_expr, STATE(44), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [455] = 15, ACTIONS(5), 1, anon_sym_LT, ACTIONS(27), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(13), 1, sym_else_if_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(29), 1, sym_else_expr, STATE(34), 1, sym_key_start_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(25), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(110), 3, sym_else_if_statement, sym_else_statement, sym_if_end_expr, STATE(12), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [520] = 15, ACTIONS(5), 1, anon_sym_LT, ACTIONS(27), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(13), 1, sym_else_if_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(29), 1, sym_else_expr, STATE(34), 1, sym_key_start_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(11), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(115), 3, sym_else_if_statement, sym_else_statement, sym_if_end_expr, STATE(44), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [585] = 15, ACTIONS(5), 1, anon_sym_LT, ACTIONS(21), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(14), 1, sym_then_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(39), 1, sym_catch_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(29), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(98), 3, sym_then_statement, sym_catch_statement, sym_await_end_expr, STATE(5), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [650] = 15, ACTIONS(5), 1, anon_sym_LT, ACTIONS(27), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(13), 1, sym_else_if_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(29), 1, sym_else_expr, STATE(34), 1, sym_key_start_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(11), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(119), 3, sym_else_if_statement, sym_else_statement, sym_if_end_expr, STATE(44), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [715] = 15, ACTIONS(5), 1, anon_sym_LT, ACTIONS(27), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(13), 1, sym_else_if_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(29), 1, sym_else_expr, STATE(34), 1, sym_key_start_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(31), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(121), 3, sym_else_if_statement, sym_else_statement, sym_if_end_expr, STATE(10), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [780] = 14, ACTIONS(5), 1, anon_sym_LT, ACTIONS(35), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(39), 1, sym_catch_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, STATE(112), 2, sym_catch_statement, sym_await_end_expr, ACTIONS(33), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(25), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [841] = 14, ACTIONS(5), 1, anon_sym_LT, ACTIONS(37), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(32), 1, sym_else_expr, STATE(34), 1, sym_key_start_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, STATE(92), 2, sym_else_each_statement, sym_each_end_expr, ACTIONS(11), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(44), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [902] = 15, ACTIONS(39), 1, anon_sym_LT, ACTIONS(41), 1, anon_sym_LT_SLASH, ACTIONS(45), 1, anon_sym_LBRACE, ACTIONS(47), 1, sym__implicit_end_tag, STATE(3), 1, sym_if_start_expr, STATE(6), 1, sym_await_start_expr, STATE(17), 1, sym_each_start_expr, STATE(18), 1, sym_start_tag, STATE(30), 1, sym_key_start_expr, STATE(66), 1, sym_self_closing_tag, STATE(80), 1, sym_end_tag, STATE(180), 1, sym_style_start_tag, STATE(184), 1, sym_script_start_tag, ACTIONS(43), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(26), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [965] = 14, ACTIONS(5), 1, anon_sym_LT, ACTIONS(37), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(32), 1, sym_else_expr, STATE(34), 1, sym_key_start_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, STATE(71), 2, sym_else_each_statement, sym_each_end_expr, ACTIONS(49), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(15), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [1026] = 15, ACTIONS(39), 1, anon_sym_LT, ACTIONS(41), 1, anon_sym_LT_SLASH, ACTIONS(45), 1, anon_sym_LBRACE, ACTIONS(53), 1, sym__implicit_end_tag, STATE(3), 1, sym_if_start_expr, STATE(6), 1, sym_await_start_expr, STATE(17), 1, sym_each_start_expr, STATE(18), 1, sym_start_tag, STATE(30), 1, sym_key_start_expr, STATE(65), 1, sym_end_tag, STATE(66), 1, sym_self_closing_tag, STATE(180), 1, sym_style_start_tag, STATE(184), 1, sym_script_start_tag, ACTIONS(51), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(16), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [1089] = 14, ACTIONS(5), 1, anon_sym_LT, ACTIONS(55), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(28), 1, sym_catch_expr, STATE(34), 1, sym_key_start_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, STATE(70), 2, sym_catch_statement, sym_await_end_expr, ACTIONS(11), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(44), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [1150] = 15, ACTIONS(39), 1, anon_sym_LT, ACTIONS(45), 1, anon_sym_LBRACE, ACTIONS(57), 1, anon_sym_LT_SLASH, ACTIONS(61), 1, sym__implicit_end_tag, STATE(3), 1, sym_if_start_expr, STATE(6), 1, sym_await_start_expr, STATE(17), 1, sym_each_start_expr, STATE(18), 1, sym_start_tag, STATE(30), 1, sym_key_start_expr, STATE(66), 1, sym_self_closing_tag, STATE(99), 1, sym_end_tag, STATE(180), 1, sym_style_start_tag, STATE(184), 1, sym_script_start_tag, ACTIONS(59), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(21), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [1213] = 15, ACTIONS(39), 1, anon_sym_LT, ACTIONS(45), 1, anon_sym_LBRACE, ACTIONS(57), 1, anon_sym_LT_SLASH, ACTIONS(63), 1, sym__implicit_end_tag, STATE(3), 1, sym_if_start_expr, STATE(6), 1, sym_await_start_expr, STATE(17), 1, sym_each_start_expr, STATE(18), 1, sym_start_tag, STATE(30), 1, sym_key_start_expr, STATE(66), 1, sym_self_closing_tag, STATE(135), 1, sym_end_tag, STATE(180), 1, sym_style_start_tag, STATE(184), 1, sym_script_start_tag, ACTIONS(43), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(26), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [1276] = 14, ACTIONS(5), 1, anon_sym_LT, ACTIONS(67), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(33), 1, sym_else_expr, STATE(34), 1, sym_key_start_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, STATE(116), 2, sym_else_each_statement, sym_each_end_expr, ACTIONS(65), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(23), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [1337] = 14, ACTIONS(5), 1, anon_sym_LT, ACTIONS(67), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(33), 1, sym_else_expr, STATE(34), 1, sym_key_start_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, STATE(113), 2, sym_else_each_statement, sym_each_end_expr, ACTIONS(11), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(44), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [1398] = 14, ACTIONS(5), 1, anon_sym_LT, ACTIONS(55), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(28), 1, sym_catch_expr, STATE(34), 1, sym_key_start_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, STATE(93), 2, sym_catch_statement, sym_await_end_expr, ACTIONS(69), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(19), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [1459] = 14, ACTIONS(5), 1, anon_sym_LT, ACTIONS(35), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(39), 1, sym_catch_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, STATE(123), 2, sym_catch_statement, sym_await_end_expr, ACTIONS(11), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(44), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [1520] = 13, ACTIONS(71), 1, anon_sym_LT, ACTIONS(79), 1, anon_sym_LBRACE, STATE(3), 1, sym_if_start_expr, STATE(6), 1, sym_await_start_expr, STATE(17), 1, sym_each_start_expr, STATE(18), 1, sym_start_tag, STATE(30), 1, sym_key_start_expr, STATE(66), 1, sym_self_closing_tag, STATE(180), 1, sym_style_start_tag, STATE(184), 1, sym_script_start_tag, ACTIONS(74), 2, sym__implicit_end_tag, anon_sym_LT_SLASH, ACTIONS(76), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(26), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [1578] = 13, ACTIONS(5), 1, anon_sym_LT, ACTIONS(82), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(122), 1, sym_self_closing_tag, STATE(124), 1, sym_await_end_expr, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(11), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(44), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [1635] = 13, ACTIONS(5), 1, anon_sym_LT, ACTIONS(86), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(95), 1, sym_await_end_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(84), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(41), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [1692] = 13, ACTIONS(5), 1, anon_sym_LT, ACTIONS(90), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(122), 1, sym_self_closing_tag, STATE(128), 1, sym_if_end_expr, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(88), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(37), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [1749] = 13, ACTIONS(5), 1, anon_sym_LT, ACTIONS(94), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(73), 1, sym_key_end_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(92), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(42), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [1806] = 13, ACTIONS(5), 1, anon_sym_LT, ACTIONS(9), 1, anon_sym_LBRACE, ACTIONS(96), 1, ts_builtin_sym_end, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(11), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(44), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [1863] = 13, ACTIONS(5), 1, anon_sym_LT, ACTIONS(100), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(90), 1, sym_each_end_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(98), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(38), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [1920] = 13, ACTIONS(5), 1, anon_sym_LT, ACTIONS(104), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(117), 1, sym_each_end_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(102), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(40), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [1977] = 13, ACTIONS(5), 1, anon_sym_LT, ACTIONS(108), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(120), 1, sym_key_end_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(106), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(43), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [2034] = 13, ACTIONS(5), 1, anon_sym_LT, ACTIONS(110), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(78), 1, sym_if_end_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(11), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(44), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [2091] = 13, ACTIONS(5), 1, anon_sym_LT, ACTIONS(110), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(86), 1, sym_if_end_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(112), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(35), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [2148] = 13, ACTIONS(5), 1, anon_sym_LT, ACTIONS(90), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(114), 1, sym_if_end_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(11), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(44), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [2205] = 13, ACTIONS(5), 1, anon_sym_LT, ACTIONS(100), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(76), 1, sym_each_end_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(11), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(44), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [2262] = 13, ACTIONS(5), 1, anon_sym_LT, ACTIONS(82), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(109), 1, sym_await_end_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(114), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(27), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [2319] = 13, ACTIONS(5), 1, anon_sym_LT, ACTIONS(104), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(118), 1, sym_each_end_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(11), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(44), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [2376] = 13, ACTIONS(5), 1, anon_sym_LT, ACTIONS(86), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(52), 1, sym_await_end_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(11), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(44), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [2433] = 13, ACTIONS(5), 1, anon_sym_LT, ACTIONS(94), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(97), 1, sym_key_end_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(11), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(44), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [2490] = 13, ACTIONS(5), 1, anon_sym_LT, ACTIONS(108), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(106), 1, sym_key_end_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(11), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(44), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [2547] = 13, ACTIONS(74), 1, ts_builtin_sym_end, ACTIONS(116), 1, anon_sym_LT, ACTIONS(122), 1, anon_sym_LBRACE, STATE(9), 1, sym_if_start_expr, STATE(11), 1, sym_await_start_expr, STATE(20), 1, sym_start_tag, STATE(22), 1, sym_each_start_expr, STATE(34), 1, sym_key_start_expr, STATE(122), 1, sym_self_closing_tag, STATE(181), 1, sym_script_start_tag, STATE(182), 1, sym_style_start_tag, ACTIONS(119), 3, sym_comment, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, STATE(44), 16, sym__node, sym__statement, sym_element, sym_script_element, sym_style_element, sym__text, sym__expression, sym_expression, sym_html_expr, sym_debug_expr, sym_const_expr, sym_if_statement, sym_each_statement, sym_await_statement, sym_key_statement, aux_sym_document_repeat1, [2604] = 7, ACTIONS(125), 1, anon_sym_GT, ACTIONS(127), 1, anon_sym_SLASH_GT, ACTIONS(129), 1, aux_sym_attribute_name_token1, ACTIONS(131), 1, anon_sym_LBRACE, STATE(139), 1, sym_attribute_name, STATE(167), 1, sym_expression, STATE(48), 2, sym_attribute, aux_sym_start_tag_repeat1, [2627] = 6, ACTIONS(131), 1, anon_sym_LBRACE, ACTIONS(133), 1, aux_sym_attribute_name_token1, ACTIONS(135), 1, anon_sym_SQUOTE, ACTIONS(137), 1, anon_sym_DQUOTE, STATE(171), 1, sym_expression, STATE(168), 3, sym_attribute_value, sym_expr_attribute_value, sym_quoted_attribute_value, [2648] = 7, ACTIONS(129), 1, aux_sym_attribute_name_token1, ACTIONS(131), 1, anon_sym_LBRACE, ACTIONS(139), 1, anon_sym_GT, ACTIONS(141), 1, anon_sym_SLASH_GT, STATE(139), 1, sym_attribute_name, STATE(167), 1, sym_expression, STATE(51), 2, sym_attribute, aux_sym_start_tag_repeat1, [2671] = 6, ACTIONS(145), 1, aux_sym_attribute_name_token1, ACTIONS(148), 1, anon_sym_LBRACE, STATE(139), 1, sym_attribute_name, STATE(167), 1, sym_expression, ACTIONS(143), 2, anon_sym_GT, anon_sym_SLASH_GT, STATE(48), 2, sym_attribute, aux_sym_start_tag_repeat1, [2692] = 7, ACTIONS(129), 1, aux_sym_attribute_name_token1, ACTIONS(131), 1, anon_sym_LBRACE, ACTIONS(139), 1, anon_sym_GT, ACTIONS(151), 1, anon_sym_SLASH_GT, STATE(139), 1, sym_attribute_name, STATE(167), 1, sym_expression, STATE(45), 2, sym_attribute, aux_sym_start_tag_repeat1, [2715] = 6, ACTIONS(153), 1, aux_sym_attribute_name_token1, ACTIONS(155), 1, anon_sym_SQUOTE, ACTIONS(157), 1, anon_sym_DQUOTE, ACTIONS(159), 1, anon_sym_LBRACE, STATE(178), 1, sym_expression, STATE(193), 3, sym_attribute_value, sym_expr_attribute_value, sym_quoted_attribute_value, [2736] = 7, ACTIONS(125), 1, anon_sym_GT, ACTIONS(129), 1, aux_sym_attribute_name_token1, ACTIONS(131), 1, anon_sym_LBRACE, ACTIONS(161), 1, anon_sym_SLASH_GT, STATE(139), 1, sym_attribute_name, STATE(167), 1, sym_expression, STATE(48), 2, sym_attribute, aux_sym_start_tag_repeat1, [2759] = 2, ACTIONS(163), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(165), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [2771] = 2, ACTIONS(167), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(169), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [2783] = 2, ACTIONS(171), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(173), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [2795] = 2, ACTIONS(175), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(177), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [2807] = 6, ACTIONS(159), 1, anon_sym_LBRACE, ACTIONS(179), 1, anon_sym_GT, ACTIONS(181), 1, aux_sym_attribute_name_token1, STATE(174), 1, sym_attribute_name, STATE(179), 1, sym_expression, STATE(91), 2, sym_attribute, aux_sym_start_tag_repeat1, [2827] = 6, ACTIONS(159), 1, anon_sym_LBRACE, ACTIONS(181), 1, aux_sym_attribute_name_token1, ACTIONS(183), 1, anon_sym_GT, STATE(174), 1, sym_attribute_name, STATE(179), 1, sym_expression, STATE(91), 2, sym_attribute, aux_sym_start_tag_repeat1, [2847] = 2, ACTIONS(185), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(187), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [2859] = 2, ACTIONS(189), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(191), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [2871] = 2, ACTIONS(193), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(195), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [2883] = 2, ACTIONS(197), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(199), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [2895] = 2, ACTIONS(201), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(203), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [2907] = 2, ACTIONS(205), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(207), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [2919] = 2, ACTIONS(209), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(211), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [2931] = 2, ACTIONS(213), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(215), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [2943] = 2, ACTIONS(217), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(219), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [2955] = 6, ACTIONS(159), 1, anon_sym_LBRACE, ACTIONS(181), 1, aux_sym_attribute_name_token1, ACTIONS(221), 1, anon_sym_GT, STATE(174), 1, sym_attribute_name, STATE(179), 1, sym_expression, STATE(56), 2, sym_attribute, aux_sym_start_tag_repeat1, [2975] = 2, ACTIONS(223), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(225), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [2987] = 2, ACTIONS(227), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(229), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [2999] = 2, ACTIONS(231), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(233), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3011] = 2, ACTIONS(235), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(237), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3023] = 2, ACTIONS(239), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(241), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3035] = 2, ACTIONS(243), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(245), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3047] = 6, ACTIONS(159), 1, anon_sym_LBRACE, ACTIONS(181), 1, aux_sym_attribute_name_token1, ACTIONS(247), 1, anon_sym_GT, STATE(174), 1, sym_attribute_name, STATE(179), 1, sym_expression, STATE(57), 2, sym_attribute, aux_sym_start_tag_repeat1, [3067] = 2, ACTIONS(249), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(251), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3079] = 2, ACTIONS(253), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(255), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3091] = 2, ACTIONS(257), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(259), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3103] = 2, ACTIONS(261), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(263), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3115] = 2, ACTIONS(265), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(267), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3127] = 2, ACTIONS(269), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(271), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3139] = 2, ACTIONS(273), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(275), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3151] = 2, ACTIONS(277), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(279), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3163] = 2, ACTIONS(281), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(283), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3175] = 2, ACTIONS(285), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(287), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3187] = 2, ACTIONS(289), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(291), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3199] = 2, ACTIONS(293), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(295), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3211] = 2, ACTIONS(297), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(299), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3223] = 2, ACTIONS(301), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(303), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3235] = 2, ACTIONS(305), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(307), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3247] = 2, ACTIONS(309), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(311), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3259] = 6, ACTIONS(143), 1, anon_sym_GT, ACTIONS(313), 1, aux_sym_attribute_name_token1, ACTIONS(316), 1, anon_sym_LBRACE, STATE(174), 1, sym_attribute_name, STATE(179), 1, sym_expression, STATE(91), 2, sym_attribute, aux_sym_start_tag_repeat1, [3279] = 2, ACTIONS(319), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(321), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3291] = 2, ACTIONS(323), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(325), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3303] = 2, ACTIONS(327), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(329), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3315] = 2, ACTIONS(331), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(333), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3327] = 2, ACTIONS(335), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(337), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3339] = 2, ACTIONS(339), 2, anon_sym_LT, anon_sym_LBRACE, ACTIONS(341), 5, sym__implicit_end_tag, sym_comment, anon_sym_LT_SLASH, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3351] = 2, ACTIONS(239), 1, anon_sym_LBRACE, ACTIONS(241), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3362] = 2, ACTIONS(213), 1, anon_sym_LBRACE, ACTIONS(215), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3373] = 2, ACTIONS(297), 1, anon_sym_LBRACE, ACTIONS(299), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3384] = 2, ACTIONS(167), 1, anon_sym_LBRACE, ACTIONS(169), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3395] = 2, ACTIONS(285), 1, anon_sym_LBRACE, ACTIONS(287), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3406] = 2, ACTIONS(335), 1, anon_sym_LBRACE, ACTIONS(337), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3417] = 2, ACTIONS(281), 1, anon_sym_LBRACE, ACTIONS(283), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3428] = 2, ACTIONS(185), 1, anon_sym_LBRACE, ACTIONS(187), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3439] = 2, ACTIONS(339), 1, anon_sym_LBRACE, ACTIONS(341), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3450] = 2, ACTIONS(249), 1, anon_sym_LBRACE, ACTIONS(251), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3461] = 2, ACTIONS(175), 1, anon_sym_LBRACE, ACTIONS(177), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3472] = 2, ACTIONS(331), 1, anon_sym_LBRACE, ACTIONS(333), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3483] = 2, ACTIONS(227), 1, anon_sym_LBRACE, ACTIONS(229), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3494] = 2, ACTIONS(277), 1, anon_sym_LBRACE, ACTIONS(279), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3505] = 2, ACTIONS(323), 1, anon_sym_LBRACE, ACTIONS(325), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3516] = 2, ACTIONS(319), 1, anon_sym_LBRACE, ACTIONS(321), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3527] = 2, ACTIONS(261), 1, anon_sym_LBRACE, ACTIONS(263), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3538] = 2, ACTIONS(257), 1, anon_sym_LBRACE, ACTIONS(259), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3549] = 2, ACTIONS(235), 1, anon_sym_LBRACE, ACTIONS(237), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3560] = 2, ACTIONS(309), 1, anon_sym_LBRACE, ACTIONS(311), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3571] = 2, ACTIONS(253), 1, anon_sym_LBRACE, ACTIONS(255), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3582] = 2, ACTIONS(305), 1, anon_sym_LBRACE, ACTIONS(307), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3593] = 2, ACTIONS(243), 1, anon_sym_LBRACE, ACTIONS(245), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3604] = 2, ACTIONS(301), 1, anon_sym_LBRACE, ACTIONS(303), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3615] = 2, ACTIONS(217), 1, anon_sym_LBRACE, ACTIONS(219), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3626] = 2, ACTIONS(231), 1, anon_sym_LBRACE, ACTIONS(233), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3637] = 2, ACTIONS(163), 1, anon_sym_LBRACE, ACTIONS(165), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3648] = 2, ACTIONS(223), 1, anon_sym_LBRACE, ACTIONS(225), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3659] = 2, ACTIONS(209), 1, anon_sym_LBRACE, ACTIONS(211), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3670] = 2, ACTIONS(205), 1, anon_sym_LBRACE, ACTIONS(207), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3681] = 2, ACTIONS(293), 1, anon_sym_LBRACE, ACTIONS(295), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3692] = 2, ACTIONS(201), 1, anon_sym_LBRACE, ACTIONS(203), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3703] = 2, ACTIONS(197), 1, anon_sym_LBRACE, ACTIONS(199), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3714] = 2, ACTIONS(193), 1, anon_sym_LBRACE, ACTIONS(195), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3725] = 2, ACTIONS(189), 1, anon_sym_LBRACE, ACTIONS(191), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3736] = 2, ACTIONS(289), 1, anon_sym_LBRACE, ACTIONS(291), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3747] = 2, ACTIONS(273), 1, anon_sym_LBRACE, ACTIONS(275), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3758] = 2, ACTIONS(269), 1, anon_sym_LBRACE, ACTIONS(271), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3769] = 2, ACTIONS(265), 1, anon_sym_LBRACE, ACTIONS(267), 5, sym_comment, ts_builtin_sym_end, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3780] = 2, ACTIONS(345), 1, anon_sym_LBRACE, ACTIONS(343), 4, sym_comment, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3790] = 2, ACTIONS(349), 1, anon_sym_LBRACE, ACTIONS(347), 4, sym_comment, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3800] = 2, ACTIONS(353), 1, anon_sym_EQ, ACTIONS(351), 4, anon_sym_GT, anon_sym_SLASH_GT, aux_sym_attribute_name_token1, anon_sym_LBRACE, [3810] = 2, ACTIONS(357), 1, anon_sym_LBRACE, ACTIONS(355), 4, sym_comment, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3820] = 1, ACTIONS(359), 5, anon_sym_GT, anon_sym_SLASH_GT, anon_sym_EQ, aux_sym_attribute_name_token1, anon_sym_LBRACE, [3828] = 5, ACTIONS(361), 1, anon_sym_AT, ACTIONS(363), 1, anon_sym_POUND, ACTIONS(365), 1, anon_sym_COLON, ACTIONS(367), 1, anon_sym_SLASH, ACTIONS(369), 1, sym_raw_text_expr, [3844] = 5, ACTIONS(361), 1, anon_sym_AT, ACTIONS(363), 1, anon_sym_POUND, ACTIONS(369), 1, sym_raw_text_expr, ACTIONS(371), 1, anon_sym_COLON, ACTIONS(373), 1, anon_sym_SLASH, [3860] = 5, ACTIONS(361), 1, anon_sym_AT, ACTIONS(363), 1, anon_sym_POUND, ACTIONS(367), 1, anon_sym_SLASH, ACTIONS(369), 1, sym_raw_text_expr, ACTIONS(375), 1, anon_sym_COLON, [3876] = 2, ACTIONS(379), 1, anon_sym_LBRACE, ACTIONS(377), 4, sym_comment, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3886] = 5, ACTIONS(361), 1, anon_sym_AT, ACTIONS(363), 1, anon_sym_POUND, ACTIONS(365), 1, anon_sym_COLON, ACTIONS(369), 1, sym_raw_text_expr, ACTIONS(381), 1, anon_sym_SLASH, [3902] = 2, ACTIONS(385), 1, anon_sym_LBRACE, ACTIONS(383), 4, sym_comment, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3912] = 5, ACTIONS(361), 1, anon_sym_AT, ACTIONS(363), 1, anon_sym_POUND, ACTIONS(369), 1, sym_raw_text_expr, ACTIONS(371), 1, anon_sym_COLON, ACTIONS(387), 1, anon_sym_SLASH, [3928] = 5, ACTIONS(361), 1, anon_sym_AT, ACTIONS(363), 1, anon_sym_POUND, ACTIONS(369), 1, sym_raw_text_expr, ACTIONS(389), 1, anon_sym_COLON, ACTIONS(391), 1, anon_sym_SLASH, [3944] = 2, ACTIONS(395), 1, anon_sym_LBRACE, ACTIONS(393), 4, sym_comment, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3954] = 5, ACTIONS(361), 1, anon_sym_AT, ACTIONS(363), 1, anon_sym_POUND, ACTIONS(369), 1, sym_raw_text_expr, ACTIONS(389), 1, anon_sym_COLON, ACTIONS(397), 1, anon_sym_SLASH, [3970] = 2, ACTIONS(401), 1, anon_sym_LBRACE, ACTIONS(399), 4, sym_comment, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [3980] = 5, ACTIONS(361), 1, anon_sym_AT, ACTIONS(363), 1, anon_sym_POUND, ACTIONS(369), 1, sym_raw_text_expr, ACTIONS(375), 1, anon_sym_COLON, ACTIONS(381), 1, anon_sym_SLASH, [3996] = 2, ACTIONS(405), 1, anon_sym_LBRACE, ACTIONS(403), 4, sym_comment, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [4006] = 2, ACTIONS(409), 1, anon_sym_LBRACE, ACTIONS(407), 4, sym_comment, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [4016] = 2, ACTIONS(413), 1, anon_sym_LBRACE, ACTIONS(411), 4, sym_comment, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [4026] = 2, ACTIONS(417), 1, anon_sym_LBRACE, ACTIONS(415), 4, sym_comment, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [4036] = 2, ACTIONS(421), 1, anon_sym_LBRACE, ACTIONS(419), 4, sym_comment, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [4046] = 2, ACTIONS(425), 1, anon_sym_LBRACE, ACTIONS(423), 4, sym_comment, anon_sym_LT, aux_sym__text_token1, anon_sym_LBRACE_RBRACE, [4056] = 4, ACTIONS(361), 1, anon_sym_AT, ACTIONS(363), 1, anon_sym_POUND, ACTIONS(369), 1, sym_raw_text_expr, ACTIONS(427), 1, anon_sym_SLASH, [4069] = 4, ACTIONS(429), 1, anon_sym_if, ACTIONS(431), 1, anon_sym_each, ACTIONS(433), 1, anon_sym_await, ACTIONS(435), 1, anon_sym_key, [4082] = 4, ACTIONS(361), 1, anon_sym_AT, ACTIONS(363), 1, anon_sym_POUND, ACTIONS(369), 1, sym_raw_text_expr, ACTIONS(381), 1, anon_sym_SLASH, [4095] = 4, ACTIONS(361), 1, anon_sym_AT, ACTIONS(363), 1, anon_sym_POUND, ACTIONS(369), 1, sym_raw_text_expr, ACTIONS(387), 1, anon_sym_SLASH, [4108] = 4, ACTIONS(361), 1, anon_sym_AT, ACTIONS(363), 1, anon_sym_POUND, ACTIONS(369), 1, sym_raw_text_expr, ACTIONS(397), 1, anon_sym_SLASH, [4121] = 1, ACTIONS(437), 4, anon_sym_GT, anon_sym_SLASH_GT, aux_sym_attribute_name_token1, anon_sym_LBRACE, [4128] = 1, ACTIONS(267), 4, anon_sym_GT, anon_sym_SLASH_GT, aux_sym_attribute_name_token1, anon_sym_LBRACE, [4135] = 1, ACTIONS(439), 4, anon_sym_GT, anon_sym_SLASH_GT, aux_sym_attribute_name_token1, anon_sym_LBRACE, [4142] = 1, ACTIONS(441), 4, anon_sym_GT, anon_sym_SLASH_GT, aux_sym_attribute_name_token1, anon_sym_LBRACE, [4149] = 1, ACTIONS(443), 4, anon_sym_GT, anon_sym_SLASH_GT, aux_sym_attribute_name_token1, anon_sym_LBRACE, [4156] = 4, ACTIONS(361), 1, anon_sym_AT, ACTIONS(363), 1, anon_sym_POUND, ACTIONS(369), 1, sym_raw_text_expr, ACTIONS(391), 1, anon_sym_SLASH, [4169] = 1, ACTIONS(445), 4, anon_sym_GT, anon_sym_SLASH_GT, aux_sym_attribute_name_token1, anon_sym_LBRACE, [4176] = 4, ACTIONS(361), 1, anon_sym_AT, ACTIONS(363), 1, anon_sym_POUND, ACTIONS(369), 1, sym_raw_text_expr, ACTIONS(373), 1, anon_sym_SLASH, [4189] = 1, ACTIONS(359), 4, anon_sym_GT, anon_sym_EQ, aux_sym_attribute_name_token1, anon_sym_LBRACE, [4196] = 2, ACTIONS(447), 1, anon_sym_EQ, ACTIONS(351), 3, anon_sym_GT, aux_sym_attribute_name_token1, anon_sym_LBRACE, [4205] = 4, ACTIONS(361), 1, anon_sym_AT, ACTIONS(363), 1, anon_sym_POUND, ACTIONS(369), 1, sym_raw_text_expr, ACTIONS(449), 1, anon_sym_SLASH, [4218] = 1, ACTIONS(451), 4, anon_sym_GT, anon_sym_SLASH_GT, aux_sym_attribute_name_token1, anon_sym_LBRACE, [4225] = 4, ACTIONS(361), 1, anon_sym_AT, ACTIONS(363), 1, anon_sym_POUND, ACTIONS(367), 1, anon_sym_SLASH, ACTIONS(369), 1, sym_raw_text_expr, [4238] = 1, ACTIONS(445), 3, anon_sym_GT, aux_sym_attribute_name_token1, anon_sym_LBRACE, [4244] = 1, ACTIONS(439), 3, anon_sym_GT, aux_sym_attribute_name_token1, anon_sym_LBRACE, [4250] = 3, ACTIONS(41), 1, anon_sym_LT_SLASH, ACTIONS(453), 1, sym_raw_text, STATE(55), 1, sym_end_tag, [4260] = 3, ACTIONS(57), 1, anon_sym_LT_SLASH, ACTIONS(455), 1, sym_raw_text, STATE(105), 1, sym_end_tag, [4270] = 3, ACTIONS(57), 1, anon_sym_LT_SLASH, ACTIONS(457), 1, sym_raw_text, STATE(108), 1, sym_end_tag, [4280] = 3, ACTIONS(459), 1, anon_sym_html, ACTIONS(461), 1, anon_sym_debug, ACTIONS(463), 1, anon_sym_const, [4290] = 3, ACTIONS(41), 1, anon_sym_LT_SLASH, ACTIONS(465), 1, sym_raw_text, STATE(58), 1, sym_end_tag, [4300] = 1, ACTIONS(267), 3, anon_sym_GT, aux_sym_attribute_name_token1, anon_sym_LBRACE, [4306] = 3, ACTIONS(467), 1, anon_sym_html, ACTIONS(469), 1, anon_sym_debug, ACTIONS(471), 1, anon_sym_const, [4316] = 1, ACTIONS(437), 3, anon_sym_GT, aux_sym_attribute_name_token1, anon_sym_LBRACE, [4322] = 1, ACTIONS(443), 3, anon_sym_GT, aux_sym_attribute_name_token1, anon_sym_LBRACE, [4328] = 3, ACTIONS(361), 1, anon_sym_AT, ACTIONS(363), 1, anon_sym_POUND, ACTIONS(369), 1, sym_raw_text_expr, [4338] = 3, ACTIONS(473), 1, sym__start_tag_name, ACTIONS(475), 1, sym__script_start_tag_name, ACTIONS(477), 1, sym__style_start_tag_name, [4348] = 3, ACTIONS(363), 1, anon_sym_POUND, ACTIONS(479), 1, anon_sym_AT, ACTIONS(481), 1, sym_raw_text_expr, [4358] = 3, ACTIONS(475), 1, sym__script_start_tag_name, ACTIONS(477), 1, sym__style_start_tag_name, ACTIONS(483), 1, sym__start_tag_name, [4368] = 1, ACTIONS(441), 3, anon_sym_GT, aux_sym_attribute_name_token1, anon_sym_LBRACE, [4374] = 1, ACTIONS(451), 3, anon_sym_GT, aux_sym_attribute_name_token1, anon_sym_LBRACE, [4380] = 1, ACTIONS(485), 2, sym_raw_text, anon_sym_LT_SLASH, [4385] = 2, ACTIONS(487), 1, sym_raw_text_expr, ACTIONS(489), 1, sym_raw_text_each, [4392] = 2, ACTIONS(491), 1, anon_sym_RBRACE, ACTIONS(493), 1, sym_raw_text_expr, [4399] = 1, ACTIONS(495), 2, sym_raw_text, anon_sym_LT_SLASH, [4404] = 2, ACTIONS(497), 1, anon_sym_RBRACE, ACTIONS(499), 1, sym_raw_text_expr, [4411] = 2, ACTIONS(501), 1, anon_sym_RBRACE, ACTIONS(503), 1, anon_sym_if, [4418] = 2, ACTIONS(505), 1, anon_sym_DQUOTE, ACTIONS(507), 1, aux_sym_quoted_attribute_value_token2, [4425] = 2, ACTIONS(505), 1, anon_sym_SQUOTE, ACTIONS(509), 1, aux_sym_quoted_attribute_value_token1, [4432] = 2, ACTIONS(511), 1, anon_sym_SQUOTE, ACTIONS(513), 1, aux_sym_quoted_attribute_value_token1, [4439] = 2, ACTIONS(41), 1, anon_sym_LT_SLASH, STATE(85), 1, sym_end_tag, [4446] = 2, ACTIONS(41), 1, anon_sym_LT_SLASH, STATE(81), 1, sym_end_tag, [4453] = 2, ACTIONS(515), 1, anon_sym_RBRACE, ACTIONS(517), 1, sym_raw_text_expr, [4460] = 2, ACTIONS(519), 1, sym_raw_text_expr, ACTIONS(521), 1, sym_raw_text_await, [4467] = 2, ACTIONS(523), 1, anon_sym_then, ACTIONS(525), 1, anon_sym_catch, [4474] = 2, ACTIONS(511), 1, anon_sym_DQUOTE, ACTIONS(527), 1, aux_sym_quoted_attribute_value_token2, [4481] = 1, ACTIONS(529), 2, sym_raw_text, anon_sym_LT_SLASH, [4486] = 2, ACTIONS(57), 1, anon_sym_LT_SLASH, STATE(133), 1, sym_end_tag, [4493] = 2, ACTIONS(57), 1, anon_sym_LT_SLASH, STATE(134), 1, sym_end_tag, [4500] = 2, ACTIONS(531), 1, anon_sym_RBRACE, ACTIONS(533), 1, sym_raw_text_expr, [4507] = 2, ACTIONS(535), 1, anon_sym_RBRACE, ACTIONS(537), 1, sym_raw_text_expr, [4514] = 2, ACTIONS(539), 1, anon_sym_RBRACE, ACTIONS(541), 1, sym_raw_text_expr, [4521] = 2, ACTIONS(543), 1, anon_sym_RBRACE, ACTIONS(545), 1, sym_raw_text_expr, [4528] = 2, ACTIONS(547), 1, anon_sym_RBRACE, ACTIONS(549), 1, sym_raw_text_expr, [4535] = 2, ACTIONS(551), 1, anon_sym_RBRACE, ACTIONS(553), 1, sym_raw_text_expr, [4542] = 1, ACTIONS(555), 2, sym_raw_text, anon_sym_LT_SLASH, [4547] = 1, ACTIONS(557), 1, anon_sym_GT, [4551] = 1, ACTIONS(559), 1, anon_sym_RBRACE, [4555] = 1, ACTIONS(561), 1, anon_sym_RBRACE, [4559] = 1, ACTIONS(563), 1, sym_raw_text_expr, [4563] = 1, ACTIONS(565), 1, sym_raw_text_expr, [4567] = 1, ACTIONS(567), 1, sym_raw_text_expr, [4571] = 1, ACTIONS(569), 1, sym_raw_text_expr, [4575] = 1, ACTIONS(571), 1, anon_sym_else, [4579] = 1, ACTIONS(573), 1, anon_sym_if, [4583] = 1, ACTIONS(575), 1, anon_sym_else, [4587] = 1, ACTIONS(577), 1, anon_sym_each, [4591] = 1, ACTIONS(579), 1, anon_sym_await, [4595] = 1, ACTIONS(581), 1, anon_sym_key, [4599] = 1, ACTIONS(583), 1, anon_sym_RBRACE, [4603] = 1, ACTIONS(585), 1, sym__end_tag_name, [4607] = 1, ACTIONS(587), 1, anon_sym_RBRACE, [4611] = 1, ACTIONS(589), 1, anon_sym_RBRACE, [4615] = 1, ACTIONS(591), 1, anon_sym_RBRACE, [4619] = 1, ACTIONS(593), 1, anon_sym_RBRACE, [4623] = 1, ACTIONS(595), 1, anon_sym_GT, [4627] = 1, ACTIONS(597), 1, anon_sym_as, [4631] = 1, ACTIONS(599), 1, anon_sym_RBRACE, [4635] = 1, ACTIONS(601), 1, anon_sym_RBRACE, [4639] = 1, ACTIONS(603), 1, anon_sym_then, [4643] = 1, ACTIONS(605), 1, ts_builtin_sym_end, [4647] = 1, ACTIONS(607), 1, anon_sym_RBRACE, [4651] = 1, ACTIONS(609), 1, anon_sym_RBRACE, [4655] = 1, ACTIONS(611), 1, anon_sym_RBRACE, [4659] = 1, ACTIONS(613), 1, anon_sym_RBRACE, [4663] = 1, ACTIONS(615), 1, anon_sym_RBRACE, [4667] = 1, ACTIONS(617), 1, anon_sym_RBRACE, [4671] = 1, ACTIONS(619), 1, anon_sym_RBRACE, [4675] = 1, ACTIONS(621), 1, anon_sym_RBRACE, [4679] = 1, ACTIONS(623), 1, anon_sym_RBRACE, [4683] = 1, ACTIONS(501), 1, anon_sym_RBRACE, [4687] = 1, ACTIONS(625), 1, anon_sym_SQUOTE, [4691] = 1, ACTIONS(625), 1, anon_sym_DQUOTE, [4695] = 1, ACTIONS(627), 1, anon_sym_RBRACE, [4699] = 1, ACTIONS(629), 1, anon_sym_RBRACE, [4703] = 1, ACTIONS(631), 1, anon_sym_RBRACE, [4707] = 1, ACTIONS(633), 1, anon_sym_RBRACE, [4711] = 1, ACTIONS(525), 1, anon_sym_catch, [4715] = 1, ACTIONS(635), 1, sym__end_tag_name, [4719] = 1, ACTIONS(637), 1, sym_raw_text_expr, [4723] = 1, ACTIONS(639), 1, anon_sym_if, [4727] = 1, ACTIONS(641), 1, sym_raw_text_expr, [4731] = 1, ACTIONS(643), 1, anon_sym_each, [4735] = 1, ACTIONS(645), 1, anon_sym_RBRACE, [4739] = 1, ACTIONS(647), 1, anon_sym_await, [4743] = 1, ACTIONS(649), 1, anon_sym_RBRACE, [4747] = 1, ACTIONS(651), 1, anon_sym_RBRACE, [4751] = 1, ACTIONS(653), 1, anon_sym_key, [4755] = 1, ACTIONS(655), 1, anon_sym_DQUOTE, [4759] = 1, ACTIONS(655), 1, anon_sym_SQUOTE, [4763] = 1, ACTIONS(657), 1, anon_sym_RBRACE, [4767] = 1, ACTIONS(659), 1, anon_sym_RBRACE, }; static uint32_t ts_small_parse_table_map[] = { [SMALL_STATE(2)] = 0, [SMALL_STATE(3)] = 65, [SMALL_STATE(4)] = 130, [SMALL_STATE(5)] = 195, [SMALL_STATE(6)] = 260, [SMALL_STATE(7)] = 325, [SMALL_STATE(8)] = 390, [SMALL_STATE(9)] = 455, [SMALL_STATE(10)] = 520, [SMALL_STATE(11)] = 585, [SMALL_STATE(12)] = 650, [SMALL_STATE(13)] = 715, [SMALL_STATE(14)] = 780, [SMALL_STATE(15)] = 841, [SMALL_STATE(16)] = 902, [SMALL_STATE(17)] = 965, [SMALL_STATE(18)] = 1026, [SMALL_STATE(19)] = 1089, [SMALL_STATE(20)] = 1150, [SMALL_STATE(21)] = 1213, [SMALL_STATE(22)] = 1276, [SMALL_STATE(23)] = 1337, [SMALL_STATE(24)] = 1398, [SMALL_STATE(25)] = 1459, [SMALL_STATE(26)] = 1520, [SMALL_STATE(27)] = 1578, [SMALL_STATE(28)] = 1635, [SMALL_STATE(29)] = 1692, [SMALL_STATE(30)] = 1749, [SMALL_STATE(31)] = 1806, [SMALL_STATE(32)] = 1863, [SMALL_STATE(33)] = 1920, [SMALL_STATE(34)] = 1977, [SMALL_STATE(35)] = 2034, [SMALL_STATE(36)] = 2091, [SMALL_STATE(37)] = 2148, [SMALL_STATE(38)] = 2205, [SMALL_STATE(39)] = 2262, [SMALL_STATE(40)] = 2319, [SMALL_STATE(41)] = 2376, [SMALL_STATE(42)] = 2433, [SMALL_STATE(43)] = 2490, [SMALL_STATE(44)] = 2547, [SMALL_STATE(45)] = 2604, [SMALL_STATE(46)] = 2627, [SMALL_STATE(47)] = 2648, [SMALL_STATE(48)] = 2671, [SMALL_STATE(49)] = 2692, [SMALL_STATE(50)] = 2715, [SMALL_STATE(51)] = 2736, [SMALL_STATE(52)] = 2759, [SMALL_STATE(53)] = 2771, [SMALL_STATE(54)] = 2783, [SMALL_STATE(55)] = 2795, [SMALL_STATE(56)] = 2807, [SMALL_STATE(57)] = 2827, [SMALL_STATE(58)] = 2847, [SMALL_STATE(59)] = 2859, [SMALL_STATE(60)] = 2871, [SMALL_STATE(61)] = 2883, [SMALL_STATE(62)] = 2895, [SMALL_STATE(63)] = 2907, [SMALL_STATE(64)] = 2919, [SMALL_STATE(65)] = 2931, [SMALL_STATE(66)] = 2943, [SMALL_STATE(67)] = 2955, [SMALL_STATE(68)] = 2975, [SMALL_STATE(69)] = 2987, [SMALL_STATE(70)] = 2999, [SMALL_STATE(71)] = 3011, [SMALL_STATE(72)] = 3023, [SMALL_STATE(73)] = 3035, [SMALL_STATE(74)] = 3047, [SMALL_STATE(75)] = 3067, [SMALL_STATE(76)] = 3079, [SMALL_STATE(77)] = 3091, [SMALL_STATE(78)] = 3103, [SMALL_STATE(79)] = 3115, [SMALL_STATE(80)] = 3127, [SMALL_STATE(81)] = 3139, [SMALL_STATE(82)] = 3151, [SMALL_STATE(83)] = 3163, [SMALL_STATE(84)] = 3175, [SMALL_STATE(85)] = 3187, [SMALL_STATE(86)] = 3199, [SMALL_STATE(87)] = 3211, [SMALL_STATE(88)] = 3223, [SMALL_STATE(89)] = 3235, [SMALL_STATE(90)] = 3247, [SMALL_STATE(91)] = 3259, [SMALL_STATE(92)] = 3279, [SMALL_STATE(93)] = 3291, [SMALL_STATE(94)] = 3303, [SMALL_STATE(95)] = 3315, [SMALL_STATE(96)] = 3327, [SMALL_STATE(97)] = 3339, [SMALL_STATE(98)] = 3351, [SMALL_STATE(99)] = 3362, [SMALL_STATE(100)] = 3373, [SMALL_STATE(101)] = 3384, [SMALL_STATE(102)] = 3395, [SMALL_STATE(103)] = 3406, [SMALL_STATE(104)] = 3417, [SMALL_STATE(105)] = 3428, [SMALL_STATE(106)] = 3439, [SMALL_STATE(107)] = 3450, [SMALL_STATE(108)] = 3461, [SMALL_STATE(109)] = 3472, [SMALL_STATE(110)] = 3483, [SMALL_STATE(111)] = 3494, [SMALL_STATE(112)] = 3505, [SMALL_STATE(113)] = 3516, [SMALL_STATE(114)] = 3527, [SMALL_STATE(115)] = 3538, [SMALL_STATE(116)] = 3549, [SMALL_STATE(117)] = 3560, [SMALL_STATE(118)] = 3571, [SMALL_STATE(119)] = 3582, [SMALL_STATE(120)] = 3593, [SMALL_STATE(121)] = 3604, [SMALL_STATE(122)] = 3615, [SMALL_STATE(123)] = 3626, [SMALL_STATE(124)] = 3637, [SMALL_STATE(125)] = 3648, [SMALL_STATE(126)] = 3659, [SMALL_STATE(127)] = 3670, [SMALL_STATE(128)] = 3681, [SMALL_STATE(129)] = 3692, [SMALL_STATE(130)] = 3703, [SMALL_STATE(131)] = 3714, [SMALL_STATE(132)] = 3725, [SMALL_STATE(133)] = 3736, [SMALL_STATE(134)] = 3747, [SMALL_STATE(135)] = 3758, [SMALL_STATE(136)] = 3769, [SMALL_STATE(137)] = 3780, [SMALL_STATE(138)] = 3790, [SMALL_STATE(139)] = 3800, [SMALL_STATE(140)] = 3810, [SMALL_STATE(141)] = 3820, [SMALL_STATE(142)] = 3828, [SMALL_STATE(143)] = 3844, [SMALL_STATE(144)] = 3860, [SMALL_STATE(145)] = 3876, [SMALL_STATE(146)] = 3886, [SMALL_STATE(147)] = 3902, [SMALL_STATE(148)] = 3912, [SMALL_STATE(149)] = 3928, [SMALL_STATE(150)] = 3944, [SMALL_STATE(151)] = 3954, [SMALL_STATE(152)] = 3970, [SMALL_STATE(153)] = 3980, [SMALL_STATE(154)] = 3996, [SMALL_STATE(155)] = 4006, [SMALL_STATE(156)] = 4016, [SMALL_STATE(157)] = 4026, [SMALL_STATE(158)] = 4036, [SMALL_STATE(159)] = 4046, [SMALL_STATE(160)] = 4056, [SMALL_STATE(161)] = 4069, [SMALL_STATE(162)] = 4082, [SMALL_STATE(163)] = 4095, [SMALL_STATE(164)] = 4108, [SMALL_STATE(165)] = 4121, [SMALL_STATE(166)] = 4128, [SMALL_STATE(167)] = 4135, [SMALL_STATE(168)] = 4142, [SMALL_STATE(169)] = 4149, [SMALL_STATE(170)] = 4156, [SMALL_STATE(171)] = 4169, [SMALL_STATE(172)] = 4176, [SMALL_STATE(173)] = 4189, [SMALL_STATE(174)] = 4196, [SMALL_STATE(175)] = 4205, [SMALL_STATE(176)] = 4218, [SMALL_STATE(177)] = 4225, [SMALL_STATE(178)] = 4238, [SMALL_STATE(179)] = 4244, [SMALL_STATE(180)] = 4250, [SMALL_STATE(181)] = 4260, [SMALL_STATE(182)] = 4270, [SMALL_STATE(183)] = 4280, [SMALL_STATE(184)] = 4290, [SMALL_STATE(185)] = 4300, [SMALL_STATE(186)] = 4306, [SMALL_STATE(187)] = 4316, [SMALL_STATE(188)] = 4322, [SMALL_STATE(189)] = 4328, [SMALL_STATE(190)] = 4338, [SMALL_STATE(191)] = 4348, [SMALL_STATE(192)] = 4358, [SMALL_STATE(193)] = 4368, [SMALL_STATE(194)] = 4374, [SMALL_STATE(195)] = 4380, [SMALL_STATE(196)] = 4385, [SMALL_STATE(197)] = 4392, [SMALL_STATE(198)] = 4399, [SMALL_STATE(199)] = 4404, [SMALL_STATE(200)] = 4411, [SMALL_STATE(201)] = 4418, [SMALL_STATE(202)] = 4425, [SMALL_STATE(203)] = 4432, [SMALL_STATE(204)] = 4439, [SMALL_STATE(205)] = 4446, [SMALL_STATE(206)] = 4453, [SMALL_STATE(207)] = 4460, [SMALL_STATE(208)] = 4467, [SMALL_STATE(209)] = 4474, [SMALL_STATE(210)] = 4481, [SMALL_STATE(211)] = 4486, [SMALL_STATE(212)] = 4493, [SMALL_STATE(213)] = 4500, [SMALL_STATE(214)] = 4507, [SMALL_STATE(215)] = 4514, [SMALL_STATE(216)] = 4521, [SMALL_STATE(217)] = 4528, [SMALL_STATE(218)] = 4535, [SMALL_STATE(219)] = 4542, [SMALL_STATE(220)] = 4547, [SMALL_STATE(221)] = 4551, [SMALL_STATE(222)] = 4555, [SMALL_STATE(223)] = 4559, [SMALL_STATE(224)] = 4563, [SMALL_STATE(225)] = 4567, [SMALL_STATE(226)] = 4571, [SMALL_STATE(227)] = 4575, [SMALL_STATE(228)] = 4579, [SMALL_STATE(229)] = 4583, [SMALL_STATE(230)] = 4587, [SMALL_STATE(231)] = 4591, [SMALL_STATE(232)] = 4595, [SMALL_STATE(233)] = 4599, [SMALL_STATE(234)] = 4603, [SMALL_STATE(235)] = 4607, [SMALL_STATE(236)] = 4611, [SMALL_STATE(237)] = 4615, [SMALL_STATE(238)] = 4619, [SMALL_STATE(239)] = 4623, [SMALL_STATE(240)] = 4627, [SMALL_STATE(241)] = 4631, [SMALL_STATE(242)] = 4635, [SMALL_STATE(243)] = 4639, [SMALL_STATE(244)] = 4643, [SMALL_STATE(245)] = 4647, [SMALL_STATE(246)] = 4651, [SMALL_STATE(247)] = 4655, [SMALL_STATE(248)] = 4659, [SMALL_STATE(249)] = 4663, [SMALL_STATE(250)] = 4667, [SMALL_STATE(251)] = 4671, [SMALL_STATE(252)] = 4675, [SMALL_STATE(253)] = 4679, [SMALL_STATE(254)] = 4683, [SMALL_STATE(255)] = 4687, [SMALL_STATE(256)] = 4691, [SMALL_STATE(257)] = 4695, [SMALL_STATE(258)] = 4699, [SMALL_STATE(259)] = 4703, [SMALL_STATE(260)] = 4707, [SMALL_STATE(261)] = 4711, [SMALL_STATE(262)] = 4715, [SMALL_STATE(263)] = 4719, [SMALL_STATE(264)] = 4723, [SMALL_STATE(265)] = 4727, [SMALL_STATE(266)] = 4731, [SMALL_STATE(267)] = 4735, [SMALL_STATE(268)] = 4739, [SMALL_STATE(269)] = 4743, [SMALL_STATE(270)] = 4747, [SMALL_STATE(271)] = 4751, [SMALL_STATE(272)] = 4755, [SMALL_STATE(273)] = 4759, [SMALL_STATE(274)] = 4763, [SMALL_STATE(275)] = 4767, }; static TSParseActionEntry ts_parse_actions[] = { [0] = {.entry = {.count = 0, .reusable = false}}, [1] = {.entry = {.count = 1, .reusable = false}}, RECOVER(), [3] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_document, 0), [5] = {.entry = {.count = 1, .reusable = true}}, SHIFT(190), [7] = {.entry = {.count = 1, .reusable = true}}, SHIFT(31), [9] = {.entry = {.count = 1, .reusable = false}}, SHIFT(189), [11] = {.entry = {.count = 1, .reusable = true}}, SHIFT(44), [13] = {.entry = {.count = 1, .reusable = false}}, SHIFT(146), [15] = {.entry = {.count = 1, .reusable = true}}, SHIFT(7), [17] = {.entry = {.count = 1, .reusable = false}}, SHIFT(151), [19] = {.entry = {.count = 1, .reusable = true}}, SHIFT(8), [21] = {.entry = {.count = 1, .reusable = false}}, SHIFT(142), [23] = {.entry = {.count = 1, .reusable = true}}, SHIFT(2), [25] = {.entry = {.count = 1, .reusable = true}}, SHIFT(12), [27] = {.entry = {.count = 1, .reusable = false}}, SHIFT(149), [29] = {.entry = {.count = 1, .reusable = true}}, SHIFT(5), [31] = {.entry = {.count = 1, .reusable = true}}, SHIFT(10), [33] = {.entry = {.count = 1, .reusable = true}}, SHIFT(25), [35] = {.entry = {.count = 1, .reusable = false}}, SHIFT(144), [37] = {.entry = {.count = 1, .reusable = false}}, SHIFT(148), [39] = {.entry = {.count = 1, .reusable = false}}, SHIFT(192), [41] = {.entry = {.count = 1, .reusable = true}}, SHIFT(262), [43] = {.entry = {.count = 1, .reusable = true}}, SHIFT(26), [45] = {.entry = {.count = 1, .reusable = false}}, SHIFT(191), [47] = {.entry = {.count = 1, .reusable = true}}, SHIFT(80), [49] = {.entry = {.count = 1, .reusable = true}}, SHIFT(15), [51] = {.entry = {.count = 1, .reusable = true}}, SHIFT(16), [53] = {.entry = {.count = 1, .reusable = true}}, SHIFT(65), [55] = {.entry = {.count = 1, .reusable = false}}, SHIFT(153), [57] = {.entry = {.count = 1, .reusable = true}}, SHIFT(234), [59] = {.entry = {.count = 1, .reusable = true}}, SHIFT(21), [61] = {.entry = {.count = 1, .reusable = true}}, SHIFT(99), [63] = {.entry = {.count = 1, .reusable = true}}, SHIFT(135), [65] = {.entry = {.count = 1, .reusable = true}}, SHIFT(23), [67] = {.entry = {.count = 1, .reusable = false}}, SHIFT(143), [69] = {.entry = {.count = 1, .reusable = true}}, SHIFT(19), [71] = {.entry = {.count = 2, .reusable = false}}, REDUCE(aux_sym_document_repeat1, 2), SHIFT_REPEAT(192), [74] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_document_repeat1, 2), [76] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_document_repeat1, 2), SHIFT_REPEAT(26), [79] = {.entry = {.count = 2, .reusable = false}}, REDUCE(aux_sym_document_repeat1, 2), SHIFT_REPEAT(191), [82] = {.entry = {.count = 1, .reusable = false}}, SHIFT(177), [84] = {.entry = {.count = 1, .reusable = true}}, SHIFT(41), [86] = {.entry = {.count = 1, .reusable = false}}, SHIFT(162), [88] = {.entry = {.count = 1, .reusable = true}}, SHIFT(37), [90] = {.entry = {.count = 1, .reusable = false}}, SHIFT(170), [92] = {.entry = {.count = 1, .reusable = true}}, SHIFT(42), [94] = {.entry = {.count = 1, .reusable = false}}, SHIFT(175), [96] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_document, 1), [98] = {.entry = {.count = 1, .reusable = true}}, SHIFT(38), [100] = {.entry = {.count = 1, .reusable = false}}, SHIFT(163), [102] = {.entry = {.count = 1, .reusable = true}}, SHIFT(40), [104] = {.entry = {.count = 1, .reusable = false}}, SHIFT(172), [106] = {.entry = {.count = 1, .reusable = true}}, SHIFT(43), [108] = {.entry = {.count = 1, .reusable = false}}, SHIFT(160), [110] = {.entry = {.count = 1, .reusable = false}}, SHIFT(164), [112] = {.entry = {.count = 1, .reusable = true}}, SHIFT(35), [114] = {.entry = {.count = 1, .reusable = true}}, SHIFT(27), [116] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_document_repeat1, 2), SHIFT_REPEAT(190), [119] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_document_repeat1, 2), SHIFT_REPEAT(44), [122] = {.entry = {.count = 2, .reusable = false}}, REDUCE(aux_sym_document_repeat1, 2), SHIFT_REPEAT(189), [125] = {.entry = {.count = 1, .reusable = true}}, SHIFT(94), [127] = {.entry = {.count = 1, .reusable = true}}, SHIFT(96), [129] = {.entry = {.count = 1, .reusable = true}}, SHIFT(141), [131] = {.entry = {.count = 1, .reusable = true}}, SHIFT(226), [133] = {.entry = {.count = 1, .reusable = true}}, SHIFT(176), [135] = {.entry = {.count = 1, .reusable = true}}, SHIFT(203), [137] = {.entry = {.count = 1, .reusable = true}}, SHIFT(209), [139] = {.entry = {.count = 1, .reusable = true}}, SHIFT(54), [141] = {.entry = {.count = 1, .reusable = true}}, SHIFT(101), [143] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_start_tag_repeat1, 2), [145] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_start_tag_repeat1, 2), SHIFT_REPEAT(141), [148] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_start_tag_repeat1, 2), SHIFT_REPEAT(226), [151] = {.entry = {.count = 1, .reusable = true}}, SHIFT(53), [153] = {.entry = {.count = 1, .reusable = true}}, SHIFT(194), [155] = {.entry = {.count = 1, .reusable = true}}, SHIFT(202), [157] = {.entry = {.count = 1, .reusable = true}}, SHIFT(201), [159] = {.entry = {.count = 1, .reusable = true}}, SHIFT(263), [161] = {.entry = {.count = 1, .reusable = true}}, SHIFT(103), [163] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_catch_statement, 3), [165] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_catch_statement, 3), [167] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_self_closing_tag, 3), [169] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_self_closing_tag, 3), [171] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_start_tag, 3), [173] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_start_tag, 3), [175] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_style_element, 2), [177] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_style_element, 2), [179] = {.entry = {.count = 1, .reusable = true}}, SHIFT(210), [181] = {.entry = {.count = 1, .reusable = true}}, SHIFT(173), [183] = {.entry = {.count = 1, .reusable = true}}, SHIFT(195), [185] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_script_element, 2), [187] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_script_element, 2), [189] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_key_end_expr, 4), [191] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_key_end_expr, 4), [193] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_await_end_expr, 4), [195] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_await_end_expr, 4), [197] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_each_end_expr, 4), [199] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_each_end_expr, 4), [201] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_if_end_expr, 4), [203] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_if_end_expr, 4), [205] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_const_expr, 5), [207] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_const_expr, 5), [209] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_debug_expr, 5), [211] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_debug_expr, 5), [213] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_element, 2), [215] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_element, 2), [217] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_element, 1), [219] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_element, 1), [221] = {.entry = {.count = 1, .reusable = true}}, SHIFT(198), [223] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_html_expr, 5), [225] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_html_expr, 5), [227] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_if_statement, 2), [229] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_if_statement, 2), [231] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_then_statement, 3), [233] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_then_statement, 3), [235] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_each_statement, 2), [237] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_each_statement, 2), [239] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_await_statement, 2), [241] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_await_statement, 2), [243] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_key_statement, 2), [245] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_key_statement, 2), [247] = {.entry = {.count = 1, .reusable = true}}, SHIFT(219), [249] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_await_statement, 3), [251] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_await_statement, 3), [253] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_else_each_statement, 3), [255] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_else_each_statement, 3), [257] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_else_if_statement, 3), [259] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_else_if_statement, 3), [261] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_else_statement, 3), [263] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_else_statement, 3), [265] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_expression, 3), [267] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_expression, 3), [269] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_element, 3), [271] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_element, 3), [273] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_script_element, 3), [275] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_script_element, 3), [277] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_end_tag, 3), [279] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_end_tag, 3), [281] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_const_expr, 4), [283] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_const_expr, 4), [285] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_debug_expr, 4), [287] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_debug_expr, 4), [289] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_style_element, 3), [291] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_style_element, 3), [293] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_else_statement, 2), [295] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_else_statement, 2), [297] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_html_expr, 4), [299] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_html_expr, 4), [301] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_else_if_statement, 2), [303] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_else_if_statement, 2), [305] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_if_statement, 3), [307] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_if_statement, 3), [309] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_else_each_statement, 2), [311] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_else_each_statement, 2), [313] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_start_tag_repeat1, 2), SHIFT_REPEAT(173), [316] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_start_tag_repeat1, 2), SHIFT_REPEAT(263), [319] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_each_statement, 3), [321] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_each_statement, 3), [323] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_then_statement, 2), [325] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_then_statement, 2), [327] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_start_tag, 4), [329] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_start_tag, 4), [331] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_catch_statement, 2), [333] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_catch_statement, 2), [335] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_self_closing_tag, 4), [337] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_self_closing_tag, 4), [339] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_key_statement, 3), [341] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_key_statement, 3), [343] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_key_start_expr, 5), [345] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_key_start_expr, 5), [347] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_each_start_expr, 7), [349] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_each_start_expr, 7), [351] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_attribute, 1), [353] = {.entry = {.count = 1, .reusable = true}}, SHIFT(46), [355] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_else_expr, 4), [357] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_else_expr, 4), [359] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_attribute_name, 1), [361] = {.entry = {.count = 1, .reusable = true}}, SHIFT(183), [363] = {.entry = {.count = 1, .reusable = true}}, SHIFT(161), [365] = {.entry = {.count = 1, .reusable = true}}, SHIFT(208), [367] = {.entry = {.count = 1, .reusable = true}}, SHIFT(231), [369] = {.entry = {.count = 1, .reusable = true}}, SHIFT(241), [371] = {.entry = {.count = 1, .reusable = true}}, SHIFT(229), [373] = {.entry = {.count = 1, .reusable = true}}, SHIFT(230), [375] = {.entry = {.count = 1, .reusable = true}}, SHIFT(261), [377] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_then_expr, 4), [379] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_then_expr, 4), [381] = {.entry = {.count = 1, .reusable = true}}, SHIFT(268), [383] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_catch_expr, 4), [385] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_catch_expr, 4), [387] = {.entry = {.count = 1, .reusable = true}}, SHIFT(266), [389] = {.entry = {.count = 1, .reusable = true}}, SHIFT(227), [391] = {.entry = {.count = 1, .reusable = true}}, SHIFT(228), [393] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_await_start_expr, 7, .production_id = 2), [395] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_await_start_expr, 7, .production_id = 2), [397] = {.entry = {.count = 1, .reusable = true}}, SHIFT(264), [399] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_else_if_expr, 6), [401] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_else_if_expr, 6), [403] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_await_start_expr, 5), [405] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_await_start_expr, 5), [407] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_if_start_expr, 5), [409] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_if_start_expr, 5), [411] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_else_if_expr, 5), [413] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_else_if_expr, 5), [415] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_then_expr, 5), [417] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_then_expr, 5), [419] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_catch_expr, 5), [421] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_catch_expr, 5), [423] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_each_start_expr, 5), [425] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_each_start_expr, 5), [427] = {.entry = {.count = 1, .reusable = true}}, SHIFT(232), [429] = {.entry = {.count = 1, .reusable = true}}, SHIFT(223), [431] = {.entry = {.count = 1, .reusable = true}}, SHIFT(196), [433] = {.entry = {.count = 1, .reusable = true}}, SHIFT(207), [435] = {.entry = {.count = 1, .reusable = true}}, SHIFT(224), [437] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_quoted_attribute_value, 3), [439] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_attribute, 1, .production_id = 1), [441] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_attribute, 3), [443] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_quoted_attribute_value, 2), [445] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_expr_attribute_value, 1), [447] = {.entry = {.count = 1, .reusable = true}}, SHIFT(50), [449] = {.entry = {.count = 1, .reusable = true}}, SHIFT(271), [451] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_attribute_value, 1), [453] = {.entry = {.count = 1, .reusable = true}}, SHIFT(204), [455] = {.entry = {.count = 1, .reusable = true}}, SHIFT(212), [457] = {.entry = {.count = 1, .reusable = true}}, SHIFT(211), [459] = {.entry = {.count = 1, .reusable = true}}, SHIFT(218), [461] = {.entry = {.count = 1, .reusable = true}}, SHIFT(217), [463] = {.entry = {.count = 1, .reusable = true}}, SHIFT(214), [465] = {.entry = {.count = 1, .reusable = true}}, SHIFT(205), [467] = {.entry = {.count = 1, .reusable = true}}, SHIFT(213), [469] = {.entry = {.count = 1, .reusable = true}}, SHIFT(215), [471] = {.entry = {.count = 1, .reusable = true}}, SHIFT(216), [473] = {.entry = {.count = 1, .reusable = true}}, SHIFT(47), [475] = {.entry = {.count = 1, .reusable = true}}, SHIFT(67), [477] = {.entry = {.count = 1, .reusable = true}}, SHIFT(74), [479] = {.entry = {.count = 1, .reusable = true}}, SHIFT(186), [481] = {.entry = {.count = 1, .reusable = true}}, SHIFT(222), [483] = {.entry = {.count = 1, .reusable = true}}, SHIFT(49), [485] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_style_start_tag, 4), [487] = {.entry = {.count = 1, .reusable = true}}, SHIFT(238), [489] = {.entry = {.count = 1, .reusable = true}}, SHIFT(240), [491] = {.entry = {.count = 1, .reusable = true}}, SHIFT(145), [493] = {.entry = {.count = 1, .reusable = true}}, SHIFT(221), [495] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_script_start_tag, 3), [497] = {.entry = {.count = 1, .reusable = true}}, SHIFT(147), [499] = {.entry = {.count = 1, .reusable = true}}, SHIFT(275), [501] = {.entry = {.count = 1, .reusable = true}}, SHIFT(140), [503] = {.entry = {.count = 1, .reusable = true}}, SHIFT(206), [505] = {.entry = {.count = 1, .reusable = false}}, SHIFT(188), [507] = {.entry = {.count = 1, .reusable = true}}, SHIFT(256), [509] = {.entry = {.count = 1, .reusable = true}}, SHIFT(255), [511] = {.entry = {.count = 1, .reusable = false}}, SHIFT(169), [513] = {.entry = {.count = 1, .reusable = true}}, SHIFT(273), [515] = {.entry = {.count = 1, .reusable = true}}, SHIFT(156), [517] = {.entry = {.count = 1, .reusable = true}}, SHIFT(267), [519] = {.entry = {.count = 1, .reusable = true}}, SHIFT(242), [521] = {.entry = {.count = 1, .reusable = true}}, SHIFT(243), [523] = {.entry = {.count = 1, .reusable = true}}, SHIFT(197), [525] = {.entry = {.count = 1, .reusable = true}}, SHIFT(199), [527] = {.entry = {.count = 1, .reusable = true}}, SHIFT(272), [529] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_script_start_tag, 4), [531] = {.entry = {.count = 1, .reusable = true}}, SHIFT(87), [533] = {.entry = {.count = 1, .reusable = true}}, SHIFT(246), [535] = {.entry = {.count = 1, .reusable = true}}, SHIFT(104), [537] = {.entry = {.count = 1, .reusable = true}}, SHIFT(236), [539] = {.entry = {.count = 1, .reusable = true}}, SHIFT(84), [541] = {.entry = {.count = 1, .reusable = true}}, SHIFT(247), [543] = {.entry = {.count = 1, .reusable = true}}, SHIFT(83), [545] = {.entry = {.count = 1, .reusable = true}}, SHIFT(248), [547] = {.entry = {.count = 1, .reusable = true}}, SHIFT(102), [549] = {.entry = {.count = 1, .reusable = true}}, SHIFT(235), [551] = {.entry = {.count = 1, .reusable = true}}, SHIFT(100), [553] = {.entry = {.count = 1, .reusable = true}}, SHIFT(233), [555] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_style_start_tag, 3), [557] = {.entry = {.count = 1, .reusable = true}}, SHIFT(111), [559] = {.entry = {.count = 1, .reusable = true}}, SHIFT(157), [561] = {.entry = {.count = 1, .reusable = true}}, SHIFT(79), [563] = {.entry = {.count = 1, .reusable = true}}, SHIFT(237), [565] = {.entry = {.count = 1, .reusable = true}}, SHIFT(245), [567] = {.entry = {.count = 1, .reusable = true}}, SHIFT(269), [569] = {.entry = {.count = 1, .reusable = true}}, SHIFT(257), [571] = {.entry = {.count = 1, .reusable = true}}, SHIFT(200), [573] = {.entry = {.count = 1, .reusable = true}}, SHIFT(253), [575] = {.entry = {.count = 1, .reusable = true}}, SHIFT(254), [577] = {.entry = {.count = 1, .reusable = true}}, SHIFT(259), [579] = {.entry = {.count = 1, .reusable = true}}, SHIFT(260), [581] = {.entry = {.count = 1, .reusable = true}}, SHIFT(274), [583] = {.entry = {.count = 1, .reusable = true}}, SHIFT(125), [585] = {.entry = {.count = 1, .reusable = true}}, SHIFT(220), [587] = {.entry = {.count = 1, .reusable = true}}, SHIFT(126), [589] = {.entry = {.count = 1, .reusable = true}}, SHIFT(127), [591] = {.entry = {.count = 1, .reusable = true}}, SHIFT(155), [593] = {.entry = {.count = 1, .reusable = true}}, SHIFT(159), [595] = {.entry = {.count = 1, .reusable = true}}, SHIFT(82), [597] = {.entry = {.count = 1, .reusable = true}}, SHIFT(265), [599] = {.entry = {.count = 1, .reusable = true}}, SHIFT(136), [601] = {.entry = {.count = 1, .reusable = true}}, SHIFT(154), [603] = {.entry = {.count = 1, .reusable = true}}, SHIFT(225), [605] = {.entry = {.count = 1, .reusable = true}}, ACCEPT_INPUT(), [607] = {.entry = {.count = 1, .reusable = true}}, SHIFT(137), [609] = {.entry = {.count = 1, .reusable = true}}, SHIFT(68), [611] = {.entry = {.count = 1, .reusable = true}}, SHIFT(64), [613] = {.entry = {.count = 1, .reusable = true}}, SHIFT(63), [615] = {.entry = {.count = 1, .reusable = true}}, SHIFT(62), [617] = {.entry = {.count = 1, .reusable = true}}, SHIFT(61), [619] = {.entry = {.count = 1, .reusable = true}}, SHIFT(60), [621] = {.entry = {.count = 1, .reusable = true}}, SHIFT(59), [623] = {.entry = {.count = 1, .reusable = true}}, SHIFT(129), [625] = {.entry = {.count = 1, .reusable = true}}, SHIFT(187), [627] = {.entry = {.count = 1, .reusable = true}}, SHIFT(166), [629] = {.entry = {.count = 1, .reusable = true}}, SHIFT(185), [631] = {.entry = {.count = 1, .reusable = true}}, SHIFT(130), [633] = {.entry = {.count = 1, .reusable = true}}, SHIFT(131), [635] = {.entry = {.count = 1, .reusable = true}}, SHIFT(239), [637] = {.entry = {.count = 1, .reusable = true}}, SHIFT(258), [639] = {.entry = {.count = 1, .reusable = true}}, SHIFT(249), [641] = {.entry = {.count = 1, .reusable = true}}, SHIFT(270), [643] = {.entry = {.count = 1, .reusable = true}}, SHIFT(250), [645] = {.entry = {.count = 1, .reusable = true}}, SHIFT(152), [647] = {.entry = {.count = 1, .reusable = true}}, SHIFT(251), [649] = {.entry = {.count = 1, .reusable = true}}, SHIFT(150), [651] = {.entry = {.count = 1, .reusable = true}}, SHIFT(138), [653] = {.entry = {.count = 1, .reusable = true}}, SHIFT(252), [655] = {.entry = {.count = 1, .reusable = true}}, SHIFT(165), [657] = {.entry = {.count = 1, .reusable = true}}, SHIFT(132), [659] = {.entry = {.count = 1, .reusable = true}}, SHIFT(158), }; #ifdef __cplusplus extern "C" { #endif void *tree_sitter_svelte_external_scanner_create(void); void tree_sitter_svelte_external_scanner_destroy(void *); bool tree_sitter_svelte_external_scanner_scan(void *, TSLexer *, const bool *); unsigned tree_sitter_svelte_external_scanner_serialize(void *, char *); void tree_sitter_svelte_external_scanner_deserialize(void *, const char *, unsigned); #ifdef _WIN32 #define extern __declspec(dllexport) #endif extern const TSLanguage *tree_sitter_svelte(void) { static TSLanguage language = { .version = LANGUAGE_VERSION, .symbol_count = SYMBOL_COUNT, .alias_count = ALIAS_COUNT, .token_count = TOKEN_COUNT, .external_token_count = EXTERNAL_TOKEN_COUNT, .symbol_names = ts_symbol_names, .symbol_metadata = ts_symbol_metadata, .parse_table = (const uint16_t *)ts_parse_table, .parse_actions = ts_parse_actions, .lex_modes = ts_lex_modes, .alias_sequences = (const TSSymbol *)ts_alias_sequences, .max_alias_sequence_length = MAX_ALIAS_SEQUENCE_LENGTH, .lex_fn = ts_lex, .external_scanner = { (const bool *)ts_external_scanner_states, ts_external_scanner_symbol_map, tree_sitter_svelte_external_scanner_create, tree_sitter_svelte_external_scanner_destroy, tree_sitter_svelte_external_scanner_scan, tree_sitter_svelte_external_scanner_serialize, tree_sitter_svelte_external_scanner_deserialize, }, .field_count = FIELD_COUNT, .large_state_count = LARGE_STATE_COUNT, .small_parse_table = (const uint16_t *)ts_small_parse_table, .small_parse_table_map = (const uint32_t *)ts_small_parse_table_map, .public_symbol_map = ts_symbol_map, .alias_map = ts_non_terminal_alias_map, .state_count = STATE_COUNT, }; return &language; } #ifdef __cplusplus } #endif
wixa/IFC_Driver_lib
src/IFC_Driver.h
#include "fw/src/mgos_init.h" #include <stdbool.h> #include <stdio.h> #include "fw/src/mgos_gpio.h" #include "freertos/FreeRTOS.h" #include "freertos/timers.h" bool mgos_IFC_Driver_init(void); // Required - initialisation function void test_on (int led); void led_start (void *pvParameters);
wixa/IFC_Driver_lib
src/IFC_Driver.c
<reponame>wixa/IFC_Driver_lib #include "IFC_Driver.h" // NOTE: library init function must be called mgos_LIBNAME_init() bool mgos_IFC_Driver_init(void) { return true; } void led_start (void *pvParameters){ for( ;; ){ printf("led_start started!!!!!!!!!! \n"); int led_on; led_on = (intptr_t) pvParameters; mgos_gpio_set_mode(led_on, MGOS_GPIO_MODE_OUTPUT); mgos_gpio_write (led_on, 1); vTaskDelay(100); } } void test_on (int led){ printf("test_on %d\n", led); xTaskCreate(led_start, "led_on", 2048,(void *)led, 4, NULL); }
compileSuccess/ttcc-sim
lib/rang.h
// Rang library, copied from https://github.com/agauniyal/rang // You can ignore this file, it is used for printing to the console in color. #ifndef RANG_DOT_HPP #define RANG_DOT_HPP #if defined(__unix__) || defined(__unix) || defined(__linux__) #define OS_LINUX #elif defined(WIN32) || defined(_WIN32) || defined(_WIN64) #define OS_WIN #elif defined(__APPLE__) || defined(__MACH__) #define OS_MAC #else #error Unknown Platform #endif #if defined(OS_LINUX) || defined(OS_MAC) #include <unistd.h> #elif defined(OS_WIN) #if defined(_WIN32_WINNT) && (_WIN32_WINNT < 0x0600) #error "Please include rang.hpp before any windows system headers or set _WIN32_WINNT at least to _WIN32_WINNT_VISTA" #elif !defined(_WIN32_WINNT) #define _WIN32_WINNT _WIN32_WINNT_VISTA #endif #include <io.h> #include <memory> #include <windows.h> // Only defined in windows 10 onwards, redefining in lower windows since it // doesn't gets used in lower versions // https://docs.microsoft.com/en-us/windows/console/getconsolemode #ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004 #endif #endif #include <algorithm> #include <atomic> #include <cstdlib> #include <cstring> #include <iostream> namespace rang { /* For better compability with most of terminals do not use any style settings * except of reset, bold and reversed. * Note that on Windows terminals bold style is same as fgB color. */ enum class style { reset = 0, bold = 1, dim = 2, italic = 3, underline = 4, blink = 5, rblink = 6, reversed = 7, conceal = 8, crossed = 9 }; enum class fg { black = 30, red = 31, green = 32, yellow = 33, blue = 34, magenta = 35, cyan = 36, gray = 37, reset = 39 }; enum class bg { black = 40, red = 41, green = 42, yellow = 43, blue = 44, magenta = 45, cyan = 46, gray = 47, reset = 49 }; enum class fgB { black = 90, red = 91, green = 92, yellow = 93, blue = 94, magenta = 95, cyan = 96, gray = 97 }; enum class bgB { black = 100, red = 101, green = 102, yellow = 103, blue = 104, magenta = 105, cyan = 106, gray = 107 }; enum class control { // Behaviour of rang function calls Off = 0, // toggle off rang style/color calls Auto = 1, // (Default) autodect terminal and colorize if needed Force = 2 // force ansi color output to non terminal streams }; // Use rang::setControlMode to set rang control mode enum class winTerm { // Windows Terminal Mode Auto = 0, // (Default) automatically detects wheter Ansi or Native API Ansi = 1, // Force use Ansi API Native = 2 // Force use Native API }; // Use rang::setWinTermMode to explicitly set terminal API for Windows // Calling rang::setWinTermMode have no effect on other OS namespace rang_implementation { inline std::atomic<control>& controlMode() noexcept { static std::atomic<control> value(control::Auto); return value; } inline std::atomic<winTerm>& winTermMode() noexcept { static std::atomic<winTerm> termMode(winTerm::Auto); return termMode; } inline bool supportsColor() noexcept { #if defined(OS_LINUX) || defined(OS_MAC) static const bool result = [] { const char* Terms[] = {"ansi", "color", "console", "cygwin", "gnome", "konsole", "kterm", "linux", "msys", "putty", "rxvt", "screen", "vt100", "xterm"}; const char* env_p = std::getenv("TERM"); if (env_p == nullptr) { return false; } return std::any_of(std::begin(Terms), std::end(Terms), [&](const char* term) { return std::strstr(env_p, term) != nullptr; }); }(); #elif defined(OS_WIN) // All windows versions support colors through native console methods static constexpr bool result = true; #endif return result; } #ifdef OS_WIN inline bool isMsysPty(int fd) noexcept { // Dynamic load for binary compability with old Windows const auto ptrGetFileInformationByHandleEx = reinterpret_cast<decltype(&GetFileInformationByHandleEx)>( GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetFileInformationByHandleEx")); if (!ptrGetFileInformationByHandleEx) { return false; } HANDLE h = reinterpret_cast<HANDLE>(_get_osfhandle(fd)); if (h == INVALID_HANDLE_VALUE) { return false; } // Check that it's a pipe: if (GetFileType(h) != FILE_TYPE_PIPE) { return false; } // POD type is binary compatible with FILE_NAME_INFO from WinBase.h // It have the same alignment and used to avoid UB in caller code struct MY_FILE_NAME_INFO { DWORD FileNameLength; WCHAR FileName[MAX_PATH]; }; auto pNameInfo = std::unique_ptr<MY_FILE_NAME_INFO>(new (std::nothrow) MY_FILE_NAME_INFO()); if (!pNameInfo) { return false; } // Check pipe name is template of // {"cygwin-","msys-"}XXXXXXXXXXXXXXX-ptyX-XX if (!ptrGetFileInformationByHandleEx(h, FileNameInfo, pNameInfo.get(), sizeof(MY_FILE_NAME_INFO))) { return false; } std::wstring name(pNameInfo->FileName, pNameInfo->FileNameLength / sizeof(WCHAR)); if ((name.find(L"msys-") == std::wstring::npos && name.find(L"cygwin-") == std::wstring::npos) || name.find(L"-pty") == std::wstring::npos) { return false; } return true; } #endif inline bool isTerminal(const std::streambuf* osbuf) noexcept { using std::cerr; using std::clog; using std::cout; #if defined(OS_LINUX) || defined(OS_MAC) if (osbuf == cout.rdbuf()) { static const bool cout_term = isatty(fileno(stdout)) != 0; return cout_term; } else if (osbuf == cerr.rdbuf() || osbuf == clog.rdbuf()) { static const bool cerr_term = isatty(fileno(stderr)) != 0; return cerr_term; } #elif defined(OS_WIN) if (osbuf == cout.rdbuf()) { static const bool cout_term = (_isatty(_fileno(stdout)) || isMsysPty(_fileno(stdout))); return cout_term; } else if (osbuf == cerr.rdbuf() || osbuf == clog.rdbuf()) { static const bool cerr_term = (_isatty(_fileno(stderr)) || isMsysPty(_fileno(stderr))); return cerr_term; } #endif return false; } template<typename T> using enableStd = typename std::enable_if< std::is_same<T, rang::style>::value || std::is_same<T, rang::fg>::value || std::is_same<T, rang::bg>::value || std::is_same<T, rang::fgB>::value || std::is_same<T, rang::bgB>::value, std::ostream&>::type; #ifdef OS_WIN struct SGR { // Select Graphic Rendition parameters for Windows console BYTE fgColor; // foreground color (0-15) lower 3 rgb bits + intense bit BYTE bgColor; // background color (0-15) lower 3 rgb bits + intense bit BYTE bold; // emulated as FOREGROUND_INTENSITY bit BYTE underline; // emulated as BACKGROUND_INTENSITY bit BOOLEAN inverse; // swap foreground/bold & background/underline BOOLEAN conceal; // set foreground/bold to background/underline }; enum class AttrColor : BYTE { // Color attributes for console screen buffer black = 0, red = 4, green = 2, yellow = 6, blue = 1, magenta = 5, cyan = 3, gray = 7 }; inline HANDLE getConsoleHandle(const std::streambuf* osbuf) noexcept { if (osbuf == std::cout.rdbuf()) { static const HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE); return hStdout; } else if (osbuf == std::cerr.rdbuf() || osbuf == std::clog.rdbuf()) { static const HANDLE hStderr = GetStdHandle(STD_ERROR_HANDLE); return hStderr; } return INVALID_HANDLE_VALUE; } inline bool setWinTermAnsiColors(const std::streambuf* osbuf) noexcept { HANDLE h = getConsoleHandle(osbuf); if (h == INVALID_HANDLE_VALUE) { return false; } DWORD dwMode = 0; if (!GetConsoleMode(h, &dwMode)) { return false; } dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; if (!SetConsoleMode(h, dwMode)) { return false; } return true; } inline bool supportsAnsi(const std::streambuf* osbuf) noexcept { using std::cerr; using std::clog; using std::cout; if (osbuf == cout.rdbuf()) { static const bool cout_ansi = (isMsysPty(_fileno(stdout)) || setWinTermAnsiColors(osbuf)); return cout_ansi; } else if (osbuf == cerr.rdbuf() || osbuf == clog.rdbuf()) { static const bool cerr_ansi = (isMsysPty(_fileno(stderr)) || setWinTermAnsiColors(osbuf)); return cerr_ansi; } return false; } inline const SGR& defaultState() noexcept { static const SGR defaultSgr = []() -> SGR { CONSOLE_SCREEN_BUFFER_INFO info; WORD attrib = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info) || GetConsoleScreenBufferInfo(GetStdHandle(STD_ERROR_HANDLE), &info)) { attrib = info.wAttributes; } SGR sgr = {0, 0, 0, 0, FALSE, FALSE}; sgr.fgColor = attrib & 0x0F; sgr.bgColor = (attrib & 0xF0) >> 4; return sgr; }(); return defaultSgr; } inline BYTE ansi2attr(BYTE rgb) noexcept { static const AttrColor rev[8] = {AttrColor::black, AttrColor::red, AttrColor::green, AttrColor::yellow, AttrColor::blue, AttrColor::magenta, AttrColor::cyan, AttrColor::gray}; return static_cast<BYTE>(rev[rgb]); } inline void setWinSGR(rang::bg col, SGR& state) noexcept { if (col != rang::bg::reset) { state.bgColor = ansi2attr(static_cast<BYTE>(col) - 40); } else { state.bgColor = defaultState().bgColor; } } inline void setWinSGR(rang::fg col, SGR& state) noexcept { if (col != rang::fg::reset) { state.fgColor = ansi2attr(static_cast<BYTE>(col) - 30); } else { state.fgColor = defaultState().fgColor; } } inline void setWinSGR(rang::bgB col, SGR& state) noexcept { state.bgColor = (BACKGROUND_INTENSITY >> 4) | ansi2attr(static_cast<BYTE>(col) - 100); } inline void setWinSGR(rang::fgB col, SGR& state) noexcept { state.fgColor = FOREGROUND_INTENSITY | ansi2attr(static_cast<BYTE>(col) - 90); } inline void setWinSGR(rang::style style, SGR& state) noexcept { switch (style) { case rang::style::reset: state = defaultState(); break; case rang::style::bold: state.bold = FOREGROUND_INTENSITY; break; case rang::style::underline: case rang::style::blink: state.underline = BACKGROUND_INTENSITY; break; case rang::style::reversed: state.inverse = TRUE; break; case rang::style::conceal: state.conceal = TRUE; break; default: break; } } inline SGR& current_state() noexcept { static SGR state = defaultState(); return state; } inline WORD SGR2Attr(const SGR& state) noexcept { WORD attrib = 0; if (state.conceal) { if (state.inverse) { attrib = (state.fgColor << 4) | state.fgColor; if (state.bold) attrib |= FOREGROUND_INTENSITY | BACKGROUND_INTENSITY; } else { attrib = (state.bgColor << 4) | state.bgColor; if (state.underline) attrib |= FOREGROUND_INTENSITY | BACKGROUND_INTENSITY; } } else if (state.inverse) { attrib = (state.fgColor << 4) | state.bgColor; if (state.bold) attrib |= BACKGROUND_INTENSITY; if (state.underline) attrib |= FOREGROUND_INTENSITY; } else { attrib = state.fgColor | (state.bgColor << 4) | state.bold | state.underline; } return attrib; } template<typename T> inline void setWinColorAnsi(std::ostream& os, T const value) { os << "\033[" << static_cast<int>(value) << "m"; } template<typename T> inline void setWinColorNative(std::ostream& os, T const value) { const HANDLE h = getConsoleHandle(os.rdbuf()); if (h != INVALID_HANDLE_VALUE) { setWinSGR(value, current_state()); // Out all buffered text to console with previous settings: os.flush(); SetConsoleTextAttribute(h, SGR2Attr(current_state())); } } template<typename T> inline enableStd<T> setColor(std::ostream& os, T const value) { if (winTermMode() == winTerm::Auto) { if (supportsAnsi(os.rdbuf())) { setWinColorAnsi(os, value); } else { setWinColorNative(os, value); } } else if (winTermMode() == winTerm::Ansi) { setWinColorAnsi(os, value); } else { setWinColorNative(os, value); } return os; } #else template<typename T> inline enableStd<T> setColor(std::ostream& os, T const value) { return os << "\033[" << static_cast<int>(value) << "m"; } #endif } // namespace rang_implementation template<typename T> inline rang_implementation::enableStd<T> operator<<(std::ostream& os, const T value) { const control option = rang_implementation::controlMode(); switch (option) { case control::Auto: return rang_implementation::supportsColor() && rang_implementation::isTerminal(os.rdbuf()) ? rang_implementation::setColor(os, value) : os; case control::Force: return rang_implementation::setColor(os, value); default: return os; } } inline void setWinTermMode(const rang::winTerm value) noexcept { rang_implementation::winTermMode() = value; } inline void setControlMode(const control value) noexcept { rang_implementation::controlMode() = value; } } // namespace rang #undef OS_LINUX #undef OS_WIN #undef OS_MAC #endif /* ifndef RANG_DOT_HPP */
compileSuccess/ttcc-sim
lib/cog.h
#ifndef COG_H #define COG_H #include <iostream> #include <string> class Cog { public: Cog() : level(0), hp(0), maxHP(0), trapped(0), luredKnockback(0), luredRounds(0), presLured(false), currLureMax(0), soaked(0), toUnsoak(false), executive(false), defense(0), version(0) {} Cog(int lvl) : Cog(lvl, false, 0) {} Cog(int lvl, bool exe, size_t ver) : level(lvl), hp((lvl + 1) * (lvl + 2) * (exe ? 1.5 : 1)), maxHP((lvl + 1) * (lvl + 2) * (exe ? 1.5 : 1)), trapped(0), luredKnockback(0), luredRounds(0), presLured(false), currLureMax(0), soaked(0), toUnsoak(false), executive(exe), defense(lvl == 1 ? 2 : (lvl >= 14 ? (exe ? 70 : 65) : ((lvl + exe - 1) * 5))), version(ver) {} Cog(std::string lvl) : Cog(std::stoi(lvl.substr(0, lvl.find("."))), lvl.find(".exe") != std::string::npos, lvl.find("v") != std::string::npos ? std::stoi(lvl.substr(lvl.find("v") + 1)) : 0) {} ~Cog() {} Cog& operator=(const Cog& other); int getHP() const { return hp; } int getLevel() const { return level; } std::string getLevelName() const; void hit(int damage); void setTrap(int trap) { if (!trapped) trapped = trap; } void untrap() { trapped = 0; } int getTrap() const { return trapped; } void setLured(int state, bool pres, int bonus = 0); void unlure(); int getLured() const { return luredRounds; } int getLuredKnockback() const { return luredKnockback; } bool getPresLured() const { return presLured; }; void setSoaked(int state); void reduceSoaked(int state); int getSoaked() const { return soaked; } int getDefense() const { return defense; } void update(); int getLureAccCap() const; size_t getPrintSize() const; friend std::ostream& operator<<(std::ostream& out, const Cog& cog); protected: int level; int hp; int maxHP; int trapped; int luredKnockback; int luredRounds; bool presLured; int currLureMax; int soaked; bool toUnsoak; bool executive; int defense; size_t version; }; #endif
compileSuccess/ttcc-sim
lib/battle.h
#ifndef BATTLE_H #define BATTLE_H #include "cogset.h" #include "gag_collection.h" #include <iostream> #include <map> #include <queue> #include <stdexcept> #include <vector> #define EXE_CHANCE 30 struct GagComparator { bool operator()(const Gag& first, const Gag& second) const { return first.damage > second.damage; } }; struct Strategy { std::vector<Gag> gags; std::vector<Sos> soses; Strategy(std::vector<Gag> gags, std::vector<Sos> soses) : gags(gags), soses(soses) {} }; struct Buff { int effect; int maxRounds; int effectiveRounds; Buff() {} Buff(int e, int r) : effect(e), maxRounds(r), effectiveRounds(r) {} }; class Battle { public: Battle() {} Battle(std::string file_path); Battle(std::string file_path, const std::queue<Cog>& cogQueue); Battle(std::string file_path, const std::vector<Cog>& set); Battle& operator=(const Battle& other) { cogset = other.cogset; loader = other.loader; posDefinition = other.posDefinition; autoPres = other.autoPres; autoHit = other.autoHit; lineInput = other.lineInput; return *this; } ~Battle() {} void generate(); void battle(); void reset(); void setPresState(bool presState) { autoPres = presState; } void setHitState(bool hitState) { autoHit = hitState; } void setUpdate(bool updateState) { cogset.setUpdate(updateState); } void setInputState(bool inputState) { lineInput = inputState; } void setPrint(bool printState) { cogset.setPrint(printState); } Cogset& getCogset() { return cogset; } void setCogset(std::vector<Cog> set) { cogset = Cogset(set); } Strategy parseOneliner(std::string strat); Gag parseGag(std::string command); void turn(std::vector<Gag> strat); void affect(std::vector<Sos> soses); private: Cogset cogset; std::queue<Cog> loader; std::vector<Gag> successfulGags; std::map<SosKind, Buff> buffs; GagCollection gc; std::map<std::string, int> posDefinition = { {"left", 0}, {"mid-left", 1}, {"mid", 1}, {"mid-right", 2}, {"right", 0} }; int validQuickhand(std::string quickhand) const; bool isPluralGag(std::string gag) const; std::vector<Gag> accuracyFilter(const std::vector<Gag>& gags); int getBonus(const Gag& g) const; bool autoPres = true; bool autoHit = true; bool lineInput = true; }; #endif
compileSuccess/ttcc-sim
lib/cogset.h
<reponame>compileSuccess/ttcc-sim #ifndef COGSET_H #define COGSET_H #include "cog.h" #include "gag_collection.h" #include <queue> #include <stdexcept> #include <stdlib.h> class Cogset { public: Cogset() {} Cogset(std::vector<Cog> set) : cogs(set) {} Cogset& operator=(const Cogset& other); void load(); void load(std::queue<Cog>& q); void update(); size_t getSize() const { return cogs.size(); } const Cog& getCog(int pos) const; Cog& getCog(int pos); bool allDead() const; int numLured() const; void gagCheck(const Gag& gagchoice) const; void attack(const std::vector<int>& affected); void attack(const std::vector<int>& affected, char type); void fireTurn(const std::vector<Gag>& fires); void trapTurn(const std::vector<Gag>& traps); void lureTurn(const std::vector<Gag>& lures); void soundTurn(const std::vector<Gag>& sounds); void squirtTurn(const std::vector<Gag>& squirts); void zapTurn(const std::vector<Gag>& zaps); void throwTurn(const std::vector<Gag>& throws); void dropTurn(const std::vector<Gag>& drops); friend std::ostream& operator<<(std::ostream& out, const Cogset& cogset); void print(const std::vector<int>& affected) const; void setPrint(bool printState) { printCogset = printState; } void setUpdate(bool updateState) { roundUpdate = updateState; } private: std::vector<Cog> cogs; bool printCogset = true; bool roundUpdate = false; }; #endif
compileSuccess/ttcc-sim
lib/gag_collection.h
#ifndef GAG_COLLECTION_H #define GAG_COLLECTION_H #include <map> #include <stdexcept> #include <stdlib.h> #include <string> enum class GagKind { PASS = -1, TOONUP = 0, TRAP = 1, LURE = 2, SOUND = 3, SQUIRT = 4, ZAP = 5, THROW = 6, DROP = 7, FIRE = 8, }; enum class SosKind { TOONUP = 0, TRAP = 1, LURE = 2, SOUND = 3, SQUIRT = 4, ZAP = 5, THROW = 6, DROP = 7, ALL = 8, ACC = 9, ATTACK_DOWN = 10, }; class ToonSelection { public: ToonSelection() {} ToonSelection(std::string n) : name(n) {} virtual bool isBuff() = 0; std::string name; }; class Gag : public ToonSelection { public: GagKind kind; unsigned short level; unsigned short damage; unsigned short accuracy; int target; bool prestiged; int passiveEffect; int bonusEffect = 0; bool isBuff() { return false; } Gag() : target(-1) { kind = GagKind::PASS; } Gag(GagKind k, unsigned short d, int t, bool p) : damage(d), target(t), prestiged(p) { kind = k; } Gag(GagKind k, std::string n, unsigned short l, unsigned short d, unsigned short a) : ToonSelection(n), kind(k), level(l), damage(d), accuracy(a), passiveEffect(0) {} Gag(GagKind k, std::string n, unsigned short l, unsigned short d, unsigned short a, int pe) : ToonSelection(n), kind(k), level(l), damage(d), accuracy(a), passiveEffect(pe) {} }; class Sos : public ToonSelection { public: SosKind kind; int passiveEffect; int duration; bool isBuff() { return true; } Sos() {} Sos(SosKind k, std::string n, int pe, int d) : ToonSelection(n), kind(k), passiveEffect(pe), duration(d) {} }; class GagCollection { public: static GagCollection read(const std::string& file_path); bool contains(std::string name) const { return isGag(name) || isSos(name); } bool isGag(std::string name) const { return gags.find(name) != gags.end(); } bool isSos(std::string name) const { return soses.find(name) != soses.end();; } const Gag& getGag(std::string name) const { return gags.at(name); } const Sos& getSos(std::string name) const { return soses.at(name); } const std::string& getGagTypeString(GagKind k) const { return gagTypeMap.at(k); } const std::string& getSosTypeString(SosKind k) const { return sosTypeMap.at(k); } private: std::map<std::string, Gag> gags; std::map<std::string, Sos> soses; std::map<GagKind, std::string> gagTypeMap; std::map<SosKind, std::string> sosTypeMap; }; #endif
compileSuccess/ttcc-sim
lib/colors.h
#ifndef COLORS_H #define COLORS_H #define TRAPPED rang::fgB::red << rang::style::bold #define LURED rang::bgB::green << rang::style::bold #define SOAKED rang::fgB::blue << rang::style::bold #define ZAPPED rang::fgB::yellow << rang::style::bold #define THROWN rang::fgB::gray << rang::style::bold #define DROPPED rang::fgB::cyan << rang::style::bold #define DEAD rang::bgB::red << rang::style::bold #define PRESLURED "*" #define DAMAGE rang::fgB::red << rang::style::bold #define KNOCKBACK rang::fgB::green << rang::style::bold #define COMBO rang::fgB::yellow << rang::style::bold #define ATTACKED "<" #define CONFIG rang::fgB::cyan << rang::style::bold #define PROMPT rang::fgB::magenta << rang::style::bold #endif
compileSuccess/ttcc-sim
lib/game_config.h
#ifndef GAME_CONFIG #define GAME_CONFIG #include <cstdint> #include <string> class GameConfig { public: bool autoPres = true; bool autoHit = true; bool roundUpdate = false; bool lineInput = true; std::string gagFilePath = "gags.txt"; static GameConfig read(std::string file); static bool toBool(std::string s); }; #endif
rebeccaserramari/Kyoshi
hapcolor.h
<reponame>rebeccaserramari/Kyoshi<filename>hapcolor.h #ifndef HAPCOLOR_H #define HAPCOLOR_H #include <iostream> #include <list> #include <vector> #include <string> #include <set> #include <unordered_set> #include <climits> #include <iostream> #include <memory> #include <iterator> #include <algorithm> #include <sstream> #include <tuple> #include <fstream> #include <math.h> #include <cmath> #include <map> #include <cassert> #include <time.h> void compute_hapcolor(std::vector<int>*,std::vector<int>*, std::vector<int>*, std::vector<std::string>*, float, std::vector<int>*, std::vector<int>*, std::vector<float>*, std::string, std::string); std::tuple<float, int, int> minimum(float*, int, bool, int, float); float fwd_bkw(std::vector<int>, std::vector<std::vector<int>>, std::string); float emission(int, int); float transition(int, int); float logSum(float, float); #endif
wwoods/job_stream
job_stream/debug_internals.h
#ifndef JOB_STREAM_DEBUG_INTERNALS_H_ #define JOB_STREAM_DEBUG_INTERNALS_H_ #include <stdexcept> #include <sstream> #if defined(__linux__) || defined(unix) || defined(__unix__) #define OS_LINUX 1 #elif defined(__APPLE__) #define OS_APPLE 1 #elif defined(_WIN32) || defined(_WIN64) #define OS_WINDOWS 1 #else #error "NO OS DETECTED" #endif /** Allows ERROR("Path not found: " << path) type throwing of errors. */ #define ERROR(msg) { std::ostringstream ss; ss << __FILE__ << ":" << __LINE__ \ << ":" << __FUNCTION__ << ": " << msg; \ throw std::runtime_error(ss.str()); } /** Allows ASSERT(cond, "AHHH" << path) type throwing of errors. */ #define ASSERT(cond, msg) if (!(cond)) ERROR(msg) #endif//JOB_STREAM_DEBUG_INTERNALS_H_
wwoods/job_stream
job_stream/job_stream.h
<filename>job_stream/job_stream.h<gh_stars>10-100 #ifndef JOB_STREAM_H_ #define JOB_STREAM_H_ #include "invoke.h" #include "message.h" #include "job.h" #include "processor.h" #include "serialization.h" #include "types.h" #include "yaml.h" #include <boost/mpi.hpp> #include <functional> #include <string> namespace job_stream { /** When you have a type where you either aren't sure or don't care what it is, use this. Used primarily for special types of jobs or reducers (see Frame) */ typedef job_stream::serialization::AnyType AnyType; /** Application exit codes for forced exits */ enum ApplicationRetval { RETVAL_OK = 0, RETVAL_CHECKPOINT_FORCED = 0x10, RETVAL_CHECKPOINT_WAS_DONE = 0x11, }; /** Specialized Job base class. */ template<typename T_derived, typename T_input> class Job : public job::JobBase { public: /** Note - don't use a constructor. Use postSetup() instead. */ Job() { //Template static member instantiation. Gotta reference it. _autoRegister.doNothing(); } /** Function to override that actually processes work */ virtual void handleWork(std::unique_ptr<T_input> work) = 0; /** Pass work into handleWork and possibly emit new tuples. */ virtual void dispatchWork(message::WorkRecord& input) { this->currentRecord = &input; input.putWorkInto(this->currentWork); { //timer scope processor::Processor::WorkTimer timer(this->processor, processor::Processor::TIME_USER); this->handleWork(std::move(this->currentWork)); } this->currentRecord = 0; } virtual bool wouldReduce(message::WorkRecord& work) { return false; } template<class T_output> void emit(T_output* o, const std::string& target = "") { this->emit(*o, target); } template<class T_output> void emit(std::unique_ptr<T_output>& o, const std::string& target = "") { this->emit(*o, target); } template<class T_output> void emit(std::unique_ptr<T_output>&& o, const std::string& target = "") { //r-value constructor - we can take o. We don't have to, but we //certainly can. this->emit(*o, target); o.reset(0); } template<class T_output> void emit(T_output&& output, const std::string& target = "") { processor::Processor::WorkTimer timer(this->processor, processor::Processor::TIME_SYSTEM); std::string nextTarget; if (target.empty()) { nextTarget = this->config["to"].template as<std::string>(); } else { nextTarget = this->config["to"][target] .template as<std::string>(); } std::unique_ptr<message::WorkRecord> wr(new message::WorkRecord( this->getTargetForJob(nextTarget), serialization::encodeAsPtr(output))); wr->chainFrom(*this->currentRecord); this->processor->addWork(std::move(wr)); } private: static thread_local std::unique_ptr<T_input> currentWork; virtual std::string getInputTypeName() { return typeid(T_input).name(); } friend class boost::serialization::access; /* Serialization for checkpoints; only used bottom up. You do not need to register your own derived classes! */ template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar & boost::serialization::base_object<job::JobBase>(*this); } /* Auto class registration. */ struct _AutoRegister { //http://stackoverflow.com/questions/1819131/c-static-member-initalization-template-fun-inside _AutoRegister() { job_stream::job::addJob(T_derived::NAME(), _AutoRegister::make); serialization::registerType<T_derived, Job<T_derived, T_input>, job::JobBase, job::SharedBase>(); } /** Called by constructor to force static member instantiation. */ void doNothing() {} static T_derived* make() { return new T_derived(); } }; static _AutoRegister _autoRegister; }; template<typename T_derived, typename T_input> thread_local std::unique_ptr<T_input> Job<T_derived, T_input>::currentWork; template<typename T_derived, typename T_input> typename Job<T_derived, T_input>::_AutoRegister Job<T_derived, T_input>::_autoRegister; /** Specialized reducer class. Default implementation relies on operator+, so have it defined (into T_accum from both T_accum and T_input) */ template<typename T_derived, typename T_accum, typename T_input = T_accum> class Reducer : public job::ReducerBase { public: /** Note - don't use a constructor. Use postSetup() instead. */ Reducer() { //Template static member instantiation. Gotta reference it. _autoRegister.doNothing(); } /** Called to initialize the accumulator for this reduce. May be called several times on different hosts, whose results will later be merged in handleJoin(). */ virtual void handleInit(T_accum& current) {} /** Used to add a new output to this accumulator */ virtual void handleAdd(T_accum& current, std::unique_ptr<T_input> work) = 0; /** Called to join this Reducer with the accumulator from another */ virtual void handleJoin(T_accum& current, std::unique_ptr<T_accum> other) = 0; /** Called when the reduction is complete, or nearly - recur() may be used to keep the reduction alive (inject new work into this reduction). */ virtual void handleDone(T_accum& current) = 0; /** Called by system to call handleDone() with proper setup */ virtual bool dispatchDone(uint64_t reduceTag) { this->setCurrentReduce(reduceTag); this->currentRecord = this->currentReduce->originalWork.get(); this->hadRecurrence = false; this->targetIsModule = true; { //timer scope processor::Processor::WorkTimer timer(this->processor, processor::Processor::TIME_USER); this->handleDone(*this->currentReduce->accumulator); } this->targetIsModule = false; this->currentRecord = 0; this->unsetCurrentReduce(); if (!this->hadRecurrence) { //The processor that calls this function ends up calling //this->reduceMap.erase(reduceTag) for us with a lock on our //mutex. This is done in the processor so that no //checkpoint-state-changing operations happen outside of //the processor's lock. return true; } return false; } /** Called by system to call handleInit() with proper setup. Also gets the reduce ring started and sets up calculation done checks. Returns true if a new ring was started, false if one was continued. */ virtual bool dispatchInit(message::WorkRecord& work) { uint64_t tag = 1; int homeRank = 0; bool reallyInit = true; Lock lock(this->reduceMapMutex); //So this is a tiny hack (for elegance though!), but essentially //if our work's target is the root module, that means root has //a reducer. But since init work can go anywhere, and is not //part of a closed system in that it originates from a single //WorkRecord, we have to use reserved tagId 1 to refer to a top //level reducer (whose parent is 0, which stops the program from //prematurely exiting). if (work.getTarget().size() != 0) { homeRank = this->processor->getRank(); //Takes the non-primary processor lock, so this is OK. tag = this->processor->getNextReduceTag(); if (this->reduceMap.count(tag) != 0) { std::ostringstream ss; ss << "Bad tag? Duplicate " << tag; throw std::runtime_error(ss.str()); } } else { //This path is only for tag 1 if (homeRank != this->processor->getRank() || this->reduceMap.count(tag) != 0) { reallyInit = false; } } if (reallyInit) { //Make a patch for the reduceMap which will erase this record on //checkpoint restore. this->reduceMapPatches[tag] = ""; this->processor->registerReduceReset(this, tag); //Fill out the reduceMap with our new information. job::ReduceAccumulator<T_accum>& record = this->reduceMap[tag]; record.originalWork.reset(new message::WorkRecord( work.serialized())); record.accumulator.reset(new T_accum()); record.gotFirstWork = false; record.shouldBePurged = false; record.mutex.lock(); { //timer scope processor::Processor::WorkTimer timer(this->processor, processor::Processor::TIME_USER); this->handleInit(*record.accumulator); } //Track when this reduction is finished this->processor->startRingTest(tag, work.getReduceTag(), this); } //Now that we've backed up the original work, overwrite the reduce //params. work.setReduce(homeRank, tag); return reallyInit; } /** Called by system to call handleAdd() with proper setup */ virtual void dispatchAdd(message::WorkRecord& work) { this->currentRecord = &work; this->setCurrentReduce(work.getReduceTag()); work.putWorkInto(this->currentWork); { //timer scope processor::Processor::WorkTimer timer(this->processor, processor::Processor::TIME_USER); this->handleAdd(*this->currentReduce->accumulator, std::move(this->currentWork)); } this->unsetCurrentReduce(); this->currentRecord = 0; } /** Called by system to call handleJoin() with proper setup */ virtual void dispatchJoin(message::WorkRecord& work) { this->currentRecord = &work; this->setCurrentReduce(work.getReduceTag()); work.putWorkInto(this->currentJoin); { //timer scope processor::Processor::WorkTimer timer(this->processor, processor::Processor::TIME_USER); this->handleJoin(*this->currentReduce->accumulator, std::move(this->currentJoin)); } this->unsetCurrentReduce(); this->currentRecord = 0; } template<class T_output> void emit(std::unique_ptr<T_output>& o) { this->emit(*o); } template<class T_output> void emit(std::unique_ptr<T_output>&& o) { this->emit(*o); } template<class T_output> void emit(T_output* o) { this->emit(*o); } /** Output some work from this module */ template<class T_output> void emit(T_output&& output) { processor::Processor::WorkTimer timer(this->processor, processor::Processor::TIME_SYSTEM); std::unique_ptr<message::WorkRecord> wr(new message::WorkRecord( this->getTargetForReducer(), serialization::encodeAsPtr(output))); wr->chainFrom(*this->currentRecord); this->processor->addWork(std::move(wr)); } template<class T_output> void recur(std::unique_ptr<T_output>& output, const std::string& target = "") { this->recur(*output, target); } template<class T_output> void recur(std::unique_ptr<T_output>&& output, const std::string& target = "") { this->recur(*output, target); } template<class T_output> void recur(T_output* output, const std::string& target = "") { this->recur(*output, target); } /** Output some work back into this module at job named under config recurTo.target. If target is empty (default), send back to module input. */ template<class T_output> void recur(T_output&& output, const std::string& target = "") { processor::Processor::WorkTimer timer(this->processor, processor::Processor::TIME_SYSTEM); //Make sure the chain takes... bit of a hack, but we need the //currentRecord (tuple that caused our reduce) to maintain its //original reduce tag and information in case it itself is part of //a reduce. int oldRank = this->currentRecord->getReduceHomeRank(); uint64_t oldTag = this->currentRecord->getReduceTag(); this->currentRecord->setReduce(this->processor->getRank(), this->currentReduceTag); std::vector<std::string> ntarget; if (target.empty()) { if (!this->config["recurTo"]) { ntarget = this->getTargetForJob( this->parent->config["input"] .template as<std::string>()); } else { ntarget = this->getTargetForJob( this->config["recurTo"].template as< std::string>()); } } else { ntarget = this->getTargetForJob( this->config["recurTo"][target].template as< std::string>()); } std::unique_ptr<message::WorkRecord> wr(new message::WorkRecord( ntarget, serialization::encodeAsPtr(output))); wr->chainFrom(*this->currentRecord); this->processor->addWork(std::move(wr)); //Restore old reduce information and set hadRecurrence so that our //reduction ring isn't marked dead this->currentRecord->setReduce(oldRank, oldTag); this->hadRecurrence = true; } private: static thread_local uint64_t currentReduceTag; static thread_local job::ReduceAccumulator<T_accum>* currentReduce; static thread_local std::unique_ptr<T_input> currentWork; static thread_local std::unique_ptr<T_accum> currentJoin; /** Used in dispatchDone() to see if we had recurrence. If we did not, the reduction is finished. */ static thread_local bool hadRecurrence; std::map<uint64_t, job::ReduceAccumulator<T_accum>> reduceMap; /** Mutex for altering reduceMap's structure. Note that when this mutex is taken, the processor's mutex MUST NOT be taken inside of its lock (if already locked, that's OK). This affects e.g. dispatchInit when we get our reduce tag for a new ring. That is why the processor uses a different lock for that functionality. */ Mutex reduceMapMutex; /** User data checkpointed before it is modified. */ std::map<uint64_t, std::string> reduceMapPatches; virtual std::string getInputTypeName() { return typeid(T_input).name(); } /** Purges checkpoint reset information. Called after processor->registerReduceReset() */ void purgeCheckpointReset(uint64_t reduceTag) override { Lock lock(this->reduceMapMutex); this->reduceMapPatches.erase(reduceTag); auto& mapTag = this->reduceMap[reduceTag]; mapTag.mutex.unlock(); if (mapTag.shouldBePurged) { this->reduceMap.erase(reduceTag); } } /** Purges a dead ring from our reduceMap. */ void purgeDeadRing(uint64_t reduceTag) override { Lock lock(this->reduceMapMutex); this->reduceMap[reduceTag].shouldBePurged = true; } /** Set currentReduce to point to the right ReduceAccumulator */ void setCurrentReduce(uint64_t reduceTag) { { //Lock and release reduceMap before locking the reduction Lock lock(this->reduceMapMutex); auto iter = this->reduceMap.find(reduceTag); if (iter == this->reduceMap.end()) { std::ostringstream ss; ss << "ReduceTag " << reduceTag << " not found on " << this->processor->getRank() << "!"; throw std::runtime_error(ss.str()); } this->currentReduceTag = reduceTag; this->currentReduce = &iter->second; } this->currentReduce->mutex.lock(); this->processor->registerReduceReset(this, reduceTag); { Lock lock(this->reduceMapMutex); if (this->reduceMapPatches.count(reduceTag) != 0) { //A dispatchInit leads to either a dispatchWork or //dispatchAdd, so thany prior reset supercedes the current //one. } else { this->reduceMapPatches[reduceTag] = serialization::encode( *this->currentReduce); } } } /** Unlock working with this particular reduceTag */ void unsetCurrentReduce() { //Most cleanup actually happens in purgeCheckpointReset this->currentReduce = 0; } //I *think* partial specialization of friend class with our T_derived //isn't allowed. A pity. template<typename Td, typename T1, typename T2, typename T3> friend class Frame; friend class boost::serialization::access; /* Serialization for checkpoints; only used bottom up. You do not need to register your own derived classes! */ template<class Archive> void serialize(Archive& ar, const unsigned int version) { Lock lock(this->reduceMapMutex); ar & boost::serialization::base_object<job::ReducerBase>(*this); ar & this->reduceMap; //We don't protect user data during checkpoint operations. So, //we checkpoint it before any work occurs (see //setCurrentReduce). Save those checkpoints. ar & this->reduceMapPatches; if (Archive::is_loading::value) { for (auto& m : this->reduceMapPatches) { if (m.second.empty()) { this->reduceMap.erase(m.first); } else { serialization::decode(m.second, this->reduceMap[m.first]); } } this->reduceMapPatches.clear(); } } /* Auto class registration. */ struct _AutoRegister { //http://stackoverflow.com/questions/1819131/c-static-member-initalization-template-fun-inside _AutoRegister() { job_stream::job::addReducer(T_derived::NAME(), _AutoRegister::make); serialization::registerType<T_derived, Reducer<T_derived, T_accum, T_input>, job::ReducerBase, job::SharedBase>(); } /** Called by constructor to force static member instantiation. */ void doNothing() {} static T_derived* make() { return new T_derived(); } }; static _AutoRegister _autoRegister; }; template<typename T_derived, typename T_accum, typename T_input> thread_local uint64_t Reducer<T_derived, T_accum, T_input>::currentReduceTag = (uint64_t)-1; template<typename T_derived, typename T_accum, typename T_input> thread_local job::ReduceAccumulator<T_accum>* Reducer<T_derived, T_accum, T_input>::currentReduce = 0; template<typename T_derived, typename T_accum, typename T_input> thread_local std::unique_ptr<T_input> Reducer<T_derived, T_accum, T_input>::currentWork; template<typename T_derived, typename T_accum, typename T_input> thread_local std::unique_ptr<T_accum> Reducer<T_derived, T_accum, T_input>::currentJoin; template<typename T_derived, typename T_accum, typename T_input> thread_local bool Reducer<T_derived, T_accum, T_input>::hadRecurrence = false; template<typename T_derived, typename T_accum, typename T_input> typename Reducer<T_derived, T_accum, T_input>::_AutoRegister Reducer<T_derived, T_accum, T_input>::_autoRegister; /** A Frame is a special type of Reducer that has special logic based on the first type of data it receives. If T_first == T_recur, you probably don't need a Frame, you probably want a Reducer. But, for instance, an algorithm that runs a simulation over and over until a dynamic number of trials have been completed (based on the results of past trials) should be implemented as a Frame. */ template<typename T_derived, typename T_accum, typename T_first, typename T_work = T_accum> class Frame : public Reducer<T_derived, T_accum, AnyType> { public: /** Note - don't use a constructor. Use postSetup() instead. */ Frame() { //Template static member instantiation. Gotta reference it. _autoRegister.doNothing(); } /** Handles the first work that initiates the Reduce loop */ virtual void handleFirst(T_accum& current, std::unique_ptr<T_first> first) = 0; /** Handles any subsequent work in this Reduce loop (from recur) */ virtual void handleNext(T_accum& current, std::unique_ptr<T_work> work) = 0; /** The AnyType resolution of handleAdd */ void handleAdd(T_accum& current, std::unique_ptr<AnyType> work) { if (!this->currentReduce->gotFirstWork) { this->currentReduce->gotFirstWork = true; this->handleFirst(current, std::move(work->as<T_first>())); } else { this->handleNext(current, std::move(work->as<T_work>())); } } /** Frames don't have a handleJoin, since there is one authority, which is the original processor to get the message. */ void handleJoin(T_accum& current, std::unique_ptr<T_accum> other) { throw std::runtime_error("Unimplemented, should never be " "triggered (Frame::handleJoin)."); } private: virtual std::string getInputTypeName() { return typeid(T_first).name(); } friend class boost::serialization::access; /* Serialization for checkpoints; only used bottom up. You do not need to register your own derived classes! */ template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar & boost::serialization::base_object< Reducer<T_derived, T_accum, AnyType>>(*this); } /* Auto class registration. */ struct _AutoRegister { //http://stackoverflow.com/questions/1819131/c-static-member-initalization-template-fun-inside _AutoRegister() { //Frames inherit from Reducer, no need to addReducer. We just //need to set up the serialization inheritance chain serialization::registerType<T_derived, Frame<T_derived, T_accum, T_first, T_work>, Reducer<T_derived, T_accum, AnyType>, job::ReducerBase, job::SharedBase>(); } /** Called by constructor to force static member instantiation. */ void doNothing() {} }; static _AutoRegister _autoRegister; }; template<typename T_derived, typename T_accum, typename T_first, typename T_work> typename Frame<T_derived, T_accum, T_first, T_work>::_AutoRegister Frame<T_derived, T_accum, T_first, T_work>::_autoRegister; /** A structure used to launch the system with non-argc, argv arguments. */ struct SystemArguments { /** The YAML text that is used as the config file */ std::string config; /** The callback function called every loop. If it returns true, then processing is aborted. */ std::function<bool ()> checkExternalSignals; /** The file to use for checkpointing, if any */ std::string checkpointFile; /** The interval between the completion of one checkpoint and the beginning of another, in milliseconds. */ int checkpointIntervalMs; /** The time between all nodes being ready for a checkpoint and the checkpoint actually starting. Used to account for e.g. different times on different machines for send and receive (send finishes, so gets cleared, but then receive starts afterward). */ int checkpointSyncIntervalMs; /** Useful mostly for debugging, disables the steal ring */ bool disableSteal; /** Callback for output tuples, rather than printing them out. Note that this function becomes responsible for checkpointing the output work! */ std::function<void (std::unique_ptr<AnyType>)> handleOutputCallback; /** The initial input string, if any. Leave empty for stdin or work enqueued via queueInitialWork() */ std::string inputLine; SystemArguments() : checkpointIntervalMs(600 * 1000), checkpointSyncIntervalMs(-1), disableSteal(false) {} }; /** Returns a human-readable string denoting details about the checkpoint file specified. */ std::string checkpointInfo(const std::string& path); /** Returns the number of CPUs in this cluster; throws an error if the * steal ring hasn't gone around yet and CPU detection hasn't happened. * */ int getCpuCount(); /** Returns the number of CPUs on this host; throws an error if a * job_stream has not yet been entered. * */ int getHostCpuCount(); /** Returns this machine's MPI rank. */ int getRank(); /** Calls mpi abort() */ void mpiAbort(); /** Add work to the initialWork queue, which overrides stdin or the argc, argv combination. */ template<typename T> void queueInitialWork(T&& work) { processor::initialWork.emplace_back(serialization::encodeAsPtr(work)); } /** Run the processor, processing either the input line specified in (argc, argv) excepting flags, the job_stream::processor::initialWork queue (populated through job_stream::queueInitialWork), or stdin. */ void runProcessor(int argc, char** argv); void runProcessor(const SystemArguments& args); } #endif//JOB_STREAM_H_
wwoods/job_stream
job_stream/workerThread.h
<gh_stars>10-100 #pragma once #include <thread> namespace job_stream { namespace processor { class Processor; class WorkerThread { public: /** Starts a new WorkerThread that processes work from p. */ WorkerThread(Processor* p, int workerIndex); /** Joins the thread. */ void join(); /** The main function that this WorkerThread runs. */ void main(); private: bool shouldRun; Processor* processor; std::thread thread; int workerIndex; }; } }
wwoods/job_stream
test/common.h
#pragma once #include <string> std::tuple<std::string, std::string> run(std::string prog, std::string args, std::string input); std::tuple<int, std::string, std::string> runRetval(std::string prog, std::string args, std::string input); void runWithExpectedOut(std::string prog, std::string args, std::string input, std::string output, bool lastOnly, bool ordered, std::function<std::string(std::string)> transform); std::vector<std::string> sortedLines(std::string input); std::vector<std::string> sortedLinesLimited(std::string input, const std::vector<std::string>& onlyIncludeIfMatching); /** Exact match only (that is, no extraneous lines) */ #define REQUIRE_UNORDERED_LINES(a, b) { \ auto sorted1 = sortedLines(a); \ auto sorted2 = sortedLines(b); \ \ for (int i = 0, m = sorted1.size(); i < m; i++) { \ REQUIRE(sorted2.size() > i); \ REQUIRE(sorted1[i] == sorted2[i]); \ } \ REQUIRE(sorted1.size() == sorted2.size()); \ } /** b must contain all lines in a, but may have extras. */ #define REQUIRE_CONTAINS_LINES(a, b) { \ INFO("==== Looking for lines ====\n" << a << "\n==== Got lines ====\n" \ << b); \ auto sorted1 = sortedLines(a); \ auto sorted2 = sortedLinesLimited(b, sorted1); \ \ for (int i = 0, m = sorted1.size(); i < m; i++) { \ REQUIRE(sorted2.size() > i); \ REQUIRE(sorted1[i] == sorted2[i]); \ } \ REQUIRE(sorted1.size() == sorted2.size()); \ }
wwoods/job_stream
job_stream/types.h
#pragma once #include <mutex> #include <sstream> namespace job_stream { typedef std::recursive_mutex Mutex; typedef std::lock_guard<Mutex> Lock; namespace processor { class Processor; } /** Helper class for debug code (see JOB_STREAM_DEBUG). Outputs the message encoded to it (at destruction) to stderr with identifying information about which process this is. Recommended usage: JobLog() << "My message: " << someCounter; That way the JobLog() gets destructed after the line. If you know what you are doing and want to emit a message all at once, feel free to make a named JobLog() object. Just scope it properly. */ class JobLog { public: JobLog(); ~JobLog(); template<typename T> JobLog& operator<<(const T& obj) { this->stream << obj; return *this; } /** Test functionality only; since some internals use JobLog() when a processor is not initialized, use JobLog::FakeHeaderForTests to override. */ struct FakeHeaderForTests { FakeHeaderForTests(); ~FakeHeaderForTests(); }; private: friend class processor::Processor; /** The stream for this JobLog */ std::ostringstream stream; /** The header for this machine, initialized by Processor. */ static std::string header; }; }
wwoods/job_stream
job_stream/module.h
<reponame>wwoods/job_stream #ifndef JOB_STREAM_MODULE_H_ #define JOB_STREAM_MODULE_H_ #include "job.h" #include "message.h" #include "types.h" #include "yaml.h" #include <map> #include <memory> #include <mutex> namespace job_stream { namespace module { /** A collection of jobs with an optional reducing component. */ class Module : public job::JobBase { public: static Module* make(); Module(); /* Find the Job responsible for processing work and run it. */ virtual void dispatchWork(message::WorkRecord& work); /** Would the given work make a new reduction? */ virtual bool wouldReduce(message::WorkRecord& work); /** Get our module level */ int getLevel() const { return this->level; } /** Does this module have a reducer? */ bool hasReducer() const { return this->reducer.get() != 0; } /** Setup self, then any instantiated children. */ virtual void populateAfterRestore(YAML::GuardedNode* globalConfig, const YAML::Node& config, job::ReducerReallocMap& reducerMap); /** Ensure that our config keys are set */ virtual void postSetup(); protected: /** Return a JobBase for the given job id */ job::JobBase* getJob(const std::string& id); /** Returns the input type of the first job (or reducer input) */ virtual std::string getInputTypeName(); private: /* Map of job ids to JobBase */ std::map<std::string, std::unique_ptr<job::JobBase> > jobMap; /* This module's level (base-0; for indexing arrays). Points to the child job of this module, more specifically. */ int level; Mutex mutex; /* Our reducer, if any */ std::unique_ptr<job::ReducerBase> reducer; friend class boost::serialization::access; template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar & boost::serialization::base_object<job::JobBase>(*this); ar & this->jobMap; ar & this->reducer; } }; } } //job_stream #endif//JOB_STREAM_MODULE_H_
wwoods/job_stream
job_stream/invoke.h
#ifndef JOB_STREAM_INVOKE_H_ #define JOB_STREAM_INVOKE_H_ #include <string> #include <tuple> #include <vector> namespace job_stream { namespace invoke { /** Runs an application to completion, returning up to two strings for stdout and stderr. Retries up to 20 times for "No child processes" issue. Raises an exception on any other error. */ std::tuple<std::string, std::string> run( const std::vector<std::string>& progAndArgs); /** Runs an application to completion, returning up to two strings for stdout and stderr. transientErrors - If specified, is a list of expected substrings to look for in stderr. If any of the strings in the vector exist in stderr, the program will be re-launched, up to maxRetries times. */ std::tuple<std::string, std::string> run( const std::vector<std::string>& progAndArgs, const std::vector<std::string>& transientErrors, int maxRetries = 20); /** Primarily for testing; run a program with given stdin, also return the exit * status. * * Does not throw exception if return value not equal to zero. * */ std::tuple<int, std::string, std::string> runWithStdin( const std::vector<std::string>& progAndArgs, const std::string& stdin); /** Called by main job_stream right before processor (and thus MPI routines and job_stream threads) starts. */ void _init(); /** Test object; construct it for when you want the invoke to NOT delay before running the application again on a transient error. */ struct FakeInvokeWait { FakeInvokeWait(); ~FakeInvokeWait(); }; } //invoke } //job_stream #endif//JOB_STREAM_INVOKE_H_
wwoods/job_stream
job_stream/job.h
#ifndef JOB_STREAM_JOB_H_ #define JOB_STREAM_JOB_H_ #include "message.h" #include "types.h" #include "yaml.h" #include <memory> #include <mutex> #include <string> namespace job_stream { namespace module { class Module; } namespace job { class JobBase; class ReducerBase; typedef std::map<ReducerBase*, ReducerBase*> ReducerReallocMap; } namespace processor { class Processor; } namespace job { void addJob(const std::string& typeName, std::function<job::JobBase* ()> allocator); void addReducer(const std::string& typeName, std::function<job::ReducerBase* ()> allocator); /** Unspecialized, internal job / reducer base class. All jobs should actually derive from job_stream::Job<WorkType>, and all reducers from job_stream::Reducer<AccumulatorType[, WorkType]>. */ class SharedBase { friend class module::Module; friend class processor::Processor; public: SharedBase(); virtual ~SharedBase(); /* Can override to check config / do something at setup() time. */ virtual void postSetup() {} /** Call this at any point to force a checkpoint after the current work completes. */ void forceCheckpoint(bool forceQuit = false); /** This utility function is used to ensure that something happens outside of a checkpoint. In testing it eliminates the chances of duplicate output due to work being repeated by a checkpoint. In practice, it only reduces the chances, and often marginally. */ void lockOutCheckpointsUntilCompletion(); /** Returns a thread-safe version of our YAML::Node */ YAML::UnlockedNode config; YAML::UnlockedNode globalConfig; /** Since mechanisms embedding job_stream (such as python) may have their own allocation techniques, it is important that we allocate the object through the native allocation methods and then serialize our parts. */ std::string getAllocationName() const { return this->allocationName; } /* For debug; return double-colon delimited job id. */ std::string getFullName() const; /* To make dispatching class types easier, the constructor does nothing. This function goes ahead and sets up the job so it can receive work. */ void setup(processor::Processor* processor, module::Module* parent, const std::string& id, const YAML::Node& config, YAML::GuardedNode* globalConfig); /** Used when restoring from a checkpoint, populate our and all allocated child jobs / reducers based on config. Also calls postSetup, since that was not triggered during checkpoint restore. Default behavior is just to call setup() with our extant parameters, and then call postSetup. */ virtual void populateAfterRestore(YAML::GuardedNode* globalConfig, const YAML::Node& config, ReducerReallocMap& reducerMap); protected: /** Populated by the processor when we are allocated, the name of the function used to allocate us. Used to restore from checkpoints. */ std::string allocationName; /* The current WorkRecord being processed; NULL out of processing */ static thread_local message::WorkRecord* currentRecord; /* This job's name (local to its module) */ std::string id; /* This job / module's parent module */ module::Module* parent; /* The processor that we are running under */ processor::Processor* processor; /** Since reducers can have handleWork() vs handleDone(), one of which has ::output as the target, and the other is the target of the module itself. */ static thread_local bool targetIsModule; /** Given a target relative to our module, return the whole path to that target. */ std::vector<std::string> getTargetForJob(std::string target); /** Get a target based on our config, if we are a reducer. */ std::vector<std::string> getTargetForReducer(); /** Look at our template arguments and return typeid(T).name() so that we can cast basic input types into the system appropriately. */ virtual std::string getInputTypeName() = 0; /** Take a line of stdin or argv input and convert it to the appropriate type for this job (or module's first job). */ std::string parseAndSerialize(const std::string& line); private: /* Our job's specific config, including "to", "id", and "type". */ YAML::GuardedNode __config; /* Our module's config, from global module_config or submodule * instantiation */ YAML::GuardedNode* __globalConfig; /** For output from either a reducer or job context, we may want to traverse our parent module chain to determine the next recipient of work. This function resolves that. isReducerEmit - If true, called from getTargetForReducer(). Sends the special ::output::reduced target when appropriate. */ std::vector<std::string> _getTargetSiblingOrReducer(bool isReducerEmit); friend class boost::serialization::access; /* Serialization for checkpoints; only used bottom up. You do not need to register your own derived classes! We just need to detect if something is a Reducer, and if so, save its reduceMap. */ template<class Archive> void serialize(Archive& ar, const unsigned int version) { //NOTE - A LOT of links are NOT serialized. The reason we serialize //SharedBase (and jobs and reducers at all) is because ReduceInfo //fingerprints need to link back to the correct objects. So, we //archive the tree's shape in general, but then fill it in from the //config file. ar & this->id; ar & this->allocationName; } }; /** Base class for Jobs */ class JobBase : public SharedBase { public: /** Pass work to handleWork() function in templated override. */ virtual void dispatchWork(message::WorkRecord& work) = 0; /** Pass work to see if it would start a new reduction. */ virtual bool wouldReduce(message::WorkRecord& work) = 0; private: friend class boost::serialization::access; template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar & boost::serialization::base_object<SharedBase>(*this); } }; /** Base class for Reducers, which take multiple outputs and combine them. */ class ReducerBase : public SharedBase { friend class processor::Processor; public: /** Dispatch to templated init */ virtual bool dispatchInit(message::WorkRecord& work) = 0; /** Dispatch to templated add T_init to T_accum */ virtual void dispatchAdd(message::WorkRecord& work) = 0; /** Dispatch to templated join T_accum with T_accum */ virtual void dispatchJoin(message::WorkRecord& work) = 0; /** Dispatch to templated done. Returns true if no recurrence occurred, and the ring is fully dead. */ virtual bool dispatchDone(uint64_t reduceTag) = 0; private: /** Called by processor when it is safe to remove the checkpoint reset on a given reduceTag in this reducer. That is, all work is finished AND there are no checkpoints happening. */ virtual void purgeCheckpointReset(uint64_t reduceTag) = 0; /** Called by processor when it is safe to remove a dead ring. Specifically, no checkpoints are occurring and handleDone() did not cause any recurrence. */ virtual void purgeDeadRing(uint64_t reduceTag) = 0; friend class boost::serialization::access; template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar & boost::serialization::base_object<SharedBase>(*this); } }; template<class T_accum> struct ReduceAccumulator { /* Copy of the original WorkRecord that spawned this reduction */ std::unique_ptr<message::WorkRecord> originalWork; /* The accumulator for this record */ std::unique_ptr<T_accum> accumulator; /** To prevent client code from needing its own locks, we ensure that one Reducer's methods aren't called simulateously for the same current reduction. */ Mutex mutex; /* Used for Frames, allows first work to be distinguished.... */ bool gotFirstWork; /** If set, then when the mutex is next unlocked in purgeCheckpointReset, it will be deleted. */ bool shouldBePurged; private: friend class boost::serialization::access; template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar & this->originalWork & this->accumulator & this->gotFirstWork & this->shouldBePurged; } }; } } #endif//JOB_STREAM_JOB_H_
wwoods/job_stream
job_stream/yaml.h
#ifndef YAML_PROTO_H_ #define YAML_PROTO_H_ #include "types.h" #include <yaml-cpp/yaml.h> namespace YAML { class GuardedNode; //Allows Node.as<NodeList>(); typedef std::vector<Node> NodeList; template<> struct convert<NodeList> { static Node encode(const NodeList& rhs) { Node node; for (int i = 0, s = rhs.size(); i < s; i++) { node.push_back(rhs[i]); } return node; } static bool decode(const Node& node, NodeList& rhs) { if (node.IsSequence()) { for (int i = 0, s = node.size(); i < s; i++) { rhs.push_back(node[i]); } } else { rhs.push_back(node); } return true; } }; /** A locked YAML::Node - that is, it locks the mutex of the closest GuardedNode. Note that since YAML::Node uses plenty of mutables (hence our issue with thread-safety even though we're read-only...), we don't have a const version of most methods. */ class LockedNode { public: LockedNode(const LockedNode& other) : mutex(other.mutex), node(other.node), lock(other.mutex) {} ~LockedNode() {} template<typename T> const T as() const { return this->node.as<T>(); } template<typename T> LockedNode& operator=(const T& rhs) { this->node = rhs; return *this; } template<typename Key> LockedNode operator[](const Key& key) { return LockedNode(this->node[key], this->mutex); } template<typename Key> const LockedNode operator[](const Key& key) const { return LockedNode(this->node[key], this->mutex); } template<typename Key> bool remove(const Key& key) { return this->node.remove(key); } std::size_t size() const { return this->node.size(); } NodeType::value Type() const { return this->node.Type(); } bool IsDefined() const { return this->node.IsDefined(); } bool IsNull() const { return this->node.IsNull(); } bool IsScalar() const { return this->node.IsScalar(); } bool IsSequence() const { return this->node.IsSequence(); } bool IsMap() const { return this->node.IsMap(); } const std::string& Scalar() const { return this->node.Scalar(); } const std::string& Tag() const { return this->node.Tag(); } //Unsafe, but... Unless the iterator gets passed between functions, //the lock on this node should outlast the begin()..end() iteration. Node::const_iterator begin() const { return this->node.begin(); } Node::const_iterator end() const { return this->node.end(); } Node::iterator begin() { return this->node.begin(); } Node::iterator end() { return this->node.end(); } operator bool() const { return this->node; } bool operator!() const { return !this->node; } /** Use with extreme caution - returns the underlying node. Shouldn't be used in user code. */ Node _getNode() { return this->node; } private: friend class GuardedNode; friend Node Clone(const LockedNode& other); LockedNode(Node n, job_stream::Mutex& mutex) : mutex(mutex), node(n), lock(mutex) {} job_stream::Mutex& mutex; Node node; job_stream::Lock lock; }; /** yaml-cpp is not thread safe. An unlocked node DOES NOT HAVE THE LOCK but only exposes array access methods. When accessed, it accesses its GuardedNode and returns the aquired version. */ class UnlockedNode { public: template<typename Key> LockedNode operator[](const Key& key); inline LockedNode get(); template<typename Key> bool remove(const Key& key); /** Points this UnlockedNode at the given GuardedNode, which must be maintained elsewhere. */ void set(GuardedNode& node) { this->node = &node; } private: GuardedNode* node; }; /** yaml-cpp is not thread safe. This class is constructed based on a YAML node and conveys functionality that is compatible with yaml-cpp yet is thread safe. Essentially just puts a mutex around the given YAML::Node. */ class GuardedNode { public: /** A thread-safe proxy for a YAML::Node and its descendents. */ GuardedNode() {} /** Sets the node to be controlled. */ void set(Node n) { job_stream::Lock locker(this->mutex); this->node = n; } /** Returns a LockedNode object, which is a Node proxy with the caveat that between its constructor and destructor, it holds our mutex. */ LockedNode acquire() { return LockedNode(this->node, this->mutex); } private: Node node; static job_stream::Mutex mutex; }; /** Allows cloning of a LockedNode. Creates an unassociated instance. */ inline Node Clone(const LockedNode& other) { return YAML::Clone(other.node); } /** Now that GuardedNode is defined, implement UnlockedNode. */ template<typename Key> LockedNode UnlockedNode::operator[](const Key& key) { return this->node->acquire()[key]; } LockedNode UnlockedNode::get() { return this->node->acquire(); } template<typename Key> bool UnlockedNode::remove(const Key& key) { return this->node->acquire().remove(key); } } #endif//YAML_PROTO_H_
wwoods/job_stream
job_stream/message.h
#ifndef JOB_STREAM_MESSAGE_H_ #define JOB_STREAM_MESSAGE_H_ #include "serialization.h" #include <string> #include <vector> namespace job_stream { namespace message { /** Meta data passed with any message. */ struct Header { /** For boost */ Header() {} Header(Header&& other) : tag(other.tag), dest(other.dest) {} Header(int tag, int dest) : tag(tag), dest(dest) {} int tag; int dest; private: friend class boost::serialization::access; template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar & tag & dest; } }; /** Used as actual vessel of send / receive over the network. */ struct _Message { _Message() {} _Message(Header header, std::string payload) : header(std::move(header)), buffer(std::move(payload)) {} Header header; std::string buffer; private: friend class boost::serialization::access; template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar & header & buffer; } }; /** A group of serialized messages */ class GroupMessage { public: GroupMessage() {} void add(int tag, std::string&& message) { this->messageTags.emplace_back(tag); this->messages.emplace_back(message); } std::string serialized() { return serialization::encode(*this); } std::vector<int> messageTags; std::vector<std::string> messages; private: friend class boost::serialization::access; template<class Archive> void serialize(Archive& ar, const unsigned int version) { int m = messageTags.size(); ar & m; if (Archive::is_saving::value) { for (int i = 0; i < m; i++) { ar & this->messageTags[i]; ar & this->messages[i]; } } else { for (int i = 0; i < m; i++) { int tag; std::string msg; ar & tag; ar & msg; this->messageTags.emplace_back(tag); this->messages.emplace_back(std::move(msg)); } } } }; /** Record of location Work flow: generation -> tsSent -> tsReceived -> tsWorkStart */ class Location { public: /* Original location */ std::string hostname; /* Target job */ std::vector<std::string> target; /* Timestamp (ms since epoch) received from this location; 0 for creation location. */ uint64_t tsReceived; /* Timestamp (ms since epoch) queued up to be sent from this location */ uint64_t tsSent; /* Timestamp (ms since epoch) work started from this location (not at this location, necessarily) */ uint64_t tsWorkStart; /** Returns current time since epoch, in ms */ static uint64_t getCurrentTimeMs(); Location() : hostname("unknown host"), tsReceived(0), tsSent(0), tsWorkStart(0) {} Location(const Location& other) : hostname(other.hostname), tsReceived(other.tsReceived), tsSent(other.tsSent), tsWorkStart(other.tsWorkStart) {} private: friend class boost::serialization::access; template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar & this->hostname; ar & this->target; ar & this->tsSent; ar & this->tsReceived; ar & this->tsWorkStart; } }; /** Record of work to be done / in progress */ class WorkRecord { public: static const int TAG_ADDRESS_BITS = 16; /* Restores a WorkRecord that has been serialized(), filling in tsReceived on source */ WorkRecord(const std::string& serialized); /** Instantiates a new _WorkRecord with source of localhost. */ WorkRecord(const std::vector<std::string>& target, const std::string& work); WorkRecord(const std::vector<std::string>& target, void* work); ~WorkRecord() {} /* Fill in this WorkRecord as though it is a continuation of wr */ void chainFrom(const WorkRecord& wr); int getReduceHomeRank() const { return this->reduceHomeRank; } uint64_t getReduceTag() const { return this->reduceTag; } const std::vector<std::string>& getTarget() const { return this->source.target; } /** Get work as a printable string; used for output. */ std::string getWorkAsString() const; size_t getWorkSize() const { return this->work.size(); } void markStarted() { this->source.tsWorkStart = Location::getCurrentTimeMs(); } /* Called when our target is a module; redirects us to first job. */ void redirectTo(const std::string& id) { this->source.target.push_back(id); } std::string serialized() const { return serialization::encode(*this); } void setReduce(int rank, uint64_t tag) { this->reduceHomeRank = rank; this->reduceTag = tag; } /** Steal our work away into an appropriately typed unique_ptr. */ template<class T> void putWorkInto(std::unique_ptr<T>& dest) { serialization::decode(this->work, dest); } protected: Location source; std::vector<Location> route; /** Rank of client that will receive output from this message. That client has the original WorkRecord that started the reduction. All results need to end up there. By default, all output goes to 0. */ int reduceHomeRank; /** The tag assigned to this WorkRecord's current reduction */ uint64_t reduceTag; std::string work; private: WorkRecord() {} friend class boost::serialization::access; template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar & this->source; ar & this->reduceHomeRank; ar & this->reduceTag; ar & this->route; ar & this->work; } }; class DeadRingTestMessage { public: uint64_t reduceTag; int sentryRank; int pass; uint64_t tsTestStarted; uint64_t processed; uint64_t created; //Used to see if there is more work being generated. While there is, //we won't pronounce this ring as dead. uint64_t createdLast; DeadRingTestMessage(const std::string& serialized) { serialization::decode(serialized, *this); } DeadRingTestMessage(int rank, uint64_t reduceTag) : reduceTag(reduceTag), sentryRank(rank), pass(0), tsTestStarted(Location::getCurrentTimeMs()), processed(0), created(0), createdLast(0) { } std::string serialized() { return serialization::encode(*this); } private: friend class boost::serialization::access; template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar & reduceTag & sentryRank & pass & tsTestStarted; ar & processed & created & createdLast; } }; /** A special message that gets passed around. Each processor will update its state in the ring, and possibly send some of its work to nodes that have no work. Note that on checkpoint resume, StealRing() will be re-initialized with the new world size. Thus, none of this data should be important. Loss must be tolerated. */ class StealRing { public: /** For each rank, the max concurrency, current work quantity, and current machine load. */ std::vector<int> capacity, slots, work; std::vector<double> load; StealRing(const std::string& buffer) { serialization::decode(buffer, *this); } StealRing(int worldCount) : capacity(worldCount), slots(worldCount), work(worldCount), load(worldCount) { for (int i = 0; i < worldCount; i++) { this->capacity[i] = 0; this->slots[i] = 0; this->work[i] = 0; this->load[i] = -1; } } std::string serialized() { return serialization::encode(*this); } private: friend class boost::serialization::access; template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar & this->capacity & this->slots & this->work & this->load; } }; } } #endif//JOB_STREAM_MESSAGE_H_
wwoods/job_stream
job_stream/pythonType.h
/** Header for the SerializedPython type so that it is integrated into decoding objects. */ #pragma once #include <boost/serialization/serialization.hpp> #include <iostream> namespace job_stream { namespace python { /** Python data stored as a pickle string */ struct SerializedPython { std::string data; SerializedPython() {} explicit SerializedPython(std::string src) : data(std::move(src)) {} SerializedPython(SerializedPython&& other) : data(std::move(other.data)) {} SerializedPython& operator=(const SerializedPython& rhs) { this->data = rhs.data; return *this; } SerializedPython& operator=(SerializedPython&& rhs) { this->data = std::move(rhs.data); return *this; } /** Implemented in _job_stream.cpp. Takes a string and turns it into a python pickled string. */ friend std::istream& operator>>(std::istream& is, SerializedPython& sp); /** Print out the repr of the stored python object. */ friend std::ostream& operator<<(std::ostream& os, const SerializedPython& sp); private: friend class boost::serialization::access; template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar & this->data; } }; } //python } //job_stream
wwoods/job_stream
job_stream/serialization.h
<filename>job_stream/serialization.h #ifndef JOB_STREAM_SERIALIZATION_H_ #define JOB_STREAM_SERIALIZATION_H_ //Guard against boost default serializations, which do not support unique_ptr //correctly. #ifdef BOOST_SERIALIZATION_VECTOR_HPP #error Include job_stream serialization before boost/serialization/vector.hpp #endif #define BOOST_SERIALIZATION_VECTOR_HPP #ifdef BOOST_SERIALIZATION_LIST_HPP #error Include job_stream serialization before boost/serialization/list.hpp #endif #define BOOST_SERIALIZATION_LIST_HPP #ifdef BOOST_SERIALIZATION_MAP_HPP #error Include job_stream serialization before boost/serialization/map.hpp #endif #define BOOST_SERIALIZATION_MAP_HPP #include <boost/archive/binary_oarchive.hpp> #include <boost/archive/binary_iarchive.hpp> #include <boost/mpl/equal.hpp> #include <boost/mpl/if.hpp> #include <boost/mpl/not.hpp> #include <boost/serialization/export.hpp> #include <boost/serialization/extended_type_info_no_rtti.hpp> #include <boost/serialization/level.hpp> #include <boost/serialization/serialization.hpp> //Bad unique_ptr support: #include <boost/serialization/list.hpp> //Bad unique_ptr support: #include <boost/serialization/map.hpp> //Bad unique_ptr support: #include <boost/serialization/vector.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits/add_pointer.hpp> #include <boost/type_traits/is_polymorphic.hpp> #include <boost/type_traits/remove_const.hpp> #include <boost/type_traits/remove_pointer.hpp> #include <boost/utility/enable_if.hpp> #include <exception> #include <list> #include <map> #include <sstream> #include <string> #include <unordered_set> /** Forward declared typedefs */ namespace job_stream { namespace serialization { typedef boost::archive::binary_oarchive OArchive; typedef boost::archive::binary_iarchive IArchive; } //serialization } //job_stream namespace boost { namespace serialization { /** Since job_stream supports smarter (type checked) serialization of pointers with polymorphic classes than boost... here's to it */ template<class T> void serialize(job_stream::serialization::OArchive& a, std::unique_ptr<T>& ptr, const unsigned int version); template<class T> void serialize(job_stream::serialization::IArchive& a, std::unique_ptr<T>& ptr, const unsigned int version); template<class T> void serialize(job_stream::serialization::OArchive& a, std::shared_ptr<T>& ptr, const unsigned int version); template<class T> void serialize(job_stream::serialization::IArchive& a, std::shared_ptr<T>& ptr, const unsigned int version); /** job_stream map encoding supports maps of unique_ptr */ template<class Archive, class U, class Allocator> inline void serialize( Archive & ar, std::list<U, Allocator> & t, const unsigned int file_version ){ boost::serialization::split_free(ar, t, file_version); } /** job_stream map encoding supports maps of unique_ptr */ template<class Archive, class Type, class Key, class Compare, class Allocator > inline void serialize( Archive & ar, std::map<Key, Type, Compare, Allocator> &t, const unsigned int file_version ){ boost::serialization::split_free(ar, t, file_version); } /** job_stream map encoding supports maps of unique_ptr */ template<class Archive, class U, class Allocator> inline void serialize( Archive & ar, std::vector<U, Allocator> & t, const unsigned int file_version ){ boost::serialization::split_free(ar, t, file_version); } } //serialization } //boost /** Helper functions for job_stream serialization */ namespace job_stream { namespace serialization { /** Public encode-to-string method; dest can be non-pointer, unique_ptr, or shared_ptr. Raw pointers are not allowed to discourage memory leaks. */ template<typename T> void decode(const std::string& message, T& dest); /** Public encode-to-string method; src can be anything, but for decoding, it's best to use non-pointer, unique_ptr, or shared_ptr. Raw pointers are not allowed to discourage memory leaks. */ template<typename T> std::string encode(const T& src); /** Lets you encode a pointer directly to a string. Note that this is not recommended, as decode is asymmetric - you MUST decode into a unique_ptr or shared_ptr. However, this is needed when you have an object that will be decoded into a pointer. */ template<typename T, typename boost::enable_if<boost::mpl::not_< boost::is_pointer<T>>, int>::type = 0> std::string encodeAsPtr(const T& src); /* Encode to archive */ template<typename T, typename boost::enable_if<boost::mpl::not_< boost::is_pointer<T>>, int>::type = 0> void decode(IArchive& a, T& dest); template<typename T, int = 0> void decode(IArchive& a, std::unique_ptr<T>& dest); template<typename T, int = 0> void decode(IArchive& a, std::shared_ptr<T>& dest); template<typename T, typename boost::enable_if<boost::mpl::not_< boost::is_pointer<T>>, int>::type = 0> void encode(OArchive& a, const T& src); template<typename T, int = 0> void encode(OArchive& a, const std::unique_ptr<T>& src); template<typename T, int = 0> void encode(OArchive& a, const std::shared_ptr<T>& src); template<typename T, typename boost::enable_if<boost::mpl::not_< boost::is_pointer<T>>, int>::type = 0> void encodeAsPtr(OArchive& a, const T& src); /** Extract the typeid(T).name() field from the given encoded message. */ std::string getDecodedType(const std::string& message); /** Register a polymorphic base class or a derivative with its bases */ template<class T, class Base1 = void, class Base2 = void, class Base3 = void, class Base4 = void, class Base5 = void, class Base6 = void> void registerType(); /** Clear all registered types. Used for testing. */ void clearRegisteredTypes(); /** Helper class for debugging registerType issues (unregistered class) */ void printRegisteredTypes(); /** Fully polymorphic object copy - even if you specify the base pointer, the derived class will be copied. */ template<class T> void copy(const T& src, T& dest); /** Base class for _SharedPtrs */ struct _SharedPtrsBase { virtual void clear() = 0; }; /** Count of currently active decode() methods, so that we do not wipe the table of decoded pointers when we still have an archive open. */ extern thread_local int _activeDecodeCount; /** Currently used _SharedPtr classes that need to be cleared when we no longer have an archive open; I'm using gcc 4.8, while the fix for extern thread_local is in 4.9... */ struct _activeSharedPtrs { /** 4.8 workaround... */ static std::unordered_set<_SharedPtrsBase*>& set() { static thread_local std::unordered_set<_SharedPtrsBase*> val; return val; } }; inline void _activeDecodeIncr() { _activeDecodeCount += 1; } inline void _activeDecodeDecr() { _activeDecodeCount -= 1; if (_activeDecodeCount < 0) { throw std::runtime_error("_activeDecodeCount decr'd below 0?"); } if (_activeDecodeCount == 0) { for (auto* ptr : _activeSharedPtrs::set()) { ptr->clear(); } _activeSharedPtrs::set().clear(); } } /** shared_ptr tracking on a per-thread basis. */ template<class T> struct _SharedPtrs : _SharedPtrsBase { /** Our instance */ static _SharedPtrs<T> instance; _SharedPtrs() { this->_decoded.reset(new std::map<T*, std::shared_ptr<T>>()); } /** Given a boost-decoded pptr, put it in our map and return the corresponding shared_ptr. */ inline std::shared_ptr<T> decoded(T* pptr) { _activeSharedPtrs::set().insert(this); if (this->_decoded->count(pptr) == 0) { this->_decoded->emplace(pptr, std::shared_ptr<T>(pptr)); } return (*this->_decoded)[pptr]; } void clear() { //Free up OUR shared_ptr, leaving responsibility with application this->_decoded->clear(); } private: /** Map of pointer (boost managed) to shared_ptr (job_stream managed); due to static initialization order, this is a unique_ptr which is initialized in our constructor. */ static thread_local std::unique_ptr<std::map<T*, std::shared_ptr<T>>> _decoded; }; template<class T> _SharedPtrs<T> _SharedPtrs<T>::instance; template<class T> thread_local std::unique_ptr<std::map<T*, std::shared_ptr<T>>> _SharedPtrs<T>::_decoded; /** A special serializable type that will preserve whatever the original type was. */ class AnyType { public: AnyType(std::string message) : data(std::move(message)) {} template<typename T> std::unique_ptr<T> as() { std::unique_ptr<T> ptr; decode(this->data, ptr); return std::move(ptr); } private: std::string data; //Note - there should not need to be any serialize() on AnyType! Otherwise //it's trying to go through the normal channels, which means it is //implemented wrong. }; //Implementations class RegisteredTypeBase { public: virtual const char* typeName() = 0; virtual const char* baseName() = 0; virtual const char* typeNameRaw() = 0; virtual const char* baseNameRaw() = 0; virtual bool tryDecode(IArchive& a, const std::string& archTypeName, const char* destTypeName, void** dest) = 0; virtual bool tryDecodeRaw(IArchive& a, const std::string& archTypeName, const char* destTypeName, void* dest) = 0; virtual bool tryEncode(OArchive& a, const char* srcTypeName, void* src) = 0; virtual bool tryEncodeRaw(OArchive& a, const char* srcTypeName, void* src) = 0; template<class U> bool isBaseClass() { return strcmp(typeid(U*).name(), baseName()) == 0; } template<class U> bool isDerivedClass() { return strcmp(typeid(U*).name(), typeName()) == 0; } }; /** Returns list of registered types; put as a static in a function so that instantiation order supports self-registering jobs and reducers. */ std::list<std::unique_ptr<RegisteredTypeBase>>& registeredTypes(); /** Relates a derivative type T to its base class B */ template<class T, class B> class RegisteredType : public RegisteredTypeBase { public: const char* baseName() { return typeid(B*).name(); } const char* baseNameRaw() { return typeid(B).name(); } const char* typeName() { return typeid(T*).name(); } const char* typeNameRaw() { return typeid(T).name(); } bool tryDecode(IArchive& a, const std::string& archTypeName, const char* destTypeName, void** dest) { if ((strcmp(destTypeName, typeName()) != 0 && strcmp(destTypeName, baseName()) != 0) || archTypeName != typeName()) { return false; } a >> *(T**)dest; return true; } bool tryDecodeRaw(IArchive& a, const std::string& archTypeName, const char* destTypeName, void* dest) { if ((strcmp(destTypeName, typeNameRaw()) != 0 && strcmp(destTypeName, baseNameRaw()) != 0) || archTypeName != typeNameRaw()) { return false; } a >> *(T*)dest; return true; } bool tryEncode(OArchive& a, const char* srcTypeName, void* src) { bool isNull = (src == 0); if (strcmp(srcTypeName, typeName()) != 0 && (strcmp(srcTypeName, baseName()) != 0 || (!isNull && dynamic_cast<T*>((B*)src) == 0))) { return false; } std::string myType = typeName(); a << myType; T* srcT = (T*)src; a << srcT; return true; } bool tryEncodeRaw(OArchive& a, const char* srcTypeName, void* src) { bool isNull = (src == 0); if (strcmp(srcTypeName, typeNameRaw()) != 0 && (strcmp(srcTypeName, baseNameRaw()) != 0 || (!isNull && dynamic_cast<T*>((B*)src) == 0))) { return false; } std::string myType = typeNameRaw(); a << myType; T& srcT = *(T*)src; a << srcT; return true; } }; template<class T, class Base> class _RegisterType_impl { public: static void doRegister() { std::unique_ptr<RegisteredTypeBase> ptr(new RegisteredType<T, Base>()); auto& registered = registeredTypes(); auto it = registered.begin(); //Prevent double registration for (; it != registered.end(); it++) { if ((*it)->isDerivedClass<T>() && (*it)->isBaseClass<Base>()) { return; } } //Register with boost (this is really hard to find in the docs, btw) boost::serialization::void_cast_register<T, Base>(); //Register internally it = registered.begin(); for (; it != registered.end(); it++) { /** Since we go through these in order, it is important that the most-derived classes are encountered first. Otherwise, encode() will find a base class before a potential better match, and since dynamic_cast will return non-zero, encoding will stop. */ if ((*it)->isDerivedClass<T>()) { //put with our people registered.insert(it, std::move(ptr)); return; } else if ((*it)->isDerivedClass<Base>()) { //We derive from this class, so go above its block, and move all //of our other instances above it too registered.insert(it, std::move(ptr)); auto insertIt = it; //it now points to one before the row that triggered this if //condition, after this decr and the first incr --it; while (++it != registered.end()) { if ((*it)->isDerivedClass<T>()) { auto toRemove = it++; std::unique_ptr<RegisteredTypeBase> ptr = std::move( *toRemove); registered.erase(toRemove); registered.insert(insertIt, std::move(ptr)); --it; } } return; } } registered.insert(it, std::move(ptr)); } }; template<class T> class _RegisterType_impl<T, void> { public: static void doRegister() { //Nothing can derive from void } }; template<class T, class Base1, class Base2, class Base3, class Base4, class Base5, class Base6> void registerType() { _RegisterType_impl<T, T>::doRegister(); #define REGISTER(Base)\ boost::mpl::if_< \ std::is_same<Base, void>, \ _RegisterType_impl<void, void>, \ _RegisterType_impl<T, Base>>::type::doRegister() REGISTER(Base1); REGISTER(Base2); REGISTER(Base3); REGISTER(Base4); REGISTER(Base5); REGISTER(Base6); #undef REGISTER } struct _SerialHelperUtility { static void typeError(const std::string& expected, const std::string& actual) { std::ostringstream ss; ss << "Expected type '" << expected << "'; got '" << actual << "'"; throw std::runtime_error(ss.str()); } }; /** To support encoding / decoding derived classes (virtual inheritance), we serialize pointers. But primitive types don't support that (as a pointer). So we use this to get around it. Non-specialized is for non pointers or pointers to non-polymorphic and non-primitive types. */ template<typename T, class Enable = void> struct _SerialHelper { //T might be a pointer, though it will be a static type. So we have to //come up with a const-stripped typed, regardless of pointer or not. typedef typename boost::mpl::if_< boost::is_pointer<T>, typename boost::add_pointer<typename boost::remove_const< typename boost::remove_pointer<T>::type>::type>::type, typename boost::remove_const<T>::type >::type T_noconst; static const char* typeName() { return typeid(T_noconst).name(); } static void encodeTypeAndObject(OArchive& a, const T& obj) { std::string tn = typeName(); a << tn; a << obj; } static void decodeTypeAndObject(IArchive& a, T& obj) { std::string objTypeName; a >> objTypeName; if (objTypeName != typeName()) { _SerialHelperUtility::typeError(typeName(), objTypeName); } a >> obj; } }; /** If a serialization attempt to a non-pointer of a polymorphic type happens, we complain. Otherwise, there's a very unhelpful "Unregistered class" message at runtime, and no other help. */ template<typename T> struct _SerialHelper<T, typename boost::enable_if< boost::is_polymorphic<T>>::type> { /*static_assert(sizeof(T) == 0, "When serializing polymorphic types, " "job_stream::serialization requires you to serialize a unique_ptr " "or shared_ptr instead of the direct object, since different " "types have different memory layouts, which will not be handled " "correctly.");*/ typedef typename boost::mpl::if_< boost::is_pointer<T>, typename boost::add_pointer<typename boost::remove_const< typename boost::remove_pointer<T>::type>::type>::type, typename boost::remove_const<T>::type >::type T_noconst; static const char* typeName() { return typeid(T_noconst).name(); } static void encodeTypeAndObject(OArchive& a, T const & obj) { //Any polymorphic class MUST be registered. Otherwise, we can't guarantee //type safety, and might end up encoding a base class representation of a non //base class. for (std::unique_ptr<RegisteredTypeBase>& m : registeredTypes()) { if (m->tryEncodeRaw(a, typeName(), (void*)&obj)) { return; } } std::ostringstream ss; ss << "Failed to encode polymorphic type '" << typeName() << "'. "; ss << "Did you call job_stream::serialization::registerType<Cls, Base>()?"; throw std::runtime_error(ss.str()); } static void decodeTypeAndObject(IArchive& a, T& obj) { std::string objTypeName; a >> objTypeName; for (std::unique_ptr<RegisteredTypeBase>& m : registeredTypes()) { if (m->tryDecodeRaw(a, objTypeName, typeName(), (void*)&obj)) { return; } } std::ostringstream ss; ss << "Failed to decode type '" << objTypeName << "' into polymorphic type '"; ss << typeName() << "'. It is likely that these types are incompatible. "; ss << "Did you call job_stream::serialization::registerType<Cls, Base>()?"; throw std::runtime_error(ss.str()); } }; /** Pointers to primitive types have different handling because boost doesn't allow serializing pointers to primitives by default. */ template<typename T> struct _SerialHelper<T*, typename boost::enable_if<boost::mpl::bool_< boost::serialization::implementation_level<T>::type::value == boost::serialization::primitive_type>>::type> { typedef typename boost::remove_const<T>::type T_noconst; static const char* typeName() { return typeid(T_noconst*).name(); } static void encodeTypeAndObject(OArchive& a, T* const & obj) { std::string tn = typeName(); bool isNull = (obj == 0); a << tn; a << isNull; if (!isNull) { a << *obj; } } static void decodeTypeAndObject(IArchive& a, T*& obj) { std::string type; bool isNull; a >> type; if (type != typeName()) { _SerialHelperUtility::typeError(typeName(), type); } a >> isNull; if (isNull) { obj = 0; } else { obj = new T(); a >> *obj; } } }; /** Polymorphic type specialization. We have to look through registeredTypes on both encode and decode to ensure that we encode the most specific class, and decode the correct derived class (and a class that is a derivative at all). */ template<typename T> struct _SerialHelper<T*, typename boost::enable_if<boost::is_polymorphic<T>>::type> { typedef typename boost::remove_const<T>::type T_noconst; static const char* typeName() { return typeid(T_noconst*).name(); } static void encodeTypeAndObject(OArchive& a, T* const & obj) { //Any polymorphic class MUST be registered. Otherwise, we can't guarantee //type safety, and might end up encoding a base class representation of a non //base class. for (std::unique_ptr<RegisteredTypeBase>& m : registeredTypes()) { if (m->tryEncode(a, typeName(), (void*)obj)) { return; } } std::ostringstream ss; ss << "Failed to encode polymorphic type '" << typeName() << "'. "; ss << "Did you call job_stream::serialization::registerType<Cls, Base>()?"; throw std::runtime_error(ss.str()); } static void decodeTypeAndObject(IArchive& a, T*& obj) { std::string objTypeName; a >> objTypeName; for (std::unique_ptr<RegisteredTypeBase>& m : registeredTypes()) { if (m->tryDecode(a, objTypeName, typeName(), (void**)&obj)) { return; } } std::ostringstream ss; ss << "Failed to decode type '" << objTypeName << "' into polymorphic type '"; ss << typeName() << "'. It is likely that these types are incompatible. "; ss << "Did you call job_stream::serialization::registerType<Cls, Base>()?"; throw std::runtime_error(ss.str()); } }; /** Encode to string; note that directly encoding a pointer is invalid. You must use encodeAsPtr on a reference instead, and only if you're sure. */ template<typename T> std::string encode(const T& src) { std::ostringstream ss; OArchive oa(ss, boost::archive::no_header); encode(oa, src); return ss.str(); } /** Decode from string */ template<typename T> void decode(const std::string& message, T& dest) { _activeDecodeIncr(); std::istringstream ss(message); IArchive ia(ss, boost::archive::no_header); decode(ia, dest); _activeDecodeDecr(); } /** Encode reference to a string, but encode it as a pointer. Useful when you'll be decoding it to a unique_ptr or shared_ptr, as in a networking protocol. */ template<typename T, typename boost::enable_if<boost::mpl::not_< boost::is_pointer<T>>, int>::type> std::string encodeAsPtr(const T& src) { std::ostringstream ss; OArchive oa(ss, boost::archive::no_header); encodeAsPtr(oa, src); return ss.str(); } template<typename T, typename boost::enable_if<boost::mpl::not_< boost::is_pointer<T>>, int>::type> void encodeAsPtr(OArchive& a, const T& src) { _SerialHelper<T*>::encodeTypeAndObject(a, const_cast<T* const>(&src)); } /** Decode a previously encoded ANYTHING into AnyType. */ template<> void decode(const std::string& message, std::unique_ptr<AnyType>& dest); /** Non-pointer decode mechanism. Avoid memory leaks by explicitly disallowing decoding to a raw pointer type. */ template<typename T, typename boost::enable_if<boost::mpl::not_< boost::is_pointer<T>>, int>::type> void decode(IArchive& ia, T& dest) { _activeDecodeIncr(); _SerialHelper<T>::decodeTypeAndObject(ia, dest); _activeDecodeDecr(); } /** Decode std::unique_ptr */ template<typename T, int> void decode(IArchive& ia, std::unique_ptr<T>& dest) { _activeDecodeIncr(); T* toAllocate; _SerialHelper<T*>::decodeTypeAndObject(ia, toAllocate); dest.reset(toAllocate); _activeDecodeDecr(); } /** Decode std::shared_ptr */ template<typename T, int> void decode(IArchive& ia, std::shared_ptr<T>& dest) { _activeDecodeIncr(); //IF THIS ASSERTION FAILS - you must wrap your shared type in a struct. //Boost does not track primitives by default; we fix normal encoding and //decoding, but cannot fix it for shared_ptr. BOOST_STATIC_ASSERT(boost::serialization::tracking_level< T >::value != boost::serialization::track_never); T* pptr; _SerialHelper<T*>::decodeTypeAndObject(ia, pptr); dest = _SharedPtrs<T>::instance.decoded(pptr); _activeDecodeDecr(); } /** Encode anything that isn't a raw pointer. */ template<typename T, typename boost::enable_if<boost::mpl::not_< boost::is_pointer<T>>, int>::type> void encode(OArchive& oa, const T& src) { _SerialHelper<T>::encodeTypeAndObject(oa, src); } template<typename T, int> void encode(OArchive& oa, const std::unique_ptr<T>& src) { _SerialHelper<T*>::encodeTypeAndObject(oa, src.get()); } template<typename T, int> void encode(OArchive& oa, const std::shared_ptr<T>& src) { //Save the object as-is; multiple shared_ptrs pointing to the same object //will be archived as the same object. We'll resolve this when we load //them. //IF THIS ASSERTION FAILS - you must wrap your shared type in a struct. //Boost does not track primitives by default; we fix normal encoding and //decoding, but cannot fix it for shared_ptr. BOOST_STATIC_ASSERT(boost::serialization::tracking_level< T >::value != boost::serialization::track_never); _SerialHelper<T*>::encodeTypeAndObject(oa, src.get()); } /** Lazy person's copy functionality */ template<class T> void copy(const T& src, T& dest) { decode(encode(src), dest); } } }//job_stream namespace boost { namespace serialization { /** Boost namespace capability to encode / decode std::unique_ptr */ template<class T> void serialize(job_stream::serialization::OArchive& a, std::unique_ptr<T>& ptr, const unsigned int version) { job_stream::serialization::encode(a, ptr); } /** Boost namespace capability to encode / decode std::unique_ptr */ template<class T> void serialize(job_stream::serialization::IArchive& a, std::unique_ptr<T>& ptr, const unsigned int version) { job_stream::serialization::decode(a, ptr); } /** Boost namespace capability to encode / decode std::shared_ptr */ template<class T> void serialize(job_stream::serialization::OArchive& a, std::shared_ptr<T>& ptr, const unsigned int version) { job_stream::serialization::encode(a, ptr); } /** Boost namespace capability to encode / decode std::shared_ptr */ template<class T> void serialize(job_stream::serialization::IArchive& a, std::shared_ptr<T>& ptr, const unsigned int version) { job_stream::serialization::decode(a, ptr); } /** NOTE ABOUT WHY THIS USE job_stream::serialization::encode: bool& has no templated serialize, bool does. job_stream automatically decodes all references as value types, which is what we want for these STL containers. */ template<class Archive, class U, class Allocator> inline void save( Archive & ar, const std::list<U, Allocator> & t, const unsigned int file_version ){ size_t sz = t.size(); ar & sz; for (auto it = t.begin(); it != t.end(); it++) { job_stream::serialization::encode(ar, *it); } } template<class Archive, class U, class Allocator> inline void load( Archive & ar, std::list<U, Allocator> & t, const unsigned int file_version ){ size_t sz; ar & sz; //Ensure we're working with all default instances t.clear(); t.resize(sz); for (auto it = t.begin(); it != t.end(); it++) { job_stream::serialization::decode(ar, *it); } } template<class Archive, class Type, class Key, class Compare, class Allocator > inline void save( Archive & ar, const std::map<Key, Type, Compare, Allocator> &t, const unsigned int /* file_version */ ){ size_t sz = t.size(); ar & sz; for (auto it = t.begin(); it != t.end(); it++) { job_stream::serialization::encode(ar, it->first); job_stream::serialization::encode(ar, it->second); } } template<class Archive, class Type, class Key, class Compare, class Allocator > inline void load( Archive & ar, std::map<Key, Type, Compare, Allocator> &t, const unsigned int /* file_version */ ){ size_t sz; ar & sz; t.clear(); Key k; for (size_t i = 0; i < sz; i++) { job_stream::serialization::decode(ar, k); job_stream::serialization::decode(ar, t[k]); } } template<class Archive, class U, class Allocator> inline void save( Archive & ar, const std::vector<U, Allocator> & t, const unsigned int file_version ){ size_t sz = t.size(); ar & sz; for (size_t i = 0; i < sz; i++) { job_stream::serialization::encode(ar, t[i]); } } template<class Archive, class U, class Allocator> inline void load( Archive & ar, std::vector<U, Allocator> & t, const unsigned int file_version ){ size_t sz; ar & sz; //Ensure we get default objects t.clear(); t.resize(sz); for (size_t i = 0; i < sz; i++) { //Weird cast needed for e.g. bool, which has its own _Bit_reference //reference type by default. job_stream::serialization::decode(ar, t[i]); } } /** bool has its own special override for vector. */ template<class Archive, class Allocator> inline void save(Archive& ar, const std::vector<bool, Allocator>& t, const unsigned int version) { size_t sz = t.size(); ar & sz; bool v; for (size_t i = 0; i < sz; i++) { //Weird cast needed for e.g. bool, which has its own _Bit_reference //reference type by default. v = t[i]; job_stream::serialization::encode(ar, v); } } /** bool has its own special override for vector. */ template<class Archive, class Allocator> inline void load(Archive& ar, std::vector<bool, Allocator>& t, const unsigned int version) { size_t sz; ar & sz; //Ensure we get default objects t.clear(); t.resize(sz); bool v; for (size_t i = 0; i < sz; i++) { //Weird cast needed for e.g. bool, which has its own _Bit_reference //reference type by default. job_stream::serialization::decode(ar, v); t[i] = v; } } } //serialization } //boost #endif//JOB_STREAM_SERIALIZATION_H_
wwoods/job_stream
job_stream/processor.h
<reponame>wwoods/job_stream<gh_stars>10-100 #ifndef JOB_STREAM_PROCESSOR_H_ #define JOB_STREAM_PROCESSOR_H_ #include "job.h" #include "message.h" #include "module.h" #include "types.h" #include "workerThread.h" #include "yaml.h" #include <boost/mpi.hpp> #include <deque> #include <fstream> #include <functional> #include <memory> #include <list> #include <thread> namespace job_stream { namespace processor { class AnyUniquePtr; } } namespace std { void swap(job_stream::processor::AnyUniquePtr& p1, job_stream::processor::AnyUniquePtr& p2); } namespace job_stream { namespace processor { /* Debug flag when testing library; 1 = basic messages (min output), 2 = very, very verbose 3 = overly verbose */ extern const int JOB_STREAM_DEBUG; /** The number of CPUs in the cluster, or -1 if uninitialized. * */ extern int cpuCount; /** The number of CPUs on this host, or -1 if uninitialized. * */ extern int hostCpuCount; /** A queue of serialized initial work. If populated (non-zero size), then this is used in lieu of either an initial input line or stdin. */ extern std::vector<std::string> initialWork; /** Generic thread-safe queue class with unique_ptrs. */ template<typename T> class ThreadSafeQueue { public: void push(std::unique_ptr<T> value) { Lock lock(this->mutex); this->queue.push_back(std::move(value)); } bool pop(std::unique_ptr<T>& value) { Lock lock(this->mutex); if (this->queue.empty()) { return false; } value = std::move(this->queue.front()); this->queue.pop_front(); return true; } size_t size() { Lock lock(this->mutex); return this->queue.size(); } private: std::deque<std::unique_ptr<T>> queue; Mutex mutex; }; /** A cheat for a unique_ptr to any class which can be retrieved later and is properly deleted. Application is responsible for keeping track of the type though. This just prevents you from needing to write a tricky destructor, so you can focus on logic. */ class AnyUniquePtr { public: AnyUniquePtr() {} template<class T> AnyUniquePtr(std::unique_ptr<T> ptr) : _impl(new AnyPtrImpl<T>(std::move(ptr))) {} AnyUniquePtr(AnyUniquePtr&& other) : _impl(std::move(other._impl)) {} virtual ~AnyUniquePtr() {} operator bool() const { return (bool)this->_impl; } template<class T> AnyUniquePtr& operator=(std::unique_ptr<T> ptr) { this->_impl.reset(new AnyPtrImpl<T>(std::move(ptr))); return *this; } template<class T> T* get() { if (!this->_impl) { return 0; } return (T*)this->_impl->get(); } void reset() { this->_impl.reset(); } template<class T> void reset(T* ptr) { this->_impl.reset(new AnyPtrImpl<T>(std::unique_ptr<T>(ptr))); } void swapWith(AnyUniquePtr& other) { std::swap(this->_impl, other._impl); } private: struct AnyPtrImplBase { AnyPtrImplBase(void* ptr) : void_ptr(ptr) {} virtual ~AnyPtrImplBase() {} void* get() { return void_ptr; } protected: void* void_ptr; }; template<class T> struct AnyPtrImpl : public AnyPtrImplBase { AnyPtrImpl(std::unique_ptr<T> ptr) : AnyPtrImplBase((void*)ptr.get()), t_ptr(std::move(ptr)) {} virtual ~AnyPtrImpl() {} private: std::unique_ptr<T> t_ptr; }; std::unique_ptr<AnyPtrImplBase> _impl; }; /** Holds information about a received MPI message, so that we process them in order. */ struct MpiMessage { /** The MPI message tag that this message belongs to */ int tag; MpiMessage(int tag, AnyUniquePtr data); /** Kind of a factory method - depending on tag, deserialize message into the desired message class, and put it in data. */ MpiMessage(int tag, std::string&& message); MpiMessage(MpiMessage&& other) : tag(other.tag) { std::swap(this->data, other.data); std::swap(this->encodedMessage, other.encodedMessage); } ~MpiMessage() {} /** Returns the serialized version of the data, NOT the whole message! */ std::string getSerializedData() const; template<typename T> T* getTypedData() const { this->_ensureDecoded(); return this->data.get<T>(); } private: /** An owned version of the data in this message - deleted manually in destructor. We would use unique_ptr, but we don't know the type of our data! */ mutable AnyUniquePtr data; /** The string representing this message, serialized. */ mutable std::string encodedMessage; /** If data == 0, populate it by deserializing encodedMessage. */ void _ensureDecoded() const; /** For serialization only */ MpiMessage() {} friend class boost::serialization::access; template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar & this->tag; if (Archive::is_saving::value) { //Ensure we're serialized std::string msg = this->getSerializedData(); ar & msg; } else { ar & this->encodedMessage; this->data.reset(); } } }; typedef std::unique_ptr<MpiMessage> MpiMessagePtr; typedef std::list<MpiMessagePtr> MpiMessageList; struct ProcessorReduceInfo { /** The number of child reduceTags this one is waiting for */ int childTagCount; /** Any messages waiting on this tag to resume (childTagCount != 0, waiting for 0). */ std::vector<MpiMessagePtr> messagesWaiting; /** The count of messages generated within this reduction. */ uint64_t countCreated; /** The count of messages processed within this reduction. */ uint64_t countProcessed; /** The parent's reduceTag */ uint64_t parentTag; /* The ReduceBase that contains our tag. We track this so we can call done on it. NULL for global ring, of course.*/ job::ReducerBase* reducer; ProcessorReduceInfo() : childTagCount(0), countCreated(0), countProcessed(0), parentTag(0), reducer(0) {} private: friend class boost::serialization::access; template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar & this->childTagCount & this->messagesWaiting; ar & this->countCreated & this->countProcessed; ar & this->parentTag; //Note - boost pointer serialization takes care of matching up our //reducer in this run with our reducer in a continuation. ar & this->reducer; } }; /** Information tied to an in-progress send */ struct ProcessorSendInfo { boost::mpi::request request; ProcessorSendInfo(boost::mpi::request request) : request(request) {} }; /** Size and other information about a processor from a checkpoint file. */ struct CheckpointInfo { uint64_t jobTreeSize; uint64_t messagesWaiting; uint64_t reduceMapSize; uint64_t totalBytes; uint64_t totalUserBytes; std::map<int, uint64_t> countByTag; std::map<int, uint64_t> bytesByTag; std::unique_ptr<message::StealRing> stealRing; /** Initialize with all zeroes */ CheckpointInfo() : jobTreeSize(0), messagesWaiting(0), reduceMapSize(0), totalBytes(0), totalUserBytes(0) {} }; /** Handles communication and job dispatch, as well as input streaming */ class Processor { friend class job::ReducerBase; friend class job::SharedBase; friend class module::Module; friend class WorkerThread; public: /* MPI message tags */ enum ProcessorSendTag { TAG_WORK, /** Work that is en-route to the only host capable of handling it. */ TAG_REDUCE_WORK, TAG_DEAD_RING_TEST, TAG_DEAD_RING_IS_DEAD, TAG_STEAL, /** A group of messages - tag, body, tag, body, etc. */ TAG_GROUP, /** Advance checkpoint to next state (either start or send) */ TAG_CHECKPOINT_NEXT, /** Processor ready to submit checkpoint data */ TAG_CHECKPOINT_READY, /** Processor's data required to resume operations. */ TAG_CHECKPOINT_DATA, /** Force a checkpoint */ TAG_CHECKPOINT_FORCE, /** Placeholder for number of tags */ TAG_COUNT, }; /* Profiler categories. User time is the most important distinction; others are internal. */ enum ProcessorTimeType { TIME_IDLE, TIME_USER, TIME_SYSTEM, TIME_COMM, //Placeholder for number of types TIME_COUNT, }; /** Checkpoint states. Checkpoints go something like this: CHECKPOINT_NONE: No checkpoint operations in progress CHECKPOINT_SYNC: A checkpoint has started, waiting for all processors to wait CHECKPOINT_SYNC_WAIT_MS after having zero-sized messageQueue and sendRequests lists. CHECKPOINT_GATHER: For rank 0 only, wait for everyone else to send their data and then package it up into the checkpoint file. For rank 1, send our state once, and then wait for TAG_CHECKPOINT_NEXT, at which point we're done. */ enum CheckpointState { CHECKPOINT_NONE, CHECKPOINT_SYNC, /** Rank 0 only; waiting for everyone else to send */ CHECKPOINT_GATHER }; /** Used to keep track of time spent not working (vs working). */ class WorkTimer { public: WorkTimer(Processor* p, ProcessorTimeType timeType) : processor(p) { this->processor->_pushWorkTimer(timeType); } ~WorkTimer() { this->processor->_popWorkTimer(); } private: Processor* processor; }; static int CHECKPOINT_SYNC_WAIT_MS; static void addJob(const std::string& typeName, std::function<job::JobBase* ()> allocator); static void addReducer(const std::string& typeName, std::function<job::ReducerBase* ()> allocator); Processor(std::shared_ptr<boost::mpi::environment> env, boost::mpi::communicator world, const std::string& config, const std::string& checkpointName); ~Processor(); /** Add work to our workInQueue when the current job finishes. We now own wr. */ void addWork(std::unique_ptr<message::WorkRecord> wr); /** Ability to use registered method to allocate a JobBase derivative. */ static job::JobBase* allocateJobForDeserialize(const std::string& typeId); /** Ability to use registered method to allocate a ReducerBase derivative. */ static job::ReducerBase* allocateReducerForDeserialize(const std::string& typeId); /** Useful for systems such as python; this function is called once per loop in the main thread. If it returns true, operation stops (shouldRun is set to false). */ std::function<bool ()> checkExternalSignals; /** Allocate and return a new tag for reduction operations. */ uint64_t getNextReduceTag(); /** Return this Processor's rank */ int getRank() const { return this->world.rank(); } /** If set, called instead of printing any output work. Note that when this is called, the work is NO LONGER UNDER CHECKPOINT! That is, if the work needs to be checkpoint-safe, then the application defining this callback must write it to disk or make it safe in its own way. */ std::function<void (std::unique_ptr<serialization::AnyType> output)> handleOutputCallback; /** Returns statistics about some processor from a serialized checkpoint buffer. */ void populateCheckpointInfo(CheckpointInfo& info, const std::string& buffer); /** Registers the given ReducerBase and reduce tag as having a reduceMapPatch that needs to be cleared on successful completion of the current work. */ void registerReduceReset(job::ReducerBase* rb, uint64_t reduceTag); /** Run all modules defined in config; inputLine (already trimmed) determines whether we are using one row of input (the inputLine) or stdin (if empty) */ void run(const std::string& inputLine); /** Sets the checkpointInterval on this processor; if called after instantiation and before run(), affects the first checkpoint as well. Otherwise, only takes effect after the next checkpoint. */ void setCheckpointInterval(int intervalMs) { this->checkpointInterval = intervalMs; } /** Can be used to turn stealing off; not recommended. */ void setStealEnabled(bool enable) { this->_stealEnabled = enable; } /** Start a dead ring test for the given reduceTag. The ring won't actually be started until the work that started it completes. Otherwise checkpoints would be broken. See _startRingTest() for implementation. */ void startRingTest(uint64_t reduceTag, uint64_t parentTag, job::ReducerBase* reducer); protected: job::JobBase* allocateJob(module::Module* parent, const std::string& id, const YAML::Node& config); job::ReducerBase* allocateReducer(module::Module* parent, const YAML::Node& config); /** Force a checkpoint after current work completes. Optionally, force a quit (exit non-zero) after the checkpoint completes. */ void forceCheckpoint(bool forceQuit = false); /** Called to handle a ring test is dead message, within either tryReceive or a work thread. */ void handleDeadRing(MpiMessagePtr message); /** Called to handle a ring test message, possibly within tryReceive, or possibly a work thread. If we are the sentry for the message's ring, we are called in work loop. Otherwise in tryReceive. Unless checkpointing interfered. */ void handleRingTest(MpiMessagePtr message); /** If we have an input thread, join it */ void joinThreads(); /** Initialize local timing info */ void localTimersInit(); /** Merge local timing info into globals */ void localTimersMerge(); /** We got a steal message; decode it and maybe give someone work. */ void maybeAllowSteal(const std::string& messageBuffer); /** Called in a worker thread; using the current thread, pull down some work and process it, while respecting checkpoint criteria. workerId - ID of worker thread; used to limit number of active workers according to capacity. Returns true if work happened, or false if there was nothing to do (which inspires the thread to sleep) */ bool processInThread(int workerId); /** Listen for input events and put them on workOutQueue. When this thread is finished, it emits a TAG_DEAD_RING_TEST message for 0. */ void processInputThread_main(const std::string& inputLine); /** Try to receive the current request, or make a new one */ bool tryReceive(); private: struct _WorkTimerRecord { uint64_t tsStart; uint64_t timeChild; uint64_t clkStart; uint64_t clksChild; int timeType; _WorkTimerRecord(uint64_t start, uint64_t clock, int type) : tsStart(start), timeChild(0), clkStart(clock), clksChild(0), timeType(type) {} }; /** Information about a WorkerThread - specifically, outbound messages waiting on the current work's completion (and the completion of checkpoint operations) before being sent. */ struct _WorkerInfo { _WorkerInfo() : p(0), isLocked(false), hasReduceTag(false), reduceTag(0) {} struct RingTestInfo { uint64_t reduceTag, parentTag; job::ReducerBase* reducer; RingTestInfo(uint64_t reduceTag, uint64_t parentTag, job::ReducerBase* reducer) : reduceTag(reduceTag), parentTag(parentTag), reducer(reducer) {} }; struct ReduceMapResetInfo { job::ReducerBase* reducer; uint64_t reduceTag; ReduceMapResetInfo(job::ReducerBase* reducer, uint64_t reduceTag) : reducer(reducer), reduceTag(reduceTag) {} }; processor::Processor* p; /** This is the only part that is serialized; the MpiMessagePtr that we started with, before any reduction ring modifications. Note that it is VITAL no state changes happen outside of the control of this struct, including network communication queuing. Otherwise, a checkpoint will re-enqueue the work, when it is partially complete, and work will be duplicated. */ std::string work; std::list<ReduceMapResetInfo> reduceMapResets; std::list<RingTestInfo> outboundRings; std::list<std::unique_ptr<message::WorkRecord>> outboundWork; std::list<std::unique_ptr<message::_Message>> outboundMessages; bool isLocked; bool hasReduceTag; /** If hasReduceTag is set, then this is the reduceTag of the work occurring in this thread. Ergo, it needs to be decremented on checkpoint load, since its childTagCount gets incremented when work begins. */ uint64_t reduceTag; void lockForWork(); friend class boost::serialization::access; template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar & this->work; ar & this->hasReduceTag; ar & this->reduceTag; } }; typedef std::list<_WorkerInfo> _WorkerInfoList; /** The file being used to write the current checkpoint. */ std::unique_ptr<std::ofstream> checkpointFile; /** The archive writing to checkpointFile */ std::unique_ptr<serialization::OArchive> checkpointAr; /** The name of the checkpoint file */ std::string checkpointFileName; /** Time between checkpoints (ms). Time from completion to start. */ int checkpointInterval; /** Time to next checkpoint (ms). Negative means disabled. */ int checkpointNext; /** Quit on a successful checkpoint? Used for debugging */ bool checkpointQuit; /** Start time for checkpoint, just for stats tracking */ uint64_t tsCheckpointStart; CheckpointState checkpointState; /** Count of processors that we're waiting on information from. Only used on rank 0. */ int checkpointWaiting; /** Our config as a string. Used for checkpointing to ensure that an existing checkpoint file matches what the user wanted. */ std::string _configStr; /** If true (default), then work is processed depth-first rather than breadth-first. This has the benefit of e.g. allowing progress meters on frame close to be more accurate. Additionally, if a bug occurs later in the pipeline, it will be discovered sooner with a depth-first approach. Note that if one stage of the pipeline depends on a prior stage (conversed over database records, for instance), the different stages may still be separated by using Frames (one Frame for stage 1, and a second Frame for stage 2). The input to this system would then be garbage, and the first Frame would need to initialize the input. */ bool depthFirst; /** Our environment */ std::shared_ptr<boost::mpi::environment> env; /** Global array; see localClksByType */ std::unique_ptr<uint64_t[]> globalClksByType; /** The root global config node, which is globally guarded. */ YAML::GuardedNode globalConfig; std::unique_ptr<uint64_t[]> globalTimesByType; /** The queue of serialized, initial work. Stolen into our possession on construction. */ std::vector<std::string> initialWork; /** Array containing how many cpu clocks were spent in each type of operation. Indexed by ProcessorTimeType */ static thread_local std::unique_ptr<uint64_t[]> localClksByType; /** Array containing how much time was spent in each type of operation. Indexed by ProcessorTimeType */ static thread_local std::unique_ptr<uint64_t[]> localTimesByType; /** The main thread id - useful for verifying there aren't errors in where certain functions are called (must be main) */ std::thread::id mainThreadId; /** Running count of messages by tag */ std::unique_ptr<uint64_t[]> msgsByTag; /* The stdin management thread; only runs on node 0 */ std::unique_ptr<std::thread> processInputThread; /* Buffers corresponding to requests */ message::_Message recvBuffer; /* The current message receiving requests (null when dead) */ boost::optional<boost::mpi::request> recvRequest; /* The current number of assigned tags for reductions */ uint64_t reduceTagCount; std::map<uint64_t, ProcessorReduceInfo> reduceInfoMap; /* The root module defined by the main config file */ std::unique_ptr<job::JobBase> root; /* Set when eof is reached on stdin (or input line), or if our index is not zero. */ bool sawEof; /** Currently pending outbound nonBlocking requests */ std::list<ProcessorSendInfo> sendRequests; /* Set when we send ring test for 0 */ bool sentEndRing0; /* True until quit message is received (ring 0 is completely closed). */ bool shouldRun; /* True if and only if this processor was restored from a checkpoint. */ bool wasRestored; /** Exceptions from worker threads. */ std::vector<std::exception_ptr> workerErrors; /** Allocated threads doing work. */ std::vector<std::unique_ptr<WorkerThread>> workers; //Any work waiting to be done on this Processor. MpiMessageList workInQueue; /** workOutQueue gets redistributed to all workers; MPI is not implicitly thread-safe, that is why this queue exists. Used for input only at the moment. */ ThreadSafeQueue<message::WorkRecord> workOutQueue; /** Outbound messages, which are sent from the main thread each loop. */ ThreadSafeQueue<message::_Message> messageQueue; /** Number of worker threads that are allowed to work. Adjusted by steal ring. */ int workersActive; /** Work happening right now, including enough static information to resume after a checkpoint. */ _WorkerInfoList workerWork; static thread_local _WorkerInfoList::iterator workerWorkThisThread; int workTarget; static thread_local std::vector<_WorkTimerRecord> workTimers; boost::mpi::communicator world; bool _stealEnabled; //Pending steal messages get stored specially for checkpoints, so that they //always get processed first. MpiMessagePtr _stealMessage; /** Locks shared resources - workInQueue, reduceInfoMap. ANY WORK requiring a mutex lock should go through workerWorkThisThread->lockForWork(). That way, the work is locked in until it finishes and all transient activity that would interfere with checkpoints completes. */ Mutex _mutex; /** Locks reduceTagCount. See getNextReduceTag() for why this is separate. */ Mutex _mutexForReduceTags; /** Adds work to our outbound work queue immediately. */ void _addWork(std::unique_ptr<message::WorkRecord> wr); /** Raises a runtime_error if this is not the main thread */ void _assertMain(); /** Update all asynchronous MPI operations to ensure our buffers are full */ void _checkMpi(); /** Called to reduce a childTagCount on a ProcessorReduceInfo for a given reduceTag. Optionally dispatch messages pending. */ void _decrReduceChildTag(uint64_t reduceTag, bool wasProcessed = false); /** Send work from workOutQueue to either our local workInQueue or send to a remote source. */ void _distributeWork(std::unique_ptr<message::WorkRecord> wr); /** Enqueue a line of input (stdin or argv) to system */ void _enqueueInputWork(const std::string& line); public: /** Return cpu time for this thread in ms */ static uint64_t _getThreadCpuTimeMs(); private: /** Return rank + 1, modulo world size */ int _getNextRank(); /** Increment and wrap workTarget, return new value */ int _getNextWorker(); /** Get work for a Worker, or return a null unique_ptr if there is no work (or we're waiting on a checkpoint). workerId - the ID of the worker thread asking for work. Used to constrain standard work based on workersActive. */ MpiMessagePtr _getWork(int workerId); /** Locks this Processor's mutex and adds work to workInQueue. */ void _lockAndAddWork(MpiMessagePtr msg); /** Send in a non-blocking manner (asynchronously, receiving all the while). reduceTags are any tags that should be kept alive by the fact that this is in the process of being sent. */ void _nonBlockingSend(message::Header header, std::string payload); void _nonBlockingSend(message::_Message&& msg); /** Push down a new timer section */ void _pushWorkTimer(ProcessorTimeType userWork); /** Pop the last timer section */ void _popWorkTimer(); public: /** Modify the current work timer, allotting the given measurements to the * given category rather than the current timer. * */ void _modifyWorkTimer(ProcessorTimeType timeType, uint64_t wallTimeMs, uint64_t cpuTimeMs); private: /** Start a dead ring test for the given reduceTag IMMEDIATELY. Shouldn't be used during work, or it would break checkpoints. */ void _startRingTest(uint64_t reduceTag, uint64_t parentTag, job::ReducerBase* reducer); /** Update current checkpoint state, given # of ms difference from last loop. Essentially, CHECKPOINT_NONE -> CHECKPOINT_START -> worker stopped and nothing left to send -> CHECKPOINT_SYNC -> all sync'd, plus a delay -> CHECKPOINT_SEND -> send data to 0, resume operations. */ void _updateCheckpoints(int msDiff); friend class boost::serialization::access; /** Either write a checkpoint or restore our state from one. */ template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar & this->_configStr; ar & this->root; ar & this->reduceTagCount & this->reduceInfoMap; ar & this->workInQueue; ar & this->sentEndRing0; ar & this->workerWork; ar & this->_stealMessage; if (Archive::is_saving::value && JOB_STREAM_DEBUG) { for (auto& m : this->workerWork) { if (!m.hasReduceTag) { continue; } fprintf(stderr, "Known checkpoint work: %lu\n", m.reduceTag); } } } }; }//processor }//job_stream #endif//JOB_STREAM_PROCESSOR_H_
ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Ivan-Garcia02
Racionales/src/racional.h
<reponame>ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Ivan-Garcia02 /** * Universidad de La Laguna * Escuela Superior de Ingeniería y Tecnología * Grado en Ingeniería Informática * Informática Básica * * @file racional.h (declaraciones) * @author <NAME> <EMAIL> * @date 7 Enero 2021 * @brief Desarrolle un programa cliente racionales.cc que permita operar con números racionales y haga uso de la clase Racional que ha de diseñarse. * La clase Racional incluirá al menos métodos para: * Crear objetos de tipo Racional. Se debe implementar un constructor por defecto y uno parametrizado. * Escribir (a fichero o a pantalla) un objeto de tipo Racional. * Leer (por teclado o desde fichero) un objeto de tipo Racional. * Sumar dos objetos de tipo Racional. * Restar dos objetos de tipo Racional. * Multiplicar dos objetos de tipo Racional. * Dividir dos objetos de tipo Racional. * Comparar objetos de tipo Racional. * El programa ha de permitir leer un fichero de texto en el que figuran pares de números racionales separados por espacios. * y para cada par de números racionales, el programa ha de imprimir en otro fichero de salida todas las operaciones posibles * @bug No hay bugs conocidos * @see https://github.com/ULL-ESIT-IB-2020-2021/IB-P11-Classes-CMake/blob/master/Classes-CMake.md */ #ifndef RACIONAL_H #define RACIONAL_H #include <iostream> #include <string> #include <fstream> #include <cmath> class Racional { private: int numerador_{0}; int denominador_{0}; std::string ficheroSalida_{"Sample.txt"}; public: Racional(); //constructor por defecto Racional(int numerador, int denominador, std::string ficheroSalida){ //Constructor especifico numerador_ = numerador; denominador_ = denominador; ficheroSalida_ = ficheroSalida; } int GetDenominador(){ return denominador_; } void simplificar(); void suma(Racional racional1, Racional racional2, int minimo_comun); void resta(Racional racional1, Racional racional2, int minimo_comun); void multiplicar(Racional racional1, Racional racional2); void dividir(Racional racional1, Racional racional2); void comparar(Racional racional1, Racional racional2); void print(); }; #endif
ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Ivan-Garcia02
Complejos/src/complejo.h
<filename>Complejos/src/complejo.h /** * Universidad de La Laguna * Escuela Superior de Ingeniería y Tecnología * Grado en Ingeniería Informática * Informática Básica * * @file complejo.h (declaraciones) * @author <NAME> <EMAIL> * @date 7 Enero 2021 * @brief Desarrolle un programa cliente complejos.cc que permita operar con números complejos y haga uso de la clase Complejo que diseñe. * La clase Complejo ha de contener al menos métodos que permitan (print()) imprimir un número complejo así como sumar (Add()) * y restar (Sub()) números complejos. * @bug No hay bugs conocidos * @see https://github.com/ULL-ESIT-IB-2020-2021/IB-P11-Classes-CMake/blob/master/Classes-CMake.md */ #ifndef COMPLEJO_H #define COMPLEJO_H #include <iostream> #include <cmath> class Complejo { private: int parteReal_{0}; int parteImaginaria_{0}; public: Complejo(int real, int imaginario){ //Constructor especifico parteReal_ = real; parteImaginaria_ = imaginario; } void suma(Complejo complejo1, Complejo complejo2); void resta(Complejo complejo1, Complejo complejo2); void multiplicacion(Complejo complejo1, Complejo complejo2); void division(Complejo complejo1, Complejo complejo2); void conjugado(); void print(); }; #endif
ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Ivan-Garcia02
Racionales/src/tools.h
/** * Universidad de La Laguna * Escuela Superior de Ingeniería y Tecnología * Grado en Ingeniería Informática * Informática Básica * * @file tools.h (declaraciones funciones) * @author <NAME> <EMAIL> * @date 7 Enero 2021 * @brief Desarrolle un programa cliente racionales.cc que permita operar con números racionales y haga uso de la clase Racional que ha de diseñarse. * La clase Racional incluirá al menos métodos para: * Crear objetos de tipo Racional. Se debe implementar un constructor por defecto y uno parametrizado. * Escribir (a fichero o a pantalla) un objeto de tipo Racional. * Leer (por teclado o desde fichero) un objeto de tipo Racional. * Sumar dos objetos de tipo Racional. * Restar dos objetos de tipo Racional. * Multiplicar dos objetos de tipo Racional. * Dividir dos objetos de tipo Racional. * Comparar objetos de tipo Racional. * El programa ha de permitir leer un fichero de texto en el que figuran pares de números racionales separados por espacios. * y para cada par de números racionales, el programa ha de imprimir en otro fichero de salida todas las operaciones posibles * @bug No hay bugs conocidos * @see https://github.com/ULL-ESIT-IB-2020-2021/IB-P11-Classes-CMake/blob/master/Classes-CMake.md */ #include <iostream> #include <string> //std::string #include <fstream> //std::ofstream #include <vector> //std::vector #include <cstdlib> //exit void usage(int& argc, char* argv[]); //Uso del programa std::vector<int> fraciones_separadas(std::string fichero); std::vector<int> fraciones_String_int(std::vector<std::string> fraciones_strings); int minimo_comun_multiplo(int denominador1, int denominador2); const std::string khelptext {"fichero_entrada: Fichero de texto conteniendo líneas con un par de números racionales: `a/b c/d` separados por un espacio fichero_salida: Fichero de texto que contendrá líneas con las operaciones realizadas: `a/b + c/d = n/m`"};
ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Ivan-Garcia02
Modificacion/src/fecha2.h
<filename>Modificacion/src/fecha2.h /** * Universidad de La Laguna * Escuela Superior de Ingeniería y Tecnología * Grado en Ingeniería Informática * Informática Básica * * @file fecha.h (declaraciones) * @author <NAME> <EMAIL> * @date 7 Enero 2021 * @brief Desarrolle una clase Fecha que permita representar y gestionar fechas. Incorpore en la clase los miembros de datos * y métodos que considere adecuados para la finalidad que se persigue en este ejercicio. * Incluya un método que permita determinar si el año correspondiente a una fecha es un año bisiesto o no. * Realice un programa cliente fechas.cc que tome como parámetro una fecha, un número y un nombre de fichero. * El programa deberá imprimir en el fichero de salida (tercer parámetro) las N (segundo parámetro) fechas cronológicamente * posteriores a la introducida (primer parámetro) con una separación de un día entre fechas sucesivas. * @bug No hay bugs conocidos * @see https://github.com/ULL-ESIT-IB-2020-2021/IB-P11-Classes-CMake/blob/master/Classes-CMake.md */ #include <string> #include <iostream> #include <fstream> class Fechas { private: int dia_{0}; int mes_{0}; int allo_{0}; std::string fichero_ {"sample.txt"}; public: void SetDia(int valor) { dia_ = valor; } void SetMes(int valor) { mes_ = valor; } void SetAllo(int valor) { allo_ = valor; } void SetFichero(std::string ficheroSalida){ fichero_ = ficheroSalida; } void printFecha(); void esBisiesto(); void siguienteFecha(); };
ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Ivan-Garcia02
Modificacion/src/tools2.h
<gh_stars>0 /** * Universidad de La Laguna * Escuela Superior de Ingeniería y Tecnología * Grado en Ingeniería Informática * Informática Básica * * @file tools.h (declaraciones funciones) * @author <NAME> <EMAIL> * @date 7 Enero 2021 * @brief Desarrolle una clase Fecha que permita representar y gestionar fechas. Incorpore en la clase los miembros de datos * y métodos que considere adecuados para la finalidad que se persigue en este ejercicio. * Incluya un método que permita determinar si el año correspondiente a una fecha es un año bisiesto o no. * Realice un programa cliente fechas.cc que tome como parámetro una fecha, un número y un nombre de fichero. * El programa deberá imprimir en el fichero de salida (tercer parámetro) las N (segundo parámetro) fechas cronológicamente * posteriores a la introducida (primer parámetro) con una separación de un día entre fechas sucesivas. * @bug No hay bugs conocidos * @see https://github.com/ULL-ESIT-IB-2020-2021/IB-P11-Classes-CMake/blob/master/Classes-CMake.md */ #include <iostream> #include <string> //std::string #include <fstream> //std::ofstream #include <cstdlib> //exit void usage(int& argc, char* argv[]); //Uso del programa void comprobarFecha(int& dia, int& mes, int& anllo); bool esBisiesto(int& allo); const std::string khelptext {"Desarrolle una clase Fecha que permita representar y gestionar fechas. Incorpore en la clase los miembros de datos y métodos que considere adecuados para la finalidad que se persigue en este ejercicio. Incluya un método que permita determinar si el año correspondiente a una fecha es un año bisiesto o no. Realice un programa cliente fechas.cc que tome como parámetro una fecha, un número y un nombre de fichero. El programa deberá imprimir en el fichero de salida (tercer parámetro) las N (segundo parámetro) fechas cronológicamente posteriores a la introducida (primer parámetro) con una separación de un día entre fechas sucesivas."};
onlyless/Vocabulary-Statistics
cpp/RBTree.h
#pragma once #include<string> #include<iostream> #include<fstream> #include<cstdio> #define RED true; #define BLACK false; using namespace std; class RBTree { private: class Node { public: string word; bool color; int cnt; int N; Node *left=NULL, *right=NULL; Node(string _word, int _cnt, int _N, bool _color) :word(_word), cnt(_cnt), N(_N), color(_color) {} Node() {} }; Node *root = NULL; bool isRed(Node *x) { if (x == NULL) return false; return x->color == RED; } int size(Node* x) { if (x == NULL) return 0; else return x->N; } /*左旋转*/ Node* rotateLeft(Node *h) { Node *x = h->right; h->right = x->left; x->left = h; x->color = h->color; h->color = RED; x->N = h->N; h->N = 1 + size(h->left) + size(h->right); return x; } /*右旋转*/ Node* rotateRight(Node *h) { Node *x = h->left; h->left = x->right; x->right = h; x->color = h->color; h->color = RED; x->N = h->N; h->N = 1 + size(h->left) + size(h->right); return x; } /*变换颜色*/ void flipColors(Node *h) { h->color = RED; h->left->color = BLACK; h->right->color = BLACK; } Node* put(Node* h, string word, int cnt) { if (h == NULL){ cout << word<<endl; return new Node(word,cnt, 1, true);} int cmp = h->word.compare(word); if (cmp>0) h->left = put(h->left, word, cnt); else if (cmp<0) h->right = put(h->right, word, cnt); else h->cnt = cnt; if (isRed(h->right) && !isRed(h->left)) h = rotateLeft(h); if (isRed(h->left) && isRed(h->left->left)) h = rotateRight(h); if (isRed(h->left) && isRed(h->right)) flipColors(h); h->N = size(h->left) + size(h->right) + 1; return h; } int get(Node* h, string word) { if (h == NULL) return 0; int cmp = h->word.compare(word); if (!cmp) return h->cnt; else if (cmp>0&&h->left) return get(h->left, word); else if(h->right) return get(h->right, word); return 0; } bool find(Node* h,string word) { if (h == NULL) return false; int cmp = h->word.compare(word); if (cmp<0) return find(root->right, word); else if (cmp>0) return find(root->left, word); else if(h->word==word) return true; return false; } void print(Node* h) { if (h == NULL) return; else { print(h->left); printf("%-20s%5d\n", h->word.c_str(), h->cnt); print(h->right); } } void output(Node* h, ofstream& out) { if (h == NULL) return; else { char strs[100]; snprintf(strs, sizeof(strs), "%-30s%5d\n", h->word.c_str(), h->cnt); output(h->left, out); out << string(strs); output(h->right, out); } } void deleteall(Node* h) { if (h == NULL) return; else { deleteall(h->left); deleteall(h->right); delete h; } } public: /*默认初始化*/ RBTree() {} /*讲键值对存入树中*/ void put(string key, int cnt) { root = put(root, key, cnt); root->color = BLACK; } /*在树中查找是否存在该字符串*/ bool find(string key) { return find(root, key); } /*在树中查找该字符串对应的频率*/ int get(string key) { return get(root,key); } /*先序遍历红黑树,并输出*/ void print() { print(root); } /*中序遍历红黑树,并存入文件流*/ void output(ofstream& out) { output(root, out); } /*该树的大小*/ int size() { return size(root); } /*删除所有节点*/ void deleteall() { deleteall(root); } };
OccasionallyPassing/XYCycleCollectionView
XYCycleCollectionView/XYCycleCollectionView/XYScycleCollectionView/XYCollectionViewCell.h
<reponame>OccasionallyPassing/XYCycleCollectionView // // XYCollectionViewCell.h // XYScyleCollectionView // // Created by MiPai on 2017/11/14. // Copyright © 2017年 wangyu. All rights reserved. // #import <UIKit/UIKit.h> @interface XYCollectionViewCell : UICollectionViewCell @property (nonatomic, strong) UIImageView *cycleImage; @property (nonatomic, assign) BOOL isShadow; @property (nonatomic, assign) BOOL isCorner; @property (nonatomic, assign) CGFloat cornerRadius; @end
OccasionallyPassing/XYCycleCollectionView
XYCycleCollectionView/XYCycleCollectionView/XYScycleCollectionView/XYScycleCollectionView.h
<filename>XYCycleCollectionView/XYCycleCollectionView/XYScycleCollectionView/XYScycleCollectionView.h // // XYScycleCollectionView.h // XYScyleCollectionView // // Created by MiPai on 2017/11/14. // Copyright © 2017年 wangyu. All rights reserved. // #import <UIKit/UIKit.h> @class XYScycleCollectionView; @protocol XYScycleCollectionViewDelegate <NSObject> @optional - (void)scycleCollectionView:(XYScycleCollectionView *)scycleCollectionView didSelectItemAtIndex:(NSInteger)index; - (void)scycleCollectionView:(XYScycleCollectionView *)scycleCollectionView didScrollToIndex:(NSInteger)index; @end @interface XYScycleCollectionView : UIView //占位图 @property (nonatomic, strong) UIImage *placeholderImage; //时间间隔,KVO监听,可以改变。 @property (nonatomic, assign) CGFloat timerInterval; //如果时间间隔相同,不必添加KVO。默认YES @property (nonatomic, assign) BOOL isSameTimerInterval; //The space between the view of UIImage @property (nonatomic, assign) CGFloat lineSpace; //The width of the view of UIImage @property (nonatomic, assign) CGFloat imageWidth; //pageControl当前索引图片 @property (nonatomic, strong) UIImage *currentImage; //pageControl默认索引图片 @property (nonatomic, strong) UIImage *defaultImage; //pageControl大小 @property (nonatomic, assign) CGSize pageSize; //图片是否有阴影,默认无阴影 @property (nonatomic, assign) BOOL isShadow; //图片是否有圆角,默认无圆角 @property (nonatomic, assign) BOOL isCorner; //图片圆角大小,默认是10 @property (nonatomic, assign) CGFloat cornerRadius; //设置图片数组存放图片名或者图片URL, //该属性尽量在所有属性设置之后设置,避免无法预估错误 @property (nonatomic, strong) NSArray *imageArr; @property (nonatomic, weak) id <XYScycleCollectionViewDelegate> delegate; //ps:轮播 不适合同时在内存中存在两个能改变timerInterval的XYScycleCollectionView对象,否则KVO监测会出现问题 @end
OccasionallyPassing/XYCycleCollectionView
XYCycleCollectionView/XYCycleCollectionView/ViewController.h
<reponame>OccasionallyPassing/XYCycleCollectionView // // ViewController.h // XYCycleCollectionView // // Created by MiPai on 2017/11/15. // Copyright © 2017年 wangyu. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
OccasionallyPassing/XYCycleCollectionView
XYCycleCollectionView/XYCycleCollectionView/XYScycleCollectionView/XYPageControl.h
// // XYPageControl.h // XYCycleCollectionView // // Created by MiPai on 2017/11/15. // Copyright © 2017年 wangyu. All rights reserved. // #import <UIKit/UIKit.h> @interface XYPageControl : UIPageControl @property (nonatomic) UIImage * currentImage; //高亮图片 @property (nonatomic) UIImage * defaultImage; //默认图片 @property (nonatomic,assign) CGSize pageSize; //图标大小 @end
OccasionallyPassing/XYCycleCollectionView
XYCycleCollectionView/XYCycleCollectionView/DeallocTestViewController.h
<filename>XYCycleCollectionView/XYCycleCollectionView/DeallocTestViewController.h // // DeallocTestViewController.h // XYCycleCollectionView // // Created by MiPai on 2017/11/20. // Copyright © 2017年 wangyu. All rights reserved. // #import <UIKit/UIKit.h> @interface DeallocTestViewController : UIViewController @end
OccasionallyPassing/XYCycleCollectionView
XYCycleCollectionView/XYCycleCollectionView/XYScycleCollectionView/XYCollectionViewFlowLayout.h
// // XYCollectionViewFlowLayout.h // XYScyleCollectionView // // Created by MiPai on 2017/11/14. // Copyright © 2017年 wangyu. All rights reserved. // #import <UIKit/UIKit.h> @interface XYCollectionViewFlowLayout : UICollectionViewFlowLayout @end
fractional-ray/ParaView
ParaViewCore/VTKExtensions/Default/vtkCSVWriter.h
<reponame>fractional-ray/ParaView<filename>ParaViewCore/VTKExtensions/Default/vtkCSVWriter.h /*========================================================================= Program: ParaView Module: vtkCSVWriter.h Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /** * @class vtkCSVWriter * @brief CSV writer for vtkTable * Writes a vtkTable as a delimited text file (such as CSV). */ #ifndef vtkCSVWriter_h #define vtkCSVWriter_h #include "vtkPVVTKExtensionsDefaultModule.h" //needed for exports #include "vtkWriter.h" class vtkStdString; class vtkTable; class VTKPVVTKEXTENSIONSDEFAULT_EXPORT vtkCSVWriter : public vtkWriter { public: static vtkCSVWriter* New(); vtkTypeMacro(vtkCSVWriter, vtkWriter); void PrintSelf(ostream& os, vtkIndent indent) override; //@{ /** * Get/Set the delimiter use to separate fields ("," by default.) */ vtkSetStringMacro(FieldDelimiter); vtkGetStringMacro(FieldDelimiter); //@} //@{ /** * Get/Set the delimiter used for string data, if any * eg. double quotes("). */ vtkSetStringMacro(StringDelimiter); vtkGetStringMacro(StringDelimiter); //@} //@{ /** * Get/Set the filename for the file. */ vtkSetStringMacro(FileName); vtkGetStringMacro(FileName); //@} //@{ /** * Get/Set if StringDelimiter must be used for string data. * True by default. */ vtkSetMacro(UseStringDelimiter, bool); vtkGetMacro(UseStringDelimiter, bool); //@} //@{ /** * Get/Set the precision to use for printing numeric values. * Default is 5. */ vtkSetClampMacro(Precision, int, 0, VTK_INT_MAX); vtkGetMacro(Precision, int); //@} //@{ /** * Get/Set whether scientific notation is used for numeric values. */ vtkSetMacro(UseScientificNotation, bool); vtkGetMacro(UseScientificNotation, bool); vtkBooleanMacro(UseScientificNotation, bool); //@} //@{ /** * Get/set the attribute data to write if the input is either * a vtkDataSet or composite of vtkDataSets. 0 is for point data (vtkDataObject::POINT), * 1 is for cell data (vtkDataObject::CELL) and 2 is for field data (vtkDataObject::FIELD). * Default is 0. */ vtkSetClampMacro(FieldAssociation, int, 0, 2); vtkGetMacro(FieldAssociation, int); //@} //@{ /** * Get/Set whether to add additional meta-data to the field data such as * point coordinates (when point attributes are selected and input is pointset) * or structured coordinates etc. if the input is either a vtkDataSet or composite * of vtkDataSets. */ vtkSetMacro(AddMetaData, bool); vtkGetMacro(AddMetaData, bool); vtkBooleanMacro(AddMetaData, bool); //@} //@{ /** * Internal method: decorates the "string" with the "StringDelimiter" if * UseStringDelimiter is true. */ vtkStdString GetString(vtkStdString string); //@} protected: vtkCSVWriter(); ~vtkCSVWriter() override; /** * Open the file. If append is true then the file will be appended. Otherwise the file * will be overwritten. */ bool OpenFile(bool append); void WriteData() override; virtual void WriteTable(vtkTable* table); // see algorithm for more info. // This writer takes in vtkTable, vtkDataSet or vtkCompositeDataSet. int FillInputPortInformation(int port, vtkInformation* info) override; // see algorithm for more info. needed here so we can request pieces. int ProcessRequest(vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) override; char* FileName; char* FieldDelimiter; char* StringDelimiter; bool UseStringDelimiter; int Precision; bool UseScientificNotation; int FieldAssociation; bool AddMetaData; ofstream* Stream; private: vtkCSVWriter(const vtkCSVWriter&) = delete; void operator=(const vtkCSVWriter&) = delete; }; #endif
OdyX/pappl
pappl/client.c
<filename>pappl/client.c // // Client processing code for the Printer Application Framework // // Copyright © 2019-2021 by <NAME>. // Copyright © 2010-2019 by Apple Inc. // // Licensed under Apache License v2.0. See the file "LICENSE" for more // information. // // // Include necessary headers... // #include "pappl-private.h" // // Local functions... // static bool eval_if_modified(pappl_client_t *client, _pappl_resource_t *r); // // '_papplClientCleanTempFiles()' - Clean temporary files... // void _papplClientCleanTempFiles( pappl_client_t *client) // I - Client { int i; // Looping var for (i = 0; i < client->num_files; i ++) { unlink(client->files[i]); free(client->files[i]); } client->num_files = 0; } // // '_papplClientCreate()' - Accept a new network connection and create a client // object. // // The new network connection is accepted from the specified listen socket. // The client object is managed by the system and is automatically freed when // the connection is closed. // // > Note: This function is normally only called from @link papplSystemRun@. // pappl_client_t * // O - Client _papplClientCreate( pappl_system_t *system, // I - Printer int sock) // I - Listen socket { pappl_client_t *client; // Client if ((client = calloc(1, sizeof(pappl_client_t))) == NULL) { papplLog(system, PAPPL_LOGLEVEL_ERROR, "Unable to allocate memory for client connection: %s", strerror(errno)); return (NULL); } client->system = system; pthread_rwlock_wrlock(&system->rwlock); client->number = system->next_client ++; pthread_rwlock_unlock(&system->rwlock); // Accept the client and get the remote address... if ((client->http = httpAcceptConnection(sock, 1)) == NULL) { papplLog(system, PAPPL_LOGLEVEL_ERROR, "Unable to accept client connection: %s", strerror(errno)); free(client); return (NULL); } httpGetHostname(client->http, client->hostname, sizeof(client->hostname)); papplLogClient(client, PAPPL_LOGLEVEL_INFO, "Accepted connection from '%s'.", client->hostname); return (client); } // // '_papplClientCreateTempFile()' - Create a temporary file. // char * // O - Temporary filename or `NULL` on error _papplClientCreateTempFile( pappl_client_t *client, // I - Client const void *data, // I - Data size_t datasize) // I - Size of data { int fd; // File descriptor char tempfile[1024]; // Temporary filename // See if we have room for another temp file... if (client->num_files >= (int)(sizeof(client->files) / sizeof(client->files[0]))) { papplLogClient(client, PAPPL_LOGLEVEL_ERROR, "Too many temporary files."); return (NULL); } // Write the data to a temporary file... if ((fd = cupsTempFd(tempfile, sizeof(tempfile))) < 0) { papplLogClient(client, PAPPL_LOGLEVEL_ERROR, "Unable to create temporary file: %s", strerror(errno)); return (NULL); } if (write(fd, data, datasize) < 0) { papplLogClient(client, PAPPL_LOGLEVEL_ERROR, "Unable to write to temporary file: %s", strerror(errno)); close(fd); unlink(tempfile); return (NULL); } close(fd); if ((client->files[client->num_files] = strdup(tempfile)) != NULL) client->num_files ++; else unlink(tempfile); if (client->num_files > 0) return (client->files[client->num_files - 1]); else return (NULL); } // // '_papplClientDelete()' - Close the client connection and free all memory used // by a client object. // // > Note: This function is normally only called by // void _papplClientDelete( pappl_client_t *client) // I - Client { papplLogClient(client, PAPPL_LOGLEVEL_INFO, "Closing connection from '%s'.", client->hostname); // Flush pending writes before closing... httpFlushWrite(client->http); _papplClientCleanTempFiles(client); // Free memory... httpClose(client->http); ippDelete(client->request); ippDelete(client->response); free(client); } // // '_papplClientProcessHTTP()' - Process a HTTP request. // bool // O - `true` on success, `false` on failure _papplClientProcessHTTP( pappl_client_t *client) // I - Client connection { char uri[1024]; // URI http_state_t http_state; // HTTP state http_status_t http_status; // HTTP status http_version_t http_version; // HTTP version ipp_state_t ipp_state; // State of IPP transfer char scheme[32], // Method/scheme userpass[128], // Username:password hostname[HTTP_MAX_HOST]; // Hostname int port; // Port number char *ptr; // Pointer into string _pappl_resource_t *resource; // Current resource static const char * const http_states[] = { // Strings for logging HTTP method "WAITING", "OPTIONS", "GET", "GET_SEND", "HEAD", "POST", "POST_RECV", "POST_SEND", "PUT", "PUT_RECV", "DELETE", "TRACE", "CONNECT", "STATUS", "UNKNOWN_METHOD", "UNKNOWN_VERSION" }; // Clear state variables... ippDelete(client->request); ippDelete(client->response); client->request = NULL; client->response = NULL; client->operation = HTTP_STATE_WAITING; // Read a request from the connection... while ((http_state = httpReadRequest(client->http, uri, sizeof(uri))) == HTTP_STATE_WAITING) usleep(1); // Parse the request line... if (http_state == HTTP_STATE_ERROR) { if (httpError(client->http) != EPIPE && httpError(client->http)) papplLogClient(client, PAPPL_LOGLEVEL_DEBUG, "Bad request line (%s).", strerror(httpError(client->http))); return (false); } else if (http_state == HTTP_STATE_UNKNOWN_METHOD) { papplLogClient(client, PAPPL_LOGLEVEL_ERROR, "Bad/unknown operation."); papplClientRespond(client, HTTP_STATUS_BAD_REQUEST, NULL, NULL, 0, 0); return (false); } else if (http_state == HTTP_STATE_UNKNOWN_VERSION) { papplLogClient(client, PAPPL_LOGLEVEL_ERROR, "Bad HTTP version."); papplClientRespond(client, HTTP_STATUS_BAD_REQUEST, NULL, NULL, 0, 0); return (false); } // Separate the URI into its components... if (httpSeparateURI(HTTP_URI_CODING_MOST, uri, scheme, sizeof(scheme), userpass, sizeof(userpass), hostname, sizeof(hostname), &port, client->uri, sizeof(client->uri)) < HTTP_URI_STATUS_OK && (http_state != HTTP_STATE_OPTIONS || strcmp(uri, "*"))) { papplLogClient(client, PAPPL_LOGLEVEL_ERROR, "Bad URI '%s'.", uri); papplClientRespond(client, HTTP_STATUS_BAD_REQUEST, NULL, NULL, 0, 0); return (false); } if ((client->options = strchr(client->uri, '?')) != NULL) *(client->options)++ = '\0'; // Process the request... client->start = time(NULL); client->operation = httpGetState(client->http); // Parse incoming parameters until the status changes... while ((http_status = httpUpdate(client->http)) == HTTP_STATUS_CONTINUE) ; // Read all HTTP headers... if (http_status != HTTP_STATUS_OK) { papplClientRespond(client, HTTP_STATUS_BAD_REQUEST, NULL, NULL, 0, 0); return (false); } http_version = httpGetVersion(client->http); papplLogClient(client, PAPPL_LOGLEVEL_INFO, "%s %s://%s%s HTTP/%d.%d", http_states[http_state], httpIsEncrypted(client->http) ? "https" : "http", httpGetField(client->http, HTTP_FIELD_HOST), uri, http_version / 100, http_version % 100); // Validate the host header... if (!httpGetField(client->http, HTTP_FIELD_HOST)[0] && httpGetVersion(client->http) >= HTTP_VERSION_1_1) { // HTTP/1.1 and higher require the "Host:" field... papplClientRespond(client, HTTP_STATUS_BAD_REQUEST, NULL, NULL, 0, 0); return (false); } strlcpy(client->host_field, httpGetField(client->http, HTTP_FIELD_HOST), sizeof(client->host_field)); if ((ptr = strrchr(client->host_field, ':')) != NULL) { char *end; // End of port number // Grab port number from Host: header... *ptr++ = '\0'; client->host_port = (int)strtol(ptr, &end, 10); if (errno == ERANGE || *end) client->host_port = client->system->port; } else { // Use the default port number... client->host_port = client->system->port; } ptr = strstr(client->host_field, ".local"); if (!isdigit(client->host_field[0] & 255) && client->host_field[0] != '[' && strcmp(client->host_field, client->system->hostname) && strcmp(client->host_field, "localhost") && (!ptr || (strcmp(ptr, ".local") && strcmp(ptr, ".local.")))) { papplLogClient(client, PAPPL_LOGLEVEL_ERROR, "Bad Host: header '%s'.", client->host_field); papplClientRespond(client, HTTP_STATUS_BAD_REQUEST, NULL, NULL, 0, 0); return (false); } // Handle HTTP Upgrade... if (!strcasecmp(httpGetField(client->http, HTTP_FIELD_CONNECTION), "Upgrade")) { if (strstr(httpGetField(client->http, HTTP_FIELD_UPGRADE), "TLS/") != NULL && !httpIsEncrypted(client->http) && !(client->system->options & PAPPL_SOPTIONS_NO_TLS)) { if (!papplClientRespond(client, HTTP_STATUS_SWITCHING_PROTOCOLS, NULL, NULL, 0, 0)) return (false); papplLogClient(client, PAPPL_LOGLEVEL_INFO, "Upgrading to encrypted connection."); if (httpEncryption(client->http, HTTP_ENCRYPTION_REQUIRED)) { papplLogClient(client, PAPPL_LOGLEVEL_ERROR, "Unable to encrypt connection: %s", cupsLastErrorString()); return (false); } papplLogClient(client, PAPPL_LOGLEVEL_INFO, "Connection now encrypted."); } else if (!papplClientRespond(client, HTTP_STATUS_NOT_IMPLEMENTED, NULL, NULL, 0, 0)) return (false); } // Handle HTTP Expect... if (httpGetExpect(client->http) && (client->operation == HTTP_STATE_POST || client->operation == HTTP_STATE_PUT)) { if (httpGetExpect(client->http) == HTTP_STATUS_CONTINUE) { // Send 100-continue header... if (!papplClientRespond(client, HTTP_STATUS_CONTINUE, NULL, NULL, 0, 0)) return (false); } else { // Send 417-expectation-failed header... if (!papplClientRespond(client, HTTP_STATUS_EXPECTATION_FAILED, NULL, NULL, 0, 0)) return (false); } } // Handle new transfers... switch (client->operation) { case HTTP_STATE_OPTIONS : // Do OPTIONS command... return (papplClientRespond(client, HTTP_STATUS_OK, NULL, NULL, 0, 0)); case HTTP_STATE_HEAD : // See if we have a matching resource to serve... if ((resource = _papplSystemFindResource(client->system, client->uri)) != NULL) { if (eval_if_modified(client, resource)) return (papplClientRespond(client, HTTP_STATUS_OK, NULL, resource->format, resource->last_modified, 0)); else return (papplClientRespond(client, HTTP_STATUS_NOT_MODIFIED, NULL, NULL, resource->last_modified, 0)); } // If we get here the resource wasn't found... return (papplClientRespond(client, HTTP_STATUS_NOT_FOUND, NULL, NULL, 0, 0)); case HTTP_STATE_GET : // See if we have a matching resource to serve... if ((resource = _papplSystemFindResource(client->system, client->uri)) != NULL) { if (!eval_if_modified(client, resource)) { return (papplClientRespond(client, HTTP_STATUS_NOT_MODIFIED, NULL, NULL, resource->last_modified, 0)); } else if (resource->cb) { // Send output of a callback... return ((resource->cb)(client, resource->cbdata)); } else if (resource->filename) { // Send an external file... int fd; // Resource file descriptor char buffer[8192]; // Copy buffer ssize_t bytes; // Bytes read/written if ((fd = open(resource->filename, O_RDONLY)) >= 0) { if (!papplClientRespond(client, HTTP_STATUS_OK, NULL, resource->format, resource->last_modified, 0)) { close(fd); return (false); } while ((bytes = read(fd, buffer, sizeof(buffer))) > 0) httpWrite2(client->http, buffer, (size_t)bytes); httpWrite2(client->http, "", 0); close(fd); return (true); } } else { // Send a static resource file... if (!papplClientRespond(client, HTTP_STATUS_OK, NULL, resource->format, resource->last_modified, resource->length)) return (false); httpWrite2(client->http, (const char *)resource->data, resource->length); httpFlushWrite(client->http); return (true); } } // If we get here then the resource wasn't found... return (papplClientRespond(client, HTTP_STATUS_NOT_FOUND, NULL, NULL, 0, 0)); case HTTP_STATE_POST : if (!strcmp(httpGetField(client->http, HTTP_FIELD_CONTENT_TYPE), "application/ipp")) { // Read the IPP request... client->request = ippNew(); while ((ipp_state = ippRead(client->http, client->request)) != IPP_STATE_DATA) { if (ipp_state == IPP_STATE_ERROR) { papplLogClient(client, PAPPL_LOGLEVEL_ERROR, "IPP read error (%s).", cupsLastErrorString()); papplClientRespond(client, HTTP_STATUS_BAD_REQUEST, NULL, NULL, 0, 0); return (false); } } // Now that we have the IPP request, process the request... return (_papplClientProcessIPP(client)); } else if ((resource = _papplSystemFindResource(client->system, client->uri)) != NULL) { // Serve a matching resource... if (resource->cb) { // Handle a post request through the callback... return ((resource->cb)(client, resource->cbdata)); } else { // Otherwise you can't POST to a resource... return (papplClientRespond(client, HTTP_STATUS_BAD_REQUEST, NULL, NULL, 0, 0)); } } else { // Not an IPP request or form, return an error... return (papplClientRespond(client, HTTP_STATUS_BAD_REQUEST, NULL, NULL, 0, 0)); } default : break; // Anti-compiler-warning-code } return (true); } // // 'papplClientRespond()' - Send a regular HTTP response. // // This function sends all of the required HTTP fields and includes standard // messages for errors. The following values for "code" are explicitly // supported: // // - `HTTP_STATUS_OK`: The request is successful. // - `HTTP_STATUS_BAD_REQUEST`: The client submitted a bad request. // - `HTTP_STATUS_CONTINUE`: An authentication challenge is not needed. // - `HTTP_STATUS_FORBIDDEN`: Authenticated but not allowed. // - `HTTP_STATUS_METHOD_NOT_ALLOWED`: The HTTP method is not supported for the // given URI. // - `HTTP_STATUS_UNAUTHORIZED`: Not authenticated. // - `HTTP_STATUS_UPGRADE_REQUIRED`: Redirects the client to a secure page. // // Use the @link papplClientRespondRedirect@ when you need to redirect the // client to another page. // bool // O - `true` on success, `false` on failure papplClientRespond( pappl_client_t *client, // I - Client http_status_t code, // I - HTTP status of response const char *content_encoding, // I - Content-Encoding of response const char *type, // I - MIME media type of response time_t last_modified, // I - Last-Modified date/time or `0` for none size_t length) // I - Length of response or `0` for variable-length { char message[1024]; // Text message if (type) papplLogClient(client, PAPPL_LOGLEVEL_INFO, "%s %s %d", httpStatus(code), type, (int)length); else papplLogClient(client, PAPPL_LOGLEVEL_INFO, "%s", httpStatus(code)); if (code == HTTP_STATUS_CONTINUE) { // 100-continue doesn't send any headers... return (httpWriteResponse(client->http, HTTP_STATUS_CONTINUE) == 0); } // Format an error message... if (!type && !length && code != HTTP_STATUS_OK && code != HTTP_STATUS_SWITCHING_PROTOCOLS) { snprintf(message, sizeof(message), "%d - %s\n", code, httpStatus(code)); type = "text/plain"; length = strlen(message); } else message[0] = '\0'; // Send the HTTP response header... httpClearFields(client->http); httpSetField(client->http, HTTP_FIELD_SERVER, papplSystemGetServerHeader(client->system)); if (last_modified) httpSetField(client->http, HTTP_FIELD_LAST_MODIFIED, httpGetDateString(last_modified)); if (code == HTTP_STATUS_METHOD_NOT_ALLOWED || client->operation == HTTP_STATE_OPTIONS) httpSetField(client->http, HTTP_FIELD_ALLOW, "GET, HEAD, OPTIONS, POST"); if (code == HTTP_STATUS_UNAUTHORIZED) { char value[HTTP_MAX_VALUE]; // WWW-Authenticate value snprintf(value, sizeof(value), "Basic realm=\"%s\"", client->system->name); httpSetField(client->http, HTTP_FIELD_WWW_AUTHENTICATE, value); } if (type) { if (!strcmp(type, "text/html")) httpSetField(client->http, HTTP_FIELD_CONTENT_TYPE, "text/html; charset=utf-8"); else httpSetField(client->http, HTTP_FIELD_CONTENT_TYPE, type); if (content_encoding) httpSetField(client->http, HTTP_FIELD_CONTENT_ENCODING, content_encoding); } httpSetLength(client->http, length); if (code == HTTP_STATUS_UPGRADE_REQUIRED && client->operation == HTTP_STATE_GET) { char redirect[1024]; // Redirect URI code = HTTP_STATUS_MOVED_PERMANENTLY; httpAssembleURI(HTTP_URI_CODING_ALL, redirect, sizeof(redirect), "https", NULL, client->host_field, client->host_port, client->uri); httpSetField(client->http, HTTP_FIELD_LOCATION, redirect); } if (httpWriteResponse(client->http, code) < 0) return (false); // Send the response data... if (message[0]) { // Send a plain text message. if (httpPrintf(client->http, "%s", message) < 0) return (false); if (httpWrite2(client->http, "", 0) < 0) return (false); } else if (client->response) { // Send an IPP response... _papplLogAttributes(client, ippOpString(client->operation_id), client->response, true); ippSetState(client->response, IPP_STATE_IDLE); if (ippWrite(client->http, client->response) != IPP_STATE_DATA) return (false); } return (true); } // // 'papplClientRespondRedirect()' - Respond with a redirect to another page. // // This function sends a HTTP response that redirects the client to another // page or URL. The most common "code" value to return is `HTTP_STATUS_FOUND`. // bool // O - `true` on success, `false` otherwise papplClientRespondRedirect( pappl_client_t *client, // I - Client http_status_t code, // I - `HTTP_STATUS_MOVED_PERMANENTLY` or `HTTP_STATUS_FOUND` const char *path) // I - Redirection path/URL { papplLogClient(client, PAPPL_LOGLEVEL_INFO, "%s %s", httpStatus(code), path); // Send the HTTP response header... httpClearFields(client->http); httpSetField(client->http, HTTP_FIELD_SERVER, papplSystemGetServerHeader(client->system)); httpSetLength(client->http, 0); if (*path == '/' || !strchr(path, ':')) { // Generate an absolute URL... char url[1024]; // Absolute URL if (*path == '/') httpAssembleURI(HTTP_URI_CODING_ALL, url, sizeof(url), "https", NULL, client->host_field, client->host_port, path); else httpAssembleURIf(HTTP_URI_CODING_ALL, url, sizeof(url), "https", NULL, client->host_field, client->host_port, "/%s", path); httpSetField(client->http, HTTP_FIELD_LOCATION, url); } else { // The path is already an absolute URL... httpSetField(client->http, HTTP_FIELD_LOCATION, path); } if (httpWriteResponse(client->http, code) < 0) return (false); return (httpWrite2(client->http, "", 0) >= 0); } // // '_papplClientRun()' - Process client requests on a thread. // void * // O - Exit status _papplClientRun( pappl_client_t *client) // I - Client { int first_time = 1; // First time request? // Loop until we are out of requests or timeout (30 seconds)... while (httpWait(client->http, 30000)) { if (first_time && !(client->system->options & PAPPL_SOPTIONS_NO_TLS)) { // See if we need to negotiate a TLS connection... char buf[1]; // First byte from client if (recv(httpGetFd(client->http), buf, 1, MSG_PEEK) == 1 && (!buf[0] || !strchr("DGHOPT", buf[0]))) { papplLogClient(client, PAPPL_LOGLEVEL_INFO, "Starting HTTPS session."); if (httpEncryption(client->http, HTTP_ENCRYPTION_ALWAYS)) { papplLogClient(client, PAPPL_LOGLEVEL_ERROR, "Unable to encrypt connection: %s", cupsLastErrorString()); break; } papplLogClient(client, PAPPL_LOGLEVEL_INFO, "Connection now encrypted."); } first_time = 0; } if (!_papplClientProcessHTTP(client)) break; _papplClientCleanTempFiles(client); } // Close the conection to the client and return... _papplClientDelete(client); return (NULL); } // // 'eval_if_modified()' - Evaluate an "If-Modified-Since" header. // static bool // O - `true` if modified, `false` otherwise eval_if_modified( pappl_client_t *client, // I - Client _pappl_resource_t *r) // I - Resource { const char *ptr; // Pointer into field time_t date = 0; // Time/date value off_t size = 0; // Size/length value // Dynamic content always needs to be updated... if (r->cb) return (true); // Get "If-Modified-Since:" header ptr = httpGetField(client->http, HTTP_FIELD_IF_MODIFIED_SINCE); if (*ptr == '\0') return (true); // Decode the If-Modified-Since: header... while (*ptr != '\0') { while (isspace(*ptr) || *ptr == ';') ptr ++; if (!strncasecmp(ptr, "length=", 7)) { char *next; // Next character size = strtoll(ptr + 7, &next, 10); if (!next) { papplLogClient(client, PAPPL_LOGLEVEL_DEBUG, "If-Modified-Since: Bad length."); return (true); } ptr = next; } else if (isalpha(*ptr & 255)) { date = httpGetDateTime(ptr); while (*ptr != '\0' && *ptr != ';') ptr ++; } else ptr ++; } // Return the evaluation based on the last modified date, time, and size... return ((size != 0 && size != (off_t)r->length) || (date != 0 && date < r->last_modified) || (size == 0 && date == 0)); }
OdyX/pappl
pappl/system-accessors.c
// // System accessor functions for the Printer Application Framework // // Copyright © 2020 by <NAME>. // // Licensed under Apache License v2.0. See the file "LICENSE" for more // information. // // // Include necessary headers... // #include "system-private.h" #ifdef HAVE_LIBJPEG # include <jpeglib.h> # ifndef JPEG_LIB_VERSION_MAJOR // Added in JPEGLIB 9 # define JPEG_LIB_VERSION_MAJOR 8 # define JPEG_LIB_VERSION_MINOR 0 # endif // !JPEG_LIB_VERSION_MAJOR #endif // HAVE_LIBJPEG #ifdef HAVE_LIBPNG # include <png.h> #endif // HAVE_LIBPNG // // Local functions... // static bool add_listeners(pappl_system_t *system, const char *name, int port, int family); static int compare_filters(_pappl_mime_filter_t *a, _pappl_mime_filter_t *b); static _pappl_mime_filter_t *copy_filter(_pappl_mime_filter_t *f); // // 'papplSystemAddListeners()' - Add network or domain socket listeners. // // This function adds socket listeners. The "name" parameter specifies the // listener address. Names starting with a slash (/) specify a UNIX domain // socket path, otherwise the name is treated as a fully-qualified domain name // or numeric IPv4 or IPv6 address. If name is `NULL`, the "any" addresses are // used ("0.0.0.0" and "[::]"). // // Listeners cannot be added after @link papplSystemRun@ is called. // bool // O - `true` on success, `false` on failure papplSystemAddListeners( pappl_system_t *system, // I - System const char *name) // I - Hostname, domain socket filename, or `NULL` { bool ret; // Return value if (!system) { return (false); } else if (system->is_running) { papplLog(system, PAPPL_LOGLEVEL_FATAL, "Tried to add listeners while system is running."); return (false); } if (name && *name == '/') { // Add a domain socket listener... ret = add_listeners(system, name, 0, AF_LOCAL); } else if (name && isdigit(*name & 255)) { // Add IPv4 listener... if (system->port) { ret = add_listeners(system, name, system->port, AF_INET); } else { int port = 7999 + (getuid() % 1000); // Current port do { port ++; ret = add_listeners(system, name, port, AF_INET); } while (!ret && port < 10000); if (ret) system->port = port; } } else if (name && *name == '[') { // Add IPv6 listener... if (system->port) { ret = add_listeners(system, name, system->port, AF_INET6); } else { int port = 7999 + (getuid() % 1000); // Current port do { port ++; ret = add_listeners(system, name, port, AF_INET6); } while (!ret && port < 10000); if (ret) system->port = port; } } else { // Add named listeners on both IPv4 and IPv6... if (system->port) { ret = add_listeners(system, name, system->port, AF_INET) || add_listeners(system, name, system->port, AF_INET6); } else { int port = 7999 + (getuid() % 1000); // Current port do { port ++; ret = add_listeners(system, name, port, AF_INET); } while (!ret && port < 10000); if (ret) { system->port = port; add_listeners(system, name, port, AF_INET6); } } } return (ret); } // // 'papplSystemAddMIMEFilter()' - Add a file filter to the system. // // This function adds a file filter to the system to be used for processing // different kinds of document data in print jobs. The "srctype" and "dsttype" // arguments specify the source and destination MIME media types as constant // strings. A destination MIME media type of "image/pwg-raster" specifies a // filter that uses the driver's raster interface. Other destination types // imply direct submission to the output device using the `papplDeviceXxx` // functions. // // > Note: This function may not be called while the system is running. // void papplSystemAddMIMEFilter( pappl_system_t *system, // I - System const char *srctype, // I - Source MIME media type (constant) string const char *dsttype, // I - Destination MIME media type (constant) string pappl_mime_filter_cb_t cb, // I - Filter callback function void *data) // I - Filter callback data { _pappl_mime_filter_t key; // Search key if (!system || system->is_running || !srctype || !dsttype || !cb) return; if (!system->filters) system->filters = cupsArrayNew3((cups_array_func_t)compare_filters, NULL, NULL, 0, (cups_acopy_func_t)copy_filter, (cups_afree_func_t)free); key.src = srctype; key.dst = dsttype; key.cb = cb; key.cbdata = data; if (!cupsArrayFind(system->filters, &key)) { papplLog(system, PAPPL_LOGLEVEL_DEBUG, "Adding '%s' to '%s' filter.", srctype, dsttype); cupsArrayAdd(system->filters, &key); } } // // '_papplSystemExportVersions()' - Export the firmware versions to IPP attributes... // void _papplSystemExportVersions( pappl_system_t *system, // I - System ipp_t *ipp, // I - IPP message ipp_tag_t group_tag, // I - Group (`IPP_TAG_PRINTER` or `IPP_TAG_SYSTEM`) cups_array_t *ra) // I - Requested attributes or `NULL` for all { int i; // Looping var ipp_attribute_t *attr; // Attribute char name[128]; // Attribute name const char *name_prefix = (group_tag == IPP_TAG_PRINTER) ? "printer" : "system"; const char *values[20]; // String values char cups_sversion[32]; // String version of libcups #ifdef HAVE_LIBJPEG char jpeg_sversion[32]; // String version of libjpeg #endif // HAVE_LIBJPEG unsigned short version[4]; // Version of software components // "xxx-firmware-name" snprintf(name, sizeof(name), "%s-firmware-name", name_prefix); if (!ra || cupsArrayFind(ra, name)) { for (i = 0; i < system->num_versions; i ++) values[i] = system->versions[i].name; values[i ++] = "PAPPL"; values[i ++] = "libcups"; #ifdef HAVE_LIBJPEG values[i ++] = "libjpeg"; #endif // HAVE_LIBJPEG #ifdef HAVE_LIBPNG values[i ++] = "libpng"; #endif // HAVE_LIBPNG ippAddStrings(ipp, group_tag, IPP_TAG_NAME, name, i, NULL, values); } // "xxx-firmware-patches" snprintf(name, sizeof(name), "%s-firmware-patches", name_prefix); if (!ra || cupsArrayFind(ra, name)) { for (i = 0; i < system->num_versions; i ++) values[i] = system->versions[i].patches; values[i ++] = ""; // No patches for PAPPL values[i ++] = ""; // No patches for CUPS #ifdef HAVE_LIBJPEG values[i ++] = ""; // No patches for libjpeg #endif // HAVE_LIBJPEG #ifdef HAVE_LIBPNG values[i ++] = ""; // No patches for libpng #endif // HAVE_LIBPNG ippAddStrings(ipp, group_tag, IPP_TAG_TEXT, name, i, NULL, values); } // "xxx-firmware-string-version" snprintf(name, sizeof(name), "%s-firmware-string-version", name_prefix); if (!ra || cupsArrayFind(ra, name)) { for (i = 0; i < system->num_versions; i ++) values[i] = system->versions[i].sversion; values[i ++] = PAPPL_VERSION; snprintf(cups_sversion, sizeof(cups_sversion), "%d.%d.%d", CUPS_VERSION_MAJOR, CUPS_VERSION_MINOR, CUPS_VERSION_PATCH); values[i ++] = cups_sversion; #ifdef HAVE_LIBJPEG snprintf(jpeg_sversion, sizeof(jpeg_sversion), "%d.%d", JPEG_LIB_VERSION_MAJOR, JPEG_LIB_VERSION_MINOR); values[i ++] = jpeg_sversion; #endif // HAVE_LIBJPEG #ifdef HAVE_LIBPNG values[i ++] = png_libpng_ver; #endif // HAVE_LIBPNG ippAddStrings(ipp, group_tag, IPP_TAG_TEXT, name, i, NULL, values); } // "xxx-firmware-version" snprintf(name, sizeof(name), "%s-firmware-version", name_prefix); if (!ra || cupsArrayFind(ra, name)) { for (i = 0, attr = NULL; i < system->num_versions; i ++) { if (attr) ippSetOctetString(ipp, &attr, ippGetCount(attr), system->versions[i].version, (int)sizeof(system->versions[i].version)); else attr = ippAddOctetString(ipp, group_tag, name, system->versions[i].version, (int)sizeof(system->versions[i].version)); } memset(version, 0, sizeof(version)); sscanf(PAPPL_VERSION, "%hu.%hu.%hu", version + 0, version + 1, version + 2); if (attr) ippSetOctetString(ipp, &attr, ippGetCount(attr), version, (int)sizeof(version)); else attr = ippAddOctetString(ipp, group_tag, name, version, (int)sizeof(version)); version[0] = CUPS_VERSION_MAJOR; version[1] = CUPS_VERSION_MINOR; version[2] = CUPS_VERSION_PATCH; ippSetOctetString(ipp, &attr, ippGetCount(attr), version, (int)sizeof(version)); #ifdef HAVE_LIBJPEG version[0] = JPEG_LIB_VERSION_MAJOR; version[1] = JPEG_LIB_VERSION_MINOR; version[2] = 0; ippSetOctetString(ipp, &attr, ippGetCount(attr), version, (int)sizeof(version)); #endif // HAVE_LIBJPEG #ifdef HAVE_LIBPNG memset(version, 0, sizeof(version)); sscanf(png_libpng_ver, "%hu.%hu.%hu", version + 0, version + 1, version + 2); ippSetOctetString(ipp, &attr, ippGetCount(attr), version, (int)sizeof(version)); #endif // HAVE_LIBPNG } } // // '_papplSystemFindMIMEFilter()' - Find a filter for the given source and destination formats. // _pappl_mime_filter_t * // O - Filter data _papplSystemFindMIMEFilter( pappl_system_t *system, // I - System const char *srctype, // I - Source MIME media type string const char *dsttype) // I - Destination MIME media type string { _pappl_mime_filter_t key, // Search key *match; // Matching filter if (!system || !srctype || !dsttype) return (NULL); pthread_rwlock_rdlock(&system->rwlock); key.src = srctype; key.dst = dsttype; match = (_pappl_mime_filter_t *)cupsArrayFind(system->filters, &key); pthread_rwlock_unlock(&system->rwlock); return (match); } // // 'papplSystemGetAdminGroup()' - Get the current administrative group, if any. // // This function copies the current administrative group, if any, to the // specified buffer. // char * // O - Admin group or `NULL` if none papplSystemGetAdminGroup( pappl_system_t *system, // I - System char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { char *ret = NULL; // Return value if (system && buffer && bufsize > 0) { pthread_rwlock_rdlock(&system->rwlock); if (system->admin_group) { strlcpy(buffer, system->admin_group, bufsize); ret = buffer; } else *buffer = '\0'; pthread_rwlock_unlock(&system->rwlock); } else if (buffer) *buffer = '\0'; return (ret); } // // 'papplSystemGetAuthService()' - Get the PAM authorization service, if any. // // This function returns the PAM authorization service being used by the system // for authentication, if any. // const char * // O - PAM authorization service or `NULL` if none papplSystemGetAuthService( pappl_system_t *system) // I - System { return (system ? system->auth_service : NULL); } // // 'papplSystemGetContact()' - Get the "system-contact" value. // // This function copies the current system contact information to the specified // buffer. // pappl_contact_t * // O - Contact papplSystemGetContact( pappl_system_t *system, // I - System pappl_contact_t *contact) // O - Contact { if (!system || !contact) { if (contact) memset(contact, 0, sizeof(pappl_contact_t)); return (contact); } pthread_rwlock_rdlock(&system->rwlock); *contact = system->contact; pthread_rwlock_unlock(&system->rwlock); return (contact); } // // 'papplSystemGetDefaultPrinterID()' - Get the current "default-printer-id" value. // // This function returns the positive integer identifier for the current // default printer or `0` if there is no default printer. // int // O - "default-printer-id" value papplSystemGetDefaultPrinterID( pappl_system_t *system) // I - System { return (system ? system->default_printer_id : 0); } // // 'papplSystemGetDefaultPrintGroup()' - Get the default print group, if any. // // This function copies the current default print group, if any, to the // specified buffer. // char * // O - Default print group or `NULL` if none papplSystemGetDefaultPrintGroup( pappl_system_t *system, // I - System char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { char *ret = NULL; // Return value if (system && buffer && bufsize > 0) { pthread_rwlock_rdlock(&system->rwlock); if (system->default_print_group) { strlcpy(buffer, system->default_print_group, bufsize); ret = buffer; } else *buffer = '\0'; pthread_rwlock_unlock(&system->rwlock); } else if (buffer) *buffer = '\0'; return (ret); } // // 'papplSystemGetDNSSDName()' - Get the current DNS-SD service name. // // This function copies the current DNS-SD service name of the system, if any, // to the specified buffer. // char * // O - Current DNS-SD service name or `NULL` for none papplSystemGetDNSSDName( pappl_system_t *system, // I - System char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { char *ret = NULL; // Return value if (system && buffer && bufsize > 0) { pthread_rwlock_rdlock(&system->rwlock); if (system->dns_sd_name) { strlcpy(buffer, system->dns_sd_name, bufsize); ret = buffer; } else *buffer = '\0'; pthread_rwlock_unlock(&system->rwlock); } else if (buffer) *buffer = '\0'; return (ret); } // // 'papplSystemGetFooterHTML()' - Get the footer HTML for the web interface, if any. // // This function returns the HTML for the web page footer, if any. The footer // HTML can be set using the @link papplSystemSetFooterHTML@ function. // const char * // O - Footer HTML or `NULL` if none papplSystemGetFooterHTML( pappl_system_t *system) // I - System { return (system ? system->footer_html : NULL); } // // 'papplSystemGetGeoLocation()' - Get the system geo-location string, if any. // // This function copies the current system geographic location as a "geo:" URI // to the specified buffer. // char * // O - "geo:" URI or `NULL` for none papplSystemGetGeoLocation( pappl_system_t *system, // I - System char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { char *ret = NULL; // Return value if (system && buffer && bufsize > 0) { pthread_rwlock_rdlock(&system->rwlock); if (system->geo_location) { strlcpy(buffer, system->geo_location, bufsize); ret = buffer; } else *buffer = '\0'; pthread_rwlock_unlock(&system->rwlock); } else if (buffer) *buffer = '\0'; return (ret); } // // 'papplSystemGetHostname()' - Get the system hostname. // // This function copies the current system hostname to the specified buffer. // char * // O - Hostname papplSystemGetHostname( pappl_system_t *system, // I - System char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { char *ret = NULL; // Return value if (system && buffer && bufsize > 0) { pthread_rwlock_rdlock(&system->rwlock); if (system->hostname) { strlcpy(buffer, system->hostname, bufsize); ret = buffer; } else *buffer = '\0'; pthread_rwlock_unlock(&system->rwlock); } else if (buffer) *buffer = '\0'; return (ret); } // // 'papplSystemGetLocation()' - Get the system location string, if any. // // This function copies the current human-readable location, if any, to the // specified buffer. // char * // O - Location string or `NULL` for none papplSystemGetLocation( pappl_system_t *system, // I - System char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { char *ret = NULL; // Return value if (system && buffer && bufsize > 0) { pthread_rwlock_rdlock(&system->rwlock); if (system->location) { strlcpy(buffer, system->location, bufsize); ret = buffer; } else *buffer = '\0'; pthread_rwlock_unlock(&system->rwlock); } else if (buffer) *buffer = '\0'; return (ret); } // // 'papplSystemGetLogLevel()' - Get the system log level. // // This function returns the current system log level as an enumeration. // pappl_loglevel_t papplSystemGetLogLevel( pappl_system_t *system) // I - System { return (system ? system->loglevel : PAPPL_LOGLEVEL_UNSPEC); } // // 'papplSystemGetMaxLogSize()' - Get the maximum log file size. // // This function gets the maximum log file size, which is only used when logging // directly to a file. When the limit is reached, the current log file is // renamed to "filename.O" and a new log file is created. Set the maximum size // to `0` to disable log file rotation. // // The default maximum log file size is 1MiB or `1048576` bytes. // size_t // O - Maximum log file size or `0` for none papplSystemGetMaxLogSize( pappl_system_t *system) // I - System { return (system ? system->logmaxsize : 0); } // // 'papplSystemGetName()' - Get the system name. // // This function copies the current system name to the specified buffer. // char * // O - Name string papplSystemGetName( pappl_system_t *system, // I - System char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { char *ret = NULL; // Return value if (system && buffer && bufsize > 0) { pthread_rwlock_rdlock(&system->rwlock); if (system->name) { strlcpy(buffer, system->name, bufsize); ret = buffer; } else *buffer = '\0'; pthread_rwlock_unlock(&system->rwlock); } else if (buffer) *buffer = '\0'; return (ret); } // // 'papplSystemGetNextPrinterID()' - Get the next "printer-id" value. // // This function returns the positive integer identifier that will be used for // the next printer that is created. // int // O - Next "printer-id" value papplSystemGetNextPrinterID( pappl_system_t *system) // I - System { return (system ? system->next_printer_id : 0); } // // 'papplSystemGetOptions()' - Get the system options. // // This function returns the system options as a bitfield. // pappl_soptions_t // O - System options papplSystemGetOptions( pappl_system_t *system) // I - System { return (system ? system->options : PAPPL_SOPTIONS_NONE); } // // 'papplSystemGetOrganization()' - Get the system organization string, if any. // // This function copies the current organization name, if any, to the // specified buffer. // char * // O - Organization string or `NULL` for none papplSystemGetOrganization( pappl_system_t *system, // I - System char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { char *ret = NULL; // Return value if (system && buffer && bufsize > 0) { pthread_rwlock_rdlock(&system->rwlock); if (system->organization) { strlcpy(buffer, system->organization, bufsize); ret = buffer; } else *buffer = '\0'; pthread_rwlock_unlock(&system->rwlock); } else if (buffer) *buffer = '\0'; return (ret); } // // 'papplSystemGetOrganizationalUnit()' - Get the system organizational unit string, if any. // // This function copies the current organizational unit name, if any, to the // specified buffer. // char * // O - Organizational unit string or `NULL` for none papplSystemGetOrganizationalUnit( pappl_system_t *system, // I - System char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { char *ret = NULL; // Return value if (system && buffer && bufsize > 0) { pthread_rwlock_rdlock(&system->rwlock); if (system->org_unit) { strlcpy(buffer, system->org_unit, bufsize); ret = buffer; } else *buffer = '\0'; pthread_rwlock_unlock(&system->rwlock); } else if (buffer) *buffer = '\0'; return (ret); } // // 'papplSystemGetPassword()' - Get the current web site access password. // // This function copies the current web site password hash, if any, to the // specified buffer. // // Note: The access password is only used when the PAM authentication service // is not set. // char * // O - Password hash papplSystemGetPassword( pappl_system_t *system, // I - System char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { if (system && buffer && bufsize > 0) { pthread_rwlock_rdlock(&system->rwlock); strlcpy(buffer, system->password_hash, bufsize); pthread_rwlock_unlock(&system->rwlock); } else if (buffer) *buffer = '\0'; return (buffer); } // // 'papplSystemGetPort()' - Get the port number for network connections to the // system. // // This function returns the port number that is used for network connections // to the system. // int // O - Port number papplSystemGetPort( pappl_system_t *system) // I - System { return (system ? system->port : 0); } // // 'papplSystemGetServerHeader()' - Get the Server: header for HTTP responses. // // This function returns the value of the HTTP "Server:" header that is used // by the system. // const char * // O - Server: header string or `NULL` for none papplSystemGetServerHeader( pappl_system_t *system) // I - System { return (system ? system->server_header : NULL); } // // 'papplSystemGetSessionKey()' - Get the current session key. // // This function copies the current session key to the specified buffer. The // session key is used for web interface forms to provide CSRF protection and is // refreshed periodically. // char * // O - Session key papplSystemGetSessionKey( pappl_system_t *system, // I - System char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { time_t curtime = time(NULL); // Current time if (system && buffer && bufsize > 0) { if ((curtime - system->session_time) > 86400) { // Lock for updating the session key with random data... pthread_rwlock_wrlock(&system->session_rwlock); snprintf(system->session_key, sizeof(system->session_key), "%08x%08x%08x%08x%08x%08x%08x%08x", _papplGetRand(), _papplGetRand(), _papplGetRand(), _papplGetRand(), _papplGetRand(), _papplGetRand(), _papplGetRand(), _papplGetRand()); system->session_time = curtime; } else { // Lock for reading... pthread_rwlock_rdlock(&system->session_rwlock); } strlcpy(buffer, system->session_key, bufsize); pthread_rwlock_unlock(&system->session_rwlock); } else if (buffer) *buffer = '\0'; return (buffer); } // // 'papplSystemGetTLSOnly()' - Get the TLS-only state of the system. // // This function returns whether the system will only accept encrypted // connections. // bool // O - `true` if the system is only accepting TLS encrypted connections, `false` otherwise papplSystemGetTLSOnly( pappl_system_t *system) // I - System { return (system ? system->tls_only : false); } // // 'papplSystemGetUUID()' - Get the "system-uuid" value. // // This function returns the system's UUID value. // const char * // O - "system-uuid" value papplSystemGetUUID( pappl_system_t *system) // I - System { return (system ? system->uuid : NULL); } // // 'papplSystemGetVersions()' - Get the firmware names and versions. // // This function copies the system firmware information to the specified buffer. // The return value is always the number of firmware versions that have been // set using the @link papplSystemSetVersions@ function, regardless of the // value of the "max_versions" argument. // int // O - Number of firmware versions papplSystemGetVersions( pappl_system_t *system, // I - System int max_versions, // I - Maximum number of versions to return pappl_version_t *versions) // O - Versions array or `NULL` for don't care { if (versions && max_versions > 0) memset(versions, 0, (size_t)max_versions * sizeof(pappl_version_t)); if (system && versions && system->num_versions > 0) { pthread_rwlock_rdlock(&system->rwlock); if (max_versions > system->num_versions) memcpy(versions, system->versions, (size_t)system->num_versions * sizeof(pappl_version_t)); else memcpy(versions, system->versions, (size_t)max_versions * sizeof(pappl_version_t)); pthread_rwlock_unlock(&system->rwlock); } return (system ? system->num_versions : 0); } // // 'papplSystemHashPassword()' - Generate a password hash using salt and password strings. // // This function generates a password hash using the "salt" and "password" // strings. The "salt" string should be `NULL` to generate a new password hash // or the value of an existing password hash to verify that a given plaintext // "password" string matches the password hash. // // > Note: Hashed access passwords are only used when the PAM authentication // > service is not set. // char * // O - Hashed password papplSystemHashPassword( pappl_system_t *system, // I - System const char *salt, // I - Existing password hash or `NULL` to generate a new hash const char *password, // I - Plain-text password string char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { if (system && password && buffer && bufsize > 0) { char nonce[100], // Nonce string *ptr, // Pointer into string temp[256]; // Temporary hash unsigned char hash[32]; // SHA2-256 hash if (salt && strchr(salt, '~')) { // Copy existing nonce from the salt string... strlcpy(nonce, salt, sizeof(nonce)); if ((ptr = strchr(nonce, ':')) != NULL) *ptr = '\0'; } else { // Generate a new random nonce... snprintf(nonce, sizeof(nonce), "%08x%08x", _papplGetRand(), _papplGetRand()); } snprintf(temp, sizeof(temp), "%s:%s", nonce, password); cupsHashData("sha2-256", temp, strlen(temp), hash, sizeof(hash)); cupsHashString(hash, sizeof(hash), temp, sizeof(temp)); snprintf(buffer, bufsize, "%s~%s", nonce, temp); } else if (buffer) *buffer = '\0'; return (buffer); } // // 'papplSystemIsRunning()' - Return whether the system is running. // // This function returns whether the system is running. // bool // O - `true` if the system is running, `false` otherwise papplSystemIsRunning( pappl_system_t *system) // I - System { return (system ? system->is_running : false); } // // 'papplSystemIsShutdown()' - Return whether the system has been shutdown. // // This function returns whether the system is shutdown or scheduled to // shutdown. // bool // O - `true` if the system is shutdown, `false` otherwise papplSystemIsShutdown( pappl_system_t *system) // I - System { return (system ? (!system->is_running || system->shutdown_time != 0) : false); } // // 'papplSystemIteratePrinters()' - Iterate all of the printers. // // This function iterates each of the printers managed by the system. The // "cb" function is called once per printer with the "system" and "data" values. // void papplSystemIteratePrinters( pappl_system_t *system, // I - System pappl_printer_cb_t cb, // I - Callback function void *data) // I - Callback data { pappl_printer_t *printer; // Current printer if (!system || !cb) return; pthread_rwlock_rdlock(&system->rwlock); for (printer = (pappl_printer_t *)cupsArrayFirst(system->printers); printer; printer = (pappl_printer_t *)cupsArrayNext(system->printers)) (cb)(printer, data); pthread_rwlock_unlock(&system->rwlock); } // // 'papplSystemMatchDriver()' - Match a driver to an IEEE-1284 device ID. // const char * papplSystemMatchDriver( pappl_system_t *system, // I - System const char *device_id) // I - IEEE-1284 device ID string { int i; // Looping var pappl_pr_driver_t *driver; // Current driver const char *drvstart, // Start of key/value pair *drvend, // End of key/value pair *didptr, // Pointer into device ID *didend; // End of device ID size_t drvlen, // Length of key/value pair didlen; // Length of device ID if (!system) return (NULL); didlen = strlen(device_id); for (i = system->num_drivers, driver = system->drivers; i > 0; i --, driver ++) { if (!driver->device_id) continue; // Parse each of the driver's device ID pairs and compare against the // supplied device ID... drvstart = driver->device_id; while (*drvstart) { // Skip leading semicolons and whitespace (not valid, but sometimes // present...) while (*drvstart == ';' || isspace(*drvstart & 255)) drvstart ++; if (!*drvstart) break; // Find the end of the current key:value pair... drvend = drvstart + 1; while (*drvend && *drvend != ';') drvend ++; if (*drvend == ';') drvend ++; drvlen = (size_t)(drvend - drvstart); // See if this string exists in the target device ID... didptr = device_id; didend = didptr + didlen - drvlen; while (didptr && didptr < didend) { if (!strncmp(didptr, drvstart, drvlen)) break; if ((didptr = strchr(didptr, ';')) != NULL) didptr ++; } if (!didptr || didptr >= didend) break; drvstart = drvend; } if (!*drvstart) break; } if (i > 0) return (driver->name); else return (NULL); } // // 'papplSystemSetAdminGroup()' - Set the administrative group. // // This function sets the group name used for administrative requests such as // adding or deleting a printer. // // > Note: The administrative group is only used when the PAM authorization // > service is also set when the system is created. // void papplSystemSetAdminGroup( pappl_system_t *system, // I - System const char *value) // I - Admin group { if (system) { pthread_rwlock_wrlock(&system->rwlock); free(system->admin_group); system->admin_group = value ? strdup(value) : NULL; if (system->admin_group && strcmp(system->admin_group, "none")) { char buffer[8192]; // Buffer for strings struct group grpbuf, // Group buffer *grp = NULL; // Admin group if (getgrnam_r(system->admin_group, &grpbuf, buffer, sizeof(buffer), &grp) || !grp) papplLog(system, PAPPL_LOGLEVEL_ERROR, "Unable to find admin group '%s'.", system->admin_group); else system->admin_gid = grp->gr_gid; } else system->admin_gid = (gid_t)-1; system->config_time = time(NULL); system->config_changes ++; pthread_rwlock_unlock(&system->rwlock); } } // // 'papplSystemSetContact()' - Set the "system-contact" value. // // This function sets the system contact value. // void papplSystemSetContact( pappl_system_t *system, // I - System pappl_contact_t *contact) // I - Contact { if (!system || !contact) return; pthread_rwlock_wrlock(&system->rwlock); system->contact = *contact; system->config_time = time(NULL); system->config_changes ++; pthread_rwlock_unlock(&system->rwlock); } // // 'papplSystemSetDefaultPrinterID()' - Set the "default-printer-id" value. // // This function sets the default printer using its unique positive integer // identifier. // void papplSystemSetDefaultPrinterID( pappl_system_t *system, // I - System int default_printer_id) // I - "default-printer-id" value { if (system) { pthread_rwlock_wrlock(&system->rwlock); system->default_printer_id = default_printer_id; system->config_time = time(NULL); system->config_changes ++; pthread_rwlock_unlock(&system->rwlock); } } // // 'papplSystemSetDefaultPrintGroup()' - Set the default print group. // // This function sets the default group name used for print requests. // // > Note: The default print group is only used when the PAM authorization // > service is also set when the system is created. // void papplSystemSetDefaultPrintGroup( pappl_system_t *system, // I - System const char *value) // I - Default print group or `NULL` for none { if (system) { pthread_rwlock_wrlock(&system->rwlock); free(system->default_print_group); system->default_print_group = value ? strdup(value) : NULL; system->config_time = time(NULL); system->config_changes ++; pthread_rwlock_unlock(&system->rwlock); } } // // 'papplSystemSetDNSSDName()' - Set the DNS-SD service name. // // This function sets the DNS-SD service name of the system. If `NULL`, the // DNS-SD registration is removed. // void papplSystemSetDNSSDName( pappl_system_t *system, // I - System const char *value) // I - DNS-SD service name or `NULL` for none { if (system) { pthread_rwlock_wrlock(&system->rwlock); free(system->dns_sd_name); system->dns_sd_name = value ? strdup(value) : NULL; system->dns_sd_collision = false; system->dns_sd_serial = 0; system->config_time = time(NULL); system->config_changes ++; if (!value) _papplSystemUnregisterDNSSDNoLock(system); else _papplSystemRegisterDNSSDNoLock(system); pthread_rwlock_unlock(&system->rwlock); } } // // 'papplSystemSetFooterHTML()' - Set the footer HTML for the web interface. // // This function sets the footer HTML for the web interface. // // > Note: The footer HTML can only be set prior to calling // > @link papplSystemRun@. // void papplSystemSetFooterHTML( pappl_system_t *system, // I - System const char *html) // I - Footer HTML or `NULL` for none { if (system && html && !system->is_running) { pthread_rwlock_wrlock(&system->rwlock); free(system->footer_html); system->footer_html = strdup(html); pthread_rwlock_unlock(&system->rwlock); } } // // 'papplSystemSetGeoLocation()' - Set the geographic location string. // // This function sets the geographic location of the system as a "geo:" URI. // If `NULL`, the location is cleared. // void papplSystemSetGeoLocation( pappl_system_t *system, // I - System const char *value) // I - "geo:" URI or `NULL` for none { if (system) { pthread_rwlock_wrlock(&system->rwlock); free(system->geo_location); system->geo_location = value ? strdup(value) : NULL; system->config_time = time(NULL); system->config_changes ++; _papplSystemRegisterDNSSDNoLock(system); pthread_rwlock_unlock(&system->rwlock); } } // // 'papplSystemSetHostname()' - Set the system hostname. // // This function sets the system hostname. If `NULL`, the default hostname // is used. // void papplSystemSetHostname( pappl_system_t *system, // I - System const char *value) // I - Hostname or `NULL` for default { if (system) { pthread_rwlock_wrlock(&system->rwlock); free(system->hostname); if (value) { #if !defined(__APPLE__) && !_WIN32 cups_file_t *fp; // Hostname file if ((fp = cupsFileOpen("/etc/hostname", "w")) != NULL) { cupsFilePrintf(fp, "%s\n", value); cupsFileClose(fp); } #endif // !__APPLE__ && !_WIN32 #ifdef HAVE_AVAHI _pappl_dns_sd_t master = _papplDNSSDInit(system); // DNS-SD master reference avahi_client_set_host_name(master, value); #endif // HAVE_AVAHI sethostname(value, (int)strlen(value)); system->hostname = strdup(value); } else { char temp[1024], // Temporary hostname string *ptr; // Pointer in temporary hostname #ifdef HAVE_AVAHI _pappl_dns_sd_t master = _papplDNSSDInit(system); // DNS-SD master reference const char *avahi_name = avahi_client_get_host_name_fqdn(master); // mDNS hostname if (avahi_name) strlcpy(temp, avahi_name, sizeof(temp)); else #endif /* HAVE_AVAHI */ httpGetHostname(NULL, temp, sizeof(temp)); if ((ptr = strstr(temp, ".lan")) != NULL && !ptr[4]) { // Replace hostname.lan with hostname.local strlcpy(ptr, ".local", sizeof(temp) - (size_t)(ptr - temp)); } else if (!strrchr(temp, '.')) { // No domain information, so append .local to hostname... ptr = temp + strlen(temp); strlcpy(ptr, ".local", sizeof(temp) - (size_t)(ptr - temp)); } system->hostname = strdup(temp); } // Force an update of all DNS-SD registrations... system->dns_sd_host_changes = -1; pthread_rwlock_unlock(&system->rwlock); } } // // 'papplSystemSetLocation()' - Set the system location string, if any. // // This function sets the human-readable location of the system. If `NULL`, // the location is cleared. // void papplSystemSetLocation( pappl_system_t *system, // I - System const char *value) // I - Location or `NULL` for none { if (system) { pthread_rwlock_wrlock(&system->rwlock); free(system->location); system->location = value ? strdup(value) : NULL; system->config_time = time(NULL); system->config_changes ++; _papplSystemRegisterDNSSDNoLock(system); pthread_rwlock_unlock(&system->rwlock); } } // // 'papplSystemSetLogLevel()' - Set the system log level // // This function sets the log level as an enumeration. // void papplSystemSetLogLevel( pappl_system_t *system, // I - System pappl_loglevel_t loglevel) // I - Log Level { if (system) { pthread_rwlock_wrlock(&system->rwlock); system->loglevel = loglevel; system->config_time = time(NULL); system->config_changes ++; pthread_rwlock_unlock(&system->rwlock); } } // // 'papplSystemSetMaxLogSize()' - Set the maximum log file size in bytes. // // This function sets the maximum log file size in bytes, which is only used // when logging directly to a file. When the limit is reached, the current log // file is renamed to "filename.O" and a new log file is created. Set the // maximum size to `0` to disable log file rotation. // // The default maximum log file size is 1MiB or `1048576` bytes. // void papplSystemSetMaxLogSize( pappl_system_t *system, // I - System size_t maxsize) // I - Maximum log size in bytes or `0` for none { if (system) { pthread_rwlock_wrlock(&system->rwlock); system->logmaxsize = maxsize; system->config_time = time(NULL); system->config_changes ++; pthread_rwlock_unlock(&system->rwlock); } } // // 'papplSystemSetMIMECallback()' - Set the MIME typing callback for the system. // // This function sets a custom MIME typing callback for the system. The MIME // typing callback extends the built-in MIME typing support for other media // types that are supported by the application, typically vendor print formats. // // The callback function receives a buffer containing the initial bytes of the // document data, the length of the buffer, and the callback data. It can then // return `NULL` if the content is not recognized or a constant string // containing the MIME media type, for example "application/vnd.hp-pcl" for // HP PCL print data. // void papplSystemSetMIMECallback( pappl_system_t *system, // I - System pappl_mime_cb_t cb, // I - Callback function void *data) // I - Callback data { if (system) { pthread_rwlock_wrlock(&system->rwlock); system->config_time = time(NULL); system->mime_cb = cb; system->mime_cbdata = data; pthread_rwlock_unlock(&system->rwlock); } } // // 'papplSystemSetNextPrinterID()' - Set the next "printer-id" value. // // This function sets the unique positive integer identifier that will be used // for the next printer that is created. It is typically only called as part // of restoring the state of a system. // // > Note: The next printer ID can only be set prior to calling // > @link papplSystemRun@. // void papplSystemSetNextPrinterID( pappl_system_t *system, // I - System int next_printer_id) // I - Next "printer-id" value { if (system && !system->is_running) { pthread_rwlock_wrlock(&system->rwlock); system->next_printer_id = next_printer_id; system->config_time = time(NULL); system->config_changes ++; pthread_rwlock_unlock(&system->rwlock); } } // // 'papplSystemSetOperationCallback()' - Set the IPP operation callback. // // This function sets a custom IPP operation handler for the system that is // called for any IPP operations that are not handled by the built-in IPP // services. // // > Note: The operation callback can only be set prior to calling // > @link papplSystemRun@. // void papplSystemSetOperationCallback( pappl_system_t *system, // I - System pappl_ipp_op_cb_t cb, // I - Callback function void *data) // I - Callback data { if (system && !system->is_running) { pthread_rwlock_wrlock(&system->rwlock); system->op_cb = cb; system->op_cbdata = data; pthread_rwlock_unlock(&system->rwlock); } } // // 'papplSystemSetOrganization()' - Set the system organization string, if any. // // This function sets the organization name for the system. If `NULL`, the // name is cleared. // void papplSystemSetOrganization( pappl_system_t *system, // I - System const char *value) // I - Organization or `NULL` for none { if (system) { pthread_rwlock_wrlock(&system->rwlock); free(system->organization); system->organization = value ? strdup(value) : NULL; system->config_time = time(NULL); system->config_changes ++; pthread_rwlock_unlock(&system->rwlock); } } // // 'papplSystemSetOrganizationalUnit()' - Set the system organizational unit // string, if any. // // This function sets the organizational unit name for the system. If `NULL`, // the name is cleared. // void papplSystemSetOrganizationalUnit( pappl_system_t *system, // I - System const char *value) // I - Organizational unit or `NULL` for none { if (system) { pthread_rwlock_wrlock(&system->rwlock); free(system->org_unit); system->org_unit = value ? strdup(value) : NULL; system->config_time = time(NULL); system->config_changes ++; pthread_rwlock_unlock(&system->rwlock); } } // // 'papplSystemSetPassword()' - Set the access password hash string. // // This function sets the hash for the web access password. The hash string is // generated using the @link papplSystemHashPassword@ function. // // > Note: The access password is only used when the PAM authentication service // > is not set. // void papplSystemSetPassword( pappl_system_t *system, // I - System const char *hash) // I - Hash string { if (system && hash) { pthread_rwlock_wrlock(&system->rwlock); strlcpy(system->password_hash, hash, sizeof(system->password_hash)); system->config_time = time(NULL); system->config_changes ++; pthread_rwlock_unlock(&system->rwlock); } } // // 'papplSystemSetPrinterDrivers()' - Set the list of drivers and the driver // callbacks. // // This function sets the lists of printer drivers, the optional auto-add // callback function, the optional creation callback, and the required driver // initialization callback function. // // The auto-add callback ("autoadd_cb") finds a compatible driver name for the // specified printer. It is used when the client or user specifies the "auto" // driver name, and for the "autoadd" sub-command for the `papplMainloop` API. // // The creation callback ("create_cb") is called at the end of printer creation // to make any common changes or additions to a new printer. It is typically // used to add extra web pages, add per-printer static resources, and/or // initialize the contact and location information. // // The driver initialization callback ("driver_cb") is called to initialize the // `pappl_pr_driver_data_t` structure, which provides all of the printer // capabilities and callbacks for printing. // void papplSystemSetPrinterDrivers( pappl_system_t *system, // I - System int num_drivers, // I - Number of drivers pappl_pr_driver_t *drivers, // I - Drivers pappl_pr_autoadd_cb_t autoadd_cb, // I - Auto-add callback function or `NULL` if none pappl_pr_create_cb_t create_cb, // I - Printer creation callback function or `NULL` if none pappl_pr_driver_cb_t driver_cb, // I - Driver initialization callback function void *data) // I - Callback data { if (system) { pthread_rwlock_wrlock(&system->rwlock); system->config_time = time(NULL); system->num_drivers = num_drivers; system->drivers = drivers; system->autoadd_cb = autoadd_cb; system->create_cb = create_cb; system->driver_cb = driver_cb; system->driver_cbdata = data; pthread_rwlock_unlock(&system->rwlock); } } // // 'papplSystemSetSaveCallback()' - Set the save callback. // // This function sets a callback that is used to periodically save the current // system state. Typically the callback function ("cb") is // @link papplSystemSaveState@ and the callback data ("data") is the name of // the state file: // // ``` // |papplSystemSetSaveCallback(system, (pappl_save_cb_t)papplSystemSaveState, // | (void *)filename); // ``` // // > Note: The save callback can only be set prior to calling // > @link papplSystemRun@. // void papplSystemSetSaveCallback( pappl_system_t *system, // I - System pappl_save_cb_t cb, // I - Callback function void *data) // I - Callback data { if (system && !system->is_running) { pthread_rwlock_wrlock(&system->rwlock); system->save_cb = cb; system->save_cbdata = data; pthread_rwlock_unlock(&system->rwlock); } } // // 'papplSystemSetUUID()' - Set the system UUID. // // This function sets the system UUID value, overridding the default (generated) // value. It is typically used when restoring the state of a previous // incarnation of the system. // // > Note: The UUID can only be set prior to calling @link papplSystemRun@. // void papplSystemSetUUID( pappl_system_t *system, // I - System const char *value) // I - UUID { if (system && !system->is_running) { pthread_rwlock_wrlock(&system->rwlock); free(system->uuid); if (value) { system->uuid = strdup(value); } else { char uuid[64]; // UUID value _papplSystemMakeUUID(system, NULL, 0, uuid, sizeof(uuid)); system->uuid = strdup(uuid); } _papplSystemRegisterDNSSDNoLock(system); pthread_rwlock_unlock(&system->rwlock); } } // // 'papplSystemSetVersions()' - Set the firmware names and versions. // // This function sets the names and versions of each firmware/software component // of the printer application. // void papplSystemSetVersions( pappl_system_t *system, // I - System int num_versions, // I - Number of versions pappl_version_t *versions) // I - Firmware versions { if (system && num_versions && versions) { pthread_rwlock_wrlock(&system->rwlock); if (num_versions > (int)(sizeof(system->versions) / sizeof(system->versions[0]))) system->num_versions = (int)(sizeof(system->versions) / sizeof(system->versions[0])); else system->num_versions = num_versions; memcpy(system->versions, versions, (size_t)system->num_versions * sizeof(pappl_version_t)); pthread_rwlock_unlock(&system->rwlock); } } // // 'add_listeners()' - Create and add listener sockets to a system. // static bool // O - `true` on success or `false` on failure add_listeners( pappl_system_t *system, // I - System const char *name, // I - Host name or `NULL` for any address int port, // I - Port number int family) // I - Address family { bool ret = false; // Return value int sock; // Listener socket http_addrlist_t *addrlist, // Listen addresses *addr; // Current address char service[255]; // Service port if (name && (!strcmp(name, "*") || !*name)) name = NULL; snprintf(service, sizeof(service), "%d", port); if ((addrlist = httpAddrGetList(name, family, service)) == NULL) { if (name && *name == '/') papplLog(system, PAPPL_LOGLEVEL_INFO, "Unable to lookup address(es) for '%s': %s", name, cupsLastErrorString()); else papplLog(system, PAPPL_LOGLEVEL_INFO, "Unable to lookup address(es) for '%s:%d': %s", name ? name : "*", port, cupsLastErrorString()); } else { for (addr = addrlist; addr && system->num_listeners < _PAPPL_MAX_LISTENERS; addr = addr->next) { if ((sock = httpAddrListen(&(addrlist->addr), port)) < 0) { char temp[256]; // String address if (system->port) { if (name && *name == '/') papplLog(system, PAPPL_LOGLEVEL_ERROR, "Unable to create listener socket for '%s': %s", name, cupsLastErrorString()); else papplLog(system, PAPPL_LOGLEVEL_ERROR, "Unable to create listener socket for '%s:%d': %s", httpAddrString(&addr->addr, temp, (int)sizeof(temp)), system->port, cupsLastErrorString()); } } else { ret = true; system->listeners[system->num_listeners].fd = sock; system->listeners[system->num_listeners ++].events = POLLIN; if (name && *name == '/') papplLog(system, PAPPL_LOGLEVEL_INFO, "Listening for connections on '%s'.", name); else papplLog(system, PAPPL_LOGLEVEL_INFO, "Listening for connections on '%s:%d'.", name ? name : "*", port); } } httpAddrFreeList(addrlist); } return (ret); } // // 'compare_filters()' - Compare two filters. // static int // O - Result of comparison compare_filters(_pappl_mime_filter_t *a,// I - First filter _pappl_mime_filter_t *b)// I - Second filter { int result = strcmp(a->src, b->src); if (!result) result = strcmp(a->dst, b->dst); return (result); } // // 'copy_filter()' - Copy a filter definition. // static _pappl_mime_filter_t * // O - New filter copy_filter(_pappl_mime_filter_t *f) // I - Filter definition { _pappl_mime_filter_t *newf = calloc(1, sizeof(_pappl_mime_filter_t)); // New filter if (newf) memcpy(newf, f, sizeof(_pappl_mime_filter_t)); return (newf); }
OdyX/pappl
pappl/job.h
<gh_stars>1-10 // // Public job header file for the Printer Application Framework // // Copyright © 2019-2020 by <NAME>. // // Licensed under Apache License v2.0. See the file "LICENSE" for more // information. // #ifndef _PAPPL_JOB_H_ # define _PAPPL_JOB_H_ // // Include necessary headers... // # include "base.h" // // C++ magic... // # ifdef __cplusplus extern "C" { # endif // __cplusplus // // Constants... // enum pappl_jreason_e // IPP "job-state-reasons" bit values { PAPPL_JREASON_NONE = 0x00000000, // 'none' PAPPL_JREASON_ABORTED_BY_SYSTEM = 0x00000001, // 'aborted-by-system' PAPPL_JREASON_COMPRESSION_ERROR = 0x00000002, // 'compression-error' PAPPL_JREASON_DOCUMENT_FORMAT_ERROR = 0x00000004, // 'document-format-error' PAPPL_JREASON_DOCUMENT_PASSWORD_ERROR = 0x00000008, // 'document-password-error' PAPPL_JREASON_DOCUMENT_PERMISSION_ERROR = 0x00000010, // 'document-permission-error' PAPPL_JREASON_DOCUMENT_UNPRINTABLE_ERROR = 0x00000020,// 'document-unprintable-error' PAPPL_JREASON_ERRORS_DETECTED = 0x00000040, // 'errors-detected' PAPPL_JREASON_JOB_CANCELED_AT_DEVICE = 0x00000080, // 'job-canceled-at-device' PAPPL_JREASON_JOB_CANCELED_BY_USER = 0x00000100, // 'job-canceled-by-user' PAPPL_JREASON_JOB_COMPLETED_SUCCESSFULLY = 0x00000200,// 'job-completed-successfully' PAPPL_JREASON_JOB_COMPLETED_WITH_ERRORS = 0x00000400, // 'job-completed-with-errors' PAPPL_JREASON_JOB_COMPLETED_WITH_WARNINGS = 0x00000800,// 'job-completed-with-warnings' PAPPL_JREASON_JOB_DATA_INSUFFICIENT = 0x00001000, // 'job-data-insufficient' PAPPL_JREASON_JOB_INCOMING = 0x000002000, // 'job-incoming' PAPPL_JREASON_JOB_PRINTING = 0x00004000, // 'job-printing' PAPPL_JREASON_JOB_QUEUED = 0x00008000, // 'job-queued' PAPPL_JREASON_JOB_SPOOLING = 0x00010000, // 'job-spooling' PAPPL_JREASON_PRINTER_STOPPED = 0x00020000, // 'printer-stopped' PAPPL_JREASON_PRINTER_STOPPED_PARTLY = 0x00040000, // 'printer-stopped-partly' PAPPL_JREASON_PROCESSING_TO_STOP_POINT = 0x00080000, // 'processing-to-stop-point' PAPPL_JREASON_QUEUED_IN_DEVICE = 0x00100000, // 'queued-in-device' PAPPL_JREASON_WARNINGS_DETECTED = 0x00200000 // 'warnings-detected' }; typedef unsigned int pappl_jreason_t; // Bitfield for IPP "job-state-reasons" values // // Functions... // extern void papplJobCancel(pappl_job_t *job) _PAPPL_PUBLIC; extern pappl_pr_options_t *papplJobCreatePrintOptions(pappl_job_t *job, unsigned num_pages, bool color) _PAPPL_PUBLIC; extern void papplJobDeletePrintOptions(pappl_pr_options_t *options); extern bool papplJobFilterImage(pappl_job_t *job, pappl_device_t *device, pappl_pr_options_t *options, const unsigned char *pixels, int width, int height, int depth, int ppi, bool smoothing) _PAPPL_PUBLIC; extern ipp_attribute_t *papplJobGetAttribute(pappl_job_t *job, const char *name) _PAPPL_PUBLIC; extern void *papplJobGetData(pappl_job_t *job) _PAPPL_PUBLIC; extern const char *papplJobGetFilename(pappl_job_t *job) _PAPPL_PUBLIC; extern const char *papplJobGetFormat(pappl_job_t *job) _PAPPL_PUBLIC; extern int papplJobGetID(pappl_job_t *job) _PAPPL_PUBLIC; extern int papplJobGetImpressions(pappl_job_t *job) _PAPPL_PUBLIC; extern int papplJobGetImpressionsCompleted(pappl_job_t *job) _PAPPL_PUBLIC; extern const char *papplJobGetMessage(pappl_job_t *job) _PAPPL_PUBLIC; extern const char *papplJobGetName(pappl_job_t *job) _PAPPL_PUBLIC; extern pappl_printer_t *papplJobGetPrinter(pappl_job_t *job) _PAPPL_PUBLIC; extern pappl_jreason_t papplJobGetReasons(pappl_job_t *job) _PAPPL_PUBLIC; extern ipp_jstate_t papplJobGetState(pappl_job_t *job) _PAPPL_PUBLIC; extern time_t papplJobGetTimeCompleted(pappl_job_t *job) _PAPPL_PUBLIC; extern time_t papplJobGetTimeCreated(pappl_job_t *job) _PAPPL_PUBLIC; extern time_t papplJobGetTimeProcessed(pappl_job_t *job) _PAPPL_PUBLIC; extern const char *papplJobGetUsername(pappl_job_t *job) _PAPPL_PUBLIC; extern bool papplJobIsCanceled(pappl_job_t *job) _PAPPL_PUBLIC; extern int papplJobOpenFile(pappl_job_t *job, char *fname, size_t fnamesize, const char *directory, const char *ext, const char *mode) _PAPPL_PUBLIC; extern void papplJobSetData(pappl_job_t *job, void *data) _PAPPL_PUBLIC; extern void papplJobSetImpressions(pappl_job_t *job, int impressions) _PAPPL_PUBLIC; extern void papplJobSetImpressionsCompleted(pappl_job_t *job, int add) _PAPPL_PUBLIC; extern void papplJobSetMessage(pappl_job_t *job, const char *message, ...) _PAPPL_PUBLIC _PAPPL_FORMAT(2,3); extern void papplJobSetReasons(pappl_job_t *job, pappl_jreason_t add, pappl_jreason_t remove) _PAPPL_PUBLIC; // // C++ magic... // # ifdef __cplusplus } # endif // __cplusplus #endif // !_PAPPL_JOB_H_
OdyX/pappl
pappl/log.c
<reponame>OdyX/pappl // // Logging functions for the Printer Application Framework // // Copyright © 2019-2020 by <NAME>. // // Licensed under Apache License v2.0. See the file "LICENSE" for more // information. // // // Include necessary headers... // #include "client-private.h" #include "job-private.h" #include "log-private.h" #include "printer-private.h" #include "system-private.h" #include <stdarg.h> #include <syslog.h> // // Local functions... // static void rotate_log(pappl_system_t *system); static void write_log(pappl_system_t *system, pappl_loglevel_t level, const char *message, va_list ap); // // Local globals... // static pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER; // Log rotation mutex static const int syslevels[] = // Mapping of log levels to syslog { LOG_DEBUG | LOG_PID | LOG_LPR, LOG_INFO | LOG_PID | LOG_LPR, LOG_WARNING | LOG_PID | LOG_LPR, LOG_ERR | LOG_PID | LOG_LPR, LOG_CRIT | LOG_PID | LOG_LPR }; // // 'papplLog()' - Log a message for the system. // // This function sends a message to the system's log file. The "level" argument // specifies the urgency of the message: // // - `PAPPL_LOGLEVEL_DEBUG`: A debugging message. // - `PAPPL_LOGLEVEL_ERROR`: An error message. // - `PAPPL_LOGLEVEL_FATAL`: A fatal error message. // - `PAPPL_LOGLEVEL_INFO`: An informational message. // - `PAPPL_LOGLEVEL_WARN`: A warning message. // // The "message" argument specifies a `printf`-style format string. Values // logged using the "%c" and "%s" format specifiers are sanitized to not // contain control characters. // void papplLog(pappl_system_t *system, // I - System pappl_loglevel_t level, // I - Log level const char *message, // I - Printf-style message string ...) // I - Additional arguments as needed { va_list ap; // Pointer to arguments if (!message) return; if (!system) { if (level >= PAPPL_LOGLEVEL_WARN) { va_start(ap, message); vfprintf(stderr, message, ap); putc('\n', stderr); va_end(ap); } return; } if (level < system->loglevel) return; va_start(ap, message); if (system->logfd >= 0) write_log(system, level, message, ap); else vsyslog(syslevels[level], message, ap); va_end(ap); } // // '_papplLogAttributes()' - Log IPP attributes for a client connection. // // This function logs the IPP attributes sent or recieved on a client // connection at the `PAPPL_LOGLEVEL_DEBUG` (debug) log level. // void _papplLogAttributes( pappl_client_t *client, // I - Client const char *title, // I - Title for attributes ipp_t *ipp, // I - IPP message bool is_response) // I - `true` if a response, `false` if a request { int major, // Major version number minor; // Minor version number ipp_attribute_t *attr; // Current attribute ipp_tag_t group = IPP_TAG_ZERO; // Current group const char *name; // Name char value[1024]; // Value if (!client || !title || !ipp) return; if (client->system->loglevel > PAPPL_LOGLEVEL_DEBUG) return; major = ippGetVersion(ipp, &minor); if (is_response) papplLogClient(client, PAPPL_LOGLEVEL_DEBUG, "%s response: IPP/%d.%d request-id=%d, status-code=%s", title, major, minor, ippGetRequestId(ipp), ippErrorString(ippGetStatusCode(ipp))); else papplLogClient(client, PAPPL_LOGLEVEL_DEBUG, "%s request: IPP/%d.%d request-id=%d", title, major, minor, ippGetRequestId(ipp)); for (attr = ippFirstAttribute(ipp); attr; attr = ippNextAttribute(ipp)) { if ((name = ippGetName(attr)) == NULL) { group = IPP_TAG_ZERO; continue; } if (ippGetGroupTag(attr) != group) { group = ippGetGroupTag(attr); papplLogClient(client, PAPPL_LOGLEVEL_DEBUG, "%s %s: %s", title, is_response ? "response" : "request", ippTagString(group)); } ippAttributeString(attr, value, sizeof(value)); papplLogClient(client, PAPPL_LOGLEVEL_DEBUG, "%s %s: %s %s%s %s", title, is_response ? "response" : "request", name, ippGetCount(attr) > 1 ? "1setOf " : "", ippTagString(ippGetValueTag(attr)), value); } } // // 'papplLogClient()' - Log a message for a client. // // This function sends a client message to the system's log file. The "level" // argument specifies the urgency of the message: // // - `PAPPL_LOGLEVEL_DEBUG`: A debugging message. // - `PAPPL_LOGLEVEL_ERROR`: An error message. // - `PAPPL_LOGLEVEL_FATAL`: A fatal error message. // - `PAPPL_LOGLEVEL_INFO`: An informational message. // - `PAPPL_LOGLEVEL_WARN`: A warning message. // // The "message" argument specifies a `printf`-style format string. Values // logged using the "%c" and "%s" format specifiers are sanitized to not // contain control characters. // void papplLogClient( pappl_client_t *client, // I - Client pappl_loglevel_t level, // I - Log level const char *message, // I - Printf-style message string ...) // I - Additional arguments as needed { char cmessage[1024]; // Message with client prefix va_list ap; // Pointer to arguments if (!client || !message) return; if (level < client->system->loglevel) return; snprintf(cmessage, sizeof(cmessage), "[Client %d] %s", client->number, message); va_start(ap, message); if (client->system->logfd >= 0) write_log(client->system, level, cmessage, ap); else vsyslog(syslevels[level], cmessage, ap); va_end(ap); } // // 'papplLogDevice()' - Log a device error for the system... // // This function sends a device error message to the system's log file. // void papplLogDevice( const char *message, // I - Message void *data) // I - System { pappl_system_t *system = (pappl_system_t *)data; // System papplLog(system, PAPPL_LOGLEVEL_ERROR, "[Device] %s", message); } // // 'papplLogJob()' - Log a message for a job. // // This function sends a job message to the system's log file. The "level" // argument specifies the urgency of the message: // // - `PAPPL_LOGLEVEL_DEBUG`: A debugging message. // - `PAPPL_LOGLEVEL_ERROR`: An error message. // - `PAPPL_LOGLEVEL_FATAL`: A fatal error message. // - `PAPPL_LOGLEVEL_INFO`: An informational message. // - `PAPPL_LOGLEVEL_WARN`: A warning message. // // The "message" argument specifies a `printf`-style format string. Values // logged using the "%c" and "%s" format specifiers are sanitized to not // contain control characters. // void papplLogJob( pappl_job_t *job, // I - Job pappl_loglevel_t level, // I - Log level const char *message, // I - Printf-style message string ...) // I - Additional arguments as needed { char jmessage[1024]; // Message with job prefix va_list ap; // Pointer to arguments if (!job || !message) return; if (level < job->system->loglevel) return; snprintf(jmessage, sizeof(jmessage), "[Job %d] %s", job->job_id, message); va_start(ap, message); if (job->system->logfd >= 0) write_log(job->system, level, jmessage, ap); else vsyslog(syslevels[level], jmessage, ap); va_end(ap); } // // '_papplLogOpen()' - Open the log file // void _papplLogOpen( pappl_system_t *system) // I - System { // Open the log file... if (!strcmp(system->logfile, "syslog")) { // Log to syslog... system->logfd = -1; } else if (!strcmp(system->logfile, "-")) { // Log to stderr... system->logfd = 2; } else { int oldfd = system->logfd; // Old log file descriptor // Log to a file... if ((system->logfd = open(system->logfile, O_CREAT | O_WRONLY | O_APPEND | O_NOFOLLOW | O_CLOEXEC, 0600)) < 0) { // Fallback to logging to stderr if we can't open the log file... perror(system->logfile); system->logfd = 2; } // Close any old file... if (oldfd != -1) close(oldfd); } // Log the system status information papplLog(system, PAPPL_LOGLEVEL_INFO, "Starting log, system up %ld second(s), %d printer(s), listening for connections on '%s:%d'.", (long)(time(NULL) - system->start_time), cupsArrayCount(system->printers), system->hostname, system->port); } // // 'papplLogPrinter()' - Log a message for a printer. // // This function sends a printer message to the system's log file. The "level" // argument specifies the urgency of the message: // // - `PAPPL_LOGLEVEL_DEBUG`: A debugging message. // - `PAPPL_LOGLEVEL_ERROR`: An error message. // - `PAPPL_LOGLEVEL_FATAL`: A fatal error message. // - `PAPPL_LOGLEVEL_INFO`: An informational message. // - `PAPPL_LOGLEVEL_WARN`: A warning message. // // The "message" argument specifies a `printf`-style format string. Values // logged using the "%c" and "%s" format specifiers are sanitized to not // contain control characters. // void papplLogPrinter( pappl_printer_t *printer, // I - Printer pappl_loglevel_t level, // I - Log level const char *message, // I - Printf-style message string ...) // I - Additional arguments as needed { char pmessage[1024], // Message with printer prefix *pptr, // Pointer into prefix *nameptr; // Pointer into printer name va_list ap; // Pointer to arguments if (!printer || !message) return; if (level < printer->system->loglevel) return; // Prefix the message with "[Printer foo]", making sure to not insert any // printf format specifiers. strlcpy(pmessage, "[Printer ", sizeof(pmessage)); for (pptr = pmessage + 9, nameptr = printer->name; *nameptr && pptr < (pmessage + 200); pptr ++) { if (*nameptr == '%') *pptr++ = '%'; *pptr = *nameptr++; } *pptr++ = ']'; *pptr++ = ' '; strlcpy(pptr, message, sizeof(pmessage) - (size_t)(pptr - pmessage)); // Write the log message... va_start(ap, message); if (printer->system->logfd >= 0) write_log(printer->system, level, pmessage, ap); else vsyslog(syslevels[level], pmessage, ap); va_end(ap); } // // 'rotate_log()' - Rotate the log file... // static void rotate_log(pappl_system_t *system) // I - System { struct stat loginfo; // Lof file information // Re-check whether we need to rotate the log file... if (!fstat(system->logfd, &loginfo) && loginfo.st_size >= (off_t)system->logmaxsize) { // Rename existing log file to "xxx.O" char backname[1024]; // Backup log filename snprintf(backname, sizeof(backname), "%s.O", system->logfile); unlink(backname); rename(system->logfile, backname); _papplLogOpen(system); } } // // 'write_log()' - Write a line to the log file... // static void write_log(pappl_system_t *system, // I - System pappl_loglevel_t level, // I - Log level const char *message, // I - Printf-style message string va_list ap) // I - Pointer to additional arguments { struct stat loginfo; // Log file information char buffer[2048], // Output buffer *bufptr, // Pointer into buffer *bufend; // Pointer to end of buffer struct timeval curtime; // Current time struct tm curdate; // Current date static const char *prefix = "DIWEF"; // Message prefix const char *sval; // String value char size, // Size character (h, l, L) type; // Format type character int width, // Width of field prec; // Number of characters of precision char tformat[100], // Temporary format string for sprintf() *tptr; // Pointer into temporary format // Rotate log as needed... if (system->logmaxsize > 0 && !fstat(system->logfd, &loginfo) && loginfo.st_size >= (off_t)system->logmaxsize) { pthread_mutex_lock(&log_mutex); rotate_log(system); pthread_mutex_unlock(&log_mutex); } // Each log line starts with a standard prefix of log level and date/time... gettimeofday(&curtime, NULL); gmtime_r(&curtime.tv_sec, &curdate); snprintf(buffer, sizeof(buffer), "%c [%04d-%02d-%02dT%02d:%02d:%02d.%03dZ] ", prefix[level], curdate.tm_year + 1900, curdate.tm_mon + 1, curdate.tm_mday, curdate.tm_hour, curdate.tm_min, curdate.tm_sec, (int)(curtime.tv_usec / 1000)); bufptr = buffer + 29; // Skip level/date/time bufend = buffer + sizeof(buffer) - 1; // Leave room for newline on end // Then format the message line using printf format sequences... while (*message && bufptr < bufend) { if (*message == '%') { tptr = tformat; *tptr++ = *message++; if (*message == '%') { *bufptr++ = *message++; continue; } else if (strchr(" -+#\'", *message)) *tptr++ = *message++; if (*message == '*') { // Get width from argument... message ++; width = va_arg(ap, int); snprintf(tptr, sizeof(tformat) - (size_t)(tptr - tformat), "%d", width); tptr += strlen(tptr); } else { width = 0; while (isdigit(*message & 255)) { if (tptr < (tformat + sizeof(tformat) - 1)) *tptr++ = *message; width = width * 10 + *message++ - '0'; } } if (*message == '.') { if (tptr < (tformat + sizeof(tformat) - 1)) *tptr++ = *message; message ++; if (*message == '*') { // Get precision from argument... message ++; prec = va_arg(ap, int); snprintf(tptr, sizeof(tformat) - (size_t)(tptr - tformat), "%d", prec); tptr += strlen(tptr); } else { prec = 0; while (isdigit(*message & 255)) { if (tptr < (tformat + sizeof(tformat) - 1)) *tptr++ = *message; prec = prec * 10 + *message++ - '0'; } } } if (*message == 'l' && message[1] == 'l') { size = 'L'; if (tptr < (tformat + sizeof(tformat) - 2)) { *tptr++ = 'l'; *tptr++ = 'l'; } message += 2; } else if (*message == 'h' || *message == 'l' || *message == 'L') { if (tptr < (tformat + sizeof(tformat) - 1)) *tptr++ = *message; size = *message++; } else size = 0; if (!*message) break; if (tptr < (tformat + sizeof(tformat) - 1)) *tptr++ = *message; type = *message++; *tptr = '\0'; switch (type) { case 'E' : // Floating point formats case 'G' : case 'e' : case 'f' : case 'g' : snprintf(bufptr, (size_t)(bufptr - bufend + 1), tformat, va_arg(ap, double)); bufptr += strlen(bufptr); break; case 'B' : // Integer formats case 'X' : case 'b' : case 'd' : case 'i' : case 'o' : case 'u' : case 'x' : # ifdef HAVE_LONG_LONG if (size == 'L') snprintf(bufptr, (size_t)(bufptr - bufend + 1), tformat, va_arg(ap, long long)); else # endif // HAVE_LONG_LONG if (size == 'l') snprintf(bufptr, (size_t)(bufptr - bufend + 1), tformat, va_arg(ap, long)); else snprintf(bufptr, (size_t)(bufptr - bufend + 1), tformat, va_arg(ap, int)); bufptr += strlen(bufptr); break; case 'p' : // Log a pointer snprintf(bufptr, (size_t)(bufptr - bufend + 1), "%p", va_arg(ap, void *)); bufptr += strlen(bufptr); break; case 'c' : // Character or character array if (width <= 1) { *bufptr++ = (char)va_arg(ap, int); } else { if ((bufend - bufptr) < width) width = (int)(bufend - bufptr); memcpy(bufptr, va_arg(ap, char *), (size_t)width); bufptr += width; } break; case 's' : // Log a string if ((sval = va_arg(ap, char *)) == NULL) sval = "(null)"; while (*sval && bufptr < bufend) { int val = (*sval++) & 255; if (val < ' ' || val == 0x7f || val == '\\' || val == '\'' || val == '\"') { // Escape control and special characters in the string... if (bufptr > (bufend - 4)) break; *bufptr++ = '\\'; if (val == '\\') *bufptr++ = '\\'; else if (val == '\'') *bufptr++ = '\''; else if (val == '\"') *bufptr++ = '\"'; else if (val == '\n') *bufptr++ = 'n'; else if (val == '\r') *bufptr++ = 'r'; else if (val == '\t') *bufptr++ = 't'; else { // Use octal escape for other control characters... *bufptr++ = (char)('0' + (val / 64)); *bufptr++ = (char)('0' + ((val / 8) & 7)); *bufptr++ = (char)('0' + (val & 7)); } } else *bufptr++ = (char)val; } break; default : // Something else we don't support strlcpy(bufptr, tformat, (size_t)(bufptr - bufend + 1)); bufptr += strlen(bufptr); break; } } else *bufptr++ = *message++; } // Add a newline and write it out... *bufptr++ = '\n'; write(system->logfd, buffer, (size_t)(bufptr - buffer)); }
OdyX/pappl
pappl/printer.c
<reponame>OdyX/pappl // // Printer object for the Printer Application Framework // // Copyright © 2019-2021 by <NAME>. // Copyright © 2010-2019 by Apple Inc. // // Licensed under Apache License v2.0. See the file "LICENSE" for more // information. // // // Include necessary headers... // #include "pappl-private.h" // // Local functions... // static int compare_active_jobs(pappl_job_t *a, pappl_job_t *b); static int compare_all_jobs(pappl_job_t *a, pappl_job_t *b); static int compare_completed_jobs(pappl_job_t *a, pappl_job_t *b); // // 'papplPrinterCancelAllJobs()' - Cancel all jobs on the printer. // // This function cancels all jobs on the printer. If any job is currently being // printed, it will be stopped at a convenient time (usually the end of a page) // so that the printer will be left in a known state. // void papplPrinterCancelAllJobs( pappl_printer_t *printer) // I - Printer { pappl_job_t *job; // Job information // Loop through all jobs and cancel them... pthread_rwlock_wrlock(&printer->rwlock); for (job = (pappl_job_t *)cupsArrayFirst(printer->active_jobs); job; job = (pappl_job_t *)cupsArrayNext(printer->active_jobs)) { // Cancel this job... if (job->state == IPP_JSTATE_PROCESSING || (job->state == IPP_JSTATE_HELD && job->fd >= 0)) { job->is_canceled = true; } else { job->state = IPP_JSTATE_CANCELED; job->completed = time(NULL); _papplJobRemoveFile(job); cupsArrayRemove(printer->active_jobs, job); cupsArrayAdd(printer->completed_jobs, job); } } pthread_rwlock_unlock(&printer->rwlock); if (!printer->system->clean_time) printer->system->clean_time = time(NULL) + 60; } // // 'papplPrinterCreate()' - Create a new printer. // // This function creates a new printer (service) on the specified system. The // "type" argument specifies the type of service to create and must currently // be the value `PAPPL_SERVICE_TYPE_PRINT`. // // The "printer_id" argument specifies a positive integer identifier that is // unique to the system. If you specify a value of `0` a new identifier will // be assigned. // // The "driver_name" argument specifies a named driver for the printer, from // the list of drivers registered with the @link papplSystemSetPrinterDrivers@ // function. // // The "device_id" and "device_uri" arguments specify the IEEE-1284 device ID // and device URI strings for the printer. // // On error, this function sets the `errno` variable to one of the following // values: // // - `EEXIST`: A printer with the specified name already exists. // - `EINVAL`: Bad values for the arguments were specified. // - `EIO`: The driver callback failed. // - `ENOENT`: No driver callback has been set. // - `ENOMEM`: Ran out of memory. // pappl_printer_t * // O - Printer or `NULL` on error papplPrinterCreate( pappl_system_t *system, // I - System int printer_id, // I - printer-id value or `0` for new const char *printer_name, // I - Human-readable printer name const char *driver_name, // I - Driver name const char *device_id, // I - IEEE-1284 device ID const char *device_uri) // I - Device URI { pappl_printer_t *printer; // Printer char resource[1024], // Resource path *resptr, // Pointer into resource path uuid[128], // printer-uuid print_group[65];// print-group value int k_supported; // Maximum file size supported struct statfs spoolinfo; // FS info for spool directory double spoolsize; // FS size char path[256]; // Path to resource pappl_pr_driver_data_t driver_data; // Driver data ipp_t *driver_attrs; // Driver attributes static const char * const ipp_versions[] = { // ipp-versions-supported values "1.1", "2.0" }; static const int operations[] = // operations-supported values { IPP_OP_PRINT_JOB, IPP_OP_VALIDATE_JOB, IPP_OP_CREATE_JOB, IPP_OP_SEND_DOCUMENT, IPP_OP_CANCEL_JOB, IPP_OP_GET_JOB_ATTRIBUTES, IPP_OP_GET_JOBS, IPP_OP_GET_PRINTER_ATTRIBUTES, IPP_OP_PAUSE_PRINTER, IPP_OP_RESUME_PRINTER, IPP_OP_SET_PRINTER_ATTRIBUTES, IPP_OP_CANCEL_MY_JOBS, IPP_OP_CLOSE_JOB, IPP_OP_IDENTIFY_PRINTER }; static const char * const charset[] = // charset-supported values { "us-ascii", "utf-8" }; static const char * const compression[] = { // compression-supported values "deflate", "gzip", "none" }; static const char * const multiple_document_handling[] = { // multiple-document-handling-supported values "separate-documents-uncollated-copies", "separate-documents-collated-copies" }; static const int orientation_requested[] = { IPP_ORIENT_PORTRAIT, IPP_ORIENT_LANDSCAPE, IPP_ORIENT_REVERSE_LANDSCAPE, IPP_ORIENT_REVERSE_PORTRAIT, IPP_ORIENT_NONE }; static const char * const print_content_optimize[] = { // print-content-optimize-supported "auto", "graphic", "photo", "text-and-graphic", "text" }; static const int print_quality[] = // print-quality-supported { IPP_QUALITY_DRAFT, IPP_QUALITY_NORMAL, IPP_QUALITY_HIGH }; static const char * const print_scaling[] = { // print-scaling-supported "auto", "auto-fit", "fill", "fit", "none" }; static const char * const uri_security[] = { // uri-security-supported values "none", "tls" }; static const char * const which_jobs[] = { // which-jobs-supported values "completed", "not-completed", "all" }; // Range check input... if (!system || !printer_name || !driver_name || !device_uri || !strcmp(printer_name, "ipp")) { errno = EINVAL; return (NULL); } if (!system->driver_cb) { papplLog(system, PAPPL_LOGLEVEL_ERROR, "No driver callback set, unable to add printer."); errno = ENOENT; return (NULL); } // Prepare URI values for the printer attributes... if (system->options & PAPPL_SOPTIONS_MULTI_QUEUE) { snprintf(resource, sizeof(resource), "/ipp/print/%s", printer_name); for (resptr = resource + 11; *resptr; resptr ++) if ((*resptr & 255) <= ' ' || *resptr == 0x7f) *resptr = '_'; } else strlcpy(resource, "/ipp/print", sizeof(resource)); // Make sure the printer doesn't already exist... if (papplSystemFindPrinter(system, resource, 0, NULL)) { papplLog(system, PAPPL_LOGLEVEL_ERROR, "Printer '%s' already exists.", printer_name); errno = EEXIST; return (NULL); } // Allocate memory for the printer... if ((printer = calloc(1, sizeof(pappl_printer_t))) == NULL) { papplLog(system, PAPPL_LOGLEVEL_ERROR, "Unable to allocate memory for printer: %s", strerror(errno)); return (NULL); } papplLog(system, PAPPL_LOGLEVEL_INFO, "Printer '%s' at resource path '%s'.", printer_name, resource); _papplSystemMakeUUID(system, printer_name, 0, uuid, sizeof(uuid)); // Get the maximum spool size based on the size of the filesystem used for // the spool directory. If the host OS doesn't support the statfs call // or the filesystem is larger than 2TiB, always report INT_MAX. if (statfs(system->directory, &spoolinfo)) k_supported = INT_MAX; else if ((spoolsize = (double)spoolinfo.f_bsize * spoolinfo.f_blocks / 1024) > INT_MAX) k_supported = INT_MAX; else k_supported = (int)spoolsize; // Initialize printer structure and attributes... pthread_rwlock_init(&printer->rwlock, NULL); printer->system = system; printer->name = strdup(printer_name); printer->dns_sd_name = strdup(printer_name); printer->resource = strdup(resource); printer->resourcelen = strlen(resource); printer->uriname = printer->resource + 10; // Skip "/ipp/print" in resource printer->device_id = device_id ? strdup(device_id) : NULL; printer->device_uri = strdup(device_uri); printer->driver_name = strdup(driver_name); printer->attrs = ippNew(); printer->start_time = time(NULL); printer->config_time = printer->start_time; printer->state = IPP_PSTATE_IDLE; printer->state_reasons = PAPPL_PREASON_NONE; printer->state_time = printer->start_time; printer->all_jobs = cupsArrayNew3((cups_array_func_t)compare_all_jobs, NULL, NULL, 0, NULL, (cups_afree_func_t)_papplJobDelete); printer->active_jobs = cupsArrayNew((cups_array_func_t)compare_active_jobs, NULL); printer->completed_jobs = cupsArrayNew((cups_array_func_t)compare_completed_jobs, NULL); printer->next_job_id = 1; printer->max_active_jobs = (system->options & PAPPL_SOPTIONS_MULTI_QUEUE) ? 0 : 1; printer->max_completed_jobs = 100; printer->usb_vendor_id = 0x1209; // See <pid.codes> printer->usb_product_id = 0x8011; if (!printer->name || !printer->dns_sd_name || !printer->resource || (device_id && !printer->device_id) || !printer->device_uri || !printer->driver_name || !printer->attrs) { // Failed to allocate one of the required members... _papplPrinterDelete(printer); return (NULL); } if (papplSystemGetDefaultPrintGroup(system, print_group, sizeof(print_group))) papplPrinterSetPrintGroup(printer, print_group); // If the driver is "auto", figure out the proper driver name... if (!strcmp(driver_name, "auto") && system->autoadd_cb) { if ((driver_name = (system->autoadd_cb)(printer_name, device_uri, device_id, system->driver_cbdata)) == NULL) { errno = EIO; _papplPrinterDelete(printer); return (NULL); } } // Initialize driver... driver_attrs = NULL; _papplPrinterInitDriverData(&driver_data); if (!(system->driver_cb)(system, driver_name, device_uri, device_id, &driver_data, &driver_attrs, system->driver_cbdata)) { errno = EIO; _papplPrinterDelete(printer); return (NULL); } papplPrinterSetDriverData(printer, &driver_data, driver_attrs); ippDelete(driver_attrs); // Generate printer-device-id value as needed... if (!printer->device_id) { char temp_id[400], // Temporary "printer-device-id" string mfg[128], // Manufacturer name *mdl, // Model name cmd[128], // Command (format) list *ptr; // Pointer into string ipp_attribute_t *formats; // "document-format-supported" attribute int i, // Looping var count; // Number of values // Assume make and model are separated by a space... strlcpy(mfg, driver_data.make_and_model, sizeof(mfg)); if ((mdl = strchr(mfg, ' ')) != NULL) *mdl++ = '\0'; // Nul-terminate the make else mdl = mfg; // No separator, so assume the make and model are the same formats = ippFindAttribute(printer->driver_attrs, "document-format-supported", IPP_TAG_MIMETYPE); count = ippGetCount(formats); for (i = 0, ptr = cmd; i < count; i ++) { const char *format = ippGetString(formats, i, NULL); // Current MIME media type if (!strcmp(format, "application/pdf")) format = "PDF"; else if (!strcmp(format, "application/postscript")) format = "PS"; else if (!strcmp(format, "application/vnd.hp-postscript")) format = "PCL"; else if (!strcmp(format, "application/vnd.zebra-zpl")) format = "ZPL"; else if (!strcmp(format, "image/jpeg")) format = "JPEG"; else if (!strcmp(format, "image/png")) format = "PNG"; else if (!strcmp(format, "image/pwg-raster")) format = "PWG"; else if (!strcmp(format, "image/urf")) format = "URF"; else if (!strcmp(format, "text/plain")) format = "TXT"; else if (!strcmp(format, "application/octet-stream")) continue; if (ptr > cmd) snprintf(ptr, sizeof(cmd) - (size_t)(ptr - cmd), ",%s", format); else strlcpy(cmd, format, sizeof(cmd)); ptr += strlen(ptr); } *ptr = '\0'; snprintf(temp_id, sizeof(temp_id), "MFG:%s;MDL:%s;CMD:%s;", mfg, mdl, cmd); if ((printer->device_id = strdup(temp_id)) == NULL) { _papplPrinterDelete(printer); return (NULL); } } // charset-configured ippAddString(printer->attrs, IPP_TAG_PRINTER, IPP_CONST_TAG(IPP_TAG_CHARSET), "charset-configured", NULL, "utf-8"); // charset-supported ippAddStrings(printer->attrs, IPP_TAG_PRINTER, IPP_CONST_TAG(IPP_TAG_CHARSET), "charset-supported", sizeof(charset) / sizeof(charset[0]), NULL, charset); // compression-supported ippAddStrings(printer->attrs, IPP_TAG_PRINTER, IPP_CONST_TAG(IPP_TAG_KEYWORD), "compression-supported", (int)(sizeof(compression) / sizeof(compression[0])), NULL, compression); // copies-default ippAddInteger(printer->attrs, IPP_TAG_PRINTER, IPP_TAG_INTEGER, "copies-default", 1); // document-format-default ippAddString(printer->attrs, IPP_TAG_PRINTER, IPP_CONST_TAG(IPP_TAG_MIMETYPE), "document-format-default", NULL, "application/octet-stream"); // generated-natural-language-supported ippAddString(printer->attrs, IPP_TAG_PRINTER, IPP_CONST_TAG(IPP_TAG_LANGUAGE), "generated-natural-language-supported", NULL, "en"); // ipp-versions-supported ippAddStrings(printer->attrs, IPP_TAG_PRINTER, IPP_CONST_TAG(IPP_TAG_KEYWORD), "ipp-versions-supported", (int)(sizeof(ipp_versions) / sizeof(ipp_versions[0])), NULL, ipp_versions); // job-ids-supported ippAddBoolean(printer->attrs, IPP_TAG_PRINTER, "job-ids-supported", 1); // job-k-octets-supported ippAddRange(printer->attrs, IPP_TAG_PRINTER, "job-k-octets-supported", 0, k_supported); // job-priority-default ippAddInteger(printer->attrs, IPP_TAG_PRINTER, IPP_TAG_INTEGER, "job-priority-default", 50); // job-priority-supported ippAddInteger(printer->attrs, IPP_TAG_PRINTER, IPP_TAG_INTEGER, "job-priority-supported", 1); // job-sheets-default ippAddString(printer->attrs, IPP_TAG_PRINTER, IPP_CONST_TAG(IPP_TAG_NAME), "job-sheets-default", NULL, "none"); // job-sheets-supported ippAddString(printer->attrs, IPP_TAG_PRINTER, IPP_CONST_TAG(IPP_TAG_NAME), "job-sheets-supported", NULL, "none"); // job-spooling-supported ippAddString(printer->attrs, IPP_TAG_PRINTER, IPP_CONST_TAG(IPP_TAG_KEYWORD), "job-spooling-supported", NULL, printer->max_active_jobs > 1 ? "spool" : "stream"); if (_papplSystemFindMIMEFilter(system, "image/jpeg", "image/pwg-raster")) { static const char * const jpeg_features_supported[] = { // "jpeg-features-supported" values "arithmetic", "cmyk", "progressive" }; // jpeg-features-supported ippAddStrings(printer->attrs, IPP_TAG_PRINTER, IPP_CONST_TAG(IPP_TAG_KEYWORD), "jpeg-features-supported", (int)(sizeof(jpeg_features_supported) / sizeof(jpeg_features_supported[0])), NULL, jpeg_features_supported); // jpeg-k-octets-supported ippAddRange(printer->attrs, IPP_TAG_PRINTER, "jpeg-k-octets-supported", 0, k_supported); // jpeg-x-dimension-supported ippAddRange(printer->attrs, IPP_TAG_PRINTER, "jpeg-x-dimension-supported", 0, 16384); // jpeg-y-dimension-supported ippAddRange(printer->attrs, IPP_TAG_PRINTER, "jpeg-y-dimension-supported", 1, 16384); } // multiple-document-handling-supported ippAddStrings(printer->attrs, IPP_TAG_PRINTER, IPP_CONST_TAG(IPP_TAG_KEYWORD), "multiple-document-handling-supported", sizeof(multiple_document_handling) / sizeof(multiple_document_handling[0]), NULL, multiple_document_handling); // multiple-document-jobs-supported ippAddBoolean(printer->attrs, IPP_TAG_PRINTER, "multiple-document-jobs-supported", 0); // multiple-operation-time-out ippAddInteger(printer->attrs, IPP_TAG_PRINTER, IPP_TAG_INTEGER, "multiple-operation-time-out", 60); // multiple-operation-time-out-action ippAddString(printer->attrs, IPP_TAG_PRINTER, IPP_CONST_TAG(IPP_TAG_KEYWORD), "multiple-operation-time-out-action", NULL, "abort-job"); // natural-language-configured ippAddString(printer->attrs, IPP_TAG_PRINTER, IPP_CONST_TAG(IPP_TAG_LANGUAGE), "natural-language-configured", NULL, "en"); // operations-supported ippAddIntegers(printer->attrs, IPP_TAG_PRINTER, IPP_TAG_ENUM, "operations-supported", (int)(sizeof(operations) / sizeof(operations[0])), operations); // orientation-requested-supported ippAddIntegers(printer->attrs, IPP_TAG_PRINTER, IPP_TAG_ENUM, "orientation-requested-supported", (int)(sizeof(orientation_requested) / sizeof(orientation_requested[0])), orientation_requested); if (_papplSystemFindMIMEFilter(system, "application/pdf", "image/pwg-raster")) { static const char * const pdf_versions_supported[] = { // "pdf-versions-supported" values "adobe-1.3", "adobe-1.4", "adobe-1.5", "adobe-1.6", "iso-32000-1_2008" // PDF 1.7 }; // max-page-ranges-supported ippAddInteger(printer->attrs, IPP_TAG_PRINTER, IPP_TAG_INTEGER, "max-page-ranges-supported", 1); // page-ranges-supported ippAddBoolean(printer->attrs, IPP_TAG_PRINTER, "page-ranges-supported", 1); // pdf-k-octets-supported ippAddRange(printer->attrs, IPP_TAG_PRINTER, "pdf-k-octets-supported", 0, k_supported); // pdf-versions-supported ippAddStrings(printer->attrs, IPP_TAG_PRINTER, IPP_CONST_TAG(IPP_TAG_KEYWORD), "pdf-versions-supported", (int)(sizeof(pdf_versions_supported) / sizeof(pdf_versions_supported[0])), NULL, pdf_versions_supported); } // pdl-override-supported ippAddString(printer->attrs, IPP_TAG_PRINTER, IPP_CONST_TAG(IPP_TAG_KEYWORD), "pdl-override-supported", NULL, "attempted"); // print-content-optimize-supported ippAddStrings(printer->attrs, IPP_TAG_PRINTER, IPP_CONST_TAG(IPP_TAG_KEYWORD), "print-content-optimize-supported", (int)(sizeof(print_content_optimize) / sizeof(print_content_optimize[0])), NULL, print_content_optimize); // print-quality-supported ippAddIntegers(printer->attrs, IPP_TAG_PRINTER, IPP_TAG_ENUM, "print-quality-supported", (int)(sizeof(print_quality) / sizeof(print_quality[0])), print_quality); // print-scaling-supported ippAddStrings(printer->attrs, IPP_TAG_PRINTER, IPP_CONST_TAG(IPP_TAG_KEYWORD), "print-scaling-supported", (int)(sizeof(print_scaling) / sizeof(print_scaling[0])), NULL, print_scaling); // printer-device-id if (printer->device_id) ippAddString(printer->attrs, IPP_TAG_PRINTER, IPP_TAG_TEXT, "printer-device-id", NULL, printer->device_id); // printer-get-attributes-supported ippAddString(printer->attrs, IPP_TAG_PRINTER, IPP_CONST_TAG(IPP_TAG_KEYWORD), "printer-get-attributes-supported", NULL, "document-format"); // printer-id ippAddInteger(printer->attrs, IPP_TAG_PRINTER, IPP_TAG_INTEGER, "printer-id", printer_id); // printer-info ippAddString(printer->attrs, IPP_TAG_PRINTER, IPP_TAG_TEXT, "printer-info", NULL, printer_name); // printer-name ippAddString(printer->attrs, IPP_TAG_PRINTER, IPP_TAG_NAME, "printer-name", NULL, printer_name); // printer-uuid ippAddString(printer->attrs, IPP_TAG_PRINTER, IPP_TAG_URI, "printer-uuid", NULL, uuid); // uri-security-supported if (system->options & PAPPL_SOPTIONS_NO_TLS) ippAddString(printer->attrs, IPP_TAG_PRINTER, IPP_CONST_TAG(IPP_TAG_KEYWORD), "uri-security-supported", NULL, "none"); else if (papplSystemGetTLSOnly(system)) ippAddString(printer->attrs, IPP_TAG_PRINTER, IPP_CONST_TAG(IPP_TAG_KEYWORD), "uri-security-supported", NULL, "tls"); else ippAddStrings(printer->attrs, IPP_TAG_PRINTER, IPP_CONST_TAG(IPP_TAG_KEYWORD), "uri-security-supported", 2, NULL, uri_security); // which-jobs-supported ippAddStrings(printer->attrs, IPP_TAG_PRINTER, IPP_CONST_TAG(IPP_TAG_KEYWORD), "which-jobs-supported", sizeof(which_jobs) / sizeof(which_jobs[0]), NULL, which_jobs); // Add the printer to the system... _papplSystemAddPrinter(system, printer, printer_id); // Do any post-creation work... if (system->create_cb) (system->create_cb)(printer, system->driver_cbdata); // Add socket listeners... if (system->options & PAPPL_SOPTIONS_RAW_SOCKET) { if (_papplPrinterAddRawListeners(printer) && system->is_running) { pthread_t tid; // Thread ID if (pthread_create(&tid, NULL, (void *(*)(void *))_papplPrinterRunRaw, printer)) { // Unable to create client thread... papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Unable to create raw listener thread: %s", strerror(errno)); } else { // Detach the main thread from the raw thread to prevent hangs... pthread_detach(tid); } } } // Add icons... _papplSystemAddPrinterIcons(system, printer); // Add web pages, if any... if (system->options & PAPPL_SOPTIONS_WEB_INTERFACE) { snprintf(path, sizeof(path), "%s/", printer->uriname); papplSystemAddResourceCallback(system, path, "text/html", (pappl_resource_cb_t)_papplPrinterWebHome, printer); snprintf(path, sizeof(path), "%s/cancel", printer->uriname); papplSystemAddResourceCallback(system, path, "text/html", (pappl_resource_cb_t)_papplPrinterWebCancelJob, printer); snprintf(path, sizeof(path), "%s/cancelall", printer->uriname); papplSystemAddResourceCallback(system, path, "text/html", (pappl_resource_cb_t)_papplPrinterWebCancelAllJobs, printer); if (system->options & PAPPL_SOPTIONS_MULTI_QUEUE) { snprintf(path, sizeof(path), "%s/delete", printer->uriname); papplSystemAddResourceCallback(system, path, "text/html", (pappl_resource_cb_t)_papplPrinterWebDelete, printer); } snprintf(path, sizeof(path), "%s/config", printer->uriname); papplSystemAddResourceCallback(system, path, "text/html", (pappl_resource_cb_t)_papplPrinterWebConfig, printer); snprintf(path, sizeof(path), "%s/jobs", printer->uriname); papplSystemAddResourceCallback(system, path, "text/html", (pappl_resource_cb_t)_papplPrinterWebJobs, printer); snprintf(path, sizeof(path), "%s/media", printer->uriname); papplSystemAddResourceCallback(system, path, "text/html", (pappl_resource_cb_t)_papplPrinterWebMedia, printer); papplPrinterAddLink(printer, "Media", path, PAPPL_LOPTIONS_NAVIGATION | PAPPL_LOPTIONS_STATUS); snprintf(path, sizeof(path), "%s/printing", printer->uriname); papplSystemAddResourceCallback(system, path, "text/html", (pappl_resource_cb_t)_papplPrinterWebDefaults, printer); papplPrinterAddLink(printer, "Printing Defaults", path, PAPPL_LOPTIONS_NAVIGATION | PAPPL_LOPTIONS_STATUS); if (printer->driver_data.has_supplies) { snprintf(path, sizeof(path), "%s/supplies", printer->uriname); papplSystemAddResourceCallback(system, path, "text/html", (pappl_resource_cb_t)_papplPrinterWebSupplies, printer); papplPrinterAddLink(printer, "Supplies", path, PAPPL_LOPTIONS_STATUS); } } _papplSystemConfigChanged(system); // Return it! return (printer); } // // '_papplPrinterDelete()' - Free memory associated with a printer. // void _papplPrinterDelete( pappl_printer_t *printer) // I - Printer { // Remove DNS-SD registrations... _papplPrinterUnregisterDNSSDNoLock(printer); // If applicable, call the delete function... if (printer->driver_data.delete_cb) (printer->driver_data.delete_cb)(printer, &printer->driver_data); // Delete jobs... cupsArrayDelete(printer->active_jobs); cupsArrayDelete(printer->completed_jobs); cupsArrayDelete(printer->all_jobs); // Free memory... free(printer->name); free(printer->dns_sd_name); free(printer->location); free(printer->geo_location); free(printer->organization); free(printer->org_unit); free(printer->resource); free(printer->device_id); free(printer->device_uri); free(printer->driver_name); free(printer->usb_storage); ippDelete(printer->driver_attrs); ippDelete(printer->attrs); cupsArrayDelete(printer->links); free(printer); } // // 'papplPrinterDelete()' - Delete a printer. // // This function deletes a printer from a system, freeing all memory and // canceling all jobs as needed. // void papplPrinterDelete( pappl_printer_t *printer) // I - Printer { pappl_system_t *system = printer->system; // System // Remove the printer from the system object... pthread_rwlock_wrlock(&system->rwlock); cupsArrayRemove(system->printers, printer); pthread_rwlock_unlock(&system->rwlock); _papplSystemConfigChanged(system); } // // 'compare_active_jobs()' - Compare two active jobs. // static int // O - Result of comparison compare_active_jobs(pappl_job_t *a, // I - First job pappl_job_t *b) // I - Second job { return (b->job_id - a->job_id); } // // 'compare_jobs()' - Compare two jobs. // static int // O - Result of comparison compare_all_jobs(pappl_job_t *a, // I - First job pappl_job_t *b) // I - Second job { return (b->job_id - a->job_id); } // // 'compare_completed_jobs()' - Compare two completed jobs. // static int // O - Result of comparison compare_completed_jobs(pappl_job_t *a, // I - First job pappl_job_t *b) // I - Second job { return (b->job_id - a->job_id); }
OdyX/pappl
pappl/printer-accessors.c
// // Printer accessor functions for the Printer Application Framework // // Copyright © 2020-2021 by <NAME>. // // Licensed under Apache License v2.0. See the file "LICENSE" for more // information. // // // Include necessary headers... // #include "printer-private.h" #include "system-private.h" // // 'papplPrinterCloseDevice()' - Close the device associated with the printer. // // This function closes the device for a printer. The device must have been // previously opened using the @link papplPrinterOpenDevice@ function. // void papplPrinterCloseDevice( pappl_printer_t *printer) // I - Printer { if (!printer || !printer->device || !printer->device_in_use || printer->processing_job) return; pthread_rwlock_wrlock(&printer->rwlock); papplLogPrinter(printer, PAPPL_LOGLEVEL_DEBUG, "Closing device."); papplDeviceClose(printer->device); printer->device = NULL; printer->device_in_use = false; papplLogPrinter(printer, PAPPL_LOGLEVEL_DEBUG, "Device closed."); pthread_rwlock_unlock(&printer->rwlock); } // // 'papplPrinterGetContact()' - Get the "printer-contact" value. // // This function copies the current printer contact information to the buffer // pointed to by the "contact" argument. // pappl_contact_t * // O - Contact papplPrinterGetContact( pappl_printer_t *printer, // I - Printer pappl_contact_t *contact) // O - Contact { if (!printer || !contact) { if (contact) memset(contact, 0, sizeof(pappl_contact_t)); return (contact); } pthread_rwlock_rdlock(&printer->rwlock); *contact = printer->contact; pthread_rwlock_unlock(&printer->rwlock); return (contact); } // // 'papplPrinterGetDeviceID()' - Get the IEEE-1284 device ID of the printer. // // This function returns the IEEE-1284 device ID of the printer. // const char * // O - IEEE-1284 device ID string papplPrinterGetDeviceID( pappl_printer_t *printer) // I - Printer { return (printer ? printer->device_id : NULL); } // // 'papplPrinterGetDeviceURI()' - Get the URI of the device associated with the // printer. // // This function returns the device URI for the printer. // const char * // O - Device URI string papplPrinterGetDeviceURI( pappl_printer_t *printer) // I - Printer { return (printer ? printer->device_uri : "file:///dev/null"); } // // 'papplPrinterGetDNSSDName()' - Get the current DNS-SD service name. // // This function copies the current DNS-SD service name to the buffer pointed // to by the "buffer" argument. // char * // O - DNS-SD service name or `NULL` for none papplPrinterGetDNSSDName( pappl_printer_t *printer, // I - Printer char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { if (!printer || !printer->dns_sd_name || !buffer || bufsize == 0) { if (buffer) *buffer = '\0'; return (NULL); } pthread_rwlock_rdlock(&printer->rwlock); strlcpy(buffer, printer->dns_sd_name, bufsize); pthread_rwlock_unlock(&printer->rwlock); return (buffer); } // // 'papplPrinterGetGeoLocation()' - Get the current geo-location as a "geo:" // URI. // // This function copies the currently configured geographic location as a "geo:" // URI to the buffer pointed to by the "buffer" argument. // char * // O - "geo:" URI or `NULL` for unknown papplPrinterGetGeoLocation( pappl_printer_t *printer, // I - Printer char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { if (!printer || !printer->geo_location || !buffer || bufsize == 0) { if (buffer) *buffer = '\0'; return (NULL); } pthread_rwlock_rdlock(&printer->rwlock); strlcpy(buffer, printer->geo_location, bufsize); pthread_rwlock_unlock(&printer->rwlock); return (buffer); } // // 'papplPrinterGetID()' - Get the printer ID. // // This function returns the printer's unique positive integer identifier. // int // O - "printer-id" value or `0` for none papplPrinterGetID( pappl_printer_t *printer) // I - Printer { return (printer ? printer->printer_id : 0); } // // 'papplPrinterGetImpressionsCompleted()' - Get the number of impressions // (sides) that have been printed. // // This function returns the number of impressions that have been printed. An // impression is one side of an output page. // int // O - Number of printed impressions/sides papplPrinterGetImpressionsCompleted( pappl_printer_t *printer) // I - Printer { return (printer ? printer->impcompleted : 0); } // // 'papplPrinterGetLocation()' - Get the location string. // // This function copies the printer's human-readable location to the buffer // pointed to by the "buffer" argument. // char * // O - Location or `NULL` for none papplPrinterGetLocation( pappl_printer_t *printer, // I - Printer char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { if (!printer || !printer->location || !buffer || bufsize == 0) { if (buffer) *buffer = '\0'; return (NULL); } pthread_rwlock_rdlock(&printer->rwlock); strlcpy(buffer, printer->location, bufsize); pthread_rwlock_unlock(&printer->rwlock); return (buffer); } // // 'papplPrinterGetMaxActiveJobs()' - Get the maximum number of active (queued) // jobs allowed by the printer. // // This function returns the maximum number of active jobs that the printer // supports, as configured by the @link papplPrinterSetMaxActiveJobs@ function. // int // O - Maximum number of active jobs papplPrinterGetMaxActiveJobs( pappl_printer_t *printer) // I - Printer { return (printer ? printer->max_active_jobs : 0); } // // 'papplPrinterGetMaxCompletedJobs()' - Get the maximum number of jobs retained // for history by the printer. // // This function returns the maximum number of jobs that are retained in the // job history as configured by the @link papplPrinterSetMaxCompletedJobs@ // function. // int // O - Maximum number of completed jobs papplPrinterGetMaxCompletedJobs( pappl_printer_t *printer) // I - Printer { return (printer ? printer->max_completed_jobs : 0); } // // 'papplPrinterGetName()' - Get the printer name. // // This function returns the printer's human-readable name. // const char * // O - Printer name papplPrinterGetName( pappl_printer_t *printer) // I - Printer { return (printer ? printer->name : NULL); } // // 'papplPrinterGetNextJobID()' - Get the next job ID. // // This function returns the positive integer identifier that will be used for // the next job that is created. // int // O - Next job ID or `0` for none papplPrinterGetNextJobID( pappl_printer_t *printer) // I - Printer { return (printer ? printer->next_job_id : 0); } // // 'papplPrinterGetNumberOfActiveJobs()' - Get the number of active print jobs. // // This function returns the number of print jobs that are either printing or // waiting to be printed. // int // O - Number of active print jobs papplPrinterGetNumberOfActiveJobs( pappl_printer_t *printer) // I - Printer { return (printer ? cupsArrayCount(printer->active_jobs) : 0); } // // 'papplPrinterGetNumberOfCompletedJobs()' - Get the number of completed print // jobs. // // This function returns the number of print jobs that have been aborted, // canceled, or completed. // int // O - Number of completed print jobs papplPrinterGetNumberOfCompletedJobs( pappl_printer_t *printer) // I - Printer { return (printer ? cupsArrayCount(printer->completed_jobs) : 0); } // // 'papplPrinterGetNumberOfJobs()' - Get the total number of print jobs. // // This function returns the number of print jobs that are printing, waiting // to be printed, have been aborted, have been canceled, or have completed. // int // O - Total number of print jobs papplPrinterGetNumberOfJobs( pappl_printer_t *printer) // I - Printer { return (printer ? cupsArrayCount(printer->all_jobs) : 0); } // // 'papplPrinterGetOrganization()' - Get the organization name. // // This function copies the printer's organization name to the buffer pointed // to by the "buffer" argument. // char * // O - Organization name or `NULL` for none papplPrinterGetOrganization( pappl_printer_t *printer, // I - Printer char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { if (!printer || !printer->organization || !buffer || bufsize == 0) { if (buffer) *buffer = '\0'; return (NULL); } pthread_rwlock_rdlock(&printer->rwlock); strlcpy(buffer, printer->organization, bufsize); pthread_rwlock_unlock(&printer->rwlock); return (buffer); } // // 'papplPrinterGetOrganizationalUnit()' - Get the organizational unit name. // // This function copies the printer's organizational unit name to the buffer // pointed to by the "buffer" argument. // char * // O - Organizational unit name or `NULL` for none papplPrinterGetOrganizationalUnit( pappl_printer_t *printer, // I - Printer char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { if (!printer || !printer->org_unit || !buffer || bufsize == 0) { if (buffer) *buffer = '\0'; return (NULL); } pthread_rwlock_rdlock(&printer->rwlock); strlcpy(buffer, printer->org_unit, bufsize); pthread_rwlock_unlock(&printer->rwlock); return (buffer); } // // 'papplPrinterGetPath()' - Get the URL path for a printer web page. // // This function generates and returns the URL path for the printer's web page. // The "subpath" argument specifies an optional sub-path for a specific printer // web page. // char * // O - URI path or `NULL` on error papplPrinterGetPath( pappl_printer_t *printer, // I - Printer const char *subpath, // I - Sub-path or `NULL` for none char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { if (!printer || !buffer || bufsize < 32) { if (buffer) *buffer = '\0'; return (NULL); } if (subpath) snprintf(buffer, bufsize, "%s/%s", printer->uriname, subpath); else strlcpy(buffer, printer->uriname, bufsize); return (buffer); } // // 'papplPrinterGetPrintGroup()' - Get the print authorization group, if any. // // This function copies the printer's authorization group name to the buffer // pointed to by the "buffer" argument. // char * // O - Print authorization group name or `NULL` for none papplPrinterGetPrintGroup( pappl_printer_t *printer, // I - Printer char *buffer, // I - String buffer size_t bufsize) // I - Size of string buffer { if (!printer || !printer->print_group || !buffer || bufsize == 0) { if (buffer) *buffer = '\0'; return (NULL); } pthread_rwlock_rdlock(&printer->rwlock); strlcpy(buffer, printer->print_group, bufsize); pthread_rwlock_unlock(&printer->rwlock); return (buffer); } // // 'papplPrinterGetReasons()' - Get the current "printer-state-reasons" bit values. // // This function returns the current printer state reasons bitfield, which can // be updated by the printer driver and/or by the @link papplPrinterSetReasons@ // function. // pappl_preason_t // O - "printer-state-reasons" bit values papplPrinterGetReasons( pappl_printer_t *printer) // I - Printer { if (!printer) return (PAPPL_PREASON_NONE); if (!printer->device_in_use && !printer->processing_job && (time(NULL) - printer->status_time) > 1 && printer->driver_data.status_cb) { // Update printer status... (printer->driver_data.status_cb)(printer); printer->status_time = time(NULL); } return (printer->state_reasons); } // // 'papplPrinterGetState()' - Get the current "printer-state" value. // // This function returns the current printer state as an enumeration: // // - `IPP_PSTATE_IDLE`: The printer is idle and has no jobs to process. // - `IPP_PSTATE_PROCESSING`: The printer is processing a job and/or producing // output. // - `IPP_PSTATE_STOPPED`: The printer is stopped for maintenance. // ipp_pstate_t // O - "printer-state" value papplPrinterGetState( pappl_printer_t *printer) // I - Printer { return (printer ? printer->state : IPP_PSTATE_STOPPED); } // // 'papplPrinterGetSupplies()' - Get the current "printer-supplies" values. // // This function copies the current printer supply values to the specified // array. The "max_supplies" and "supplies" arguments can be `0` and `NULL` // to query the number of supplies used. // // The return value is the actual number of supplies used by the printer, // regardless of the size of the array. // int // O - Number of values papplPrinterGetSupplies( pappl_printer_t *printer, // I - Printer int max_supplies, // I - Maximum number of supplies pappl_supply_t *supplies) // I - Array for supplies { int count; // Number of supplies if (!printer || max_supplies < 0 || (max_supplies > 0 && !supplies)) return (0); if (max_supplies == 0) return (printer->num_supply); memset(supplies, 0, (size_t)max_supplies * sizeof(pappl_supply_t)); pthread_rwlock_rdlock(&printer->rwlock); if ((count = printer->num_supply) > max_supplies) count = max_supplies; memcpy(supplies, printer->supply, (size_t)count * sizeof(pappl_supply_t)); pthread_rwlock_unlock(&printer->rwlock); return (count); } // // 'papplPrinterGetSystem()' - Get the system associated with the printer. // // This function returns a pointer to the system object that contains the // printer. // pappl_system_t * // O - System papplPrinterGetSystem( pappl_printer_t *printer) // I - Printer { return (printer ? printer->system : NULL); } // // 'papplPrinterIterateActiveJobs()' - Iterate over the active jobs. // // This function iterates over jobs that are either printing or waiting to be // printed. The specified callback "cb" will be called once per job with the // data pointer "data". // // The "job_index" argument specifies the first job in the list to iterate, // where `1` is the first job, etc. The "limit" argument specifies the maximum // number of jobs to iterate - use `0` to iterate an unlimited number of jobs. // void papplPrinterIterateActiveJobs( pappl_printer_t *printer, // I - Printer pappl_job_cb_t cb, // I - Callback function void *data, // I - Callback data int job_index, // I - First job to iterate (1-based) int limit) // I - Maximum jobs to iterate or `0` for no limit { pappl_job_t *job; // Current job int count; // Number of jobs if (!printer || !cb) return; pthread_rwlock_rdlock(&printer->rwlock); for (job = (pappl_job_t *)cupsArrayIndex(printer->active_jobs, job_index - 1), count = 0; job; job = (pappl_job_t *)cupsArrayNext(printer->active_jobs), count ++) { if (limit == 0 || count < limit) (cb)(job, data); else break; } pthread_rwlock_unlock(&printer->rwlock); } // // 'papplPrinterIterateAllJobs()' - Iterate over all the jobs. // // This function iterates over all jobs. The specified callback "cb" will be // called once per job with the data pointer "data". // // The "job_index" argument specifies the first job in the list to iterate, // where `1` is the first job, etc. The "limit" argument specifies the maximum // number of jobs to iterate - use `0` to iterate an unlimited number of jobs. // void papplPrinterIterateAllJobs( pappl_printer_t *printer, // I - Printer pappl_job_cb_t cb, // I - Callback function void *data, // I - Callback data int job_index, // I - First job to iterate (1-based) int limit) // I - Maximum jobs to iterate, `0` for no limit { pappl_job_t *job; // Current job int count; // Number of jobs if (!printer || !cb) return; pthread_rwlock_rdlock(&printer->rwlock); for (job = (pappl_job_t *)cupsArrayIndex(printer->all_jobs, job_index - 1), count = 0; job; job = (pappl_job_t *)cupsArrayNext(printer->all_jobs), count ++) { if (limit == 0 || count < limit) (cb)(job, data); else break; } pthread_rwlock_unlock(&printer->rwlock); } // // 'papplPrinterIterateCompletedJobs()' - Iterate over the completed jobs. // // This function iterates over jobs that are aborted, canceled, or completed. // The specified callback "cb" will be called once per job with the data pointer // "data". // // The "job_index" argument specifies the first job in the list to iterate, // where `1` is the first job, etc. The "limit" argument specifies the maximum // number of jobs to iterate - use `0` to iterate an unlimited number of jobs. // void papplPrinterIterateCompletedJobs( pappl_printer_t *printer, // I - Printer pappl_job_cb_t cb, // I - Callback function void *data, // I - Callback data int job_index, // I - First job to iterate (1-based) int limit) // I - Maximum jobs to iterate, `0` for no limit { pappl_job_t *job; // Current job int count; // Number of jobs if (!printer || !cb) return; pthread_rwlock_rdlock(&printer->rwlock); for (job = (pappl_job_t *)cupsArrayIndex(printer->completed_jobs, job_index - 1), count = 0; job; job = (pappl_job_t *)cupsArrayNext(printer->completed_jobs), count ++) { if (limit == 0 || count < limit) (cb)(job, data); else break; } pthread_rwlock_unlock(&printer->rwlock); } // // 'papplPrinterOpenDevice()' - Open the device associated with a printer. // // This function opens the printer's device. `NULL` is returned if the device // is already in use, for example while a job is being printed. // // The returned device must be closed using the @link papplPrinterCloseDevice@ // function. // pappl_device_t * // O - Device or `NULL` if not possible papplPrinterOpenDevice( pappl_printer_t *printer) // I - Printer { pappl_device_t *device = NULL; // Open device if (!printer || printer->device_in_use || printer->processing_job || !printer->device_uri) return (NULL); pthread_rwlock_wrlock(&printer->rwlock); if (!printer->device_in_use && !printer->processing_job) { papplLogPrinter(printer, PAPPL_LOGLEVEL_DEBUG, "Opening device."); printer->device = device = papplDeviceOpen(printer->device_uri, "printer", papplLogDevice, printer->system); printer->device_in_use = device != NULL; } if (device) papplLogPrinter(printer, PAPPL_LOGLEVEL_DEBUG, "Device open."); else papplLogPrinter(printer, PAPPL_LOGLEVEL_DEBUG, "Device not open."); pthread_rwlock_unlock(&printer->rwlock); return (device); } // // 'papplPrinterPause()' - Pause (stop) a printer. // // This function pauses a printer. If the printer is currently processing // (printing) a job, it will be completed before the printer is stopped. // void papplPrinterPause( pappl_printer_t *printer) // I - Printer { if (!printer) return; pthread_rwlock_wrlock(&printer->rwlock); if (printer->processing_job) printer->is_stopped = true; else printer->state = IPP_PSTATE_STOPPED; pthread_rwlock_unlock(&printer->rwlock); } // // 'papplPrinterResume()' - Resume (start) a printer. // // This function resumes a printer and starts processing any pending jobs. // void papplPrinterResume( pappl_printer_t *printer) // I - Printer { if (!printer) return; pthread_rwlock_wrlock(&printer->rwlock); printer->is_stopped = false; printer->state = IPP_PSTATE_IDLE; pthread_rwlock_unlock(&printer->rwlock); _papplPrinterCheckJobs(printer); } // // 'papplPrinterSetContact()' - Set the "printer-contact" value. // // This function sets the printer's contact information. // void papplPrinterSetContact( pappl_printer_t *printer, // I - Printer pappl_contact_t *contact) // I - Contact { if (!printer || !contact) return; pthread_rwlock_wrlock(&printer->rwlock); printer->contact = *contact; printer->config_time = time(NULL); pthread_rwlock_unlock(&printer->rwlock); _papplSystemConfigChanged(printer->system); } // // 'papplPrinterSetDNSSDName()' - Set the DNS-SD service name. // // This function sets the printer's DNS-SD service name. If `NULL`, the printer // will stop advertising the printer. // void papplPrinterSetDNSSDName( pappl_printer_t *printer, // I - Printer const char *value) // I - DNS-SD service name or `NULL` for none { if (!printer) return; pthread_rwlock_wrlock(&printer->rwlock); free(printer->dns_sd_name); printer->dns_sd_name = value ? strdup(value) : NULL; printer->dns_sd_collision = false; printer->dns_sd_serial = 0; printer->config_time = time(NULL); if (!value) _papplPrinterUnregisterDNSSDNoLock(printer); else _papplPrinterRegisterDNSSDNoLock(printer); pthread_rwlock_unlock(&printer->rwlock); _papplSystemConfigChanged(printer->system); } // // 'papplPrinterSetGeoLocation()' - Set the geo-location value as a "geo:" URI. // // This function sets the printer's geographic location as a "geo:" URI. If // `NULL`, the location is cleared to the 'unknown' value. // void papplPrinterSetGeoLocation( pappl_printer_t *printer, // I - Printer const char *value) // I - "geo:" URI or `NULL` for unknown { if (!printer) return; pthread_rwlock_wrlock(&printer->rwlock); free(printer->geo_location); printer->geo_location = value ? strdup(value) : NULL; printer->config_time = time(NULL); _papplPrinterRegisterDNSSDNoLock(printer); pthread_rwlock_unlock(&printer->rwlock); _papplSystemConfigChanged(printer->system); } // // 'papplPrinterSetImpressionsCompleted()' - Add impressions (sides) to the // total count of printed impressions. // // This function adds to the printer's impressions counter. An impression is // one side of an output page. // void papplPrinterSetImpressionsCompleted( pappl_printer_t *printer, // I - Printer int add) // I - Number of impressions/sides to add { if (!printer || add <= 0) return; pthread_rwlock_wrlock(&printer->rwlock); printer->impcompleted += add; printer->state_time = time(NULL); pthread_rwlock_unlock(&printer->rwlock); _papplSystemConfigChanged(printer->system); } // // 'papplPrinterSetLocation()' - Set the location string. // // This function sets the printer's human-readable location string. If `NULL`, // the location is cleared. // void papplPrinterSetLocation( pappl_printer_t *printer, // I - Printer const char *value) // I - Location ("Bob's Office", etc.) or `NULL` for none { if (!printer) return; pthread_rwlock_wrlock(&printer->rwlock); free(printer->location); printer->location = value ? strdup(value) : NULL; printer->config_time = time(NULL); _papplPrinterRegisterDNSSDNoLock(printer); pthread_rwlock_unlock(&printer->rwlock); _papplSystemConfigChanged(printer->system); } // // 'papplPrinterSetMaxActiveJobs()' - Set the maximum number of active jobs for // the printer. // // This function sets the maximum number of jobs that can be spooled on the // printer at one time. // // > Note: This limit does not apply to streaming raster formats such as PWG // > Raster since they are not spooled. // void papplPrinterSetMaxActiveJobs( pappl_printer_t *printer, // I - Printer int max_active_jobs) // I - Maximum number of active jobs, `0` for unlimited { if (!printer || max_active_jobs < 0) return; pthread_rwlock_wrlock(&printer->rwlock); printer->max_active_jobs = max_active_jobs; printer->config_time = time(NULL); pthread_rwlock_unlock(&printer->rwlock); _papplSystemConfigChanged(printer->system); } // // 'papplPrinterSetMaxCompletedJobs()' - Set the maximum number of completed // jobs for the printer. // // This function sets the maximum number of aborted, canceled, or completed jobs // that are retained in the job history. // void papplPrinterSetMaxCompletedJobs( pappl_printer_t *printer, // I - Printer int max_completed_jobs) // I - Maximum number of completed jobs, `0` for unlimited { if (!printer || max_completed_jobs < 0) return; pthread_rwlock_wrlock(&printer->rwlock); printer->max_completed_jobs = max_completed_jobs; printer->config_time = time(NULL); pthread_rwlock_unlock(&printer->rwlock); _papplSystemConfigChanged(printer->system); } // // 'papplPrinterSetNextJobID()' - Set the next "job-id" value. // // This function sets the next unique positive integer identifier that will be // used for a job. // // > Note: This function is normally only called once to restore the previous // > state of the printer. // void papplPrinterSetNextJobID( pappl_printer_t *printer, // I - Printer int next_job_id) // I - Next "job-id" value { if (!printer || next_job_id < 1) return; pthread_rwlock_wrlock(&printer->rwlock); printer->next_job_id = next_job_id; printer->config_time = time(NULL); pthread_rwlock_unlock(&printer->rwlock); _papplSystemConfigChanged(printer->system); } // // 'papplPrinterSetOrganization()' - Set the organization name. // // This function sets the printer's organization name. If `NULL` the value is // cleared. // void papplPrinterSetOrganization( pappl_printer_t *printer, // I - Printer const char *value) // I - Organization name or `NULL` for none { if (!printer) return; pthread_rwlock_wrlock(&printer->rwlock); free(printer->organization); printer->organization = value ? strdup(value) : NULL; printer->config_time = time(NULL); pthread_rwlock_unlock(&printer->rwlock); _papplSystemConfigChanged(printer->system); } // // 'papplPrinterSetOrganizationalUnit()' - Set the organizational unit name. // // This function sets the printer's organizational unit name. If `NULL` the // value is cleared. // void papplPrinterSetOrganizationalUnit( pappl_printer_t *printer, // I - Printer const char *value) // I - Organizational unit name or `NULL` for none { if (!printer) return; pthread_rwlock_wrlock(&printer->rwlock); free(printer->org_unit); printer->org_unit = value ? strdup(value) : NULL; printer->config_time = time(NULL); pthread_rwlock_unlock(&printer->rwlock); _papplSystemConfigChanged(printer->system); } // // 'papplPrinterSetPrintGroup()' - Set the print authorization group, if any. // // This function sets the printer's authorization group. If `NULL`, the group // is cleared. // // > Note: The authorization group is only used if the system is created with a // > named authorization service. // void papplPrinterSetPrintGroup( pappl_printer_t *printer, // I - Printer const char *value) // I - Print authorization group or `NULL` for none { if (!printer) return; pthread_rwlock_wrlock(&printer->rwlock); free(printer->print_group); printer->print_group = value ? strdup(value) : NULL; printer->config_time = time(NULL); if (printer->print_group && strcmp(printer->print_group, "none")) { char buffer[8192]; // Buffer for strings struct group grpbuf, // Group buffer *grp = NULL; // Print group if (getgrnam_r(printer->print_group, &grpbuf, buffer, sizeof(buffer), &grp) || !grp) papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Unable to find print group '%s'.", printer->print_group); else printer->print_gid = grp->gr_gid; } else printer->print_gid = (gid_t)-1; pthread_rwlock_unlock(&printer->rwlock); _papplSystemConfigChanged(printer->system); } // // 'papplPrinterSetReasons()' - Add or remove values from // "printer-state-reasons". // // This function updates the printer state reasons bitfield by clearing any bit // values in the "remove" argument and setting any bit values in the "add" // argument. // void papplPrinterSetReasons( pappl_printer_t *printer, // I - Printer pappl_preason_t add, // I - "printer-state-reasons" bit values to add or `PAPPL_PREASON_NONE` for none pappl_preason_t remove) // I - "printer-state-reasons" bit values to remove or `PAPPL_PREASON_NONE` for none { if (!printer) return; pthread_rwlock_wrlock(&printer->rwlock); printer->state_reasons &= ~remove; printer->state_reasons |= add; printer->state_time = printer->status_time = time(NULL); pthread_rwlock_unlock(&printer->rwlock); } // // 'papplPrinterSetSupplies()' - Set/update the supplies for a printer. // // This function updates the supply information for the printer. // void papplPrinterSetSupplies( pappl_printer_t *printer, // I - Printer int num_supplies, // I - Number of supplies pappl_supply_t *supplies) // I - Array of supplies { if (!printer || num_supplies < 0 || num_supplies > PAPPL_MAX_SUPPLY || (num_supplies > 0 && !supplies)) return; pthread_rwlock_wrlock(&printer->rwlock); printer->num_supply = num_supplies; memset(printer->supply, 0, sizeof(printer->supply)); if (supplies) memcpy(printer->supply, supplies, (size_t)num_supplies * sizeof(pappl_supply_t)); printer->state_time = time(NULL); pthread_rwlock_unlock(&printer->rwlock); }
OdyX/pappl
pappl/printer-usb.c
<filename>pappl/printer-usb.c // // USB printer class support for the Printer Application Framework // // Copyright © 2019-2020 by <NAME>. // Copyright © 2010-2019 by Apple Inc. // // Licensed under Apache License v2.0. See the file "LICENSE" for more // information. // // // Include necessary headers... // #include "pappl-private.h" #include <cups/dir.h> #ifdef __linux # include <sys/ioctl.h> # include <sys/syscall.h> # include <linux/usb/g_printer.h> #endif // __linux // // Local constants... // #ifdef __linux # define LINUX_USB_CONTROLLER "/sys/class/udc" # define LINUX_USB_GADGET "/sys/kernel/config/usb_gadget/g1" #endif // __linux // // Local functions... // #ifdef __linux static void disable_usb_printer(pappl_printer_t *printer); static bool enable_usb_printer(pappl_printer_t *printer); #endif // __linux // // '_papplPrinterRunUSB() ' - Run the USB printer thread. // void * // O - Thread exit status (not used) _papplPrinterRunUSB( pappl_printer_t *printer) // I - Printer { #ifdef __linux struct pollfd data; // USB printer gadget listener int count; // Number of file descriptors from poll() pappl_device_t *device = NULL; // Printer port data char buffer[8192]; // Print data buffer ssize_t bytes; // Bytes in buffer time_t status_time = 0; // Last port status update if (!enable_usb_printer(printer)) return (NULL); if ((data.fd = open("/dev/g_printer0", O_RDWR | O_EXCL)) < 0) { papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Unable to open USB printer gadget: %s", strerror(errno)); return (NULL); } data.events = POLLIN | POLLRDNORM; papplLogPrinter(printer, PAPPL_LOGLEVEL_INFO, "Monitoring USB for incoming print jobs."); while (printer->system->is_running) { if ((count = poll(&data, 1, 1000)) < 0) { papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "USB poll failed: %s", strerror(errno)); sleep(1); } else if (count > 0) { if (!device) { papplLogPrinter(printer, PAPPL_LOGLEVEL_INFO, "Starting USB print job."); while ((device = papplPrinterOpenDevice(printer)) == NULL) { papplLogPrinter(printer, PAPPL_LOGLEVEL_DEBUG, "Waiting for USB access."); sleep(1); } // Start looking for back-channel data and port status status_time = 0; data.events = POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM; } if ((time(NULL) - status_time) >= 1) { // Update port status once a second... pappl_preason_t reasons = papplDeviceGetStatus(device); // Current USB status bits unsigned char port_status = PRINTER_NOT_ERROR | PRINTER_SELECTED; // Current port status bits if (reasons & PAPPL_PREASON_OTHER) port_status &= ~PRINTER_NOT_ERROR; if (reasons & PAPPL_PREASON_MEDIA_EMPTY) port_status |= PRINTER_PAPER_EMPTY; if (reasons & PAPPL_PREASON_MEDIA_JAM) port_status |= 0x40; // Extension if (reasons & PAPPL_PREASON_COVER_OPEN) port_status |= 0x80; // Extension ioctl(data.fd, GADGET_SET_PRINTER_STATUS, (unsigned char)port_status); status_time = time(NULL); } if (data.revents & POLLRDNORM) { if ((bytes = read(data.fd, buffer, sizeof(buffer))) > 0) { papplLogPrinter(printer, PAPPL_LOGLEVEL_DEBUG, "Read %d bytes from USB port.", (int)bytes); papplDeviceWrite(device, buffer, (size_t)bytes); papplDeviceFlush(device); } else { if (bytes < 0) papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Read error from USB port: %s", strerror(errno)); papplLogPrinter(printer, PAPPL_LOGLEVEL_INFO, "Finishing USB print job."); papplPrinterCloseDevice(printer); device = NULL; } } if (data.revents & POLLWRNORM) { if ((bytes = papplDeviceRead(device, buffer, sizeof(buffer))) > 0) { papplLogPrinter(printer, PAPPL_LOGLEVEL_DEBUG, "Read %d bytes from printer.", (int)bytes); write(data.fd, buffer, (size_t)bytes); } } } else if (device) { papplLogPrinter(printer, PAPPL_LOGLEVEL_INFO, "Finishing USB print job."); papplPrinterCloseDevice(printer); device = NULL; // Stop doing back-channel data data.events = POLLIN | POLLRDNORM; } } if (device) { papplLogPrinter(printer, PAPPL_LOGLEVEL_INFO, "Finishing USB print job."); papplPrinterCloseDevice(printer); } papplLogPrinter(printer, PAPPL_LOGLEVEL_INFO, "Disabling USB for incoming print jobs."); disable_usb_printer(printer); #else (void)printer; #endif // __linux return (NULL); } // // 'papplPrinterSetUSB()' - Set the USB vendor and product IDs for a printer. // // This function sets the USB vendor and product IDs for a printer as well as // specifying USB gadget options when the printer is registered with the USB // device controller. // // > Note: USB gadget functionality is currently only available when running // > on Linux with compatible hardware such as the Raspberry Pi. // void papplPrinterSetUSB( pappl_printer_t *printer, // I - Printer unsigned vendor_id, // I - USB vendor ID unsigned product_id, // I - USB product ID pappl_uoptions_t options, // I - USB gadget options const char *storagefile) // I - USB storage file, if any { if (printer) { printer->usb_vendor_id = (unsigned short)vendor_id; printer->usb_product_id = (unsigned short)product_id; printer->usb_options = options; free(printer->usb_storage); if (storagefile) printer->usb_storage = strdup(storagefile); else printer->usb_storage = NULL; } } #ifdef __linux // // 'disable_usb_printer()' - Disable the USB printer gadget module. // static void disable_usb_printer( pappl_printer_t *printer) // I - Printer { const char *gadget_dir = LINUX_USB_GADGET; // Gadget directory char filename[1024]; // Filename cups_file_t *fp; // File snprintf(filename, sizeof(filename), "%s/UDC", gadget_dir); if ((fp = cupsFileOpen(filename, "w")) != NULL) { cupsFilePuts(fp, "\n"); cupsFileClose(fp); } else { papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Unable to create USB gadget file '%s': %s", filename, strerror(errno)); } } // // 'enable_usb_printer()' - Configure and enable the USB printer gadget module. // static bool // O - `true` on success, `false` otherwise enable_usb_printer( pappl_printer_t *printer) // I - Printer { const char *gadget_dir = LINUX_USB_GADGET; // Gadget directory char filename[1024], // Filename destname[1024]; // Destination filename for symlinks cups_dir_t *dir; // Controller directory cups_dentry_t *dent; // Directory entry cups_file_t *fp; // File int num_devid; // Number of device ID values cups_option_t *devid; // Device ID values const char *val; // Value char mfg[256], // Manufacturer mdl[256], // Model name sn[256]; // Serial number // Get the information for this printer - vendor ID, product ID, etc. num_devid = papplDeviceParseID(printer->device_id, &devid); val = cupsGetOption("MANUFACTURER", num_devid, devid); if (!val) val = cupsGetOption("MFG", num_devid, devid); if (!val) val = cupsGetOption("MFR", num_devid, devid); if (val) strlcpy(mfg, val, sizeof(mfg)); else strlcpy(mfg, "Unknown", sizeof(mfg)); val = cupsGetOption("MODEL", num_devid, devid); if (!val) val = cupsGetOption("MDL", num_devid, devid); if (val) strlcpy(mdl, val, sizeof(mdl)); else strlcpy(mdl, "Printer", sizeof(mdl)); val = cupsGetOption("SERIALNUMBER", num_devid, devid); if (!val) val = cupsGetOption("SN", num_devid, devid); if (!val) val = cupsGetOption("SER", num_devid, devid); if (!val) val = cupsGetOption("SERN", num_devid, devid); if (!val && (val = strstr(printer->device_uri, "?serial=")) != NULL) val += 8; if (val) strlcpy(sn, val, sizeof(sn)); else strlcpy(sn, "0", sizeof(sn)); cupsFreeOptions(num_devid, devid); // Modern Linux kernels support USB gadgets through the configfs interface. // PAPPL takes control of this interface, so if you need (for example) a // serial gadget in addition to the printer gadget you need to specify that // with a call to papplPrinterSetUSB. // // The configfs interface lives under "/sys/kernel/config/usb_gadget/". The // available USB Device Controllers can be found under "/sys/class/udc". We // currently assume there will only be one of those and will expand the USB // gadget interface later as needed. // // The typical directory structure looks like this: // // g1/ // idVendor (usb_vendor ID as a hex number, e.g. "0x12CD") // idProduct (usb product ID as a hex number, e.g. "0x34AB") // strings/0x409/ // manufacturer (manufacturer name string) // product (model name string) // serialnumber (serial number string) // configs/c.1/ // symlink to functions/printer.g_printer0 // functions/printer.g_printer0 // pnp_string (IEEE-1284 device ID string) // UDC (first entry from /sys/class/udc) // Create the gadget configuration files and directories... if (mkdir(gadget_dir, 0777) && errno != EEXIST) { papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Unable to create USB gadget directory '%s': %s", gadget_dir, strerror(errno)); return (false); } snprintf(filename, sizeof(filename), "%s/idVendor", gadget_dir); if ((fp = cupsFileOpen(filename, "w")) == NULL) { papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Unable to create USB gadget file '%s': %s", filename, strerror(errno)); return (false); } cupsFilePrintf(fp, "0x%04X\n", printer->usb_vendor_id); cupsFileClose(fp); snprintf(filename, sizeof(filename), "%s/idProduct", gadget_dir); if ((fp = cupsFileOpen(filename, "w")) == NULL) { papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Unable to create USB gadget file '%s': %s", filename, strerror(errno)); return (false); } cupsFilePrintf(fp, "0x%04X\n", printer->usb_product_id); cupsFileClose(fp); snprintf(filename, sizeof(filename), "%s/strings/0x409", gadget_dir); if (mkdir(filename, 0777) && errno != EEXIST) { papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Unable to create USB gadget directory '%s': %s", filename, strerror(errno)); return (false); } snprintf(filename, sizeof(filename), "%s/strings/0x409/manufacturer", gadget_dir); if ((fp = cupsFileOpen(filename, "w")) == NULL) { papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Unable to create USB gadget file '%s': %s", filename, strerror(errno)); return (false); } cupsFilePrintf(fp, "%s\n", mfg); cupsFileClose(fp); snprintf(filename, sizeof(filename), "%s/strings/0x409/product", gadget_dir); if ((fp = cupsFileOpen(filename, "w")) == NULL) { papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Unable to create USB gadget file '%s': %s", filename, strerror(errno)); return (false); } cupsFilePrintf(fp, "%s\n", mdl); cupsFileClose(fp); snprintf(filename, sizeof(filename), "%s/strings/0x409/serialnumber", gadget_dir); if ((fp = cupsFileOpen(filename, "w")) == NULL) { papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Unable to create USB gadget file '%s': %s", filename, strerror(errno)); return (false); } cupsFilePrintf(fp, "%s\n", sn); cupsFileClose(fp); snprintf(filename, sizeof(filename), "%s/configs/c.1", gadget_dir); if (mkdir(filename, 0777) && errno != EEXIST) { papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Unable to create USB gadget directory '%s': %s", filename, strerror(errno)); return (false); } snprintf(filename, sizeof(filename), "%s/functions/printer.g_printer0", gadget_dir); if (mkdir(filename, 0777) && errno != EEXIST) { papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Unable to create USB gadget directory '%s': %s", filename, strerror(errno)); return (false); } snprintf(filename, sizeof(filename), "%s/functions/printer.g_printer0/pnp_string", gadget_dir); if ((fp = cupsFileOpen(filename, "w")) == NULL) { papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Unable to create USB gadget file '%s': %s", filename, strerror(errno)); return (false); } cupsFilePrintf(fp, "%s\n", printer->device_id); cupsFileClose(fp); snprintf(filename, sizeof(filename), "%s/functions/printer.g_printer0/q_len", gadget_dir); if ((fp = cupsFileOpen(filename, "w")) == NULL) { papplLogPrinter(printer, PAPPL_LOGLEVEL_WARN, "Unable to create USB gadget file '%s': %s", filename, strerror(errno)); } cupsFilePuts(fp, "10\n"); cupsFileClose(fp); snprintf(filename, sizeof(filename), "%s/functions/printer.g_printer0", gadget_dir); snprintf(destname, sizeof(destname), "%s/configs/c.1/printer.g_printer0", gadget_dir); if (symlink(filename, destname) && errno != EEXIST) { papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Unable to create USB gadget symlink '%s': %s", destname, strerror(errno)); return (false); } // Add optional gadgets... if (printer->usb_options & PAPPL_UOPTIONS_ETHERNET) { // Standard USB-Ethernet interface... snprintf(filename, sizeof(filename), "%s/functions/ncm.usb0", gadget_dir); if (mkdir(filename, 0777) && errno != EEXIST) { papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Unable to create USB gadget directory '%s': %s", filename, strerror(errno)); return (false); } snprintf(destname, sizeof(destname), "%s/configs/c.1/ncm.usb0", gadget_dir); if (symlink(filename, destname) && errno != EEXIST) { papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Unable to create USB gadget symlink '%s': %s", destname, strerror(errno)); return (false); } } if (printer->usb_options & PAPPL_UOPTIONS_SERIAL) { // Standard serial port... snprintf(filename, sizeof(filename), "%s/functions/acm.ttyGS0", gadget_dir); if (mkdir(filename, 0777) && errno != EEXIST) { papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Unable to create USB gadget directory '%s': %s", filename, strerror(errno)); return (false); } snprintf(destname, sizeof(destname), "%s/configs/c.1/acm.ttyGS0", gadget_dir); if (symlink(filename, destname) && errno != EEXIST) { papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Unable to create USB gadget symlink '%s': %s", destname, strerror(errno)); return (false); } } if ((printer->usb_options & PAPPL_UOPTIONS_STORAGE) && printer->usb_storage) { // Standard USB mass storage device... snprintf(filename, sizeof(filename), "%s/functions/mass_storage.0", gadget_dir); if (mkdir(filename, 0777) && errno != EEXIST) { papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Unable to create USB gadget directory '%s': %s", filename, strerror(errno)); return (false); } snprintf(filename, sizeof(filename), "%s/functions/mass_storage.0/lun.0/file", gadget_dir); if ((fp = cupsFileOpen(filename, "w")) == NULL) { papplLogPrinter(printer, PAPPL_LOGLEVEL_WARN, "Unable to create USB gadget file '%s': %s", filename, strerror(errno)); } cupsFilePrintf(fp, "%s\n", printer->usb_storage); cupsFileClose(fp); if (printer->usb_options & PAPPL_UOPTIONS_STORAGE_READONLY) { snprintf(filename, sizeof(filename), "%s/functions/mass_storage.0/lun.0/ro", gadget_dir); if ((fp = cupsFileOpen(filename, "w")) == NULL) { papplLogPrinter(printer, PAPPL_LOGLEVEL_WARN, "Unable to create USB gadget file '%s': %s", filename, strerror(errno)); } cupsFilePuts(fp, "1\n"); cupsFileClose(fp); } if (printer->usb_options & PAPPL_UOPTIONS_STORAGE_REMOVABLE) { snprintf(filename, sizeof(filename), "%s/functions/mass_storage.0/lun.0/removable", gadget_dir); if ((fp = cupsFileOpen(filename, "w")) == NULL) { papplLogPrinter(printer, PAPPL_LOGLEVEL_WARN, "Unable to create USB gadget file '%s': %s", filename, strerror(errno)); } cupsFilePuts(fp, "1\n"); cupsFileClose(fp); } snprintf(filename, sizeof(filename), "%s/functions/mass_storage.0", gadget_dir); snprintf(destname, sizeof(destname), "%s/configs/c.1/mass_storage.0", gadget_dir); if (symlink(filename, destname) && errno != EEXIST) { papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Unable to create USB gadget symlink '%s': %s", destname, strerror(errno)); return (false); } } // Then assign this configuration to the first USB device controller if ((dir = cupsDirOpen(LINUX_USB_CONTROLLER)) == NULL) { papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Unable to find USB device controller in '%s': %s", LINUX_USB_CONTROLLER, strerror(errno)); return (false); } while ((dent = cupsDirRead(dir)) != NULL) { if (dent->filename[0] != '.' && dent->filename[0]) break; } if (!dent) { papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "No USB device controller in '%s': %s", LINUX_USB_CONTROLLER, strerror(errno)); cupsDirClose(dir); return (false); } papplLogPrinter(printer, PAPPL_LOGLEVEL_DEBUG, "Using UDC '%s' for USB gadgets.", dent->filename); snprintf(filename, sizeof(filename), "%s/UDC", gadget_dir); if ((fp = cupsFileOpen(filename, "w")) == NULL) { papplLogPrinter(printer, PAPPL_LOGLEVEL_ERROR, "Unable to create USB gadget file '%s': %s", filename, strerror(errno)); cupsDirClose(dir); return (false); } cupsFilePrintf(fp, "%s\n", dent->filename); cupsFileClose(fp); cupsDirClose(dir); papplLogPrinter(printer, PAPPL_LOGLEVEL_INFO, "USB printer gadget configured."); return (true); } #endif // __linux
melexis-fir/mlx90640-driver-py
mlx90640/c-code/src/mlx90640_driver_register.c
<filename>mlx90640/c-code/src/mlx90640_driver_register.c #include "mlx90640_driver_register.h" #include <string.h> #include <stdio.h> #include <stdlib.h> #define DRIVER_LIST_LEN 10 static struct MLX90640DriverRegister_t *g_driver_list[DRIVER_LIST_LEN]; static int16_t g_active_driver_index = -1; void mlx90640_register_driver(struct MLX90640DriverRegister_t *driver) { for (uint8_t i=0; i<DRIVER_LIST_LEN; i++) { if (g_driver_list[i] == NULL) { // ok found empty slot! g_driver_list[i] = driver; return; } } printf("mlx90640_register_driver: ERROR, no free slot!\n"); } struct MLX90640DriverRegister_t * mlx90640_get_driver(const char *name) { for (uint8_t i=0; i<DRIVER_LIST_LEN; i++) { if (g_driver_list[i] != NULL) { // ok found empty slot! if (!strcmp(g_driver_list[i]->name_, name)) { return g_driver_list[i]; } } } return NULL; } struct MLX90640DriverRegister_t * mlx90640_get_active_driver(void) { if (g_active_driver_index < 0) return NULL; if (g_active_driver_index >= DRIVER_LIST_LEN) return NULL; return g_driver_list[g_active_driver_index]; } int mlx90640_activate_driver(const char *name) { for (uint8_t i=0; i<DRIVER_LIST_LEN; i++) { if (g_driver_list[i] != NULL) { // ok found used slot! if (!strncmp(name, g_driver_list[i]->name_, strlen(g_driver_list[i]->name_))) { // ok, found driver with a name that starts the same way as <name> starts! (no exact match needed!) g_active_driver_index = i; return 0; } } } return -1; } void * MLX90640_get_i2c_handle(void) { if (g_active_driver_index < 0) return NULL; return g_driver_list[g_active_driver_index]->MLX90640_get_i2c_handle_(); } void MLX90640_set_i2c_handle(void *handle) { if (g_active_driver_index < 0) return; g_driver_list[g_active_driver_index]->MLX90640_set_i2c_handle_(handle); } void MLX90640_I2CInit(const char *port) { mlx90640_activate_driver(port); if (g_active_driver_index < 0) return; g_driver_list[g_active_driver_index]->MLX90640_I2CInit_(port); } void MLX90640_I2CClose(void) { if (g_active_driver_index < 0) return; g_driver_list[g_active_driver_index]->MLX90640_I2CClose_(); } int MLX90640_I2CRead(uint8_t slaveAddr, uint16_t startAddr, uint16_t nMemAddressRead, uint16_t *data) { if (g_active_driver_index < 0) return -1; return g_driver_list[g_active_driver_index]->MLX90640_I2CRead_(slaveAddr, startAddr, nMemAddressRead, data); } void MLX90640_I2CFreqSet(int freq) { if (g_active_driver_index < 0) return; g_driver_list[g_active_driver_index]->MLX90640_I2CFreqSet_(freq); } int MLX90640_I2CGeneralReset(void) { if (g_active_driver_index < 0) return -1; return g_driver_list[g_active_driver_index]->MLX90640_I2CGeneralReset_(); } int MLX90640_I2CWrite(uint8_t slaveAddr, uint16_t writeAddress, uint16_t data) { if (g_active_driver_index < 0) return -1; return g_driver_list[g_active_driver_index]->MLX90640_I2CWrite_(slaveAddr, writeAddress, data); }
melexis-fir/mlx90640-driver-py
mlx90640/c-code/main.c
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include "MLX90640_I2C_Driver.h" #include "MLX90640_API.h" #include "mlx90640_driver_register.h" // #include "MLX90640_I2C_Driver_mcp2221.h" // #include "MLX90640_I2C_Driver_devtree.h" #define MLX_I2C_ADDR 0x33 int main(void){ // mlx90640_register_driver(MLX90640_get_register_mcp2221()); // mlx90640_register_driver(MLX90640_get_register_devtree()); MLX90640_I2CInit("mcp://mcp:2221/0"); //MLX90640_I2CInit("/dev/i2c-1"); // int state = 0; printf("Starting...\n"); static uint16_t eeMLX90640[832]; float emissivity = 1; uint16_t frame[834]; // static float image[768]; float eTa; // static uint16_t data[768*sizeof(float)]; int r = MLX90640_SetRefreshRate(MLX_I2C_ADDR, 2); printf("Configured...%d\n", r); printf("refresh = %d\n", MLX90640_GetRefreshRate (MLX_I2C_ADDR)); paramsMLX90640 mlx90640; MLX90640_DumpEE(MLX_I2C_ADDR, eeMLX90640); MLX90640_ExtractParameters(eeMLX90640, &mlx90640); int refresh = MLX90640_GetRefreshRate(MLX_I2C_ADDR); printf("EE Dumped...\n"); printf("Refresh Rate = %d\n", refresh); static float mlx90640To[768]; int counter =0; while(1){ MLX90640_GetFrameData(MLX_I2C_ADDR, frame); eTa = MLX90640_GetTa(frame, &mlx90640)-5.0; printf("TA = %0.2f -- %d\n", eTa, counter); counter++; MLX90640_CalculateTo(frame, &mlx90640, emissivity, eTa, mlx90640To); for(int i=0; i<12; i++){ for(int j=0; j<16; j++){ if(j!=19) printf("%0.2f,", mlx90640To[i*16+j]); else printf("%0.2f\n", mlx90640To[i*16+j]); } } printf("\n"); } /* uint16_t data[4]; MLX90640_I2CInit(); MLX90640_I2CRead(0x33, 0x800D, 4, data); for (int i=0; i<4; i++){ printf("%d\n", data[i]); // printf("\n"); } MLX90640_I2CWrite(0x33, 0x800D, 0); MLX90640_I2CRead(0x33, 0x800D, 4, data); for (int i=0; i<4; i++){ printf("%d\n", data[i]); // printf("\n"); } MLX90640_I2CWrite(0x33, 0x800D, 6401); MLX90640_I2CRead(0x33, 0x800D, 4, data); for (int i=0; i<4; i++){ printf("%d\n", data[i]); // printf("\n"); } MLX90640_I2CClose(); */ }
dorinbotan/M1280-Board-Drivers
Clock/Clock/DS1337.h
<reponame>dorinbotan/M1280-Board-Drivers<filename>Clock/Clock/DS1337.h #ifndef DS1337_H_ #define DS1337_H_ #include <avr/io.h> //void rtc_init(void (*)(uint8_t*)); void rtc_setTime(uint8_t h, uint8_t m, uint8_t s, void (*)(uint8_t*)); void rtc_setDate(uint8_t y, uint8_t m, uint8_t d, void (*)(uint8_t*)); void rtc_getTime(void (*)(uint8_t*)); void rtc_getDate(void (*)(uint8_t*)); void rtc_getStatus(void (*)(uint8_t*)); #endif /* DS1337_H_ */
dorinbotan/M1280-Board-Drivers
ringbuffer.h
<reponame>dorinbotan/M1280-Board-Drivers #include <inttypes.h> #ifndef RINGBUFFER_H #define RINGBUFFER_H #define RING_BUFFER_SIZE 128 #if (RING_BUFFER_SIZE & (RING_BUFFER_SIZE - 1)) != 0 #error "RING_BUFFER_SIZE must be a power of two" #endif typedef uint8_t ring_buffer_size_t; #define RING_BUFFER_MASK (RING_BUFFER_SIZE-1) typedef struct ring_buffer_t ring_buffer_t; struct ring_buffer_t { char buffer[RING_BUFFER_SIZE]; ring_buffer_size_t tail_index; ring_buffer_size_t head_index; }; void ring_buffer_init(ring_buffer_t *buffer); void ring_buffer_queue(ring_buffer_t *buffer, char data); void ring_buffer_queue_arr(ring_buffer_t *buffer, const char *data, ring_buffer_size_t size); uint8_t ring_buffer_dequeue(ring_buffer_t *buffer, char *data); uint8_t ring_buffer_dequeue_arr(ring_buffer_t *buffer, char *data, ring_buffer_size_t len); uint8_t ring_buffer_peek(ring_buffer_t *buffer, char *data, ring_buffer_size_t index); inline uint8_t ring_buffer_is_empty(ring_buffer_t *buffer) { return (buffer->head_index == buffer->tail_index); } inline uint8_t ring_buffer_is_full(ring_buffer_t *buffer) { return ((buffer->head_index - buffer->tail_index) & RING_BUFFER_MASK) == RING_BUFFER_MASK; } inline ring_buffer_size_t ring_buffer_num_items(ring_buffer_t *buffer) { return ((buffer->head_index - buffer->tail_index) & RING_BUFFER_MASK); } #endif /* RINGBUFFER_H */
dorinbotan/M1280-Board-Drivers
HandIn/DS1337.c
#include "DS1337.h" #include "twi.h" #define DEVICE_ID 0x68 uint8_t _toBcd(uint8_t value) { return ((value / 10) << 4) + (value % 10); } //uint8_t fromBcd(uint8_t value) //{ //return (value >> 4) * 10 + (value & 0x0F); //} void rtc_init(void (*callbackFunction)(uint8_t*)) { twi_init(100000L); uint8_t data[1] = { 0b00000100 }; twi_write(DEVICE_ID, 0x0E, data, 1, callbackFunction); } void rtc_setTime(uint8_t h, uint8_t m, uint8_t s, void (*callback)(uint8_t*)) { if(s < 0 || s > 59 || m < 0 || m > 59 || h < 0 || h > 23) { callback(0); } else { uint8_t data[3] = { _toBcd(s), _toBcd(m), _toBcd(h) }; twi_write(DEVICE_ID, 0x00, data, 3, callback); } } void rtc_setDate(uint8_t y, uint8_t m, uint8_t d, void (*callback)(uint8_t*)) { if(d < 0 || d > 31 || m < 1 || m > 12 || y < 0 || y > 99) { callback(0); } else { uint8_t data[3] = { _toBcd(d), _toBcd(m), _toBcd(y) }; twi_write(DEVICE_ID, 0x04, data, 3, callback); } } void rtc_getTime(void (*callback)(uint8_t *)) { twi_read(DEVICE_ID, 0x00, 3, callback); } void rtc_getDate(void (*callback)(uint8_t *)) { twi_read(DEVICE_ID, 0x04, 3, callback); } void rtc_getStatus(void (*callback)(uint8_t *)) { twi_read(DEVICE_ID, 0x0F, 1, callback); }
dorinbotan/M1280-Board-Drivers
HandIn/main1.c
<reponame>dorinbotan/M1280-Board-Drivers #include <avr/io.h> #include <avr/interrupt.h> #include "display.h" #include "DS1337.h" void _display_value(uint8_t *value) { // From BCD uint8_t second = (value[0] >> 4) * 10 + (value[0] & 0x0F); uint8_t minute = (value[1] >> 4) * 10 + (value[1] & 0x0F); float toDisplay = minute + (float)second / 100; display_7_segment(toDisplay, 2); } ISR(TIMER1_OVF_vect) { rtc_getTime(_display_value); TCNT1 = 51136; } void _timer_setup(uint8_t *dummy) { TCNT1 = 51136; // 14400 ticks (2 Hz) TCCR1B |= _BV(CS12); // 256 prescaler TIMSK1 |= _BV(TOIE1); // enable overflow interrupt (16 bit) } void _set_time(uint8_t *dummy) { rtc_setTime(0, 0, 0, _timer_setup); } int main(void) { sei(); rtc_init(_set_time); while (1); }
dorinbotan/M1280-Board-Drivers
HandIn/main2.c
<reponame>dorinbotan/M1280-Board-Drivers<gh_stars>0 #include <avr/io.h> #include <avr/interrupt.h> #include "mcu.h" const uint8_t DIGIT[10] = { 0xFC, 0x60, 0xDA, 0xF2, 0x66, 0xB6, 0xBE, 0xE0, 0xFE, 0xF6 }; uint8_t init = 0; int8_t value_by_digits[4] = { -1, -1, -1, -1 }; uint8_t current = 0; ISR(TIMER0_OVF_vect) { TCNT0 = 136; uint8_t digit_value = value_by_digits[current]; if(digit_value != -1) { for (uint8_t i = 0; i < 8; i++) { if (digit_value & 0x01) SET_BIT(PORTB, PB2); else CLEAR_BIT(PORTB, PB2); CLOCK_PIN(PORTB, PB1); digit_value >>= 1; } PORTL &= ~0x0F; CLOCK_PIN(PORTK, PK3); SET_BIT(PORTL, 3 - current); current = (current + 1) % 4; } } void init_7_segment() { DDRB = _BV(PB3) | _BV(PB2) | _BV(PB1); // MR, DS, SHCP DDRK = _BV(PK3); // STCP to output DDRL = 0x0F; // PL0 .. PL3 PORTB = _BV(PB3); // MR // Refreshes display TCNT0 = 136; // 120 ticks (240 Hz) TCCR0B = _BV(CS02); // 256 prescaler TIMSK0 = _BV(TOIE0); // Enable timer compare interrupt (8 bit) } void display_7_segment(float value, uint8_t no_of_decimals) { if(!init) { init = 1; init_7_segment(); } uint16_t pow_ten[] = { 1, 10, 100, 1000 }; uint32_t real = value * pow_ten[no_of_decimals]; for(int i = 0; i < 4; i++) { uint8_t digit = (real / pow_ten[3 - i]) % 10; value_by_digits[i] = DIGIT[digit] | (i == 3 - no_of_decimals); } } float counter = 0; ISR(TIMER1_OVF_vect) { TCNT1 = 58336; display_7_segment(counter, 2); counter += 0.01; } int main(void) { sei(); display_7_segment(123.4, 1); // Updates shown value TCNT1 = 58336; // 7200 ticks (4 Hz) TCCR1B |= _BV(CS12); // 256 prescaler TIMSK1 |= _BV(TOIE1); // enable overflow interrupt while (1); }
dorinbotan/M1280-Board-Drivers
usart0.c
#include <avr/interrupt.h> #include <avr/io.h> #include <util/atomic.h> #include "usart0.h" ring_buffer_t usart0_recv_ring_buf; ring_buffer_t usart0_send_ring_buf; void usart0_init(void) { cli(); ring_buffer_init(&usart0_recv_ring_buf); ring_buffer_init(&usart0_send_ring_buf); UCSR0A = 0; // Enable USART0 TX and RX UCSR0B = (1 << RXEN0) | (1 << TXEN0) | (1 << RXCIE0); // Async USART, 8bit, no parity and 1 stop bit UCSR0C = (1 << UCSZ00) | (1 << UCSZ01); // 9600 Baud Rate at 7.37 MHz UBRR0L = 47; UBRR0H = 0; sei(); } ring_buffer_size_t usart0_recv_queue_size(void) { ring_buffer_size_t result; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { result = ring_buffer_num_items(&usart0_recv_ring_buf); } return result; } ring_buffer_size_t usart0_recv_dequeue(char *data) { ring_buffer_size_t result; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { result = ring_buffer_dequeue(&usart0_recv_ring_buf, data); } return result; } ring_buffer_size_t usart0_recv_peek(char *data, ring_buffer_size_t index) { ring_buffer_size_t result; ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { result = ring_buffer_peek(&usart0_recv_ring_buf, data, index); } return result; } void usart0_send(char data) { ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { ring_buffer_queue(&usart0_send_ring_buf, data); UCSR0B |= (1 << UDRIE0); } } void usart0_send_arr(const char *data, ring_buffer_size_t size) { ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { ring_buffer_queue_arr(&usart0_send_ring_buf, data, size); UCSR0B |= (1 << UDRIE0); } } usart_desc_t *get_usart0_descriptor(void) { static usart_desc_t descriptor = { .usart_recv_queue_size = usart0_recv_queue_size, .usart_recv_dequeue = usart0_recv_dequeue, .usart_recv_peek = usart0_recv_peek, .usart_send = usart0_send, .usart_send_arr = usart0_send_arr }; return &descriptor; } ISR(USART0_RX_vect) { char received_data = UDR0; ring_buffer_queue(&usart0_recv_ring_buf, received_data); } ISR(USART0_UDRE_vect) { char data; if(ring_buffer_dequeue(&usart0_send_ring_buf, &data) > 0) UDR0 = data; else UCSR0B &= ~(1 << UDRIE0); }
dorinbotan/M1280-Board-Drivers
usart.h
#include <avr/io.h> #include "ringbuffer.h" #ifndef USART_H #define USART_H typedef struct { ring_buffer_size_t (*usart_recv_queue_size)(void); ring_buffer_size_t (*usart_recv_dequeue)(char *data); ring_buffer_size_t (*usart_recv_peek)(char *data, ring_buffer_size_t index); void (*usart_send)(char data); void (*usart_send_arr)(const char *data, ring_buffer_size_t size); } usart_desc_t; #endif /* USART_H */
dorinbotan/M1280-Board-Drivers
spi.c
#include "spi.h" #include <avr/interrupt.h> void (*callbackFunction)(uint8_t*); ISR(SPI_STC_vect) { callbackFunction(SPDR); } void spi_init(uint8_t data_order, uint8_t mode, uint8_t polarity, uint8_t phase) { // MOSI SCK SS DDRB |= _BV(PINB2) | _BV(PINB1) | _BV(PINB0); SPCR = ( _BV(SPIE) | _BV(SPE) | (data_order << DORD) | (mode << MSTR) | (polarity << CPOL) | (phase << CPHA) | _BV(SPR1) | _BV(SPR0) ); } void spi_send_byte(uint8_t value, void (*callback)(uint8_t*)) { callbackFunction = callback; SPDR = value; }
dorinbotan/M1280-Board-Drivers
Clock/Clock/twi.c
<reponame>dorinbotan/M1280-Board-Drivers #include "twi.h" #include <avr/interrupt.h> #include <util/twi.h> #include "mcu.h" #define TWI_SendStart() (TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN) | (1 << TWIE)) #define TWI_SendStop() (TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN) | (1 << TWIE)) #define TWI_SendTransmit() (TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWIE)) #define TWI_SendACK() (TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWIE) | (1 << TWEA)) #define TWI_SendNACK() (TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWIE)) typedef enum { Sending, Receiving } TWIMode; TWIMode mode; uint8_t deviceId; uint8_t reg; uint8_t *TXBuffer; volatile int TXIndex; int TXSize; void (*callbackFunction)(uint8_t*); ISR(TWI_vect) { switch(TW_STATUS) { case TW_START: //usart0_send_arr("S", 1); TWDR = (deviceId << 1); TWI_SendTransmit(); break; case TW_REP_START: //usart0_send_arr("2", 1); TWDR = (deviceId << 1) | 0x01; TWI_SendTransmit(); case TW_MT_SLA_ACK: //usart0_send_arr("3", 1); TWDR = reg; TWI_SendTransmit(); break; case TW_MR_SLA_ACK: //usart0_send_arr("4", 1); TWI_SendACK(); break; case TW_MT_DATA_ACK: //usart0_send_arr("5", 1); if(mode == Sending) { if(TXIndex < TXSize) { TWDR = TXBuffer[TXIndex++]; TWI_SendTransmit(); } else { TWI_SendStop(); if(callbackFunction) callbackFunction(0); } } else { TWI_SendStart(); } break; case TW_MR_DATA_ACK: //usart0_send_arr("6", 1); TXBuffer[TXIndex++] = TWDR; if(TXIndex < TXSize) { TWI_SendACK(); } else { TWI_SendNACK(); while((TWCR & (1 << TWINT)) == 0); TWI_SendStop(); if(callbackFunction) callbackFunction(TXBuffer); free(TXBuffer); } break; // Loosing Arbitration (wail a sec and try again) case TW_MT_ARB_LOST: // Trying to access non-existing device here !!! case TW_MT_SLA_NACK: case TW_MR_SLA_NACK: // Data not transmitted here !!! case TW_MT_DATA_NACK: case TW_MR_DATA_NACK: break; } } uint8_t twi_init(long sclFrequency) { // Set no pre-scaling TWSR = !((1 << TWPS0) | (1<< TWPS1)); // Set bit rate TWBR = (F_CPU / sclFrequency - 16) / 2; // Enable TWI and interrupt TWCR = (1 << TWEN) | (1 << TWIE); return TWBR; } void twi_write(uint8_t device, uint8_t address, uint8_t *data, int len, void (*callback)(uint8_t*)) { //usart0_send_arr(" W-", 3); mode = Sending; deviceId = device; reg = address; TXBuffer = data; TXIndex = 0; TXSize = len; callbackFunction = callback; TWI_SendStart(); } void twi_read(uint8_t device, uint8_t address, int len, void (*callback)(uint8_t*)) { //usart0_send_arr(" R-", 3); mode = Receiving; deviceId = device; reg = address; TXBuffer = (uint8_t*)malloc(len); TXIndex = 0; TXSize = len; callbackFunction = callback; TWI_SendStart(); }
dorinbotan/M1280-Board-Drivers
mcu.h
<reponame>dorinbotan/M1280-Board-Drivers #ifndef BIT_MANIPULATION_ #define BIT_MANIPULATION_ #ifndef F_CPU #define F_CPU 7372800L #endif #define SET_BIT(ADDRESS, BIT_POSITION) (ADDRESS |= _BV(BIT_POSITION)) #define CLEAR_BIT(ADDRESS, BIT_POSITION) (ADDRESS &= ~_BV(BIT_POSITION)) #define TOGGLE_BIT(ADDRESS, BIT_POSITION) (ADDRESS ^= _BV(BIT_POSITION)) #define WRITE_BIT(ADDRESS, BIT_POSITION, BIT_VALUE) (BIT_VALUE ? SET_BIT(ADDRESS, _BV(BIT_POSITION)) : CLEAR_BIT(ADDRESS, _BV(BIT_POSITION))) #define CLOCK_PIN(ADDRESS, BIT_POSITION) (SET_BIT(ADDRESS,BIT_POSITION), CLEAR_BIT(ADDRESS,BIT_POSITION)) #endif /* BIT_MANIPULATION_ */
dorinbotan/M1280-Board-Drivers
Clock/Clock/spi.h
#ifndef SPI_H_ #define SPI_H_ #include <avr/io.h> #define SPI_DATA_ORDER_LSB_FIRST 1 #define SPI_DATA_ORDER_MSB_FIRST 0 #define SPI_MODE_MASTER 1 #define SPI_MODE_SLAVE 0 #define SPI_CLOCK_POLARITY_HIGH 1 #define SPI_CLOCK_POLARITY_LOW 0 #define SPI_CLOCK_PHASE_SAMPLE_LEADING 0 #define SPI_CLOCK_PHASE_SAMPLE_TRAILING 1 void spi_init(uint8_t, uint8_t, uint8_t, uint8_t); uint8_t spi_send_byte(uint8_t); #endif /* SPI_H_ */
dorinbotan/M1280-Board-Drivers
HandIn/display.c
#include "display.h" #include "spi.h" #include "mcu.h" #include <avr/interrupt.h> const uint8_t DIGIT[10] = { 0xFC, 0x60, 0xDA, 0xF2, 0x66, 0xB6, 0xBE, 0xE0, 0xFE, 0xF6 }; uint8_t init = 0; int8_t value_by_digits[4] = { -1, -1, -1, -1 }; uint8_t current = 0; void _trigger(uint8_t *dummy) { // Display value PORTL &= ~0xFF; CLOCK_PIN(PORTK, PK3); SET_BIT(PORTL, current); current = (current + 1) % 4; } ISR(TIMER0_OVF_vect) { TCNT0 = 136; uint8_t digit_value = value_by_digits[current]; if(digit_value != -1) { spi_init(SPI_MODE_MASTER, SPI_DATA_ORDER_LSB_FIRST, SPI_CLOCK_POLARITY_LOW, SPI_CLOCK_PHASE_LEADING); spi_send_byte(digit_value, _trigger); } } void _init_7_segment() { // DDRB |= _BV(DDB3); DDRK |= _BV(DDK3); DDRL |= _BV(DDL3) | _BV(DDL2) | _BV(DDL1) | _BV(DDL0); PORTB |= _BV(PB3); TCNT0 = 136; // 120 ticks (240 Hz) TCCR0B |= _BV(CS02); // 256 prescaler TIMSK0 = _BV(TOIE0); // Enable timer compare interrupt (8 bit) } void display_7_segment(float value, uint8_t no_of_decimals) { if(!init) { init = 1; _init_7_segment(); } // Math.pow gives wrong results uint16_t pow_ten[] = { 1, 10, 100, 1000, 10000 }; uint32_t real = value * pow_ten[no_of_decimals]; for(int i = 0; i < 4; i++) { uint8_t digit = (real / pow_ten[i]) % 10; value_by_digits[i] = DIGIT[digit] | (i == no_of_decimals && no_of_decimals); } }
dorinbotan/M1280-Board-Drivers
usart0.h
<filename>usart0.h<gh_stars>0 #include "usart.h" #include "ringbuffer.h" #ifndef USART0_H #define USART0_H void usart0_init(void); ring_buffer_size_t usart0_recv_queue_size(void); ring_buffer_size_t usart0_recv_dequeue(char *data); ring_buffer_size_t usart0_recv_peek(char *data, ring_buffer_size_t index); void usart0_send(char data); void usart0_send_arr(const char *data, ring_buffer_size_t size); usart_desc_t *get_usart0_descriptor(void); #endif /* USART0_H */
dorinbotan/M1280-Board-Drivers
ringbuffer.c
<gh_stars>0 #include "ringbuffer.h" void ring_buffer_init(ring_buffer_t *buffer) { buffer->tail_index = 0; buffer->head_index = 0; } void ring_buffer_queue(ring_buffer_t *buffer, char data) { if(ring_buffer_is_full(buffer)) buffer->tail_index = ((buffer->tail_index + 1) & RING_BUFFER_MASK); buffer->buffer[buffer->head_index] = data; buffer->head_index = ((buffer->head_index + 1) & RING_BUFFER_MASK); } void ring_buffer_queue_arr(ring_buffer_t *buffer, const char *data, ring_buffer_size_t size) { ring_buffer_size_t i; for(i = 0; i < size; i++) ring_buffer_queue(buffer, data[i]); } ring_buffer_size_t ring_buffer_dequeue(ring_buffer_t *buffer, char *data) { if(ring_buffer_is_empty(buffer)) return 0; *data = buffer->buffer[buffer->tail_index]; buffer->tail_index = ((buffer->tail_index + 1) & RING_BUFFER_MASK); return 1; } ring_buffer_size_t ring_buffer_dequeue_arr(ring_buffer_t *buffer, char *data, ring_buffer_size_t len) { if(ring_buffer_is_empty(buffer)) return 0; char *data_ptr = data; ring_buffer_size_t cnt = 0; while((cnt < len) && ring_buffer_dequeue(buffer, data_ptr)) { cnt++; data_ptr++; } return cnt; } ring_buffer_size_t ring_buffer_peek(ring_buffer_t *buffer, char *data, ring_buffer_size_t index) { if(index >= ring_buffer_num_items(buffer)) return 0; ring_buffer_size_t data_index = ((buffer->tail_index + index) & RING_BUFFER_MASK); *data = buffer->buffer[data_index]; return 1; } extern inline uint8_t ring_buffer_is_empty(ring_buffer_t *buffer); extern inline uint8_t ring_buffer_is_full(ring_buffer_t *buffer); extern inline uint8_t ring_buffer_num_items(ring_buffer_t *buffer);
dorinbotan/M1280-Board-Drivers
display.c
#include "display.h" #include "spi.h" #include "mcu.h" #include <avr/interrupt.h> const uint16_t DISPLAY[4] = { PL3, PL0, PL1, PL2 }; const uint8_t DIGIT[10] = { 0xFC, 0x60, 0xDA, 0xF2, 0x66, 0xB6, 0xBE, 0xE0, 0xFE, 0xF6 }; uint8_t init = 0; int8_t value_by_digits[4] = { -1, -1, -1, -1 }; uint8_t current = 0; ISR(TIMER0_OVF_vect) { uint8_t value_digit = value_by_digits[current]; if(value_digit != -1) { spi_init(SPI_MODE_MASTER, SPI_DATA_ORDER_LSB_FIRST, SPI_CLOCK_POLARITY_LOW, SPI_CLOCK_PHASE_SAMPLE_LEADING); spi_send_byte(value_digit); _trigger_display(); } } void _display_init() { DDRB |= _BV(DDB3); DDRK |= _BV(DDK3); DDRL |= _BV(DDL3) | _BV(DDL2) | _BV(DDL1) | _BV(DDL0); PORTB |= _BV(PB3); // Timer TCCR0B |= _BV(CS01) | _BV(CS00); TIMSK0 = _BV(TOIE0); } void _trigger_display() { CLEAR_BIT(PORTL, DISPLAY[current]); CLOCK_PIN(PORTK, PK3); SET_BIT(PORTL, current); current++; current %= 4; } void display_value(unsigned short value) { if(!init) { _display_init(); init = 1; } unsigned short n = value; uint8_t count = 0; while(n != 0 || count == 0) { n /= 10; ++count; } for(int i = 0; i < 4; i++) { if(i < count) value_by_digits[i] = DIGIT[value % 10]; else value_by_digits[i] = 0; value /= 10; } }
dorinbotan/M1280-Board-Drivers
spi.h
<gh_stars>0 #ifndef SPI_H_ #define SPI_H_ #include <avr/io.h> #define SPI_DATA_ORDER_LSB_FIRST 1 #define SPI_DATA_ORDER_MSB_FIRST 0 #define SPI_MODE_MASTER 1 #define SPI_MODE_SLAVE 0 #define SPI_CLOCK_POLARITY_HIGH 1 #define SPI_CLOCK_POLARITY_LOW 0 #define SPI_CLOCK_PHASE_LEADING 0 #define SPI_CLOCK_PHASE_TRAILING 1 void spi_init(uint8_t data_order, uint8_t mode, uint8_t polarity, uint8_t phase); void spi_send_byte(uint8_t, void (*)(uint8_t*)); #endif /* SPI_H_ */
dorinbotan/M1280-Board-Drivers
display.h
#ifndef DISPLAY_H_ #define DISPLAY_H_ void display_value(unsigned short); #endif /* DISPLAY_H_ */
dorinbotan/M1280-Board-Drivers
Clock/Clock/main.c
#include <avr/io.h> #include <avr/interrupt.h> #include "display.h" #include "DS1337.h" #include "twi.h" //#include "USART/usart.h" //#include "USART/usart0.h" uint8_t fromBcd(uint8_t value) { return (value >> 4) * 10 + (value & 0x0F); } uint8_t status = 0; void a1(uint8_t *value) { status = 1; display_value(fromBcd(value[1]) * 100 + fromBcd(value[0])); } void a0(uint8_t *value) { status = 1; } int main(void) { sei(); // char buf; // usart0_init(); // usart0_send_arr("\r\n", 2); // twi_init(100000L); rtc_setTime(10, 21, 0, a0); while(1) { // if(usart0_recv_dequeue(&buf)) // usart0_send(buf); if(status) { status = 0; rtc_getTime(a1); } else if(status) { rtc_getTime(a1); } } }
dorinbotan/M1280-Board-Drivers
led.h
#ifndef LED_H_ #define LED_H_ void init_leds() { DDRH = 0xFF; PORTH = 0x00; } // led_no [1..8], state [0..1] void set_led(uint8_t led_no, uint8_t state) { if(led_no < 9 && led_no > 0) if(state) PORTH |= 1 << (8 - led_no); else PORTH &= ~(1 << (8 - led_no)); } #endif /* LED_H_ */
dorinbotan/M1280-Board-Drivers
debounced_key.h
#ifndef DEBOUNCED_KEY_H_ #define DEBOUNCED_KEY_H_ void init_debounced_keys() { DDRE &= ~((1 << 4) | (1 << 5)); } // key_no [1..2], return true if key pressed uint8_t get_debounced_key(uint8_t key_no) { if (key_no != 1 && key_no != 2) return 0; if ((1 << key_no + 3) & PINE) return 1; return 0; } #endif /* DEBOUNCED_KEY_H_ */