code
stringlengths 6
250k
| repo_name
stringlengths 5
70
| path
stringlengths 3
177
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 6
250k
|
|---|---|---|---|---|---|
/*
* Multi2Sim
* Copyright (C) 2012 Rafael Ubal (ubal@ece.neu.edu)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <assert.h>
#include <lib/mhandle/mhandle.h>
#include <lib/util/debug.h>
#include <lib/util/linked-list.h>
#include "opencl-repo.h"
#include "opencl-command-queue.h"
#include "opencl-context.h"
#include "opencl-device.h"
#include "opencl-event.h"
#include "opencl-kernel.h"
#include "opencl-mem.h"
#include "opencl-platform.h"
#include "opencl-program.h"
#include "opencl-sampler.h"
struct si_opencl_repo_t
{
struct linked_list_t *object_list;
};
struct si_opencl_repo_t *si_opencl_repo_create(void)
{
struct si_opencl_repo_t *repo;
/* Initialize */
repo = xcalloc(1, sizeof(struct si_opencl_repo_t));
repo->object_list = linked_list_create();
/* Return */
return repo;
}
void si_opencl_repo_free(struct si_opencl_repo_t *repo)
{
linked_list_free(repo->object_list);
free(repo);
}
void si_opencl_repo_add_object(struct si_opencl_repo_t *repo,
void *object)
{
struct linked_list_t *object_list = repo->object_list;
/* Check that object does not exist */
linked_list_find(object_list, object);
if (!object_list->error_code)
fatal("%s: object already exists", __FUNCTION__);
/* Insert */
linked_list_add(object_list, object);
}
void si_opencl_repo_remove_object(struct si_opencl_repo_t *repo,
void *object)
{
struct linked_list_t *object_list = repo->object_list;
/* Check that object exists */
linked_list_find(object_list, object);
if (object_list->error_code)
fatal("%s: object does not exist", __FUNCTION__);
/* Remove */
linked_list_remove(object_list);
}
/* Look for an object in the repository. The first field of every OpenCL object
* is its identifier. */
void *si_opencl_repo_get_object(struct si_opencl_repo_t *repo,
enum si_opencl_object_type_t type, unsigned int object_id)
{
struct linked_list_t *object_list = repo->object_list;
void *object;
unsigned int current_object_id;
/* Upper 16-bits represent the type of the object */
if (object_id >> 16 != type)
fatal("%s: requested OpenCL object of incorrect type",
__FUNCTION__);
/* Search object */
LINKED_LIST_FOR_EACH(object_list)
{
object = linked_list_get(object_list);
assert(object);
current_object_id = * (unsigned int *) object;
if (current_object_id == object_id)
return object;
}
/* Not found */
fatal("%s: requested OpenCL does not exist (id=0x%x)",
__FUNCTION__, object_id);
return NULL;
}
/* Get the oldest created OpenCL object of the specified type */
void *si_opencl_repo_get_object_of_type(struct si_opencl_repo_t *repo,
enum si_opencl_object_type_t type)
{
struct linked_list_t *object_list = repo->object_list;
void *object;
unsigned int object_id;
/* Find object. Upper 16-bits of identifier contain its type. */
LINKED_LIST_FOR_EACH(object_list)
{
object = linked_list_get(object_list);
assert(object);
object_id = * (unsigned int *) object;
if (object_id >> 16 == type)
return object;
}
/* No object found */
return NULL;
}
/* Assignment of OpenCL object identifiers
* An identifier is a 32-bit value, whose 16 most significant bits represent the
* object type, while the 16 least significant bits represent a unique object ID. */
unsigned int si_opencl_repo_new_object_id(struct si_opencl_repo_t *repo,
enum si_opencl_object_type_t type)
{
static unsigned int si_opencl_object_id_counter;
unsigned int object_id;
object_id = (type << 16) | si_opencl_object_id_counter;
si_opencl_object_id_counter++;
if (si_opencl_object_id_counter > 0xffff)
fatal("%s: limit of OpenCL objects exceeded\n", __FUNCTION__);
return object_id;
}
void si_opencl_repo_free_all_objects(struct si_opencl_repo_t *repo)
{
void *object;
/* Platforms */
while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_platform)))
si_opencl_platform_free((struct si_opencl_platform_t *) object);
/* Devices */
while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_device)))
si_opencl_device_free((struct si_opencl_device_t *) object);
/* Contexts */
while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_context)))
si_opencl_context_free((struct si_opencl_context_t *) object);
/* Command queues */
while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_command_queue)))
si_opencl_command_queue_free((struct si_opencl_command_queue_t *) object);
/* Programs */
while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_program)))
si_opencl_program_free((struct si_opencl_program_t *) object);
/* Kernels */
while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_kernel)))
si_opencl_kernel_free((struct si_opencl_kernel_t *) object);
/* Mems */
while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_mem)))
si_opencl_mem_free((struct si_opencl_mem_t *) object);
/* Events */
while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_event)))
si_opencl_event_free((struct si_opencl_event_t *) object);
/* Samplers */
while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_sampler)))
si_opencl_sampler_free((struct si_opencl_sampler_t *) object);
/* Any object left */
if (linked_list_count(repo->object_list))
panic("%s: not all objects were freed", __FUNCTION__);
}
|
filippo-ceid/multi2sim
|
src/arch/southern-islands/emu/opencl-repo.c
|
C
|
gpl-3.0
| 6,076
|
/* Multiple Lua Programming Language : Intermediate Code Generator
* Copyright(C) 2014 Cheryl Natsu
* This file is part of multiple - Multiple Paradigm Language Interpreter
* multiple is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* multiple is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "selfcheck.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "multiple_ir.h"
#include "multiply.h"
#include "multiply_assembler.h"
#include "multiply_str_aux.h"
#include "multiple_misc.h"
#include "multiple_err.h"
#include "vm_predef.h"
#include "vm_opcode.h"
#include "vm_types.h"
#include "mlua_lexer.h"
#include "mlua_ast.h"
#include "mlua_icg.h"
#include "mlua_icg_aux.h"
#include "mlua_icg_fcb.h"
#include "mlua_icg_context.h"
#include "mlua_icg_expr.h"
#include "mlua_icg_stmt.h"
#include "mlua_icg_built_in_proc.h"
#include "mlua_icg_built_in_table.h"
/* Declaration */
int mlua_icodegen_statement_list(struct multiple_error *err, \
struct mlua_icg_context *context, \
struct mlua_icg_fcb_block *icg_fcb_block, \
struct mlua_map_offset_label_list *map_offset_label_list, \
struct mlua_ast_statement_list *list, \
struct multiply_offset_item_pack *offset_pack_break);
static int mlua_icodegen_merge_blocks(struct multiple_error *err, \
struct mlua_icg_context *context)
{
int ret = 0;
struct mlua_icg_fcb_block *icg_fcb_block_cur;
struct mlua_icg_fcb_line *icg_fcb_line_cur;
uint32_t instrument_number;
struct multiple_ir_export_section_item *export_section_item_cur;
struct multiple_ir_text_section_item *text_section_item_cur;
uint32_t offset_start;
uint32_t fcb_size = 0;
uint32_t count;
/* Do not disturb the instrument produced by other way */
offset_start = (uint32_t)(context->icode->text_section->size);
export_section_item_cur = context->icode->export_section->begin;
icg_fcb_block_cur = context->icg_fcb_block_list->begin;
while (icg_fcb_block_cur != NULL)
{
icg_fcb_line_cur = icg_fcb_block_cur->begin;
/* Record the absolute instrument number */
instrument_number = (uint32_t)context->icode->text_section->size;
if (export_section_item_cur == NULL)
{
MULTIPLE_ERROR_INTERNAL();
ret = -MULTIPLE_ERR_INTERNAL;
goto fail;
}
export_section_item_cur->instrument_number = instrument_number;
while (icg_fcb_line_cur != NULL)
{
switch (icg_fcb_line_cur->type)
{
case MLUA_ICG_FCB_LINE_TYPE_NORMAL:
if ((ret = multiply_icodegen_text_section_append(err, \
context->icode, \
icg_fcb_line_cur->opcode, icg_fcb_line_cur->operand)) != 0)
{ goto fail; }
break;
case MLUA_ICG_FCB_LINE_TYPE_PC:
if ((ret = multiply_icodegen_text_section_append(err, \
context->icode, \
icg_fcb_line_cur->opcode, instrument_number + icg_fcb_line_cur->operand)) != 0)
{ goto fail; }
break;
case MLUA_ICG_FCB_LINE_TYPE_LAMBDA_MK:
/* Operand of this instrument here is the index number of lambda */
if ((ret = multiply_icodegen_text_section_append(err, \
context->icode, \
icg_fcb_line_cur->opcode, icg_fcb_line_cur->operand)) != 0)
{ goto fail; }
break;
case MLUA_ICG_FCB_LINE_TYPE_BLTIN_PROC_MK:
if ((ret = multiply_icodegen_text_section_append(err, \
context->icode, \
icg_fcb_line_cur->opcode, icg_fcb_line_cur->operand)) != 0)
{ goto fail; }
break;
}
fcb_size += 1;
icg_fcb_line_cur = icg_fcb_line_cur->next;
}
icg_fcb_block_cur = icg_fcb_block_cur->next;
export_section_item_cur = export_section_item_cur->next;
}
/* 2nd pass, dealing with lambdas */
icg_fcb_block_cur = context->icg_fcb_block_list->begin;
/* Skip text body of built-in procedures at the beginning part */
text_section_item_cur = context->icode->text_section->begin;
while (offset_start-- > 0)
{
text_section_item_cur = text_section_item_cur->next;
}
/* Process lambda mks */
while (icg_fcb_block_cur != NULL)
{
icg_fcb_line_cur = icg_fcb_block_cur->begin;
while (icg_fcb_line_cur != NULL)
{
if (icg_fcb_line_cur->type == MLUA_ICG_FCB_LINE_TYPE_LAMBDA_MK)
{
/* Locate to the export section item */
count = icg_fcb_line_cur->operand;
export_section_item_cur = context->icode->export_section->begin;
while ((export_section_item_cur != NULL) && (count != 0))
{
count--;
export_section_item_cur = export_section_item_cur->next;
}
if (export_section_item_cur == NULL)
{
MULTIPLE_ERROR_INTERNAL();
ret = -MULTIPLE_ERR_INTERNAL;
goto fail;
}
text_section_item_cur->operand = export_section_item_cur->instrument_number;
}
text_section_item_cur = text_section_item_cur->next;
icg_fcb_line_cur = icg_fcb_line_cur->next;
}
icg_fcb_block_cur = icg_fcb_block_cur->next;
}
goto done;
fail:
done:
return ret;
}
static int mlua_icodegen_special(struct multiple_error *err, \
struct multiple_ir *icode, \
struct multiply_resource_id_pool *res_id, \
struct mlua_icg_fcb_block_list *icg_fcb_block_list, \
struct mlua_icg_fcb_block *icg_fcb_block, \
const char *name, const size_t name_len)
{
int ret = 0;
uint32_t id;
struct multiple_ir_export_section_item *new_export_section_item = NULL;
new_export_section_item = multiple_ir_export_section_item_new();
if (new_export_section_item == NULL)
{
MULTIPLE_ERROR_MALLOC();
ret = -MULTIPLE_ERR_MALLOC;
goto fail;
}
new_export_section_item->args_count = 0;
new_export_section_item->args = NULL;
new_export_section_item->args_types = NULL;
/* Return */
if ((ret = mlua_icg_fcb_block_append_with_configure(icg_fcb_block, OP_RETNONE, 0)) != 0)
{ goto fail; }
/* Append block */
if ((ret = mlua_icg_fcb_block_list_append(icg_fcb_block_list, icg_fcb_block)) != 0)
{
MULTIPLE_ERROR_INTERNAL();
goto fail;
}
/* Append export section item */
if ((ret = multiply_resource_get_id( \
err, \
icode, \
res_id, \
&id, \
name, name_len)) != 0)
{ goto fail; }
new_export_section_item->name = id;
new_export_section_item->instrument_number = (uint32_t)icode->export_section->size;
multiple_ir_export_section_append(icode->export_section, new_export_section_item);
goto done;
fail:
if (new_export_section_item != NULL) multiple_ir_export_section_item_destroy(new_export_section_item);
done:
return ret;
}
static int mlua_icodegen_program(struct multiple_error *err, \
struct mlua_icg_context *context, \
struct mlua_ast_program *program)
{
int ret = 0;
struct mlua_icg_fcb_block *new_icg_fcb_block_autorun = NULL;
struct mlua_map_offset_label_list *new_map_offset_label_list = NULL;
uint32_t id;
struct multiple_ir_export_section_item *new_export_section_item = NULL;
uint32_t instrument_number_insert_point_built_in_proc;
uint32_t instrument_count_built_in_proc;
new_icg_fcb_block_autorun = mlua_icg_fcb_block_new();
if (new_icg_fcb_block_autorun == NULL)
{
MULTIPLE_ERROR_MALLOC();
ret = -MULTIPLE_ERR_MALLOC;
goto fail;
}
new_map_offset_label_list = mlua_map_offset_label_list_new();
if (new_map_offset_label_list == NULL)
{
MULTIPLE_ERROR_MALLOC();
ret = -MULTIPLE_ERR_MALLOC;
goto fail;
}
new_export_section_item = multiple_ir_export_section_item_new();
if (new_export_section_item == NULL)
{
MULTIPLE_ERROR_MALLOC();
ret = -MULTIPLE_ERR_MALLOC;
goto fail;
}
/* def in .text section */
if ((ret = multiply_resource_get_id( \
err, \
context->icode, \
context->res_id, \
&id, \
VM_PREDEF_MODULE_AUTORUN, \
VM_PREDEF_MODULE_AUTORUN_LEN)) != 0)
{ goto fail; }
if ((ret = mlua_icg_fcb_block_append_with_configure(new_icg_fcb_block_autorun, OP_DEF, id)) != 0) { goto fail; }
new_export_section_item->name = id;
new_export_section_item->args_count = 0;
new_export_section_item->args = NULL;
new_export_section_item->args_types = NULL;
instrument_number_insert_point_built_in_proc = mlua_icg_fcb_block_get_instrument_number(new_icg_fcb_block_autorun);
/* Statements of top level */
if ((ret = mlua_icodegen_statement_list(err, context, \
new_icg_fcb_block_autorun, \
new_map_offset_label_list, \
program->stmts, NULL)) != 0)
{ goto fail; }
/* Apply goto to label */
if ((ret = mlua_icodegen_statement_list_apply_goto(err, \
context, \
new_icg_fcb_block_autorun, \
new_map_offset_label_list)) != 0)
{ goto fail; }
/* Pop a label offset pack */
multiply_offset_item_pack_stack_pop(context->offset_item_pack_stack);
/* Put built-in procedures directly into icode,
* and put initialize code into '__autorun__' */
if ((ret = mlua_icg_add_built_in_procs(err, \
context->icode, \
context->res_id, \
new_icg_fcb_block_autorun, \
context->customizable_built_in_procedure_list, \
instrument_number_insert_point_built_in_proc,
&instrument_count_built_in_proc)) != 0)
{ goto fail; }
/* Put built-in 'tables' directly into icode,
* and put initialize code into '__autorun__' */
if ((ret = mlua_icg_add_built_in_tables(err, \
context->icode, \
context->res_id, \
new_icg_fcb_block_autorun, \
context->stdlibs, \
instrument_number_insert_point_built_in_proc,
&instrument_count_built_in_proc)) != 0)
{ goto fail; }
/* '__autorun__' subroutine */
if ((ret = mlua_icodegen_special( \
err, \
context->icode, \
context->res_id, \
context->icg_fcb_block_list, new_icg_fcb_block_autorun, \
VM_PREDEF_MODULE_AUTORUN, VM_PREDEF_MODULE_AUTORUN_LEN)) != 0)
{ goto fail; }
new_icg_fcb_block_autorun = NULL;
/* Append export section item */
if ((ret = multiply_resource_get_id( \
err, \
context->icode, \
context->res_id, \
&id, \
VM_PREDEF_MODULE_AUTORUN, \
VM_PREDEF_MODULE_AUTORUN_LEN)) != 0)
{ goto fail; }
new_export_section_item->name = id;
goto done;
fail:
if (new_icg_fcb_block_autorun != NULL) mlua_icg_fcb_block_destroy(new_icg_fcb_block_autorun);
done:
if (new_export_section_item != NULL) multiple_ir_export_section_item_destroy(new_export_section_item);
if (new_map_offset_label_list != NULL) mlua_map_offset_label_list_destroy(new_map_offset_label_list);
return ret;
}
int mlua_irgen(struct multiple_error *err, \
struct multiple_ir **icode_out, \
struct mlua_ast_program *program, \
int verbose)
{
int ret = 0;
struct mlua_icg_context context;
struct mlua_icg_fcb_block_list *new_icg_fcb_block_list = NULL;
struct multiple_ir *new_icode = NULL;
struct multiply_resource_id_pool *new_res_id = NULL;
struct mlua_icg_customizable_built_in_procedure_list *new_customizable_built_in_procedure_list = NULL;
struct multiply_offset_item_pack_stack *new_offset_item_pack_stack = NULL;
struct mlua_icg_stdlib_table_list *new_table_list = NULL;
(void)verbose;
if ((new_customizable_built_in_procedure_list = mlua_icg_customizable_built_in_procedure_list_new()) == NULL)
{ MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; }
if ((new_icg_fcb_block_list = mlua_icg_fcb_block_list_new()) == NULL)
{ MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; }
if ((new_offset_item_pack_stack = multiply_offset_item_pack_stack_new()) == NULL)
{ MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; }
if ((new_table_list = mlua_icg_stdlib_table_list_new()) == NULL)
{ MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; }
if ((new_icode = multiple_ir_new()) == NULL)
{ MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; }
if ((new_res_id = multiply_resource_id_pool_new()) == NULL)
{ MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; }
mlua_icg_context_init(&context);
context.icg_fcb_block_list = new_icg_fcb_block_list;
context.icode = new_icode;
context.res_id = new_res_id;
context.customizable_built_in_procedure_list = new_customizable_built_in_procedure_list;
context.offset_item_pack_stack = new_offset_item_pack_stack;
context.stdlibs = new_table_list;
/* Generating icode for '__init__' */
if ((ret = mlua_icodegen_program(err, \
&context, \
program)) != 0)
{ goto fail; }
/* Merge blocks */
if ((ret = mlua_icodegen_merge_blocks(err, \
&context)) != 0)
{ goto fail; }
*icode_out = new_icode;
ret = 0;
goto done;
fail:
if (new_icode != NULL) multiple_ir_destroy(new_icode);
done:
if (new_res_id != NULL) multiply_resource_id_pool_destroy(new_res_id);
if (new_icg_fcb_block_list != NULL) mlua_icg_fcb_block_list_destroy(new_icg_fcb_block_list);
if (new_customizable_built_in_procedure_list != NULL) \
{ mlua_icg_customizable_built_in_procedure_list_destroy(new_customizable_built_in_procedure_list); }
if (new_offset_item_pack_stack != NULL)
{ multiply_offset_item_pack_stack_destroy(new_offset_item_pack_stack); }
if (new_table_list != NULL)
{ mlua_icg_stdlib_table_list_destroy(new_table_list); }
return ret;
}
|
zooxyt/lua
|
mlua_icg.c
|
C
|
gpl-3.0
| 15,534
|
/**
******************************************************************************
* @file Examples_LL/USART/USART_Communication_TxRx_DMA/Src/main.c
* @author MCD Application Team
* @brief This example describes how to send/receive bytes over USART IP using
* the STM32F0xx USART LL API in DMA mode.
* Peripheral initialization done using LL unitary services functions.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/** @addtogroup STM32F0xx_LL_Examples
* @{
*/
/** @addtogroup USART_Communication_TxRx_DMA
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
__IO uint8_t ubButtonPress = 0;
__IO uint8_t ubSend = 0;
/* Buffer used for transmission */
const uint8_t aTxBuffer[] = "STM32F0xx USART LL API Example : TX/RX in DMA mode\r\nConfiguration UART 115200 bps, 8 data bit/1 stop bit/No parity/No HW flow control\r\nPlease enter 'END' string ...\r\n";
uint8_t ubNbDataToTransmit = sizeof(aTxBuffer);
__IO uint8_t ubTransmissionComplete = 0;
/* Buffer used for reception */
const uint8_t aStringToReceive[] = "END";
uint8_t ubNbDataToReceive = sizeof(aStringToReceive) - 1;
uint8_t aRxBuffer[sizeof(aStringToReceive) - 1];
__IO uint8_t ubReceptionComplete = 0;
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
void Configure_DMA(void);
void Configure_USART(void);
void StartTransfers(void);
void LED_Init(void);
void LED_On(void);
void LED_Blinking(uint32_t Period);
void LED_Off(void);
void UserButton_Init(void);
void WaitForUserButtonPress(void);
void WaitAndCheckEndOfTransfer(void);
uint8_t Buffercmp8(uint8_t* pBuffer1, uint8_t* pBuffer2, uint8_t BufferLength);
/* Private functions ---------------------------------------------------------*/
/**
* @brief Main program
* @param None
* @retval None
*/
int main(void)
{
/* Configure the system clock to 48 MHz */
SystemClock_Config();
/* Initialize LED2 */
LED_Init();
/* Initialize button in EXTI mode */
UserButton_Init();
/* Configure USARTx (USART IP configuration and related GPIO initialization) */
Configure_USART();
/* Configure DMA channels for USART instance */
Configure_DMA();
/* Wait for User push-button press to start transfer */
WaitForUserButtonPress();
/* Initiate DMA transfers */
StartTransfers();
/* Wait for the end of the transfer and check received data */
WaitAndCheckEndOfTransfer();
/* Infinite loop */
while (1)
{
}
}
/**
* @brief This function configures the DMA Channels for TX and RX transfers
* @note This function is used to :
* -1- Enable DMA1 clock
* -2- Configure NVIC for DMA transfer complete/error interrupts
* -3- Configure DMA TX channel functional parameters
* -4- Configure DMA RX channel functional parameters
* -5- Enable transfer complete/error interrupts
* @param None
* @retval None
*/
void Configure_DMA(void)
{
/* DMA1 used for USART2 Transmission and Reception
*/
/* (1) Enable the clock of DMA1 */
LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_DMA1);
/* (2) Configure NVIC for DMA transfer complete/error interrupts */
NVIC_SetPriority(DMA1_Channel4_5_6_7_IRQn, 0);
NVIC_EnableIRQ(DMA1_Channel4_5_6_7_IRQn);
/* (3) Configure the DMA functional parameters for transmission */
LL_DMA_ConfigTransfer(DMA1, LL_DMA_CHANNEL_4,
LL_DMA_DIRECTION_MEMORY_TO_PERIPH |
LL_DMA_PRIORITY_HIGH |
LL_DMA_MODE_NORMAL |
LL_DMA_PERIPH_NOINCREMENT |
LL_DMA_MEMORY_INCREMENT |
LL_DMA_PDATAALIGN_BYTE |
LL_DMA_MDATAALIGN_BYTE);
LL_DMA_ConfigAddresses(DMA1, LL_DMA_CHANNEL_4,
(uint32_t)aTxBuffer,
LL_USART_DMA_GetRegAddr(USART2, LL_USART_DMA_REG_DATA_TRANSMIT),
LL_DMA_GetDataTransferDirection(DMA1, LL_DMA_CHANNEL_4));
LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_4, ubNbDataToTransmit);
/* (4) Configure the DMA functional parameters for reception */
LL_DMA_ConfigTransfer(DMA1, LL_DMA_CHANNEL_5,
LL_DMA_DIRECTION_PERIPH_TO_MEMORY |
LL_DMA_PRIORITY_HIGH |
LL_DMA_MODE_NORMAL |
LL_DMA_PERIPH_NOINCREMENT |
LL_DMA_MEMORY_INCREMENT |
LL_DMA_PDATAALIGN_BYTE |
LL_DMA_MDATAALIGN_BYTE);
LL_DMA_ConfigAddresses(DMA1, LL_DMA_CHANNEL_5,
LL_USART_DMA_GetRegAddr(USART2, LL_USART_DMA_REG_DATA_RECEIVE),
(uint32_t)aRxBuffer,
LL_DMA_GetDataTransferDirection(DMA1, LL_DMA_CHANNEL_5));
LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_5, ubNbDataToReceive);
/* (5) Enable DMA transfer complete/error interrupts */
LL_DMA_EnableIT_TC(DMA1, LL_DMA_CHANNEL_4);
LL_DMA_EnableIT_TE(DMA1, LL_DMA_CHANNEL_4);
LL_DMA_EnableIT_TC(DMA1, LL_DMA_CHANNEL_5);
LL_DMA_EnableIT_TE(DMA1, LL_DMA_CHANNEL_5);
}
/**
* @brief This function configures USARTx Instance.
* @note This function is used to :
* -1- Enable GPIO clock and configures the USART2 pins.
* -2- Enable the USART2 peripheral clock and clock source.
* -3- Configure USART2 functional parameters.
* -4- Enable USART2.
* @note Peripheral configuration is minimal configuration from reset values.
* Thus, some useless LL unitary functions calls below are provided as
* commented examples - setting is default configuration from reset.
* @param None
* @retval None
*/
void Configure_USART(void)
{
/* (1) Enable GPIO clock and configures the USART pins **********************/
/* Enable the peripheral clock of GPIO Port */
LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_GPIOA);
/* Configure Tx Pin as : Alternate function, High Speed, Push pull, Pull up */
LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_2, LL_GPIO_MODE_ALTERNATE);
LL_GPIO_SetAFPin_0_7(GPIOA, LL_GPIO_PIN_2, LL_GPIO_AF_1);
LL_GPIO_SetPinSpeed(GPIOA, LL_GPIO_PIN_2, LL_GPIO_SPEED_FREQ_HIGH);
LL_GPIO_SetPinOutputType(GPIOA, LL_GPIO_PIN_2, LL_GPIO_OUTPUT_PUSHPULL);
LL_GPIO_SetPinPull(GPIOA, LL_GPIO_PIN_2, LL_GPIO_PULL_UP);
/* Configure Rx Pin as : Alternate function, High Speed, Push pull, Pull up */
LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_3, LL_GPIO_MODE_ALTERNATE);
LL_GPIO_SetAFPin_0_7(GPIOA, LL_GPIO_PIN_3, LL_GPIO_AF_1);
LL_GPIO_SetPinSpeed(GPIOA, LL_GPIO_PIN_3, LL_GPIO_SPEED_FREQ_HIGH);
LL_GPIO_SetPinOutputType(GPIOA, LL_GPIO_PIN_3, LL_GPIO_OUTPUT_PUSHPULL);
LL_GPIO_SetPinPull(GPIOA, LL_GPIO_PIN_3, LL_GPIO_PULL_UP);
/* (2) Enable USART2 peripheral clock and clock source ****************/
LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_USART2);
/* Set clock source */
LL_RCC_SetUSARTClockSource(LL_RCC_USART2_CLKSOURCE_PCLK1);
/* (3) Configure USART2 functional parameters ********************************/
/* Disable USART prior modifying configuration registers */
/* Note: Commented as corresponding to Reset value */
// LL_USART_Disable(USART2);
/* TX/RX direction */
LL_USART_SetTransferDirection(USART2, LL_USART_DIRECTION_TX_RX);
/* 8 data bit, 1 start bit, 1 stop bit, no parity */
LL_USART_ConfigCharacter(USART2, LL_USART_DATAWIDTH_8B, LL_USART_PARITY_NONE, LL_USART_STOPBITS_1);
/* No Hardware Flow control */
/* Reset value is LL_USART_HWCONTROL_NONE */
// LL_USART_SetHWFlowCtrl(USART2, LL_USART_HWCONTROL_NONE);
/* Oversampling by 16 */
/* Reset value is LL_USART_OVERSAMPLING_16 */
// LL_USART_SetOverSampling(USART2, LL_USART_OVERSAMPLING_16);
/* Set Baudrate to 115200 using APB frequency set to 48000000 Hz */
/* Frequency available for USART peripheral can also be calculated through LL RCC macro */
/* Ex :
Periphclk = LL_RCC_GetUSARTClockFreq(Instance); or LL_RCC_GetUARTClockFreq(Instance); depending on USART/UART instance
In this example, Peripheral Clock is expected to be equal to 48000000 Hz => equal to SystemCoreClock
*/
LL_USART_SetBaudRate(USART2, SystemCoreClock, LL_USART_OVERSAMPLING_16, 115200);
/* (4) Enable USART2 **********************************************************/
LL_USART_Enable(USART2);
/* Polling USART initialisation */
while((!(LL_USART_IsActiveFlag_TEACK(USART2))) || (!(LL_USART_IsActiveFlag_REACK(USART2))))
{
}
}
/**
* @brief This function initiates TX and RX DMA transfers by enabling DMA channels
* @param None
* @retval None
*/
void StartTransfers(void)
{
/* Enable DMA RX Interrupt */
LL_USART_EnableDMAReq_RX(USART2);
/* Enable DMA TX Interrupt */
LL_USART_EnableDMAReq_TX(USART2);
/* Enable DMA Channel Rx */
LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_5);
/* Enable DMA Channel Tx */
LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_4);
}
/**
* @brief Initialize LED2.
* @param None
* @retval None
*/
void LED_Init(void)
{
/* Enable the LED2 Clock */
LED2_GPIO_CLK_ENABLE();
/* Configure IO in output push-pull mode to drive external LED2 */
LL_GPIO_SetPinMode(LED2_GPIO_PORT, LED2_PIN, LL_GPIO_MODE_OUTPUT);
/* Reset value is LL_GPIO_OUTPUT_PUSHPULL */
//LL_GPIO_SetPinOutputType(LED2_GPIO_PORT, LED2_PIN, LL_GPIO_OUTPUT_PUSHPULL);
/* Reset value is LL_GPIO_SPEED_FREQ_LOW */
//LL_GPIO_SetPinSpeed(LED2_GPIO_PORT, LED2_PIN, LL_GPIO_SPEED_FREQ_LOW);
/* Reset value is LL_GPIO_PULL_NO */
//LL_GPIO_SetPinPull(LED2_GPIO_PORT, LED2_PIN, LL_GPIO_PULL_NO);
}
/**
* @brief Turn-on LED2.
* @param None
* @retval None
*/
void LED_On(void)
{
/* Turn LED2 on */
LL_GPIO_SetOutputPin(LED2_GPIO_PORT, LED2_PIN);
}
/**
* @brief Turn-off LED2.
* @param None
* @retval None
*/
void LED_Off(void)
{
/* Turn LED2 off */
LL_GPIO_ResetOutputPin(LED2_GPIO_PORT, LED2_PIN);
}
/**
* @brief Set LED2 to Blinking mode for an infinite loop (toggle period based on value provided as input parameter).
* @param Period : Period of time (in ms) between each toggling of LED
* This parameter can be user defined values. Pre-defined values used in that example are :
* @arg LED_BLINK_FAST : Fast Blinking
* @arg LED_BLINK_SLOW : Slow Blinking
* @arg LED_BLINK_ERROR : Error specific Blinking
* @retval None
*/
void LED_Blinking(uint32_t Period)
{
/* Toggle LED2 in an infinite loop */
while (1)
{
LL_GPIO_TogglePin(LED2_GPIO_PORT, LED2_PIN);
LL_mDelay(Period);
}
}
/**
* @brief Configures User push-button in GPIO or EXTI Line Mode.
* @param None
* @retval None
*/
void UserButton_Init(void)
{
/* Enable the BUTTON Clock */
USER_BUTTON_GPIO_CLK_ENABLE();
/* Configure GPIO for BUTTON */
LL_GPIO_SetPinMode(USER_BUTTON_GPIO_PORT, USER_BUTTON_PIN, LL_GPIO_MODE_INPUT);
LL_GPIO_SetPinPull(USER_BUTTON_GPIO_PORT, USER_BUTTON_PIN, LL_GPIO_PULL_NO);
/* Connect External Line to the GPIO*/
USER_BUTTON_SYSCFG_SET_EXTI();
/* Enable a rising trigger EXTI_Line4_15 Interrupt */
USER_BUTTON_EXTI_LINE_ENABLE();
USER_BUTTON_EXTI_FALLING_TRIG_ENABLE();
/* Configure NVIC for USER_BUTTON_EXTI_IRQn */
NVIC_SetPriority(USER_BUTTON_EXTI_IRQn, 3);
NVIC_EnableIRQ(USER_BUTTON_EXTI_IRQn);
}
/**
* @brief Wait for User push-button press to start transfer.
* @param None
* @retval None
*/
/* */
void WaitForUserButtonPress(void)
{
while (ubButtonPress == 0)
{
LL_GPIO_TogglePin(LED2_GPIO_PORT, LED2_PIN);
LL_mDelay(LED_BLINK_FAST);
}
/* Ensure that LED2 is turned Off */
LED_Off();
}
/**
* @brief Wait end of transfer and check if received Data are well.
* @param None
* @retval None
*/
void WaitAndCheckEndOfTransfer(void)
{
/* 1 - Wait end of transmission */
while (ubTransmissionComplete != 1)
{
}
/* Disable DMA1 Tx Channel */
LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_4);
/* 2 - Wait end of reception */
while (ubReceptionComplete != 1)
{
}
/* Disable DMA1 Rx Channel */
LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_5);
/* 3 - Compare received string to expected one */
if(Buffercmp8((uint8_t*)aStringToReceive, (uint8_t*)aRxBuffer, ubNbDataToReceive))
{
/* Processing Error */
LED_Blinking(LED_BLINK_ERROR);
}
else
{
/* Turn On Led if data are well received */
LED_On();
}
}
/**
* @brief Compares two 8-bit buffers and returns the comparison result.
* @param pBuffer1: pointer to the source buffer to be compared to.
* @param pBuffer2: pointer to the second source buffer to be compared to the first.
* @param BufferLength: buffer's length.
* @retval 0: Comparison is OK (the two Buffers are identical)
* Value different from 0: Comparison is NOK (Buffers are different)
*/
uint8_t Buffercmp8(uint8_t* pBuffer1, uint8_t* pBuffer2, uint8_t BufferLength)
{
while (BufferLength--)
{
if (*pBuffer1 != *pBuffer2)
{
return 1;
}
pBuffer1++;
pBuffer2++;
}
return 0;
}
/**
* @brief System Clock Configuration
* The system Clock is configured as follow :
* System Clock source = PLL (HSI48)
* SYSCLK(Hz) = 48000000
* HCLK(Hz) = 48000000
* AHB Prescaler = 1
* APB1 Prescaler = 1
* HSI Frequency(Hz) = 48000000
* PREDIV = 2
* PLLMUL = 2
* Flash Latency(WS) = 1
* @param None
* @retval None
*/
void SystemClock_Config(void)
{
/* Set FLASH latency */
LL_FLASH_SetLatency(LL_FLASH_LATENCY_1);
/* Enable HSI48 and wait for activation*/
LL_RCC_HSI48_Enable();
while(LL_RCC_HSI48_IsReady() != 1)
{
};
/* Main PLL configuration and activation */
LL_RCC_PLL_ConfigDomain_SYS(LL_RCC_PLLSOURCE_HSI48, LL_RCC_PLL_MUL_2, LL_RCC_PREDIV_DIV_2);
LL_RCC_PLL_Enable();
while(LL_RCC_PLL_IsReady() != 1)
{
};
/* Sysclk activation on the main PLL */
LL_RCC_SetAHBPrescaler(LL_RCC_SYSCLK_DIV_1);
LL_RCC_SetSysClkSource(LL_RCC_SYS_CLKSOURCE_PLL);
while(LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_PLL)
{
};
/* Set APB1 prescaler */
LL_RCC_SetAPB1Prescaler(LL_RCC_APB1_DIV_1);
/* Set systick to 1ms in using frequency set to 48MHz */
/* This frequency can be calculated through LL RCC macro */
/* ex: __LL_RCC_CALC_PLLCLK_FREQ (HSI48_VALUE, LL_RCC_PLL_MUL_2, LL_RCC_PREDIV_DIV_2) */
LL_Init1msTick(48000000);
/* Update CMSIS variable (which can be updated also through SystemCoreClockUpdate function) */
LL_SetSystemCoreClock(48000000);
}
/******************************************************************************/
/* USER IRQ HANDLER TREATMENT Functions */
/******************************************************************************/
/**
* @brief Function to manage User push-button
* @param None
* @retval None
*/
void UserButton_Callback(void)
{
/* Update User push-button variable : to be checked in waiting loop in main program */
ubButtonPress = 1;
}
/**
* @brief Function called from DMA1 IRQ Handler when Tx transfer is completed
* @param None
* @retval None
*/
void DMA1_TransmitComplete_Callback(void)
{
/* DMA Tx transfer completed */
ubTransmissionComplete = 1;
}
/**
* @brief Function called from DMA1 IRQ Handler when Rx transfer is completed
* @param None
* @retval None
*/
void DMA1_ReceiveComplete_Callback(void)
{
/* DMA Rx transfer completed */
ubReceptionComplete = 1;
}
/**
* @brief Function called in case of error detected in USART IT Handler
* @param None
* @retval None
*/
void USART_TransferError_Callback(void)
{
/* Disable DMA1 Tx Channel */
LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_4);
/* Disable DMA1 Rx Channel */
LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_5);
/* Set LED2 to Blinking mode to indicate error occurs */
LED_Blinking(LED_BLINK_ERROR);
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d", file, line) */
/* Infinite loop */
while (1)
{
}
}
#endif
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
Fdepraetre/Handmouse
|
Software/Handmouse_STM/Lib_DL/STM32Cube_FW_F0_V1.8.0/Projects/STM32F072RB-Nucleo/Examples_LL/USART/USART_Communication_TxRx_DMA/Src/main.c
|
C
|
gpl-3.0
| 19,128
|
/*
* FuchsTracker.c Copyright (C) 1999 Sylvain "Asle" Chipaux
*
* Depacks Fuchs Tracker modules
*
* Modified in 2006,2007,2014 by Claudio Matsuoka
*/
#include <string.h>
#include <stdlib.h>
#include "prowiz.h"
static int depack_fuchs(HIO_HANDLE *in, FILE *out)
{
uint8 *tmp;
uint8 max_pat;
/*int ssize;*/
uint8 data[1080];
unsigned smp_len[16];
unsigned loop_start[16];
unsigned pat_size;
unsigned i;
memset(smp_len, 0, 16 * 4);
memset(loop_start, 0, 16 * 4);
memset(data, 0, 1080);
hio_read(data, 1, 10, in); /* read/write title */
/*ssize =*/ hio_read32b(in); /* read all sample data size */
/* read/write sample sizes */
for (i = 0; i < 16; i++) {
smp_len[i] = hio_read16b(in);
data[42 + i * 30] = smp_len[i] >> 9;
data[43 + i * 30] = smp_len[i] >> 1;
}
/* read/write volumes */
for (i = 0; i < 16; i++) {
data[45 + i * 30] = hio_read16b(in);
}
/* read/write loop start */
for (i = 0; i < 16; i++) {
loop_start[i] = hio_read16b(in);
data[46 + i * 30] = loop_start[i] >> 1;
}
/* write replen */
for (i = 0; i < 16; i++) {
int loop_size;
loop_size = smp_len[i] - loop_start[i];
if (loop_size == 0 || loop_start[i] == 0) {
data[49 + i * 30] = 1;
} else {
data[48 + i * 30] = loop_size >> 9;
data[49 + i * 30] = loop_size >> 1;
}
}
/* fill replens up to 31st sample wiz $0001 */
for (i = 16; i < 31; i++) {
data[49 + i * 30] = 1;
}
/* that's it for the samples ! */
/* now, the pattern list */
/* read number of pattern to play */
data[950] = hio_read16b(in);
data[951] = 0x7f;
/* read/write pattern list */
for (max_pat = i = 0; i < 40; i++) {
uint8 pat = hio_read16b(in);
data[952 + i] = pat;
if (pat > max_pat) {
max_pat = pat;
}
}
/* write ptk's ID */
if (fwrite(data, 1, 1080, out) != 1080) {
return -1;
}
write32b(out, PW_MOD_MAGIC);
/* now, the pattern data */
/* bypass the "SONG" ID */
hio_read32b(in);
/* read pattern data size */
pat_size = hio_read32b(in);
/* Sanity check */
if (pat_size <= 0 || pat_size > 0x20000)
return -1;
/* read pattern data */
tmp = (uint8 *)malloc(pat_size);
if (hio_read(tmp, 1, pat_size, in) != pat_size) {
free(tmp);
return -1;
}
/* convert shits */
for (i = 0; i < pat_size; i += 4) {
/* convert fx C arg back to hex value */
if ((tmp[i + 2] & 0x0f) == 0x0c) {
int x = tmp[i + 3];
tmp[i + 3] = 10 * (x >> 4) + (x & 0xf);
}
}
/* write pattern data */
fwrite(tmp, pat_size, 1, out);
free(tmp);
/* read/write sample data */
hio_read32b(in); /* bypass "INST" Id */
for (i = 0; i < 16; i++) {
if (smp_len[i] != 0)
pw_move_data(out, in, smp_len[i]);
}
return 0;
}
static int test_fuchs (uint8 *data, char *t, int s)
{
int i;
int ssize, hdr_ssize;
#if 0
/* test #1 */
if (i < 192) {
Test = BAD;
return;
}
start = i - 192;
#endif
if (readmem32b(data + 192) != 0x534f4e47) /* SONG */
return -1;
/* all sample size */
hdr_ssize = readmem32b(data + 10);
if (hdr_ssize <= 2 || hdr_ssize >= 65535 * 16)
return -1;
/* samples descriptions */
ssize = 0;
for (i = 0; i < 16; i++) {
uint8 *d = data + i * 2;
int len = readmem16b(d + 14);
int start = readmem16b(d + 78);
/* volumes */
if (d[46] > 0x40)
return -1;
if (len < start)
return -1;
ssize += len;
}
if (ssize <= 2 || ssize > hdr_ssize)
return -1;
/* get highest pattern number in pattern list */
/*max_pat = 0;*/
for (i = 0; i < 40; i++) {
int pat = data[i * 2 + 113];
if (pat > 40)
return -1;
/*if (pat > max_pat)
max_pat = pat;*/
}
#if 0
/* input file not long enough ? */
max_pat++;
max_pat *= 1024;
PW_REQUEST_DATA (s, k + 200);
#endif
pw_read_title(NULL, t, 0);
return 0;
}
const struct pw_format pw_fchs = {
"Fuchs Tracker",
test_fuchs,
depack_fuchs
};
|
DodgeeSoftware/OpenALWrapper
|
_dependencies/libxmp-4.4.0/src/loaders/prowizard/fuchs.c
|
C
|
gpl-3.0
| 3,794
|
/**
******************************************************************************
* @file I2C/I2C_TwoBoards_ComPolling/Src/stm32f4xx_it.c
* @author MCD Application Team
* @version V1.2.7
* @date 17-February-2017
* @brief Main Interrupt Service Routines.
* This file provides template for all exceptions handler and
* peripherals interrupt service routine.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2017 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32f4xx_it.h"
/** @addtogroup STM32F4xx_HAL_Examples
* @{
*/
/** @addtogroup I2C_TwoBoards_ComPolling
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* I2C handler declared in "main.c" file */
extern I2C_HandleTypeDef hi2c;
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/******************************************************************************/
/* Cortex-M4 Processor Exceptions Handlers */
/******************************************************************************/
/**
* @brief This function handles NMI exception.
* @param None
* @retval None
*/
void NMI_Handler(void)
{
}
/**
* @brief This function handles Hard Fault exception.
* @param None
* @retval None
*/
void HardFault_Handler(void)
{
/* Go to infinite loop when Hard Fault exception occurs */
while (1)
{
}
}
/**
* @brief This function handles Memory Manage exception.
* @param None
* @retval None
*/
void MemManage_Handler(void)
{
/* Go to infinite loop when Memory Manage exception occurs */
while (1)
{
}
}
/**
* @brief This function handles Bus Fault exception.
* @param None
* @retval None
*/
void BusFault_Handler(void)
{
/* Go to infinite loop when Bus Fault exception occurs */
while (1)
{
}
}
/**
* @brief This function handles Usage Fault exception.
* @param None
* @retval None
*/
void UsageFault_Handler(void)
{
/* Go to infinite loop when Usage Fault exception occurs */
while (1)
{
}
}
/**
* @brief This function handles SVCall exception.
* @param None
* @retval None
*/
void SVC_Handler(void)
{
}
/**
* @brief This function handles Debug Monitor exception.
* @param None
* @retval None
*/
void DebugMon_Handler(void)
{
}
/**
* @brief This function handles PendSVC exception.
* @param None
* @retval None
*/
void PendSV_Handler(void)
{
}
/**
* @brief This function handles SysTick Handler.
* @param None
* @retval None
*/
void SysTick_Handler(void)
{
HAL_IncTick();
}
/******************************************************************************/
/* STM32F4xx Peripherals Interrupt Handlers */
/* Add here the Interrupt Handler for the used peripheral(s) (PPP), for the */
/* available peripheral interrupt handler's name please refer to the startup */
/* file (startup_stm32f4xx.s). */
/******************************************************************************/
/**
* @brief This function handles PPP interrupt request.
* @param None
* @retval None
*/
/*void PPP_IRQHandler(void)
{
}*/
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
TRothfelder/Multicopter
|
libs/STM32Cube_FW_F4_V1.16.0/Projects/STM32F4-Discovery/Examples/I2C/I2C_TwoBoards_ComPolling/Src/stm32f4xx_it.c
|
C
|
gpl-3.0
| 5,686
|
/*
* sound/oss/ad1848.c
*
* The low level driver for the AD1848/CS4248 codec chip which
* is used for example in the MS Sound System.
*
* The CS4231 which is used in the GUS MAX and some other cards is
* upwards compatible with AD1848 and this driver is able to drive it.
*
* CS4231A and AD1845 are upward compatible with CS4231. However
* the new features of these chips are different.
*
* CS4232 is a PnP audio chip which contains a CS4231A (and SB, MPU).
* CS4232A is an improved version of CS4232.
*
*
*
* Copyright (C) by Hannu Savolainen 1993-1997
*
* OSS/Free for Linux is distributed under the GNU GENERAL PUBLIC LICENSE (GPL)
* Version 2 (June 1991). See the "COPYING" file distributed with this software
* for more info.
*
*
* Thomas Sailer : ioctl code reworked (vmalloc/vfree removed)
* general sleep/wakeup clean up.
* Alan Cox : reformatted. Fixed SMP bugs. Moved to kernel alloc/free
* of irqs. Use dev_id.
* Christoph Hellwig : adapted to module_init/module_exit
* Aki Laukkanen : added power management support
* Arnaldo C. de Melo : added missing restore_flags in ad1848_resume
* Miguel Freitas : added ISA PnP support
* Alan Cox : Added CS4236->4239 identification
* Daniel T. Cobra : Alernate config/mixer for later chips
* Alan Cox : Merged chip idents and config code
*
* TODO
* APM save restore assist code on IBM thinkpad
*
* Status:
* Tested. Believed fully functional.
*/
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/stddef.h>
#include <linux/slab.h>
#include <linux/isapnp.h>
#include <linux/pnp.h>
#include <linux/spinlock.h>
#include "sound_config.h"
#include "ad1848.h"
#include "ad1848_mixer.h"
typedef struct
{
spinlock_t lock;
int base;
int irq;
int dma1, dma2;
int dual_dma; /* 1, when two DMA channels allocated */
int subtype;
unsigned char MCE_bit;
unsigned char saved_regs[64]; /* Includes extended register space */
int debug_flag;
int audio_flags;
int record_dev, playback_dev;
int xfer_count;
int audio_mode;
int open_mode;
int intr_active;
char *chip_name, *name;
int model;
#define MD_1848 1
#define MD_4231 2
#define MD_4231A 3
#define MD_1845 4
#define MD_4232 5
#define MD_C930 6
#define MD_IWAVE 7
#define MD_4235 8 /* Crystal Audio CS4235 */
#define MD_1845_SSCAPE 9 /* Ensoniq Soundscape PNP*/
#define MD_4236 10 /* 4236 and higher */
#define MD_42xB 11 /* CS 42xB */
#define MD_4239 12 /* CS4239 */
/* Mixer parameters */
int recmask;
int supported_devices, orig_devices;
int supported_rec_devices, orig_rec_devices;
int *levels;
short mixer_reroute[32];
int dev_no;
volatile unsigned long timer_ticks;
int timer_running;
int irq_ok;
mixer_ents *mix_devices;
int mixer_output_port;
} ad1848_info;
typedef struct ad1848_port_info
{
int open_mode;
int speed;
unsigned char speed_bits;
int channels;
int audio_format;
unsigned char format_bits;
}
ad1848_port_info;
static struct address_info cfg;
static int nr_ad1848_devs;
static bool deskpro_xl;
static bool deskpro_m;
static bool soundpro;
static volatile signed char irq2dev[17] =
{
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1
};
#ifndef EXCLUDE_TIMERS
static int timer_installed = -1;
#endif
static int loaded;
static int ad_format_mask[13 /*devc->model */ ] =
{
0,
AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW,
AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM,
AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM,
AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW, /* AD1845 */
AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM,
AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM,
AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM,
AFMT_U8 | AFMT_S16_LE /* CS4235 */,
AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW /* Ensoniq Soundscape*/,
AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM,
AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM,
AFMT_U8 | AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW | AFMT_S16_BE | AFMT_IMA_ADPCM
};
static ad1848_info adev_info[MAX_AUDIO_DEV];
#define io_Index_Addr(d) ((d)->base)
#define io_Indexed_Data(d) ((d)->base+1)
#define io_Status(d) ((d)->base+2)
#define io_Polled_IO(d) ((d)->base+3)
static struct
{
unsigned char flags;
#define CAP_F_TIMER 0x01
} capabilities [10 /*devc->model */ ] =
{
{0}
, {0} /* MD_1848 */
, {CAP_F_TIMER} /* MD_4231 */
, {CAP_F_TIMER} /* MD_4231A */
, {CAP_F_TIMER} /* MD_1845 */
, {CAP_F_TIMER} /* MD_4232 */
, {0} /* MD_C930 */
, {CAP_F_TIMER} /* MD_IWAVE */
, {0} /* MD_4235 */
, {CAP_F_TIMER} /* MD_1845_SSCAPE */
};
#ifdef CONFIG_PNP
static int isapnp = 1;
static int isapnpjump;
static bool reverse;
static int audio_activated;
#else
static int isapnp;
#endif
static int ad1848_open(int dev, int mode);
static void ad1848_close(int dev);
static void ad1848_output_block(int dev, unsigned long buf, int count, int intrflag);
static void ad1848_start_input(int dev, unsigned long buf, int count, int intrflag);
static int ad1848_prepare_for_output(int dev, int bsize, int bcount);
static int ad1848_prepare_for_input(int dev, int bsize, int bcount);
static void ad1848_halt(int dev);
static void ad1848_halt_input(int dev);
static void ad1848_halt_output(int dev);
static void ad1848_trigger(int dev, int bits);
static irqreturn_t adintr(int irq, void *dev_id);
#ifndef EXCLUDE_TIMERS
static int ad1848_tmr_install(int dev);
static void ad1848_tmr_reprogram(int dev);
#endif
static int ad_read(ad1848_info *devc, int reg)
{
int x;
int timeout = 900000;
while (timeout > 0 && inb(devc->base) == 0x80) /*Are we initializing */
{
timeout--;
}
if (reg < 32)
{
outb(((unsigned char) (reg & 0xff) | devc->MCE_bit), io_Index_Addr(devc));
x = inb(io_Indexed_Data(devc));
}
else
{
int xreg, xra;
xreg = (reg & 0xff) - 32;
xra = (((xreg & 0x0f) << 4) & 0xf0) | 0x08 | ((xreg & 0x10) >> 2);
outb(((unsigned char) (23 & 0xff) | devc->MCE_bit), io_Index_Addr(devc));
outb(((unsigned char) (xra & 0xff)), io_Indexed_Data(devc));
x = inb(io_Indexed_Data(devc));
}
return x;
}
static void ad_write(ad1848_info *devc, int reg, int data)
{
int timeout = 900000;
while (timeout > 0 && inb(devc->base) == 0x80) /* Are we initializing */
{
timeout--;
}
if (reg < 32)
{
outb(((unsigned char) (reg & 0xff) | devc->MCE_bit), io_Index_Addr(devc));
outb(((unsigned char) (data & 0xff)), io_Indexed_Data(devc));
}
else
{
int xreg, xra;
xreg = (reg & 0xff) - 32;
xra = (((xreg & 0x0f) << 4) & 0xf0) | 0x08 | ((xreg & 0x10) >> 2);
outb(((unsigned char) (23 & 0xff) | devc->MCE_bit), io_Index_Addr(devc));
outb(((unsigned char) (xra & 0xff)), io_Indexed_Data(devc));
outb((unsigned char) (data & 0xff), io_Indexed_Data(devc));
}
}
static void wait_for_calibration(ad1848_info *devc)
{
int timeout;
/*
* Wait until the auto calibration process has finished.
*
* 1) Wait until the chip becomes ready (reads don't return 0x80).
* 2) Wait until the ACI bit of I11 gets on and then off.
*/
timeout = 100000;
while (timeout > 0 && inb(devc->base) == 0x80)
{
timeout--;
}
if (inb(devc->base) & 0x80)
{
printk(KERN_WARNING "ad1848: Auto calibration timed out(1).\n");
}
timeout = 100;
while (timeout > 0 && !(ad_read(devc, 11) & 0x20))
{
timeout--;
}
if (!(ad_read(devc, 11) & 0x20))
{
return;
}
timeout = 80000;
while (timeout > 0 && (ad_read(devc, 11) & 0x20))
{
timeout--;
}
if (ad_read(devc, 11) & 0x20)
if ((devc->model != MD_1845) && (devc->model != MD_1845_SSCAPE))
{
printk(KERN_WARNING "ad1848: Auto calibration timed out(3).\n");
}
}
static void ad_mute(ad1848_info *devc)
{
int i;
unsigned char prev;
/*
* Save old register settings and mute output channels
*/
for (i = 6; i < 8; i++)
{
prev = devc->saved_regs[i] = ad_read(devc, i);
}
}
static void ad_unmute(ad1848_info *devc)
{
}
static void ad_enter_MCE(ad1848_info *devc)
{
int timeout = 1000;
unsigned short prev;
while (timeout > 0 && inb(devc->base) == 0x80) /*Are we initializing */
{
timeout--;
}
devc->MCE_bit = 0x40;
prev = inb(io_Index_Addr(devc));
if (prev & 0x40)
{
return;
}
outb((devc->MCE_bit), io_Index_Addr(devc));
}
static void ad_leave_MCE(ad1848_info *devc)
{
unsigned char prev, acal;
int timeout = 1000;
while (timeout > 0 && inb(devc->base) == 0x80) /*Are we initializing */
{
timeout--;
}
acal = ad_read(devc, 9);
devc->MCE_bit = 0x00;
prev = inb(io_Index_Addr(devc));
outb((0x00), io_Index_Addr(devc)); /* Clear the MCE bit */
if ((prev & 0x40) == 0) /* Not in MCE mode */
{
return;
}
outb((0x00), io_Index_Addr(devc)); /* Clear the MCE bit */
if (acal & 0x08) /* Auto calibration is enabled */
{
wait_for_calibration(devc);
}
}
static int ad1848_set_recmask(ad1848_info *devc, int mask)
{
unsigned char recdev;
int i, n;
unsigned long flags;
mask &= devc->supported_rec_devices;
/* Rename the mixer bits if necessary */
for (i = 0; i < 32; i++)
{
if (devc->mixer_reroute[i] != i)
{
if (mask & (1 << i))
{
mask &= ~(1 << i);
mask |= (1 << devc->mixer_reroute[i]);
}
}
}
n = 0;
for (i = 0; i < 32; i++) /* Count selected device bits */
if (mask & (1 << i))
{
n++;
}
spin_lock_irqsave(&devc->lock, flags);
if (!soundpro)
{
if (n == 0)
{
mask = SOUND_MASK_MIC;
}
else if (n != 1) /* Too many devices selected */
{
mask &= ~devc->recmask; /* Filter out active settings */
n = 0;
for (i = 0; i < 32; i++) /* Count selected device bits */
if (mask & (1 << i))
{
n++;
}
if (n != 1)
{
mask = SOUND_MASK_MIC;
}
}
switch (mask)
{
case SOUND_MASK_MIC:
recdev = 2;
break;
case SOUND_MASK_LINE:
case SOUND_MASK_LINE3:
recdev = 0;
break;
case SOUND_MASK_CD:
case SOUND_MASK_LINE1:
recdev = 1;
break;
case SOUND_MASK_IMIX:
recdev = 3;
break;
default:
mask = SOUND_MASK_MIC;
recdev = 2;
}
recdev <<= 6;
ad_write(devc, 0, (ad_read(devc, 0) & 0x3f) | recdev);
ad_write(devc, 1, (ad_read(devc, 1) & 0x3f) | recdev);
}
else /* soundpro */
{
unsigned char val;
int set_rec_bit;
int j;
for (i = 0; i < 32; i++) /* For each bit */
{
if ((devc->supported_rec_devices & (1 << i)) == 0)
{
continue; /* Device not supported */
}
for (j = LEFT_CHN; j <= RIGHT_CHN; j++)
{
if (devc->mix_devices[i][j].nbits == 0) /* Inexistent channel */
{
continue;
}
/*
* This is tricky:
* set_rec_bit becomes 1 if the corresponding bit in mask is set
* then it gets flipped if the polarity is inverse
*/
set_rec_bit = ((mask & (1 << i)) != 0) ^ devc->mix_devices[i][j].recpol;
val = ad_read(devc, devc->mix_devices[i][j].recreg);
val &= ~(1 << devc->mix_devices[i][j].recpos);
val |= (set_rec_bit << devc->mix_devices[i][j].recpos);
ad_write(devc, devc->mix_devices[i][j].recreg, val);
}
}
}
spin_unlock_irqrestore(&devc->lock, flags);
/* Rename the mixer bits back if necessary */
for (i = 0; i < 32; i++)
{
if (devc->mixer_reroute[i] != i)
{
if (mask & (1 << devc->mixer_reroute[i]))
{
mask &= ~(1 << devc->mixer_reroute[i]);
mask |= (1 << i);
}
}
}
devc->recmask = mask;
return mask;
}
static void oss_change_bits(ad1848_info *devc, unsigned char *regval,
unsigned char *muteval, int dev, int chn, int newval)
{
unsigned char mask;
int shift;
int mute;
int mutemask;
int set_mute_bit;
set_mute_bit = (newval == 0) ^ devc->mix_devices[dev][chn].mutepol;
if (devc->mix_devices[dev][chn].polarity == 1) /* Reverse */
{
newval = 100 - newval;
}
mask = (1 << devc->mix_devices[dev][chn].nbits) - 1;
shift = devc->mix_devices[dev][chn].bitpos;
if (devc->mix_devices[dev][chn].mutepos == 8)
{
/* if there is no mute bit */
mute = 0; /* No mute bit; do nothing special */
mutemask = ~0; /* No mute bit; do nothing special */
}
else
{
mute = (set_mute_bit << devc->mix_devices[dev][chn].mutepos);
mutemask = ~(1 << devc->mix_devices[dev][chn].mutepos);
}
newval = (int) ((newval * mask) + 50) / 100; /* Scale it */
*regval &= ~(mask << shift); /* Clear bits */
*regval |= (newval & mask) << shift; /* Set new value */
*muteval &= mutemask;
*muteval |= mute;
}
static int ad1848_mixer_get(ad1848_info *devc, int dev)
{
if (!((1 << dev) & devc->supported_devices))
{
return -EINVAL;
}
dev = devc->mixer_reroute[dev];
return devc->levels[dev];
}
static void ad1848_mixer_set_channel(ad1848_info *devc, int dev, int value, int channel)
{
int regoffs, muteregoffs;
unsigned char val, muteval;
unsigned long flags;
regoffs = devc->mix_devices[dev][channel].regno;
muteregoffs = devc->mix_devices[dev][channel].mutereg;
val = ad_read(devc, regoffs);
if (muteregoffs != regoffs)
{
muteval = ad_read(devc, muteregoffs);
oss_change_bits(devc, &val, &muteval, dev, channel, value);
}
else
{
oss_change_bits(devc, &val, &val, dev, channel, value);
}
spin_lock_irqsave(&devc->lock, flags);
ad_write(devc, regoffs, val);
devc->saved_regs[regoffs] = val;
if (muteregoffs != regoffs)
{
ad_write(devc, muteregoffs, muteval);
devc->saved_regs[muteregoffs] = muteval;
}
spin_unlock_irqrestore(&devc->lock, flags);
}
static int ad1848_mixer_set(ad1848_info *devc, int dev, int value)
{
int left = value & 0x000000ff;
int right = (value & 0x0000ff00) >> 8;
int retvol;
if (dev > 31)
{
return -EINVAL;
}
if (!(devc->supported_devices & (1 << dev)))
{
return -EINVAL;
}
dev = devc->mixer_reroute[dev];
if (devc->mix_devices[dev][LEFT_CHN].nbits == 0)
{
return -EINVAL;
}
if (left > 100)
{
left = 100;
}
if (right > 100)
{
right = 100;
}
if (devc->mix_devices[dev][RIGHT_CHN].nbits == 0) /* Mono control */
{
right = left;
}
retvol = left | (right << 8);
/* Scale volumes */
left = mix_cvt[left];
right = mix_cvt[right];
devc->levels[dev] = retvol;
/*
* Set the left channel
*/
ad1848_mixer_set_channel(devc, dev, left, LEFT_CHN);
/*
* Set the right channel
*/
if (devc->mix_devices[dev][RIGHT_CHN].nbits == 0)
{
goto out;
}
ad1848_mixer_set_channel(devc, dev, right, RIGHT_CHN);
out:
return retvol;
}
static void ad1848_mixer_reset(ad1848_info *devc)
{
int i;
char name[32];
unsigned long flags;
devc->mix_devices = &(ad1848_mix_devices[0]);
sprintf(name, "%s_%d", devc->chip_name, nr_ad1848_devs);
for (i = 0; i < 32; i++)
{
devc->mixer_reroute[i] = i;
}
devc->supported_rec_devices = MODE1_REC_DEVICES;
switch (devc->model)
{
case MD_4231:
case MD_4231A:
case MD_1845:
case MD_1845_SSCAPE:
devc->supported_devices = MODE2_MIXER_DEVICES;
break;
case MD_C930:
devc->supported_devices = C930_MIXER_DEVICES;
devc->mix_devices = &(c930_mix_devices[0]);
break;
case MD_IWAVE:
devc->supported_devices = MODE3_MIXER_DEVICES;
devc->mix_devices = &(iwave_mix_devices[0]);
break;
case MD_42xB:
case MD_4239:
devc->mix_devices = &(cs42xb_mix_devices[0]);
devc->supported_devices = MODE3_MIXER_DEVICES;
break;
case MD_4232:
case MD_4235:
case MD_4236:
devc->supported_devices = MODE3_MIXER_DEVICES;
break;
case MD_1848:
if (soundpro)
{
devc->supported_devices = SPRO_MIXER_DEVICES;
devc->supported_rec_devices = SPRO_REC_DEVICES;
devc->mix_devices = &(spro_mix_devices[0]);
break;
}
default:
devc->supported_devices = MODE1_MIXER_DEVICES;
}
devc->orig_devices = devc->supported_devices;
devc->orig_rec_devices = devc->supported_rec_devices;
devc->levels = load_mixer_volumes(name, default_mixer_levels, 1);
for (i = 0; i < SOUND_MIXER_NRDEVICES; i++)
{
if (devc->supported_devices & (1 << i))
{
ad1848_mixer_set(devc, i, devc->levels[i]);
}
}
ad1848_set_recmask(devc, SOUND_MASK_MIC);
devc->mixer_output_port = devc->levels[31] | AUDIO_HEADPHONE | AUDIO_LINE_OUT;
spin_lock_irqsave(&devc->lock, flags);
if (!soundpro)
{
if (devc->mixer_output_port & AUDIO_SPEAKER)
{
ad_write(devc, 26, ad_read(devc, 26) & ~0x40); /* Unmute mono out */
}
else
{
ad_write(devc, 26, ad_read(devc, 26) | 0x40); /* Mute mono out */
}
}
else
{
/*
* From the "wouldn't it be nice if the mixer API had (better)
* support for custom stuff" category
*/
/* Enable surround mode and SB16 mixer */
ad_write(devc, 16, 0x60);
}
spin_unlock_irqrestore(&devc->lock, flags);
}
static int ad1848_mixer_ioctl(int dev, unsigned int cmd, void __user *arg)
{
ad1848_info *devc = mixer_devs[dev]->devc;
int val;
if (cmd == SOUND_MIXER_PRIVATE1)
{
if (get_user(val, (int __user *)arg))
{
return -EFAULT;
}
if (val != 0xffff)
{
unsigned long flags;
val &= (AUDIO_SPEAKER | AUDIO_HEADPHONE | AUDIO_LINE_OUT);
devc->mixer_output_port = val;
val |= AUDIO_HEADPHONE | AUDIO_LINE_OUT; /* Always on */
devc->mixer_output_port = val;
spin_lock_irqsave(&devc->lock, flags);
if (val & AUDIO_SPEAKER)
{
ad_write(devc, 26, ad_read(devc, 26) & ~0x40); /* Unmute mono out */
}
else
{
ad_write(devc, 26, ad_read(devc, 26) | 0x40); /* Mute mono out */
}
spin_unlock_irqrestore(&devc->lock, flags);
}
val = devc->mixer_output_port;
return put_user(val, (int __user *)arg);
}
if (cmd == SOUND_MIXER_PRIVATE2)
{
if (get_user(val, (int __user *)arg))
{
return -EFAULT;
}
return (ad1848_control(AD1848_MIXER_REROUTE, val));
}
if (((cmd >> 8) & 0xff) == 'M')
{
if (_SIOC_DIR(cmd) & _SIOC_WRITE)
{
switch (cmd & 0xff)
{
case SOUND_MIXER_RECSRC:
if (get_user(val, (int __user *)arg))
{
return -EFAULT;
}
val = ad1848_set_recmask(devc, val);
break;
default:
if (get_user(val, (int __user *)arg))
{
return -EFAULT;
}
val = ad1848_mixer_set(devc, cmd & 0xff, val);
break;
}
return put_user(val, (int __user *)arg);
}
else
{
switch (cmd & 0xff)
{
/*
* Return parameters
*/
case SOUND_MIXER_RECSRC:
val = devc->recmask;
break;
case SOUND_MIXER_DEVMASK:
val = devc->supported_devices;
break;
case SOUND_MIXER_STEREODEVS:
val = devc->supported_devices;
if (devc->model != MD_C930)
{
val &= ~(SOUND_MASK_SPEAKER | SOUND_MASK_IMIX);
}
break;
case SOUND_MIXER_RECMASK:
val = devc->supported_rec_devices;
break;
case SOUND_MIXER_CAPS:
val = SOUND_CAP_EXCL_INPUT;
break;
default:
val = ad1848_mixer_get(devc, cmd & 0xff);
break;
}
return put_user(val, (int __user *)arg);
}
}
else
{
return -EINVAL;
}
}
static int ad1848_set_speed(int dev, int arg)
{
ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc;
ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc;
/*
* The sampling speed is encoded in the least significant nibble of I8. The
* LSB selects the clock source (0=24.576 MHz, 1=16.9344 MHz) and other
* three bits select the divisor (indirectly):
*
* The available speeds are in the following table. Keep the speeds in
* the increasing order.
*/
typedef struct
{
int speed;
unsigned char bits;
}
speed_struct;
static speed_struct speed_table[] =
{
{5510, (0 << 1) | 1},
{5510, (0 << 1) | 1},
{6620, (7 << 1) | 1},
{8000, (0 << 1) | 0},
{9600, (7 << 1) | 0},
{11025, (1 << 1) | 1},
{16000, (1 << 1) | 0},
{18900, (2 << 1) | 1},
{22050, (3 << 1) | 1},
{27420, (2 << 1) | 0},
{32000, (3 << 1) | 0},
{33075, (6 << 1) | 1},
{37800, (4 << 1) | 1},
{44100, (5 << 1) | 1},
{48000, (6 << 1) | 0}
};
int i, n, selected = -1;
n = sizeof(speed_table) / sizeof(speed_struct);
if (arg <= 0)
{
return portc->speed;
}
if (devc->model == MD_1845 || devc->model == MD_1845_SSCAPE) /* AD1845 has different timer than others */
{
if (arg < 4000)
{
arg = 4000;
}
if (arg > 50000)
{
arg = 50000;
}
portc->speed = arg;
portc->speed_bits = speed_table[3].bits;
return portc->speed;
}
if (arg < speed_table[0].speed)
{
selected = 0;
}
if (arg > speed_table[n - 1].speed)
{
selected = n - 1;
}
for (i = 1 /*really */ ; selected == -1 && i < n; i++)
{
if (speed_table[i].speed == arg)
{
selected = i;
}
else if (speed_table[i].speed > arg)
{
int diff1, diff2;
diff1 = arg - speed_table[i - 1].speed;
diff2 = speed_table[i].speed - arg;
if (diff1 < diff2)
{
selected = i - 1;
}
else
{
selected = i;
}
}
}
if (selected == -1)
{
printk(KERN_WARNING "ad1848: Can't find speed???\n");
selected = 3;
}
portc->speed = speed_table[selected].speed;
portc->speed_bits = speed_table[selected].bits;
return portc->speed;
}
static short ad1848_set_channels(int dev, short arg)
{
ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc;
if (arg != 1 && arg != 2)
{
return portc->channels;
}
portc->channels = arg;
return arg;
}
static unsigned int ad1848_set_bits(int dev, unsigned int arg)
{
ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc;
ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc;
static struct format_tbl
{
int format;
unsigned char bits;
}
format2bits[] =
{
{
0, 0
}
,
{
AFMT_MU_LAW, 1
}
,
{
AFMT_A_LAW, 3
}
,
{
AFMT_IMA_ADPCM, 5
}
,
{
AFMT_U8, 0
}
,
{
AFMT_S16_LE, 2
}
,
{
AFMT_S16_BE, 6
}
,
{
AFMT_S8, 0
}
,
{
AFMT_U16_LE, 0
}
,
{
AFMT_U16_BE, 0
}
};
int i, n = sizeof(format2bits) / sizeof(struct format_tbl);
if (arg == 0)
{
return portc->audio_format;
}
if (!(arg & ad_format_mask[devc->model]))
{
arg = AFMT_U8;
}
portc->audio_format = arg;
for (i = 0; i < n; i++)
if (format2bits[i].format == arg)
{
if ((portc->format_bits = format2bits[i].bits) == 0)
{
return portc->audio_format = AFMT_U8; /* Was not supported */
}
return arg;
}
/* Still hanging here. Something must be terribly wrong */
portc->format_bits = 0;
return portc->audio_format = AFMT_U8;
}
static struct audio_driver ad1848_audio_driver =
{
.owner = THIS_MODULE,
.open = ad1848_open,
.close = ad1848_close,
.output_block = ad1848_output_block,
.start_input = ad1848_start_input,
.prepare_for_input = ad1848_prepare_for_input,
.prepare_for_output = ad1848_prepare_for_output,
.halt_io = ad1848_halt,
.halt_input = ad1848_halt_input,
.halt_output = ad1848_halt_output,
.trigger = ad1848_trigger,
.set_speed = ad1848_set_speed,
.set_bits = ad1848_set_bits,
.set_channels = ad1848_set_channels
};
static struct mixer_operations ad1848_mixer_operations =
{
.owner = THIS_MODULE,
.id = "SOUNDPORT",
.name = "AD1848/CS4248/CS4231",
.ioctl = ad1848_mixer_ioctl
};
static int ad1848_open(int dev, int mode)
{
ad1848_info *devc;
ad1848_port_info *portc;
unsigned long flags;
if (dev < 0 || dev >= num_audiodevs)
{
return -ENXIO;
}
devc = (ad1848_info *) audio_devs[dev]->devc;
portc = (ad1848_port_info *) audio_devs[dev]->portc;
/* here we don't have to protect against intr */
spin_lock(&devc->lock);
if (portc->open_mode || (devc->open_mode & mode))
{
spin_unlock(&devc->lock);
return -EBUSY;
}
devc->dual_dma = 0;
if (audio_devs[dev]->flags & DMA_DUPLEX)
{
devc->dual_dma = 1;
}
devc->intr_active = 0;
devc->audio_mode = 0;
devc->open_mode |= mode;
portc->open_mode = mode;
spin_unlock(&devc->lock);
ad1848_trigger(dev, 0);
if (mode & OPEN_READ)
{
devc->record_dev = dev;
}
if (mode & OPEN_WRITE)
{
devc->playback_dev = dev;
}
/*
* Mute output until the playback really starts. This decreases clicking (hope so).
*/
spin_lock_irqsave(&devc->lock, flags);
ad_mute(devc);
spin_unlock_irqrestore(&devc->lock, flags);
return 0;
}
static void ad1848_close(int dev)
{
unsigned long flags;
ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc;
ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc;
devc->intr_active = 0;
ad1848_halt(dev);
spin_lock_irqsave(&devc->lock, flags);
devc->audio_mode = 0;
devc->open_mode &= ~portc->open_mode;
portc->open_mode = 0;
ad_unmute(devc);
spin_unlock_irqrestore(&devc->lock, flags);
}
static void ad1848_output_block(int dev, unsigned long buf, int count, int intrflag)
{
unsigned long flags, cnt;
ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc;
ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc;
cnt = count;
if (portc->audio_format == AFMT_IMA_ADPCM)
{
cnt /= 4;
}
else
{
if (portc->audio_format & (AFMT_S16_LE | AFMT_S16_BE)) /* 16 bit data */
{
cnt >>= 1;
}
}
if (portc->channels > 1)
{
cnt >>= 1;
}
cnt--;
if ((devc->audio_mode & PCM_ENABLE_OUTPUT) && (audio_devs[dev]->flags & DMA_AUTOMODE) &&
intrflag &&
cnt == devc->xfer_count)
{
devc->audio_mode |= PCM_ENABLE_OUTPUT;
devc->intr_active = 1;
return; /*
* Auto DMA mode on. No need to react
*/
}
spin_lock_irqsave(&devc->lock, flags);
ad_write(devc, 15, (unsigned char) (cnt & 0xff));
ad_write(devc, 14, (unsigned char) ((cnt >> 8) & 0xff));
devc->xfer_count = cnt;
devc->audio_mode |= PCM_ENABLE_OUTPUT;
devc->intr_active = 1;
spin_unlock_irqrestore(&devc->lock, flags);
}
static void ad1848_start_input(int dev, unsigned long buf, int count, int intrflag)
{
unsigned long flags, cnt;
ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc;
ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc;
cnt = count;
if (portc->audio_format == AFMT_IMA_ADPCM)
{
cnt /= 4;
}
else
{
if (portc->audio_format & (AFMT_S16_LE | AFMT_S16_BE)) /* 16 bit data */
{
cnt >>= 1;
}
}
if (portc->channels > 1)
{
cnt >>= 1;
}
cnt--;
if ((devc->audio_mode & PCM_ENABLE_INPUT) && (audio_devs[dev]->flags & DMA_AUTOMODE) &&
intrflag &&
cnt == devc->xfer_count)
{
devc->audio_mode |= PCM_ENABLE_INPUT;
devc->intr_active = 1;
return; /*
* Auto DMA mode on. No need to react
*/
}
spin_lock_irqsave(&devc->lock, flags);
if (devc->model == MD_1848)
{
ad_write(devc, 15, (unsigned char) (cnt & 0xff));
ad_write(devc, 14, (unsigned char) ((cnt >> 8) & 0xff));
}
else
{
ad_write(devc, 31, (unsigned char) (cnt & 0xff));
ad_write(devc, 30, (unsigned char) ((cnt >> 8) & 0xff));
}
ad_unmute(devc);
devc->xfer_count = cnt;
devc->audio_mode |= PCM_ENABLE_INPUT;
devc->intr_active = 1;
spin_unlock_irqrestore(&devc->lock, flags);
}
static int ad1848_prepare_for_output(int dev, int bsize, int bcount)
{
int timeout;
unsigned char fs, old_fs, tmp = 0;
unsigned long flags;
ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc;
ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc;
ad_mute(devc);
spin_lock_irqsave(&devc->lock, flags);
fs = portc->speed_bits | (portc->format_bits << 5);
if (portc->channels > 1)
{
fs |= 0x10;
}
ad_enter_MCE(devc); /* Enables changes to the format select reg */
if (devc->model == MD_1845 || devc->model == MD_1845_SSCAPE) /* Use alternate speed select registers */
{
fs &= 0xf0; /* Mask off the rate select bits */
ad_write(devc, 22, (portc->speed >> 8) & 0xff); /* Speed MSB */
ad_write(devc, 23, portc->speed & 0xff); /* Speed LSB */
}
old_fs = ad_read(devc, 8);
if (devc->model == MD_4232 || devc->model >= MD_4236)
{
tmp = ad_read(devc, 16);
ad_write(devc, 16, tmp | 0x30);
}
if (devc->model == MD_IWAVE)
{
ad_write(devc, 17, 0xc2); /* Disable variable frequency select */
}
ad_write(devc, 8, fs);
/*
* Write to I8 starts resynchronization. Wait until it completes.
*/
timeout = 0;
while (timeout < 100 && inb(devc->base) != 0x80)
{
timeout++;
}
timeout = 0;
while (timeout < 10000 && inb(devc->base) == 0x80)
{
timeout++;
}
if (devc->model >= MD_4232)
{
ad_write(devc, 16, tmp & ~0x30);
}
ad_leave_MCE(devc); /*
* Starts the calibration process.
*/
spin_unlock_irqrestore(&devc->lock, flags);
devc->xfer_count = 0;
#ifndef EXCLUDE_TIMERS
if (dev == timer_installed && devc->timer_running)
if ((fs & 0x01) != (old_fs & 0x01))
{
ad1848_tmr_reprogram(dev);
}
#endif
ad1848_halt_output(dev);
return 0;
}
static int ad1848_prepare_for_input(int dev, int bsize, int bcount)
{
int timeout;
unsigned char fs, old_fs, tmp = 0;
unsigned long flags;
ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc;
ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc;
if (devc->audio_mode)
{
return 0;
}
spin_lock_irqsave(&devc->lock, flags);
fs = portc->speed_bits | (portc->format_bits << 5);
if (portc->channels > 1)
{
fs |= 0x10;
}
ad_enter_MCE(devc); /* Enables changes to the format select reg */
if ((devc->model == MD_1845) || (devc->model == MD_1845_SSCAPE)) /* Use alternate speed select registers */
{
fs &= 0xf0; /* Mask off the rate select bits */
ad_write(devc, 22, (portc->speed >> 8) & 0xff); /* Speed MSB */
ad_write(devc, 23, portc->speed & 0xff); /* Speed LSB */
}
if (devc->model == MD_4232)
{
tmp = ad_read(devc, 16);
ad_write(devc, 16, tmp | 0x30);
}
if (devc->model == MD_IWAVE)
{
ad_write(devc, 17, 0xc2); /* Disable variable frequency select */
}
/*
* If mode >= 2 (CS4231), set I28. It's the capture format register.
*/
if (devc->model != MD_1848)
{
old_fs = ad_read(devc, 28);
ad_write(devc, 28, fs);
/*
* Write to I28 starts resynchronization. Wait until it completes.
*/
timeout = 0;
while (timeout < 100 && inb(devc->base) != 0x80)
{
timeout++;
}
timeout = 0;
while (timeout < 10000 && inb(devc->base) == 0x80)
{
timeout++;
}
if (devc->model != MD_1848 && devc->model != MD_1845 && devc->model != MD_1845_SSCAPE)
{
/*
* CS4231 compatible devices don't have separate sampling rate selection
* register for recording an playback. The I8 register is shared so we have to
* set the speed encoding bits of it too.
*/
unsigned char tmp = portc->speed_bits | (ad_read(devc, 8) & 0xf0);
ad_write(devc, 8, tmp);
/*
* Write to I8 starts resynchronization. Wait until it completes.
*/
timeout = 0;
while (timeout < 100 && inb(devc->base) != 0x80)
{
timeout++;
}
timeout = 0;
while (timeout < 10000 && inb(devc->base) == 0x80)
{
timeout++;
}
}
}
else
{
/* For AD1848 set I8. */
old_fs = ad_read(devc, 8);
ad_write(devc, 8, fs);
/*
* Write to I8 starts resynchronization. Wait until it completes.
*/
timeout = 0;
while (timeout < 100 && inb(devc->base) != 0x80)
{
timeout++;
}
timeout = 0;
while (timeout < 10000 && inb(devc->base) == 0x80)
{
timeout++;
}
}
if (devc->model == MD_4232)
{
ad_write(devc, 16, tmp & ~0x30);
}
ad_leave_MCE(devc); /*
* Starts the calibration process.
*/
spin_unlock_irqrestore(&devc->lock, flags);
devc->xfer_count = 0;
#ifndef EXCLUDE_TIMERS
if (dev == timer_installed && devc->timer_running)
{
if ((fs & 0x01) != (old_fs & 0x01))
{
ad1848_tmr_reprogram(dev);
}
}
#endif
ad1848_halt_input(dev);
return 0;
}
static void ad1848_halt(int dev)
{
ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc;
ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc;
unsigned char bits = ad_read(devc, 9);
if (bits & 0x01 && (portc->open_mode & OPEN_WRITE))
{
ad1848_halt_output(dev);
}
if (bits & 0x02 && (portc->open_mode & OPEN_READ))
{
ad1848_halt_input(dev);
}
devc->audio_mode = 0;
}
static void ad1848_halt_input(int dev)
{
ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc;
unsigned long flags;
if (!(ad_read(devc, 9) & 0x02))
{
return; /* Capture not enabled */
}
spin_lock_irqsave(&devc->lock, flags);
ad_mute(devc);
{
int tmout;
if (!isa_dma_bridge_buggy)
{
disable_dma(audio_devs[dev]->dmap_in->dma);
}
for (tmout = 0; tmout < 100000; tmout++)
if (ad_read(devc, 11) & 0x10)
{
break;
}
ad_write(devc, 9, ad_read(devc, 9) & ~0x02); /* Stop capture */
if (!isa_dma_bridge_buggy)
{
enable_dma(audio_devs[dev]->dmap_in->dma);
}
devc->audio_mode &= ~PCM_ENABLE_INPUT;
}
outb(0, io_Status(devc)); /* Clear interrupt status */
outb(0, io_Status(devc)); /* Clear interrupt status */
devc->audio_mode &= ~PCM_ENABLE_INPUT;
spin_unlock_irqrestore(&devc->lock, flags);
}
static void ad1848_halt_output(int dev)
{
ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc;
unsigned long flags;
if (!(ad_read(devc, 9) & 0x01))
{
return; /* Playback not enabled */
}
spin_lock_irqsave(&devc->lock, flags);
ad_mute(devc);
{
int tmout;
if (!isa_dma_bridge_buggy)
{
disable_dma(audio_devs[dev]->dmap_out->dma);
}
for (tmout = 0; tmout < 100000; tmout++)
if (ad_read(devc, 11) & 0x10)
{
break;
}
ad_write(devc, 9, ad_read(devc, 9) & ~0x01); /* Stop playback */
if (!isa_dma_bridge_buggy)
{
enable_dma(audio_devs[dev]->dmap_out->dma);
}
devc->audio_mode &= ~PCM_ENABLE_OUTPUT;
}
outb((0), io_Status(devc)); /* Clear interrupt status */
outb((0), io_Status(devc)); /* Clear interrupt status */
devc->audio_mode &= ~PCM_ENABLE_OUTPUT;
spin_unlock_irqrestore(&devc->lock, flags);
}
static void ad1848_trigger(int dev, int state)
{
ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc;
ad1848_port_info *portc = (ad1848_port_info *) audio_devs[dev]->portc;
unsigned long flags;
unsigned char tmp, old;
spin_lock_irqsave(&devc->lock, flags);
state &= devc->audio_mode;
tmp = old = ad_read(devc, 9);
if (portc->open_mode & OPEN_READ)
{
if (state & PCM_ENABLE_INPUT)
{
tmp |= 0x02;
}
else
{
tmp &= ~0x02;
}
}
if (portc->open_mode & OPEN_WRITE)
{
if (state & PCM_ENABLE_OUTPUT)
{
tmp |= 0x01;
}
else
{
tmp &= ~0x01;
}
}
/* ad_mute(devc); */
if (tmp != old)
{
ad_write(devc, 9, tmp);
ad_unmute(devc);
}
spin_unlock_irqrestore(&devc->lock, flags);
}
static void ad1848_init_hw(ad1848_info *devc)
{
int i;
int *init_values;
/*
* Initial values for the indirect registers of CS4248/AD1848.
*/
static int init_values_a[] =
{
0xa8, 0xa8, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00,
0x00, 0x0c, 0x02, 0x00, 0x8a, 0x01, 0x00, 0x00,
/* Positions 16 to 31 just for CS4231/2 and ad1845 */
0x80, 0x00, 0x10, 0x10, 0x00, 0x00, 0x1f, 0x40,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
static int init_values_b[] =
{
/*
Values for the newer chips
Some of the register initialization values were changed. In
order to get rid of the click that preceded PCM playback,
calibration was disabled on the 10th byte. On that same byte,
dual DMA was enabled; on the 11th byte, ADC dithering was
enabled, since that is theoretically desirable; on the 13th
byte, Mode 3 was selected, to enable access to extended
registers.
*/
0xa8, 0xa8, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00,
0x00, 0x00, 0x06, 0x00, 0xe0, 0x01, 0x00, 0x00,
0x80, 0x00, 0x10, 0x10, 0x00, 0x00, 0x1f, 0x40,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
/*
* Select initialisation data
*/
init_values = init_values_a;
if (devc->model >= MD_4236)
{
init_values = init_values_b;
}
for (i = 0; i < 16; i++)
{
ad_write(devc, i, init_values[i]);
}
ad_mute(devc); /* Initialize some variables */
ad_unmute(devc); /* Leave it unmuted now */
if (devc->model > MD_1848)
{
if (devc->model == MD_1845_SSCAPE)
{
ad_write(devc, 12, ad_read(devc, 12) | 0x50);
}
else
{
ad_write(devc, 12, ad_read(devc, 12) | 0x40); /* Mode2 = enabled */
}
if (devc->model == MD_IWAVE)
{
ad_write(devc, 12, 0x6c); /* Select codec mode 3 */
}
if (devc->model != MD_1845_SSCAPE)
for (i = 16; i < 32; i++)
{
ad_write(devc, i, init_values[i]);
}
if (devc->model == MD_IWAVE)
{
ad_write(devc, 16, 0x30); /* Playback and capture counters enabled */
}
}
if (devc->model > MD_1848)
{
if (devc->audio_flags & DMA_DUPLEX)
{
ad_write(devc, 9, ad_read(devc, 9) & ~0x04); /* Dual DMA mode */
}
else
{
ad_write(devc, 9, ad_read(devc, 9) | 0x04); /* Single DMA mode */
}
if (devc->model == MD_1845 || devc->model == MD_1845_SSCAPE)
{
ad_write(devc, 27, ad_read(devc, 27) | 0x08); /* Alternate freq select enabled */
}
if (devc->model == MD_IWAVE)
{
/* Some magic Interwave specific initialization */
ad_write(devc, 12, 0x6c); /* Select codec mode 3 */
ad_write(devc, 16, 0x30); /* Playback and capture counters enabled */
ad_write(devc, 17, 0xc2); /* Alternate feature enable */
}
}
else
{
devc->audio_flags &= ~DMA_DUPLEX;
ad_write(devc, 9, ad_read(devc, 9) | 0x04); /* Single DMA mode */
if (soundpro)
{
ad_write(devc, 12, ad_read(devc, 12) | 0x40); /* Mode2 = enabled */
}
}
outb((0), io_Status(devc)); /* Clear pending interrupts */
/*
* Toggle the MCE bit. It completes the initialization phase.
*/
ad_enter_MCE(devc); /* In case the bit was off */
ad_leave_MCE(devc);
ad1848_mixer_reset(devc);
}
int ad1848_detect(struct resource *ports, int *ad_flags, int *osp)
{
unsigned char tmp;
ad1848_info *devc = &adev_info[nr_ad1848_devs];
unsigned char tmp1 = 0xff, tmp2 = 0xff;
int optiC930 = 0; /* OPTi 82C930 flag */
int interwave = 0;
int ad1847_flag = 0;
int cs4248_flag = 0;
int sscape_flag = 0;
int io_base = ports->start;
int i;
DDB(printk("ad1848_detect(%x)\n", io_base));
if (ad_flags)
{
if (*ad_flags == 0x12345678)
{
interwave = 1;
*ad_flags = 0;
}
if (*ad_flags == 0x87654321)
{
sscape_flag = 1;
*ad_flags = 0;
}
if (*ad_flags == 0x12345677)
{
cs4248_flag = 1;
*ad_flags = 0;
}
}
if (nr_ad1848_devs >= MAX_AUDIO_DEV)
{
printk(KERN_ERR "ad1848 - Too many audio devices\n");
return 0;
}
spin_lock_init(&devc->lock);
devc->base = io_base;
devc->irq_ok = 0;
devc->timer_running = 0;
devc->MCE_bit = 0x40;
devc->irq = 0;
devc->open_mode = 0;
devc->chip_name = devc->name = "AD1848";
devc->model = MD_1848; /* AD1848 or CS4248 */
devc->levels = NULL;
devc->debug_flag = 0;
/*
* Check that the I/O address is in use.
*
* The bit 0x80 of the base I/O port is known to be 0 after the
* chip has performed its power on initialization. Just assume
* this has happened before the OS is starting.
*
* If the I/O address is unused, it typically returns 0xff.
*/
if (inb(devc->base) == 0xff)
{
DDB(printk("ad1848_detect: The base I/O address appears to be dead\n"));
}
/*
* Wait for the device to stop initialization
*/
DDB(printk("ad1848_detect() - step 0\n"));
for (i = 0; i < 10000000; i++)
{
unsigned char x = inb(devc->base);
if (x == 0xff || !(x & 0x80))
{
break;
}
}
DDB(printk("ad1848_detect() - step A\n"));
if (inb(devc->base) == 0x80) /* Not ready. Let's wait */
{
ad_leave_MCE(devc);
}
if ((inb(devc->base) & 0x80) != 0x00) /* Not a AD1848 */
{
DDB(printk("ad1848 detect error - step A (%02x)\n", (int) inb(devc->base)));
return 0;
}
/*
* Test if it's possible to change contents of the indirect registers.
* Registers 0 and 1 are ADC volume registers. The bit 0x10 is read only
* so try to avoid using it.
*/
DDB(printk("ad1848_detect() - step B\n"));
ad_write(devc, 0, 0xaa);
ad_write(devc, 1, 0x45); /* 0x55 with bit 0x10 clear */
if ((tmp1 = ad_read(devc, 0)) != 0xaa || (tmp2 = ad_read(devc, 1)) != 0x45)
{
if (tmp2 == 0x65) /* AD1847 has couple of bits hardcoded to 1 */
{
ad1847_flag = 1;
}
else
{
DDB(printk("ad1848 detect error - step B (%x/%x)\n", tmp1, tmp2));
return 0;
}
}
DDB(printk("ad1848_detect() - step C\n"));
ad_write(devc, 0, 0x45);
ad_write(devc, 1, 0xaa);
if ((tmp1 = ad_read(devc, 0)) != 0x45 || (tmp2 = ad_read(devc, 1)) != 0xaa)
{
if (tmp2 == 0x8a) /* AD1847 has few bits hardcoded to 1 */
{
ad1847_flag = 1;
}
else
{
DDB(printk("ad1848 detect error - step C (%x/%x)\n", tmp1, tmp2));
return 0;
}
}
/*
* The indirect register I12 has some read only bits. Let's
* try to change them.
*/
DDB(printk("ad1848_detect() - step D\n"));
tmp = ad_read(devc, 12);
ad_write(devc, 12, (~tmp) & 0x0f);
if ((tmp & 0x0f) != ((tmp1 = ad_read(devc, 12)) & 0x0f))
{
DDB(printk("ad1848 detect error - step D (%x)\n", tmp1));
return 0;
}
/*
* NOTE! Last 4 bits of the reg I12 tell the chip revision.
* 0x01=RevB and 0x0A=RevC.
*/
/*
* The original AD1848/CS4248 has just 15 indirect registers. This means
* that I0 and I16 should return the same value (etc.).
* However this doesn't work with CS4248. Actually it seems to be impossible
* to detect if the chip is a CS4231 or CS4248.
* Ensure that the Mode2 enable bit of I12 is 0. Otherwise this test fails
* with CS4231.
*/
/*
* OPTi 82C930 has mode2 control bit in another place. This test will fail
* with it. Accept this situation as a possible indication of this chip.
*/
DDB(printk("ad1848_detect() - step F\n"));
ad_write(devc, 12, 0); /* Mode2=disabled */
for (i = 0; i < 16; i++)
{
if ((tmp1 = ad_read(devc, i)) != (tmp2 = ad_read(devc, i + 16)))
{
DDB(printk("ad1848 detect step F(%d/%x/%x) - OPTi chip???\n", i, tmp1, tmp2));
if (!ad1847_flag)
{
optiC930 = 1;
}
break;
}
}
/*
* Try to switch the chip to mode2 (CS4231) by setting the MODE2 bit (0x40).
* The bit 0x80 is always 1 in CS4248 and CS4231.
*/
DDB(printk("ad1848_detect() - step G\n"));
if (ad_flags && *ad_flags == 400)
{
*ad_flags = 0;
}
else
{
ad_write(devc, 12, 0x40); /* Set mode2, clear 0x80 */
}
if (ad_flags)
{
*ad_flags = 0;
}
tmp1 = ad_read(devc, 12);
if (tmp1 & 0x80)
{
if (ad_flags)
{
*ad_flags |= AD_F_CS4248;
}
devc->chip_name = "CS4248"; /* Our best knowledge just now */
}
if (optiC930 || (tmp1 & 0xc0) == (0x80 | 0x40))
{
/*
* CS4231 detected - is it?
*
* Verify that setting I0 doesn't change I16.
*/
DDB(printk("ad1848_detect() - step H\n"));
ad_write(devc, 16, 0); /* Set I16 to known value */
ad_write(devc, 0, 0x45);
if ((tmp1 = ad_read(devc, 16)) != 0x45) /* No change -> CS4231? */
{
ad_write(devc, 0, 0xaa);
if ((tmp1 = ad_read(devc, 16)) == 0xaa) /* Rotten bits? */
{
DDB(printk("ad1848 detect error - step H(%x)\n", tmp1));
return 0;
}
/*
* Verify that some bits of I25 are read only.
*/
DDB(printk("ad1848_detect() - step I\n"));
tmp1 = ad_read(devc, 25); /* Original bits */
ad_write(devc, 25, ~tmp1); /* Invert all bits */
if ((ad_read(devc, 25) & 0xe7) == (tmp1 & 0xe7))
{
int id;
/*
* It's at least CS4231
*/
devc->chip_name = "CS4231";
devc->model = MD_4231;
/*
* It could be an AD1845 or CS4231A as well.
* CS4231 and AD1845 report the same revision info in I25
* while the CS4231A reports different.
*/
id = ad_read(devc, 25);
if ((id & 0xe7) == 0x80) /* Device busy??? */
{
id = ad_read(devc, 25);
}
if ((id & 0xe7) == 0x80) /* Device still busy??? */
{
id = ad_read(devc, 25);
}
DDB(printk("ad1848_detect() - step J (%02x/%02x)\n", id, ad_read(devc, 25)));
if ((id & 0xe7) == 0x80)
{
/*
* It must be a CS4231 or AD1845. The register I23 of
* CS4231 is undefined and it appears to be read only.
* AD1845 uses I23 for setting sample rate. Assume
* the chip is AD1845 if I23 is changeable.
*/
unsigned char tmp = ad_read(devc, 23);
ad_write(devc, 23, ~tmp);
if (interwave)
{
devc->model = MD_IWAVE;
devc->chip_name = "IWave";
}
else if (ad_read(devc, 23) != tmp) /* AD1845 ? */
{
devc->chip_name = "AD1845";
devc->model = MD_1845;
}
else if (cs4248_flag)
{
if (ad_flags)
{
*ad_flags |= AD_F_CS4248;
}
devc->chip_name = "CS4248";
devc->model = MD_1848;
ad_write(devc, 12, ad_read(devc, 12) & ~0x40); /* Mode2 off */
}
ad_write(devc, 23, tmp); /* Restore */
}
else
{
switch (id & 0x1f)
{
case 3: /* CS4236/CS4235/CS42xB/CS4239 */
{
int xid;
ad_write(devc, 12, ad_read(devc, 12) | 0x60); /* switch to mode 3 */
ad_write(devc, 23, 0x9c); /* select extended register 25 */
xid = inb(io_Indexed_Data(devc));
ad_write(devc, 12, ad_read(devc, 12) & ~0x60); /* back to mode 0 */
switch (xid & 0x1f)
{
case 0x00:
devc->chip_name = "CS4237B(B)";
devc->model = MD_42xB;
break;
case 0x08:
/* Seems to be a 4238 ?? */
devc->chip_name = "CS4238";
devc->model = MD_42xB;
break;
case 0x09:
devc->chip_name = "CS4238B";
devc->model = MD_42xB;
break;
case 0x0b:
devc->chip_name = "CS4236B";
devc->model = MD_4236;
break;
case 0x10:
devc->chip_name = "CS4237B";
devc->model = MD_42xB;
break;
case 0x1d:
devc->chip_name = "CS4235";
devc->model = MD_4235;
break;
case 0x1e:
devc->chip_name = "CS4239";
devc->model = MD_4239;
break;
default:
printk("Chip ident is %X.\n", xid & 0x1F);
devc->chip_name = "CS42xx";
devc->model = MD_4232;
break;
}
}
break;
case 2: /* CS4232/CS4232A */
devc->chip_name = "CS4232";
devc->model = MD_4232;
break;
case 0:
if ((id & 0xe0) == 0xa0)
{
devc->chip_name = "CS4231A";
devc->model = MD_4231A;
}
else
{
devc->chip_name = "CS4321";
devc->model = MD_4231;
}
break;
default: /* maybe */
DDB(printk("ad1848: I25 = %02x/%02x\n", ad_read(devc, 25), ad_read(devc, 25) & 0xe7));
if (optiC930)
{
devc->chip_name = "82C930";
devc->model = MD_C930;
}
else
{
devc->chip_name = "CS4231";
devc->model = MD_4231;
}
}
}
}
ad_write(devc, 25, tmp1); /* Restore bits */
DDB(printk("ad1848_detect() - step K\n"));
}
}
else if (tmp1 == 0x0a)
{
/*
* Is it perhaps a SoundPro CMI8330?
* If so, then we should be able to change indirect registers
* greater than I15 after activating MODE2, even though reading
* back I12 does not show it.
*/
/*
* Let's try comparing register values
*/
for (i = 0; i < 16; i++)
{
if ((tmp1 = ad_read(devc, i)) != (tmp2 = ad_read(devc, i + 16)))
{
DDB(printk("ad1848 detect step H(%d/%x/%x) - SoundPro chip?\n", i, tmp1, tmp2));
soundpro = 1;
devc->chip_name = "SoundPro CMI 8330";
break;
}
}
}
DDB(printk("ad1848_detect() - step L\n"));
if (ad_flags)
{
if (devc->model != MD_1848)
{
*ad_flags |= AD_F_CS4231;
}
}
DDB(printk("ad1848_detect() - Detected OK\n"));
if (devc->model == MD_1848 && ad1847_flag)
{
devc->chip_name = "AD1847";
}
if (sscape_flag == 1)
{
devc->model = MD_1845_SSCAPE;
}
return 1;
}
int ad1848_init (char *name, struct resource *ports, int irq, int dma_playback,
int dma_capture, int share_dma, int *osp, struct module *owner)
{
/*
* NOTE! If irq < 0, there is another driver which has allocated the IRQ
* so that this driver doesn't need to allocate/deallocate it.
* The actually used IRQ is ABS(irq).
*/
int my_dev;
char dev_name[100];
int e;
ad1848_info *devc = &adev_info[nr_ad1848_devs];
ad1848_port_info *portc = NULL;
devc->irq = (irq > 0) ? irq : 0;
devc->open_mode = 0;
devc->timer_ticks = 0;
devc->dma1 = dma_playback;
devc->dma2 = dma_capture;
devc->subtype = cfg.card_subtype;
devc->audio_flags = DMA_AUTOMODE;
devc->playback_dev = devc->record_dev = 0;
if (name != NULL)
{
devc->name = name;
}
if (name != NULL && name[0] != 0)
sprintf(dev_name,
"%s (%s)", name, devc->chip_name);
else
sprintf(dev_name,
"Generic audio codec (%s)", devc->chip_name);
rename_region(ports, devc->name);
conf_printf2(dev_name, devc->base, devc->irq, dma_playback, dma_capture);
if (devc->model == MD_1848 || devc->model == MD_C930)
{
devc->audio_flags |= DMA_HARDSTOP;
}
if (devc->model > MD_1848)
{
if (devc->dma1 == devc->dma2 || devc->dma2 == -1 || devc->dma1 == -1)
{
devc->audio_flags &= ~DMA_DUPLEX;
}
else
{
devc->audio_flags |= DMA_DUPLEX;
}
}
portc = kmalloc(sizeof(ad1848_port_info), GFP_KERNEL);
if (portc == NULL)
{
release_region(devc->base, 4);
return -1;
}
if ((my_dev = sound_install_audiodrv(AUDIO_DRIVER_VERSION,
dev_name,
&ad1848_audio_driver,
sizeof(struct audio_driver),
devc->audio_flags,
ad_format_mask[devc->model],
devc,
dma_playback,
dma_capture)) < 0)
{
release_region(devc->base, 4);
kfree(portc);
return -1;
}
audio_devs[my_dev]->portc = portc;
audio_devs[my_dev]->mixer_dev = -1;
if (owner)
{
audio_devs[my_dev]->d->owner = owner;
}
memset((char *) portc, 0, sizeof(*portc));
nr_ad1848_devs++;
ad1848_init_hw(devc);
if (irq > 0)
{
devc->dev_no = my_dev;
if (request_irq(devc->irq, adintr, 0, devc->name,
(void *)(long)my_dev) < 0)
{
printk(KERN_WARNING "ad1848: Unable to allocate IRQ\n");
/* Don't free it either then.. */
devc->irq = 0;
}
if (capabilities[devc->model].flags & CAP_F_TIMER)
{
#ifndef CONFIG_SMP
int x;
unsigned char tmp = ad_read(devc, 16);
#endif
devc->timer_ticks = 0;
ad_write(devc, 21, 0x00); /* Timer MSB */
ad_write(devc, 20, 0x10); /* Timer LSB */
#ifndef CONFIG_SMP
ad_write(devc, 16, tmp | 0x40); /* Enable timer */
for (x = 0; x < 100000 && devc->timer_ticks == 0; x++);
ad_write(devc, 16, tmp & ~0x40); /* Disable timer */
if (devc->timer_ticks == 0)
{
printk(KERN_WARNING "ad1848: Interrupt test failed (IRQ%d)\n", irq);
}
else
{
DDB(printk("Interrupt test OK\n"));
devc->irq_ok = 1;
}
#else
devc->irq_ok = 1;
#endif
}
else
{
devc->irq_ok = 1; /* Couldn't test. assume it's OK */
}
}
else if (irq < 0)
{
irq2dev[-irq] = devc->dev_no = my_dev;
}
#ifndef EXCLUDE_TIMERS
if ((capabilities[devc->model].flags & CAP_F_TIMER) &&
devc->irq_ok)
{
ad1848_tmr_install(my_dev);
}
#endif
if (!share_dma)
{
if (sound_alloc_dma(dma_playback, devc->name))
{
printk(KERN_WARNING "ad1848.c: Can't allocate DMA%d\n", dma_playback);
}
if (dma_capture != dma_playback)
if (sound_alloc_dma(dma_capture, devc->name))
{
printk(KERN_WARNING "ad1848.c: Can't allocate DMA%d\n", dma_capture);
}
}
if ((e = sound_install_mixer(MIXER_DRIVER_VERSION,
dev_name,
&ad1848_mixer_operations,
sizeof(struct mixer_operations),
devc)) >= 0)
{
audio_devs[my_dev]->mixer_dev = e;
if (owner)
{
mixer_devs[e]->owner = owner;
}
}
return my_dev;
}
int ad1848_control(int cmd, int arg)
{
ad1848_info *devc;
unsigned long flags;
if (nr_ad1848_devs < 1)
{
return -ENODEV;
}
devc = &adev_info[nr_ad1848_devs - 1];
switch (cmd)
{
case AD1848_SET_XTAL: /* Change clock frequency of AD1845 (only ) */
if (devc->model != MD_1845 && devc->model != MD_1845_SSCAPE)
{
return -EINVAL;
}
spin_lock_irqsave(&devc->lock, flags);
ad_enter_MCE(devc);
ad_write(devc, 29, (ad_read(devc, 29) & 0x1f) | (arg << 5));
ad_leave_MCE(devc);
spin_unlock_irqrestore(&devc->lock, flags);
break;
case AD1848_MIXER_REROUTE:
{
int o = (arg >> 8) & 0xff;
int n = arg & 0xff;
if (o < 0 || o >= SOUND_MIXER_NRDEVICES)
{
return -EINVAL;
}
if (!(devc->supported_devices & (1 << o)) &&
!(devc->supported_rec_devices & (1 << o)))
{
return -EINVAL;
}
if (n == SOUND_MIXER_NONE)
{
/* Just hide this control */
ad1848_mixer_set(devc, o, 0); /* Shut up it */
devc->supported_devices &= ~(1 << o);
devc->supported_rec_devices &= ~(1 << o);
break;
}
/* Make the mixer control identified by o to appear as n */
if (n < 0 || n >= SOUND_MIXER_NRDEVICES)
{
return -EINVAL;
}
devc->mixer_reroute[n] = o; /* Rename the control */
if (devc->supported_devices & (1 << o))
{
devc->supported_devices |= (1 << n);
}
if (devc->supported_rec_devices & (1 << o))
{
devc->supported_rec_devices |= (1 << n);
}
devc->supported_devices &= ~(1 << o);
devc->supported_rec_devices &= ~(1 << o);
}
break;
}
return 0;
}
void ad1848_unload(int io_base, int irq, int dma_playback, int dma_capture, int share_dma)
{
int i, mixer, dev = 0;
ad1848_info *devc = NULL;
for (i = 0; devc == NULL && i < nr_ad1848_devs; i++)
{
if (adev_info[i].base == io_base)
{
devc = &adev_info[i];
dev = devc->dev_no;
}
}
if (devc != NULL)
{
kfree(audio_devs[dev]->portc);
release_region(devc->base, 4);
if (!share_dma)
{
if (devc->irq > 0) /* There is no point in freeing irq, if it wasn't allocated */
{
free_irq(devc->irq, (void *)(long)devc->dev_no);
}
sound_free_dma(dma_playback);
if (dma_playback != dma_capture)
{
sound_free_dma(dma_capture);
}
}
mixer = audio_devs[devc->dev_no]->mixer_dev;
if (mixer >= 0)
{
sound_unload_mixerdev(mixer);
}
nr_ad1848_devs--;
for ( ; i < nr_ad1848_devs ; i++)
{
adev_info[i] = adev_info[i + 1];
}
}
else
{
printk(KERN_ERR "ad1848: Can't find device to be unloaded. Base=%x\n", io_base);
}
}
static irqreturn_t adintr(int irq, void *dev_id)
{
unsigned char status;
ad1848_info *devc;
int dev;
int alt_stat = 0xff;
unsigned char c930_stat = 0;
int cnt = 0;
dev = (long)dev_id;
devc = (ad1848_info *) audio_devs[dev]->devc;
interrupt_again: /* Jump back here if int status doesn't reset */
status = inb(io_Status(devc));
if (status == 0x80)
{
printk(KERN_DEBUG "adintr: Why?\n");
}
if (devc->model == MD_1848)
{
outb((0), io_Status(devc)); /* Clear interrupt status */
}
if (status & 0x01)
{
if (devc->model == MD_C930)
{
/* 82C930 has interrupt status register in MAD16 register MC11 */
spin_lock(&devc->lock);
/* 0xe0e is C930 address port
* 0xe0f is C930 data port
*/
outb(11, 0xe0e);
c930_stat = inb(0xe0f);
outb((~c930_stat), 0xe0f);
spin_unlock(&devc->lock);
alt_stat = (c930_stat << 2) & 0x30;
}
else if (devc->model != MD_1848)
{
spin_lock(&devc->lock);
alt_stat = ad_read(devc, 24);
ad_write(devc, 24, ad_read(devc, 24) & ~alt_stat); /* Selective ack */
spin_unlock(&devc->lock);
}
if ((devc->open_mode & OPEN_READ) && (devc->audio_mode & PCM_ENABLE_INPUT) && (alt_stat & 0x20))
{
DMAbuf_inputintr(devc->record_dev);
}
if ((devc->open_mode & OPEN_WRITE) && (devc->audio_mode & PCM_ENABLE_OUTPUT) &&
(alt_stat & 0x10))
{
DMAbuf_outputintr(devc->playback_dev, 1);
}
if (devc->model != MD_1848 && (alt_stat & 0x40)) /* Timer interrupt */
{
devc->timer_ticks++;
#ifndef EXCLUDE_TIMERS
if (timer_installed == dev && devc->timer_running)
{
sound_timer_interrupt();
}
#endif
}
}
/*
* Sometimes playback or capture interrupts occur while a timer interrupt
* is being handled. The interrupt will not be retriggered if we don't
* handle it now. Check if an interrupt is still pending and restart
* the handler in this case.
*/
if (inb(io_Status(devc)) & 0x01 && cnt++ < 4)
{
goto interrupt_again;
}
return IRQ_HANDLED;
}
/*
* Experimental initialization sequence for the integrated sound system
* of the Compaq Deskpro M.
*/
static int init_deskpro_m(struct address_info *hw_config)
{
unsigned char tmp;
if ((tmp = inb(0xc44)) == 0xff)
{
DDB(printk("init_deskpro_m: Dead port 0xc44\n"));
return 0;
}
outb(0x10, 0xc44);
outb(0x40, 0xc45);
outb(0x00, 0xc46);
outb(0xe8, 0xc47);
outb(0x14, 0xc44);
outb(0x40, 0xc45);
outb(0x00, 0xc46);
outb(0xe8, 0xc47);
outb(0x10, 0xc44);
return 1;
}
/*
* Experimental initialization sequence for the integrated sound system
* of Compaq Deskpro XL.
*/
static int init_deskpro(struct address_info *hw_config)
{
unsigned char tmp;
if ((tmp = inb(0xc44)) == 0xff)
{
DDB(printk("init_deskpro: Dead port 0xc44\n"));
return 0;
}
outb((tmp | 0x04), 0xc44); /* Select bank 1 */
if (inb(0xc44) != 0x04)
{
DDB(printk("init_deskpro: Invalid bank1 signature in port 0xc44\n"));
return 0;
}
/*
* OK. It looks like a Deskpro so let's proceed.
*/
/*
* I/O port 0xc44 Audio configuration register.
*
* bits 0xc0: Audio revision bits
* 0x00 = Compaq Business Audio
* 0x40 = MS Sound System Compatible (reset default)
* 0x80 = Reserved
* 0xc0 = Reserved
* bit 0x20: No Wait State Enable
* 0x00 = Disabled (reset default, DMA mode)
* 0x20 = Enabled (programmed I/O mode)
* bit 0x10: MS Sound System Decode Enable
* 0x00 = Decoding disabled (reset default)
* 0x10 = Decoding enabled
* bit 0x08: FM Synthesis Decode Enable
* 0x00 = Decoding Disabled (reset default)
* 0x08 = Decoding enabled
* bit 0x04 Bank select
* 0x00 = Bank 0
* 0x04 = Bank 1
* bits 0x03 MSS Base address
* 0x00 = 0x530 (reset default)
* 0x01 = 0x604
* 0x02 = 0xf40
* 0x03 = 0xe80
*/
#ifdef DEBUGXL
/* Debug printing */
printk("Port 0xc44 (before): ");
outb((tmp & ~0x04), 0xc44);
printk("%02x ", inb(0xc44));
outb((tmp | 0x04), 0xc44);
printk("%02x\n", inb(0xc44));
#endif
/* Set bank 1 of the register */
tmp = 0x58; /* MSS Mode, MSS&FM decode enabled */
switch (hw_config->io_base)
{
case 0x530:
tmp |= 0x00;
break;
case 0x604:
tmp |= 0x01;
break;
case 0xf40:
tmp |= 0x02;
break;
case 0xe80:
tmp |= 0x03;
break;
default:
DDB(printk("init_deskpro: Invalid MSS port %x\n", hw_config->io_base));
return 0;
}
outb((tmp & ~0x04), 0xc44); /* Write to bank=0 */
#ifdef DEBUGXL
/* Debug printing */
printk("Port 0xc44 (after): ");
outb((tmp & ~0x04), 0xc44); /* Select bank=0 */
printk("%02x ", inb(0xc44));
outb((tmp | 0x04), 0xc44); /* Select bank=1 */
printk("%02x\n", inb(0xc44));
#endif
/*
* I/O port 0xc45 FM Address Decode/MSS ID Register.
*
* bank=0, bits 0xfe: FM synthesis Decode Compare bits 7:1 (default=0x88)
* bank=0, bit 0x01: SBIC Power Control Bit
* 0x00 = Powered up
* 0x01 = Powered down
* bank=1, bits 0xfc: MSS ID (default=0x40)
*/
#ifdef DEBUGXL
/* Debug printing */
printk("Port 0xc45 (before): ");
outb((tmp & ~0x04), 0xc44); /* Select bank=0 */
printk("%02x ", inb(0xc45));
outb((tmp | 0x04), 0xc44); /* Select bank=1 */
printk("%02x\n", inb(0xc45));
#endif
outb((tmp & ~0x04), 0xc44); /* Select bank=0 */
outb((0x88), 0xc45); /* FM base 7:0 = 0x88 */
outb((tmp | 0x04), 0xc44); /* Select bank=1 */
outb((0x10), 0xc45); /* MSS ID = 0x10 (MSS port returns 0x04) */
#ifdef DEBUGXL
/* Debug printing */
printk("Port 0xc45 (after): ");
outb((tmp & ~0x04), 0xc44); /* Select bank=0 */
printk("%02x ", inb(0xc45));
outb((tmp | 0x04), 0xc44); /* Select bank=1 */
printk("%02x\n", inb(0xc45));
#endif
/*
* I/O port 0xc46 FM Address Decode/Address ASIC Revision Register.
*
* bank=0, bits 0xff: FM synthesis Decode Compare bits 15:8 (default=0x03)
* bank=1, bits 0xff: Audio addressing ASIC id
*/
#ifdef DEBUGXL
/* Debug printing */
printk("Port 0xc46 (before): ");
outb((tmp & ~0x04), 0xc44); /* Select bank=0 */
printk("%02x ", inb(0xc46));
outb((tmp | 0x04), 0xc44); /* Select bank=1 */
printk("%02x\n", inb(0xc46));
#endif
outb((tmp & ~0x04), 0xc44); /* Select bank=0 */
outb((0x03), 0xc46); /* FM base 15:8 = 0x03 */
outb((tmp | 0x04), 0xc44); /* Select bank=1 */
outb((0x11), 0xc46); /* ASIC ID = 0x11 */
#ifdef DEBUGXL
/* Debug printing */
printk("Port 0xc46 (after): ");
outb((tmp & ~0x04), 0xc44); /* Select bank=0 */
printk("%02x ", inb(0xc46));
outb((tmp | 0x04), 0xc44); /* Select bank=1 */
printk("%02x\n", inb(0xc46));
#endif
/*
* I/O port 0xc47 FM Address Decode Register.
*
* bank=0, bits 0xff: Decode enable selection for various FM address bits
* bank=1, bits 0xff: Reserved
*/
#ifdef DEBUGXL
/* Debug printing */
printk("Port 0xc47 (before): ");
outb((tmp & ~0x04), 0xc44); /* Select bank=0 */
printk("%02x ", inb(0xc47));
outb((tmp | 0x04), 0xc44); /* Select bank=1 */
printk("%02x\n", inb(0xc47));
#endif
outb((tmp & ~0x04), 0xc44); /* Select bank=0 */
outb((0x7c), 0xc47); /* FM decode enable bits = 0x7c */
outb((tmp | 0x04), 0xc44); /* Select bank=1 */
outb((0x00), 0xc47); /* Reserved bank1 = 0x00 */
#ifdef DEBUGXL
/* Debug printing */
printk("Port 0xc47 (after): ");
outb((tmp & ~0x04), 0xc44); /* Select bank=0 */
printk("%02x ", inb(0xc47));
outb((tmp | 0x04), 0xc44); /* Select bank=1 */
printk("%02x\n", inb(0xc47));
#endif
/*
* I/O port 0xc6f = Audio Disable Function Register
*/
#ifdef DEBUGXL
printk("Port 0xc6f (before) = %02x\n", inb(0xc6f));
#endif
outb((0x80), 0xc6f);
#ifdef DEBUGXL
printk("Port 0xc6f (after) = %02x\n", inb(0xc6f));
#endif
return 1;
}
int probe_ms_sound(struct address_info *hw_config, struct resource *ports)
{
unsigned char tmp;
DDB(printk("Entered probe_ms_sound(%x, %d)\n", hw_config->io_base, hw_config->card_subtype));
if (hw_config->card_subtype == 1) /* Has no IRQ/DMA registers */
{
/* check_opl3(0x388, hw_config); */
return ad1848_detect(ports, NULL, hw_config->osp);
}
if (deskpro_xl && hw_config->card_subtype == 2) /* Compaq Deskpro XL */
{
if (!init_deskpro(hw_config))
{
return 0;
}
}
if (deskpro_m) /* Compaq Deskpro M */
{
if (!init_deskpro_m(hw_config))
{
return 0;
}
}
/*
* Check if the IO port returns valid signature. The original MS Sound
* system returns 0x04 while some cards (AudioTrix Pro for example)
* return 0x00 or 0x0f.
*/
if ((tmp = inb(hw_config->io_base + 3)) == 0xff) /* Bus float */
{
int ret;
DDB(printk("I/O address is inactive (%x)\n", tmp));
if (!(ret = ad1848_detect(ports, NULL, hw_config->osp)))
{
return 0;
}
return 1;
}
DDB(printk("MSS signature = %x\n", tmp & 0x3f));
if ((tmp & 0x3f) != 0x04 &&
(tmp & 0x3f) != 0x0f &&
(tmp & 0x3f) != 0x00)
{
int ret;
MDB(printk(KERN_ERR "No MSS signature detected on port 0x%x (0x%x)\n", hw_config->io_base,
(int) inb(hw_config->io_base + 3)));
DDB(printk("Trying to detect codec anyway but IRQ/DMA may not work\n"));
if (!(ret = ad1848_detect(ports, NULL, hw_config->osp)))
{
return 0;
}
hw_config->card_subtype = 1;
return 1;
}
if ((hw_config->irq != 5) &&
(hw_config->irq != 7) &&
(hw_config->irq != 9) &&
(hw_config->irq != 10) &&
(hw_config->irq != 11) &&
(hw_config->irq != 12))
{
printk(KERN_ERR "MSS: Bad IRQ %d\n", hw_config->irq);
return 0;
}
if (hw_config->dma != 0 && hw_config->dma != 1 && hw_config->dma != 3)
{
printk(KERN_ERR "MSS: Bad DMA %d\n", hw_config->dma);
return 0;
}
/*
* Check that DMA0 is not in use with a 8 bit board.
*/
if (hw_config->dma == 0 && inb(hw_config->io_base + 3) & 0x80)
{
printk(KERN_ERR "MSS: Can't use DMA0 with a 8 bit card/slot\n");
return 0;
}
if (hw_config->irq > 7 && hw_config->irq != 9 && inb(hw_config->io_base + 3) & 0x80)
{
printk(KERN_ERR "MSS: Can't use IRQ%d with a 8 bit card/slot\n", hw_config->irq);
return 0;
}
return ad1848_detect(ports, NULL, hw_config->osp);
}
void attach_ms_sound(struct address_info *hw_config, struct resource *ports, struct module *owner)
{
static signed char interrupt_bits[12] =
{
-1, -1, -1, -1, -1, 0x00, -1, 0x08, -1, 0x10, 0x18, 0x20
};
signed char bits;
char dma2_bit = 0;
static char dma_bits[4] =
{
1, 2, 0, 3
};
int config_port = hw_config->io_base + 0;
int version_port = hw_config->io_base + 3;
int dma = hw_config->dma;
int dma2 = hw_config->dma2;
if (hw_config->card_subtype == 1) /* Has no IRQ/DMA registers */
{
hw_config->slots[0] = ad1848_init("MS Sound System", ports,
hw_config->irq,
hw_config->dma,
hw_config->dma2, 0,
hw_config->osp,
owner);
return;
}
/*
* Set the IRQ and DMA addresses.
*/
bits = interrupt_bits[hw_config->irq];
if (bits == -1)
{
printk(KERN_ERR "MSS: Bad IRQ %d\n", hw_config->irq);
release_region(ports->start, 4);
release_region(ports->start - 4, 4);
return;
}
outb((bits | 0x40), config_port);
if ((inb(version_port) & 0x40) == 0)
{
printk(KERN_ERR "[MSS: IRQ Conflict?]\n");
}
/*
* Handle the capture DMA channel
*/
if (dma2 != -1 && dma2 != dma)
{
if (!((dma == 0 && dma2 == 1) ||
(dma == 1 && dma2 == 0) ||
(dma == 3 && dma2 == 0)))
{
/* Unsupported combination. Try to swap channels */
int tmp = dma;
dma = dma2;
dma2 = tmp;
}
if ((dma == 0 && dma2 == 1) ||
(dma == 1 && dma2 == 0) ||
(dma == 3 && dma2 == 0))
{
dma2_bit = 0x04; /* Enable capture DMA */
}
else
{
printk(KERN_WARNING "MSS: Invalid capture DMA\n");
dma2 = dma;
}
}
else
{
dma2 = dma;
}
hw_config->dma = dma;
hw_config->dma2 = dma2;
outb((bits | dma_bits[dma] | dma2_bit), config_port); /* Write IRQ+DMA setup */
hw_config->slots[0] = ad1848_init("MS Sound System", ports,
hw_config->irq,
dma, dma2, 0,
hw_config->osp,
THIS_MODULE);
}
void unload_ms_sound(struct address_info *hw_config)
{
ad1848_unload(hw_config->io_base + 4,
hw_config->irq,
hw_config->dma,
hw_config->dma2, 0);
sound_unload_audiodev(hw_config->slots[0]);
release_region(hw_config->io_base, 4);
}
#ifndef EXCLUDE_TIMERS
/*
* Timer stuff (for /dev/music).
*/
static unsigned int current_interval;
static unsigned int ad1848_tmr_start(int dev, unsigned int usecs)
{
unsigned long flags;
ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc;
unsigned long xtal_nsecs; /* nanoseconds per xtal oscillator tick */
unsigned long divider;
spin_lock_irqsave(&devc->lock, flags);
/*
* Length of the timer interval (in nanoseconds) depends on the
* selected crystal oscillator. Check this from bit 0x01 of I8.
*
* AD1845 has just one oscillator which has cycle time of 10.050 us
* (when a 24.576 MHz xtal oscillator is used).
*
* Convert requested interval to nanoseconds before computing
* the timer divider.
*/
if (devc->model == MD_1845 || devc->model == MD_1845_SSCAPE)
{
xtal_nsecs = 10050;
}
else if (ad_read(devc, 8) & 0x01)
{
xtal_nsecs = 9920;
}
else
{
xtal_nsecs = 9969;
}
divider = (usecs * 1000 + xtal_nsecs / 2) / xtal_nsecs;
if (divider < 100) /* Don't allow shorter intervals than about 1ms */
{
divider = 100;
}
if (divider > 65535) /* Overflow check */
{
divider = 65535;
}
ad_write(devc, 21, (divider >> 8) & 0xff); /* Set upper bits */
ad_write(devc, 20, divider & 0xff); /* Set lower bits */
ad_write(devc, 16, ad_read(devc, 16) | 0x40); /* Start the timer */
devc->timer_running = 1;
spin_unlock_irqrestore(&devc->lock, flags);
return current_interval = (divider * xtal_nsecs + 500) / 1000;
}
static void ad1848_tmr_reprogram(int dev)
{
/*
* Audio driver has changed sampling rate so that a different xtal
* oscillator was selected. We have to reprogram the timer rate.
*/
ad1848_tmr_start(dev, current_interval);
sound_timer_syncinterval(current_interval);
}
static void ad1848_tmr_disable(int dev)
{
unsigned long flags;
ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc;
spin_lock_irqsave(&devc->lock, flags);
ad_write(devc, 16, ad_read(devc, 16) & ~0x40);
devc->timer_running = 0;
spin_unlock_irqrestore(&devc->lock, flags);
}
static void ad1848_tmr_restart(int dev)
{
unsigned long flags;
ad1848_info *devc = (ad1848_info *) audio_devs[dev]->devc;
if (current_interval == 0)
{
return;
}
spin_lock_irqsave(&devc->lock, flags);
ad_write(devc, 16, ad_read(devc, 16) | 0x40);
devc->timer_running = 1;
spin_unlock_irqrestore(&devc->lock, flags);
}
static struct sound_lowlev_timer ad1848_tmr =
{
0,
2,
ad1848_tmr_start,
ad1848_tmr_disable,
ad1848_tmr_restart
};
static int ad1848_tmr_install(int dev)
{
if (timer_installed != -1)
{
return 0; /* Don't install another timer */
}
timer_installed = ad1848_tmr.dev = dev;
sound_timer_init(&ad1848_tmr, audio_devs[dev]->name);
return 1;
}
#endif /* EXCLUDE_TIMERS */
EXPORT_SYMBOL(ad1848_detect);
EXPORT_SYMBOL(ad1848_init);
EXPORT_SYMBOL(ad1848_unload);
EXPORT_SYMBOL(ad1848_control);
EXPORT_SYMBOL(probe_ms_sound);
EXPORT_SYMBOL(attach_ms_sound);
EXPORT_SYMBOL(unload_ms_sound);
static int __initdata io = -1;
static int __initdata irq = -1;
static int __initdata dma = -1;
static int __initdata dma2 = -1;
static int __initdata type = 0;
module_param(io, int, 0); /* I/O for a raw AD1848 card */
module_param(irq, int, 0); /* IRQ to use */
module_param(dma, int, 0); /* First DMA channel */
module_param(dma2, int, 0); /* Second DMA channel */
module_param(type, int, 0); /* Card type */
module_param(deskpro_xl, bool, 0); /* Special magic for Deskpro XL boxen */
module_param(deskpro_m, bool, 0); /* Special magic for Deskpro M box */
module_param(soundpro, bool, 0); /* More special magic for SoundPro chips */
#ifdef CONFIG_PNP
module_param(isapnp, int, 0);
module_param(isapnpjump, int, 0);
module_param(reverse, bool, 0);
MODULE_PARM_DESC(isapnp, "When set to 0, Plug & Play support will be disabled");
MODULE_PARM_DESC(isapnpjump, "Jumps to a specific slot in the driver's PnP table. Use the source, Luke.");
MODULE_PARM_DESC(reverse, "When set to 1, will reverse ISAPnP search order");
static struct pnp_dev *ad1848_dev = NULL;
/* Please add new entries at the end of the table */
static struct
{
char *name;
unsigned short card_vendor, card_device,
vendor, function;
short mss_io, irq, dma, dma2; /* index into isapnp table */
int type;
} ad1848_isapnp_list[] __initdata =
{
{
"CMI 8330 SoundPRO",
ISAPNP_VENDOR('C', 'M', 'I'), ISAPNP_DEVICE(0x0001),
ISAPNP_VENDOR('@', '@', '@'), ISAPNP_FUNCTION(0x0001),
0, 0, 0, -1, 0
},
{
"CS4232 based card",
ISAPNP_ANY_ID, ISAPNP_ANY_ID,
ISAPNP_VENDOR('C', 'S', 'C'), ISAPNP_FUNCTION(0x0000),
0, 0, 0, 1, 0
},
{
"CS4232 based card",
ISAPNP_ANY_ID, ISAPNP_ANY_ID,
ISAPNP_VENDOR('C', 'S', 'C'), ISAPNP_FUNCTION(0x0100),
0, 0, 0, 1, 0
},
{
"OPL3-SA2 WSS mode",
ISAPNP_ANY_ID, ISAPNP_ANY_ID,
ISAPNP_VENDOR('Y', 'M', 'H'), ISAPNP_FUNCTION(0x0021),
1, 0, 0, 1, 1
},
{
"Advanced Gravis InterWave Audio",
ISAPNP_VENDOR('G', 'R', 'V'), ISAPNP_DEVICE(0x0001),
ISAPNP_VENDOR('G', 'R', 'V'), ISAPNP_FUNCTION(0x0000),
0, 0, 0, 1, 0
},
{NULL}
};
#ifdef MODULE
static struct isapnp_device_id id_table[] =
{
{
ISAPNP_VENDOR('C', 'M', 'I'), ISAPNP_DEVICE(0x0001),
ISAPNP_VENDOR('@', '@', '@'), ISAPNP_FUNCTION(0x0001), 0
},
{
ISAPNP_ANY_ID, ISAPNP_ANY_ID,
ISAPNP_VENDOR('C', 'S', 'C'), ISAPNP_FUNCTION(0x0000), 0
},
{
ISAPNP_ANY_ID, ISAPNP_ANY_ID,
ISAPNP_VENDOR('C', 'S', 'C'), ISAPNP_FUNCTION(0x0100), 0
},
/* The main driver for this card is opl3sa2
{ ISAPNP_ANY_ID, ISAPNP_ANY_ID,
ISAPNP_VENDOR('Y','M','H'), ISAPNP_FUNCTION(0x0021), 0 },
*/
{
ISAPNP_VENDOR('G', 'R', 'V'), ISAPNP_DEVICE(0x0001),
ISAPNP_VENDOR('G', 'R', 'V'), ISAPNP_FUNCTION(0x0000), 0
},
{0}
};
MODULE_DEVICE_TABLE(isapnp, id_table);
#endif
static struct pnp_dev *activate_dev(char *devname, char *resname, struct pnp_dev *dev)
{
int err;
err = pnp_device_attach(dev);
if (err < 0)
{
return (NULL);
}
if ((err = pnp_activate_dev(dev)) < 0)
{
printk(KERN_ERR "ad1848: %s %s config failed (out of resources?)[%d]\n", devname, resname, err);
pnp_device_detach(dev);
return (NULL);
}
audio_activated = 1;
return (dev);
}
static struct pnp_dev __init *ad1848_init_generic(struct pnp_card *bus,
struct address_info *hw_config, int slot)
{
/* Configure Audio device */
if ((ad1848_dev = pnp_find_dev(bus, ad1848_isapnp_list[slot].vendor, ad1848_isapnp_list[slot].function, NULL)))
{
if ((ad1848_dev = activate_dev(ad1848_isapnp_list[slot].name, "ad1848", ad1848_dev)))
{
hw_config->io_base = pnp_port_start(ad1848_dev, ad1848_isapnp_list[slot].mss_io);
hw_config->irq = pnp_irq(ad1848_dev, ad1848_isapnp_list[slot].irq);
hw_config->dma = pnp_dma(ad1848_dev, ad1848_isapnp_list[slot].dma);
if (ad1848_isapnp_list[slot].dma2 != -1)
{
hw_config->dma2 = pnp_dma(ad1848_dev, ad1848_isapnp_list[slot].dma2);
}
else
{
hw_config->dma2 = -1;
}
hw_config->card_subtype = ad1848_isapnp_list[slot].type;
}
else
{
return (NULL);
}
}
else
{
return (NULL);
}
return (ad1848_dev);
}
static int __init ad1848_isapnp_init(struct address_info *hw_config, struct pnp_card *bus, int slot)
{
char *busname = bus->name[0] ? bus->name : ad1848_isapnp_list[slot].name;
/* Initialize this baby. */
if (ad1848_init_generic(bus, hw_config, slot))
{
/* We got it. */
printk(KERN_NOTICE "ad1848: PnP reports '%s' at i/o %#x, irq %d, dma %d, %d\n",
busname,
hw_config->io_base, hw_config->irq, hw_config->dma,
hw_config->dma2);
return 1;
}
return 0;
}
static int __init ad1848_isapnp_probe(struct address_info *hw_config)
{
static int first = 1;
int i;
/* Count entries in sb_isapnp_list */
for (i = 0; ad1848_isapnp_list[i].card_vendor != 0; i++);
i--;
/* Check and adjust isapnpjump */
if ( isapnpjump < 0 || isapnpjump > i)
{
isapnpjump = reverse ? i : 0;
printk(KERN_ERR "ad1848: Valid range for isapnpjump is 0-%d. Adjusted to %d.\n", i, isapnpjump);
}
if (!first || !reverse)
{
i = isapnpjump;
}
first = 0;
while (ad1848_isapnp_list[i].card_vendor != 0)
{
static struct pnp_card *bus = NULL;
while ((bus = pnp_find_card(
ad1848_isapnp_list[i].card_vendor,
ad1848_isapnp_list[i].card_device,
bus)))
{
if (ad1848_isapnp_init(hw_config, bus, i))
{
isapnpjump = i; /* start next search from here */
return 0;
}
}
i += reverse ? -1 : 1;
}
return -ENODEV;
}
#endif
static int __init init_ad1848(void)
{
printk(KERN_INFO "ad1848/cs4248 codec driver Copyright (C) by Hannu Savolainen 1993-1996\n");
#ifdef CONFIG_PNP
if (isapnp && (ad1848_isapnp_probe(&cfg) < 0) )
{
printk(KERN_NOTICE "ad1848: No ISAPnP cards found, trying standard ones...\n");
isapnp = 0;
}
#endif
if (io != -1)
{
struct resource *ports;
if ( isapnp == 0 )
{
if (irq == -1 || dma == -1)
{
printk(KERN_WARNING "ad1848: must give I/O , IRQ and DMA.\n");
return -EINVAL;
}
cfg.irq = irq;
cfg.io_base = io;
cfg.dma = dma;
cfg.dma2 = dma2;
cfg.card_subtype = type;
}
ports = request_region(io + 4, 4, "ad1848");
if (!ports)
{
return -EBUSY;
}
if (!request_region(io, 4, "WSS config"))
{
release_region(io + 4, 4);
return -EBUSY;
}
if (!probe_ms_sound(&cfg, ports))
{
release_region(io + 4, 4);
release_region(io, 4);
return -ENODEV;
}
attach_ms_sound(&cfg, ports, THIS_MODULE);
loaded = 1;
}
return 0;
}
static void __exit cleanup_ad1848(void)
{
if (loaded)
{
unload_ms_sound(&cfg);
}
#ifdef CONFIG_PNP
if (ad1848_dev)
{
if (audio_activated)
{
pnp_device_detach(ad1848_dev);
}
}
#endif
}
module_init(init_ad1848);
module_exit(cleanup_ad1848);
#ifndef MODULE
static int __init setup_ad1848(char *str)
{
/* io, irq, dma, dma2, type */
int ints[6];
str = get_options(str, ARRAY_SIZE(ints), ints);
io = ints[1];
irq = ints[2];
dma = ints[3];
dma2 = ints[4];
type = ints[5];
return 1;
}
__setup("ad1848=", setup_ad1848);
#endif
MODULE_LICENSE("GPL");
|
williamfdevine/PrettyLinux
|
sound/oss/ad1848.c
|
C
|
gpl-3.0
| 77,160
|
/**
* @file gensvm_debug.c
* @author G.J.J. van den Burg
* @date 2016-05-01
* @brief Functions facilitating debugging
*
* @details
* Defines functions useful for debugging matrices.
*
* @copyright
Copyright 2016, G.J.J. van den Burg.
This file is part of GenSVM.
GenSVM is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
GenSVM is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with GenSVM. If not, see <http://www.gnu.org/licenses/>.
*/
#include "gensvm_debug.h"
/**
* @brief Print a dense matrix
*
* @details
* Debug function to print a matrix
*
* @param[in] M matrix
* @param[in] rows number of rows of M
* @param[in] cols number of columns of M
*/
void gensvm_print_matrix(double *M, long rows, long cols)
{
long i, j;
for (i=0; i<rows; i++) {
for (j=0; j<cols; j++) {
if (j > 0)
note(" ");
note("%+6.6f", matrix_get(M, cols, i, j));
}
note("\n");
}
note("\n");
}
/**
* @brief Print a sparse matrix
*
* @details
* Debug function to print a GenSparse sparse matrix
*
* @param[in] A a GenSparse matrix to print
*
*/
void gensvm_print_sparse(struct GenSparse *A)
{
long i;
// print matrix dimensions
note("Sparse Matrix:\n");
note("\tnnz = %li, rows = %li, cols = %li\n", A->nnz, A->n_row,
A->n_col);
// print nonzero values
note("\tvalues = [ ");
for (i=0; i<A->nnz; i++) {
if (i != 0) note(", ");
note("%f", A->values[i]);
}
note(" ]\n");
// print row indices
note("\tIA = [ ");
for (i=0; i<A->n_row+1; i++) {
if (i != 0) note(", ");
note("%i", A->ia[i]);
}
note(" ]\n");
// print column indices
note("\tJA = [ ");
for (i=0; i<A->nnz; i++) {
if (i != 0) note(", ");
note("%i", A->ja[i]);
}
note(" ]\n");
}
|
GjjvdBurg/GenSVM
|
src/gensvm_debug.c
|
C
|
gpl-3.0
| 2,141
|
/*
* Copyright (C) 2007-2009 Daniel Prevost <dprevost@photonsoftware.org>
*
* This file is part of Photon (photonsoftware.org).
*
* This file may be distributed and/or modified under the terms of the
* GNU General Public License version 2 or version 3 as published by the
* Free Software Foundation and appearing in the file COPYING.GPL2 and
* COPYING.GPL3 included in the packaging of this software.
*
* Licensees holding a valid Photon Commercial license can use this file
* in accordance with the terms of their license.
*
* This software 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.
*/
/* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */
#include "Nucleus/Hash.h"
#include "Nucleus/Tests/Hash/HashTest.h"
const bool expectedToPass = true;
/* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */
int main()
{
psonSessionContext context;
psonHash* pHash;
enum psoErrors errcode;
char* key1 = "My Key 1";
char* key2 = "My Key 2";
char* data1 = "My Data 1";
char* data2 = "My Data 2";
psonHashItem * pHashItem;
pHash = initHashTest( expectedToPass, &context );
errcode = psonHashInit( pHash, g_memObjOffset, 100, &context );
if ( errcode != PSO_OK ) {
ERROR_EXIT( expectedToPass, &context.errorHandler, ; );
}
errcode = psonHashInsert( pHash,
(unsigned char*)key1,
strlen(key1),
data1,
strlen(data1),
&pHashItem,
&context );
if ( errcode != PSO_OK ) {
ERROR_EXIT( expectedToPass, &context.errorHandler, ; );
}
/* A duplicate - not allowed */
errcode = psonHashInsert( pHash,
(unsigned char*)key1,
strlen(key1),
data2,
strlen(data2),
&pHashItem,
&context );
if ( errcode != PSO_ITEM_ALREADY_PRESENT ) {
ERROR_EXIT( expectedToPass, NULL, ; );
}
errcode = psonHashInsert( pHash,
(unsigned char*)key2,
strlen(key2),
data1,
strlen(data1),
&pHashItem,
&context );
if ( errcode != PSO_OK ) {
ERROR_EXIT( expectedToPass, &context.errorHandler, ; );
}
return 0;
}
/* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */
|
dprevost/photon
|
src/Nucleus/Tests/Hash/InsertPass.c
|
C
|
gpl-3.0
| 2,772
|
/*
* This file is part of Cleanflight.
*
* Cleanflight is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Cleanflight is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cleanflight. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* telemetry_hott.c
*
* Authors:
* Konstantin Sharlaimov - HoTT code cleanup, proper state machine implementation, bi-directional serial port operation cleanup
* Dominic Clifton - Hydra - Software Serial, Electronics, Hardware Integration and debugging, HoTT Code cleanup and fixes, general telemetry improvements.
* Carsten Giesen - cGiesen - Baseflight port
* Oliver Bayer - oBayer - MultiWii-HoTT, HoTT reverse engineering
* Adam Majerczyk - HoTT-for-ardupilot from which some information and ideas are borrowed.
*
* https://github.com/obayer/MultiWii-HoTT
* https://github.com/oBayer/MultiHoTT-Module
* https://code.google.com/p/hott-for-ardupilot
*
* HoTT is implemented in Graupner equipment using a bi-directional protocol over a single wire.
*
* Generally the receiver sends a single request byte out using normal uart signals, then waits a short period for a
* multiple byte response and checksum byte before it sends out the next request byte.
* Each response byte must be send with a protocol specific delay between them.
*
* Serial ports use two wires but HoTT uses a single wire so some electronics are required so that
* the signals don't get mixed up. When cleanflight transmits it should not receive it's own transmission.
*
* Connect as follows:
* HoTT TX/RX -> Serial RX (connect directly)
* Serial TX -> 1N4148 Diode -(| )-> HoTT TX/RX (connect via diode)
*
* The diode should be arranged to allow the data signals to flow the right way
* -(| )- == Diode, | indicates cathode marker.
*
* As noticed by Skrebber the GR-12 (and probably GR-16/24, too) are based on a PIC 24FJ64GA-002, which has 5V tolerant digital pins.
*
* Note: The softserial ports are not listed as 5V tolerant in the STM32F103xx data sheet pinouts and pin description
* section. Verify if you require a 5v/3.3v level shifters. The softserial port should not be inverted.
*
* There is a technical discussion (in German) about HoTT here
* http://www.rc-network.de/forum/showthread.php/281496-Graupner-HoTT-Telemetrie-Sensoren-Eigenbau-DIY-Telemetrie-Protokoll-entschl%C3%BCsselt/page21
*/
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include "platform.h"
#if defined(TELEMETRY) && defined(TELEMETRY_HOTT)
#include "build/build_config.h"
#include "build/debug.h"
#include "common/axis.h"
#include "common/time.h"
#include "drivers/time.h"
#include "drivers/serial.h"
#include "fc/runtime_config.h"
#include "flight/pid.h"
#include "io/serial.h"
#include "io/gps.h"
#include "navigation/navigation.h"
#include "sensors/sensors.h"
#include "sensors/battery.h"
#include "telemetry/telemetry.h"
#include "telemetry/hott.h"
//#define HOTT_DEBUG
typedef enum {
HOTT_WAITING_FOR_REQUEST,
HOTT_RECEIVING_REQUEST,
HOTT_WAITING_FOR_TX_WINDOW,
HOTT_TRANSMITTING,
HOTT_ENDING_TRANSMISSION
} hottState_e;
#define HOTT_MESSAGE_PREPARATION_FREQUENCY_5_HZ ((1000 * 1000) / 5)
#define HOTT_RX_SCHEDULE 4000
#define HOTT_TX_SCHEDULE 5000
#define HOTT_TX_DELAY_US 2000
#define MILLISECONDS_IN_A_SECOND 1000
static hottState_e hottState = HOTT_WAITING_FOR_REQUEST;
static timeUs_t hottStateChangeUs = 0;
static uint8_t *hottTxMsg = NULL;
static uint8_t hottTxMsgSize;
static uint8_t hottTxMsgCrc;
#define HOTT_BAUDRATE 19200
#define HOTT_INITIAL_PORT_MODE MODE_RXTX
static serialPort_t *hottPort = NULL;
static serialPortConfig_t *portConfig;
static bool hottTelemetryEnabled = false;
static portSharing_e hottPortSharing;
static HOTT_GPS_MSG_t hottGPSMessage;
static HOTT_EAM_MSG_t hottEAMMessage;
static void hottSwitchState(hottState_e newState, timeUs_t currentTimeUs)
{
if (hottState != newState) {
hottState = newState;
hottStateChangeUs = currentTimeUs;
}
}
static void initialiseEAMMessage(HOTT_EAM_MSG_t *msg, size_t size)
{
memset(msg, 0, size);
msg->start_byte = 0x7C;
msg->eam_sensor_id = HOTT_TELEMETRY_EAM_SENSOR_ID;
msg->sensor_id = HOTT_EAM_SENSOR_TEXT_ID;
msg->stop_byte = 0x7D;
}
#ifdef GPS
typedef enum {
GPS_FIX_CHAR_NONE = '-',
GPS_FIX_CHAR_2D = '2',
GPS_FIX_CHAR_3D = '3',
GPS_FIX_CHAR_DGPS = 'D',
} gpsFixChar_e;
static void initialiseGPSMessage(HOTT_GPS_MSG_t *msg, size_t size)
{
memset(msg, 0, size);
msg->start_byte = 0x7C;
msg->gps_sensor_id = HOTT_TELEMETRY_GPS_SENSOR_ID;
msg->sensor_id = HOTT_GPS_SENSOR_TEXT_ID;
msg->stop_byte = 0x7D;
}
#endif
static void initialiseMessages(void)
{
initialiseEAMMessage(&hottEAMMessage, sizeof(hottEAMMessage));
#ifdef GPS
initialiseGPSMessage(&hottGPSMessage, sizeof(hottGPSMessage));
#endif
}
#ifdef GPS
void addGPSCoordinates(HOTT_GPS_MSG_t *hottGPSMessage, int32_t latitude, int32_t longitude)
{
int16_t deg = latitude / GPS_DEGREES_DIVIDER;
int32_t sec = (latitude - (deg * GPS_DEGREES_DIVIDER)) * 6;
int8_t min = sec / 1000000L;
sec = (sec % 1000000L) / 100L;
uint16_t degMin = (deg * 100L) + min;
hottGPSMessage->pos_NS = (latitude < 0);
hottGPSMessage->pos_NS_dm_L = degMin;
hottGPSMessage->pos_NS_dm_H = degMin >> 8;
hottGPSMessage->pos_NS_sec_L = sec;
hottGPSMessage->pos_NS_sec_H = sec >> 8;
deg = longitude / GPS_DEGREES_DIVIDER;
sec = (longitude - (deg * GPS_DEGREES_DIVIDER)) * 6;
min = sec / 1000000L;
sec = (sec % 1000000L) / 100L;
degMin = (deg * 100L) + min;
hottGPSMessage->pos_EW = (longitude < 0);
hottGPSMessage->pos_EW_dm_L = degMin;
hottGPSMessage->pos_EW_dm_H = degMin >> 8;
hottGPSMessage->pos_EW_sec_L = sec;
hottGPSMessage->pos_EW_sec_H = sec >> 8;
}
void hottPrepareGPSResponse(HOTT_GPS_MSG_t *hottGPSMessage)
{
hottGPSMessage->gps_satelites = gpsSol.numSat;
// Report climb rate regardless of GPS fix
const int32_t climbrate = MAX(0, getEstimatedActualVelocity(Z) + 30000);
hottGPSMessage->climbrate_L = climbrate & 0xFF;
hottGPSMessage->climbrate_H = climbrate >> 8;
const int32_t climbrate3s = MAX(0, 3.0f * getEstimatedActualVelocity(Z) / 100 + 120);
hottGPSMessage->climbrate3s = climbrate3s & 0xFF;
if (!STATE(GPS_FIX)) {
hottGPSMessage->gps_fix_char = GPS_FIX_CHAR_NONE;
return;
}
if (gpsSol.fixType == GPS_FIX_3D) {
hottGPSMessage->gps_fix_char = GPS_FIX_CHAR_3D;
} else {
hottGPSMessage->gps_fix_char = GPS_FIX_CHAR_2D;
}
addGPSCoordinates(hottGPSMessage, gpsSol.llh.lat, gpsSol.llh.lon);
// GPS Speed is returned in cm/s (from io/gps.c) and must be sent in km/h (Hott requirement)
const uint16_t speed = (gpsSol.groundSpeed * 36) / 1000;
hottGPSMessage->gps_speed_L = speed & 0x00FF;
hottGPSMessage->gps_speed_H = speed >> 8;
hottGPSMessage->home_distance_L = GPS_distanceToHome & 0x00FF;
hottGPSMessage->home_distance_H = GPS_distanceToHome >> 8;
const uint16_t hottGpsAltitude = (gpsSol.llh.alt / 100) + HOTT_GPS_ALTITUDE_OFFSET; // meters
hottGPSMessage->altitude_L = hottGpsAltitude & 0x00FF;
hottGPSMessage->altitude_H = hottGpsAltitude >> 8;
hottGPSMessage->home_direction = GPS_directionToHome;
}
#endif
static inline void updateAlarmBatteryStatus(HOTT_EAM_MSG_t *hottEAMMessage)
{
static uint32_t lastHottAlarmSoundTime = 0;
if (((millis() - lastHottAlarmSoundTime) >= (telemetryConfig()->hottAlarmSoundInterval * MILLISECONDS_IN_A_SECOND))){
lastHottAlarmSoundTime = millis();
batteryState_e batteryState = getBatteryState();
if (batteryState == BATTERY_WARNING || batteryState == BATTERY_CRITICAL){
hottEAMMessage->warning_beeps = 0x10;
hottEAMMessage->alarm_invers1 = HOTT_EAM_ALARM1_FLAG_BATTERY_1;
}
else {
hottEAMMessage->warning_beeps = HOTT_EAM_ALARM1_FLAG_NONE;
hottEAMMessage->alarm_invers1 = HOTT_EAM_ALARM1_FLAG_NONE;
}
}
}
static inline void hottEAMUpdateBattery(HOTT_EAM_MSG_t *hottEAMMessage)
{
hottEAMMessage->main_voltage_L = vbat & 0xFF;
hottEAMMessage->main_voltage_H = vbat >> 8;
hottEAMMessage->batt1_voltage_L = vbat & 0xFF;
hottEAMMessage->batt1_voltage_H = vbat >> 8;
updateAlarmBatteryStatus(hottEAMMessage);
}
static inline void hottEAMUpdateCurrentMeter(HOTT_EAM_MSG_t *hottEAMMessage)
{
const int32_t amp = amperage / 10;
hottEAMMessage->current_L = amp & 0xFF;
hottEAMMessage->current_H = amp >> 8;
}
static inline void hottEAMUpdateBatteryDrawnCapacity(HOTT_EAM_MSG_t *hottEAMMessage)
{
const int32_t mAh = mAhDrawn / 10;
hottEAMMessage->batt_cap_L = mAh & 0xFF;
hottEAMMessage->batt_cap_H = mAh >> 8;
}
static inline void hottEAMUpdateAltitudeAndClimbrate(HOTT_EAM_MSG_t *hottEAMMessage)
{
const int32_t alt = MAX(0, getEstimatedActualPosition(Z) / 100.0f + HOTT_GPS_ALTITUDE_OFFSET); // Value of 500 = 0m
hottEAMMessage->altitude_L = alt & 0xFF;
hottEAMMessage->altitude_H = alt >> 8;
const int32_t climbrate = MAX(0, getEstimatedActualVelocity(Z) + 30000);
hottEAMMessage->climbrate_L = climbrate & 0xFF;
hottEAMMessage->climbrate_H = climbrate >> 8;
const int32_t climbrate3s = MAX(0, 3.0f * getEstimatedActualVelocity(Z) / 100 + 120);
hottEAMMessage->climbrate3s = climbrate3s & 0xFF;
}
void hottPrepareEAMResponse(HOTT_EAM_MSG_t *hottEAMMessage)
{
// Reset alarms
hottEAMMessage->warning_beeps = 0x0;
hottEAMMessage->alarm_invers1 = 0x0;
hottEAMUpdateBattery(hottEAMMessage);
hottEAMUpdateCurrentMeter(hottEAMMessage);
hottEAMUpdateBatteryDrawnCapacity(hottEAMMessage);
hottEAMUpdateAltitudeAndClimbrate(hottEAMMessage);
}
static void hottSerialWrite(uint8_t c)
{
static uint8_t serialWrites = 0;
serialWrites++;
serialWrite(hottPort, c);
}
void freeHoTTTelemetryPort(void)
{
closeSerialPort(hottPort);
hottPort = NULL;
hottTelemetryEnabled = false;
}
void initHoTTTelemetry(void)
{
portConfig = findSerialPortConfig(FUNCTION_TELEMETRY_HOTT);
hottPortSharing = determinePortSharing(portConfig, FUNCTION_TELEMETRY_HOTT);
initialiseMessages();
}
void configureHoTTTelemetryPort(void)
{
if (!portConfig) {
return;
}
hottPort = openSerialPort(portConfig->identifier, FUNCTION_TELEMETRY_HOTT, NULL, HOTT_BAUDRATE, HOTT_INITIAL_PORT_MODE, SERIAL_NOT_INVERTED);
if (!hottPort) {
return;
}
hottTelemetryEnabled = true;
}
static void hottQueueSendResponse(uint8_t *buffer, int length)
{
hottTxMsg = buffer;
hottTxMsgSize = length;
}
static bool processBinaryModeRequest(uint8_t address)
{
switch (address) {
#ifdef GPS
case 0x8A:
if (sensors(SENSOR_GPS)) {
hottPrepareGPSResponse(&hottGPSMessage);
hottQueueSendResponse((uint8_t *)&hottGPSMessage, sizeof(hottGPSMessage));
return true;
}
break;
#endif
case 0x8E:
hottPrepareEAMResponse(&hottEAMMessage);
hottQueueSendResponse((uint8_t *)&hottEAMMessage, sizeof(hottEAMMessage));
return true;
}
return false;
}
static void flushHottRxBuffer(void)
{
while (serialRxBytesWaiting(hottPort) > 0) {
serialRead(hottPort);
}
}
static bool hottSendTelemetryDataByte(timeUs_t currentTimeUs)
{
static timeUs_t byteSentTimeUs = 0;
// Guard intra-byte interval
if (currentTimeUs - byteSentTimeUs < HOTT_TX_DELAY_US) {
return false;
}
if (hottTxMsgSize == 0) {
// Send CRC byte
hottSerialWrite(hottTxMsgCrc);
return true;
}
else {
// Send data byte
hottTxMsgCrc += *hottTxMsg;
hottSerialWrite(*hottTxMsg);
hottTxMsg++;
hottTxMsgSize--;
return false;
}
}
void checkHoTTTelemetryState(void)
{
bool newTelemetryEnabledValue = telemetryDetermineEnabledState(hottPortSharing);
if (newTelemetryEnabledValue == hottTelemetryEnabled) {
return;
}
if (newTelemetryEnabledValue)
configureHoTTTelemetryPort();
else
freeHoTTTelemetryPort();
}
void handleHoTTTelemetry(timeUs_t currentTimeUs)
{
static uint8_t hottRequestBuffer[2];
static int hottRequestBufferPtr = 0;
if (!hottTelemetryEnabled)
return;
bool reprocessState;
do {
reprocessState = false;
switch (hottState) {
case HOTT_WAITING_FOR_REQUEST:
if (serialRxBytesWaiting(hottPort)) {
hottRequestBufferPtr = 0;
hottSwitchState(HOTT_RECEIVING_REQUEST, currentTimeUs);
reprocessState = true;
}
break;
case HOTT_RECEIVING_REQUEST:
if ((currentTimeUs - hottStateChangeUs) >= HOTT_RX_SCHEDULE) {
// Waiting for too long - resync
flushHottRxBuffer();
hottSwitchState(HOTT_WAITING_FOR_REQUEST, currentTimeUs);
}
else {
while (serialRxBytesWaiting(hottPort) && hottRequestBufferPtr < 2) {
hottRequestBuffer[hottRequestBufferPtr++] = serialRead(hottPort);
}
if (hottRequestBufferPtr >= 2) {
if ((hottRequestBuffer[0] == 0) || (hottRequestBuffer[0] == HOTT_BINARY_MODE_REQUEST_ID)) {
/*
* FIXME the first byte of the HoTT request frame is ONLY either 0x80 (binary mode) or 0x7F (text mode).
* The binary mode is read as 0x00 (error reading the upper bit) while the text mode is correctly decoded.
* The (requestId == 0) test is a workaround for detecting the binary mode with no ambiguity as there is only
* one other valid value (0x7F) for text mode.
* The error reading for the upper bit should nevertheless be fixed
*/
if (processBinaryModeRequest(hottRequestBuffer[1])) {
hottSwitchState(HOTT_WAITING_FOR_TX_WINDOW, currentTimeUs);
}
else {
hottSwitchState(HOTT_WAITING_FOR_REQUEST, currentTimeUs);
}
}
else if (hottRequestBuffer[0] == HOTT_TEXT_MODE_REQUEST_ID) {
// FIXME Text mode
hottSwitchState(HOTT_WAITING_FOR_REQUEST, currentTimeUs);
}
else {
// Received garbage - resync
flushHottRxBuffer();
hottSwitchState(HOTT_WAITING_FOR_REQUEST, currentTimeUs);
}
reprocessState = true;
}
}
break;
case HOTT_WAITING_FOR_TX_WINDOW:
if ((currentTimeUs - hottStateChangeUs) >= HOTT_TX_SCHEDULE) {
hottTxMsgCrc = 0;
hottSwitchState(HOTT_TRANSMITTING, currentTimeUs);
}
break;
case HOTT_TRANSMITTING:
if (hottSendTelemetryDataByte(currentTimeUs)) {
hottSwitchState(HOTT_ENDING_TRANSMISSION, currentTimeUs);
}
break;
case HOTT_ENDING_TRANSMISSION:
if ((currentTimeUs - hottStateChangeUs) >= HOTT_TX_DELAY_US) {
flushHottRxBuffer();
hottSwitchState(HOTT_WAITING_FOR_REQUEST, currentTimeUs);
reprocessState = true;
}
break;
};
} while (reprocessState);
}
#endif
|
rb1205/inav
|
src/main/telemetry/hott.c
|
C
|
gpl-3.0
| 16,523
|
#include "config.h"
#include "hardware.h"
#include "data.h"
#include "instruction.h"
#include "rung.h"
#include "plclib.h"
#include "project.h"
int project_task(plc_t p)
{ //
/**************start editing here***************************/
BYTE one, two, three;
one = resolve(p, BOOL_DI, 1);
two = fe(p, BOOL_DI, 2);
three = re(p, BOOL_DI, 3);
/* contact(p,BOOL_DQ,1,one);
contact(p,BOOL_DQ,2,two);
contact(p,BOOL_DQ,3,three); */
if (one)
set(p, BOOL_TIMER, 0);
if (three)
reset(p, BOOL_TIMER, 0);
if (two)
down_timer(p, 0);
return 0;
/***************end of editable portion***********************/
}
int project_init()
{
/*********************same here******************************/
return 0;
}
|
kalamara/plcemu
|
src/project.c
|
C
|
gpl-3.0
| 768
|
/* vim: set ts=8 sw=4 sts=4 et: */
/*======================================================================
Copyright (C) 2008,2009,2014 OSSO B.V. <walter+rtpsniff@osso.nl>
This file is part of RTPSniff.
RTPSniff is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
RTPSniff is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License along
with RTPSniff. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
#include "rtpsniff.h"
#include <assert.h>
#include <sys/time.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>
/* Settings */
#ifndef INTERVAL_SECONDS
# define INTERVAL_SECONDS 10 /* wake the storage engine every N seconds */
#endif /* INTERVAL_SECONDS */
#if INTERVAL_SECONDS < 2
# error INTERVAL_SECONDS be too low
#endif
#define TIMER__METHOD_NSLEEP 1
#define TIMER__METHOD_SEMAPHORE 2
#if !defined(USE_NSLEEP_TIMER) && (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600)
# define TIMER__METHOD TIMER__METHOD_SEMAPHORE
# include <errno.h>
# include <semaphore.h>
#else
# define TIMER__METHOD TIMER__METHOD_NSLEEP
#endif
static pthread_t timer__thread;
static struct memory_t *timer__memory;
#if TIMER__METHOD == TIMER__METHOD_NSLEEP
static volatile int timer__done; /* whether we're done */
#elif TIMER__METHOD == TIMER__METHOD_SEMAPHORE
static sem_t timer__semaphore; /* semaphore to synchronize the threads */
#endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */
static void *timer__run(void *thread_arg);
void timer_help() {
printf(
"/*********************"
" module: timer (interval) *******************************/\n"
"#%s USE_NSLEEP_TIMER\n"
"#define INTERVAL_SECONDS %" SCNu32 "\n"
"\n"
"Sleeps until the specified interval of %.2f minutes have passed and wakes up\n"
"to tell the storage engine to write averages.\n"
"\n"
"The USE_NSLEEP_TIMER define forces the module to use a polling sleep loop even\n"
"when the (probably) less cpu intensive and more accurate sem_timedwait()\n"
"function is available. The currently compiled in timer method is: %s\n"
"\n",
#ifdef USE_NSLEEP_TIMER
"define",
#else /* !USE_NSLEEP_TIMER */
"undef",
#endif
(uint32_t)INTERVAL_SECONDS, (float)INTERVAL_SECONDS / 60,
#if TIMER__METHOD == TIMER__METHOD_NSLEEP
"n_sleep"
#elif TIMER__METHOD == TIMER__METHOD_SEMAPHORE
"semaphore"
#endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */
);
}
int timer_loop_bg(struct memory_t *memory) {
pthread_attr_t attr;
/* Set internal config */
timer__memory = memory;
#if TIMER__METHOD == TIMER__METHOD_NSLEEP
/* Initialize polling variable */
timer__done = 0;
#elif TIMER__METHOD == TIMER__METHOD_SEMAPHORE
/* Initialize semaphore */
if (sem_init(&timer__semaphore, 0, 0) != 0) {
perror("sem_init");
return -1;
}
#endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */
/* We want default pthread attributes */
if (pthread_attr_init(&attr) != 0) {
perror("pthread_attr_init");
return -1;
}
/* Run thread */
if (pthread_create(&timer__thread, &attr, &timer__run, NULL) != 0) {
perror("pthread_create");
return -1;
}
#ifndef NDEBUG
fprintf(stderr, "timer_loop_bg: Thread %p started.\n", (void*)timer__thread);
#endif
return 0;
}
void timer_loop_stop() {
void *ret;
/* Tell our thread that it is time */
#if TIMER__METHOD == TIMER__METHOD_NSLEEP
timer__done = 1;
#elif TIMER__METHOD == TIMER__METHOD_SEMAPHORE
sem_post(&timer__semaphore);
#endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */
/* Get its exit status */
if (pthread_join(timer__thread, &ret) != 0)
perror("pthread_join");
#ifndef NDEBUG
fprintf(stderr, "timer_loop_stop: Thread %p joined.\n", (void*)timer__thread);
#endif
#if TIMER__METHOD == TIMER__METHOD_SEMAPHORE
/* Destroy semaphore */
if (sem_destroy(&timer__semaphore) != 0)
perror("sem_destroy");
#endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */
}
/* The timers job is to run storage function after after every INTERVAL_SECONDS time. */
static void *timer__run(void *thread_arg) {
int first_run_skipped = 0; /* do not store the first run because the interval is wrong */
#ifndef NDEBUG
fprintf(stderr, "timer__run: Thread started.\n");
#endif
while (1) {
struct timeval current_time; /* current time is in UTC */
int sample_begin_time;
#if TIMER__METHOD == TIMER__METHOD_NSLEEP
int sleep_useconds;
#elif TIMER__METHOD == TIMER__METHOD_SEMAPHORE
struct timespec new_time;
int ret;
#endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */
int previously_active;
/* Get current time */
if (gettimeofday(¤t_time, NULL) != 0) {
perror("gettimeofday");
return (void*)-1;
}
/* Yes, we started sampling when SIGUSR1 fired, so this is correct */
sample_begin_time = current_time.tv_sec - (current_time.tv_sec % INTERVAL_SECONDS);
/* Calculate how long to sleep */
#if TIMER__METHOD == TIMER__METHOD_NSLEEP
sleep_useconds = (1000000 *
(INTERVAL_SECONDS - (current_time.tv_sec % INTERVAL_SECONDS)) -
current_time.tv_usec);
# ifndef NDEBUG
fprintf(stderr, "timer__run: Current time is %i (%02i:%02i:%02i.%06i), "
"sleep planned for %i useconds.\n",
(int)current_time.tv_sec,
(int)(current_time.tv_sec / 3600) % 24,
(int)(current_time.tv_sec / 60) % 60,
(int)current_time.tv_sec % 60,
(int)current_time.tv_usec, sleep_useconds);
# endif /* NDEBUG */
#elif TIMER__METHOD == TIMER__METHOD_SEMAPHORE
new_time.tv_sec = sample_begin_time + INTERVAL_SECONDS;
new_time.tv_nsec = 0;
# ifndef NDEBUG
fprintf(stderr, "timer__run: Current time is %i (%02i:%02i:%02i.%06i), "
"sleep planned until %02i:%02i:%02i.\n",
(int)current_time.tv_sec,
(int)(current_time.tv_sec / 3600) % 24,
(int)(current_time.tv_sec / 60) % 60,
(int)current_time.tv_sec % 60,
(int)current_time.tv_usec,
(int)(new_time.tv_sec / 3600) % 24,
(int)(new_time.tv_sec / 60) % 60,
(int)new_time.tv_sec % 60);
# endif /* NDEBUG */
#endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */
#if TIMER__METHOD == TIMER__METHOD_NSLEEP
/* The sleep in this thread won't wake up (EINTR) from a SIGALRM in the other
* thread. Pause/alarm won't work either. We use this crappy polling loop as
* an alternative. Observe that the semaphore below method is way more
* accurate and probably uses less cpu. */
while (!timer__done && sleep_useconds > 999999) {
sleep(1);
sleep_useconds -= 1000000;
}
if (timer__done)
break;
usleep(sleep_useconds);
#elif TIMER__METHOD == TIMER__METHOD_SEMAPHORE
/* The sem_timedwait function will sleep happily until the absolutely specified
* time has been reached. */
while ((ret = sem_timedwait(&timer__semaphore, &new_time)) == -1 && errno == EINTR)
continue; /* restart if interrupted by handler */
if (ret == 0)
break; /* if the semaphore was hit, we're done */
if (errno != ETIMEDOUT)
perror("sem_timedwait");
#endif /* TIMER__METHOD == TIMER__METHOD_SEMAPHORE */
#ifndef NDEBUG
if (gettimeofday(¤t_time, NULL) != 0) {
perror("gettimeofday");
return (void*)-1;
}
fprintf(stderr, "timer__run: Awake! Time is now %i (%02i:%02i:%02i.%06i).\n",
(int)current_time.tv_sec,
(int)(current_time.tv_sec / 3600) % 24,
(int)(current_time.tv_sec / 60) % 60,
(int)current_time.tv_sec % 60,
(int)current_time.tv_usec);
#endif
/* Poke other thread to switch memory */
previously_active = timer__memory->active;
raise(SIGUSR1);
sleep(1); /* wait a second to let other thread finish switching memory */
assert(previously_active != timer__memory->active);
if (first_run_skipped) {
/* Delegate the actual writing to storage. */
out_write(sample_begin_time, INTERVAL_SECONDS,
timer__memory->rtphash[previously_active]);
} else {
/* On first run, we started too late in the interval. Ignore those counts. */
first_run_skipped = 1;
}
/* Reset mem for next run */
sniff_release(&timer__memory->rtphash[previously_active]);
}
#ifndef NDEBUG
fprintf(stderr, "timer__run: Thread done.\n");
#endif
return 0;
}
|
ossobv/rtpsniff
|
timer_interval.c
|
C
|
gpl-3.0
| 9,457
|
#include<stdio.h>
#include<big_integer.h>
#include<string.h>
#include<time.h>
#include"gen_lib.h"
int main(int argc,char** argv)
{
if(argc<3)
{
printf("usage %s <length> <num> \n",argv[0]);
exit(-1);
}
FILE* bash=fopen("bash.dat","w+");
FILE* python=fopen("py.dat","w+");
int length=atoi(argv[1]);
int num=atoi(argv[2]);
srand(time(NULL));
set_exe_name("");
gen_cmp(bash,python,length,num);
fwrite("\nquit\n",1,strlen("\nquit"),bash);
fclose(bash);
fclose(python);
return 0;
}
|
NosicLin/Codger
|
src/rtype_v3.0/debug/gen_cmp2.c
|
C
|
gpl-3.0
| 504
|
/*
* OpenSplice DDS
*
* This software and documentation are Copyright 2006 to 2013 PrismTech
* Limited and its licensees. All rights reserved. See file:
*
* $OSPL_HOME/LICENSE
*
* for full copyright notice and license terms.
*
*/
#include <assert.h>
#include "c_typebase.h"
#include "idl_scope.h"
#include "idl_genCxxHelper.h"
#include "os_heap.h"
#include "os_stdlib.h"
#define IDL_MAXSCOPE (20)
/*
This modules handles the name scopes of objects by providing
a scope stack. Each time a name scope is defined, the name
is pushed on the stack. Each time the name scope is left,
the name is popped from the stack. Name scopes are defined
by the IDL definition "module <name>", "struct <name>" and
"union <name>".
*/
/* idl_scopeElement specifies a scope stack element where
"scopeName" specifies the name of the scope and "scopeType"
specifies the kind of scope, either "idl_tFile" which
is currently not used, "idl_tModule" for a module definition,
"idl_tStruct" for a structure definition and "idl_tUnion"
for a union definition.
*/
C_STRUCT(idl_scopeElement) {
c_char *scopeName;
idl_scopeType scopeType;
};
/* idl_scope specifies the scope stack where "stack" is an
array of "idl_scopeElement", "baseName" specifies the
basename of the file that contains the scope stack and
"scopePointer" specifies the actual top of the stack
(-1 specifies an empty stack).
*/
C_STRUCT(idl_scope) {
idl_scopeElement stack[IDL_MAXSCOPE];
c_char *baseName;
c_long scopePointer;
};
/* Create a new scope element with the specified name and type */
idl_scopeElement
idl_scopeElementNew (
const char *scopeName,
idl_scopeType scopeType)
{
idl_scopeElement element;
assert (scopeName);
assert (strlen(scopeName));
element = os_malloc ((size_t)C_SIZEOF(idl_scopeElement));
element->scopeName = os_strdup (scopeName);
element->scopeType = scopeType;
return element;
}
/* Free a scope element */
void
idl_scopeElementFree (
idl_scopeElement element)
{
assert (element);
os_free (element->scopeName);
os_free (element);
}
/* Create a copy of an existing scope element */
idl_scopeElement
idl_scopeElementDup (
idl_scopeElement element)
{
idl_scopeElement new_element;
assert (element);
new_element = os_malloc ((size_t)C_SIZEOF(idl_scopeElement));
new_element->scopeName = os_strdup (element->scopeName);
new_element->scopeType = element->scopeType;
return new_element;
}
/* Return the scope name related to a specific scope element */
c_char *
idl_scopeElementName (
idl_scopeElement element)
{
if (element) {
return element->scopeName;
}
return "";
}
/* Return the scope type related to a specific scope element */
idl_scopeType
idl_scopeElementType (
idl_scopeElement element)
{
if (element == NULL) {
/* Empty scope stack will deliver NULL scope element */
return idl_tModule;
}
return element->scopeType;
}
/* Create a new and empty scope stack, for a specified basename */
idl_scope
idl_scopeNew (
const char *baseName)
{
idl_scope scope = os_malloc ((size_t)C_SIZEOF(idl_scope));
scope->baseName = os_strdup (baseName);
scope->scopePointer = -1;
return scope;
}
/* Create a new and empty scope stack, for a specified basename */
idl_scope
idl_scopeDup (
idl_scope scope)
{
idl_scope newScope = idl_scopeNew(idl_scopeBasename(scope));
c_long si;
for (si = 0; si < (scope->scopePointer+1); si++) {
idl_scopePush (newScope, idl_scopeElementDup(scope->stack[si]));
}
return newScope;
}
/* Free a scope stack, also freeing all scope elements */
void
idl_scopeFree (
idl_scope scope)
{
c_long si;
assert (scope);
for (si = 0; si < (scope->scopePointer+1); si++) {
idl_scopeElementFree(scope->stack[si]);
}
os_free (scope->baseName);
os_free (scope);
return;
}
/* Push a scope element on the scope stack */
void
idl_scopePush (
idl_scope scope,
idl_scopeElement element
)
{
assert (scope);
assert (scope->scopePointer < IDL_MAXSCOPE);
assert (element);
scope->scopePointer++;
scope->stack[scope->scopePointer] = element;
}
/* Return the size of a scope stack (the amount of scope elements) */
c_long
idl_scopeStackSize (
idl_scope scope)
{
return (scope->scopePointer+1);
}
/* Remove the top element from a scope stack */
void
idl_scopePop (
idl_scope scope)
{
assert (scope);
assert (scope->scopePointer >= 0);
scope->scopePointer--;
}
/* Remove the top element from a scope stack, and free its resources */
void
idl_scopePopFree (
idl_scope scope)
{
assert (scope);
assert (scope->scopePointer >= 0);
idl_scopeElementFree(scope->stack[scope->scopePointer]);
scope->scopePointer--;
}
/* Return the top element from a scope stack */
idl_scopeElement
idl_scopeCur (
idl_scope scope)
{
assert (scope);
assert (scope->scopePointer >= -1);
if (scope->scopePointer == -1) {
return NULL;
}
return scope->stack[scope->scopePointer];
}
/* Return the element from a scope stack, by index
where "index" >= 0 and "index" <= "scopePointer"
*/
idl_scopeElement
idl_scopeIndexed (
idl_scope scope,
c_long index)
{
assert (index >= 0);
assert (index <= scope->scopePointer);
return scope->stack[index];
}
/* Determine if two scope stacks are equal */
c_bool
idl_scopeEqual (
idl_scope scope1,
idl_scope scope2)
{
c_long i;
/* If the "scopePointer"s are unequal, the stack do not equal */
if (scope1->scopePointer != scope2->scopePointer) {
return FALSE;
}
/* Per stack element compare the names, if any does not equal the stacks are unequal */
for (i = 0; i < (scope1->scopePointer + 1); i++) {
if (strcmp(idl_scopeElementName(scope1->stack[i]), idl_scopeElementName(scope2->stack[i])) != 0) {
return FALSE;
}
}
return TRUE;
}
/* Determine if a scope stack is contained by a second stack */
c_bool
idl_scopeSub (
idl_scope scope, /* moduleScope */
idl_scope scopeSub) /* keyScope */
{
c_long i;
/* If the "scopePointer" of the stack is higher than the "scopePointer" of the second
stack, the second stack can not contain the first stack
*/
if (scope->scopePointer > scopeSub->scopePointer) {
return FALSE;
}
/* For all scope elements of the stack with the scope elements of the second stack.
If one of them does not equal, the second stack can not contain the first.
The scope element types are not compared, this should not a real problem.
*/
for (i = 0; i < (scope->scopePointer + 1); i++) {
if (strcmp(idl_scopeElementName(scope->stack[i]), idl_scopeElementName(scopeSub->stack[i])) != 0) {
return FALSE;
}
}
return TRUE;
}
/* Build a textual representation of a scope stack with a
specified seperator and optionally add a user specified
identifier
*/
c_char *
idl_scopeStack (
idl_scope scope,
const char *scopeSepp,
const char *name)
{
c_long si;
c_char *scopeStack;
c_char *elName;
if (scope && (scope->scopePointer >= 0)) {
/* If the stack is not empty */
si = 0;
/* copy the first scope element name */
scopeStack = os_strdup (idl_scopeElementName(scope->stack[si]));
si++;
/* for all scope elements */
while (si <= scope->scopePointer) {
elName = idl_scopeElementName(scope->stack[si]);
/* allocate space for current scope stack +
separator + next scope name
*/
scopeStack = os_realloc (scopeStack, (size_t)(
(int)strlen(scopeStack)+
(int)strlen(scopeSepp)+
(int)strlen(elName)+1));
/* concatinate the separator */
os_strcat (scopeStack, scopeSepp);
/* concatinate scope name */
os_strcat (scopeStack, elName);
si++;
}
if (name) {
/* if a user identifier is specified,
allocate space for current scope stack +
separator + user identifier
*/
scopeStack = os_realloc (scopeStack, (size_t)(
(int)strlen(scopeStack)+
(int)strlen(scopeSepp)+
(int)strlen(name)+1));
/* concatinate the separator */
os_strcat (scopeStack, scopeSepp);
/* concatinate user identifier */
os_strcat (scopeStack, name);
}
} else {
/* Empty scope stack */
if (name) {
/* if a user identifier is specified,
copy the user identifier
*/
scopeStack = os_strdup (name);
} else {
/* make the scope stack representation empty */
scopeStack = os_strdup("");
}
}
/* return the scope stack represenation */
return scopeStack;
}
/* Return the basename related to a scope */
c_char *
idl_scopeBasename (
idl_scope scope)
{
return os_strdup(scope->baseName);
}
|
SanderMertens/opensplice
|
src/tools/idlpp/code/idl_scope.c
|
C
|
gpl-3.0
| 9,149
|
/*
*
* Mouse driver
*
*/
#include <kernel/system.h>
#include <kernel/logging.h>
#include <kernel/pipe.h>
#include <kernel/module.h>
#include <kernel/mouse.h>
#include <kernel/args.h>
static uint8_t mouse_cycle = 0;
static uint8_t mouse_byte[4];
#define PACKETS_IN_PIPE 1024
#define DISCARD_POINT 32
#define MOUSE_IRQ 12
#define MOUSE_PORT 0x60
#define MOUSE_STATUS 0x64
#define MOUSE_ABIT 0x02
#define MOUSE_BBIT 0x01
#define MOUSE_WRITE 0xD4
#define MOUSE_F_BIT 0x20
#define MOUSE_V_BIT 0x08
#define MOUSE_DEFAULT 0
#define MOUSE_SCROLLWHEEL 1
#define MOUSE_BUTTONS 2
static int8_t mouse_mode = MOUSE_DEFAULT;
static fs_node_t * mouse_pipe;
void (*ps2_mouse_alternate)(void) = NULL;
static void mouse_wait(uint8_t a_type) {
uint32_t timeout = 100000;
if (!a_type) {
while (--timeout) {
if ((inportb(MOUSE_STATUS) & MOUSE_BBIT) == 1) {
return;
}
}
debug_print(INFO, "mouse timeout");
return;
} else {
while (--timeout) {
if (!((inportb(MOUSE_STATUS) & MOUSE_ABIT))) {
return;
}
}
debug_print(INFO, "mouse timeout");
return;
}
}
static void mouse_write(uint8_t write) {
mouse_wait(1);
outportb(MOUSE_STATUS, MOUSE_WRITE);
mouse_wait(1);
outportb(MOUSE_PORT, write);
}
static uint8_t mouse_read(void) {
mouse_wait(0);
char t = inportb(MOUSE_PORT);
return t;
}
static int mouse_handler(struct regs *r) {
uint8_t status = inportb(MOUSE_STATUS);
while ((status & MOUSE_BBIT) && (status & MOUSE_F_BIT)) {
if (ps2_mouse_alternate) {
ps2_mouse_alternate();
break;
}
int8_t mouse_in = inportb(MOUSE_PORT);
switch (mouse_cycle) {
case 0:
mouse_byte[0] = mouse_in;
if (!(mouse_in & MOUSE_V_BIT)) break;
++mouse_cycle;
break;
case 1:
mouse_byte[1] = mouse_in;
++mouse_cycle;
break;
case 2:
mouse_byte[2] = mouse_in;
if (mouse_mode == MOUSE_SCROLLWHEEL || mouse_mode == MOUSE_BUTTONS) {
++mouse_cycle;
break;
}
goto finish_packet;
case 3:
mouse_byte[3] = mouse_in;
goto finish_packet;
}
goto read_next;
finish_packet:
mouse_cycle = 0;
/* We now have a full mouse packet ready to use */
mouse_device_packet_t packet;
packet.magic = MOUSE_MAGIC;
int x = mouse_byte[1];
int y = mouse_byte[2];
if (x && mouse_byte[0] & (1 << 4)) {
/* Sign bit */
x = x - 0x100;
}
if (y && mouse_byte[0] & (1 << 5)) {
/* Sign bit */
y = y - 0x100;
}
if (mouse_byte[0] & (1 << 6) || mouse_byte[0] & (1 << 7)) {
/* Overflow */
x = 0;
y = 0;
}
packet.x_difference = x;
packet.y_difference = y;
packet.buttons = 0;
if (mouse_byte[0] & 0x01) {
packet.buttons |= LEFT_CLICK;
}
if (mouse_byte[0] & 0x02) {
packet.buttons |= RIGHT_CLICK;
}
if (mouse_byte[0] & 0x04) {
packet.buttons |= MIDDLE_CLICK;
}
if (mouse_mode == MOUSE_SCROLLWHEEL && mouse_byte[3]) {
if ((int8_t)mouse_byte[3] > 0) {
packet.buttons |= MOUSE_SCROLL_DOWN;
} else if ((int8_t)mouse_byte[3] < 0) {
packet.buttons |= MOUSE_SCROLL_UP;
}
}
mouse_device_packet_t bitbucket;
while (pipe_size(mouse_pipe) > (int)(DISCARD_POINT * sizeof(packet))) {
read_fs(mouse_pipe, 0, sizeof(packet), (uint8_t *)&bitbucket);
}
write_fs(mouse_pipe, 0, sizeof(packet), (uint8_t *)&packet);
read_next:
break;
}
irq_ack(MOUSE_IRQ);
return 1;
}
static int ioctl_mouse(fs_node_t * node, int request, void * argp) {
if (request == 1) {
mouse_cycle = 0;
return 0;
}
return -1;
}
static int mouse_install(void) {
debug_print(NOTICE, "Initializing PS/2 mouse interface");
uint8_t status, result;
IRQ_OFF;
while ((inportb(0x64) & 1)) {
inportb(0x60);
}
mouse_pipe = make_pipe(sizeof(mouse_device_packet_t) * PACKETS_IN_PIPE);
mouse_wait(1);
outportb(MOUSE_STATUS, 0xA8);
mouse_read();
mouse_wait(1);
outportb(MOUSE_STATUS, 0x20);
mouse_wait(0);
status = inportb(0x60) | 3;
mouse_wait(1);
outportb(MOUSE_STATUS, 0x60);
mouse_wait(1);
outportb(MOUSE_PORT, status);
mouse_write(0xF6);
mouse_read();
mouse_write(0xF4);
mouse_read();
/* Try to enable scroll wheel (but not buttons) */
if (!args_present("nomousescroll")) {
mouse_write(0xF2);
mouse_read();
result = mouse_read();
mouse_write(0xF3);
mouse_read();
mouse_write(200);
mouse_read();
mouse_write(0xF3);
mouse_read();
mouse_write(100);
mouse_read();
mouse_write(0xF3);
mouse_read();
mouse_write(80);
mouse_read();
mouse_write(0xF2);
mouse_read();
result = mouse_read();
if (result == 3) {
mouse_mode = MOUSE_SCROLLWHEEL;
}
}
/* keyboard scancode set */
mouse_wait(1);
outportb(MOUSE_PORT, 0xF0);
mouse_wait(1);
outportb(MOUSE_PORT, 0x02);
mouse_wait(1);
mouse_read();
irq_install_handler(MOUSE_IRQ, mouse_handler, "ps2 mouse");
IRQ_RES;
uint8_t tmp = inportb(0x61);
outportb(0x61, tmp | 0x80);
outportb(0x61, tmp & 0x7F);
inportb(MOUSE_PORT);
while ((inportb(0x64) & 1)) {
inportb(0x60);
}
mouse_pipe->flags = FS_CHARDEVICE;
mouse_pipe->ioctl = ioctl_mouse;
vfs_mount("/dev/mouse", mouse_pipe);
return 0;
}
static int mouse_uninstall(void) {
/* TODO */
return 0;
}
MODULE_DEF(ps2mouse, mouse_install, mouse_uninstall);
|
jpacanowski/GekonOS
|
kernel/mouse.c
|
C
|
gpl-3.0
| 5,159
|
/*
* Copyright 2014 Tilera Corporation. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, version 2.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for
* more details.
*
*
* Perf_events support for Tile processor.
*
* This code is based upon the x86 perf event
* code, which is:
*
* Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
* Copyright (C) 2008-2009 Red Hat, Inc., Ingo Molnar
* Copyright (C) 2009 Jaswinder Singh Rajput
* Copyright (C) 2009 Advanced Micro Devices, Inc., Robert Richter
* Copyright (C) 2008-2009 Red Hat, Inc., Peter Zijlstra
* Copyright (C) 2009 Intel Corporation, <markus.t.metzger@intel.com>
* Copyright (C) 2009 Google, Inc., Stephane Eranian
*/
#include <linux/kprobes.h>
#include <linux/kernel.h>
#include <linux/kdebug.h>
#include <linux/mutex.h>
#include <linux/bitmap.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/perf_event.h>
#include <linux/atomic.h>
#include <asm/traps.h>
#include <asm/stack.h>
#include <asm/pmc.h>
#include <hv/hypervisor.h>
#define TILE_MAX_COUNTERS 4
#define PERF_COUNT_0_IDX 0
#define PERF_COUNT_1_IDX 1
#define AUX_PERF_COUNT_0_IDX 2
#define AUX_PERF_COUNT_1_IDX 3
struct cpu_hw_events
{
int n_events;
struct perf_event *events[TILE_MAX_COUNTERS]; /* counter order */
struct perf_event *event_list[TILE_MAX_COUNTERS]; /* enabled
order */
int assign[TILE_MAX_COUNTERS];
unsigned long active_mask[BITS_TO_LONGS(TILE_MAX_COUNTERS)];
unsigned long used_mask;
};
/* TILE arch specific performance monitor unit */
struct tile_pmu
{
const char *name;
int version;
const int *hw_events; /* generic hw events table */
/* generic hw cache events table */
const int (*cache_events)[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX];
int (*map_hw_event)(u64); /*method used to map
hw events */
int (*map_cache_event)(u64); /*method used to map
cache events */
u64 max_period; /* max sampling period */
u64 cntval_mask; /* counter width mask */
int cntval_bits; /* counter width */
int max_events; /* max generic hw events
in map */
int num_counters; /* number base + aux counters */
int num_base_counters; /* number base counters */
};
DEFINE_PER_CPU(u64, perf_irqs);
static DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events);
#define TILE_OP_UNSUPP (-1)
#ifndef __tilegx__
/* TILEPro hardware events map */
static const int tile_hw_event_map[] =
{
[PERF_COUNT_HW_CPU_CYCLES] = 0x01, /* ONE */
[PERF_COUNT_HW_INSTRUCTIONS] = 0x06, /* MP_BUNDLE_RETIRED */
[PERF_COUNT_HW_CACHE_REFERENCES] = TILE_OP_UNSUPP,
[PERF_COUNT_HW_CACHE_MISSES] = TILE_OP_UNSUPP,
[PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = 0x16, /*
MP_CONDITIONAL_BRANCH_ISSUED */
[PERF_COUNT_HW_BRANCH_MISSES] = 0x14, /*
MP_CONDITIONAL_BRANCH_MISSPREDICT */
[PERF_COUNT_HW_BUS_CYCLES] = TILE_OP_UNSUPP,
};
#else
/* TILEGx hardware events map */
static const int tile_hw_event_map[] =
{
[PERF_COUNT_HW_CPU_CYCLES] = 0x181, /* ONE */
[PERF_COUNT_HW_INSTRUCTIONS] = 0xdb, /* INSTRUCTION_BUNDLE */
[PERF_COUNT_HW_CACHE_REFERENCES] = TILE_OP_UNSUPP,
[PERF_COUNT_HW_CACHE_MISSES] = TILE_OP_UNSUPP,
[PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = 0xd9, /*
COND_BRANCH_PRED_CORRECT */
[PERF_COUNT_HW_BRANCH_MISSES] = 0xda, /*
COND_BRANCH_PRED_INCORRECT */
[PERF_COUNT_HW_BUS_CYCLES] = TILE_OP_UNSUPP,
};
#endif
#define C(x) PERF_COUNT_HW_CACHE_##x
/*
* Generalized hw caching related hw_event table, filled
* in on a per model basis. A value of -1 means
* 'not supported', any other value means the
* raw hw_event ID.
*/
#ifndef __tilegx__
/* TILEPro hardware cache event map */
static const int tile_cache_event_map[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] =
{
[C(L1D)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = 0x21, /* RD_MISS */
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = 0x22, /* WR_MISS */
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
},
[C(L1I)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = 0x12, /* MP_ICACHE_HIT_ISSUED */
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
},
[C(LL)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
},
[C(DTLB)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = 0x1d, /* TLB_CNT */
[C(RESULT_MISS)] = 0x20, /* TLB_EXCEPTION */
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
},
[C(ITLB)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = 0x13, /* MP_ITLB_HIT_ISSUED */
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
},
[C(BPU)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
},
};
#else
/* TILEGx hardware events map */
static const int tile_cache_event_map[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] =
{
[C(L1D)] = {
/*
* Like some other architectures (e.g. ARM), the performance
* counters don't differentiate between read and write
* accesses/misses, so this isn't strictly correct, but it's the
* best we can do. Writes and reads get combined.
*/
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = 0x44, /* RD_MISS */
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = 0x45, /* WR_MISS */
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
},
[C(L1I)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
},
[C(LL)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
},
[C(DTLB)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = 0x40, /* TLB_CNT */
[C(RESULT_MISS)] = 0x43, /* TLB_EXCEPTION */
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = 0x40, /* TLB_CNT */
[C(RESULT_MISS)] = 0x43, /* TLB_EXCEPTION */
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
},
[C(ITLB)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = 0xd4, /* ITLB_MISS_INT */
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = 0xd4, /* ITLB_MISS_INT */
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
},
[C(BPU)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = TILE_OP_UNSUPP,
[C(RESULT_MISS)] = TILE_OP_UNSUPP,
},
},
};
#endif
static atomic_t tile_active_events;
static DEFINE_MUTEX(perf_intr_reserve_mutex);
static int tile_map_hw_event(u64 config);
static int tile_map_cache_event(u64 config);
static int tile_pmu_handle_irq(struct pt_regs *regs, int fault);
/*
* To avoid new_raw_count getting larger then pre_raw_count
* in tile_perf_event_update(), we limit the value of max_period to 2^31 - 1.
*/
static const struct tile_pmu tilepmu =
{
#ifndef __tilegx__
.name = "tilepro",
#else
.name = "tilegx",
#endif
.max_events = ARRAY_SIZE(tile_hw_event_map),
.map_hw_event = tile_map_hw_event,
.hw_events = tile_hw_event_map,
.map_cache_event = tile_map_cache_event,
.cache_events = &tile_cache_event_map,
.cntval_bits = 32,
.cntval_mask = (1ULL << 32) - 1,
.max_period = (1ULL << 31) - 1,
.num_counters = TILE_MAX_COUNTERS,
.num_base_counters = TILE_BASE_COUNTERS,
};
static const struct tile_pmu *tile_pmu __read_mostly;
/*
* Check whether perf event is enabled.
*/
int tile_perf_enabled(void)
{
return atomic_read(&tile_active_events) != 0;
}
/*
* Read Performance Counters.
*/
static inline u64 read_counter(int idx)
{
u64 val = 0;
/* __insn_mfspr() only takes an immediate argument */
switch (idx)
{
case PERF_COUNT_0_IDX:
val = __insn_mfspr(SPR_PERF_COUNT_0);
break;
case PERF_COUNT_1_IDX:
val = __insn_mfspr(SPR_PERF_COUNT_1);
break;
case AUX_PERF_COUNT_0_IDX:
val = __insn_mfspr(SPR_AUX_PERF_COUNT_0);
break;
case AUX_PERF_COUNT_1_IDX:
val = __insn_mfspr(SPR_AUX_PERF_COUNT_1);
break;
default:
WARN_ON_ONCE(idx > AUX_PERF_COUNT_1_IDX ||
idx < PERF_COUNT_0_IDX);
}
return val;
}
/*
* Write Performance Counters.
*/
static inline void write_counter(int idx, u64 value)
{
/* __insn_mtspr() only takes an immediate argument */
switch (idx)
{
case PERF_COUNT_0_IDX:
__insn_mtspr(SPR_PERF_COUNT_0, value);
break;
case PERF_COUNT_1_IDX:
__insn_mtspr(SPR_PERF_COUNT_1, value);
break;
case AUX_PERF_COUNT_0_IDX:
__insn_mtspr(SPR_AUX_PERF_COUNT_0, value);
break;
case AUX_PERF_COUNT_1_IDX:
__insn_mtspr(SPR_AUX_PERF_COUNT_1, value);
break;
default:
WARN_ON_ONCE(idx > AUX_PERF_COUNT_1_IDX ||
idx < PERF_COUNT_0_IDX);
}
}
/*
* Enable performance event by setting
* Performance Counter Control registers.
*/
static inline void tile_pmu_enable_event(struct perf_event *event)
{
struct hw_perf_event *hwc = &event->hw;
unsigned long cfg, mask;
int shift, idx = hwc->idx;
/*
* prevent early activation from tile_pmu_start() in hw_perf_enable
*/
if (WARN_ON_ONCE(idx == -1))
{
return;
}
if (idx < tile_pmu->num_base_counters)
{
cfg = __insn_mfspr(SPR_PERF_COUNT_CTL);
}
else
{
cfg = __insn_mfspr(SPR_AUX_PERF_COUNT_CTL);
}
switch (idx)
{
case PERF_COUNT_0_IDX:
case AUX_PERF_COUNT_0_IDX:
mask = TILE_EVENT_MASK;
shift = 0;
break;
case PERF_COUNT_1_IDX:
case AUX_PERF_COUNT_1_IDX:
mask = TILE_EVENT_MASK << 16;
shift = 16;
break;
default:
WARN_ON_ONCE(idx < PERF_COUNT_0_IDX ||
idx > AUX_PERF_COUNT_1_IDX);
return;
}
/* Clear mask bits to enable the event. */
cfg &= ~mask;
cfg |= hwc->config << shift;
if (idx < tile_pmu->num_base_counters)
{
__insn_mtspr(SPR_PERF_COUNT_CTL, cfg);
}
else
{
__insn_mtspr(SPR_AUX_PERF_COUNT_CTL, cfg);
}
}
/*
* Disable performance event by clearing
* Performance Counter Control registers.
*/
static inline void tile_pmu_disable_event(struct perf_event *event)
{
struct hw_perf_event *hwc = &event->hw;
unsigned long cfg, mask;
int idx = hwc->idx;
if (idx == -1)
{
return;
}
if (idx < tile_pmu->num_base_counters)
{
cfg = __insn_mfspr(SPR_PERF_COUNT_CTL);
}
else
{
cfg = __insn_mfspr(SPR_AUX_PERF_COUNT_CTL);
}
switch (idx)
{
case PERF_COUNT_0_IDX:
case AUX_PERF_COUNT_0_IDX:
mask = TILE_PLM_MASK;
break;
case PERF_COUNT_1_IDX:
case AUX_PERF_COUNT_1_IDX:
mask = TILE_PLM_MASK << 16;
break;
default:
WARN_ON_ONCE(idx < PERF_COUNT_0_IDX ||
idx > AUX_PERF_COUNT_1_IDX);
return;
}
/* Set mask bits to disable the event. */
cfg |= mask;
if (idx < tile_pmu->num_base_counters)
{
__insn_mtspr(SPR_PERF_COUNT_CTL, cfg);
}
else
{
__insn_mtspr(SPR_AUX_PERF_COUNT_CTL, cfg);
}
}
/*
* Propagate event elapsed time into the generic event.
* Can only be executed on the CPU where the event is active.
* Returns the delta events processed.
*/
static u64 tile_perf_event_update(struct perf_event *event)
{
struct hw_perf_event *hwc = &event->hw;
int shift = 64 - tile_pmu->cntval_bits;
u64 prev_raw_count, new_raw_count;
u64 oldval;
int idx = hwc->idx;
u64 delta;
/*
* Careful: an NMI might modify the previous event value.
*
* Our tactic to handle this is to first atomically read and
* exchange a new raw count - then add that new-prev delta
* count to the generic event atomically:
*/
again:
prev_raw_count = local64_read(&hwc->prev_count);
new_raw_count = read_counter(idx);
oldval = local64_cmpxchg(&hwc->prev_count, prev_raw_count,
new_raw_count);
if (oldval != prev_raw_count)
{
goto again;
}
/*
* Now we have the new raw value and have updated the prev
* timestamp already. We can now calculate the elapsed delta
* (event-)time and add that to the generic event.
*
* Careful, not all hw sign-extends above the physical width
* of the count.
*/
delta = (new_raw_count << shift) - (prev_raw_count << shift);
delta >>= shift;
local64_add(delta, &event->count);
local64_sub(delta, &hwc->period_left);
return new_raw_count;
}
/*
* Set the next IRQ period, based on the hwc->period_left value.
* To be called with the event disabled in hw:
*/
static int tile_event_set_period(struct perf_event *event)
{
struct hw_perf_event *hwc = &event->hw;
int idx = hwc->idx;
s64 left = local64_read(&hwc->period_left);
s64 period = hwc->sample_period;
int ret = 0;
/*
* If we are way outside a reasonable range then just skip forward:
*/
if (unlikely(left <= -period))
{
left = period;
local64_set(&hwc->period_left, left);
hwc->last_period = period;
ret = 1;
}
if (unlikely(left <= 0))
{
left += period;
local64_set(&hwc->period_left, left);
hwc->last_period = period;
ret = 1;
}
if (left > tile_pmu->max_period)
{
left = tile_pmu->max_period;
}
/*
* The hw event starts counting from this event offset,
* mark it to be able to extra future deltas:
*/
local64_set(&hwc->prev_count, (u64) - left);
write_counter(idx, (u64)(-left) & tile_pmu->cntval_mask);
perf_event_update_userpage(event);
return ret;
}
/*
* Stop the event but do not release the PMU counter
*/
static void tile_pmu_stop(struct perf_event *event, int flags)
{
struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
struct hw_perf_event *hwc = &event->hw;
int idx = hwc->idx;
if (__test_and_clear_bit(idx, cpuc->active_mask))
{
tile_pmu_disable_event(event);
cpuc->events[hwc->idx] = NULL;
WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED);
hwc->state |= PERF_HES_STOPPED;
}
if ((flags & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE))
{
/*
* Drain the remaining delta count out of a event
* that we are disabling:
*/
tile_perf_event_update(event);
hwc->state |= PERF_HES_UPTODATE;
}
}
/*
* Start an event (without re-assigning counter)
*/
static void tile_pmu_start(struct perf_event *event, int flags)
{
struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
int idx = event->hw.idx;
if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED)))
{
return;
}
if (WARN_ON_ONCE(idx == -1))
{
return;
}
if (flags & PERF_EF_RELOAD)
{
WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
tile_event_set_period(event);
}
event->hw.state = 0;
cpuc->events[idx] = event;
__set_bit(idx, cpuc->active_mask);
unmask_pmc_interrupts();
tile_pmu_enable_event(event);
perf_event_update_userpage(event);
}
/*
* Add a single event to the PMU.
*
* The event is added to the group of enabled events
* but only if it can be scehduled with existing events.
*/
static int tile_pmu_add(struct perf_event *event, int flags)
{
struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
struct hw_perf_event *hwc;
unsigned long mask;
int b, max_cnt;
hwc = &event->hw;
/*
* We are full.
*/
if (cpuc->n_events == tile_pmu->num_counters)
{
return -ENOSPC;
}
cpuc->event_list[cpuc->n_events] = event;
cpuc->n_events++;
hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
if (!(flags & PERF_EF_START))
{
hwc->state |= PERF_HES_ARCH;
}
/*
* Find first empty counter.
*/
max_cnt = tile_pmu->num_counters;
mask = ~cpuc->used_mask;
/* Find next free counter. */
b = find_next_bit(&mask, max_cnt, 0);
/* Should not happen. */
if (WARN_ON_ONCE(b == max_cnt))
{
return -ENOSPC;
}
/*
* Assign counter to event.
*/
event->hw.idx = b;
__set_bit(b, &cpuc->used_mask);
/*
* Start if requested.
*/
if (flags & PERF_EF_START)
{
tile_pmu_start(event, PERF_EF_RELOAD);
}
return 0;
}
/*
* Delete a single event from the PMU.
*
* The event is deleted from the group of enabled events.
* If it is the last event, disable PMU interrupt.
*/
static void tile_pmu_del(struct perf_event *event, int flags)
{
struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
int i;
/*
* Remove event from list, compact list if necessary.
*/
for (i = 0; i < cpuc->n_events; i++)
{
if (cpuc->event_list[i] == event)
{
while (++i < cpuc->n_events)
{
cpuc->event_list[i - 1] = cpuc->event_list[i];
}
--cpuc->n_events;
cpuc->events[event->hw.idx] = NULL;
__clear_bit(event->hw.idx, &cpuc->used_mask);
tile_pmu_stop(event, PERF_EF_UPDATE);
break;
}
}
/*
* If there are no events left, then mask PMU interrupt.
*/
if (cpuc->n_events == 0)
{
mask_pmc_interrupts();
}
perf_event_update_userpage(event);
}
/*
* Propagate event elapsed time into the event.
*/
static inline void tile_pmu_read(struct perf_event *event)
{
tile_perf_event_update(event);
}
/*
* Map generic events to Tile PMU.
*/
static int tile_map_hw_event(u64 config)
{
if (config >= tile_pmu->max_events)
{
return -EINVAL;
}
return tile_pmu->hw_events[config];
}
/*
* Map generic hardware cache events to Tile PMU.
*/
static int tile_map_cache_event(u64 config)
{
unsigned int cache_type, cache_op, cache_result;
int code;
if (!tile_pmu->cache_events)
{
return -ENOENT;
}
cache_type = (config >> 0) & 0xff;
if (cache_type >= PERF_COUNT_HW_CACHE_MAX)
{
return -EINVAL;
}
cache_op = (config >> 8) & 0xff;
if (cache_op >= PERF_COUNT_HW_CACHE_OP_MAX)
{
return -EINVAL;
}
cache_result = (config >> 16) & 0xff;
if (cache_result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
{
return -EINVAL;
}
code = (*tile_pmu->cache_events)[cache_type][cache_op][cache_result];
if (code == TILE_OP_UNSUPP)
{
return -EINVAL;
}
return code;
}
static void tile_event_destroy(struct perf_event *event)
{
if (atomic_dec_return(&tile_active_events) == 0)
{
release_pmc_hardware();
}
}
static int __tile_event_init(struct perf_event *event)
{
struct perf_event_attr *attr = &event->attr;
struct hw_perf_event *hwc = &event->hw;
int code;
switch (attr->type)
{
case PERF_TYPE_HARDWARE:
code = tile_pmu->map_hw_event(attr->config);
break;
case PERF_TYPE_HW_CACHE:
code = tile_pmu->map_cache_event(attr->config);
break;
case PERF_TYPE_RAW:
code = attr->config & TILE_EVENT_MASK;
break;
default:
/* Should not happen. */
return -EOPNOTSUPP;
}
if (code < 0)
{
return code;
}
hwc->config = code;
hwc->idx = -1;
if (attr->exclude_user)
{
hwc->config |= TILE_CTL_EXCL_USER;
}
if (attr->exclude_kernel)
{
hwc->config |= TILE_CTL_EXCL_KERNEL;
}
if (attr->exclude_hv)
{
hwc->config |= TILE_CTL_EXCL_HV;
}
if (!hwc->sample_period)
{
hwc->sample_period = tile_pmu->max_period;
hwc->last_period = hwc->sample_period;
local64_set(&hwc->period_left, hwc->sample_period);
}
event->destroy = tile_event_destroy;
return 0;
}
static int tile_event_init(struct perf_event *event)
{
int err = 0;
perf_irq_t old_irq_handler = NULL;
if (atomic_inc_return(&tile_active_events) == 1)
{
old_irq_handler = reserve_pmc_hardware(tile_pmu_handle_irq);
}
if (old_irq_handler)
{
pr_warn("PMC hardware busy (reserved by oprofile)\n");
atomic_dec(&tile_active_events);
return -EBUSY;
}
switch (event->attr.type)
{
case PERF_TYPE_RAW:
case PERF_TYPE_HARDWARE:
case PERF_TYPE_HW_CACHE:
break;
default:
return -ENOENT;
}
err = __tile_event_init(event);
if (err)
{
if (event->destroy)
{
event->destroy(event);
}
}
return err;
}
static struct pmu tilera_pmu =
{
.event_init = tile_event_init,
.add = tile_pmu_add,
.del = tile_pmu_del,
.start = tile_pmu_start,
.stop = tile_pmu_stop,
.read = tile_pmu_read,
};
/*
* PMU's IRQ handler, PMU has 2 interrupts, they share the same handler.
*/
int tile_pmu_handle_irq(struct pt_regs *regs, int fault)
{
struct perf_sample_data data;
struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
struct perf_event *event;
struct hw_perf_event *hwc;
u64 val;
unsigned long status;
int bit;
__this_cpu_inc(perf_irqs);
if (!atomic_read(&tile_active_events))
{
return 0;
}
status = pmc_get_overflow();
pmc_ack_overflow(status);
for_each_set_bit(bit, &status, tile_pmu->num_counters)
{
event = cpuc->events[bit];
if (!event)
{
continue;
}
if (!test_bit(bit, cpuc->active_mask))
{
continue;
}
hwc = &event->hw;
val = tile_perf_event_update(event);
if (val & (1ULL << (tile_pmu->cntval_bits - 1)))
{
continue;
}
perf_sample_data_init(&data, 0, event->hw.last_period);
if (!tile_event_set_period(event))
{
continue;
}
if (perf_event_overflow(event, &data, regs))
{
tile_pmu_stop(event, 0);
}
}
return 0;
}
static bool __init supported_pmu(void)
{
tile_pmu = &tilepmu;
return true;
}
int __init init_hw_perf_events(void)
{
supported_pmu();
perf_pmu_register(&tilera_pmu, "cpu", PERF_TYPE_RAW);
return 0;
}
arch_initcall(init_hw_perf_events);
/* Callchain handling code. */
/*
* Tile specific backtracing code for perf_events.
*/
static inline void perf_callchain(struct perf_callchain_entry_ctx *entry,
struct pt_regs *regs)
{
struct KBacktraceIterator kbt;
unsigned int i;
/*
* Get the address just after the "jalr" instruction that
* jumps to the handler for a syscall. When we find this
* address in a backtrace, we silently ignore it, which gives
* us a one-step backtrace connection from the sys_xxx()
* function in the kernel to the xxx() function in libc.
* Otherwise, we lose the ability to properly attribute time
* from the libc calls to the kernel implementations, since
* oprofile only considers PCs from backtraces a pair at a time.
*/
unsigned long handle_syscall_pc = handle_syscall_link_address();
KBacktraceIterator_init(&kbt, NULL, regs);
kbt.profile = 1;
/*
* The sample for the pc is already recorded. Now we are adding the
* address of the callsites on the stack. Our iterator starts
* with the frame of the (already sampled) call site. If our
* iterator contained a "return address" field, we could have just
* used it and wouldn't have needed to skip the first
* frame. That's in effect what the arm and x86 versions do.
* Instead we peel off the first iteration to get the equivalent
* behavior.
*/
if (KBacktraceIterator_end(&kbt))
{
return;
}
KBacktraceIterator_next(&kbt);
/*
* Set stack depth to 16 for user and kernel space respectively, that
* is, total 32 stack frames.
*/
for (i = 0; i < 16; ++i)
{
unsigned long pc;
if (KBacktraceIterator_end(&kbt))
{
break;
}
pc = kbt.it.pc;
if (pc != handle_syscall_pc)
{
perf_callchain_store(entry, pc);
}
KBacktraceIterator_next(&kbt);
}
}
void perf_callchain_user(struct perf_callchain_entry_ctx *entry,
struct pt_regs *regs)
{
perf_callchain(entry, regs);
}
void perf_callchain_kernel(struct perf_callchain_entry_ctx *entry,
struct pt_regs *regs)
{
perf_callchain(entry, regs);
}
|
williamfdevine/PrettyLinux
|
arch/tile/kernel/perf_event.c
|
C
|
gpl-3.0
| 24,932
|
#include "defs.h"
#include "fdefs.h"
#include <stdlib.h>
void
gasify(job)
char *job;
{
char command[MAXCOMM] ;
char g_type[MAXCOMM] ;
double temp_y ;
double temp_slope ;
double rho_shock ;
double temp_shock ;
double gas_frac ;
double rhobar ;
double metal ;
double rho ;
int i,j ;
int old_nsph ;
struct dark_particle *dp ;
/* Gas particles are created from dark matter particles.
* Masses are gas_frac * masses of dm particles
* dm particle masses are multiplied by (1-gas_frac).
* Temperatures are set to t=temp_y*(rho/rhobar)^temp_slope,
* or to t=temp_shock if rho/rhobar>rho_shock.
*/
if (!boxes_loaded[0]){
printf("<sorry, no boxes are loaded, %s>\n",title) ;
}
else {
if (sscanf(job,"%s %lf %lf %lf %lf %lf %lf %lf %s",command,&gas_frac,
&rhobar,&temp_y,&temp_slope,&rho_shock,&temp_shock,
&metal,g_type) == 8) {
calc_density(&box0_smx, 1, 0, 0);
header.nbodies += boxlist[0].ndark ;
old_nsph = header.nsph ;
header.nsph += boxlist[0].ndark ;
if(header.nsph != 0) {
gas_particles = (struct gas_particle *) realloc(gas_particles,
header.nsph*sizeof(*gas_particles));
if(gas_particles == NULL) {
printf("<sorry, no memory for gas particles, %s>\n",title) ;
return ;
}
mark_gas = (short *)realloc(mark_gas,header.nsph*sizeof(*mark_gas));
if(mark_gas == NULL) {
printf("<sorry, no memory for gas particle markers, %s>\n",
title) ;
return ;
}
for (i = old_nsph; i < header.nsph; i++) mark_gas[i] = 0;
}
else
gas_particles = NULL;
for (i = 0 ;i < boxlist[0].ndark ;i++) {
dp = boxlist[0].dp[i] ;
gas_particles[i+old_nsph].mass = gas_frac*(dp->mass) ;
dp->mass = (1. - gas_frac)*(dp->mass) ;
for(j = 0; j < header.ndim; j++){
gas_particles[i+old_nsph].pos[j] = dp->pos[j] ;
gas_particles[i+old_nsph].vel[j] = dp->vel[j] ;
}
gas_particles[i+old_nsph].rho =
gas_frac*(box0_smx->kd->p[i].fDensity);
gas_particles[i+old_nsph].temp = temp_y*
pow((gas_particles[i+old_nsph].rho/rhobar),temp_slope) ;
if (gas_particles[i+old_nsph].rho > rhobar*rho_shock) {
gas_particles[i+old_nsph].temp = temp_shock ;
}
gas_particles[i+old_nsph].hsmooth =
sqrt(box0_smx->kd->p[i].fBall2)/2.0;
gas_particles[i+old_nsph].metals = metal ;
gas_particles[i+old_nsph].phi = dp->phi ;
}
if(box0_smx) {
kdFinish(box0_smx->kd);
smFinish(box0_smx);
box0_smx = NULL;
}
boxes_loaded[0] = NO ;
unload_all() ;
active_box = 0 ;
binary_loaded = LOADED ;
current_project = NO ;
current_color = NO ;
divv_loaded = NO ;
hneutral_loaded = NO ;
meanmwt_loaded = NO ;
xray_loaded = NO ;
dudt_loaded = NO ;
starform_loaded = NO ;
}
else if (sscanf(job,"%s %lf %lf %lf %lf %lf %lf %lf %s",command,
&gas_frac,&rhobar,&temp_y,&temp_slope,&rho_shock,
&temp_shock,&metal,g_type) == 9) {
if (strcmp(g_type,"destroy") != 0 && strcmp(g_type,"d") != 0){
printf("<sorry, %s is not a gasify type, %s",g_type,title) ;
return;
}
calc_density(&box0_smx, 1, 0, 0);
printf("<warning, destroying original dark and gas particles, %s>\n",
title) ;
header.nbodies -= header.nsph ;
header.nsph = boxlist[0].ndark ;
header.ndark = 0 ;
if(header.nsph != 0) {
dark_particles = (struct dark_particle *) realloc(dark_particles,
header.nsph*sizeof(*gas_particles));
if(dark_particles == NULL) {
printf("<sorry, no memory for gas particles, %s>\n",title) ;
return ;
}
gas_particles = (struct gas_particle *)dark_particles ;
free(mark_dark) ;
if(header.nsph != 0)
mark_gas = (short *)calloc(header.nsph, sizeof(*mark_gas));
if(mark_gas == NULL && header.nsph != 0) {
printf("<sorry, no memory for gas particle markers, %s>\n",
title) ;
return ;
}
for (i = 0; i < header.nsph; i++) mark_gas[i] = 0;
}
else
gas_particles = NULL;
for (i = boxlist[0].ndark - 1 ;i >= 0 ;i--) {
dp = boxlist[0].dp[i] ;
gas_particles[i].phi = dp->phi ;
gas_particles[i].metals = metal ;
gas_particles[i].hsmooth = sqrt(box0_smx->kd->p[i].fBall2)/2.0;
rho = gas_frac*(box0_smx->kd->p[i].fDensity);
gas_particles[i].temp = temp_y*pow((rho/rhobar),temp_slope) ;
if (rho > rhobar*rho_shock) {
gas_particles[i].temp = temp_shock ;
}
gas_particles[i].rho = rho ;
for(j = header.ndim - 1; j >= 0; j--){
gas_particles[i+old_nsph].vel[j] = dp->vel[j] ;
}
for(j = header.ndim - 1; j >= 0; j--){
gas_particles[i+old_nsph].pos[j] = dp->pos[j] ;
}
gas_particles[i].mass = gas_frac*(dp->mass) ;
}
if(box0_smx) {
kdFinish(box0_smx->kd);
smFinish(box0_smx);
box0_smx = NULL;
}
dark_particles = NULL;
boxes_loaded[0] = NO ;
unload_all() ;
active_box = 0 ;
binary_loaded = LOADED ;
current_project = NO ;
current_color = NO ;
divv_loaded = NO ;
hneutral_loaded = NO ;
meanmwt_loaded = NO ;
xray_loaded = NO ;
starform_loaded = NO ;
dudt_loaded = NO ;
}
else {
input_error(command) ;
}
}
}
|
FavioVazquez/MexicanNumericalSimulationSchool
|
preschool/tipsy-2.2.3d/code/gasify.c
|
C
|
gpl-3.0
| 5,301
|
/*
** AACPlayer - Freeware Advanced Audio (AAC) Player for Android
** Copyright (C) 2011 Spolecne s.r.o., http://www.biophysics.com
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
**/
#define AACD_MODULE "Decoder[FFMPEG/WMA]"
#include "aac-array-common.h"
#include <string.h>
#include "libavcodec/avcodec.h"
#include "libavcodec/aac_parser.h"
#include "libavcodec/get_bits.h"
#include "libavcodec/mpeg4audio.h"
#include "libavutil/mem.h"
#include "libavutil/log.h"
#include "libavformat/avformat.h"
typedef struct AACDFFmpegInfo {
AACDCommonInfo *cinfo;
AVInputFormat *avifmt;
AVFormatContext *avfctx;
AVPacket *avpkt;
AVPacket *pkt;
int audio_stream_index;
unsigned int bytesconsumed;
} AACDFFmpegInfo;
extern AVCodec wmav1_decoder;
extern AVCodec wmav2_decoder;
extern AVInputFormat asf_demuxer;
static const char* aacd_ffwma_name()
{
return "FFmpeg/WMA";
}
static const char *aacd_ffwma_logname( void *ctx )
{
return AACD_MODULE;
}
/**
* Creates a new AVPacket.
*/
static AVPacket* aacd_ff_create_avpkt()
{
AVPacket *avpkt = (AVPacket*) av_mallocz( sizeof(AVPacket));
avpkt->data = NULL;
avpkt->size = 0;
return avpkt;
}
/**
* A wrapper method which reads packets.
* It only reads them from the internal pre-fetched buffer in AACDCommonInfo.
*/
static int aacd_ff_io_read_packet( void *opaque, uint8_t *buf, int buf_size)
{
AACD_TRACE( "io_read_packet() start" );
AACDFFmpegInfo *ff = (AACDFFmpegInfo*) opaque;
AACDCommonInfo *cinfo = ff->cinfo;
if (cinfo->bytesleft < buf_size)
{
// Let's cheat now:
AACDArrayInfo *ainfo = (AACDArrayInfo*) cinfo;
if (!aacda_read_buffer( ainfo ))
{
AACD_INFO( "io_read_packet() EOF detected" );
}
}
int len = buf_size < cinfo->bytesleft ? buf_size : cinfo->bytesleft;
if (!len)
{
AACD_WARN( "read_packet(): no bytes left, returning 0" );
return 0;
}
memcpy( buf, cinfo->buffer, len );
cinfo->buffer += len;
cinfo->bytesleft -= len;
ff->bytesconsumed += len;
AACD_TRACE( "io_read_packet() stop" );
return len;
}
/**
* Creates a new ByteIOContext.
*/
static ByteIOContext* aacd_ff_create_byteioctx( AACDFFmpegInfo *ff )
{
int buffer_size = ff->cinfo->bbsize;
unsigned char *buffer = av_mallocz( buffer_size );
ByteIOContext *pb = av_alloc_put_byte( buffer, buffer_size, 0, ff, aacd_ff_io_read_packet, NULL, NULL);
if (!pb)
{
av_free( buffer );
AACD_WARN( "create_byteioctx(): ByteIOContext could not be created" );
}
return pb;
}
/**
* Destroys a ByteIOContext.
*/
static void aacd_ff_destroy_byteioctx( ByteIOContext *pb )
{
if (!pb) return;
if (pb->buffer) av_free( pb->buffer );
av_free( pb );
}
/**
* Destroys our context.
*/
static void aacd_ff_destroy( AACDFFmpegInfo *ff )
{
if ( !ff ) return;
AACD_TRACE( "destroy() start" );
AVFormatContext *ic = ff->avfctx;
if ( ic )
{
if ( ff->audio_stream_index > -1) avcodec_close( ic->streams[ff->audio_stream_index]->codec );
ByteIOContext *pb = ic->pb;
av_close_input_stream( ff->avfctx );
if ( pb ) aacd_ff_destroy_byteioctx( pb );
}
if (ff->avpkt) av_free( ff->avpkt );
if (ff->pkt) av_free( ff->pkt );
av_free( ff );
AACD_TRACE( "destroy() stop" );
}
static void aacd_ffwma_stop( AACDCommonInfo *cinfo, void *ext )
{
if ( !ext ) return;
AACDFFmpegInfo *ff = (AACDFFmpegInfo*) ext;
aacd_ff_destroy( ff );
}
/**
* Initializes our context.
*/
static int aacd_ff_init( void **pext, AVInputFormat *fmt )
{
AACD_TRACE( "init() start" );
av_log_set_level( AV_LOG_VERBOSE );
AACDFFmpegInfo *ff = (AACDFFmpegInfo*) av_mallocz( sizeof(struct AACDFFmpegInfo));
if (!ff) return -1;
ff->avpkt = aacd_ff_create_avpkt();
ff->pkt = aacd_ff_create_avpkt();
if (!ff->avpkt || !ff->pkt)
{
AACD_ERROR( "init() out of memory error !" );
aacd_ff_destroy( ff );
return -2;
}
ff->avifmt = fmt;
ff->audio_stream_index = -1;
av_log( ff->avfctx, AV_LOG_INFO, "Test of AV_LOG_INFO\n" );
av_log( ff->avfctx, AV_LOG_DEBUG, "Test of AV_LOG_DEBUG\n" );
av_log( ff->avfctx, AV_LOG_VERBOSE, "Test of AV_LOG_VERBOSE\n" );
(*pext) = ff;
AACD_TRACE( "init() stop" );
return 0;
}
static int aacd_ffwma_init( void **pext )
{
return aacd_ff_init( pext, &asf_demuxer );
}
/**
* Finds a stream's position or return -1.
* This method also discards all streams.
*/
static int aacd_ff_find_stream( AVFormatContext *ic, enum AVMediaType codec_type )
{
int i;
int ret = -1;
for (i = 0; i < ic->nb_streams; i++)
{
AVStream *st = ic->streams[i];
AVCodecContext *avctx = st->codec;
st->discard = AVDISCARD_ALL;
if (ret == -1 && avctx->codec_type == codec_type) ret = i;
}
return ret;
}
/**
* Simple method for looking up only our supported codecs.
*/
static AVCodec* aacd_ffwma_find_codec( enum CodecID id )
{
switch (id)
{
case CODEC_ID_WMAV1: return &wmav1_decoder;
case CODEC_ID_WMAV2: return &wmav2_decoder;
}
return NULL;
}
static long aacd_ffwma_start( AACDCommonInfo *cinfo, void *ext, unsigned char *buffer, unsigned long buffer_size)
{
AACD_TRACE( "start() start" );
AACDFFmpegInfo *ff = (AACDFFmpegInfo*) ext;
ff->cinfo = cinfo;
// take control over the input reading:
cinfo->input_ctrl = 1;
ByteIOContext *pb = aacd_ff_create_byteioctx( ff );
if (!pb) return -1;
AACD_TRACE( "start() opening stream" );
ff->bytesconsumed = 0;
int err = av_open_input_stream( &ff->avfctx, pb, "filename.asf", ff->avifmt, NULL );
AVFormatContext *ic = ff->avfctx;
if (err)
{
char s[80];
av_strerror( err, s, 80);
AACD_ERROR("start() cannot open demuxer - [%d] - $s", err, s );
// we must dealloc what we allocated locally:
aacd_ff_destroy_byteioctx( pb );
return -1;
}
AACD_TRACE( "start() stream opened" );
//err = av_find_stream_info(ic)
AACD_DEBUG( "start() streams=%d", ic->nb_streams);
dump_format(ic, 0, "", 0);
ff->audio_stream_index = aacd_ff_find_stream( ic, AVMEDIA_TYPE_AUDIO );
if (ff->audio_stream_index < 0)
{
AACD_ERROR( "start() cannot find audio stream" );
return -1;
}
AVStream *st = ic->streams[ff->audio_stream_index];
st->discard = AVDISCARD_DEFAULT;
AVCodecContext *avctx = st->codec;
AACD_DEBUG( "start() samplerate=%d channels=%d codec=%x", avctx->sample_rate, avctx->channels, avctx->codec_id);
AVCodec *codec = aacd_ffwma_find_codec( avctx->codec_id );
if (!codec)
{
AACD_ERROR("start() audio - not a WMA codec - %x", avctx->codec_id);
return -1;
}
if (avcodec_open( avctx, codec ))
{
AACD_ERROR("start() audio cannot open audio codec - %x", avctx->codec_id);
return -1;
}
cinfo->samplerate = avctx->sample_rate;
cinfo->channels = avctx->channels;
AACD_TRACE( "start() stop - ic->format=%x, ff->avfctx->format=%x", ic->iformat, ff->avfctx->iformat );
// we return more than we consumed:
return ff->bytesconsumed;
}
static int aacd_ffwma_decode( AACDCommonInfo *cinfo, void *ext, unsigned char *buffer, unsigned long buffer_size, jshort *jsamples, jint outLen )
{
AACD_TRACE( "decode() start" );
AACDFFmpegInfo *ff = (AACDFFmpegInfo*) ext;
AVFormatContext *ic = ff->avfctx;
AVPacket *avpkt = ff->avpkt;
AVPacket *pkt = ff->pkt;
ff->bytesconsumed = 0;
#ifdef AACD_LOGLEVEL_TRACE
ic->debug = FF_FDEBUG_TS;
#endif
while (!pkt->size)
{
AACD_TRACE( "decode() calling av_read_frame..." );
int err = av_read_frame( ic, avpkt );
AACD_TRACE( "decode() av_read_frame returned: %d", err );
if (err < 0)
{
AACD_ERROR( "decode() cannot read av frame" );
return AACD_DECODE_EOF;
}
if (avpkt->stream_index == ff->audio_stream_index)
{
pkt->data = avpkt->data;
pkt->size = avpkt->size;
break;
}
// TODO: delete packet's buffer ?
AACD_TRACE( "decode() : freeing packet's data" );
av_freep( &avpkt->data );
}
AACD_TRACE( "decode() packet demuxed, will decode..." );
AVCodecContext *avctx = ic->streams[ff->audio_stream_index]->codec;
AVCodec *codec = avctx->codec;
AACD_DEBUG( "decode() frame_size=%d", avctx->frame_size );
// aac_decode_frame
int outSize = outLen * 2;
int consumed = (*codec->decode)( avctx, jsamples, &outSize, pkt );
if (consumed <= 0)
{
AACD_ERROR( "decode() cannot decode frame pkt->size=%d, outSize=%d, error: %d", pkt->size, outSize, consumed );
if ( cinfo->frame_samples < outLen * 3 / 2 )
{
AACD_WARN( "decode() trying to obtain large output buffer" );
return AACD_DECODE_OUTPUT_NEEDED;
}
pkt->size = 0;
return AACD_DECODE_OTHER;
}
pkt->data += consumed;
pkt->size -= consumed;
cinfo->frame_bytesconsumed = consumed;
//cinfo->frame_samples = avctx->frame_size * avctx->channels;
cinfo->frame_samples = (outSize >> 1);
AACD_TRACE( "decode() stop - consumed %d, pkt->size=%d", consumed, pkt->size );
return AACD_DECODE_OK;
}
static int aacd_ffwma_probe( unsigned char *buffer, int len )
{
return 0;
}
AACDDecoder aacd_ffmpeg_wma_decoder = {
aacd_ffwma_name,
aacd_ffwma_init,
aacd_ffwma_start,
aacd_ffwma_decode,
aacd_ffwma_stop,
aacd_ffwma_probe
};
|
gmavenis/RadioPlayer
|
jni/aac-decoder/aac-ffmpeg-wma-decoder.c
|
C
|
gpl-3.0
| 10,374
|
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fap.h>
#define EXIT_SUCCESS 0
char *readstdin(void);
int main()
{
char* input;
unsigned int input_len;
fap_packet_t* packet;
char fap_error_output[1024];
fap_init();
/* Get packet to parse from stdin */
input = readstdin();
input_len = strlen(input);
/* Process the packet. */
packet = fap_parseaprs(input, input_len, 0);
if ( packet->error_code ) {
fap_explain_error(*packet->error_code, fap_error_output);
printf("Failed to parse packet (%s): %s\n",
input, fap_error_output);
} else if ( packet->src_callsign ) {
printf("Got packet from %s.\n", packet->src_callsign);
}
fap_free(packet);
fap_cleanup();
return EXIT_SUCCESS;
}
char *readstdin(void)
{
#define BUF_SIZE 1024
char buffer[BUF_SIZE];
size_t contentSize = 1; /* includes NULL */
/* Preallocate space. We could just allocate one char here,
but that wouldn't be efficient. */
char *content = malloc(sizeof(char) * BUF_SIZE);
if(content == NULL) {
perror("Failed to allocate content");
exit(1);
}
content[0] = '\0'; /* null-terminated */
while(fgets(buffer, BUF_SIZE, stdin)) {
char *old = content;
contentSize += strlen(buffer);
content = realloc(content, contentSize);
if(content == NULL) {
perror("Failed to reallocate content");
free(old);
exit(2);
}
strcat(content, buffer);
}
if(ferror(stdin)) {
free(content);
perror("Error reading from stdin.");
exit(3);
}
return(content);
}
|
n7nix/dantracker
|
faptest.c
|
C
|
gpl-3.0
| 1,515
|
#include <thread.h>
#include <processor.h>
#include <interrupt.h>
#include <printk.h>
_Atomic long long min_time = 0;
static struct thread *__select_thread(struct processor *proc)
{
/* throw the old process back on the queue */
spinlock_acquire(&proc->schedlock);
if(current_thread->flags & THREAD_DEAD)
current_thread->flags |= THREAD_GONE;
if(likely(proc->running->state == THREADSTATE_RUNNING && proc->running != &proc->idle_thread)) {
if(likely(!(atomic_fetch_or(&proc->running->flags, THREAD_ONQUEUE) & THREAD_ONQUEUE))) {
assert(proc->running == current_thread && !(current_thread->flags & THREAD_DEAD));
priqueue_insert(&proc->runqueue, &proc->running->runqueue_node, proc->running, thread_current_priority(proc->running));
}
}
struct thread *thread = priqueue_pop(&proc->runqueue);
if(unlikely(!thread))
thread = &proc->idle_thread;
else {
thread->flags &= ~THREAD_ONQUEUE;
}
if(((thread->flags & THREAD_UNINTER) && thread->state != THREADSTATE_RUNNING) || thread->flags & THREAD_DEAD) {
thread = &proc->idle_thread;
}
/* this is a weird edge case (that should probably get fixed up, TODO):
* if a thread exits and another thread unblocks that exiting thread (for
* example, it gets a signal), then the thread may be added to the runqueue
* during its exiting. Threads that are exiting don't "remove" themselves from
* the runqueue because that happens in the scheduler above, so they could be
* in the runqueue in an unrunnable state. Then, another thread creates a new
* thread and the slab allocator returns the recently exited thread. The flags
* are cleared and the scheduler is then free to run that "new" thread...with the
* old state. Thus allowing the thread to reach the unreachable part of thread_exit.
*
* So, if a thread's state is INIT, then don't run it. Wait until the creating thread
* sets it to runable. */
if(unlikely(thread->state == THREADSTATE_INIT)) {
thread = &proc->idle_thread;
}
proc->running = thread;
spinlock_release(&proc->schedlock);
return thread;
}
static void _check_signals(struct thread *thread)
{
spinlock_acquire(&thread->signal_lock);
if(!sigisemptyset(&thread->pending_signals)) {
for(int i = 1; i < _NSIG; i++) {
if(sigismember(&thread->pending_signals, i)) {
sigdelset(&thread->pending_signals, i);
thread->signal = i;
if(!(thread->flags & THREAD_UNINTER)) {
thread->state = THREADSTATE_RUNNING;
thread->processor->running = thread;
}
break;
}
}
}
spinlock_release(&thread->signal_lock);
}
static void __do_schedule(int save_preempt)
{
int old = arch_interrupt_set(0);
struct processor *curproc = processor_get_current();
struct workqueue *wq = &curproc->workqueue;
int preempt_old = curproc->preempt_disable - 1 /* -1 for the handle of curproc we hold */;
assert(preempt_old >= 0);
if(!save_preempt && curproc->preempt_disable > 1) {
processor_release(curproc);
arch_interrupt_set(old);
return;
} else {
curproc->preempt_disable = 1;
}
#if CONFIG_DEBUG
//assert(current_thread->held_spinlocks == 0);
#endif
_check_signals(current_thread);
struct thread *next = __select_thread(curproc);
processor_release(curproc);
current_thread->flags &= ~THREAD_RESCHEDULE;
if(next != current_thread) {
//printk(":%d: %ld -> %ld\n", curproc->id, current_thread->tid, next->tid);
arch_thread_context_switch(current_thread, next);
_check_signals(current_thread);
}
if(save_preempt) {
/* we're playing fast-and-loose here with references. We know that we'll be
* fine since we've disabled interrupts, so we can technically drop the reference
* to curproc before we get here... uhg */
curproc->preempt_disable = preempt_old;
}
arch_interrupt_set(old);
/* threads have to do some kernel work! */
if(!save_preempt && !workqueue_empty(wq)) {
workqueue_execute(wq);
}
}
void schedule()
{
__do_schedule(1);
}
void preempt()
{
__do_schedule(0);
}
|
Dennisbonke/DB-OS
|
kernel/schedule.c
|
C
|
gpl-3.0
| 3,944
|
/*****************************************************************************\
* $Id: ipmiping.c,v 1.75 2010-02-08 22:02:31 chu11 Exp $
*****************************************************************************
* Copyright (C) 2007-2015 Lawrence Livermore National Security, LLC.
* Copyright (C) 2003-2007 The Regents of the University of California.
* Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
* Written by Albert Chu <chu11@llnl.gov>
* UCRL-CODE-155448
*
* This file is part of Ipmiping, tools for pinging IPMI and RMCP compliant
* remote systems. For details, see http://www.llnl.gov/linux/.
*
* Ipmiping is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* Ipmiping is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with Ipmiping. If not, see <http://www.gnu.org/licenses/>.
\*****************************************************************************/
#if HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#include <stdio.h>
#include <stdlib.h>
#if STDC_HEADERS
#include <string.h>
#endif /* STDC_HEADERS */
#if HAVE_UNISTD_H
#include <unistd.h>
#endif /* HAVE_UNISTD_H */
#include <assert.h>
#include <errno.h>
#include <freeipmi/freeipmi.h>
#include "freeipmi-portability.h"
#include "debug-util.h"
#include "ping-tool-common.h"
#define _setstr(x) (x) ? "set" : "clear"
/* IPMI has a 6 bit sequence number */
#define IPMI_RQ_SEQ_MAX 0x3F
int
createpacket (const char *destination,
void *buf,
unsigned int buflen,
unsigned int sequence_number,
int version,
int debug)
{
fiid_obj_t obj_rmcp_hdr = NULL;
fiid_obj_t obj_lan_session_hdr = NULL;
fiid_obj_t obj_lan_msg_hdr = NULL;
fiid_obj_t obj_cmd = NULL;
int len;
assert (destination);
assert (buf);
assert (version == IPMI_PING_VERSION_1_5 || version == IPMI_PING_VERSION_2_0);
if (!buflen)
return (0);
if (!(obj_rmcp_hdr = fiid_obj_create (tmpl_rmcp_hdr)))
ipmi_ping_err_exit ("fiid_obj_create: %s", strerror (errno));
if (!(obj_lan_session_hdr = fiid_obj_create (tmpl_lan_session_hdr)))
ipmi_ping_err_exit ("fiid_obj_create: %s", strerror (errno));
if (!(obj_lan_msg_hdr = fiid_obj_create (tmpl_lan_msg_hdr_rq)))
ipmi_ping_err_exit ("fiid_obj_create: %s", strerror (errno));
if (!(obj_cmd = fiid_obj_create (tmpl_cmd_get_channel_authentication_capabilities_rq)))
ipmi_ping_err_exit ("fiid_obj_create: %s", strerror (errno));
if (fill_rmcp_hdr_ipmi (obj_rmcp_hdr) < 0)
ipmi_ping_err_exit ("fill_rmcp_hdr_ipmi: %s", strerror (errno));
if (fill_lan_session_hdr (IPMI_AUTHENTICATION_TYPE_NONE,
0,
0,
obj_lan_session_hdr) < 0)
ipmi_ping_err_exit ("fill_lan_session_hdr: %s", strerror (errno));
if (fill_lan_msg_hdr (IPMI_SLAVE_ADDRESS_BMC,
IPMI_NET_FN_APP_RQ,
IPMI_BMC_IPMB_LUN_BMC,
sequence_number % (IPMI_RQ_SEQ_MAX+1),
obj_lan_msg_hdr) < 0)
ipmi_ping_err_exit ("fill_lan_msg_hdr: %s", strerror (errno));
if (version == IPMI_PING_VERSION_1_5)
{
if (fill_cmd_get_channel_authentication_capabilities (IPMI_CHANNEL_NUMBER_CURRENT_CHANNEL,
IPMI_PRIVILEGE_LEVEL_USER,
IPMI_GET_IPMI_V15_DATA,
obj_cmd) < 0)
ipmi_ping_err_exit ("fill_cmd_get_channel_authentication_capabilities: %s", strerror (errno));
}
else
{
if (fill_cmd_get_channel_authentication_capabilities (IPMI_CHANNEL_NUMBER_CURRENT_CHANNEL,
IPMI_PRIVILEGE_LEVEL_USER,
IPMI_GET_IPMI_V20_EXTENDED_DATA,
obj_cmd) < 0)
ipmi_ping_err_exit ("fill_cmd_get_channel_authentication_capabilities: %s", strerror (errno));
}
if ((len = assemble_ipmi_lan_pkt (obj_rmcp_hdr,
obj_lan_session_hdr,
obj_lan_msg_hdr,
obj_cmd,
NULL,
0,
buf,
buflen,
IPMI_INTERFACE_FLAGS_DEFAULT)) < 0)
ipmi_ping_err_exit ("assemble_ipmi_lan_pkt: %s", strerror (errno));
if (debug)
{
char hdrbuf[DEBUG_UTIL_HDR_BUFLEN];
debug_hdr_cmd ((version == IPMI_PING_VERSION_1_5) ? DEBUG_UTIL_TYPE_IPMI_1_5 : DEBUG_UTIL_TYPE_IPMI_2_0,
DEBUG_UTIL_DIRECTION_REQUEST,
IPMI_NET_FN_APP_RQ,
IPMI_CMD_GET_CHANNEL_AUTHENTICATION_CAPABILITIES,
0,
hdrbuf,
DEBUG_UTIL_HDR_BUFLEN);
if (ipmi_dump_lan_packet (STDERR_FILENO,
destination,
hdrbuf,
NULL,
buf,
len,
tmpl_lan_msg_hdr_rq,
tmpl_cmd_get_channel_authentication_capabilities_rq) < 0)
ipmi_ping_err_exit ("ipmi_dump_lan_packet: %s", strerror (errno));
}
fiid_obj_destroy (obj_rmcp_hdr);
fiid_obj_destroy (obj_lan_session_hdr);
fiid_obj_destroy (obj_lan_msg_hdr);
fiid_obj_destroy (obj_cmd);
return (len);
}
int
parsepacket (const char *destination,
const void *buf,
unsigned int buflen,
const char *from,
unsigned int sequence_number,
int verbose,
int version,
int debug)
{
fiid_obj_t obj_rmcp_hdr = NULL;
fiid_obj_t obj_lan_session_hdr = NULL;
fiid_obj_t obj_lan_msg_hdr = NULL;
fiid_obj_t obj_cmd = NULL;
fiid_obj_t obj_lan_msg_trlr = NULL;
uint8_t req_seq, none, md2, md5, straight_password_key, oem,
anonymous_login, null_username, non_null_username,
user_level_authentication, per_message_authentication,
k_g, ipmi_v20_extended_capabilities_available, ipmi_v15, ipmi_v20;
uint64_t val;
int ret, rv = -1;
assert (destination);
assert (buf);
assert (from);
assert (version == IPMI_PING_VERSION_1_5 || version == IPMI_PING_VERSION_2_0);
if (!buflen)
return (0);
if (!(obj_rmcp_hdr = fiid_obj_create (tmpl_rmcp_hdr)))
ipmi_ping_err_exit ("fiid_obj_create: %s", strerror (errno));
if (!(obj_lan_session_hdr = fiid_obj_create (tmpl_lan_session_hdr)))
ipmi_ping_err_exit ("fiid_obj_create: %s", strerror (errno));
if (!(obj_lan_msg_hdr = fiid_obj_create (tmpl_lan_msg_hdr_rs)))
ipmi_ping_err_exit ("fiid_obj_create: %s", strerror (errno));
if (!(obj_cmd = fiid_obj_create (tmpl_cmd_get_channel_authentication_capabilities_rs)))
ipmi_ping_err_exit ("fiid_obj_create: %s", strerror (errno));
if (!(obj_lan_msg_trlr = fiid_obj_create (tmpl_lan_msg_trlr)))
ipmi_ping_err_exit ("fiid_obj_create: %s", strerror (errno));
if (debug)
{
char hdrbuf[DEBUG_UTIL_HDR_BUFLEN];
debug_hdr_cmd ((version == IPMI_PING_VERSION_1_5) ? DEBUG_UTIL_TYPE_IPMI_1_5 : DEBUG_UTIL_TYPE_IPMI_2_0,
DEBUG_UTIL_DIRECTION_RESPONSE,
IPMI_NET_FN_APP_RQ,
IPMI_CMD_GET_CHANNEL_AUTHENTICATION_CAPABILITIES,
0,
hdrbuf,
DEBUG_UTIL_HDR_BUFLEN);
if (ipmi_dump_lan_packet (STDERR_FILENO,
destination,
hdrbuf,
NULL,
buf,
buflen,
tmpl_lan_msg_hdr_rs,
tmpl_cmd_get_channel_authentication_capabilities_rs) < 0)
ipmi_ping_err_exit ("ipmi_dump_lan_packet: %s", strerror (errno));
}
if ((ret = ipmi_lan_check_packet_checksum (buf, buflen)) < 0)
ipmi_ping_err_exit ("ipmi_lan_check_checksum: %s", strerror (errno));
if (!ret)
{
if (debug)
fprintf (stderr, "%s(%d): checksum failed\n", __FUNCTION__, __LINE__);
rv = 0;
goto cleanup;
}
if ((ret = unassemble_ipmi_lan_pkt (buf,
buflen,
obj_rmcp_hdr,
obj_lan_session_hdr,
obj_lan_msg_hdr,
obj_cmd,
obj_lan_msg_trlr,
IPMI_INTERFACE_FLAGS_DEFAULT)) < 0)
ipmi_ping_err_exit ("unassemble_ipmi_lan_pkt: %s", strerror (errno));
if (!ret)
{
if (debug)
fprintf (stderr, "%s(%d): Could not unassemble packet\n", __FUNCTION__, __LINE__);
rv = 0;
goto cleanup;
}
if ((ret = ipmi_lan_check_net_fn (obj_lan_msg_hdr, IPMI_NET_FN_APP_RS)) < 0)
ipmi_ping_err_exit ("ipmi_lan_check_net_fn: %s", strerror (errno));
if (!ret)
{
if (debug)
fprintf (stderr, "%s(%d): net_fn failed\n", __FUNCTION__, __LINE__);
rv = 0;
goto cleanup;
}
if ((ret = ipmi_check_cmd (obj_cmd, IPMI_CMD_GET_CHANNEL_AUTHENTICATION_CAPABILITIES)) < 0)
ipmi_ping_err_exit ("ipmi_check_cmd: %s", strerror (errno));
if (!ret)
{
if (debug)
fprintf (stderr, "%s(%d): cmd failed\n", __FUNCTION__, __LINE__);
rv = 0;
goto cleanup;
}
if ((ret = ipmi_check_completion_code_success (obj_cmd)) < 0)
ipmi_ping_err_exit ("ipmi_check_comp_code: %s", strerror (errno));
if (!ret)
{
if (debug)
fprintf (stderr, "%s(%d): comp_code failed\n", __FUNCTION__, __LINE__);
rv = 0;
goto cleanup;
}
if (FIID_OBJ_GET (obj_lan_msg_hdr,
"rq_seq",
&val) < 0)
ipmi_ping_err_exit ("fiid_obj_get: 'rq_seq': %s",
fiid_obj_errormsg (obj_lan_msg_hdr));
req_seq = val;
if (req_seq != sequence_number % (IPMI_RQ_SEQ_MAX + 1))
{
if (debug)
fprintf (stderr, "%s(%d): req_seq failed\n", __FUNCTION__, __LINE__);
rv = 0;
goto cleanup;
}
printf ("response received from %s: rq_seq=%u", from, req_seq);
if (verbose)
{
if (FIID_OBJ_GET (obj_cmd,
"authentication_type.none",
&val) < 0)
ipmi_ping_err_exit ("fiid_obj_get: 'authentication_type.none': %s",
fiid_obj_errormsg (obj_cmd));
none = val;
if (FIID_OBJ_GET (obj_cmd,
"authentication_type.md2",
&val) < 0)
ipmi_ping_err_exit ("fiid_obj_get: 'authentication_type.md2': %s",
fiid_obj_errormsg (obj_cmd));
md2 = val;
if (FIID_OBJ_GET (obj_cmd,
"authentication_type.md5",
&val) < 0)
ipmi_ping_err_exit ("fiid_obj_get: 'authentication_type.md5': %s",
fiid_obj_errormsg (obj_cmd));
md5 = val;
if (FIID_OBJ_GET (obj_cmd,
"authentication_type.straight_password_key",
&val) < 0)
ipmi_ping_err_exit ("fiid_obj_get: 'authentication_type.straight_password_key': %s",
fiid_obj_errormsg (obj_cmd));
straight_password_key = val;
if (FIID_OBJ_GET (obj_cmd,
"authentication_type.oem_prop",
&val) < 0)
ipmi_ping_err_exit ("fiid_obj_get: 'authentication_type.oem_prop': %s",
fiid_obj_errormsg (obj_cmd));
oem = val;
if (FIID_OBJ_GET (obj_cmd,
"authentication_status.anonymous_login",
&val) < 0)
ipmi_ping_err_exit ("fiid_obj_get: 'authentication_status.anonymous_login': %s",
fiid_obj_errormsg (obj_cmd));
anonymous_login = val;
if (FIID_OBJ_GET (obj_cmd,
"authentication_status.null_username",
&val) < 0)
ipmi_ping_err_exit ("fiid_obj_get: 'authentication_status.null_username': %s",
fiid_obj_errormsg (obj_cmd));
null_username = val;
if (FIID_OBJ_GET (obj_cmd,
"authentication_status.non_null_username",
&val) < 0)
ipmi_ping_err_exit ("fiid_obj_get: 'authentication_status.non_null_username': %s",
fiid_obj_errormsg (obj_cmd));
non_null_username = val;
if (FIID_OBJ_GET (obj_cmd,
"authentication_status.user_level_authentication",
&val) < 0)
ipmi_ping_err_exit ("fiid_obj_get: 'authentication_status.user_level_authentication': %s",
fiid_obj_errormsg (obj_cmd));
user_level_authentication = val;
if (FIID_OBJ_GET (obj_cmd,
"authentication_status.per_message_authentication",
&val) < 0)
ipmi_ping_err_exit ("fiid_obj_get: 'authentication_status.per_message_authentication': %s",
fiid_obj_errormsg (obj_cmd));
per_message_authentication = val;
if (FIID_OBJ_GET (obj_cmd,
"authentication_status.per_message_authentication",
&val) < 0)
ipmi_ping_err_exit ("fiid_obj_get: 'authentication_status.per_message_authentication': %s",
fiid_obj_errormsg (obj_cmd));
per_message_authentication = val;
printf (", auth: none=%s md2=%s md5=%s password=%s oem=%s anon=%s null=%s non-null=%s user=%s permsg=%s ",
_setstr (none), _setstr (md2), _setstr (md5),
_setstr (straight_password_key),_setstr (oem),
_setstr (anonymous_login), _setstr (null_username),
_setstr (non_null_username), _setstr (user_level_authentication),
_setstr (per_message_authentication));
if (version == IPMI_PING_VERSION_2_0)
{
if (FIID_OBJ_GET (obj_cmd,
"authentication_type.ipmi_v2.0_extended_capabilities_available",
&val) < 0)
ipmi_ping_err_exit ("fiid_obj_get: 'authentication_type.ipmi_v2.0_extended_capabilities_available': %s",
fiid_obj_errormsg (obj_cmd));
ipmi_v20_extended_capabilities_available = val;
if (FIID_OBJ_GET (obj_cmd,
"authentication_status.k_g",
&val) < 0)
ipmi_ping_err_exit ("fiid_obj_get: 'authentication_status.k_g': %s",
fiid_obj_errormsg (obj_cmd));
k_g = val;
printf ("k_g=%s ipmi_v2.0_extended_capabilities_available=%s ",
_setstr (k_g),
_setstr (ipmi_v20_extended_capabilities_available));
if (ipmi_v20_extended_capabilities_available)
{
if (FIID_OBJ_GET (obj_cmd,
"channel_supports_ipmi_v1.5_connections",
&val) < 0)
ipmi_ping_err_exit ("fiid_obj_get: 'channel_supports_ipmi_v1.5_connections': %s",
fiid_obj_errormsg (obj_cmd));
ipmi_v15 = val;
if (FIID_OBJ_GET (obj_cmd,
"channel_supports_ipmi_v2.0_connections",
&val) < 0)
ipmi_ping_err_exit ("fiid_obj_get: 'channel_supports_ipmi_v2.0_connections': %s",
fiid_obj_errormsg (obj_cmd));
ipmi_v20 = val;
printf ("ipmi_v1.5=%s ipmi_v2.0=%s ", _setstr (ipmi_v15), _setstr (ipmi_v20));
}
}
}
printf ("\n");
rv = 1;
cleanup:
fiid_obj_destroy (obj_rmcp_hdr);
fiid_obj_destroy (obj_lan_session_hdr);
fiid_obj_destroy (obj_lan_msg_hdr);
fiid_obj_destroy (obj_cmd);
fiid_obj_destroy (obj_lan_msg_trlr);
return (rv);
}
void
latepacket (unsigned int sequence_number)
{
printf ("response timed out: rq_seq=%u\n", sequence_number % (IPMI_RQ_SEQ_MAX + 1));
}
int
endresult (const char *progname,
const char *dest,
unsigned int sent_count,
unsigned int recv_count)
{
double percent = 0;
assert (progname);
assert (dest);
if (sent_count > 0)
percent = ((double)(sent_count - recv_count)/sent_count)*100;
printf ("--- %s %s statistics ---\n", progname, dest);
printf ("%d requests transmitted, %d responses received in time, "
"%2.1f%% packet loss\n",
sent_count, recv_count, percent);
return ((recv_count > 0) ? 0 : 1);
}
int
main (int argc, char **argv)
{
ipmi_ping_setup (argc, argv, 0, IPMI_RQ_SEQ_MAX, "hVc:i:I:t:vr:s:d");
ipmi_ping_loop (createpacket, parsepacket, latepacket, endresult);
exit (EXIT_FAILURE); /* NOT REACHED */
}
|
chu11/freeipmi
|
ipmiping/ipmiping.c
|
C
|
gpl-3.0
| 17,845
|
/*
* Copyright (c) 2008, Jerome Fimes, Communications & Systemes <jerome.fimes@c-s.fr>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#define USE_OPJ_DEPRECATED
/* set this macro to enable profiling for the given test */
/* warning : in order to be effective, openjpeg must have been built with profiling enabled !! */
/*#define _PROFILE*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#ifdef _WIN32
#include <malloc.h>
#else
#include <stdlib.h>
#endif
#include "opj_config.h"
#include <stdlib.h>
#ifdef _WIN32
#include <windows.h>
#define strcasecmp _stricmp
#define strncasecmp _strnicmp
#else
#include <strings.h>
#endif /* _WIN32 */
#include "openjpeg.h"
#include "format_defs.h"
/* -------------------------------------------------------------------------- */
/* Declarations */
int get_file_format(const char *filename);
static int infile_format(const char *fname);
/* -------------------------------------------------------------------------- */
int get_file_format(const char *filename) {
unsigned int i;
static const char *extension[] = {"pgx", "pnm", "pgm", "ppm", "bmp","tif", "raw", "rawl", "tga", "png", "j2k", "jp2", "jpt", "j2c", "jpc" };
static const int format[] = { PGX_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, BMP_DFMT, TIF_DFMT, RAW_DFMT, RAWL_DFMT, TGA_DFMT, PNG_DFMT, J2K_CFMT, JP2_CFMT, JPT_CFMT, J2K_CFMT, J2K_CFMT };
char * ext = strrchr(filename, '.');
if (ext == NULL)
return -1;
ext++;
if(ext) {
for(i = 0; i < sizeof(format)/sizeof(*format); i++) {
if(strcasecmp(ext, extension[i]) == 0) {
return format[i];
}
}
}
return -1;
}
/* -------------------------------------------------------------------------- */
#define JP2_RFC3745_MAGIC "\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a"
#define JP2_MAGIC "\x0d\x0a\x87\x0a"
/* position 45: "\xff\x52" */
#define J2K_CODESTREAM_MAGIC "\xff\x4f\xff\x51"
static int infile_format(const char *fname)
{
FILE *reader;
const char *s, *magic_s;
int ext_format, magic_format;
unsigned char buf[12];
unsigned int l_nb_read;
reader = fopen(fname, "rb");
if (reader == NULL)
return -1;
memset(buf, 0, 12);
l_nb_read = (unsigned int)fread(buf, 1, 12, reader);
fclose(reader);
if (l_nb_read != 12)
return -1;
ext_format = get_file_format(fname);
if (ext_format == JPT_CFMT)
return JPT_CFMT;
if (memcmp(buf, JP2_RFC3745_MAGIC, 12) == 0 || memcmp(buf, JP2_MAGIC, 4) == 0) {
magic_format = JP2_CFMT;
magic_s = ".jp2";
}
else if (memcmp(buf, J2K_CODESTREAM_MAGIC, 4) == 0) {
magic_format = J2K_CFMT;
magic_s = ".j2k or .jpc or .j2c";
}
else
return -1;
if (magic_format == ext_format)
return ext_format;
s = fname + strlen(fname) - 4;
fputs("\n===========================================\n", stderr);
fprintf(stderr, "The extension of this file is incorrect.\n"
"FOUND %s. SHOULD BE %s\n", s, magic_s);
fputs("===========================================\n", stderr);
return magic_format;
}
/* -------------------------------------------------------------------------- */
/**
sample error debug callback expecting no client object
*/
static void error_callback(const char *msg, void *client_data) {
(void)client_data;
fprintf(stdout, "[ERROR] %s", msg);
}
/**
sample warning debug callback expecting no client object
*/
static void warning_callback(const char *msg, void *client_data) {
(void)client_data;
fprintf(stdout, "[WARNING] %s", msg);
}
/**
sample debug callback expecting no client object
*/
static void info_callback(const char *msg, void *client_data) {
(void)client_data;
fprintf(stdout, "[INFO] %s", msg);
}
/* -------------------------------------------------------------------------- */
int main (int argc, char *argv[])
{
opj_dparameters_t l_param;
opj_codec_t * l_codec;
opj_image_t * l_image;
FILE * l_file;
opj_stream_t * l_stream;
OPJ_UINT32 l_data_size;
OPJ_UINT32 l_max_data_size = 1000;
OPJ_UINT32 l_tile_index;
OPJ_BYTE * l_data = (OPJ_BYTE *) malloc(1000);
OPJ_BOOL l_go_on = OPJ_TRUE;
OPJ_UINT32 l_nb_comps=0 ;
OPJ_INT32 l_current_tile_x0,l_current_tile_y0,l_current_tile_x1,l_current_tile_y1;
int da_x0=0;
int da_y0=0;
int da_x1=1000;
int da_y1=1000;
char input_file[64];
/* should be test_tile_decoder 0 0 1000 1000 tte1.j2k */
if( argc == 6 )
{
da_x0=atoi(argv[1]);
da_y0=atoi(argv[2]);
da_x1=atoi(argv[3]);
da_y1=atoi(argv[4]);
strcpy(input_file,argv[5]);
}
else
{
da_x0=0;
da_y0=0;
da_x1=1000;
da_y1=1000;
strcpy(input_file,"test.j2k");
}
if (! l_data) {
return EXIT_FAILURE;
}
l_file = fopen(input_file,"rb");
if (! l_file)
{
fprintf(stdout, "ERROR while opening input file\n");
free(l_data);
return EXIT_FAILURE;
}
l_stream = opj_stream_create_default_file_stream(l_file,OPJ_TRUE);
if (!l_stream){
fclose(l_file);
free(l_data);
fprintf(stderr, "ERROR -> failed to create the stream from the file\n");
return EXIT_FAILURE;
}
/* Set the default decoding parameters */
opj_set_default_decoder_parameters(&l_param);
/* */
l_param.decod_format = infile_format(input_file);
/** you may here add custom decoding parameters */
/* do not use layer decoding limitations */
l_param.cp_layer = 0;
/* do not use resolutions reductions */
l_param.cp_reduce = 0;
/* to decode only a part of the image data */
/*opj_restrict_decoding(&l_param,0,0,1000,1000);*/
switch(l_param.decod_format) {
case J2K_CFMT: /* JPEG-2000 codestream */
{
/* Get a decoder handle */
l_codec = opj_create_decompress(OPJ_CODEC_J2K);
break;
}
case JP2_CFMT: /* JPEG 2000 compressed image data */
{
/* Get a decoder handle */
l_codec = opj_create_decompress(OPJ_CODEC_JP2);
break;
}
default:
{
fprintf(stderr, "ERROR -> Not a valid JPEG2000 file!\n");
fclose(l_file);
free(l_data);
opj_stream_destroy(l_stream);
return EXIT_FAILURE;
}
}
/* catch events using our callbacks and give a local context */
opj_set_info_handler(l_codec, info_callback,00);
opj_set_warning_handler(l_codec, warning_callback,00);
opj_set_error_handler(l_codec, error_callback,00);
/* Setup the decoder decoding parameters using user parameters */
if (! opj_setup_decoder(l_codec, &l_param))
{
fprintf(stderr, "ERROR -> j2k_dump: failed to setup the decoder\n");
fclose(l_file);
free(l_data);
opj_stream_destroy(l_stream);
opj_destroy_codec(l_codec);
return EXIT_FAILURE;
}
/* Read the main header of the codestream and if necessary the JP2 boxes*/
if (! opj_read_header(l_stream, l_codec, &l_image))
{
fprintf(stderr, "ERROR -> j2k_to_image: failed to read the header\n");
fclose(l_file);
free(l_data);
opj_stream_destroy(l_stream);
opj_destroy_codec(l_codec);
return EXIT_FAILURE;
}
if (!opj_set_decode_area(l_codec, l_image, da_x0, da_y0,da_x1, da_y1)){
fprintf(stderr, "ERROR -> j2k_to_image: failed to set the decoded area\n");
fclose(l_file);
free(l_data);
opj_stream_destroy(l_stream);
opj_destroy_codec(l_codec);
opj_image_destroy(l_image);
return EXIT_FAILURE;
}
while (l_go_on)
{
if (! opj_read_tile_header( l_codec,
l_stream,
&l_tile_index,
&l_data_size,
&l_current_tile_x0,
&l_current_tile_y0,
&l_current_tile_x1,
&l_current_tile_y1,
&l_nb_comps,
&l_go_on))
{
fclose(l_file);
free(l_data);
opj_stream_destroy(l_stream);
opj_destroy_codec(l_codec);
opj_image_destroy(l_image);
return EXIT_FAILURE;
}
if (l_go_on)
{
if (l_data_size > l_max_data_size)
{
OPJ_BYTE *l_new_data = (OPJ_BYTE *) realloc(l_data, l_data_size);
if (! l_new_data)
{
fclose(l_file);
free(l_new_data);
opj_stream_destroy(l_stream);
opj_destroy_codec(l_codec);
opj_image_destroy(l_image);
return EXIT_FAILURE;
}
l_data = l_new_data;
l_max_data_size = l_data_size;
}
if (! opj_decode_tile_data(l_codec,l_tile_index,l_data,l_data_size,l_stream))
{
fclose(l_file);
free(l_data);
opj_stream_destroy(l_stream);
opj_destroy_codec(l_codec);
opj_image_destroy(l_image);
return EXIT_FAILURE;
}
/** now should inspect image to know the reduction factor and then how to behave with data */
}
}
if (! opj_end_decompress(l_codec,l_stream))
{
fclose(l_file);
free(l_data);
opj_stream_destroy(l_stream);
opj_destroy_codec(l_codec);
opj_image_destroy(l_image);
return EXIT_FAILURE;
}
/* Free memory */
fclose(l_file);
free(l_data);
opj_stream_destroy(l_stream);
opj_destroy_codec(l_codec);
opj_image_destroy(l_image);
/* Print profiling*/
/*PROFPRINT();*/
return EXIT_SUCCESS;
}
|
Alexander-M-Waldman/local_currency_site
|
geodjango/openjpeg-2.0.1/tests/test_tile_decoder.c
|
C
|
gpl-3.0
| 13,343
|
/*
* G. Rilling, last modification: 3.2007
* gabriel.rilling@ens-lyon.fr
*
* code based on a student project by T. Boustane and G. Quellec, 11.03.2004
* supervised by P. Chainais (ISIMA - LIMOS - Universite Blaise Pascal - Clermont II
* email : pchainai@isima.fr).
*/
/************************************************************************/
/* */
/* GET INPUT DATA */
/* */
/************************************************************************/
input_t get_input(int nlhs,int nrhs,const mxArray *prhs[]) {
input_t input;
int n,i;
double *x,*y,*y_temp,*third,fourth;
input.stop_params.threshold = DEFAULT_THRESHOLD;
input.stop_params.tolerance = DEFAULT_TOLERANCE;
input.allocated_x=0;
#ifdef _ALT_MEXERRMSGTXT_
input.error_flag=0;
#endif
input.max_imfs=0;
input.is_circular=false;
/* argument checking*/
if (nrhs>5)
mexErrMsgTxt("Too many arguments");
if (nrhs<2)
mexErrMsgTxt("Not enough arguments");
if (nlhs>2)
mexErrMsgTxt("Too many output arguments");
if (!mxIsEmpty(prhs[0]))
if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) ||
mxIsSparse(prhs[0]) || !mxIsDouble(prhs[0]) ||
(mxGetNumberOfDimensions(prhs[0]) > 2))
mexErrMsgTxt("X must be either empty or a double precision real vector.");
if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) ||
mxIsSparse(prhs[1]) || !mxIsDouble(prhs[1]) ||
(mxGetNumberOfDimensions(prhs[1]) > 2))
mexErrMsgTxt("Y must be a double precision real vector.");
/* input reading: x and y */
n=GREATER(mxGetN(prhs[1]),mxGetM(prhs[1])); /* length of vector x */
if (mxIsEmpty(prhs[0])) {
input.allocated_x = 1;
x = (double *)malloc(n*sizeof(double));
for(i=0;i<n;i++) x[i] = i;
}
else
x=mxGetPr(prhs[0]);
y_temp=mxGetPr(prhs[1]);
/* Third argument, circularity */
if (nrhs>=3) {
if(!mxIsEmpty(prhs[2])) {
if (!mxIsLogical(prhs[2]) || mxGetNumberOfElements(prhs[2])!=1){
mexErrMsgTxt("CIRCULARITY must be boolean element");
} else {
input.is_circular = (bool)mxGetScalar(prhs[2]);
}
}
}
/* fourth argument */
if (nrhs>=4) {
if(!mxIsEmpty(prhs[3])) {
if (!mxIsNumeric(prhs[3]) || mxIsComplex(prhs[3]) || mxIsSparse(prhs[3])
|| !mxIsDouble(prhs[3]) || (mxGetN(prhs[3])!=1 && mxGetM(prhs[3])!=1))
mexErrMsgTxt("STOP must be a real vector of 1 or 2 elements");
i = GREATER(mxGetN(prhs[3]),mxGetM(prhs[3]));
if (i>2)
mexErrMsgTxt("STOP must be a vector of 1 or 2 elements");
third=mxGetPr(prhs[3]);
switch (i) {
case 1 : {
if (nrhs==4 && *third==(int)*third && *third > 0) {/* third argument is max_imfs */
input.max_imfs=(int)*third;
}
else {/* third argument is input.stop_params.threshold */
input.stop_params.threshold=*third;
}
}
break;
case 2 : {
input.stop_params.threshold=third[0];
input.stop_params.tolerance=third[1];
}
}
/* input checking */
if (input.stop_params.threshold <= 0){
mexErrMsgTxt("threshold must be a positive number");
}
if (input.stop_params.threshold >= 1){
mexWarnMsgTxt("threshold should be lower than 1");
}
if (input.stop_params.tolerance < 0 || input.stop_params.tolerance >= 1){
mexErrMsgTxt("tolerance must be a real number in [O,1]");
}
}
}
/* fifth argument */
if (nrhs==5) {
if (!mxIsEmpty(prhs[4])) { /* if empty -> do nothing */
if (!mxIsNumeric(prhs[4]) || mxIsComplex(prhs[4]) || mxIsSparse(prhs[4])
|| !mxIsDouble(prhs[4]) || mxGetN(prhs[4])!=1 || mxGetM(prhs[4])!=1)
mexErrMsgTxt("NB_IMFS must be a positive integer");
fourth=*mxGetPr(prhs[4]);
if ((unsigned int)fourth != fourth)
mexErrMsgTxt("NB_IMFS must be a positive integer");
input.max_imfs=(int)fourth;
}
}
/* more input checking */
if (!input.allocated_x && (SMALLER(mxGetN(prhs[0]),mxGetM(prhs[0]))!=1 ||
SMALLER(mxGetN(prhs[1]),mxGetM(prhs[1]))!=1))
mexErrMsgTxt("X and Y must be vectors");
if (GREATER(mxGetN(prhs[1]),mxGetM(prhs[1]))!=n)
mexErrMsgTxt("X and Y must have the same length");
i=1;
while (i<n && x[i]>x[i-1]) i++;
if (i<n) mexErrMsgTxt("Values in X must be non decreasing");
/* copy vector y to avoid erasing input data */
y=(double *)malloc(n*sizeof(double));
for (i=0;i<n;i++){
y[i]=y_temp[i];
}
input.n=n;
input.x=x;
input.y=y;
return input;
}
/************************************************************************/
/* */
/* INITIALIZATION OF THE LIST */
/* */
/************************************************************************/
imf_list_t init_imf_list(int n) {
imf_list_t list;
list.first=NULL;
list.last=NULL;
list.n=n;
list.m=0;
return list;
}
/************************************************************************/
/* */
/* ADD AN IMF TO THE LIST */
/* */
/************************************************************************/
void add_imf(imf_list_t *list,double *p,int nb_it) {
double *v=(double *)malloc(list->n*sizeof(double));
int i;
imf_t *mode=(imf_t *)malloc(sizeof(imf_t));
for (i=0;i<list->n;i++) v[i]=p[i];
mode->pointer=v;
mode->nb_iterations=nb_it;
mode->next=NULL;
if (!list->first) {
list->first=mode;
} else {
(list->last)->next=mode;
}
list->last=mode;
list->m++;
}
/************************************************************************/
/* */
/* FREE MEMORY ALLOCATED FOR THE LIST */
/* */
/************************************************************************/
void free_imf_list(imf_list_t list) {
imf_t *current=list.first, *previous;
while (current) {
previous=current;
current=current->next;
free(previous->pointer);
free(previous);
}
}
/************************************************************************/
/* */
/* OUTPUT INTO MATLAB ARRAY */
/* */
/************************************************************************/
void write_output(imf_list_t list,mxArray *plhs[]) {
double *out1,*out2;
imf_t *current;
int i=0,j,m=list.m,n=list.n;
plhs[0]=mxCreateDoubleMatrix(m,n,mxREAL);
out1=mxGetPr(plhs[0]);
plhs[1]=mxCreateDoubleMatrix(1,m-1,mxREAL);
out2=mxGetPr(plhs[1]);
for (current=list.first;current;current=current->next) {
for (j=0;j<n;j++){
*(out1+j*m+i)=current->pointer[j];
}
if (i<m-1) *(out2+i)=current->nb_iterations;
i++;
}
}
|
pintomollo/asset
|
MEX/io.c
|
C
|
gpl-3.0
| 7,428
|
/*****************************************************************************
* Written by Chris Dunlap <cdunlap@llnl.gov>.
* Copyright (C) 2007-2021 Lawrence Livermore National Security, LLC.
* Copyright (C) 2001-2007 The Regents of the University of California.
* UCRL-CODE-2002-009.
*
* This file is part of ConMan: The Console Manager.
* For details, see <https://dun.github.io/conman/>.
*
* ConMan is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* ConMan is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with ConMan. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
/* FIXME:
* This code does not fully handle the following cases:
* - when the watched directory does not yet exist
* - when the watched directory is later deleted
* In the event of the watched directory not yet existing, this code should
* watch the parent directory for its subsequent creation; if the parent
* does not yet exist, it should watch the parent's parent, etc., up to the
* root. This might be best accomplished by initially registering all of
* parent directories up to the root for the directory being watched.
* In the event of the watched directory being deleted (event IN_IGNORED),
* once the existing watch has been removed, this should degenerate into the
* case above where the watched directory does not yet exist.
*
* Currently, inotify works as expected as long as the parent directory being
* watched persists for the lifetime of the daemon. But once that
* directory's inode is removed, the daemon falls back to using timers to
* periodically resurrect downed objects.
*/
#if HAVE_CONFIG_H
# include <config.h>
#endif /* HAVE_CONFIG_H */
/*****************************************************************************
* Stubbed Routines for building without <sys/inotify.h>.
*
* These routines preserve type-checking while allowing any decent compiler
* to optimize the case of simply returning a constant integer such that
* no function call overhead is incurred.
*****************************************************************************/
#if ! HAVE_SYS_INOTIFY_H
#include "inevent.h"
int
inevent_add (const char *filename, inevent_cb_f cb_fnc, void *cb_arg)
{
return (-1);
}
int
inevent_remove (const char *filename)
{
return (-1);
}
int
inevent_get_fd (void)
{
return (-1);
}
int inevent_process (void)
{
return (-1);
}
/*****************************************************************************
* Routines for building with <sys/inotify.h> (Linux 2.6.13+).
*****************************************************************************/
#else /* HAVE_SYS_INOTIFY_H */
#include <assert.h>
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/inotify.h>
#include <unistd.h>
#include "inevent.h"
#include "list.h"
#include "log.h"
#include "util-file.h"
/*****************************************************************************
* Constants
*****************************************************************************/
/* Number of bytes for the average inotify event (w/ 16 bytes for name).
*/
#define INEVENT_SIZE ((sizeof (struct inotify_event)) + 16)
/* Number of average inotify events to process per read invocation.
*/
#define INEVENT_NUM 128
/* Number of bytes to allocate for the inotify event buffer.
*/
#define INEVENT_BUF_LEN ((INEVENT_SIZE) * (INEVENT_NUM))
/*****************************************************************************
* Internal Data Types
*****************************************************************************/
struct inevent {
char *pathname; /* pathname being watched */
char *dirname; /* directory component of pathname */
char *filename; /* filename component of pathname */
inevent_cb_f cb_fnc; /* callback function */
void *cb_arg; /* callback function arg */
int wd; /* inotify watch descriptor */
};
typedef struct inevent inevent_t;
/*****************************************************************************
* Private Function Prototypes
*****************************************************************************/
static int _inevent_init (void);
static void _inevent_fini (void);
static inevent_t * _inevent_create (const char *pathname,
inevent_cb_f cb_fnc, void *cb_arg);
static void _inevent_destroy (inevent_t *inevent_ptr);
static int _list_find_by_path (const inevent_t *inevent_ptr,
const char *pathname);
static int _list_find_by_wd (const inevent_t *inevent_ptr,
const int *wd_ptr);
static int _list_find_by_event (const inevent_t *inevent_ptr,
const struct inotify_event *event_ptr);
/*****************************************************************************
* Internal Data Variables
*****************************************************************************/
static int inevent_fd = -1; /* inotify file descriptor */
static List inevent_list = NULL; /* list of inevent structs */
/*****************************************************************************
* Public Functions
*****************************************************************************/
int
inevent_add (const char *pathname, inevent_cb_f cb_fnc, void *cb_arg)
{
/* Adds an inotify event for [pathname], causing [cb_fnc] to be invoked with
* [cb_arg] whenever the specified file is created.
* Returns 0 on success, or -1 on error.
*/
inevent_t *inevent_ptr;
if (pathname == NULL) {
log_msg (LOG_ERR, "inotify event pathname not specified");
return (-1);
}
if (cb_fnc == NULL) {
log_msg (LOG_ERR, "inotify event callback not specified");
return (-1);
}
if (pathname[0] != '/') {
log_msg (LOG_ERR, "inotify event path \"%s\" is not absolute",
pathname);
return (-1);
}
if (inevent_fd == -1) {
if (_inevent_init () < 0) {
log_msg (LOG_ERR, "unable to initialize inotify: %s",
strerror (errno));
return (-1);
}
}
if (list_find_first (inevent_list, (ListFindF) _list_find_by_path,
(void *) pathname)) {
log_msg (LOG_ERR, "inotify event path \"%s\" already specified",
pathname);
return (-1);
}
inevent_ptr = _inevent_create (pathname, cb_fnc, cb_arg);
if (inevent_ptr == NULL) {
return (-1);
}
list_append (inevent_list, inevent_ptr);
return (0);
}
int
inevent_remove (const char *pathname)
{
/* Removes the inotify event (if present) for [pathname].
* Returns 0 on success, or -1 on error.
*/
ListIterator li = NULL;
inevent_t *inevent_ptr;
int wd_cnt;
if (pathname == NULL) {
return (0);
}
if (inevent_list == NULL) {
return (0);
}
li = list_iterator_create (inevent_list);
inevent_ptr = list_find (li, (ListFindF) _list_find_by_path,
(void *) pathname);
if (inevent_ptr == NULL) {
log_msg (LOG_ERR, "inotify event path \"%s\" not registered",
pathname);
list_iterator_destroy (li);
return (0);
}
(void) list_remove (li);
list_iterator_reset (li);
wd_cnt = 0;
while (list_find (li, (ListFindF) _list_find_by_wd, &(inevent_ptr->wd))) {
wd_cnt++;
}
list_iterator_destroy (li);
/* If no other inevents were found with a matching wd, then this inevent
* is the only one associated with this watch descriptor. As such, the
* watch associated with this watch descriptor can be removed since no
* other objects are relying on it.
* Note that multiple files may share the same watch descriptor since it
* is the file's directory that is watched.
*/
if ((inevent_ptr->wd >= 0) && (wd_cnt == 0)) {
(void) inotify_rm_watch (inevent_fd, inevent_ptr->wd);
DPRINTF((10, "Removed inotify watch wd=%d for directory \"%s\".\n",
inevent_ptr->wd, inevent_ptr->dirname));
}
_inevent_destroy (inevent_ptr);
if (list_is_empty (inevent_list)) {
_inevent_fini ();
}
return (0);
}
int
inevent_get_fd (void)
{
/* Returns the file descriptor associated with the inotify event queue,
* or -1 on error.
*/
return (inevent_fd);
}
int
inevent_process (void)
{
/* Processes the callback functions for all available events in the inotify
* event queue.
* Returns the number of events processed on success, or -1 on error.
*/
char buf [INEVENT_BUF_LEN];
int len;
int n = 0;
if (inevent_fd == -1) {
return (-1);
}
retry_read:
len = read (inevent_fd, buf, sizeof (buf));
if (len < 0) {
if (errno == EINTR) {
goto retry_read;
}
log_msg (LOG_ERR, "unable to read inotify fd: %s", strerror (errno));
return (-1);
}
else if (len == 0) {
log_msg (LOG_ERR, "inotify read buffer is too small");
return (-1);
}
else {
unsigned int i = 0;
uint32_t event_mask = IN_CREATE | IN_MOVED_TO;
while (i < (unsigned int) len) {
struct inotify_event *event_ptr;
inevent_t *inevent_ptr;
event_ptr = (struct inotify_event *) &buf[i];
DPRINTF((15,
"Received inotify event wd=%d mask=0x%x len=%u name=\"%s\".\n",
event_ptr->wd, event_ptr->mask, event_ptr->len,
(event_ptr->len > 0 ? event_ptr->name : "")));
if (event_ptr->mask & IN_IGNORED) {
(void) list_delete_all (inevent_list,
(ListFindF) _list_find_by_wd, &(event_ptr->wd));
}
else if ((event_ptr->mask & event_mask) && (event_ptr->len > 0)) {
inevent_ptr = list_find_first (inevent_list,
(ListFindF) _list_find_by_event, event_ptr);
if ((inevent_ptr != NULL) && (inevent_ptr->cb_fnc != NULL)) {
inevent_ptr->cb_fnc (inevent_ptr->cb_arg);
}
}
i += sizeof (struct inotify_event) + event_ptr->len;
n++;
}
}
return (n);
}
/*****************************************************************************
* Private Functions
*****************************************************************************/
static int
_inevent_init (void)
{
/* Initializes the inotify event subsystem.
* Returns 0 on success, or -1 on error (with errno set).
*/
assert (inevent_fd == -1);
assert (inevent_list == NULL);
if (inevent_fd == -1) {
inevent_fd = inotify_init ();
if (inevent_fd == -1) {
goto err;
}
set_fd_closed_on_exec (inevent_fd);
set_fd_nonblocking (inevent_fd);
}
if (inevent_list == NULL) {
inevent_list = list_create ((ListDelF) _inevent_destroy);
if (inevent_list == NULL) {
goto err;
}
}
DPRINTF((5, "Initialized inotify event subsystem.\n"));
return (inevent_fd);
err:
_inevent_fini ();
return (-1);
}
static void
_inevent_fini (void)
{
/* Shuts down the inotify event subsystem.
*/
assert (inevent_fd >= 0);
assert (inevent_list != NULL);
if (inevent_fd >= 0) {
(void) close (inevent_fd);
inevent_fd = -1;
}
if (inevent_list != NULL) {
list_destroy (inevent_list);
inevent_list = NULL;
}
DPRINTF((5, "Shut down inotify event subsystem.\n"));
return;
}
static inevent_t *
_inevent_create (const char *pathname, inevent_cb_f cb_fnc, void *cb_arg)
{
/* Creates an inotify event object for [cb_fnc] to be invoked with [cb_arg]
* whenever the file specified by [pathname] is created.
* Returns a pointer to the new object on success, or NULL on error
* (with errno set).
*/
inevent_t *inevent_ptr = NULL;
char *p;
uint32_t event_mask = IN_CREATE | IN_MOVED_TO;
assert (pathname != NULL);
assert (pathname[0] == '/');
assert (cb_fnc != NULL);
inevent_ptr = malloc (sizeof (*inevent_ptr));
if (inevent_ptr == NULL) {
goto err;
}
memset (inevent_ptr, 0, sizeof (*inevent_ptr));
inevent_ptr->wd = -1;
inevent_ptr->pathname = strdup (pathname);
if (inevent_ptr->pathname == NULL) {
goto err;
}
inevent_ptr->dirname = strdup (pathname);
if (inevent_ptr->dirname == NULL) {
goto err;
}
p = strrchr (inevent_ptr->dirname, '/');
inevent_ptr->filename = strdup (p + 1);
if (inevent_ptr->filename == NULL) {
goto err;
}
if (p == inevent_ptr->dirname) { /* dirname is root directory ("/") */
*++p = '\0';
}
else {
*p = '\0';
}
inevent_ptr->cb_fnc = cb_fnc;
inevent_ptr->cb_arg = cb_arg;
inevent_ptr->wd = inotify_add_watch (inevent_fd, inevent_ptr->dirname,
event_mask);
if (inevent_ptr->wd == -1) {
goto err;
}
DPRINTF((10, "Added inotify watch wd=%d for \"%s\".\n",
inevent_ptr->wd, inevent_ptr->pathname));
return (inevent_ptr);
err:
_inevent_destroy (inevent_ptr);
return (NULL);
}
static void
_inevent_destroy (inevent_t *inevent_ptr)
{
/* Destroys the inotify event object referenced by [inevent_ptr].
*/
assert (inevent_ptr != NULL);
if (inevent_ptr == NULL) {
return;
}
DPRINTF((10, "Removed inotify watch wd=%d for \"%s\".\n",
inevent_ptr->wd, inevent_ptr->pathname));
if (inevent_ptr->pathname != NULL) {
free (inevent_ptr->pathname);
}
if (inevent_ptr->dirname != NULL) {
free (inevent_ptr->dirname);
}
if (inevent_ptr->filename != NULL) {
free (inevent_ptr->filename);
}
free (inevent_ptr);
return;
}
static int
_list_find_by_path (const inevent_t *inevent_ptr, const char *pathname)
{
/* List function helper to match items in a list of inevent_t pointers using
* the pathname [pathname] as the key.
* Returns non-zero if the key is found; o/w, returns zero.
*/
assert (inevent_ptr != NULL);
assert (pathname != NULL);
return (strcmp (inevent_ptr->pathname, pathname) == 0);
}
static int
_list_find_by_wd (const inevent_t *inevent_ptr, const int *wd_ptr)
{
/* List function helper to match items in a list of inevent_t pointers using
* a pointer to an inotify watch descriptor [wd_ptr] as the key.
* Returns non-zero if the key is found; o/w, returns zero.
*/
assert (inevent_ptr != NULL);
assert (wd_ptr != NULL);
return (inevent_ptr->wd == *wd_ptr);
}
static int
_list_find_by_event (const inevent_t *inevent_ptr,
const struct inotify_event *event_ptr)
{
/* List function helper to match items in a list of inevent_t pointers using
* a pointer to an inotify_event struct [event_ptr] as the key.
* Returns non-zero if the key is found; o/w, returns zero.
*/
assert (inevent_ptr != NULL);
assert (inevent_ptr->filename != NULL);
assert (event_ptr != NULL);
assert (event_ptr->len > 0);
assert (event_ptr->name != NULL);
return ((inevent_ptr->wd == event_ptr->wd) &&
(strcmp (inevent_ptr->filename, event_ptr->name) == 0));
}
#endif /* HAVE_SYS_INOTIFY_H */
|
dun/conman
|
inevent.c
|
C
|
gpl-3.0
| 16,114
|
//cmdtypist: the main of cmdtypist
/*
Program title: CMDTYPIST
Author: Chiatiah Calson
License: GPL 3 or later versions
Date and Time: 5 July 2017 @ 10:40PM
Program Size: 2.8MB
*/
#include<math.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#include<ctype.h>
#include <unistd.h>
//cmdtypist.c: Implementing the main
#include"functions_for_cmd_typist.h"//function prototypes and global variables.
#include"display.h"//display fixing
#include"utils.h"//useful functions
#include"files.h"//file manipulations
#include"config.h"//configuration
#include"terminal.h"//manipulating the terminal
char argv[5][18];
int main(int argc, char **argv)//argc=command line counter, argv=pointer to pointer to character(command line arguments)
{
redirect();
lmt_pg_size();
name_display();
read_message_conf();//welcome message for first time users.
int lesson_choice=1;//global variable to hold the number corresponding to the chosen lesson.
//char commands[][10]={"0ls","1edituser","2myown","3--help","4man","5mkuser","6mkrand","7mkstd", "8select","9chblk","10sound","11--off","12--on","13cch","14reset","15timeset","16atv","17raw"};
char commands[][10]={"ls","edituser","myown","--help","man","mkuser","mkrand","mkstd", "select","chblk","sound","--off","--on","cch","reset","timeset","atv","raw"};
if(argc<1||argc>3)
{
fprintf(stderr, "%s\n", "Invalid number of arguments to cmdtypist");
exit(EXIT_FAILURE);
}
switch(argc)//switching command depending on the number of command line arguments.
{
case 1:
if(read_myown_config()!=0)
{
lesson_list();//list all lessons present.
select_lesson(argc,&lesson_choice);
}
main_play(argc,&lesson_choice);
break;
case 2:
if(strcmp(argv[1],commands[2])==0)
{
write_myown_config(0);
main_play(argc,&lesson_choice);
}
else if(strcmp(argv[1],commands[13])==0)
{
write_myown_config(1);
lesson_list();
select_lesson(argc,&lesson_choice);
system("clear");
main_play(argc,&lesson_choice);
}
else if(strcmp(argv[1],commands[3])==0)
{
FILE *fp;
if((fp=fopen("help.md","r"))==NULL)
{
fprintf(stderr, "%s\n", "Fatal Error, Some files are missing");
exit(EXIT_FAILURE);
}
while((ch=getc(fp))!=EOF)
printf("%c", ch);
puts("");
if(fclose(fp))
{
fprintf(stderr, "%s\n", "Fatal Error, Unable to close some files\n");
exit(EXIT_FAILURE);
}
}
else if(strcmp(argv[1],commands[4])==0)
{
FILE *fp;
if((fp=fopen("Readme.txt","r"))==NULL)
{
fprintf(stderr, "%s\n", "Fatal Error, Some files are missing");
exit(EXIT_FAILURE);
}
while((ch=getc(fp))!=EOF)
printf("%c", ch);
}
else if(strcmp(argv[1],commands[6])==0)
write_conf_mode(0);
else if(strcmp(argv[1],commands[7])==0)
write_conf_mode(1);
else if(strcmp(argv[1],commands[14])==0)
{
printf("%s","Will reset to default; continue? [y/n]:");
if(get_only_char()=='n')
exit(EXIT_SUCCESS);
reset_default_config(argv[2],argc);
printf("%s\n","Settings reset to default");
exit(EXIT_SUCCESS);
}
else if(strcmp(argv[1],commands[16])==0)
{
adapt_to_ver();
exit(EXIT_SUCCESS);
}
else if(strcmp(argv[1],commands[0])==0)
{
lesson_list();
select_lesson(argc,&lesson_choice);
main_play(argc,&lesson_choice);
}
else fprintf(stderr, "%s\n", "Ensure the second argument is corrrectly spelled");
break;
case 3:
if(strcmp(argv[1],commands[5])==0)
{
test_new_user(argv[2]);
lesson_list();
select_lesson(argc,&lesson_choice);
main_play(argc,&lesson_choice);
}
else if(strcmp(argv[1],commands[14])==0&&strcmp(argv[2],commands[17])==0)
{
reset_default_config(argv[2],argc);
exit(EXIT_SUCCESS);
}
else if(strcmp(argv[1],commands[8])==0)
{
if(read_myown_config()==1)
lesson_choice = range_verifier(is_integral(argv[2],argc));
else
{
lesson_choice=1;
fprintf(stderr, "%s\n\n", "You have been redirected here because you are typing in \"myown\"");
}
main_play(argc,&lesson_choice);
}
/*
else if((strcmp(argv[1],"sound")==0)&&strcmp(argv[2],"--on")==0)//modifying system sound
{
sound_config_write(1);
exit(EXIT_SUCCESS);
}
else if((strcmp(argv[1],"sound")==0)&&strcmp(argv[2],"--off")==0)
{
sound_config_write(0);
exit(EXIT_SUCCESS);
}*/
else if((strcmp(argv[1],commands[10])==0))//modifying system sound
{
if(strcmp(argv[2],commands[12])==0)
{
sound_config_write(1);
exit(EXIT_SUCCESS);
}
else if(strcmp(argv[2],commands[11])==0)
{
sound_config_write(0);
exit(EXIT_SUCCESS);
}
else
{
fprintf(stderr, "%s\n", "Check argument 3 for errors, can be \"--on or --off\"");
exit(EXIT_SUCCESS);
}
}
else if(strcmp(argv[1],commands[9])==0)
{
write_conf_block_read(is_integral(argv[2],argc));
exit(EXIT_SUCCESS);
}
break;
/*case 4://later update
if((strcmp(argv[1],"timeset")==0))//testing if user wants to play for specific amount of time.
{
if(strcmp(argv[2],"--on")==0)
{
time_set=1;
main_play();
}
else
{
fprintf(stderr, "%s\n", "Argument 3 invalid or not recognized");
exit(EXIT_SUCCESS);
}
}*/
default:
fprintf(stderr, "%s\n", "Argument is invalid, use \"help\" to find out more");
break;
}
return 0;
}
void select_lesson(int argc_cmd, int* user_choice)
{
char firstarg[81];//
if(argc_cmd>0&&argc_cmd<4)//checking on the command line argument.
{
char ch;//
printf("%s", "Enter command >>");
while(scanf("%s",firstarg)!=1||(scanf("%d",&*user_choice))!=1||*user_choice<1||*user_choice>15||strncmp(firstarg,"select",6)!=0)//Ensuring that "select"
{ //is entered accurately and the selected value is within the correct range.
if((strncmp(firstarg,"se",2)==0||strcmp(firstarg,"sel")==0||strcmp(firstarg,"sele")==0||strcmp(firstarg,"selec")==0)&&strcmp(firstarg,"select")!=0)
//Making suggestion to help user prevent errors.
fprintf(stderr, "\n%s\n%s", "Did you mean \"select usernumber\"","Enter command >>");
else if(ch!=1&&strcmp(firstarg,"select")==0)
printf("%s%s", "Lesson number cannot contain symbols or alphas\n","Enter command >>");
else if((*user_choice<1||*user_choice>20)&&strcmp(firstarg,"select")==0)
fprintf(stderr, "%s %d\n", "No lesson entry for ",*user_choice);
else printf("%s\nEnter command >>", "Command not found");
while(ch=getchar()!='\n');//disposing off wrong input string.
}
}
else
{
fprintf(stderr, "%s\n", "Invalid number of arguments, consult \"cmdtypist --help\" for more");
exit(EXIT_FAILURE);
}
/*
if(argc_cmd==3)
if(strncmp(argv[2],"select",6)!=0||lesson_choice<1||lesson_choice>20)
{
fprintf(stderr, "%s\n", "Command not found\n");
if(strncmp(argv[2],"se",2))
fprintf(stderr, "%s\n", "Did you mean \"select\"");
else if(lesson_choice<1||lesson_choice>20)
fprintf(stderr, "%s %d\n", "No lesson entry for ",lesson_choice);
//else if(ch!=1)
printf("%s", "Lesson number cannot contain symbols or alpha letters.\n");
exit(EXIT_FAILURE);
}*/
printf("\n");
}
void urs_or_cchl(void)
{
if(read_myown_config()==0)
{
strcpy(file_to_read,"my_own.txt");
mode=1;
}
else if(read_myown_config()==1)
strcpy(file_to_read,"noslaclessons.txt");
else
{
fprintf(stderr, "%s\n", "Fatal Error, lesson file corrupted or does not exist");
exit(EXIT_FAILURE);
}
}
void lesson_position(long *read_this_length,long *point_to,int *my_choice)//setting up the pointer in a position of the file to start reading.
{
FILE *lesson_point;
urs_or_cchl();
if((lesson_point=fopen(file_to_read,"r+"))==NULL)
{
fprintf(stderr, "%s\n", "Fatal Error, Some files are missing");
exit(EXIT_FAILURE);
}
if(read_myown_config()==0)
{
rewind(lesson_point);//return to beginning
*read_this_length=read_file_size(lesson_point);
*point_to=0;
}
else
switch(*my_choice)
{
case 1:
*point_to=0;
if(read_myown_config()==1)
*read_this_length=25510;
break;
case 2:
*point_to=25512L;
*read_this_length=21660;
break;
case 3:
*point_to=39326L;
*read_this_length=397417;
break;
case 4:
*point_to=444591L;
*read_this_length=11142;
break;
case 5:
*point_to=455733L;
*read_this_length=98588;
break;
case 6:
*point_to=554321L;
*read_this_length=19564;
break;
case 7:
*point_to=573885L;
*read_this_length=79999;
break;
case 8:
*point_to=653884L;
*read_this_length=327523;
break;
case 9:
*point_to=981407L;
*read_this_length=208614;
break;
case 10:
*point_to=1190021L;
*read_this_length=400980;
break;
case 11:
*point_to=1591001L;
*read_this_length=625353;
break;
case 12:
*point_to=2216354L;
*read_this_length=1132581;
break;
default:
*point_to=0;
}
if(fclose(lesson_point))
{
fprintf(stderr, "%s\n", "Unable to close lesson file");
exit(EXIT_FAILURE);
}
}
void main_play(int argc_cmd,int *lesson_choice)
{
//lmt_pg_size();
char terminate=0;
long length_to_read;//holds information on how long the text to be read is.
long move_lesson_to;
lesson_position(&length_to_read,&move_lesson_to,lesson_choice);
unsigned short block_count=0;
user_test();//test if a user already exists or not.
long num_of_chars_typed=0;
block_length=read_conf_block_read();
mode=read_conf_mode();
urs_or_cchl();//selects file to read from
remove_ext_ascii();//removes any non ascii 7 bits characters from lesson file.
unsigned int start_time,elapsed_time=0;//elapsed_time: time used during the typing session measured from start time.
unsigned short number_of_lines_count=1;//used to count the total number of lines to print.
const unsigned short chars_to_read=77;//total number of characters to read for each line.
unsigned int i=0;//counter variable for loop counting.
char linetype[150];//char array to hold the total number of characters to to read from file per line.
//lesson_list();
//fseek(noslac_lessonsp,25531L,SEEK_SET);//places the pointer to the position of the file to read.
int wrong_letters=0;//sums up the total number of wrong characters entered during program run.
srand((unsigned)time(NULL));//randomizing seed
FILE *noslac_lessonsp;//lesson pointer
if((noslac_lessonsp=fopen(file_to_read,"r"))==NULL)
{
fprintf(stderr, "%s\n", "Fatal Error, Some files are missing");
exit(EXIT_FAILURE);
}
fseek(noslac_lessonsp,move_lesson_to,SEEK_SET);
while(block_count <= (int)(length_to_read/((chars_to_read+1) * block_length)))//testing inorder to read the entire lesson chosen.
{
num_of_chars_typed=0;
char time_checker=0;//changes back to zero after every block typing
/*goes =reads a certain number of characters in the file using a loop determined
by the random generator and places the pointer at the end of it's reading. thereby
making the lesson each time to be random*/
if(mode==0)
{
int u=0;//counter
while(u<=rand()%(length_to_read-((chars_to_read+1)*block_length))&&(ch=getc(noslac_lessonsp))!=EOF)//program feels new
u++;
do
fseek(noslac_lessonsp,-2L,SEEK_CUR);
while((ch=getc(noslac_lessonsp))!=' ');//moving backwards from where it is placed
//to start reading from where there is a space or has found an uppercase letter.
}
number_of_lines_count=1;
while(number_of_lines_count<=block_length)//testing for number of lines to read.
{
i=0;
char endl = guess(14, 33);//endl holds the char to end a line in place of usual '\n'
char startl = guess(14, 33); //guess generates a random char
while(i <= chars_to_read)//test on i to get 77 characters. the screen size is exactly 77 characters.
{
linetype[i] = getc(noslac_lessonsp);//getting characters and placing in the linetype array.
if(linetype[0] == ' ')//prevent a the start of a line from ever being a space character
linetype[0] = startl; //replace with random char
if(linetype[chars_to_read] == ' ')//ensuring a line does not end with a space character.
linetype[chars_to_read] = '-';//replacing space character at the end of a line with a -
if(i > 1)
if(linetype[i-1] == ' ' && linetype[i] == ' ')//preventing two consecutive space characters since text read is random.
i -= 2;
//checking and eliminating newlines to prevent brakes.
if(linetype[i]=='\n'){
linetype[i] = endl;
linetype[++i] = ' ';
}
if(linetype[i]==EOF)//making sure a line does not contain any end of file character by any chance
{
fprintf(stderr, "%s\n", "Closed unexpectedly, <possibly a corrupt cmdtypist file OR you haven't placed any text in myown.txt>");
exit(EXIT_FAILURE);
}
i++;
}
linetype[i]='\0';//Adding string terminator and subtracting the number of spaces removed.
if((number_of_lines_count % (block_length)) == 0 && number_of_lines_count != 0)
printf(""LAST_LINE_BLUE"");
else
printf(""RESET"");
puts(linetype);//using puts inorder to print the a line and move to the next for the user to follow
number_of_lines_count++;
i=0;//setting i to 0 to begin new counting.
unsigned short error_store[3000], j=0;//error_store: array of ints to note the index of a wrong character.
while(i <= chars_to_read+1)//adding 1 for the extra enter key after the 77 letters are entered.
{
int u=0;//loop counter
if((ch=getche())!='\n'&&ch!=EOF)//using getche to prevent printing of enter key.
{
putchar(ch);
if(time_checker==0)//Making sure time is initialized only once
{
time_checker=1;
wrong_letters=0;//setting errors to 0 to start next typing session
start_time=(unsigned)time(NULL);//to start timing.
}
}
if(ch==EOF)
{
fprintf(stderr, "%s\n", "Closed unexpectedly, <an unexpected character keyed in>");
exit(EXIT_FAILURE);
}
if(ch == 27 || ch == '\t')/*testing for ESC character or a tab to exit program.
iscntrl ensures a control character is entered to exit the program*/
{
terminate=1;
letter_clear(1);
puts("\n");
break;
}
if((ch==127 || ch == 8)&& i == 0)//not using '\b' since most terminals are 'cooked' (keys like backspace are handled by terminal driver) //checking for both delete and backspace.
letter_clear(adapt_to_ver_read());
else if((ch == 127 || ch == 8) && i > 0)//testing for delete of backspace
{
i--;//decremting the number of characters entered when backspaced is pressed.
letter_clear(adapt_to_ver_read());
j=wrong_letters;
while(j>u)//counting from u to j, to find if there is a wrong character stored in the error_store array of ints.
{
//printf("j=%d and u=%d\n", j,u);
if(error_store[j]==i)//checking through the array for errased wrong charactes initially entered.
{ //also ensuring before any decrement, wrong_letters>0
wrong_letters--;//decrementing the number of wrong letters.
/*if(wrong_letters<0)
{
printf("finally got a case %d\n",wrong_letters);
wrong_letters=0;
}*/
error_store[j]=-99;//-99 is a value which will never be reached.
//this is to mark the erased index as no longer wrong.
break;//Ensuring that immediately there is a match, the while loop is escaped for speed.
}
j--;
}
}
else if(i==78&&ch!='\n')
letter_clear(1);
else if(ch!=linetype[i])
{
if(ch!='\n')//testing for ENTER to prevent its printing by printf which will cause a newline.
{
num_of_chars_typed++;
letter_clear(1);//clearing the wrong character
//printf("\a"RED"%c"RESET"",ch );//to print again with color RED. \a is used to include a beep for wrong charater
printf("%s%c",(sound_config_read())==1? "\a"RED"":""RED"",ch);//\a is used to include a beep for wrong character entries
wrong_letters++;
error_store[wrong_letters]=i;//recording the index of a wrong letter
u=0;
j++; //Incrementing the backspace counter.
i++; //incrementing the number of wrong characters entered.
}
}
else
{
if(ch!='\n')//Preventing printing of newline which causes an escape from current typing position in the console.
{
letter_clear(1);
num_of_chars_typed++;
printf(""GREEN"%c"RESET"", ch);//changing color of correct character to green.
i++;
}
}
if(ch=='\n'&&i==78)
break;//escaping loop when the user keys in an Enter.
}
printf("%s","\n" ); //Prints two spaces to ensure the two console spaces left are used, so next printing goes to next line. Game console is 80 and 78 is being used.
if(terminate==1||argc_cmd==4)
break;
}
elapsed_time = (unsigned)time(NULL) - start_time;/*getting the final time and subtracting from the initial
to get the elapsed time*/
block_count++;
//printf("lines=%d block = %d\n",number_of_lines_count,block_length );
if(terminate==1)//exiting on tabs and other systme keys
{
char user_name[81];
if(elapsed_time <= 10)
{
fprintf(stderr, "%s\n", "Speed not recorded");
printf(""RESET"\n");
exit(EXIT_SUCCESS);
}
get_user_name(user_name);
printf(""GREEN" ");
printf("%s", user_name);
if(wrong_letters<0)//optional statement to reduce proberbility of ever having a -ve wrong_letters.
wrong_letters=0;
write_user_speed(elapsed_time,wrong_letters,num_of_chars_typed);
session_style(elapsed_time,wrong_letters,num_of_chars_typed);
exit(EXIT_SUCCESS);//display current typing speed and error
}
if(((number_of_lines_count-1)%block_length)==0)
{
char user_name[81];
if(wrong_letters<0)//optional statement to reduce proberbility of ever having a -ve wrong_letters.
wrong_letters=0;
printf(""GREEN" ");
get_user_name(user_name);//reading user name from file to display in session
printf("%s", user_name);
session_style(elapsed_time,wrong_letters,num_of_chars_typed);//printing session speed details
write_user_speed(elapsed_time,wrong_letters,num_of_chars_typed);//writing user speed to speed file
}
}
}
/*Wrong letters algorithm:
if a user is at the first position of the line and presses backspace, then, that backspace is simply cleared and i not incremented
the array error_store[] keeps track of the index(the i position of the wrong character) and increments a counter variable j, which which be used as
A stop point in a for loop when this stored inex is searched.
When ever backspace keyed in(i!=0), i is first decremented and a search is done through out the loop to see if the decremented i was stored in error store,
if so, then the user is erasing a wrong character, so the wrong_letters is decremented.*/
/*solving the case where wrong_letters shows a messy value
changing it's type to int and making sure it's always greater than 0
*/
|
Noslac/cmd_typist
|
cmd_typist.c
|
C
|
gpl-3.0
| 19,200
|
/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo
* This benchmark is part of SWSC */
#include <assert.h>
#include <stdint.h>
#include <stdatomic.h>
#include <pthread.h>
atomic_int vars[5];
atomic_int atom_1_r1_1;
atomic_int atom_1_r13_0;
void *t0(void *arg){
label_1:;
atomic_store_explicit(&vars[0], 1, memory_order_seq_cst);
atomic_store_explicit(&vars[1], 1, memory_order_seq_cst);
return NULL;
}
void *t1(void *arg){
label_2:;
int v2_r1 = atomic_load_explicit(&vars[1], memory_order_seq_cst);
int v3_r3 = v2_r1 ^ v2_r1;
int v6_r4 = atomic_load_explicit(&vars[2+v3_r3], memory_order_seq_cst);
int v7_r6 = v6_r4 ^ v6_r4;
int v8_r6 = v7_r6 + 1;
atomic_store_explicit(&vars[3], v8_r6, memory_order_seq_cst);
int v10_r8 = atomic_load_explicit(&vars[3], memory_order_seq_cst);
int v11_cmpeq = (v10_r8 == v10_r8);
if (v11_cmpeq) goto lbl_LC00; else goto lbl_LC00;
lbl_LC00:;
atomic_store_explicit(&vars[4], 1, memory_order_seq_cst);
int v13_r11 = atomic_load_explicit(&vars[4], memory_order_seq_cst);
int v14_r12 = v13_r11 ^ v13_r11;
int v17_r13 = atomic_load_explicit(&vars[0+v14_r12], memory_order_seq_cst);
int v21 = (v2_r1 == 1);
atomic_store_explicit(&atom_1_r1_1, v21, memory_order_seq_cst);
int v22 = (v17_r13 == 0);
atomic_store_explicit(&atom_1_r13_0, v22, memory_order_seq_cst);
return NULL;
}
int main(int argc, char *argv[]){
pthread_t thr0;
pthread_t thr1;
atomic_init(&vars[3], 0);
atomic_init(&vars[2], 0);
atomic_init(&vars[0], 0);
atomic_init(&vars[4], 0);
atomic_init(&vars[1], 0);
atomic_init(&atom_1_r1_1, 0);
atomic_init(&atom_1_r13_0, 0);
pthread_create(&thr0, NULL, t0, NULL);
pthread_create(&thr1, NULL, t1, NULL);
pthread_join(thr0, NULL);
pthread_join(thr1, NULL);
int v18 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst);
int v19 = atomic_load_explicit(&atom_1_r13_0, memory_order_seq_cst);
int v20_conj = v18 & v19;
if (v20_conj == 1) assert(0);
return 0;
}
|
nidhugg/nidhugg
|
tests/litmus/C-tests/MP+PPO073.c
|
C
|
gpl-3.0
| 1,993
|
#include "CAN.h"
#include "led.h"
#include "delay.h"
#include "usart.h"
//////////////////////////////////////////////////////////////////////////////////
//±¾³ÌÐòÖ»¹©Ñ§Ï°Ê¹Óã¬Î´¾×÷ÕßÐí¿É£¬²»µÃÓÃÓÚÆäËüÈκÎÓÃ;
//ALIENTEKÕ½½¢STM32¿ª·¢°å
//CANÇý¶¯ ´úÂë
//ÕýµãÔ×Ó@ALIENTEK
//¼¼ÊõÂÛ̳:www.openedv.com
//ÐÞ¸ÄÈÕÆÚ:2012/9/11
//°æ±¾£ºV1.0
//°æÈ¨ËùÓУ¬µÁ°æ±Ø¾¿¡£
//Copyright(C) ¹ãÖÝÊÐÐÇÒíµç×ӿƼ¼ÓÐÏÞ¹«Ë¾ 2009-2019
//All rights reserved
//////////////////////////////////////////////////////////////////////////////////
//CAN³õʼ»¯
//tsjw:ÖØÐÂͬ²½ÌøÔ¾Ê±¼äµ¥Ôª.·¶Î§:1~3; CAN_SJW_1tq CAN_SJW_2tq CAN_SJW_3tq CAN_SJW_4tq
//tbs2:ʱ¼ä¶Î2µÄʱ¼äµ¥Ôª.·¶Î§:1~8;
//tbs1:ʱ¼ä¶Î1µÄʱ¼äµ¥Ôª.·¶Î§:1~16; CAN_BS1_1tq ~CAN_BS1_16tq
//brp :²¨ÌØÂÊ·ÖÆµÆ÷.·¶Î§:1~1024;(ʵ¼ÊÒª¼Ó1,Ò²¾ÍÊÇ1~1024) tq=(brp)*tpclk1
//×¢ÒâÒÔÉϲÎÊýÈκÎÒ»¸ö¶¼²»ÄÜÉèΪ0,·ñÔò»áÂÒ.
//²¨ÌØÂÊ=Fpclk1/((tsjw+tbs1+tbs2)*brp);
//mode:0,ÆÕͨģʽ;1,»Ø»·Ä£Ê½;
//Fpclk1µÄʱÖÓÔÚ³õʼ»¯µÄʱºòÉèÖÃΪ36M,Èç¹ûÉèÖÃCAN_Normal_Init(1,8,7,5,1);
//Ôò²¨ÌØÂÊΪ:36M/((1+8+7)*5)=450Kbps
//·µ»ØÖµ:0,³õʼ»¯OK;
// ÆäËû,³õʼ»¯Ê§°Ü;
u8 CAN_Mode_Init(u8 tsjw,u8 tbs2,u8 tbs1,u16 brp,u8 mode)
{
GPIO_InitTypeDef GPIO_InitStructure;
CAN_InitTypeDef CAN_InitStructure;
CAN_FilterInitTypeDef CAN_FilterInitStructure;
#if CAN_RX0_INT_ENABLE
NVIC_InitTypeDef NVIC_InitStructure;
#endif
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);//ʹÄÜPORTAʱÖÓ
RCC_APB1PeriphClockCmd(RCC_APB1Periph_CAN2, ENABLE);//ʹÄÜCAN2ʱÖÓ
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //¸´ÓÃÍÆÍì
GPIO_Init(GPIOB, &GPIO_InitStructure); //³õʼ»¯IO
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;//ÉÏÀÊäÈë
GPIO_Init(GPIOB, &GPIO_InitStructure);//³õʼ»¯IO
//CANµ¥ÔªÉèÖÃ
CAN_InitStructure.CAN_TTCM=DISABLE; //·Çʱ¼ä´¥·¢Í¨ÐÅģʽ //
CAN_InitStructure.CAN_ABOM=DISABLE; //Èí¼þ×Ô¶¯ÀëÏß¹ÜÀí //
CAN_InitStructure.CAN_AWUM=DISABLE; //˯Ãßģʽͨ¹ýÈí¼þ»½ÐÑ(Çå³ýCAN->MCRµÄSLEEPλ)//
CAN_InitStructure.CAN_NART=ENABLE; //½ûÖ¹±¨ÎÄ×Ô¶¯´«ËÍ //
CAN_InitStructure.CAN_RFLM=DISABLE; //±¨ÎIJ»Ëø¶¨,еĸ²¸Ç¾ÉµÄ //
CAN_InitStructure.CAN_TXFP=DISABLE; //ÓÅÏȼ¶Óɱ¨Îıêʶ·û¾ö¶¨ //
CAN_InitStructure.CAN_Mode= mode; //ģʽÉèÖ㺠mode:0,ÆÕͨģʽ;1,»Ø»·Ä£Ê½; //
//ÉèÖò¨ÌØÂÊ
CAN_InitStructure.CAN_SJW=tsjw; //ÖØÐÂͬ²½ÌøÔ¾¿í¶È(Tsjw)Ϊtsjw+1¸öʱ¼äµ¥Î» CAN_SJW_1tq CAN_SJW_2tq CAN_SJW_3tq CAN_SJW_4tq
CAN_InitStructure.CAN_BS1=tbs1; //Tbs1=tbs1+1¸öʱ¼äµ¥Î»CAN_BS1_1tq ~CAN_BS1_16tq
CAN_InitStructure.CAN_BS2=tbs2;//Tbs2=tbs2+1¸öʱ¼äµ¥Î»CAN_BS2_1tq ~ CAN_BS2_8tq
CAN_InitStructure.CAN_Prescaler=brp; //·ÖƵϵÊý(Fdiv)Ϊbrp+1 //
CAN_Init(CAN2, &CAN_InitStructure); // ³õʼ»¯CAN1
CAN_FilterInitStructure.CAN_FilterNumber=0; //¹ýÂËÆ÷0
CAN_FilterInitStructure.CAN_FilterMode=CAN_FilterMode_IdMask;
CAN_FilterInitStructure.CAN_FilterScale=CAN_FilterScale_32bit; //32λ
CAN_FilterInitStructure.CAN_FilterIdHigh=0x0000;////32λID
CAN_FilterInitStructure.CAN_FilterIdLow=0x0000;
CAN_FilterInitStructure.CAN_FilterMaskIdHigh=0x0000;//32λMASK
CAN_FilterInitStructure.CAN_FilterMaskIdLow=0x0000;
CAN_FilterInitStructure.CAN_FilterFIFOAssignment=CAN_Filter_FIFO0;//¹ýÂËÆ÷0¹ØÁªµ½FIFO0
CAN_FilterInitStructure.CAN_FilterActivation=ENABLE; //¼¤»î¹ýÂËÆ÷0
CAN_FilterInit(&CAN_FilterInitStructure);//Â˲¨Æ÷³õʼ»¯
return 0;
}
//can·¢ËÍÒ»×éÊý¾Ý(¹Ì¶¨¸ñʽ:IDΪ0X12,±ê×¼Ö¡,Êý¾ÝÖ¡)
//len:Êý¾Ý³¤¶È(×î´óΪ8)
//msg:Êý¾ÝÖ¸Õë,×î´óΪ8¸ö×Ö½Ú.
//·µ»ØÖµ:0,³É¹¦;
// ÆäËû,ʧ°Ü;
u8 Can_Send_Msg(u8* msg,u8 len)
{
u8 mbox;
u16 i=0;
CanTxMsg TxMessage;
TxMessage.StdId=0x12; // ±ê×¼±êʶ·ûΪ0
TxMessage.ExtId=0x12; // ÉèÖÃÀ©Õ¹±êʾ·û£¨29룩
TxMessage.IDE=0; // ʹÓÃÀ©Õ¹±êʶ·û
TxMessage.RTR=0; // ÏûÏ¢ÀàÐÍΪÊý¾ÝÖ¡£¬Ò»Ö¡8λ
TxMessage.DLC=len; // ·¢ËÍÁ½Ö¡ÐÅÏ¢
for(i=0;i<len;i++)
TxMessage.Data[i]=msg[i]; // µÚÒ»Ö¡ÐÅÏ¢
mbox= CAN_Transmit(CAN2, &TxMessage);
i=0;
while((CAN_TransmitStatus(CAN2, mbox)==CAN_TxStatus_Failed)&&(i<0XFFF))i++; //µÈ´ý·¢ËͽáÊø
if(i>=0XFFF)return 1;
return 0;
}
//can¿Ú½ÓÊÕÊý¾Ý²éѯ
//buf:Êý¾Ý»º´æÇø;
//·µ»ØÖµ:0,ÎÞÊý¾Ý±»ÊÕµ½;
// ÆäËû,½ÓÊÕµÄÊý¾Ý³¤¶È;
u8 Can_Receive_Msg(u8 *buf)
{
u32 i;
CanRxMsg RxMessage;
if( CAN_MessagePending(CAN2,CAN_FIFO0)==0)return 0; //ûÓнÓÊÕµ½Êý¾Ý,Ö±½ÓÍ˳ö
CAN_Receive(CAN2, CAN_FIFO0, &RxMessage);//¶ÁÈ¡Êý¾Ý
for(i=0;i<8;i++)
buf[i]=RxMessage.Data[i];
return RxMessage.DLC;
}
|
chempin/stm32f107-
|
10.CAN/OV/can.c
|
C
|
gpl-3.0
| 4,689
|
/*
Liquid War 6 is a unique multiplayer wargame.
Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 Christian Mauduit <ufoot@ufoot.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Liquid War 6 homepage : http://www.gnu.org/software/liquidwar6/
Contact author : ufoot@ufoot.org
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H
#include <CUnit/CUnit.h>
#include "mat.h"
int
main (int argc, const char *argv[])
{
int ret = 0;
lw6sys_context_t *sys_context = NULL;
int mode = 0;
LW6SYS_MAIN_BEGIN (sys_context);
lw6sys_log_clear (sys_context, NULL);
mode = lw6sys_arg_test_mode (sys_context, argc, argv);
if (CU_initialize_registry () == CUE_SUCCESS)
{
if (lw6mat_test_register (sys_context, mode))
{
ret = lw6mat_test_run (sys_context, mode);
}
CU_cleanup_registry ();
}
LW6SYS_TEST_OUTPUT;
LW6SYS_MAIN_END (sys_context);
return (!ret);
}
|
lijiaqigreat/liquidwar-web
|
reference/src/lib/mat/mat-testmain.c
|
C
|
gpl-3.0
| 1,546
|
/* Copyright (C) 2005-2012 by George Williams */
/*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "fontforgeui.h"
#include "groups.h"
#include <unistd.h>
#include <ustring.h>
#include <utype.h>
#include <gkeysym.h>
#include <math.h>
/******************************************************************************/
/******************************** Group Widget ********************************/
/******************************************************************************/
#define COLOR_CHOOSE (-10)
static GTextInfo std_colors[] = {
{ (unichar_t *) N_("Select by Color"), NULL, 0, 0, (void *) COLOR_DEFAULT, NULL, 0, 1, 0, 0, 0, 0, 1, 0, 0, '\0' },
{ (unichar_t *) N_("Color|Choose..."), NULL, 0, 0, (void *) COLOR_CHOOSE, NULL, 0, 1, 0, 0, 0, 0, 1, 0, 0, '\0' },
{ (unichar_t *) N_("Color|Default"), &def_image, 0, 0, (void *) COLOR_DEFAULT, NULL, 0, 1, 0, 0, 0, 0, 1, 0, 0, '\0' },
{ NULL, &white_image, 0, 0, (void *) 0xffffff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' },
{ NULL, &red_image, 0, 0, (void *) 0xff0000, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' },
{ NULL, &green_image, 0, 0, (void *) 0x00ff00, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' },
{ NULL, &blue_image, 0, 0, (void *) 0x0000ff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' },
{ NULL, &yellow_image, 0, 0, (void *) 0xffff00, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' },
{ NULL, &cyan_image, 0, 0, (void *) 0x00ffff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' },
{ NULL, &magenta_image, 0, 0, (void *) 0xff00ff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' },
GTEXTINFO_EMPTY
};
struct groupdlg {
unsigned int oked: 1;
unsigned int done: 1;
unsigned int select_many: 1;
/* define groups can only select one group at a time, select/restrict */
/* to groups can select multiple things */
unsigned int select_kids_too: 1;
/* When we select a parent group do we want to select all the kids? */
Group *root;
Group *oldsel;
int open_cnt, lines_page, off_top, off_left, page_width, bmargin;
int maxl;
GWindow gw,v;
GGadget *vsb, *hsb, *cancel, *ok, *compact;
GGadget *newsub, *delete, *line1, *gpnamelab, *gpname, *glyphslab, *glyphs;
GGadget *idlab, *idname, *iduni, *set, *select, *unique, *colour, *line2;
int fh, as;
GFont *font;
FontView *fv;
void (*select_callback)(struct groupdlg *);
GTimer *showchange;
};
extern int _GScrollBar_Width;
static Group *GroupFindLPos(Group *group,int lpos,int *depth) {
int i;
forever {
if ( group->lpos==lpos )
return( group );
if ( !group->open )
return( NULL );
for ( i=0; i<group->kid_cnt-1; ++i ) {
if ( lpos<group->kids[i+1]->lpos )
break;
}
group = group->kids[i];
++*depth;
}
}
static int GroupPosInParent(Group *group) {
Group *parent = group->parent;
int i;
if ( parent==NULL )
return( 0 );
for ( i=0; i<parent->kid_cnt; ++i )
if ( parent->kids[i]==group )
return( i );
return( -1 );
}
static Group *GroupNext(Group *group,int *depth) {
if ( group->open && group->kids ) {
++*depth;
return( group->kids[0] );
}
forever {
int pos;
if ( group->parent==NULL )
return( NULL );
pos = GroupPosInParent(group);
if ( pos+1<group->parent->kid_cnt )
return( group->parent->kids[pos+1] );
group = group->parent;
--*depth;
}
}
static Group *GroupPrev(struct groupdlg *grp, Group *group,int *depth) {
int pos;
while ( group->parent!=NULL && group==group->parent->kids[0] ) {
group = group->parent;
--*depth;
}
if ( group->parent==NULL )
return( NULL );
pos = GroupPosInParent(group);
group = group->parent->kids[pos-1];
while ( group->open ) {
group = group->kids[group->kid_cnt-1];
++*depth;
}
return( group );
}
static int _GroupSBSizes(struct groupdlg *grp, Group *group, int lpos, int depth) {
int i, len;
group->lpos = lpos++;
len = 5+8*depth+ grp->as + 5 + GDrawGetText8Width(grp->v,group->name,-1);
if ( group->glyphs!=NULL )
len += 5 + GDrawGetText8Width(grp->v,group->glyphs,-1);
if ( len > grp->maxl )
grp->maxl = len;
if ( group->open ) {
for ( i=0; i< group->kid_cnt; ++i )
lpos = _GroupSBSizes(grp,group->kids[i],lpos,depth+1);
}
return( lpos );
}
static int GroupSBSizes(struct groupdlg *grp) {
int lpos;
grp->maxl = 0;
GDrawSetFont(grp->v,grp->font);
lpos = _GroupSBSizes(grp,grp->root,0,0);
grp->maxl += 5; /* margin */
GScrollBarSetBounds(grp->vsb,0,lpos,grp->lines_page);
GScrollBarSetBounds(grp->hsb,0,grp->maxl,grp->page_width);
grp->open_cnt = lpos;
return( lpos );
}
static void GroupSelectKids(Group *group,int sel) {
int i;
group->selected = sel;
for ( i=0; i<group->kid_cnt; ++i )
GroupSelectKids(group->kids[i],sel);
}
static void GroupDeselectAllBut(Group *root,Group *group) {
int i;
if ( root!=group )
root->selected = false;
for ( i=0; i<root->kid_cnt; ++i )
GroupDeselectAllBut(root->kids[i],group);
}
static Group *_GroupCurrentlySelected(Group *group) {
int i;
Group *sel;
if ( group->selected )
return( group );
for ( i=0; i<group->kid_cnt; ++i ) {
sel = _GroupCurrentlySelected(group->kids[i]);
if ( sel!=NULL )
return( sel );
}
return( NULL );
}
static Group *GroupCurrentlySelected(struct groupdlg *grp) {
if ( grp->select_many )
return( NULL );
return( _GroupCurrentlySelected(grp->root));
}
static void GroupWExpose(struct groupdlg *grp,GWindow pixmap,GRect *rect) {
int depth, y, len;
Group *group;
GRect r;
Color fg;
GDrawFillRect(pixmap,rect,GDrawGetDefaultBackground(NULL));
GDrawSetLineWidth(pixmap,0);
r.height = r.width = grp->as;
y = (rect->y/grp->fh) * grp->fh + grp->as;
depth=0;
group = GroupFindLPos(grp->root,rect->y/grp->fh+grp->off_top,&depth);
GDrawSetFont(pixmap,grp->font);
while ( group!=NULL ) {
r.y = y-grp->as+1;
r.x = 5+8*depth - grp->off_left;
fg = group->selected ? 0xff0000 : 0x000000;
if ( group->glyphs==NULL ) {
GDrawDrawRect(pixmap,&r,fg);
GDrawDrawLine(pixmap,r.x+2,r.y+grp->as/2,r.x+grp->as-2,r.y+grp->as/2,
fg);
if ( !group->open )
GDrawDrawLine(pixmap,r.x+grp->as/2,r.y+2,r.x+grp->as/2,r.y+grp->as-2,
fg);
}
len = GDrawDrawText8(pixmap,r.x+r.width+5,y,group->name,-1,fg);
if ( group->glyphs )
GDrawDrawText8(pixmap,r.x+r.width+5+len+5,y,group->glyphs,-1,fg);
group = GroupNext(group,&depth);
y += grp->fh;
if ( y-grp->fh>rect->y+rect->height )
break;
}
}
static void GroupWMouse(struct groupdlg *grp,GEvent *event) {
int x;
int depth=0;
Group *group;
group = GroupFindLPos(grp->root,event->u.mouse.y/grp->fh+grp->off_top,&depth);
if ( group==NULL )
return;
x = 5+8*depth - grp->off_left;
if ( event->u.mouse.x<x )
return;
if ( event->u.mouse.x<=x+grp->as ) {
if ( group->glyphs != NULL )
return;
group->open = !group->open;
GroupSBSizes(grp);
} else {
group->selected = !group->selected;
if ( grp->select_kids_too )
GroupSelectKids(group,group->selected);
else if ( group->selected && !grp->select_many )
GroupDeselectAllBut(grp->root,group);
if ( grp->select_callback!=NULL )
(grp->select_callback)(grp);
}
GDrawRequestExpose(grp->v,NULL,false);
}
static void GroupScroll(struct groupdlg *grp,struct sbevent *sb) {
int newpos = grp->off_top;
switch( sb->type ) {
case et_sb_top:
newpos = 0;
break;
case et_sb_uppage:
newpos -= grp->lines_page;
break;
case et_sb_up:
--newpos;
break;
case et_sb_down:
++newpos;
break;
case et_sb_downpage:
newpos += grp->lines_page;
break;
case et_sb_bottom:
newpos = grp->open_cnt-grp->lines_page;
break;
case et_sb_thumb:
case et_sb_thumbrelease:
newpos = sb->pos;
break;
}
if ( newpos>grp->open_cnt-grp->lines_page )
newpos = grp->open_cnt-grp->lines_page;
if ( newpos<0 ) newpos =0;
if ( newpos!=grp->off_top ) {
int diff = newpos-grp->off_top;
grp->off_top = newpos;
GScrollBarSetPos(grp->vsb,grp->off_top);
GDrawScroll(grp->v,NULL,0,diff*grp->fh);
}
}
static void GroupHScroll(struct groupdlg *grp,struct sbevent *sb) {
int newpos = grp->off_left;
switch( sb->type ) {
case et_sb_top:
newpos = 0;
break;
case et_sb_uppage:
newpos -= grp->page_width;
break;
case et_sb_up:
--newpos;
break;
case et_sb_down:
++newpos;
break;
case et_sb_downpage:
newpos += grp->page_width;
break;
case et_sb_bottom:
newpos = grp->maxl-grp->page_width;
break;
case et_sb_thumb:
case et_sb_thumbrelease:
newpos = sb->pos;
break;
}
if ( newpos>grp->maxl-grp->page_width )
newpos = grp->maxl-grp->page_width;
if ( newpos<0 ) newpos =0;
if ( newpos!=grp->off_left ) {
int diff = newpos-grp->off_left;
grp->off_left = newpos;
GScrollBarSetPos(grp->hsb,grp->off_left);
GDrawScroll(grp->v,NULL,-diff,0);
}
}
static void GroupResize(struct groupdlg *grp,GEvent *event) {
GRect size, wsize;
int lcnt, offy;
int sbsize = GDrawPointsToPixels(grp->gw,_GScrollBar_Width);
GDrawGetSize(grp->gw,&size);
lcnt = (size.height-grp->bmargin)/grp->fh;
GGadgetResize(grp->vsb,sbsize,lcnt*grp->fh);
GGadgetMove(grp->vsb,size.width-sbsize,0);
GGadgetResize(grp->hsb,size.width-sbsize,sbsize);
GGadgetMove(grp->hsb,0,lcnt*grp->fh);
GDrawResize(grp->v,size.width-sbsize,lcnt*grp->fh);
grp->page_width = size.width-sbsize;
grp->lines_page = lcnt;
GScrollBarSetBounds(grp->vsb,0,grp->open_cnt,grp->lines_page);
GScrollBarSetBounds(grp->hsb,0,grp->maxl,grp->page_width);
GGadgetGetSize(grp->cancel,&wsize);
offy = size.height-wsize.height-6 - wsize.y;
GGadgetMove(grp->cancel,size.width-wsize.width-30, wsize.y+offy);
GGadgetMove(grp->ok , 30-3,wsize.y+offy-3);
if ( grp->newsub!=NULL ) {
GGadgetGetSize(grp->newsub,&wsize);
GGadgetMove(grp->newsub,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->delete,&wsize);
GGadgetMove(grp->delete,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->line1,&wsize);
GGadgetMove(grp->line1,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->gpnamelab,&wsize);
GGadgetMove(grp->gpnamelab,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->gpname,&wsize);
GGadgetMove(grp->gpname,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->glyphslab,&wsize);
GGadgetMove(grp->glyphslab,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->glyphs,&wsize);
GGadgetMove(grp->glyphs,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->idlab,&wsize);
GGadgetMove(grp->idlab,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->idname,&wsize);
GGadgetMove(grp->idname,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->iduni,&wsize);
GGadgetMove(grp->iduni,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->set,&wsize);
GGadgetMove(grp->set,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->select,&wsize);
GGadgetMove(grp->select,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->unique,&wsize);
GGadgetMove(grp->unique,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->colour,&wsize);
GGadgetMove(grp->colour,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->line2,&wsize);
GGadgetMove(grp->line2,wsize.x,wsize.y+offy);
} else {
GGadgetGetSize(grp->compact,&wsize);
GGadgetMove(grp->compact,wsize.x,wsize.y+offy);
}
GDrawRequestExpose(grp->v,NULL,true);
GDrawRequestExpose(grp->gw,NULL,true);
}
static void GroupWChangeCurrent(struct groupdlg *grp,Group *current,Group *next ) {
if ( current!=NULL )
current->selected = false;
next->selected = true;
if ( next->lpos<grp->off_top || next->lpos>=grp->off_top+grp->lines_page ) {
if ( next->lpos>=grp->off_top+grp->lines_page )
grp->off_top = next->lpos;
else {
grp->off_top = next->lpos-grp->lines_page-1;
if ( grp->off_top<0 ) grp->off_top = 0;
}
GScrollBarSetPos(grp->vsb,grp->off_top);
GDrawRequestExpose(grp->v,NULL,false);
}
}
static int GroupChar(struct groupdlg *grp,GEvent *event) {
int depth = 0;
int pos;
Group *current = GroupCurrentlySelected(grp);
switch (event->u.chr.keysym) {
case GK_F1: case GK_Help:
help("groups.html");
return( true );
case GK_Return: case GK_KP_Enter:
if ( current!=NULL ) {
current->open = !current->open;
GroupSBSizes(grp);
GDrawRequestExpose(grp->v,NULL,false);
}
return( true );
case GK_Page_Down: case GK_KP_Page_Down:
pos = grp->off_top+(grp->lines_page<=1?1:grp->lines_page-1);
if ( pos >= grp->open_cnt-grp->lines_page )
pos = grp->open_cnt-grp->lines_page;
if ( pos<0 ) pos = 0;
grp->off_top = pos;
GScrollBarSetPos(grp->vsb,pos);
GDrawRequestExpose(grp->v,NULL,false);
return( true );
case GK_Down: case GK_KP_Down:
if ( current==NULL || (event->u.chr.state&ksm_control)) {
if ( grp->off_top<grp->open_cnt-1 ) {
++grp->off_top;
GScrollBarSetPos(grp->vsb,grp->off_top);
GDrawScroll(grp->v,NULL,0,grp->fh);
}
} else
GroupWChangeCurrent(grp,current,GroupNext(current,&depth));
return( true );
case GK_Up: case GK_KP_Up:
if ( current==NULL || (event->u.chr.state&ksm_control)) {
if (grp->off_top!=0 ) {
--grp->off_top;
GScrollBarSetPos(grp->vsb,grp->off_top);
GDrawScroll(grp->v,NULL,0,-grp->fh);
}
} else
GroupWChangeCurrent(grp,current,GroupPrev(grp,current,&depth));
return( true );
case GK_Page_Up: case GK_KP_Page_Up:
pos = grp->off_top-(grp->lines_page<=1?1:grp->lines_page-1);
if ( pos<0 ) pos = 0;
grp->off_top = pos;
GScrollBarSetPos(grp->vsb,pos);
GDrawRequestExpose(grp->v,NULL,false);
return( true );
case GK_Left: case GK_KP_Left:
if ( !grp->select_many && current!=NULL )
GroupWChangeCurrent(grp,current,current->parent);
return( true );
case GK_Right: case GK_KP_Right:
if ( !grp->select_many && current != NULL && current->kid_cnt!=0 ) {
if ( !current->open ) {
current->open = !current->open;
GroupSBSizes(grp);
}
GroupWChangeCurrent(grp,current,current->kids[0]);
}
return( true );
case GK_Home: case GK_KP_Home:
if ( grp->off_top!=0 ) {
grp->off_top = 0;
GScrollBarSetPos(grp->vsb,0);
GDrawRequestExpose(grp->v,NULL,false);
}
if ( !grp->select_many )
GroupWChangeCurrent(grp,current,grp->root);
return( true );
case GK_End: case GK_KP_End:
pos = grp->open_cnt-grp->lines_page;
if ( pos<0 ) pos = 0;
if ( pos!=grp->off_top ) {
grp->off_top = pos;
GScrollBarSetPos(grp->vsb,pos);
GDrawRequestExpose(grp->v,NULL,false);
}
if ( !grp->select_many )
GroupWChangeCurrent(grp,current,GroupFindLPos(grp->root,grp->open_cnt-1,&depth));
return( true );
}
return( false );
}
static int grpv_e_h(GWindow gw, GEvent *event) {
struct groupdlg *grp = (struct groupdlg *) GDrawGetUserData(gw);
if (( event->type==et_mouseup || event->type==et_mousedown ) &&
(event->u.mouse.button>=4 && event->u.mouse.button<=7) ) {
return( GGadgetDispatchEvent(grp->vsb,event));
}
switch ( event->type ) {
case et_expose:
GroupWExpose(grp,gw,&event->u.expose.rect);
break;
case et_char:
return( GroupChar(grp,event));
case et_mouseup:
GroupWMouse(grp,event);
break;
}
return( true );
}
static void GroupWCreate(struct groupdlg *grp,GRect *pos) {
FontRequest rq;
int as, ds, ld;
GGadgetCreateData gcd[5];
GTextInfo label[4];
int sbsize = GDrawPointsToPixels(NULL,_GScrollBar_Width);
GWindowAttrs wattrs;
static GFont *font=NULL;
if ( font==NULL ) {
memset(&rq,'\0',sizeof(rq));
rq.utf8_family_name = SANS_UI_FAMILIES;
rq.point_size = 12;
rq.weight = 400;
font = GDrawInstanciateFont(grp->gw,&rq);
font = GResourceFindFont("Groups.Font",font);
}
grp->font = font;
GDrawWindowFontMetrics(grp->gw,grp->font,&as,&ds,&ld);
grp->fh = as+ds; grp->as = as;
grp->lines_page = (pos->height-grp->bmargin)/grp->fh;
grp->page_width = pos->width-sbsize;
wattrs.mask = wam_events|wam_cursor/*|wam_bordwidth|wam_bordcol*/;
wattrs.event_masks = ~0;
wattrs.border_width = 1;
wattrs.border_color = 0x000000;
wattrs.cursor = ct_pointer;
pos->x = 0; pos->y = 0;
pos->width -= sbsize; pos->height = grp->lines_page*grp->fh;
grp->v = GWidgetCreateSubWindow(grp->gw,pos,grpv_e_h,grp,&wattrs);
GDrawSetVisible(grp->v,true);
memset(&label,0,sizeof(label));
memset(&gcd,0,sizeof(gcd));
gcd[0].gd.pos.x = pos->width; gcd[0].gd.pos.y = 0;
gcd[0].gd.pos.width = sbsize;
gcd[0].gd.pos.height = pos->height;
gcd[0].gd.flags = gg_visible | gg_enabled | gg_pos_in_pixels | gg_sb_vert;
gcd[0].creator = GScrollBarCreate;
gcd[1].gd.pos.x = 0; gcd[1].gd.pos.y = pos->height;
gcd[1].gd.pos.height = sbsize;
gcd[1].gd.pos.width = pos->width;
gcd[1].gd.flags = gg_visible | gg_enabled | gg_pos_in_pixels;
gcd[1].creator = GScrollBarCreate;
GGadgetsCreate(grp->gw,gcd);
grp->vsb = gcd[0].ret;
grp->hsb = gcd[1].ret;
}
/******************************************************************************/
/******************************** Group Dialogs *******************************/
/******************************************************************************/
static int FindDuplicateNumberInString(int seek,char *str) {
char *start;
if ( str==NULL )
return( false );
while ( *str!='\0' ) {
while ( *str==' ' ) ++str;
start = str;
while ( *str!=' ' && *str!='\0' ) ++str;
if ( start==str )
break;
if ( (start[0]=='U' || start[0]=='u') && start[1]=='+' ) {
char *end;
int val = strtol(start+2,&end,16), val2=val;
if ( *end=='-' ) {
if ( (end[1]=='u' || end[1]=='U') && end[2]=='+' )
end+=2;
val2 = strtol(end+1,NULL,16);
}
if ( seek>=val && seek<=val2 )
return( true );
}
}
return( false );
}
static int FindDuplicateNameInString(char *name,char *str) {
char *start;
if ( str==NULL )
return( false );
while ( *str!='\0' ) {
while ( *str==' ' ) ++str;
start = str;
while ( *str!=' ' && *str!='\0' ) ++str;
if ( start==str )
break;
if ( (start[0]=='U' || start[0]=='u') && start[1]=='+' )
/* Skip it */;
else {
int ch = *str;
*str = '\0';
if ( strcmp(name,start)==0 ) {
*str = ch;
return( true );
}
*str = ch;
}
}
return( false );
}
static Group *FindDuplicateNumber(Group *top,int val,Group *cur,char *str) {
int i;
Group *grp;
if ( FindDuplicateNumberInString(val,str))
return( cur );
if ( top==cur )
return( NULL );
if ( FindDuplicateNumberInString(val,top->glyphs))
return( top );
for ( i=0; i<top->kid_cnt; ++i )
if ( (grp = FindDuplicateNumber(top->kids[i],val,cur,NULL))!=NULL )
return( grp );
return( NULL );
}
static Group *FindDuplicateName(Group *top,char *name,Group *cur,char *str) {
int i;
Group *grp;
if ( FindDuplicateNameInString(name,str))
return( cur );
if ( top==cur )
return( NULL );
if ( FindDuplicateNameInString(name,top->glyphs))
return( top );
for ( i=0; i<top->kid_cnt; ++i )
if ( (grp = FindDuplicateName(top->kids[i],name,cur,NULL))!=NULL )
return( grp );
return( NULL );
}
static int GroupValidateGlyphs(Group *cur,char *g,const unichar_t *gu,int unique) {
char *gpt, *start;
Group *top, *grp;
if ( gu!=NULL ) {
for ( ; *gu!='\0'; ++gu ) {
if ( *gu<' ' || *gu>=0x7f || *gu=='(' || *gu==')' ||
*gu=='[' || *gu==']' || *gu=='{' || *gu=='}' ||
*gu=='<' || *gu=='>' || *gu=='%' || *gu=='/' ) {
ff_post_error(_("Glyph names must be valid postscript names"),_("Glyph names must be valid postscript names"));
return( false );
}
}
}
if ( unique ) { /* Can't use cur->unique because it hasn't been set yet */
top = cur;
while ( top->parent!=NULL && top->parent->unique )
top = top->parent;
for ( gpt=g; *gpt!='\0' ; ) {
while ( *gpt==' ' ) ++gpt;
start = gpt;
while ( *gpt!=' ' && *gpt!='\0' ) ++gpt;
if ( start==gpt )
break;
if ( (start[0]=='U' || start[0]=='u') && start[1]=='+' ) {
char *end;
int val = strtol(start+2,&end,16), val2=val;
if ( *end=='-' ) {
if ( (end[1]=='u' || end[1]=='U') && end[2]=='+' )
end+=2;
val2 = strtol(end+1,NULL,16);
}
if ( val2<val ) {
ff_post_error(_("Bad Range"),_("Bad Range, start (%1$04X) is greater than end (%2$04X)"), val, val2 );
return( false );
}
for ( ; val<=val2; ++val )
if ( (grp=FindDuplicateNumber(top,val,cur,gpt))!=NULL ) {
ff_post_error(_("Duplicate Name"),_("The code point U+%1$04X occurs in groups %2$.30s and %3$.30s"), val, cur->name, grp->name);
return( false );
}
} else {
int ch = *gpt;
*gpt = '\0';
if ( (grp=FindDuplicateName(top,start,cur,ch!='\0'?gpt+1:NULL))!=NULL ) {
ff_post_error(_("Duplicate Name"),_("The glyph name \"%1$.30s\" occurs in groups %2$.30s and %3$.30s"), start, cur->name, grp->name);
*gpt = ch;
return( false );
}
*gpt = ch;
}
}
}
return( true );
}
static int GroupSetKidsUnique(Group *group) {
int i;
group->unique = true;
for ( i=0; i<group->kid_cnt; ++i )
if ( !GroupSetKidsUnique(group->kids[i]))
return( false );
if ( group->glyphs!=NULL ) {
if ( !GroupValidateGlyphs(group,group->glyphs,NULL,true))
return( false );
}
return( true );
}
static int GroupFinishOld(struct groupdlg *grp) {
if ( grp->oldsel!=NULL ) {
const unichar_t *gu = _GGadgetGetTitle(grp->glyphs);
char *g = cu_copy(gu);
int oldunique = grp->oldsel->unique;
if ( !GroupValidateGlyphs(grp->oldsel,g,gu,GGadgetIsChecked(grp->unique))) {
free(g);
return( false );
}
free(grp->oldsel->name);
grp->oldsel->name = GGadgetGetTitle8(grp->gpname);
free(grp->oldsel->glyphs);
if ( *g=='\0' ) {
grp->oldsel->glyphs = NULL;
free(g);
} else
grp->oldsel->glyphs = g;
grp->oldsel->unique = GGadgetIsChecked(grp->unique);
if ( grp->oldsel->unique && !oldunique ) {
/* The just set the unique bit. We must force it set in all */
/* kids. We really should check for uniqueness too!!!!! */
if ( !GroupSetKidsUnique(grp->oldsel))
return( false );
}
}
return( true );
}
static void GroupSelected(struct groupdlg *grp) {
Group *current = GroupCurrentlySelected(grp);
if ( !GroupFinishOld(grp)) {
if ( current!=NULL )
current->selected=false;
if ( grp->oldsel!=NULL )
grp->oldsel->selected = true;
return;
}
grp->oldsel = current;
if ( current == NULL ) {
GGadgetSetEnabled(grp->newsub,false);
GGadgetSetEnabled(grp->delete,false);
GGadgetSetEnabled(grp->gpnamelab,false);
GGadgetSetEnabled(grp->gpname,false);
GGadgetSetEnabled(grp->glyphslab,false);
GGadgetSetEnabled(grp->glyphs,false);
GGadgetSetEnabled(grp->set,false);
GGadgetSetEnabled(grp->select,false);
GGadgetSetEnabled(grp->unique,false);
GGadgetSetEnabled(grp->colour,false);
} else {
unichar_t *glyphs = uc_copy(current->glyphs);
GGadgetSetTitle8(grp->gpname,current->name);
if ( glyphs==NULL ) glyphs = uc_copy("");
GGadgetSetTitle(grp->glyphs,glyphs);
free(glyphs);
GGadgetSetChecked(grp->unique,current->unique);
GGadgetSetEnabled(grp->newsub,current->glyphs==NULL || *current->glyphs=='\0');
GGadgetSetEnabled(grp->delete,current->parent!=NULL);
GGadgetSetEnabled(grp->gpnamelab,true);
GGadgetSetEnabled(grp->gpname,true);
GGadgetSetEnabled(grp->glyphslab,current->kid_cnt==0);
GGadgetSetEnabled(grp->glyphs,current->kid_cnt==0);
GGadgetSetEnabled(grp->set,current->kid_cnt==0);
GGadgetSetEnabled(grp->select,current->kid_cnt==0);
GGadgetSetEnabled(grp->unique,current->parent==NULL || !current->parent->unique);
GGadgetSetEnabled(grp->colour,current->kid_cnt==0);
}
}
static void GroupShowChange(struct groupdlg *grp) {
if ( GroupFinishOld(grp))
GDrawRequestExpose(grp->v,NULL,false);
grp->showchange = NULL;
}
static int Group_GlyphListChanged(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_textchanged ) {
struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g));
const unichar_t *glyphs = _GGadgetGetTitle(g);
GGadgetSetEnabled(grp->newsub,*glyphs=='\0');
if ( grp->showchange!=NULL )
GDrawCancelTimer(grp->showchange);
grp->showchange = GDrawRequestTimer(grp->gw,500,0,NULL);
}
return( true );
}
static int Group_ToSelection(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g));
const unichar_t *ret = _GGadgetGetTitle(grp->glyphs);
SplineFont *sf = grp->fv->b.sf;
FontView *fv = grp->fv;
const unichar_t *end;
int pos, found=-1;
char *nm;
GDrawSetVisible(fv->gw,true);
GDrawRaise(fv->gw);
memset(fv->b.selected,0,fv->b.map->enccount);
while ( *ret ) {
end = u_strchr(ret,' ');
if ( end==NULL ) end = ret+u_strlen(ret);
nm = cu_copybetween(ret,end);
for ( ret = end; isspace(*ret); ++ret);
if ( (nm[0]=='U' || nm[0]=='u') && nm[1]=='+' ) {
char *end;
int val = strtol(nm+2,&end,16), val2=val;
if ( *end=='-' ) {
if ( (end[1]=='u' || end[1]=='U') && end[2]=='+' )
end+=2;
val2 = strtol(end+1,NULL,16);
}
for ( ; val<=val2; ++val ) {
if (( pos = SFFindSlot(sf,fv->b.map,val,NULL))!=-1 ) {
if ( found==-1 ) found = pos;
if ( pos!=-1 )
fv->b.selected[pos] = true;
}
}
} else if ( strncasecmp(nm,"color=#",strlen("color=#"))==0 ) {
Color col = strtoul(nm+strlen("color=#"),NULL,16);
int gid; SplineChar *sc;
for ( pos=0; pos<fv->b.map->enccount; ++pos )
if ( (gid=fv->b.map->map[pos])!=-1 &&
(sc = sf->glyphs[gid])!=NULL &&
sc->color == col )
fv->b.selected[pos] = true;
} else {
if (( pos = SFFindSlot(sf,fv->b.map,-1,nm))!=-1 ) {
if ( found==-1 ) found = pos;
if ( pos!=-1 )
fv->b.selected[pos] = true;
}
}
free(nm);
}
if ( found!=-1 )
FVScrollToChar(fv,found);
GDrawRequestExpose(fv->v,NULL,false);
}
return( true );
}
static int Group_FromSelection(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g));
SplineFont *sf = grp->fv->b.sf;
FontView *fv = grp->fv;
unichar_t *vals, *pt;
int i, len, max, gid, k;
SplineChar *sc, dummy;
char buffer[20];
if ( GGadgetIsChecked(grp->idname) ) {
for ( i=len=max=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i]) {
gid = fv->b.map->map[i];
if ( gid!=-1 && sf->glyphs[gid]!=NULL )
sc = sf->glyphs[gid];
else
sc = SCBuildDummy(&dummy,sf,fv->b.map,i);
len += strlen(sc->name)+1;
if ( fv->b.selected[i]>max ) max = fv->b.selected[i];
}
pt = vals = galloc((len+1)*sizeof(unichar_t));
*pt = '\0';
for ( i=len=max=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i]) {
gid = fv->b.map->map[i];
if ( gid!=-1 && sf->glyphs[gid]!=NULL )
sc = sf->glyphs[gid];
else
sc = SCBuildDummy(&dummy,sf,fv->b.map,i);
uc_strcpy(pt,sc->name);
pt += u_strlen(pt);
*pt++ = ' ';
}
if ( pt>vals ) pt[-1]='\0';
} else {
vals = NULL;
for ( k=0; k<2; ++k ) {
int last=-2, start=-2;
len = 0;
for ( i=len=max=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i]) {
gid = fv->b.map->map[i];
if ( gid!=-1 && sf->glyphs[gid]!=NULL )
sc = sf->glyphs[gid];
else
sc = SCBuildDummy(&dummy,sf,fv->b.map,i);
if ( sc->unicodeenc==-1 )
continue;
if ( sc->unicodeenc==last+1 )
last = sc->unicodeenc;
else {
if ( last!=-2 ) {
if ( start!=last )
sprintf( buffer, "U+%04X-U+%04X ", start, last );
else
sprintf( buffer, "U+%04X ", start );
if ( vals!=NULL )
uc_strcpy(vals+len,buffer);
len += strlen(buffer);
}
start = last = sc->unicodeenc;
}
}
if ( last!=-2 ) {
if ( start!=last )
sprintf( buffer, "U+%04X-U+%04X ", start, last );
else
sprintf( buffer, "U+%04X ", start );
if ( vals!=NULL )
uc_strcpy(vals+len,buffer);
len += strlen(buffer);
}
if ( !k )
vals = galloc((len+1)*sizeof(unichar_t));
else if ( len!=0 )
vals[len-1] = '\0';
else
*vals = '\0';
}
}
GGadgetSetTitle(grp->glyphs,vals);
free(vals);
}
return( true );
}
static int Group_AddColor(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_listselected ) {
struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g));
GTextInfo *ti = GGadgetGetListItemSelected(g);
int set=false;
Color xcol=0;
if ( ti==NULL )
/* Can't happen */;
else if ( ti->userdata == (void *) COLOR_CHOOSE ) {
struct hslrgb col, font_cols[6];
memset(&col,0,sizeof(col));
col = GWidgetColor(_("Pick a color"),&col,SFFontCols(grp->fv->b.sf,font_cols));
if ( col.rgb ) {
xcol = (((int) rint(255.*col.r))<<16 ) |
(((int) rint(255.*col.g))<<8 ) |
(((int) rint(255.*col.b)) );
set = true;
}
} else {
xcol = (intpt) ti->userdata;
set = true;
}
if ( set ) {
char buffer[40]; unichar_t ubuf[40];
sprintf(buffer," color=#%06x", xcol );
uc_strcpy(ubuf,buffer);
GTextFieldReplace(grp->glyphs,ubuf);
if ( grp->showchange==NULL )
GroupShowChange(grp);
}
GGadgetSelectOneListItem(g,0);
}
return( true );
}
static int Group_NewSubGroup(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g));
Group *new_grp;
if ( !GroupFinishOld(grp))
return( true );
GDrawRequestExpose(grp->v,NULL,false);
if ( grp->oldsel==NULL )
return( true );
if ( grp->oldsel->glyphs!=NULL && grp->oldsel->glyphs!='\0' ) {
GGadgetSetEnabled(grp->newsub,false);
return( true );
}
grp->oldsel->kids = grealloc(grp->oldsel->kids,(++grp->oldsel->kid_cnt)*sizeof(Group *));
grp->oldsel->kids[grp->oldsel->kid_cnt-1] = new_grp = chunkalloc(sizeof(Group));
new_grp->parent = grp->oldsel;
new_grp->unique = grp->oldsel->unique;
new_grp->name = copy(_("UntitledGroup"));
grp->oldsel->selected = false;
grp->oldsel->open = true;
new_grp->selected = true;
GroupSBSizes(grp);
GroupSelected(grp);
GDrawRequestExpose(grp->v,NULL,false);
}
return( true );
}
static int Group_Delete(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g));
Group *parent;
int pos, i;
if ( grp->oldsel==NULL || grp->oldsel->parent==NULL )
return( true );
parent = grp->oldsel->parent;
pos = GroupPosInParent(grp->oldsel);
if ( pos==-1 )
return( true );
for ( i=pos; i<parent->kid_cnt-1; ++i )
parent->kids[i] = parent->kids[i+1];
--parent->kid_cnt;
GroupFree(grp->oldsel);
grp->oldsel = NULL;
GroupSBSizes(grp);
GroupSelected(grp);
GDrawRequestExpose(grp->v,NULL,false);
}
return( true );
}
static int displaygrp_e_h(GWindow gw, GEvent *event) {
struct groupdlg *grp = (struct groupdlg *) GDrawGetUserData(gw);
if (( event->type==et_mouseup || event->type==et_mousedown ) &&
(event->u.mouse.button>=4 && event->u.mouse.button<=7) ) {
return( GGadgetDispatchEvent(grp->vsb,event));
}
if ( grp==NULL )
return( true );
switch ( event->type ) {
case et_expose:
break;
case et_char:
return( GroupChar(grp,event));
break;
case et_timer:
GroupShowChange(grp);
break;
case et_resize:
if ( event->u.resize.sized )
GroupResize(grp,event);
break;
case et_controlevent:
switch ( event->u.control.subtype ) {
case et_scrollbarchange:
if ( event->u.control.g == grp->vsb )
GroupScroll(grp,&event->u.control.u.sb);
else
GroupHScroll(grp,&event->u.control.u.sb);
break;
case et_buttonactivate:
grp->done = true;
grp->oked = event->u.control.g == grp->ok;
break;
}
break;
case et_close:
grp->done = true;
break;
case et_destroy:
if ( grp->newsub!=NULL )
free(grp);
return( true );
}
if ( grp->done && grp->newsub!=NULL ) {
if ( grp->oked ) {
if ( !GroupFinishOld(grp)) {
grp->done = grp->oked = false;
return( true );
}
GroupFree(group_root);
if ( grp->root->kid_cnt==0 && grp->root->glyphs==NULL ) {
group_root = NULL;
GroupFree(grp->root);
} else
group_root = grp->root;
SaveGroupList();
} else
GroupFree(grp->root);
GDrawDestroyWindow(grp->gw);
}
return( true );
}
void DefineGroups(FontView *fv) {
struct groupdlg *grp;
GRect pos;
GWindowAttrs wattrs;
GGadgetCreateData gcd[20];
GTextInfo label[19];
int h, k,kk;
grp = gcalloc(1,sizeof(*grp));
grp->fv = fv;
grp->select_many = grp->select_kids_too = false;
grp->select_callback = GroupSelected;
if ( group_root==NULL ) {
grp->root = chunkalloc(sizeof(Group));
grp->root->name = copy(_("Groups"));
} else
grp->root = GroupCopy(group_root);
memset(&wattrs,0,sizeof(wattrs));
wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor|wam_isdlg|wam_restrict;
wattrs.event_masks = ~(1<<et_charup);
wattrs.is_dlg = true;
wattrs.restrict_input_to_me = false;
wattrs.undercursor = 1;
wattrs.cursor = ct_pointer;
wattrs.utf8_window_title = _("Define Groups");
pos.x = pos.y = 0;
pos.width =GDrawPointsToPixels(NULL,GGadgetScale(200));
pos.height = h = GDrawPointsToPixels(NULL,482);
grp->gw = GDrawCreateTopWindow(NULL,&pos,displaygrp_e_h,grp,&wattrs);
grp->bmargin = GDrawPointsToPixels(NULL,248)+GDrawPointsToPixels(grp->gw,_GScrollBar_Width);
GroupWCreate(grp,&pos);
memset(&label,0,sizeof(label));
memset(&gcd,0,sizeof(gcd));
k = 0;
gcd[k].gd.pos.x = 20;
gcd[k].gd.pos.y = GDrawPixelsToPoints(NULL,h-grp->bmargin)+12;
gcd[k].gd.flags = gg_visible;
label[k].text = (unichar_t *) _("New Sub-Group");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.handle_controlevent = Group_NewSubGroup;
gcd[k++].creator = GButtonCreate;
gcd[k].gd.pos.width = -1;
gcd[k].gd.pos.x = GDrawPixelsToPoints(NULL,(pos.width-30-GIntGetResource(_NUM_Buttonsize)*100/GIntGetResource(_NUM_ScaleFactor)));
gcd[k].gd.pos.y = gcd[k-1].gd.pos.y;
gcd[k].gd.flags = gg_visible;
label[k].text = (unichar_t *) _("_Delete");
label[k].text_is_1byte = true;
label[k].text_in_resource = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.handle_controlevent = Group_Delete;
gcd[k++].creator = GButtonCreate;
gcd[k].gd.pos.width = GDrawPixelsToPoints(NULL,pos.width)-20;
gcd[k].gd.pos.x = 10;
gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+26;
gcd[k].gd.flags = gg_visible | gg_enabled;
gcd[k++].creator = GLineCreate;
gcd[k].gd.pos.x = 5;
gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+8;
gcd[k].gd.flags = gg_visible;
label[k].text = (unichar_t *) _("Group Name:");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k++].creator = GLabelCreate;
gcd[k].gd.pos.x = 80; gcd[k].gd.pos.width = 115;
gcd[k].gd.pos.y = gcd[k-1].gd.pos.y-3;
gcd[k].gd.flags = gg_visible;
gcd[k++].creator = GTextFieldCreate;
gcd[k].gd.pos.x = 5;
gcd[k].gd.pos.y = gcd[k-2].gd.pos.y+16;
gcd[k].gd.flags = gg_visible;
label[k].text = (unichar_t *) _("Glyphs:");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k++].creator = GLabelCreate;
gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+14;
gcd[k].gd.pos.width = GDrawPixelsToPoints(NULL,pos.width)-10; gcd[k].gd.pos.height = 4*13+4;
gcd[k].gd.flags = gg_visible | gg_enabled | gg_textarea_wrap;
gcd[k].gd.handle_controlevent = Group_GlyphListChanged;
gcd[k++].creator = GTextAreaCreate;
gcd[k].gd.pos.x = 5;
gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+gcd[k-1].gd.pos.height+5;
gcd[k].gd.flags = gg_visible | gg_enabled | gg_utf8_popup;
label[k].text = (unichar_t *) _("Identify by");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.popup_msg = (unichar_t *) _("Glyphs may be either identified by name or by unicode code point.\nGenerally you control this by what you type in.\nTyping \"A\" would identify a glyph by name.\nTyping \"U+0041\" identifies a glyph by code point.\nWhen loading glyphs from the selection you must specify which format is desired.");
gcd[k++].creator = GLabelCreate;
gcd[k].gd.pos.x = 90; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y-2;
label[k].text = (unichar_t *) _("Name");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.flags = (gg_visible | gg_enabled | gg_cb_on | gg_utf8_popup);
gcd[k].gd.popup_msg = (unichar_t *) _("Glyphs may be either identified by name or by unicode code point.\nGenerally you control this by what you type in.\nTyping \"A\" would identify a glyph by name.\nTyping \"U+0041\" identifies a glyph by code point.\nWhen loading glyphs from the selection you must specify which format is desired.");
gcd[k++].creator = GRadioCreate;
gcd[k].gd.pos.x = 140; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y;
label[k].text = (unichar_t *) _("Unicode");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.flags = gg_visible | gg_enabled | gg_utf8_popup;
gcd[k].gd.popup_msg = (unichar_t *) _("Glyphs may be either identified by name or by unicode code point.\nGenerally you control this by what you type in.\nTyping \"A\" would identify a glyph by name.\nTyping \"U+0041\" identifies a glyph by code point.\nWhen loading glyphs from the selection you must specify which format is desired.");
gcd[k++].creator = GRadioCreate;
label[k].text = (unichar_t *) _("Set From Font");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.pos.x = 5; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+18;
gcd[k].gd.popup_msg = (unichar_t *) _("Set this glyph list to be the glyphs selected in the fontview");
gcd[k].gd.flags = gg_visible | gg_utf8_popup;
gcd[k].gd.handle_controlevent = Group_FromSelection;
gcd[k++].creator = GButtonCreate;
label[k].text = (unichar_t *) _("Select In Font");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.pos.x = 110; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y;
gcd[k].gd.popup_msg = (unichar_t *) _("Set the fontview's selection to be the glyphs named here");
gcd[k].gd.flags = gg_visible | gg_utf8_popup;
gcd[k].gd.handle_controlevent = Group_ToSelection;
gcd[k++].creator = GButtonCreate;
gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+26;
label[k].text = (unichar_t *) _("No Glyph Duplicates");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.flags = gg_visible | gg_utf8_popup;
gcd[k].gd.popup_msg = (unichar_t *) _("Glyph names (or unicode code points) may occur at most once in this group and any of its sub-groups");
gcd[k++].creator = GCheckBoxCreate;
for ( kk=0; kk<3; ++kk )
std_colors[kk].text = (unichar_t *) S_((char *) std_colors[kk].text);
std_colors[1].image = GGadgetImageCache("colorwheel.png");
std_colors[0].selected = true;
gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+15;
gcd[k].gd.label = &std_colors[0];
gcd[k].gd.u.list = std_colors;
gcd[k].gd.handle_controlevent = Group_AddColor;
gcd[k].gd.flags = gg_visible | gg_utf8_popup;
gcd[k++].creator = GListButtonCreate;
gcd[k].gd.pos.width = GDrawPixelsToPoints(NULL,pos.width)-20;
gcd[k].gd.pos.x = 10;
gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+28;
gcd[k].gd.flags = gg_visible | gg_enabled;
gcd[k++].creator = GLineCreate;
gcd[k].gd.pos.width = -1;
gcd[k].gd.pos.x = 30;
gcd[k].gd.pos.y = h-GDrawPointsToPixels(NULL,32);
gcd[k].gd.flags = gg_visible | gg_enabled | gg_but_default | gg_pos_in_pixels;
label[k].text = (unichar_t *) _("_OK");
label[k].text_is_1byte = true;
label[k].text_in_resource = true;
gcd[k].gd.label = &label[k];
gcd[k++].creator = GButtonCreate;
gcd[k].gd.pos.width = -1;
gcd[k].gd.pos.x = (pos.width-30-GIntGetResource(_NUM_Buttonsize)*100/GIntGetResource(_NUM_ScaleFactor));
gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+3;
gcd[k].gd.flags = gg_visible | gg_enabled | gg_but_cancel | gg_pos_in_pixels;
label[k].text = (unichar_t *) _("_Cancel");
label[k].text_is_1byte = true;
label[k].text_in_resource = true;
gcd[k].gd.label = &label[k];
gcd[k++].creator = GButtonCreate;
GGadgetsCreate(grp->gw,gcd);
grp->newsub = gcd[0].ret;
grp->delete = gcd[1].ret;
grp->line1 = gcd[2].ret;
grp->gpnamelab = gcd[3].ret;
grp->gpname = gcd[4].ret;
grp->glyphslab = gcd[5].ret;
grp->glyphs = gcd[6].ret;
grp->idlab = gcd[7].ret;
grp->idname = gcd[8].ret;
grp->iduni = gcd[9].ret;
grp->set = gcd[10].ret;
grp->select = gcd[11].ret;
grp->unique = gcd[12].ret;
grp->colour = gcd[13].ret;
grp->line2 = gcd[14].ret;
grp->ok = gcd[15].ret;
grp->cancel = gcd[16].ret;
GroupSBSizes(grp);
GroupResize(grp,NULL);
GDrawSetVisible(grp->gw,true);
}
static void MapEncAddGid(EncMap *map,SplineFont *sf, int compacted,
int gid, int uni, char *name) {
if ( compacted && gid==-1 )
return;
if ( gid!=-1 && map->backmap[gid]==-1 )
map->backmap[gid] = map->enccount;
if ( map->enccount>=map->encmax )
map->map = grealloc(map->map,(map->encmax+=100)*sizeof(int));
map->map[map->enccount++] = gid;
if ( !compacted ) {
Encoding *enc = map->enc;
if ( enc->char_cnt>=enc->char_max ) {
enc->unicode = grealloc(enc->unicode,(enc->char_max+=256)*sizeof(int));
enc->psnames = grealloc(enc->psnames,enc->char_max*sizeof(char *));
}
if ( uni==-1 && name!=NULL ) {
if ( gid!=-1 && sf->glyphs[gid]!=NULL )
uni = sf->glyphs[gid]->unicodeenc;
else
uni = UniFromName(name,ui_none,&custom);
}
enc->unicode[enc->char_cnt] = uni;
enc->psnames[enc->char_cnt++] = copy( name );
}
}
static void MapAddGroupGlyph(EncMap *map,SplineFont *sf,char *name, int compacted) {
int gid;
if ( (name[0]=='u' || name[0]=='U') && name[1]=='+' && ishexdigit(name[2])) {
char *end;
int val = strtol(name+2,&end,16), val2=val;
if ( *end=='-' ) {
if ( (end[1]=='u' || end[1]=='U') && end[2]=='+' )
end+=2;
val2 = strtol(end+1,NULL,16);
}
for ( ; val<=val2; ++val ) {
gid = SFFindExistingSlot(sf,val,NULL);
MapEncAddGid(map,sf,compacted,gid,val,NULL);
}
} else if ( strncasecmp(name,"color=#",strlen("color=#"))==0 ) {
Color col = strtoul(name+strlen("color=#"),NULL,16);
int gid; SplineChar *sc;
for ( gid=0; gid<sf->glyphcnt; ++gid )
if ( (sc = sf->glyphs[gid])!=NULL &&
sc->color == col )
MapEncAddGid(map,sf,compacted,gid,sc->unicodeenc,NULL);
} else {
gid = SFFindExistingSlot(sf,-1,name);
MapEncAddGid(map,sf,compacted,gid,-1,name);
}
}
static int MapAddSelectedGroups(EncMap *map,SplineFont *sf,Group *group, int compacted) {
int i, cnt=0;
char *start, *pt;
int ch;
if ( group->glyphs==NULL ) {
for ( i=0; i<group->kid_cnt; ++i )
cnt += MapAddSelectedGroups(map,sf,group->kids[i], compacted);
} else if ( group->selected ) {
for ( pt=group->glyphs; *pt!='\0'; ) {
while ( *pt==' ' ) ++pt;
start = pt;
while ( *pt!=' ' && *pt!='\0' ) ++pt;
ch = *pt; *pt='\0';
if ( *start!='\0' )
MapAddGroupGlyph(map,sf,start, compacted);
*pt=ch;
}
++cnt;
}
return( cnt );
}
static int GroupSelCnt(Group *group, Group **first, Group **second) {
int cnt = 0, i;
if ( group->glyphs==NULL ) {
for ( i=0; i<group->kid_cnt; ++i )
cnt += GroupSelCnt(group->kids[i],first,second);
} else if ( group->selected ) {
if ( *first==NULL )
*first = group;
else if ( *second==NULL )
*second = group;
++cnt;
}
return( cnt );
}
static char *EncNameFromGroups(Group *group) {
Group *first = NULL, *second = NULL;
int cnt = GroupSelCnt(group,&first,&second);
char *prefix = P_("Group","Groups",cnt);
char *ret;
switch ( cnt ) {
case 0:
return( copy( _("No Groups")) );
case 1:
ret = galloc(strlen(prefix) + strlen(first->name) + 3 );
sprintf( ret, "%s: %s", prefix, first->name);
break;
case 2:
ret = galloc(strlen(prefix) + strlen(first->name) + strlen(second->name) + 5 );
sprintf( ret, "%s: %s, %s", prefix, first->name, second->name );
break;
default:
ret = galloc(strlen(prefix) + strlen(first->name) + strlen(second->name) + 9 );
sprintf( ret, "%s: %s, %s ...", prefix, first->name, second->name );
break;
}
return( ret );
}
static void EncodeToGroups(FontView *fv,Group *group, int compacted) {
SplineFont *sf = fv->b.sf;
EncMap *map;
if ( compacted )
map = EncMapNew(0,sf->glyphcnt,&custom);
else {
Encoding *enc = gcalloc(1,sizeof(Encoding));
enc->enc_name = EncNameFromGroups(group);
enc->is_temporary = true;
enc->char_max = 256;
enc->unicode = galloc(256*sizeof(int32));
enc->psnames = galloc(256*sizeof(char *));
map = EncMapNew(0,sf->glyphcnt,enc);
}
if ( MapAddSelectedGroups(map,sf,group,compacted)==0 ) {
ff_post_error(_("Nothing Selected"),_("Nothing Selected"));
EncMapFree(map);
} else if ( map->enccount==0 ) {
ff_post_error(_("Nothing Selected"),_("None of the glyphs in the current font match any names or code points in the selected groups"));
EncMapFree(map);
} else {
fv->b.selected = grealloc(fv->b.selected,map->enccount);
memset(fv->b.selected,0,map->enccount);
EncMapFree(fv->b.map);
fv->b.map = map;
FVSetTitle((FontViewBase *) fv);
FontViewReformatOne((FontViewBase *) fv);
}
}
void DisplayGroups(FontView *fv) {
struct groupdlg grp;
GRect pos;
GWindowAttrs wattrs;
GGadgetCreateData gcd[6];
GTextInfo label[5];
int h;
memset( &grp,0,sizeof(grp));
grp.fv = fv;
grp.select_many = grp.select_kids_too = true;
grp.root = group_root;
if ( grp.root==NULL ) {
grp.root = chunkalloc(sizeof(Group));
grp.root->name = copy(_("Groups"));
}
memset(&wattrs,0,sizeof(wattrs));
wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor|wam_isdlg|wam_restrict;
wattrs.event_masks = ~(1<<et_charup);
wattrs.is_dlg = true;
wattrs.restrict_input_to_me = 1;
wattrs.undercursor = 1;
wattrs.cursor = ct_pointer;
wattrs.utf8_window_title = _("Display By Groups");
pos.x = pos.y = 0;
pos.width =GDrawPointsToPixels(NULL,GGadgetScale(200));
pos.height = h = GDrawPointsToPixels(NULL,317);
grp.gw = GDrawCreateTopWindow(NULL,&pos,displaygrp_e_h,&grp,&wattrs);
grp.bmargin = GDrawPointsToPixels(NULL,50)+GDrawPointsToPixels(grp.gw,_GScrollBar_Width);
GroupWCreate(&grp,&pos);
memset(&label,0,sizeof(label));
memset(&gcd,0,sizeof(gcd));
gcd[0].gd.pos.width = -1;
gcd[0].gd.pos.x = 30;
gcd[0].gd.pos.y = h-GDrawPointsToPixels(NULL,30);
gcd[0].gd.flags = gg_visible | gg_enabled | gg_but_default | gg_pos_in_pixels;
label[0].text = (unichar_t *) _("_OK");
label[0].text_is_1byte = true;
label[0].text_in_resource = true;
gcd[0].gd.label = &label[0];
gcd[0].creator = GButtonCreate;
gcd[1].gd.pos.width = -1;
gcd[1].gd.pos.x = (pos.width-30-GIntGetResource(_NUM_Buttonsize)*100/GIntGetResource(_NUM_ScaleFactor));
gcd[1].gd.pos.y = gcd[0].gd.pos.y+3;
gcd[1].gd.flags = gg_visible | gg_enabled | gg_but_cancel | gg_pos_in_pixels;
label[1].text = (unichar_t *) _("_Cancel");
label[1].text_is_1byte = true;
label[1].text_in_resource = true;
gcd[1].gd.label = &label[1];
gcd[1].creator = GButtonCreate;
gcd[2].gd.pos.width = -1;
gcd[2].gd.pos.x = 10;
gcd[2].gd.pos.y = gcd[0].gd.pos.y-GDrawPointsToPixels(NULL,17);
gcd[2].gd.flags = gg_visible | gg_enabled | gg_cb_on | gg_pos_in_pixels;
label[2].text = (unichar_t *) _("Compacted");
label[2].text_is_1byte = true;
label[2].text_in_resource = true;
gcd[2].gd.label = &label[2];
gcd[2].creator = GCheckBoxCreate;
GGadgetsCreate(grp.gw,gcd);
grp.ok = gcd[0].ret;
grp.cancel = gcd[1].ret;
grp.compact = gcd[2].ret;
GroupSBSizes(&grp);
GDrawSetVisible(grp.gw,true);
while ( !grp.done )
GDrawProcessOneEvent(NULL);
GDrawSetUserData(grp.gw,NULL);
if ( grp.oked )
EncodeToGroups(fv,grp.root, GGadgetIsChecked(gcd[2].ret));
if ( grp.root!=group_root )
GroupFree(grp.root);
GDrawDestroyWindow(grp.gw);
}
|
rakeshyeka/PDFprocessor
|
pdf2htmlEX/fontforge-pdf2htmlEX/fontforgeexe/groupsdlg.c
|
C
|
gpl-3.0
| 50,023
|
/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo
* This benchmark is part of SWSC */
#include <assert.h>
#include <stdint.h>
#include <stdatomic.h>
#include <pthread.h>
atomic_int vars[5];
atomic_int atom_1_r1_1;
void *t0(void *arg){
label_1:;
atomic_store_explicit(&vars[0], 2, memory_order_seq_cst);
atomic_store_explicit(&vars[1], 1, memory_order_seq_cst);
return NULL;
}
void *t1(void *arg){
label_2:;
int v2_r1 = atomic_load_explicit(&vars[1], memory_order_seq_cst);
int v3_r3 = v2_r1 ^ v2_r1;
int v6_r4 = atomic_load_explicit(&vars[2+v3_r3], memory_order_seq_cst);
int v7_r6 = v6_r4 ^ v6_r4;
atomic_store_explicit(&vars[3+v7_r6], 1, memory_order_seq_cst);
int v9_r9 = atomic_load_explicit(&vars[3], memory_order_seq_cst);
int v10_r10 = v9_r9 ^ v9_r9;
atomic_store_explicit(&vars[4+v10_r10], 1, memory_order_seq_cst);
int v12_r13 = atomic_load_explicit(&vars[4], memory_order_seq_cst);
int v13_cmpeq = (v12_r13 == v12_r13);
if (v13_cmpeq) goto lbl_LC00; else goto lbl_LC00;
lbl_LC00:;
atomic_store_explicit(&vars[0], 1, memory_order_seq_cst);
int v18 = (v2_r1 == 1);
atomic_store_explicit(&atom_1_r1_1, v18, memory_order_seq_cst);
return NULL;
}
int main(int argc, char *argv[]){
pthread_t thr0;
pthread_t thr1;
atomic_init(&vars[3], 0);
atomic_init(&vars[1], 0);
atomic_init(&vars[0], 0);
atomic_init(&vars[2], 0);
atomic_init(&vars[4], 0);
atomic_init(&atom_1_r1_1, 0);
pthread_create(&thr0, NULL, t0, NULL);
pthread_create(&thr1, NULL, t1, NULL);
pthread_join(thr0, NULL);
pthread_join(thr1, NULL);
int v14 = atomic_load_explicit(&vars[0], memory_order_seq_cst);
int v15 = (v14 == 2);
int v16 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst);
int v17_conj = v15 & v16;
if (v17_conj == 1) assert(0);
return 0;
}
|
nidhugg/nidhugg
|
tests/litmus/C-tests/S+PPO645.c
|
C
|
gpl-3.0
| 1,822
|
/*
============================================================================
Name : lcd_scroll_text.c
Author : Kiran N <niekiran@gmail.com >
Version : 1.0
Copyright : Your copyright notice
Description : This application prints pre-stored strings on a LCD panel with shifting/scrolling effect
TODOs for the students
1) Take multiple strings as a command line argumentsinstead of pre-stored.
============================================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#include<stdint.h>
#include <time.h>
#include <math.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>
#include "lcd_driver.h"
#include "gpio_driver.h"
#include "lcd_text_scroll.h"
/*=========================================================================================================
BBB_expansion_heade_P8_pins GPIO number 16x2 LCD pin Purpose
===========================================================================================================
P8.7 GPIO_66 4(RS) Register selection (Character vs. Command)
P8.8 GPIO_67 5(RW) Read/write
P8.9 GPIO_69 6(EN) Enable
P8.10 GPIO_68 7(D4) Data line 4
P8.11 GPIO_45 8(D5) Data line 5
P8.12 GPIO_44 9(D6) Data line 6
P8.14 GPIO_26 10(D7) Data line 7
P8.16 GPIO_46 15(BKLTA) Backlight anode
P9.15 GPIO_48 16(BKLTK) Backlight cathode
============================================================================================================= */
char* some_strings[]=
{
"Mahatma Gandhi said,",
"First they ignore you,",
"then they laugh at you ",
"then they fight with you,",
"then you win !",
};
/* This function initializes all the gpios for this application
* TODO : Error handling implementation
*/
int initialize_all_gpios(void)
{
/* first lets export all the GPIOs */
gpio_export(GPIO_66_P8_7_RS_4);
gpio_export(GPIO_67_P8_8_RW_5);
gpio_export(GPIO_69_P8_9_EN_6);
gpio_export(GPIO_68_P8_10_D4_11);
gpio_export(GPIO_45_P8_11_D5_12);
gpio_export(GPIO_44_P8_12_D6_13);
gpio_export(GPIO_26_P8_14_D7_14);
/*first configure the direction for LCD pins */
gpio_configure_dir(GPIO_66_P8_7_RS_4,GPIO_DIR_OUT);
gpio_configure_dir(GPIO_67_P8_8_RW_5,GPIO_DIR_OUT);
gpio_configure_dir(GPIO_69_P8_9_EN_6,GPIO_DIR_OUT);
gpio_configure_dir(GPIO_68_P8_10_D4_11,GPIO_DIR_OUT);
gpio_configure_dir(GPIO_45_P8_11_D5_12,GPIO_DIR_OUT);
gpio_configure_dir(GPIO_44_P8_12_D6_13,GPIO_DIR_OUT);
gpio_configure_dir(GPIO_26_P8_14_D7_14,GPIO_DIR_OUT);
return 0;
}
/* This function gathers the ip address of the system and prints it on LCD */
int print_ip_address()
{
int fd;
struct ifreq ifr;
char iface[] = "usb0";
fd = socket(AF_INET, SOCK_DGRAM, 0);
//Type of address to retrieve - IPv4 IP address
ifr.ifr_addr.sa_family = AF_INET;
//Copy the interface name in the ifreq structure
strncpy(ifr.ifr_name , iface , IFNAMSIZ-1);
ioctl(fd, SIOCGIFADDR, &ifr);
close(fd);
//display result
lcd_printf("%s - %s\n" , iface , inet_ntoa(( (struct sockaddr_in *)&ifr.ifr_addr )->sin_addr) );
return 0;
}
/* Some silly graphics :) */
void tansition_graphics(void)
{
sleep(1);
lcd_set_cursor(1,1);
lcd_send_command(LCD_CMD_CLEAR_DISPLAY);
for (uint8_t n =0 ; n < 2 ; n++)
{
for(uint8_t i=0;i<16;i++)
{
lcd_print_char('*');
usleep(75*1000);
}
lcd_set_cursor(2,16);
lcd_send_command(0x04);
}
lcd_set_cursor(1,1);
lcd_send_command(0x06);
usleep(450 * 1000);
lcd_send_command(LCD_CMD_CLEAR_DISPLAY);
}
int main(int argc, char *argv[])
{
printf("Application to print text in scrollable fashion on LCD\n");
initialize_all_gpios();
gpio_write_value(GPIO_66_P8_7_RS_4,LOW_VALUE);
/*The RW pin is always tied to ground in this implementation, meaning that you are only writing to
the display and never reading from it.*/
gpio_write_value(GPIO_67_P8_8_RW_5,LOW_VALUE);
/* The EN pin is used to tell the LCD when data is ready*/
gpio_write_value(GPIO_69_P8_9_EN_6,LOW_VALUE);
/*Data pins 4~7 are used for actually transmitting data, and data pins 0~3 are left unconnected*/
gpio_write_value(GPIO_68_P8_10_D4_11,LOW_VALUE);
gpio_write_value(GPIO_45_P8_11_D5_12,LOW_VALUE);
gpio_write_value(GPIO_44_P8_12_D6_13,LOW_VALUE);
gpio_write_value(GPIO_26_P8_14_D7_14,LOW_VALUE);
/*
You can illuminate the backlight by connecting the anode pin to 5V and the cathode pin to ground
if you are using an LCD with a built-in resistor for the backlight. If you are not, you must put a
current-limiting resistor in-line with the anode or cathode pin. The datasheet for your device will
generally tell you if you need to do this. */
uint8_t cmd=0;
lcd_init();
//setting function
// only single line mode is chosen here , that means all the 80 characters of the DDRAM will be mapped to lcd line 1.
cmd= LCD_CMD_FUNCTION_SET | DATA_LEN_4 | DISPLAY_1_LINE | MATRIX_5_X_8;
lcd_send_command(cmd);
//3.display on/off control , no cursor
cmd = LCD_CMD_DISPLAY_CURSOR_ONOFF_CONTROL |DISPLAY_ON |CURSOR_OFF ;
lcd_send_command(cmd);
lcd_send_command(LCD_CMD_CLEAR_DISPLAY yo);
//lets start printing from extreme right end of first row of the lcd. .
lcd_set_cursor( 1,17);
#if 1
char *ptr = NULL;
uint8_t i;
while(1)
{
//we have total five strings.
for ( i = 0 ;i < 5 ; i++)
{
//print till each string meets NULL char
ptr= some_strings[i];
while( *ptr != '\0' )
{
lcd_print_char((uint8_t)*ptr);
//printing one character at a time and then left shifting by sending this command.
cmd = LCD_CMD_CURSOR_DISPLAY_SHIFT_CONTROL | DISPLAY_SHIFT | SHIFT_TO_LEFT ;
lcd_send_command(cmd);
ptr++;
usleep(500 * 1000);
}
}
}
#endif
}
|
niekiran/EmbeddedLinuxBBB
|
Project_Src/lcd_scrollable_text/src/lcd_text_scroll.c
|
C
|
gpl-3.0
| 6,531
|
/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo
* This benchmark is part of SWSC */
#include <assert.h>
#include <stdint.h>
#include <stdatomic.h>
#include <pthread.h>
atomic_int vars[3];
atomic_int atom_0_r3_2;
atomic_int atom_1_r1_1;
void *t0(void *arg){
label_1:;
atomic_store_explicit(&vars[0], 2, memory_order_seq_cst);
int v2_r3 = atomic_load_explicit(&vars[0], memory_order_seq_cst);
int v3_r4 = v2_r3 ^ v2_r3;
atomic_store_explicit(&vars[1+v3_r4], 1, memory_order_seq_cst);
atomic_store_explicit(&vars[2], 1, memory_order_seq_cst);
int v14 = (v2_r3 == 2);
atomic_store_explicit(&atom_0_r3_2, v14, memory_order_seq_cst);
return NULL;
}
void *t1(void *arg){
label_2:;
int v5_r1 = atomic_load_explicit(&vars[2], memory_order_seq_cst);
int v6_r3 = v5_r1 ^ v5_r1;
int v7_r3 = v6_r3 + 1;
atomic_store_explicit(&vars[0], v7_r3, memory_order_seq_cst);
int v15 = (v5_r1 == 1);
atomic_store_explicit(&atom_1_r1_1, v15, memory_order_seq_cst);
return NULL;
}
int main(int argc, char *argv[]){
pthread_t thr0;
pthread_t thr1;
atomic_init(&vars[0], 0);
atomic_init(&vars[2], 0);
atomic_init(&vars[1], 0);
atomic_init(&atom_0_r3_2, 0);
atomic_init(&atom_1_r1_1, 0);
pthread_create(&thr0, NULL, t0, NULL);
pthread_create(&thr1, NULL, t1, NULL);
pthread_join(thr0, NULL);
pthread_join(thr1, NULL);
int v8 = atomic_load_explicit(&atom_0_r3_2, memory_order_seq_cst);
int v9 = atomic_load_explicit(&vars[0], memory_order_seq_cst);
int v10 = (v9 == 2);
int v11 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst);
int v12_conj = v10 & v11;
int v13_conj = v8 & v12_conj;
if (v13_conj == 1) assert(0);
return 0;
}
|
nidhugg/nidhugg
|
tests/litmus/C-tests/DETOUR0477.c
|
C
|
gpl-3.0
| 1,695
|
#include <stdlib.h>
#include <stdio.h>
#include "array_heap.h"
int array_init(array* arr, int size) {
arr->data = realloc(NULL, sizeof(void*) * size);
if (0 == (size_t)arr->data) {
return -1;
}
arr->length = size;
arr->index = 0;
return 0;
}
int array_push(array* arr, void* data) {
((size_t*)arr->data)[arr->index] = (size_t)data;
arr->index += 1;
if (arr->index >= arr->length) {
if (-1 == array_grow(arr, arr->length * 2))
{
return -1;
}
}
return arr->index - 1;
}
int array_grow(array* arr, int size) {
if (size <= arr->length) {
return -1;
}
arr->data = realloc(arr->data, sizeof(void*) * size);
if (-1 == (size_t)arr->data) {
return -1;
}
arr->length = size;
return 0;
}
void array_free(array* arr, void (*free_element)(void*)) {
int i;
for (i = 0; i < arr->index; i += 1) {
free_element((void*)((size_t*)arr->data)[i]);
}
free(arr->data);
arr->index = -1;
arr->length = 0;
arr->data = NULL;
}
|
kristov/vroom
|
module/array_heap.c
|
C
|
gpl-3.0
| 989
|
/*
* Copyright (C) 2006-2009 Daniel Prevost <dprevost@photonsoftware.org>
*
* This file is part of Photon (photonsoftware.org).
*
* This file may be distributed and/or modified under the terms of the
* GNU General Public License version 2 or version 3 as published by the
* Free Software Foundation and appearing in the file COPYING.GPL2 and
* COPYING.GPL3 included in the packaging of this software.
*
* Licensees holding a valid Photon Commercial license can use this file
* in accordance with the terms of their license.
*
* This software 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.
*/
/* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */
#include "Common/Options.h"
#include "Tests/PrintError.h"
const bool expectedToPass = false;
/* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */
int main()
{
#if defined(USE_DBC)
int errcode = 0;
char dummyArgs[100];
char *dummyPtrs[10];
psocOptionHandle handle;
bool ok;
struct psocOptStruct opts[5] = {
{ '3', "three", 1, "", "repeat the loop three times" },
{ 'a', "address", 0, "QUASAR_ADDRESS", "tcp/ip port number of the server" },
{ 'x', "", 1, "DISPLAY", "X display to use" },
{ 'v', "verbose", 1, "", "try to explain what is going on" },
{ 'z', "zzz", 1, "", "go to sleep..." }
};
ok = psocSetSupportedOptions( 5, opts, &handle );
if ( ok != true ) {
ERROR_EXIT( expectedToPass, NULL, ; );
}
strcpy( dummyArgs, "OptionTest2 --address 12345 -v --zzz" );
/* 012345678901234567890123456789012345 */
dummyPtrs[0] = dummyArgs;
dummyPtrs[1] = &dummyArgs[12];
dummyPtrs[2] = &dummyArgs[22];
dummyPtrs[3] = &dummyArgs[28];
dummyPtrs[4] = &dummyArgs[31];
dummyArgs[11] = 0;
dummyArgs[21] = 0;
dummyArgs[27] = 0;
dummyArgs[30] = 0;
errcode = psocValidateUserOptions( handle, 5, dummyPtrs, 1 );
if ( errcode != 0 ) {
ERROR_EXIT( expectedToPass, NULL, ; );
}
psocIsShortOptPresent( NULL, 'a' );
ERROR_EXIT( expectedToPass, NULL, ; );
#else
return 1;
#endif
}
/* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */
|
dprevost/photon
|
src/Common/Tests/Options/IsShortPresentNullHandle.c
|
C
|
gpl-3.0
| 2,353
|
/* glpapi16.c (basic graph and network routines) */
/***********************************************************************
* This code is part of GLPK (GNU Linear Programming Kit).
*
* Copyright (C) 2000,01,02,03,04,05,06,07,08,2009 Andrew Makhorin,
* Department for Applied Informatics, Moscow Aviation Institute,
* Moscow, Russia. All rights reserved. E-mail: <mao@mai2.rcnet.ru>.
*
* GLPK is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GLPK is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
* License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GLPK. If not, see <http://www.gnu.org/licenses/>.
***********************************************************************/
#include "glpapi.h"
/* CAUTION: DO NOT CHANGE THE LIMITS BELOW */
#define NV_MAX 100000000 /* = 100*10^6 */
/* maximal number of vertices in the graph */
#define NA_MAX 500000000 /* = 500*10^6 */
/* maximal number of arcs in the graph */
/***********************************************************************
* NAME
*
* glp_create_graph - create graph
*
* SYNOPSIS
*
* glp_graph *glp_create_graph(int v_size, int a_size);
*
* DESCRIPTION
*
* The routine creates a new graph, which initially is empty, i.e. has
* no vertices and arcs.
*
* The parameter v_size specifies the size of data associated with each
* vertex of the graph (0 to 256 bytes).
*
* The parameter a_size specifies the size of data associated with each
* arc of the graph (0 to 256 bytes).
*
* RETURNS
*
* The routine returns a pointer to the graph created. */
static void create_graph(glp_graph *G, int v_size, int a_size)
{ G->pool = dmp_create_pool();
G->name = NULL;
G->nv_max = 50;
G->nv = G->na = 0;
G->v = xcalloc(1+G->nv_max, sizeof(glp_vertex *));
G->index = NULL;
G->v_size = v_size;
G->a_size = a_size;
return;
}
glp_graph *glp_create_graph(int v_size, int a_size)
{ glp_graph *G;
if (!(0 <= v_size && v_size <= 256))
xerror("glp_create_graph: v_size = %d; invalid size of vertex "
"data\n", v_size);
if (!(0 <= a_size && a_size <= 256))
xerror("glp_create_graph: a_size = %d; invalid size of arc dat"
"a\n", a_size);
G = xmalloc(sizeof(glp_graph));
create_graph(G, v_size, a_size);
return G;
}
/***********************************************************************
* NAME
*
* glp_set_graph_name - assign (change) graph name
*
* SYNOPSIS
*
* void glp_set_graph_name(glp_graph *G, const char *name);
*
* DESCRIPTION
*
* The routine glp_set_graph_name assigns a symbolic name specified by
* the character string name (1 to 255 chars) to the graph.
*
* If the parameter name is NULL or an empty string, the routine erases
* the existing symbolic name of the graph. */
void glp_set_graph_name(glp_graph *G, const char *name)
{ if (G->name != NULL)
{ dmp_free_atom(G->pool, G->name, strlen(G->name)+1);
G->name = NULL;
}
if (!(name == NULL || name[0] == '\0'))
{ int j;
for (j = 0; name[j] != '\0'; j++)
{ if (j == 256)
xerror("glp_set_graph_name: graph name too long\n");
if (iscntrl((unsigned char)name[j]))
xerror("glp_set_graph_name: graph name contains invalid "
"character(s)\n");
}
G->name = dmp_get_atom(G->pool, strlen(name)+1);
strcpy(G->name, name);
}
return;
}
/***********************************************************************
* NAME
*
* glp_add_vertices - add new vertices to graph
*
* SYNOPSIS
*
* int glp_add_vertices(glp_graph *G, int nadd);
*
* DESCRIPTION
*
* The routine glp_add_vertices adds nadd vertices to the specified
* graph. New vertices are always added to the end of the vertex list,
* so ordinal numbers of existing vertices remain unchanged.
*
* Being added each new vertex is isolated (has no incident arcs).
*
* RETURNS
*
* The routine glp_add_vertices returns an ordinal number of the first
* new vertex added to the graph. */
int glp_add_vertices(glp_graph *G, int nadd)
{ int i, nv_new;
if (nadd < 1)
xerror("glp_add_vertices: nadd = %d; invalid number of vertice"
"s\n", nadd);
if (nadd > NV_MAX - G->nv)
xerror("glp_add_vertices: nadd = %d; too many vertices\n",
nadd);
/* determine new number of vertices */
nv_new = G->nv + nadd;
/* increase the room, if necessary */
if (G->nv_max < nv_new)
{ glp_vertex **save = G->v;
while (G->nv_max < nv_new)
{ G->nv_max += G->nv_max;
xassert(G->nv_max > 0);
}
G->v = xcalloc(1+G->nv_max, sizeof(glp_vertex *));
memcpy(&G->v[1], &save[1], G->nv * sizeof(glp_vertex *));
xfree(save);
}
/* add new vertices to the end of the vertex list */
for (i = G->nv+1; i <= nv_new; i++)
{ glp_vertex *v;
G->v[i] = v = dmp_get_atom(G->pool, sizeof(glp_vertex));
v->i = i;
v->name = NULL;
v->entry = NULL;
if (G->v_size == 0)
v->data = NULL;
else
{ v->data = dmp_get_atom(G->pool, G->v_size);
memset(v->data, 0, G->v_size);
}
v->temp = NULL;
v->in = v->out = NULL;
}
/* set new number of vertices */
G->nv = nv_new;
/* return the ordinal number of the first vertex added */
return nv_new - nadd + 1;
}
/**********************************************************************/
void glp_set_vertex_name(glp_graph *G, int i, const char *name)
{ /* assign (change) vertex name */
glp_vertex *v;
if (!(1 <= i && i <= G->nv))
xerror("glp_set_vertex_name: i = %d; vertex number out of rang"
"e\n", i);
v = G->v[i];
if (v->name != NULL)
{ if (v->entry != NULL)
{ xassert(G->index != NULL);
avl_delete_node(G->index, v->entry);
v->entry = NULL;
}
dmp_free_atom(G->pool, v->name, strlen(v->name)+1);
v->name = NULL;
}
if (!(name == NULL || name[0] == '\0'))
{ int k;
for (k = 0; name[k] != '\0'; k++)
{ if (k == 256)
xerror("glp_set_vertex_name: i = %d; vertex name too lon"
"g\n", i);
if (iscntrl((unsigned char)name[k]))
xerror("glp_set_vertex_name: i = %d; vertex name contain"
"s invalid character(s)\n", i);
}
v->name = dmp_get_atom(G->pool, strlen(name)+1);
strcpy(v->name, name);
if (G->index != NULL)
{ xassert(v->entry == NULL);
v->entry = avl_insert_node(G->index, v->name);
avl_set_node_link(v->entry, v);
}
}
return;
}
/***********************************************************************
* NAME
*
* glp_add_arc - add new arc to graph
*
* SYNOPSIS
*
* glp_arc *glp_add_arc(glp_graph *G, int i, int j);
*
* DESCRIPTION
*
* The routine glp_add_arc adds a new arc to the specified graph.
*
* The parameters i and j specify the ordinal numbers of, resp., tail
* and head vertices of the arc. Note that self-loops and multiple arcs
* are allowed.
*
* RETURNS
*
* The routine glp_add_arc returns a pointer to the arc added. */
glp_arc *glp_add_arc(glp_graph *G, int i, int j)
{ glp_arc *a;
if (!(1 <= i && i <= G->nv))
xerror("glp_add_arc: i = %d; tail vertex number out of range\n"
, i);
if (!(1 <= j && j <= G->nv))
xerror("glp_add_arc: j = %d; head vertex number out of range\n"
, j);
if (G->na == NA_MAX)
xerror("glp_add_arc: too many arcs\n");
a = dmp_get_atom(G->pool, sizeof(glp_arc));
a->tail = G->v[i];
a->head = G->v[j];
if (G->a_size == 0)
a->data = NULL;
else
{ a->data = dmp_get_atom(G->pool, G->a_size);
memset(a->data, 0, G->a_size);
}
a->temp = NULL;
a->t_prev = NULL;
a->t_next = G->v[i]->out;
if (a->t_next != NULL) a->t_next->t_prev = a;
a->h_prev = NULL;
a->h_next = G->v[j]->in;
if (a->h_next != NULL) a->h_next->h_prev = a;
G->v[i]->out = G->v[j]->in = a;
G->na++;
return a;
}
/***********************************************************************
* NAME
*
* glp_del_vertices - delete vertices from graph
*
* SYNOPSIS
*
* void glp_del_vertices(glp_graph *G, int ndel, const int num[]);
*
* DESCRIPTION
*
* The routine glp_del_vertices deletes vertices along with all
* incident arcs from the specified graph. Ordinal numbers of vertices
* to be deleted should be placed in locations num[1], ..., num[ndel],
* ndel > 0.
*
* Note that deleting vertices involves changing ordinal numbers of
* other vertices remaining in the graph. New ordinal numbers of the
* remaining vertices are assigned under the assumption that the
* original order of vertices is not changed. */
void glp_del_vertices(glp_graph *G, int ndel, const int num[])
{ glp_vertex *v;
int i, k, nv_new;
/* scan the list of vertices to be deleted */
if (!(1 <= ndel && ndel <= G->nv))
xerror("glp_del_vertices: ndel = %d; invalid number of vertice"
"s\n", ndel);
for (k = 1; k <= ndel; k++)
{ /* take the number of vertex to be deleted */
i = num[k];
/* obtain pointer to i-th vertex */
if (!(1 <= i && i <= G->nv))
xerror("glp_del_vertices: num[%d] = %d; vertex number out o"
"f range\n", k, i);
v = G->v[i];
/* check that the vertex is not marked yet */
if (v->i == 0)
xerror("glp_del_vertices: num[%d] = %d; duplicate vertex nu"
"mbers not allowed\n", k, i);
/* erase symbolic name assigned to the vertex */
glp_set_vertex_name(G, i, NULL);
xassert(v->name == NULL);
xassert(v->entry == NULL);
/* free vertex data, if allocated */
if (v->data != NULL)
dmp_free_atom(G->pool, v->data, G->v_size);
/* delete all incoming arcs */
while (v->in != NULL)
glp_del_arc(G, v->in);
/* delete all outgoing arcs */
while (v->out != NULL)
glp_del_arc(G, v->out);
/* mark the vertex to be deleted */
v->i = 0;
}
/* delete all marked vertices from the vertex list */
nv_new = 0;
for (i = 1; i <= G->nv; i++)
{ /* obtain pointer to i-th vertex */
v = G->v[i];
/* check if the vertex is marked */
if (v->i == 0)
{ /* it is marked, delete it */
dmp_free_atom(G->pool, v, sizeof(glp_vertex));
}
else
{ /* it is not marked, keep it */
v->i = ++nv_new;
G->v[v->i] = v;
}
}
/* set new number of vertices in the graph */
G->nv = nv_new;
return;
}
/***********************************************************************
* NAME
*
* glp_del_arc - delete arc from graph
*
* SYNOPSIS
*
* void glp_del_arc(glp_graph *G, glp_arc *a);
*
* DESCRIPTION
*
* The routine glp_del_arc deletes an arc from the specified graph.
* The arc to be deleted must exist. */
void glp_del_arc(glp_graph *G, glp_arc *a)
{ /* some sanity checks */
xassert(G->na > 0);
xassert(1 <= a->tail->i && a->tail->i <= G->nv);
xassert(a->tail == G->v[a->tail->i]);
xassert(1 <= a->head->i && a->head->i <= G->nv);
xassert(a->head == G->v[a->head->i]);
/* remove the arc from the list of incoming arcs */
if (a->h_prev == NULL)
a->head->in = a->h_next;
else
a->h_prev->h_next = a->h_next;
if (a->h_next == NULL)
;
else
a->h_next->h_prev = a->h_prev;
/* remove the arc from the list of outgoing arcs */
if (a->t_prev == NULL)
a->tail->out = a->t_next;
else
a->t_prev->t_next = a->t_next;
if (a->t_next == NULL)
;
else
a->t_next->t_prev = a->t_prev;
/* free arc data, if allocated */
if (a->data != NULL)
dmp_free_atom(G->pool, a->data, G->a_size);
/* delete the arc from the graph */
dmp_free_atom(G->pool, a, sizeof(glp_arc));
G->na--;
return;
}
/***********************************************************************
* NAME
*
* glp_erase_graph - erase graph content
*
* SYNOPSIS
*
* void glp_erase_graph(glp_graph *G, int v_size, int a_size);
*
* DESCRIPTION
*
* The routine glp_erase_graph erases the content of the specified
* graph. The effect of this operation is the same as if the graph
* would be deleted with the routine glp_delete_graph and then created
* anew with the routine glp_create_graph, with exception that the
* handle (pointer) to the graph remains valid. */
static void delete_graph(glp_graph *G)
{ dmp_delete_pool(G->pool);
xfree(G->v);
if (G->index != NULL) avl_delete_tree(G->index);
return;
}
void glp_erase_graph(glp_graph *G, int v_size, int a_size)
{ if (!(0 <= v_size && v_size <= 256))
xerror("glp_erase_graph: v_size = %d; invalid size of vertex d"
"ata\n", v_size);
if (!(0 <= a_size && a_size <= 256))
xerror("glp_erase_graph: a_size = %d; invalid size of arc data"
"\n", a_size);
delete_graph(G);
create_graph(G, v_size, a_size);
return;
}
/***********************************************************************
* NAME
*
* glp_delete_graph - delete graph
*
* SYNOPSIS
*
* void glp_delete_graph(glp_graph *G);
*
* DESCRIPTION
*
* The routine glp_delete_graph deletes the specified graph and frees
* all the memory allocated to this program object. */
void glp_delete_graph(glp_graph *G)
{ delete_graph(G);
xfree(G);
return;
}
/**********************************************************************/
void glp_create_v_index(glp_graph *G)
{ /* create vertex name index */
glp_vertex *v;
int i;
if (G->index == NULL)
{ G->index = avl_create_tree(avl_strcmp, NULL);
for (i = 1; i <= G->nv; i++)
{ v = G->v[i];
xassert(v->entry == NULL);
if (v->name != NULL)
{ v->entry = avl_insert_node(G->index, v->name);
avl_set_node_link(v->entry, v);
}
}
}
return;
}
int glp_find_vertex(glp_graph *G, const char *name)
{ /* find vertex by its name */
AVLNODE *node;
int i = 0;
if (G->index == NULL)
xerror("glp_find_vertex: vertex name index does not exist\n");
if (!(name == NULL || name[0] == '\0' || strlen(name) > 255))
{ node = avl_find_node(G->index, name);
if (node != NULL)
i = ((glp_vertex *)avl_get_node_link(node))->i;
}
return i;
}
void glp_delete_v_index(glp_graph *G)
{ /* delete vertex name index */
int i;
if (G->index != NULL)
{ avl_delete_tree(G->index), G->index = NULL;
for (i = 1; i <= G->nv; i++) G->v[i]->entry = NULL;
}
return;
}
/***********************************************************************
* NAME
*
* glp_read_graph - read graph from plain text file
*
* SYNOPSIS
*
* int glp_read_graph(glp_graph *G, const char *fname);
*
* DESCRIPTION
*
* The routine glp_read_graph reads a graph from a plain text file.
*
* RETURNS
*
* If the operation was successful, the routine returns zero. Otherwise
* it prints an error message and returns non-zero. */
int glp_read_graph(glp_graph *G, const char *fname)
{ glp_data *data;
jmp_buf jump;
int nv, na, i, j, k, ret;
glp_erase_graph(G, G->v_size, G->a_size);
xprintf("Reading graph from `%s'...\n", fname);
data = glp_sdf_open_file(fname);
if (data == NULL)
{ ret = 1;
goto done;
}
if (setjmp(jump))
{ ret = 1;
goto done;
}
glp_sdf_set_jump(data, jump);
nv = glp_sdf_read_int(data);
if (nv < 0)
glp_sdf_error(data, "invalid number of vertices\n");
na = glp_sdf_read_int(data);
if (na < 0)
glp_sdf_error(data, "invalid number of arcs\n");
xprintf("Graph has %d vert%s and %d arc%s\n",
nv, nv == 1 ? "ex" : "ices", na, na == 1 ? "" : "s");
if (nv > 0) glp_add_vertices(G, nv);
for (k = 1; k <= na; k++)
{ i = glp_sdf_read_int(data);
if (!(1 <= i && i <= nv))
glp_sdf_error(data, "tail vertex number out of range\n");
j = glp_sdf_read_int(data);
if (!(1 <= j && j <= nv))
glp_sdf_error(data, "head vertex number out of range\n");
glp_add_arc(G, i, j);
}
xprintf("%d lines were read\n", glp_sdf_line(data));
ret = 0;
done: if (data != NULL) glp_sdf_close_file(data);
return ret;
}
/***********************************************************************
* NAME
*
* glp_write_graph - write graph to plain text file
*
* SYNOPSIS
*
* int glp_write_graph(glp_graph *G, const char *fname).
*
* DESCRIPTION
*
* The routine glp_write_graph writes the specified graph to a plain
* text file.
*
* RETURNS
*
* If the operation was successful, the routine returns zero. Otherwise
* it prints an error message and returns non-zero. */
int glp_write_graph(glp_graph *G, const char *fname)
{ XFILE *fp;
glp_vertex *v;
glp_arc *a;
int i, count, ret;
xprintf("Writing graph to `%s'...\n", fname);
fp = xfopen(fname, "w"), count = 0;
if (fp == NULL)
{ xprintf("Unable to create `%s' - %s\n", fname, xerrmsg());
ret = 1;
goto done;
}
xfprintf(fp, "%d %d\n", G->nv, G->na), count++;
for (i = 1; i <= G->nv; i++)
{ v = G->v[i];
for (a = v->out; a != NULL; a = a->t_next)
xfprintf(fp, "%d %d\n", a->tail->i, a->head->i), count++;
}
xfflush(fp);
if (xferror(fp))
{ xprintf("Write error on `%s' - %s\n", fname, xerrmsg());
ret = 1;
goto done;
}
xprintf("%d lines were written\n", count);
ret = 0;
done: if (fp != NULL) xfclose(fp);
return ret;
}
/* eof */
|
macmanes-lab/BinPacker
|
glpk-4.40/src/glpapi16.c
|
C
|
gpl-3.0
| 18,723
|
#include "report_mib_feature.h"
#include "mib_feature_definition.h"
#include "report_manager.h"
#include "protocol.h"
#include "bus_slave.h"
#include "momo_config.h"
#include "report_log.h"
#include "report_comm_stream.h"
#include "system_log.h"
#include <string.h>
#define BASE64_REPORT_MAX_LENGTH 160 //( 4 * ( ( RAW_REPORT_MAX_LENGTH + 2 ) / 3) )
extern char base64_report_buffer[BASE64_REPORT_MAX_LENGTH+1];
static void start_scheduled_reporting(void)
{
set_momo_state_flag( kStateFlagReportingEnabled, true );
start_report_scheduling();
}
static void stop_scheduled_reporting(void)
{
set_momo_state_flag( kStateFlagReportingEnabled, false );
stop_report_scheduling();
}
static void get_scheduled_reporting(void)
{
bus_slave_return_int16( get_momo_state_flag( kStateFlagReportingEnabled ) );
}
static void send_report(void)
{
taskloop_add( post_report, NULL );
}
static void set_reporting_interval(void)
{
set_report_scheduling_interval( plist_get_int16(0) );
}
static void get_reporting_interval(void)
{
bus_slave_return_int16( current_momo_state.report_config.report_interval );
}
static void set_reporting_route(void)
{
update_report_route( (plist_get_int16(0) >> 8) & 0xFF
, plist_get_int16(0) & 0xFF
, (const char*)plist_get_buffer(1)
, plist_get_buffer_length() );
}
static void get_reporting_route(void)
{
const char* route = get_report_route( ( plist_get_int16(0) >> 8 ) & 0xFF );
if ( !route )
{
bus_slave_seterror( kUnknownError );
return;
}
uint8 start = plist_get_int16(0) & 0xFF;
uint8 len = strlen( route ) - start;
if ( len < 0 )
{
bus_slave_seterror( kCallbackError );
return;
}
if ( len > kBusMaxMessageSize )
len = kBusMaxMessageSize;
bus_slave_return_buffer( route + start, len );
}
static void set_reporting_apn(void)
{
set_gprs_apn( (const char*)plist_get_buffer(0), plist_get_buffer_length() );
}
static void get_reporting_apn(void)
{
bus_slave_return_buffer( current_momo_state.report_config.gprs_apn, strlen(current_momo_state.report_config.gprs_apn) );
}
static void set_reporting_flags(void)
{
current_momo_state.report_config.report_flags = plist_get_int16(0);
}
static void get_reporting_flags(void)
{
bus_slave_return_int16( current_momo_state.report_config.report_flags );
}
static void set_reporting_aggregates(void)
{
current_momo_state.report_config.bulk_aggregates = plist_get_int16(0);
current_momo_state.report_config.interval_aggregates = plist_get_int16(1);
}
static void get_reporting_aggregates(void)
{
plist_set_int16( 0, current_momo_state.report_config.bulk_aggregates );
plist_set_int16( 1, current_momo_state.report_config.interval_aggregates );
bus_slave_setreturn( pack_return_status( kNoMIBError, 4 ) );
}
static void build_report()
{
construct_report();
}
static void get_report()
{
uint16 offset = plist_get_int16(0);
memcpy(plist_get_buffer(0), base64_report_buffer+offset, 20);
bus_slave_setreturn( pack_return_status(kNoMIBError, 20 ));
}
static void get_reporting_sequence(void)
{
bus_slave_return_int16( current_momo_state.report_config.transmit_sequence );
}
static BYTE report_buffer[RAW_REPORT_MAX_LENGTH];
static void read_report_log_mib(void)
{
uint16 index = plist_get_int16(0);
uint16 offset = plist_get_int16(1);
if ( offset >= RAW_REPORT_MAX_LENGTH )
{
bus_slave_seterror( kCallbackError );
return;
}
uint8 length = RAW_REPORT_MAX_LENGTH - offset;
if ( length > kBusMaxMessageSize )
length = kBusMaxMessageSize;
if ( report_log_read( index, (void*)&report_buffer, 1 ) == 0 )
{
// No more entries
bus_slave_seterror( kCallbackError );
return;
}
bus_slave_return_buffer( report_buffer+offset, length );
}
static void count_report_log_mib(void)
{
bus_slave_return_int16( report_log_count() );
}
static void clear_report_log_mib(void)
{
report_log_clear();
}
static void handle_report_stream_success(void)
{
notify_report_success();
}
static void handle_report_stream_failure(void)
{
notify_report_failure();
}
DEFINE_MIB_FEATURE_COMMANDS(reporting) {
{ 0x00, send_report, plist_spec_empty() },
{ 0x01, start_scheduled_reporting, plist_spec_empty() },
{ 0x02, stop_scheduled_reporting, plist_spec_empty() },
{ 0x03, set_reporting_interval, plist_spec(1, false) },
{ 0x04, get_reporting_interval, plist_spec_empty() },
{ 0x05, set_reporting_route, plist_spec(1, true) },
{ 0x06, get_reporting_route, plist_spec(1, false) },
{ 0x07, set_reporting_flags, plist_spec(1, false) },
{ 0x08, get_reporting_flags, plist_spec_empty() },
{ 0x09, set_reporting_aggregates, plist_spec(2, false) },
{ 0x0A, get_reporting_aggregates, plist_spec_empty() },
{ 0x0B, get_reporting_sequence, plist_spec_empty() },
{ 0x0C, build_report, plist_spec_empty() },
{ 0x0D, get_report, plist_spec(1, false) },
{ 0x0E, get_scheduled_reporting, plist_spec_empty() },
{ 0x0F, read_report_log_mib, plist_spec(2, false) },
{ 0x10, count_report_log_mib, plist_spec_empty() },
{ 0x11, clear_report_log_mib, plist_spec_empty() },
{ 0x12, init_report_config, plist_spec_empty() },
{ 0x13, set_reporting_apn, plist_spec(0,true) },
{ 0x14, get_reporting_apn, plist_spec_empty() },
{ 0xF0, handle_report_stream_success, plist_spec_empty() },
{ 0xF1, handle_report_stream_failure, plist_spec_empty() }
};
DEFINE_MIB_FEATURE(reporting);
|
WellDone/MoMo-Firmware
|
momo_modules/mainboard/src/mib/commands/report_mib_feature.c
|
C
|
gpl-3.0
| 5,340
|
/**
* \file stack.c
*
* Time-stamp: "2012-03-31 13:16:41 bkorb"
*
* This is a special option processing routine that will save the
* argument to an option in a FIFO queue.
*
* This file is part of AutoOpts, a companion to AutoGen.
* AutoOpts is free software.
* AutoOpts is Copyright (c) 1992-2012 by Bruce Korb - all rights reserved
*
* AutoOpts is available under any one of two licenses. The license
* in use must be one of these two and the choice is under the control
* of the user of the license.
*
* The GNU Lesser General Public License, version 3 or later
* See the files "COPYING.lgplv3" and "COPYING.gplv3"
*
* The Modified Berkeley Software Distribution License
* See the file "COPYING.mbsd"
*
* These files have the following md5sums:
*
* 43b91e8ca915626ed3818ffb1b71248b pkg/libopts/COPYING.gplv3
* 06a1a2e4760c90ea5e1dad8dfaac4d39 pkg/libopts/COPYING.lgplv3
* 66a5cedaf62c4b2637025f049f9b826f pkg/libopts/COPYING.mbsd
*/
#ifdef WITH_LIBREGEX
# include REGEX_HEADER
#endif
/*=export_func optionUnstackArg
* private:
*
* what: Remove option args from a stack
* arg: + tOptions* + pOpts + program options descriptor +
* arg: + tOptDesc* + pOptDesc + the descriptor for this arg +
*
* doc:
* Invoked for options that are equivalenced to stacked options.
=*/
void
optionUnstackArg(tOptions * pOpts, tOptDesc * pOptDesc)
{
tArgList * pAL;
(void)pOpts;
if ((pOptDesc->fOptState & OPTST_RESET) != 0)
return;
pAL = (tArgList*)pOptDesc->optCookie;
/*
* IF we don't have any stacked options,
* THEN indicate that we don't have any of these options
*/
if (pAL == NULL) {
pOptDesc->fOptState &= OPTST_PERSISTENT_MASK;
if ((pOptDesc->fOptState & OPTST_INITENABLED) == 0)
pOptDesc->fOptState |= OPTST_DISABLED;
return;
}
#ifdef WITH_LIBREGEX
{
regex_t re;
int i, ct, dIdx;
if (regcomp(&re, pOptDesc->optArg.argString, REG_NOSUB) != 0)
return;
/*
* search the list for the entry(s) to remove. Entries that
* are removed are *not* copied into the result. The source
* index is incremented every time. The destination only when
* we are keeping a define.
*/
for (i = 0, dIdx = 0, ct = pAL->useCt; --ct >= 0; i++) {
char const * pzSrc = pAL->apzArgs[ i ];
char * pzEq = strchr(pzSrc, '=');
int res;
if (pzEq != NULL)
*pzEq = NUL;
res = regexec(&re, pzSrc, (size_t)0, NULL, 0);
switch (res) {
case 0:
/*
* Remove this entry by reducing the in-use count
* and *not* putting the string pointer back into
* the list.
*/
AGFREE(pzSrc);
pAL->useCt--;
break;
default:
case REG_NOMATCH:
if (pzEq != NULL)
*pzEq = '=';
/*
* IF we have dropped an entry
* THEN we have to move the current one.
*/
if (dIdx != i)
pAL->apzArgs[ dIdx ] = pzSrc;
dIdx++;
}
}
regfree(&re);
}
#else /* not WITH_LIBREGEX */
{
int i, ct, dIdx;
/*
* search the list for the entry(s) to remove. Entries that
* are removed are *not* copied into the result. The source
* index is incremented every time. The destination only when
* we are keeping a define.
*/
for (i = 0, dIdx = 0, ct = pAL->useCt; --ct >= 0; i++) {
tCC* pzSrc = pAL->apzArgs[ i ];
char* pzEq = strchr(pzSrc, '=');
if (pzEq != NULL)
*pzEq = NUL;
if (strcmp(pzSrc, pOptDesc->optArg.argString) == 0) {
/*
* Remove this entry by reducing the in-use count
* and *not* putting the string pointer back into
* the list.
*/
AGFREE(pzSrc);
pAL->useCt--;
} else {
if (pzEq != NULL)
*pzEq = '=';
/*
* IF we have dropped an entry
* THEN we have to move the current one.
*/
if (dIdx != i)
pAL->apzArgs[ dIdx ] = pzSrc;
dIdx++;
}
}
}
#endif /* WITH_LIBREGEX */
/*
* IF we have unstacked everything,
* THEN indicate that we don't have any of these options
*/
if (pAL->useCt == 0) {
pOptDesc->fOptState &= OPTST_PERSISTENT_MASK;
if ((pOptDesc->fOptState & OPTST_INITENABLED) == 0)
pOptDesc->fOptState |= OPTST_DISABLED;
AGFREE((void*)pAL);
pOptDesc->optCookie = NULL;
}
}
/*
* Put an entry into an argument list. The first argument points to
* a pointer to the argument list structure. It gets passed around
* as an opaque address.
*/
LOCAL void
addArgListEntry(void** ppAL, void* entry)
{
tArgList* pAL = *(void**)ppAL;
/*
* IF we have never allocated one of these,
* THEN allocate one now
*/
if (pAL == NULL) {
pAL = (tArgList*)AGALOC(sizeof(*pAL), "new option arg stack");
if (pAL == NULL)
return;
pAL->useCt = 0;
pAL->allocCt = MIN_ARG_ALLOC_CT;
*ppAL = (void*)pAL;
}
/*
* ELSE if we are out of room
* THEN make it bigger
*/
else if (pAL->useCt >= pAL->allocCt) {
size_t sz = sizeof(*pAL);
pAL->allocCt += INCR_ARG_ALLOC_CT;
/*
* The base structure contains space for MIN_ARG_ALLOC_CT
* pointers. We subtract it off to find our augment size.
*/
sz += sizeof(char*) * (pAL->allocCt - MIN_ARG_ALLOC_CT);
pAL = (tArgList*)AGREALOC((void*)pAL, sz, "expanded opt arg stack");
if (pAL == NULL)
return;
*ppAL = (void*)pAL;
}
/*
* Insert the new argument into the list
*/
pAL->apzArgs[ (pAL->useCt)++ ] = entry;
}
/*=export_func optionStackArg
* private:
*
* what: put option args on a stack
* arg: + tOptions* + pOpts + program options descriptor +
* arg: + tOptDesc* + pOptDesc + the descriptor for this arg +
*
* doc:
* Keep an entry-ordered list of option arguments.
=*/
void
optionStackArg(tOptions * pOpts, tOptDesc * pOD)
{
char * pz;
(void)pOpts;
if ((pOD->fOptState & OPTST_RESET) != 0) {
tArgList* pAL = (void*)pOD->optCookie;
int ix;
if (pAL == NULL)
return;
ix = pAL->useCt;
while (--ix >= 0)
AGFREE(pAL->apzArgs[ix]);
AGFREE(pAL);
} else {
if (pOD->optArg.argString == NULL)
return;
AGDUPSTR(pz, pOD->optArg.argString, "stack arg");
addArgListEntry(&(pOD->optCookie), (void*)pz);
}
}
/*
* Local Variables:
* mode: C
* c-file-style: "stroustrup"
* indent-tabs-mode: nil
* End:
* end of autoopts/stack.c */
|
nobled/gnutls
|
src/libopts/stack.c
|
C
|
gpl-3.0
| 7,335
|
/**
******************************************************************************
* @file LibJPEG/LibJPEG_Encoding/Src/encode.c
* @author MCD Application Team
* @version V1.1.0
* @date 17-February-2017
* @brief This file contain the compress method.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2017 STMicroelectronics International N.V.
* All rights reserved.</center></h2>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted, provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of other
* contributors to this software may be used to endorse or promote products
* derived from this software without specific written permission.
* 4. This software, including modifications and/or derivative works of this
* software, must execute solely and exclusively on microcontroller or
* microprocessor devices manufactured by or for STMicroelectronics.
* 5. Redistribution and use of this software other than as permitted under
* this license is void and will automatically terminate your rights under
* this license.
*
* THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY
* RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT
* SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "encode.h"
/* Private typedef -----------------------------------------------------------*/
/* This struct contains the JPEG compression parameters */
static struct jpeg_compress_struct cinfo;
/* This struct represents a JPEG error handler */
static struct jpeg_error_mgr jerr;
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
extern RGB_typedef *RGB_matrix;
/**
* @brief Jpeg Encode
* @param file: pointer to the bmp file
* @param file1: pointer to the jpg file
* @param width: image width
* @param height: image height
* @param image_quality: image quality
* @param buff: pointer to the image line
* @retval None
*/
void jpeg_encode(JFILE *file, JFILE *file1, uint32_t width, uint32_t height, uint32_t image_quality, uint8_t * buff)
{
/* Encode BMP Image to JPEG */
JSAMPROW row_pointer; /* Pointer to a single row */
uint32_t bytesread;
/* Step 1: allocate and initialize JPEG compression object */
/* Set up the error handler */
cinfo.err = jpeg_std_error(&jerr);
/* Initialize the JPEG compression object */
jpeg_create_compress(&cinfo);
/* Step 2: specify data destination */
jpeg_stdio_dest(&cinfo, file1);
/* Step 3: set parameters for compression */
cinfo.image_width = width;
cinfo.image_height = height;
cinfo.input_components = 3;
cinfo.in_color_space = JCS_RGB;
/* Set default compression parameters */
jpeg_set_defaults(&cinfo);
cinfo.dct_method = JDCT_FLOAT;
jpeg_set_quality(&cinfo, image_quality, TRUE);
/* Step 4: start compressor */
jpeg_start_compress(&cinfo, TRUE);
/* Bypass the header bmp file */
f_read(file, buff, 54, (UINT*)&bytesread);
while (cinfo.next_scanline < cinfo.image_height)
{
/* In this application, the input file is a BMP, which first encodes the bottom of the picture */
/* JPEG encodes the highest part of the picture first. We need to read the lines upside down */
/* Move the read pointer to 'last line of the picture - next_scanline' */
f_lseek(file, ((cinfo.image_height-1-cinfo.next_scanline)*width*3)+54);
if(f_read(file, buff, width*3, (UINT*)&bytesread) == FR_OK)
{
row_pointer = (JSAMPROW)buff;
jpeg_write_scanlines(&cinfo, &row_pointer, 1);
}
}
/* Step 5: finish compression */
jpeg_finish_compress(&cinfo);
/* Step 6: release JPEG compression object */
jpeg_destroy_compress(&cinfo);
}
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
TRothfelder/Multicopter
|
libs/STM32Cube_FW_F4_V1.16.0/Projects/STM32469I_EVAL/Applications/LibJPEG/LibJPEG_Encoding/Src/encode.c
|
C
|
gpl-3.0
| 5,814
|
/* ptinit.c - ptinit */
#include <xinu.h>
struct ptnode *ptfree; /* list of free message nodes */
struct ptentry porttab[NPORTS]; /* port table */
int32 ptnextid; /* next table entry to try */
/*------------------------------------------------------------------------
* ptinit -- initialize all ports
*------------------------------------------------------------------------
*/
syscall ptinit(
int32 maxmsgs /* total messages in all ports */
)
{
int32 i; /* runs through port table */
struct ptnode *next, *prev; /* used to build free list */
ptfree = (struct ptnode *)getmem(maxmsgs*sizeof(struct ptnode));
if (ptfree == (struct ptnode *)SYSERR) {
panic("pinit - insufficient memory");
}
/* Initialize all port table entries to free */
for (i=0 ; i<NPORTS ; i++) {
porttab[i].ptstate = PT_FREE;
porttab[i].ptseq = 0;
}
ptnextid = 0;
/* Create free list of message pointer nodes */
for ( prev=next=ptfree ; --maxmsgs > 0 ; prev=next )
prev->ptnext = ++next;
prev->ptnext = NULL;
return(OK);
}
|
rhexsel/xinu-cMIPS
|
xinu/system/ptinit.c
|
C
|
gpl-3.0
| 1,044
|
/* This file is part of libcuzmem
Copyright (C) 2011 James A. Shackleford
libcuzmem is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <math.h>
#include "context.h"
#include "plans.h"
#include "tuner_util.h"
#include "tuner_exhaust.h"
//------------------------------------------------------------------------------
// TUNER INTERFACE
//------------------------------------------------------------------------------
cuzmem_plan*
cuzmem_tuner_exhaust (enum cuzmem_tuner_action action, void* parm)
{
CUZMEM_CONTEXT ctx = get_context();
// =========================================================================
// TUNER START
// =========================================================================
if (CUZMEM_TUNER_START == action) {
// For now, do nothing special.
if (ctx->tune_iter == 0) {
// if we are in the 0th tuning cycle, do nothing here.
// CUZMEM_TUNER_LOOKUP is determining the search space
return NULL;
}
else {
// start timing the iteration
ctx->start_time = get_time ();
}
// Return value currently has no meaning
return NULL;
}
// =========================================================================
// TUNER LOOKUP
// =========================================================================
else if (CUZMEM_TUNER_LOOKUP == action) {
// parm: pointer to size of allocation
size_t size = *(size_t*)(parm);
CUresult ret;
int loopy = 0;
cuzmem_plan* entry = NULL;
int loc;
// default 0th tuning iteration handling
if (ctx->tune_iter == 0) {
return zeroth_lookup_handler (ctx, size);
}
// handle looping allocations & get current entry
if (loopy_entry (ctx, &entry, size)) {
return loopy_entry_handler (entry, size);
}
// exhaustive tuning
// ---------------------------------------------------------------------
entry->loc = (ctx->tune_iter >> ctx->current_knob) & 0x0001;
loc = entry->loc;
ret = alloc_mem (entry, size);
// "natural mutation"
if (loc != entry->loc) {
// add large value to timer to invalidate this plan
ctx->start_time -= (0.50*ctx->start_time);
}
// ---------------------------------------------------------------------
ctx->current_knob++;
return entry;
}
// =========================================================================
// TUNER END
// =========================================================================
else if (CUZMEM_TUNER_END == action) {
int i;
double time;
cuzmem_plan* entry = NULL;
int all_global = 1;
int satisfied = 0;
unsigned int gpu_mem_free, gpu_mem_total, gpu_mem_req;
unsigned int gpu_mem_min;
CUresult ret;
// standard tuner structure
// ---------------------------------------------------------------------
if (ctx->tune_iter == 0) {
if (zeroth_end_handler (ctx)) {
// everything fits in GPU memory, returning ends search
return NULL;
}
// exhaustive search specific: compute # of tune iterations
ctx->tune_iter_max = (unsigned long long)pow (2, ctx->num_knobs);
}
// get the time to complete this iteration
time = get_time() - ctx->start_time;
if (time < ctx->best_time) {
ctx->best_time = time;
ctx->best_plan = ctx->tune_iter; // algorithm dependent
}
// reset current knob for next tune iteration
ctx->current_knob = 0;
// ---------------------------------------------------------------------
printf ("libcuzmem: best plan is #%llu of %llu\n", ctx->best_plan, ctx->tune_iter_max);
// pull down GPU global memory usage from CUDA driver
ret = cuMemGetInfo (&gpu_mem_free, &gpu_mem_total);
if (ret != CUDA_SUCCESS) {
fprintf (stderr, "libcuzmem: could not retrieve GPU memory info from CUDA Driver!\n");
exit (1);
} else {
gpu_mem_min = (unsigned int)((float)gpu_mem_free * (float)ctx->gpu_mem_percent * 0.01f);
gpu_mem_free -= 20000000;
}
// check to make sure the next iteration's plan draft meets the GPU
// global memory utilization constraint if it doesn't, we will skip it
// and subsequent plans until we find one that does.
//
// we also use this oppurtunity to clear out all of our inloop entry's
// 1st hit flags
i = ctx->tune_iter + 1;
do {
gpu_mem_req = 0;
entry = ctx->plan;
while (entry != NULL) {
entry->loc = (i >> entry->id) & 0x0001;
entry->first_hit = 1;
if (entry->loc == 1 && entry->gold_member) {
gpu_mem_req += entry->size;
}
entry = entry->next;
}
fprintf (stderr,
" Request for Plan %i of %llu: %i (min: %i)\n",
i,
ctx->tune_iter_max,
gpu_mem_req,
gpu_mem_min
);
if ((gpu_mem_req >= gpu_mem_min) && (gpu_mem_req < gpu_mem_free)) {
// we subtract one beacuse tune_iter is auto-increment after this
// function returns (before the next tune iterations starts)
ctx->tune_iter = i - 1;
satisfied = 1;
} else {
i++;
}
} while (!satisfied);
// always end with this
max_iteration_handler (ctx);
return NULL;
}
// =========================================================================
// TUNER: UNKNOWN ACTION SPECIFIED
// =========================================================================
else {
printf ("libcuzmem: tuner asked to perform unknown action!\n");
exit (1);
return NULL;
}
// =========================================================================
}
|
tshack/libcuzmem
|
tuner_exhaust.c
|
C
|
gpl-3.0
| 6,949
|
/* Copyright 2004,2007,2008,2010,2011,2014 IPB, Universite de Bordeaux, INRIA & CNRS
**
** This file is part of the Scotch software package for static mapping,
** graph partitioning and sparse matrix ordering.
**
** This software is governed by the CeCILL-C license under French law
** and abiding by the rules of distribution of free software. You can
** use, modify and/or redistribute the software under the terms of the
** CeCILL-C license as circulated by CEA, CNRS and INRIA at the following
** URL: "http://www.cecill.info".
**
** As a counterpart to the access to the source code and rights to copy,
** modify and redistribute granted by the license, users are provided
** only with a limited warranty and the software's author, the holder of
** the economic rights, and the successive licensors have only limited
** liability.
**
** In this respect, the user's attention is drawn to the risks associated
** with loading, using, modifying and/or developing or reproducing the
** software by the user in light of its specific status of free software,
** that may mean that it is complicated to manipulate, and that also
** therefore means that it is reserved for developers and experienced
** professionals having in-depth computer knowledge. Users are therefore
** encouraged to load and test the software's suitability as regards
** their requirements in conditions enabling the security of their
** systems and/or data to be ensured and, more generally, to use and
** operate it in the same conditions as regards security.
**
** The fact that you are presently reading this means that you have had
** knowledge of the CeCILL-C license and that you accept its terms.
*/
/************************************************************/
/** **/
/** NAME : bgraph_bipart_bd.c **/
/** **/
/** AUTHOR : Francois PELLEGRINI **/
/** **/
/** FUNCTION : This module builds a band graph around **/
/** the frontier in order to decrease **/
/** problem size for the strategy to be **/
/** applied. **/
/** **/
/** DATES : # Version 5.0 : from : 27 nov 2006 **/
/** to : 23 dec 2007 **/
/** # Version 5.1 : from : 09 nov 2008 **/
/** to : 26 mar 2011 **/
/** # Version 6.0 : from : 07 nov 2011 **/
/** to : 08 aug 2014 **/
/** **/
/************************************************************/
/*
** The defines and includes.
*/
#define BGRAPH_BIPART_BD
#include "module.h"
#include "common.h"
#include "parser.h"
#include "graph.h"
#include "arch.h"
#include "bgraph.h"
#include "bgraph_bipart_bd.h"
#include "bgraph_bipart_st.h"
/*****************************/
/* */
/* This is the main routine. */
/* */
/*****************************/
int
bgraphBipartBd (
Bgraph * restrict const orggrafptr, /*+ Active graph +*/
const BgraphBipartBdParam * const paraptr) /*+ Method parameters +*/
{
Gnum * restrict queutab;
Gnum queuheadval;
Gnum queutailval;
Gnum distmax; /* Maximum distance allowed */
Gnum * restrict orgindxtax; /* Based access to index array for original graph */
Gnum orgfronnum;
Gnum ancfronnum;
Gnum bndfronnum;
Bgraph bndgrafdat; /* Band graph structure */
Gnum bndvertnbr; /* Number of regular vertices in band graph (without anchors) */
Gnum bndvertnnd;
const Gnum * restrict bndvnumtax; /* Band vertex number array, recycling queutab */
Gnum * restrict bndveextax; /* External gain array of band graph, if present */
Gnum bndveexnbr; /* Number of external array vertices */
Gnum bndvelosum; /* Load of regular vertices in band graph */
Gnum bndedlosum; /* Sum of edge loads */
Gnum bndcompsize1; /* Number of regular vertices in part 1 of band graph */
Gnum bndcompload1; /* Load of regular vertices in part 1 */
Gnum bndvlvlnum; /* Index of first band graph vertex to belong to the last layer */
Gnum bndvertnum;
Gnum bndeancnbr; /* Number of anchor edges */
Gnum bndedgenbr; /* Upper bound on the number of edges, including anchor edges */
Gnum bndedgenum;
Gnum * restrict bndedgetax;
Gnum * restrict bndedlotax;
Gnum bndedgetmp;
Gnum bnddegrmax;
Gnum bndcommgainextn; /* Sum of all external gains in band graph */
Gnum bndcommgainextn1; /* Sum of external gains accounted for in load, since in part 1 */
size_t bndedlooftval; /* Offset of edge load array with respect to edge array */
const Gnum * restrict const orgverttax = orggrafptr->s.verttax; /* Fast accesses */
const Gnum * restrict const orgvendtax = orggrafptr->s.vendtax;
const Gnum * restrict const orgvelotax = orggrafptr->s.velotax;
const Gnum * restrict const orgedgetax = orggrafptr->s.edgetax;
const Gnum * restrict const orgedlotax = orggrafptr->s.edlotax;
GraphPart * restrict const orgparttax = orggrafptr->parttax;
Gnum * restrict const orgfrontab = orggrafptr->frontab;
if (orggrafptr->fronnbr == 0) /* If no separator vertices, apply strategy to full (original) graph */
return (bgraphBipartSt (orggrafptr, paraptr->stratorg));
distmax = (Gnum) paraptr->distmax;
if (distmax < 1) /* Always at least one layer of vertices around separator */
distmax = 1;
if (memAllocGroup ((void **) (void *)
&queutab, (size_t) (orggrafptr->s.vertnbr * sizeof (Gnum)),
&orgindxtax, (size_t) (orggrafptr->s.vertnbr * sizeof (Gnum)), NULL) == NULL) {
errorPrint ("bgraphBipartBd: out of memory (1)");
return (1);
}
memSet (orgindxtax, ~0, orggrafptr->s.vertnbr * sizeof (Gnum)); /* Initialize index array */
orgindxtax -= orggrafptr->s.baseval;
queuheadval = orggrafptr->fronnbr; /* First layer is vertices in frontier array */
for (orgfronnum = 0, bndvertnnd = orggrafptr->s.baseval; /* Flag vertices belonging to frontier as band vertices */
orgfronnum < queuheadval; orgfronnum ++) {
Gnum orgvertnum;
orgvertnum = orgfrontab[orgfronnum];
orgindxtax[orgvertnum] = bndvertnnd ++;
queutab[orgfronnum] = orgvertnum; /* Copy frontier array in queue array */
}
bndvelosum = 0;
bndedgenbr = 0; /* Estimate upper bound on the number of edges */
bndcompsize1 = 0;
bndcompload1 = 0;
queutailval = 0;
bndvlvlnum = 0; /* Assume first layer is last layer */
while (distmax -- > 0) { /* For all passes except the last one */
Gnum orgvertnum;
Gnum orgdistval;
bndvlvlnum = queuheadval; /* Record start of last layer */
while (queutailval < bndvlvlnum) { /* For all vertices in queue */
Gnum orgvertnum;
Gnum orgedgenum;
Gnum orgpartval;
orgvertnum = queutab[queutailval ++];
#ifdef SCOTCH_DEBUG_BGRAPH2
if ((orgvertnum < orggrafptr->s.baseval) || (orgvertnum >= orggrafptr->s.vertnnd)) {
errorPrint ("bgraphBipartBd: internal error (1)");
return (1);
}
#endif /* SCOTCH_DEBUG_BGRAPH2 */
bndedgenbr += orgvendtax[orgvertnum] - orgverttax[orgvertnum]; /* Exact number of edges */
orgpartval = orgparttax[orgvertnum];
bndcompsize1 += orgpartval; /* Count vertices in part 1 */
if (orgvelotax != NULL) {
Gnum orgveloval;
orgveloval = orgvelotax[orgvertnum];
bndvelosum += orgveloval;
bndcompload1 += orgveloval * orgpartval;
}
for (orgedgenum = orgverttax[orgvertnum];
orgedgenum < orgvendtax[orgvertnum]; orgedgenum ++) {
Gnum orgvertend;
orgvertend = orgedgetax[orgedgenum];
if (orgindxtax[orgvertend] == ~0) { /* If vertex not visited yet */
orgindxtax[orgvertend] = bndvertnnd ++; /* Flag it as enqueued */
queutab[queuheadval ++] = orgvertend; /* Enqueue it */
}
}
}
}
bndedgenbr += queuheadval - queutailval; /* As many edges from anchors as remaining vertices */
while (queutailval < queuheadval) { /* Process vertices in last layer */
Gnum orgvertnum;
Gnum orgpartval;
orgvertnum = queutab[queutailval ++];
#ifdef SCOTCH_DEBUG_BGRAPH2
if ((orgvertnum < orggrafptr->s.baseval) || (orgvertnum >= orggrafptr->s.vertnnd)) {
errorPrint ("bgraphBipartBd: internal error (2)");
return (1);
}
#endif /* SCOTCH_DEBUG_BGRAPH2 */
bndedgenbr += orgvendtax[orgvertnum] - orgverttax[orgvertnum]; /* Upper bound on number of edges, including anchor edge */
orgpartval = orgparttax[orgvertnum];
bndcompsize1 += orgpartval; /* Count vertices in part 1 */
if (orgvelotax != NULL) {
Gnum orgveloval;
orgveloval = orgvelotax[orgvertnum];
bndvelosum += orgveloval;
bndcompload1 += orgveloval * orgpartval;
}
}
bndvertnbr = bndvertnnd - orggrafptr->s.baseval;
if (orgvelotax == NULL) {
bndvelosum = bndvertnbr;
bndcompload1 = bndcompsize1;
}
if ((bndcompsize1 >= (orggrafptr->s.vertnbr - orggrafptr->compsize0)) || /* If either part has all of its vertices in band, use plain graph instead */
((bndvertnbr - bndcompsize1) >= orggrafptr->compsize0)) {
memFree (queutab);
return (bgraphBipartSt (orggrafptr, paraptr->stratorg));
} /* TRICK: since always at least one missing vertex per part, there is room for anchor vertices */
queutab[bndvertnbr] = /* Anchor vertices do not have original vertex numbers */
queutab[bndvertnbr + 1] = -1;
memSet (&bndgrafdat, 0, sizeof (Bgraph));
bndgrafdat.s.flagval = GRAPHFREETABS | GRAPHVERTGROUP | GRAPHEDGEGROUP | BGRAPHHASANCHORS; /* All Bgraph arrays are non-freeable by bgraphExit() */
bndgrafdat.s.baseval = orggrafptr->s.baseval;
bndgrafdat.s.vertnbr = bndvertnbr += 2; /* "+ 2" for anchor vertices */
bndgrafdat.s.vertnnd = bndvertnnd + 2;
bndveexnbr = (orggrafptr->veextax != NULL) ? bndvertnbr : 0;
if (memAllocGroup ((void **) (void *) /* Do not allocate vnumtax but keep queutab instead */
&bndgrafdat.s.verttax, (size_t) ((bndvertnbr + 1) * sizeof (Gnum)),
&bndgrafdat.s.velotax, (size_t) (bndvertnbr * sizeof (Gnum)),
&bndveextax, (size_t) (bndveexnbr * sizeof (Gnum)),
&bndgrafdat.frontab, (size_t) (bndvertnbr * sizeof (Gnum)),
&bndgrafdat.parttax, (size_t) (bndvertnbr * sizeof (GraphPart)), NULL) == NULL) {
errorPrint ("bgraphBipartBd: out of memory (2)");
memFree (queutab);
return (1);
}
bndgrafdat.parttax -= orggrafptr->s.baseval; /* From now on we should free a Bgraph and not a Graph */
bndgrafdat.s.verttax -= orggrafptr->s.baseval;
bndgrafdat.s.vendtax = bndgrafdat.s.verttax + 1; /* Band graph is compact */
bndgrafdat.s.velotax -= orggrafptr->s.baseval;
bndgrafdat.s.vnumtax = queutab - orggrafptr->s.baseval; /* TRICK: re-use queue array as vertex number array since vertices taken in queue order; will not be freed as graph vertex arrays are said to be grouped */
bndgrafdat.s.velosum = orggrafptr->s.velosum;
bndgrafdat.s.velotax[bndvertnnd] = orggrafptr->compload0 - (bndvelosum - bndcompload1); /* Set loads of anchor vertices */
bndgrafdat.s.velotax[bndvertnnd + 1] = orggrafptr->s.velosum - orggrafptr->compload0 - bndcompload1;
if (bndveexnbr != 0) {
bndveextax -= orggrafptr->s.baseval;
bndgrafdat.veextax = bndveextax;
}
else
bndveextax = NULL;
if (memAllocGroup ((void **) (void *)
&bndgrafdat.s.edgetax, (size_t) (bndedgenbr * sizeof (Gnum)),
&bndgrafdat.s.edlotax, (size_t) (bndedgenbr * sizeof (Gnum)), NULL) == NULL) {
errorPrint ("bgraphBipartBd: out of memory (3)");
bgraphExit (&bndgrafdat);
memFree (queutab);
return (1);
}
bndgrafdat.s.edgetax -= orggrafptr->s.baseval;
bndgrafdat.s.edlotax -= orggrafptr->s.baseval;
bndedgetax = bndgrafdat.s.edgetax;
bndedlotax = bndgrafdat.s.edlotax;
bndvnumtax = bndgrafdat.s.vnumtax;
for (bndvertnum = bndedgenum = orggrafptr->s.baseval, bnddegrmax = bndedlosum = bndcommgainextn = bndcommgainextn1 = 0;
bndvertnum < bndvlvlnum; bndvertnum ++) { /* Fill index array for vertices not belonging to last level */
Gnum orgvertnum;
GraphPart orgpartval;
Gnum orgedgenum;
Gnum orgedloval;
Gnum bnddegrval;
orgvertnum = bndvnumtax[bndvertnum];
orgpartval = orgparttax[orgvertnum];
bndgrafdat.s.verttax[bndvertnum] = bndedgenum;
bndgrafdat.s.velotax[bndvertnum] = (orgvelotax != NULL) ? orgvelotax[orgvertnum] : 1;
bndgrafdat.parttax[bndvertnum] = orgpartval;
if (bndveextax != NULL) {
Gnum orgveexval;
orgveexval = orggrafptr->veextax[orgvertnum];
bndveextax[bndvertnum] = orgveexval;
bndcommgainextn += orgveexval;
bndcommgainextn1 += orgveexval * (Gnum) orgpartval;
}
orgedloval = 1; /* Assume unity edge loads if not present */
for (orgedgenum = orgverttax[orgvertnum]; /* All edges of first levels are kept */
orgedgenum < orgvendtax[orgvertnum]; orgedgenum ++, bndedgenum ++) {
#ifdef SCOTCH_DEBUG_BGRAPH2
if ((bndedgenum >= (bndedgenbr + orggrafptr->s.baseval)) ||
(orgindxtax[orgedgetax[orgedgenum]] < 0)) {
errorPrint ("bgraphBipartBd: internal error (3)");
return (1);
}
#endif /* SCOTCH_DEBUG_BGRAPH2 */
if (orgedlotax != NULL)
orgedloval = orgedlotax[orgedgenum];
bndedlosum += orgedloval;
bndedgetax[bndedgenum] = orgindxtax[orgedgetax[orgedgenum]];
bndedlotax[bndedgenum] = orgedloval;
}
bnddegrval = bndedgenum - bndgrafdat.s.verttax[bndvertnum];
if (bnddegrmax < bnddegrval)
bnddegrmax = bnddegrval;
}
bndeancnbr = 0;
for ( ; bndvertnum < bndvertnnd; bndvertnum ++) { /* Fill index array for vertices belonging to last level */
Gnum orgvertnum;
Gnum orgedgenum;
GraphPart orgpartval;
Gnum bnddegrval;
Gnum orgedloval;
Gnum ancedloval; /* Accumulated edge load for anchor edge */
orgvertnum = bndvnumtax[bndvertnum];
orgpartval = orgparttax[orgvertnum];
bndgrafdat.s.verttax[bndvertnum] = bndedgenum;
bndgrafdat.s.velotax[bndvertnum] = (orgvelotax != NULL) ? orgvelotax[orgvertnum] : 1;
bndgrafdat.parttax[bndvertnum] = orgpartval; /* Record part for vertices of last level */
if (bndveextax != NULL) {
Gnum orgveexval;
orgveexval = orggrafptr->veextax[orgvertnum];
bndveextax[bndvertnum] = orgveexval;
bndcommgainextn += orgveexval;
bndcommgainextn1 += orgveexval * (Gnum) orgpartval;
}
ancedloval = 0;
orgedloval = 1; /* Assume unity edge loads if not present */
for (orgedgenum = orgverttax[orgvertnum]; /* Keep only band edges */
orgedgenum < orgvendtax[orgvertnum]; orgedgenum ++) {
Gnum bndvertend;
#ifdef SCOTCH_DEBUG_BGRAPH2
if (bndedgenum >= (bndedgenbr + orggrafptr->s.baseval)) {
errorPrint ("bgraphBipartBd: internal error (4)");
return (1);
}
#endif /* SCOTCH_DEBUG_BGRAPH2 */
if (orgedlotax != NULL)
orgedloval = orgedlotax[orgedgenum];
bndedlosum += orgedloval; /* Normal arcs are accounted for twice; anchor arcs only once */
bndvertend = orgindxtax[orgedgetax[orgedgenum]];
if (bndvertend != ~0) {
bndedgetax[bndedgenum] = bndvertend;
bndedlotax[bndedgenum ++] = orgedloval;
}
else
ancedloval += orgedloval; /* Accumulate loads of edges linking to anchor vertex */
}
bndedlosum += ancedloval; /* Account for anchor edges a second time */
if (ancedloval > 0) { /* If vertex is connected to rest of part */
bndedlotax[bndedgenum] = ancedloval;
bndedgetax[bndedgenum ++] = bndvertnnd + (Gnum) orgpartval; /* Add anchor edge to proper anchor vertex */
bndeancnbr ++;
}
bnddegrval = bndedgenum - bndgrafdat.s.verttax[bndvertnum];
if (bnddegrmax < bnddegrval)
bnddegrmax = bnddegrval;
}
bndgrafdat.parttax[bndvertnnd] = 0; /* Set parts of anchor vertices */
bndgrafdat.parttax[bndvertnnd + 1] = 1;
bndgrafdat.s.edlosum = bndedlosum;
bndgrafdat.s.verttax[bndvertnnd] = bndedgenum; /* Mark end of regular edge array and start of first anchor edge array */
bndedgetmp = bndedgenum + bndeancnbr;
#ifdef SCOTCH_DEBUG_BGRAPH2
if ((bndedgetmp - 1) >= (bndedgenbr + orggrafptr->s.baseval)) {
errorPrint ("bgraphBipartBd: internal error (5)");
return (1);
}
#endif /* SCOTCH_DEBUG_BGRAPH2 */
bndgrafdat.s.edgenbr = bndedgetmp - orggrafptr->s.baseval;
bndgrafdat.s.verttax[bndvertnnd + 2] = bndedgetmp; /* Mark end of edge array with anchor vertices */
for (bndvertnum = bndvlvlnum; bndvertnum < bndvertnnd; bndvertnum ++) { /* Fill anchor edge arrays */
Gnum orgvertnum;
orgvertnum = bndvnumtax[bndvertnum];
if (bndgrafdat.s.verttax[bndvertnum + 1] > bndgrafdat.s.verttax[bndvertnum]) { /* If vertex is not isolated */
Gnum bndedgelst; /* Number of last edge */
Gnum bndvertend;
bndedgelst = bndgrafdat.s.verttax[bndvertnum + 1] - 1;
bndvertend = bndedgetax[bndedgelst]; /* Get last neighbor of its edge sub-array */
if (bndvertend >= bndvertnnd) { /* If it is an anchor */
Gnum bndedloval;
bndedloval = bndedlotax[bndedgelst];
bndedlosum += bndedloval;
if (bndvertend == bndvertnnd) { /* Add edge from proper anchor */
bndedgetax[bndedgenum] = bndvertnum;
bndedlotax[bndedgenum ++] = bndedloval;
}
else {
bndedgetax[-- bndedgetmp] = bndvertnum;
bndedlotax[bndedgetmp] = bndedloval;
}
}
}
}
bndgrafdat.s.verttax[bndvertnnd + 1] = bndedgenum; /* Mark end of edge array of first anchor and start of second */
#ifdef SCOTCH_DEBUG_BGRAPH2
if (bndedgenum != bndedgetmp) {
errorPrint ("bgraphBipartBd: internal error (6)");
return (1);
}
#endif /* SCOTCH_DEBUG_BGRAPH2 */
if ((bndedgenum == bndgrafdat.s.verttax[bndvertnnd]) || /* If any of the anchor edges is isolated */
(bndedgenum == bndgrafdat.s.verttax[bndvertnnd + 2])) {
bgraphExit (&bndgrafdat); /* Free all band graph related data */
memFree (queutab);
return (bgraphBipartSt (orggrafptr, paraptr->stratorg)); /* Work on original graph */
}
if (bnddegrmax < (bndgrafdat.s.verttax[bndvertnnd + 1] - bndgrafdat.s.verttax[bndvertnnd]))
bnddegrmax = (bndgrafdat.s.verttax[bndvertnnd + 1] - bndgrafdat.s.verttax[bndvertnnd]);
if (bnddegrmax < (bndgrafdat.s.verttax[bndvertnnd + 2] - bndgrafdat.s.verttax[bndvertnnd + 1]))
bnddegrmax = (bndgrafdat.s.verttax[bndvertnnd + 2] - bndgrafdat.s.verttax[bndvertnnd + 1]);
bndgrafdat.s.degrmax = bnddegrmax;
bndedlooftval = bndedlotax - bndedgetax;
bndgrafdat.s.edgetax = (Gnum *) memRealloc (bndedgetax + bndgrafdat.s.baseval, (bndedlooftval + bndgrafdat.s.edgenbr) * sizeof (Gnum)) - bndgrafdat.s.baseval;
bndgrafdat.s.edlotax = bndgrafdat.s.edgetax + bndedlooftval; /* Use old index into old array as new index */
bndedgetax = bndgrafdat.s.edgetax;
bndedlotax = bndgrafdat.s.edlotax;
for (bndfronnum = 0, bndvertnum = orggrafptr->s.baseval; /* Fill band frontier array with first vertex indices as they make the separator */
bndfronnum < orggrafptr->fronnbr; bndfronnum ++, bndvertnum ++)
bndgrafdat.frontab[bndfronnum] = bndvertnum;
if (bndveextax != NULL) {
Gnum bndcommloadintn;
Gnum bndfronnnd;
Gnum bndvertnum;
Gnum bndedgenum;
Gnum bndedloval;
bndedloval = 1; /* Assume unity edge weights */
bndcommloadintn = 0;
for (bndvertnum = orggrafptr->s.baseval, bndfronnnd = bndvertnum + orggrafptr->fronnbr; /* Compute communication load at frontier */
bndvertnum < bndfronnnd; bndvertnum ++) {
Gnum bndpartval;
bndpartval = (Gnum) bndgrafdat.parttax[bndvertnum];
if (bndpartval != 0) /* Process only frontier vertices in part 0 */
continue;
for (bndedgenum = bndgrafdat.s.verttax[bndvertnum]; bndedgenum < bndgrafdat.s.vendtax[bndvertnum]; bndedgenum ++) {
Gnum bndpartend;
bndpartend = (Gnum) bndgrafdat.parttax[bndedgetax[bndedgenum]];
bndedloval = bndedlotax[bndedgenum];
bndcommloadintn += bndedloval * bndpartend;
}
}
bndcommloadintn *= orggrafptr->domndist;
bndveextax[bndvertnnd + 1] = (orggrafptr->commload - orggrafptr->commloadextn0 - bndcommloadintn) - bndcommgainextn1;
bndveextax[bndvertnnd] = (orggrafptr->commload - orggrafptr->commloadextn0 - bndcommloadintn) - bndcommgainextn + bndcommgainextn1 + orggrafptr->commgainextn;
}
bndgrafdat.fronnbr = orggrafptr->fronnbr;
bndgrafdat.compload0 = orggrafptr->compload0;
bndgrafdat.compload0min = orggrafptr->compload0min;
bndgrafdat.compload0max = orggrafptr->compload0max;
bndgrafdat.compload0avg = orggrafptr->compload0avg;
bndgrafdat.compload0dlt = orggrafptr->compload0dlt;
bndgrafdat.compsize0 = bndvertnbr - bndcompsize1 - 1; /* "- 1" for anchor vertex in part 0 */
bndgrafdat.commload = orggrafptr->commload;
bndgrafdat.commloadextn0 = orggrafptr->commloadextn0;
bndgrafdat.commgainextn = orggrafptr->commgainextn;
bndgrafdat.commgainextn0 = orggrafptr->commgainextn0;
bndgrafdat.domndist = orggrafptr->domndist;
bndgrafdat.domnwght[0] = orggrafptr->domnwght[0];
bndgrafdat.domnwght[1] = orggrafptr->domnwght[1];
bndgrafdat.vfixload[0] = orggrafptr->vfixload[0];
bndgrafdat.vfixload[1] = orggrafptr->vfixload[1];
bndgrafdat.bbalval = orggrafptr->bbalval;
bndgrafdat.levlnum = orggrafptr->levlnum;
#ifdef SCOTCH_DEBUG_BGRAPH2
if ((graphCheck (&bndgrafdat.s) != 0) || /* Check band graph consistency */
(bgraphCheck (&bndgrafdat) != 0)) {
errorPrint ("bgraphBipartBd: inconsistent band graph data");
bgraphExit (&bndgrafdat);
memFree (queutab);
return (1);
}
#endif /* SCOTCH_DEBUG_BGRAPH2 */
if (bgraphBipartSt (&bndgrafdat, paraptr->stratbnd) != 0) { /* Apply strategy to band graph */
errorPrint ("bgraphBipartBd: cannot bipartition band graph");
bgraphExit (&bndgrafdat);
memFree (queutab);
return (1);
}
if (bndgrafdat.parttax[bndvertnnd] == /* If band graph was too small and anchors went to the same part, apply strategy on full graph */
bndgrafdat.parttax[bndvertnnd + 1]) {
bgraphExit (&bndgrafdat);
memFree (queutab);
return (bgraphBipartSt (orggrafptr, paraptr->stratorg));
}
orggrafptr->compload0 = bndgrafdat.compload0;
orggrafptr->compload0dlt = bndgrafdat.compload0dlt;
orggrafptr->commload = bndgrafdat.commload;
orggrafptr->commgainextn = bndgrafdat.commgainextn;
orggrafptr->bbalval = bndgrafdat.bbalval;
if (bndgrafdat.parttax[bndvertnnd] != 0) { /* If anchors swapped parts, swap all parts of original vertices */
Gnum orgvertnum;
orggrafptr->compsize0 = orggrafptr->s.vertnbr - orggrafptr->compsize0 - bndcompsize1 + bndgrafdat.compsize0 - 1; /* "- 1" for anchor 0 */
for (orgvertnum = orggrafptr->s.baseval; orgvertnum < orggrafptr->s.vertnnd; orgvertnum ++)
orgparttax[orgvertnum] ^= 1;
}
else
orggrafptr->compsize0 = orggrafptr->compsize0 - (bndvertnbr - bndcompsize1) + bndgrafdat.compsize0 + 1; /* "+ 1" for anchor 0 */
for (bndvertnum = bndgrafdat.s.baseval; bndvertnum < bndvertnnd; bndvertnum ++) /* Update part array of full graph */
orgparttax[bndvnumtax[bndvertnum]] = bndgrafdat.parttax[bndvertnum];
for (bndfronnum = orgfronnum = ancfronnum = 0; /* Update frontier array of full graph */
bndfronnum < bndgrafdat.fronnbr; bndfronnum ++) {
Gnum bndvertnum;
Gnum orgvertnum;
bndvertnum = bndgrafdat.frontab[bndfronnum];
orgvertnum = bndvnumtax[bndvertnum];
if (orgvertnum != -1) /* If frontier vertex is not an anchor vertex */
orgfrontab[orgfronnum ++] = orgvertnum; /* Record it as original frontier vertex */
else
bndgrafdat.frontab[ancfronnum ++] = bndvertnum; /* Else record it for future processing */
}
while (ancfronnum > 0) { /* For all recorded frontier anchor vertices */
Gnum bndvertnum; /* Index of frontier anchor vertex in band graph */
GraphPart ancpartval;
bndvertnum = bndgrafdat.frontab[-- ancfronnum];
ancpartval = bndgrafdat.parttax[bndvertnum];
for (bndedgenum = bndgrafdat.s.verttax[bndvertnum];
bndedgenum < bndgrafdat.s.vendtax[bndvertnum]; bndedgenum ++) {
Gnum bndvertend; /* Index of neighbor of anchor vertex in band graph */
Gnum orgvertnum; /* Index of neighbor of anchor vertex in original graph */
Gnum orgedgenum;
bndvertend = bndedgetax[bndedgenum];
if (bndgrafdat.parttax[bndvertend] == ancpartval) /* If neighbor is in same part as anchor, skip to next */
continue;
orgvertnum = bndvnumtax[bndvertend];
for (orgedgenum = orgverttax[orgvertnum]; /* For all neighbors of neighbor */
orgedgenum < orgvendtax[orgvertnum]; orgedgenum ++) {
Gnum orgvertend;
orgvertend = orgedgetax[orgedgenum]; /* Get end vertex in original graph */
if (orgindxtax[orgvertend] == ~0) { /* If vertex never considered before */
#ifdef SCOTCH_DEBUG_BGRAPH2
if (orgparttax[orgvertend] != ancpartval) { /* Original vertex should always be in same part as anchor */
errorPrint ("bgraphBipartBd: internal error (7)");
return (1);
}
#endif /* SCOTCH_DEBUG_BGRAPH2 */
orggrafptr->frontab[orgfronnum ++] = orgvertend; /* Add vertex to frontier array */
orgindxtax[orgvertend] = 0; /* Flag vertex as already enqueued */
}
}
}
}
orggrafptr->fronnbr = orgfronnum;
bgraphExit (&bndgrafdat); /* Free band graph structures */
memFree (queutab);
#ifdef SCOTCH_DEBUG_BGRAPH2
if (bgraphCheck (orggrafptr) != 0) {
errorPrint ("bgraphBipartBd: inconsistent graph data");
return (1);
}
#endif /* SCOTCH_DEBUG_BGRAPH2 */
return (0);
}
|
HopeFOAM/HopeFOAM
|
ThirdParty-0.1/scotch_6.0.3/src/libscotch/bgraph_bipart_bd.c
|
C
|
gpl-3.0
| 29,153
|
#include "../lib/includes.h"
#include "../lib/utils.h"
#include "../lib/methnum.h"
#include "../Enum_type.h"
#include "../Var/var.h"
#include "../T0/t0.h"
#include "upot.h"
void test_der ( Upot * U , U_type upot_t , T0_type t0_t, bool phi_eq_phibar );
#define TD_T(f,df,nf,str) do{ testderiv(f,df,Tmin ,Tmax ,N,0.001,nf,str); } while(0)
#define TD_phi(f,df,nf,str) do{ testderiv(f,df,phimin,phimax,N,0.001,nf,str); } while(0)
#define TD_mu(f,df,nf,str) do{ testderiv(f,df,mumin ,mumax ,N,0.001,nf,str); } while(0)
#define TOTO(i) do{ printf("toto %d\n", i); } while(0)
int main ( void )
{
bool all_test = false ;
printf ("testing Gluonic potential derivatives \n" );
bool phi_eq_phibar = true ;
Upot * U = Upot_alloc_32 ( U_POW, T0_CST, C_ANA, 0.650, phi_eq_phibar );
test_der ( U , U_POW , T0_T2, true );
if ( false ){
test_der ( U , U_POW , T0_CST, phi_eq_phibar );
test_der ( U , U_POW , T0_T1, phi_eq_phibar );
test_der ( U , U_POW , T0_T2, phi_eq_phibar );
}
if ( false )
{
test_der ( U , U_POW , T0_T2, phi_eq_phibar );
test_der ( U , U_LOG , T0_T2, phi_eq_phibar );
test_der ( U , U_FUK , T0_T2, phi_eq_phibar );
test_der ( U , U_DEX , T0_T2, phi_eq_phibar );
}
if ( all_test )
{
test_der ( U , U_POW , T0_CST, phi_eq_phibar );
test_der ( U , U_POW , T0_T1, phi_eq_phibar );
test_der ( U , U_POW , T0_T2, phi_eq_phibar );
test_der ( U , U_LOG , T0_CST, phi_eq_phibar );
test_der ( U , U_LOG , T0_T1, phi_eq_phibar );
test_der ( U , U_LOG , T0_T2, phi_eq_phibar );
test_der ( U , U_FUK , T0_CST, phi_eq_phibar );
test_der ( U , U_DEX , T0_CST, phi_eq_phibar );
test_der ( U , U_DEX , T0_T1, phi_eq_phibar );
test_der ( U , U_DEX , T0_T2, phi_eq_phibar );
}
Upot_free ( U );
return 0 ;
}
void test_der ( Upot * U , U_type upot_t , T0_type t0_t, bool phi_eq_phibar )
{
// Upot_set_type ( U , upot_t, t0_t, ANA );
double T_ = 0.1 , phi_ = 0.5 , phibar_= 0.7, mu_= 0.1 ;
double Tmin= 0.1, Tmax=0.5, mumin=0., mumax=0.2, phimin=0.01,phimax=0.1 ;
int N = 40 ;
char pref[128], nf[256] ;
Var * V = Var_alloc ( );
if ( upot_t == U_POW )
{
Upot_set_pow_std ( U , t0_t, phi_eq_phibar);
if ( phi_eq_phibar )
{
if ( t0_t == T0_CST ) sprintf (pref ,"%s" ,"Upow_T0_cst_phi_eq_phibar" );
else if ( t0_t == T0_T1 ) sprintf (pref ,"%s" ,"Upow_T0_t1_phi_eq_phibar" );
else if ( t0_t == T0_T2 ) sprintf (pref ,"%s" ,"Upow_T0_t2_phi_eq_phibar" );
else { Var_free ( V ); Upot_free ( U ); ERROR ( stdout , "T0 type error"); }
}
else
{
if ( t0_t == T0_CST ) sprintf (pref ,"%s" ,"Upow_T0_cst" );
else if ( t0_t == T0_T1 ) sprintf (pref ,"%s" ,"Upow_T0_t1" );
else if ( t0_t == T0_T2 ) sprintf (pref ,"%s" ,"Upow_T0_t2" );
else { Var_free ( V ); Upot_free ( U ); ERROR ( stdout , "T0 type error"); }
}
}
else if ( upot_t == U_LOG )
{
Upot_set_log_std ( U , t0_t, phi_eq_phibar);
if ( phi_eq_phibar )
{
if ( t0_t == T0_CST ) sprintf (pref ,"%s" ,"Ulog_T0_cst_phi_eq_phibar" );
else if ( t0_t == T0_T1 ) sprintf (pref ,"%s" ,"Ulog_T0_t1_phi_eq_phibar" );
else if ( t0_t == T0_T2 ) sprintf (pref ,"%s" ,"Ulog_T0_t2_phi_eq_phibar" );
else { Var_free ( V ); Upot_free ( U ); ERROR ( stdout , "T0 type error");}
}
else
{
if ( t0_t == T0_CST ) sprintf (pref ,"%s" ,"Ulog_T0_cst" );
else if ( t0_t == T0_T1 ) sprintf (pref ,"%s" ,"Ulog_T0_t1" );
else if ( t0_t == T0_T2 ) sprintf (pref ,"%s" ,"Ulog_T0_t2" );
else { Var_free ( V ); Upot_free ( U ); ERROR ( stdout , "T0 type error");}
}
}
else if ( upot_t == U_FUK )
{
Upot_set_fuk_std ( U , t0_t, 0.650, phi_eq_phibar);
if ( phi_eq_phibar )
sprintf (pref ,"%s" ,"Ufuk_phi_eq_phibar" );
else
sprintf (pref ,"%s" ,"Ufuk" );
}
else if ( upot_t == U_DEX )
{
Upot_set_dex_std ( U , t0_t, phi_eq_phibar);
if ( phi_eq_phibar )
{
if ( t0_t == T0_CST ) sprintf (pref ,"%s" ,"Udex_T0_cst_phi_eq_phibar" );
else if ( t0_t == T0_T1 ) sprintf (pref ,"%s" ,"Udex_T0_t1_phi_eq_phibar" );
else if ( t0_t == T0_T2 ) sprintf (pref ,"%s" ,"Udex_T0_t2_phi_eq_phibar" );
else { Var_free ( V ); Upot_free ( U );ERROR ( stdout , "T0 type error"); }
}
else
{
if ( t0_t == T0_CST ) sprintf (pref ,"%s" ,"Udex_T0_cst" );
else if ( t0_t == T0_T1 ) sprintf (pref ,"%s" ,"Udex_T0_t1" );
else if ( t0_t == T0_T2 ) sprintf (pref ,"%s" ,"Udex_T0_t2" );
else { Var_free ( V ); Upot_free ( U );ERROR ( stdout , "T0 type error"); }
}
}
else
{
Var_free ( V ); Upot_free ( U );ERROR ( stdout , "U type error");
}
if ( !phi_eq_phibar )
{
//////////// GRAND POTENTIAL
////
double u_phi ( double phi ) { Var_set_Tmuphiphibar ( V, T_, mu_, phi , phibar_); return U->Ug( U->P , U->T0, V ); }
double u_phibar ( double phibar ) { Var_set_Tmuphiphibar ( V, T_, mu_, phi_, phibar ); return U->Ug( U->P , U->T0, V ); }
double u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->Ug( U->P , U->T0, V ); }
double u_mu ( double mu ) { Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->Ug( U->P , U->T0, V ); }
sprintf ( nf , "%s_phi" , pref ); plot_2D ( u_phi , phimin,phimax,N,nf,"set xla \"phi\"; set xzeroaxis" , false );
sprintf ( nf , "%s_phibar", pref ); plot_2D ( u_phibar, phimin,phimax,N,nf,"set xla \"phibar\"; set xzeroaxis", false );
sprintf ( nf , "%s_T" , pref ); plot_2D ( u_T , Tmin ,Tmax ,N,nf,"set xla \"T\"; set xzeroaxis" , false );
sprintf ( nf , "%s_mu" , pref ); plot_2D ( u_mu , mumin ,mumax ,N,nf,"set xla \"mu\"; set xzeroaxis" , false );
//////////// 1ST DERIVATIVES
////
double dphi_u_phi ( double phi ) { Var_set_Tmuphiphibar ( V, T_, mu_, phi , phibar_); return U->dphi_Ug ( U->P , U->T0, V ); }
double dphibar_u_phibar ( double phibar ) { Var_set_Tmuphiphibar ( V, T_, mu_, phi_, phibar ); return U->dphibar_Ug( U->P , U->T0, V ); }
double dT_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dT_Ug ( U->P , U->T0, V ); }
double dmu_u_mu ( double mu ) { Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dmu_Ug ( U->P , U->T0, V ); }
sprintf ( nf , "dphi_%s_phi" , pref ); TD_phi(u_phi ,dphi_u_phi ,nf,"set xla\"phi\"");
sprintf ( nf , "dphibar_%s_phibar", pref ); TD_phi(u_phibar,dphibar_u_phibar,nf,"set xla\"phibar\"");
sprintf ( nf , "dT_%s_T" , pref ); TD_T (u_T ,dT_u_T ,nf,"set xla\"T\"");
sprintf ( nf , "dmu_%s_mu" , pref ); TD_mu (u_mu ,dmu_u_mu ,nf,"set xla\"mu\"");
//////////// 2ND DERIVATIVES
////
double dT2_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dT2_Ug ( U->P , U->T0, V ); }
double dTmu_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dTmu_Ug ( U->P , U->T0, V ); }
double dmu_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dmu_Ug ( U->P , U->T0, V ); }
double dTphi_u_T( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dTphi_Ug ( U->P , U->T0, V ); }
double dphi_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dphi_Ug ( U->P , U->T0, V ); }
double dTphibar_u_T( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dTphibar_Ug ( U->P , U->T0, V ); }
double dphibar_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dphibar_Ug ( U->P , U->T0, V ); }
double dmu2_u_mu ( double mu ) { Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dmu2_Ug ( U->P , U->T0, V ); }
double dmuphi_u_mu ( double mu ){ Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dmuphi_Ug ( U->P , U->T0, V ); }
double dphi_u_mu( double mu ){ Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dphi_Ug ( U->P , U->T0, V ); }
double dmuphibar_u_mu ( double mu ){ Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dmuphibar_Ug ( U->P , U->T0, V ); }
double dphibar_u_mu( double mu ){ Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dphibar_Ug ( U->P , U->T0, V ); }
double dphi2_u_phi ( double phi ) { Var_set_Tmuphiphibar ( V, T_, mu_, phi , phibar_); return U->dphi2_Ug ( U->P , U->T0, V ); }
double dphiphibar_u_phi ( double phi ) { Var_set_Tmuphiphibar ( V, T_, mu_, phi , phibar_); return U->dphiphibar_Ug ( U->P , U->T0, V ); }
double dphibar_u_phi ( double phi ) { Var_set_Tmuphiphibar ( V, T_, mu_, phi , phibar_); return U->dphibar_Ug ( U->P , U->T0, V ); }
double dphibar2_u_phibar ( double phibar ) { Var_set_Tmuphiphibar ( V, T_, mu_, phi_, phibar ); return U->dphibar2_Ug( U->P , U->T0, V ); }
sprintf ( nf , "dT2_%s_T", pref ); TD_T(dT_u_T, dT2_u_T,nf , "set xla\"T\"");
sprintf ( nf , "dTmu_%s_T", pref ); TD_T(dmu_u_T, dTmu_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTphi_%s_T", pref ); TD_T(dphi_u_T, dTphi_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTphibar_%s_T", pref ); TD_T(dphibar_u_T, dTphibar_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dmu2_%s_mu", pref ); TD_mu (dmu_u_mu,dmu2_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dmuphi_%s_mu", pref ); TD_mu (dphi_u_mu,dmuphi_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dmuphibar_%s_mu", pref ); TD_mu (dphibar_u_mu,dmuphibar_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dphi2_%s_phi" , pref ); TD_phi(dphi_u_phi,dphi2_u_phi,nf,"set xla\"phi\"");
sprintf ( nf , "dphiphibar_%s_phi" , pref ); TD_phi(dphibar_u_phi,dphiphibar_u_phi,nf,"set xla\"phi\"");
sprintf ( nf , "dphibar2_%s_phibar", pref ); TD_phi(dphibar_u_phibar,dphibar2_u_phibar,nf,"set xla\"phibar\"");
//////////// 3RD DERIVATIVES
////
double dT3_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dT3_Ug ( U->P , U->T0, V ); }
double dT2mu_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dT2mu_Ug ( U->P , U->T0, V ); }
double dT2phi_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dT2phi_Ug ( U->P , U->T0, V ); }
double dT2phibar_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dT2phibar_Ug ( U->P , U->T0, V ); }
double dTmu2_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dTmu2_Ug ( U->P , U->T0, V ); }
double dmu2_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dmu2_Ug ( U->P , U->T0, V ); }
double dTmuphi_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dTmuphi_Ug ( U->P , U->T0, V ); }
double dmuphi_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dmuphi_Ug ( U->P , U->T0, V ); }
double dTmuphibar_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dTmuphibar_Ug ( U->P , U->T0, V ); }
double dmuphibar_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dmuphibar_Ug ( U->P , U->T0, V ); }
double dTphi2_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dTphi2_Ug ( U->P , U->T0, V ); }
double dphi2_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dphi2_Ug ( U->P , U->T0, V ); }
double dTphiphibar_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dTphiphibar_Ug ( U->P , U->T0, V ); }
double dphiphibar_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dphiphibar_Ug ( U->P , U->T0, V ); }
double dTphibar2_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dTphibar2_Ug ( U->P , U->T0, V ); }
double dphibar2_u_T ( double T ) { Var_set_Tmuphiphibar ( V, T , mu_, phi_, phibar_); return U->dphibar2_Ug ( U->P , U->T0, V ); }
double dmu3_u_mu ( double mu ) { Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dmu3_Ug ( U->P , U->T0, V ); }
double dmu2phi_u_mu ( double mu ) { Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dmu2phi_Ug ( U->P , U->T0, V ); }
double dmu2phibar_u_mu ( double mu ) { Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dmu2phibar_Ug ( U->P , U->T0, V ); }
double dmuphi2_u_mu ( double mu ) { Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dmuphi2_Ug ( U->P , U->T0, V ); }
double dphi2_u_mu ( double mu ) {Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dphi2_Ug ( U->P , U->T0, V ); }
double dmuphiphibar_u_mu ( double mu ) { Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dmuphiphibar_Ug ( U->P , U->T0, V ); }
double dphiphibar_u_mu ( double mu ) {Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dphiphibar_Ug ( U->P , U->T0, V ); }
double dmuphibar2_u_mu ( double mu ) { Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dmuphibar2_Ug ( U->P , U->T0, V ); }
double dphibar2_u_mu ( double mu ) { Var_set_Tmuphiphibar ( V, T_, mu , phi_, phibar_); return U->dphibar2_Ug ( U->P , U->T0, V ); }
double dphi3_u_phi ( double phi ) { Var_set_Tmuphiphibar ( V, T_, mu_, phi , phibar_); return U->dphi3_Ug ( U->P , U->T0, V ); }
double dphi2phibar_u_phi ( double phi ) { Var_set_Tmuphiphibar ( V, T_, mu_, phi , phibar_); return U->dphi2phibar_Ug ( U->P , U->T0, V ); }
double dphiphibar2_u_phi ( double phi ) {Var_set_Tmuphiphibar ( V, T_, mu_, phi , phibar_); return U->dphiphibar2_Ug ( U->P , U->T0, V ); }
double dphibar2_u_phi ( double phi ){Var_set_Tmuphiphibar ( V, T_, mu_, phi , phibar_); return U->dphibar2_Ug ( U->P , U->T0, V ); }
double dphibar3_u_phibar ( double phibar ) { Var_set_Tmuphiphibar( V, T_, mu_, phi_, phibar ); return U->dphibar3_Ug( U->P , U->T0, V ); }
sprintf ( nf , "dT3_%s_T", pref ); TD_T(dT2_u_T, dT3_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dT2mu_%s_T", pref ); TD_T(dTmu_u_T, dT2mu_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dT2phi_%s_T", pref ); TD_T(dTphi_u_T, dT2phi_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dT2phibar_%s_T", pref ); TD_T(dTphibar_u_T, dT2phibar_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTmu2_%s_T", pref ); TD_T(dmu2_u_T, dTmu2_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTmuphi_%s_T", pref ); TD_T(dmuphi_u_T, dTmuphi_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTmuphibar_%s_T", pref ); TD_T(dmuphibar_u_T, dTmuphibar_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTphi2_%s_T", pref ); TD_T(dphi2_u_T, dTphi2_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTphiphibar_%s_T", pref ); TD_T(dphiphibar_u_T, dTphiphibar_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTphibar2_%s_T", pref ); TD_T(dphibar2_u_T, dTphibar2_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dmu3_%s_mu", pref ); TD_mu (dmu2_u_mu,dmu3_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dmu2phi_%s_mu", pref ); TD_mu (dmuphi_u_mu,dmu2phi_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dmu2phibar_%s_mu", pref ); TD_mu (dmuphibar_u_mu,dmu2phibar_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dmuphi2_%s_mu", pref ); TD_mu (dphi2_u_mu,dmuphi2_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dmuphiphibar_%s_mu", pref ); TD_mu (dphiphibar_u_mu,dmuphiphibar_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dmuphibar2_%s_mu", pref ); TD_mu (dphibar2_u_mu,dmuphibar2_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dphi3_%s_phi", pref ); TD_phi(dphi2_u_phi,dphi3_u_phi,nf,"set xla\"phi\"");
sprintf ( nf , "dphiphibar_%s_phi", pref ); TD_phi(dphiphibar_u_phi,dphi2phibar_u_phi,nf,"set xla\"phi\"");
sprintf ( nf , "dphiphibar2_%s_phi", pref ); TD_phi(dphibar2_u_phi,dphiphibar2_u_phi,nf,"set xla\"phi\"");
sprintf ( nf , "dphibar3_%s_phibar", pref ); TD_phi(dphibar2_u_phibar,dphibar3_u_phibar,nf,"set xla\"phibar\"");
}
else // phi = phibar
{
//////////// GRAND POTENTIAL
////
double u_phi ( double phi ) { Var_set_Tmuphi ( V, T_, mu_, phi ); return U->Ug( U->P , U->T0, V ); }
double u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->Ug( U->P , U->T0, V ); }
double u_mu ( double mu ) { Var_set_Tmuphi ( V, T_, mu , phi_); return U->Ug( U->P , U->T0, V ); }
sprintf ( nf , "%s_phi" , pref ); plot_2D ( u_phi , phimin,phimax,N,nf,"set xla \"phi\"; set xzeroaxis" , false );
sprintf ( nf , "%s_T" , pref ); plot_2D ( u_T , Tmin ,Tmax ,N,nf,"set xla \"T\"; set xzeroaxis" , false );
sprintf ( nf , "%s_mu" , pref ); plot_2D ( u_mu , mumin ,mumax ,N,nf,"set xla \"mu\"; set xzeroaxis" , false );
//////////// 1ST DERIVATIVES
////
double dphi_u_phi ( double phi ) { Var_set_Tmuphi ( V, T_, mu_, phi ); return U->dphi_Ug ( U->P , U->T0, V ); }
double dT_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dT_Ug ( U->P , U->T0, V ); }
double dmu_u_mu ( double mu ) { Var_set_Tmuphi ( V, T_, mu , phi_); return U->dmu_Ug ( U->P , U->T0, V ); }
sprintf ( nf , "dphi_%s_phi" , pref ); TD_phi(u_phi ,dphi_u_phi ,nf,"set xla\"phi\"");
sprintf ( nf , "dT_%s_T" , pref ); TD_T (u_T ,dT_u_T ,nf,"set xla\"T\"");
sprintf ( nf , "dmu_%s_mu" , pref ); TD_mu (u_mu ,dmu_u_mu ,nf,"set xla\"mu\"");
//////////// 2ND DERIVATIVES
////
double dT2_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dT2_Ug ( U->P , U->T0, V ); }
double dTmu_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dTmu_Ug ( U->P , U->T0, V ); }
double dmu_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dmu_Ug ( U->P , U->T0, V ); }
double dTphi_u_T( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dTphi_Ug ( U->P , U->T0, V ); }
double dphi_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dphi_Ug ( U->P , U->T0, V ); }
double dmu2_u_mu ( double mu ) { Var_set_Tmuphi ( V, T_, mu , phi_); return U->dmu2_Ug ( U->P , U->T0, V ); }
double dmuphi_u_mu ( double mu ){ Var_set_Tmuphi ( V, T_, mu , phi_); return U->dmuphi_Ug ( U->P , U->T0, V ); }
double dphi_u_mu( double mu ){ Var_set_Tmuphi ( V, T_, mu , phi_); return U->dphi_Ug ( U->P , U->T0, V ); }
double dphi2_u_phi ( double phi ) { Var_set_Tmuphi ( V, T_, mu_, phi ); return U->dphi2_Ug ( U->P , U->T0, V ); }
//if ( false ) {
sprintf ( nf , "dT2_%s_T", pref ); TD_T(dT_u_T, dT2_u_T,nf , "set xla\"T\"");
sprintf ( nf , "dTmu_%s_T", pref ); TD_T(dmu_u_T, dTmu_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTphi_%s_T", pref ); TD_T(dphi_u_T, dTphi_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dmu2_%s_mu", pref ); TD_mu (dmu_u_mu,dmu2_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dmuphi_%s_mu", pref ); TD_mu (dphi_u_mu,dmuphi_u_mu ,nf,"set xla\"mu\""); //}
sprintf ( nf , "dphi2_%s_phi" , pref ); TD_phi(dphi_u_phi,dphi2_u_phi,nf,"set xla\"phi\""); //}
//////////// 3RD DERIVATIVES
////
double dT3_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dT3_Ug ( U->P , U->T0, V ); }
double dT2mu_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dT2mu_Ug ( U->P , U->T0, V ); }
double dT2phi_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dT2phi_Ug ( U->P , U->T0, V ); }
double dTmu2_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dTmu2_Ug ( U->P , U->T0, V ); }
double dmu2_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dmu2_Ug ( U->P , U->T0, V ); }
double dTmuphi_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dTmuphi_Ug ( U->P , U->T0, V ); }
double dmuphi_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dmuphi_Ug ( U->P , U->T0, V ); }
double dTphi2_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dTphi2_Ug ( U->P , U->T0, V ); }
double dphi2_u_T ( double T ) { Var_set_Tmuphi ( V, T , mu_, phi_); return U->dphi2_Ug ( U->P , U->T0, V ); }
double dmu3_u_mu ( double mu ) { Var_set_Tmuphi ( V, T_, mu , phi_); return U->dmu3_Ug ( U->P , U->T0, V ); }
double dmu2phi_u_mu ( double mu ) { Var_set_Tmuphi ( V, T_, mu , phi_); return U->dmu2phi_Ug ( U->P , U->T0, V ); }
double dmuphi2_u_mu ( double mu ) { Var_set_Tmuphi ( V, T_, mu , phi_); return U->dmuphi2_Ug ( U->P , U->T0, V ); }
double dphi2_u_mu ( double mu ) {Var_set_Tmuphi ( V, T_, mu , phi_); return U->dphi2_Ug ( U->P , U->T0, V ); }
double dphi3_u_phi ( double phi ) { Var_set_Tmuphi ( V, T_, mu_, phi ); return U->dphi3_Ug ( U->P , U->T0, V ); }
//if ( false ){
sprintf ( nf , "dT3_%s_T", pref ); TD_T(dT2_u_T, dT3_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dT2mu_%s_T", pref ); TD_T(dTmu_u_T, dT2mu_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dT2phi_%s_T", pref ); TD_T(dTphi_u_T, dT2phi_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTmu2_%s_T", pref ); TD_T(dmu2_u_T, dTmu2_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTmuphi_%s_T", pref ); TD_T(dmuphi_u_T, dTmuphi_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dTphi2_%s_T", pref ); TD_T(dphi2_u_T, dTphi2_u_T,nf,"set xla\"T\"");
sprintf ( nf , "dmu3_%s_mu", pref ); TD_mu (dmu2_u_mu,dmu3_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dmu2phi_%s_mu", pref ); TD_mu (dmuphi_u_mu,dmu2phi_u_mu ,nf,"set xla\"mu\"");
sprintf ( nf , "dmuphi2_%s_mu", pref ); TD_mu (dphi2_u_mu,dmuphi2_u_mu ,nf,"set xla\"mu\""); // }
sprintf ( nf , "dphi3_%s_phi", pref ); TD_phi(dphi2_u_phi,dphi3_u_phi,nf,"set xla\"phi\"");
/* double dphi2_u ( double phi ) */
/* { */
/* Var_set_Tmuphi( V, T_, mu_, phi ); */
/* double dphi_u( double phi ) */
/* { */
/* Var_set_Tmuphi( V, T_, mu_, phi); */
/* double u ( double phi ) */
/* { */
/* Var_set_Tmuphi( V, T_, mu_, phi); */
/* return upot_pow_phi_eq_phibar( U->P, U->T0, V ); */
/* } */
/* return deriv ( u, phi, 0.001 ) ; */
/* } */
/* return deriv( dphi_u, phi, 0.001 ) ; */
/* } */
/* sprintf( nf, "all-num__dphi3_%s_phi", pref ) ; TD_phi( dphi2_u, dphi3_u_phi,nf, "set xla\"phi\"" ); */
}
Var_free ( V );
}
|
AlexandreBiguet/NJLlikeModels
|
legacy/programs/njl-1/Upot/test_der.c
|
C
|
gpl-3.0
| 22,920
|
#include "gremlin.h"
void cs_kroneckerIupdate(const cs *A, int nI, const cs *C){
int i, j, k, cnt, an, am;
double *Ax;
an = A->n;
am = A->m;
Ax = A->x;
cnt = 0;
for(i = 0; i < an; i++){
for(j = 0 ; j < nI ; j++){
for(k = 0; k < am; k++){
C->x[cnt] = Ax[i*an+k];
cnt++;
}
}
}
}
|
matthewwolak/gremlin
|
src/cs_kroneckerIupdate.c
|
C
|
gpl-3.0
| 376
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <volk_fft/volk_fft_prefs.h>
//#if defined(_WIN32)
//#include <Windows.h>
//#endif
void volk_fft_get_config_path(char *path)
{
if (!path) return;
const char *suffix = "/.volk_fft/volk_fft_config";
char *home = NULL;
if (home == NULL) home = getenv("HOME");
if (home == NULL) home = getenv("APPDATA");
if (home == NULL){
path[0] = 0;
return;
}
strcpy(path, home);
strcat(path, suffix);
}
size_t volk_fft_load_preferences(volk_fft_arch_pref_t **prefs_res)
{
FILE *config_file;
char path[512], line[512];
size_t n_arch_prefs = 0;
volk_fft_arch_pref_t *prefs = NULL;
//get the config path
volk_fft_get_config_path(path);
if (!path[0]) return n_arch_prefs; //no prefs found
config_file = fopen(path, "r");
if(!config_file) return n_arch_prefs; //no prefs found
//reset the file pointer and write the prefs into volk_fft_arch_prefs
while(fgets(line, sizeof(line), config_file) != NULL)
{
prefs = (volk_fft_arch_pref_t *) realloc(prefs, (n_arch_prefs+1) * sizeof(*prefs));
volk_fft_arch_pref_t *p = prefs + n_arch_prefs;
if(sscanf(line, "%s %s %s", p->name, p->impl_a, p->impl_u) == 3 && !strncmp(p->name, "volk_fft_", 5))
{
n_arch_prefs++;
}
}
fclose(config_file);
*prefs_res = prefs;
return n_arch_prefs;
}
|
hamgravy/volk-fft
|
lib/volk_fft_prefs.c
|
C
|
gpl-3.0
| 1,442
|
/*
* Generic DSI Command Mode panel driver
*
* Copyright (C) 2013 Texas Instruments
* Author: Tomi Valkeinen <tomi.valkeinen@ti.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*/
/* #define DEBUG */
#include <linux/backlight.h>
#include <linux/delay.h>
#include <linux/fb.h>
#include <linux/gpio.h>
#include <linux/interrupt.h>
#include <linux/jiffies.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include <linux/of_device.h>
#include <linux/of_gpio.h>
#include <video/omapfb_dss.h>
#include <video/mipi_display.h>
/* DSI Virtual channel. Hardcoded for now. */
#define TCH 0
#define DCS_READ_NUM_ERRORS 0x05
#define DCS_BRIGHTNESS 0x51
#define DCS_CTRL_DISPLAY 0x53
#define DCS_GET_ID1 0xda
#define DCS_GET_ID2 0xdb
#define DCS_GET_ID3 0xdc
struct panel_drv_data
{
struct omap_dss_device dssdev;
struct omap_dss_device *in;
struct omap_video_timings timings;
struct platform_device *pdev;
struct mutex lock;
struct backlight_device *bldev;
unsigned long hw_guard_end; /* next value of jiffies when we can
* issue the next sleep in/out command
*/
unsigned long hw_guard_wait; /* max guard time in jiffies */
/* panel HW configuration from DT or platform data */
int reset_gpio;
int ext_te_gpio;
bool use_dsi_backlight;
struct omap_dsi_pin_config pin_config;
/* runtime variables */
bool enabled;
bool te_enabled;
atomic_t do_update;
int channel;
struct delayed_work te_timeout_work;
bool intro_printed;
bool ulps_enabled;
unsigned ulps_timeout;
struct delayed_work ulps_work;
};
#define to_panel_data(p) container_of(p, struct panel_drv_data, dssdev)
static irqreturn_t dsicm_te_isr(int irq, void *data);
static void dsicm_te_timeout_work_callback(struct work_struct *work);
static int _dsicm_enable_te(struct panel_drv_data *ddata, bool enable);
static int dsicm_panel_reset(struct panel_drv_data *ddata);
static void dsicm_ulps_work(struct work_struct *work);
static void hw_guard_start(struct panel_drv_data *ddata, int guard_msec)
{
ddata->hw_guard_wait = msecs_to_jiffies(guard_msec);
ddata->hw_guard_end = jiffies + ddata->hw_guard_wait;
}
static void hw_guard_wait(struct panel_drv_data *ddata)
{
unsigned long wait = ddata->hw_guard_end - jiffies;
if ((long)wait > 0 && wait <= ddata->hw_guard_wait)
{
set_current_state(TASK_UNINTERRUPTIBLE);
schedule_timeout(wait);
}
}
static int dsicm_dcs_read_1(struct panel_drv_data *ddata, u8 dcs_cmd, u8 *data)
{
struct omap_dss_device *in = ddata->in;
int r;
u8 buf[1];
r = in->ops.dsi->dcs_read(in, ddata->channel, dcs_cmd, buf, 1);
if (r < 0)
{
return r;
}
*data = buf[0];
return 0;
}
static int dsicm_dcs_write_0(struct panel_drv_data *ddata, u8 dcs_cmd)
{
struct omap_dss_device *in = ddata->in;
return in->ops.dsi->dcs_write(in, ddata->channel, &dcs_cmd, 1);
}
static int dsicm_dcs_write_1(struct panel_drv_data *ddata, u8 dcs_cmd, u8 param)
{
struct omap_dss_device *in = ddata->in;
u8 buf[2] = { dcs_cmd, param };
return in->ops.dsi->dcs_write(in, ddata->channel, buf, 2);
}
static int dsicm_sleep_in(struct panel_drv_data *ddata)
{
struct omap_dss_device *in = ddata->in;
u8 cmd;
int r;
hw_guard_wait(ddata);
cmd = MIPI_DCS_ENTER_SLEEP_MODE;
r = in->ops.dsi->dcs_write_nosync(in, ddata->channel, &cmd, 1);
if (r)
{
return r;
}
hw_guard_start(ddata, 120);
usleep_range(5000, 10000);
return 0;
}
static int dsicm_sleep_out(struct panel_drv_data *ddata)
{
int r;
hw_guard_wait(ddata);
r = dsicm_dcs_write_0(ddata, MIPI_DCS_EXIT_SLEEP_MODE);
if (r)
{
return r;
}
hw_guard_start(ddata, 120);
usleep_range(5000, 10000);
return 0;
}
static int dsicm_get_id(struct panel_drv_data *ddata, u8 *id1, u8 *id2, u8 *id3)
{
int r;
r = dsicm_dcs_read_1(ddata, DCS_GET_ID1, id1);
if (r)
{
return r;
}
r = dsicm_dcs_read_1(ddata, DCS_GET_ID2, id2);
if (r)
{
return r;
}
r = dsicm_dcs_read_1(ddata, DCS_GET_ID3, id3);
if (r)
{
return r;
}
return 0;
}
static int dsicm_set_update_window(struct panel_drv_data *ddata,
u16 x, u16 y, u16 w, u16 h)
{
struct omap_dss_device *in = ddata->in;
int r;
u16 x1 = x;
u16 x2 = x + w - 1;
u16 y1 = y;
u16 y2 = y + h - 1;
u8 buf[5];
buf[0] = MIPI_DCS_SET_COLUMN_ADDRESS;
buf[1] = (x1 >> 8) & 0xff;
buf[2] = (x1 >> 0) & 0xff;
buf[3] = (x2 >> 8) & 0xff;
buf[4] = (x2 >> 0) & 0xff;
r = in->ops.dsi->dcs_write_nosync(in, ddata->channel, buf, sizeof(buf));
if (r)
{
return r;
}
buf[0] = MIPI_DCS_SET_PAGE_ADDRESS;
buf[1] = (y1 >> 8) & 0xff;
buf[2] = (y1 >> 0) & 0xff;
buf[3] = (y2 >> 8) & 0xff;
buf[4] = (y2 >> 0) & 0xff;
r = in->ops.dsi->dcs_write_nosync(in, ddata->channel, buf, sizeof(buf));
if (r)
{
return r;
}
in->ops.dsi->bta_sync(in, ddata->channel);
return r;
}
static void dsicm_queue_ulps_work(struct panel_drv_data *ddata)
{
if (ddata->ulps_timeout > 0)
schedule_delayed_work(&ddata->ulps_work,
msecs_to_jiffies(ddata->ulps_timeout));
}
static void dsicm_cancel_ulps_work(struct panel_drv_data *ddata)
{
cancel_delayed_work(&ddata->ulps_work);
}
static int dsicm_enter_ulps(struct panel_drv_data *ddata)
{
struct omap_dss_device *in = ddata->in;
int r;
if (ddata->ulps_enabled)
{
return 0;
}
dsicm_cancel_ulps_work(ddata);
r = _dsicm_enable_te(ddata, false);
if (r)
{
goto err;
}
if (gpio_is_valid(ddata->ext_te_gpio))
{
disable_irq(gpio_to_irq(ddata->ext_te_gpio));
}
in->ops.dsi->disable(in, false, true);
ddata->ulps_enabled = true;
return 0;
err:
dev_err(&ddata->pdev->dev, "enter ULPS failed");
dsicm_panel_reset(ddata);
ddata->ulps_enabled = false;
dsicm_queue_ulps_work(ddata);
return r;
}
static int dsicm_exit_ulps(struct panel_drv_data *ddata)
{
struct omap_dss_device *in = ddata->in;
int r;
if (!ddata->ulps_enabled)
{
return 0;
}
r = in->ops.dsi->enable(in);
if (r)
{
dev_err(&ddata->pdev->dev, "failed to enable DSI\n");
goto err1;
}
in->ops.dsi->enable_hs(in, ddata->channel, true);
r = _dsicm_enable_te(ddata, true);
if (r)
{
dev_err(&ddata->pdev->dev, "failed to re-enable TE");
goto err2;
}
if (gpio_is_valid(ddata->ext_te_gpio))
{
enable_irq(gpio_to_irq(ddata->ext_te_gpio));
}
dsicm_queue_ulps_work(ddata);
ddata->ulps_enabled = false;
return 0;
err2:
dev_err(&ddata->pdev->dev, "failed to exit ULPS");
r = dsicm_panel_reset(ddata);
if (!r)
{
if (gpio_is_valid(ddata->ext_te_gpio))
{
enable_irq(gpio_to_irq(ddata->ext_te_gpio));
}
ddata->ulps_enabled = false;
}
err1:
dsicm_queue_ulps_work(ddata);
return r;
}
static int dsicm_wake_up(struct panel_drv_data *ddata)
{
if (ddata->ulps_enabled)
{
return dsicm_exit_ulps(ddata);
}
dsicm_cancel_ulps_work(ddata);
dsicm_queue_ulps_work(ddata);
return 0;
}
static int dsicm_bl_update_status(struct backlight_device *dev)
{
struct panel_drv_data *ddata = dev_get_drvdata(&dev->dev);
struct omap_dss_device *in = ddata->in;
int r;
int level;
if (dev->props.fb_blank == FB_BLANK_UNBLANK &&
dev->props.power == FB_BLANK_UNBLANK)
{
level = dev->props.brightness;
}
else
{
level = 0;
}
dev_dbg(&ddata->pdev->dev, "update brightness to %d\n", level);
mutex_lock(&ddata->lock);
if (ddata->enabled)
{
in->ops.dsi->bus_lock(in);
r = dsicm_wake_up(ddata);
if (!r)
{
r = dsicm_dcs_write_1(ddata, DCS_BRIGHTNESS, level);
}
in->ops.dsi->bus_unlock(in);
}
else
{
r = 0;
}
mutex_unlock(&ddata->lock);
return r;
}
static int dsicm_bl_get_intensity(struct backlight_device *dev)
{
if (dev->props.fb_blank == FB_BLANK_UNBLANK &&
dev->props.power == FB_BLANK_UNBLANK)
{
return dev->props.brightness;
}
return 0;
}
static const struct backlight_ops dsicm_bl_ops =
{
.get_brightness = dsicm_bl_get_intensity,
.update_status = dsicm_bl_update_status,
};
static void dsicm_get_resolution(struct omap_dss_device *dssdev,
u16 *xres, u16 *yres)
{
*xres = dssdev->panel.timings.x_res;
*yres = dssdev->panel.timings.y_res;
}
static ssize_t dsicm_num_errors_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
struct omap_dss_device *in = ddata->in;
u8 errors = 0;
int r;
mutex_lock(&ddata->lock);
if (ddata->enabled)
{
in->ops.dsi->bus_lock(in);
r = dsicm_wake_up(ddata);
if (!r)
r = dsicm_dcs_read_1(ddata, DCS_READ_NUM_ERRORS,
&errors);
in->ops.dsi->bus_unlock(in);
}
else
{
r = -ENODEV;
}
mutex_unlock(&ddata->lock);
if (r)
{
return r;
}
return snprintf(buf, PAGE_SIZE, "%d\n", errors);
}
static ssize_t dsicm_hw_revision_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
struct omap_dss_device *in = ddata->in;
u8 id1, id2, id3;
int r;
mutex_lock(&ddata->lock);
if (ddata->enabled)
{
in->ops.dsi->bus_lock(in);
r = dsicm_wake_up(ddata);
if (!r)
{
r = dsicm_get_id(ddata, &id1, &id2, &id3);
}
in->ops.dsi->bus_unlock(in);
}
else
{
r = -ENODEV;
}
mutex_unlock(&ddata->lock);
if (r)
{
return r;
}
return snprintf(buf, PAGE_SIZE, "%02x.%02x.%02x\n", id1, id2, id3);
}
static ssize_t dsicm_store_ulps(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct platform_device *pdev = to_platform_device(dev);
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
struct omap_dss_device *in = ddata->in;
unsigned long t;
int r;
r = kstrtoul(buf, 0, &t);
if (r)
{
return r;
}
mutex_lock(&ddata->lock);
if (ddata->enabled)
{
in->ops.dsi->bus_lock(in);
if (t)
{
r = dsicm_enter_ulps(ddata);
}
else
{
r = dsicm_wake_up(ddata);
}
in->ops.dsi->bus_unlock(in);
}
mutex_unlock(&ddata->lock);
if (r)
{
return r;
}
return count;
}
static ssize_t dsicm_show_ulps(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
unsigned t;
mutex_lock(&ddata->lock);
t = ddata->ulps_enabled;
mutex_unlock(&ddata->lock);
return snprintf(buf, PAGE_SIZE, "%u\n", t);
}
static ssize_t dsicm_store_ulps_timeout(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct platform_device *pdev = to_platform_device(dev);
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
struct omap_dss_device *in = ddata->in;
unsigned long t;
int r;
r = kstrtoul(buf, 0, &t);
if (r)
{
return r;
}
mutex_lock(&ddata->lock);
ddata->ulps_timeout = t;
if (ddata->enabled)
{
/* dsicm_wake_up will restart the timer */
in->ops.dsi->bus_lock(in);
r = dsicm_wake_up(ddata);
in->ops.dsi->bus_unlock(in);
}
mutex_unlock(&ddata->lock);
if (r)
{
return r;
}
return count;
}
static ssize_t dsicm_show_ulps_timeout(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
unsigned t;
mutex_lock(&ddata->lock);
t = ddata->ulps_timeout;
mutex_unlock(&ddata->lock);
return snprintf(buf, PAGE_SIZE, "%u\n", t);
}
static DEVICE_ATTR(num_dsi_errors, S_IRUGO, dsicm_num_errors_show, NULL);
static DEVICE_ATTR(hw_revision, S_IRUGO, dsicm_hw_revision_show, NULL);
static DEVICE_ATTR(ulps, S_IRUGO | S_IWUSR,
dsicm_show_ulps, dsicm_store_ulps);
static DEVICE_ATTR(ulps_timeout, S_IRUGO | S_IWUSR,
dsicm_show_ulps_timeout, dsicm_store_ulps_timeout);
static struct attribute *dsicm_attrs[] =
{
&dev_attr_num_dsi_errors.attr,
&dev_attr_hw_revision.attr,
&dev_attr_ulps.attr,
&dev_attr_ulps_timeout.attr,
NULL,
};
static struct attribute_group dsicm_attr_group =
{
.attrs = dsicm_attrs,
};
static void dsicm_hw_reset(struct panel_drv_data *ddata)
{
if (!gpio_is_valid(ddata->reset_gpio))
{
return;
}
gpio_set_value(ddata->reset_gpio, 1);
udelay(10);
/* reset the panel */
gpio_set_value(ddata->reset_gpio, 0);
/* assert reset */
udelay(10);
gpio_set_value(ddata->reset_gpio, 1);
/* wait after releasing reset */
usleep_range(5000, 10000);
}
static int dsicm_power_on(struct panel_drv_data *ddata)
{
struct omap_dss_device *in = ddata->in;
u8 id1, id2, id3;
int r;
struct omap_dss_dsi_config dsi_config =
{
.mode = OMAP_DSS_DSI_CMD_MODE,
.pixel_format = OMAP_DSS_DSI_FMT_RGB888,
.timings = &ddata->timings,
.hs_clk_min = 150000000,
.hs_clk_max = 300000000,
.lp_clk_min = 7000000,
.lp_clk_max = 10000000,
};
if (ddata->pin_config.num_pins > 0)
{
r = in->ops.dsi->configure_pins(in, &ddata->pin_config);
if (r)
{
dev_err(&ddata->pdev->dev,
"failed to configure DSI pins\n");
goto err0;
}
}
r = in->ops.dsi->set_config(in, &dsi_config);
if (r)
{
dev_err(&ddata->pdev->dev, "failed to configure DSI\n");
goto err0;
}
r = in->ops.dsi->enable(in);
if (r)
{
dev_err(&ddata->pdev->dev, "failed to enable DSI\n");
goto err0;
}
dsicm_hw_reset(ddata);
in->ops.dsi->enable_hs(in, ddata->channel, false);
r = dsicm_sleep_out(ddata);
if (r)
{
goto err;
}
r = dsicm_get_id(ddata, &id1, &id2, &id3);
if (r)
{
goto err;
}
r = dsicm_dcs_write_1(ddata, DCS_BRIGHTNESS, 0xff);
if (r)
{
goto err;
}
r = dsicm_dcs_write_1(ddata, DCS_CTRL_DISPLAY,
(1 << 2) | (1 << 5)); /* BL | BCTRL */
if (r)
{
goto err;
}
r = dsicm_dcs_write_1(ddata, MIPI_DCS_SET_PIXEL_FORMAT,
MIPI_DCS_PIXEL_FMT_24BIT);
if (r)
{
goto err;
}
r = dsicm_dcs_write_0(ddata, MIPI_DCS_SET_DISPLAY_ON);
if (r)
{
goto err;
}
r = _dsicm_enable_te(ddata, ddata->te_enabled);
if (r)
{
goto err;
}
r = in->ops.dsi->enable_video_output(in, ddata->channel);
if (r)
{
goto err;
}
ddata->enabled = 1;
if (!ddata->intro_printed)
{
dev_info(&ddata->pdev->dev, "panel revision %02x.%02x.%02x\n",
id1, id2, id3);
ddata->intro_printed = true;
}
in->ops.dsi->enable_hs(in, ddata->channel, true);
return 0;
err:
dev_err(&ddata->pdev->dev, "error while enabling panel, issuing HW reset\n");
dsicm_hw_reset(ddata);
in->ops.dsi->disable(in, true, false);
err0:
return r;
}
static void dsicm_power_off(struct panel_drv_data *ddata)
{
struct omap_dss_device *in = ddata->in;
int r;
in->ops.dsi->disable_video_output(in, ddata->channel);
r = dsicm_dcs_write_0(ddata, MIPI_DCS_SET_DISPLAY_OFF);
if (!r)
{
r = dsicm_sleep_in(ddata);
}
if (r)
{
dev_err(&ddata->pdev->dev,
"error disabling panel, issuing HW reset\n");
dsicm_hw_reset(ddata);
}
in->ops.dsi->disable(in, true, false);
ddata->enabled = 0;
}
static int dsicm_panel_reset(struct panel_drv_data *ddata)
{
dev_err(&ddata->pdev->dev, "performing LCD reset\n");
dsicm_power_off(ddata);
dsicm_hw_reset(ddata);
return dsicm_power_on(ddata);
}
static int dsicm_connect(struct omap_dss_device *dssdev)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
struct device *dev = &ddata->pdev->dev;
int r;
if (omapdss_device_is_connected(dssdev))
{
return 0;
}
r = in->ops.dsi->connect(in, dssdev);
if (r)
{
dev_err(dev, "Failed to connect to video source\n");
return r;
}
r = in->ops.dsi->request_vc(ddata->in, &ddata->channel);
if (r)
{
dev_err(dev, "failed to get virtual channel\n");
goto err_req_vc;
}
r = in->ops.dsi->set_vc_id(ddata->in, ddata->channel, TCH);
if (r)
{
dev_err(dev, "failed to set VC_ID\n");
goto err_vc_id;
}
return 0;
err_vc_id:
in->ops.dsi->release_vc(ddata->in, ddata->channel);
err_req_vc:
in->ops.dsi->disconnect(in, dssdev);
return r;
}
static void dsicm_disconnect(struct omap_dss_device *dssdev)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
if (!omapdss_device_is_connected(dssdev))
{
return;
}
in->ops.dsi->release_vc(in, ddata->channel);
in->ops.dsi->disconnect(in, dssdev);
}
static int dsicm_enable(struct omap_dss_device *dssdev)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
int r;
dev_dbg(&ddata->pdev->dev, "enable\n");
mutex_lock(&ddata->lock);
if (!omapdss_device_is_connected(dssdev))
{
r = -ENODEV;
goto err;
}
if (omapdss_device_is_enabled(dssdev))
{
r = 0;
goto err;
}
in->ops.dsi->bus_lock(in);
r = dsicm_power_on(ddata);
in->ops.dsi->bus_unlock(in);
if (r)
{
goto err;
}
dssdev->state = OMAP_DSS_DISPLAY_ACTIVE;
mutex_unlock(&ddata->lock);
return 0;
err:
dev_dbg(&ddata->pdev->dev, "enable failed\n");
mutex_unlock(&ddata->lock);
return r;
}
static void dsicm_disable(struct omap_dss_device *dssdev)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
int r;
dev_dbg(&ddata->pdev->dev, "disable\n");
mutex_lock(&ddata->lock);
dsicm_cancel_ulps_work(ddata);
in->ops.dsi->bus_lock(in);
if (omapdss_device_is_enabled(dssdev))
{
r = dsicm_wake_up(ddata);
if (!r)
{
dsicm_power_off(ddata);
}
}
in->ops.dsi->bus_unlock(in);
dssdev->state = OMAP_DSS_DISPLAY_DISABLED;
mutex_unlock(&ddata->lock);
}
static void dsicm_framedone_cb(int err, void *data)
{
struct panel_drv_data *ddata = data;
struct omap_dss_device *in = ddata->in;
dev_dbg(&ddata->pdev->dev, "framedone, err %d\n", err);
in->ops.dsi->bus_unlock(ddata->in);
}
static irqreturn_t dsicm_te_isr(int irq, void *data)
{
struct panel_drv_data *ddata = data;
struct omap_dss_device *in = ddata->in;
int old;
int r;
old = atomic_cmpxchg(&ddata->do_update, 1, 0);
if (old)
{
cancel_delayed_work(&ddata->te_timeout_work);
r = in->ops.dsi->update(in, ddata->channel, dsicm_framedone_cb,
ddata);
if (r)
{
goto err;
}
}
return IRQ_HANDLED;
err:
dev_err(&ddata->pdev->dev, "start update failed\n");
in->ops.dsi->bus_unlock(in);
return IRQ_HANDLED;
}
static void dsicm_te_timeout_work_callback(struct work_struct *work)
{
struct panel_drv_data *ddata = container_of(work, struct panel_drv_data,
te_timeout_work.work);
struct omap_dss_device *in = ddata->in;
dev_err(&ddata->pdev->dev, "TE not received for 250ms!\n");
atomic_set(&ddata->do_update, 0);
in->ops.dsi->bus_unlock(in);
}
static int dsicm_update(struct omap_dss_device *dssdev,
u16 x, u16 y, u16 w, u16 h)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
int r;
dev_dbg(&ddata->pdev->dev, "update %d, %d, %d x %d\n", x, y, w, h);
mutex_lock(&ddata->lock);
in->ops.dsi->bus_lock(in);
r = dsicm_wake_up(ddata);
if (r)
{
goto err;
}
if (!ddata->enabled)
{
r = 0;
goto err;
}
/* XXX no need to send this every frame, but dsi break if not done */
r = dsicm_set_update_window(ddata, 0, 0,
dssdev->panel.timings.x_res,
dssdev->panel.timings.y_res);
if (r)
{
goto err;
}
if (ddata->te_enabled && gpio_is_valid(ddata->ext_te_gpio))
{
schedule_delayed_work(&ddata->te_timeout_work,
msecs_to_jiffies(250));
atomic_set(&ddata->do_update, 1);
}
else
{
r = in->ops.dsi->update(in, ddata->channel, dsicm_framedone_cb,
ddata);
if (r)
{
goto err;
}
}
/* note: no bus_unlock here. unlock is in framedone_cb */
mutex_unlock(&ddata->lock);
return 0;
err:
in->ops.dsi->bus_unlock(in);
mutex_unlock(&ddata->lock);
return r;
}
static int dsicm_sync(struct omap_dss_device *dssdev)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
dev_dbg(&ddata->pdev->dev, "sync\n");
mutex_lock(&ddata->lock);
in->ops.dsi->bus_lock(in);
in->ops.dsi->bus_unlock(in);
mutex_unlock(&ddata->lock);
dev_dbg(&ddata->pdev->dev, "sync done\n");
return 0;
}
static int _dsicm_enable_te(struct panel_drv_data *ddata, bool enable)
{
struct omap_dss_device *in = ddata->in;
int r;
if (enable)
{
r = dsicm_dcs_write_1(ddata, MIPI_DCS_SET_TEAR_ON, 0);
}
else
{
r = dsicm_dcs_write_0(ddata, MIPI_DCS_SET_TEAR_OFF);
}
if (!gpio_is_valid(ddata->ext_te_gpio))
{
in->ops.dsi->enable_te(in, enable);
}
/* possible panel bug */
msleep(100);
return r;
}
static int dsicm_enable_te(struct omap_dss_device *dssdev, bool enable)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
int r;
mutex_lock(&ddata->lock);
if (ddata->te_enabled == enable)
{
goto end;
}
in->ops.dsi->bus_lock(in);
if (ddata->enabled)
{
r = dsicm_wake_up(ddata);
if (r)
{
goto err;
}
r = _dsicm_enable_te(ddata, enable);
if (r)
{
goto err;
}
}
ddata->te_enabled = enable;
in->ops.dsi->bus_unlock(in);
end:
mutex_unlock(&ddata->lock);
return 0;
err:
in->ops.dsi->bus_unlock(in);
mutex_unlock(&ddata->lock);
return r;
}
static int dsicm_get_te(struct omap_dss_device *dssdev)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
int r;
mutex_lock(&ddata->lock);
r = ddata->te_enabled;
mutex_unlock(&ddata->lock);
return r;
}
static int dsicm_memory_read(struct omap_dss_device *dssdev,
void *buf, size_t size,
u16 x, u16 y, u16 w, u16 h)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
int r;
int first = 1;
int plen;
unsigned buf_used = 0;
if (size < w * h * 3)
{
return -ENOMEM;
}
mutex_lock(&ddata->lock);
if (!ddata->enabled)
{
r = -ENODEV;
goto err1;
}
size = min(w * h * 3,
dssdev->panel.timings.x_res *
dssdev->panel.timings.y_res * 3);
in->ops.dsi->bus_lock(in);
r = dsicm_wake_up(ddata);
if (r)
{
goto err2;
}
/* plen 1 or 2 goes into short packet. until checksum error is fixed,
* use short packets. plen 32 works, but bigger packets seem to cause
* an error. */
if (size % 2)
{
plen = 1;
}
else
{
plen = 2;
}
dsicm_set_update_window(ddata, x, y, w, h);
r = in->ops.dsi->set_max_rx_packet_size(in, ddata->channel, plen);
if (r)
{
goto err2;
}
while (buf_used < size)
{
u8 dcs_cmd = first ? 0x2e : 0x3e;
first = 0;
r = in->ops.dsi->dcs_read(in, ddata->channel, dcs_cmd,
buf + buf_used, size - buf_used);
if (r < 0)
{
dev_err(dssdev->dev, "read error\n");
goto err3;
}
buf_used += r;
if (r < plen)
{
dev_err(&ddata->pdev->dev, "short read\n");
break;
}
if (signal_pending(current))
{
dev_err(&ddata->pdev->dev, "signal pending, "
"aborting memory read\n");
r = -ERESTARTSYS;
goto err3;
}
}
r = buf_used;
err3:
in->ops.dsi->set_max_rx_packet_size(in, ddata->channel, 1);
err2:
in->ops.dsi->bus_unlock(in);
err1:
mutex_unlock(&ddata->lock);
return r;
}
static void dsicm_ulps_work(struct work_struct *work)
{
struct panel_drv_data *ddata = container_of(work, struct panel_drv_data,
ulps_work.work);
struct omap_dss_device *dssdev = &ddata->dssdev;
struct omap_dss_device *in = ddata->in;
mutex_lock(&ddata->lock);
if (dssdev->state != OMAP_DSS_DISPLAY_ACTIVE || !ddata->enabled)
{
mutex_unlock(&ddata->lock);
return;
}
in->ops.dsi->bus_lock(in);
dsicm_enter_ulps(ddata);
in->ops.dsi->bus_unlock(in);
mutex_unlock(&ddata->lock);
}
static struct omap_dss_driver dsicm_ops =
{
.connect = dsicm_connect,
.disconnect = dsicm_disconnect,
.enable = dsicm_enable,
.disable = dsicm_disable,
.update = dsicm_update,
.sync = dsicm_sync,
.get_resolution = dsicm_get_resolution,
.get_recommended_bpp = omapdss_default_get_recommended_bpp,
.enable_te = dsicm_enable_te,
.get_te = dsicm_get_te,
.memory_read = dsicm_memory_read,
};
static int dsicm_probe_of(struct platform_device *pdev)
{
struct device_node *node = pdev->dev.of_node;
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
struct omap_dss_device *in;
int gpio;
gpio = of_get_named_gpio(node, "reset-gpios", 0);
if (!gpio_is_valid(gpio))
{
dev_err(&pdev->dev, "failed to parse reset gpio\n");
return gpio;
}
ddata->reset_gpio = gpio;
gpio = of_get_named_gpio(node, "te-gpios", 0);
if (gpio_is_valid(gpio) || gpio == -ENOENT)
{
ddata->ext_te_gpio = gpio;
}
else
{
dev_err(&pdev->dev, "failed to parse TE gpio\n");
return gpio;
}
in = omapdss_of_find_source_for_first_ep(node);
if (IS_ERR(in))
{
dev_err(&pdev->dev, "failed to find video source\n");
return PTR_ERR(in);
}
ddata->in = in;
/* TODO: ulps, backlight */
return 0;
}
static int dsicm_probe(struct platform_device *pdev)
{
struct backlight_properties props;
struct panel_drv_data *ddata;
struct backlight_device *bldev = NULL;
struct device *dev = &pdev->dev;
struct omap_dss_device *dssdev;
int r;
dev_dbg(dev, "probe\n");
if (!pdev->dev.of_node)
{
return -ENODEV;
}
ddata = devm_kzalloc(dev, sizeof(*ddata), GFP_KERNEL);
if (!ddata)
{
return -ENOMEM;
}
platform_set_drvdata(pdev, ddata);
ddata->pdev = pdev;
r = dsicm_probe_of(pdev);
if (r)
{
return r;
}
ddata->timings.x_res = 864;
ddata->timings.y_res = 480;
ddata->timings.pixelclock = 864 * 480 * 60;
dssdev = &ddata->dssdev;
dssdev->dev = dev;
dssdev->driver = &dsicm_ops;
dssdev->panel.timings = ddata->timings;
dssdev->type = OMAP_DISPLAY_TYPE_DSI;
dssdev->owner = THIS_MODULE;
dssdev->panel.dsi_pix_fmt = OMAP_DSS_DSI_FMT_RGB888;
dssdev->caps = OMAP_DSS_DISPLAY_CAP_MANUAL_UPDATE |
OMAP_DSS_DISPLAY_CAP_TEAR_ELIM;
r = omapdss_register_display(dssdev);
if (r)
{
dev_err(dev, "Failed to register panel\n");
goto err_reg;
}
mutex_init(&ddata->lock);
atomic_set(&ddata->do_update, 0);
if (gpio_is_valid(ddata->reset_gpio))
{
r = devm_gpio_request_one(dev, ddata->reset_gpio,
GPIOF_OUT_INIT_LOW, "taal rst");
if (r)
{
dev_err(dev, "failed to request reset gpio\n");
return r;
}
}
if (gpio_is_valid(ddata->ext_te_gpio))
{
r = devm_gpio_request_one(dev, ddata->ext_te_gpio,
GPIOF_IN, "taal irq");
if (r)
{
dev_err(dev, "GPIO request failed\n");
return r;
}
r = devm_request_irq(dev, gpio_to_irq(ddata->ext_te_gpio),
dsicm_te_isr,
IRQF_TRIGGER_RISING,
"taal vsync", ddata);
if (r)
{
dev_err(dev, "IRQ request failed\n");
return r;
}
INIT_DEFERRABLE_WORK(&ddata->te_timeout_work,
dsicm_te_timeout_work_callback);
dev_dbg(dev, "Using GPIO TE\n");
}
INIT_DELAYED_WORK(&ddata->ulps_work, dsicm_ulps_work);
dsicm_hw_reset(ddata);
if (ddata->use_dsi_backlight)
{
memset(&props, 0, sizeof(struct backlight_properties));
props.max_brightness = 255;
props.type = BACKLIGHT_RAW;
bldev = backlight_device_register(dev_name(dev),
dev, ddata, &dsicm_bl_ops, &props);
if (IS_ERR(bldev))
{
r = PTR_ERR(bldev);
goto err_reg;
}
ddata->bldev = bldev;
bldev->props.fb_blank = FB_BLANK_UNBLANK;
bldev->props.power = FB_BLANK_UNBLANK;
bldev->props.brightness = 255;
dsicm_bl_update_status(bldev);
}
r = sysfs_create_group(&dev->kobj, &dsicm_attr_group);
if (r)
{
dev_err(dev, "failed to create sysfs files\n");
goto err_sysfs_create;
}
return 0;
err_sysfs_create:
if (bldev != NULL)
{
backlight_device_unregister(bldev);
}
err_reg:
return r;
}
static int __exit dsicm_remove(struct platform_device *pdev)
{
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
struct omap_dss_device *dssdev = &ddata->dssdev;
struct backlight_device *bldev;
dev_dbg(&pdev->dev, "remove\n");
omapdss_unregister_display(dssdev);
dsicm_disable(dssdev);
dsicm_disconnect(dssdev);
sysfs_remove_group(&pdev->dev.kobj, &dsicm_attr_group);
bldev = ddata->bldev;
if (bldev != NULL)
{
bldev->props.power = FB_BLANK_POWERDOWN;
dsicm_bl_update_status(bldev);
backlight_device_unregister(bldev);
}
omap_dss_put_device(ddata->in);
dsicm_cancel_ulps_work(ddata);
/* reset, to be sure that the panel is in a valid state */
dsicm_hw_reset(ddata);
return 0;
}
static const struct of_device_id dsicm_of_match[] =
{
{ .compatible = "omapdss,panel-dsi-cm", },
{},
};
MODULE_DEVICE_TABLE(of, dsicm_of_match);
static struct platform_driver dsicm_driver =
{
.probe = dsicm_probe,
.remove = __exit_p(dsicm_remove),
.driver = {
.name = "panel-dsi-cm",
.of_match_table = dsicm_of_match,
.suppress_bind_attrs = true,
},
};
module_platform_driver(dsicm_driver);
MODULE_AUTHOR("Tomi Valkeinen <tomi.valkeinen@ti.com>");
MODULE_DESCRIPTION("Generic DSI Command Mode Panel Driver");
MODULE_LICENSE("GPL");
|
williamfdevine/PrettyLinux
|
drivers/video/fbdev/omap2/omapfb/displays/panel-dsi-cm.c
|
C
|
gpl-3.0
| 28,860
|
/* Copyright (C) 2014 CZ.NIC, z.s.p.o. <knot-dns@labs.nic.cz>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <tap/basic.h>
#include <string.h>
#include <stdlib.h>
#include "libknot/internal/mempattern.h"
#include "libknot/internal/mempool.h"
#include "libknot/errcode.h"
#include "knot/nameserver/query_module.h"
#include "libknot/packet/pkt.h"
/* Universal processing stage. */
int state_visit(int state, knot_pkt_t *pkt, struct query_data *qdata, void *ctx)
{
/* Visit current state */
bool *state_map = ctx;
state_map[state] = true;
return state + 1;
}
int main(int argc, char *argv[])
{
plan(4);
/* Create processing context. */
mm_ctx_t mm;
mm_ctx_mempool(&mm, MM_DEFAULT_BLKSIZE);
/* Create a map of expected steps. */
bool state_map[QUERY_PLAN_STAGES] = { false };
/* Prepare query plan. */
struct query_plan *plan = query_plan_create(&mm);
ok(plan != NULL, "query_plan: create");
/* Register all stage visits. */
int ret = KNOT_EOK;
for (unsigned stage = QPLAN_BEGIN; stage < QUERY_PLAN_STAGES; ++stage) {
ret = query_plan_step(plan, stage, state_visit, state_map);
if (ret != KNOT_EOK) {
break;
}
}
ok(ret == KNOT_EOK, "query_plan: planned all steps");
/* Execute the plan. */
int state = 0, next_state = 0;
for (unsigned stage = QPLAN_BEGIN; stage < QUERY_PLAN_STAGES; ++stage) {
struct query_step *step = NULL;
WALK_LIST(step, plan->stage[stage]) {
next_state = step->process(state, NULL, NULL, step->ctx);
if (next_state != state + 1) {
break;
}
state = next_state;
}
}
ok(state == QUERY_PLAN_STAGES, "query_plan: executed all steps");
/* Verify if all steps executed their callback. */
for (state = 0; state < QUERY_PLAN_STAGES; ++state) {
if (state_map[state] == false) {
break;
}
}
ok(state == QUERY_PLAN_STAGES, "query_plan: executed all callbacks");
/* Free the query plan. */
query_plan_free(plan);
/* Cleanup. */
mp_delete((struct mempool *)mm.ctx);
return 0;
}
|
jkadlec/knot-dns-zoneapi
|
tests/query_module.c
|
C
|
gpl-3.0
| 2,585
|
/*
* gtpm-mgr
*
* Version 1.00
* Copyright (C) 2012-2014 Nicolas Provost dev AT doronic DOT fr
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <gtk/gtk.h>
#include "llib_tpm.h"
#include "llib_opt.h"
#include "llib_print.h"
#include "llib_gtk.h"
#include "gtpm_mgr.h"
#include "gtpm_ui.h"
#include "gtpm_tpm.h"
#include "gtpm_uio.h"
static void gtpm_mgr_reset_vars(gtpm_config_t* gmgr)
{
llib_data_free(&gmgr->args.output);
llib_data_free(&gmgr->args.data);
llib_data_free(&gmgr->args.data2);
llib_data_free(&gmgr->args.encdata);
gmgr->args.set = 0;
llib_tpm_keystore_release_one_shot_key(gmgr->args.keystore);
}
/* run a command from the label of the clicked item */
void gtpm_mgr_run (gtpm_config_t* gmgr, const char* label)
{
lbool res;
const struct gtpm_menu_action_t* entry = >pm_tpm_menu_entries[0];
/* find the command from the label */
while (entry && entry->label && entry->job)
{
if (llib_str_equ(entry->label, label,0))
break;
entry++;
}
if (!entry || !entry->label || !entry->job)
{
gmgr->tpm.last_error = LLIB_TPM_ERROR_UNIMPLEMENTED;
llib_tpm_uio_error (&gmgr->args, "Unable to run command");
llib_print_f(2, "[gtpm-mgr] unknown command label '%s'\n", label);
return;
}
/* get descriptor */
gmgr->args.desc = llib_tpm_find_descriptor (entry->job);
if (!gmgr->args.desc)
{
gmgr->tpm.last_error = LLIB_TPM_ERROR_UNIMPLEMENTED;
llib_tpm_uio_error (&gmgr->args, "Unable to run command");
llib_print_f(2, "[gtpm-mgr] unknown descriptor '%s'\n",
gmgr->args.desc);
return;
}
/* set standard output if no other choice */
if ((gmgr->args.desc->in & LLIB_TPM_FOUTPUT) &&
!gmgr->args.cargs->output &&
!(gmgr->args.desc->sin & LLIB_TPM_FSOUTPUTNODEF))
{
gmgr->args.output = llib_data_create_text_buffer();
if (!gmgr->args.output)
{
llib_tpm_uio_printf (&gmgr->args, LLIB_TPM_UIO_ERR,
"unable to open standard output\n");
return;
}
gmgr->args.set |= LLIB_TPM_FOUTPUT;
}
/* run the command */
llib_gtku_set_cursor (GTK_WIDGET(gmgr->ui.gWindow), GDK_CIRCLE);
llib_gtku_process_signals ();
if (llib_tpm_run (&gmgr->tpm, entry->job, &gmgr->args, &res) && res)
{
llib_gtku_set_cursor (GTK_WIDGET(gmgr->ui.gWindow), GDK_ARROW);
llib_tpm_keystore_add_one_shot_key (gmgr->args.keystore);
if (gmgr->args.output &&
(gmgr->args.output->type == LLIB_DATA_TYPE_BUFFER) &&
(llib_buffer_type(&gmgr->args.output->data.buffer)
== LLIB_BUFFER_TEXT))
{
gtpmuio_output_text (&gmgr->args, "command result",
&gmgr->args.output->data.buffer);
}
}
else
{
llib_gtku_set_cursor (GTK_WIDGET(gmgr->ui.gWindow), GDK_ARROW);
llib_tpm_uio_error (&gmgr->args, "Unable to run command");
}
gtpm_mgr_reset_vars(gmgr);
llib_gtku_set_cursor(GTK_WIDGET(gmgr->ui.gWindow), GDK_ARROW);
}
static void gtpm_mgr_clean(gtpm_config_t* gmgr) {
llib_tpm_free(&gmgr->tpm);
llib_tpm_store_free(gmgr->args.store);
llib_tpm_keystore_free(gmgr->args.keystore);
llib_tpm_uio_free(&gmgr->uio);
}
int main(int argc, char* argv[])
{
gtpm_config_t gmgr;
int retcode = EXIT_FAILURE;
char c;
char* arg = NULL;
char* devpath = NULL;
llib_mem_zero(&gmgr, sizeof(gtpm_config_t));
gmgr.args.cargs = &gmgr.cargs;
gmgr.args.store = gmgr.cargs.store = &gmgr.cargs.st.store;
llib_tpm_key_init(&gmgr.cargs.st.store_key);
llib_tpm_store_init(gmgr.args.store, &gmgr.tpm, NULL);
gmgr.cargs.st.store.key = &gmgr.cargs.st.store_key;
gmgr.args.uio = &gmgr.uio;
gmgr.cargs.st.ui = &gmgr.ui;
gmgr.args.tpm = &gmgr.tpm;
gmgr.args.keystore = &gmgr.cargs.st.keystore;
gmgr.args.o = gmgr.cargs.o = &gmgr.cargs.st.o;
llib_tpm_store_object_init(gmgr.args.o, NULL, NULL);
gtpmuio_init(&gmgr.uio, &gmgr.args);
llib_tpm_keystore_init(gmgr.args.keystore);
llib_print_f(1, "gtpm-mgr v" VERSION "\n");
llib_print_f(1, "usage: [-dtpm|store|all (debug)] [-v (verbose)] "
"[-tTPM_DEV_PATH (default is /dev/tpm0)]\n");
while ((c = llib_opt_get_short(argc, argv, "vd::t::", &arg)) != -1)
{
switch (c)
{
case 'v':
gmgr.args.verbose = TRUE;
break;
case 'd':
if (llib_str_equ(arg, "all", 0) ||
llib_str_equ(arg, "store", 0))
{
gmgr.args.debug = TRUE;
gmgr.args.store->debug = TRUE;
}
if (llib_str_equ(arg, "all", 0) ||
llib_str_equ(arg, "tpm",0))
gmgr.tpm.debug = TRUE;
break;
case 't':
if (!arg)
{
llib_print_f(2, "[gtpm-mgr] FATAL: missing TPM device path\n");
return EXIT_FAILURE;
}
devpath = llib_str_dup(arg);
llib_print_f(2, "[gtpm-mgr] using TPM at %s\n", arg);
break;
}
llib_str_release(&arg);
}
gtk_init(&argc, &argv);
if (!gtpm_ui_build(&gmgr))
{
llib_print_f(2, "[gtpm-mgr] FATAL: unable to build graphical "
"interface, aborting\n");
}
else
{
if (!llib_tpm_init(&gmgr.tpm, devpath, 30, gmgr.tpm.debug))
llib_tpm_uio_error(&gmgr.args, "TPM initialization error");
else
{
gtk_widget_show_all(GTK_WIDGET(gmgr.ui.gWindow));
gtk_main();
retcode = EXIT_SUCCESS;
}
}
llib_mem_free(devpath);
gtpm_mgr_clean(&gmgr);
return retcode;
}
|
doronic/llib
|
src/tpm/mgr/gtpm_mgr.c
|
C
|
gpl-3.0
| 5,773
|
/* LIBGIMP - The GIMP Library
* Copyright (C) 1995-2003 Peter Mattis and Spencer Kimball
*
* gimplayer_pdb.c
*
* 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 3 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, see
* <http://www.gnu.org/licenses/>.
*/
/* NOTE: This file is auto-generated by pdbgen.pl */
#include "config.h"
#include "gimp.h"
/**
* SECTION: gimplayer
* @title: gimplayer
* @short_description: Operations on a single layer.
*
* Operations on a single layer.
**/
/**
* _gimp_layer_new:
* @image_ID: The image to which to add the layer.
* @width: The layer width.
* @height: The layer height.
* @type: The layer type.
* @name: The layer name.
* @opacity: The layer opacity.
* @mode: The layer combination mode.
*
* Create a new layer.
*
* This procedure creates a new layer with the specified width, height,
* and type. Name, opacity, and mode are also supplied parameters. The
* new layer still needs to be added to the image, as this is not
* automatic. Add the new layer with the gimp_image_insert_layer()
* command. Other attributes such as layer mask modes, and offsets
* should be set with explicit procedure calls.
*
* Returns: The newly created layer.
**/
gint32
_gimp_layer_new (gint32 image_ID,
gint width,
gint height,
GimpImageType type,
const gchar *name,
gdouble opacity,
GimpLayerModeEffects mode)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 layer_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-new",
&nreturn_vals,
GIMP_PDB_IMAGE, image_ID,
GIMP_PDB_INT32, width,
GIMP_PDB_INT32, height,
GIMP_PDB_INT32, type,
GIMP_PDB_STRING, name,
GIMP_PDB_FLOAT, opacity,
GIMP_PDB_INT32, mode,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
layer_ID = return_vals[1].data.d_layer;
gimp_destroy_params (return_vals, nreturn_vals);
return layer_ID;
}
/**
* gimp_layer_new_from_visible:
* @image_ID: The source image from where the content is copied.
* @dest_image_ID: The destination image to which to add the layer.
* @name: The layer name.
*
* Create a new layer from what is visible in an image.
*
* This procedure creates a new layer from what is visible in the given
* image. The new layer still needs to be added to the destination
* image, as this is not automatic. Add the new layer with the
* gimp_image_insert_layer() command. Other attributes such as layer
* mask modes, and offsets should be set with explicit procedure calls.
*
* Returns: The newly created layer.
*
* Since: GIMP 2.6
**/
gint32
gimp_layer_new_from_visible (gint32 image_ID,
gint32 dest_image_ID,
const gchar *name)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 layer_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-new-from-visible",
&nreturn_vals,
GIMP_PDB_IMAGE, image_ID,
GIMP_PDB_IMAGE, dest_image_ID,
GIMP_PDB_STRING, name,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
layer_ID = return_vals[1].data.d_layer;
gimp_destroy_params (return_vals, nreturn_vals);
return layer_ID;
}
/**
* gimp_layer_new_from_drawable:
* @drawable_ID: The source drawable from where the new layer is copied.
* @dest_image_ID: The destination image to which to add the layer.
*
* Create a new layer by copying an existing drawable.
*
* This procedure creates a new layer as a copy of the specified
* drawable. The new layer still needs to be added to the image, as
* this is not automatic. Add the new layer with the
* gimp_image_insert_layer() command. Other attributes such as layer
* mask modes, and offsets should be set with explicit procedure calls.
*
* Returns: The newly copied layer.
**/
gint32
gimp_layer_new_from_drawable (gint32 drawable_ID,
gint32 dest_image_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 layer_copy_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-new-from-drawable",
&nreturn_vals,
GIMP_PDB_DRAWABLE, drawable_ID,
GIMP_PDB_IMAGE, dest_image_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
layer_copy_ID = return_vals[1].data.d_layer;
gimp_destroy_params (return_vals, nreturn_vals);
return layer_copy_ID;
}
/**
* gimp_layer_group_new:
* @image_ID: The image to which to add the layer group.
*
* Create a new layer group.
*
* This procedure creates a new layer group. Attributes such as layer
* mode and opacity should be set with explicit procedure calls. Add
* the new layer group (which is a kind of layer) with the
* gimp_image_insert_layer() command.
*
* Returns: The newly created layer group.
*
* Since: GIMP 2.8
**/
gint32
gimp_layer_group_new (gint32 image_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 layer_group_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-group-new",
&nreturn_vals,
GIMP_PDB_IMAGE, image_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
layer_group_ID = return_vals[1].data.d_layer;
gimp_destroy_params (return_vals, nreturn_vals);
return layer_group_ID;
}
/**
* _gimp_layer_copy:
* @layer_ID: The layer to copy.
* @add_alpha: Add an alpha channel to the copied layer.
*
* Copy a layer.
*
* This procedure copies the specified layer and returns the copy. The
* newly copied layer is for use within the original layer's image. It
* should not be subsequently added to any other image. The copied
* layer can optionally have an added alpha channel. This is useful if
* the background layer in an image is being copied and added to the
* same image.
*
* Returns: The newly copied layer.
**/
gint32
_gimp_layer_copy (gint32 layer_ID,
gboolean add_alpha)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 layer_copy_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-copy",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, add_alpha,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
layer_copy_ID = return_vals[1].data.d_layer;
gimp_destroy_params (return_vals, nreturn_vals);
return layer_copy_ID;
}
/**
* gimp_layer_add_alpha:
* @layer_ID: The layer.
*
* Add an alpha channel to the layer if it doesn't already have one.
*
* This procedure adds an additional component to the specified layer
* if it does not already possess an alpha channel. An alpha channel
* makes it possible to clear and erase to transparency, instead of the
* background color. This transforms layers of type RGB to RGBA, GRAY
* to GRAYA, and INDEXED to INDEXEDA.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_add_alpha (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-add-alpha",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_flatten:
* @layer_ID: The layer.
*
* Remove the alpha channel from the layer if it has one.
*
* This procedure removes the alpha channel from a layer, blending all
* (partially) transparent pixels in the layer against the background
* color. This transforms layers of type RGBA to RGB, GRAYA to GRAY,
* and INDEXEDA to INDEXED.
*
* Returns: TRUE on success.
*
* Since: GIMP 2.4
**/
gboolean
gimp_layer_flatten (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-flatten",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_scale:
* @layer_ID: The layer.
* @new_width: New layer width.
* @new_height: New layer height.
* @local_origin: Use a local origin (as opposed to the image origin).
*
* Scale the layer using the default interpolation method.
*
* This procedure scales the layer so that its new width and height are
* equal to the supplied parameters. The 'local-origin' parameter
* specifies whether to scale from the center of the layer, or from the
* image origin. This operation only works if the layer has been added
* to an image. The interpolation method used can be set with
* gimp_context_set_interpolation().
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_scale (gint32 layer_ID,
gint new_width,
gint new_height,
gboolean local_origin)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-scale",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, new_width,
GIMP_PDB_INT32, new_height,
GIMP_PDB_INT32, local_origin,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_scale_full:
* @layer_ID: The layer.
* @new_width: New layer width.
* @new_height: New layer height.
* @local_origin: Use a local origin (as opposed to the image origin).
* @interpolation: Type of interpolation.
*
* Deprecated: Use gimp_layer_scale() instead.
*
* Returns: TRUE on success.
*
* Since: GIMP 2.6
**/
gboolean
gimp_layer_scale_full (gint32 layer_ID,
gint new_width,
gint new_height,
gboolean local_origin,
GimpInterpolationType interpolation)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-scale-full",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, new_width,
GIMP_PDB_INT32, new_height,
GIMP_PDB_INT32, local_origin,
GIMP_PDB_INT32, interpolation,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_resize:
* @layer_ID: The layer.
* @new_width: New layer width.
* @new_height: New layer height.
* @offx: x offset between upper left corner of old and new layers: (old - new).
* @offy: y offset between upper left corner of old and new layers: (old - new).
*
* Resize the layer to the specified extents.
*
* This procedure resizes the layer so that its new width and height
* are equal to the supplied parameters. Offsets are also provided
* which describe the position of the previous layer's content. This
* operation only works if the layer has been added to an image.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_resize (gint32 layer_ID,
gint new_width,
gint new_height,
gint offx,
gint offy)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-resize",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, new_width,
GIMP_PDB_INT32, new_height,
GIMP_PDB_INT32, offx,
GIMP_PDB_INT32, offy,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_resize_to_image_size:
* @layer_ID: The layer to resize.
*
* Resize a layer to the image size.
*
* This procedure resizes the layer so that it's new width and height
* are equal to the width and height of its image container.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_resize_to_image_size (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-resize-to-image-size",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_translate:
* @layer_ID: The layer.
* @offx: Offset in x direction.
* @offy: Offset in y direction.
*
* Translate the layer by the specified offsets.
*
* This procedure translates the layer by the amounts specified in the
* x and y arguments. These can be negative, and are considered offsets
* from the current position. This command only works if the layer has
* been added to an image. All additional layers contained in the image
* which have the linked flag set to TRUE w ill also be translated by
* the specified offsets.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_translate (gint32 layer_ID,
gint offx,
gint offy)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-translate",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, offx,
GIMP_PDB_INT32, offy,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_set_offsets:
* @layer_ID: The layer.
* @offx: Offset in x direction.
* @offy: Offset in y direction.
*
* Set the layer offsets.
*
* This procedure sets the offsets for the specified layer. The offsets
* are relative to the image origin and can be any values. This
* operation is valid only on layers which have been added to an image.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_set_offsets (gint32 layer_ID,
gint offx,
gint offy)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-set-offsets",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, offx,
GIMP_PDB_INT32, offy,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_create_mask:
* @layer_ID: The layer to which to add the mask.
* @mask_type: The type of mask.
*
* Create a layer mask for the specified layer.
*
* This procedure creates a layer mask for the specified layer. Layer
* masks serve as an additional alpha channel for a layer. A number of
* different types of masks are allowed for initialisation: completely
* white masks (which will leave the layer fully visible), completely
* black masks (which will give the layer complete transparency, the
* layer's already existing alpha channel (which will leave the layer
* fully visible, but which may be more useful than a white mask), the
* current selection or a grayscale copy of the layer. The layer mask
* still needs to be added to the layer. This can be done with a call
* to gimp_layer_add_mask().
*
* Returns: The newly created mask.
**/
gint32
gimp_layer_create_mask (gint32 layer_ID,
GimpAddMaskType mask_type)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 mask_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-create-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, mask_type,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
mask_ID = return_vals[1].data.d_layer_mask;
gimp_destroy_params (return_vals, nreturn_vals);
return mask_ID;
}
/**
* gimp_layer_get_mask:
* @layer_ID: The layer.
*
* Get the specified layer's mask if it exists.
*
* This procedure returns the specified layer's mask, or -1 if none
* exists.
*
* Returns: The layer mask.
**/
gint32
gimp_layer_get_mask (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 mask_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-get-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
mask_ID = return_vals[1].data.d_layer_mask;
gimp_destroy_params (return_vals, nreturn_vals);
return mask_ID;
}
/**
* gimp_layer_from_mask:
* @mask_ID: Mask for which to return the layer.
*
* Get the specified mask's layer.
*
* This procedure returns the specified mask's layer , or -1 if none
* exists.
*
* Returns: The mask's layer.
*
* Since: GIMP 2.2
**/
gint32
gimp_layer_from_mask (gint32 mask_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 layer_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-from-mask",
&nreturn_vals,
GIMP_PDB_CHANNEL, mask_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
layer_ID = return_vals[1].data.d_layer;
gimp_destroy_params (return_vals, nreturn_vals);
return layer_ID;
}
/**
* gimp_layer_add_mask:
* @layer_ID: The layer to receive the mask.
* @mask_ID: The mask to add to the layer.
*
* Add a layer mask to the specified layer.
*
* This procedure adds a layer mask to the specified layer. Layer masks
* serve as an additional alpha channel for a layer. This procedure
* will fail if a number of prerequisites aren't met. The layer cannot
* already have a layer mask. The specified mask must exist and have
* the same dimensions as the layer. The layer must have been created
* for use with the specified image and the mask must have been created
* with the procedure 'gimp-layer-create-mask'.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_add_mask (gint32 layer_ID,
gint32 mask_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-add-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_CHANNEL, mask_ID,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_remove_mask:
* @layer_ID: The layer from which to remove mask.
* @mode: Removal mode.
*
* Remove the specified layer mask from the layer.
*
* This procedure removes the specified layer mask from the layer. If
* the mask doesn't exist, an error is returned.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_remove_mask (gint32 layer_ID,
GimpMaskApplyMode mode)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-remove-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, mode,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_is_floating_sel:
* @layer_ID: The layer.
*
* Is the specified layer a floating selection?
*
* This procedure returns whether the layer is a floating selection.
* Floating selections are special cases of layers which are attached
* to a specific drawable.
*
* Returns: TRUE if the layer is a floating selection.
**/
gboolean
gimp_layer_is_floating_sel (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean is_floating_sel = FALSE;
return_vals = gimp_run_procedure ("gimp-layer-is-floating-sel",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
is_floating_sel = return_vals[1].data.d_int32;
gimp_destroy_params (return_vals, nreturn_vals);
return is_floating_sel;
}
/**
* gimp_layer_get_lock_alpha:
* @layer_ID: The layer.
*
* Get the lock alpha channel setting of the specified layer.
*
* This procedure returns the specified layer's lock alpha channel
* setting.
*
* Returns: The layer's lock alpha channel setting.
**/
gboolean
gimp_layer_get_lock_alpha (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean lock_alpha = FALSE;
return_vals = gimp_run_procedure ("gimp-layer-get-lock-alpha",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
lock_alpha = return_vals[1].data.d_int32;
gimp_destroy_params (return_vals, nreturn_vals);
return lock_alpha;
}
/**
* gimp_layer_set_lock_alpha:
* @layer_ID: The layer.
* @lock_alpha: The new layer's lock alpha channel setting.
*
* Set the lock alpha channel setting of the specified layer.
*
* This procedure sets the specified layer's lock alpha channel
* setting.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_set_lock_alpha (gint32 layer_ID,
gboolean lock_alpha)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-set-lock-alpha",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, lock_alpha,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_get_apply_mask:
* @layer_ID: The layer.
*
* Get the apply mask setting of the specified layer.
*
* This procedure returns the specified layer's apply mask setting. If
* the value is TRUE, then the layer mask for this layer is currently
* being composited with the layer's alpha channel.
*
* Returns: The layer's apply mask setting.
**/
gboolean
gimp_layer_get_apply_mask (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean apply_mask = FALSE;
return_vals = gimp_run_procedure ("gimp-layer-get-apply-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
apply_mask = return_vals[1].data.d_int32;
gimp_destroy_params (return_vals, nreturn_vals);
return apply_mask;
}
/**
* gimp_layer_set_apply_mask:
* @layer_ID: The layer.
* @apply_mask: The new layer's apply mask setting.
*
* Set the apply mask setting of the specified layer.
*
* This procedure sets the specified layer's apply mask setting. This
* controls whether the layer's mask is currently affecting the alpha
* channel. If there is no layer mask, this function will return an
* error.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_set_apply_mask (gint32 layer_ID,
gboolean apply_mask)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-set-apply-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, apply_mask,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_get_show_mask:
* @layer_ID: The layer.
*
* Get the show mask setting of the specified layer.
*
* This procedure returns the specified layer's show mask setting. This
* controls whether the layer or its mask is visible. TRUE indicates
* that the mask should be visible. If the layer has no mask, then this
* function returns an error.
*
* Returns: The layer's show mask setting.
**/
gboolean
gimp_layer_get_show_mask (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean show_mask = FALSE;
return_vals = gimp_run_procedure ("gimp-layer-get-show-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
show_mask = return_vals[1].data.d_int32;
gimp_destroy_params (return_vals, nreturn_vals);
return show_mask;
}
/**
* gimp_layer_set_show_mask:
* @layer_ID: The layer.
* @show_mask: The new layer's show mask setting.
*
* Set the show mask setting of the specified layer.
*
* This procedure sets the specified layer's show mask setting. This
* controls whether the layer or its mask is visible. TRUE indicates
* that the mask should be visible. If there is no layer mask, this
* function will return an error.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_set_show_mask (gint32 layer_ID,
gboolean show_mask)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-set-show-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, show_mask,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_get_edit_mask:
* @layer_ID: The layer.
*
* Get the edit mask setting of the specified layer.
*
* This procedure returns the specified layer's edit mask setting. If
* the value is TRUE, then the layer mask for this layer is currently
* active, and not the layer.
*
* Returns: The layer's edit mask setting.
**/
gboolean
gimp_layer_get_edit_mask (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean edit_mask = FALSE;
return_vals = gimp_run_procedure ("gimp-layer-get-edit-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
edit_mask = return_vals[1].data.d_int32;
gimp_destroy_params (return_vals, nreturn_vals);
return edit_mask;
}
/**
* gimp_layer_set_edit_mask:
* @layer_ID: The layer.
* @edit_mask: The new layer's edit mask setting.
*
* Set the edit mask setting of the specified layer.
*
* This procedure sets the specified layer's edit mask setting. This
* controls whether the layer or it's mask is currently active for
* editing. If the specified layer has no layer mask, then this
* procedure will return an error.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_set_edit_mask (gint32 layer_ID,
gboolean edit_mask)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-set-edit-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, edit_mask,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_get_opacity:
* @layer_ID: The layer.
*
* Get the opacity of the specified layer.
*
* This procedure returns the specified layer's opacity.
*
* Returns: The layer opacity.
**/
gdouble
gimp_layer_get_opacity (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gdouble opacity = 0.0;
return_vals = gimp_run_procedure ("gimp-layer-get-opacity",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
opacity = return_vals[1].data.d_float;
gimp_destroy_params (return_vals, nreturn_vals);
return opacity;
}
/**
* gimp_layer_set_opacity:
* @layer_ID: The layer.
* @opacity: The new layer opacity.
*
* Set the opacity of the specified layer.
*
* This procedure sets the specified layer's opacity.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_set_opacity (gint32 layer_ID,
gdouble opacity)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-set-opacity",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_FLOAT, opacity,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_get_mode:
* @layer_ID: The layer.
*
* Get the combination mode of the specified layer.
*
* This procedure returns the specified layer's combination mode.
*
* Returns: The layer combination mode.
**/
GimpLayerModeEffects
gimp_layer_get_mode (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
GimpLayerModeEffects mode = 0;
return_vals = gimp_run_procedure ("gimp-layer-get-mode",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
mode = return_vals[1].data.d_int32;
gimp_destroy_params (return_vals, nreturn_vals);
return mode;
}
/**
* gimp_layer_set_mode:
* @layer_ID: The layer.
* @mode: The new layer combination mode.
*
* Set the combination mode of the specified layer.
*
* This procedure sets the specified layer's combination mode.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_set_mode (gint32 layer_ID,
GimpLayerModeEffects mode)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-set-mode",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, mode,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
|
elektroll/etaimp
|
libgimp/gimplayer_pdb.c
|
C
|
gpl-3.0
| 33,949
|
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
#include "common.h"
#include "seafile-session.h"
#include "bloom-filter.h"
#include "gc-core.h"
#include "utils.h"
#define DEBUG_FLAG SEAFILE_DEBUG_OTHER
#include "log.h"
#define MAX_BF_SIZE (((size_t)1) << 29) /* 64 MB */
/* Total number of blocks to be scanned. */
static guint64 total_blocks;
static guint64 removed_blocks;
static guint64 reachable_blocks;
/*
* The number of bits in the bloom filter is 4 times the number of all blocks.
* Let m be the bits in the bf, n be the number of blocks to be added to the bf
* (the number of live blocks), and k = 3 (closed to optimal for m/n = 4),
* the probability of false-positive is
*
* p = (1 - e^(-kn/m))^k = 0.15
*
* Because m = 4 * total_blocks >= 4 * (live blocks) = 4n, we should have p <= 0.15.
* Put it another way, we'll clean up at least 85% dead blocks in each gc operation.
* See http://en.wikipedia.org/wiki/Bloom_filter.
*
* Supose we have 8TB space, and the avg block size is 1MB, we'll have 8M blocks, then
* the size of bf is (8M * 4)/8 = 4MB.
*
* If total_blocks is a small number (e.g. < 100), we should try to clean all dead blocks.
* So we set the minimal size of the bf to 1KB.
*/
static Bloom *
alloc_gc_index ()
{
size_t size;
size = (size_t) MAX(total_blocks << 2, 1 << 13);
size = MIN (size, MAX_BF_SIZE);
seaf_message ("GC index size is %u Byte.\n", (int)size >> 3);
return bloom_create (size, 3, 0);
}
typedef struct {
SeafRepo *repo;
Bloom *index;
GHashTable *visited;
/* > 0: keep a period of history;
* == 0: only keep data in head commit;
* < 0: keep all history data.
*/
gint64 truncate_time;
gboolean traversed_head;
int traversed_commits;
gint64 traversed_blocks;
gboolean ignore_errors;
} GCData;
static int
add_blocks_to_index (SeafFSManager *mgr, GCData *data, const char *file_id)
{
SeafRepo *repo = data->repo;
Bloom *index = data->index;
Seafile *seafile;
int i;
seafile = seaf_fs_manager_get_seafile (mgr, repo->store_id, repo->version, file_id);
if (!seafile) {
seaf_warning ("Failed to find file %s.\n", file_id);
return -1;
}
for (i = 0; i < seafile->n_blocks; ++i) {
bloom_add (index, seafile->blk_sha1s[i]);
++data->traversed_blocks;
}
seafile_unref (seafile);
return 0;
}
static gboolean
fs_callback (SeafFSManager *mgr,
const char *store_id,
int version,
const char *obj_id,
int type,
void *user_data,
gboolean *stop)
{
GCData *data = user_data;
if (data->visited != NULL) {
if (g_hash_table_lookup (data->visited, obj_id) != NULL) {
*stop = TRUE;
return TRUE;
}
char *key = g_strdup(obj_id);
g_hash_table_insert (data->visited, key, key);
}
if (type == SEAF_METADATA_TYPE_FILE &&
add_blocks_to_index (mgr, data, obj_id) < 0)
return FALSE;
return TRUE;
}
static gboolean
traverse_commit (SeafCommit *commit, void *vdata, gboolean *stop)
{
GCData *data = vdata;
int ret;
if (data->truncate_time == 0)
{
*stop = TRUE;
/* Stop after traversing the head commit. */
}
else if (data->truncate_time > 0 &&
(gint64)(commit->ctime) < data->truncate_time &&
data->traversed_head)
{
/* Still traverse the first commit older than truncate_time.
* If a file in the child commit of this commit is deleted,
* we need to access this commit in order to restore it
* from trash.
*/
*stop = TRUE;
}
if (!data->traversed_head)
data->traversed_head = TRUE;
seaf_debug ("Traversed commit %.8s.\n", commit->commit_id);
++data->traversed_commits;
ret = seaf_fs_manager_traverse_tree (seaf->fs_mgr,
data->repo->store_id, data->repo->version,
commit->root_id,
fs_callback,
data, data->ignore_errors);
if (ret < 0 && !data->ignore_errors)
return FALSE;
return TRUE;
}
static int
populate_gc_index_for_repo (SeafRepo *repo, Bloom *index, gboolean ignore_errors)
{
GList *branches, *ptr;
SeafBranch *branch;
GCData *data;
int ret = 0;
seaf_message ("Populating index for repo %.8s.\n", repo->id);
branches = seaf_branch_manager_get_branch_list (seaf->branch_mgr, repo->id);
if (branches == NULL) {
seaf_warning ("[GC] Failed to get branch list of repo %s.\n", repo->id);
return -1;
}
data = g_new0(GCData, 1);
data->repo = repo;
data->index = index;
data->visited = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
gint64 truncate_time = seaf_repo_manager_get_repo_truncate_time (repo->manager,
repo->id);
if (truncate_time > 0) {
seaf_repo_manager_set_repo_valid_since (repo->manager,
repo->id,
truncate_time);
} else if (truncate_time == 0) {
/* Only the head commit is valid after GC if no history is kept. */
SeafCommit *head = seaf_commit_manager_get_commit (seaf->commit_mgr,
repo->id, repo->version,
repo->head->commit_id);
if (head)
seaf_repo_manager_set_repo_valid_since (repo->manager,
repo->id,
head->ctime);
seaf_commit_unref (head);
}
data->truncate_time = truncate_time;
data->ignore_errors = ignore_errors;
for (ptr = branches; ptr != NULL; ptr = ptr->next) {
branch = ptr->data;
gboolean res = seaf_commit_manager_traverse_commit_tree (seaf->commit_mgr,
repo->id,
repo->version,
branch->commit_id,
traverse_commit,
data,
ignore_errors);
seaf_branch_unref (branch);
if (!res && !ignore_errors) {
ret = -1;
break;
}
}
seaf_message ("Traversed %d commits, %"G_GINT64_FORMAT" blocks.\n",
data->traversed_commits, data->traversed_blocks);
reachable_blocks += data->traversed_blocks;
g_list_free (branches);
g_hash_table_destroy (data->visited);
g_free (data);
return ret;
}
typedef struct {
Bloom *index;
int dry_run;
} CheckBlocksData;
static gboolean
check_block_liveness (const char *store_id, int version,
const char *block_id, void *vdata)
{
CheckBlocksData *data = vdata;
Bloom *index = data->index;
if (!bloom_test (index, block_id)) {
++removed_blocks;
if (!data->dry_run)
seaf_block_manager_remove_block (seaf->block_mgr,
store_id, version,
block_id);
}
return TRUE;
}
static int
populate_gc_index_for_virtual_repos (SeafRepo *repo, Bloom *index, int ignore_errors)
{
GList *vrepo_ids = NULL, *ptr;
char *repo_id;
SeafRepo *vrepo;
int ret = 0;
vrepo_ids = seaf_repo_manager_get_virtual_repo_ids_by_origin (seaf->repo_mgr,
repo->id);
for (ptr = vrepo_ids; ptr; ptr = ptr->next) {
repo_id = ptr->data;
vrepo = seaf_repo_manager_get_repo (seaf->repo_mgr, repo_id);
if (!vrepo) {
seaf_warning ("Failed to get repo %s.\n", repo_id);
if (!ignore_errors) {
ret = -1;
goto out;
} else
continue;
}
ret = populate_gc_index_for_repo (vrepo, index, ignore_errors);
seaf_repo_unref (vrepo);
if (ret < 0 && !ignore_errors)
goto out;
}
out:
string_list_free (vrepo_ids);
return ret;
}
int
gc_v1_repo (SeafRepo *repo, int dry_run, int ignore_errors)
{
Bloom *index;
int ret;
total_blocks = seaf_block_manager_get_block_number (seaf->block_mgr,
repo->store_id, repo->version);
removed_blocks = 0;
reachable_blocks = 0;
if (total_blocks == 0) {
seaf_message ("No blocks. Skip GC.\n");
return 0;
}
seaf_message ("GC started. Total block number is %"G_GUINT64_FORMAT".\n", total_blocks);
/*
* Store the index of live blocks in bloom filter to save memory.
* Since bloom filters only have false-positive, we
* may skip some garbage blocks, but we won't delete
* blocks that are still alive.
*/
index = alloc_gc_index ();
if (!index) {
seaf_warning ("GC: Failed to allocate index.\n");
return -1;
}
seaf_message ("Populating index.\n");
ret = populate_gc_index_for_repo (repo, index, ignore_errors);
if (ret < 0 && !ignore_errors)
goto out;
/* Since virtual repos share fs and block store with the origin repo,
* it's necessary to do GC for them together.
*/
ret = populate_gc_index_for_virtual_repos (repo, index, ignore_errors);
if (ret < 0 && !ignore_errors)
goto out;
if (!dry_run)
seaf_message ("Scanning and deleting unused blocks.\n");
else
seaf_message ("Scanning unused blocks.\n");
CheckBlocksData data;
data.index = index;
data.dry_run = dry_run;
ret = seaf_block_manager_foreach_block (seaf->block_mgr,
repo->store_id, repo->version,
check_block_liveness,
&data);
if (ret < 0) {
seaf_warning ("GC: Failed to clean dead blocks.\n");
goto out;
}
if (!dry_run)
seaf_message ("GC finished. %"G_GUINT64_FORMAT" blocks total, "
"about %"G_GUINT64_FORMAT" reachable blocks, "
"%"G_GUINT64_FORMAT" blocks are removed.\n",
total_blocks, reachable_blocks, removed_blocks);
else
seaf_message ("GC finished. %"G_GUINT64_FORMAT" blocks total, "
"about %"G_GUINT64_FORMAT" reachable blocks, "
"%"G_GUINT64_FORMAT" blocks can be removed.\n",
total_blocks, reachable_blocks, removed_blocks);
out:
bloom_destroy (index);
return ret;
}
int
gc_core_run (int dry_run)
{
GList *repos = NULL, *del_repos = NULL, *ptr;
SeafRepo *repo;
GList *corrupt_repos = NULL;
gboolean error = FALSE;
repos = seaf_repo_manager_get_repo_list (seaf->repo_mgr, -1, -1, &error);
if (error) {
seaf_warning ("Failed to load repo list.\n");
return -1;
}
for (ptr = repos; ptr; ptr = ptr->next) {
repo = ptr->data;
if (repo->is_corrupted) {
corrupt_repos = g_list_prepend (corrupt_repos, g_strdup(repo->id));
continue;
}
if (!repo->is_virtual) {
seaf_message ("GC version %d repo %s(%.8s)\n",
repo->version, repo->name, repo->id);
if (gc_v1_repo (repo, dry_run, FALSE) < 0)
corrupt_repos = g_list_prepend (corrupt_repos, g_strdup(repo->id));
}
seaf_repo_unref (repo);
}
g_list_free (repos);
seaf_message ("=== GC deleted repos ===\n");
del_repos = seaf_repo_manager_list_garbage_repos (seaf->repo_mgr);
for (ptr = del_repos; ptr; ptr = ptr->next) {
char *repo_id = ptr->data;
/* Confirm repo doesn't exist before removing blocks. */
if (!seaf_repo_manager_repo_exists (seaf->repo_mgr, repo_id)) {
if (!dry_run) {
seaf_message ("GC deleted repo %.8s.\n", repo_id);
seaf_block_manager_remove_store (seaf->block_mgr, repo_id);
} else {
seaf_message ("Repo %.8s can be GC'ed.\n", repo_id);
}
}
if (!dry_run)
seaf_repo_manager_remove_garbage_repo (seaf->repo_mgr, repo_id);
g_free (repo_id);
}
g_list_free (del_repos);
seaf_message ("=== GC is finished ===\n");
if (corrupt_repos) {
seaf_message ("The following repos are corrupted. "
"You can run seaf-fsck to fix them.\n");
for (ptr = corrupt_repos; ptr; ptr = ptr->next) {
char *repo_id = ptr->data;
seaf_message ("%s\n", repo_id);
g_free (repo_id);
}
g_list_free (corrupt_repos);
}
return 0;
}
|
skmezanul/disk42
|
server/gc/gc-core.c
|
C
|
gpl-3.0
| 13,299
|
/* radare - LGPL - Copyright 2008-2014 - pancake */
// TODO: implement a more inteligent way to store cached memory
// TODO: define limit of max mem to cache
#include "r_io.h"
static void cache_item_free(RIOCache *cache) {
if (!cache)
return;
if (cache->data)
free (cache->data);
free (cache);
}
R_API void r_io_cache_init(RIO *io) {
io->cache = r_list_new ();
io->cache->free = (RListFree)cache_item_free;
io->cached = R_FALSE; // cache write ops
io->cached_read = R_FALSE; // cached read ops
}
R_API void r_io_cache_enable(RIO *io, int read, int write) {
io->cached = read | write;
io->cached_read = read;
}
R_API void r_io_cache_commit(RIO *io) {
RListIter *iter;
RIOCache *c;
if (io->cached) {
io->cached = R_FALSE;
r_list_foreach (io->cache, iter, c) {
if (!r_io_write_at (io, c->from, c->data, c->size))
eprintf ("Error writing change at 0x%08"PFMT64x"\n", c->from);
}
io->cached = R_TRUE;
r_io_cache_reset (io, io->cached);
}
}
R_API void r_io_cache_reset(RIO *io, int set) {
io->cached = set;
r_list_purge (io->cache);
}
R_API int r_io_cache_invalidate(RIO *io, ut64 from, ut64 to) {
RListIter *iter, *iter_tmp;
RIOCache *c;
if (from>=to) return R_FALSE;
r_list_foreach_safe (io->cache, iter, iter_tmp, c) {
if (c->from >= from && c->to <= to) {
r_list_delete (io->cache, iter);
}
}
return R_FALSE;
}
R_API int r_io_cache_list(RIO *io, int rad) {
int i, j = 0;
RListIter *iter;
RIOCache *c;
r_list_foreach (io->cache, iter, c) {
if (rad) {
io->printf ("wx ");
for (i=0; i<c->size; i++)
io->printf ("%02x", c->data[i]);
io->printf (" @ 0x%08"PFMT64x"\n", c->from);
} else {
io->printf ("idx=%d addr=0x%08"PFMT64x" size=%d ",
j, c->from, c->size);
for (i=0; i<c->size; i++)
io->printf ("%02x", c->data[i]);
io->printf ("\n");
}
j++;
}
return R_FALSE;
}
R_API int r_io_cache_write(RIO *io, ut64 addr, const ut8 *buf, int len) {
RIOCache *ch = R_NEW (RIOCache);
ch->from = addr;
ch->to = addr + len;
ch->size = len;
ch->data = (ut8*)malloc (len);
memcpy (ch->data, buf, len);
r_list_append (io->cache, ch);
return len;
}
R_API int r_io_cache_read(RIO *io, ut64 addr, ut8 *buf, int len) {
int l, ret, da, db;
RListIter *iter;
RIOCache *c;
r_list_foreach (io->cache, iter, c) {
if (r_range_overlap (addr, addr+len-1, c->from, c->to, &ret)) {
if (ret>0) {
da = ret;
db = 0;
l = c->size-da;
} else if (ret<0) {
da = 0;
db = -ret;
l = c->size-db;
} else {
da = 0;
db = 0;
l = c->size;
}
if (l>len) l = len;
if (l<1) l = 1; // XXX: fail
else memcpy (buf+da, c->data+db, l);
}
}
return len;
}
|
jpenalbae/radare2
|
libr/io/cache.c
|
C
|
gpl-3.0
| 2,674
|
/*
* Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
* Copyright (C) 1999-2014 Hiroyuki Yamamoto and the Claws Mail team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#include "claws-features.h"
#endif
#include <glib.h>
#include <glib/gi18n.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>
#ifdef G_OS_WIN32
# include <w32lib.h>
#endif
#include "procheader.h"
#include "procmsg.h"
#include "codeconv.h"
#include "prefs_common.h"
#include "hooks.h"
#include "utils.h"
#include "defs.h"
#define BUFFSIZE 8192
static gchar monthstr[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
typedef char *(*getlinefunc) (char *, size_t, void *);
typedef int (*peekcharfunc) (void *);
typedef int (*getcharfunc) (void *);
typedef gint (*get_one_field_func) (gchar *, size_t, void *, HeaderEntry[]);
static gint string_get_one_field(gchar *buf, size_t len, char **str,
HeaderEntry hentry[]);
static char *string_getline(char *buf, size_t len, char **str);
static int string_peekchar(char **str);
static int file_peekchar(FILE *fp);
static gint generic_get_one_field(gchar *buf, size_t len, void *data,
HeaderEntry hentry[],
getlinefunc getline,
peekcharfunc peekchar,
gboolean unfold);
static MsgInfo *parse_stream(void *data, gboolean isstring, MsgFlags flags,
gboolean full, gboolean decrypted);
gint procheader_get_one_field(gchar *buf, size_t len, FILE *fp,
HeaderEntry hentry[])
{
return generic_get_one_field(buf, len, fp, hentry,
(getlinefunc)fgets_crlf, (peekcharfunc)file_peekchar,
TRUE);
}
static gint string_get_one_field(gchar *buf, size_t len, char **str,
HeaderEntry hentry[])
{
return generic_get_one_field(buf, len, str, hentry,
(getlinefunc)string_getline,
(peekcharfunc)string_peekchar,
TRUE);
}
static char *string_getline(char *buf, size_t len, char **str)
{
gboolean is_cr = FALSE;
gboolean last_was_cr = FALSE;
if (!*str || !**str)
return NULL;
for (; **str && len > 1; --len) {
is_cr = (**str == '\r');
if ((*buf++ = *(*str)++) == '\n') {
break;
}
if (last_was_cr) {
*(--buf) = '\n';
buf++;
break;
}
last_was_cr = is_cr;
}
*buf = '\0';
return buf;
}
static int string_peekchar(char **str)
{
return **str;
}
static int file_peekchar(FILE *fp)
{
return ungetc(getc(fp), fp);
}
static gint generic_get_one_field(gchar *buf, size_t len, void *data,
HeaderEntry *hentry,
getlinefunc getline, peekcharfunc peekchar,
gboolean unfold)
{
gint nexthead;
gint hnum = 0;
HeaderEntry *hp = NULL;
if (hentry != NULL) {
/* skip non-required headers */
do {
do {
if (getline(buf, len, data) == NULL)
return -1;
if (buf[0] == '\r' || buf[0] == '\n')
return -1;
} while (buf[0] == ' ' || buf[0] == '\t');
for (hp = hentry, hnum = 0; hp->name != NULL;
hp++, hnum++) {
if (!g_ascii_strncasecmp(hp->name, buf,
strlen(hp->name)))
break;
}
} while (hp->name == NULL);
} else {
if (getline(buf, len, data) == NULL) return -1;
if (buf[0] == '\r' || buf[0] == '\n') return -1;
}
/* unfold line */
while (1) {
nexthead = peekchar(data);
/* ([*WSP CRLF] 1*WSP) */
if (nexthead == ' ' || nexthead == '\t') {
size_t buflen;
gboolean skiptab = (nexthead == '\t');
/* trim previous trailing \n if requesting one header or
* unfolding was requested */
if ((!hentry && unfold) || (hp && hp->unfold))
strretchomp(buf);
buflen = strlen(buf);
/* concatenate next line */
if ((len - buflen) > 2) {
if (getline(buf + buflen, len - buflen, data) == NULL)
break;
if (skiptab) { /* replace tab with space */
*(buf + buflen) = ' ';
}
} else
break;
} else {
/* remove trailing new line */
strretchomp(buf);
break;
}
}
return hnum;
}
gint procheader_get_one_field_asis(gchar *buf, size_t len, FILE *fp)
{
return generic_get_one_field(buf, len, fp, NULL,
(getlinefunc)fgets_crlf,
(peekcharfunc)file_peekchar,
FALSE);
}
GPtrArray *procheader_get_header_array_asis(FILE *fp)
{
gchar buf[BUFFSIZE];
GPtrArray *headers;
Header *header;
cm_return_val_if_fail(fp != NULL, NULL);
headers = g_ptr_array_new();
while (procheader_get_one_field_asis(buf, sizeof(buf), fp) != -1) {
if ((header = procheader_parse_header(buf)) != NULL)
g_ptr_array_add(headers, header);
}
return headers;
}
void procheader_header_array_destroy(GPtrArray *harray)
{
gint i;
Header *header;
for (i = 0; i < harray->len; i++) {
header = g_ptr_array_index(harray, i);
procheader_header_free(header);
}
g_ptr_array_free(harray, TRUE);
}
void procheader_header_free(Header *header)
{
if (!header) return;
g_free(header->name);
g_free(header->body);
g_free(header);
}
/*
tests whether two headers' names are equal
remove the trailing ':' or ' ' before comparing
*/
gboolean procheader_headername_equal(char * hdr1, char * hdr2)
{
int len1;
int len2;
len1 = strlen(hdr1);
len2 = strlen(hdr2);
if (hdr1[len1 - 1] == ':')
len1--;
if (hdr2[len2 - 1] == ':')
len2--;
if (len1 != len2)
return 0;
return (g_ascii_strncasecmp(hdr1, hdr2, len1) == 0);
}
/*
parse headers, for example :
From: dinh@enseirb.fr becomes :
header->name = "From:"
header->body = "dinh@enseirb.fr"
*/
static gboolean header_is_addr_field(const gchar *hdr)
{
static char *addr_headers[] = {
"To:",
"Cc:",
"Bcc:",
"From:",
"Reply-To:",
"Followup-To:",
"Followup-and-Reply-To:",
"Disposition-Notification-To:",
"Return-Receipt-To:",
NULL};
int i;
if (!hdr)
return FALSE;
for (i = 0; addr_headers[i] != NULL; i++)
if (!strcasecmp(hdr, addr_headers[i]))
return FALSE;
return FALSE;
}
Header * procheader_parse_header(gchar * buf)
{
gchar *p;
Header * header;
gboolean addr_field = FALSE;
if ((*buf == ':') || (*buf == ' '))
return NULL;
for (p = buf; *p ; p++) {
if ((*p == ':') || (*p == ' ')) {
header = g_new(Header, 1);
header->name = g_strndup(buf, p - buf + 1);
addr_field = header_is_addr_field(header->name);
p++;
while (*p == ' ' || *p == '\t') p++;
header->body = conv_unmime_header(p, NULL, addr_field);
return header;
}
}
return NULL;
}
void procheader_get_header_fields(FILE *fp, HeaderEntry hentry[])
{
gchar buf[BUFFSIZE];
HeaderEntry *hp;
gint hnum;
gchar *p;
if (hentry == NULL) return;
while ((hnum = procheader_get_one_field(buf, sizeof(buf), fp, hentry))
!= -1) {
hp = hentry + hnum;
p = buf + strlen(hp->name);
while (*p == ' ' || *p == '\t') p++;
if (hp->body == NULL)
hp->body = g_strdup(p);
else if (procheader_headername_equal(hp->name, "To") ||
procheader_headername_equal(hp->name, "Cc")) {
gchar *tp = hp->body;
hp->body = g_strconcat(tp, ", ", p, NULL);
g_free(tp);
}
}
}
MsgInfo *procheader_parse_file(const gchar *file, MsgFlags flags,
gboolean full, gboolean decrypted)
{
GStatBuf s;
FILE *fp;
MsgInfo *msginfo;
if (g_stat(file, &s) < 0) {
FILE_OP_ERROR(file, "stat");
return NULL;
}
if (!S_ISREG(s.st_mode))
return NULL;
if ((fp = g_fopen(file, "rb")) == NULL) {
FILE_OP_ERROR(file, "fopen");
return NULL;
}
msginfo = procheader_parse_stream(fp, flags, full, decrypted);
fclose(fp);
if (msginfo) {
msginfo->size = s.st_size;
msginfo->mtime = s.st_mtime;
}
return msginfo;
}
MsgInfo *procheader_parse_str(const gchar *str, MsgFlags flags, gboolean full,
gboolean decrypted)
{
return parse_stream(&str, TRUE, flags, full, decrypted);
}
enum
{
H_DATE = 0,
H_FROM,
H_TO,
H_CC,
H_NEWSGROUPS,
H_SUBJECT,
H_MSG_ID,
H_REFERENCES,
H_IN_REPLY_TO,
H_CONTENT_TYPE,
H_SEEN,
H_STATUS,
H_FROM_SPACE,
H_SC_PLANNED_DOWNLOAD,
H_SC_MESSAGE_SIZE,
H_FACE,
H_X_FACE,
H_DISPOSITION_NOTIFICATION_TO,
H_RETURN_RECEIPT_TO,
H_SC_PARTIALLY_RETRIEVED,
H_SC_ACCOUNT_SERVER,
H_SC_ACCOUNT_LOGIN,
H_LIST_POST,
H_LIST_SUBSCRIBE,
H_LIST_UNSUBSCRIBE,
H_LIST_HELP,
H_LIST_ARCHIVE,
H_LIST_OWNER,
H_RESENT_FROM,
};
static HeaderEntry hentry_full[] = {
{"Date:", NULL, FALSE},
{"From:", NULL, TRUE},
{"To:", NULL, TRUE},
{"Cc:", NULL, TRUE},
{"Newsgroups:", NULL, TRUE},
{"Subject:", NULL, TRUE},
{"Message-ID:", NULL, FALSE},
{"References:", NULL, FALSE},
{"In-Reply-To:", NULL, FALSE},
{"Content-Type:", NULL, FALSE},
{"Seen:", NULL, FALSE},
{"Status:", NULL, FALSE},
{"From ", NULL, FALSE},
{"SC-Marked-For-Download:", NULL, FALSE},
{"SC-Message-Size:", NULL, FALSE},
{"Face:", NULL, FALSE},
{"X-Face:", NULL, FALSE},
{"Disposition-Notification-To:", NULL, FALSE},
{"Return-Receipt-To:", NULL, FALSE},
{"SC-Partially-Retrieved:", NULL, FALSE},
{"SC-Account-Server:", NULL, FALSE},
{"SC-Account-Login:",NULL, FALSE},
{"List-Post:", NULL, TRUE},
{"List-Subscribe:", NULL, TRUE},
{"List-Unsubscribe:",NULL, TRUE},
{"List-Help:", NULL, TRUE},
{"List-Archive:", NULL, TRUE},
{"List-Owner:", NULL, TRUE},
{"Resent-From:", NULL, TRUE},
{NULL, NULL, FALSE}};
static HeaderEntry hentry_short[] = {
{"Date:", NULL, FALSE},
{"From:", NULL, TRUE},
{"To:", NULL, TRUE},
{"Cc:", NULL, TRUE},
{"Newsgroups:", NULL, TRUE},
{"Subject:", NULL, TRUE},
{"Message-ID:", NULL, FALSE},
{"References:", NULL, FALSE},
{"In-Reply-To:", NULL, FALSE},
{"Content-Type:", NULL, FALSE},
{"Seen:", NULL, FALSE},
{"Status:", NULL, FALSE},
{"From ", NULL, FALSE},
{"SC-Marked-For-Download:", NULL, FALSE},
{"SC-Message-Size:",NULL, FALSE},
{NULL, NULL, FALSE}};
static HeaderEntry* procheader_get_headernames(gboolean full)
{
return full ? hentry_full : hentry_short;
}
MsgInfo *procheader_parse_stream(FILE *fp, MsgFlags flags, gboolean full,
gboolean decrypted)
{
return parse_stream(fp, FALSE, flags, full, decrypted);
}
static gboolean avatar_from_some_face(gpointer source, gpointer userdata)
{
AvatarCaptureData *acd = (AvatarCaptureData *)source;
if (*(acd->content) == '\0') /* won't be null, but may be empty */
return FALSE;
if (!strcmp(acd->header, hentry_full[H_FACE].name)) {
debug_print("avatar_from_some_face: found 'Face' header\n");
procmsg_msginfo_add_avatar(acd->msginfo, AVATAR_FACE, acd->content);
}
#if HAVE_LIBCOMPFACE
else if (!strcmp(acd->header, hentry_full[H_X_FACE].name)) {
debug_print("avatar_from_some_face: found 'X-Face' header\n");
procmsg_msginfo_add_avatar(acd->msginfo, AVATAR_XFACE, acd->content);
}
#endif
return FALSE;
}
static guint avatar_hook_id = 0;
static MsgInfo *parse_stream(void *data, gboolean isstring, MsgFlags flags,
gboolean full, gboolean decrypted)
{
MsgInfo *msginfo;
gchar buf[BUFFSIZE];
gchar *p, *tmp;
gchar *hp;
HeaderEntry *hentry;
gint hnum;
void *orig_data = data;
get_one_field_func get_one_field =
isstring ? (get_one_field_func)string_get_one_field
: (get_one_field_func)procheader_get_one_field;
hentry = procheader_get_headernames(full);
if (MSG_IS_QUEUED(flags) || MSG_IS_DRAFT(flags)) {
while (get_one_field(buf, sizeof(buf), data, NULL) != -1) {
if ((!strncmp(buf, "X-Claws-End-Special-Headers: 1",
strlen("X-Claws-End-Special-Headers:"))) ||
(!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
strlen("X-Sylpheed-End-Special-Headers:"))))
break;
/* from other mailers */
if (!strncmp(buf, "Date: ", 6)
|| !strncmp(buf, "To: ", 4)
|| !strncmp(buf, "From: ", 6)
|| !strncmp(buf, "Subject: ", 9)) {
if (isstring)
data = orig_data;
else
rewind((FILE *)data);
break;
}
}
}
msginfo = procmsg_msginfo_new();
if (flags.tmp_flags || flags.perm_flags)
msginfo->flags = flags;
else
MSG_SET_PERM_FLAGS(msginfo->flags, MSG_NEW | MSG_UNREAD);
msginfo->inreplyto = NULL;
if (avatar_hook_id == 0 && (prefs_common.enable_avatars & AVATARS_ENABLE_CAPTURE)) {
avatar_hook_id = hooks_register_hook(AVATAR_HEADER_UPDATE_HOOKLIST, avatar_from_some_face, NULL);
} else if (avatar_hook_id != 0 && !(prefs_common.enable_avatars & AVATARS_ENABLE_CAPTURE)) {
hooks_unregister_hook(AVATAR_HEADER_UPDATE_HOOKLIST, avatar_hook_id);
avatar_hook_id = 0;
}
while ((hnum = get_one_field(buf, sizeof(buf), data, hentry))
!= -1) {
hp = buf + strlen(hentry[hnum].name);
while (*hp == ' ' || *hp == '\t') hp++;
switch (hnum) {
case H_DATE:
if (msginfo->date) break;
msginfo->date_t =
procheader_date_parse(NULL, hp, 0);
if (g_utf8_validate(hp, -1, NULL)) {
msginfo->date = g_strdup(hp);
} else {
gchar *utf = conv_codeset_strdup(
hp,
conv_get_locale_charset_str_no_utf8(),
CS_INTERNAL);
if (utf == NULL ||
!g_utf8_validate(utf, -1, NULL)) {
g_free(utf);
utf = g_malloc(strlen(buf)*2+1);
conv_localetodisp(utf,
strlen(hp)*2+1, hp);
}
msginfo->date = utf;
}
break;
case H_FROM:
if (msginfo->from) break;
msginfo->from = conv_unmime_header(hp, NULL, TRUE);
msginfo->fromname = procheader_get_fromname(msginfo->from);
remove_return(msginfo->from);
remove_return(msginfo->fromname);
break;
case H_TO:
tmp = conv_unmime_header(hp, NULL, TRUE);
remove_return(tmp);
if (msginfo->to) {
p = msginfo->to;
msginfo->to =
g_strconcat(p, ", ", tmp, NULL);
g_free(p);
} else
msginfo->to = g_strdup(tmp);
g_free(tmp);
break;
case H_CC:
tmp = conv_unmime_header(hp, NULL, TRUE);
remove_return(tmp);
if (msginfo->cc) {
p = msginfo->cc;
msginfo->cc =
g_strconcat(p, ", ", tmp, NULL);
g_free(p);
} else
msginfo->cc = g_strdup(tmp);
g_free(tmp);
break;
case H_NEWSGROUPS:
if (msginfo->newsgroups) {
p = msginfo->newsgroups;
msginfo->newsgroups =
g_strconcat(p, ",", hp, NULL);
g_free(p);
} else
msginfo->newsgroups = g_strdup(hp);
break;
case H_SUBJECT:
if (msginfo->subject) break;
msginfo->subject = conv_unmime_header(hp, NULL, FALSE);
unfold_line(msginfo->subject);
break;
case H_MSG_ID:
if (msginfo->msgid) break;
extract_parenthesis(hp, '<', '>');
remove_space(hp);
msginfo->msgid = g_strdup(hp);
break;
case H_REFERENCES:
msginfo->references =
references_list_prepend(msginfo->references,
hp);
break;
case H_IN_REPLY_TO:
if (msginfo->inreplyto) break;
eliminate_parenthesis(hp, '(', ')');
if ((p = strrchr(hp, '<')) != NULL &&
strchr(p + 1, '>') != NULL) {
extract_parenthesis(p, '<', '>');
remove_space(p);
if (*p != '\0')
msginfo->inreplyto = g_strdup(p);
}
break;
case H_CONTENT_TYPE:
if (!g_ascii_strncasecmp(hp, "multipart/", 10))
MSG_SET_TMP_FLAGS(msginfo->flags, MSG_MULTIPART);
break;
case H_DISPOSITION_NOTIFICATION_TO:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->dispositionnotificationto) break;
msginfo->extradata->dispositionnotificationto = g_strdup(hp);
break;
case H_RETURN_RECEIPT_TO:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->returnreceiptto) break;
msginfo->extradata->returnreceiptto = g_strdup(hp);
break;
/* partial download infos */
case H_SC_PARTIALLY_RETRIEVED:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->partial_recv) break;
msginfo->extradata->partial_recv = g_strdup(hp);
break;
case H_SC_ACCOUNT_SERVER:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->account_server) break;
msginfo->extradata->account_server = g_strdup(hp);
break;
case H_SC_ACCOUNT_LOGIN:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->account_login) break;
msginfo->extradata->account_login = g_strdup(hp);
break;
case H_SC_MESSAGE_SIZE:
if (msginfo->total_size) break;
msginfo->total_size = atoi(hp);
break;
case H_SC_PLANNED_DOWNLOAD:
msginfo->planned_download = atoi(hp);
break;
/* end partial download infos */
case H_FROM_SPACE:
if (msginfo->fromspace) break;
msginfo->fromspace = g_strdup(hp);
remove_return(msginfo->fromspace);
break;
/* list infos */
case H_LIST_POST:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->list_post) break;
msginfo->extradata->list_post = g_strdup(hp);
break;
case H_LIST_SUBSCRIBE:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->list_subscribe) break;
msginfo->extradata->list_subscribe = g_strdup(hp);
break;
case H_LIST_UNSUBSCRIBE:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->list_unsubscribe) break;
msginfo->extradata->list_unsubscribe = g_strdup(hp);
break;
case H_LIST_HELP:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->list_help) break;
msginfo->extradata->list_help = g_strdup(hp);
break;
case H_LIST_ARCHIVE:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->list_archive) break;
msginfo->extradata->list_archive = g_strdup(hp);
break;
case H_LIST_OWNER:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->list_owner) break;
msginfo->extradata->list_owner = g_strdup(hp);
break;
case H_RESENT_FROM:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->resent_from) break;
msginfo->extradata->resent_from = g_strdup(hp);
break;
/* end list infos */
default:
break;
}
/* to avoid performance penalty hooklist is invoked only for
headers known to be able to generate avatars */
if (hnum == H_FROM || hnum == H_X_FACE || hnum == H_FACE) {
AvatarCaptureData *acd = g_new0(AvatarCaptureData, 1);
/* no extra memory is wasted, hooks are expected to
take care of copying members when needed */
acd->msginfo = msginfo;
acd->header = hentry_full[hnum].name;
acd->content = hp;
hooks_invoke(AVATAR_HEADER_UPDATE_HOOKLIST, (gpointer)acd);
g_free(acd);
}
}
if (!msginfo->inreplyto && msginfo->references)
msginfo->inreplyto =
g_strdup((gchar *)msginfo->references->data);
return msginfo;
}
gchar *procheader_get_fromname(const gchar *str)
{
gchar *tmp, *name;
Xstrdup_a(tmp, str, return NULL);
if (*tmp == '\"') {
extract_quote(tmp, '\"');
g_strstrip(tmp);
} else if (strchr(tmp, '<')) {
eliminate_parenthesis(tmp, '<', '>');
g_strstrip(tmp);
if (*tmp == '\0') {
strcpy(tmp, str);
extract_parenthesis(tmp, '<', '>');
g_strstrip(tmp);
}
} else if (strchr(tmp, '(')) {
extract_parenthesis(tmp, '(', ')');
g_strstrip(tmp);
}
if (*tmp == '\0')
name = g_strdup(str);
else
name = g_strdup(tmp);
return name;
}
static gint procheader_scan_date_string(const gchar *str,
gchar *weekday, gint *day,
gchar *month, gint *year,
gint *hh, gint *mm, gint *ss,
gchar *zone)
{
gint result;
gint month_n;
gint secfract;
gint zone1 = 0, zone2 = 0;
gchar offset_sign, zonestr[7];
gchar sep1;
if (str == NULL)
return -1;
result = sscanf(str, "%10s %d %9s %d %2d:%2d:%2d %6s",
weekday, day, month, year, hh, mm, ss, zone);
if (result == 8) return 0;
/* RFC2822 */
result = sscanf(str, "%3s,%d %9s %d %2d:%2d:%2d %6s",
weekday, day, month, year, hh, mm, ss, zone);
if (result == 8) return 0;
result = sscanf(str, "%d %9s %d %2d:%2d:%2d %6s",
day, month, year, hh, mm, ss, zone);
if (result == 7) return 0;
*zone = '\0';
result = sscanf(str, "%10s %d %9s %d %2d:%2d:%2d",
weekday, day, month, year, hh, mm, ss);
if (result == 7) return 0;
result = sscanf(str, "%d %9s %d %2d:%2d:%2d",
day, month, year, hh, mm, ss);
if (result == 6) return 0;
*ss = 0;
result = sscanf(str, "%10s %d %9s %d %2d:%2d %6s",
weekday, day, month, year, hh, mm, zone);
if (result == 7) return 0;
result = sscanf(str, "%d %9s %d %2d:%2d %5s",
day, month, year, hh, mm, zone);
if (result == 6) return 0;
*zone = '\0';
result = sscanf(str, "%10s %d %9s %d %2d:%2d",
weekday, day, month, year, hh, mm);
if (result == 6) return 0;
result = sscanf(str, "%d %9s %d %2d:%2d",
day, month, year, hh, mm);
if (result == 5) return 0;
*weekday = '\0';
/* RFC3339 subset, with fraction of second */
result = sscanf(str, "%4d-%2d-%2d%c%2d:%2d:%2d.%d%6s",
year, &month_n, day, &sep1, hh, mm, ss, &secfract, zonestr);
if (result == 9
&& (sep1 == 'T' || sep1 == 't' || sep1 == ' ')) {
if (month_n >= 1 && month_n <= 12) {
strncpy2(month, monthstr+((month_n-1)*3), 4);
if (zonestr[0] == 'z' || zonestr[0] == 'Z') {
strcat(zone, "+00:00");
} else if (sscanf(zonestr, "%c%2d:%2d",
&offset_sign, &zone1, &zone2) == 3) {
strcat(zone, zonestr);
}
return 0;
}
}
/* RFC3339 subset, no fraction of second */
result = sscanf(str, "%4d-%2d-%2d%c%2d:%2d:%2d%6s",
year, &month_n, day, &sep1, hh, mm, ss, zonestr);
if (result == 8
&& (sep1 == 'T' || sep1 == 't' || sep1 == ' ')) {
if (month_n >= 1 && month_n <= 12) {
strncpy2(month, monthstr+((month_n-1)*3), 4);
if (zonestr[0] == 'z' || zonestr[0] == 'Z') {
strcat(zone, "+00:00");
} else if (sscanf(zonestr, "%c%2d:%2d",
&offset_sign, &zone1, &zone2) == 3) {
strcat(zone, zonestr);
}
return 0;
}
}
*zone = '\0';
/* RFC3339 subset */
/* This particular "subset" is invalid, RFC requires the time offset */
result = sscanf(str, "%4d-%2d-%2d %2d:%2d:%2d",
year, &month_n, day, hh, mm, ss);
if (result == 6) {
if (1 <= month_n && month_n <= 12) {
strncpy2(month, monthstr+((month_n-1)*3), 4);
return 0;
}
}
return -1;
}
/*
* Hiro, most UNIXen support this function:
* http://www.mcsr.olemiss.edu/cgi-bin/man-cgi?getdate
*/
gboolean procheader_date_parse_to_tm(const gchar *src, struct tm *t, char *zone)
{
gchar weekday[11];
gint day;
gchar month[10];
gint year;
gint hh, mm, ss;
GDateMonth dmonth;
gchar *p;
if (!t)
return FALSE;
memset(t, 0, sizeof *t);
if (procheader_scan_date_string(src, weekday, &day, month, &year,
&hh, &mm, &ss, zone) < 0) {
g_warning("Invalid date: %s", src);
return FALSE;
}
/* Y2K compliant :) */
if (year < 100) {
if (year < 70)
year += 2000;
else
year += 1900;
}
month[3] = '\0';
if ((p = strstr(monthstr, month)) != NULL)
dmonth = (gint)(p - monthstr) / 3 + 1;
else {
g_warning("Invalid month: %s", month);
dmonth = G_DATE_BAD_MONTH;
}
t->tm_sec = ss;
t->tm_min = mm;
t->tm_hour = hh;
t->tm_mday = day;
t->tm_mon = dmonth - 1;
t->tm_year = year - 1900;
t->tm_wday = 0;
t->tm_yday = 0;
t->tm_isdst = -1;
mktime(t);
return TRUE;
}
time_t procheader_date_parse(gchar *dest, const gchar *src, gint len)
{
gchar weekday[11];
gint day;
gchar month[10];
gint year;
gint hh, mm, ss;
gchar zone[7];
GDateMonth dmonth = G_DATE_BAD_MONTH;
struct tm t;
gchar *p;
time_t timer;
time_t tz_offset;
if (procheader_scan_date_string(src, weekday, &day, month, &year,
&hh, &mm, &ss, zone) < 0) {
if (dest && len > 0)
strncpy2(dest, src, len);
return 0;
}
/* Y2K compliant :) */
if (year < 1000) {
if (year < 50)
year += 2000;
else
year += 1900;
}
month[3] = '\0';
for (p = monthstr; *p != '\0'; p += 3) {
if (!g_ascii_strncasecmp(p, month, 3)) {
dmonth = (gint)(p - monthstr) / 3 + 1;
break;
}
}
t.tm_sec = ss;
t.tm_min = mm;
t.tm_hour = hh;
t.tm_mday = day;
t.tm_mon = dmonth - 1;
t.tm_year = year - 1900;
t.tm_wday = 0;
t.tm_yday = 0;
t.tm_isdst = -1;
timer = mktime(&t);
tz_offset = remote_tzoffset_sec(zone);
if (tz_offset != -1)
timer += tzoffset_sec(&timer) - tz_offset;
if (dest)
procheader_date_get_localtime(dest, len, timer);
return timer;
}
void procheader_date_get_localtime(gchar *dest, gint len, const time_t timer)
{
struct tm *lt;
gchar *default_format = "%y/%m/%d(%a) %H:%M";
gchar *str;
const gchar *src_codeset, *dest_codeset;
struct tm buf;
if (timer > 0)
lt = localtime_r(&timer, &buf);
else {
time_t dummy = 1;
lt = localtime_r(&dummy, &buf);
}
if (prefs_common.date_format)
fast_strftime(dest, len, prefs_common.date_format, lt);
else
fast_strftime(dest, len, default_format, lt);
if (!g_utf8_validate(dest, -1, NULL)) {
src_codeset = conv_get_locale_charset_str_no_utf8();
dest_codeset = CS_UTF_8;
str = conv_codeset_strdup(dest, src_codeset, dest_codeset);
if (str) {
strncpy2(dest, str, len);
g_free(str);
}
}
}
/* Added by Mel Hadasht on 27 Aug 2001 */
/* Get a header from msginfo */
gint procheader_get_header_from_msginfo(MsgInfo *msginfo, gchar *buf, gint len, gchar *header)
{
gchar *file;
FILE *fp;
HeaderEntry hentry[]={ { NULL, NULL, TRUE },
{ NULL, NULL, FALSE } };
gint val;
hentry[0].name = header;
cm_return_val_if_fail(msginfo != NULL, -1);
file = procmsg_get_message_file_path(msginfo);
if ((fp = g_fopen(file, "rb")) == NULL) {
FILE_OP_ERROR(file, "fopen");
g_free(file);
return -1;
}
val = procheader_get_one_field(buf,len, fp, hentry);
if (fclose(fp) == EOF) {
FILE_OP_ERROR(file, "fclose");
claws_unlink(file);
g_free(file);
return -1;
}
g_free(file);
if (val == -1)
return -1;
return 0;
}
HeaderEntry *procheader_entries_from_str(const gchar *str)
{
HeaderEntry *entries = NULL, *he;
int numh = 0, i = 0;
gchar **names = NULL;
const gchar *s = str;
if (s == NULL) {
return NULL;
}
while (*s != '\0') {
if (*s == ' ') ++numh;
++s;
}
if (numh == 0) {
return NULL;
}
entries = g_new0(HeaderEntry, numh + 1); /* room for last NULL */
s = str;
++s; /* skip first space */
names = g_strsplit(s, " ", numh);
he = entries;
while (names[i]) {
he->name = g_strdup_printf("%s:", names[i]);
he->body = NULL;
he->unfold = FALSE;
++i, ++he;
}
he->name = NULL;
g_strfreev(names);
return entries;
}
void procheader_entries_free (HeaderEntry *entries)
{
if (entries != NULL) {
HeaderEntry *he = entries;
while (he->name != NULL) {
g_free(he->name);
if (he->body != NULL)
g_free(he->body);
++he;
}
g_free(entries);
}
}
gboolean procheader_header_is_internal(const gchar *hdr_name)
{
const gchar *internal_hdrs[] = {
"AF:", "NF:", "PS:", "SRH:", "SFN:", "DSR:", "MID:", "CFG:",
"PT:", "S:", "RQ:", "SSV:", "NSV:", "SSH:", "R:", "MAID:",
"SCF:", "RMID:", "FMID:", "NAID:",
"X-Claws-Account-Id:",
"X-Claws-Sign:",
"X-Claws-Encrypt:",
"X-Claws-Privacy-System:",
"X-Claws-Auto-Wrapping:",
"X-Claws-Auto-Indent:",
"X-Claws-End-Special-Headers:",
"X-Sylpheed-Account-Id:",
"X-Sylpheed-Sign:",
"X-Sylpheed-Encrypt:",
"X-Sylpheed-Privacy-System:",
"X-Sylpheed-End-Special-Headers:",
NULL
};
int i;
for (i = 0; internal_hdrs[i]; i++) {
if (!strcmp(hdr_name, internal_hdrs[i]))
return TRUE;
}
return FALSE;
}
|
ferdv/claws
|
src/procheader.c
|
C
|
gpl-3.0
| 28,320
|
/*
* Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
* Copyright (C) 1999-2015 Hiroyuki Yamamoto and the Claws Mail team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/* alfons - all folder item specific settings should migrate into
* folderlist.xml!!! the old folderitemrc file will only serve for a few
* versions (for compatibility) */
#ifdef HAVE_CONFIG_H
# include "config.h"
#include "claws-features.h"
#endif
#include "defs.h"
#include <glib.h>
#include <glib/gi18n.h>
#include "folder.h"
#include "alertpanel.h"
#include "prefs_folder_item.h"
#include "folderview.h"
#include "folder.h"
#include "summaryview.h"
#include "menu.h"
#include "account.h"
#include "prefs_gtk.h"
#include "manage_window.h"
#include "utils.h"
#include "addr_compl.h"
#include "prefs_common.h"
#include "gtkutils.h"
#include "filtering.h"
#include "folder_item_prefs.h"
#include "gtk/colorsel.h"
#include "string_match.h"
#include "quote_fmt.h"
#include "combobox.h"
#if USE_ENCHANT
#include "gtkaspell.h"
#endif
#define ASSIGN_STRING(string, value) \
{ \
g_free(string); \
string = (value); \
}
typedef struct _FolderItemGeneralPage FolderItemGeneralPage;
typedef struct _FolderItemComposePage FolderItemComposePage;
typedef struct _FolderItemTemplatesPage FolderItemTemplatesPage;
static gboolean can_save = TRUE;
struct _FolderItemGeneralPage
{
PrefsPage page;
FolderItem *item;
GtkWidget *table;
GtkWidget *no_save_warning;
GtkWidget *folder_type;
#ifndef G_OS_WIN32
GtkWidget *checkbtn_simplify_subject;
GtkWidget *entry_simplify_subject;
GtkWidget *entry_regexp_test_string;
GtkWidget *entry_regexp_test_result;
#endif
GtkWidget *checkbtn_folder_chmod;
GtkWidget *entry_folder_chmod;
GtkWidget *folder_color_btn;
GtkWidget *checkbtn_enable_processing;
GtkWidget *checkbtn_enable_processing_when_opening;
GtkWidget *checkbtn_newmailcheck;
GtkWidget *checkbtn_offlinesync;
GtkWidget *label_offlinesync;
GtkWidget *entry_offlinesync;
GtkWidget *label_end_offlinesync;
GtkWidget *checkbtn_remove_old_offlinesync;
GtkWidget *promote_html_part;
/* apply to sub folders */
#ifndef G_OS_WIN32
GtkWidget *simplify_subject_rec_checkbtn;
#endif
GtkWidget *folder_chmod_rec_checkbtn;
GtkWidget *folder_color_rec_checkbtn;
GtkWidget *enable_processing_rec_checkbtn;
GtkWidget *enable_processing_when_opening_rec_checkbtn;
GtkWidget *newmailcheck_rec_checkbtn;
GtkWidget *offlinesync_rec_checkbtn;
GtkWidget *promote_html_part_rec_checkbtn;
gint folder_color;
};
struct _FolderItemComposePage
{
PrefsPage page;
FolderItem *item;
GtkWidget *window;
GtkWidget *table;
GtkWidget *no_save_warning;
GtkWidget *checkbtn_request_return_receipt;
GtkWidget *checkbtn_save_copy_to_folder;
GtkWidget *checkbtn_default_to;
GtkWidget *entry_default_to;
GtkWidget *checkbtn_default_reply_to;
GtkWidget *entry_default_reply_to;
GtkWidget *checkbtn_default_cc;
GtkWidget *entry_default_cc;
GtkWidget *checkbtn_default_bcc;
GtkWidget *entry_default_bcc;
GtkWidget *checkbtn_default_replyto;
GtkWidget *entry_default_replyto;
GtkWidget *checkbtn_enable_default_account;
GtkWidget *optmenu_default_account;
#if USE_ENCHANT
GtkWidget *checkbtn_enable_default_dictionary;
GtkWidget *checkbtn_enable_default_alt_dictionary;
GtkWidget *combo_default_dictionary;
GtkWidget *combo_default_alt_dictionary;
#endif
/* apply to sub folders */
GtkWidget *request_return_receipt_rec_checkbtn;
GtkWidget *save_copy_to_folder_rec_checkbtn;
GtkWidget *default_to_rec_checkbtn;
GtkWidget *default_reply_to_rec_checkbtn;
GtkWidget *default_cc_rec_checkbtn;
GtkWidget *default_bcc_rec_checkbtn;
GtkWidget *default_replyto_rec_checkbtn;
GtkWidget *default_account_rec_checkbtn;
#if USE_ENCHANT
GtkWidget *default_dictionary_rec_checkbtn;
GtkWidget *default_alt_dictionary_rec_checkbtn;
#endif
};
struct _FolderItemTemplatesPage
{
PrefsPage page;
FolderItem *item;
GtkWidget *window;
GtkWidget *table;
GtkWidget *checkbtn_compose_with_format;
GtkWidget *compose_override_from_format;
GtkWidget *compose_subject_format;
GtkWidget *compose_body_format;
GtkWidget *checkbtn_reply_with_format;
GtkWidget *reply_quotemark;
GtkWidget *reply_override_from_format;
GtkWidget *reply_body_format;
GtkWidget *checkbtn_forward_with_format;
GtkWidget *forward_quotemark;
GtkWidget *forward_override_from_format;
GtkWidget *forward_body_format;
/* apply to sub folders */
GtkWidget *new_msg_format_rec_checkbtn;
GtkWidget *reply_format_rec_checkbtn;
GtkWidget *forward_format_rec_checkbtn;
};
static void general_save_folder_prefs(FolderItem *folder, FolderItemGeneralPage *page);
static void compose_save_folder_prefs(FolderItem *folder, FolderItemComposePage *page);
static void templates_save_folder_prefs(FolderItem *folder, FolderItemTemplatesPage *page);
static gboolean general_save_recurse_func(GNode *node, gpointer data);
static gboolean compose_save_recurse_func(GNode *node, gpointer data);
static gboolean templates_save_recurse_func(GNode *node, gpointer data);
static gint prefs_folder_item_chmod_mode (gchar *folder_chmod);
static void folder_color_set_dialog(GtkWidget *widget, gpointer data);
static void clean_cache_cb(GtkWidget *widget, gpointer data);
#ifndef G_OS_WIN32
static void folder_regexp_test_cb(GtkWidget *widget, gpointer data);
static void folder_regexp_set_subject_example_cb(GtkWidget *widget, gpointer data);
#endif
#define SAFE_STRING(str) \
(str) ? (str) : ""
static void prefs_folder_item_general_create_widget_func(PrefsPage * page_,
GtkWindow * window,
gpointer data)
{
FolderItemGeneralPage *page = (FolderItemGeneralPage *) page_;
FolderItem *item = (FolderItem *) data;
guint rowcount;
GtkWidget *table;
GtkWidget *hbox, *hbox2, *hbox_spc;
GtkWidget *label;
GtkListStore *folder_type_menu;
GtkWidget *folder_type;
GtkTreeIter iter;
GtkWidget *dummy_checkbtn, *clean_cache_btn;
SpecialFolderItemType type;
GtkWidget *no_save_warning = NULL;
#ifndef G_OS_WIN32
GtkWidget *checkbtn_simplify_subject;
GtkWidget *entry_simplify_subject;
GtkWidget *label_regexp_test;
GtkWidget *entry_regexp_test_string;
GtkWidget *label_regexp_result;
GtkWidget *entry_regexp_test_result;
#endif
GtkWidget *checkbtn_folder_chmod;
GtkWidget *entry_folder_chmod;
GtkWidget *folder_color;
GtkWidget *folder_color_btn;
GtkWidget *checkbtn_enable_processing;
GtkWidget *checkbtn_enable_processing_when_opening;
GtkWidget *checkbtn_newmailcheck;
GtkWidget *checkbtn_offlinesync;
GtkWidget *label_offlinesync;
GtkWidget *entry_offlinesync;
GtkWidget *label_end_offlinesync;
GtkWidget *checkbtn_remove_old_offlinesync;
GtkWidget *promote_html_part;
GtkListStore *promote_html_part_menu;
#ifndef G_OS_WIN32
GtkWidget *simplify_subject_rec_checkbtn;
#endif
GtkWidget *folder_chmod_rec_checkbtn;
GtkWidget *folder_color_rec_checkbtn;
GtkWidget *enable_processing_rec_checkbtn;
GtkWidget *enable_processing_when_opening_rec_checkbtn;
GtkWidget *newmailcheck_rec_checkbtn;
GtkWidget *offlinesync_rec_checkbtn;
GtkWidget *promote_html_part_rec_checkbtn;
page->item = item;
/* Table */
table = gtk_table_new(12, 3, FALSE);
gtk_container_set_border_width (GTK_CONTAINER (table), VBOX_BORDER);
gtk_table_set_row_spacings(GTK_TABLE(table), 4);
gtk_table_set_col_spacings(GTK_TABLE(table), 4);
rowcount = 0;
if (!can_save) {
no_save_warning = gtk_label_new(
_("<i>These preferences will not be saved as this folder "
"is a top-level folder. However, you can set them for the "
"whole mailbox tree by using \"Apply to subfolders\".</i>"));
gtk_label_set_use_markup(GTK_LABEL(no_save_warning), TRUE);
gtk_label_set_line_wrap(GTK_LABEL(no_save_warning), TRUE);
gtk_misc_set_alignment(GTK_MISC(no_save_warning), 0.0, 0.5);
gtk_table_attach(GTK_TABLE(table), no_save_warning, 0, 3,
rowcount, rowcount + 1, GTK_FILL, 0, 0, 0);
rowcount++;
}
/* Apply to subfolders */
label = gtk_label_new(_("Apply to\nsubfolders"));
gtk_misc_set_alignment(GTK_MISC(label), 0.5, 0.5);
gtk_table_attach(GTK_TABLE(table), label, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* folder_type */
folder_type = gtkut_sc_combobox_create(NULL, FALSE);
gtk_widget_show (folder_type);
type = F_NORMAL;
if (item->stype == F_INBOX)
type = F_INBOX;
else if (folder_has_parent_of_type(item, F_OUTBOX))
type = F_OUTBOX;
else if (folder_has_parent_of_type(item, F_DRAFT))
type = F_DRAFT;
else if (folder_has_parent_of_type(item, F_QUEUE))
type = F_QUEUE;
else if (folder_has_parent_of_type(item, F_TRASH))
type = F_TRASH;
folder_type_menu = GTK_LIST_STORE(gtk_combo_box_get_model(
GTK_COMBO_BOX(folder_type)));
COMBOBOX_ADD (folder_type_menu, _("Normal"), F_NORMAL);
COMBOBOX_ADD (folder_type_menu, _("Inbox"), F_INBOX);
COMBOBOX_ADD (folder_type_menu, _("Outbox"), F_OUTBOX);
COMBOBOX_ADD (folder_type_menu, _("Drafts"), F_DRAFT);
COMBOBOX_ADD (folder_type_menu, _("Queue"), F_QUEUE);
COMBOBOX_ADD (folder_type_menu, _("Trash"), F_TRASH);
combobox_select_by_data(GTK_COMBO_BOX(folder_type), type);
dummy_checkbtn = gtk_check_button_new();
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(dummy_checkbtn), type != F_INBOX);
gtk_widget_set_sensitive(dummy_checkbtn, FALSE);
if (type == item->stype && type == F_NORMAL)
gtk_widget_set_sensitive(folder_type, TRUE);
else
gtk_widget_set_sensitive(folder_type, FALSE);
label = gtk_label_new(_("Folder type"));
gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
gtk_table_attach(GTK_TABLE(table), label, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
gtk_table_attach(GTK_TABLE(table), folder_type, 1, 2,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
gtk_table_attach(GTK_TABLE(table), dummy_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
#ifndef G_OS_WIN32
/* Simplify Subject */
checkbtn_simplify_subject = gtk_check_button_new_with_label(_("Simplify Subject RegExp"));
gtk_table_attach(GTK_TABLE(table), checkbtn_simplify_subject, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_simplify_subject),
item->prefs->enable_simplify_subject);
g_signal_connect(G_OBJECT(checkbtn_simplify_subject), "toggled",
G_CALLBACK(folder_regexp_set_subject_example_cb), page);
entry_simplify_subject = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_simplify_subject, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_simplify_subject, entry_simplify_subject);
gtk_entry_set_text(GTK_ENTRY(entry_simplify_subject),
SAFE_STRING(item->prefs->simplify_subject_regexp));
g_signal_connect(G_OBJECT(entry_simplify_subject), "changed",
G_CALLBACK(folder_regexp_test_cb), page);
simplify_subject_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), simplify_subject_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Test string */
label_regexp_test = gtk_label_new(_("Test string:"));
gtk_misc_set_alignment(GTK_MISC(label_regexp_test), 1, 0.5);
gtk_table_attach(GTK_TABLE(table), label_regexp_test, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_simplify_subject, label_regexp_test);
entry_regexp_test_string = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_regexp_test_string, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_simplify_subject, entry_regexp_test_string);
g_signal_connect(G_OBJECT(entry_regexp_test_string), "changed",
G_CALLBACK(folder_regexp_test_cb), page);
rowcount++;
/* Test result */
label_regexp_result = gtk_label_new(_("Result:"));
gtk_misc_set_alignment(GTK_MISC(label_regexp_result), 1, 0.5);
gtk_table_attach(GTK_TABLE(table), label_regexp_result, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_simplify_subject, label_regexp_result);
entry_regexp_test_result = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_regexp_test_result, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_simplify_subject, entry_regexp_test_result);
gtk_editable_set_editable(GTK_EDITABLE(entry_regexp_test_result), FALSE);
rowcount++;
#endif
/* Folder chmod */
checkbtn_folder_chmod = gtk_check_button_new_with_label(_("Folder chmod"));
gtk_table_attach(GTK_TABLE(table), checkbtn_folder_chmod, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_folder_chmod),
item->prefs->enable_folder_chmod);
entry_folder_chmod = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_folder_chmod, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_folder_chmod, entry_folder_chmod);
if (item->prefs->folder_chmod) {
gchar *buf;
buf = g_strdup_printf("%o", item->prefs->folder_chmod);
gtk_entry_set_text(GTK_ENTRY(entry_folder_chmod), buf);
g_free(buf);
}
folder_chmod_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), folder_chmod_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Folder color */
folder_color = gtk_label_new(_("Folder color"));
gtk_misc_set_alignment(GTK_MISC(folder_color), 0, 0.5);
gtk_table_attach(GTK_TABLE(table), folder_color, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
hbox = gtk_hbox_new(FALSE, 0);
gtk_table_attach(GTK_TABLE(table), hbox, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
folder_color_btn = gtk_button_new_with_label("");
gtk_widget_set_size_request(folder_color_btn, 36, 26);
gtk_box_pack_start (GTK_BOX(hbox), folder_color_btn, FALSE, FALSE, 0);
CLAWS_SET_TIP(folder_color_btn,
_("Pick color for folder"));
page->folder_color = item->prefs->color;
g_signal_connect(G_OBJECT(folder_color_btn), "clicked",
G_CALLBACK(folder_color_set_dialog),
page);
gtkut_set_widget_bgcolor_rgb(folder_color_btn, item->prefs->color);
folder_color_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), folder_color_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Enable processing at startup */
checkbtn_enable_processing =
gtk_check_button_new_with_label(_("Run Processing rules at start-up"));
gtk_table_attach(GTK_TABLE(table), checkbtn_enable_processing, 0, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_enable_processing),
item->prefs->enable_processing);
enable_processing_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), enable_processing_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Enable processing rules when opening folder */
checkbtn_enable_processing_when_opening =
gtk_check_button_new_with_label(_("Run Processing rules when opening"));
gtk_table_attach(GTK_TABLE(table), checkbtn_enable_processing_when_opening, 0, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_enable_processing_when_opening),
item->prefs->enable_processing_when_opening);
enable_processing_when_opening_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), enable_processing_when_opening_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Check folder for new mail */
checkbtn_newmailcheck = gtk_check_button_new_with_label(_("Scan for new mail"));
CLAWS_SET_TIP(checkbtn_newmailcheck,
_("Turn this option on if mail is delivered directly "
"to this folder by server side filtering on IMAP or "
"by an external application"));
gtk_table_attach(GTK_TABLE(table), checkbtn_newmailcheck, 0, 2,
rowcount, rowcount+1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_newmailcheck),
item->prefs->newmailcheck);
newmailcheck_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), newmailcheck_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Select HTML part by default? */
hbox = gtk_hbox_new (FALSE, 2);
gtk_widget_show (hbox);
gtk_table_attach (GTK_TABLE(table), hbox, 0, 2,
rowcount, rowcount+1, GTK_FILL, GTK_FILL, 0, 0);
label = gtk_label_new(_("Select the HTML part of multipart messages"));
gtk_widget_show (label);
gtk_box_pack_start (GTK_BOX(hbox), label, FALSE, FALSE, 0);
promote_html_part = gtkut_sc_combobox_create (NULL, FALSE);
gtk_widget_show (promote_html_part);
gtk_box_pack_start (GTK_BOX(hbox), promote_html_part, FALSE, FALSE, 0);
promote_html_part_menu = GTK_LIST_STORE(gtk_combo_box_get_model(
GTK_COMBO_BOX(promote_html_part)));
COMBOBOX_ADD (promote_html_part_menu, _("Default"), HTML_PROMOTE_DEFAULT);
COMBOBOX_ADD (promote_html_part_menu, _("No"), HTML_PROMOTE_NEVER);
COMBOBOX_ADD (promote_html_part_menu, _("Yes"), HTML_PROMOTE_ALWAYS);
combobox_select_by_data(GTK_COMBO_BOX(promote_html_part),
item->prefs->promote_html_part);
CLAWS_SET_TIP(hbox, _("\"Default\" will follow global preference (found in /Preferences/"
"Message View/Text Options)"));
promote_html_part_rec_checkbtn = gtk_check_button_new();
gtk_widget_show (promote_html_part_rec_checkbtn);
gtk_table_attach(GTK_TABLE(table), promote_html_part_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Synchronise folder for offline use */
checkbtn_offlinesync = gtk_check_button_new_with_label(_("Synchronise for offline use"));
gtk_table_attach(GTK_TABLE(table), checkbtn_offlinesync, 0, 2,
rowcount, rowcount+1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
offlinesync_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), offlinesync_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
hbox = gtk_hbox_new (FALSE, 8);
gtk_widget_show (hbox);
gtk_table_attach(GTK_TABLE(table), hbox, 0, 3,
rowcount, rowcount+1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
rowcount++;
hbox_spc = gtk_hbox_new (FALSE, 0);
gtk_widget_show (hbox_spc);
gtk_box_pack_start (GTK_BOX (hbox), hbox_spc, FALSE, FALSE, 0);
gtk_widget_set_size_request (hbox_spc, 12, -1);
label_offlinesync = gtk_label_new(_("Fetch message bodies from the last"));
gtk_widget_show (label_offlinesync);
gtk_box_pack_start (GTK_BOX (hbox), label_offlinesync, FALSE, FALSE, 0);
entry_offlinesync = gtk_entry_new();
gtk_widget_set_size_request (entry_offlinesync, 64, -1);
gtk_widget_show (entry_offlinesync);
CLAWS_SET_TIP(entry_offlinesync, _("0: all bodies"));
gtk_box_pack_start (GTK_BOX (hbox), entry_offlinesync, FALSE, FALSE, 0);
label_end_offlinesync = gtk_label_new(_("days"));
gtk_widget_show (label_end_offlinesync);
gtk_box_pack_start (GTK_BOX (hbox), label_end_offlinesync, FALSE, FALSE, 0);
checkbtn_remove_old_offlinesync = gtk_check_button_new_with_label(
_("Remove older messages bodies"));
hbox2 = gtk_hbox_new (FALSE, 8);
gtk_widget_show (hbox2);
gtk_table_attach(GTK_TABLE(table), hbox2, 0, 3,
rowcount, rowcount+1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
rowcount++;
hbox_spc = gtk_hbox_new (FALSE, 0);
gtk_widget_show (hbox_spc);
gtk_box_pack_start (GTK_BOX (hbox2), hbox_spc, FALSE, FALSE, 0);
gtk_widget_set_size_request (hbox_spc, 12, -1);
gtk_box_pack_start (GTK_BOX (hbox2), checkbtn_remove_old_offlinesync, FALSE, FALSE, 0);
SET_TOGGLE_SENSITIVITY (checkbtn_offlinesync, hbox);
SET_TOGGLE_SENSITIVITY (checkbtn_offlinesync, hbox2);
clean_cache_btn = gtk_button_new_with_label(_("Discard folder cache"));
gtk_widget_show (clean_cache_btn);
gtk_table_attach(GTK_TABLE(table), clean_cache_btn, 0, 1,
rowcount, rowcount+1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
g_signal_connect(G_OBJECT(clean_cache_btn), "clicked",
G_CALLBACK(clean_cache_cb),
page);
gtk_widget_show_all(table);
if (item->folder && (item->folder->klass->type != F_IMAP &&
item->folder->klass->type != F_NEWS)) {
item->prefs->offlinesync = TRUE;
item->prefs->offlinesync_days = 0;
item->prefs->remove_old_bodies = FALSE;
gtk_widget_set_sensitive(GTK_WIDGET(checkbtn_offlinesync),
FALSE);
gtk_widget_set_sensitive(GTK_WIDGET(offlinesync_rec_checkbtn),
FALSE);
gtk_widget_hide(GTK_WIDGET(checkbtn_offlinesync));
gtk_widget_hide(GTK_WIDGET(hbox));
gtk_widget_hide(GTK_WIDGET(hbox2));
gtk_widget_hide(GTK_WIDGET(offlinesync_rec_checkbtn));
gtk_widget_hide(GTK_WIDGET(clean_cache_btn));
}
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_offlinesync),
item->prefs->offlinesync);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_remove_old_offlinesync),
item->prefs->remove_old_bodies);
gtk_entry_set_text(GTK_ENTRY(entry_offlinesync), itos(item->prefs->offlinesync_days));
page->table = table;
page->folder_type = folder_type;
page->no_save_warning = no_save_warning;
#ifndef G_OS_WIN32
page->checkbtn_simplify_subject = checkbtn_simplify_subject;
page->entry_simplify_subject = entry_simplify_subject;
page->entry_regexp_test_string = entry_regexp_test_string;
page->entry_regexp_test_result = entry_regexp_test_result;
#endif
page->checkbtn_folder_chmod = checkbtn_folder_chmod;
page->entry_folder_chmod = entry_folder_chmod;
page->folder_color_btn = folder_color_btn;
page->checkbtn_enable_processing = checkbtn_enable_processing;
page->checkbtn_enable_processing_when_opening = checkbtn_enable_processing_when_opening;
page->checkbtn_newmailcheck = checkbtn_newmailcheck;
page->checkbtn_offlinesync = checkbtn_offlinesync;
page->label_offlinesync = label_offlinesync;
page->entry_offlinesync = entry_offlinesync;
page->label_end_offlinesync = label_end_offlinesync;
page->checkbtn_remove_old_offlinesync = checkbtn_remove_old_offlinesync;
page->promote_html_part = promote_html_part;
#ifndef G_OS_WIN32
page->simplify_subject_rec_checkbtn = simplify_subject_rec_checkbtn;
#endif
page->folder_chmod_rec_checkbtn = folder_chmod_rec_checkbtn;
page->folder_color_rec_checkbtn = folder_color_rec_checkbtn;
page->enable_processing_rec_checkbtn = enable_processing_rec_checkbtn;
page->enable_processing_when_opening_rec_checkbtn = enable_processing_when_opening_rec_checkbtn;
page->newmailcheck_rec_checkbtn = newmailcheck_rec_checkbtn;
page->offlinesync_rec_checkbtn = offlinesync_rec_checkbtn;
page->promote_html_part_rec_checkbtn = promote_html_part_rec_checkbtn;
page->page.widget = table;
#ifndef G_OS_WIN32
folder_regexp_set_subject_example_cb(NULL, page);
#endif
}
static void prefs_folder_item_general_destroy_widget_func(PrefsPage *page_)
{
/* FolderItemGeneralPage *page = (FolderItemGeneralPage *) page_; */
}
/** \brief Save the prefs in page to folder.
*
* If the folder is not the one specified in page->item, then only those properties
* that have the relevant 'apply to sub folders' button checked are saved
*/
static void general_save_folder_prefs(FolderItem *folder, FolderItemGeneralPage *page)
{
FolderItemPrefs *prefs = folder->prefs;
gchar *buf;
gboolean all = FALSE, summary_update_needed = FALSE;
SpecialFolderItemType type = F_NORMAL;
FolderView *folderview = mainwindow_get_mainwindow()->folderview;
HTMLPromoteType promote_html_part = HTML_PROMOTE_DEFAULT;
if (folder->path == NULL)
return;
cm_return_if_fail(prefs != NULL);
if (page->item == folder)
all = TRUE;
type = combobox_get_active_data(GTK_COMBO_BOX(page->folder_type));
if (all && folder->stype != type && page->item->parent_stype == F_NORMAL) {
folder_item_change_type(folder, type);
summary_update_needed = TRUE;
}
promote_html_part =
combobox_get_active_data(GTK_COMBO_BOX(page->promote_html_part));
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->promote_html_part_rec_checkbtn)))
prefs->promote_html_part = promote_html_part;
#ifndef G_OS_WIN32
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->simplify_subject_rec_checkbtn))) {
gboolean old_simplify_subject = prefs->enable_simplify_subject;
int regexp_diffs = strcmp2(prefs->simplify_subject_regexp, gtk_editable_get_chars(
GTK_EDITABLE(page->entry_simplify_subject), 0, -1));
prefs->enable_simplify_subject =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_simplify_subject));
ASSIGN_STRING(prefs->simplify_subject_regexp,
gtk_editable_get_chars(GTK_EDITABLE(page->entry_simplify_subject), 0, -1));
if (old_simplify_subject != prefs->enable_simplify_subject || regexp_diffs != 0)
summary_update_needed = TRUE;
}
#endif
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->folder_chmod_rec_checkbtn))) {
prefs->enable_folder_chmod =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_folder_chmod));
buf = gtk_editable_get_chars(GTK_EDITABLE(page->entry_folder_chmod), 0, -1);
prefs->folder_chmod = prefs_folder_item_chmod_mode(buf);
g_free(buf);
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->folder_color_rec_checkbtn))) {
int old_color = prefs->color;
prefs->color = page->folder_color;
/* update folder view */
if (prefs->color != old_color)
folder_item_update(folder, F_ITEM_UPDATE_MSGCNT);
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->enable_processing_rec_checkbtn))) {
prefs->enable_processing =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_enable_processing));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->enable_processing_when_opening_rec_checkbtn))) {
prefs->enable_processing_when_opening =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_enable_processing_when_opening));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->newmailcheck_rec_checkbtn))) {
prefs->newmailcheck =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_newmailcheck));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->offlinesync_rec_checkbtn))) {
prefs->offlinesync =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_offlinesync));
prefs->offlinesync_days =
atoi(gtk_entry_get_text(GTK_ENTRY(page->entry_offlinesync)));
prefs->remove_old_bodies =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_remove_old_offlinesync));
}
folder_item_prefs_save_config(folder);
if (folder->opened && summary_update_needed) {
summary_set_prefs_from_folderitem(folderview->summaryview, folder);
summary_show(folderview->summaryview, folder);
}
}
static gboolean general_save_recurse_func(GNode *node, gpointer data)
{
FolderItem *item = (FolderItem *) node->data;
FolderItemGeneralPage *page = (FolderItemGeneralPage *) data;
cm_return_val_if_fail(item != NULL, TRUE);
cm_return_val_if_fail(page != NULL, TRUE);
general_save_folder_prefs(item, page);
/* optimise by not continuing if none of the 'apply to sub folders'
check boxes are selected - and optimise the checking by only doing
it once */
if ((node == page->item->node) &&
!(
#ifndef G_OS_WIN32
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->simplify_subject_rec_checkbtn)) ||
#endif
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->folder_chmod_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->folder_color_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->enable_processing_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->enable_processing_when_opening_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->newmailcheck_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->offlinesync_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->promote_html_part_rec_checkbtn))
))
return TRUE;
else
return FALSE;
}
static void prefs_folder_item_general_save_func(PrefsPage *page_)
{
FolderItemGeneralPage *page = (FolderItemGeneralPage *) page_;
g_node_traverse(page->item->node, G_PRE_ORDER, G_TRAVERSE_ALL,
-1, general_save_recurse_func, page);
main_window_set_menu_sensitive(mainwindow_get_mainwindow());
}
static RecvProtocol item_protocol(FolderItem *item)
{
if (!item)
return A_NONE;
if (!item->folder)
return A_NONE;
if (!item->folder->account)
return A_NONE;
return item->folder->account->protocol;
}
static void prefs_folder_item_compose_create_widget_func(PrefsPage * page_,
GtkWindow * window,
gpointer data)
{
FolderItemComposePage *page = (FolderItemComposePage *) page_;
FolderItem *item = (FolderItem *) data;
guint rowcount;
gchar *text = NULL;
GtkWidget *table;
GtkWidget *label;
GtkWidget *no_save_warning = NULL;
GtkWidget *checkbtn_request_return_receipt = NULL;
GtkWidget *checkbtn_save_copy_to_folder = NULL;
GtkWidget *checkbtn_default_to = NULL;
GtkWidget *entry_default_to = NULL;
GtkWidget *checkbtn_default_reply_to = NULL;
GtkWidget *entry_default_reply_to = NULL;
GtkWidget *checkbtn_default_cc = NULL;
GtkWidget *entry_default_cc = NULL;
GtkWidget *checkbtn_default_bcc = NULL;
GtkWidget *entry_default_bcc = NULL;
GtkWidget *checkbtn_default_replyto = NULL;
GtkWidget *entry_default_replyto = NULL;
GtkWidget *checkbtn_enable_default_account = NULL;
GtkWidget *optmenu_default_account = NULL;
GtkListStore *optmenu_default_account_menu = NULL;
GtkTreeIter iter;
#if USE_ENCHANT
GtkWidget *checkbtn_enable_default_dictionary = NULL;
GtkWidget *combo_default_dictionary = NULL;
GtkWidget *checkbtn_enable_default_alt_dictionary = NULL;
GtkWidget *combo_default_alt_dictionary = NULL;
GtkWidget *default_dictionary_rec_checkbtn = NULL;
GtkWidget *default_alt_dictionary_rec_checkbtn = NULL;
gchar *dictionary;
#endif
GtkWidget *request_return_receipt_rec_checkbtn = NULL;
GtkWidget *save_copy_to_folder_rec_checkbtn = NULL;
GtkWidget *default_to_rec_checkbtn = NULL;
GtkWidget *default_reply_to_rec_checkbtn = NULL;
GtkWidget *default_cc_rec_checkbtn = NULL;
GtkWidget *default_bcc_rec_checkbtn = NULL;
GtkWidget *default_replyto_rec_checkbtn = NULL;
GtkWidget *default_account_rec_checkbtn = NULL;
GList *cur_ac;
GList *account_list;
PrefsAccount *ac_prefs;
gboolean default_account_set = FALSE;
page->item = item;
/* Table */
#if USE_ENCHANT
# define TABLEHEIGHT 7
#else
# define TABLEHEIGHT 6
#endif
table = gtk_table_new(TABLEHEIGHT, 3, FALSE);
gtk_container_set_border_width (GTK_CONTAINER (table), VBOX_BORDER);
gtk_table_set_row_spacings(GTK_TABLE(table), 4);
gtk_table_set_col_spacings(GTK_TABLE(table), 4);
rowcount = 0;
if (!can_save) {
no_save_warning = gtk_label_new(
_("<i>These preferences will not be saved as this folder "
"is a top-level folder. However, you can set them for the "
"whole mailbox tree by using \"Apply to subfolders\".</i>"));
gtk_label_set_use_markup(GTK_LABEL(no_save_warning), TRUE);
gtk_label_set_line_wrap(GTK_LABEL(no_save_warning), TRUE);
gtk_misc_set_alignment(GTK_MISC(no_save_warning), 0.0, 0.5);
gtk_table_attach(GTK_TABLE(table), no_save_warning, 0, 3,
rowcount, rowcount + 1, GTK_FILL, 0, 0, 0);
rowcount++;
}
/* Apply to subfolders */
label = gtk_label_new(_("Apply to\nsubfolders"));
gtk_misc_set_alignment(GTK_MISC(label), 0.5, 0.5);
gtk_table_attach(GTK_TABLE(table), label, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
if (item_protocol(item) != A_NNTP) {
/* Request Return Receipt */
checkbtn_request_return_receipt = gtk_check_button_new_with_label
(_("Request Return Receipt"));
gtk_table_attach(GTK_TABLE(table), checkbtn_request_return_receipt,
0, 2, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL,
GTK_FILL, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_request_return_receipt),
item->ret_rcpt ? TRUE : FALSE);
request_return_receipt_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), request_return_receipt_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Save Copy to Folder */
checkbtn_save_copy_to_folder = gtk_check_button_new_with_label
(_("Save copy of outgoing messages to this folder instead of Sent"));
gtk_table_attach(GTK_TABLE(table), checkbtn_save_copy_to_folder, 0, 2,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_save_copy_to_folder),
item->prefs->save_copy_to_folder ? TRUE : FALSE);
save_copy_to_folder_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), save_copy_to_folder_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Default To */
text = g_strconcat(_("Default "), prefs_common_translated_header_name("To:"), NULL);
checkbtn_default_to = gtk_check_button_new_with_label(text);
gtk_table_attach(GTK_TABLE(table), checkbtn_default_to, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_default_to),
item->prefs->enable_default_to);
g_free(text);
entry_default_to = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_default_to, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_default_to, entry_default_to);
gtk_entry_set_text(GTK_ENTRY(entry_default_to), SAFE_STRING(item->prefs->default_to));
address_completion_register_entry(GTK_ENTRY(entry_default_to),
TRUE);
default_to_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_to_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Default address to reply to */
text = g_strconcat(_("Default "), prefs_common_translated_header_name("To:"),
_(" for replies"), NULL);
checkbtn_default_reply_to = gtk_check_button_new_with_label(text);
gtk_table_attach(GTK_TABLE(table), checkbtn_default_reply_to, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_default_reply_to),
item->prefs->enable_default_reply_to);
g_free(text);
entry_default_reply_to = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_default_reply_to, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_default_reply_to, entry_default_reply_to);
gtk_entry_set_text(GTK_ENTRY(entry_default_reply_to), SAFE_STRING(item->prefs->default_reply_to));
address_completion_register_entry(
GTK_ENTRY(entry_default_reply_to), TRUE);
default_reply_to_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_reply_to_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Default Cc */
text = g_strconcat(_("Default "), prefs_common_translated_header_name("Cc:"), NULL);
checkbtn_default_cc = gtk_check_button_new_with_label(text);
gtk_table_attach(GTK_TABLE(table), checkbtn_default_cc, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_default_cc),
item->prefs->enable_default_cc);
g_free(text);
entry_default_cc = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_default_cc, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_default_cc, entry_default_cc);
gtk_entry_set_text(GTK_ENTRY(entry_default_cc), SAFE_STRING(item->prefs->default_cc));
address_completion_register_entry(GTK_ENTRY(entry_default_cc),
TRUE);
default_cc_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_cc_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Default Bcc */
text = g_strconcat(_("Default "), prefs_common_translated_header_name("Bcc:"), NULL);
checkbtn_default_bcc = gtk_check_button_new_with_label(text);
gtk_table_attach(GTK_TABLE(table), checkbtn_default_bcc, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_default_bcc),
item->prefs->enable_default_bcc);
g_free(text);
entry_default_bcc = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_default_bcc, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_default_bcc, entry_default_bcc);
gtk_entry_set_text(GTK_ENTRY(entry_default_bcc), SAFE_STRING(item->prefs->default_bcc));
address_completion_register_entry(GTK_ENTRY(entry_default_bcc),
TRUE);
default_bcc_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_bcc_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Default Reply-to */
text = g_strconcat(_("Default "), prefs_common_translated_header_name("Reply-To:"), NULL);
checkbtn_default_replyto = gtk_check_button_new_with_label(text);
gtk_table_attach(GTK_TABLE(table), checkbtn_default_replyto, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_default_replyto),
item->prefs->enable_default_replyto);
g_free(text);
entry_default_replyto = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_default_replyto, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_default_replyto, entry_default_replyto);
gtk_entry_set_text(GTK_ENTRY(entry_default_replyto), SAFE_STRING(item->prefs->default_replyto));
address_completion_register_entry(GTK_ENTRY(entry_default_replyto),
TRUE);
default_replyto_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_replyto_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
}
/* Default account */
checkbtn_enable_default_account = gtk_check_button_new_with_label(_("Default account"));
gtk_table_attach(GTK_TABLE(table), checkbtn_enable_default_account, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_enable_default_account),
item->prefs->enable_default_account);
optmenu_default_account = gtkut_sc_combobox_create(NULL, FALSE);
gtk_table_attach(GTK_TABLE(table), optmenu_default_account, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
optmenu_default_account_menu = GTK_LIST_STORE(
gtk_combo_box_get_model(GTK_COMBO_BOX(optmenu_default_account)));
account_list = account_get_list();
for (cur_ac = account_list; cur_ac != NULL; cur_ac = cur_ac->next) {
ac_prefs = (PrefsAccount *)cur_ac->data;
if (item->folder->account &&
( (item_protocol(item) == A_NNTP && ac_prefs->protocol != A_NNTP)
||(item_protocol(item) != A_NNTP && ac_prefs->protocol == A_NNTP)))
continue;
if (item->folder->klass->type != F_NEWS && ac_prefs->protocol == A_NNTP)
continue;
COMBOBOX_ADD_ESCAPED (optmenu_default_account_menu,
ac_prefs->account_name?ac_prefs->account_name : _("Untitled"),
ac_prefs->account_id);
/* Set combobox to current default account id */
if (ac_prefs->account_id == item->prefs->default_account) {
combobox_select_by_data(GTK_COMBO_BOX(optmenu_default_account),
ac_prefs->account_id);
default_account_set = TRUE;
}
}
/* If nothing has been set (folder doesn't have a default account set),
* pre-select global default account, since that's what actually used
* anyway. We don't want nothing selected in combobox. */
if( !default_account_set )
combobox_select_by_data(GTK_COMBO_BOX(optmenu_default_account),
account_get_default()->account_id);
SET_TOGGLE_SENSITIVITY(checkbtn_enable_default_account, optmenu_default_account);
default_account_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_account_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
#if USE_ENCHANT
/* Default dictionary */
checkbtn_enable_default_dictionary = gtk_check_button_new_with_label(_("Default dictionary"));
gtk_table_attach(GTK_TABLE(table), checkbtn_enable_default_dictionary, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_enable_default_dictionary),
item->prefs->enable_default_dictionary);
combo_default_dictionary = gtkaspell_dictionary_combo_new(TRUE);
gtk_table_attach(GTK_TABLE(table), combo_default_dictionary, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
dictionary = item->prefs->default_dictionary;
if (dictionary && strrchr(dictionary, '/')) {
gchar *tmp = g_strdup(strrchr(dictionary, '/')+1);
g_free(item->prefs->default_dictionary);
item->prefs->default_dictionary = tmp;
dictionary = item->prefs->default_dictionary;
}
if (item->prefs->default_dictionary &&
strchr(item->prefs->default_dictionary, '-')) {
*(strchr(item->prefs->default_dictionary, '-')) = '\0';
}
if (dictionary)
gtkaspell_set_dictionary_menu_active_item(
GTK_COMBO_BOX(combo_default_dictionary), dictionary);
SET_TOGGLE_SENSITIVITY(checkbtn_enable_default_dictionary, combo_default_dictionary);
default_dictionary_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_dictionary_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Default dictionary */
checkbtn_enable_default_alt_dictionary = gtk_check_button_new_with_label(_("Default alternate dictionary"));
gtk_table_attach(GTK_TABLE(table), checkbtn_enable_default_alt_dictionary, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_enable_default_alt_dictionary),
item->prefs->enable_default_alt_dictionary);
combo_default_alt_dictionary = gtkaspell_dictionary_combo_new(FALSE);
gtk_table_attach(GTK_TABLE(table), combo_default_alt_dictionary, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
dictionary = item->prefs->default_alt_dictionary;
if (dictionary && strrchr(dictionary, '/')) {
gchar *tmp = g_strdup(strrchr(dictionary, '/')+1);
g_free(item->prefs->default_alt_dictionary);
item->prefs->default_alt_dictionary = tmp;
dictionary = item->prefs->default_alt_dictionary;
}
if (item->prefs->default_alt_dictionary &&
strchr(item->prefs->default_alt_dictionary, '-')) {
*(strchr(item->prefs->default_alt_dictionary, '-')) = '\0';
}
if (dictionary)
gtkaspell_set_dictionary_menu_active_item(
GTK_COMBO_BOX(combo_default_alt_dictionary), dictionary);
SET_TOGGLE_SENSITIVITY(checkbtn_enable_default_alt_dictionary, combo_default_alt_dictionary);
default_alt_dictionary_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_alt_dictionary_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
#endif
gtk_widget_show_all(table);
page->window = GTK_WIDGET(window);
page->table = table;
page->no_save_warning = no_save_warning;
page->checkbtn_request_return_receipt = checkbtn_request_return_receipt;
page->checkbtn_save_copy_to_folder = checkbtn_save_copy_to_folder;
page->checkbtn_default_to = checkbtn_default_to;
page->entry_default_to = entry_default_to;
page->checkbtn_default_reply_to = checkbtn_default_reply_to;
page->entry_default_reply_to = entry_default_reply_to;
page->checkbtn_default_cc = checkbtn_default_cc;
page->entry_default_cc = entry_default_cc;
page->checkbtn_default_bcc = checkbtn_default_bcc;
page->entry_default_bcc = entry_default_bcc;
page->checkbtn_default_replyto = checkbtn_default_replyto;
page->entry_default_replyto = entry_default_replyto;
page->checkbtn_enable_default_account = checkbtn_enable_default_account;
page->optmenu_default_account = optmenu_default_account;
#ifdef USE_ENCHANT
page->checkbtn_enable_default_dictionary = checkbtn_enable_default_dictionary;
page->combo_default_dictionary = combo_default_dictionary;
page->checkbtn_enable_default_alt_dictionary = checkbtn_enable_default_alt_dictionary;
page->combo_default_alt_dictionary = combo_default_alt_dictionary;
#endif
page->request_return_receipt_rec_checkbtn = request_return_receipt_rec_checkbtn;
page->save_copy_to_folder_rec_checkbtn = save_copy_to_folder_rec_checkbtn;
page->default_to_rec_checkbtn = default_to_rec_checkbtn;
page->default_reply_to_rec_checkbtn = default_reply_to_rec_checkbtn;
page->default_cc_rec_checkbtn = default_cc_rec_checkbtn;
page->default_bcc_rec_checkbtn = default_bcc_rec_checkbtn;
page->default_replyto_rec_checkbtn = default_replyto_rec_checkbtn;
page->default_account_rec_checkbtn = default_account_rec_checkbtn;
#if USE_ENCHANT
page->default_dictionary_rec_checkbtn = default_dictionary_rec_checkbtn;
page->default_alt_dictionary_rec_checkbtn = default_alt_dictionary_rec_checkbtn;
#endif
page->page.widget = table;
}
static void prefs_folder_item_compose_destroy_widget_func(PrefsPage *page_)
{
FolderItemComposePage *page = (FolderItemComposePage *) page_;
if (page->entry_default_to)
address_completion_unregister_entry(GTK_ENTRY(page->entry_default_to));
if (page->entry_default_reply_to)
address_completion_unregister_entry(GTK_ENTRY(page->entry_default_reply_to));
if (page->entry_default_cc)
address_completion_unregister_entry(GTK_ENTRY(page->entry_default_cc));
if (page->entry_default_bcc)
address_completion_unregister_entry(GTK_ENTRY(page->entry_default_bcc));
if (page->entry_default_replyto)
address_completion_unregister_entry(GTK_ENTRY(page->entry_default_replyto));
}
/** \brief Save the prefs in page to folder.
*
* If the folder is not the one specified in page->item, then only those properties
* that have the relevant 'apply to sub folders' button checked are saved
*/
static void compose_save_folder_prefs(FolderItem *folder, FolderItemComposePage *page)
{
FolderItemPrefs *prefs = folder->prefs;
gboolean all = FALSE;
if (folder->path == NULL)
return;
if (page->item == folder)
all = TRUE;
cm_return_if_fail(prefs != NULL);
if (item_protocol(folder) != A_NNTP) {
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->request_return_receipt_rec_checkbtn))) {
prefs->request_return_receipt =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_request_return_receipt));
/* MIGRATION */
folder->ret_rcpt = prefs->request_return_receipt;
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->save_copy_to_folder_rec_checkbtn))) {
prefs->save_copy_to_folder =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_save_copy_to_folder));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_to_rec_checkbtn))) {
prefs->enable_default_to =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_default_to));
ASSIGN_STRING(prefs->default_to,
gtk_editable_get_chars(GTK_EDITABLE(page->entry_default_to), 0, -1));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_reply_to_rec_checkbtn))) {
prefs->enable_default_reply_to =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_default_reply_to));
ASSIGN_STRING(prefs->default_reply_to,
gtk_editable_get_chars(GTK_EDITABLE(page->entry_default_reply_to), 0, -1));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_cc_rec_checkbtn))) {
prefs->enable_default_cc =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_default_cc));
ASSIGN_STRING(prefs->default_cc,
gtk_editable_get_chars(GTK_EDITABLE(page->entry_default_cc), 0, -1));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_bcc_rec_checkbtn))) {
prefs->enable_default_bcc =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_default_bcc));
ASSIGN_STRING(prefs->default_bcc,
gtk_editable_get_chars(GTK_EDITABLE(page->entry_default_bcc), 0, -1));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_replyto_rec_checkbtn))) {
prefs->enable_default_replyto =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_default_replyto));
ASSIGN_STRING(prefs->default_replyto,
gtk_editable_get_chars(GTK_EDITABLE(page->entry_default_replyto), 0, -1));
}
} else {
prefs->request_return_receipt = FALSE;
prefs->save_copy_to_folder = FALSE;
prefs->enable_default_to = FALSE;
prefs->enable_default_reply_to = FALSE;
prefs->enable_default_cc = FALSE;
prefs->enable_default_bcc = FALSE;
prefs->enable_default_replyto = FALSE;
}
if (all || gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON(page->default_account_rec_checkbtn))) {
prefs->enable_default_account =
gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON(page->checkbtn_enable_default_account));
prefs->default_account = combobox_get_active_data(
GTK_COMBO_BOX(page->optmenu_default_account));
}
#if USE_ENCHANT
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_dictionary_rec_checkbtn))) {
prefs->enable_default_dictionary =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_enable_default_dictionary));
ASSIGN_STRING(prefs->default_dictionary,
gtkaspell_get_dictionary_menu_active_item(
GTK_COMBO_BOX(page->combo_default_dictionary)));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_alt_dictionary_rec_checkbtn))) {
prefs->enable_default_alt_dictionary =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_enable_default_alt_dictionary));
ASSIGN_STRING(prefs->default_alt_dictionary,
gtkaspell_get_dictionary_menu_active_item(
GTK_COMBO_BOX(page->combo_default_alt_dictionary)));
}
#endif
folder_item_prefs_save_config(folder);
}
static gboolean compose_save_recurse_func(GNode *node, gpointer data)
{
FolderItem *item = (FolderItem *) node->data;
FolderItemComposePage *page = (FolderItemComposePage *) data;
cm_return_val_if_fail(item != NULL, TRUE);
cm_return_val_if_fail(page != NULL, TRUE);
compose_save_folder_prefs(item, page);
/* optimise by not continuing if none of the 'apply to sub folders'
check boxes are selected - and optimise the checking by only doing
it once */
if ((node == page->item->node) && item_protocol(item) != A_NNTP &&
!(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->request_return_receipt_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->save_copy_to_folder_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_to_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_account_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_cc_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_bcc_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_replyto_rec_checkbtn)) ||
#if USE_ENCHANT
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_dictionary_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_alt_dictionary_rec_checkbtn)) ||
#endif
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_reply_to_rec_checkbtn))
))
return TRUE;
else if ((node == page->item->node) && item_protocol(item) == A_NNTP &&
!(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_account_rec_checkbtn))
#if USE_ENCHANT
|| gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_dictionary_rec_checkbtn))
|| gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_alt_dictionary_rec_checkbtn))
#endif
))
return TRUE;
else
return FALSE;
}
static void prefs_folder_item_compose_save_func(PrefsPage *page_)
{
FolderItemComposePage *page = (FolderItemComposePage *) page_;
g_node_traverse(page->item->node, G_PRE_ORDER, G_TRAVERSE_ALL,
-1, compose_save_recurse_func, page);
}
static void prefs_folder_item_templates_create_widget_func(PrefsPage * page_,
GtkWindow * window,
gpointer data)
{
FolderItemTemplatesPage *page = (FolderItemTemplatesPage *) page_;
FolderItem *item = (FolderItem *) data;
GtkWidget *notebook;
GtkWidget *vbox;
GtkWidget *page_vbox;
GtkWidget *no_save_warning;
GtkWidget *new_msg_format_rec_checkbtn;
GtkWidget *reply_format_rec_checkbtn;
GtkWidget *forward_format_rec_checkbtn;
GtkWidget *hbox;
GtkWidget *vbox_format;
page->item = item;
page_vbox = gtk_vbox_new (FALSE, 0);
gtk_container_set_border_width (GTK_CONTAINER (page_vbox), VBOX_BORDER);
gtk_widget_show (page_vbox);
if (!can_save) {
no_save_warning = gtk_label_new(
_("<i>These preferences will not be saved as this folder "
"is a top-level folder. However, you can set them for the "
"whole mailbox tree by using \"Apply to subfolders\".</i>"));
gtk_label_set_use_markup(GTK_LABEL(no_save_warning), TRUE);
gtk_label_set_line_wrap(GTK_LABEL(no_save_warning), TRUE);
gtk_misc_set_alignment(GTK_MISC(no_save_warning), 0.0, 0.5);
gtk_box_pack_start(GTK_BOX(page_vbox), no_save_warning, FALSE, FALSE, 0);
}
/* Notebook */
notebook = gtk_notebook_new();
gtk_widget_show(notebook);
gtk_box_pack_start(GTK_BOX(page_vbox), notebook, TRUE, TRUE, 4);
/* compose format */
vbox = gtk_vbox_new (FALSE, VSPACING);
gtk_widget_show (vbox);
gtk_container_set_border_width (GTK_CONTAINER (vbox), VBOX_BORDER);
quotefmt_create_new_msg_fmt_widgets(
window,
vbox,
&page->checkbtn_compose_with_format,
&page->compose_override_from_format,
&page->compose_subject_format,
&page->compose_body_format,
FALSE, FALSE);
address_completion_register_entry(GTK_ENTRY(page->compose_override_from_format),
TRUE);
vbox_format = gtk_widget_get_parent(
gtk_widget_get_parent(page->compose_body_format));
hbox = gtk_hbox_new (FALSE, 0);
gtk_box_pack_end (GTK_BOX(vbox_format), hbox, FALSE, FALSE, 0);
quotefmt_add_info_button(window, hbox);
new_msg_format_rec_checkbtn = gtk_check_button_new_with_label(
_("Apply to subfolders"));
gtk_box_pack_end (GTK_BOX(hbox), new_msg_format_rec_checkbtn, FALSE, FALSE, 0);
gtk_notebook_append_page(GTK_NOTEBOOK(notebook), vbox, gtk_label_new(_("Compose")));
/* reply format */
vbox = gtk_vbox_new (FALSE, VSPACING);
gtk_widget_show (vbox);
gtk_container_set_border_width (GTK_CONTAINER (vbox), VBOX_BORDER);
quotefmt_create_reply_fmt_widgets(
window,
vbox,
&page->checkbtn_reply_with_format,
&page->reply_override_from_format,
&page->reply_quotemark,
&page->reply_body_format,
FALSE, FALSE);
address_completion_register_entry(GTK_ENTRY(page->reply_override_from_format),
TRUE);
vbox_format = gtk_widget_get_parent(
gtk_widget_get_parent(page->reply_body_format));
hbox = gtk_hbox_new (FALSE, 0);
gtk_box_pack_end (GTK_BOX(vbox_format), hbox, FALSE, FALSE, 0);
quotefmt_add_info_button(window, hbox);
reply_format_rec_checkbtn = gtk_check_button_new_with_label(
_("Apply to subfolders"));
gtk_box_pack_end (GTK_BOX(hbox), reply_format_rec_checkbtn, FALSE, FALSE, 0);
gtk_notebook_append_page(GTK_NOTEBOOK(notebook), vbox, gtk_label_new(_("Reply")));
/* forward format */
vbox = gtk_vbox_new (FALSE, VSPACING);
gtk_widget_show (vbox);
gtk_container_set_border_width (GTK_CONTAINER (vbox), VBOX_BORDER);
quotefmt_create_forward_fmt_widgets(
window,
vbox,
&page->checkbtn_forward_with_format,
&page->forward_override_from_format,
&page->forward_quotemark,
&page->forward_body_format,
FALSE, FALSE);
address_completion_register_entry(GTK_ENTRY(page->forward_override_from_format),
TRUE);
vbox_format = gtk_widget_get_parent(
gtk_widget_get_parent(page->forward_body_format));
hbox = gtk_hbox_new (FALSE, 0);
gtk_box_pack_end (GTK_BOX(vbox_format), hbox, FALSE, FALSE, 0);
quotefmt_add_info_button(window, hbox);
forward_format_rec_checkbtn = gtk_check_button_new_with_label(
_("Apply to subfolders"));
gtk_box_pack_end (GTK_BOX(hbox), forward_format_rec_checkbtn, FALSE, FALSE, 0);
gtk_notebook_append_page(GTK_NOTEBOOK(notebook), vbox, gtk_label_new(_("Forward")));
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(page->checkbtn_compose_with_format),
item->prefs->compose_with_format);
pref_set_entry_from_pref(GTK_ENTRY(page->compose_override_from_format),
item->prefs->compose_override_from_format);
pref_set_entry_from_pref(GTK_ENTRY(page->compose_subject_format),
item->prefs->compose_subject_format);
pref_set_textview_from_pref(GTK_TEXT_VIEW(page->compose_body_format),
item->prefs->compose_body_format);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(page->checkbtn_reply_with_format),
item->prefs->reply_with_format);
pref_set_entry_from_pref(GTK_ENTRY(page->reply_quotemark),
item->prefs->reply_quotemark);
pref_set_entry_from_pref(GTK_ENTRY(page->reply_override_from_format),
item->prefs->reply_override_from_format);
pref_set_textview_from_pref(GTK_TEXT_VIEW(page->reply_body_format),
item->prefs->reply_body_format);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(page->checkbtn_forward_with_format),
item->prefs->forward_with_format);
pref_set_entry_from_pref(GTK_ENTRY(page->forward_quotemark),
item->prefs->forward_quotemark);
pref_set_entry_from_pref(GTK_ENTRY(page->forward_override_from_format),
item->prefs->forward_override_from_format);
pref_set_textview_from_pref(GTK_TEXT_VIEW(page->forward_body_format),
item->prefs->forward_body_format);
gtk_widget_show_all(page_vbox);
page->window = GTK_WIDGET(window);
page->new_msg_format_rec_checkbtn = new_msg_format_rec_checkbtn;
page->reply_format_rec_checkbtn = reply_format_rec_checkbtn;
page->forward_format_rec_checkbtn = forward_format_rec_checkbtn;
page->page.widget = page_vbox;
}
static void prefs_folder_item_templates_destroy_widget_func(PrefsPage *page_)
{
FolderItemTemplatesPage *page = (FolderItemTemplatesPage *) page_;
if (page->compose_override_from_format)
address_completion_unregister_entry(GTK_ENTRY(page->compose_override_from_format));
if (page->reply_override_from_format)
address_completion_unregister_entry(GTK_ENTRY(page->reply_override_from_format));
if (page->forward_override_from_format)
address_completion_unregister_entry(GTK_ENTRY(page->forward_override_from_format));
}
/** \brief Save the prefs in page to folder.
*
* If the folder is not the one specified in page->item, then only those properties
* that have the relevant 'apply to sub folders' button checked are saved
*/
static void templates_save_folder_prefs(FolderItem *folder, FolderItemTemplatesPage *page)
{
FolderItemPrefs *prefs = folder->prefs;
gboolean all = FALSE;
if (folder->path == NULL)
return;
if (page->item == folder)
all = TRUE;
cm_return_if_fail(prefs != NULL);
/* save and check formats */
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->new_msg_format_rec_checkbtn))) {
prefs->compose_with_format =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_compose_with_format));
prefs->compose_override_from_format = pref_get_pref_from_entry(
GTK_ENTRY(page->compose_override_from_format));
prefs->compose_subject_format = pref_get_pref_from_entry(
GTK_ENTRY(page->compose_subject_format));
prefs->compose_body_format = pref_get_pref_from_textview(
GTK_TEXT_VIEW(page->compose_body_format));
quotefmt_check_new_msg_formats(prefs->compose_with_format,
prefs->compose_override_from_format,
prefs->compose_subject_format,
prefs->compose_body_format);
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->reply_format_rec_checkbtn))) {
prefs->reply_with_format =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_reply_with_format));
prefs->reply_quotemark = gtk_editable_get_chars(
GTK_EDITABLE(page->reply_quotemark), 0, -1);
prefs->reply_override_from_format = pref_get_pref_from_entry(
GTK_ENTRY(page->reply_override_from_format));
prefs->reply_body_format = pref_get_pref_from_textview(
GTK_TEXT_VIEW(page->reply_body_format));
quotefmt_check_reply_formats(prefs->reply_with_format,
prefs->reply_override_from_format,
prefs->reply_quotemark,
prefs->reply_body_format);
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->forward_format_rec_checkbtn))) {
prefs->forward_with_format =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_forward_with_format));
prefs->forward_quotemark = gtk_editable_get_chars(
GTK_EDITABLE(page->forward_quotemark), 0, -1);
prefs->forward_override_from_format = pref_get_pref_from_entry(
GTK_ENTRY(page->forward_override_from_format));
prefs->forward_body_format = pref_get_pref_from_textview(
GTK_TEXT_VIEW(page->forward_body_format));
quotefmt_check_forward_formats(prefs->forward_with_format,
prefs->forward_override_from_format,
prefs->forward_quotemark,
prefs->forward_body_format);
}
folder_item_prefs_save_config(folder);
}
static gboolean templates_save_recurse_func(GNode *node, gpointer data)
{
FolderItem *item = (FolderItem *) node->data;
FolderItemTemplatesPage *page = (FolderItemTemplatesPage *) data;
cm_return_val_if_fail(item != NULL, TRUE);
cm_return_val_if_fail(page != NULL, TRUE);
templates_save_folder_prefs(item, page);
/* optimise by not continuing if none of the 'apply to sub folders'
check boxes are selected - and optimise the checking by only doing
it once */
if ((node == page->item->node) &&
!(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->new_msg_format_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->reply_format_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->forward_format_rec_checkbtn))))
return TRUE;
else
return FALSE;
return FALSE;
}
static void prefs_folder_item_templates_save_func(PrefsPage *page_)
{
FolderItemTemplatesPage *page = (FolderItemTemplatesPage *) page_;
g_node_traverse(page->item->node, G_PRE_ORDER, G_TRAVERSE_ALL,
-1, templates_save_recurse_func, page);
}
static gint prefs_folder_item_chmod_mode(gchar *folder_chmod)
{
gint newmode = 0;
gchar *tmp;
if (folder_chmod) {
newmode = strtol(folder_chmod, &tmp, 8);
if (!(*(folder_chmod) && !(*tmp)))
newmode = 0;
}
return newmode;
}
static void folder_color_set_dialog(GtkWidget *widget, gpointer data)
{
FolderItemGeneralPage *page = (FolderItemGeneralPage *) data;
gint rgbcolor;
rgbcolor = colorsel_select_color_rgb(_("Pick color for folder"),
page->folder_color);
gtkut_set_widget_bgcolor_rgb(page->folder_color_btn, rgbcolor);
page->folder_color = rgbcolor;
}
static void clean_cache_cb(GtkWidget *widget, gpointer data)
{
FolderItemGeneralPage *page = (FolderItemGeneralPage *) data;
FolderItem *item = page->item;
gboolean was_open = FALSE;
FolderView *folderview = NULL;
if (alertpanel_full(_("Discard cache"),
_("Do you really want to discard the local cached "
"data for this folder?"),
GTK_STOCK_CANCEL, _("+Discard"), NULL, FALSE,
NULL, ALERT_WARNING, G_ALERTDEFAULT)
!= G_ALERTALTERNATE)
return;
if (mainwindow_get_mainwindow())
folderview = mainwindow_get_mainwindow()->folderview;
if (folderview && item->opened) {
folderview_close_opened(folderview);
was_open = TRUE;
}
folder_item_discard_cache(item);
if (was_open)
folderview_select(folderview,item);
}
#ifndef G_OS_WIN32
static regex_t *summary_compile_simplify_regexp(gchar *simplify_subject_regexp)
{
int err;
gchar buf[BUFFSIZE];
regex_t *preg = NULL;
preg = g_new0(regex_t, 1);
err = string_match_precompile(simplify_subject_regexp,
preg, REG_EXTENDED);
if (err) {
regerror(err, preg, buf, BUFFSIZE);
g_free(preg);
preg = NULL;
}
return preg;
}
static void folder_regexp_test_cb(GtkWidget *widget, gpointer data)
{
#if !GTK_CHECK_VERSION(3, 0, 0)
static GdkColor red;
static gboolean colors_initialised = FALSE;
#else
static GdkColor red = { (guint32)0, (guint16)0xff, (guint16)0x70, (guint16)0x70 };
#endif
static gchar buf[BUFFSIZE];
FolderItemGeneralPage *page = (FolderItemGeneralPage *)data;
gchar *test_string, *regexp;
regex_t *preg;
regexp = g_strdup(gtk_entry_get_text(GTK_ENTRY(page->entry_simplify_subject)));
test_string = g_strdup(gtk_entry_get_text(GTK_ENTRY(page->entry_regexp_test_string)));
if (!regexp || !regexp[0]) {
gtk_widget_modify_base(page->entry_simplify_subject,
GTK_STATE_NORMAL, NULL);
if (test_string)
gtk_entry_set_text(GTK_ENTRY(page->entry_regexp_test_result), test_string);
g_free(test_string);
g_free(regexp);
return;
}
if (!test_string || !test_string[0]) {
g_free(test_string);
g_free(regexp);
return;
}
#if !GTK_CHECK_VERSION(3, 0, 0)
if (!colors_initialised) {
gdk_color_parse("#ff7070", &red);
colors_initialised = gdk_colormap_alloc_color(
gdk_colormap_get_system(), &red, FALSE, TRUE);
}
#endif
preg = summary_compile_simplify_regexp(regexp);
#if !GTK_CHECK_VERSION(3, 0, 0)
if (colors_initialised)
gtk_widget_modify_base(page->entry_simplify_subject,
GTK_STATE_NORMAL, preg ? NULL : &red);
#endif
if (preg != NULL) {
string_remove_match(buf, BUFFSIZE, test_string, preg);
gtk_entry_set_text(GTK_ENTRY(page->entry_regexp_test_result), buf);
regfree(preg);
g_free(preg);
}
g_free(test_string);
g_free(regexp);
}
static gchar *folder_regexp_get_subject_example(void)
{
MsgInfo *msginfo_selected;
SummaryView *summaryview = NULL;
if (!mainwindow_get_mainwindow())
return NULL;
summaryview = mainwindow_get_mainwindow()->summaryview;
msginfo_selected = summary_get_selected_msg(summaryview);
return msginfo_selected ? g_strdup(msginfo_selected->subject) : NULL;
}
static void folder_regexp_set_subject_example_cb(GtkWidget *widget, gpointer data)
{
FolderItemGeneralPage *page = (FolderItemGeneralPage *)data;
if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_simplify_subject))) {
gchar *subject = folder_regexp_get_subject_example();
if (subject) {
gtk_entry_set_text(GTK_ENTRY(page->entry_regexp_test_string), subject);
g_free(subject);
}
}
}
#endif
static void register_general_page()
{
static gchar *pfi_general_path[2];
static FolderItemGeneralPage folder_item_general_page;
pfi_general_path[0] = _("General");
pfi_general_path[1] = NULL;
folder_item_general_page.page.path = pfi_general_path;
folder_item_general_page.page.create_widget = prefs_folder_item_general_create_widget_func;
folder_item_general_page.page.destroy_widget = prefs_folder_item_general_destroy_widget_func;
folder_item_general_page.page.save_page = prefs_folder_item_general_save_func;
prefs_folder_item_register_page((PrefsPage *) &folder_item_general_page, NULL);
}
static void register_compose_page(void)
{
static gchar *pfi_compose_path[2];
static FolderItemComposePage folder_item_compose_page;
pfi_compose_path[0] = _("Compose");
pfi_compose_path[1] = NULL;
folder_item_compose_page.page.path = pfi_compose_path;
folder_item_compose_page.page.create_widget = prefs_folder_item_compose_create_widget_func;
folder_item_compose_page.page.destroy_widget = prefs_folder_item_compose_destroy_widget_func;
folder_item_compose_page.page.save_page = prefs_folder_item_compose_save_func;
prefs_folder_item_register_page((PrefsPage *) &folder_item_compose_page, NULL);
}
static void register_templates_page(void)
{
static gchar *pfi_templates_path[2];
static FolderItemTemplatesPage folder_item_templates_page;
pfi_templates_path[0] = _("Templates");
pfi_templates_path[1] = NULL;
folder_item_templates_page.page.path = pfi_templates_path;
folder_item_templates_page.page.create_widget = prefs_folder_item_templates_create_widget_func;
folder_item_templates_page.page.destroy_widget = prefs_folder_item_templates_destroy_widget_func;
folder_item_templates_page.page.save_page = prefs_folder_item_templates_save_func;
prefs_folder_item_register_page((PrefsPage *) &folder_item_templates_page, NULL);
}
static GSList *prefs_pages = NULL;
static void prefs_folder_item_address_completion_start(PrefsWindow *window)
{
address_completion_start(window->window);
}
static void prefs_folder_item_address_completion_end(PrefsWindow *window)
{
address_completion_end(window->window);
}
void prefs_folder_item_open(FolderItem *item)
{
gchar *id, *title;
GSList *pages;
if (prefs_pages == NULL) {
register_general_page();
register_compose_page();
register_templates_page();
}
if (item->path) {
id = folder_item_get_identifier (item);
can_save = TRUE;
} else {
id = g_strdup(item->name);
can_save = FALSE;
}
pages = g_slist_concat(
g_slist_copy(prefs_pages),
g_slist_copy(item->folder->klass->prefs_pages));
title = g_strdup_printf (_("Properties for folder %s"), id);
g_free (id);
prefswindow_open(title, pages, item,
&prefs_common.folderitemwin_width, &prefs_common.folderitemwin_height,
prefs_folder_item_address_completion_start,
NULL,
prefs_folder_item_address_completion_end);
g_slist_free(pages);
g_free (title);
}
void prefs_folder_item_register_page(PrefsPage *page, FolderClass *klass)
{
if (klass != NULL)
klass->prefs_pages = g_slist_append(klass->prefs_pages, page);
else
prefs_pages = g_slist_append(prefs_pages, page);
}
void prefs_folder_item_unregister_page(PrefsPage *page, FolderClass *klass)
{
if (klass != NULL)
klass->prefs_pages = g_slist_remove(klass->prefs_pages, page);
else
prefs_pages = g_slist_remove(prefs_pages, page);
}
|
buzz/claws
|
src/prefs_folder_item.c
|
C
|
gpl-3.0
| 71,677
|
/******************************************************************************
* NTRU Cryptography Reference Source Code
* Copyright (c) 2009-2013, by Security Innovation, Inc. All rights reserved.
*
* ntru_crypto_hash.c is a component of ntru-crypto.
*
* Copyright (C) 2009-2013 Security Innovation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*****************************************************************************/
/******************************************************************************
*
* File: ntru_crypto_hash.c
*
* Contents: Routines implementing the hash object abstraction.
*
*****************************************************************************/
#include "ntru_crypto.h"
#include "ntru_crypto_hash.h"
typedef uint32_t (*NTRU_CRYPTO_HASH_INIT_FN)(
void *c);
typedef uint32_t (*NTRU_CRYPTO_HASH_UPDATE_FN)(
void *c,
void const *data,
uint32_t len);
typedef uint32_t (*NTRU_CRYPTO_HASH_FINAL_FN)(
void *c,
void *md);
typedef uint32_t (*NTRU_CRYPTO_HASH_DIGEST_FN)(
void const *data,
uint32_t len,
void *md);
typedef struct _NTRU_CRYPTO_HASH_ALG_PARAMS {
uint8_t algid;
uint16_t block_length;
uint16_t digest_length;
NTRU_CRYPTO_HASH_INIT_FN init;
NTRU_CRYPTO_HASH_UPDATE_FN update;
NTRU_CRYPTO_HASH_FINAL_FN final;
NTRU_CRYPTO_HASH_DIGEST_FN digest;
} NTRU_CRYPTO_HASH_ALG_PARAMS;
static NTRU_CRYPTO_HASH_ALG_PARAMS const algs_params[] = {
{
NTRU_CRYPTO_HASH_ALGID_SHA1,
SHA_1_BLK_LEN,
SHA_1_MD_LEN,
(NTRU_CRYPTO_HASH_INIT_FN) SHA_1_INIT_FN,
(NTRU_CRYPTO_HASH_UPDATE_FN) SHA_1_UPDATE_FN,
(NTRU_CRYPTO_HASH_FINAL_FN) SHA_1_FINAL_FN,
(NTRU_CRYPTO_HASH_DIGEST_FN) SHA_1_DIGEST_FN,
},
{
NTRU_CRYPTO_HASH_ALGID_SHA256,
SHA_256_BLK_LEN,
SHA_256_MD_LEN,
(NTRU_CRYPTO_HASH_INIT_FN) SHA_256_INIT_FN,
(NTRU_CRYPTO_HASH_UPDATE_FN) SHA_256_UPDATE_FN,
(NTRU_CRYPTO_HASH_FINAL_FN) SHA_256_FINAL_FN,
(NTRU_CRYPTO_HASH_DIGEST_FN) SHA_256_DIGEST_FN,
},
};
static int const numalgs = (sizeof(algs_params)/sizeof(algs_params[0]));
/* get_alg_params
*
* Return a pointer to the hash algorithm parameters for the hash algorithm
* specified, by looking for algid in the global algs_params table.
* If not found, return NULL.
*/
static NTRU_CRYPTO_HASH_ALG_PARAMS const *
get_alg_params(
NTRU_CRYPTO_HASH_ALGID algid) /* in - the hash algorithm to find */
{
int i;
for (i = 0; i < numalgs; i++)
{
if (algs_params[i].algid == algid)
{
return &algs_params[i];
}
}
return NULL;
}
/* ntru_crypto_hash_set_alg
*
* Sets the hash algorithm for the hash context. This must be called before
* any calls to ntru_crypto_hash_block_length(),
* ntru_crypto_hash_digest_length(), or ntru_crypto_hash_init() are made.
*
* Returns NTRU_CRYPTO_HASH_OK on success.
* Returns NTRU_CRYPTO_HASH_BAD_ALG if the specified algorithm is not supported.
*/
uint32_t
ntru_crypto_hash_set_alg(
NTRU_CRYPTO_HASH_ALGID algid, /* in - hash algorithm to be used */
NTRU_CRYPTO_HASH_CTX *c) /* in/out - pointer to the hash context */
{
if (!c)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_PARAMETER);
}
c->alg_params = get_alg_params(algid);
if (!c->alg_params)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_ALG);
}
HASH_RET(NTRU_CRYPTO_HASH_OK);
}
/* ntru_crypto_hash_block_length
*
* Gets the number of bytes in an input block for the hash algorithm
* specified in the hash context. The hash algorithm must have been set
* in the hash context with a call to ntru_crypto_hash_set_alg() prior to
* calling this function.
*
* Returns NTRU_CRYPTO_HASH_OK on success.
* Returns NTRU_CRYPTO_HASH_BAD_PARAMETER if inappropriate NULL pointers are
* passed.
* Returns NTRU_CRYPTO_HASH_BAD_ALG if the algorithm has not been set.
*/
uint32_t
ntru_crypto_hash_block_length(
NTRU_CRYPTO_HASH_CTX *c, /* in - pointer to the hash context */
uint16_t *blk_len) /* out - address for block length in bytes */
{
if (!c || !blk_len)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_PARAMETER);
}
if (!c->alg_params)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_ALG);
}
*blk_len = c->alg_params->block_length;
HASH_RET(NTRU_CRYPTO_HASH_OK);
}
/* ntru_crypto_hash_digest_length
*
* Gets the number of bytes needed to hold the message digest for the
* hash algorithm specified in the hash context. The algorithm must have
* been set in the hash context with a call to ntru_crypto_hash_set_alg() prior
* to calling this function.
*
* Returns NTRU_CRYPTO_HASH_OK on success.
* Returns NTRU_CRYPTO_HASH_BAD_PARAMETER if inappropriate NULL pointers are
* passed.
* Returns NTRU_CRYPTO_HASH_BAD_ALG if the algorithm has not been set.
*/
uint32_t
ntru_crypto_hash_digest_length(
NTRU_CRYPTO_HASH_CTX const *c, /* in - pointer to the hash context */
uint16_t *md_len) /* out - addr for digest length in bytes */
{
if (!c || !md_len)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_PARAMETER);
}
if (!c->alg_params)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_ALG);
}
*md_len = c->alg_params->digest_length;
HASH_RET(NTRU_CRYPTO_HASH_OK);
}
/* ntru_crypto_hash_init
*
* This routine performs standard initialization of the hash state.
*
* Returns NTRU_CRYPTO_HASH_OK on success.
* Returns NTRU_CRYPTO_HASH_FAIL with corrupted context.
* Returns NTRU_CRYPTO_HASH_BAD_PARAMETER if inappropriate NULL pointers are
* passed.
* Returns NTRU_CRYPTO_HASH_BAD_ALG if the algorithm has not been set.
*/
uint32_t
ntru_crypto_hash_init(
NTRU_CRYPTO_HASH_CTX *c) /* in/out - pointer to hash context */
{
if (!c)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_PARAMETER);
}
if (!c->alg_params)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_ALG);
}
return c->alg_params->init(&c->alg_ctx);
}
/* ntru_crypto_hash_update
*
* This routine processes input data and updates the hash calculation.
*
* Returns NTRU_CRYPTO_HASH_OK on success.
* Returns NTRU_CRYPTO_HASH_FAIL with corrupted context.
* Returns NTRU_CRYPTO_HASH_BAD_PARAMETER if inappropriate NULL pointers are
* passed.
* Returns NTRU_CRYPTO_HASH_OVERFLOW if too much text has been fed to the
* hash algorithm. The size limit is dependent on the hash algorithm,
* and not all algorithms have this limit.
* Returns NTRU_CRYPTO_HASH_BAD_ALG if the algorithm has not been set.
*/
uint32_t
ntru_crypto_hash_update(
NTRU_CRYPTO_HASH_CTX *c, /* in/out - pointer to hash context */
uint8_t const *data, /* in - pointer to input data */
uint32_t data_len) /* in - number of bytes of input data */
{
if (!c || (data_len && !data))
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_PARAMETER);
}
if (!c->alg_params)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_ALG);
}
return c->alg_params->update(&c->alg_ctx, data, data_len);
}
/* ntru_crypto_hash_final
*
* This routine completes the hash calculation and returns the message digest.
*
* Returns NTRU_CRYPTO_HASH_OK on success.
* Returns NTRU_CRYPTO_HASH_FAIL with corrupted context.
* Returns NTRU_CRYPTO_HASH_BAD_PARAMETER if inappropriate NULL pointers are
* passed.
* Returns NTRU_CRYPTO_HASH_BAD_ALG if the algorithm has not been set.
*/
uint32_t
ntru_crypto_hash_final(
NTRU_CRYPTO_HASH_CTX *c, /* in/out - pointer to hash context */
uint8_t *md) /* out - address for message digest */
{
if (!c || !md)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_PARAMETER);
}
if (!c->alg_params)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_ALG);
}
return c->alg_params->final(&c->alg_ctx, md);
}
/* ntru_crypto_hash_digest
*
* This routine computes a message digest. It is assumed that the
* output buffer md is large enough to hold the output (see
* ntru_crypto_hash_digest_length)
*
* Returns NTRU_CRYPTO_HASH_OK on success.
* Returns NTRU_CRYPTO_HASH_FAIL with corrupted context.
* Returns NTRU_CRYPTO_HASH_BAD_PARAMETER if inappropriate NULL pointers are
* passed.
* Returns NTRU_CRYPTO_HASH_OVERFLOW if too much text has been fed to the
* hash algorithm. The size limit is dependent on the hash algorithm,
* and not all algorithms have this limit.
* Returns NTRU_CRYPTO_HASH_BAD_ALG if the specified algorithm is not supported.
*/
uint32_t
ntru_crypto_hash_digest(
NTRU_CRYPTO_HASH_ALGID algid, /* in - the hash algorithm to use */
uint8_t const *data, /* in - pointer to input data */
uint32_t data_len, /* in - number of bytes of input data */
uint8_t *md) /* out - address for message digest */
{
NTRU_CRYPTO_HASH_ALG_PARAMS const *alg_params = get_alg_params(algid);
if (!alg_params)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_ALG);
}
if ((data_len && !data) || !md)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_PARAMETER);
}
return alg_params->digest(data, data_len, md);
}
|
jschanck-si/NTRUEncrypt
|
src/ntru_crypto_hash.c
|
C
|
gpl-3.0
| 10,074
|
#include "config.h"
#include "syshead.h"
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <setjmp.h>
#include <cmocka.h>
#include <assert.h>
#include "argv.h"
#include "buffer.h"
/* Defines for use in the tests and the mock parse_line() */
#define PATH1 "/s p a c e"
#define PATH2 "/foo bar/baz"
#define PARAM1 "param1"
#define PARAM2 "param two"
#define SCRIPT_CMD "\"" PATH1 PATH2 "\"" PARAM1 "\"" PARAM2 "\""
int
__wrap_parse_line(const char *line, char **p, const int n, const char *file,
const int line_num, int msglevel, struct gc_arena *gc)
{
p[0] = PATH1 PATH2;
p[1] = PARAM1;
p[2] = PARAM2;
return 3;
}
static void
argv_printf__multiple_spaces_in_format__parsed_as_one(void **state)
{
struct argv a = argv_new();
argv_printf(&a, " %s %s %d ", PATH1, PATH2, 42);
assert_int_equal(a.argc, 3);
argv_reset(&a);
}
static void
argv_printf_cat__multiple_spaces_in_format__parsed_as_one(void **state)
{
struct argv a = argv_new();
argv_printf(&a, "%s ", PATH1);
argv_printf_cat(&a, " %s %s", PATH2, PARAM1);
assert_int_equal(a.argc, 3);
argv_reset(&a);
}
static void
argv_printf__combined_path_with_spaces__argc_correct(void **state)
{
struct argv a = argv_new();
argv_printf(&a, "%s%sc", PATH1, PATH2);
assert_int_equal(a.argc, 1);
argv_printf(&a, "%s%sc %d", PATH1, PATH2, 42);
assert_int_equal(a.argc, 2);
argv_printf(&a, "foo %s%sc %s x y", PATH2, PATH1, "foo");
assert_int_equal(a.argc, 5);
argv_reset(&a);
}
static void
argv_parse_cmd__command_string__argc_correct(void **state)
{
struct argv a = argv_new();
argv_parse_cmd(&a, SCRIPT_CMD);
assert_int_equal(a.argc, 3);
argv_reset(&a);
}
static void
argv_parse_cmd__command_and_extra_options__argc_correct(void **state)
{
struct argv a = argv_new();
argv_parse_cmd(&a, SCRIPT_CMD);
argv_printf_cat(&a, "bar baz %d %s", 42, PATH1);
assert_int_equal(a.argc, 7);
argv_reset(&a);
}
static void
argv_printf_cat__used_twice__argc_correct(void **state)
{
struct argv a = argv_new();
argv_printf(&a, "%s %s %s", PATH1, PATH2, PARAM1);
argv_printf_cat(&a, "%s", PARAM2);
argv_printf_cat(&a, "foo");
assert_int_equal(a.argc, 5);
argv_reset(&a);
}
static void
argv_str__multiple_argv__correct_output(void **state)
{
struct argv a = argv_new();
struct gc_arena gc = gc_new();
const char *output;
argv_printf(&a, "%s%sc", PATH1, PATH2);
argv_printf_cat(&a, "%s", PARAM1);
argv_printf_cat(&a, "%s", PARAM2);
output = argv_str(&a, &gc, PA_BRACKET);
assert_string_equal(output, "[" PATH1 PATH2 "] [" PARAM1 "] [" PARAM2 "]");
argv_reset(&a);
gc_free(&gc);
}
static void
argv_insert_head__empty_argv__head_only(void **state)
{
struct argv a = argv_new();
struct argv b;
b = argv_insert_head(&a, PATH1);
assert_int_equal(b.argc, 1);
assert_string_equal(b.argv[0], PATH1);
argv_reset(&b);
argv_reset(&a);
}
static void
argv_insert_head__non_empty_argv__head_added(void **state)
{
struct argv a = argv_new();
struct argv b;
int i;
argv_printf(&a, "%s", PATH2);
b = argv_insert_head(&a, PATH1);
assert_int_equal(b.argc, a.argc + 1);
for (i = 0; i < b.argc; i++) {
if (i == 0)
{
assert_string_equal(b.argv[i], PATH1);
}
else
{
assert_string_equal(b.argv[i], a.argv[i - 1]);
}
}
argv_reset(&b);
argv_reset(&a);
}
int
main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(argv_printf__multiple_spaces_in_format__parsed_as_one),
cmocka_unit_test(argv_printf_cat__multiple_spaces_in_format__parsed_as_one),
cmocka_unit_test(argv_printf__combined_path_with_spaces__argc_correct),
cmocka_unit_test(argv_parse_cmd__command_string__argc_correct),
cmocka_unit_test(argv_parse_cmd__command_and_extra_options__argc_correct),
cmocka_unit_test(argv_printf_cat__used_twice__argc_correct),
cmocka_unit_test(argv_str__multiple_argv__correct_output),
cmocka_unit_test(argv_insert_head__non_empty_argv__head_added),
};
return cmocka_run_group_tests_name("argv", tests, NULL, NULL);
}
|
anoidgit/padavan
|
trunk/user/openvpn/openvpn-2.4.x/tests/unit_tests/openvpn/test_argv.c
|
C
|
gpl-3.0
| 4,359
|
/*
* Unix SMB/CIFS implementation.
* NetApi LocalGroup Support
* Copyright (C) Guenther Deschner 2008
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include "includes.h"
#include "librpc/gen_ndr/libnetapi.h"
#include "lib/netapi/netapi.h"
#include "lib/netapi/netapi_private.h"
#include "lib/netapi/libnetapi.h"
#include "rpc_client/rpc_client.h"
#include "../librpc/gen_ndr/ndr_samr_c.h"
#include "../librpc/gen_ndr/ndr_lsa_c.h"
#include "rpc_client/cli_lsarpc.h"
#include "rpc_client/init_lsa.h"
#include "../libcli/security/security.h"
static NTSTATUS libnetapi_samr_lookup_and_open_alias(TALLOC_CTX *mem_ctx,
struct rpc_pipe_client *pipe_cli,
struct policy_handle *domain_handle,
const char *group_name,
uint32_t access_rights,
struct policy_handle *alias_handle)
{
NTSTATUS status, result;
struct lsa_String lsa_account_name;
struct samr_Ids user_rids, name_types;
struct dcerpc_binding_handle *b = pipe_cli->binding_handle;
init_lsa_String(&lsa_account_name, group_name);
status = dcerpc_samr_LookupNames(b, mem_ctx,
domain_handle,
1,
&lsa_account_name,
&user_rids,
&name_types,
&result);
if (!NT_STATUS_IS_OK(status)) {
return status;
}
if (!NT_STATUS_IS_OK(result)) {
return result;
}
if (user_rids.count != 1) {
return NT_STATUS_INVALID_NETWORK_RESPONSE;
}
if (name_types.count != 1) {
return NT_STATUS_INVALID_NETWORK_RESPONSE;
}
switch (name_types.ids[0]) {
case SID_NAME_ALIAS:
case SID_NAME_WKN_GRP:
break;
default:
return NT_STATUS_INVALID_SID;
}
status = dcerpc_samr_OpenAlias(b, mem_ctx,
domain_handle,
access_rights,
user_rids.ids[0],
alias_handle,
&result);
if (!NT_STATUS_IS_OK(status)) {
return status;
}
return result;
}
/****************************************************************
****************************************************************/
static NTSTATUS libnetapi_samr_open_alias_queryinfo(TALLOC_CTX *mem_ctx,
struct rpc_pipe_client *pipe_cli,
struct policy_handle *handle,
uint32_t rid,
uint32_t access_rights,
enum samr_AliasInfoEnum level,
union samr_AliasInfo **alias_info)
{
NTSTATUS status, result;
struct policy_handle alias_handle;
union samr_AliasInfo *_alias_info = NULL;
struct dcerpc_binding_handle *b = pipe_cli->binding_handle;
ZERO_STRUCT(alias_handle);
status = dcerpc_samr_OpenAlias(b, mem_ctx,
handle,
access_rights,
rid,
&alias_handle,
&result);
if (!NT_STATUS_IS_OK(status)) {
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
status = result;
goto done;
}
status = dcerpc_samr_QueryAliasInfo(b, mem_ctx,
&alias_handle,
level,
&_alias_info,
&result);
if (!NT_STATUS_IS_OK(status)) {
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
status = result;
goto done;
}
*alias_info = _alias_info;
done:
if (is_valid_policy_hnd(&alias_handle)) {
dcerpc_samr_Close(b, mem_ctx, &alias_handle, &result);
}
return status;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupAdd_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupAdd *r)
{
struct rpc_pipe_client *pipe_cli = NULL;
NTSTATUS status, result;
WERROR werr;
struct lsa_String lsa_account_name;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
uint32_t rid;
struct dcerpc_binding_handle *b = NULL;
struct LOCALGROUP_INFO_0 *info0 = NULL;
struct LOCALGROUP_INFO_1 *info1 = NULL;
const char *alias_name = NULL;
if (!r->in.buffer) {
return WERR_INVALID_PARAM;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
switch (r->in.level) {
case 0:
info0 = (struct LOCALGROUP_INFO_0 *)r->in.buffer;
alias_name = info0->lgrpi0_name;
break;
case 1:
info1 = (struct LOCALGROUP_INFO_1 *)r->in.buffer;
alias_name = info1->lgrpi1_name;
break;
default:
werr = WERR_UNKNOWN_LEVEL;
goto done;
}
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
b = pipe_cli->binding_handle;
werr = libnetapi_samr_open_builtin_domain(ctx, pipe_cli,
SAMR_ACCESS_LOOKUP_DOMAIN |
SAMR_ACCESS_ENUM_DOMAINS,
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&builtin_handle,
alias_name,
SAMR_ALIAS_ACCESS_LOOKUP_INFO,
&alias_handle);
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
}
if (NT_STATUS_IS_OK(status)) {
werr = WERR_ALIAS_EXISTS;
goto done;
}
werr = libnetapi_samr_open_domain(ctx, pipe_cli,
SAMR_ACCESS_ENUM_DOMAINS |
SAMR_ACCESS_LOOKUP_DOMAIN,
SAMR_DOMAIN_ACCESS_CREATE_ALIAS |
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
init_lsa_String(&lsa_account_name, alias_name);
status = dcerpc_samr_CreateDomAlias(b, talloc_tos(),
&domain_handle,
&lsa_account_name,
SEC_STD_DELETE |
SAMR_ALIAS_ACCESS_SET_INFO,
&alias_handle,
&rid,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
if (r->in.level == 1 && info1->lgrpi1_comment) {
union samr_AliasInfo alias_info;
init_lsa_String(&alias_info.description, info1->lgrpi1_comment);
status = dcerpc_samr_SetAliasInfo(b, talloc_tos(),
&alias_handle,
ALIASINFODESCRIPTION,
&alias_info,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
}
werr = WERR_OK;
done:
if (is_valid_policy_hnd(&alias_handle)) {
dcerpc_samr_Close(b, talloc_tos(), &alias_handle, &result);
}
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
libnetapi_samr_close_connect_handle(ctx, &connect_handle);
}
return werr;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupAdd_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupAdd *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupAdd);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupDel_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupDel *r)
{
struct rpc_pipe_client *pipe_cli = NULL;
NTSTATUS status, result;
WERROR werr;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
struct dcerpc_binding_handle *b = NULL;
if (!r->in.group_name) {
return WERR_INVALID_PARAM;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
b = pipe_cli->binding_handle;
werr = libnetapi_samr_open_builtin_domain(ctx, pipe_cli,
SAMR_ACCESS_LOOKUP_DOMAIN |
SAMR_ACCESS_ENUM_DOMAINS,
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&builtin_handle,
r->in.group_name,
SEC_STD_DELETE,
&alias_handle);
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
}
if (NT_STATUS_IS_OK(status)) {
goto delete_alias;
}
werr = libnetapi_samr_open_domain(ctx, pipe_cli,
SAMR_ACCESS_ENUM_DOMAINS |
SAMR_ACCESS_LOOKUP_DOMAIN,
SAMR_DOMAIN_ACCESS_CREATE_ALIAS |
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&domain_handle,
r->in.group_name,
SEC_STD_DELETE,
&alias_handle);
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
}
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
delete_alias:
status = dcerpc_samr_DeleteDomAlias(b, talloc_tos(),
&alias_handle,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
ZERO_STRUCT(alias_handle);
werr = WERR_OK;
done:
if (is_valid_policy_hnd(&alias_handle)) {
dcerpc_samr_Close(b, talloc_tos(), &alias_handle, &result);
}
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
libnetapi_samr_close_connect_handle(ctx, &connect_handle);
}
return werr;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupDel_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupDel *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupDel);
}
/****************************************************************
****************************************************************/
static WERROR map_alias_info_to_buffer(TALLOC_CTX *mem_ctx,
const char *alias_name,
struct samr_AliasInfoAll *info,
uint32_t level,
uint32_t *entries_read,
uint8_t **buffer)
{
struct LOCALGROUP_INFO_0 g0;
struct LOCALGROUP_INFO_1 g1;
struct LOCALGROUP_INFO_1002 g1002;
switch (level) {
case 0:
g0.lgrpi0_name = talloc_strdup(mem_ctx, alias_name);
W_ERROR_HAVE_NO_MEMORY(g0.lgrpi0_name);
ADD_TO_ARRAY(mem_ctx, struct LOCALGROUP_INFO_0, g0,
(struct LOCALGROUP_INFO_0 **)buffer, entries_read);
break;
case 1:
g1.lgrpi1_name = talloc_strdup(mem_ctx, alias_name);
g1.lgrpi1_comment = talloc_strdup(mem_ctx, info->description.string);
W_ERROR_HAVE_NO_MEMORY(g1.lgrpi1_name);
ADD_TO_ARRAY(mem_ctx, struct LOCALGROUP_INFO_1, g1,
(struct LOCALGROUP_INFO_1 **)buffer, entries_read);
break;
case 1002:
g1002.lgrpi1002_comment = talloc_strdup(mem_ctx, info->description.string);
ADD_TO_ARRAY(mem_ctx, struct LOCALGROUP_INFO_1002, g1002,
(struct LOCALGROUP_INFO_1002 **)buffer, entries_read);
break;
default:
return WERR_UNKNOWN_LEVEL;
}
return WERR_OK;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupGetInfo_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupGetInfo *r)
{
struct rpc_pipe_client *pipe_cli = NULL;
NTSTATUS status, result;
WERROR werr;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
union samr_AliasInfo *alias_info = NULL;
uint32_t entries_read = 0;
struct dcerpc_binding_handle *b = NULL;
if (!r->in.group_name) {
return WERR_INVALID_PARAM;
}
switch (r->in.level) {
case 0:
case 1:
case 1002:
break;
default:
return WERR_UNKNOWN_LEVEL;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
b = pipe_cli->binding_handle;
werr = libnetapi_samr_open_builtin_domain(ctx, pipe_cli,
SAMR_ACCESS_LOOKUP_DOMAIN |
SAMR_ACCESS_ENUM_DOMAINS,
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&builtin_handle,
r->in.group_name,
SAMR_ALIAS_ACCESS_LOOKUP_INFO,
&alias_handle);
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
}
if (NT_STATUS_IS_OK(status)) {
goto query_alias;
}
werr = libnetapi_samr_open_domain(ctx, pipe_cli,
SAMR_ACCESS_ENUM_DOMAINS |
SAMR_ACCESS_LOOKUP_DOMAIN,
SAMR_DOMAIN_ACCESS_CREATE_ALIAS |
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&domain_handle,
r->in.group_name,
SAMR_ALIAS_ACCESS_LOOKUP_INFO,
&alias_handle);
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
}
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
query_alias:
status = dcerpc_samr_QueryAliasInfo(b, talloc_tos(),
&alias_handle,
ALIASINFOALL,
&alias_info,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
werr = map_alias_info_to_buffer(ctx,
r->in.group_name,
&alias_info->all,
r->in.level, &entries_read,
r->out.buffer);
done:
if (is_valid_policy_hnd(&alias_handle)) {
dcerpc_samr_Close(b, talloc_tos(), &alias_handle, &result);
}
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
libnetapi_samr_close_connect_handle(ctx, &connect_handle);
}
return werr;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupGetInfo_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupGetInfo *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupGetInfo);
}
/****************************************************************
****************************************************************/
static WERROR map_buffer_to_alias_info(TALLOC_CTX *mem_ctx,
uint32_t level,
uint8_t *buffer,
enum samr_AliasInfoEnum *alias_level,
union samr_AliasInfo **alias_info)
{
struct LOCALGROUP_INFO_0 *info0;
struct LOCALGROUP_INFO_1 *info1;
struct LOCALGROUP_INFO_1002 *info1002;
union samr_AliasInfo *info = NULL;
info = talloc_zero(mem_ctx, union samr_AliasInfo);
W_ERROR_HAVE_NO_MEMORY(info);
switch (level) {
case 0:
info0 = (struct LOCALGROUP_INFO_0 *)buffer;
init_lsa_String(&info->name, info0->lgrpi0_name);
*alias_level = ALIASINFONAME;
break;
case 1:
info1 = (struct LOCALGROUP_INFO_1 *)buffer;
/* group name will be ignored */
init_lsa_String(&info->description, info1->lgrpi1_comment);
*alias_level = ALIASINFODESCRIPTION;
break;
case 1002:
info1002 = (struct LOCALGROUP_INFO_1002 *)buffer;
init_lsa_String(&info->description, info1002->lgrpi1002_comment);
*alias_level = ALIASINFODESCRIPTION;
break;
}
*alias_info = info;
return WERR_OK;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupSetInfo_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupSetInfo *r)
{
struct rpc_pipe_client *pipe_cli = NULL;
NTSTATUS status, result;
WERROR werr;
struct lsa_String lsa_account_name;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
enum samr_AliasInfoEnum alias_level = 0;
union samr_AliasInfo *alias_info = NULL;
struct dcerpc_binding_handle *b = NULL;
if (!r->in.group_name) {
return WERR_INVALID_PARAM;
}
switch (r->in.level) {
case 0:
case 1:
case 1002:
break;
default:
return WERR_UNKNOWN_LEVEL;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
b = pipe_cli->binding_handle;
werr = libnetapi_samr_open_builtin_domain(ctx, pipe_cli,
SAMR_ACCESS_LOOKUP_DOMAIN |
SAMR_ACCESS_ENUM_DOMAINS,
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
init_lsa_String(&lsa_account_name, r->in.group_name);
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&builtin_handle,
r->in.group_name,
SAMR_ALIAS_ACCESS_SET_INFO,
&alias_handle);
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
}
if (NT_STATUS_IS_OK(status)) {
goto set_alias;
}
werr = libnetapi_samr_open_domain(ctx, pipe_cli,
SAMR_ACCESS_ENUM_DOMAINS |
SAMR_ACCESS_LOOKUP_DOMAIN,
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&domain_handle,
r->in.group_name,
SAMR_ALIAS_ACCESS_SET_INFO,
&alias_handle);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
}
set_alias:
werr = map_buffer_to_alias_info(ctx, r->in.level, r->in.buffer,
&alias_level, &alias_info);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = dcerpc_samr_SetAliasInfo(b, talloc_tos(),
&alias_handle,
alias_level,
alias_info,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
werr = WERR_OK;
done:
if (is_valid_policy_hnd(&alias_handle)) {
dcerpc_samr_Close(b, talloc_tos(), &alias_handle, &result);
}
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
libnetapi_samr_close_connect_handle(ctx, &connect_handle);
}
return werr;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupSetInfo_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupSetInfo *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupSetInfo);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupEnum_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupEnum *r)
{
struct rpc_pipe_client *pipe_cli = NULL;
NTSTATUS status, result;
WERROR werr;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
uint32_t entries_read = 0;
union samr_DomainInfo *domain_info = NULL;
union samr_DomainInfo *builtin_info = NULL;
struct samr_SamArray *domain_sam_array = NULL;
struct samr_SamArray *builtin_sam_array = NULL;
int i;
struct dcerpc_binding_handle *b = NULL;
if (!r->out.buffer) {
return WERR_INVALID_PARAM;
}
switch (r->in.level) {
case 0:
case 1:
break;
default:
return WERR_UNKNOWN_LEVEL;
}
if (r->out.total_entries) {
*r->out.total_entries = 0;
}
if (r->out.entries_read) {
*r->out.entries_read = 0;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
b = pipe_cli->binding_handle;
werr = libnetapi_samr_open_builtin_domain(ctx, pipe_cli,
SAMR_ACCESS_LOOKUP_DOMAIN |
SAMR_ACCESS_ENUM_DOMAINS,
SAMR_DOMAIN_ACCESS_LOOKUP_INFO_2 |
SAMR_DOMAIN_ACCESS_ENUM_ACCOUNTS |
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
werr = libnetapi_samr_open_domain(ctx, pipe_cli,
SAMR_ACCESS_LOOKUP_DOMAIN |
SAMR_ACCESS_ENUM_DOMAINS,
SAMR_DOMAIN_ACCESS_LOOKUP_INFO_2 |
SAMR_DOMAIN_ACCESS_ENUM_ACCOUNTS |
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = dcerpc_samr_QueryDomainInfo(b, talloc_tos(),
&builtin_handle,
2,
&builtin_info,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
if (r->out.total_entries) {
*r->out.total_entries += builtin_info->general.num_aliases;
}
status = dcerpc_samr_QueryDomainInfo(b, talloc_tos(),
&domain_handle,
2,
&domain_info,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
if (r->out.total_entries) {
*r->out.total_entries += domain_info->general.num_aliases;
}
status = dcerpc_samr_EnumDomainAliases(b, talloc_tos(),
&builtin_handle,
r->in.resume_handle,
&builtin_sam_array,
r->in.prefmaxlen,
&entries_read,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
for (i=0; i<builtin_sam_array->count; i++) {
union samr_AliasInfo *alias_info = NULL;
if (r->in.level == 1) {
status = libnetapi_samr_open_alias_queryinfo(ctx, pipe_cli,
&builtin_handle,
builtin_sam_array->entries[i].idx,
SAMR_ALIAS_ACCESS_LOOKUP_INFO,
ALIASINFOALL,
&alias_info);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
werr = map_alias_info_to_buffer(ctx,
builtin_sam_array->entries[i].name.string,
alias_info ? &alias_info->all : NULL,
r->in.level,
r->out.entries_read,
r->out.buffer);
}
status = dcerpc_samr_EnumDomainAliases(b, talloc_tos(),
&domain_handle,
r->in.resume_handle,
&domain_sam_array,
r->in.prefmaxlen,
&entries_read,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
for (i=0; i<domain_sam_array->count; i++) {
union samr_AliasInfo *alias_info = NULL;
if (r->in.level == 1) {
status = libnetapi_samr_open_alias_queryinfo(ctx, pipe_cli,
&domain_handle,
domain_sam_array->entries[i].idx,
SAMR_ALIAS_ACCESS_LOOKUP_INFO,
ALIASINFOALL,
&alias_info);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
werr = map_alias_info_to_buffer(ctx,
domain_sam_array->entries[i].name.string,
alias_info ? &alias_info->all : NULL,
r->in.level,
r->out.entries_read,
r->out.buffer);
}
done:
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
libnetapi_samr_close_connect_handle(ctx, &connect_handle);
}
return werr;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupEnum_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupEnum *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupEnum);
}
/****************************************************************
****************************************************************/
static NTSTATUS libnetapi_lsa_lookup_names3(TALLOC_CTX *mem_ctx,
struct rpc_pipe_client *lsa_pipe,
const char *name,
struct dom_sid *sid)
{
NTSTATUS status, result;
struct policy_handle lsa_handle;
struct dcerpc_binding_handle *b = lsa_pipe->binding_handle;
struct lsa_RefDomainList *domains = NULL;
struct lsa_TransSidArray3 sids;
uint32_t count = 0;
struct lsa_String names;
uint32_t num_names = 1;
if (!sid || !name) {
return NT_STATUS_INVALID_PARAMETER;
}
ZERO_STRUCT(sids);
init_lsa_String(&names, name);
status = rpccli_lsa_open_policy2(lsa_pipe, mem_ctx,
false,
SEC_STD_READ_CONTROL |
LSA_POLICY_VIEW_LOCAL_INFORMATION |
LSA_POLICY_LOOKUP_NAMES,
&lsa_handle);
NT_STATUS_NOT_OK_RETURN(status);
status = dcerpc_lsa_LookupNames3(b, mem_ctx,
&lsa_handle,
num_names,
&names,
&domains,
&sids,
LSA_LOOKUP_NAMES_ALL, /* sure ? */
&count,
0, 0,
&result);
NT_STATUS_NOT_OK_RETURN(status);
NT_STATUS_NOT_OK_RETURN(result);
if (count != 1 || sids.count != 1) {
return NT_STATUS_INVALID_NETWORK_RESPONSE;
}
sid_copy(sid, sids.sids[0].sid);
return NT_STATUS_OK;
}
/****************************************************************
****************************************************************/
static WERROR NetLocalGroupModifyMembers_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupAddMembers *add,
struct NetLocalGroupDelMembers *del,
struct NetLocalGroupSetMembers *set)
{
struct NetLocalGroupAddMembers *r = NULL;
struct rpc_pipe_client *pipe_cli = NULL;
struct rpc_pipe_client *lsa_pipe = NULL;
NTSTATUS status, result;
WERROR werr;
struct lsa_String lsa_account_name;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
struct dom_sid *member_sids = NULL;
int i = 0, k = 0;
struct LOCALGROUP_MEMBERS_INFO_0 *info0 = NULL;
struct LOCALGROUP_MEMBERS_INFO_3 *info3 = NULL;
struct dom_sid *add_sids = NULL;
struct dom_sid *del_sids = NULL;
uint32_t num_add_sids = 0;
uint32_t num_del_sids = 0;
struct dcerpc_binding_handle *b = NULL;
if ((!add && !del && !set) || (add && del && set)) {
return WERR_INVALID_PARAM;
}
if (add) {
r = add;
}
if (del) {
r = (struct NetLocalGroupAddMembers *)del;
}
if (set) {
r = (struct NetLocalGroupAddMembers *)set;
}
if (!r->in.group_name) {
return WERR_INVALID_PARAM;
}
switch (r->in.level) {
case 0:
case 3:
break;
default:
return WERR_UNKNOWN_LEVEL;
}
if (r->in.total_entries == 0 || !r->in.buffer) {
return WERR_INVALID_PARAM;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
member_sids = talloc_zero_array(ctx, struct dom_sid,
r->in.total_entries);
W_ERROR_HAVE_NO_MEMORY(member_sids);
switch (r->in.level) {
case 0:
info0 = (struct LOCALGROUP_MEMBERS_INFO_0 *)r->in.buffer;
for (i=0; i < r->in.total_entries; i++) {
sid_copy(&member_sids[i], (struct dom_sid *)info0[i].lgrmi0_sid);
}
break;
case 3:
info3 = (struct LOCALGROUP_MEMBERS_INFO_3 *)r->in.buffer;
break;
default:
break;
}
if (r->in.level == 3) {
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_lsarpc.syntax_id,
&lsa_pipe);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
for (i=0; i < r->in.total_entries; i++) {
status = libnetapi_lsa_lookup_names3(ctx, lsa_pipe,
info3[i].lgrmi3_domainandname,
&member_sids[i]);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
TALLOC_FREE(lsa_pipe);
}
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
b = pipe_cli->binding_handle;
werr = libnetapi_samr_open_builtin_domain(ctx, pipe_cli,
SAMR_ACCESS_LOOKUP_DOMAIN |
SAMR_ACCESS_ENUM_DOMAINS,
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
init_lsa_String(&lsa_account_name, r->in.group_name);
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&builtin_handle,
r->in.group_name,
SAMR_ALIAS_ACCESS_ADD_MEMBER |
SAMR_ALIAS_ACCESS_REMOVE_MEMBER |
SAMR_ALIAS_ACCESS_GET_MEMBERS |
SAMR_ALIAS_ACCESS_LOOKUP_INFO,
&alias_handle);
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
}
if (NT_STATUS_IS_OK(status)) {
goto modify_membership;
}
werr = libnetapi_samr_open_domain(ctx, pipe_cli,
SAMR_ACCESS_ENUM_DOMAINS |
SAMR_ACCESS_LOOKUP_DOMAIN,
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&domain_handle,
r->in.group_name,
SAMR_ALIAS_ACCESS_ADD_MEMBER |
SAMR_ALIAS_ACCESS_REMOVE_MEMBER |
SAMR_ALIAS_ACCESS_GET_MEMBERS |
SAMR_ALIAS_ACCESS_LOOKUP_INFO,
&alias_handle);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
}
modify_membership:
if (add) {
for (i=0; i < r->in.total_entries; i++) {
status = add_sid_to_array_unique(ctx, &member_sids[i],
&add_sids,
&num_add_sids);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
}
if (del) {
for (i=0; i < r->in.total_entries; i++) {
status = add_sid_to_array_unique(ctx, &member_sids[i],
&del_sids,
&num_del_sids);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
}
if (set) {
struct lsa_SidArray current_sids;
status = dcerpc_samr_GetMembersInAlias(b, talloc_tos(),
&alias_handle,
¤t_sids,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
/* add list */
for (i=0; i < r->in.total_entries; i++) {
bool already_member = false;
for (k=0; k < current_sids.num_sids; k++) {
if (dom_sid_equal(&member_sids[i],
current_sids.sids[k].sid)) {
already_member = true;
break;
}
}
if (!already_member) {
status = add_sid_to_array_unique(ctx,
&member_sids[i],
&add_sids, &num_add_sids);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
}
/* del list */
for (k=0; k < current_sids.num_sids; k++) {
bool keep_member = false;
for (i=0; i < r->in.total_entries; i++) {
if (dom_sid_equal(&member_sids[i],
current_sids.sids[k].sid)) {
keep_member = true;
break;
}
}
if (!keep_member) {
status = add_sid_to_array_unique(ctx,
current_sids.sids[k].sid,
&del_sids, &num_del_sids);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
}
}
/* add list */
for (i=0; i < num_add_sids; i++) {
status = dcerpc_samr_AddAliasMember(b, talloc_tos(),
&alias_handle,
&add_sids[i],
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
}
/* del list */
for (i=0; i < num_del_sids; i++) {
status = dcerpc_samr_DeleteAliasMember(b, talloc_tos(),
&alias_handle,
&del_sids[i],
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
}
werr = WERR_OK;
done:
if (b && is_valid_policy_hnd(&alias_handle)) {
dcerpc_samr_Close(b, talloc_tos(), &alias_handle, &result);
}
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
libnetapi_samr_close_connect_handle(ctx, &connect_handle);
}
return werr;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupAddMembers_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupAddMembers *r)
{
return NetLocalGroupModifyMembers_r(ctx, r, NULL, NULL);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupAddMembers_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupAddMembers *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupAddMembers);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupDelMembers_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupDelMembers *r)
{
return NetLocalGroupModifyMembers_r(ctx, NULL, r, NULL);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupDelMembers_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupDelMembers *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupDelMembers);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupGetMembers_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupGetMembers *r)
{
return WERR_NOT_SUPPORTED;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupGetMembers_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupGetMembers *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupGetMembers);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupSetMembers_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupSetMembers *r)
{
return NetLocalGroupModifyMembers_r(ctx, NULL, NULL, r);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupSetMembers_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupSetMembers *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupSetMembers);
}
|
rchicoli/samba
|
source3/lib/netapi/localgroup.c
|
C
|
gpl-3.0
| 36,680
|
/* This file is part of the hkl library.
*
* The hkl library is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The hkl 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the hkl library. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright (C) 2003-2015 Synchrotron SOLEIL
* L'Orme des Merisiers Saint-Aubin
* BP 48 91192 GIF-sur-YVETTE CEDEX
*
* Authors: Picca Frédéric-Emmanuel <picca@synchrotron-soleil.fr>
*/
#include "hkl.h"
#include <tap/basic.h>
#include <tap/float.h>
#include "hkl-vector-private.h"
#include "hkl-matrix-private.h" /* we will check also the private API */
static void init(void)
{
HklMatrix m;
hkl_matrix_init(&m, 1, 1, 0, 0, 1, 0, 0, 0, 1);
is_double(1., m.data[0][0], HKL_EPSILON, __func__);
is_double(1., m.data[0][1], HKL_EPSILON, __func__);
is_double(0., m.data[0][2], HKL_EPSILON, __func__);
is_double(0., m.data[1][0], HKL_EPSILON, __func__);
is_double(1., m.data[1][1], HKL_EPSILON, __func__);
is_double(0., m.data[1][2], HKL_EPSILON, __func__);
is_double(0., m.data[2][0], HKL_EPSILON, __func__);
is_double(0., m.data[2][1], HKL_EPSILON, __func__);
is_double(1., m.data[2][2], HKL_EPSILON, __func__);
}
static void cmp(void)
{
HklMatrix m1 = {{{0.0, 1.0, 2.0},
{3.0, 4.0, 5.0},
{6.0, 7.0, 8.0}}};
HklMatrix m2 = {{{1.0, 1.0, 2.0},
{3.0, 4.0, 5.0},
{6.0, 7.0, 8.0}}};
ok(TRUE == hkl_matrix_cmp(&m1, &m1), __func__);
ok(FALSE == hkl_matrix_cmp(&m1, &m2), __func__);
}
static void assignement(void)
{
HklMatrix m1 = {{{0.0, 1.0, 2.0},
{3.0, 4.0, 5.0},
{6.0, 7.0, 8.0}}};
HklMatrix m;
m = m1;
ok(TRUE == hkl_matrix_cmp(&m1, &m), __func__);
}
static void init_from_euler(void)
{
HklMatrix m_ref = {{{ 1./2., -1./2., sqrt(2)/2.},
{ sqrt(2.)/4.+1./2., -sqrt(2.)/4.+1./2., -1./2.},
{-sqrt(2.)/4.+1./2., sqrt(2.)/4.+1./2., 1./2.}}};
HklMatrix m;
hkl_matrix_init_from_euler(&m, 45.*HKL_DEGTORAD, 45.*HKL_DEGTORAD, 45.*HKL_DEGTORAD);
ok(TRUE == hkl_matrix_cmp(&m_ref, &m), __func__);
}
static void init_from_two_vector(void)
{
HklVector v1 = {{0.0, 1.0, 2.0}};
HklVector v2 = {{1.0, 2.0, 3.0}};
HklMatrix m_ref = {{{0.0, 5.0 / sqrt(30.0), -1.0 / sqrt(6.0)},
{1.0 / sqrt(5.0), 2.0 / sqrt(30.0), 2.0 / sqrt(6.0)},
{2.0 / sqrt(5.0),-1.0 / sqrt(30.0), -1.0 / sqrt(6.0)}}
};
HklMatrix m;
hkl_matrix_init_from_two_vector(&m, &v1, &v2);
ok(TRUE == hkl_matrix_cmp(&m_ref, &m), __func__);
}
static void times_vector(void)
{
HklMatrix m = {{{ 1.0, 3.0,-2.0},
{10.0, 5.0, 5.0},
{-3.0, 2.0, 0.0}}
};
HklVector v = {{1, 2, 3}};
HklVector v_ref = {{1, 35, 1}};
hkl_matrix_times_vector(&m, &v);
ok(0 == hkl_vector_cmp(&v_ref, &v), __func__);
}
static void times_matrix(void)
{
HklMatrix m_ref = {{{37., 14., 13.},
{45., 65., 5.},
{17., 1., 16.}}
};
HklMatrix m = {{{ 1., 3.,-2.},
{10., 5., 5.},
{-3., 2., 0.}}
};
hkl_matrix_times_matrix(&m, &m);
ok(TRUE == hkl_matrix_cmp(&m_ref, &m), __func__);
}
static void transpose(void)
{
HklMatrix m_ref = {{{37., 14., 13.},
{45., 65., 5.},
{17., 1., 16.}}
};
HklMatrix m = {{{37., 45., 17.},
{14., 65., 1.},
{13., 5., 16.}}
};
hkl_matrix_transpose(&m);
ok(TRUE == hkl_matrix_cmp(&m_ref, &m), __func__);
}
int main(void)
{
plan(17);
init();
cmp();
assignement();
init_from_euler();
init_from_two_vector();
times_vector();
times_matrix();
transpose();
return 0;
}
|
klauer/hkl
|
tests/hkl-matrix-t.c
|
C
|
gpl-3.0
| 3,973
|
/*-------------------------------------------------------------------------
*
* prepjointree.c
* Planner preprocessing for subqueries and join tree manipulation.
*
* NOTE: the intended sequence for invoking these operations is
* pull_up_sublinks
* inline_set_returning_functions
* pull_up_subqueries
* do expression preprocessing (including flattening JOIN alias vars)
* reduce_outer_joins
*
*
* Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/prep/prepjointree.c,v 1.73 2010/07/06 19:18:56 momjian Exp $
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "catalog/pg_type.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/placeholder.h"
#include "optimizer/prep.h"
#include "optimizer/subselect.h"
#include "optimizer/tlist.h"
#include "optimizer/var.h"
#include "parser/parse_relation.h"
#include "parser/parsetree.h"
#include "rewrite/rewriteManip.h"
typedef struct pullup_replace_vars_context
{
PlannerInfo *root;
List *targetlist; /* tlist of subquery being pulled up */
RangeTblEntry *target_rte; /* RTE of subquery */
bool *outer_hasSubLinks; /* -> outer query's hasSubLinks */
int varno; /* varno of subquery */
bool need_phvs; /* do we need PlaceHolderVars? */
bool wrap_non_vars; /* do we need 'em on *all* non-Vars? */
Node **rv_cache; /* cache for results with PHVs */
} pullup_replace_vars_context;
typedef struct reduce_outer_joins_state
{
Relids relids; /* base relids within this subtree */
bool contains_outer; /* does subtree contain outer join(s)? */
List *sub_states; /* List of states for subtree components */
} reduce_outer_joins_state;
static Node *pull_up_sublinks_jointree_recurse(PlannerInfo *root, Node *jtnode,
Relids *relids);
static Node *pull_up_sublinks_qual_recurse(PlannerInfo *root, Node *node,
Relids available_rels, Node **jtlink);
static Node *pull_up_simple_subquery(PlannerInfo *root, Node *jtnode,
RangeTblEntry *rte,
JoinExpr *lowest_outer_join,
AppendRelInfo *containing_appendrel);
static Node *pull_up_simple_union_all(PlannerInfo *root, Node *jtnode,
RangeTblEntry *rte);
static void pull_up_union_leaf_queries(Node *setOp, PlannerInfo *root,
int parentRTindex, Query *setOpQuery,
int childRToffset);
static void make_setop_translation_list(Query *query, Index newvarno,
List **translated_vars);
static bool is_simple_subquery(Query *subquery);
static bool is_simple_union_all(Query *subquery);
static bool is_simple_union_all_recurse(Node *setOp, Query *setOpQuery,
List *colTypes);
static bool is_safe_append_member(Query *subquery);
static void replace_vars_in_jointree(Node *jtnode,
pullup_replace_vars_context *context,
JoinExpr *lowest_outer_join);
static Node *pullup_replace_vars(Node *expr,
pullup_replace_vars_context *context);
static Node *pullup_replace_vars_callback(Var *var,
replace_rte_variables_context *context);
static reduce_outer_joins_state *reduce_outer_joins_pass1(Node *jtnode);
static void reduce_outer_joins_pass2(Node *jtnode,
reduce_outer_joins_state *state,
PlannerInfo *root,
Relids nonnullable_rels,
List *nonnullable_vars,
List *forced_null_vars);
static void substitute_multiple_relids(Node *node,
int varno, Relids subrelids);
static void fix_append_rel_relids(List *append_rel_list, int varno,
Relids subrelids);
static Node *find_jointree_node_for_rel(Node *jtnode, int relid);
/*
* pull_up_sublinks
* Attempt to pull up ANY and EXISTS SubLinks to be treated as
* semijoins or anti-semijoins.
*
* A clause "foo op ANY (sub-SELECT)" can be processed by pulling the
* sub-SELECT up to become a rangetable entry and treating the implied
* comparisons as quals of a semijoin. However, this optimization *only*
* works at the top level of WHERE or a JOIN/ON clause, because we cannot
* distinguish whether the ANY ought to return FALSE or NULL in cases
* involving NULL inputs. Also, in an outer join's ON clause we can only
* do this if the sublink is degenerate (ie, references only the nullable
* side of the join). In that case it is legal to push the semijoin
* down into the nullable side of the join. If the sublink references any
* nonnullable-side variables then it would have to be evaluated as part
* of the outer join, which makes things way too complicated.
*
* Under similar conditions, EXISTS and NOT EXISTS clauses can be handled
* by pulling up the sub-SELECT and creating a semijoin or anti-semijoin.
*
* This routine searches for such clauses and does the necessary parsetree
* transformations if any are found.
*
* This routine has to run before preprocess_expression(), so the quals
* clauses are not yet reduced to implicit-AND format. That means we need
* to recursively search through explicit AND clauses, which are
* probably only binary ANDs. We stop as soon as we hit a non-AND item.
*/
void
pull_up_sublinks(PlannerInfo *root)
{
Node *jtnode;
Relids relids;
/* Begin recursion through the jointree */
jtnode = pull_up_sublinks_jointree_recurse(root,
(Node *) root->parse->jointree,
&relids);
/*
* root->parse->jointree must always be a FromExpr, so insert a dummy one
* if we got a bare RangeTblRef or JoinExpr out of the recursion.
*/
if (IsA(jtnode, FromExpr))
root->parse->jointree = (FromExpr *) jtnode;
else
root->parse->jointree = makeFromExpr(list_make1(jtnode), NULL);
}
/*
* Recurse through jointree nodes for pull_up_sublinks()
*
* In addition to returning the possibly-modified jointree node, we return
* a relids set of the contained rels into *relids.
*/
static Node *
pull_up_sublinks_jointree_recurse(PlannerInfo *root, Node *jtnode,
Relids *relids)
{
if (jtnode == NULL)
{
*relids = NULL;
}
else if (IsA(jtnode, RangeTblRef))
{
int varno = ((RangeTblRef *) jtnode)->rtindex;
*relids = bms_make_singleton(varno);
/* jtnode is returned unmodified */
}
else if (IsA(jtnode, FromExpr))
{
FromExpr *f = (FromExpr *) jtnode;
List *newfromlist = NIL;
Relids frelids = NULL;
FromExpr *newf;
Node *jtlink;
ListCell *l;
/* First, recurse to process children and collect their relids */
foreach(l, f->fromlist)
{
Node *newchild;
Relids childrelids;
newchild = pull_up_sublinks_jointree_recurse(root,
lfirst(l),
&childrelids);
newfromlist = lappend(newfromlist, newchild);
frelids = bms_join(frelids, childrelids);
}
/* Build the replacement FromExpr; no quals yet */
newf = makeFromExpr(newfromlist, NULL);
/* Set up a link representing the rebuilt jointree */
jtlink = (Node *) newf;
/* Now process qual --- all children are available for use */
newf->quals = pull_up_sublinks_qual_recurse(root, f->quals, frelids,
&jtlink);
/*
* Note that the result will be either newf, or a stack of JoinExprs
* with newf at the base. We rely on subsequent optimization steps to
* flatten this and rearrange the joins as needed.
*
* Although we could include the pulled-up subqueries in the returned
* relids, there's no need since upper quals couldn't refer to their
* outputs anyway.
*/
*relids = frelids;
jtnode = jtlink;
}
else if (IsA(jtnode, JoinExpr))
{
JoinExpr *j;
Relids leftrelids;
Relids rightrelids;
Node *jtlink;
/*
* Make a modifiable copy of join node, but don't bother copying its
* subnodes (yet).
*/
j = (JoinExpr *) palloc(sizeof(JoinExpr));
memcpy(j, jtnode, sizeof(JoinExpr));
jtlink = (Node *) j;
/* Recurse to process children and collect their relids */
j->larg = pull_up_sublinks_jointree_recurse(root, j->larg,
&leftrelids);
j->rarg = pull_up_sublinks_jointree_recurse(root, j->rarg,
&rightrelids);
/*
* Now process qual, showing appropriate child relids as available,
* and attach any pulled-up jointree items at the right place. In the
* inner-join case we put new JoinExprs above the existing one (much
* as for a FromExpr-style join). In outer-join cases the new
* JoinExprs must go into the nullable side of the outer join. The
* point of the available_rels machinations is to ensure that we only
* pull up quals for which that's okay.
*
* XXX for the moment, we refrain from pulling up IN/EXISTS clauses
* appearing in LEFT or RIGHT join conditions. Although it is
* semantically valid to do so under the above conditions, we end up
* with a query in which the semijoin or antijoin must be evaluated
* below the outer join, which could perform far worse than leaving it
* as a sublink that is executed only for row pairs that meet the
* other join conditions. Fixing this seems to require considerable
* restructuring of the executor, but maybe someday it can happen.
*
* We don't expect to see any pre-existing JOIN_SEMI or JOIN_ANTI
* nodes here.
*/
switch (j->jointype)
{
case JOIN_INNER:
j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
bms_union(leftrelids,
rightrelids),
&jtlink);
break;
case JOIN_LEFT:
#ifdef NOT_USED /* see XXX comment above */
j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
rightrelids,
&j->rarg);
#endif
break;
case JOIN_FULL:
/* can't do anything with full-join quals */
break;
case JOIN_RIGHT:
#ifdef NOT_USED /* see XXX comment above */
j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
leftrelids,
&j->larg);
#endif
break;
default:
elog(ERROR, "unrecognized join type: %d",
(int) j->jointype);
break;
}
/*
* Although we could include the pulled-up subqueries in the returned
* relids, there's no need since upper quals couldn't refer to their
* outputs anyway. But we *do* need to include the join's own rtindex
* because we haven't yet collapsed join alias variables, so upper
* levels would mistakenly think they couldn't use references to this
* join.
*/
*relids = bms_join(leftrelids, rightrelids);
if (j->rtindex)
*relids = bms_add_member(*relids, j->rtindex);
jtnode = jtlink;
}
else
elog(ERROR, "unrecognized node type: %d",
(int) nodeTag(jtnode));
return jtnode;
}
/*
* Recurse through top-level qual nodes for pull_up_sublinks()
*
* jtlink points to the link in the jointree where any new JoinExprs should be
* inserted. If we find multiple pull-up-able SubLinks, they'll get stacked
* there in the order we encounter them. We rely on subsequent optimization
* to rearrange the stack if appropriate.
*/
static Node *
pull_up_sublinks_qual_recurse(PlannerInfo *root, Node *node,
Relids available_rels, Node **jtlink)
{
if (node == NULL)
return NULL;
if (IsA(node, SubLink))
{
SubLink *sublink = (SubLink *) node;
JoinExpr *j;
/* Is it a convertible ANY or EXISTS clause? */
if (sublink->subLinkType == ANY_SUBLINK)
{
j = convert_ANY_sublink_to_join(root, sublink,
available_rels);
if (j)
{
/* Yes, insert the new join node into the join tree */
j->larg = *jtlink;
*jtlink = (Node *) j;
/* and return NULL representing constant TRUE */
return NULL;
}
}
else if (sublink->subLinkType == EXISTS_SUBLINK)
{
j = convert_EXISTS_sublink_to_join(root, sublink, false,
available_rels);
if (j)
{
/* Yes, insert the new join node into the join tree */
j->larg = *jtlink;
*jtlink = (Node *) j;
/* and return NULL representing constant TRUE */
return NULL;
}
}
/* Else return it unmodified */
return node;
}
if (not_clause(node))
{
/* If the immediate argument of NOT is EXISTS, try to convert */
SubLink *sublink = (SubLink *) get_notclausearg((Expr *) node);
JoinExpr *j;
if (sublink && IsA(sublink, SubLink))
{
if (sublink->subLinkType == EXISTS_SUBLINK)
{
j = convert_EXISTS_sublink_to_join(root, sublink, true,
available_rels);
if (j)
{
/* Yes, insert the new join node into the join tree */
j->larg = *jtlink;
*jtlink = (Node *) j;
/* and return NULL representing constant TRUE */
return NULL;
}
}
}
/* Else return it unmodified */
return node;
}
if (and_clause(node))
{
/* Recurse into AND clause */
List *newclauses = NIL;
ListCell *l;
foreach(l, ((BoolExpr *) node)->args)
{
Node *oldclause = (Node *) lfirst(l);
Node *newclause;
newclause = pull_up_sublinks_qual_recurse(root,
oldclause,
available_rels,
jtlink);
if (newclause)
newclauses = lappend(newclauses, newclause);
}
/* We might have got back fewer clauses than we started with */
if (newclauses == NIL)
return NULL;
else if (list_length(newclauses) == 1)
return (Node *) linitial(newclauses);
else
return (Node *) make_andclause(newclauses);
}
/* Stop if not an AND */
return node;
}
/*
* inline_set_returning_functions
* Attempt to "inline" set-returning functions in the FROM clause.
*
* If an RTE_FUNCTION rtable entry invokes a set-returning function that
* contains just a simple SELECT, we can convert the rtable entry to an
* RTE_SUBQUERY entry exposing the SELECT directly. This is especially
* useful if the subquery can then be "pulled up" for further optimization,
* but we do it even if not, to reduce executor overhead.
*
* This has to be done before we have started to do any optimization of
* subqueries, else any such steps wouldn't get applied to subqueries
* obtained via inlining. However, we do it after pull_up_sublinks
* so that we can inline any functions used in SubLink subselects.
*
* Like most of the planner, this feels free to scribble on its input data
* structure.
*/
void
inline_set_returning_functions(PlannerInfo *root)
{
ListCell *rt;
foreach(rt, root->parse->rtable)
{
RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
if (rte->rtekind == RTE_FUNCTION)
{
Query *funcquery;
/* Check safety of expansion, and expand if possible */
funcquery = inline_set_returning_function(root, rte);
if (funcquery)
{
/* Successful expansion, replace the rtable entry */
rte->rtekind = RTE_SUBQUERY;
rte->subquery = funcquery;
rte->funcexpr = NULL;
rte->funccoltypes = NIL;
rte->funccoltypmods = NIL;
}
}
}
}
/*
* pull_up_subqueries
* Look for subqueries in the rangetable that can be pulled up into
* the parent query. If the subquery has no special features like
* grouping/aggregation then we can merge it into the parent's jointree.
* Also, subqueries that are simple UNION ALL structures can be
* converted into "append relations".
*
* If this jointree node is within the nullable side of an outer join, then
* lowest_outer_join references the lowest such JoinExpr node; otherwise it
* is NULL. This forces use of the PlaceHolderVar mechanism for references
* to non-nullable targetlist items, but only for references above that join.
*
* If we are looking at a member subquery of an append relation,
* containing_appendrel describes that relation; else it is NULL.
* This forces use of the PlaceHolderVar mechanism for all non-Var targetlist
* items, and puts some additional restrictions on what can be pulled up.
*
* A tricky aspect of this code is that if we pull up a subquery we have
* to replace Vars that reference the subquery's outputs throughout the
* parent query, including quals attached to jointree nodes above the one
* we are currently processing! We handle this by being careful not to
* change the jointree structure while recursing: no nodes other than
* subquery RangeTblRef entries will be replaced. Also, we can't turn
* pullup_replace_vars loose on the whole jointree, because it'll return a
* mutated copy of the tree; we have to invoke it just on the quals, instead.
* This behavior is what makes it reasonable to pass lowest_outer_join as a
* pointer rather than some more-indirect way of identifying the lowest OJ.
* Likewise, we don't replace append_rel_list members but only their
* substructure, so the containing_appendrel reference is safe to use.
*/
Node *
pull_up_subqueries(PlannerInfo *root, Node *jtnode,
JoinExpr *lowest_outer_join,
AppendRelInfo *containing_appendrel)
{
if (jtnode == NULL)
return NULL;
if (IsA(jtnode, RangeTblRef))
{
int varno = ((RangeTblRef *) jtnode)->rtindex;
RangeTblEntry *rte = rt_fetch(varno, root->parse->rtable);
/*
* Is this a subquery RTE, and if so, is the subquery simple enough to
* pull up?
*
* If we are looking at an append-relation member, we can't pull it up
* unless is_safe_append_member says so.
*/
if (rte->rtekind == RTE_SUBQUERY &&
is_simple_subquery(rte->subquery) &&
(containing_appendrel == NULL ||
is_safe_append_member(rte->subquery)))
return pull_up_simple_subquery(root, jtnode, rte,
lowest_outer_join,
containing_appendrel);
/*
* Alternatively, is it a simple UNION ALL subquery? If so, flatten
* into an "append relation".
*
* It's safe to do this regardless of whether this query is itself an
* appendrel member. (If you're thinking we should try to flatten the
* two levels of appendrel together, you're right; but we handle that
* in set_append_rel_pathlist, not here.)
*/
if (rte->rtekind == RTE_SUBQUERY &&
is_simple_union_all(rte->subquery))
return pull_up_simple_union_all(root, jtnode, rte);
/* Otherwise, do nothing at this node. */
}
else if (IsA(jtnode, FromExpr))
{
FromExpr *f = (FromExpr *) jtnode;
ListCell *l;
Assert(containing_appendrel == NULL);
foreach(l, f->fromlist)
lfirst(l) = pull_up_subqueries(root, lfirst(l),
lowest_outer_join, NULL);
}
else if (IsA(jtnode, JoinExpr))
{
JoinExpr *j = (JoinExpr *) jtnode;
Assert(containing_appendrel == NULL);
/* Recurse, being careful to tell myself when inside outer join */
switch (j->jointype)
{
case JOIN_INNER:
j->larg = pull_up_subqueries(root, j->larg,
lowest_outer_join, NULL);
j->rarg = pull_up_subqueries(root, j->rarg,
lowest_outer_join, NULL);
break;
case JOIN_LEFT:
case JOIN_SEMI:
case JOIN_ANTI:
j->larg = pull_up_subqueries(root, j->larg,
lowest_outer_join, NULL);
j->rarg = pull_up_subqueries(root, j->rarg,
j, NULL);
break;
case JOIN_FULL:
j->larg = pull_up_subqueries(root, j->larg,
j, NULL);
j->rarg = pull_up_subqueries(root, j->rarg,
j, NULL);
break;
case JOIN_RIGHT:
j->larg = pull_up_subqueries(root, j->larg,
j, NULL);
j->rarg = pull_up_subqueries(root, j->rarg,
lowest_outer_join, NULL);
break;
default:
elog(ERROR, "unrecognized join type: %d",
(int) j->jointype);
break;
}
}
else
elog(ERROR, "unrecognized node type: %d",
(int) nodeTag(jtnode));
return jtnode;
}
/*
* pull_up_simple_subquery
* Attempt to pull up a single simple subquery.
*
* jtnode is a RangeTblRef that has been tentatively identified as a simple
* subquery by pull_up_subqueries. We return the replacement jointree node,
* or jtnode itself if we determine that the subquery can't be pulled up after
* all.
*
* rte is the RangeTblEntry referenced by jtnode. Remaining parameters are
* as for pull_up_subqueries.
*/
static Node *
pull_up_simple_subquery(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte,
JoinExpr *lowest_outer_join,
AppendRelInfo *containing_appendrel)
{
Query *parse = root->parse;
int varno = ((RangeTblRef *) jtnode)->rtindex;
Query *subquery;
PlannerInfo *subroot;
int rtoffset;
pullup_replace_vars_context rvcontext;
ListCell *lc;
/*
* Need a modifiable copy of the subquery to hack on. Even if we didn't
* sometimes choose not to pull up below, we must do this to avoid
* problems if the same subquery is referenced from multiple jointree
* items (which can't happen normally, but might after rule rewriting).
*/
subquery = copyObject(rte->subquery);
/*
* Create a PlannerInfo data structure for this subquery.
*
* NOTE: the next few steps should match the first processing in
* subquery_planner(). Can we refactor to avoid code duplication, or
* would that just make things uglier?
*/
subroot = makeNode(PlannerInfo);
subroot->parse = subquery;
subroot->glob = root->glob;
subroot->query_level = root->query_level;
subroot->parent_root = root->parent_root;
subroot->planner_cxt = CurrentMemoryContext;
subroot->init_plans = NIL;
subroot->cte_plan_ids = NIL;
subroot->eq_classes = NIL;
subroot->append_rel_list = NIL;
subroot->rowMarks = NIL;
subroot->hasRecursion = false;
subroot->wt_param_id = -1;
subroot->non_recursive_plan = NULL;
/* No CTEs to worry about */
Assert(subquery->cteList == NIL);
/*
* Pull up any SubLinks within the subquery's quals, so that we don't
* leave unoptimized SubLinks behind.
*/
if (subquery->hasSubLinks)
pull_up_sublinks(subroot);
/*
* Similarly, inline any set-returning functions in its rangetable.
*/
inline_set_returning_functions(subroot);
/*
* Recursively pull up the subquery's subqueries, so that
* pull_up_subqueries' processing is complete for its jointree and
* rangetable.
*
* Note: we should pass NULL for containing-join info even if we are
* within an outer join in the upper query; the lower query starts with a
* clean slate for outer-join semantics. Likewise, we say we aren't
* handling an appendrel member.
*/
subquery->jointree = (FromExpr *)
pull_up_subqueries(subroot, (Node *) subquery->jointree, NULL, NULL);
/*
* Now we must recheck whether the subquery is still simple enough to pull
* up. If not, abandon processing it.
*
* We don't really need to recheck all the conditions involved, but it's
* easier just to keep this "if" looking the same as the one in
* pull_up_subqueries.
*/
if (is_simple_subquery(subquery) &&
(containing_appendrel == NULL || is_safe_append_member(subquery)))
{
/* good to go */
}
else
{
/*
* Give up, return unmodified RangeTblRef.
*
* Note: The work we just did will be redone when the subquery gets
* planned on its own. Perhaps we could avoid that by storing the
* modified subquery back into the rangetable, but I'm not gonna risk
* it now.
*/
return jtnode;
}
/*
* Adjust level-0 varnos in subquery so that we can append its rangetable
* to upper query's. We have to fix the subquery's append_rel_list as
* well.
*/
rtoffset = list_length(parse->rtable);
OffsetVarNodes((Node *) subquery, rtoffset, 0);
OffsetVarNodes((Node *) subroot->append_rel_list, rtoffset, 0);
/*
* Upper-level vars in subquery are now one level closer to their parent
* than before.
*/
IncrementVarSublevelsUp((Node *) subquery, -1, 1);
IncrementVarSublevelsUp((Node *) subroot->append_rel_list, -1, 1);
/*
* The subquery's targetlist items are now in the appropriate form to
* insert into the top query, but if we are under an outer join then
* non-nullable items may have to be turned into PlaceHolderVars. If we
* are dealing with an appendrel member then anything that's not a simple
* Var has to be turned into a PlaceHolderVar. Set up appropriate context
* data for pullup_replace_vars.
*/
rvcontext.root = root;
rvcontext.targetlist = subquery->targetList;
rvcontext.target_rte = rte;
rvcontext.outer_hasSubLinks = &parse->hasSubLinks;
rvcontext.varno = varno;
rvcontext.need_phvs = (lowest_outer_join != NULL ||
containing_appendrel != NULL);
rvcontext.wrap_non_vars = (containing_appendrel != NULL);
/* initialize cache array with indexes 0 .. length(tlist) */
rvcontext.rv_cache = palloc0((list_length(subquery->targetList) + 1) *
sizeof(Node *));
/*
* Replace all of the top query's references to the subquery's outputs
* with copies of the adjusted subtlist items, being careful not to
* replace any of the jointree structure. (This'd be a lot cleaner if we
* could use query_tree_mutator.) We have to use PHVs in the targetList,
* returningList, and havingQual, since those are certainly above any
* outer join. replace_vars_in_jointree tracks its location in the
* jointree and uses PHVs or not appropriately.
*/
parse->targetList = (List *)
pullup_replace_vars((Node *) parse->targetList, &rvcontext);
parse->returningList = (List *)
pullup_replace_vars((Node *) parse->returningList, &rvcontext);
replace_vars_in_jointree((Node *) parse->jointree, &rvcontext,
lowest_outer_join);
Assert(parse->setOperations == NULL);
parse->havingQual = pullup_replace_vars(parse->havingQual, &rvcontext);
/*
* Replace references in the translated_vars lists of appendrels. When
* pulling up an appendrel member, we do not need PHVs in the list of the
* parent appendrel --- there isn't any outer join between. Elsewhere, use
* PHVs for safety. (This analysis could be made tighter but it seems
* unlikely to be worth much trouble.)
*/
foreach(lc, root->append_rel_list)
{
AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(lc);
bool save_need_phvs = rvcontext.need_phvs;
if (appinfo == containing_appendrel)
rvcontext.need_phvs = false;
appinfo->translated_vars = (List *)
pullup_replace_vars((Node *) appinfo->translated_vars, &rvcontext);
rvcontext.need_phvs = save_need_phvs;
}
/*
* Replace references in the joinaliasvars lists of join RTEs.
*
* You might think that we could avoid using PHVs for alias vars of joins
* below lowest_outer_join, but that doesn't work because the alias vars
* could be referenced above that join; we need the PHVs to be present in
* such references after the alias vars get flattened. (It might be worth
* trying to be smarter here, someday.)
*/
foreach(lc, parse->rtable)
{
RangeTblEntry *otherrte = (RangeTblEntry *) lfirst(lc);
if (otherrte->rtekind == RTE_JOIN)
otherrte->joinaliasvars = (List *)
pullup_replace_vars((Node *) otherrte->joinaliasvars,
&rvcontext);
}
/*
* Now append the adjusted rtable entries to upper query. (We hold off
* until after fixing the upper rtable entries; no point in running that
* code on the subquery ones too.)
*/
parse->rtable = list_concat(parse->rtable, subquery->rtable);
/*
* Pull up any FOR UPDATE/SHARE markers, too. (OffsetVarNodes already
* adjusted the marker rtindexes, so just concat the lists.)
*/
parse->rowMarks = list_concat(parse->rowMarks, subquery->rowMarks);
/*
* We also have to fix the relid sets of any PlaceHolderVar nodes in the
* parent query. (This could perhaps be done by pullup_replace_vars(),
* but it seems cleaner to use two passes.) Note in particular that any
* PlaceHolderVar nodes just created by pullup_replace_vars() will be
* adjusted, so having created them with the subquery's varno is correct.
*
* Likewise, relids appearing in AppendRelInfo nodes have to be fixed. We
* already checked that this won't require introducing multiple subrelids
* into the single-slot AppendRelInfo structs.
*/
if (parse->hasSubLinks || root->glob->lastPHId != 0 ||
root->append_rel_list)
{
Relids subrelids;
subrelids = get_relids_in_jointree((Node *) subquery->jointree, false);
substitute_multiple_relids((Node *) parse, varno, subrelids);
fix_append_rel_relids(root->append_rel_list, varno, subrelids);
}
/*
* And now add subquery's AppendRelInfos to our list.
*/
root->append_rel_list = list_concat(root->append_rel_list,
subroot->append_rel_list);
/*
* We don't have to do the equivalent bookkeeping for outer-join info,
* because that hasn't been set up yet. placeholder_list likewise.
*/
Assert(root->join_info_list == NIL);
Assert(subroot->join_info_list == NIL);
Assert(root->placeholder_list == NIL);
Assert(subroot->placeholder_list == NIL);
/*
* Miscellaneous housekeeping.
*
* Although replace_rte_variables() faithfully updated parse->hasSubLinks
* if it copied any SubLinks out of the subquery's targetlist, we still
* could have SubLinks added to the query in the expressions of FUNCTION
* and VALUES RTEs copied up from the subquery. So it's necessary to copy
* subquery->hasSubLinks anyway. Perhaps this can be improved someday.
*/
parse->hasSubLinks |= subquery->hasSubLinks;
/*
* subquery won't be pulled up if it hasAggs or hasWindowFuncs, so no work
* needed on those flags
*/
/*
* Return the adjusted subquery jointree to replace the RangeTblRef entry
* in parent's jointree.
*/
return (Node *) subquery->jointree;
}
/*
* pull_up_simple_union_all
* Pull up a single simple UNION ALL subquery.
*
* jtnode is a RangeTblRef that has been identified as a simple UNION ALL
* subquery by pull_up_subqueries. We pull up the leaf subqueries and
* build an "append relation" for the union set. The result value is just
* jtnode, since we don't actually need to change the query jointree.
*/
static Node *
pull_up_simple_union_all(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte)
{
int varno = ((RangeTblRef *) jtnode)->rtindex;
Query *subquery = rte->subquery;
int rtoffset;
List *rtable;
/*
* Append the subquery rtable entries to upper query.
*/
rtoffset = list_length(root->parse->rtable);
/*
* Append child RTEs to parent rtable.
*
* Upper-level vars in subquery are now one level closer to their parent
* than before. We don't have to worry about offsetting varnos, though,
* because any such vars must refer to stuff above the level of the query
* we are pulling into.
*/
rtable = copyObject(subquery->rtable);
IncrementVarSublevelsUp_rtable(rtable, -1, 1);
root->parse->rtable = list_concat(root->parse->rtable, rtable);
/*
* Recursively scan the subquery's setOperations tree and add
* AppendRelInfo nodes for leaf subqueries to the parent's
* append_rel_list.
*/
Assert(subquery->setOperations);
pull_up_union_leaf_queries(subquery->setOperations, root, varno, subquery,
rtoffset);
/*
* Mark the parent as an append relation.
*/
rte->inh = true;
return jtnode;
}
/*
* pull_up_union_leaf_queries -- recursive guts of pull_up_simple_union_all
*
* Note that setOpQuery is the Query containing the setOp node, whose rtable
* is where to look up the RTE if setOp is a RangeTblRef. This is *not* the
* same as root->parse, which is the top-level Query we are pulling up into.
*
* parentRTindex is the appendrel parent's index in root->parse->rtable.
*
* The child RTEs have already been copied to the parent. childRToffset
* tells us where in the parent's range table they were copied.
*/
static void
pull_up_union_leaf_queries(Node *setOp, PlannerInfo *root, int parentRTindex,
Query *setOpQuery, int childRToffset)
{
if (IsA(setOp, RangeTblRef))
{
RangeTblRef *rtr = (RangeTblRef *) setOp;
int childRTindex;
AppendRelInfo *appinfo;
/*
* Calculate the index in the parent's range table
*/
childRTindex = childRToffset + rtr->rtindex;
/*
* Build a suitable AppendRelInfo, and attach to parent's list.
*/
appinfo = makeNode(AppendRelInfo);
appinfo->parent_relid = parentRTindex;
appinfo->child_relid = childRTindex;
appinfo->parent_reltype = InvalidOid;
appinfo->child_reltype = InvalidOid;
make_setop_translation_list(setOpQuery, childRTindex,
&appinfo->translated_vars);
appinfo->parent_reloid = InvalidOid;
root->append_rel_list = lappend(root->append_rel_list, appinfo);
/*
* Recursively apply pull_up_subqueries to the new child RTE. (We
* must build the AppendRelInfo first, because this will modify it.)
* Note that we can pass NULL for containing-join info even if we're
* actually under an outer join, because the child's expressions
* aren't going to propagate up above the join.
*/
rtr = makeNode(RangeTblRef);
rtr->rtindex = childRTindex;
(void) pull_up_subqueries(root, (Node *) rtr, NULL, appinfo);
}
else if (IsA(setOp, SetOperationStmt))
{
SetOperationStmt *op = (SetOperationStmt *) setOp;
/* Recurse to reach leaf queries */
pull_up_union_leaf_queries(op->larg, root, parentRTindex, setOpQuery,
childRToffset);
pull_up_union_leaf_queries(op->rarg, root, parentRTindex, setOpQuery,
childRToffset);
}
else
{
elog(ERROR, "unrecognized node type: %d",
(int) nodeTag(setOp));
}
}
/*
* make_setop_translation_list
* Build the list of translations from parent Vars to child Vars for
* a UNION ALL member. (At this point it's just a simple list of
* referencing Vars, but if we succeed in pulling up the member
* subquery, the Vars will get replaced by pulled-up expressions.)
*/
static void
make_setop_translation_list(Query *query, Index newvarno,
List **translated_vars)
{
List *vars = NIL;
ListCell *l;
foreach(l, query->targetList)
{
TargetEntry *tle = (TargetEntry *) lfirst(l);
if (tle->resjunk)
continue;
vars = lappend(vars, makeVar(newvarno,
tle->resno,
exprType((Node *) tle->expr),
exprTypmod((Node *) tle->expr),
0));
}
*translated_vars = vars;
}
/*
* is_simple_subquery
* Check a subquery in the range table to see if it's simple enough
* to pull up into the parent query.
*/
static bool
is_simple_subquery(Query *subquery)
{
/*
* Let's just make sure it's a valid subselect ...
*/
if (!IsA(subquery, Query) ||
subquery->commandType != CMD_SELECT ||
subquery->utilityStmt != NULL ||
subquery->intoClause != NULL)
elog(ERROR, "subquery is bogus");
/*
* Can't currently pull up a query with setops (unless it's simple UNION
* ALL, which is handled by a different code path). Maybe after querytree
* redesign...
*/
if (subquery->setOperations)
return false;
/*
* Can't pull up a subquery involving grouping, aggregation, sorting,
* limiting, or WITH. (XXX WITH could possibly be allowed later)
*
* We also don't pull up a subquery that has explicit FOR UPDATE/SHARE
* clauses, because pullup would cause the locking to occur semantically
* higher than it should. Implicit FOR UPDATE/SHARE is okay because in
* that case the locking was originally declared in the upper query
* anyway.
*/
if (subquery->hasAggs ||
subquery->hasWindowFuncs ||
subquery->groupClause ||
subquery->havingQual ||
subquery->sortClause ||
subquery->distinctClause ||
subquery->limitOffset ||
subquery->limitCount ||
subquery->hasForUpdate ||
subquery->cteList)
return false;
/*
* Don't pull up a subquery that has any set-returning functions in its
* targetlist. Otherwise we might well wind up inserting set-returning
* functions into places where they mustn't go, such as quals of higher
* queries.
*/
if (expression_returns_set((Node *) subquery->targetList))
return false;
/*
* Don't pull up a subquery that has any volatile functions in its
* targetlist. Otherwise we might introduce multiple evaluations of these
* functions, if they get copied to multiple places in the upper query,
* leading to surprising results. (Note: the PlaceHolderVar mechanism
* doesn't quite guarantee single evaluation; else we could pull up anyway
* and just wrap such items in PlaceHolderVars ...)
*/
if (contain_volatile_functions((Node *) subquery->targetList))
return false;
/*
* Hack: don't try to pull up a subquery with an empty jointree.
* query_planner() will correctly generate a Result plan for a jointree
* that's totally empty, but I don't think the right things happen if an
* empty FromExpr appears lower down in a jointree. It would pose a
* problem for the PlaceHolderVar mechanism too, since we'd have no way to
* identify where to evaluate a PHV coming out of the subquery. Not worth
* working hard on this, just to collapse SubqueryScan/Result into Result;
* especially since the SubqueryScan can often be optimized away by
* setrefs.c anyway.
*/
if (subquery->jointree->fromlist == NIL)
return false;
return true;
}
/*
* is_simple_union_all
* Check a subquery to see if it's a simple UNION ALL.
*
* We require all the setops to be UNION ALL (no mixing) and there can't be
* any datatype coercions involved, ie, all the leaf queries must emit the
* same datatypes.
*/
static bool
is_simple_union_all(Query *subquery)
{
SetOperationStmt *topop;
/* Let's just make sure it's a valid subselect ... */
if (!IsA(subquery, Query) ||
subquery->commandType != CMD_SELECT ||
subquery->utilityStmt != NULL ||
subquery->intoClause != NULL)
elog(ERROR, "subquery is bogus");
/* Is it a set-operation query at all? */
topop = (SetOperationStmt *) subquery->setOperations;
if (!topop)
return false;
Assert(IsA(topop, SetOperationStmt));
/* Can't handle ORDER BY, LIMIT/OFFSET, locking, or WITH */
if (subquery->sortClause ||
subquery->limitOffset ||
subquery->limitCount ||
subquery->rowMarks ||
subquery->cteList)
return false;
/* Recursively check the tree of set operations */
return is_simple_union_all_recurse((Node *) topop, subquery,
topop->colTypes);
}
static bool
is_simple_union_all_recurse(Node *setOp, Query *setOpQuery, List *colTypes)
{
if (IsA(setOp, RangeTblRef))
{
RangeTblRef *rtr = (RangeTblRef *) setOp;
RangeTblEntry *rte = rt_fetch(rtr->rtindex, setOpQuery->rtable);
Query *subquery = rte->subquery;
Assert(subquery != NULL);
/* Leaf nodes are OK if they match the toplevel column types */
/* We don't have to compare typmods here */
return tlist_same_datatypes(subquery->targetList, colTypes, true);
}
else if (IsA(setOp, SetOperationStmt))
{
SetOperationStmt *op = (SetOperationStmt *) setOp;
/* Must be UNION ALL */
if (op->op != SETOP_UNION || !op->all)
return false;
/* Recurse to check inputs */
return is_simple_union_all_recurse(op->larg, setOpQuery, colTypes) &&
is_simple_union_all_recurse(op->rarg, setOpQuery, colTypes);
}
else
{
elog(ERROR, "unrecognized node type: %d",
(int) nodeTag(setOp));
return false; /* keep compiler quiet */
}
}
/*
* is_safe_append_member
* Check a subquery that is a leaf of a UNION ALL appendrel to see if it's
* safe to pull up.
*/
static bool
is_safe_append_member(Query *subquery)
{
FromExpr *jtnode;
/*
* It's only safe to pull up the child if its jointree contains exactly
* one RTE, else the AppendRelInfo data structure breaks. The one base RTE
* could be buried in several levels of FromExpr, however.
*
* Also, the child can't have any WHERE quals because there's no place to
* put them in an appendrel. (This is a bit annoying...) If we didn't
* need to check this, we'd just test whether get_relids_in_jointree()
* yields a singleton set, to be more consistent with the coding of
* fix_append_rel_relids().
*/
jtnode = subquery->jointree;
while (IsA(jtnode, FromExpr))
{
if (jtnode->quals != NULL)
return false;
if (list_length(jtnode->fromlist) != 1)
return false;
jtnode = linitial(jtnode->fromlist);
}
if (!IsA(jtnode, RangeTblRef))
return false;
return true;
}
/*
* Helper routine for pull_up_subqueries: do pullup_replace_vars on every
* expression in the jointree, without changing the jointree structure itself.
* Ugly, but there's no other way...
*
* If we are at or below lowest_outer_join, we can suppress use of
* PlaceHolderVars wrapped around the replacement expressions.
*/
static void
replace_vars_in_jointree(Node *jtnode,
pullup_replace_vars_context *context,
JoinExpr *lowest_outer_join)
{
if (jtnode == NULL)
return;
if (IsA(jtnode, RangeTblRef))
{
/* nothing to do here */
}
else if (IsA(jtnode, FromExpr))
{
FromExpr *f = (FromExpr *) jtnode;
ListCell *l;
foreach(l, f->fromlist)
replace_vars_in_jointree(lfirst(l), context, lowest_outer_join);
f->quals = pullup_replace_vars(f->quals, context);
}
else if (IsA(jtnode, JoinExpr))
{
JoinExpr *j = (JoinExpr *) jtnode;
bool save_need_phvs = context->need_phvs;
if (j == lowest_outer_join)
{
/* no more PHVs in or below this join */
context->need_phvs = false;
lowest_outer_join = NULL;
}
replace_vars_in_jointree(j->larg, context, lowest_outer_join);
replace_vars_in_jointree(j->rarg, context, lowest_outer_join);
j->quals = pullup_replace_vars(j->quals, context);
/*
* We don't bother to update the colvars list, since it won't be used
* again ...
*/
context->need_phvs = save_need_phvs;
}
else
elog(ERROR, "unrecognized node type: %d",
(int) nodeTag(jtnode));
}
/*
* Apply pullup variable replacement throughout an expression tree
*
* Returns a modified copy of the tree, so this can't be used where we
* need to do in-place replacement.
*/
static Node *
pullup_replace_vars(Node *expr, pullup_replace_vars_context *context)
{
return replace_rte_variables(expr,
context->varno, 0,
pullup_replace_vars_callback,
(void *) context,
context->outer_hasSubLinks);
}
static Node *
pullup_replace_vars_callback(Var *var,
replace_rte_variables_context *context)
{
pullup_replace_vars_context *rcon = (pullup_replace_vars_context *) context->callback_arg;
int varattno = var->varattno;
Node *newnode;
/*
* If PlaceHolderVars are needed, we cache the modified expressions in
* rcon->rv_cache[]. This is not in hopes of any material speed gain
* within this function, but to avoid generating identical PHVs with
* different IDs. That would result in duplicate evaluations at runtime,
* and possibly prevent optimizations that rely on recognizing different
* references to the same subquery output as being equal(). So it's worth
* a bit of extra effort to avoid it.
*/
if (rcon->need_phvs &&
varattno >= InvalidAttrNumber &&
varattno <= list_length(rcon->targetlist) &&
rcon->rv_cache[varattno] != NULL)
{
/* Just copy the entry and fall through to adjust its varlevelsup */
newnode = copyObject(rcon->rv_cache[varattno]);
}
else if (varattno == InvalidAttrNumber)
{
/* Must expand whole-tuple reference into RowExpr */
RowExpr *rowexpr;
List *colnames;
List *fields;
bool save_need_phvs = rcon->need_phvs;
int save_sublevelsup = context->sublevels_up;
/*
* If generating an expansion for a var of a named rowtype (ie, this
* is a plain relation RTE), then we must include dummy items for
* dropped columns. If the var is RECORD (ie, this is a JOIN), then
* omit dropped columns. Either way, attach column names to the
* RowExpr for use of ruleutils.c.
*
* In order to be able to cache the results, we always generate the
* expansion with varlevelsup = 0, and then adjust if needed.
*/
expandRTE(rcon->target_rte,
var->varno, 0 /* not varlevelsup */ , var->location,
(var->vartype != RECORDOID),
&colnames, &fields);
/* Adjust the generated per-field Vars, but don't insert PHVs */
rcon->need_phvs = false;
context->sublevels_up = 0; /* to match the expandRTE output */
fields = (List *) replace_rte_variables_mutator((Node *) fields,
context);
rcon->need_phvs = save_need_phvs;
context->sublevels_up = save_sublevelsup;
rowexpr = makeNode(RowExpr);
rowexpr->args = fields;
rowexpr->row_typeid = var->vartype;
rowexpr->row_format = COERCE_IMPLICIT_CAST;
rowexpr->colnames = colnames;
rowexpr->location = var->location;
newnode = (Node *) rowexpr;
/*
* Insert PlaceHolderVar if needed. Notice that we are wrapping one
* PlaceHolderVar around the whole RowExpr, rather than putting one
* around each element of the row. This is because we need the
* expression to yield NULL, not ROW(NULL,NULL,...) when it is forced
* to null by an outer join.
*/
if (rcon->need_phvs)
{
/* RowExpr is certainly not strict, so always need PHV */
newnode = (Node *)
make_placeholder_expr(rcon->root,
(Expr *) newnode,
bms_make_singleton(rcon->varno));
/* cache it with the PHV, and with varlevelsup still zero */
rcon->rv_cache[InvalidAttrNumber] = copyObject(newnode);
}
}
else
{
/* Normal case referencing one targetlist element */
TargetEntry *tle = get_tle_by_resno(rcon->targetlist, varattno);
if (tle == NULL) /* shouldn't happen */
elog(ERROR, "could not find attribute %d in subquery targetlist",
varattno);
/* Make a copy of the tlist item to return */
newnode = copyObject(tle->expr);
/* Insert PlaceHolderVar if needed */
if (rcon->need_phvs)
{
bool wrap;
if (newnode && IsA(newnode, Var) &&
((Var *) newnode)->varlevelsup == 0)
{
/* Simple Vars always escape being wrapped */
wrap = false;
}
else if (rcon->wrap_non_vars)
{
/* Wrap all non-Vars in a PlaceHolderVar */
wrap = true;
}
else
{
/*
* If it contains a Var of current level, and does not contain
* any non-strict constructs, then it's certainly nullable and
* we don't need to insert a PlaceHolderVar. (Note: in future
* maybe we should insert PlaceHolderVars anyway, when a tlist
* item is expensive to evaluate?
*/
if (contain_vars_of_level((Node *) newnode, 0) &&
!contain_nonstrict_functions((Node *) newnode))
{
/* No wrap needed */
wrap = false;
}
else
{
/* Else wrap it in a PlaceHolderVar */
wrap = true;
}
}
if (wrap)
newnode = (Node *)
make_placeholder_expr(rcon->root,
(Expr *) newnode,
bms_make_singleton(rcon->varno));
/*
* Cache it if possible (ie, if the attno is in range, which it
* probably always should be). We can cache the value even if we
* decided we didn't need a PHV, since this result will be
* suitable for any request that has need_phvs.
*/
if (varattno > InvalidAttrNumber &&
varattno <= list_length(rcon->targetlist))
rcon->rv_cache[varattno] = copyObject(newnode);
}
}
/* Must adjust varlevelsup if tlist item is from higher query */
if (var->varlevelsup > 0)
IncrementVarSublevelsUp(newnode, var->varlevelsup, 0);
return newnode;
}
/*
* reduce_outer_joins
* Attempt to reduce outer joins to plain inner joins.
*
* The idea here is that given a query like
* SELECT ... FROM a LEFT JOIN b ON (...) WHERE b.y = 42;
* we can reduce the LEFT JOIN to a plain JOIN if the "=" operator in WHERE
* is strict. The strict operator will always return NULL, causing the outer
* WHERE to fail, on any row where the LEFT JOIN filled in NULLs for b's
* columns. Therefore, there's no need for the join to produce null-extended
* rows in the first place --- which makes it a plain join not an outer join.
* (This scenario may not be very likely in a query written out by hand, but
* it's reasonably likely when pushing quals down into complex views.)
*
* More generally, an outer join can be reduced in strength if there is a
* strict qual above it in the qual tree that constrains a Var from the
* nullable side of the join to be non-null. (For FULL joins this applies
* to each side separately.)
*
* Another transformation we apply here is to recognize cases like
* SELECT ... FROM a LEFT JOIN b ON (a.x = b.y) WHERE b.y IS NULL;
* If the join clause is strict for b.y, then only null-extended rows could
* pass the upper WHERE, and we can conclude that what the query is really
* specifying is an anti-semijoin. We change the join type from JOIN_LEFT
* to JOIN_ANTI. The IS NULL clause then becomes redundant, and must be
* removed to prevent bogus selectivity calculations, but we leave it to
* distribute_qual_to_rels to get rid of such clauses.
*
* Also, we get rid of JOIN_RIGHT cases by flipping them around to become
* JOIN_LEFT. This saves some code here and in some later planner routines,
* but the main reason to do it is to not need to invent a JOIN_REVERSE_ANTI
* join type.
*
* To ease recognition of strict qual clauses, we require this routine to be
* run after expression preprocessing (i.e., qual canonicalization and JOIN
* alias-var expansion).
*/
void
reduce_outer_joins(PlannerInfo *root)
{
reduce_outer_joins_state *state;
/*
* To avoid doing strictness checks on more quals than necessary, we want
* to stop descending the jointree as soon as there are no outer joins
* below our current point. This consideration forces a two-pass process.
* The first pass gathers information about which base rels appear below
* each side of each join clause, and about whether there are outer
* join(s) below each side of each join clause. The second pass examines
* qual clauses and changes join types as it descends the tree.
*/
state = reduce_outer_joins_pass1((Node *) root->parse->jointree);
/* planner.c shouldn't have called me if no outer joins */
if (state == NULL || !state->contains_outer)
elog(ERROR, "so where are the outer joins?");
reduce_outer_joins_pass2((Node *) root->parse->jointree,
state, root, NULL, NIL, NIL);
}
/*
* reduce_outer_joins_pass1 - phase 1 data collection
*
* Returns a state node describing the given jointree node.
*/
static reduce_outer_joins_state *
reduce_outer_joins_pass1(Node *jtnode)
{
reduce_outer_joins_state *result;
result = (reduce_outer_joins_state *)
palloc(sizeof(reduce_outer_joins_state));
result->relids = NULL;
result->contains_outer = false;
result->sub_states = NIL;
if (jtnode == NULL)
return result;
if (IsA(jtnode, RangeTblRef))
{
int varno = ((RangeTblRef *) jtnode)->rtindex;
result->relids = bms_make_singleton(varno);
}
else if (IsA(jtnode, FromExpr))
{
FromExpr *f = (FromExpr *) jtnode;
ListCell *l;
foreach(l, f->fromlist)
{
reduce_outer_joins_state *sub_state;
sub_state = reduce_outer_joins_pass1(lfirst(l));
result->relids = bms_add_members(result->relids,
sub_state->relids);
result->contains_outer |= sub_state->contains_outer;
result->sub_states = lappend(result->sub_states, sub_state);
}
}
else if (IsA(jtnode, JoinExpr))
{
JoinExpr *j = (JoinExpr *) jtnode;
reduce_outer_joins_state *sub_state;
/* join's own RT index is not wanted in result->relids */
if (IS_OUTER_JOIN(j->jointype))
result->contains_outer = true;
sub_state = reduce_outer_joins_pass1(j->larg);
result->relids = bms_add_members(result->relids,
sub_state->relids);
result->contains_outer |= sub_state->contains_outer;
result->sub_states = lappend(result->sub_states, sub_state);
sub_state = reduce_outer_joins_pass1(j->rarg);
result->relids = bms_add_members(result->relids,
sub_state->relids);
result->contains_outer |= sub_state->contains_outer;
result->sub_states = lappend(result->sub_states, sub_state);
}
else
elog(ERROR, "unrecognized node type: %d",
(int) nodeTag(jtnode));
return result;
}
/*
* reduce_outer_joins_pass2 - phase 2 processing
*
* jtnode: current jointree node
* state: state data collected by phase 1 for this node
* root: toplevel planner state
* nonnullable_rels: set of base relids forced non-null by upper quals
* nonnullable_vars: list of Vars forced non-null by upper quals
* forced_null_vars: list of Vars forced null by upper quals
*/
static void
reduce_outer_joins_pass2(Node *jtnode,
reduce_outer_joins_state *state,
PlannerInfo *root,
Relids nonnullable_rels,
List *nonnullable_vars,
List *forced_null_vars)
{
/*
* pass 2 should never descend as far as an empty subnode or base rel,
* because it's only called on subtrees marked as contains_outer.
*/
if (jtnode == NULL)
elog(ERROR, "reached empty jointree");
if (IsA(jtnode, RangeTblRef))
elog(ERROR, "reached base rel");
else if (IsA(jtnode, FromExpr))
{
FromExpr *f = (FromExpr *) jtnode;
ListCell *l;
ListCell *s;
Relids pass_nonnullable_rels;
List *pass_nonnullable_vars;
List *pass_forced_null_vars;
/* Scan quals to see if we can add any constraints */
pass_nonnullable_rels = find_nonnullable_rels(f->quals);
pass_nonnullable_rels = bms_add_members(pass_nonnullable_rels,
nonnullable_rels);
/* NB: we rely on list_concat to not damage its second argument */
pass_nonnullable_vars = find_nonnullable_vars(f->quals);
pass_nonnullable_vars = list_concat(pass_nonnullable_vars,
nonnullable_vars);
pass_forced_null_vars = find_forced_null_vars(f->quals);
pass_forced_null_vars = list_concat(pass_forced_null_vars,
forced_null_vars);
/* And recurse --- but only into interesting subtrees */
Assert(list_length(f->fromlist) == list_length(state->sub_states));
forboth(l, f->fromlist, s, state->sub_states)
{
reduce_outer_joins_state *sub_state = lfirst(s);
if (sub_state->contains_outer)
reduce_outer_joins_pass2(lfirst(l), sub_state, root,
pass_nonnullable_rels,
pass_nonnullable_vars,
pass_forced_null_vars);
}
bms_free(pass_nonnullable_rels);
/* can't so easily clean up var lists, unfortunately */
}
else if (IsA(jtnode, JoinExpr))
{
JoinExpr *j = (JoinExpr *) jtnode;
int rtindex = j->rtindex;
JoinType jointype = j->jointype;
reduce_outer_joins_state *left_state = linitial(state->sub_states);
reduce_outer_joins_state *right_state = lsecond(state->sub_states);
List *local_nonnullable_vars = NIL;
bool computed_local_nonnullable_vars = false;
/* Can we simplify this join? */
switch (jointype)
{
case JOIN_INNER:
break;
case JOIN_LEFT:
if (bms_overlap(nonnullable_rels, right_state->relids))
jointype = JOIN_INNER;
break;
case JOIN_RIGHT:
if (bms_overlap(nonnullable_rels, left_state->relids))
jointype = JOIN_INNER;
break;
case JOIN_FULL:
if (bms_overlap(nonnullable_rels, left_state->relids))
{
if (bms_overlap(nonnullable_rels, right_state->relids))
jointype = JOIN_INNER;
else
jointype = JOIN_LEFT;
}
else
{
if (bms_overlap(nonnullable_rels, right_state->relids))
jointype = JOIN_RIGHT;
}
break;
case JOIN_SEMI:
case JOIN_ANTI:
/*
* These could only have been introduced by pull_up_sublinks,
* so there's no way that upper quals could refer to their
* righthand sides, and no point in checking.
*/
break;
default:
elog(ERROR, "unrecognized join type: %d",
(int) jointype);
break;
}
/*
* Convert JOIN_RIGHT to JOIN_LEFT. Note that in the case where we
* reduced JOIN_FULL to JOIN_RIGHT, this will mean the JoinExpr no
* longer matches the internal ordering of any CoalesceExpr's built to
* represent merged join variables. We don't care about that at
* present, but be wary of it ...
*/
if (jointype == JOIN_RIGHT)
{
Node *tmparg;
tmparg = j->larg;
j->larg = j->rarg;
j->rarg = tmparg;
jointype = JOIN_LEFT;
right_state = linitial(state->sub_states);
left_state = lsecond(state->sub_states);
}
/*
* See if we can reduce JOIN_LEFT to JOIN_ANTI. This is the case if
* the join's own quals are strict for any var that was forced null by
* higher qual levels. NOTE: there are other ways that we could
* detect an anti-join, in particular if we were to check whether Vars
* coming from the RHS must be non-null because of table constraints.
* That seems complicated and expensive though (in particular, one
* would have to be wary of lower outer joins). For the moment this
* seems sufficient.
*/
if (jointype == JOIN_LEFT)
{
List *overlap;
local_nonnullable_vars = find_nonnullable_vars(j->quals);
computed_local_nonnullable_vars = true;
/*
* It's not sufficient to check whether local_nonnullable_vars and
* forced_null_vars overlap: we need to know if the overlap
* includes any RHS variables.
*/
overlap = list_intersection(local_nonnullable_vars,
forced_null_vars);
if (overlap != NIL &&
bms_overlap(pull_varnos((Node *) overlap),
right_state->relids))
jointype = JOIN_ANTI;
}
/* Apply the jointype change, if any, to both jointree node and RTE */
if (rtindex && jointype != j->jointype)
{
RangeTblEntry *rte = rt_fetch(rtindex, root->parse->rtable);
Assert(rte->rtekind == RTE_JOIN);
Assert(rte->jointype == j->jointype);
rte->jointype = jointype;
}
j->jointype = jointype;
/* Only recurse if there's more to do below here */
if (left_state->contains_outer || right_state->contains_outer)
{
Relids local_nonnullable_rels;
List *local_forced_null_vars;
Relids pass_nonnullable_rels;
List *pass_nonnullable_vars;
List *pass_forced_null_vars;
/*
* If this join is (now) inner, we can add any constraints its
* quals provide to those we got from above. But if it is outer,
* we can pass down the local constraints only into the nullable
* side, because an outer join never eliminates any rows from its
* non-nullable side. Also, there is no point in passing upper
* constraints into the nullable side, since if there were any
* we'd have been able to reduce the join. (In the case of upper
* forced-null constraints, we *must not* pass them into the
* nullable side --- they either applied here, or not.) The upshot
* is that we pass either the local or the upper constraints,
* never both, to the children of an outer join.
*
* At a FULL join we just punt and pass nothing down --- is it
* possible to be smarter?
*/
if (jointype != JOIN_FULL)
{
local_nonnullable_rels = find_nonnullable_rels(j->quals);
if (!computed_local_nonnullable_vars)
local_nonnullable_vars = find_nonnullable_vars(j->quals);
local_forced_null_vars = find_forced_null_vars(j->quals);
if (jointype == JOIN_INNER)
{
/* OK to merge upper and local constraints */
local_nonnullable_rels = bms_add_members(local_nonnullable_rels,
nonnullable_rels);
local_nonnullable_vars = list_concat(local_nonnullable_vars,
nonnullable_vars);
local_forced_null_vars = list_concat(local_forced_null_vars,
forced_null_vars);
}
}
else
{
/* no use in calculating these */
local_nonnullable_rels = NULL;
local_forced_null_vars = NIL;
}
if (left_state->contains_outer)
{
if (jointype == JOIN_INNER)
{
/* pass union of local and upper constraints */
pass_nonnullable_rels = local_nonnullable_rels;
pass_nonnullable_vars = local_nonnullable_vars;
pass_forced_null_vars = local_forced_null_vars;
}
else if (jointype != JOIN_FULL) /* ie, LEFT/SEMI/ANTI */
{
/* can't pass local constraints to non-nullable side */
pass_nonnullable_rels = nonnullable_rels;
pass_nonnullable_vars = nonnullable_vars;
pass_forced_null_vars = forced_null_vars;
}
else
{
/* no constraints pass through JOIN_FULL */
pass_nonnullable_rels = NULL;
pass_nonnullable_vars = NIL;
pass_forced_null_vars = NIL;
}
reduce_outer_joins_pass2(j->larg, left_state, root,
pass_nonnullable_rels,
pass_nonnullable_vars,
pass_forced_null_vars);
}
if (right_state->contains_outer)
{
if (jointype != JOIN_FULL) /* ie, INNER/LEFT/SEMI/ANTI */
{
/* pass appropriate constraints, per comment above */
pass_nonnullable_rels = local_nonnullable_rels;
pass_nonnullable_vars = local_nonnullable_vars;
pass_forced_null_vars = local_forced_null_vars;
}
else
{
/* no constraints pass through JOIN_FULL */
pass_nonnullable_rels = NULL;
pass_nonnullable_vars = NIL;
pass_forced_null_vars = NIL;
}
reduce_outer_joins_pass2(j->rarg, right_state, root,
pass_nonnullable_rels,
pass_nonnullable_vars,
pass_forced_null_vars);
}
bms_free(local_nonnullable_rels);
}
}
else
elog(ERROR, "unrecognized node type: %d",
(int) nodeTag(jtnode));
}
/*
* substitute_multiple_relids - adjust node relid sets after pulling up
* a subquery
*
* Find any PlaceHolderVar nodes in the given tree that reference the
* pulled-up relid, and change them to reference the replacement relid(s).
* We do not need to recurse into subqueries, since no subquery of the current
* top query could (yet) contain such a reference.
*
* NOTE: although this has the form of a walker, we cheat and modify the
* nodes in-place. This should be OK since the tree was copied by
* pullup_replace_vars earlier. Avoid scribbling on the original values of
* the bitmapsets, though, because expression_tree_mutator doesn't copy those.
*/
typedef struct
{
int varno;
Relids subrelids;
} substitute_multiple_relids_context;
static bool
substitute_multiple_relids_walker(Node *node,
substitute_multiple_relids_context *context)
{
if (node == NULL)
return false;
if (IsA(node, PlaceHolderVar))
{
PlaceHolderVar *phv = (PlaceHolderVar *) node;
if (bms_is_member(context->varno, phv->phrels))
{
phv->phrels = bms_union(phv->phrels,
context->subrelids);
phv->phrels = bms_del_member(phv->phrels,
context->varno);
}
/* fall through to examine children */
}
/* Shouldn't need to handle planner auxiliary nodes here */
Assert(!IsA(node, SpecialJoinInfo));
Assert(!IsA(node, AppendRelInfo));
Assert(!IsA(node, PlaceHolderInfo));
return expression_tree_walker(node, substitute_multiple_relids_walker,
(void *) context);
}
static void
substitute_multiple_relids(Node *node, int varno, Relids subrelids)
{
substitute_multiple_relids_context context;
context.varno = varno;
context.subrelids = subrelids;
/*
* Must be prepared to start with a Query or a bare expression tree.
*/
query_or_expression_tree_walker(node,
substitute_multiple_relids_walker,
(void *) &context,
0);
}
/*
* fix_append_rel_relids: update RT-index fields of AppendRelInfo nodes
*
* When we pull up a subquery, any AppendRelInfo references to the subquery's
* RT index have to be replaced by the substituted relid (and there had better
* be only one). We also need to apply substitute_multiple_relids to their
* translated_vars lists, since those might contain PlaceHolderVars.
*
* We assume we may modify the AppendRelInfo nodes in-place.
*/
static void
fix_append_rel_relids(List *append_rel_list, int varno, Relids subrelids)
{
ListCell *l;
int subvarno = -1;
/*
* We only want to extract the member relid once, but we mustn't fail
* immediately if there are multiple members; it could be that none of the
* AppendRelInfo nodes refer to it. So compute it on first use. Note that
* bms_singleton_member will complain if set is not singleton.
*/
foreach(l, append_rel_list)
{
AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
/* The parent_relid shouldn't ever be a pullup target */
Assert(appinfo->parent_relid != varno);
if (appinfo->child_relid == varno)
{
if (subvarno < 0)
subvarno = bms_singleton_member(subrelids);
appinfo->child_relid = subvarno;
}
/* Also finish fixups for its translated vars */
substitute_multiple_relids((Node *) appinfo->translated_vars,
varno, subrelids);
}
}
/*
* get_relids_in_jointree: get set of RT indexes present in a jointree
*
* If include_joins is true, join RT indexes are included; if false,
* only base rels are included.
*/
Relids
get_relids_in_jointree(Node *jtnode, bool include_joins)
{
Relids result = NULL;
if (jtnode == NULL)
return result;
if (IsA(jtnode, RangeTblRef))
{
int varno = ((RangeTblRef *) jtnode)->rtindex;
result = bms_make_singleton(varno);
}
else if (IsA(jtnode, FromExpr))
{
FromExpr *f = (FromExpr *) jtnode;
ListCell *l;
foreach(l, f->fromlist)
{
result = bms_join(result,
get_relids_in_jointree(lfirst(l),
include_joins));
}
}
else if (IsA(jtnode, JoinExpr))
{
JoinExpr *j = (JoinExpr *) jtnode;
result = get_relids_in_jointree(j->larg, include_joins);
result = bms_join(result,
get_relids_in_jointree(j->rarg, include_joins));
if (include_joins && j->rtindex)
result = bms_add_member(result, j->rtindex);
}
else
elog(ERROR, "unrecognized node type: %d",
(int) nodeTag(jtnode));
return result;
}
/*
* get_relids_for_join: get set of base RT indexes making up a join
*/
Relids
get_relids_for_join(PlannerInfo *root, int joinrelid)
{
Node *jtnode;
jtnode = find_jointree_node_for_rel((Node *) root->parse->jointree,
joinrelid);
if (!jtnode)
elog(ERROR, "could not find join node %d", joinrelid);
return get_relids_in_jointree(jtnode, false);
}
/*
* find_jointree_node_for_rel: locate jointree node for a base or join RT index
*
* Returns NULL if not found
*/
static Node *
find_jointree_node_for_rel(Node *jtnode, int relid)
{
if (jtnode == NULL)
return NULL;
if (IsA(jtnode, RangeTblRef))
{
int varno = ((RangeTblRef *) jtnode)->rtindex;
if (relid == varno)
return jtnode;
}
else if (IsA(jtnode, FromExpr))
{
FromExpr *f = (FromExpr *) jtnode;
ListCell *l;
foreach(l, f->fromlist)
{
jtnode = find_jointree_node_for_rel(lfirst(l), relid);
if (jtnode)
return jtnode;
}
}
else if (IsA(jtnode, JoinExpr))
{
JoinExpr *j = (JoinExpr *) jtnode;
if (relid == j->rtindex)
return jtnode;
jtnode = find_jointree_node_for_rel(j->larg, relid);
if (jtnode)
return jtnode;
jtnode = find_jointree_node_for_rel(j->rarg, relid);
if (jtnode)
return jtnode;
}
else
elog(ERROR, "unrecognized node type: %d",
(int) nodeTag(jtnode));
return NULL;
}
|
TextusData/Mover
|
thirdparty/postgresql-9.0.1/src/backend/optimizer/prep/prepjointree.c
|
C
|
gpl-3.0
| 66,368
|
/*
* This is a plugin for GIMP.
*
* Copyright (C) 1997 Xavier Bouchoux
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/*
* This plug-in produces sinus textures.
*
* Please send any patches or suggestions to me: Xavier.Bouchoux@ensimag.imag.fr.
*/
/* Version 0.99 */
#include "config.h"
#include <libgimp/gimp.h>
#include <libgimp/gimpui.h>
#include "libgimp/stdplugins-intl.h"
#define PLUG_IN_PROC "plug-in-sinus"
#define PLUG_IN_BINARY "sinus"
#define PLUG_IN_ROLE "gimp-sinus"
/*
* This structure is used for persistent data.
*/
#define B_W 0L /* colors setting */
#define USE_FG_BG 1L
#define USE_COLORS 2L
#define LINEAR 0L /* colorization settings */
#define BILINEAR 1L
#define SINUS 2L
#define IDEAL 0L /* Perturbation settings */
#define PERTURBED 1L
typedef struct
{
gdouble scalex;
gdouble scaley;
gdouble cmplx;
gdouble blend_power;
guint32 seed;
gint tiling;
glong perturbation;
glong colorization;
glong colors;
GimpRGB col1;
GimpRGB col2;
gboolean random_seed;
} SinusVals;
static SinusVals svals =
{
15.0,
15.0,
1.0,
0.0,
42,
TRUE,
PERTURBED,
LINEAR,
USE_COLORS,
{ 1.0, 1.0, 0.0, 1.0 },
{ 0.0, 0.0, 1.0, 1.0 },
FALSE
};
typedef struct
{
gint height, width;
gdouble c11, c12, c13, c21, c22, c23, c31, c32, c33;
gdouble (*blend) (double );
guchar r, g, b, a;
gint dr, dg, db, da;
} params;
typedef struct
{
gint width;
gint height;
gint bpp;
gdouble scale;
guchar *bits;
} mwPreview;
static gboolean drawable_is_grayscale = FALSE;
static mwPreview *thePreview;
static GimpDrawable *drawable;
/* preview stuff -- to be removed as soon as we have a real libgimp preview */
#define PREVIEW_SIZE 100
static gboolean do_preview = TRUE;
static GtkWidget * mw_preview_new (GtkWidget *parent,
mwPreview *mwp);
static mwPreview * mw_preview_build_virgin (GimpDrawable *drw);
/* Declare functions */
static void query (void);
static void run (const gchar *name,
gint nparams,
const GimpParam *param,
gint *nreturn_vals,
GimpParam **return_vals);
static void sinus (void);
static gdouble linear (gdouble v);
static gdouble bilinear (gdouble v);
static gdouble cosinus (gdouble v);
static gint sinus_dialog (void);
static void sinus_do_preview (GtkWidget *widget);
static void assign_block_4 (guchar *dest, gdouble grey, params *p);
static void assign_block_3 (guchar *dest, gdouble grey, params *p);
static void assign_block_2 (guchar *dest, gdouble grey, params *p);
static void assign_block_1 (guchar *dest, gdouble grey, params *p);
static void compute_block_x (guchar *dest_row,
guint rowstride,
gint x0, gint y0, gint w, gint h,
gint bpp,
void (*assign)(guchar *dest, gdouble grey,
params *p),
params *p);
const GimpPlugInInfo PLUG_IN_INFO =
{
NULL, /* init_proc */
NULL, /* quit_proc */
query, /* query_proc */
run, /* run_proc */
};
MAIN ()
static void
query (void)
{
static const GimpParamDef args[] =
{
{ GIMP_PDB_INT32, "run-mode", "The run mode { RUN-INTERACTIVE (0), RUN-NONINTERACTIVE (1) }" },
{ GIMP_PDB_IMAGE, "image", "Input image (unused)" },
{ GIMP_PDB_DRAWABLE, "drawable", "Input drawable" },
{ GIMP_PDB_FLOAT, "xscale", "Scale value for x axis" },
{ GIMP_PDB_FLOAT, "yscale", "Scale value dor y axis" },
{ GIMP_PDB_FLOAT, "complex", "Complexity factor" },
{ GIMP_PDB_INT32, "seed", "Seed value for random number generator" },
{ GIMP_PDB_INT32, "tiling", "If set, the pattern generated will tile" },
{ GIMP_PDB_INT32, "perturb", "If set, the pattern is a little more distorted..." },
{ GIMP_PDB_INT32, "colors", "where to take the colors (0= B&W, 1= fg/bg, 2= col1/col2)"},
{ GIMP_PDB_COLOR, "col1", "fist color (sometimes unused)" },
{ GIMP_PDB_COLOR, "col2", "second color (sometimes unused)" },
{ GIMP_PDB_FLOAT, "alpha1", "alpha for the first color (used if the drawable has an alpha chanel)" },
{ GIMP_PDB_FLOAT, "alpha2", "alpha for the second color (used if the drawable has an alpha chanel)" },
{ GIMP_PDB_INT32, "blend", "0= linear, 1= bilinear, 2= sinusoidal" },
{ GIMP_PDB_FLOAT, "blend-power", "Power used to strech the blend" }
};
gimp_install_procedure (PLUG_IN_PROC,
N_("Generate complex sinusoidal textures"),
"FIX ME: sinus help",
"Xavier Bouchoux",
"Xavier Bouchoux",
"1997",
N_("_Sinus..."),
"RGB*, GRAY*",
GIMP_PLUGIN,
G_N_ELEMENTS (args), 0,
args, NULL);
gimp_plugin_menu_register (PLUG_IN_PROC, "<Image>/Filters/Render/Pattern");
}
static void
run (const gchar *name,
gint nparams,
const GimpParam *param,
gint *nreturn_vals,
GimpParam **return_vals)
{
static GimpParam values[1];
GimpRunMode run_mode;
GimpPDBStatusType status = GIMP_PDB_SUCCESS;
run_mode = param[0].data.d_int32;
*nreturn_vals = 1;
*return_vals = values;
values[0].type = GIMP_PDB_STATUS;
values[0].data.d_status = status;
INIT_I18N ();
switch (run_mode)
{
case GIMP_RUN_INTERACTIVE:
/* Possibly retrieve data */
gimp_get_data (PLUG_IN_PROC, &svals);
/* In order to prepare the dialog I need to know whether it's grayscale or not */
drawable = gimp_drawable_get (param[2].data.d_drawable);
thePreview = mw_preview_build_virgin(drawable);
drawable_is_grayscale = gimp_drawable_is_gray (drawable->drawable_id);
if (! sinus_dialog ())
return;
break;
case GIMP_RUN_NONINTERACTIVE:
/* Make sure all the arguments are there! */
if (nparams != 17)
{
status = GIMP_PDB_CALLING_ERROR;
}
else
{
svals.scalex = param[3].data.d_float;
svals.scaley = param[4].data.d_float;
svals.cmplx = param[5].data.d_float;
svals.seed = param[6].data.d_int32;
svals.tiling = param[7].data.d_int32;
svals.perturbation = param[8].data.d_int32;
svals.colors = param[9].data.d_int32;
svals.col1 = param[10].data.d_color;
svals.col2 = param[11].data.d_color;
gimp_rgb_set_alpha (&svals.col1, param[12].data.d_float);
gimp_rgb_set_alpha (&svals.col2, param[13].data.d_float);
svals.colorization = param[14].data.d_int32;
svals.blend_power = param[15].data.d_float;
if (svals.random_seed)
svals.seed = g_random_int ();
}
break;
case GIMP_RUN_WITH_LAST_VALS:
/* Possibly retrieve data */
gimp_get_data (PLUG_IN_PROC, &svals);
if (svals.random_seed)
svals.seed = g_random_int ();
break;
default:
break;
}
/* Get the specified drawable */
drawable = gimp_drawable_get (param[2].data.d_drawable);
/* Make sure that the drawable is gray or RGB */
if ((status == GIMP_PDB_SUCCESS) &&
(gimp_drawable_is_rgb (drawable->drawable_id) ||
gimp_drawable_is_gray (drawable->drawable_id)))
{
gimp_progress_init (_("Sinus: rendering"));
gimp_tile_cache_ntiles (1);
sinus ();
if (run_mode != GIMP_RUN_NONINTERACTIVE)
gimp_displays_flush ();
/* Store data */
if (run_mode == GIMP_RUN_INTERACTIVE)
gimp_set_data (PLUG_IN_PROC, &svals, sizeof (SinusVals));
}
else
{
status = GIMP_PDB_EXECUTION_ERROR;
}
values[0].data.d_status = status;
gimp_drawable_detach (drawable);
}
/*
* Main procedure
*/
static void
prepare_coef (params *p)
{
GimpRGB color1;
GimpRGB color2;
gdouble scalex = svals.scalex;
gdouble scaley = svals.scaley;
GRand *gr;
gr = g_rand_new ();
g_rand_set_seed (gr, svals.seed);
switch (svals.colorization)
{
case BILINEAR:
p->blend = bilinear;
break;
case SINUS:
p->blend = cosinus;
break;
case LINEAR:
default:
p->blend = linear;
}
if (svals.perturbation==IDEAL)
{
/* Presumably the 0 * g_rand_int ()s are to pop random
* values off the prng, I don't see why though. */
p->c11= 0 * g_rand_int (gr);
p->c12= g_rand_double_range (gr, -1, 1) * scaley;
p->c13= g_rand_double_range (gr, 0, 2 * G_PI);
p->c21= 0 * g_rand_int (gr);
p->c22= g_rand_double_range (gr, -1, 1) * scaley;
p->c23= g_rand_double_range (gr, 0, 2 * G_PI);
p->c31= g_rand_double_range (gr, -1, 1) * scalex;
p->c32= 0 * g_rand_int (gr);
p->c33= g_rand_double_range (gr, 0, 2 * G_PI);
}
else
{
p->c11= g_rand_double_range (gr, -1, 1) * scalex;
p->c12= g_rand_double_range (gr, -1, 1) * scaley;
p->c13= g_rand_double_range (gr, 0, 2 * G_PI);
p->c21= g_rand_double_range (gr, -1, 1) * scalex;
p->c22= g_rand_double_range (gr, -1, 1) * scaley;
p->c23= g_rand_double_range (gr, 0, 2 * G_PI);
p->c31= g_rand_double_range (gr, -1, 1) * scalex;
p->c32= g_rand_double_range (gr, -1, 1) * scaley;
p->c33= g_rand_double_range (gr, 0, 2 * G_PI);
}
if (svals.tiling)
{
p->c11= ROUND (p->c11/(2*G_PI))*2*G_PI;
p->c12= ROUND (p->c12/(2*G_PI))*2*G_PI;
p->c21= ROUND (p->c21/(2*G_PI))*2*G_PI;
p->c22= ROUND (p->c22/(2*G_PI))*2*G_PI;
p->c31= ROUND (p->c31/(2*G_PI))*2*G_PI;
p->c32= ROUND (p->c32/(2*G_PI))*2*G_PI;
}
color1 = svals.col1;
color2 = svals.col2;
if (drawable_is_grayscale)
{
gimp_rgb_set (&color1, 1.0, 1.0, 1.0);
gimp_rgb_set (&color2, 0.0, 0.0, 0.0);
}
else
{
switch (svals.colors)
{
case USE_COLORS:
break;
case B_W:
gimp_rgb_set (&color1, 1.0, 1.0, 1.0);
gimp_rgb_set (&color2, 0.0, 0.0, 0.0);
break;
case USE_FG_BG:
gimp_context_get_background (&color1);
gimp_context_get_foreground (&color2);
break;
}
}
gimp_rgba_get_uchar (&color1, &p->r, &p->g, &p->b, &p->a);
gimp_rgba_subtract (&color2, &color1);
p->dr = color2.r * 255.0;
p->dg = color2.g * 255.0;
p->db = color2.b * 255.0;
p->da = color2.a * 255.0;
g_rand_free (gr);
}
static void
sinus (void)
{
params p;
gint bytes;
GimpPixelRgn dest_rgn;
gint x1, y1, x2, y2;
gpointer pr;
gint progress, max_progress;
prepare_coef(&p);
gimp_drawable_mask_bounds(drawable->drawable_id, &x1, &y1, &x2, &y2);
p.width = drawable->width;
p.height = drawable->height;
bytes = drawable->bpp;
gimp_pixel_rgn_init (&dest_rgn, drawable,
x1, y1, x2 - x1, y2 - y1, TRUE,TRUE);
progress = 0;
max_progress = (x2 - x1) * (y2 - y1);
for (pr = gimp_pixel_rgns_register (1, &dest_rgn);
pr != NULL;
pr = gimp_pixel_rgns_process (pr))
{
switch (bytes)
{
case 4:
compute_block_x (dest_rgn.data, dest_rgn.rowstride,
dest_rgn.x, dest_rgn.y, dest_rgn.w, dest_rgn.h,
4, assign_block_4, &p);
break;
case 3:
compute_block_x (dest_rgn.data, dest_rgn.rowstride,
dest_rgn.x, dest_rgn.y, dest_rgn.w, dest_rgn.h,
3, assign_block_3, &p);
break;
case 2:
compute_block_x (dest_rgn.data, dest_rgn.rowstride,
dest_rgn.x, dest_rgn.y, dest_rgn.w, dest_rgn.h,
2, assign_block_2, &p);
break;
case 1:
compute_block_x (dest_rgn.data, dest_rgn.rowstride,
dest_rgn.x, dest_rgn.y, dest_rgn.w, dest_rgn.h,
1, assign_block_1, &p);
break;
}
progress += dest_rgn.w * dest_rgn.h;
gimp_progress_update ((double) progress / (double) max_progress);
}
gimp_progress_update (1.0);
gimp_drawable_flush (drawable);
gimp_drawable_merge_shadow (drawable->drawable_id, TRUE);
gimp_drawable_update (drawable->drawable_id, x1, y1, x2 - x1, y2 - y1);
}
static gdouble
linear (gdouble v)
{
double a = v - (int) v;
return (a < 0 ? 1.0 + a : a);
}
static gdouble
bilinear (gdouble v)
{
double a = v - (int) v;
a = (a < 0 ? 1.0 + a : a);
return (a > 0.5 ? 2 - 2 * a : 2 * a);
}
static gdouble
cosinus (gdouble v)
{
return 0.5 - 0.5 * sin ((v + 0.25) * G_PI * 2);
}
static void
assign_block_4 (guchar *dest, gdouble grey, params *p)
{
dest[0] = p->r + (gint) (grey * p->dr);
dest[1] = p->g + (gint) (grey * p->dg);
dest[2] = p->b + (gint) (grey * p->db);
dest[3] = p->a + (gint) (grey * p->da);
}
static void
assign_block_3 (guchar *dest, gdouble grey, params *p)
{
dest[0] = p->r + (gint) (grey * p->dr);
dest[1] = p->g + (gint) (grey * p->dg);
dest[2] = p->b + (gint) (grey * p->db);
}
static void
assign_block_2 (guchar *dest, gdouble grey, params *p)
{
dest[0] = (guchar) (grey * 255.0);
dest[1] = p->a + (gint)(grey * p->da);
}
static void
assign_block_1 (guchar *dest, gdouble grey, params *p)
{
dest[0]= (guchar) (grey * 255.0);
}
static void
compute_block_x (guchar *dest_row, guint rowstride,
gint x0, gint y0, gint w, gint h,
gint bpp,
void (*assign)(guchar *dest, gdouble grey, params *p),
params *p)
{
gint i, j;
gdouble x, y, grey;
gdouble pow_exp;
guchar *dest;
pow_exp = exp (svals.blend_power);
for (j = y0; j < y0 + h; j++)
{
y= ((gdouble) j) / p->height;
dest = dest_row;
for (i = x0; i < x0 + w; i++)
{
gdouble c;
x = ((gdouble) i) / p->width;
c = 0.5 * sin(p->c31 * x + p->c32 * y + p->c33);
grey = sin(p->c11 * x + p->c12 * y + p->c13) * (0.5 + 0.5 * c) +
sin(p->c21 * x + p->c22 * y + p->c23) * (0.5 - 0.5 * c);
grey = pow(p->blend(svals.cmplx * (0.5 + 0.5 * grey)), pow_exp);
assign (dest, grey, p);
dest += bpp;
}
dest_row += rowstride;
}
}
static void
alpha_scale_cb (GtkAdjustment *adj,
gpointer data)
{
GimpColorButton *color_button;
GimpRGB color;
if (!data)
return;
color_button = GIMP_COLOR_BUTTON (data);
gimp_color_button_get_color (GIMP_COLOR_BUTTON (color_button), &color);
gimp_rgb_set_alpha (&color, gtk_adjustment_get_value (adj));
gimp_color_button_set_color (GIMP_COLOR_BUTTON (color_button), &color);
}
static void
alpha_scale_update (GtkWidget *color_button,
gpointer data)
{
GtkAdjustment *adj;
GimpRGB color;
adj = GTK_ADJUSTMENT (data);
gimp_color_button_get_color (GIMP_COLOR_BUTTON (color_button), &color);
gtk_adjustment_set_value (adj, color.a);
sinus_do_preview (NULL);
}
static void
sinus_toggle_button_update (GtkWidget *widget,
gpointer data)
{
gimp_toggle_button_update (widget, data);
sinus_do_preview (NULL);
}
static void
sinus_radio_button_update (GtkWidget *widget,
gpointer data)
{
gimp_radio_button_update (widget, data);
sinus_do_preview (NULL);
}
static void
sinus_double_adjustment_update (GtkAdjustment *adjustment,
gpointer data)
{
gimp_double_adjustment_update (adjustment, data);
sinus_do_preview (NULL);
}
static void
sinus_random_update (GObject *unused,
gpointer data)
{
sinus_do_preview (NULL);
}
/*****************************************/
/* The note book */
/*****************************************/
static gint
sinus_dialog (void)
{
GtkWidget *dlg;
GtkWidget *main_hbox;
GtkWidget *preview;
GtkWidget *notebook;
GtkWidget *page;
GtkWidget *frame;
GtkWidget *label;
GtkWidget *vbox;
GtkWidget *vbox2;
GtkWidget *hbox;
GtkWidget *table;
GtkWidget *toggle;
GtkWidget *push_col1 = NULL;
GtkWidget *push_col2 = NULL;
GtkAdjustment *adj;
gboolean run;
gimp_ui_init (PLUG_IN_BINARY, TRUE);
/* Create Main window with a vbox */
/* ============================== */
dlg = gimp_dialog_new (_("Sinus"), PLUG_IN_ROLE,
NULL, 0,
gimp_standard_help_func, PLUG_IN_PROC,
GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
GTK_STOCK_OK, GTK_RESPONSE_OK,
NULL);
gtk_dialog_set_alternative_button_order (GTK_DIALOG (dlg),
GTK_RESPONSE_OK,
GTK_RESPONSE_CANCEL,
-1);
gimp_window_set_transient (GTK_WINDOW (dlg));
main_hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 12);
gtk_container_set_border_width (GTK_CONTAINER (main_hbox), 12);
gtk_box_pack_start (GTK_BOX (gtk_dialog_get_content_area (GTK_DIALOG (dlg))),
main_hbox, TRUE, TRUE, 0);
gtk_widget_show (main_hbox);
/* Create preview */
/* ============== */
vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 6);
gtk_box_pack_start (GTK_BOX (main_hbox), vbox, FALSE, FALSE, 0);
gtk_widget_show (vbox);
preview = mw_preview_new (vbox, thePreview);
/* Create the notebook */
/* =================== */
notebook = gtk_notebook_new ();
gtk_notebook_set_tab_pos (GTK_NOTEBOOK (notebook), GTK_POS_TOP);
gtk_box_pack_start (GTK_BOX (main_hbox), notebook, FALSE, FALSE, 0);
gtk_widget_show (notebook);
/* Create the drawing settings frame */
/* ================================= */
page = gtk_box_new (GTK_ORIENTATION_VERTICAL, 12);
gtk_container_set_border_width (GTK_CONTAINER (page), 12);
frame = gimp_frame_new (_("Drawing Settings"));
gtk_box_pack_start (GTK_BOX (page), frame, FALSE, FALSE, 0);
gtk_widget_show (frame);
table = gtk_table_new (3, 3, FALSE);
gtk_table_set_col_spacings (GTK_TABLE (table), 6);
gtk_table_set_row_spacings (GTK_TABLE (table), 6);
gtk_container_add (GTK_CONTAINER(frame), table);
adj = gimp_scale_entry_new (GTK_TABLE (table), 0, 0,
_("_X scale:"), 140, 8,
svals.scalex, 0.0001, 100.0, 0.0001, 5, 4,
TRUE, 0, 0,
NULL, NULL);
g_signal_connect (adj, "value-changed",
G_CALLBACK (sinus_double_adjustment_update),
&svals.scalex);
adj = gimp_scale_entry_new (GTK_TABLE (table), 0, 1,
_("_Y scale:"), 140, 8,
svals.scaley, 0.0001, 100.0, 0.0001, 5, 4,
TRUE, 0, 0,
NULL, NULL);
g_signal_connect (adj, "value-changed",
G_CALLBACK (sinus_double_adjustment_update),
&svals.scaley);
adj = gimp_scale_entry_new (GTK_TABLE (table), 0, 2,
_("Co_mplexity:"), 140, 8,
svals.cmplx, 0.0, 15.0, 0.01, 5, 2,
TRUE, 0, 0,
NULL, NULL);
g_signal_connect (adj, "value-changed",
G_CALLBACK (sinus_double_adjustment_update),
&svals.cmplx);
gtk_widget_show (table);
frame= gimp_frame_new (_("Calculation Settings"));
gtk_box_pack_start (GTK_BOX (page), frame, FALSE, FALSE, 0);
gtk_widget_show (frame);
vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 6);
gtk_container_add (GTK_CONTAINER (frame), vbox);
gtk_widget_show (vbox);
table = gtk_table_new (3, 1, FALSE);
gtk_table_set_col_spacings (GTK_TABLE (table), 6);
gtk_box_pack_start (GTK_BOX (vbox), table, FALSE, FALSE, 0);
hbox = gimp_random_seed_new (&svals.seed, &svals.random_seed);
label = gimp_table_attach_aligned (GTK_TABLE (table), 0, 0,
_("R_andom seed:"), 1.0, 0.5,
hbox, 1, TRUE);
gtk_label_set_mnemonic_widget (GTK_LABEL (label),
GIMP_RANDOM_SEED_SPINBUTTON (hbox));
g_signal_connect (GIMP_RANDOM_SEED_SPINBUTTON_ADJ (hbox),
"value-changed", G_CALLBACK (sinus_random_update), NULL);
gtk_widget_show (table);
toggle = gtk_check_button_new_with_mnemonic (_("_Force tiling?"));
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (toggle), svals.tiling);
gtk_box_pack_start (GTK_BOX (vbox), toggle, FALSE, FALSE, 0);
gtk_widget_show (toggle);
g_signal_connect (toggle, "toggled",
G_CALLBACK (sinus_toggle_button_update),
&svals.tiling);
vbox2 = gimp_int_radio_group_new (FALSE, NULL,
G_CALLBACK (sinus_radio_button_update),
&svals.perturbation, svals.perturbation,
_("_Ideal"), IDEAL, NULL,
_("_Distorted"), PERTURBED, NULL,
NULL);
gtk_box_pack_start (GTK_BOX (vbox), vbox2, FALSE, FALSE, 0);
gtk_widget_show (vbox2);
label = gtk_label_new_with_mnemonic (_("_Settings"));
gtk_notebook_append_page (GTK_NOTEBOOK (notebook), page, label);
gtk_widget_show (page);
/* Color settings dialog: */
/* ====================== */
page = gtk_box_new (GTK_ORIENTATION_VERTICAL, 12);
gtk_container_set_border_width (GTK_CONTAINER (page), 12);
if (drawable_is_grayscale)
{
frame = gimp_frame_new (_("Colors"));
gtk_box_pack_start(GTK_BOX(page), frame, FALSE, FALSE, 0);
gtk_widget_show (frame);
vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 6);
gtk_container_add (GTK_CONTAINER (frame), vbox);
gtk_widget_show (vbox);
/*if in grey scale, the colors are necessarily black and white */
label = gtk_label_new (_("The colors are white and black."));
gtk_misc_set_alignment (GTK_MISC (label), 0.5, 0.5);
gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, FALSE, 0);
gtk_widget_show (label);
}
else
{
frame = gimp_int_radio_group_new (TRUE, _("Colors"),
G_CALLBACK (sinus_radio_button_update),
&svals.colors, svals.colors,
_("Bl_ack & white"),
B_W, NULL,
_("_Foreground & background"),
USE_FG_BG, NULL,
_("C_hoose here:"),
USE_COLORS, NULL,
NULL);
gtk_box_pack_start(GTK_BOX(page), frame, FALSE, FALSE, 0);
gtk_widget_show (frame);
vbox = gtk_bin_get_child (GTK_BIN (frame));
hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 12);
gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0);
push_col1 = gimp_color_button_new (_("First color"), 32, 32,
&svals.col1,
GIMP_COLOR_AREA_SMALL_CHECKS);
gtk_box_pack_start (GTK_BOX (hbox), push_col1, FALSE, FALSE, 0);
gtk_widget_show (push_col1);
g_signal_connect (push_col1, "color-changed",
G_CALLBACK (gimp_color_button_get_color),
&svals.col1);
push_col2 = gimp_color_button_new (_("Second color"), 32, 32,
&svals.col2,
GIMP_COLOR_AREA_SMALL_CHECKS);
gtk_box_pack_start (GTK_BOX (hbox), push_col2, FALSE, FALSE, 0);
gtk_widget_show (push_col2);
g_signal_connect (push_col2, "color-changed",
G_CALLBACK (gimp_color_button_get_color),
&svals.col2);
gtk_widget_show (hbox);
}
frame = gimp_frame_new (_("Alpha Channels"));
gtk_box_pack_start (GTK_BOX (page), frame, FALSE, FALSE, 0);
gtk_widget_show (frame);
gtk_widget_set_sensitive (frame,
gimp_drawable_has_alpha (drawable->drawable_id));
table = gtk_table_new (2, 3, FALSE);
gtk_table_set_col_spacings (GTK_TABLE (table), 6);
gtk_table_set_row_spacings (GTK_TABLE (table), 6);
gtk_container_add (GTK_CONTAINER (frame), table);
adj = gimp_scale_entry_new (GTK_TABLE (table), 0, 0,
_("F_irst color:"), 0, 0,
svals.col1.a, 0.0, 1.0, 0.01, 0.1, 2,
TRUE, 0, 0,
NULL, NULL);
g_signal_connect (adj, "value-changed",
G_CALLBACK (alpha_scale_cb),
push_col1);
if (push_col1)
g_signal_connect (push_col1, "color-changed",
G_CALLBACK (alpha_scale_update),
adj);
adj = gimp_scale_entry_new (GTK_TABLE (table), 0, 1,
_("S_econd color:"), 0, 0,
svals.col2.a, 0.0, 1.0, 0.01, 0.1, 2,
TRUE, 0, 0,
NULL, NULL);
g_signal_connect (adj, "value-changed",
G_CALLBACK (alpha_scale_cb),
push_col2);
if (push_col2)
g_signal_connect (push_col2, "color-changed",
G_CALLBACK (alpha_scale_update),
adj);
gtk_widget_show (table);
label = gtk_label_new_with_mnemonic (_("Co_lors"));
gtk_notebook_append_page (GTK_NOTEBOOK (notebook), page, label);
gtk_widget_show (page);
/* blend settings dialog: */
/* ====================== */
page = gtk_box_new (GTK_ORIENTATION_VERTICAL, 12);
gtk_container_set_border_width (GTK_CONTAINER (page), 12);
frame = gimp_frame_new (_("Blend Settings"));
gtk_box_pack_start (GTK_BOX (page), frame, TRUE, TRUE, 0);
gtk_widget_show (frame);
vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 12);
gtk_container_add (GTK_CONTAINER (frame), vbox);
gtk_widget_show (vbox);
frame =
gimp_int_radio_group_new (TRUE, _("Gradient"),
G_CALLBACK (sinus_radio_button_update),
&svals.colorization, svals.colorization,
_("L_inear"), LINEAR, NULL,
_("Bili_near"), BILINEAR, NULL,
_("Sin_usoidal"), SINUS, NULL,
NULL);
gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, FALSE, 0);
gtk_widget_show (frame);
table = gtk_table_new (1, 3, FALSE);
gtk_table_set_col_spacings (GTK_TABLE (table), 6);
gtk_box_pack_start (GTK_BOX (vbox), table, TRUE, TRUE, 0);
adj = gimp_scale_entry_new (GTK_TABLE (table), 0, 0,
_("_Exponent:"), 0, 0,
svals.blend_power, -7.5, 7.5, 0.01, 5.0, 2,
TRUE, 0, 0,
NULL, NULL);
g_signal_connect (adj, "value-changed",
G_CALLBACK (sinus_double_adjustment_update),
&svals.blend_power);
gtk_widget_show (table);
label = gtk_label_new_with_mnemonic (_("_Blend"));
gtk_notebook_append_page (GTK_NOTEBOOK (notebook), page, label);
gtk_widget_show (page);
gtk_widget_show (dlg);
sinus_do_preview (preview);
run = (gimp_dialog_run (GIMP_DIALOG (dlg)) == GTK_RESPONSE_OK);
gtk_widget_destroy (dlg);
return run;
}
/******************************************************************/
/* Draw preview image. if DoCompute is TRUE then recompute image. */
/******************************************************************/
static void
sinus_do_preview (GtkWidget *widget)
{
static GtkWidget *theWidget = NULL;
gint rowsize;
guchar *buf;
params p;
if (!do_preview)
return;
if (theWidget == NULL)
{
theWidget = widget;
}
rowsize = thePreview->width * thePreview->bpp;
buf = g_new (guchar, thePreview->width*thePreview->height*thePreview->bpp);
p.height = thePreview->height;
p.width = thePreview->width;
prepare_coef (&p);
if (thePreview->bpp == 3) /* [dindinx]: it looks to me that this is always true... */
compute_block_x (buf, rowsize, 0, 0, thePreview->width, thePreview->height,
3, assign_block_3, &p);
else if (thePreview->bpp == 1)
{
compute_block_x (buf, rowsize, 0, 0, thePreview->width,
thePreview->height, 1, assign_block_1, &p);
}
gimp_preview_area_draw (GIMP_PREVIEW_AREA (theWidget),
0, 0, thePreview->width, thePreview->height,
GIMP_RGB_IMAGE,
buf,
rowsize);
g_free (buf);
}
static void
mw_preview_toggle_callback (GtkWidget *widget,
gpointer data)
{
gimp_toggle_button_update (widget, data);
sinus_do_preview (NULL);
}
static mwPreview *
mw_preview_build_virgin (GimpDrawable *drw)
{
mwPreview *mwp;
mwp = g_new (mwPreview, 1);
if (drw->width > drw->height)
{
mwp->scale = (gdouble) drw->width / (gdouble) PREVIEW_SIZE;
mwp->width = PREVIEW_SIZE;
mwp->height = drw->height / mwp->scale;
}
else
{
mwp->scale = (gdouble) drw->height / (gdouble) PREVIEW_SIZE;
mwp->height = PREVIEW_SIZE;
mwp->width = drw->width / mwp->scale;
}
mwp->bpp = 3;
mwp->bits = NULL;
return mwp;
}
static GtkWidget *
mw_preview_new (GtkWidget *parent,
mwPreview *mwp)
{
GtkWidget *preview;
GtkWidget *frame;
GtkWidget *vbox;
GtkWidget *button;
vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 6);
gtk_box_pack_start (GTK_BOX (parent), vbox, FALSE, FALSE, 0);
gtk_widget_show (vbox);
frame = gtk_aspect_frame_new (NULL, 0.5, 0.5, 1, TRUE);
gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_IN);
gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, FALSE, 0);
gtk_widget_show (frame);
preview = gimp_preview_area_new ();
gtk_widget_set_size_request (preview, mwp->width, mwp->height);
gtk_container_add (GTK_CONTAINER (frame), preview);
gtk_widget_show (preview);
button = gtk_check_button_new_with_mnemonic (_("Do _preview"));
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button), do_preview);
gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, FALSE, 0);
gtk_widget_show (button);
g_signal_connect (button, "toggled",
G_CALLBACK (mw_preview_toggle_callback),
&do_preview);
return preview;
}
|
brion/gimp
|
plug-ins/common/sinus.c
|
C
|
gpl-3.0
| 32,096
|
/**
* @file udp_socket.c
* @author Ricardo Tubío (rtpardavila[at]gmail.com)
* @version 0.1
*
* @section LICENSE
*
* This file is part of udpip-broadcaster.
* udpip-broadcaster is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* udpip-broadcaster is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with udpip-broadcaster. If not, see <http://www.gnu.org/licenses/>.
*/
#include "udp_socket.h"
/* new_ifreq */
ifreq_t *new_ifreq()
{
ifreq_t *s = NULL;
if ( ( s = (ifreq_t *)malloc(LEN__IFREQ) ) == NULL )
{ handle_sys_error("new_ifreq: <malloc> returns NULL.\n"); }
if ( memset(s, 0, LEN__IFREQ) == NULL )
{ handle_sys_error("new_ifreq: <memset> returns NULL.\n"); }
return(s);
}
/* init_ifreq */
ifreq_t *init_ifreq(const char *if_name)
{
ifreq_t *s = new_ifreq();
int if_name_len = 0;
int ifr_name_len = sizeof(s->ifr_name);
if ( ( if_name_len = strlen(if_name) ) < 0 )
{ handle_sys_error("init_ifreq: <strlen> returns < 0.\n"); }
if ( if_name_len > ifr_name_len )
{ handle_app_error("init_ifreq: if_name's length bigger than ifr's " \
"buffer.\n"); }
if ( strncpy(s->ifr_name, if_name, if_name_len) == NULL )
{ handle_sys_error("init_ifreq: <strncpy> returns NULL.\n"); }
return(s);
}
/* new_sockaddr */
sockaddr_t *new_sockaddr()
{
sockaddr_t *s = NULL;
if ( ( s = (sockaddr_t *)malloc(LEN__SOCKADDR) ) == NULL )
{ handle_sys_error("new_sockaddr: <malloc> returns NULL.\n"); }
if ( memset(s, 0, LEN__SOCKADDR) == NULL )
{ handle_sys_error("new_sockaddr: <memset> returns NULL.\n"); }
return(s);
}
/* new_sockaddr_in */
sockaddr_in_t *new_sockaddr_in()
{
sockaddr_in_t *s = NULL;
if ( ( s = (sockaddr_in_t *)malloc(LEN__SOCKADDR_IN) ) == NULL )
{ handle_sys_error("new_sockaddr_in: <malloc> returns NULL.\n"); }
if ( memset(s, 0, LEN__SOCKADDR) == NULL )
{ handle_sys_error("new_sockaddr_in: <memset> returns NULL.\n"); }
return(s);
}
/* new_iovec */
iovec_t *new_iovec()
{
iovec_t *s = NULL;
if ( ( s = (iovec_t *)malloc(LEN__IOVEC) ) == NULL )
{ handle_sys_error("new_iovec: <malloc> returns NULL.\n"); }
if ( memset(s, 0, LEN__IOVEC) == NULL )
{ handle_sys_error("new_iovec: <memset> returns NULL.\n"); }
return(s);
}
/* new_msg_header */
msg_header_t *new_msg_header()
{
msg_header_t *s = NULL;
if ( ( s = (msg_header_t *)malloc(LEN__MSG_HEADER) ) == NULL )
{ handle_sys_error("new_msg_header: <malloc> returns NULL.\n"); }
if ( memset(s, 0, LEN__MSG_HEADER) == NULL )
{ handle_sys_error("new_msg_header: <memset> returns NULL.\n"); }
if ( ( s->msg_control = malloc(CONTROL_BUFFER_LEN) ) == NULL )
{ handle_sys_error("init_msg_header: <malloc> returns NULL.\n"); }
if ( memset(s->msg_control, 0, CONTROL_BUFFER_LEN) == NULL )
{ handle_sys_error("init_msg_header: <memset> returns NULL.\n"); }
s->msg_controllen = CONTROL_BUFFER_LEN;
s->msg_flags = 0;
s->msg_name = new_sockaddr_in();
s->msg_namelen = LEN__SOCKADDR_IN;
s->msg_iov = new_iovec();
s->msg_iovlen = 0;
return(s);
}
/* init_msg_header */
msg_header_t *init_msg_header(void* buffer, const int buffer_len)
{
msg_header_t *s = new_msg_header();
s->msg_iovlen = 1;
s->msg_iov->iov_base = buffer;
s->msg_iov->iov_len = buffer_len;
return(s);
}
/* init_broadcast_sockaddr_in */
sockaddr_in_t *init_broadcast_sockaddr_in(const int port)
{
sockaddr_in_t *s = new_sockaddr_in();
s->sin_family = AF_INET;
s->sin_port = (in_port_t)htons(port);
s->sin_addr.s_addr = htonl(INADDR_BROADCAST);
return(s);
}
/* init_any_sockaddr_in */
sockaddr_in_t *init_any_sockaddr_in(const int port)
{
sockaddr_in_t *s = new_sockaddr_in();
s->sin_family = AF_INET;
s->sin_port = (in_port_t)htons(port);
s->sin_addr.s_addr = htonl(INADDR_ANY);
return(s);
}
/* init_sockaddr_in */
sockaddr_in_t *init_sockaddr_in(const char *address, const int port)
{
sockaddr_in_t *s = new_sockaddr_in();
s->sin_family = AF_INET;
s->sin_port = (in_port_t)htons(port);
printf("8\n");
// if ( ( s->sin_addr.s_addr = inet_addr(address) ) < 0 )
// {
//
// printf("entro no erro\n");
// perror("init_sockaddr_in: " \
// "<inet_addr> returns error.\n"); }
printf("9\n");
return(s);
}
/* init_if_sockaddr_in */
sockaddr_in_t *init_if_sockaddr_in(const char *if_name, const int port)
{
sockaddr_in_t *s = NULL;
struct ifaddrs *ifaddr, *ifa;
int i;
char host[NI_MAXHOST];
bool if_found = false;
if ( getifaddrs(&ifaddr) < 0 )
{
handle_sys_error("init_if_sockaddr_in: " \
"<getifaddrs> returned error. Error: ");
}
for ( ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next )
{
if ( ifa->ifa_addr == NULL ) { continue; }
i = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in)
, host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
if ( ( strcmp(ifa->ifa_name,if_name) == 0 ) &&
( ifa->ifa_addr->sa_family == AF_INET ) )
{
if ( i != 0 )
{
handle_app_error("init_if_sockaddr_in: " \
"<getnameinfo> failed: %s\n"
, gai_strerror(i));
}
s = init_sockaddr_in(host, port);
if_found = true;
}
}
freeifaddrs(ifaddr);
if ( if_found == false )
{
handle_app_error("Could not get local interface, if_name = %s.\n"
, if_name);
}
return(s);
}
/* open_receiver_udp_socket */
int open_receiver_udp_socket(const int port)
{
int fd = -1;
// 1) socket creation
if ( ( fd = socket(AF_INET, SOCK_DGRAM, 0) ) < 0 )
{ handle_sys_error("open_receiver_udp_socket: " \
"<socket> returns error. Description"); }
// 2) local address for binding
sockaddr_in_t* addr = init_any_sockaddr_in(port);
if ( bind(fd, (sockaddr_t *)addr, LEN__SOCKADDR_IN) < 0 )
{ handle_sys_error("open_receiver_udp_socket: " \
"<bind> returns error. Description"); }
// 3) for analyzing received message's headers
if ( set_msghdrs_socket(fd) < 0 )
{ handle_app_error("open_receiver_udp_socket: " \
"<set_msghdrs_socket> returns error.\n"); }
return(fd);
}
/* open_transmitter_udp_socket */
int open_transmitter_udp_socket(const int port)
{
int fd = -1;
// 1) socket creation
if ( ( fd = socket(AF_INET, SOCK_DGRAM, 0) ) < 0 )
{ handle_sys_error("open_udp_socket: <socket> returns error.\n"); }
return(fd);
}
/* open_broadcast_udp_socket */
int open_broadcast_udp_socket(const char *iface, const int port)
{
int fd = -1;
// 1) socket creation
if ( ( fd = socket(AF_INET, SOCK_DGRAM, 0) ) < 0 )
{ handle_sys_error("open_udp_socket: <socket> returns error.\n"); }
// 2) set broadcast socket options
if ( set_broadcast_socket(fd) < 0 )
{
handle_app_error("open_broadcast_udp_socket: " \
"<set_broadcast_socket> returns error.\n");
}
// 3) broadcast socket must be bound to a specific network interface
if ( set_bindtodevice_socket(iface, fd) < 0 )
{
handle_app_error("open_broadcast_udp_socket: " \
"<set_bindtodevice_socket> returns error.\n");
}
printf("saio do open_broadcast_udp_socket\n");
return(fd);
}
/* set_broadcast_socket */
int set_broadcast_socket(const int socket_fd)
{
int bcast = 1;
if ( setsockopt(socket_fd, SOL_SOCKET, SO_BROADCAST, &bcast, sizeof(int))
< 0 )
{ handle_sys_error("set_broadcast_socket: " \
"<setsockopt> returns error."); }
return(EX_OK);
}
/* set_bindtodevice_socket */
int set_bindtodevice_socket(const char *if_name, const int socket_fd)
{
ifreq_t *ifr = init_ifreq(if_name);
if ( setsockopt(socket_fd, SOL_SOCKET, SO_BINDTODEVICE, ifr, LEN__IFREQ)
< 0 )
{ handle_sys_error("set_bindtodevice_socket: " \
"<setsockopt> returns error"); }
return(EX_OK);
}
/* set_msghdrs_socket */
int set_msghdrs_socket(const int socket_fd)
{
ifreq_t *ifr = new_ifreq();
if ( setsockopt(socket_fd, IPPROTO_IP, IP_PKTINFO, &ifr, LEN__IFREQ)
< 0 )
{ handle_sys_error("set_generate_headers: " \
"<setsockopt> returns error"); }
return(EX_OK);
}
/* send_message */
int send_message( const sockaddr_t* dest_addr, const int socket_fd,
const void *buffer, const int len )
{
int sent_bytes = 0;
if ( ( sent_bytes = sendto(socket_fd, buffer, len
, 0, dest_addr, LEN__SOCKADDR_IN) ) < 0 )
{
log_sys_error("cb_broadcast_sendto (fd=%d): <sendto> ERROR.\n"
, socket_fd);
getchar();
return(EX_ERR);
}
if ( sent_bytes < len )
{
log_app_msg("send_message: sent %d bytes, requested %d.\n"
, sent_bytes, len);
return(EX_ERR);
}
return(sent_bytes);
}
/* recv_message */
int recv_message(const int socket_fd, void *data)
{
int rx_bytes = 0;
if ( ( rx_bytes = recvfrom(socket_fd, data, UDP_BUFFER_LEN
, 0, NULL, NULL) ) < 0 )
{
log_sys_error("recv_message: wrong <recvfrom> call. ");
return(EX_ERR);
}
return(rx_bytes);
}
/* recv_msg */
int recv_msg( const int socket_fd, msg_header_t *msg,
const in_addr_t block_ip, bool *blocked )
{
int rx_bytes = 0;
// 1) read UDP message from network level
if ( ( rx_bytes = recvmsg(socket_fd, msg, 0) ) < 0 )
{
log_sys_error("recv_msg: wrong <recvmsg> call. ");
return(EX_ERR);
}
in_addr_t src_addr = get_source_address(msg);
if ( block_ip == src_addr )
{ *blocked = true; }
else
{ *blocked = false; }
return(rx_bytes);
}
/* get_source_address */
in_addr_t get_source_address(msg_header_t *msg)
{
sockaddr_in_t *src = NULL;
// iterate through all the control headers
for (
struct cmsghdr *cmsg = CMSG_FIRSTHDR(msg);
cmsg != NULL;
cmsg = CMSG_NXTHDR(msg, cmsg)
)
{
// ignore the control headers that don't match what we want
if ( ( cmsg->cmsg_level != IPPROTO_IP ) ||
( cmsg->cmsg_type != IP_PKTINFO ) )
{ continue; }
//struct in_pktinfo *pi = CMSG_DATA(cmsg);
src = (sockaddr_in_t *)msg->msg_name;
break;
}
return(src->sin_addr.s_addr);
}
/* print_hex_data */
int print_hex_data(const char *buffer, const int len)
{
int last_byte = len - 1;
if ( len < 0 ) { return(EX_WRONG_PARAM); }
for ( int i = 0; i < len; i++ )
{
if ( ( i != 0 ) && ( ( i % BYTES_PER_LINE ) == 0 ) )
{ log_app_msg("\n\t\t\t"); }
log_app_msg("%02X", 0xFF & (unsigned int)buffer[i]);
if ( i < last_byte ) { log_app_msg(":"); }
}
return(EX_OK);
}
/* print_eth_address */
void print_eth_address(const unsigned char *eth_address)
{
printf("%02X:%02X:%02X:%02X:%02X:%02X",
(unsigned char) eth_address[0],
(unsigned char) eth_address[1],
(unsigned char) eth_address[2],
(unsigned char) eth_address[3],
(unsigned char) eth_address[4],
(unsigned char) eth_address[5]);
}
|
vieites4/udpip_broadcaster
|
src/udpev/udp_socket.c
|
C
|
gpl-3.0
| 11,081
|
/* «Camelion» - Perl storable/C struct back-and-forth translator
*
* Copyright (C) Alexey Shishkin 2016
*
* This file is part of Project «Camelion».
*
* Project «Camelion» 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 3 of the License, or
* (at your option) any later version.
*
* Project «Camelion» 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 Project «Camelion». If not, see <http://www.gnu.org/licenses/>.
*/
#include "../serials/sread.h"
CML_Error CML_SerialsReadINT8(CML_Bytes * bytes, uint32_t * bpos, int8_t * result)
{
if (*bpos + sizeof(int8_t) > bytes->size)
return CML_ERROR_USER_BADDATA;
*result = bytes->data[*bpos];
*bpos += 1;
/* Need to reverse signed char */
/* It's a perl thing */
*result ^= 1 << 7;
return CML_ERROR_SUCCESS;
}
CML_Error CML_SerialsReadUINT8(CML_Bytes * bytes, uint32_t * bpos, uint8_t * result)
{
if (*bpos + sizeof(uint8_t) > bytes->size)
return CML_ERROR_USER_BADDATA;
*result = bytes->data[*bpos];
*bpos += 1;
return CML_ERROR_SUCCESS;
}
CML_Error CML_SerialsReadINT32(CML_Bytes * bytes, uint32_t * bpos, int32_t * result)
{
if (*bpos + sizeof(int32_t) > bytes->size)
return CML_ERROR_USER_BADDATA;
union
{
int32_t res;
uint8_t bytes[sizeof(int32_t)];
} conv;
uint32_t i;
for (i = 0; i < sizeof(int32_t); i++, *bpos += 1)
conv.bytes[3 - i] = bytes->data[*bpos];
*result = conv.res;
return CML_ERROR_SUCCESS;
}
CML_Error CML_SerialsReadUINT32(CML_Bytes * bytes, uint32_t * bpos, uint32_t * result)
{
if (*bpos + sizeof(uint32_t) > bytes->size)
return CML_ERROR_USER_BADDATA;
union
{
uint32_t res;
uint8_t bytes[sizeof(uint32_t)];
} conv;
uint32_t i;
for (i = 0; i < sizeof(uint32_t); i++, *bpos += 1)
conv.bytes[3 - i] = bytes->data[*bpos];
*result = conv.res;
return CML_ERROR_SUCCESS;
}
CML_Error CML_SerialsReadDATA(CML_Bytes * bytes, uint32_t * bpos, uint8_t * result, uint32_t length)
{
if (*bpos + length > bytes->size)
return CML_ERROR_USER_BADDATA;
uint32_t i;
for (i = 0; i < length; i++, *bpos += 1)
result[i] = bytes->data[*bpos];
result[i] = '\0';
return CML_ERROR_SUCCESS;
}
|
kimiby/camelion
|
serials/sread.c
|
C
|
gpl-3.0
| 2,718
|
/*
* Copyright 2013, winocm. <winocm@icloud.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* If you are going to use this software in any form that does not involve
* releasing the source to this project or improving it, let me know beforehand.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Compatibility support to bridge old pe_arm_xxx api and new
* AWESOME SOC DISPATCH STUFF.
*/
#include <mach/mach_types.h>
#include <pexpert/pexpert.h>
#include <pexpert/arm/protos.h>
#include <pexpert/arm/boot.h>
#include <machine/machine_routines.h>
#include <kern/debug.h>
/**
* pe_arm_init_interrupts
*
* Initialize the SoC dependent interrrupt controller.
*/
uint32_t pe_arm_init_interrupts(__unused void *args)
{
if (gPESocDispatch.interrupt_init == NULL)
panic("gPESocDispatch.interrupt_init was null, did you forget to set up the table?");
gPESocDispatch.interrupt_init();
return 0;
}
/**
* pe_arm_init_timebase
*
* Initialize the SoC dependent timebase.
*/
uint32_t pe_arm_init_timebase(__unused void *args)
{
if (gPESocDispatch.timebase_init == NULL)
panic("gPESocDispatch.timebase_init was null, did you forget to set up the table?");
gPESocDispatch.timebase_init();
return 0;
}
/**
* pe_arm_dispatch_interrupt
*
* Dispatch IRQ requests to the SoC specific handler.
*/
boolean_t pe_arm_dispatch_interrupt(void *context)
{
if (gPESocDispatch.handle_interrupt == NULL)
panic("gPESocDispatch.handle_interrupt was null, did you forget to set up the table?");
gPESocDispatch.handle_interrupt(context);
return TRUE;
}
/**
* pe_arm_get_timebase
*
* Get current system timebase from the SoC handler.
*/
uint64_t pe_arm_get_timebase(__unused void *args)
{
if (gPESocDispatch.get_timebase == NULL)
panic("gPESocDispatch.get_timebase was null, did you forget to set up the table?");
return gPESocDispatch.get_timebase();
}
/**
* pe_arm_set_timer_enabled
*
* Set platform timer enabled status.
*/
void pe_arm_set_timer_enabled(boolean_t enable)
{
if (gPESocDispatch.timer_enabled == NULL)
panic("gPESocDispatch.timer_enabled was null, did you forget to set up the table?");
gPESocDispatch.timer_enabled(enable);
}
/*
* iOS like functionality.
*/
uint32_t debug_enabled = 1;
uint32_t PE_i_can_has_debugger(uint32_t * pe_debug)
{
if (pe_debug) {
if (debug_enabled)
*pe_debug = 1;
else
*pe_debug = 0;
}
return debug_enabled;
}
uint32_t PE_get_security_epoch(void)
{
return 0;
}
|
p01arst0rm/decorum-linux
|
_resources/kernels/xnu-arm/pexpert/arm/common/pe_armsupport.c
|
C
|
gpl-3.0
| 3,815
|
#include <stdio.h>
#include <string.h>
#include "stdbool.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_log.h"
#include "bt.h"
#define GATTS_TAG "MAIN"
#define HCI_H4_CMD_PREAMBLE_SIZE (4)
/* HCI Command opcode group field(OGF) */
#define HCI_GRP_HOST_CONT_BASEBAND_CMDS (0x03 << 10) /* 0x0C00 */
#define HCI_GRP_BLE_CMDS (0x08 << 10)
#define HCI_RESET (0x0003 | HCI_GRP_HOST_CONT_BASEBAND_CMDS)
#define HCI_BLE_WRITE_ADV_ENABLE (0x000A | HCI_GRP_BLE_CMDS)
#define HCI_BLE_WRITE_ADV_PARAMS (0x0006 | HCI_GRP_BLE_CMDS)
#define HCI_BLE_WRITE_ADV_DATA (0x0008 | HCI_GRP_BLE_CMDS)
#define HCIC_PARAM_SIZE_WRITE_ADV_ENABLE (1)
#define HCIC_PARAM_SIZE_BLE_WRITE_ADV_PARAMS (15)
#define HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA (31)
#define BD_ADDR_LEN (6) /* Device address length */
typedef uint8_t bd_addr_t[BD_ADDR_LEN]; /* Device address */
#define UINT16_TO_STREAM(p, u16) {*(p)++ = (uint8_t)(u16); *(p)++ = (uint8_t)((u16) >> 8);}
#define UINT8_TO_STREAM(p, u8) {*(p)++ = (uint8_t)(u8);}
#define BDADDR_TO_STREAM(p, a) {int ijk; for (ijk = 0; ijk < BD_ADDR_LEN; ijk++) *(p)++ = (uint8_t) a[BD_ADDR_LEN - 1 - ijk];}
#define ARRAY_TO_STREAM(p, a, len) {int ijk; for (ijk = 0; ijk < len; ijk++) *(p)++ = (uint8_t) a[ijk];}
enum {
H4_TYPE_COMMAND = 1,
H4_TYPE_ACL = 2,
H4_TYPE_SCO = 3,
H4_TYPE_EVENT = 4
};
static uint8_t hci_cmd_buf[128];
/*
* @brief: BT controller callback function, used to notify the upper layer that
* controller is ready to receive command
*/
static void controller_rcv_pkt_ready(void)
{
printf("controller rcv pkt ready\n");
}
/*
* @brief: BT controller callback function, to transfer data packet to upper
* controller is ready to receive command
*/
static int host_rcv_pkt(uint8_t *data, uint16_t len)
{
printf("host rcv pkt: ");
for (uint16_t i=0; i<len; i++)
printf("%02x", data[i]);
printf("\n");
return 0;
}
static esp_vhci_host_callback_t vhci_host_cb = {
controller_rcv_pkt_ready,
host_rcv_pkt
};
static uint16_t make_cmd_reset(uint8_t *buf)
{
UINT8_TO_STREAM (buf, H4_TYPE_COMMAND);
UINT16_TO_STREAM (buf, HCI_RESET);
UINT8_TO_STREAM (buf, 0);
return HCI_H4_CMD_PREAMBLE_SIZE;
}
static uint16_t make_cmd_ble_set_adv_enable (uint8_t *buf, uint8_t adv_enable)
{
UINT8_TO_STREAM (buf, H4_TYPE_COMMAND);
UINT16_TO_STREAM (buf, HCI_BLE_WRITE_ADV_ENABLE);
UINT8_TO_STREAM (buf, HCIC_PARAM_SIZE_WRITE_ADV_ENABLE);
UINT8_TO_STREAM (buf, adv_enable);
return HCI_H4_CMD_PREAMBLE_SIZE + HCIC_PARAM_SIZE_WRITE_ADV_ENABLE;
}
static uint16_t make_cmd_ble_set_adv_param (uint8_t *buf, uint16_t adv_int_min, uint16_t adv_int_max,
uint8_t adv_type, uint8_t addr_type_own,
uint8_t addr_type_dir, bd_addr_t direct_bda,
uint8_t channel_map, uint8_t adv_filter_policy)
{
UINT8_TO_STREAM (buf, H4_TYPE_COMMAND);
UINT16_TO_STREAM (buf, HCI_BLE_WRITE_ADV_PARAMS);
UINT8_TO_STREAM (buf, HCIC_PARAM_SIZE_BLE_WRITE_ADV_PARAMS );
UINT16_TO_STREAM (buf, adv_int_min);
UINT16_TO_STREAM (buf, adv_int_max);
UINT8_TO_STREAM (buf, adv_type);
UINT8_TO_STREAM (buf, addr_type_own);
UINT8_TO_STREAM (buf, addr_type_dir);
BDADDR_TO_STREAM (buf, direct_bda);
UINT8_TO_STREAM (buf, channel_map);
UINT8_TO_STREAM (buf, adv_filter_policy);
return HCI_H4_CMD_PREAMBLE_SIZE + HCIC_PARAM_SIZE_BLE_WRITE_ADV_PARAMS;
}
static uint16_t make_cmd_ble_set_adv_data(uint8_t *buf, uint8_t data_len, uint8_t *p_data)
{
UINT8_TO_STREAM (buf, H4_TYPE_COMMAND);
UINT16_TO_STREAM (buf, HCI_BLE_WRITE_ADV_DATA);
UINT8_TO_STREAM (buf, HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA + 1);
memset(buf, 0, HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA);
if (p_data != NULL && data_len > 0) {
if (data_len > HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA) {
data_len = HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA;
}
UINT8_TO_STREAM (buf, data_len);
ARRAY_TO_STREAM (buf, p_data, data_len);
}
return HCI_H4_CMD_PREAMBLE_SIZE + HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA + 1;
}
static void hci_cmd_send_reset(void)
{
uint16_t sz = make_cmd_reset (hci_cmd_buf);
esp_vhci_host_send_packet(hci_cmd_buf, sz);
}
static void hci_cmd_send_ble_adv_start(void)
{
uint16_t sz = make_cmd_ble_set_adv_enable (hci_cmd_buf, 1);
esp_vhci_host_send_packet(hci_cmd_buf, sz);
}
static void hci_cmd_send_ble_set_adv_param(void)
{
uint16_t adv_intv_min = 256; // 160ms
uint16_t adv_intv_max = 256; // 160ms
uint8_t adv_type = 0; // connectable undirected advertising (ADV_IND)
uint8_t own_addr_type = 0; // Public Device Address
uint8_t peer_addr_type = 0; // Public Device Address
uint8_t peer_addr[6] = {0x80, 0x81, 0x82, 0x83, 0x84, 0x85};
uint8_t adv_chn_map = 0x07; // 37, 38, 39
uint8_t adv_filter_policy = 0; // Process All Conn and Scan
uint16_t sz = make_cmd_ble_set_adv_param(hci_cmd_buf,
adv_intv_min,
adv_intv_max,
adv_type,
own_addr_type,
peer_addr_type,
peer_addr,
adv_chn_map,
adv_filter_policy);
esp_vhci_host_send_packet(hci_cmd_buf, sz);
}
static void hci_cmd_send_ble_set_adv_data(void)
{
uint8_t adv_data[31];
uint8_t adv_data_len;
adv_data[0] = 2; // Len
adv_data[1] = 0x01; // Type Flags
adv_data[2] = 0x06; // GENERAL_DISC_MODE 0x02 | BR_EDR_NOT_SUPPORTED 0x04
adv_data[3] = 3; // Len
adv_data[4] = 0x03; // Type 16-Bit UUID
adv_data[5] = 0xAA; // Eddystone UUID 2 -> 0xFEAA LSB
adv_data[6] = 0xFE; // Eddystone UUID 1 MSB
adv_data[7] = 19; // Length of Beacon Data
adv_data[8] = 0x16; // Type Service Data
adv_data[9] = 0xAA; // Eddystone UUID 2 -> 0xFEAA LSB
adv_data[10] = 0xFE; // Eddystone UUID 1 MSB
adv_data[11] = 0x10; // Eddystone Frame Type
adv_data[12] = 0x20; // Beacons TX power at 0m
adv_data[13] = 0x03; // URL Scheme 'https://'
adv_data[14] = 0x67; // URL add 1 'g'
adv_data[15] = 0x6F; // URL add 2 'o'
adv_data[16] = 0x6F; // URL add 3 'o'
adv_data[17] = 0x2E; // URL add 4 '.'
adv_data[18] = 0x67; // URL add 5 'g'
adv_data[19] = 0x6C; // URL add 6 'l'
adv_data[20] = 0x2F; // URL add 7 '/'
adv_data[21] = 0x32; // URL add 8 '2'
adv_data[22] = 0x79; // URL add 9 'y'
adv_data[23] = 0x43; // URL add 10 'C'
adv_data[24] = 0x36; // URL add 11 '6'
adv_data[25] = 0x4B; // URL add 12 'K'
adv_data[26] = 0x58; // URL add 13 'X'
adv_data_len = 27;
printf("Eddystone adv_data [%d]=",adv_data_len);
for (int i=0; i<adv_data_len; i++) {
printf("%02x",adv_data[i]);
}
printf("\n");
uint16_t sz = make_cmd_ble_set_adv_data(hci_cmd_buf, adv_data_len, (uint8_t *)adv_data);
esp_vhci_host_send_packet(hci_cmd_buf, sz);
}
/*
* @brief: send HCI commands to perform BLE advertising;
*/
void bleAdvtTask(void *pvParameters)
{
int cmd_cnt = 0;
bool send_avail = false;
esp_vhci_host_register_callback(&vhci_host_cb);
printf("BLE advt task start\n");
while (1) {
vTaskDelay(5000 / portTICK_PERIOD_MS);
send_avail = esp_vhci_host_check_send_available();
if (send_avail) {
switch (cmd_cnt) {
case 0: hci_cmd_send_reset(); ++cmd_cnt; break;
case 1: hci_cmd_send_ble_set_adv_param(); ++cmd_cnt; break;
case 2: hci_cmd_send_ble_set_adv_data(); ++cmd_cnt; break;
case 3: hci_cmd_send_ble_adv_start(); ++cmd_cnt; break;
}
}
printf("BLE Advertise, flag_send_avail: %d, cmd_sent: %d\n", send_avail, cmd_cnt);
}
}
int app_main() {
esp_err_t ret;
esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
ret = esp_bt_controller_init(&bt_cfg);
if (ret) {
ESP_LOGE(GATTS_TAG, "%s initialize controller failed\n", __func__);
return 1;
}
ret = esp_bt_controller_enable(ESP_BT_MODE_BTDM);
if (ret) {
ESP_LOGE(GATTS_TAG, "%s enable controller failed\n", __func__);
return 1;
}
xTaskCreatePinnedToCore(&bleAdvtTask, "bleAdvtTask", 2048, NULL, 5, NULL, 0);
return 0;
}
|
pcbreflux/espressif
|
esp32/app/ble_app_eddystone/main/app_bt.c
|
C
|
gpl-3.0
| 8,842
|
/*
* AverMedia RM-KS remote controller keytable
*
* Copyright (C) 2010 Antti Palosaari <crope@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <media/rc-map.h>
#include <linux/module.h>
/* Initial keytable is from Jose Alberto Reguero <jareguero@telefonica.net>
and Felipe Morales Moreno <felipe.morales.moreno@gmail.com> */
/* Keytable fixed by Philippe Valembois <lephilousophe@users.sourceforge.net> */
static struct rc_map_table avermedia_rm_ks[] =
{
{ 0x0501, KEY_POWER2 }, /* Power (RED POWER BUTTON) */
{ 0x0502, KEY_CHANNELUP }, /* Channel+ */
{ 0x0503, KEY_CHANNELDOWN }, /* Channel- */
{ 0x0504, KEY_VOLUMEUP }, /* Volume+ */
{ 0x0505, KEY_VOLUMEDOWN }, /* Volume- */
{ 0x0506, KEY_MUTE }, /* Mute */
{ 0x0507, KEY_AGAIN }, /* Recall */
{ 0x0508, KEY_VIDEO }, /* Source */
{ 0x0509, KEY_1 }, /* 1 */
{ 0x050a, KEY_2 }, /* 2 */
{ 0x050b, KEY_3 }, /* 3 */
{ 0x050c, KEY_4 }, /* 4 */
{ 0x050d, KEY_5 }, /* 5 */
{ 0x050e, KEY_6 }, /* 6 */
{ 0x050f, KEY_7 }, /* 7 */
{ 0x0510, KEY_8 }, /* 8 */
{ 0x0511, KEY_9 }, /* 9 */
{ 0x0512, KEY_0 }, /* 0 */
{ 0x0513, KEY_AUDIO }, /* Audio */
{ 0x0515, KEY_EPG }, /* EPG */
{ 0x0516, KEY_PLAYPAUSE }, /* Play/Pause */
{ 0x0517, KEY_RECORD }, /* Record */
{ 0x0518, KEY_STOP }, /* Stop */
{ 0x051c, KEY_BACK }, /* << */
{ 0x051d, KEY_FORWARD }, /* >> */
{ 0x054d, KEY_INFO }, /* Display information */
{ 0x0556, KEY_ZOOM }, /* Fullscreen */
};
static struct rc_map_list avermedia_rm_ks_map =
{
.map = {
.scan = avermedia_rm_ks,
.size = ARRAY_SIZE(avermedia_rm_ks),
.rc_type = RC_TYPE_NEC,
.name = RC_MAP_AVERMEDIA_RM_KS,
}
};
static int __init init_rc_map_avermedia_rm_ks(void)
{
return rc_map_register(&avermedia_rm_ks_map);
}
static void __exit exit_rc_map_avermedia_rm_ks(void)
{
rc_map_unregister(&avermedia_rm_ks_map);
}
module_init(init_rc_map_avermedia_rm_ks)
module_exit(exit_rc_map_avermedia_rm_ks)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Antti Palosaari <crope@iki.fi>");
|
williamfdevine/PrettyLinux
|
drivers/media/rc/keymaps/rc-avermedia-rm-ks.c
|
C
|
gpl-3.0
| 2,710
|
/*
FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd.
All rights reserved
VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
This file is part of the FreeRTOS distribution.
FreeRTOS is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License (version 2) as published by the
Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception.
***************************************************************************
>>! NOTE: The modification to the GPL is included to allow you to !<<
>>! distribute a combined work that includes FreeRTOS without being !<<
>>! obliged to provide the source code for proprietary components !<<
>>! outside of the FreeRTOS kernel. !<<
***************************************************************************
FreeRTOS 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. Full license text is available on the following
link: http://www.freertos.org/a00114.html
***************************************************************************
* *
* FreeRTOS provides completely free yet professionally developed, *
* robust, strictly quality controlled, supported, and cross *
* platform software that is more than just the market leader, it *
* is the industry's de facto standard. *
* *
* Help yourself get started quickly while simultaneously helping *
* to support the FreeRTOS project by purchasing a FreeRTOS *
* tutorial book, reference manual, or both: *
* http://www.FreeRTOS.org/Documentation *
* *
***************************************************************************
http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading
the FAQ page "My application does not run, what could be wrong?". Have you
defined configASSERT()?
http://www.FreeRTOS.org/support - In return for receiving this top quality
embedded software for free we request you assist our global community by
participating in the support forum.
http://www.FreeRTOS.org/training - Investing in training allows your team to
be as productive as possible as early as possible. Now you can receive
FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
Ltd, and the world's leading authority on the world's leading RTOS.
http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
including FreeRTOS+Trace - an indispensable productivity tool, a DOS
compatible FAT file system, and our tiny thread aware UDP/IP stack.
http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS
licenses offer ticketed support, indemnification and commercial middleware.
http://www.SafeRTOS.com - High Integrity Systems also provide a safety
engineered and independently SIL3 certified version for use in safety and
mission critical applications that require provable dependability.
1 tab == 4 spaces!
*/
/*
* Creates all the demo application tasks, then starts the scheduler. The WEB
* documentation provides more details of the demo application tasks.
*
* In addition to the standard demo tasks, the follow demo specific tasks are
* create:
*
* The "Check" task. This only executes every three seconds but has the highest
* priority so is guaranteed to get processor time. Its main function is to
* check that all the other tasks are still operational. Most tasks maintain
* a unique count that is incremented each time the task successfully completes
* its function. Should any error occur within such a task the count is
* permanently halted. The check task inspects the count of each task to ensure
* it has changed since the last time the check task executed. If all the count
* variables have changed all the tasks are still executing error free, and the
* check task toggles the onboard LED. Should any task contain an error at any time
* the LED toggle rate will change from 3 seconds to 500ms.
*
* The "Register Check" tasks. These tasks fill the CPU registers with known
* values, then check that each register still contains the expected value, the
* discovery of an unexpected value being indicative of an error in the RTOS
* context switch mechanism. The register check tasks operate at low priority
* so are switched in and out frequently.
*
*/
/* Scheduler includes. */
#include "FreeRTOS.h"
#include "task.h"
/* Xilinx library includes. */
#include "xcache_l.h"
#include "xintc.h"
/* Demo application includes. */
#include "flash.h"
#include "integer.h"
#include "comtest2.h"
#include "semtest.h"
#include "BlockQ.h"
#include "dynamic.h"
#include "GenQTest.h"
#include "QPeek.h"
#include "blocktim.h"
#include "death.h"
#include "partest.h"
#include "countsem.h"
#include "recmutex.h"
#include "flop.h"
#include "flop-reg-test.h"
/* Priorities assigned to the demo tasks. */
#define mainCHECK_TASK_PRIORITY ( tskIDLE_PRIORITY + 4 )
#define mainSEM_TEST_PRIORITY ( tskIDLE_PRIORITY + 2 )
#define mainCOM_TEST_PRIORITY ( tskIDLE_PRIORITY + 1 )
#define mainQUEUE_BLOCK_PRIORITY ( tskIDLE_PRIORITY + 1 )
#define mainDEATH_PRIORITY ( tskIDLE_PRIORITY + 1 )
#define mainLED_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 )
#define mainGENERIC_QUEUE_PRIORITY ( tskIDLE_PRIORITY )
#define mainQUEUE_POLL_PRIORITY ( tskIDLE_PRIORITY + 1 )
#define mainFLOP_PRIORITY ( tskIDLE_PRIORITY )
/* The first LED used by the COM test and check tasks respectively. */
#define mainCOM_TEST_LED ( 4 )
#define mainCHECK_TEST_LED ( 3 )
/* The baud rate used by the comtest tasks is set by the hardware, so the
baud rate parameters passed into the comtest initialisation has no effect. */
#define mainBAUD_SET_IN_HARDWARE ( 0 )
/* Delay periods used by the check task. If no errors have been found then
the check LED will toggle every mainNO_ERROR_CHECK_DELAY milliseconds. If an
error has been found at any time then the toggle rate will increase to
mainERROR_CHECK_DELAY milliseconds. */
#define mainNO_ERROR_CHECK_DELAY ( ( TickType_t ) 3000 / portTICK_PERIOD_MS )
#define mainERROR_CHECK_DELAY ( ( TickType_t ) 500 / portTICK_PERIOD_MS )
/*
* The tasks defined within this file - described within the comments at the
* head of this page.
*/
static void prvRegTestTask1( void *pvParameters );
static void prvRegTestTask2( void *pvParameters );
static void prvErrorChecks( void *pvParameters );
/*
* Called by the 'check' task to inspect all the standard demo tasks within
* the system, as described within the comments at the head of this page.
*/
static portBASE_TYPE prvCheckOtherTasksAreStillRunning( void );
/*
* Perform any hardware initialisation required by the demo application.
*/
static void prvSetupHardware( void );
/*-----------------------------------------------------------*/
/* xRegTestStatus will get set to pdFAIL by the regtest tasks if they
discover an unexpected value. */
static volatile unsigned portBASE_TYPE xRegTestStatus = pdPASS;
/* Counters used to ensure the regtest tasks are still running. */
static volatile unsigned long ulRegTest1Counter = 0UL, ulRegTest2Counter = 0UL;
/*-----------------------------------------------------------*/
int main( void )
{
/* Must be called prior to installing any interrupt handlers! */
vPortSetupInterruptController();
/* In this case prvSetupHardware() just enables the caches and and
configures the IO ports for the LED outputs. */
prvSetupHardware();
/* Start the standard demo application tasks. Note that the baud rate used
by the comtest tasks is set by the hardware, so the baud rate parameter
passed has no effect. */
vStartLEDFlashTasks( mainLED_TASK_PRIORITY );
vStartIntegerMathTasks( tskIDLE_PRIORITY );
vAltStartComTestTasks( mainCOM_TEST_PRIORITY, mainBAUD_SET_IN_HARDWARE, mainCOM_TEST_LED );
vStartSemaphoreTasks( mainSEM_TEST_PRIORITY );
vStartBlockingQueueTasks ( mainQUEUE_BLOCK_PRIORITY );
vStartDynamicPriorityTasks();
vStartGenericQueueTasks( mainGENERIC_QUEUE_PRIORITY );
vStartQueuePeekTasks();
vCreateBlockTimeTasks();
vStartCountingSemaphoreTasks();
vStartRecursiveMutexTasks();
#if ( configUSE_FPU == 1 )
{
/* A different project is provided that has configUSE_FPU set to 1
in order to demonstrate all the settings required to use the floating
point unit. If you wish to use the floating point unit do not start
with this project. */
vStartMathTasks( mainFLOP_PRIORITY );
vStartFlopRegTests();
}
#endif
/* Create the tasks defined within this file. */
xTaskCreate( prvRegTestTask1, "Regtest1", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
xTaskCreate( prvRegTestTask2, "Regtest2", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
xTaskCreate( prvErrorChecks, "Check", configMINIMAL_STACK_SIZE, NULL, mainCHECK_TASK_PRIORITY, NULL );
/* The suicide tasks must be started last as they record the number of other
tasks that exist within the system. The value is then used to ensure at run
time the number of tasks that exists is within expected bounds. */
vCreateSuicidalTasks( mainDEATH_PRIORITY );
/* Now start the scheduler. Following this call the created tasks should
be executing. */
vTaskStartScheduler();
/* vTaskStartScheduler() will only return if an error occurs while the
idle task is being created. */
for( ;; );
return 0;
}
/*-----------------------------------------------------------*/
static portBASE_TYPE prvCheckOtherTasksAreStillRunning( void )
{
portBASE_TYPE lReturn = pdPASS;
static unsigned long ulLastRegTest1Counter= 0UL, ulLastRegTest2Counter = 0UL;
/* The demo tasks maintain a count that increments every cycle of the task
provided that the task has never encountered an error. This function
checks the counts maintained by the tasks to ensure they are still being
incremented. A count remaining at the same value between calls therefore
indicates that an error has been detected. */
if( xAreIntegerMathsTaskStillRunning() != pdTRUE )
{
lReturn = pdFAIL;
}
if( xAreComTestTasksStillRunning() != pdTRUE )
{
lReturn = pdFAIL;
}
if( xAreSemaphoreTasksStillRunning() != pdTRUE )
{
lReturn = pdFAIL;
}
if( xAreBlockingQueuesStillRunning() != pdTRUE )
{
lReturn = pdFAIL;
}
if( xAreDynamicPriorityTasksStillRunning() != pdTRUE )
{
lReturn = pdFAIL;
}
if( xIsCreateTaskStillRunning() != pdTRUE )
{
lReturn = pdFAIL;
}
if( xAreBlockTimeTestTasksStillRunning() != pdTRUE )
{
lReturn = pdFAIL;
}
if( xAreGenericQueueTasksStillRunning() != pdTRUE )
{
lReturn = pdFAIL;
}
if( xAreQueuePeekTasksStillRunning() != pdTRUE )
{
lReturn = pdFAIL;
}
if( xAreCountingSemaphoreTasksStillRunning() != pdTRUE )
{
lReturn = pdFAIL;
}
if( xAreRecursiveMutexTasksStillRunning() != pdTRUE )
{
lReturn = pdFAIL;
}
#if ( configUSE_FPU == 1 )
if( xAreMathsTaskStillRunning() != pdTRUE )
{
lReturn = pdFAIL;
}
if( xAreFlopRegisterTestsStillRunning() != pdTRUE )
{
lReturn = pdFAIL;
}
#endif
/* Have the register test tasks found any errors? */
if( xRegTestStatus != pdPASS )
{
lReturn = pdFAIL;
}
/* Are the register test tasks still looping? */
if( ulLastRegTest1Counter == ulRegTest1Counter )
{
lReturn = pdFAIL;
}
else
{
ulLastRegTest1Counter = ulRegTest1Counter;
}
if( ulLastRegTest2Counter == ulRegTest2Counter )
{
lReturn = pdFAIL;
}
else
{
ulLastRegTest2Counter = ulRegTest2Counter;
}
return lReturn;
}
/*-----------------------------------------------------------*/
static void prvErrorChecks( void *pvParameters )
{
TickType_t xDelayPeriod = mainNO_ERROR_CHECK_DELAY, xLastExecutionTime;
volatile unsigned portBASE_TYPE uxFreeStack;
/* Just to remove compiler warning. */
( void ) pvParameters;
/* This call is just to demonstrate the use of the function - nothing is
done with the value. You would expect the stack high water mark to be
lower (the function to return a larger value) here at function entry than
later following calls to other functions. */
uxFreeStack = uxTaskGetStackHighWaterMark( NULL );
/* Initialise xLastExecutionTime so the first call to vTaskDelayUntil()
works correctly. */
xLastExecutionTime = xTaskGetTickCount();
/* Cycle for ever, delaying then checking all the other tasks are still
operating without error. */
for( ;; )
{
/* Again just for demo purposes - uxFreeStack should have a lower value
here than following the call to uxTaskGetStackHighWaterMark() on the
task entry. */
uxFreeStack = uxTaskGetStackHighWaterMark( NULL );
/* Wait until it is time to check again. The time we wait here depends
on whether an error has been detected or not. When an error is
detected the time is shortened resulting in a faster LED flash rate. */
vTaskDelayUntil( &xLastExecutionTime, xDelayPeriod );
/* See if the other tasks are all ok. */
if( prvCheckOtherTasksAreStillRunning() != pdPASS )
{
/* An error occurred in one of the tasks so shorten the delay
period - which has the effect of increasing the frequency of the
LED toggle. */
xDelayPeriod = mainERROR_CHECK_DELAY;
}
/* Flash! */
vParTestToggleLED( mainCHECK_TEST_LED );
}
}
/*-----------------------------------------------------------*/
static void prvSetupHardware( void )
{
XCache_EnableICache( 0x80000000 );
XCache_EnableDCache( 0x80000000 );
/* Setup the IO port for use with the LED outputs. */
vParTestInitialise();
}
/*-----------------------------------------------------------*/
void prvRegTest1Pass( void )
{
/* Called from the inline assembler - this cannot be static
otherwise it can get optimised away. */
ulRegTest1Counter++;
}
/*-----------------------------------------------------------*/
void prvRegTest2Pass( void )
{
/* Called from the inline assembler - this cannot be static
otherwise it can get optimised away. */
ulRegTest2Counter++;
}
/*-----------------------------------------------------------*/
void prvRegTestFail( void )
{
/* Called from the inline assembler - this cannot be static
otherwise it can get optimised away. */
xRegTestStatus = pdFAIL;
}
/*-----------------------------------------------------------*/
static void prvRegTestTask1( void *pvParameters )
{
/* Just to remove compiler warning. */
( void ) pvParameters;
/* The first register test task as described at the top of this file. The
values used in the registers are different to those use in the second
register test task. Also, unlike the second register test task, this task
yields between setting the register values and subsequently checking the
register values. */
asm volatile
(
"RegTest1Start: \n\t" \
" \n\t" \
" li 0, 301 \n\t" \
" mtspr 256, 0 #USPRG0 \n\t" \
" li 0, 501 \n\t" \
" mtspr 8, 0 #LR \n\t" \
" li 0, 4 \n\t" \
" mtspr 1, 0 #XER \n\t" \
" \n\t" \
" li 0, 1 \n\t" \
" li 2, 2 \n\t" \
" li 3, 3 \n\t" \
" li 4, 4 \n\t" \
" li 5, 5 \n\t" \
" li 6, 6 \n\t" \
" li 7, 7 \n\t" \
" li 8, 8 \n\t" \
" li 9, 9 \n\t" \
" li 10, 10 \n\t" \
" li 11, 11 \n\t" \
" li 12, 12 \n\t" \
" li 13, 13 \n\t" \
" li 14, 14 \n\t" \
" li 15, 15 \n\t" \
" li 16, 16 \n\t" \
" li 17, 17 \n\t" \
" li 18, 18 \n\t" \
" li 19, 19 \n\t" \
" li 20, 20 \n\t" \
" li 21, 21 \n\t" \
" li 22, 22 \n\t" \
" li 23, 23 \n\t" \
" li 24, 24 \n\t" \
" li 25, 25 \n\t" \
" li 26, 26 \n\t" \
" li 27, 27 \n\t" \
" li 28, 28 \n\t" \
" li 29, 29 \n\t" \
" li 30, 30 \n\t" \
" li 31, 31 \n\t" \
" \n\t" \
" sc \n\t" \
" nop \n\t" \
" \n\t" \
" cmpwi 0, 1 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 2, 2 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 3, 3 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 4, 4 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 5, 5 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 6, 6 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 7, 7 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 8, 8 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 9, 9 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 10, 10 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 11, 11 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 12, 12 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 13, 13 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 14, 14 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 15, 15 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 16, 16 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 17, 17 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 18, 18 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 19, 19 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 20, 20 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 21, 21 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 22, 22 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 23, 23 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 24, 24 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 25, 25 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 26, 26 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 27, 27 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 28, 28 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 29, 29 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 30, 30 \n\t" \
" bne RegTest1Fail \n\t" \
" cmpwi 31, 31 \n\t" \
" bne RegTest1Fail \n\t" \
" \n\t" \
" mfspr 0, 256 #USPRG0 \n\t" \
" cmpwi 0, 301 \n\t" \
" bne RegTest1Fail \n\t" \
" mfspr 0, 8 #LR \n\t" \
" cmpwi 0, 501 \n\t" \
" bne RegTest1Fail \n\t" \
" mfspr 0, 1 #XER \n\t" \
" cmpwi 0, 4 \n\t" \
" bne RegTest1Fail \n\t" \
" \n\t" \
" bl prvRegTest1Pass \n\t" \
" b RegTest1Start \n\t" \
" \n\t" \
"RegTest1Fail: \n\t" \
" \n\t" \
" \n\t" \
" bl prvRegTestFail \n\t" \
" b RegTest1Start \n\t" \
);
}
/*-----------------------------------------------------------*/
static void prvRegTestTask2( void *pvParameters )
{
/* Just to remove compiler warning. */
( void ) pvParameters;
/* The second register test task as described at the top of this file.
Note that this task fills the registers with different values to the
first register test task. */
asm volatile
(
"RegTest2Start: \n\t" \
" \n\t" \
" li 0, 300 \n\t" \
" mtspr 256, 0 #USPRG0 \n\t" \
" li 0, 500 \n\t" \
" mtspr 8, 0 #LR \n\t" \
" li 0, 4 \n\t" \
" mtspr 1, 0 #XER \n\t" \
" \n\t" \
" li 0, 11 \n\t" \
" li 2, 12 \n\t" \
" li 3, 13 \n\t" \
" li 4, 14 \n\t" \
" li 5, 15 \n\t" \
" li 6, 16 \n\t" \
" li 7, 17 \n\t" \
" li 8, 18 \n\t" \
" li 9, 19 \n\t" \
" li 10, 110 \n\t" \
" li 11, 111 \n\t" \
" li 12, 112 \n\t" \
" li 13, 113 \n\t" \
" li 14, 114 \n\t" \
" li 15, 115 \n\t" \
" li 16, 116 \n\t" \
" li 17, 117 \n\t" \
" li 18, 118 \n\t" \
" li 19, 119 \n\t" \
" li 20, 120 \n\t" \
" li 21, 121 \n\t" \
" li 22, 122 \n\t" \
" li 23, 123 \n\t" \
" li 24, 124 \n\t" \
" li 25, 125 \n\t" \
" li 26, 126 \n\t" \
" li 27, 127 \n\t" \
" li 28, 128 \n\t" \
" li 29, 129 \n\t" \
" li 30, 130 \n\t" \
" li 31, 131 \n\t" \
" \n\t" \
" cmpwi 0, 11 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 2, 12 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 3, 13 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 4, 14 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 5, 15 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 6, 16 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 7, 17 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 8, 18 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 9, 19 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 10, 110 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 11, 111 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 12, 112 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 13, 113 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 14, 114 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 15, 115 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 16, 116 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 17, 117 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 18, 118 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 19, 119 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 20, 120 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 21, 121 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 22, 122 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 23, 123 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 24, 124 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 25, 125 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 26, 126 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 27, 127 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 28, 128 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 29, 129 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 30, 130 \n\t" \
" bne RegTest2Fail \n\t" \
" cmpwi 31, 131 \n\t" \
" bne RegTest2Fail \n\t" \
" \n\t" \
" mfspr 0, 256 #USPRG0 \n\t" \
" cmpwi 0, 300 \n\t" \
" bne RegTest2Fail \n\t" \
" mfspr 0, 8 #LR \n\t" \
" cmpwi 0, 500 \n\t" \
" bne RegTest2Fail \n\t" \
" mfspr 0, 1 #XER \n\t" \
" cmpwi 0, 4 \n\t" \
" bne RegTest2Fail \n\t" \
" \n\t" \
" bl prvRegTest2Pass \n\t" \
" b RegTest2Start \n\t" \
" \n\t" \
"RegTest2Fail: \n\t" \
" \n\t" \
" \n\t" \
" bl prvRegTestFail \n\t" \
" b RegTest2Start \n\t" \
);
}
/*-----------------------------------------------------------*/
/* This hook function will get called if there is a suspected stack overflow.
An overflow can cause the task name to be corrupted, in which case the task
handle needs to be used to determine the offending task. */
void vApplicationStackOverflowHook( TaskHandle_t xTask, signed char *pcTaskName );
void vApplicationStackOverflowHook( TaskHandle_t xTask, signed char *pcTaskName )
{
/* To prevent the optimiser removing the variables. */
volatile TaskHandle_t xTaskIn = xTask;
volatile signed char *pcTaskNameIn = pcTaskName;
/* Remove compiler warnings. */
( void ) xTaskIn;
( void ) pcTaskNameIn;
/* The following three calls are simply to stop compiler warnings about the
functions not being used - they are called from the inline assembly. */
prvRegTest1Pass();
prvRegTest2Pass();
prvRegTestFail();
for( ;; );
}
|
RobsonRojas/frertos-udemy
|
FreeRTOSv9.0.0/FreeRTOS/Demo/PPC440_Xilinx_Virtex5_GCC/RTOSDemo/main.c
|
C
|
gpl-3.0
| 24,378
|
/*-------------------------------------------------------------------------
*
* wparser.c
* Standard interface to word parser
*
* Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
*
*
* IDENTIFICATION
* src/backend/tsearch/wparser.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "funcapi.h"
#include "catalog/namespace.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "tsearch/ts_cache.h"
#include "tsearch/ts_utils.h"
#include "utils/builtins.h"
#include "utils/jsonapi.h"
#include "utils/varlena.h"
/******sql-level interface******/
typedef struct
{
int cur;
LexDescr *list;
} TSTokenTypeStorage;
/* state for ts_headline_json_* */
typedef struct HeadlineJsonState
{
HeadlineParsedText *prs;
TSConfigCacheEntry *cfg;
TSParserCacheEntry *prsobj;
TSQuery query;
List *prsoptions;
bool transformed;
} HeadlineJsonState;
static text *headline_json_value(void *_state, char *elem_value, int elem_len);
static void
tt_setup_firstcall(FuncCallContext *funcctx, Oid prsid)
{
TupleDesc tupdesc;
MemoryContext oldcontext;
TSTokenTypeStorage *st;
TSParserCacheEntry *prs = lookup_ts_parser_cache(prsid);
if (!OidIsValid(prs->lextypeOid))
elog(ERROR, "method lextype isn't defined for text search parser %u",
prsid);
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
st = (TSTokenTypeStorage *) palloc(sizeof(TSTokenTypeStorage));
st->cur = 0;
/* lextype takes one dummy argument */
st->list = (LexDescr *) DatumGetPointer(OidFunctionCall1(prs->lextypeOid,
(Datum) 0));
funcctx->user_fctx = (void *) st;
tupdesc = CreateTemplateTupleDesc(3, false);
TupleDescInitEntry(tupdesc, (AttrNumber) 1, "tokid",
INT4OID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 2, "alias",
TEXTOID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 3, "description",
TEXTOID, -1, 0);
funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc);
MemoryContextSwitchTo(oldcontext);
}
static Datum
tt_process_call(FuncCallContext *funcctx)
{
TSTokenTypeStorage *st;
st = (TSTokenTypeStorage *) funcctx->user_fctx;
if (st->list && st->list[st->cur].lexid)
{
Datum result;
char *values[3];
char txtid[16];
HeapTuple tuple;
sprintf(txtid, "%d", st->list[st->cur].lexid);
values[0] = txtid;
values[1] = st->list[st->cur].alias;
values[2] = st->list[st->cur].descr;
tuple = BuildTupleFromCStrings(funcctx->attinmeta, values);
result = HeapTupleGetDatum(tuple);
pfree(values[1]);
pfree(values[2]);
st->cur++;
return result;
}
if (st->list)
pfree(st->list);
pfree(st);
return (Datum) 0;
}
Datum
ts_token_type_byid(PG_FUNCTION_ARGS)
{
FuncCallContext *funcctx;
Datum result;
if (SRF_IS_FIRSTCALL())
{
funcctx = SRF_FIRSTCALL_INIT();
tt_setup_firstcall(funcctx, PG_GETARG_OID(0));
}
funcctx = SRF_PERCALL_SETUP();
if ((result = tt_process_call(funcctx)) != (Datum) 0)
SRF_RETURN_NEXT(funcctx, result);
SRF_RETURN_DONE(funcctx);
}
Datum
ts_token_type_byname(PG_FUNCTION_ARGS)
{
FuncCallContext *funcctx;
Datum result;
if (SRF_IS_FIRSTCALL())
{
text *prsname = PG_GETARG_TEXT_PP(0);
Oid prsId;
funcctx = SRF_FIRSTCALL_INIT();
prsId = get_ts_parser_oid(textToQualifiedNameList(prsname), false);
tt_setup_firstcall(funcctx, prsId);
}
funcctx = SRF_PERCALL_SETUP();
if ((result = tt_process_call(funcctx)) != (Datum) 0)
SRF_RETURN_NEXT(funcctx, result);
SRF_RETURN_DONE(funcctx);
}
typedef struct
{
int type;
char *lexeme;
} LexemeEntry;
typedef struct
{
int cur;
int len;
LexemeEntry *list;
} PrsStorage;
static void
prs_setup_firstcall(FuncCallContext *funcctx, Oid prsid, text *txt)
{
TupleDesc tupdesc;
MemoryContext oldcontext;
PrsStorage *st;
TSParserCacheEntry *prs = lookup_ts_parser_cache(prsid);
char *lex = NULL;
int llen = 0,
type = 0;
void *prsdata;
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
st = (PrsStorage *) palloc(sizeof(PrsStorage));
st->cur = 0;
st->len = 16;
st->list = (LexemeEntry *) palloc(sizeof(LexemeEntry) * st->len);
prsdata = (void *) DatumGetPointer(FunctionCall2(&prs->prsstart,
PointerGetDatum(VARDATA_ANY(txt)),
Int32GetDatum(VARSIZE_ANY_EXHDR(txt))));
while ((type = DatumGetInt32(FunctionCall3(&prs->prstoken,
PointerGetDatum(prsdata),
PointerGetDatum(&lex),
PointerGetDatum(&llen)))) != 0)
{
if (st->cur >= st->len)
{
st->len = 2 * st->len;
st->list = (LexemeEntry *) repalloc(st->list, sizeof(LexemeEntry) * st->len);
}
st->list[st->cur].lexeme = palloc(llen + 1);
memcpy(st->list[st->cur].lexeme, lex, llen);
st->list[st->cur].lexeme[llen] = '\0';
st->list[st->cur].type = type;
st->cur++;
}
FunctionCall1(&prs->prsend, PointerGetDatum(prsdata));
st->len = st->cur;
st->cur = 0;
funcctx->user_fctx = (void *) st;
tupdesc = CreateTemplateTupleDesc(2, false);
TupleDescInitEntry(tupdesc, (AttrNumber) 1, "tokid",
INT4OID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 2, "token",
TEXTOID, -1, 0);
funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc);
MemoryContextSwitchTo(oldcontext);
}
static Datum
prs_process_call(FuncCallContext *funcctx)
{
PrsStorage *st;
st = (PrsStorage *) funcctx->user_fctx;
if (st->cur < st->len)
{
Datum result;
char *values[2];
char tid[16];
HeapTuple tuple;
values[0] = tid;
sprintf(tid, "%d", st->list[st->cur].type);
values[1] = st->list[st->cur].lexeme;
tuple = BuildTupleFromCStrings(funcctx->attinmeta, values);
result = HeapTupleGetDatum(tuple);
pfree(values[1]);
st->cur++;
return result;
}
else
{
if (st->list)
pfree(st->list);
pfree(st);
}
return (Datum) 0;
}
Datum
ts_parse_byid(PG_FUNCTION_ARGS)
{
FuncCallContext *funcctx;
Datum result;
if (SRF_IS_FIRSTCALL())
{
text *txt = PG_GETARG_TEXT_PP(1);
funcctx = SRF_FIRSTCALL_INIT();
prs_setup_firstcall(funcctx, PG_GETARG_OID(0), txt);
PG_FREE_IF_COPY(txt, 1);
}
funcctx = SRF_PERCALL_SETUP();
if ((result = prs_process_call(funcctx)) != (Datum) 0)
SRF_RETURN_NEXT(funcctx, result);
SRF_RETURN_DONE(funcctx);
}
Datum
ts_parse_byname(PG_FUNCTION_ARGS)
{
FuncCallContext *funcctx;
Datum result;
if (SRF_IS_FIRSTCALL())
{
text *prsname = PG_GETARG_TEXT_PP(0);
text *txt = PG_GETARG_TEXT_PP(1);
Oid prsId;
funcctx = SRF_FIRSTCALL_INIT();
prsId = get_ts_parser_oid(textToQualifiedNameList(prsname), false);
prs_setup_firstcall(funcctx, prsId, txt);
}
funcctx = SRF_PERCALL_SETUP();
if ((result = prs_process_call(funcctx)) != (Datum) 0)
SRF_RETURN_NEXT(funcctx, result);
SRF_RETURN_DONE(funcctx);
}
Datum
ts_headline_byid_opt(PG_FUNCTION_ARGS)
{
Oid tsconfig = PG_GETARG_OID(0);
text *in = PG_GETARG_TEXT_PP(1);
TSQuery query = PG_GETARG_TSQUERY(2);
text *opt = (PG_NARGS() > 3 && PG_GETARG_POINTER(3)) ? PG_GETARG_TEXT_PP(3) : NULL;
HeadlineParsedText prs;
List *prsoptions;
text *out;
TSConfigCacheEntry *cfg;
TSParserCacheEntry *prsobj;
cfg = lookup_ts_config_cache(tsconfig);
prsobj = lookup_ts_parser_cache(cfg->prsId);
if (!OidIsValid(prsobj->headlineOid))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("text search parser does not support headline creation")));
memset(&prs, 0, sizeof(HeadlineParsedText));
prs.lenwords = 32;
prs.words = (HeadlineWordEntry *) palloc(sizeof(HeadlineWordEntry) * prs.lenwords);
hlparsetext(cfg->cfgId, &prs, query,
VARDATA_ANY(in), VARSIZE_ANY_EXHDR(in));
if (opt)
prsoptions = deserialize_deflist(PointerGetDatum(opt));
else
prsoptions = NIL;
FunctionCall3(&(prsobj->prsheadline),
PointerGetDatum(&prs),
PointerGetDatum(prsoptions),
PointerGetDatum(query));
out = generateHeadline(&prs);
PG_FREE_IF_COPY(in, 1);
PG_FREE_IF_COPY(query, 2);
if (opt)
PG_FREE_IF_COPY(opt, 3);
pfree(prs.words);
pfree(prs.startsel);
pfree(prs.stopsel);
PG_RETURN_POINTER(out);
}
Datum
ts_headline_byid(PG_FUNCTION_ARGS)
{
PG_RETURN_DATUM(DirectFunctionCall3(ts_headline_byid_opt,
PG_GETARG_DATUM(0),
PG_GETARG_DATUM(1),
PG_GETARG_DATUM(2)));
}
Datum
ts_headline(PG_FUNCTION_ARGS)
{
PG_RETURN_DATUM(DirectFunctionCall3(ts_headline_byid_opt,
ObjectIdGetDatum(getTSCurrentConfig(true)),
PG_GETARG_DATUM(0),
PG_GETARG_DATUM(1)));
}
Datum
ts_headline_opt(PG_FUNCTION_ARGS)
{
PG_RETURN_DATUM(DirectFunctionCall4(ts_headline_byid_opt,
ObjectIdGetDatum(getTSCurrentConfig(true)),
PG_GETARG_DATUM(0),
PG_GETARG_DATUM(1),
PG_GETARG_DATUM(2)));
}
Datum
ts_headline_jsonb_byid_opt(PG_FUNCTION_ARGS)
{
Oid tsconfig = PG_GETARG_OID(0);
Jsonb *jb = PG_GETARG_JSONB_P(1);
TSQuery query = PG_GETARG_TSQUERY(2);
text *opt = (PG_NARGS() > 3 && PG_GETARG_POINTER(3)) ? PG_GETARG_TEXT_P(3) : NULL;
Jsonb *out;
JsonTransformStringValuesAction action = (JsonTransformStringValuesAction) headline_json_value;
HeadlineParsedText prs;
HeadlineJsonState *state = palloc0(sizeof(HeadlineJsonState));
memset(&prs, 0, sizeof(HeadlineParsedText));
prs.lenwords = 32;
prs.words = (HeadlineWordEntry *) palloc(sizeof(HeadlineWordEntry) * prs.lenwords);
state->prs = &prs;
state->cfg = lookup_ts_config_cache(tsconfig);
state->prsobj = lookup_ts_parser_cache(state->cfg->prsId);
state->query = query;
if (opt)
state->prsoptions = deserialize_deflist(PointerGetDatum(opt));
else
state->prsoptions = NIL;
if (!OidIsValid(state->prsobj->headlineOid))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("text search parser does not support headline creation")));
out = transform_jsonb_string_values(jb, state, action);
PG_FREE_IF_COPY(jb, 1);
PG_FREE_IF_COPY(query, 2);
if (opt)
PG_FREE_IF_COPY(opt, 3);
pfree(prs.words);
if (state->transformed)
{
pfree(prs.startsel);
pfree(prs.stopsel);
}
PG_RETURN_JSONB_P(out);
}
Datum
ts_headline_jsonb(PG_FUNCTION_ARGS)
{
PG_RETURN_DATUM(DirectFunctionCall3(ts_headline_jsonb_byid_opt,
ObjectIdGetDatum(getTSCurrentConfig(true)),
PG_GETARG_DATUM(0),
PG_GETARG_DATUM(1)));
}
Datum
ts_headline_jsonb_byid(PG_FUNCTION_ARGS)
{
PG_RETURN_DATUM(DirectFunctionCall3(ts_headline_jsonb_byid_opt,
PG_GETARG_DATUM(0),
PG_GETARG_DATUM(1),
PG_GETARG_DATUM(2)));
}
Datum
ts_headline_jsonb_opt(PG_FUNCTION_ARGS)
{
PG_RETURN_DATUM(DirectFunctionCall4(ts_headline_jsonb_byid_opt,
ObjectIdGetDatum(getTSCurrentConfig(true)),
PG_GETARG_DATUM(0),
PG_GETARG_DATUM(1),
PG_GETARG_DATUM(2)));
}
Datum
ts_headline_json_byid_opt(PG_FUNCTION_ARGS)
{
Oid tsconfig = PG_GETARG_OID(0);
text *json = PG_GETARG_TEXT_P(1);
TSQuery query = PG_GETARG_TSQUERY(2);
text *opt = (PG_NARGS() > 3 && PG_GETARG_POINTER(3)) ? PG_GETARG_TEXT_P(3) : NULL;
text *out;
JsonTransformStringValuesAction action = (JsonTransformStringValuesAction) headline_json_value;
HeadlineParsedText prs;
HeadlineJsonState *state = palloc0(sizeof(HeadlineJsonState));
memset(&prs, 0, sizeof(HeadlineParsedText));
prs.lenwords = 32;
prs.words = (HeadlineWordEntry *) palloc(sizeof(HeadlineWordEntry) * prs.lenwords);
state->prs = &prs;
state->cfg = lookup_ts_config_cache(tsconfig);
state->prsobj = lookup_ts_parser_cache(state->cfg->prsId);
state->query = query;
if (opt)
state->prsoptions = deserialize_deflist(PointerGetDatum(opt));
else
state->prsoptions = NIL;
if (!OidIsValid(state->prsobj->headlineOid))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("text search parser does not support headline creation")));
out = transform_json_string_values(json, state, action);
PG_FREE_IF_COPY(json, 1);
PG_FREE_IF_COPY(query, 2);
if (opt)
PG_FREE_IF_COPY(opt, 3);
pfree(prs.words);
if (state->transformed)
{
pfree(prs.startsel);
pfree(prs.stopsel);
}
PG_RETURN_TEXT_P(out);
}
Datum
ts_headline_json(PG_FUNCTION_ARGS)
{
PG_RETURN_DATUM(DirectFunctionCall3(ts_headline_json_byid_opt,
ObjectIdGetDatum(getTSCurrentConfig(true)),
PG_GETARG_DATUM(0),
PG_GETARG_DATUM(1)));
}
Datum
ts_headline_json_byid(PG_FUNCTION_ARGS)
{
PG_RETURN_DATUM(DirectFunctionCall3(ts_headline_json_byid_opt,
PG_GETARG_DATUM(0),
PG_GETARG_DATUM(1),
PG_GETARG_DATUM(2)));
}
Datum
ts_headline_json_opt(PG_FUNCTION_ARGS)
{
PG_RETURN_DATUM(DirectFunctionCall4(ts_headline_json_byid_opt,
ObjectIdGetDatum(getTSCurrentConfig(true)),
PG_GETARG_DATUM(0),
PG_GETARG_DATUM(1),
PG_GETARG_DATUM(2)));
}
/*
* Return headline in text from, generated from a json(b) element
*/
static text *
headline_json_value(void *_state, char *elem_value, int elem_len)
{
HeadlineJsonState *state = (HeadlineJsonState *) _state;
HeadlineParsedText *prs = state->prs;
TSConfigCacheEntry *cfg = state->cfg;
TSParserCacheEntry *prsobj = state->prsobj;
TSQuery query = state->query;
List *prsoptions = state->prsoptions;
prs->curwords = 0;
hlparsetext(cfg->cfgId, prs, query, elem_value, elem_len);
FunctionCall3(&(prsobj->prsheadline),
PointerGetDatum(prs),
PointerGetDatum(prsoptions),
PointerGetDatum(query));
state->transformed = true;
return generateHeadline(prs);
}
|
robins/postgres
|
src/backend/tsearch/wparser.c
|
C
|
gpl-3.0
| 13,513
|
/*
* object.c
*
* Copyright (C) 2012 - Dr.NP
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Universal hash array object
*
* @package bsp::libbsp-core
* @author Dr.NP <np@bsgroup.org>
* @update 05/21/2013
* @changelog
* [06/11/2012] - Creation
* [08/14/2012] - Float / Double byte order
* [09/28/2012] - Array support
* [05/21/2013] - Remove float / double byte-order reverse
* [12/17/2013] - Lightuserdata supported
* [08/05/2014] - Rebuild
*/
#include "bsp.h"
/* Set values */
/*
void set_item_int8(BSP_VALUE *val, const int8_t value)
{
if (val)
{
set_int8(value, val->lval);
val->type = BSP_VAL_INT8;
}
return;
}
void set_item_int16(BSP_VALUE *val, const int16_t value)
{
if (val)
{
set_int16(value, val->lval);
val->type = BSP_VAL_INT16;
}
return;
}
void set_item_int32(BSP_VALUE *val, const int32_t value)
{
if (val)
{
set_int32(value, val->lval);
val->type = BSP_VAL_INT32;
}
return;
}
void set_item_int64(BSP_VALUE *val, const int64_t value)
{
if (val)
{
set_int64(value, val->lval);
item->value.type = BSP_VAL_INT64;
}
return;
}
*/
// Set value to value
void value_set_int(BSP_VALUE *val, const int64_t value)
{
if (val)
{
set_vint(value, val->lval);
val->type = BSP_VAL_INT;
}
}
void value_set_float(BSP_VALUE *val, const float value)
{
if (val)
{
set_float(value, val->lval);
val->type = BSP_VAL_FLOAT;
}
return;
}
void value_set_double(BSP_VALUE *val, const double value)
{
if (val)
{
set_double(value, val->lval);
val->type = BSP_VAL_DOUBLE;
}
return;
}
void value_set_boolean_true(BSP_VALUE *val)
{
if (val)
{
set_vint(1, val->lval);
val->type = BSP_VAL_BOOLEAN_TRUE;
}
return;
}
void value_set_boolean_false(BSP_VALUE *val)
{
if (val)
{
set_vint(0, val->lval);
val->type = BSP_VAL_BOOLEAN_FALSE;
}
return;
}
void value_set_pointer(BSP_VALUE *val, const void *p)
{
if (val)
{
val->rval = (void *) p;
val->type = BSP_VAL_POINTER;
}
return;
}
void value_set_string(BSP_VALUE *val, BSP_STRING *str)
{
if (val && str)
{
val->rval = (void *) str;
val->type = BSP_VAL_STRING;
}
return;
}
void value_set_object(BSP_VALUE *val, BSP_OBJECT *obj)
{
if (val && obj)
{
val->rval = (void *) obj;
val->type = BSP_VAL_OBJECT;
}
return;
}
void value_set_null(BSP_VALUE *val)
{
if (val)
{
val->type = BSP_VAL_NULL;
}
return;
}
// Get value from value
int64_t value_get_int(BSP_VALUE *val)
{
int64_t ret = 0;
if (val)
{
if (BSP_VAL_INT == val->type)
{
// int64
ret = get_vint(val->lval, NULL);
}
else if (BSP_VAL_INT29 == val->type)
{
// int29
ret = get_vint29(val->lval, NULL);
}
}
return ret;
}
int value_get_boolean(BSP_VALUE *val)
{
int ret = BSP_BOOLEAN_FALSE;
if (val && BSP_VAL_BOOLEAN_TRUE == val->type)
{
ret = BSP_BOOLEAN_TRUE;
}
return ret;
}
float value_get_float(BSP_VALUE *val)
{
float ret = 0.0;
if (val && BSP_VAL_FLOAT == val->type)
{
ret = get_float(val->rval);
}
return ret;
}
double value_get_double(BSP_VALUE *val)
{
double ret = 0.0;
if (val && BSP_VAL_DOUBLE == val->type)
{
ret = get_double(val->rval);
}
return ret;
}
void * value_get_pointer(BSP_VALUE *val)
{
void *ret = NULL;
if (val && BSP_VAL_POINTER == val->type)
{
ret = val->rval;
}
return ret;
}
BSP_STRING * value_get_string(BSP_VALUE *val)
{
BSP_STRING *ret = NULL;
if (val && BSP_VAL_STRING == val->type)
{
ret = (BSP_STRING *) val->rval;
}
return ret;
}
BSP_OBJECT * value_get_object(BSP_VALUE *val)
{
BSP_OBJECT *ret = NULL;
if (val && BSP_VAL_OBJECT == val->type)
{
ret = (BSP_OBJECT *) val->rval;
}
return ret;
}
/* Object & Value */
BSP_OBJECT * new_object(char type)
{
BSP_OBJECT *obj = bsp_calloc(1, sizeof(BSP_OBJECT));
if (obj)
{
obj->type = type;
bsp_spin_init(&obj->lock);
}
return obj;
}
void del_object(BSP_OBJECT *obj)
{
if (!obj)
{
return;
}
BSP_VALUE *val = NULL;
struct bsp_array_t *array = NULL;
struct bsp_hash_t *hash = NULL;
struct bsp_hash_item_t *item = NULL, *old = NULL;
size_t idx, bucket, seq;
bsp_spin_lock(&obj->lock);
switch (obj->type)
{
case OBJECT_TYPE_SINGLE :
val = (BSP_VALUE *) obj->node;
del_value(val);
break;
case OBJECT_TYPE_ARRAY :
array = (struct bsp_array_t *) obj->node;
if (array)
{
for (idx = 0; idx < array->nitems; idx ++)
{
bucket = (idx / ARRAY_BUCKET_SIZE);
seq = idx % ARRAY_BUCKET_SIZE;
if (bucket < array->nbuckets && array->items[bucket])
{
val = array->items[bucket][seq];
del_value(val);
}
}
bsp_free(array);
}
break;
case OBJECT_TYPE_HASH :
hash = (struct bsp_hash_t *) obj->node;
if (hash)
{
item = hash->head;
while (item)
{
del_string(item->key);
del_value(item->value);
old = item;
item = old->lnext;
bsp_free(old);
}
bsp_free(hash);
}
break;
case OBJECT_TYPE_UNDETERMINED :
default :
break;
}
bsp_spin_unlock(&obj->lock);
bsp_free(obj);
return;
}
BSP_VALUE * new_value()
{
return (BSP_VALUE *) bsp_calloc(1, sizeof(BSP_VALUE));
}
void del_value(BSP_VALUE *val)
{
if (val)
{
if (BSP_VAL_POINTER == val->type)
{
// Just ignore, we cannot determine what you are
}
else if (BSP_VAL_STRING == val->type)
{
del_string((BSP_STRING *) val->rval);
}
else if (BSP_VAL_OBJECT == val->type)
{
del_object((BSP_OBJECT *) val->rval);
}
else
{
// Local value, Just free
}
}
return bsp_free(val);
}
/* Item cursor operates */
// TODO : Not thread-safe, but maybe not neccessery
BSP_VALUE * curr_item(BSP_OBJECT *obj)
{
if (!obj)
{
return NULL;
}
BSP_VALUE *curr = NULL;
struct bsp_array_t *array = NULL;
struct bsp_hash_t *hash = NULL;
switch (obj->type)
{
case OBJECT_TYPE_SINGLE :
curr = (BSP_VALUE *) obj->node;
break;
case OBJECT_TYPE_ARRAY :
array = (struct bsp_array_t *) obj->node;
if (array)
{
size_t bucket = (array->curr / ARRAY_BUCKET_SIZE);
if (array->curr < array->nitems && bucket < array->nbuckets && array->items[bucket])
{
curr = array->items[bucket][array->curr % ARRAY_BUCKET_SIZE];
}
}
break;
case OBJECT_TYPE_HASH :
hash = (struct bsp_hash_t *) obj->node;
if (hash && hash->curr)
{
// Just value
// You can get current key with curr_item_key()
curr = hash->curr->value;
}
break;
default :
curr = NULL;
break;
}
return curr;
}
// Current array index
size_t curr_array_index(BSP_OBJECT *obj)
{
size_t idx = 0;
if (obj && OBJECT_TYPE_ARRAY == obj->type)
{
struct bsp_array_t *array = (struct bsp_array_t *) obj->node;
if (array)
{
idx = array->curr;
}
}
return idx;
}
// Current hash key
BSP_STRING * curr_hash_key(BSP_OBJECT *obj)
{
BSP_STRING *key = NULL;
if (obj && OBJECT_TYPE_HASH == obj->type)
{
struct bsp_hash_t *hash = (struct bsp_hash_t *) obj->node;
if (hash && hash->curr)
{
key = hash->curr->key;
}
}
return key;
}
size_t object_size(BSP_OBJECT *obj)
{
size_t ret = 0;
struct bsp_array_t *array = NULL;
struct bsp_hash_t *hash = NULL;
if (obj)
{
switch (obj->type)
{
case OBJECT_TYPE_SINGLE :
if (obj->node)
{
ret = 1;
}
break;
case OBJECT_TYPE_ARRAY :
array = (struct bsp_array_t *) obj->node;
if (array)
{
ret = array->nitems;
}
break;
case OBJECT_TYPE_HASH :
hash = (struct bsp_hash_t *) obj->node;
if (hash)
{
ret = hash->nitems;
}
break;
default :
break;
}
}
return ret;
}
void reset_object(BSP_OBJECT *obj)
{
if (!obj)
{
return;
}
struct bsp_array_t *array = NULL;
struct bsp_hash_t *hash = NULL;
switch (obj->type)
{
case OBJECT_TYPE_ARRAY :
array = (struct bsp_array_t *) obj->node;
if (array)
{
array->curr = 0;
}
break;
case OBJECT_TYPE_HASH :
hash = (struct bsp_hash_t *) obj->node;
if (hash)
{
hash->curr = hash->head;
}
break;
case OBJECT_TYPE_SINGLE :
default :
// Nothing to do
break;
}
return;
}
void next_item(BSP_OBJECT *obj)
{
if (!obj)
{
return;
}
struct bsp_array_t *array = NULL;
struct bsp_hash_t *hash = NULL;
switch (obj->type)
{
case OBJECT_TYPE_ARRAY :
array = (struct bsp_array_t *) obj->node;
if (array && array->curr < array->nitems)
{
array->curr ++;
}
break;
case OBJECT_TYPE_HASH :
hash = (struct bsp_hash_t *) obj->node;
if (hash && hash->curr)
{
hash->curr = hash->curr->lnext;
}
break;
case OBJECT_TYPE_SINGLE :
default :
// Nothing to NEXT
break;
}
return;
}
void prev_item(BSP_OBJECT *obj)
{
if (!obj)
{
return;
}
struct bsp_array_t *array = NULL;
struct bsp_hash_t *hash = NULL;
switch (obj->type)
{
case OBJECT_TYPE_ARRAY :
array = (struct bsp_array_t *) obj->node;
if (array && array->curr > 0)
{
array->curr --;
}
break;
case OBJECT_TYPE_HASH :
hash = (struct bsp_hash_t *) obj->node;
if (hash && hash->curr)
{
hash->curr = hash->curr->lprev;
}
break;
case OBJECT_TYPE_SINGLE :
default :
// Nothing to PREV
break;
}
}
/* Sort */
/*
inline static int __sort_compare(const char *v1,
size_t v1_len,
long long int v1_int,
const char *v2,
size_t v2_len,
long long int v2_int)
{
register int is_d1 = 1, is_d2 = 1;
if (v1_int == 0)
{
if (0 != strcmp(v1, "0"))
{
is_d1 = 0;
}
}
if (v2_int == 0)
{
if (0 != strcmp(v2, "0"))
{
is_d2 = 0;
}
}
if (is_d1 && is_d2)
{
if (v1_int > v2_int)
{
return 1;
}
else
{
return -1;
}
}
if (!is_d1 && !is_d2)
{
// Strings
if (v1_len > v2_len)
{
return memcmp(v1, v2, v2_len);
}
else
{
return memcmp(v1, v2, v1_len);
}
}
return (is_d1 > is_d2) ? -1 : 1;
}
inline static int _sort_compare(const char *v1,
size_t v1_len,
long long int v1_int,
const char *v2,
size_t v2_len,
long long int v2_int)
{
return (v1_len > v2_len) ? memcmp(v1, v2, v2_len) : memcmp(v1, v2, v1_len);
}
inline static void _sort_qsort(BSP_OBJECT_ITEM **list, size_t nitems)
{
int64_t begin_stack[256];
int64_t end_stack[256];
register int64_t begin;
register int64_t end;
register int64_t middle;
register int64_t pivot;
register int64_t seg1;
register int64_t seg2;
register int loop, c1, c2, c3;
register BSP_OBJECT_ITEM *tmp;
begin_stack[0] = 0;
end_stack[0] = nitems - 1;
for (loop = 0; loop >= 0; loop --)
{
begin = begin_stack[loop];
end = end_stack[loop];
while (begin < end)
{
// Find pivot
middle = (end - begin) >> 1;
c1 = _sort_compare(
list[begin]->key,
list[begin]->key_len,
list[begin]->key_int,
list[middle]->key,
list[middle]->key_len,
list[middle]->key_int);
c2 = _sort_compare(
list[middle]->key,
list[middle]->key_len,
list[middle]->key_int,
list[end]->key,
list[end]->key_len,
list[end]->key_int);
c3 = _sort_compare(
list[end]->key,
list[end]->key_len,
list[end]->key_int,
list[begin]->key,
list[begin]->key_len,
list[begin]->key_int);
if (c1 >= 0)
{
pivot = (c2 >= 0) ? middle : ((c3 >= 0) ? begin : end);
}
else
{
pivot = (c2 < 0) ? middle : ((c3 < 0) ? begin : end);
}
if (pivot != begin)
{
// Swap pivot & begin
tmp = list[begin]; list[begin] = list[pivot]; list[pivot] = tmp;
}
seg1 = begin + 1;
seg2 = end;
while (1)
{
for (
;
seg1 < seg2 && _sort_compare(
list[begin]->key,
list[begin]->key_len,
list[begin]->key_int,
list[seg1]->key,
list[seg1]->key_len,
list[seg1]->key_int) > 0;
seg1 ++);
for (
;
seg2 >= seg1 && _sort_compare(
list[seg2]->key,
list[seg2]->key_len,
list[seg2]->key_int,
list[begin]->key,
list[begin]->key_len,
list[begin]->key_int) > 0;
seg2 --);
if (seg1 >= seg2)
{
break;
}
tmp = list[seg1]; list[seg1] = list[seg2]; list[seg2] = tmp;
seg1 ++;
seg2 --;
}
// Swap begin & seg2
tmp = list[begin]; list[begin] = list[seg2]; list[seg2] = tmp;
if ((seg2 - begin) <= (end - seg2))
{
if ((seg2 + 1) < end)
{
begin_stack[loop] = seg2 + 1;
end_stack[loop ++] = end;
}
end = seg2 - 1;
}
else
{
if ((seg2 - 1) > begin)
{
begin_stack[loop] = begin;
end_stack[loop ++] = seg2 - 1;
}
begin = seg2 + 1;
}
}
}
return;
}
// Quicksort
int sort_object(BSP_OBJECT *obj)
{
if (!obj || 2 > obj->nitems )
{
return BSP_RTN_ERROR_GENERAL;
}
// Make a copy of item link
BSP_OBJECT_ITEM **list = bsp_calloc(obj->nitems, sizeof(BSP_OBJECT_ITEM *));
if (!list)
{
return BSP_RTN_ERROR_MEMORY;
}
bsp_spin_lock(&obj->obj_lock);
BSP_OBJECT_ITEM *curr = NULL;
int i = 0;
reset_object(obj);
curr = curr_item(obj);
while (curr)
{
if (i > obj->nitems - 1)
{
break;
}
list[i ++] = curr;
next_item(obj);
curr = curr_item(obj);
}
_sort_qsort(list, obj->nitems);
// Relink item link
for (i = 1; i < obj->nitems - 1; i ++)
{
list[i]->lnext = list[i + 1];
list[i]->lprev = list[i - 1];
}
list[0]->lnext = list[1];
list[0]->lprev = NULL;
obj->head = list[0];
list[obj->nitems - 1]->lnext = NULL;
list[obj->nitems - 1]->lprev = list[obj->nitems - 2];
obj->tail = list[obj->nitems - 1];
bsp_spin_unlock(&obj->obj_lock);
bsp_free(list);
return BSP_RTN_SUCCESS;
}
*/
// Find item from hash
static inline struct bsp_hash_item_t * _find_hash(struct bsp_hash_t *hash, BSP_STRING *key)
{
struct bsp_hash_item_t *ret = NULL;
if (hash && key && hash->hash_table)
{
uint32_t hash_key = bsp_hash(STR_STR(key), STR_LEN(key));
struct bsp_hash_item_t *bucket = &hash->hash_table[hash_key % hash->hash_size];
struct bsp_hash_item_t *curr = bucket->next;
while (curr)
{
if (STR_IS_EQUAL(key, curr->key))
{
ret = curr;
break;
}
curr = curr->next;
}
}
return ret;
}
static inline struct bsp_hash_item_t * _find_hash_str(struct bsp_hash_t *hash, const char *key)
{
struct bsp_hash_item_t *ret = NULL;
if (hash && key && hash->hash_table)
{
uint32_t hash_key = bsp_hash(key, -1);
struct bsp_hash_item_t *bucket = &hash->hash_table[hash_key % hash->hash_size];
struct bsp_hash_item_t *curr = bucket->next;
while (curr)
{
if (0 == strncmp(key, STR_STR(curr->key), STR_LEN(curr->key)))
{
ret = curr;
break;
}
curr = curr->next;
}
}
return ret;
}
// Remove item from hash
static inline int _remove_hash(struct bsp_hash_t *hash, BSP_STRING *key)
{
int ret = 0;
struct bsp_hash_item_t *item = _find_hash(hash, key);
if (item)
{
if (hash->head == item)
{
hash->head = item->lnext;
}
if (hash->tail == item)
{
hash->tail = item->lprev;
}
if (hash->curr == item)
{
hash->curr = item->lnext;
}
if (item->lnext)
{
item->lnext->lprev = item->lprev;
}
if (item->next)
{
item->next->prev = item->prev;
}
if (item->lprev)
{
item->lprev->lnext = item->lnext;
}
if (item->prev)
{
item->prev->next = item->next;
}
ret = 1;
// Delete item
del_value(item->value);
del_string(item->key);
bsp_free(item);
item = NULL;
}
return ret;
}
static inline int _remove_hash_str(struct bsp_hash_t *hash, const char *key)
{
int ret = 0;
struct bsp_hash_item_t *item = _find_hash_str(hash, key);
if (item)
{
if (hash->head == item)
{
hash->head = item->lnext;
}
if (hash->tail == item)
{
hash->tail = item->lprev;
}
if (hash->curr == item)
{
hash->curr = item->lnext;
}
if (item->lnext)
{
item->lnext->lprev = item->lprev;
}
if (item->next)
{
item->next->prev = item->prev;
}
if (item->lprev)
{
item->lprev->lnext = item->lnext;
}
if (item->prev)
{
item->prev->next = item->next;
}
ret = 1;
// Delete item
del_value(item->value);
del_string(item->key);
bsp_free(item);
item = NULL;
}
return ret;
}
// Insert an item into hash
static int _insert_hash(struct bsp_hash_t *hash, BSP_STRING *key, BSP_VALUE *val)
{
int ret = 0;
if (hash && hash->hash_table && key && val)
{
struct bsp_hash_item_t *item = _find_hash(hash, key);
if (item)
{
// Just overwrite value
if (item->value)
{
del_value(item->value);
}
item->value = val;
}
else
{
item = bsp_calloc(1, sizeof(struct bsp_hash_item_t));
item->key = key;
item->value = val;
// Insert into link
if (!hash->head)
{
hash->head = item;
}
if (hash->tail)
{
hash->tail->lnext = item;
item->lprev = hash->tail;
}
hash->tail = item;
// Insert into hash table
uint32_t hash_key = bsp_hash(STR_STR(key), STR_LEN(key));
struct bsp_hash_item_t *bucket = &hash->hash_table[hash_key % hash->hash_size];
item->next = bucket->next;
item->prev = bucket;
bucket->next = item;
ret = 1;
}
}
return ret;
}
static int _insert_hash_str(struct bsp_hash_t *hash, const char *key, BSP_VALUE *val)
{
int ret = 0;
if (hash && hash->hash_table && key && val)
{
struct bsp_hash_item_t *item = _find_hash_str(hash, key);
if (item)
{
// Just overwrite value
if (item->value)
{
del_value(item->value);
}
item->value = val;
}
else
{
item = bsp_calloc(1, sizeof(struct bsp_hash_item_t));
item->key = new_string(key, -1);
item->value = val;
// Insert into link
if (!hash->head)
{
hash->head = item;
}
if (hash->tail)
{
hash->tail->lnext = item;
item->lprev = hash->tail;
}
hash->tail = item;
// Insert into hash table
uint32_t hash_key = bsp_hash(key, -1);
struct bsp_hash_item_t *bucket = &hash->hash_table[hash_key % hash->hash_size];
item->next = bucket->next;
item->prev = bucket;
bucket->next = item;
ret = 1;
}
}
return ret;
}
// Enlarge hash table, rebuild hash link
static void _rebuild_hash(struct bsp_hash_t *hash, size_t new_hash_size)
{
if (hash && new_hash_size)
{
if (new_hash_size == hash->hash_size)
{
return;
}
if (hash->hash_table)
{
bsp_free(hash->hash_table);
}
hash->hash_table = bsp_calloc(new_hash_size, sizeof(struct bsp_hash_item_t));
hash->hash_size = new_hash_size;
// Insert every item from link
struct bsp_hash_item_t *curr = hash->head;
struct bsp_hash_item_t *bucket;
uint32_t hash_key;
while (curr && curr->key)
{
hash_key = bsp_hash(STR_STR(curr->key), STR_LEN(curr->key));
bucket = &hash->hash_table[hash_key % hash->hash_size];
curr->next = bucket->next;
curr->prev = bucket;
bucket->next = curr;
curr = curr->lnext;
}
}
return;
}
// Evalute a single (Number / String / Boolean etc) to a object
void object_set_single(BSP_OBJECT *obj, BSP_VALUE *val)
{
if (obj && OBJECT_TYPE_SINGLE == obj->type)
{
bsp_spin_lock(&obj->lock);
if (obj->node)
{
BSP_VALUE *old = (BSP_VALUE *) obj->node;
del_value(old);
}
obj->node = (BSP_VALUE *) val;
bsp_spin_unlock(&obj->lock);
}
return;
}
// Add an item into array
void object_set_array(BSP_OBJECT *obj, ssize_t idx, BSP_VALUE *val)
{
if (obj && OBJECT_TYPE_ARRAY == obj->type)
{
bsp_spin_lock(&obj->lock);
struct bsp_array_t *array = (struct bsp_array_t *) obj->node;
if (!array)
{
// Make a new array
array = bsp_calloc(1, sizeof(struct bsp_array_t));
obj->node = (void *) array;
}
if (idx < 0)
{
idx = array->nitems;
}
size_t bucket = (idx / ARRAY_BUCKET_SIZE);
size_t seq = idx % ARRAY_BUCKET_SIZE;
size_t nbuckets = array->nbuckets;
if (bucket >= nbuckets)
{
// Enlarge buckets
nbuckets = 2 << (int) (log2(bucket + 1));
array->items = bsp_realloc(array->items, nbuckets * sizeof(struct BSP_VAL **));
size_t i;
for (i = array->nbuckets; i < nbuckets; i ++)
{
array->items[i] = NULL;
}
array->nbuckets = nbuckets;
}
if (!array->items[bucket])
{
// New bucket
array->items[bucket] = bsp_calloc(ARRAY_BUCKET_SIZE, sizeof(struct BSP_VAL *));
}
if (array->items[bucket][seq])
{
// Remove old value
del_value(array->items[bucket][seq]);
}
array->items[bucket][seq] = val;
if (idx >= array->nitems)
{
array->nitems = idx + 1;
}
bsp_spin_unlock(&obj->lock);
}
return;
}
// Insert / Remove an item into / from a hash
void object_set_hash(BSP_OBJECT *obj, BSP_STRING *key, BSP_VALUE *val)
{
if (obj && OBJECT_TYPE_HASH == obj->type && key)
{
bsp_spin_lock(&obj->lock);
struct bsp_hash_t *hash = (struct bsp_hash_t *) obj->node;
if (!hash)
{
// Make a new hash
hash = bsp_calloc(1, sizeof(struct bsp_hash_t));
hash->hash_size = HASH_SIZE_INITIAL;
hash->hash_table = bsp_calloc(HASH_SIZE_INITIAL, sizeof(struct bsp_hash_item_t));
obj->node = (void *) hash;
}
if (val)
{
// Insert
hash->nitems += _insert_hash(hash, key, val);
if (hash->nitems > 8 * hash->hash_size)
{
// Rehash
_rebuild_hash(hash, hash->hash_size * 8);
}
}
else
{
// Remove
hash->nitems -= _remove_hash(hash, key);
}
bsp_spin_unlock(&obj->lock);
}
return;
}
void object_set_hash_str(BSP_OBJECT *obj, const char *key, BSP_VALUE *val)
{
if (obj && OBJECT_TYPE_HASH == obj->type && key)
{
bsp_spin_lock(&obj->lock);
struct bsp_hash_t *hash = (struct bsp_hash_t *) obj->node;
if (!hash)
{
// Make a new hash
hash = bsp_calloc(1, sizeof(struct bsp_hash_t));
hash->hash_size = HASH_SIZE_INITIAL;
hash->hash_table = bsp_calloc(HASH_SIZE_INITIAL, sizeof(struct bsp_hash_item_t));
obj->node = (void *) hash;
}
if (val)
{
// Insert
hash->nitems += _insert_hash_str(hash, key, val);
if (hash->nitems > 8 * hash->hash_size)
{
// Rehash
_rebuild_hash(hash, hash->hash_size * 8);
}
}
else
{
// Remove
hash->nitems -= _remove_hash_str(hash, key);
}
bsp_spin_unlock(&obj->lock);
}
return;
}
// Get single value from object
BSP_VALUE * object_get_single(BSP_OBJECT *obj)
{
BSP_VALUE *ret = NULL;
if (obj && OBJECT_TYPE_SINGLE == obj->type)
{
bsp_spin_lock(&obj->lock);
ret = (BSP_VALUE *) obj->node;
bsp_spin_unlock(&obj->lock);
}
return ret;
}
// Get value from array by given index
BSP_VALUE * object_get_array(BSP_OBJECT *obj, size_t idx)
{
BSP_VALUE *ret = NULL;
if (obj && OBJECT_TYPE_ARRAY == obj->type)
{
bsp_spin_lock(&obj->lock);
struct bsp_array_t *array = (struct bsp_array_t *) obj->node;
size_t bucket = idx / ARRAY_BUCKET_SIZE;
size_t seq = idx % ARRAY_BUCKET_SIZE;
if (array && idx < array->nitems && bucket < array->nbuckets && array->items[bucket])
{
ret = array->items[bucket][seq];
}
bsp_spin_unlock(&obj->lock);
}
return ret;
}
// Get value from hash table
BSP_VALUE * object_get_hash(BSP_OBJECT *obj, BSP_STRING *key)
{
BSP_VALUE *ret = NULL;
if (obj && key && OBJECT_TYPE_HASH == obj->type)
{
bsp_spin_lock(&obj->lock);
struct bsp_hash_t *hash = (struct bsp_hash_t *) obj->node;
if (hash)
{
struct bsp_hash_item_t *item = _find_hash(hash, key);
if (item)
{
ret = item->value;
}
}
bsp_spin_unlock(&obj->lock);
}
return ret;
}
BSP_VALUE * object_get_hash_str(BSP_OBJECT *obj, const char *key)
{
BSP_VALUE *ret = NULL;
if (obj && key && OBJECT_TYPE_HASH == obj->type)
{
bsp_spin_lock(&obj->lock);
struct bsp_hash_t *hash = (struct bsp_hash_t *) obj->node;
if (hash)
{
struct bsp_hash_item_t *item = _find_hash_str(hash, key);
if (item)
{
ret = item->value;
}
}
bsp_spin_unlock(&obj->lock);
}
return ret;
}
/* Magic path */
BSP_VALUE * object_get_value(BSP_OBJECT *obj, const char *path)
{
if (!obj)
{
return NULL;
}
BSP_VALUE *ret = NULL;
BSP_VALUE *curr_val = NULL;
BSP_OBJECT *curr_obj = obj;
BSP_STRING *key = NULL;
size_t idx = 0;
size_t i;
ssize_t start = -1;
int invalid = 0;
unsigned char c;
char *endptr = NULL;
if (OBJECT_TYPE_SINGLE == obj->type)
{
// Return full
ret = object_get_single(obj);
}
else
{
if (!path || 0 == strlen(path))
{
// No path
}
else
{
// Parse path normally
for (i = 0; i <= strlen(path); i ++)
{
c = (unsigned char) path[i];
if ('.' == c || '\0' == c)
{
// Hash seg
if (start < i && start >= 0 && curr_obj)
{
if (OBJECT_TYPE_HASH == curr_obj->type)
{
key = new_string_const(path + start, (i - start));
curr_val = object_get_hash(curr_obj, key);
del_string(key);
if (!curr_val)
{
// False
invalid = 1;
break;
}
curr_obj = value_get_object(curr_val);
start = -1;
}
else if (OBJECT_TYPE_ARRAY == curr_obj->type)
{
idx = (size_t) strtoull(path + start, &endptr, 0);
if (!idx && (path + start) == endptr)
{
// No digital
invalid = 1;
break;
}
curr_val = object_get_array(curr_obj, idx);
if (!curr_val)
{
invalid = 1;
break;
}
curr_obj = value_get_object(curr_val);
start = -1;
}
else
{
// False
curr_val = object_get_single(curr_obj);
break;
}
}
else
{
invalid = 1;
break;
}
}
else
{
// Normal char
if (start < 0)
{
start = i;
}
}
}
if (!invalid)
{
ret = curr_val;
}
}
}
return ret;
}
/* Serializer & Unserializer */
static void _pack_key(BSP_STRING *str, BSP_STRING *key);
static void _pack_value(BSP_STRING *str, BSP_VALUE *val);
static void _pack_object(BSP_STRING *str, BSP_OBJECT *obj);
static void _pack_key(BSP_STRING *str, BSP_STRING *key)
{
if (str)
{
char buf[9];
if (key)
{
string_append(str, buf, set_vint(STR_LEN(key), buf));
string_append(str, STR_STR(key), STR_LEN(key));
}
else
{
string_append(str, buf, set_vint(strlen(NO_HASH_KEY), buf));
string_append(str, NO_HASH_KEY, -1);
}
}
return;
}
static void _pack_value(BSP_STRING *str, BSP_VALUE *val)
{
char tmp[9];
int tmp_len;
BSP_STRING *sub_str = NULL;
BSP_OBJECT *sub_obj = NULL;
if (val && str)
{
string_append(str, &val->type, 1);
switch (val->type)
{
case BSP_VAL_INT :
string_append(str, val->lval, vintlen(val->lval, -1));
break;
case BSP_VAL_FLOAT :
string_append(str, val->lval, sizeof(float));
break;
case BSP_VAL_DOUBLE :
string_append(str, val->lval, sizeof(float));
break;
case BSP_VAL_STRING :
sub_str = (BSP_STRING *) val->rval;
if (sub_str)
{
tmp_len = set_vint(STR_LEN(sub_str), tmp);
string_append(str, tmp, tmp_len);
string_append(str, STR_STR(sub_str), STR_LEN(sub_str));
}
else
{
tmp[0] = 0;
string_append(str, tmp, 1);
}
break;
case BSP_VAL_POINTER :
set_pointer(val->rval, tmp);
string_append(str, tmp, sizeof(void *));
break;
case BSP_VAL_OBJECT :
sub_obj = (BSP_OBJECT *) val->rval;
if (sub_obj)
{
_pack_object(str, sub_obj);
}
break;
case BSP_VAL_BOOLEAN_TRUE :
case BSP_VAL_BOOLEAN_FALSE :
case BSP_VAL_NULL :
case BSP_VAL_UNKNOWN :
default :
// No value
break;
}
}
return;
}
static void _pack_object(BSP_STRING *str, BSP_OBJECT *obj)
{
char value_type[1];
BSP_VALUE *val = NULL;
if (obj && str)
{
bsp_spin_lock(&obj->lock);
switch (obj->type)
{
case OBJECT_TYPE_SINGLE :
// A single value
value_type[0] = BSP_VAL_OBJECT_SINGLE;
string_append(str, value_type, 1);
// Push value
val = (BSP_VALUE *) obj->node;
_pack_value(str, val);
value_type[0] = BSP_VAL_OBJECT_SINGLE_END;
string_append(str, value_type, 1);
break;
case OBJECT_TYPE_ARRAY :
// Array
value_type[0] = BSP_VAL_OBJECT_ARRAY;
string_append(str, value_type, 1);
// Every item
struct bsp_array_t *array = (struct bsp_array_t *) obj->node;
size_t idx, bucket, seq;
if (array)
{
for (idx = 9; idx < array->nitems; idx ++)
{
bucket = idx / ARRAY_BUCKET_SIZE;
seq = idx % ARRAY_BUCKET_SIZE;
val = NULL;
if (bucket < array->nbuckets && array->items[bucket])
{
val = array->items[bucket][seq];
_pack_value(str, val);
}
else
{
// Empty
value_type[0] = BSP_VAL_NULL;
string_append(str, value_type, 1);
}
}
}
value_type[0] = BSP_VAL_OBJECT_ARRAY_END;
string_append(str, value_type, 1);
break;
case OBJECT_TYPE_HASH :
// Dict
value_type[0] = BSP_VAL_OBJECT_HASH;
string_append(str, value_type, 1);
// Traverse items
BSP_STRING *key;
reset_object(obj);
val = curr_item(obj);
while (val)
{
key = curr_hash_key(obj);
// Set key and value
_pack_key(str, key);
_pack_value(str, val);
next_item(obj);
val = curr_item(obj);
}
value_type[0] = BSP_VAL_OBJECT_HASH_END;
string_append(str, value_type, 1);
break;
case OBJECT_TYPE_UNDETERMINED :
default :
// Yaaaahhh~~~?
break;
}
bsp_spin_unlock(&obj->lock);
}
return;
}
BSP_STRING * object_serialize(BSP_OBJECT *obj)
{
BSP_STRING * ret = new_string(NULL, 0);
if (obj && ret)
{
_pack_object(ret, obj);
}
return ret;
}
static BSP_STRING * _unpack_key(BSP_STRING *str);
static BSP_VALUE * _unpack_value(BSP_STRING *str);
static BSP_OBJECT * _unpack_object(BSP_STRING *str);
static BSP_STRING * _unpack_key(BSP_STRING *str)
{
BSP_STRING *ret = NULL;
char *data;
if (str)
{
size_t left = STR_LEN(str) - str->cursor;
size_t vlen = 0;
if (left > 0)
{
data = STR_STR(str);
vlen = vintlen(data, left);
if (left >= vlen)
{
int nouse = 0;
int64_t str_len = get_vint(data, &nouse);
if (left >= vlen + str_len)
{
ret = new_string(data + vlen, str_len);
vlen += str_len;
}
}
}
str->cursor += vlen;
}
return ret;
}
static BSP_VALUE * _unpack_value(BSP_STRING *str)
{
BSP_VALUE *ret = NULL;
char *data;
char type;
if (str)
{
size_t left = STR_LEN(str) - str->cursor;
size_t vlen = 0;
BSP_OBJECT *obj = NULL;
if (left > 0)
{
// 1st byte : Type
type = STR_STR(str)[str->cursor];
data = STR_STR(str) + 1;
ret = new_value();
ret->type = type;
switch (type)
{
case BSP_VAL_INT :
vlen = vintlen(data, left - 1);
memcpy(ret->lval, data, vlen);
break;
case BSP_VAL_FLOAT :
vlen = (left > sizeof(float)) ? sizeof(float) : (left - 1);
memcpy(ret->lval, data, vlen);
break;
case BSP_VAL_DOUBLE :
vlen = (left > sizeof(double)) ? sizeof(double) : (left - 1);
memcpy(ret->lval, data, vlen);
break;
case BSP_VAL_STRING :
vlen = vintlen(data, left - 1);
if (left >= vlen)
{
int nouse = 0;
int64_t str_len = get_vint(data, &nouse);
if (left >= vlen + str_len)
{
ret->rval = (void *) new_string(data + vlen, str_len);
vlen += str_len;
}
}
break;
case BSP_VAL_POINTER :
vlen = (left > sizeof(void *)) ? sizeof(void *) : (left - 1);
memcpy(&ret->rval, data, vlen);
break;
case BSP_VAL_OBJECT :
obj = _unpack_object(str);
ret->rval = (void *) obj;
break;
case BSP_VAL_BOOLEAN_TRUE :
case BSP_VAL_BOOLEAN_FALSE :
case BSP_VAL_NULL :
case BSP_VAL_UNKNOWN :
default :
// Single values
break;
}
str->cursor += vlen + 1;
}
}
return ret;
}
static BSP_OBJECT * _unpack_object(BSP_STRING *str)
{
BSP_OBJECT *obj = NULL;
if (str)
{
bsp_spin_lock(&str->lock);
if (str->cursor < STR_LEN(str))
{
// Read first
BSP_VALUE *val = NULL;
BSP_STRING *key = NULL;
char type = STR_STR(str)[str->cursor];
obj = new_object(type);
str->cursor ++;
switch (type)
{
case BSP_VAL_OBJECT_SINGLE :
val = _unpack_value(str);
object_set_single(obj, val);
// Pass endding
str->cursor ++;
break;
case BSP_VAL_OBJECT_ARRAY :
while (1)
{
val = _unpack_value(str);
if (!val)
{
break;
}
if (str->cursor < STR_LEN(str) && BSP_VAL_OBJECT_ARRAY_END == STR_STR(str)[str->cursor])
{
// Endding
str->cursor ++;
break;
}
object_set_array(obj, -1, val);
}
break;
case BSP_VAL_OBJECT_HASH :
while (1)
{
// Read key first
key = _unpack_key(str);
if (!key)
{
break;
}
val = _unpack_value(str);
if (!val)
{
break;
}
if (str->cursor < STR_LEN(str) && BSP_VAL_OBJECT_HASH_END == STR_STR(str)[str->cursor])
{
// Endding
str->cursor ++;
break;
}
object_set_hash(obj, key, val);
}
break;
default :
break;
}
}
bsp_spin_unlock(&str->lock);
}
return obj;
}
BSP_OBJECT * object_unserialize(BSP_STRING *str)
{
BSP_OBJECT * ret = NULL;
if (str)
{
str->cursor = 0;
ret = _unpack_object(str);
}
return ret;
}
/* Object <-> LUA stack */
static void _push_value_to_lua(lua_State *s, BSP_VALUE *val);
static void _push_object_to_lua(lua_State *s, BSP_OBJECT *obj);
static void _push_value_to_lua(lua_State *s, BSP_VALUE *val)
{
if (!s)
{
return;
}
if (!val)
{
lua_pushnil(s);
return;
}
int v_intlen = 0;
uint64_t v_int = 0;
float v_float = 0.0;
double v_double = 0.0;
BSP_STRING *v_str = NULL;
void *v_ptr = NULL;
BSP_OBJECT *v_obj = NULL;
switch (val->type)
{
case BSP_VAL_INT :
v_int = get_vint(val->lval, &v_intlen);
lua_pushinteger(s, (lua_Integer) v_int);
break;
case BSP_VAL_FLOAT :
v_float = get_float(val->lval);
lua_pushnumber(s, (lua_Number) v_float);
break;
case BSP_VAL_DOUBLE :
v_double = get_double(val->lval);
lua_pushnumber(s, (lua_Number) v_double);
break;
case BSP_VAL_BOOLEAN_TRUE :
lua_pushboolean(s, BSP_BOOLEAN_TRUE);
break;
case BSP_VAL_BOOLEAN_FALSE :
lua_pushboolean(s, BSP_BOOLEAN_FALSE);
break;
case BSP_VAL_STRING :
v_str = (BSP_STRING *) val->rval;
lua_pushlstring(s, STR_STR(v_str), STR_LEN(v_str));
break;
case BSP_VAL_POINTER :
v_ptr = val->rval;
lua_pushlightuserdata(s, v_ptr);
break;
case BSP_VAL_OBJECT :
v_obj = (BSP_OBJECT *) val->rval;
_push_object_to_lua(s, v_obj);
break;
case BSP_VAL_NULL :
case BSP_VAL_UNKNOWN :
default :
lua_pushnil(s);
break;
}
return;
}
static void _push_object_to_lua(lua_State *s, BSP_OBJECT *obj)
{
if (!s)
{
return;
}
if (!obj)
{
lua_pushnil(s);
return;
}
BSP_VALUE *val = NULL;
BSP_STRING *key = NULL;
bsp_spin_lock(&obj->lock);
lua_checkstack(s, 1);
switch (obj->type)
{
case OBJECT_TYPE_SINGLE :
// Single value
val = (BSP_VALUE *) obj->node;
_push_value_to_lua(s, val);
break;
case OBJECT_TYPE_ARRAY :
// Array
lua_newtable(s);
struct bsp_array_t *array = (struct bsp_array_t *) obj->node;
size_t idx;
if (array)
{
for (idx = 0; idx < array->nitems; idx ++)
{
size_t bucket = idx / ARRAY_BUCKET_SIZE;
size_t seq = idx % ARRAY_BUCKET_SIZE;
if (bucket < array->nbuckets && array->items[bucket])
{
val = array->items[bucket][seq];
if (val)
{
lua_checkstack(s, 2);
lua_pushinteger(s, (lua_Integer) idx + 1);
_push_value_to_lua(s, val);
lua_settable(s, -3);
}
}
}
}
break;
case OBJECT_TYPE_HASH :
// Hash
lua_newtable(s);
reset_object(obj);
val = curr_item(obj);
while (val)
{
key = curr_hash_key(obj);
if (key)
{
lua_checkstack(s, 2);
lua_pushlstring(s, STR_STR(key), STR_LEN(key));
_push_value_to_lua(s, val);
if (lua_istable(s, -3))
{
lua_settable(s, -3);
}
}
next_item(obj);
val = curr_item(obj);
}
break;
case OBJECT_TYPE_UNDETERMINED :
default :
lua_pushnil(s);
break;
}
bsp_spin_unlock(&obj->lock);
return;
}
void object_to_lua_stack(lua_State *s, BSP_OBJECT *obj)
{
if (!obj || !s)
{
return;
}
_push_object_to_lua(s, obj);
return;
}
static BSP_VALUE * _lua_value_to_value(lua_State *s);
static BSP_OBJECT * _lua_table_to_object(lua_State *s);
static BSP_VALUE * _lua_value_to_value(lua_State *s)
{
if (!s)
{
return NULL;
}
BSP_VALUE *ret = new_value();
if (ret)
{
lua_Number v_number = 0;
int v_boolean = 0;
size_t str_len = 0;
const char *v_str = NULL;
void *v_ptr = NULL;
BSP_OBJECT *v_obj = NULL;
switch (lua_type(s, -1))
{
case LUA_TNIL :
value_set_null(ret);
break;
case LUA_TNUMBER :
v_number = lua_tonumber(s, -1);
if (v_number == (lua_Number)(int64_t) v_number)
{
// Integer
value_set_int(ret, (const int64_t) v_number);
}
else
{
// Double / Float
value_set_double(ret, (const double) v_number);
}
break;
case LUA_TBOOLEAN :
v_boolean = lua_toboolean(s, -1);
if (BSP_BOOLEAN_FALSE == v_boolean)
{
value_set_boolean_false(ret);
}
else
{
value_set_boolean_true(ret);
}
break;
case LUA_TSTRING :
v_str = lua_tolstring(s, -1, &str_len);
value_set_string(ret, new_string(v_str, str_len));
break;
case LUA_TUSERDATA :
v_ptr = lua_touserdata(s, -1);
value_set_pointer(ret, (const void *) v_ptr);
break;
case LUA_TTABLE :
v_obj = _lua_table_to_object(s);
value_set_object(ret, v_obj);
break;
default :
value_set_null(ret);
break;
}
}
return ret;
}
static BSP_OBJECT * _lua_table_to_object(lua_State *s)
{
if (!s || !lua_istable(s, -1))
{
return NULL;
}
BSP_OBJECT *ret = NULL;
BSP_VALUE *val = NULL;
// Is array or hash?
if (luaL_len(s, -1) == lua_table_size(s, -1))
{
// Array
ret = new_object(OBJECT_TYPE_ARRAY);
size_t idx;
for (idx = 1; idx <= luaL_len(s, -1); idx ++)
{
lua_rawgeti(s, -1, idx);
val = _lua_value_to_value(s);
object_set_array(ret, idx - 1, val);
}
}
else
{
// Hash
ret = new_object(OBJECT_TYPE_HASH);
const char *key_str = NULL;
size_t key_len = 0;
BSP_STRING *key = NULL;
lua_checkstack(s, 2);
lua_pushnil(s);
while (0 != lua_next(s, -2))
{
// Key
key_str = lua_tolstring(s, -2, &key_len);
key = new_string(key_str, key_len);
// Value
val = _lua_value_to_value(s);
object_set_hash(ret, key, val);
lua_pop(s, 1);
}
}
return ret;
}
BSP_OBJECT * lua_stack_to_object(lua_State *s)
{
if (!s)
{
return NULL;
}
BSP_OBJECT *ret = NULL;
if (lua_istable(s, -1))
{
// Array or hash
ret = _lua_table_to_object(s);
}
else
{
// Single
ret = new_object(OBJECT_TYPE_SINGLE);
object_set_single(ret, _lua_value_to_value(s));
}
return ret;
}
|
drnp/bsp
|
src/lib/bsp-core/object.c
|
C
|
gpl-3.0
| 53,620
|
/*
Copyright (C) 2016 Sergo Pasoevi.
This pragram is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Written by Sergo Pasoevi <spasoevi@gmail.com>
*/
#include "util.h"
#include <math.h>
/* Geometry helper functions */
double distance(int x1, int y1, int x2, int y2)
{
int dx = x1 - x2;
int dy = y1 - y2;
return sqrt(dx * dx + dy * dy);
}
void each_actor(struct engine *engine, TCOD_list_t lst,
void (*action)(struct engine *engine,
struct actor *actor))
{
struct actor **iterator;
for (iterator = (struct actor **) TCOD_list_begin(engine->actors);
iterator != (struct actor **) TCOD_list_end(engine->actors);
iterator++)
action(engine, *iterator);
}
const char *generate_name(const char *filename)
{
TCOD_namegen_parse(filename, TCOD_random_get_instance());
return TCOD_namegen_generate("Celtic male", false);
}
void free_name_generator(void)
{
TCOD_namegen_destroy();
}
|
pasoev/dungeons
|
src/util.c
|
C
|
gpl-3.0
| 1,578
|
/*!
* \file db_mysql_list_entities_report_sql.c
* \brief Returns MYSQL SQL query to create list entities report.
* \author Paul Griffiths
* \copyright Copyright 2014 Paul Griffiths. Distributed under the terms
* of the GNU General Public License. <http://www.gnu.org/licenses/>
*/
const char * db_list_entities_report_sql(void) {
static const char * query =
"SELECT"
" id AS 'ID',"
" shortname AS 'Short',"
" name AS 'Entity Name',"
" currency AS 'Curr.',"
" parent AS 'Parent'"
" FROM entities"
" ORDER BY id";
return query;
}
|
paulgriffiths/general_ledger
|
lib/database/mysql/db_mysql_list_entities_report_sql.c
|
C
|
gpl-3.0
| 652
|
/*
This project is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Deviation is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Deviation. If not, see <http://www.gnu.org/licenses/>.
*/
#define OVERRIDE_PLACEMENT
#include "common.h"
#include "pages.h"
#include "gui/gui.h"
#include "config/model.h"
#include "config/ini.h"
#include <stdlib.h>
enum {
LABELNUM_X = 0,
LABELNUM_WIDTH = 16,
LABEL_X = 17,
LABEL_WIDTH = 0,
};
#include "../128x64x1/model_loadsave.c"
|
Chen-Leon/DeviationX
|
src/pages/text/model_loadsave.c
|
C
|
gpl-3.0
| 943
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "p12plcy.h"
#include "secoid.h"
#include "secport.h"
#include "secpkcs5.h"
#define PKCS12_NULL 0x0000
typedef struct pkcs12SuiteMapStr {
SECOidTag algTag;
unsigned int keyLengthBits; /* in bits */
unsigned long suite;
PRBool allowed;
PRBool preferred;
} pkcs12SuiteMap;
static pkcs12SuiteMap pkcs12SuiteMaps[] = {
{ SEC_OID_RC4, 40, PKCS12_RC4_40, PR_FALSE, PR_FALSE },
{ SEC_OID_RC4, 128, PKCS12_RC4_128, PR_FALSE, PR_FALSE },
{ SEC_OID_RC2_CBC, 40, PKCS12_RC2_CBC_40, PR_FALSE, PR_TRUE },
{ SEC_OID_RC2_CBC, 128, PKCS12_RC2_CBC_128, PR_FALSE, PR_FALSE },
{ SEC_OID_DES_CBC, 64, PKCS12_DES_56, PR_FALSE, PR_FALSE },
{ SEC_OID_DES_EDE3_CBC, 192, PKCS12_DES_EDE3_168, PR_FALSE, PR_FALSE },
{ SEC_OID_UNKNOWN, 0, PKCS12_NULL, PR_FALSE, PR_FALSE },
{ SEC_OID_UNKNOWN, 0, 0L, PR_FALSE, PR_FALSE }
};
/* determine if algid is an algorithm which is allowed */
PRBool
SEC_PKCS12DecryptionAllowed(SECAlgorithmID *algid)
{
unsigned int keyLengthBits;
SECOidTag algId;
int i;
algId = SEC_PKCS5GetCryptoAlgorithm(algid);
if (algId == SEC_OID_UNKNOWN) {
return PR_FALSE;
}
keyLengthBits = (unsigned int)(SEC_PKCS5GetKeyLength(algid) * 8);
i = 0;
while (pkcs12SuiteMaps[i].algTag != SEC_OID_UNKNOWN) {
if ((pkcs12SuiteMaps[i].algTag == algId) &&
(pkcs12SuiteMaps[i].keyLengthBits == keyLengthBits)) {
return pkcs12SuiteMaps[i].allowed;
}
i++;
}
return PR_FALSE;
}
/* is any encryption allowed? */
PRBool
SEC_PKCS12IsEncryptionAllowed(void)
{
int i;
i = 0;
while (pkcs12SuiteMaps[i].algTag != SEC_OID_UNKNOWN) {
if (pkcs12SuiteMaps[i].allowed == PR_TRUE) {
return PR_TRUE;
}
i++;
}
return PR_FALSE;
}
SECStatus
SEC_PKCS12EnableCipher(long which, int on)
{
int i;
i = 0;
while (pkcs12SuiteMaps[i].suite != 0L) {
if (pkcs12SuiteMaps[i].suite == (unsigned long)which) {
if (on) {
pkcs12SuiteMaps[i].allowed = PR_TRUE;
} else {
pkcs12SuiteMaps[i].allowed = PR_FALSE;
}
return SECSuccess;
}
i++;
}
return SECFailure;
}
SECStatus
SEC_PKCS12SetPreferredCipher(long which, int on)
{
int i;
PRBool turnedOff = PR_FALSE;
PRBool turnedOn = PR_FALSE;
i = 0;
while (pkcs12SuiteMaps[i].suite != 0L) {
if (pkcs12SuiteMaps[i].preferred == PR_TRUE) {
pkcs12SuiteMaps[i].preferred = PR_FALSE;
turnedOff = PR_TRUE;
}
if (pkcs12SuiteMaps[i].suite == (unsigned long)which) {
pkcs12SuiteMaps[i].preferred = PR_TRUE;
turnedOn = PR_TRUE;
}
i++;
}
if ((turnedOn) && (turnedOff)) {
return SECSuccess;
}
return SECFailure;
}
|
Yukarumya/Yukarum-Redfoxes
|
security/nss/lib/pkcs12/p12plcy.c
|
C
|
mpl-2.0
| 3,082
|
//*****************************************************************************
//
// startup_gcc.c - Startup code for use with GNU tools.
//
// Copyright (c) 2012-2013 Texas Instruments Incorporated. All rights reserved.
// Software License Agreement
//
// Texas Instruments (TI) is supplying this software for use solely and
// exclusively on TI's microcontroller products. The software is owned by
// TI and/or its suppliers, and is protected under applicable copyright
// laws. You may not combine this software with "viral" open-source
// software in order to form a larger program.
//
// THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS.
// NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT
// NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY
// CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
// DAMAGES, FOR ANY REASON WHATSOEVER.
//
// This is part of revision 2.0.1.11577 of the EK-TM4C123GXL Firmware Package.
//
//*****************************************************************************
#include <stdint.h>
#include "inc/hw_nvic.h"
#include "inc/hw_types.h"
//*****************************************************************************
//
// Forward declaration of the default fault handlers.
//
//*****************************************************************************
void ResetISR(void);
static void NmiSR(void);
static void FaultISR(void);
static void IntDefaultHandler(void);
//*****************************************************************************
//
// External declarations for the interrupt handlers used by the application.
//
//*****************************************************************************
extern void SysTickIntHandler(void);
extern void USBUARTIntHandler(void);
extern void USB0DeviceIntHandler(void);
//*****************************************************************************
//
// The entry point for the application.
//
//*****************************************************************************
extern int main(void);
//*****************************************************************************
//
// Reserve space for the system stack.
//
//*****************************************************************************
static uint32_t pui32Stack[256];
//*****************************************************************************
//
// The vector table. Note that the proper constructs must be placed on this to
// ensure that it ends up at physical address 0x0000.0000.
//
//*****************************************************************************
__attribute__ ((section(".isr_vector")))
void (* const g_pfnVectors[])(void) =
{
(void (*)(void))((uint32_t)pui32Stack + sizeof(pui32Stack)),
// The initial stack pointer
ResetISR, // The reset handler
NmiSR, // The NMI handler
FaultISR, // The hard fault handler
IntDefaultHandler, // The MPU fault handler
IntDefaultHandler, // The bus fault handler
IntDefaultHandler, // The usage fault handler
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
IntDefaultHandler, // SVCall handler
IntDefaultHandler, // Debug monitor handler
0, // Reserved
IntDefaultHandler, // The PendSV handler
SysTickIntHandler, // The SysTick handler
IntDefaultHandler, // GPIO Port A
IntDefaultHandler, // GPIO Port B
IntDefaultHandler, // GPIO Port C
IntDefaultHandler, // GPIO Port D
IntDefaultHandler, // GPIO Port E
USBUARTIntHandler, // UART0 Rx and Tx
IntDefaultHandler, // UART1 Rx and Tx
IntDefaultHandler, // SSI0 Rx and Tx
IntDefaultHandler, // I2C0 Master and Slave
IntDefaultHandler, // PWM Fault
IntDefaultHandler, // PWM Generator 0
IntDefaultHandler, // PWM Generator 1
IntDefaultHandler, // PWM Generator 2
IntDefaultHandler, // Quadrature Encoder 0
IntDefaultHandler, // ADC Sequence 0
IntDefaultHandler, // ADC Sequence 1
IntDefaultHandler, // ADC Sequence 2
IntDefaultHandler, // ADC Sequence 3
IntDefaultHandler, // Watchdog timer
IntDefaultHandler, // Timer 0 subtimer A
IntDefaultHandler, // Timer 0 subtimer B
IntDefaultHandler, // Timer 1 subtimer A
IntDefaultHandler, // Timer 1 subtimer B
IntDefaultHandler, // Timer 2 subtimer A
IntDefaultHandler, // Timer 2 subtimer B
IntDefaultHandler, // Analog Comparator 0
IntDefaultHandler, // Analog Comparator 1
IntDefaultHandler, // Analog Comparator 2
IntDefaultHandler, // System Control (PLL, OSC, BO)
IntDefaultHandler, // FLASH Control
IntDefaultHandler, // GPIO Port F
IntDefaultHandler, // GPIO Port G
IntDefaultHandler, // GPIO Port H
IntDefaultHandler, // UART2 Rx and Tx
IntDefaultHandler, // SSI1 Rx and Tx
IntDefaultHandler, // Timer 3 subtimer A
IntDefaultHandler, // Timer 3 subtimer B
IntDefaultHandler, // I2C1 Master and Slave
IntDefaultHandler, // Quadrature Encoder 1
IntDefaultHandler, // CAN0
IntDefaultHandler, // CAN1
IntDefaultHandler, // CAN2
0, // Reserved
IntDefaultHandler, // Hibernate
USB0DeviceIntHandler, // USB0
IntDefaultHandler, // PWM Generator 3
IntDefaultHandler, // uDMA Software Transfer
IntDefaultHandler, // uDMA Error
IntDefaultHandler, // ADC1 Sequence 0
IntDefaultHandler, // ADC1 Sequence 1
IntDefaultHandler, // ADC1 Sequence 2
IntDefaultHandler, // ADC1 Sequence 3
0, // Reserved
0, // Reserved
IntDefaultHandler, // GPIO Port J
IntDefaultHandler, // GPIO Port K
IntDefaultHandler, // GPIO Port L
IntDefaultHandler, // SSI2 Rx and Tx
IntDefaultHandler, // SSI3 Rx and Tx
IntDefaultHandler, // UART3 Rx and Tx
IntDefaultHandler, // UART4 Rx and Tx
IntDefaultHandler, // UART5 Rx and Tx
IntDefaultHandler, // UART6 Rx and Tx
IntDefaultHandler, // UART7 Rx and Tx
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
IntDefaultHandler, // I2C2 Master and Slave
IntDefaultHandler, // I2C3 Master and Slave
IntDefaultHandler, // Timer 4 subtimer A
IntDefaultHandler, // Timer 4 subtimer B
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
IntDefaultHandler, // Timer 5 subtimer A
IntDefaultHandler, // Timer 5 subtimer B
IntDefaultHandler, // Wide Timer 0 subtimer A
IntDefaultHandler, // Wide Timer 0 subtimer B
IntDefaultHandler, // Wide Timer 1 subtimer A
IntDefaultHandler, // Wide Timer 1 subtimer B
IntDefaultHandler, // Wide Timer 2 subtimer A
IntDefaultHandler, // Wide Timer 2 subtimer B
IntDefaultHandler, // Wide Timer 3 subtimer A
IntDefaultHandler, // Wide Timer 3 subtimer B
IntDefaultHandler, // Wide Timer 4 subtimer A
IntDefaultHandler, // Wide Timer 4 subtimer B
IntDefaultHandler, // Wide Timer 5 subtimer A
IntDefaultHandler, // Wide Timer 5 subtimer B
IntDefaultHandler, // FPU
0, // Reserved
0, // Reserved
IntDefaultHandler, // I2C4 Master and Slave
IntDefaultHandler, // I2C5 Master and Slave
IntDefaultHandler, // GPIO Port M
IntDefaultHandler, // GPIO Port N
IntDefaultHandler, // Quadrature Encoder 2
0, // Reserved
0, // Reserved
IntDefaultHandler, // GPIO Port P (Summary or P0)
IntDefaultHandler, // GPIO Port P1
IntDefaultHandler, // GPIO Port P2
IntDefaultHandler, // GPIO Port P3
IntDefaultHandler, // GPIO Port P4
IntDefaultHandler, // GPIO Port P5
IntDefaultHandler, // GPIO Port P6
IntDefaultHandler, // GPIO Port P7
IntDefaultHandler, // GPIO Port Q (Summary or Q0)
IntDefaultHandler, // GPIO Port Q1
IntDefaultHandler, // GPIO Port Q2
IntDefaultHandler, // GPIO Port Q3
IntDefaultHandler, // GPIO Port Q4
IntDefaultHandler, // GPIO Port Q5
IntDefaultHandler, // GPIO Port Q6
IntDefaultHandler, // GPIO Port Q7
IntDefaultHandler, // GPIO Port R
IntDefaultHandler, // GPIO Port S
IntDefaultHandler, // PWM 1 Generator 0
IntDefaultHandler, // PWM 1 Generator 1
IntDefaultHandler, // PWM 1 Generator 2
IntDefaultHandler, // PWM 1 Generator 3
IntDefaultHandler // PWM 1 Fault
};
//*****************************************************************************
//
// The following are constructs created by the linker, indicating where the
// the "data" and "bss" segments reside in memory. The initializers for the
// for the "data" segment resides immediately following the "text" segment.
//
//*****************************************************************************
extern uint32_t _etext;
extern uint32_t _data;
extern uint32_t _edata;
extern uint32_t _bss;
extern uint32_t _ebss;
//*****************************************************************************
//
// This is the code that gets called when the processor first starts execution
// following a reset event. Only the absolutely necessary set is performed,
// after which the application supplied entry() routine is called. Any fancy
// actions (such as making decisions based on the reset cause register, and
// resetting the bits in that register) are left solely in the hands of the
// application.
//
//*****************************************************************************
void
ResetISR(void)
{
uint32_t *pui32Src, *pui32Dest;
//
// Copy the data segment initializers from flash to SRAM.
//
pui32Src = &_etext;
for(pui32Dest = &_data; pui32Dest < &_edata; )
{
*pui32Dest++ = *pui32Src++;
}
//
// Zero fill the bss segment.
//
__asm(" ldr r0, =_bss\n"
" ldr r1, =_ebss\n"
" mov r2, #0\n"
" .thumb_func\n"
"zero_loop:\n"
" cmp r0, r1\n"
" it lt\n"
" strlt r2, [r0], #4\n"
" blt zero_loop");
//
// Enable the floating-point unit. This must be done here to handle the
// case where main() uses floating-point and the function prologue saves
// floating-point registers (which will fault if floating-point is not
// enabled). Any configuration of the floating-point unit using DriverLib
// APIs must be done here prior to the floating-point unit being enabled.
//
// Note that this does not use DriverLib since it might not be included in
// this project.
//
HWREG(NVIC_CPAC) = ((HWREG(NVIC_CPAC) &
~(NVIC_CPAC_CP10_M | NVIC_CPAC_CP11_M)) |
NVIC_CPAC_CP10_FULL | NVIC_CPAC_CP11_FULL);
//
// Call the application's entry point.
//
main();
}
//*****************************************************************************
//
// This is the code that gets called when the processor receives a NMI. This
// simply enters an infinite loop, preserving the system state for examination
// by a debugger.
//
//*****************************************************************************
static void
NmiSR(void)
{
//
// Enter an infinite loop.
//
while(1)
{
}
}
//*****************************************************************************
//
// This is the code that gets called when the processor receives a fault
// interrupt. This simply enters an infinite loop, preserving the system state
// for examination by a debugger.
//
//*****************************************************************************
static void
FaultISR(void)
{
//
// Enter an infinite loop.
//
while(1)
{
}
}
//*****************************************************************************
//
// This is the code that gets called when the processor receives an unexpected
// interrupt. This simply enters an infinite loop, preserving the system state
// for examination by a debugger.
//
//*****************************************************************************
static void
IntDefaultHandler(void)
{
//
// Go into an infinite loop.
//
while(1)
{
}
}
|
trfiladelfo/unesp_mdt
|
boards/SW-TM4C-2.0.1.11577/examples/boards/ek-tm4c123gxl/usb_dev_serial/startup_gcc.c
|
C
|
mpl-2.0
| 16,631
|
//*****************************************************************************
//
// pushbutton.c - Various types of push buttons.
//
// Copyright (c) 2008-2013 Texas Instruments Incorporated. All rights reserved.
// Software License Agreement
//
// Texas Instruments (TI) is supplying this software for use solely and
// exclusively on TI's microcontroller products. The software is owned by
// TI and/or its suppliers, and is protected under applicable copyright
// laws. You may not combine this software with "viral" open-source
// software in order to form a larger program.
//
// THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS.
// NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT
// NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY
// CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
// DAMAGES, FOR ANY REASON WHATSOEVER.
//
// This is part of revision 2.0.1.11577 of the Tiva Graphics Library.
//
//*****************************************************************************
#include <stdint.h>
#include <stdbool.h>
#include "driverlib/debug.h"
#include "grlib/grlib.h"
#include "grlib/widget.h"
#include "grlib/pushbutton.h"
//*****************************************************************************
//
//! \addtogroup pushbutton_api
//! @{
//
//*****************************************************************************
//*****************************************************************************
//
//! Draws a rectangular push button.
//!
//! \param psWidget is a pointer to the push button widget to be drawn.
//!
//! This function draws a rectangular push button on the display. This is
//! called in response to a \b #WIDGET_MSG_PAINT message.
//!
//! \return None.
//
//*****************************************************************************
static void
RectangularButtonPaint(tWidget *psWidget)
{
const uint8_t *pui8Image;
tPushButtonWidget *pPush;
tContext sCtx;
int32_t i32X, i32Y;
//
// Check the arguments.
//
ASSERT(psWidget);
//
// Convert the generic widget pointer into a push button widget pointer.
//
pPush = (tPushButtonWidget *)psWidget;
//
// Initialize a drawing context.
//
GrContextInit(&sCtx, psWidget->psDisplay);
//
// Initialize the clipping region based on the extents of this rectangular
// push button.
//
GrContextClipRegionSet(&sCtx, &(psWidget->sPosition));
//
// See if the push button fill style is selected.
//
if(pPush->ui32Style & PB_STYLE_FILL)
{
//
// Fill the push button with the fill color.
//
GrContextForegroundSet(&sCtx, ((pPush->ui32Style & PB_STYLE_PRESSED) ?
pPush->ui32PressFillColor :
pPush->ui32FillColor));
GrRectFill(&sCtx, &(psWidget->sPosition));
}
//
// See if the push button outline style is selected.
//
if(pPush->ui32Style & PB_STYLE_OUTLINE)
{
//
// Outline the push button with the outline color.
//
GrContextForegroundSet(&sCtx, pPush->ui32OutlineColor);
GrRectDraw(&sCtx, &(psWidget->sPosition));
}
//
// See if the push button text or image style is selected.
//
if(pPush->ui32Style & (PB_STYLE_TEXT | PB_STYLE_IMG))
{
//
// Compute the center of the push button.
//
i32X = (psWidget->sPosition.i16XMin +
((psWidget->sPosition.i16XMax -
psWidget->sPosition.i16XMin + 1) / 2));
i32Y = (psWidget->sPosition.i16YMin +
((psWidget->sPosition.i16YMax -
psWidget->sPosition.i16YMin + 1) / 2));
//
// If the push button outline style is selected then shrink the
// clipping region by one pixel on each side so that the outline is not
// overwritten by the text or image.
//
if(pPush->ui32Style & PB_STYLE_OUTLINE)
{
sCtx.sClipRegion.i16XMin++;
sCtx.sClipRegion.i16YMin++;
sCtx.sClipRegion.i16XMax--;
sCtx.sClipRegion.i16YMax--;
}
//
// See if the push button image style is selected.
//
if(pPush->ui32Style & PB_STYLE_IMG)
{
//
// Set the foreground and background colors to use for 1 BPP
// images.
//
GrContextForegroundSet(&sCtx, pPush->ui32TextColor);
GrContextBackgroundSet(&sCtx,
((pPush->ui32Style & PB_STYLE_PRESSED) ?
pPush->ui32PressFillColor :
pPush->ui32FillColor));
//
// Get the image to be drawn.
//
pui8Image = (((pPush->ui32Style & PB_STYLE_PRESSED) &&
pPush->pui8PressImage) ?
pPush->pui8PressImage : pPush->pui8Image);
//
// Draw the image centered in the push button.
//
GrImageDraw(&sCtx, pui8Image,
i32X - (GrImageWidthGet(pui8Image) / 2),
i32Y - (GrImageHeightGet(pui8Image) / 2));
}
//
// See if the push button text style is selected.
//
if(pPush->ui32Style & PB_STYLE_TEXT)
{
//
// Draw the text centered in the middle of the push button.
//
GrContextFontSet(&sCtx, pPush->psFont);
GrContextForegroundSet(&sCtx, pPush->ui32TextColor);
GrContextBackgroundSet(&sCtx,
((pPush->ui32Style & PB_STYLE_PRESSED) ?
pPush->ui32PressFillColor :
pPush->ui32FillColor));
GrStringDrawCentered(&sCtx, pPush->pcText, -1, i32X, i32Y,
pPush->ui32Style & PB_STYLE_TEXT_OPAQUE);
}
}
}
//*****************************************************************************
//
//! Handles pointer events for a rectangular push button.
//!
//! \param psWidget is a pointer to the push button widget.
//! \param ui32Msg is the pointer event message.
//! \param i32X is the X coordinate of the pointer event.
//! \param i32Y is the Y coordinate of the pointer event.
//!
//! This function processes pointer event messages for a rectangular push
//! button. This is called in response to a \b #WIDGET_MSG_PTR_DOWN,
//! \b #WIDGET_MSG_PTR_MOVE, and \b #WIDGET_MSG_PTR_UP messages.
//!
//! If the \b #WIDGET_MSG_PTR_UP message is received with a position within the
//! extents of the push button, the push button's OnClick callback function is
//! called.
//!
//! \return Returns 1 if the coordinates are within the extents of the push
//! button and 0 otherwise.
//
//*****************************************************************************
static int32_t
RectangularButtonClick(tWidget *psWidget, uint32_t ui32Msg, int32_t i32X,
int32_t i32Y)
{
tPushButtonWidget *pPush;
//
// Check the arguments.
//
ASSERT(psWidget);
//
// Convert the generic widget pointer into a push button widget pointer.
//
pPush = (tPushButtonWidget *)psWidget;
//
// See if this is a pointer up message.
//
if(ui32Msg == WIDGET_MSG_PTR_UP)
{
//
// Indicate that this push button is no longer pressed.
//
pPush->ui32Style &= ~(PB_STYLE_PRESSED);
//
// If filling is enabled for this push button, or if an image is being
// used and a pressed button image is provided, then redraw the push
// button to show it in its non-pressed state.
//
if((pPush->ui32Style & PB_STYLE_FILL) ||
((pPush->ui32Style & PB_STYLE_IMG) && pPush->pui8PressImage))
{
RectangularButtonPaint(psWidget);
}
//
// If the pointer is still within the button bounds, and it is a
// release notify button, call the notification function here.
//
if(GrRectContainsPoint(&psWidget->sPosition, i32X, i32Y) &&
(pPush->ui32Style & PB_STYLE_RELEASE_NOTIFY) && pPush->pfnOnClick)
{
pPush->pfnOnClick(psWidget);
}
}
//
// See if the given coordinates are within the extents of the push button.
//
if(GrRectContainsPoint(&psWidget->sPosition, i32X, i32Y))
{
//
// See if this is a pointer down message.
//
if(ui32Msg == WIDGET_MSG_PTR_DOWN)
{
//
// Indicate that this push button is pressed.
//
pPush->ui32Style |= PB_STYLE_PRESSED;
//
// If filling is enabled for this push button, or if an image is
// being used and a pressed button image is provided, then redraw
// the push button to show it in its pressed state.
//
if((pPush->ui32Style & PB_STYLE_FILL) ||
((pPush->ui32Style & PB_STYLE_IMG) && pPush->pui8PressImage))
{
RectangularButtonPaint(psWidget);
}
}
//
// See if there is an OnClick callback for this widget.
//
if(pPush->pfnOnClick)
{
//
// If the pointer was just pressed then call the callback.
//
if((ui32Msg == WIDGET_MSG_PTR_DOWN) &&
!(pPush->ui32Style & PB_STYLE_RELEASE_NOTIFY))
{
pPush->pfnOnClick(psWidget);
}
//
// See if auto-repeat is enabled for this widget.
//
if(pPush->ui32Style & PB_STYLE_AUTO_REPEAT)
{
//
// If the pointer was just pressed, reset the auto-repeat
// count.
//
if(ui32Msg == WIDGET_MSG_PTR_DOWN)
{
pPush->ui32AutoRepeatCount = 0;
}
//
// See if the pointer was moved.
//
else if(ui32Msg == WIDGET_MSG_PTR_MOVE)
{
//
// Increment the auto-repeat count.
//
pPush->ui32AutoRepeatCount++;
//
// If the auto-repeat count exceeds the auto-repeat delay,
// and it is a multiple of the auto-repeat rate, then
// call the callback.
//
if((pPush->ui32AutoRepeatCount >=
pPush->ui16AutoRepeatDelay) &&
(((pPush->ui32AutoRepeatCount -
pPush->ui16AutoRepeatDelay) %
pPush->ui16AutoRepeatRate) == 0))
{
pPush->pfnOnClick(psWidget);
}
}
}
}
//
// These coordinates are within the extents of the push button widget.
//
return(1);
}
//
// These coordinates are not within the extents of the push button widget.
//
return(0);
}
//*****************************************************************************
//
//! Handles messages for a rectangular push button widget.
//!
//! \param psWidget is a pointer to the push button widget.
//! \param ui32Msg is the message.
//! \param ui32Param1 is the first parameter to the message.
//! \param ui32Param2 is the second parameter to the message.
//!
//! This function receives messages intended for this push button widget and
//! processes them accordingly. The processing of the message varies based on
//! the message in question.
//!
//! Unrecognized messages are handled by calling WidgetDefaultMsgProc().
//!
//! \return Returns a value appropriate to the supplied message.
//
//*****************************************************************************
int32_t
RectangularButtonMsgProc(tWidget *psWidget, uint32_t ui32Msg,
uint32_t ui32Param1, uint32_t ui32Param2)
{
//
// Check the arguments.
//
ASSERT(psWidget);
//
// Determine which message is being sent.
//
switch(ui32Msg)
{
//
// The widget paint request has been sent.
//
case WIDGET_MSG_PAINT:
{
//
// Handle the widget paint request.
//
RectangularButtonPaint(psWidget);
//
// Return one to indicate that the message was successfully
// processed.
//
return(1);
}
//
// One of the pointer requests has been sent.
//
case WIDGET_MSG_PTR_DOWN:
case WIDGET_MSG_PTR_MOVE:
case WIDGET_MSG_PTR_UP:
{
//
// Handle the pointer request, returning the appropriate value.
//
return(RectangularButtonClick(psWidget, ui32Msg, ui32Param1,
ui32Param2));
}
//
// An unknown request has been sent.
//
default:
{
//
// Let the default message handler process this message.
//
return(WidgetDefaultMsgProc(psWidget, ui32Msg, ui32Param1,
ui32Param2));
}
}
}
//*****************************************************************************
//
//! Initializes a rectangular push button widget.
//!
//! \param psWidget is a pointer to the push button widget to initialize.
//! \param psDisplay is a pointer to the display on which to draw the push
//! button.
//! \param i32X is the X coordinate of the upper left corner of the push
//! button.
//! \param i32Y is the Y coordinate of the upper left corner of the push
//! button.
//! \param i32Width is the width of the push button.
//! \param i32Height is the height of the push button.
//!
//! This function initializes the provided push button widget so that it will
//! be a rectangular push button.
//!
//! \return None.
//
//*****************************************************************************
void
RectangularButtonInit(tPushButtonWidget *psWidget, const tDisplay *psDisplay,
int32_t i32X, int32_t i32Y, int32_t i32Width,
int32_t i32Height)
{
uint32_t ui32Idx;
//
// Check the arguments.
//
ASSERT(psWidget);
ASSERT(psDisplay);
//
// Clear out the widget structure.
//
for(ui32Idx = 0; ui32Idx < sizeof(tPushButtonWidget); ui32Idx += 4)
{
((uint32_t *)psWidget)[ui32Idx / 4] = 0;
}
//
// Set the size of the push button widget structure.
//
psWidget->sBase.i32Size = sizeof(tPushButtonWidget);
//
// Mark this widget as fully disconnected.
//
psWidget->sBase.psParent = 0;
psWidget->sBase.psNext = 0;
psWidget->sBase.psChild = 0;
//
// Save the display pointer.
//
psWidget->sBase.psDisplay = psDisplay;
//
// Set the extents of this rectangular push button.
//
psWidget->sBase.sPosition.i16XMin = i32X;
psWidget->sBase.sPosition.i16YMin = i32Y;
psWidget->sBase.sPosition.i16XMax = i32X + i32Width - 1;
psWidget->sBase.sPosition.i16YMax = i32Y + i32Height - 1;
//
// Use the rectangular push button message handler to process messages to
// this push button.
//
psWidget->sBase.pfnMsgProc = RectangularButtonMsgProc;
}
//*****************************************************************************
//
//! Draws a circular push button.
//!
//! \param psWidget is a pointer to the push button widget to be drawn.
//!
//! This function draws a circular push button on the display. This is called
//! in response to a \b #WIDGET_MSG_PAINT message.
//!
//! \return None.
//
//*****************************************************************************
static void
CircularButtonPaint(tWidget *psWidget)
{
const uint8_t *pui8Image;
tPushButtonWidget *pPush;
tContext sCtx;
int32_t i32X, i32Y, i32R;
//
// Check the arguments.
//
ASSERT(psWidget);
//
// Convert the generic widget pointer into a push button widget pointer.
//
pPush = (tPushButtonWidget *)psWidget;
//
// Initialize a drawing context.
//
GrContextInit(&sCtx, psWidget->psDisplay);
//
// Initialize the clipping region based on the extents of this circular
// push button.
//
GrContextClipRegionSet(&sCtx, &(psWidget->sPosition));
//
// Get the radius of the circular push button, along with the X and Y
// coordinates for its center.
//
i32R = (psWidget->sPosition.i16XMax - psWidget->sPosition.i16XMin + 1) / 2;
i32X = psWidget->sPosition.i16XMin + i32R;
i32Y = psWidget->sPosition.i16YMin + i32R;
//
// See if the push button fill style is selected.
//
if(pPush->ui32Style & PB_STYLE_FILL)
{
//
// Fill the push button with the fill color.
//
GrContextForegroundSet(&sCtx, ((pPush->ui32Style & PB_STYLE_PRESSED) ?
pPush->ui32PressFillColor :
pPush->ui32FillColor));
GrCircleFill(&sCtx, i32X, i32Y, i32R);
}
//
// See if the push button outline style is selected.
//
if(pPush->ui32Style & PB_STYLE_OUTLINE)
{
//
// Outline the push button with the outline color.
//
GrContextForegroundSet(&sCtx, pPush->ui32OutlineColor);
GrCircleDraw(&sCtx, i32X, i32Y, i32R);
}
//
// See if the push button text or image style is selected.
//
if(pPush->ui32Style & (PB_STYLE_TEXT | PB_STYLE_IMG))
{
//
// If the push button outline style is selected then shrink the
// clipping region by one pixel on each side so that the outline is not
// overwritten by the text or image.
//
if(pPush->ui32Style & PB_STYLE_OUTLINE)
{
sCtx.sClipRegion.i16XMin++;
sCtx.sClipRegion.i16YMin++;
sCtx.sClipRegion.i16XMax--;
sCtx.sClipRegion.i16YMax--;
}
//
// See if the push button image style is selected.
//
if(pPush->ui32Style & PB_STYLE_IMG)
{
//
// Set the foreground and background colors to use for 1 BPP
// images.
//
GrContextForegroundSet(&sCtx, pPush->ui32TextColor);
GrContextBackgroundSet(&sCtx,
((pPush->ui32Style & PB_STYLE_PRESSED) ?
pPush->ui32PressFillColor :
pPush->ui32FillColor));
//
// Get the image to be drawn.
//
pui8Image = (((pPush->ui32Style & PB_STYLE_PRESSED) &&
pPush->pui8PressImage) ?
pPush->pui8PressImage : pPush->pui8Image);
//
// Draw the image centered in the push button.
//
GrImageDraw(&sCtx, pui8Image, i32X - (GrImageWidthGet(pui8Image) / 2),
i32Y - (GrImageHeightGet(pui8Image) / 2));
}
//
// See if the push button text style is selected.
//
if(pPush->ui32Style & PB_STYLE_TEXT)
{
//
// Draw the text centered in the middle of the push button.
//
GrContextFontSet(&sCtx, pPush->psFont);
GrContextForegroundSet(&sCtx, pPush->ui32TextColor);
GrContextBackgroundSet(&sCtx,
((pPush->ui32Style & PB_STYLE_PRESSED) ?
pPush->ui32PressFillColor :
pPush->ui32FillColor));
GrStringDrawCentered(&sCtx, pPush->pcText, -1, i32X, i32Y,
pPush->ui32Style & PB_STYLE_TEXT_OPAQUE);
}
}
}
//*****************************************************************************
//
//! Handles pointer events for a circular push button.
//!
//! \param psWidget is a pointer to the push button widget.
//! \param ui32Msg is the pointer event message.
//! \param i32X is the X coordinate of the pointer event.
//! \param i32Y is the Y coordinate of the pointer event.
//!
//! This function processes pointer event messages for a circular push button.
//! This is called in response to a \b #WIDGET_MSG_PTR_DOWN,
//! \b #WIDGET_MSG_PTR_MOVE, and \b #WIDGET_MSG_PTR_UP messages.
//!
//! If the \b #WIDGET_MSG_PTR_UP message is received with a position within the
//! extents of the push button, the push button's OnClick callback function is
//! called.
//!
//! \return Returns 1 if the coordinates are within the extents of the push
//! button and 0 otherwise.
//
//*****************************************************************************
static int32_t
CircularButtonClick(tWidget *psWidget, uint32_t ui32Msg, int32_t i32X,
int32_t i32Y)
{
tPushButtonWidget *pPush;
int32_t i32Xc, i32Yc, i32R;
//
// Check the arguments.
//
ASSERT(psWidget);
//
// Convert the generic widget pointer into a push button widget pointer.
//
pPush = (tPushButtonWidget *)psWidget;
//
// See if this is a pointer up message.
//
if(ui32Msg == WIDGET_MSG_PTR_UP)
{
//
// Indicate that this push button is no longer pressed.
//
pPush->ui32Style &= ~(PB_STYLE_PRESSED);
//
// If filling is enabled for this push button, or if an image is being
// used and a pressed button image is provided, then redraw the push
// button to show it in its non-pressed state.
//
if((pPush->ui32Style & PB_STYLE_FILL) ||
((pPush->ui32Style & PB_STYLE_IMG) && pPush->pui8PressImage))
{
CircularButtonPaint(psWidget);
}
}
//
// Get the radius of the circular push button, along with the X and Y
// coordinates for its center.
//
i32R = (psWidget->sPosition.i16XMax - psWidget->sPosition.i16XMin + 1) / 2;
i32Xc = psWidget->sPosition.i16XMin + i32R;
i32Yc = psWidget->sPosition.i16YMin + i32R;
//
// See if the given coordinates are within the radius of the push button.
//
if((((i32X - i32Xc) * (i32X - i32Xc)) +
((i32Y - i32Yc) * (i32Y - i32Yc))) <= (i32R * i32R))
{
//
// See if this is a pointer down message.
//
if(ui32Msg == WIDGET_MSG_PTR_DOWN)
{
//
// Indicate that this push button is pressed.
//
pPush->ui32Style |= PB_STYLE_PRESSED;
//
// If filling is enabled for this push button, or if an image is
// being used and a pressed button image is provided, then redraw
// the push button to show it in its pressed state.
//
if((pPush->ui32Style & PB_STYLE_FILL) ||
((pPush->ui32Style & PB_STYLE_IMG) && pPush->pui8PressImage))
{
CircularButtonPaint(psWidget);
}
}
//
// See if there is an OnClick callback for this widget.
//
if(pPush->pfnOnClick)
{
//
// If the pointer was just pressed or if the pointer was released
// and this button is set for release notification then call the
// callback.
//
if(((ui32Msg == WIDGET_MSG_PTR_DOWN) &&
!(pPush->ui32Style & PB_STYLE_RELEASE_NOTIFY)) ||
((ui32Msg == WIDGET_MSG_PTR_UP) &&
(pPush->ui32Style & PB_STYLE_RELEASE_NOTIFY)))
{
pPush->pfnOnClick(psWidget);
}
//
// See if auto-repeat is enabled for this widget.
//
if(pPush->ui32Style & PB_STYLE_AUTO_REPEAT)
{
//
// If the pointer was just pressed, reset the auto-repeat
// count.
//
if(ui32Msg == WIDGET_MSG_PTR_DOWN)
{
pPush->ui32AutoRepeatCount = 0;
}
//
// See if the pointer was moved.
//
else if(ui32Msg == WIDGET_MSG_PTR_MOVE)
{
//
// Increment the auto-repeat count.
//
pPush->ui32AutoRepeatCount++;
//
// If the auto-repeat count exceeds the auto-repeat delay,
// and it is a multiple of the auto-repeat rate, then
// call the callback.
//
if((pPush->ui32AutoRepeatCount >=
pPush->ui16AutoRepeatDelay) &&
(((pPush->ui32AutoRepeatCount -
pPush->ui16AutoRepeatDelay) %
pPush->ui16AutoRepeatRate) == 0))
{
pPush->pfnOnClick(psWidget);
}
}
}
}
//
// These coordinates are within the extents of the push button widget.
//
return(1);
}
//
// These coordinates are not within the extents of the push button widget.
//
return(0);
}
//*****************************************************************************
//
//! Handles messages for a circular push button widget.
//!
//! \param psWidget is a pointer to the push button widget.
//! \param ui32Msg is the message.
//! \param ui32Param1 is the first parameter to the message.
//! \param ui32Param2 is the second parameter to the message.
//!
//! This function receives messages intended for this push button widget and
//! processes them accordingly. The processing of the message varies based on
//! the message in question.
//!
//! Unrecognized messages are handled by calling WidgetDefaultMsgProc().
//!
//! \return Returns a value appropriate to the supplied message.
//
//*****************************************************************************
int32_t
CircularButtonMsgProc(tWidget *psWidget, uint32_t ui32Msg,
uint32_t ui32Param1, uint32_t ui32Param2)
{
//
// Check the arguments.
//
ASSERT(psWidget);
//
// Determine which message is being sent.
//
switch(ui32Msg)
{
//
// The widget paint request has been sent.
//
case WIDGET_MSG_PAINT:
{
//
// Handle the widget paint request.
//
CircularButtonPaint(psWidget);
//
// Return one to indicate that the message was successfully
// processed.
//
return(1);
}
//
// One of the pointer requests has been sent.
//
case WIDGET_MSG_PTR_DOWN:
case WIDGET_MSG_PTR_MOVE:
case WIDGET_MSG_PTR_UP:
{
//
// Handle the pointer request, returning the appropriate value.
//
return(CircularButtonClick(psWidget, ui32Msg, ui32Param1,
ui32Param2));
}
//
// An unknown request has been sent.
//
default:
{
//
// Let the default message handler process this message.
//
return(WidgetDefaultMsgProc(psWidget, ui32Msg, ui32Param1,
ui32Param2));
}
}
}
//*****************************************************************************
//
//! Initializes a circular push button widget.
//!
//! \param psWidget is a pointer to the push button widget to initialize.
//! \param psDisplay is a pointer to the display on which to draw the push
//! button.
//! \param i32X is the X coordinate of the upper left corner of the push
//! button.
//! \param i32Y is the Y coordinate of the upper left corner of the push
//! button.
//! \param i32R is the radius of the push button.
//!
//! This function initializes the provided push button widget so that it will
//! be a circular push button.
//!
//! \return None.
//
//*****************************************************************************
void
CircularButtonInit(tPushButtonWidget *psWidget, const tDisplay *psDisplay,
int32_t i32X, int32_t i32Y, int32_t i32R)
{
uint32_t ui32Idx;
//
// Check the arguments.
//
ASSERT(psWidget);
ASSERT(psDisplay);
//
// Clear out the widget structure.
//
for(ui32Idx = 0; ui32Idx < sizeof(tPushButtonWidget); ui32Idx += 4)
{
((uint32_t *)psWidget)[ui32Idx / 4] = 0;
}
//
// Set the size of the push button widget structure.
//
psWidget->sBase.i32Size = sizeof(tPushButtonWidget);
//
// Mark this widget as fully disconnected.
//
psWidget->sBase.psParent = 0;
psWidget->sBase.psNext = 0;
psWidget->sBase.psChild = 0;
//
// Save the display pointer.
//
psWidget->sBase.psDisplay = psDisplay;
//
// Set the extents of this circular push button.
//
psWidget->sBase.sPosition.i16XMin = i32X - i32R;
psWidget->sBase.sPosition.i16YMin = i32Y - i32R;
psWidget->sBase.sPosition.i16XMax = i32X + i32R;
psWidget->sBase.sPosition.i16YMax = i32Y + i32R;
//
// Use the circular push button message handler to processes messages to
// this push button.
//
psWidget->sBase.pfnMsgProc = CircularButtonMsgProc;
}
//*****************************************************************************
//
// Close the Doxygen group.
//! @}
//
//*****************************************************************************
|
trfiladelfo/unesp_mdt
|
boards/SW-TM4C-2.0.1.11577/grlib/pushbutton.c
|
C
|
mpl-2.0
| 31,307
|
#include <stdio.h>
int main(int argc, char const *argv[])
{
//COQ=customer order quantity, COQV=COQ value, SV= Stock value
int COQ,COQV,Credit,SV;
if ((COQ<SV)&&(Credit>=COQV))
{
printf("Supply successfull\n");
}
else if ((COQ<SV)&&(Credit<COQV))
{
/* code */
printf("Amount given is less than value of stock supplied.");
}
else if((COQ>SV)&&(Credit>=COQV)){
printf("Whatever in stock is given. Remaining balance would be returned in two days.\n");
}
}
|
saarques/Cprogramming
|
company_policy.c
|
C
|
mpl-2.0
| 472
|
/*
* This file is part of Espruino, a JavaScript interpreter for Microcontrollers
*
* Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* ----------------------------------------------------------------------------
* Utilities and definitions for handling Pins
* ----------------------------------------------------------------------------
*/
#include "jspin.h"
#include "jspininfo.h" // auto-generated
#include "jsinteractive.h"
#include "jshardware.h"
#if defined(PICO) || defined(NUCLEOF401RE) || defined(NUCLEOF411RE)
#define PIN_NAMES_DIRECT // work out pin names directly from port + pin in pinInfo
#endif
bool jshIsPinValid(Pin pin) {
// Note, PIN_UNDEFINED is always > JSH_PIN_COUNT
return pin < JSH_PIN_COUNT && pinInfo[pin].port!=JSH_PORT_NONE;
}
Pin jshGetPinFromString(const char *s) {
// built in constants
if (s[0]=='B' && s[1]=='T' && s[2]=='N') {
#ifdef BTN1_PININDEX
if (!s[3]) return BTN1_PININDEX;
if (s[3]=='1' && !s[4]) return BTN1_PININDEX;
#endif
#ifdef BTN2_PININDEX
if (s[3]=='2' && !s[4]) return BTN2_PININDEX;
#endif
#ifdef BTN3_PININDEX
if (s[3]=='3' && !s[4]) return BTN3_PININDEX;
#endif
#ifdef BTN4_PININDEX
if (s[3]=='4' && !s[4]) return BTN4_PININDEX;
#endif
}
if (s[0]=='L' && s[1]=='E' && s[2]=='D') {
#ifdef LED1_PININDEX
if (!s[3]) return LED1_PININDEX;
if (s[3]=='1' && !s[4]) return LED1_PININDEX;
#endif
#ifdef LED2_PININDEX
if (s[3]=='2' && !s[4]) return LED2_PININDEX;
#endif
#ifdef LED3_PININDEX
if (s[3]=='3' && !s[4]) return LED3_PININDEX;
#endif
#ifdef LED4_PININDEX
if (s[3]=='4' && !s[4]) return LED4_PININDEX;
#endif
#ifdef LED5_PININDEX
if (s[3]=='5' && !s[4]) return LED5_PININDEX;
#endif
#ifdef LED6_PININDEX
if (s[3]=='6' && !s[4]) return LED6_PININDEX;
#endif
#ifdef LED7_PININDEX
if (s[3]=='7' && !s[4]) return LED7_PININDEX;
#endif
#ifdef LED8_PININDEX
if (s[3]=='8' && !s[4]) return LED8_PININDEX;
#endif
}
if ((s[0]>='A' && s[0]<='H') && s[1]) {
int port = JSH_PORTA+s[0]-'A';
int pin = -1;
if (s[1]>='0' && s[1]<='9') {
if (!s[2]) { // D0-D9
pin = (s[1]-'0');
} else if (s[2]>='0' && s[2]<='9') {
if (!s[3]) {
pin = ((s[1]-'0')*10 + (s[2]-'0'));
} else if (!s[4] && s[3]>='0' && s[3]<='9') {
pin = ((s[1]-'0')*100 + (s[2]-'0')*10 + (s[3]-'0'));
}
}
}
if (pin>=0) {
#ifdef PIN_NAMES_DIRECT
int i;
for (i=0;i<JSH_PIN_COUNT;i++)
if (pinInfo[i].port == port && pinInfo[i].pin==pin)
return (Pin)i;
#else
if (port == JSH_PORTA) {
if (pin<JSH_PORTA_COUNT) return (Pin)(JSH_PORTA_OFFSET + pin);
} else if (port == JSH_PORTB) {
if (pin<JSH_PORTB_COUNT) return (Pin)(JSH_PORTB_OFFSET + pin);
} else if (port == JSH_PORTC) {
if (pin<JSH_PORTC_COUNT) return (Pin)(JSH_PORTC_OFFSET + pin);
} else if (port == JSH_PORTD) {
if (pin<JSH_PORTD_COUNT) return (Pin)(JSH_PORTD_OFFSET + pin);
#if JSH_PORTE_OFFSET!=-1
} else if (port == JSH_PORTE) {
if (pin<JSH_PORTE_COUNT) return (Pin)(JSH_PORTE_OFFSET + pin);
#endif
#if JSH_PORTF_OFFSET!=-1
} else if (port == JSH_PORTF) {
if (pin<JSH_PORTF_COUNT) return (Pin)(JSH_PORTF_OFFSET + pin);
#endif
#if JSH_PORTG_OFFSET!=-1
} else if (port == JSH_PORTG) {
if (pin<JSH_PORTG_COUNT) return (Pin)(JSH_PORTG_OFFSET + pin);
#endif
#if JSH_PORTH_OFFSET!=-1
} else if (port == JSH_PORTH) {
if (pin<JSH_PORTH_COUNT) return (Pin)(JSH_PORTH_OFFSET + pin);
#endif
}
#endif
}
}
return PIN_UNDEFINED;
}
/** Write the pin name to a string. String must have at least 8 characters (to be safe) */
void jshGetPinString(char *result, Pin pin) {
result[0] = 0; // just in case
#ifdef PIN_NAMES_DIRECT
if (jshIsPinValid(pin)) {
result[0] = (char)('A'+pinInfo[pin].port-JSH_PORTA);
itostr(pinInfo[pin].pin-JSH_PIN0,&result[1],10);
#else
if (
#if JSH_PORTA_OFFSET!=0
pin>=JSH_PORTA_OFFSET &&
#endif
pin<JSH_PORTA_OFFSET+JSH_PORTA_COUNT) {
result[0]='A';
itostr(pin-JSH_PORTA_OFFSET,&result[1],10);
} else if (pin>=JSH_PORTB_OFFSET && pin<JSH_PORTB_OFFSET+JSH_PORTB_COUNT) {
result[0]='B';
itostr(pin-JSH_PORTB_OFFSET,&result[1],10);
} else if (pin>=JSH_PORTC_OFFSET && pin<JSH_PORTC_OFFSET+JSH_PORTC_COUNT) {
result[0]='C';
itostr(pin-JSH_PORTC_OFFSET,&result[1],10);
} else if (pin>=JSH_PORTD_OFFSET && pin<JSH_PORTD_OFFSET+JSH_PORTD_COUNT) {
result[0]='D';
itostr(pin-JSH_PORTD_OFFSET,&result[1],10);
#if JSH_PORTE_OFFSET!=-1
} else if (pin>=JSH_PORTE_OFFSET && pin<JSH_PORTE_OFFSET+JSH_PORTE_COUNT) {
result[0]='E';
itostr(pin-JSH_PORTE_OFFSET,&result[1],10);
#endif
#if JSH_PORTF_OFFSET!=-1
} else if (pin>=JSH_PORTF_OFFSET && pin<JSH_PORTF_OFFSET+JSH_PORTF_COUNT) {
result[0]='F';
itostr(pin-JSH_PORTF_OFFSET,&result[1],10);
#endif
#if JSH_PORTG_OFFSET!=-1
} else if (pin>=JSH_PORTG_OFFSET && pin<JSH_PORTG_OFFSET+JSH_PORTG_COUNT) {
result[0]='G';
itostr(pin-JSH_PORTG_OFFSET,&result[1],10);
#endif
#if JSH_PORTH_OFFSET!=-1
} else if (pin>=JSH_PORTH_OFFSET && pin<JSH_PORTH_OFFSET+JSH_PORTH_COUNT) {
result[0]='H';
itostr(pin-JSH_PORTH_OFFSET,&result[1],10);
#endif
#endif
} else {
strncpy(result, "UNKNOWN", 8);
}
}
/// Given a var, convert it to a pin ID (or -1 if it doesn't exist). safe for undefined!
Pin jshGetPinFromVar(JsVar *pinv) {
if (jsvIsString(pinv) && pinv->varData.str[5]==0/*should never be more than 4 chars!*/) {
return jshGetPinFromString(&pinv->varData.str[0]);
} else if (jsvIsInt(pinv) /* This also tests for the Pin datatype */) {
return (Pin)jsvGetInteger(pinv);
} else return PIN_UNDEFINED;
}
Pin jshGetPinFromVarAndUnLock(JsVar *pinv) {
Pin pin = jshGetPinFromVar(pinv);
jsvUnLock(pinv);
return pin;
}
// ----------------------------------------------------------------------------
// Whether a pin's state has been set manually or not
BITFIELD_DECL(jshPinStateIsManual, JSH_PIN_COUNT); // TODO: This should be set to all 0
bool jshGetPinStateIsManual(Pin pin) {
return BITFIELD_GET(jshPinStateIsManual, pin);
}
void jshSetPinStateIsManual(Pin pin, bool manual) {
BITFIELD_SET(jshPinStateIsManual, pin, manual);
}
// ----------------------------------------------------------------------------
bool jshPinInput(Pin pin) {
bool value = false;
if (jshIsPinValid(pin)) {
if (!jshGetPinStateIsManual(pin))
jshPinSetState(pin, JSHPINSTATE_GPIO_IN);
value = jshPinGetValue(pin);
} else jsExceptionHere(JSET_ERROR, "Invalid pin!");
return value;
}
void jshPinOutput(Pin pin, bool value) {
if (jshIsPinValid(pin)) {
if (!jshGetPinStateIsManual(pin))
jshPinSetState(pin, JSHPINSTATE_GPIO_OUT);
jshPinSetValue(pin, value);
} else jsExceptionHere(JSET_ERROR, "Invalid pin!");
}
// ----------------------------------------------------------------------------
// Convert an event type flag into a jshPinFunction for an actual hardware device
JshPinFunction jshGetPinFunctionFromDevice(IOEventFlags device) {
switch (device) {
case EV_SERIAL1 : return JSH_USART1;
case EV_SERIAL2 : return JSH_USART2;
case EV_SERIAL3 : return JSH_USART3;
case EV_SERIAL4 : return JSH_USART4;
case EV_SERIAL5 : return JSH_USART5;
case EV_SERIAL6 : return JSH_USART6;
case EV_SPI1 : return JSH_SPI1;
case EV_SPI2 : return JSH_SPI2;
case EV_SPI3 : return JSH_SPI3;
case EV_I2C1 : return JSH_I2C1;
case EV_I2C2 : return JSH_I2C2;
case EV_I2C3 : return JSH_I2C3;
default: return 0;
}
}
/** Try and find a specific type of function for the given pin. Can be given an invalid pin and will return 0. */
JshPinFunction NO_INLINE jshGetPinFunctionForPin(Pin pin, JshPinFunction functionType) {
if (!jshIsPinValid(pin)) return 0;
int i;
for (i=0;i<JSH_PININFO_FUNCTIONS;i++) {
if ((pinInfo[pin].functions[i]&JSH_MASK_TYPE) == functionType)
return pinInfo[pin].functions[i];
}
return 0;
}
/** Try and find the best pin suitable for the given function. Can return -1. */
Pin NO_INLINE jshFindPinForFunction(JshPinFunction functionType, JshPinFunction functionInfo) {
#ifdef OLIMEXINO_STM32
/** Hack, as you can't mix AFs on the STM32F1, and Olimexino reordered the pins
* such that D4(AF1) is before D11(AF0) - and there are no SCK/MISO for AF1! */
if (functionType == JSH_SPI1 && functionInfo==JSH_SPI_MOSI) return JSH_PORTD_OFFSET+11;
#endif
#ifdef PICO
/* On the Pico, A9 is used for sensing when USB power is applied. Is someone types in
* Serial1.setup(9600) it'll get chosen as it's the first pin, but setting it to an output
* totally messes up the STM32 as it's fed with 5V. This ensures that it won't get chosen
* UNLESS it is explicitly selected.
*
* TODO: better way of doing this? A JSH_DONT_DEFAULT flag for pin functions? */
if (functionType == JSH_USART1) {
if (functionInfo==JSH_USART_TX) return JSH_PORTB_OFFSET+6;
if (functionInfo==JSH_USART_RX) return JSH_PORTB_OFFSET+7;
}
#endif
Pin i;
int j;
// first, try and find the pin with an AF of 0 - this is usually the 'default'
for (i=0;i<JSH_PIN_COUNT;i++)
for (j=0;j<JSH_PININFO_FUNCTIONS;j++)
if ((pinInfo[i].functions[j]&JSH_MASK_AF) == JSH_AF0 &&
(pinInfo[i].functions[j]&JSH_MASK_TYPE) == functionType &&
(pinInfo[i].functions[j]&JSH_MASK_INFO) == functionInfo)
return i;
// otherwise just try and find anything
for (i=0;i<JSH_PIN_COUNT;i++)
for (j=0;j<JSH_PININFO_FUNCTIONS;j++)
if ((pinInfo[i].functions[j]&JSH_MASK_TYPE) == functionType &&
(pinInfo[i].functions[j]&JSH_MASK_INFO) == functionInfo)
return i;
return PIN_UNDEFINED;
}
/// Given a full pin function, return a string describing it depending of what's in the flags enum
void jshPinFunctionToString(JshPinFunction pinFunc, JshPinFunctionToStringFlags flags, char *buf, size_t bufSize) {
const char *devStr = "";
JshPinFunction info = JSH_MASK_INFO & pinFunc;
JshPinFunction firstDevice = 0;
const char *infoStr = 0;
buf[0]=0;
if (JSH_PINFUNCTION_IS_USART(pinFunc)) {
devStr="USART";
firstDevice=JSH_USART1;
if (info==JSH_USART_RX) infoStr="RX";
else if (info==JSH_USART_TX) infoStr="TX";
else if (info==JSH_USART_CK) infoStr="CK";
} else if (JSH_PINFUNCTION_IS_SPI(pinFunc)) {
devStr="SPI";
firstDevice=JSH_SPI1;
if (info==JSH_SPI_MISO) infoStr="MISO";
else if (info==JSH_SPI_MOSI) infoStr="MOSI";
else if (info==JSH_SPI_SCK) infoStr="SCK";
} else if (JSH_PINFUNCTION_IS_I2C(pinFunc)) {
devStr="I2C";
firstDevice=JSH_I2C1;
if (info==JSH_I2C_SCL) infoStr="SCL";
else if (info==JSH_I2C_SDA) infoStr="SDA";
} else if (JSH_PINFUNCTION_IS_DAC(pinFunc)) {
devStr="DAC";
firstDevice=JSH_DAC;
if (info==JSH_DAC_CH1) infoStr="CH1";
else if (info==JSH_DAC_CH2) infoStr="CH2";
} else if (JSH_PINFUNCTION_IS_TIMER(pinFunc)) {
devStr="TIM";
firstDevice=JSH_TIMER1;
char infoStrBuf[5];
infoStr = &infoStrBuf[0];
infoStrBuf[0] = 'C';
infoStrBuf[1] = 'H';
infoStrBuf[2] = (char)('1' + ((info&JSH_MASK_TIMER_CH)>>JSH_SHIFT_INFO));
if (info & JSH_TIMER_NEGATED) {
infoStrBuf[3]='N';
infoStrBuf[4] = 0;
} else {
infoStrBuf[3] = 0;
}
}
int devIdx = 1 + ((((pinFunc&JSH_MASK_TYPE) - firstDevice) >> JSH_SHIFT_TYPE));
if (!devStr) {
jsiConsolePrintf("Couldn't convert pin function %d\n", pinFunc);
return;
}
if (flags & JSPFTS_DEVICE) strncat(buf, devStr, bufSize);
if (flags & JSPFTS_DEVICE_NUMBER) itostr(devIdx, &buf[strlen(buf)], 10);
if (flags & JSPFTS_SPACE) strncat(buf, " ", bufSize);
if (infoStr && (flags & JSPFTS_TYPE)) strncat(buf, infoStr, bufSize);
}
/** Prints a list of capable pins, eg:
jshPrintCapablePins(..., "PWM", JSH_TIMER1, JSH_TIMERMAX, 0,0, false)
jshPrintCapablePins(..., "SPI", JSH_SPI1, JSH_SPIMAX, JSH_MASK_INFO,JSH_SPI_SCK, false)
jshPrintCapablePins(..., "Analog Input", 0,0,0,0, true) - for analogs */
void NO_INLINE jshPrintCapablePins(Pin existingPin, const char *functionName, JshPinFunction typeMin, JshPinFunction typeMax, JshPinFunction pMask, JshPinFunction pData, bool printAnalogs) {
if (functionName) {
jsError("Pin %p is not capable of %s\nSuitable pins are:", existingPin, functionName);
}
Pin pin;
int i,n=0;
for (pin=0;pin<JSH_PIN_COUNT;pin++) {
bool has = false;
#ifdef STM32F1
int af = 0;
#endif
if (printAnalogs) {
has = pinInfo[pin].analog!=JSH_ANALOG_NONE;
} else {
for (i=0;i<JSH_PININFO_FUNCTIONS;i++) {
JshPinFunction type = pinInfo[pin].functions[i] & JSH_MASK_TYPE;
if (type>=typeMin && type<=typeMax && ((pinInfo[pin].functions[i]&pMask)==pData)) {
has = true;
#ifdef STM32F1
af = pinInfo[pin].functions[i] & JSH_MASK_AF;
#endif
}
}
}
if (has) {
jsiConsolePrintf("%p",pin);
#ifdef STM32F1
if (af!=JSH_AF0) jsiConsolePrint("(AF)");
#endif
jsiConsolePrint(" ");
if (n++==8) { n=0; jsiConsolePrint("\n"); }
}
}
jsiConsolePrint("\n");
}
|
vshymanskyy/Espruino
|
src/jspin.c
|
C
|
mpl-2.0
| 13,871
|
/*-------------------------------------------------------------------------
*
* pqmq.c
* Use the frontend/backend protocol for communication over a shm_mq
*
* Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* src/backend/libpq/pqmq.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "libpq/libpq.h"
#include "libpq/pqformat.h"
#include "libpq/pqmq.h"
#include "miscadmin.h"
#include "tcop/tcopprot.h"
#include "utils/builtins.h"
static shm_mq *pq_mq;
static shm_mq_handle *pq_mq_handle;
static bool pq_mq_busy = false;
static pid_t pq_mq_parallel_master_pid = 0;
static pid_t pq_mq_parallel_master_backend_id = InvalidBackendId;
static void pq_cleanup_redirect_to_shm_mq(dsm_segment *seg, Datum arg);
static void mq_comm_reset(void);
static int mq_flush(void);
static int mq_flush_if_writable(void);
static bool mq_is_send_pending(void);
static int mq_putmessage(char msgtype, const char *s, size_t len);
static void mq_putmessage_noblock(char msgtype, const char *s, size_t len);
static void mq_startcopyout(void);
static void mq_endcopyout(bool errorAbort);
static PQcommMethods PqCommMqMethods = {
mq_comm_reset,
mq_flush,
mq_flush_if_writable,
mq_is_send_pending,
mq_putmessage,
mq_putmessage_noblock,
mq_startcopyout,
mq_endcopyout
};
/*
* Arrange to redirect frontend/backend protocol messages to a shared-memory
* message queue.
*/
void
pq_redirect_to_shm_mq(dsm_segment *seg, shm_mq_handle *mqh)
{
PqCommMethods = &PqCommMqMethods;
pq_mq = shm_mq_get_queue(mqh);
pq_mq_handle = mqh;
whereToSendOutput = DestRemote;
FrontendProtocol = PG_PROTOCOL_LATEST;
on_dsm_detach(seg, pq_cleanup_redirect_to_shm_mq, (Datum) 0);
}
/*
* When the DSM that contains our shm_mq goes away, we need to stop sending
* messages to it.
*/
static void
pq_cleanup_redirect_to_shm_mq(dsm_segment *seg, Datum arg)
{
pq_mq = NULL;
pq_mq_handle = NULL;
whereToSendOutput = DestNone;
}
/*
* Arrange to SendProcSignal() to the parallel master each time we transmit
* message data via the shm_mq.
*/
void
pq_set_parallel_master(pid_t pid, BackendId backend_id)
{
Assert(PqCommMethods == &PqCommMqMethods);
pq_mq_parallel_master_pid = pid;
pq_mq_parallel_master_backend_id = backend_id;
}
static void
mq_comm_reset(void)
{
/* Nothing to do. */
}
static int
mq_flush(void)
{
/* Nothing to do. */
return 0;
}
static int
mq_flush_if_writable(void)
{
/* Nothing to do. */
return 0;
}
static bool
mq_is_send_pending(void)
{
/* There's never anything pending. */
return 0;
}
/*
* Transmit a libpq protocol message to the shared memory message queue
* selected via pq_mq_handle. We don't include a length word, because the
* receiver will know the length of the message from shm_mq_receive().
*/
static int
mq_putmessage(char msgtype, const char *s, size_t len)
{
shm_mq_iovec iov[2];
shm_mq_result result;
/*
* If we're sending a message, and we have to wait because the queue is
* full, and then we get interrupted, and that interrupt results in trying
* to send another message, we respond by detaching the queue. There's no
* way to return to the original context, but even if there were, just
* queueing the message would amount to indefinitely postponing the
* response to the interrupt. So we do this instead.
*/
if (pq_mq_busy)
{
if (pq_mq != NULL)
shm_mq_detach(pq_mq);
pq_mq = NULL;
pq_mq_handle = NULL;
return EOF;
}
/*
* If the message queue is already gone, just ignore the message. This
* doesn't necessarily indicate a problem; for example, DEBUG messages
* can be generated late in the shutdown sequence, after all DSMs have
* already been detached.
*/
if (pq_mq == NULL)
return 0;
pq_mq_busy = true;
iov[0].data = &msgtype;
iov[0].len = 1;
iov[1].data = s;
iov[1].len = len;
Assert(pq_mq_handle != NULL);
for (;;)
{
result = shm_mq_sendv(pq_mq_handle, iov, 2, true);
if (pq_mq_parallel_master_pid != 0)
SendProcSignal(pq_mq_parallel_master_pid,
PROCSIG_PARALLEL_MESSAGE,
pq_mq_parallel_master_backend_id);
if (result != SHM_MQ_WOULD_BLOCK)
break;
WaitLatch(&MyProc->procLatch, WL_LATCH_SET, 0);
CHECK_FOR_INTERRUPTS();
ResetLatch(&MyProc->procLatch);
}
pq_mq_busy = false;
Assert(result == SHM_MQ_SUCCESS || result == SHM_MQ_DETACHED);
if (result != SHM_MQ_SUCCESS)
return EOF;
return 0;
}
static void
mq_putmessage_noblock(char msgtype, const char *s, size_t len)
{
/*
* While the shm_mq machinery does support sending a message in
* non-blocking mode, there's currently no way to try sending beginning to
* send the message that doesn't also commit us to completing the
* transmission. This could be improved in the future, but for now we
* don't need it.
*/
elog(ERROR, "not currently supported");
}
static void
mq_startcopyout(void)
{
/* Nothing to do. */
}
static void
mq_endcopyout(bool errorAbort)
{
/* Nothing to do. */
}
/*
* Parse an ErrorResponse or NoticeResponse payload and populate an ErrorData
* structure with the results.
*/
void
pq_parse_errornotice(StringInfo msg, ErrorData *edata)
{
/* Initialize edata with reasonable defaults. */
MemSet(edata, 0, sizeof(ErrorData));
edata->elevel = ERROR;
edata->assoc_context = CurrentMemoryContext;
/* Loop over fields and extract each one. */
for (;;)
{
char code = pq_getmsgbyte(msg);
const char *value;
if (code == '\0')
{
pq_getmsgend(msg);
break;
}
value = pq_getmsgstring(msg);
switch (code)
{
case PG_DIAG_SEVERITY:
if (strcmp(value, "DEBUG") == 0)
edata->elevel = DEBUG1; /* or some other DEBUG level */
else if (strcmp(value, "LOG") == 0)
edata->elevel = LOG; /* can't be COMMERROR */
else if (strcmp(value, "INFO") == 0)
edata->elevel = INFO;
else if (strcmp(value, "NOTICE") == 0)
edata->elevel = NOTICE;
else if (strcmp(value, "WARNING") == 0)
edata->elevel = WARNING;
else if (strcmp(value, "ERROR") == 0)
edata->elevel = ERROR;
else if (strcmp(value, "FATAL") == 0)
edata->elevel = FATAL;
else if (strcmp(value, "PANIC") == 0)
edata->elevel = PANIC;
else
elog(ERROR, "unknown error severity");
break;
case PG_DIAG_SQLSTATE:
if (strlen(value) != 5)
elog(ERROR, "malformed sql state");
edata->sqlerrcode = MAKE_SQLSTATE(value[0], value[1], value[2],
value[3], value[4]);
break;
case PG_DIAG_MESSAGE_PRIMARY:
edata->message = pstrdup(value);
break;
case PG_DIAG_MESSAGE_DETAIL:
edata->detail = pstrdup(value);
break;
case PG_DIAG_MESSAGE_HINT:
edata->hint = pstrdup(value);
break;
case PG_DIAG_STATEMENT_POSITION:
edata->cursorpos = pg_atoi(value, sizeof(int), '\0');
break;
case PG_DIAG_INTERNAL_POSITION:
edata->internalpos = pg_atoi(value, sizeof(int), '\0');
break;
case PG_DIAG_INTERNAL_QUERY:
edata->internalquery = pstrdup(value);
break;
case PG_DIAG_CONTEXT:
edata->context = pstrdup(value);
break;
case PG_DIAG_SCHEMA_NAME:
edata->schema_name = pstrdup(value);
break;
case PG_DIAG_TABLE_NAME:
edata->table_name = pstrdup(value);
break;
case PG_DIAG_COLUMN_NAME:
edata->column_name = pstrdup(value);
break;
case PG_DIAG_DATATYPE_NAME:
edata->datatype_name = pstrdup(value);
break;
case PG_DIAG_CONSTRAINT_NAME:
edata->constraint_name = pstrdup(value);
break;
case PG_DIAG_SOURCE_FILE:
edata->filename = pstrdup(value);
break;
case PG_DIAG_SOURCE_LINE:
edata->lineno = pg_atoi(value, sizeof(int), '\0');
break;
case PG_DIAG_SOURCE_FUNCTION:
edata->funcname = pstrdup(value);
break;
default:
elog(ERROR, "unknown error field: %d", (int) code);
break;
}
}
}
|
zeroae/postgres-xl
|
src/backend/libpq/pqmq.c
|
C
|
mpl-2.0
| 7,913
|
#include "legato.h"
#include "interfaces.h"
#define dhubIO_DataType_t io_DataType_t
static bool IsEnabled = false;
static le_timer_Ref_t Timer;
#define LATITUDE_NAME "location/value/latitude"
#define LONGITUDE_NAME "location/value/longitude"
#define PERIOD_NAME "location/period"
#define ENABLE_NAME "location/enable"
//--------------------------------------------------------------------------------------------------
/**
* Function called when the timer expires.
*/
//--------------------------------------------------------------------------------------------------
static void TimerExpired
(
le_timer_Ref_t timer ///< Timer reference
)
//--------------------------------------------------------------------------------------------------
{
static unsigned int counter = 0;
int32_t latitude = 0;
int32_t longitude = 0;
int32_t horizontalAccuracy = 0;
counter += 1;
le_result_t result = le_pos_Get2DLocation(&latitude, &longitude, &horizontalAccuracy);
if (LE_OK != result)
{
LE_ERROR("Error %d getting position", result);
}
LE_INFO("Location: Latitude %d Longitude %d Accuracy %d", latitude, longitude, horizontalAccuracy);
// introduce oscillations (20 meters) to latitude
latitude += counter % 200;
// Location units have to be converted from 1e-6 degrees to degrees
io_PushNumeric(LATITUDE_NAME, IO_NOW, latitude * 0.000001);
io_PushNumeric(LONGITUDE_NAME, IO_NOW, longitude * 0.000001);
}
//--------------------------------------------------------------------------------------------------
/**
* Call-back function called when an update is received from the Data Hub for the "period"
* config setting.
*/
//--------------------------------------------------------------------------------------------------
static void PeriodUpdateHandler
(
double timestamp, ///< time stamp
double value, ///< period value, seconds
void* contextPtr ///< not used
)
//--------------------------------------------------------------------------------------------------
{
LE_INFO("Received update to 'period' setting: %lf (timestamped %lf)", value, timestamp);
uint32_t ms = (uint32_t)(value * 1000);
if (ms == 0)
{
le_timer_Stop(Timer);
}
else
{
le_timer_SetMsInterval(Timer, ms);
// If the sensor is enabled and the timer is not already running, start it now.
if (IsEnabled && (!le_timer_IsRunning(Timer)))
{
le_timer_Start(Timer);
}
}
}
//--------------------------------------------------------------------------------------------------
/**
* Call-back function called when an update is received from the Data Hub for the "enable"
* control.
*/
//--------------------------------------------------------------------------------------------------
static void EnableUpdateHandler
(
double timestamp, ///< time stamp
bool value, ///< whether input is enabled
void* contextPtr ///< not used
)
//--------------------------------------------------------------------------------------------------
{
LE_INFO("Received update to 'enable' setting: %s (timestamped %lf)",
value == false ? "false" : "true",
timestamp);
IsEnabled = value;
if (value)
{
// If the timer has a non-zero interval and is not already running, start it now.
if ((le_timer_GetMsInterval(Timer) != 0) && (!le_timer_IsRunning(Timer)))
{
le_timer_Start(Timer);
}
}
else
{
le_timer_Stop(Timer);
}
}
//--------------------------------------------------------------------------------------------------
/**
* Call-back for receiving notification that an update is happening.
*/
//--------------------------------------------------------------------------------------------------
static void UpdateStartEndHandler
(
bool isStarting, //< input is starting
void* contextPtr //< Not used.
)
//--------------------------------------------------------------------------------------------------
{
LE_INFO("Configuration update %s.", isStarting ? "starting" : "finished");
}
COMPONENT_INIT
{
le_result_t result;
io_AddUpdateStartEndHandler(UpdateStartEndHandler, NULL);
// This will be provided to the Data Hub.
result = io_CreateInput(LATITUDE_NAME, IO_DATA_TYPE_NUMERIC, "degrees");
LE_ASSERT(result == LE_OK);
result = io_CreateInput(LONGITUDE_NAME, IO_DATA_TYPE_NUMERIC, "degrees");
LE_ASSERT(result == LE_OK);
// This is my configuration setting.
result = io_CreateOutput(PERIOD_NAME, IO_DATA_TYPE_NUMERIC, "s");
LE_ASSERT(result == LE_OK);
// Register for notification of updates to our configuration setting.
io_AddNumericPushHandler(PERIOD_NAME, PeriodUpdateHandler, NULL);
// This is my enable/disable control.
result = io_CreateOutput(ENABLE_NAME, IO_DATA_TYPE_BOOLEAN, "");
LE_ASSERT(result == LE_OK);
// Set the defaults: enable the sensor, set period to 1s
io_SetBooleanDefault(ENABLE_NAME, true);
io_SetNumericDefault(PERIOD_NAME, 1);
// Register for notification of updates to our enable/disable control.
io_AddBooleanPushHandler(ENABLE_NAME, EnableUpdateHandler, NULL);
// Create a repeating timer that will call TimerExpired() each time it expires.
// Note: we'll start the timer when we receive our configuration setting.
Timer = le_timer_Create("gpsSensorTimer");
le_timer_SetRepeat(Timer, 0);
le_timer_SetHandler(Timer, TimerExpired);
}
|
legatoproject/legato-af
|
apps/sample/datahubGps/gpsSensor/gpsSensor.c
|
C
|
mpl-2.0
| 5,575
|
/* Copyright (C) 2015, Hsiang Kao (e0e1e) <0xe0e1e@gmail.com>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <openssl/evp.h>
#include "highway/encrypt.h"
_record(methodinfo)
_methodinfo_0 *_0;
char *name;
const EVP_CIPHER *cipher;
int ivsiz;
_end_record(methodinfo)
#include "highway/encrypt_openssl_impl.h"
int encrypt_rc4_md5_iv_length(_methodinfo *method)
{
return method->ivsiz;
}
extern _methodinfo_0 methodinfo_0_rc4_md5;
static
_methodinfo method_supported[] = {
{&methodinfo_0_rc4_md5, "rc4-md5", NULL, 16},
{&methodinfo_0_rc4_md5, "rc4-md5_8", NULL, 8}
};
#define N_METHODS (sizeof(method_supported)/sizeof(_methodinfo))
#include <string.h>
#ifdef _POSIX_C_SOURCE
#define stricmp strcasecmp
#endif
_methodinfo *
encrypt_rc4_md5_get_methodbyname(const char *name)
{
_methodinfo *p = method_supported;
for(;p < &method_supported[N_METHODS]; ++p) {
if (!stricmp(name, p->name)) {
if (p->cipher == NULL)
p->cipher = EVP_rc4();
return p;
}
}
return NULL;
}
#include <string.h>
#include <openssl/md5.h>
_cipher *
encrypt_rc4_md5_cipher_init(_methodinfo *method, char *key, char *iv, int op)
{
char md5_key[EVP_MAX_KEY_LENGTH + EVP_MAX_IV_LENGTH];
int keysiz = encrypt_openssl_key_length(method);
memcpy(md5_key, key, keysiz); memcpy(md5_key + keysiz, iv, method->ivsiz);
MD5(md5_key, keysiz+method->ivsiz, md5_key);
return encrypt_openssl_cipher_init(method, md5_key, NULL, op);
}
_methodinfo_0 methodinfo_0_rc4_md5 = {
encrypt_openssl_key_length,
encrypt_rc4_md5_iv_length,
encrypt_rc4_md5_cipher_init,
encrypt_openssl_cipher_update,
encrypt_openssl_cipher_final,
encrypt_openssl_cipher_exit
};
void encryptor_rc4_md5_init(void)
{
}
|
MaticsL/highway_client-libuv
|
encrypt_rc4-md5.c
|
C
|
mpl-2.0
| 1,858
|
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/cryptlib.h"
#include "buildinf.h"
unsigned long OpenSSL_version_num(void)
{
return OPENSSL_VERSION_NUMBER;
}
unsigned int OPENSSL_version_major(void)
{
return OPENSSL_VERSION_MAJOR;
}
unsigned int OPENSSL_version_minor(void)
{
return OPENSSL_VERSION_MINOR;
}
unsigned int OPENSSL_version_patch(void)
{
return OPENSSL_VERSION_PATCH;
}
const char *OPENSSL_version_pre_release(void)
{
return OPENSSL_VERSION_PRE_RELEASE_STR;
}
const char *OPENSSL_version_build_metadata(void)
{
return OPENSSL_VERSION_BUILD_METADATA_STR;
}
extern char ossl_cpu_info_str[];
const char *OpenSSL_version(int t)
{
switch (t) {
case OPENSSL_VERSION:
return OPENSSL_VERSION_TEXT;
case OPENSSL_VERSION_STRING:
return OPENSSL_VERSION_STR;
case OPENSSL_FULL_VERSION_STRING:
return OPENSSL_FULL_VERSION_STR;
case OPENSSL_BUILT_ON:
return DATE;
case OPENSSL_CFLAGS:
return compiler_flags;
case OPENSSL_PLATFORM:
return PLATFORM;
case OPENSSL_DIR:
#ifdef OPENSSLDIR
return "OPENSSLDIR: \"" OPENSSLDIR "\"";
#else
return "OPENSSLDIR: N/A";
#endif
case OPENSSL_ENGINES_DIR:
#ifdef ENGINESDIR
return "ENGINESDIR: \"" ENGINESDIR "\"";
#else
return "ENGINESDIR: N/A";
#endif
case OPENSSL_MODULES_DIR:
#ifdef MODULESDIR
return "MODULESDIR: \"" MODULESDIR "\"";
#else
return "MODULESDIR: N/A";
#endif
case OPENSSL_CPU_INFO:
if (OPENSSL_info(OPENSSL_INFO_CPU_SETTINGS) != NULL)
return ossl_cpu_info_str;
else
return "CPUINFO: N/A";
}
return "not available";
}
|
FriendSoftwareLabs/friendup
|
libs-ext/openssl/crypto/cversion.c
|
C
|
agpl-3.0
| 1,997
|
/****************************************************************
* *
* Copyright 2001, 2009 Fidelity Information Services, Inc *
* *
* This source code contains the intellectual property *
* of its copyright holder(s), and is made available *
* under a license. If you do not know the terms of *
* the license, please stop and do not read further. *
* *
****************************************************************/
#include "mdef.h"
#include "gtm_string.h"
#include <ssdef.h>
#include <descrip.h>
#include <rmsdef.h>
#include <prcdef.h>
#include "job.h"
#include "min_max.h"
static readonly unsigned char definput[] = "NL:";
static readonly unsigned char deflogfile[] = "NL:";
static unsigned char *defoutbuf;
static unsigned char *deferrbuf;
LITREF jp_datatype job_param_datatypes[];
LITREF mstr define_gtm$job$_;
LITREF mstr set_default_;
LITREF mstr atsign;
LITREF mstr run__nodebug_;
void ojparams(unsigned char *p, mval *routine, bool *defprcnam, int4 *cmaxmsg, mstr *image,
mstr *input, mstr *output, mstr *error, struct dsc$descriptor_s *prcnam, int4 *baspri,
int4 *stsflg, mstr *gbldir, mstr *startup, struct dsc$descriptor_s *logfile, mstr *deffs,
quadword *schedule)
{
jp_type ch;
int4 status;
struct dsc$descriptor_s timdsc;
int4 defstsflg;
MSTR_CONST(defoutext, ".MJO");
MSTR_CONST(deferrext, ".MJE");
error_def (ERR_IVTIME);
error_def (ERR_PRCNAMLEN);
error_def (ERR_PARFILSPC);
/* Initializations */
*defprcnam = FALSE;
defstsflg = PRC$M_DETACH;
*cmaxmsg = MAX(*cmaxmsg, (define_gtm$job$_.len + MAX_PIDSTR_LEN));
image->len = 0;
input->len = output->len = error->len = 0;
prcnam->dsc$w_length = 0;
prcnam->dsc$b_dtype = DSC$K_DTYPE_T;
prcnam->dsc$b_class = DSC$K_CLASS_S;
*baspri = JP_NO_BASPRI;
*stsflg = defstsflg;
gbldir->len = 0;
startup->len = 0;
logfile->dsc$w_length = 0;
logfile->dsc$b_dtype = DSC$K_DTYPE_T;
logfile->dsc$b_class = DSC$K_CLASS_S;
deffs->len = 0;
schedule->hi = schedule->lo = 0;
/* Process parameter list */
while (*p != jp_eol)
{
switch (ch = *p++)
{
case jp_account:
*stsflg &= (~PRC$M_NOACNT);
break;
case jp_default:
if (*p != 0)
{
deffs->len = *p;
deffs->addr = (p + 1);
}
break;
case jp_detached:
*stsflg |= PRC$M_DETACH;
break;
case jp_error:
if (*p != 0)
{
error->len = *p;
error->addr = (p + 1);
}
break;
case jp_gbldir:
if (*p != 0)
{
gbldir->len = *p;
gbldir->addr = (p + 1);
}
break;
case jp_image:
if (*p != 0)
{
image->len = *p;
image->addr = p + 1;
}
break;
case jp_input:
if (*p != 0)
{
input->len = *p;
input->addr = p + 1;
}
break;
case jp_logfile:
if (*p != 0)
{
logfile->dsc$w_length = *p;
logfile->dsc$a_pointer = p + 1;
}
break;
case jp_noaccount:
*stsflg |= PRC$M_NOACNT;
break;
case jp_nodetached:
*stsflg &= (~PRC$M_DETACH);
break;
case jp_noswapping:
*stsflg |= PRC$M_PSWAPM;
break;
case jp_output:
if (*p != 0)
{
output->len = *p;
output->addr = p + 1;
}
break;
case jp_priority:
*baspri = *(int4 *)p;
break;
case jp_process_name:
if (*p != 0)
{
prcnam->dsc$w_length = *p;
prcnam->dsc$a_pointer = p + 1;
}
break;
case jp_schedule:
timdsc.dsc$w_length = *p;
timdsc.dsc$b_dtype = DSC$K_DTYPE_T;
timdsc.dsc$b_class = DSC$K_CLASS_S;
timdsc.dsc$a_pointer = p + 1;
status = sys$bintim (&timdsc, schedule);
if (status != SS$_NORMAL)
rts_error(VARLSTCNT(4) ERR_IVTIME, 2, timdsc.dsc$w_length, timdsc.dsc$a_pointer);
break;
case jp_startup:
if (*p != 0)
{
startup->len = *p;
startup->addr = p + 1;
}
break;
case jp_swapping:
*stsflg &= (~PRC$M_PSWAPM);
break;
default:
GTMASSERT;
}
switch (job_param_datatypes[ch])
{
case jpdt_nul:
break;
case jpdt_num:
p += SIZEOF(int4);
break;
case jpdt_str:
p += (unsigned) *p + 1;
break;
default:
GTMASSERT;
}
}
/* Defaults and Checks */
if (image->len == 0)
ojdefimage (image);
else
if ((status = ojchkfs (image->addr, image->len, TRUE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 5, "IMAGE", image->len, image->addr, status);
*cmaxmsg = MAX(*cmaxmsg, run__nodebug_.len + image->len);
if (input->len == 0)
{
input->len = SIZEOF(definput) - 1;
input->addr = definput;
}
else
if ((status = ojchkfs (input->addr, input->len, TRUE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 5, "INPUT", input->len, input->addr, status);
*cmaxmsg = MAX(*cmaxmsg, 1 + input->len);
if (output->len == 0)
{
if (!defoutbuf)
defoutbuf = malloc(MAX_FILSPC_LEN);
memcpy (&defoutbuf[0], routine->str.addr, routine->str.len);
memcpy (&defoutbuf[routine->str.len], defoutext.addr, defoutext.len);
if (*defoutbuf == '%')
*defoutbuf = '_';
output->len = routine->str.len + defoutext.len;
output->addr = &defoutbuf[0];
}
else
if ((status = ojchkfs (output->addr, output->len, FALSE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 6, "OUTPUT", output->len, output->addr, status);
*cmaxmsg = MAX(*cmaxmsg, 1 + output->len);
if (error->len == 0)
{
if (!deferrbuf)
deferrbuf = malloc(MAX_FILSPC_LEN);
memcpy (&deferrbuf[0], routine->str.addr, routine->str.len);
memcpy (&deferrbuf[routine->str.len], deferrext.addr, deferrext.len);
if (*deferrbuf == '%')
*deferrbuf = '_';
error->len = routine->str.len + deferrext.len;
error->addr = &deferrbuf[0];
}
else
if ((status = ojchkfs (error->addr, error->len, FALSE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 5, "ERROR", error->len, error->addr, status);
*cmaxmsg = MAX(*cmaxmsg, 1 + error->len);
if (prcnam->dsc$w_length > MAX_PRCNAM_LEN)
rts_error(VARLSTCNT(5) ERR_PRCNAMLEN, 3, prcnam->dsc$w_length, prcnam->dsc$a_pointer, MAX_PRCNAM_LEN);
if (prcnam->dsc$w_length == 0)
{
ojdefprcnam (prcnam);
*defprcnam = TRUE;
}
if (*baspri == JP_NO_BASPRI)
ojdefbaspri (baspri);
if (gbldir->len != 0)
if ((status = ojchkfs (gbldir->addr, gbldir->len, FALSE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 6, "GBLDIR", gbldir->len, gbldir->addr, status);
*cmaxmsg = MAX(*cmaxmsg, 1 + gbldir->len);
if (startup->len != 0)
if ((status = ojchkfs (startup->addr, startup->len, TRUE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 7, "STARTUP", startup->len, startup->addr, status);
*cmaxmsg = MAX(*cmaxmsg, atsign.len + startup->len);
if (deffs->len == 0)
ojdefdeffs (deffs);
else
if ((status = ojchkfs (deffs->addr, deffs->len, FALSE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 7, "DEFAULT", deffs->len, deffs->addr, status);
*cmaxmsg = MAX(*cmaxmsg, set_default_.len + deffs->len);
if (logfile->dsc$w_length == 0)
{
logfile->dsc$w_length = SIZEOF(deflogfile) - 1;
logfile->dsc$a_pointer = deflogfile;
}
else
if ((status = ojchkfs (logfile->dsc$a_pointer, logfile->dsc$w_length, FALSE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 7, "LOGFILE", logfile->dsc$w_length,
logfile->dsc$a_pointer, status);
return;
}
|
ChristyV/fis-gtm
|
sr_vvms/ojparams.c
|
C
|
agpl-3.0
| 7,183
|
/*
* This file is part of Kotaka, a mud library for DGD
* http://github.com/shentino/kotaka
*
* Copyright (C) 2018, 2021 Raymond Jennings
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <kotaka/paths/account.h>
#include <kotaka/paths/verb.h>
inherit LIB_VERB;
inherit "/lib/sort";
inherit "~/lib/banlist";
inherit "~System/lib/string/align";
string *query_parse_methods()
{
return ({ "raw" });
}
int compare_sites(string a, string b)
{
int o1a, o2a, o3a, o4a, cidra;
int o1b, o2b, o3b, o4b, cidrb;
sscanf(a, "%d.%d.%d.%d/%d", o1a, o2a, o3a, o4a, cidra);
sscanf(b, "%d.%d.%d.%d/%d", o1b, o2b, o3b, o4b, cidrb);
if (o1a < o1b) {
return -1;
}
if (o1a > o1b) {
return 1;
}
if (o2a < o2b) {
return -1;
}
if (o2a > o2b) {
return 1;
}
if (o3a < o3b) {
return -1;
}
if (o3a > o3b) {
return 1;
}
if (o4a < o4b) {
return -1;
}
if (o4a > o4b) {
return 1;
}
if (cidra < cidrb) {
return -1;
}
if (cidra > cidrb) {
return 1;
}
return 0;
}
string query_help_title()
{
return "Sitebans";
}
string *query_help_contents()
{
return ({ "Lists sitebans" });
}
void main(object actor, mapping roles)
{
string *sites;
object user;
int sz;
user = query_user();
if (user->query_class() < 3) {
send_out("You do not have sufficient access rights to list sitebans.\n");
return;
}
if (roles["raw"]) {
send_out("Usage: sitebans\n");
return;
}
sites = BAND->query_sitebans();
sz = sizeof(sites);
qsort(sites, 0, sz, "compare_sites");
if (sz) {
mapping *bans;
int i;
bans = allocate(sz);
for (i = 0; i < sz; i++) {
mapping ban;
ban = BAND->query_siteban(sites[i]);
if (!ban) {
sites[i] = nil;
continue;
}
bans[i] = ban;
}
sites -= ({ nil });
bans -= ({ nil });
send_out(print_bans("Site", sites, bans));
send_out("\n");
} else {
send_out("There are no banned sites.\n");
}
}
|
shentino/kotaka
|
mud/home/Verb/sys/verb/ooc/wiz/sitebans.c
|
C
|
agpl-3.0
| 2,528
|
/*
===========================================================================
Return to Castle Wolfenstein multiplayer GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Return to Castle Wolfenstein multiplayer GPL Source Code (RTCW MP Source Code).
RTCW MP Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RTCW MP Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with RTCW MP Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the RTCW MP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW MP Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#include "g_shared.h"
#include "cmd.h"
#include "cvar.h"
#include "qcommon_io.h"
#include "g_sv_shared.h"
#include "scr_vm.h"
#include "sv_snapshot.h"
/*
==================
CheatsOk
==================
*/
int __cdecl CheatsOk(gentity_t *ent)
{
const char *v1;
int result;
const char *v3;
bool bCreateFX;
if ( g_cheats->boolean )
{
bCreateFX = 0;
if ( Cvar_FindVar("createfx") )
{
bCreateFX = 1;
}
if ( ent->health > 0 || bCreateFX )
{
result = 1;
}
else
{
v3 = va("%c \"GAME_MUSTBEALIVECOMMAND\"", 101);
SV_GameSendServerCommand(ent - g_entities, 0, v3);
result = 0;
}
}
else
{
v1 = va("%c \"GAME_CHEATSNOTENABLED\"", 101);
SV_GameSendServerCommand(ent - g_entities, 0, v1);
result = 0;
}
return result;
}
#if 0
void __cdecl Cmd_Take_f(gentity_t *ent)
{
char *amt; // ST3C_4@2
int v2; // ST08_4@28
WeaponVariantDef *v3; // eax@28
int v4; // eax@34
int v5; // ST08_4@43
WeaponVariantDef *v6; // eax@43
signed int j; // [sp+20h] [bp-20h]@38
signed int i; // [sp+24h] [bp-1Ch]@30
int slot; // [sp+28h] [bp-18h]@15
char *name; // [sp+2Ch] [bp-14h]@2
int amount; // [sp+34h] [bp-Ch]@2
unsigned int weapIndex; // [sp+38h] [bp-8h]@27
int take_all; // [sp+3Ch] [bp-4h]@5
if ( CheatsOk(ent) )
{
amt = SV_Cmd_Argv(2);
amount = atoi(amt);
name = SV_Cmd_Argv(1);
if ( name )
{
if ( strlen(name) )
{
take_all = Q_stricmp(name, "all") == 0;
if ( !take_all )
{
if ( Q_stricmpn(name, "health", 6) )
{
goto LABEL_47;
}
}
if ( amount )
{
ent->health -= amount;
if ( ent->health < 1 )
{
ent->health = 1;
}
}
else
{
ent->health = 1;
}
if ( take_all )
{
LABEL_47:
if ( !take_all && Q_stricmp(name, "weapons") )
{
goto LABEL_48;
}
for ( slot = 0; slot < 15; ++slot )
{
if ( ent->client->ps.heldWeapons[slot].weapon )
{
BG_TakePlayerWeapon(&ent->client->ps, ent->client->ps.heldWeapons[slot].weapon);
}
}
if ( ent->client->ps.weapon )
{
ent->client->ps.weapon = 0;
G_SelectWeaponIndex(ent - g_entities, 0);
}
if ( take_all )
{
LABEL_48:
if ( !take_all && Q_stricmpn(name, "ammo", 4) )
{
goto LABEL_49;
}
if ( amount )
{
if ( ent->client->ps.weapon )
{
weapIndex = ent->client->ps.weapon;
BG_AddAmmoToPool(&ent->client->ps, weapIndex, -amount);
if ( BG_GetAmmoNotInClip(&ent->client->ps, weapIndex) < 0 )
{
v2 = BG_GetAmmoNotInClip(&ent->client->ps, weapIndex);
v3 = BG_GetWeaponVariantDef(weapIndex);
BG_AddAmmoToClip(&ent->client->ps, v3->iClipIndex, v2);
BG_SetAmmoInPool(&ent->client->ps, weapIndex, 0);
}
}
}
else
{
for ( i = 0; i < 15; ++i )
{
weapIndex = ent->client->ps.heldWeapons[i].weapon;
if ( weapIndex )
{
BG_SetAmmoInPool(&ent->client->ps, weapIndex, 0);
v4 = BG_ClipForWeapon(weapIndex);
BG_SetAmmoInClip(&ent->client->ps, v4, 0);
}
}
}
if ( take_all )
{
LABEL_49:
if ( !Q_stricmpn(name, "allammo", 7) && amount )
{
for ( j = 0; j < 15; ++j )
{
weapIndex = ent->client->ps.heldWeapons[j].weapon;
if ( weapIndex )
{
BG_AddAmmoToPool(&ent->client->ps, weapIndex, -amount);
if ( BG_GetAmmoNotInClip(&ent->client->ps, weapIndex) < 0 )
{
v5 = BG_GetAmmoNotInClip(&ent->client->ps, weapIndex);
v6 = BG_GetWeaponVariantDef(weapIndex);
BG_AddAmmoToClip(&ent->client->ps, v6->iClipIndex, v5);
BG_SetAmmoInPool(&ent->client->ps, weapIndex, 0);
}
}
}
}
}
}
}
}
}
}
}
/*
==================
Cmd_Give_f
Give items to a client
==================
*/
void __cdecl Cmd_Give_f(gentity_t *ent)
{
char *amt; // ST70_4@2
char v2; // al@23
float *v3; // ST40_4@38
int v4; // ST10_4@46
int v5; // eax@46
int v6; // ST10_4@46
unsigned int v7; // eax@46
signed int i; // [sp+48h] [bp-2Ch]@31
int slot; // [sp+4Ch] [bp-28h]@25
gentity_t *it_ent; // [sp+50h] [bp-24h]@38
char *name; // [sp+54h] [bp-20h]@2
int give_all; // [sp+58h] [bp-1Ch]@5
WeaponVariantDef *weapVariantDef; // [sp+60h] [bp-14h]@36
int amount; // [sp+64h] [bp-10h]@2
unsigned int weapIndex; // [sp+68h] [bp-Ch]@13
WeaponDef *weapDef; // [sp+6Ch] [bp-8h]@39
gitem_s *it; // [sp+70h] [bp-4h]@36
if ( CheatsOk(ent) )
{
amt = SV_Cmd_Argv(2);
amount = atoi(amt);
name = SV_Cmd_Argv(1);
if ( name )
{
if ( strlen(name) )
{
give_all = Q_stricmp(name, "all") == 0;
if ( !give_all && Q_stricmpn(name, "health", 6)
|| (!amount ? (ent->health = ent->client->ps.stats[2]) : (ent->health += amount), give_all) )
{
if ( !give_all && Q_stricmp(name, "weapons") )
{
goto LABEL_50;
}
for ( weapIndex = 1; weapIndex < BG_GetNumWeapons(); ++weapIndex )
{
if ( BG_CanPlayerHaveWeapon(weapIndex) )
{
BG_TakePlayerWeapon(&ent->client->ps, weapIndex);
G_GivePlayerWeapon(&ent->client->ps, weapIndex, 0, 0);
}
}
if ( give_all )
{
LABEL_50:
if ( !give_all && Q_stricmpn(name, "ammo", 4) )
{
goto LABEL_51;
}
if ( amount )
{
if ( ent->client->ps.weapon )
{
v2 = BG_GetPlayerWeaponModel(&ent->client->ps, ent->client->ps.weapon);
Add_Ammo(ent, ent->client->ps.weapon, v2, amount, 1);
}
}
else
{
for ( slot = 0; slot < 15; Add_Ammo(ent, ent->client->ps.heldWeapons[slot++].weapon, 0, 998, 1) )
{
;
}
}
if ( give_all )
{
LABEL_51:
if ( Q_stricmpn(name, "allammo", 7) )
{
goto LABEL_52;
}
if ( !amount )
{
goto LABEL_52;
}
for ( i = 0; i < 15; Add_Ammo(ent, ent->client->ps.heldWeapons[i++].weapon, 0, amount, 1) )
{
;
}
if ( give_all )
{
LABEL_52:
if ( !give_all )
{
level.initializing = 1;
weapVariantDef = 0;
weapIndex = 0;
it = G_FindItem(name, 0);
if ( it )
{
it_ent = G_Spawn();
v3 = it_ent->r.currentOrigin;
it_ent->r.currentOrigin[0] = ent->r.currentOrigin[0];
v3[1] = ent->r.currentOrigin[1];
v3[2] = ent->r.currentOrigin[2];
G_GetItemClassname(it, &it_ent->classname);
G_SpawnItem(it_ent, it);
it_ent->active = 1;
if ( it->giType == IT_WEAPON )
{
weapIndex = it_ent->trigger.timestamp % 2048;
weapVariantDef = BG_GetWeaponVariantDef(weapIndex);
weapDef = BG_GetWeaponDef(weapIndex);
if ( weapDef->offhandClass == 3 )
{
ent->client->ps.offhandSecondary = 1;
}
else if ( weapDef->offhandClass == 2 )
{
ent->client->ps.offhandSecondary = 0;
}
}
Touch_Item(it_ent, ent, 0);
it_ent->active = 0;
if ( it_ent->r.inuse )
{
G_FreeEntity(it_ent);
}
if ( it->giType == IT_WEAPON )
{
v4 = weapVariantDef->iClipSize;
v5 = BG_ClipForWeapon(weapIndex);
BG_SetAmmoInClip(&ent->client->ps, v5, v4);
v6 = BG_GetStartAmmo(weapIndex) - weapVariantDef->iClipSize;
v7 = BG_AmmoForWeapon(weapIndex);
BG_SetAmmoInPool(&ent->client->ps, v7, v6);
}
level.initializing = 0;
}
else
{
level.initializing = 0;
}
}
}
}
}
}
}
}
}
}
#endif
void __cdecl Cmd_DemiGod_f(gentity_t *ent)
{
const char *msg;
if ( CheatsOk(ent) )
{
ent->flags ^= 2u;
if ( ent->flags & 2 )
{
msg = "GAME_DEMI_GODMODE_ON";
}
else
{
msg = "GAME_DEMI_GODMODE_OFF";
}
SV_GameSendServerCommand(ent - g_entities, 0, va("%c \"%s\"", 101, msg));
}
}
/*
==================
Cmd_God_f
Sets client to godmode
argv(0) god
==================
*/
void __cdecl Cmd_God_f(gentity_t *ent)
{
const char *msg;
if ( CheatsOk(ent) )
{
ent->flags ^= 1u;
if ( ent->flags & 1 )
{
msg = "GAME_GODMODE_ON";
}
else
{
msg = "GAME_GODMODE_OFF";
}
SV_GameSendServerCommand(ent - g_entities, 0, va("%c \"%s\"", 101, msg));
}
}
/*
==================
Cmd_Notarget_f
Sets client to notarget
argv(0) notarget
==================
*/
void __cdecl Cmd_Notarget_f(gentity_t *ent)
{
const char *msg;
if ( CheatsOk(ent) )
{
ent->flags ^= 4u;
if ( ent->flags & 4 )
{
msg = va("%c \"%s\"", 101, "GAME_NOTARGETON");
}
else
{
msg = va("%c \"%s\"", 101, "GAME_NOTARGETOFF");
}
SV_GameSendServerCommand(ent - g_entities, 0, msg);
}
}
void __cdecl Cmd_UFO_f(gentity_t *ent)
{
const char *v1; // eax@3
if ( CheatsOk(ent) )
{
if ( ent->client->ufo )
{
ent->client->ufo = qfalse;
v1 = va("%c \"%s\"", 101, "GAME_UFOOFF");
}
else
{
ent->client->ufo = qtrue;
v1 = va("%c \"%s\"", 101, "GAME_UFOON");
}
SV_GameSendServerCommand(ent - g_entities, 0, v1);
}
}
/*
==================
Cmd_Noclip_f
argv(0) noclip
==================
*/
void __cdecl Cmd_Noclip_f(gentity_t *ent)
{
const char *v1;
if ( CheatsOk(ent) )
{
if ( ent->client->noclip )
{
ent->client->noclip = qfalse;
v1 = va("%c \"%s\"", 101, "GAME_NOCLIPOFF");
}
else
{
ent->client->noclip = qtrue;
v1 = va("%c \"%s\"", 101, "GAME_NOCLIPON");
}
SV_GameSendServerCommand(ent - g_entities, 0, v1);
}
}
/*
=================
Cmd_Kill_f
=================
*/
void Cmd_Kill_f( gentity_t *ent ) {
if(ent->client->sess.sessionState != SESS_STATE_PLAYING || !CheatsOk(ent))
{
return;
}
ent->flags &= 0xFFFFFFFC;
ent->health = 0;
ent->client->ps.stats[0] = 0;
player_die(ent, ent, ent, 100000, 13, 0, 0, HITLOC_NONE, 0);
}
/*
==================
Cmd_Tell_f
==================
*/
/*
static void Cmd_Tell_f( gentity_t *ent ) {
int targetNum;
gentity_t *target;
char *p;
char arg[MAX_TOKEN_CHARS];
if ( SV_Cmd_Argc() < 2 ) {
return;
}
targetNum = atoi( SV_Cmd_Argv( 1 ) );
if ( targetNum < 0 || targetNum >= level.maxclients ) {
return;
}
target = &g_entities[targetNum];
if ( !target || !target->client ) {
return;
}
p = SV_Cmd_Argsv( 2, arg, sizeof(arg) );
G_LogPrintf( "tell: %s to %s: %s\n", ent->client->ps.netname, target->client->ps.netname, p );
G_Say( ent, target, SAY_TELL, p );
G_Say( ent, ent, SAY_TELL, p );
}
*/
/*
==================
Cmd_Where_f
==================
*/
void Cmd_Where_f( gentity_t *ent ) {
char s[64];
Com_sprintf(s, sizeof(s), "(%g %g %g)", ent->r.currentOrigin[0], ent->r.currentOrigin[1], ent->r.currentOrigin[2]);
SV_GameSendServerCommand( ent - g_entities, 0, va("%c \"\x15%s\n\"", 'e', s) );
}
void __cdecl Scr_PlayerVote(gentity_t *self, char *option)
{
Scr_AddString(option);
Scr_Notify(self, scr_const.vote, 1u);
}
void __cdecl Cmd_Vote_f(gentity_t *ent)
{
const char *msg;
if ( g_oldVoting->boolean )
{
if ( !level.voteTime )
{
SV_GameSendServerCommand(ent - g_entities, 0, va("%c \"GAME_NOVOTEINPROGRESS\"", 'e'));
return;
}
if ( ent->client->ps.eFlags & 0x100000 )
{
SV_GameSendServerCommand(ent - g_entities, 0, va("%c \"GAME_VOTEALREADYCAST\"", 'e'));
return;
}
/*
if ( ent->client->sess.cs.team == 3 )
{
SV_GameSendServerCommand(ent - g_entities, 0, va("%c \"GAME_NOSPECTATORVOTE\"", 'e'));
return;
}
*/
SV_GameSendServerCommand(ent - g_entities, 0, va("%c \"GAME_VOTECAST\"", 'e'));
ent->client->ps.eFlags |= 0x100000u;
}
msg = SV_Cmd_Argv(1);
if ( msg[0] != 'y' && msg[1] != 'Y' && msg[1] != '1' )
{
if ( g_oldVoting->boolean )
{
SV_SetConfigstring(CS_VOTE_NO, va("%i", ++level.voteNo));
}
else
{
Scr_PlayerVote(ent, "no");
}
}
else if ( g_oldVoting->boolean )
{
SV_SetConfigstring(CS_VOTE_YES, va("%i", ++level.voteYes));
}
else
{
Scr_PlayerVote(ent, "yes");
}
}
/*
=================
Cmd_SetViewpos_f
=================
*/
void Cmd_SetViewpos_f( gentity_t *ent ) {
vec3_t origin, angles;
int i;
if ( !g_cheats->boolean ) {
SV_GameSendServerCommand( ent - g_entities, 0, va("%c \"GAME_CHEATSNOTENABLED\"", 101) );
return;
}
if ( SV_Cmd_Argc() < 4 || SV_Cmd_Argc() > 6 )
{
SV_GameSendServerCommand( ent - g_entities, 0, va("%c \"GAME_USAGE\x15: setviewpos x y z yaw\"", 101) );
return;
}
VectorClear( angles );
for ( i = 0 ; i < 3 ; i++ ) {
origin[i] = atof( SV_Cmd_Argv( i + 1 ) );
}
angles[YAW] = atof( SV_Cmd_Argv( 4 ) );
angles[PITCH] = atof( SV_Cmd_Argv( 5 ) );
TeleportPlayer( ent, origin, angles );
}
/*
==============
Cmd_EntityCount_f
==============
*/
void Cmd_EntityCount_f( gentity_t *ent ) {
if ( !g_cheats->integer ) {
return;
}
Com_Printf(CON_CHANNEL_DONT_FILTER, "entity count = %i\n", level.num_entities );
}
void Cmd_PrintEntities_f()
{
G_PrintEntities();
}
void __cdecl Cmd_Say_f(gentity_t *ent, int mode, int arg0)
{
char *p;
char b[1024];
if ( SV_Cmd_Argc() >= 2 || arg0 )
{
if ( arg0 )
{
p = SV_Cmd_Argsv(0, b, sizeof(b));
}
else
{
p = SV_Cmd_Argsv(1, b, sizeof(b));
}
G_Say(ent, 0, mode, p);
}
}
void __cdecl Cmd_MenuResponse_f(gentity_t *pEnt)
{
char szServerId[1024];
char szMenuName[1024];
int iMenuIndex;
char szResponse[1024];
iMenuIndex = -1;
if ( SV_Cmd_Argc() == 4 )
{
SV_Cmd_ArgvBuffer(1, szServerId, 1024);
if ( atoi(szServerId) != Cvar_GetInt("sv_serverId"))
{
return;
}
SV_Cmd_ArgvBuffer(2, szMenuName, 1024);
iMenuIndex = atoi(szMenuName);
if ( iMenuIndex >= 0 && iMenuIndex < 32 )
{
SV_GetConfigstring(iMenuIndex + 1970, szMenuName, 1024);
}
SV_Cmd_ArgvBuffer(3, szResponse, 1024);
}
else
{
szMenuName[0] = 0;
strcpy(szResponse, "bad");
}
Scr_AddString(szResponse);
Scr_AddString(szMenuName);
Scr_Notify(pEnt, scr_const.menuresponse, 2u);
}
void Cmd_Score_f(gentity_t* ent)
{
SendScoreboard(ent);
}
int __cdecl Cmd_FollowCycle_f(gentity_t *ent, int dir)
{
int i;
int health;
int clientNum;
int otherFlags;
struct clientState_s archcs;
struct playerState_s ps;
if ( dir != 1 && dir != -1 )
{
Com_Error(ERR_DROP, "Cmd_FollowCycle_f: bad dir %i", dir);
}
assert ( ent->client != NULL);
if ( ent->client->sess.sessionState != SESS_STATE_SPECTATOR )
{
return qfalse;
}
ent->client->lastFollowedClient = -1; //Clear this so we never jump back onto old player
if ( ent->client->sess.forceSpectatorClient < 0 )
{
clientNum = ent->client->spectatorClient;
if ( clientNum < 0 )
{
clientNum = 0;
}
i = clientNum;
do
{
clientNum += dir;
if ( clientNum >= level.maxclients )
{
clientNum = 0;
}
if ( clientNum < 0 )
{
clientNum = level.maxclients - 1;
}
if ( SV_GetArchivedClientInfo(clientNum, &ent->client->sess.archiveTime, &ps, &archcs, 0, &health, &otherFlags) )
{
assert(otherFlags & POF_PLAYER);
if ( G_ClientCanSpectateTeamOrLocalPlayer(ent->client, &archcs) )
{
ent->client->spectatorClient = clientNum;
ent->client->sess.sessionState = SESS_STATE_SPECTATOR;
/* Scr_AddEntity(&g_entities[clientNum], 0);
Scr_Notify(ent, scr_const.spectator_cycle, 1u);
*/
return qtrue;
}
}
}
while ( clientNum != i );
}
return qfalse;
}
void __cdecl StopFollowing(gentity_t *ent)
{
gclient_t *client;
vec3_t vAngles;
// col_context_t context;
vec3_t vEnd;
vec3_t vMins;
trace_t trace;
vec3_t vForward;
vec3_t vPos;
vec3_t vUp;
vec3_t vMaxs;
/*
trace.normal.vec.v[0] = 0.0;
trace.normal.vec.v[1] = 0.0;
trace.normal.vec.v[2] = 0.0;
trace.normal.vec.v[3] = 0.0;
col_context_t::col_context_t(&context);
*/
client = ent->client;
assert(client != NULL);
client->sess.forceSpectatorClient = -1;
client->sess.killCamEntity = -1;
// client->sess.killCamTargetEntity = ent->s.number;
client->spectatorClient = -1;
if ( client->ps.otherFlags & 2 )
{
/*
client->ps.eFlags &= 0xFFFFBCFF;
client->ps.viewlocked = 0;
client->ps.viewlocked_entNum = 1023;
*/
G_GetPlayerViewOrigin(&client->ps, vPos);
BG_GetPlayerViewDirection(&client->ps, vForward, 0, vUp);
vAngles[0] = client->ps.viewangles[0];
vAngles[1] = client->ps.viewangles[1];
vAngles[2] = client->ps.viewangles[2];
vAngles[0] = vAngles[0] + 15.0;
vEnd[0] = (float)(-40.0 * vForward[0]) + vPos[0];
vEnd[1] = (float)(-40.0 * vForward[1]) + vPos[1];
vEnd[2] = (float)(-40.0 * vForward[2]) + vPos[2];
vEnd[0] = (float)(10.0 * vUp[0]) + vEnd[0];
vEnd[1] = (float)(10.0 * vUp[1]) + vEnd[1];
vEnd[2] = (float)(10.0 * vUp[2]) + vEnd[2];
vMins[0] = -8.0;
vMins[1] = -8.0;
vMins[2] = -8.0;
vMaxs[0] = 8.0;
vMaxs[1] = 8.0;
vMaxs[2] = 8.0;
G_TraceCapsule(&trace, vPos, vMins, vMaxs, vEnd, 1023, 0x810011/*, &context*/);
Vec3Lerp(vPos, vEnd, trace.fraction, vPos);
client->ps.clientNum = ent - g_entities;
//Not in Blackops
client->ps.eFlags &= 0xFFFFFCFF;
client->ps.viewlocked = 0;
client->ps.viewlocked_entNum = 1023;
///
client->ps.pm_flags &= 0xFFFEFFEF;
client->ps.weapFlags &= 0xFFFFFFBF;
client->ps.otherFlags &= 0xFFFFFFFD;
client->ps.fWeaponPosFrac = 0.0;
G_SetOrigin(ent, vPos);
client->ps.origin[0] = vPos[0];
client->ps.origin[1] = vPos[1];
client->ps.origin[2] = vPos[2];
SetClientViewAngle(ent, vAngles);
if ( !ent->tagInfo )
{
ent->r.currentAngles[0] = 0.0;
}
client->ps.shellshockIndex = 0;
client->ps.shellshockTime = 0;
client->ps.shellshockDuration = 0;
/*
client->ps.predictableEventSequence = 0;
client->ps.predictableEventSequenceOld = 0;
client->ps.unpredictableEventSequence = 0;
client->ps.unpredictableEventSequenceOld = 0;
v2 = client->ps.predictableEvents;
*v2 = 0;
v2[1] = 0;
v2[2] = 0;
v2[3] = 0;
v3 = client->ps.unpredictableEvents;
*v3 = 0;
v3[1] = 0;
v3[2] = 0;
v3[3] = 0;
*/
}
}
/*
=================
ClientCommand
=================
*/
void ClientCommand( int clientNum ) {
gentity_t *ent;
char cmd[MAX_TOKEN_CHARS];
ent = g_entities + clientNum;
if ( !ent->client ) {
return; // not fully in game yet
}
SV_Cmd_ArgvBuffer( 0, cmd, sizeof( cmd ) );
if ( Q_stricmp( cmd, "say" ) == 0 ) {
Cmd_Say_f( ent, SAY_ALL, qfalse );
return;
}
if ( Q_stricmp( cmd, "say_team" ) == 0 ) {
Cmd_Say_f( ent, SAY_TEAM, qfalse );
return;
}
// -NERVE - SMF
if ( Q_stricmp( cmd, "tell" ) == 0 ) {
// Cmd_Tell_f( ent );
return;
}
if ( Q_stricmp( cmd, "score" ) == 0 ) {
Cmd_Score_f( ent );
return;
}
if ( Q_stricmp( cmd, "mr" ) == 0 ) {
Cmd_MenuResponse_f(ent);
return;
}
// ignore all other commands when at intermission
// if ( level.intermissiontime ) {
// Cmd_Say_f (ent, qfalse, qtrue); // NERVE - SMF - we don't want to spam the clients with this.
// return;
// }
if ( Q_stricmp( cmd, "give" ) == 0 ) {
Cmd_Give_f( ent );
} else if ( Q_stricmp( cmd, "god" ) == 0 ) {
Cmd_God_f( ent );
} else if ( Q_stricmp( cmd, "demigod" ) == 0 ) {
Cmd_DemiGod_f( ent );
} else if ( Q_stricmp( cmd, "take" ) == 0 ) {
Cmd_Take_f( ent );
} else if ( Q_stricmp( cmd, "notarget" ) == 0 ) {
Cmd_Notarget_f( ent );
} else if ( Q_stricmp( cmd, "noclip" ) == 0 ) {
Cmd_Noclip_f( ent );
} else if ( Q_stricmp( cmd, "ufo" ) == 0 ) {
Cmd_UFO_f( ent );
} else if ( Q_stricmp( cmd, "kill" ) == 0 ) {
Cmd_Kill_f( ent );
} else if ( Q_stricmp( cmd, "where" ) == 0 ) {
Cmd_Where_f( ent );
} else if ( Q_stricmp( cmd, "callvote" ) == 0 ) {
Cmd_CallVote_f( ent );
} else if ( Q_stricmp( cmd, "vote" ) == 0 ) {
Cmd_Vote_f( ent );
} else if ( Q_stricmp( cmd, "setviewpos" ) == 0 ) {
Cmd_SetViewpos_f( ent );
} else if ( Q_stricmp( cmd, "entitycount" ) == 0 ) {
Cmd_EntityCount_f( ent );
} else if ( Q_stricmp( cmd, "printentities" ) == 0 ) {
Cmd_PrintEntities_f( ent );
} else {
SV_GameSendServerCommand( clientNum, 0, va( "%c \"GAME_UNKNOWNCLIENTCOMMAND\x15%s\"", 101, cmd ) );
}
}
|
D4edalus/CoD4x1.8_Server_Pub
|
src/g_cmds.c
|
C
|
agpl-3.0
| 23,983
|
// regversion.c - Oniguruma (regular expression library)
// Copyright (c) 2002-2020 K.Kosako All rights reserved.
//
#include "regint.h"
#pragma hdrstop
extern const char * onig_version(void)
{
static char s[12];
/*xsnprintf*/slsprintf_s(s, sizeof(s), "%d.%d.%d", ONIGURUMA_VERSION_MAJOR, ONIGURUMA_VERSION_MINOR, ONIGURUMA_VERSION_TEENY);
return s;
}
extern const char * onig_copyright(void)
{
static char s[58];
/*xsnprintf*/slsprintf_s(s, sizeof(s), "Oniguruma %d.%d.%d : Copyright (C) 2002-2018 K.Kosako", ONIGURUMA_VERSION_MAJOR, ONIGURUMA_VERSION_MINOR, ONIGURUMA_VERSION_TEENY);
return s;
}
|
papyrussolution/OpenPapyrus
|
Src/OSF/oniguruma/src/regversion.c
|
C
|
agpl-3.0
| 608
|
/*
* Realmedia RTSP protocol (RDT) support.
* Copyright (c) 2007 Ronald S. Bultje
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* @brief Realmedia RTSP protocol (RDT) support
* @author Ronald S. Bultje <rbultje@ronald.bitfreak.net>
*/
#include "avformat.h"
#include "libavutil/avstring.h"
#include "rtpdec.h"
#include "rdt.h"
#include "libavutil/base64.h"
#include "libavutil/md5.h"
#include "rm.h"
#include "internal.h"
#include "avio_internal.h"
#include "libavcodec/get_bits.h"
struct RDTDemuxContext {
AVFormatContext *ic; /**< the containing (RTSP) demux context */
/** Each RDT stream-set (represented by one RTSPStream) can contain
* multiple streams (of the same content, but with possibly different
* codecs/bitrates). Each such stream is represented by one AVStream
* in the AVFormatContext, and this variable points to the offset in
* that array such that the first is the first stream of this set. */
AVStream **streams;
int n_streams; /**< streams with identifical content in this set */
void *dynamic_protocol_context;
DynamicPayloadPacketHandlerProc parse_packet;
uint32_t prev_timestamp;
int prev_set_id, prev_stream_id;
};
RDTDemuxContext *
ff_rdt_parse_open(AVFormatContext *ic, int first_stream_of_set_idx,
void *priv_data, RTPDynamicProtocolHandler *handler)
{
RDTDemuxContext *s = av_mallocz(sizeof(RDTDemuxContext));
if (!s)
return NULL;
s->ic = ic;
s->streams = &ic->streams[first_stream_of_set_idx];
do {
s->n_streams++;
} while (first_stream_of_set_idx + s->n_streams < ic->nb_streams &&
s->streams[s->n_streams]->id == s->streams[0]->id);
s->prev_set_id = -1;
s->prev_stream_id = -1;
s->prev_timestamp = -1;
s->parse_packet = handler ? handler->parse_packet : NULL;
s->dynamic_protocol_context = priv_data;
return s;
}
void
ff_rdt_parse_close(RDTDemuxContext *s)
{
av_free(s);
}
struct PayloadContext {
AVFormatContext *rmctx;
int nb_rmst;
RMStream **rmst;
uint8_t *mlti_data;
unsigned int mlti_data_size;
char buffer[RTP_MAX_PACKET_LENGTH + FF_INPUT_BUFFER_PADDING_SIZE];
int audio_pkt_cnt; /**< remaining audio packets in rmdec */
};
void
ff_rdt_calc_response_and_checksum(char response[41], char chksum[9],
const char *challenge)
{
int ch_len = strlen (challenge), i;
unsigned char zres[16],
buf[64] = { 0xa1, 0xe9, 0x14, 0x9d, 0x0e, 0x6b, 0x3b, 0x59 };
#define XOR_TABLE_SIZE 37
const unsigned char xor_table[XOR_TABLE_SIZE] = {
0x05, 0x18, 0x74, 0xd0, 0x0d, 0x09, 0x02, 0x53,
0xc0, 0x01, 0x05, 0x05, 0x67, 0x03, 0x19, 0x70,
0x08, 0x27, 0x66, 0x10, 0x10, 0x72, 0x08, 0x09,
0x63, 0x11, 0x03, 0x71, 0x08, 0x08, 0x70, 0x02,
0x10, 0x57, 0x05, 0x18, 0x54 };
/* some (length) checks */
if (ch_len == 40) /* what a hack... */
ch_len = 32;
else if (ch_len > 56)
ch_len = 56;
memcpy(buf + 8, challenge, ch_len);
/* xor challenge bytewise with xor_table */
for (i = 0; i < XOR_TABLE_SIZE; i++)
buf[8 + i] ^= xor_table[i];
av_md5_sum(zres, buf, 64);
ff_data_to_hex(response, zres, 16, 1);
/* add tail */
strcpy (response + 32, "01d0a8e3");
/* calculate checksum */
for (i = 0; i < 8; i++)
chksum[i] = response[i * 4];
chksum[8] = 0;
}
static int
rdt_load_mdpr (PayloadContext *rdt, AVStream *st, int rule_nr)
{
AVIOContext pb;
int size;
uint32_t tag;
/**
* Layout of the MLTI chunk:
* 4: MLTI
* 2: number of streams
* Then for each stream ([number_of_streams] times):
* 2: mdpr index
* 2: number of mdpr chunks
* Then for each mdpr chunk ([number_of_mdpr_chunks] times):
* 4: size
* [size]: data
* we skip MDPR chunks until we reach the one of the stream
* we're interested in, and forward that ([size]+[data]) to
* the RM demuxer to parse the stream-specific header data.
*/
if (!rdt->mlti_data)
return -1;
ffio_init_context(&pb, rdt->mlti_data, rdt->mlti_data_size, 0,
NULL, NULL, NULL, NULL);
tag = avio_rl32(&pb);
if (tag == MKTAG('M', 'L', 'T', 'I')) {
int num, chunk_nr;
/* read index of MDPR chunk numbers */
num = avio_rb16(&pb);
if (rule_nr < 0 || rule_nr >= num)
return -1;
avio_seek(&pb, rule_nr * 2, SEEK_CUR);
chunk_nr = avio_rb16(&pb);
avio_seek(&pb, (num - 1 - rule_nr) * 2, SEEK_CUR);
/* read MDPR chunks */
num = avio_rb16(&pb);
if (chunk_nr >= num)
return -1;
while (chunk_nr--)
avio_seek(&pb, avio_rb32(&pb), SEEK_CUR);
size = avio_rb32(&pb);
} else {
size = rdt->mlti_data_size;
avio_seek(&pb, 0, SEEK_SET);
}
if (ff_rm_read_mdpr_codecdata(rdt->rmctx, &pb, st, rdt->rmst[st->index], size) < 0)
return -1;
return 0;
}
/**
* Actual data handling.
*/
int
ff_rdt_parse_header(const uint8_t *buf, int len,
int *pset_id, int *pseq_no, int *pstream_id,
int *pis_keyframe, uint32_t *ptimestamp)
{
GetBitContext gb;
int consumed = 0, set_id, seq_no, stream_id, is_keyframe,
len_included, need_reliable;
uint32_t timestamp;
/* skip status packets */
while (len >= 5 && buf[1] == 0xFF /* status packet */) {
int pkt_len;
if (!(buf[0] & 0x80))
return -1; /* not followed by a data packet */
pkt_len = AV_RB16(buf+3);
buf += pkt_len;
len -= pkt_len;
consumed += pkt_len;
}
if (len < 16)
return -1;
/**
* Layout of the header (in bits):
* 1: len_included
* Flag indicating whether this header includes a length field;
* this can be used to concatenate multiple RDT packets in a
* single UDP/TCP data frame and is used to precede RDT data
* by stream status packets
* 1: need_reliable
* Flag indicating whether this header includes a "reliable
* sequence number"; these are apparently sequence numbers of
* data packets alone. For data packets, this flag is always
* set, according to the Real documentation [1]
* 5: set_id
* ID of a set of streams of identical content, possibly with
* different codecs or bitrates
* 1: is_reliable
* Flag set for certain streams deemed less tolerable for packet
* loss
* 16: seq_no
* Packet sequence number; if >=0xFF00, this is a non-data packet
* containing stream status info, the second byte indicates the
* type of status packet (see wireshark docs / source code [2])
* if (len_included) {
* 16: packet_len
* } else {
* packet_len = remainder of UDP/TCP frame
* }
* 1: is_back_to_back
* Back-to-Back flag; used for timing, set for one in every 10
* packets, according to the Real documentation [1]
* 1: is_slow_data
* Slow-data flag; currently unused, according to Real docs [1]
* 5: stream_id
* ID of the stream within this particular set of streams
* 1: is_no_keyframe
* Non-keyframe flag (unset if packet belongs to a keyframe)
* 32: timestamp (PTS)
* if (set_id == 0x1F) {
* 16: set_id (extended set-of-streams ID; see set_id)
* }
* if (need_reliable) {
* 16: reliable_seq_no
* Reliable sequence number (see need_reliable)
* }
* if (stream_id == 0x3F) {
* 16: stream_id (extended stream ID; see stream_id)
* }
* [1] https://protocol.helixcommunity.org/files/2005/devdocs/RDT_Feature_Level_20.txt
* [2] http://www.wireshark.org/docs/dfref/r/rdt.html and
* http://anonsvn.wireshark.org/viewvc/trunk/epan/dissectors/packet-rdt.c
*/
init_get_bits(&gb, buf, len << 3);
len_included = get_bits1(&gb);
need_reliable = get_bits1(&gb);
set_id = get_bits(&gb, 5);
skip_bits(&gb, 1);
seq_no = get_bits(&gb, 16);
if (len_included)
skip_bits(&gb, 16);
skip_bits(&gb, 2);
stream_id = get_bits(&gb, 5);
is_keyframe = !get_bits1(&gb);
timestamp = get_bits_long(&gb, 32);
if (set_id == 0x1f)
set_id = get_bits(&gb, 16);
if (need_reliable)
skip_bits(&gb, 16);
if (stream_id == 0x1f)
stream_id = get_bits(&gb, 16);
if (pset_id) *pset_id = set_id;
if (pseq_no) *pseq_no = seq_no;
if (pstream_id) *pstream_id = stream_id;
if (pis_keyframe) *pis_keyframe = is_keyframe;
if (ptimestamp) *ptimestamp = timestamp;
return consumed + (get_bits_count(&gb) >> 3);
}
/**< return 0 on packet, no more left, 1 on packet, 1 on partial packet... */
static int
rdt_parse_packet (AVFormatContext *ctx, PayloadContext *rdt, AVStream *st,
AVPacket *pkt, uint32_t *timestamp,
const uint8_t *buf, int len, int flags)
{
int seq = 1, res;
AVIOContext pb;
if (rdt->audio_pkt_cnt == 0) {
int pos;
ffio_init_context(&pb, buf, len, 0, NULL, NULL, NULL, NULL);
flags = (flags & RTP_FLAG_KEY) ? 2 : 0;
res = ff_rm_parse_packet (rdt->rmctx, &pb, st, rdt->rmst[st->index], len, pkt,
&seq, flags, *timestamp);
pos = url_ftell(&pb);
if (res < 0)
return res;
if (res > 0) {
if (st->codec->codec_id == CODEC_ID_AAC) {
memcpy (rdt->buffer, buf + pos, len - pos);
rdt->rmctx->pb = avio_alloc_context (rdt->buffer, len - pos, 0,
NULL, NULL, NULL, NULL);
}
goto get_cache;
}
} else {
get_cache:
rdt->audio_pkt_cnt =
ff_rm_retrieve_cache (rdt->rmctx, rdt->rmctx->pb,
st, rdt->rmst[st->index], pkt);
if (rdt->audio_pkt_cnt == 0 &&
st->codec->codec_id == CODEC_ID_AAC)
av_freep(&rdt->rmctx->pb);
}
pkt->stream_index = st->index;
pkt->pts = *timestamp;
return rdt->audio_pkt_cnt > 0;
}
int
ff_rdt_parse_packet(RDTDemuxContext *s, AVPacket *pkt,
uint8_t **bufptr, int len)
{
uint8_t *buf = bufptr ? *bufptr : NULL;
int seq_no, flags = 0, stream_id, set_id, is_keyframe;
uint32_t timestamp;
int rv= 0;
if (!s->parse_packet)
return -1;
if (!buf && s->prev_stream_id != -1) {
/* return the next packets, if any */
timestamp= 0; ///< Should not be used if buf is NULL, but should be set to the timestamp of the packet returned....
rv= s->parse_packet(s->ic, s->dynamic_protocol_context,
s->streams[s->prev_stream_id],
pkt, ×tamp, NULL, 0, flags);
return rv;
}
if (len < 12)
return -1;
rv = ff_rdt_parse_header(buf, len, &set_id, &seq_no, &stream_id, &is_keyframe, ×tamp);
if (rv < 0)
return rv;
if (is_keyframe &&
(set_id != s->prev_set_id || timestamp != s->prev_timestamp ||
stream_id != s->prev_stream_id)) {
flags |= RTP_FLAG_KEY;
s->prev_set_id = set_id;
s->prev_timestamp = timestamp;
}
s->prev_stream_id = stream_id;
buf += rv;
len -= rv;
if (s->prev_stream_id >= s->n_streams) {
s->prev_stream_id = -1;
return -1;
}
rv = s->parse_packet(s->ic, s->dynamic_protocol_context,
s->streams[s->prev_stream_id],
pkt, ×tamp, buf, len, flags);
return rv;
}
void
ff_rdt_subscribe_rule (char *cmd, int size,
int stream_nr, int rule_nr)
{
av_strlcatf(cmd, size, "stream=%d;rule=%d,stream=%d;rule=%d",
stream_nr, rule_nr * 2, stream_nr, rule_nr * 2 + 1);
}
static unsigned char *
rdt_parse_b64buf (unsigned int *target_len, const char *p)
{
unsigned char *target;
int len = strlen(p);
if (*p == '\"') {
p++;
len -= 2; /* skip embracing " at start/end */
}
*target_len = len * 3 / 4;
target = av_mallocz(*target_len + FF_INPUT_BUFFER_PADDING_SIZE);
av_base64_decode(target, p, *target_len);
return target;
}
static int
rdt_parse_sdp_line (AVFormatContext *s, int st_index,
PayloadContext *rdt, const char *line)
{
AVStream *stream = s->streams[st_index];
const char *p = line;
if (av_strstart(p, "OpaqueData:buffer;", &p)) {
rdt->mlti_data = rdt_parse_b64buf(&rdt->mlti_data_size, p);
} else if (av_strstart(p, "StartTime:integer;", &p))
stream->first_dts = atoi(p);
else if (av_strstart(p, "ASMRuleBook:string;", &p)) {
int n, first = -1;
for (n = 0; n < s->nb_streams; n++)
if (s->streams[n]->id == stream->id) {
int count = s->streams[n]->index + 1;
if (first == -1) first = n;
if (rdt->nb_rmst < count) {
RMStream **rmst= av_realloc(rdt->rmst, count*sizeof(*rmst));
if (!rmst)
return AVERROR(ENOMEM);
memset(rmst + rdt->nb_rmst, 0,
(count - rdt->nb_rmst) * sizeof(*rmst));
rdt->rmst = rmst;
rdt->nb_rmst = count;
}
rdt->rmst[s->streams[n]->index] = ff_rm_alloc_rmstream();
rdt_load_mdpr(rdt, s->streams[n], (n - first) * 2);
if (s->streams[n]->codec->codec_id == CODEC_ID_AAC)
s->streams[n]->codec->frame_size = 1; // FIXME
}
}
return 0;
}
static void
real_parse_asm_rule(AVStream *st, const char *p, const char *end)
{
do {
/* can be either averagebandwidth= or AverageBandwidth= */
if (sscanf(p, " %*1[Aa]verage%*1[Bb]andwidth=%d", &st->codec->bit_rate) == 1)
break;
if (!(p = strchr(p, ',')) || p > end)
p = end;
p++;
} while (p < end);
}
static AVStream *
add_dstream(AVFormatContext *s, AVStream *orig_st)
{
AVStream *st;
if (!(st = av_new_stream(s, orig_st->id)))
return NULL;
st->codec->codec_type = orig_st->codec->codec_type;
st->first_dts = orig_st->first_dts;
return st;
}
static void
real_parse_asm_rulebook(AVFormatContext *s, AVStream *orig_st,
const char *p)
{
const char *end;
int n_rules = 0, odd = 0;
AVStream *st;
/**
* The ASMRuleBook contains a list of comma-separated strings per rule,
* and each rule is separated by a ;. The last one also has a ; at the
* end so we can use it as delimiter.
* Every rule occurs twice, once for when the RTSP packet header marker
* is set and once for if it isn't. We only read the first because we
* don't care much (that's what the "odd" variable is for).
* Each rule contains a set of one or more statements, optionally
* preceeded by a single condition. If there's a condition, the rule
* starts with a '#'. Multiple conditions are merged between brackets,
* so there are never multiple conditions spread out over separate
* statements. Generally, these conditions are bitrate limits (min/max)
* for multi-bitrate streams.
*/
if (*p == '\"') p++;
while (1) {
if (!(end = strchr(p, ';')))
break;
if (!odd && end != p) {
if (n_rules > 0)
st = add_dstream(s, orig_st);
else
st = orig_st;
if (!st)
break;
real_parse_asm_rule(st, p, end);
n_rules++;
}
p = end + 1;
odd ^= 1;
}
}
void
ff_real_parse_sdp_a_line (AVFormatContext *s, int stream_index,
const char *line)
{
const char *p = line;
if (av_strstart(p, "ASMRuleBook:string;", &p))
real_parse_asm_rulebook(s, s->streams[stream_index], p);
}
static PayloadContext *
rdt_new_context (void)
{
PayloadContext *rdt = av_mallocz(sizeof(PayloadContext));
av_open_input_stream(&rdt->rmctx, NULL, "", &ff_rdt_demuxer, NULL);
return rdt;
}
static void
rdt_free_context (PayloadContext *rdt)
{
int i;
for (i = 0; i < rdt->nb_rmst; i++)
if (rdt->rmst[i]) {
ff_rm_free_rmstream(rdt->rmst[i]);
av_freep(&rdt->rmst[i]);
}
if (rdt->rmctx)
av_close_input_stream(rdt->rmctx);
av_freep(&rdt->mlti_data);
av_freep(&rdt->rmst);
av_free(rdt);
}
#if __STDC_VERSION >= 1999001L
#define RDT_HANDLER(n, s, t) \
static RTPDynamicProtocolHandler ff_rdt_ ## n ## _handler = { \
.enc_name = s, \
.codec_type = t, \
.codec_id = CODEC_ID_NONE, \
.parse_sdp_a_line = rdt_parse_sdp_line, \
.open = rdt_new_context, \
.close = rdt_free_context, \
.parse_packet = rdt_parse_packet \
}
#else
#define RDT_HANDLER(n, s, t) \
static RTPDynamicProtocolHandler ff_rdt_ ## n ## _handler = { \
s, \
t, \
CODEC_ID_NONE, \
0, \
rdt_parse_sdp_line, \
rdt_new_context, \
rdt_free_context, \
rdt_parse_packet \
, NULL \
}
#endif
RDT_HANDLER(live_video, "x-pn-multirate-realvideo-live", AVMEDIA_TYPE_VIDEO);
RDT_HANDLER(live_audio, "x-pn-multirate-realaudio-live", AVMEDIA_TYPE_AUDIO);
RDT_HANDLER(video, "x-pn-realvideo", AVMEDIA_TYPE_VIDEO);
RDT_HANDLER(audio, "x-pn-realaudio", AVMEDIA_TYPE_AUDIO);
void av_register_rdt_dynamic_payload_handlers(void)
{
ff_register_dynamic_payload_handler(&ff_rdt_video_handler);
ff_register_dynamic_payload_handler(&ff_rdt_audio_handler);
ff_register_dynamic_payload_handler(&ff_rdt_live_video_handler);
ff_register_dynamic_payload_handler(&ff_rdt_live_audio_handler);
}
|
ging/isabel
|
lib/ffmpeg/Win32/src/ffmpeg/libavformat/rdt.c
|
C
|
agpl-3.0
| 18,890
|
#include "fitz-imp.h"
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
struct fz_style_context_s
{
int refs;
char *user_css;
int use_document_css;
};
static void fz_new_style_context(fz_context *ctx)
{
if (ctx)
{
ctx->style = fz_malloc_struct(ctx, fz_style_context);
ctx->style->refs = 1;
ctx->style->user_css = NULL;
ctx->style->use_document_css = 1;
}
}
static fz_style_context *fz_keep_style_context(fz_context *ctx)
{
if (!ctx)
return NULL;
return fz_keep_imp(ctx, ctx->style, &ctx->style->refs);
}
static void fz_drop_style_context(fz_context *ctx)
{
if (!ctx)
return;
if (fz_drop_imp(ctx, ctx->style, &ctx->style->refs))
{
fz_free(ctx, ctx->style->user_css);
fz_free(ctx, ctx->style);
}
}
/*
Toggle whether to respect document styles in HTML and EPUB.
*/
void fz_set_use_document_css(fz_context *ctx, int use)
{
ctx->style->use_document_css = use;
}
/*
Return whether to respect document styles in HTML and EPUB.
*/
int fz_use_document_css(fz_context *ctx)
{
return ctx->style->use_document_css;
}
/*
Set the user stylesheet source text for use with HTML and EPUB.
*/
void fz_set_user_css(fz_context *ctx, const char *user_css)
{
fz_free(ctx, ctx->style->user_css);
ctx->style->user_css = user_css ? fz_strdup(ctx, user_css) : NULL;
}
/*
Get the user stylesheet source text.
*/
const char *fz_user_css(fz_context *ctx)
{
return ctx->style->user_css;
}
static void fz_new_tuning_context(fz_context *ctx)
{
if (ctx)
{
ctx->tuning = fz_malloc_struct(ctx, fz_tuning_context);
ctx->tuning->refs = 1;
ctx->tuning->image_decode = fz_default_image_decode;
ctx->tuning->image_scale = fz_default_image_scale;
}
}
static fz_tuning_context *fz_keep_tuning_context(fz_context *ctx)
{
if (!ctx)
return NULL;
return fz_keep_imp(ctx, ctx->tuning, &ctx->tuning->refs);
}
static void fz_drop_tuning_context(fz_context *ctx)
{
if (!ctx)
return;
if (fz_drop_imp(ctx, ctx->tuning, &ctx->tuning->refs))
{
fz_free(ctx, ctx->tuning);
}
}
/*
Set the tuning function to use for
image decode.
image_decode: Function to use.
arg: Opaque argument to be passed to tuning function.
*/
void fz_tune_image_decode(fz_context *ctx, fz_tune_image_decode_fn *image_decode, void *arg)
{
ctx->tuning->image_decode = image_decode ? image_decode : fz_default_image_decode;
ctx->tuning->image_decode_arg = arg;
}
/*
Set the tuning function to use for
image scaling.
image_scale: Function to use.
arg: Opaque argument to be passed to tuning function.
*/
void fz_tune_image_scale(fz_context *ctx, fz_tune_image_scale_fn *image_scale, void *arg)
{
ctx->tuning->image_scale = image_scale ? image_scale : fz_default_image_scale;
ctx->tuning->image_scale_arg = arg;
}
static void fz_init_random_context(fz_context *ctx)
{
if (!ctx)
return;
ctx->seed48[0] = 0;
ctx->seed48[1] = 0;
ctx->seed48[2] = 0;
ctx->seed48[3] = 0xe66d;
ctx->seed48[4] = 0xdeec;
ctx->seed48[5] = 0x5;
ctx->seed48[6] = 0xb;
fz_srand48(ctx, (uint32_t)time(NULL));
}
/*
Free a context and its global state.
The context and all of its global state is freed, and any
buffered warnings are flushed (see fz_flush_warnings). If NULL
is passed in nothing will happen.
*/
void
fz_drop_context(fz_context *ctx)
{
if (!ctx)
return;
/* Other finalisation calls go here (in reverse order) */
fz_drop_document_handler_context(ctx);
fz_drop_glyph_cache_context(ctx);
fz_drop_store_context(ctx);
fz_drop_style_context(ctx);
fz_drop_tuning_context(ctx);
fz_drop_colorspace_context(ctx);
fz_drop_font_context(ctx);
fz_flush_warnings(ctx);
assert(ctx->error.top == ctx->error.stack);
/* Free the context itself */
ctx->alloc.free(ctx->alloc.user, ctx);
}
static void
fz_init_error_context(fz_context *ctx)
{
ctx->error.top = ctx->error.stack;
ctx->error.errcode = FZ_ERROR_NONE;
ctx->error.message[0] = 0;
ctx->warn.message[0] = 0;
ctx->warn.count = 0;
}
/*
Allocate context containing global state.
The global state contains an exception stack, resource store,
etc. Most functions in MuPDF take a context argument to be
able to reference the global state. See fz_drop_context for
freeing an allocated context.
alloc: Supply a custom memory allocator through a set of
function pointers. Set to NULL for the standard library
allocator. The context will keep the allocator pointer, so the
data it points to must not be modified or freed during the
lifetime of the context.
locks: Supply a set of locks and functions to lock/unlock
them, intended for multi-threaded applications. Set to NULL
when using MuPDF in a single-threaded applications. The
context will keep the locks pointer, so the data it points to
must not be modified or freed during the lifetime of the
context.
max_store: Maximum size in bytes of the resource store, before
it will start evicting cached resources such as fonts and
images. FZ_STORE_UNLIMITED can be used if a hard limit is not
desired. Use FZ_STORE_DEFAULT to get a reasonable size.
May return NULL.
*/
fz_context *
fz_new_context_imp(const fz_alloc_context *alloc, const fz_locks_context *locks, size_t max_store, const char *version)
{
fz_context *ctx;
if (strcmp(version, FZ_VERSION))
{
fprintf(stderr, "cannot create context: incompatible header (%s) and library (%s) versions\n", version, FZ_VERSION);
return NULL;
}
if (!alloc)
alloc = &fz_alloc_default;
if (!locks)
locks = &fz_locks_default;
ctx = Memento_label(alloc->malloc(alloc->user, sizeof(fz_context)), "fz_context");
if (!ctx)
{
fprintf(stderr, "cannot create context (phase 1)\n");
return NULL;
}
memset(ctx, 0, sizeof *ctx);
ctx->user = NULL;
ctx->alloc = *alloc;
ctx->locks = *locks;
ctx->error.print = fz_default_error_callback;
ctx->warn.print = fz_default_warning_callback;
fz_init_error_context(ctx);
fz_init_aa_context(ctx);
fz_init_random_context(ctx);
/* Now initialise sections that are shared */
fz_try(ctx)
{
fz_new_store_context(ctx, max_store);
fz_new_glyph_cache_context(ctx);
fz_new_colorspace_context(ctx);
fz_new_font_context(ctx);
fz_new_document_handler_context(ctx);
fz_new_style_context(ctx);
fz_new_tuning_context(ctx);
}
fz_catch(ctx)
{
fprintf(stderr, "cannot create context (phase 2)\n");
fz_drop_context(ctx);
return NULL;
}
return ctx;
}
/*
Make a clone of an existing context.
This function is meant to be used in multi-threaded
applications where each thread requires its own context, yet
parts of the global state, for example caching, are shared.
ctx: Context obtained from fz_new_context to make a copy of.
ctx must have had locks and lock/functions setup when created.
The two contexts will share the memory allocator, resource
store, locks and lock/unlock functions. They will each have
their own exception stacks though.
May return NULL.
*/
fz_context *
fz_clone_context(fz_context *ctx)
{
fz_context *new_ctx;
/* We cannot safely clone the context without having locking/
* unlocking functions. */
if (ctx == NULL || (ctx->locks.lock == fz_locks_default.lock && ctx->locks.unlock == fz_locks_default.unlock))
return NULL;
new_ctx = ctx->alloc.malloc(ctx->alloc.user, sizeof(fz_context));
if (!new_ctx)
return NULL;
/* First copy old context, including pointers to shared contexts */
memcpy(new_ctx, ctx, sizeof (fz_context));
/* Reset error context to initial state. */
fz_init_error_context(new_ctx);
/* Then keep lock checking happy by keeping shared contexts with new context */
fz_keep_document_handler_context(new_ctx);
fz_keep_style_context(new_ctx);
fz_keep_tuning_context(new_ctx);
fz_keep_font_context(new_ctx);
fz_keep_colorspace_context(new_ctx);
fz_keep_store_context(new_ctx);
fz_keep_glyph_cache(new_ctx);
return new_ctx;
}
/*
Set the user field in the context.
NULL initially, this field can be set to any opaque value
required by the user. It is copied on clones.
*/
void fz_set_user_context(fz_context *ctx, void *user)
{
if (ctx != NULL)
ctx->user = user;
}
/*
Read the user field from the context.
*/
void *fz_user_context(fz_context *ctx)
{
if (ctx == NULL)
return NULL;
return ctx->user;
}
|
fluks/mupdf-x11-bookmarks
|
source/fitz/context.c
|
C
|
agpl-3.0
| 8,170
|
/* gzlib.c -- zlib functions common to reading and writing gzip files
* Copyright (C) 2004-2017 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#include "gzguts.h"
#if defined(_WIN32) && !defined(__BORLANDC__)
# define LSEEK _lseeki64
#else
#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
# define LSEEK lseek64
#else
# define LSEEK lseek
#endif
#endif
/* Local functions */
local void gz_reset OF((gz_statep));
local gzFile gz_open OF((const void *, int, const char *));
#if defined UNDER_CE
/* Map the Windows error number in ERROR to a locale-dependent error message
string and return a pointer to it. Typically, the values for ERROR come
from GetLastError.
The string pointed to shall not be modified by the application, but may be
overwritten by a subsequent call to gz_strwinerror
The gz_strwinerror function does not change the current setting of
GetLastError. */
char ZLIB_INTERNAL *gz_strwinerror (error)
DWORD error;
{
static char buf[1024];
wchar_t *msgbuf;
DWORD lasterr = GetLastError();
DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL,
error,
0, /* Default language */
(LPVOID)&msgbuf,
0,
NULL);
if (chars != 0) {
/* If there is an \r\n appended, zap it. */
if (chars >= 2
&& msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') {
chars -= 2;
msgbuf[chars] = 0;
}
if (chars > sizeof (buf) - 1) {
chars = sizeof (buf) - 1;
msgbuf[chars] = 0;
}
wcstombs(buf, msgbuf, chars + 1);
LocalFree(msgbuf);
}
else {
sprintf(buf, "unknown win32 error (%ld)", error);
}
SetLastError(lasterr);
return buf;
}
#endif /* UNDER_CE */
/* Reset gzip file state */
local void gz_reset(state)
gz_statep state;
{
state->x.have = 0; /* no output data available */
if (state->mode == GZ_READ) { /* for reading ... */
state->eof = 0; /* not at end of file */
state->past = 0; /* have not read past end yet */
state->how = LOOK; /* look for gzip header */
}
else /* for writing ... */
state->reset = 0; /* no deflateReset pending */
state->seek = 0; /* no seek request pending */
gz_error(state, Z_OK, NULL); /* clear error */
state->x.pos = 0; /* no uncompressed data yet */
state->strm.avail_in = 0; /* no input data yet */
}
/* Open a gzip file either by name or file descriptor. */
local gzFile gz_open(path, fd, mode)
const void *path;
int fd;
const char *mode;
{
gz_statep state;
z_size_t len;
int oflag;
#ifdef O_CLOEXEC
int cloexec = 0;
#endif
#ifdef O_EXCL
int exclusive = 0;
#endif
/* check input */
if (path == NULL)
return NULL;
/* allocate gzFile structure to return */
state = (gz_statep)malloc(sizeof(gz_state));
if (state == NULL)
return NULL;
state->size = 0; /* no buffers allocated yet */
state->want = GZBUFSIZE; /* requested buffer size */
state->msg = NULL; /* no error message yet */
/* interpret mode */
state->mode = GZ_NONE;
state->level = Z_DEFAULT_COMPRESSION;
state->strategy = Z_DEFAULT_STRATEGY;
state->direct = 0;
while (*mode) {
if (*mode >= '0' && *mode <= '9')
state->level = *mode - '0';
else
switch (*mode) {
case 'r':
state->mode = GZ_READ;
break;
#ifndef NO_GZCOMPRESS
case 'w':
state->mode = GZ_WRITE;
break;
case 'a':
state->mode = GZ_APPEND;
break;
#endif
case '+': /* can't read and write at the same time */
free(state);
return NULL;
case 'b': /* ignore -- will request binary anyway */
break;
#ifdef O_CLOEXEC
case 'e':
cloexec = 1;
break;
#endif
#ifdef O_EXCL
case 'x':
exclusive = 1;
break;
#endif
case 'f':
state->strategy = Z_FILTERED;
break;
case 'h':
state->strategy = Z_HUFFMAN_ONLY;
break;
case 'R':
state->strategy = Z_RLE;
break;
case 'F':
state->strategy = Z_FIXED;
break;
case 'T':
state->direct = 1;
break;
default: /* could consider as an error, but just ignore */
;
}
mode++;
}
/* must provide an "r", "w", or "a" */
if (state->mode == GZ_NONE) {
free(state);
return NULL;
}
/* can't force transparent read */
if (state->mode == GZ_READ) {
if (state->direct) {
free(state);
return NULL;
}
state->direct = 1; /* for empty file */
}
/* save the path name for error messages */
#ifdef WIDECHAR
if (fd == -2) {
len = wcstombs(NULL, path, 0);
if (len == (z_size_t)-1)
len = 0;
}
else
#endif
len = strlen((const char *)path);
state->path = (char *)malloc(len + 1);
if (state->path == NULL) {
free(state);
return NULL;
}
#ifdef WIDECHAR
if (fd == -2)
if (len)
wcstombs(state->path, path, len + 1);
else
*(state->path) = 0;
else
#endif
#if !defined(NO_snprintf) && !defined(NO_vsnprintf)
(void)snprintf(state->path, len + 1, "%s", (const char *)path);
#else
strcpy(state->path, path);
#endif
/* compute the flags for open() */
oflag =
#ifdef O_LARGEFILE
O_LARGEFILE |
#endif
#ifdef O_BINARY
O_BINARY |
#endif
#ifdef O_CLOEXEC
(cloexec ? O_CLOEXEC : 0) |
#endif
(state->mode == GZ_READ ?
O_RDONLY :
(O_WRONLY | O_CREAT |
#ifdef O_EXCL
(exclusive ? O_EXCL : 0) |
#endif
(state->mode == GZ_WRITE ?
O_TRUNC :
O_APPEND)));
/* open the file with the appropriate flags (or just use fd) */
state->fd = fd > -1 ? fd : (
#ifdef WIDECHAR
fd == -2 ? _wopen(path, oflag, 0666) :
#endif
open((const char *)path, oflag, 0666));
if (state->fd == -1) {
free(state->path);
free(state);
return NULL;
}
if (state->mode == GZ_APPEND) {
LSEEK(state->fd, 0, SEEK_END); /* so gzoffset() is correct */
state->mode = GZ_WRITE; /* simplify later checks */
}
/* save the current position for rewinding (only if reading) */
if (state->mode == GZ_READ) {
state->start = LSEEK(state->fd, 0, SEEK_CUR);
if (state->start == -1) state->start = 0;
}
/* initialize stream */
gz_reset(state);
/* return stream */
return (gzFile)state;
}
/* -- see zlib.h -- */
gzFile ZEXPORT gzopen(path, mode)
const char *path;
const char *mode;
{
return gz_open(path, -1, mode);
}
/* -- see zlib.h -- */
gzFile ZEXPORT gzopen64(path, mode)
const char *path;
const char *mode;
{
return gz_open(path, -1, mode);
}
/* -- see zlib.h -- */
gzFile ZEXPORT gzdopen(fd, mode)
int fd;
const char *mode;
{
char *path; /* identifier for error messages */
gzFile gz;
if (fd == -1 || (path = (char *)malloc(7 + 3 * sizeof(int))) == NULL)
return NULL;
#if !defined(NO_snprintf) && !defined(NO_vsnprintf)
(void)snprintf(path, 7 + 3 * sizeof(int), "<fd:%d>", fd);
#else
sprintf(path, "<fd:%d>", fd); /* for debugging */
#endif
gz = gz_open(path, fd, mode);
free(path);
return gz;
}
/* -- see zlib.h -- */
#ifdef WIDECHAR
gzFile ZEXPORT gzopen_w(path, mode)
const wchar_t *path;
const char *mode;
{
return gz_open(path, -2, mode);
}
#endif
/* -- see zlib.h -- */
int ZEXPORT gzbuffer(file, size)
gzFile file;
unsigned size;
{
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return -1;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return -1;
/* make sure we haven't already allocated memory */
if (state->size != 0)
return -1;
/* check and set requested size */
if ((size << 1) < size)
return -1; /* need to be able to double it */
if (size < 2)
size = 2; /* need two bytes to check magic header */
state->want = size;
return 0;
}
/* -- see zlib.h -- */
int ZEXPORT gzrewind(file)
gzFile file;
{
gz_statep state;
/* get internal structure */
if (file == NULL)
return -1;
state = (gz_statep)file;
/* check that we're reading and that there's no error */
if (state->mode != GZ_READ ||
(state->err != Z_OK && state->err != Z_BUF_ERROR))
return -1;
/* back up and start over */
if (LSEEK(state->fd, state->start, SEEK_SET) == -1)
return -1;
gz_reset(state);
return 0;
}
/* -- see zlib.h -- */
z_off64_t ZEXPORT gzseek64(file, offset, whence)
gzFile file;
z_off64_t offset;
int whence;
{
unsigned n;
z_off64_t ret;
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return -1;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return -1;
/* check that there's no error */
if (state->err != Z_OK && state->err != Z_BUF_ERROR)
return -1;
/* can only seek from start or relative to current position */
if (whence != SEEK_SET && whence != SEEK_CUR)
return -1;
/* normalize offset to a SEEK_CUR specification */
if (whence == SEEK_SET)
offset -= state->x.pos;
else if (state->seek)
offset += state->skip;
state->seek = 0;
/* if within raw area while reading, just go there */
if (state->mode == GZ_READ && state->how == COPY &&
state->x.pos + offset >= 0) {
ret = LSEEK(state->fd, offset - (z_off64_t)state->x.have, SEEK_CUR);
if (ret == -1)
return -1;
state->x.have = 0;
state->eof = 0;
state->past = 0;
state->seek = 0;
gz_error(state, Z_OK, NULL);
state->strm.avail_in = 0;
state->x.pos += offset;
return state->x.pos;
}
/* calculate skip amount, rewinding if needed for back seek when reading */
if (offset < 0) {
if (state->mode != GZ_READ) /* writing -- can't go backwards */
return -1;
offset += state->x.pos;
if (offset < 0) /* before start of file! */
return -1;
if (gzrewind(file) == -1) /* rewind, then skip to offset */
return -1;
}
/* if reading, skip what's in output buffer (one less gzgetc() check) */
if (state->mode == GZ_READ) {
n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > offset ?
(unsigned)offset : state->x.have;
state->x.have -= n;
state->x.next += n;
state->x.pos += n;
offset -= n;
}
/* request skip (if not zero) */
if (offset) {
state->seek = 1;
state->skip = offset;
}
return state->x.pos + offset;
}
/* -- see zlib.h -- */
z_off_t ZEXPORT gzseek(file, offset, whence)
gzFile file;
z_off_t offset;
int whence;
{
z_off64_t ret;
ret = gzseek64(file, (z_off64_t)offset, whence);
return ret == (z_off_t)ret ? (z_off_t)ret : -1;
}
/* -- see zlib.h -- */
z_off64_t ZEXPORT gztell64(file)
gzFile file;
{
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return -1;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return -1;
/* return position */
return state->x.pos + (state->seek ? state->skip : 0);
}
/* -- see zlib.h -- */
z_off_t ZEXPORT gztell(file)
gzFile file;
{
z_off64_t ret;
ret = gztell64(file);
return ret == (z_off_t)ret ? (z_off_t)ret : -1;
}
/* -- see zlib.h -- */
z_off64_t ZEXPORT gzoffset64(file)
gzFile file;
{
z_off64_t offset;
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return -1;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return -1;
/* compute and return effective offset in file */
offset = LSEEK(state->fd, 0, SEEK_CUR);
if (offset == -1)
return -1;
if (state->mode == GZ_READ) /* reading */
offset -= state->strm.avail_in; /* don't count buffered input */
return offset;
}
/* -- see zlib.h -- */
z_off_t ZEXPORT gzoffset(file)
gzFile file;
{
z_off64_t ret;
ret = gzoffset64(file);
return ret == (z_off_t)ret ? (z_off_t)ret : -1;
}
/* -- see zlib.h -- */
int ZEXPORT gzeof(file)
gzFile file;
{
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return 0;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return 0;
/* return end-of-file state */
return state->mode == GZ_READ ? state->past : 0;
}
/* -- see zlib.h -- */
const char * ZEXPORT gzerror(file, errnum)
gzFile file;
int *errnum;
{
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return NULL;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return NULL;
/* return error information */
if (errnum != NULL)
*errnum = state->err;
return state->err == Z_MEM_ERROR ? "out of memory" :
(state->msg == NULL ? "" : state->msg);
}
/* -- see zlib.h -- */
void ZEXPORT gzclearerr(file)
gzFile file;
{
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return;
/* clear error and end-of-file */
if (state->mode == GZ_READ) {
state->eof = 0;
state->past = 0;
}
gz_error(state, Z_OK, NULL);
}
/* Create an error message in allocated memory and set state->err and
state->msg accordingly. Free any previous error message already there. Do
not try to free or allocate space if the error is Z_MEM_ERROR (out of
memory). Simply save the error message as a static string. If there is an
allocation failure constructing the error message, then convert the error to
out of memory. */
void ZLIB_INTERNAL gz_error(state, err, msg)
gz_statep state;
int err;
const char *msg;
{
/* free previously allocated message and clear */
if (state->msg != NULL) {
if (state->err != Z_MEM_ERROR)
free(state->msg);
state->msg = NULL;
}
/* if fatal, set state->x.have to 0 so that the gzgetc() macro fails */
if (err != Z_OK && err != Z_BUF_ERROR)
state->x.have = 0;
/* set error code, and if no message, then done */
state->err = err;
if (msg == NULL)
return;
/* for an out of memory error, return literal string when requested */
if (err == Z_MEM_ERROR)
return;
/* construct error message with path */
if ((state->msg = (char *)malloc(strlen(state->path) + strlen(msg) + 3)) ==
NULL) {
state->err = Z_MEM_ERROR;
return;
}
#if !defined(NO_snprintf) && !defined(NO_vsnprintf)
(void)snprintf(state->msg, strlen(state->path) + strlen(msg) + 3,
"%s%s%s", state->path, ": ", msg);
#else
strcpy(state->msg, state->path);
strcat(state->msg, ": ");
strcat(state->msg, msg);
#endif
}
#ifndef INT_MAX
/* portably return maximum value for an int (when limits.h presumed not
available) -- we need to do this to cover cases where 2's complement not
used, since C standard permits 1's complement and sign-bit representations,
otherwise we could just use ((unsigned)-1) >> 1 */
unsigned ZLIB_INTERNAL gz_intmax()
{
unsigned p, q;
p = 1;
do {
q = p;
p <<= 1;
p++;
} while (p > q);
return q >> 1;
}
#endif
|
sagiadinos/garlic-player
|
src/ext/zlib/gzlib.c
|
C
|
agpl-3.0
| 16,709
|
/* $OpenBSD: bcrypt_pbkdf.c,v 1.4 2013/07/29 00:55:53 tedu Exp $ */
/*
* Copyright (c) 2013 Ted Unangst <tedu@openbsd.org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef HAVE_BCRYPT_PBKDF
#include "libssh2_priv.h"
#include <stdlib.h>
#include <sys/types.h>
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#include "blf.h"
#define MINIMUM(a,b) (((a) < (b)) ? (a) : (b))
/*
* pkcs #5 pbkdf2 implementation using the "bcrypt" hash
*
* The bcrypt hash function is derived from the bcrypt password hashing
* function with the following modifications:
* 1. The input password and salt are preprocessed with SHA512.
* 2. The output length is expanded to 256 bits.
* 3. Subsequently the magic string to be encrypted is lengthened and modified
* to "OxychromaticBlowfishSwatDynamite"
* 4. The hash function is defined to perform 64 rounds of initial state
* expansion. (More rounds are performed by iterating the hash.)
*
* Note that this implementation pulls the SHA512 operations into the caller
* as a performance optimization.
*
* One modification from official pbkdf2. Instead of outputting key material
* linearly, we mix it. pbkdf2 has a known weakness where if one uses it to
* generate (i.e.) 512 bits of key material for use as two 256 bit keys, an
* attacker can merely run once through the outer loop below, but the user
* always runs it twice. Shuffling output bytes requires computing the
* entirety of the key material to assemble any subkey. This is something a
* wise caller could do; we just do it for you.
*/
#define BCRYPT_BLOCKS 8
#define BCRYPT_HASHSIZE (BCRYPT_BLOCKS * 4)
static void
bcrypt_hash(uint8_t *sha2pass, uint8_t *sha2salt, uint8_t *out)
{
blf_ctx state;
uint8_t ciphertext[BCRYPT_HASHSIZE] =
"OxychromaticBlowfishSwatDynamite";
uint32_t cdata[BCRYPT_BLOCKS];
int i;
uint16_t j;
size_t shalen = SHA512_DIGEST_LENGTH;
/* key expansion */
Blowfish_initstate(&state);
Blowfish_expandstate(&state, sha2salt, shalen, sha2pass, shalen);
for(i = 0; i < 64; i++) {
Blowfish_expand0state(&state, sha2salt, shalen);
Blowfish_expand0state(&state, sha2pass, shalen);
}
/* encryption */
j = 0;
for(i = 0; i < BCRYPT_BLOCKS; i++)
cdata[i] = Blowfish_stream2word(ciphertext, sizeof(ciphertext),
&j);
for(i = 0; i < 64; i++)
blf_enc(&state, cdata, sizeof(cdata) / sizeof(uint64_t));
/* copy out */
for(i = 0; i < BCRYPT_BLOCKS; i++) {
out[4 * i + 3] = (cdata[i] >> 24) & 0xff;
out[4 * i + 2] = (cdata[i] >> 16) & 0xff;
out[4 * i + 1] = (cdata[i] >> 8) & 0xff;
out[4 * i + 0] = cdata[i] & 0xff;
}
/* zap */
_libssh2_explicit_zero(ciphertext, sizeof(ciphertext));
_libssh2_explicit_zero(cdata, sizeof(cdata));
_libssh2_explicit_zero(&state, sizeof(state));
}
int
bcrypt_pbkdf(const char *pass, size_t passlen, const uint8_t *salt,
size_t saltlen,
uint8_t *key, size_t keylen, unsigned int rounds)
{
uint8_t sha2pass[SHA512_DIGEST_LENGTH];
uint8_t sha2salt[SHA512_DIGEST_LENGTH];
uint8_t out[BCRYPT_HASHSIZE];
uint8_t tmpout[BCRYPT_HASHSIZE];
uint8_t *countsalt;
size_t i, j, amt, stride;
uint32_t count;
size_t origkeylen = keylen;
libssh2_sha512_ctx ctx;
/* nothing crazy */
if(rounds < 1)
return -1;
if(passlen == 0 || saltlen == 0 || keylen == 0 ||
keylen > sizeof(out) * sizeof(out) || saltlen > 1<<20)
return -1;
countsalt = calloc(1, saltlen + 4);
if(countsalt == NULL)
return -1;
stride = (keylen + sizeof(out) - 1) / sizeof(out);
amt = (keylen + stride - 1) / stride;
memcpy(countsalt, salt, saltlen);
/* collapse password */
libssh2_sha512_init(&ctx);
libssh2_sha512_update(ctx, pass, passlen);
libssh2_sha512_final(ctx, sha2pass);
/* generate key, sizeof(out) at a time */
for(count = 1; keylen > 0; count++) {
countsalt[saltlen + 0] = (count >> 24) & 0xff;
countsalt[saltlen + 1] = (count >> 16) & 0xff;
countsalt[saltlen + 2] = (count >> 8) & 0xff;
countsalt[saltlen + 3] = count & 0xff;
/* first round, salt is salt */
libssh2_sha512_init(&ctx);
libssh2_sha512_update(ctx, countsalt, saltlen + 4);
libssh2_sha512_final(ctx, sha2salt);
bcrypt_hash(sha2pass, sha2salt, tmpout);
memcpy(out, tmpout, sizeof(out));
for(i = 1; i < rounds; i++) {
/* subsequent rounds, salt is previous output */
libssh2_sha512_init(&ctx);
libssh2_sha512_update(ctx, tmpout, sizeof(tmpout));
libssh2_sha512_final(ctx, sha2salt);
bcrypt_hash(sha2pass, sha2salt, tmpout);
for(j = 0; j < sizeof(out); j++)
out[j] ^= tmpout[j];
}
/*
* pbkdf2 deviation: output the key material non-linearly.
*/
amt = MINIMUM(amt, keylen);
for(i = 0; i < amt; i++) {
size_t dest = i * stride + (count - 1);
if(dest >= origkeylen) {
break;
}
key[dest] = out[i];
}
keylen -= i;
}
/* zap */
_libssh2_explicit_zero(out, sizeof(out));
free(countsalt);
return 0;
}
#endif /* HAVE_BCRYPT_PBKDF */
|
FriendSoftwareLabs/friendup
|
libs-ext/libssh2/src/bcrypt_pbkdf.c
|
C
|
agpl-3.0
| 6,092
|
/*
* Copyright 2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/evp.h>
#include <openssl/core_names.h>
#include "internal/provider_util.h"
void ossl_prov_cipher_reset(PROV_CIPHER *pc)
{
EVP_CIPHER_free(pc->alloc_cipher);
pc->alloc_cipher = NULL;
pc->cipher = NULL;
pc->engine = NULL;
}
int ossl_prov_cipher_copy(PROV_CIPHER *dst, const PROV_CIPHER *src)
{
if (src->alloc_cipher != NULL && !EVP_CIPHER_up_ref(src->alloc_cipher))
return 0;
dst->engine = src->engine;
dst->cipher = src->cipher;
dst->alloc_cipher = src->alloc_cipher;
return 1;
}
static int load_common(const OSSL_PARAM params[], const char **propquery,
ENGINE **engine)
{
const OSSL_PARAM *p;
*propquery = NULL;
p = OSSL_PARAM_locate_const(params, OSSL_ALG_PARAM_PROPERTIES);
if (p != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
*propquery = p->data;
}
*engine = NULL;
/* TODO legacy stuff, to be removed */
/* Inside the FIPS module, we don't support legacy ciphers */
#if !defined(FIPS_MODE) && !defined(OPENSSL_NO_ENGINE)
p = OSSL_PARAM_locate_const(params, "engine");
if (p != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
ENGINE_finish(*engine);
*engine = ENGINE_by_id(p->data);
if (*engine == NULL)
return 0;
}
#endif
return 1;
}
int ossl_prov_cipher_load_from_params(PROV_CIPHER *pc,
const OSSL_PARAM params[],
OPENSSL_CTX *ctx)
{
const OSSL_PARAM *p;
const char *propquery;
if (!load_common(params, &propquery, &pc->engine))
return 0;
p = OSSL_PARAM_locate_const(params, OSSL_ALG_PARAM_CIPHER);
if (p == NULL)
return 1;
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
EVP_CIPHER_free(pc->alloc_cipher);
pc->cipher = pc->alloc_cipher = EVP_CIPHER_fetch(ctx, p->data, propquery);
/* TODO legacy stuff, to be removed */
#ifndef FIPS_MODE /* Inside the FIPS module, we don't support legacy ciphers */
if (pc->cipher == NULL)
pc->cipher = EVP_get_cipherbyname(p->data);
#endif
return pc->cipher != NULL;
}
const EVP_CIPHER *ossl_prov_cipher_cipher(const PROV_CIPHER *pc)
{
return pc->cipher;
}
ENGINE *ossl_prov_cipher_engine(const PROV_CIPHER *pc)
{
return pc->engine;
}
void ossl_prov_digest_reset(PROV_DIGEST *pd)
{
EVP_MD_free(pd->alloc_md);
pd->alloc_md = NULL;
pd->md = NULL;
pd->engine = NULL;
}
int ossl_prov_digest_copy(PROV_DIGEST *dst, const PROV_DIGEST *src)
{
if (src->alloc_md != NULL && !EVP_MD_up_ref(src->alloc_md))
return 0;
dst->engine = src->engine;
dst->md = src->md;
dst->alloc_md = src->alloc_md;
return 1;
}
int ossl_prov_digest_load_from_params(PROV_DIGEST *pd,
const OSSL_PARAM params[],
OPENSSL_CTX *ctx)
{
const OSSL_PARAM *p;
const char *propquery;
if (!load_common(params, &propquery, &pd->engine))
return 0;
p = OSSL_PARAM_locate_const(params, OSSL_ALG_PARAM_DIGEST);
if (p == NULL)
return 1;
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
EVP_MD_free(pd->alloc_md);
pd->md = pd->alloc_md = EVP_MD_fetch(ctx, p->data, propquery);
/* TODO legacy stuff, to be removed */
#ifndef FIPS_MODE /* Inside the FIPS module, we don't support legacy digests */
if (pd->md == NULL)
pd->md = EVP_get_digestbyname(p->data);
#endif
return pd->md != NULL;
}
const EVP_MD *ossl_prov_digest_md(const PROV_DIGEST *pd)
{
return pd->md;
}
ENGINE *ossl_prov_digest_engine(const PROV_DIGEST *pd)
{
return pd->engine;
}
int ossl_prov_macctx_load_from_params(EVP_MAC_CTX **macctx,
const OSSL_PARAM params[],
const char *macname,
const char *ciphername,
const char *mdname,
OPENSSL_CTX *libctx)
{
const OSSL_PARAM *p;
OSSL_PARAM mac_params[5], *mp = mac_params;
const char *properties = NULL;
if (macname == NULL
&& (p = OSSL_PARAM_locate_const(params, OSSL_ALG_PARAM_MAC)) != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
macname = p->data;
}
if ((p = OSSL_PARAM_locate_const(params,
OSSL_ALG_PARAM_PROPERTIES)) != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
properties = p->data;
}
/* If we got a new mac name, we make a new EVP_MAC_CTX */
if (macname != NULL) {
EVP_MAC *mac = EVP_MAC_fetch(libctx, macname, properties);
EVP_MAC_CTX_free(*macctx);
*macctx = mac == NULL ? NULL : EVP_MAC_CTX_new(mac);
/* The context holds on to the MAC */
EVP_MAC_free(mac);
if (*macctx == NULL)
return 0;
}
/*
* If there is no MAC yet (and therefore, no MAC context), we ignore
* all other parameters.
*/
if (*macctx == NULL)
return 1;
if (mdname == NULL) {
if ((p = OSSL_PARAM_locate_const(params,
OSSL_ALG_PARAM_DIGEST)) != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
mdname = p->data;
}
}
if (ciphername == NULL) {
if ((p = OSSL_PARAM_locate_const(params,
OSSL_ALG_PARAM_CIPHER)) != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
ciphername = p->data;
}
}
if (mdname != NULL)
*mp++ = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
(char *)mdname, 0);
if (ciphername != NULL)
*mp++ = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
(char *)ciphername, 0);
if (properties != NULL)
*mp++ = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_PROPERTIES,
(char *)properties, 0);
#if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODE)
if ((p = OSSL_PARAM_locate_const(params, "engine")) != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
*mp++ = OSSL_PARAM_construct_utf8_string("engine",
p->data, p->data_size);
}
#endif
*mp = OSSL_PARAM_construct_end();
if (EVP_MAC_CTX_set_params(*macctx, mac_params))
return 1;
EVP_MAC_CTX_free(*macctx);
*macctx = NULL;
return 0;
}
|
FriendSoftwareLabs/friendup
|
libs-ext/openssl/providers/common/provider_util.c
|
C
|
agpl-3.0
| 7,174
|
/*
* qemu_domain.h: QEMU domain private state
*
* Copyright (C) 2006-2011 Red Hat, Inc.
* Copyright (C) 2006 Daniel P. Berrange
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* 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
*
* Author: Daniel P. Berrange <berrange@redhat.com>
*/
#include <config.h>
#include "qemu_domain.h"
#include "qemu_command.h"
#include "memory.h"
#include "logging.h"
#include "virterror_internal.h"
#include "c-ctype.h"
#include <sys/time.h>
#include <libxml/xpathInternals.h>
#define VIR_FROM_THIS VIR_FROM_QEMU
#define QEMU_NAMESPACE_HREF "http://libvirt.org/schemas/domain/qemu/1.0"
#define timeval_to_ms(tv) (((tv).tv_sec * 1000ull) + ((tv).tv_usec / 1000))
static void *qemuDomainObjPrivateAlloc(void)
{
qemuDomainObjPrivatePtr priv;
if (VIR_ALLOC(priv) < 0)
return NULL;
return priv;
}
static void qemuDomainObjPrivateFree(void *data)
{
qemuDomainObjPrivatePtr priv = data;
qemuDomainPCIAddressSetFree(priv->pciaddrs);
virDomainChrSourceDefFree(priv->monConfig);
VIR_FREE(priv->vcpupids);
/* This should never be non-NULL if we get here, but just in case... */
if (priv->mon) {
VIR_ERROR0(_("Unexpected QEMU monitor still active during domain deletion"));
qemuMonitorClose(priv->mon);
}
VIR_FREE(priv);
}
static int qemuDomainObjPrivateXMLFormat(virBufferPtr buf, void *data)
{
qemuDomainObjPrivatePtr priv = data;
const char *monitorpath;
/* priv->monitor_chr is set only for qemu */
if (priv->monConfig) {
switch (priv->monConfig->type) {
case VIR_DOMAIN_CHR_TYPE_UNIX:
monitorpath = priv->monConfig->data.nix.path;
break;
default:
case VIR_DOMAIN_CHR_TYPE_PTY:
monitorpath = priv->monConfig->data.file.path;
break;
}
virBufferEscapeString(buf, " <monitor path='%s'", monitorpath);
if (priv->monJSON)
virBufferAddLit(buf, " json='1'");
virBufferVSprintf(buf, " type='%s'/>\n",
virDomainChrTypeToString(priv->monConfig->type));
}
if (priv->nvcpupids) {
int i;
virBufferAddLit(buf, " <vcpus>\n");
for (i = 0 ; i < priv->nvcpupids ; i++) {
virBufferVSprintf(buf, " <vcpu pid='%d'/>\n", priv->vcpupids[i]);
}
virBufferAddLit(buf, " </vcpus>\n");
}
return 0;
}
static int qemuDomainObjPrivateXMLParse(xmlXPathContextPtr ctxt, void *data)
{
qemuDomainObjPrivatePtr priv = data;
char *monitorpath;
char *tmp;
int n, i;
xmlNodePtr *nodes = NULL;
if (VIR_ALLOC(priv->monConfig) < 0) {
virReportOOMError();
goto error;
}
if (!(monitorpath =
virXPathString("string(./monitor[1]/@path)", ctxt))) {
qemuReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("no monitor path"));
goto error;
}
tmp = virXPathString("string(./monitor[1]/@type)", ctxt);
if (tmp)
priv->monConfig->type = virDomainChrTypeFromString(tmp);
else
priv->monConfig->type = VIR_DOMAIN_CHR_TYPE_PTY;
VIR_FREE(tmp);
if (virXPathBoolean("count(./monitor[@json = '1']) > 0", ctxt)) {
priv->monJSON = 1;
} else {
priv->monJSON = 0;
}
switch (priv->monConfig->type) {
case VIR_DOMAIN_CHR_TYPE_PTY:
priv->monConfig->data.file.path = monitorpath;
break;
case VIR_DOMAIN_CHR_TYPE_UNIX:
priv->monConfig->data.nix.path = monitorpath;
break;
default:
VIR_FREE(monitorpath);
qemuReportError(VIR_ERR_INTERNAL_ERROR,
_("unsupported monitor type '%s'"),
virDomainChrTypeToString(priv->monConfig->type));
goto error;
}
n = virXPathNodeSet("./vcpus/vcpu", ctxt, &nodes);
if (n < 0)
goto error;
if (n) {
priv->nvcpupids = n;
if (VIR_REALLOC_N(priv->vcpupids, priv->nvcpupids) < 0) {
virReportOOMError();
goto error;
}
for (i = 0 ; i < n ; i++) {
char *pidstr = virXMLPropString(nodes[i], "pid");
if (!pidstr)
goto error;
if (virStrToLong_i(pidstr, NULL, 10, &(priv->vcpupids[i])) < 0) {
VIR_FREE(pidstr);
goto error;
}
VIR_FREE(pidstr);
}
VIR_FREE(nodes);
}
return 0;
error:
virDomainChrSourceDefFree(priv->monConfig);
priv->monConfig = NULL;
VIR_FREE(nodes);
return -1;
}
static void
qemuDomainDefNamespaceFree(void *nsdata)
{
qemuDomainCmdlineDefPtr cmd = nsdata;
unsigned int i;
if (!cmd)
return;
for (i = 0; i < cmd->num_args; i++)
VIR_FREE(cmd->args[i]);
for (i = 0; i < cmd->num_env; i++) {
VIR_FREE(cmd->env_name[i]);
VIR_FREE(cmd->env_value[i]);
}
VIR_FREE(cmd->args);
VIR_FREE(cmd->env_name);
VIR_FREE(cmd->env_value);
VIR_FREE(cmd);
}
static int
qemuDomainDefNamespaceParse(xmlDocPtr xml,
xmlNodePtr root,
xmlXPathContextPtr ctxt,
void **data)
{
qemuDomainCmdlineDefPtr cmd = NULL;
xmlNsPtr ns;
xmlNodePtr *nodes = NULL;
int n, i;
ns = xmlSearchNs(xml, root, BAD_CAST "qemu");
if (!ns)
/* this is fine; it just means there was no qemu namespace listed */
return 0;
if (STRNEQ((const char *)ns->href, QEMU_NAMESPACE_HREF)) {
qemuReportError(VIR_ERR_INTERNAL_ERROR,
_("Found namespace '%s' doesn't match expected '%s'"),
ns->href, QEMU_NAMESPACE_HREF);
return -1;
}
if (xmlXPathRegisterNs(ctxt, ns->prefix, ns->href) < 0) {
qemuReportError(VIR_ERR_INTERNAL_ERROR,
_("Failed to register xml namespace '%s'"), ns->href);
return -1;
}
if (VIR_ALLOC(cmd) < 0) {
virReportOOMError();
return -1;
}
/* first handle the extra command-line arguments */
n = virXPathNodeSet("./qemu:commandline/qemu:arg", ctxt, &nodes);
if (n < 0)
/* virXPathNodeSet already set the error */
goto error;
if (n && VIR_ALLOC_N(cmd->args, n) < 0)
goto no_memory;
for (i = 0; i < n; i++) {
cmd->args[cmd->num_args] = virXMLPropString(nodes[i], "value");
if (cmd->args[cmd->num_args] == NULL) {
qemuReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("No qemu command-line argument specified"));
goto error;
}
cmd->num_args++;
}
VIR_FREE(nodes);
/* now handle the extra environment variables */
n = virXPathNodeSet("./qemu:commandline/qemu:env", ctxt, &nodes);
if (n < 0)
/* virXPathNodeSet already set the error */
goto error;
if (n && VIR_ALLOC_N(cmd->env_name, n) < 0)
goto no_memory;
if (n && VIR_ALLOC_N(cmd->env_value, n) < 0)
goto no_memory;
for (i = 0; i < n; i++) {
char *tmp;
tmp = virXMLPropString(nodes[i], "name");
if (tmp == NULL) {
qemuReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("No qemu environment name specified"));
goto error;
}
if (tmp[0] == '\0') {
qemuReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("Empty qemu environment name specified"));
goto error;
}
if (!c_isalpha(tmp[0]) && tmp[0] != '_') {
qemuReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("Invalid environment name, it must begin with a letter or underscore"));
goto error;
}
if (strspn(tmp, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_") != strlen(tmp)) {
qemuReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("Invalid environment name, it must contain only alphanumerics and underscore"));
goto error;
}
cmd->env_name[cmd->num_env] = tmp;
cmd->env_value[cmd->num_env] = virXMLPropString(nodes[i], "value");
/* a NULL value for command is allowed, since it might be empty */
cmd->num_env++;
}
VIR_FREE(nodes);
*data = cmd;
return 0;
no_memory:
virReportOOMError();
error:
VIR_FREE(nodes);
qemuDomainDefNamespaceFree(cmd);
return -1;
}
static int
qemuDomainDefNamespaceFormatXML(virBufferPtr buf,
void *nsdata)
{
qemuDomainCmdlineDefPtr cmd = nsdata;
unsigned int i;
if (!cmd->num_args && !cmd->num_env)
return 0;
virBufferAddLit(buf, " <qemu:commandline>\n");
for (i = 0; i < cmd->num_args; i++)
virBufferEscapeString(buf, " <qemu:arg value='%s'/>\n",
cmd->args[i]);
for (i = 0; i < cmd->num_env; i++) {
virBufferVSprintf(buf, " <qemu:env name='%s'", cmd->env_name[i]);
if (cmd->env_value[i])
virBufferEscapeString(buf, " value='%s'", cmd->env_value[i]);
virBufferAddLit(buf, "/>\n");
}
virBufferAddLit(buf, " </qemu:commandline>\n");
return 0;
}
static const char *
qemuDomainDefNamespaceHref(void)
{
return "xmlns:qemu='" QEMU_NAMESPACE_HREF "'";
}
void qemuDomainSetPrivateDataHooks(virCapsPtr caps)
{
/* Domain XML parser hooks */
caps->privateDataAllocFunc = qemuDomainObjPrivateAlloc;
caps->privateDataFreeFunc = qemuDomainObjPrivateFree;
caps->privateDataXMLFormat = qemuDomainObjPrivateXMLFormat;
caps->privateDataXMLParse = qemuDomainObjPrivateXMLParse;
}
void qemuDomainSetNamespaceHooks(virCapsPtr caps)
{
/* Domain Namespace XML parser hooks */
caps->ns.parse = qemuDomainDefNamespaceParse;
caps->ns.free = qemuDomainDefNamespaceFree;
caps->ns.format = qemuDomainDefNamespaceFormatXML;
caps->ns.href = qemuDomainDefNamespaceHref;
}
/*
* obj must be locked before calling, qemud_driver must NOT be locked
*
* This must be called by anything that will change the VM state
* in any way, or anything that will use the QEMU monitor.
*
* Upon successful return, the object will have its ref count increased,
* successful calls must be followed by EndJob eventually
*/
/* Give up waiting for mutex after 30 seconds */
#define QEMU_JOB_WAIT_TIME (1000ull * 30)
int qemuDomainObjBeginJob(virDomainObjPtr obj)
{
qemuDomainObjPrivatePtr priv = obj->privateData;
struct timeval now;
unsigned long long then;
if (gettimeofday(&now, NULL) < 0) {
virReportSystemError(errno, "%s",
_("cannot get time of day"));
return -1;
}
then = timeval_to_ms(now) + QEMU_JOB_WAIT_TIME;
virDomainObjRef(obj);
while (priv->jobActive) {
if (virCondWaitUntil(&priv->jobCond, &obj->lock, then) < 0) {
virDomainObjUnref(obj);
if (errno == ETIMEDOUT)
qemuReportError(VIR_ERR_OPERATION_TIMEOUT,
"%s", _("cannot acquire state change lock"));
else
virReportSystemError(errno,
"%s", _("cannot acquire job mutex"));
return -1;
}
}
priv->jobActive = QEMU_JOB_UNSPECIFIED;
priv->jobSignals = 0;
memset(&priv->jobSignalsData, 0, sizeof(priv->jobSignalsData));
priv->jobStart = timeval_to_ms(now);
memset(&priv->jobInfo, 0, sizeof(priv->jobInfo));
return 0;
}
/*
* obj must be locked before calling, qemud_driver must be locked
*
* This must be called by anything that will change the VM state
* in any way, or anything that will use the QEMU monitor.
*/
int qemuDomainObjBeginJobWithDriver(struct qemud_driver *driver,
virDomainObjPtr obj)
{
qemuDomainObjPrivatePtr priv = obj->privateData;
struct timeval now;
unsigned long long then;
if (gettimeofday(&now, NULL) < 0) {
virReportSystemError(errno, "%s",
_("cannot get time of day"));
return -1;
}
then = timeval_to_ms(now) + QEMU_JOB_WAIT_TIME;
virDomainObjRef(obj);
qemuDriverUnlock(driver);
while (priv->jobActive) {
if (virCondWaitUntil(&priv->jobCond, &obj->lock, then) < 0) {
virDomainObjUnref(obj);
if (errno == ETIMEDOUT)
qemuReportError(VIR_ERR_OPERATION_TIMEOUT,
"%s", _("cannot acquire state change lock"));
else
virReportSystemError(errno,
"%s", _("cannot acquire job mutex"));
qemuDriverLock(driver);
return -1;
}
}
priv->jobActive = QEMU_JOB_UNSPECIFIED;
priv->jobSignals = 0;
memset(&priv->jobSignalsData, 0, sizeof(priv->jobSignalsData));
priv->jobStart = timeval_to_ms(now);
memset(&priv->jobInfo, 0, sizeof(priv->jobInfo));
virDomainObjUnlock(obj);
qemuDriverLock(driver);
virDomainObjLock(obj);
return 0;
}
/*
* obj must be locked before calling, qemud_driver does not matter
*
* To be called after completing the work associated with the
* earlier qemuDomainBeginJob() call
*
* Returns remaining refcount on 'obj', maybe 0 to indicated it
* was deleted
*/
int qemuDomainObjEndJob(virDomainObjPtr obj)
{
qemuDomainObjPrivatePtr priv = obj->privateData;
priv->jobActive = QEMU_JOB_NONE;
priv->jobSignals = 0;
memset(&priv->jobSignalsData, 0, sizeof(priv->jobSignalsData));
priv->jobStart = 0;
memset(&priv->jobInfo, 0, sizeof(priv->jobInfo));
virCondSignal(&priv->jobCond);
return virDomainObjUnref(obj);
}
/*
* obj must be locked before calling, qemud_driver must be unlocked
*
* To be called immediately before any QEMU monitor API call
* Must have already called qemuDomainObjBeginJob(), and checked
* that the VM is still active.
*
* To be followed with qemuDomainObjExitMonitor() once complete
*/
void qemuDomainObjEnterMonitor(virDomainObjPtr obj)
{
qemuDomainObjPrivatePtr priv = obj->privateData;
qemuMonitorLock(priv->mon);
qemuMonitorRef(priv->mon);
virDomainObjUnlock(obj);
}
/* obj must NOT be locked before calling, qemud_driver must be unlocked
*
* Should be paired with an earlier qemuDomainObjEnterMonitor() call
*/
void qemuDomainObjExitMonitor(virDomainObjPtr obj)
{
qemuDomainObjPrivatePtr priv = obj->privateData;
int refs;
refs = qemuMonitorUnref(priv->mon);
if (refs > 0)
qemuMonitorUnlock(priv->mon);
virDomainObjLock(obj);
if (refs == 0) {
priv->mon = NULL;
}
}
/*
* obj must be locked before calling, qemud_driver must be locked
*
* To be called immediately before any QEMU monitor API call
* Must have already called qemuDomainObjBeginJob().
*
* To be followed with qemuDomainObjExitMonitorWithDriver() once complete
*/
void qemuDomainObjEnterMonitorWithDriver(struct qemud_driver *driver,
virDomainObjPtr obj)
{
qemuDomainObjPrivatePtr priv = obj->privateData;
qemuMonitorLock(priv->mon);
qemuMonitorRef(priv->mon);
virDomainObjUnlock(obj);
qemuDriverUnlock(driver);
}
/* obj must NOT be locked before calling, qemud_driver must be unlocked,
* and will be locked after returning
*
* Should be paired with an earlier qemuDomainObjEnterMonitorWithDriver() call
*/
void qemuDomainObjExitMonitorWithDriver(struct qemud_driver *driver,
virDomainObjPtr obj)
{
qemuDomainObjPrivatePtr priv = obj->privateData;
int refs;
refs = qemuMonitorUnref(priv->mon);
if (refs > 0)
qemuMonitorUnlock(priv->mon);
qemuDriverLock(driver);
virDomainObjLock(obj);
if (refs == 0) {
priv->mon = NULL;
}
}
void qemuDomainObjEnterRemoteWithDriver(struct qemud_driver *driver,
virDomainObjPtr obj)
{
virDomainObjRef(obj);
virDomainObjUnlock(obj);
qemuDriverUnlock(driver);
}
void qemuDomainObjExitRemoteWithDriver(struct qemud_driver *driver,
virDomainObjPtr obj)
{
qemuDriverLock(driver);
virDomainObjLock(obj);
virDomainObjUnref(obj);
}
|
sshah-solarflare/Libvirt-PCI-passthrough-
|
src/qemu/qemu_domain.c
|
C
|
lgpl-2.1
| 17,049
|
/*
aim_rxqueue.c
This file contains the management routines for the receive
(incoming packet) queue. The actual packet handlers are in
aim_rxhandlers.c.
*/
#include "aim.h"
/*
This is a modified read() to make SURE we get the number
of bytes we are told to, otherwise block.
*/
int Read(int fd, u_char *buf, int len)
{
int i = 0;
int j = 0;
while ((i < len) && (!(i < 0)))
{
j = read(fd, &(buf[i]), len-i);
if ( (j < 0) && (errno != EAGAIN))
return -errno; /* fail */
else
i += j; /* success, continue */
}
#if 0
printf("\nRead Block: (%d/%04x)\n", len, len);
printf("\t");
for (j = 0; j < len; j++)
{
if (j % 8 == 0)
printf("\n\t");
if (buf[j] >= ' ' && buf[j] < 127)
printf("%c=%02x ",buf[j], buf[j]);
else
printf("0x%02x ", buf[j]);
}
printf("\n\n");
#endif
return i;
}
/*
struct command_struct *
get_generic(
struct connection_info struct *,
struct command_struct *
)
Grab as many command sequences as we can off the socket, and enqueue
each command in the incoming event queue in a seperate struct.
*/
int aim_get_command(void)
{
int i, readgood, j, isav, err;
int s;
fd_set fds;
struct timeval tv;
char generic[6];
struct command_rx_struct *workingStruct = NULL;
struct command_rx_struct *workingPtr = NULL;
struct aim_conn_t *conn = NULL;
#if debug > 0
printf("Reading generic/unknown response...");
#endif
/* dont wait at all (ie, never call this unless something is there) */
tv.tv_sec = 0;
tv.tv_usec = 0;
conn = aim_select(&tv);
if (conn==NULL)
return 0; /* nothing waiting */
s = conn->fd;
FD_ZERO(&fds);
FD_SET(s, &fds);
tv.tv_sec = 0; /* wait, but only for 10us */
tv.tv_usec = 10;
generic[0] = 0x00;
readgood = 0;
i = 0;
j = 0;
/* read first 6 bytes (the FLAP header only) off the socket */
while ( (select(s+1, &fds, NULL, NULL, &tv) == 1) && (i < 6))
{
if ((err = Read(s, &(generic[i]), 1)) < 0)
{
/* error is probably not recoverable...(must be a pessimistic day) */
aim_conn_close(conn);
return err;
}
if (readgood == 0)
{
if (generic[i] == 0x2a)
{
readgood = 1;
#if debug > 1
printf("%x ", generic[i]);
fflush(stdout);
#endif
i++;
}
else
{
#if debug > 1
printf("skipping 0x%d ", generic[i]);
fflush(stdout);
#endif
j++;
}
}
else
{
#if debug > 1
printf("%x ", generic[i]);
#endif
i++;
}
FD_ZERO(&fds);
FD_SET(s, &fds);
tv.tv_sec= 2;
tv.tv_usec= 2;
}
if (generic[0] != 0x2a)
{
/* this really shouldn't happen, since the main loop
select() should protect us from entering this function
without data waiting */
printf("Bad incoming data!");
return -1;
}
isav = i;
/* allocate a new struct */
workingStruct = (struct command_rx_struct *) malloc(sizeof(struct command_rx_struct));
workingStruct->lock = 1; /* lock the struct */
/* store type -- byte 2 */
workingStruct->type = (char) generic[1];
/* store seqnum -- bytes 3 and 4 */
workingStruct->seqnum = ( (( (unsigned int) generic[2]) & 0xFF) << 8);
workingStruct->seqnum += ( (unsigned int) generic[3]) & 0xFF;
/* store commandlen -- bytes 5 and 6 */
workingStruct->commandlen = ( (( (unsigned int) generic[4]) & 0xFF ) << 8);
workingStruct->commandlen += ( (unsigned int) generic[5]) & 0xFF;
/* malloc for data portion */
workingStruct->data = (char *) malloc(workingStruct->commandlen);
/* read the data portion of the packet */
i = Read(s, workingStruct->data, workingStruct->commandlen);
if (i < 0)
{
aim_conn_close(conn);
return i;
}
#if debug > 0
printf(" done. (%db+%db read, %db skipped)\n", isav, i, j);
#endif
workingStruct->conn = conn;
workingStruct->next = NULL; /* this will always be at the bottom */
workingStruct->lock = 0; /* unlock */
/* enqueue this packet */
if (aim_queue_incoming == NULL)
aim_queue_incoming = workingStruct;
else
{
workingPtr = aim_queue_incoming;
while (workingPtr->next != NULL)
workingPtr = workingPtr->next;
workingPtr->next = workingStruct;
}
return 0;
}
/*
purge_rxqueue()
This is just what it sounds. It purges the receive (rx) queue of
all handled commands. This is normally called from inside
aim_rxdispatch() after it's processed all the commands in the queue.
*/
struct command_rx_struct *aim_purge_rxqueue(struct command_rx_struct *queue)
{
int i = 0;
struct command_rx_struct *workingPtr = NULL;
struct command_rx_struct *workingPtr2 = NULL;
workingPtr = queue;
if (queue == NULL)
{
return queue;
}
else if (queue->next == NULL)
{
if (queue->handled == 1)
{
workingPtr2 = queue;
queue = NULL;
free(workingPtr2->data);
free(workingPtr2);
}
return queue;
}
else
{
for (i = 0; workingPtr != NULL; i++)
{
if (workingPtr->next->handled == 1)
{
/* save struct */
workingPtr2 = workingPtr->next;
/* dequeue */
workingPtr->next = workingPtr2->next;
/* free */
free(workingPtr2->data);
free(workingPtr2);
}
workingPtr = workingPtr->next;
}
}
return queue;
}
|
midendian/libfaim
|
deprecated/aim_rxqueue.orig.c
|
C
|
lgpl-2.1
| 5,386
|
/* Copyright (C) 2008-2011 D. V. Wiebe
*
***************************************************************************
*
* This file is part of the GetData project.
*
* GetData is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* GetData 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 GetData; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* Attempt to read INT32 as INT64 */
#include "test.h"
#include <inttypes.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
int main(void)
{
const char *filedir = "dirfile";
const char *format = "dirfile/format";
const char *data = "dirfile/data";
const char *format_data = "data RAW INT32 8\n";
int32_t data_data[256];
int64_t c[8];
int fd, i, n, error, r = 0;
DIRFILE *D;
memset(c, 0, 8);
rmdirfile();
mkdir(filedir, 0777);
for (fd = 0; fd < 256; ++fd)
data_data[fd] = fd;
fd = open(format, O_CREAT | O_EXCL | O_WRONLY, 0666);
write(fd, format_data, strlen(format_data));
close(fd);
fd = open(data, O_CREAT | O_EXCL | O_WRONLY | O_BINARY, 0666);
write(fd, data_data, 256 * sizeof(int32_t));
close(fd);
D = gd_open(filedir, GD_RDONLY | GD_VERBOSE);
n = gd_getdata(D, "data", 5, 0, 1, 0, GD_INT64, c);
error = gd_error(D);
gd_close(D);
unlink(data);
unlink(format);
rmdir(filedir);
CHECKI(error, 0);
CHECKI(n, 8);
for (i = 0; i < 8; ++i)
CHECKIi(i,c[i], 40 + i);
return r;
}
|
syntheticpp/dirfile
|
test/convert_int32_int64.c
|
C
|
lgpl-2.1
| 2,026
|
/*
* Copyright (C) 2007-2010 Red Hat, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* 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
*
* Authors:
* Mark McLoughlin <markmc@redhat.com>
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <limits.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#ifdef HAVE_PATHS_H
# include <paths.h>
#endif
#include "internal.h"
#include "iptables.h"
#include "util.h"
#include "memory.h"
#include "virterror_internal.h"
#include "logging.h"
enum {
ADD = 0,
REMOVE
};
typedef struct
{
char *table;
char *chain;
} iptRules;
struct _iptablesContext
{
iptRules *input_filter;
iptRules *forward_filter;
iptRules *nat_postrouting;
};
static void
iptRulesFree(iptRules *rules)
{
VIR_FREE(rules->table);
VIR_FREE(rules->chain);
VIR_FREE(rules);
}
static iptRules *
iptRulesNew(const char *table,
const char *chain)
{
iptRules *rules;
if (VIR_ALLOC(rules) < 0)
return NULL;
if (!(rules->table = strdup(table)))
goto error;
if (!(rules->chain = strdup(chain)))
goto error;
return rules;
error:
iptRulesFree(rules);
return NULL;
}
static int ATTRIBUTE_SENTINEL
iptablesAddRemoveRule(iptRules *rules, int action, const char *arg, ...)
{
va_list args;
int retval = ENOMEM;
const char **argv;
const char *s;
int n;
n = 1 + /* /sbin/iptables */
2 + /* --table foo */
2 + /* --insert bar */
1; /* arg */
va_start(args, arg);
while (va_arg(args, const char *))
n++;
va_end(args);
if (VIR_ALLOC_N(argv, n + 1) < 0)
goto error;
n = 0;
if (!(argv[n++] = strdup(IPTABLES_PATH)))
goto error;
if (!(argv[n++] = strdup("--table")))
goto error;
if (!(argv[n++] = strdup(rules->table)))
goto error;
if (!(argv[n++] = strdup(action == ADD ? "--insert" : "--delete")))
goto error;
if (!(argv[n++] = strdup(rules->chain)))
goto error;
if (!(argv[n++] = strdup(arg)))
goto error;
va_start(args, arg);
while ((s = va_arg(args, const char *))) {
if (!(argv[n++] = strdup(s))) {
va_end(args);
goto error;
}
}
va_end(args);
if (virRun(argv, NULL) < 0) {
retval = errno;
goto error;
}
retval = 0;
error:
if (argv) {
n = 0;
while (argv[n])
VIR_FREE(argv[n++]);
VIR_FREE(argv);
}
return retval;
}
/**
* iptablesContextNew:
*
* Create a new IPtable context
*
* Returns a pointer to the new structure or NULL in case of error
*/
iptablesContext *
iptablesContextNew(void)
{
iptablesContext *ctx;
if (VIR_ALLOC(ctx) < 0)
return NULL;
if (!(ctx->input_filter = iptRulesNew("filter", "INPUT")))
goto error;
if (!(ctx->forward_filter = iptRulesNew("filter", "FORWARD")))
goto error;
if (!(ctx->nat_postrouting = iptRulesNew("nat", "POSTROUTING")))
goto error;
return ctx;
error:
iptablesContextFree(ctx);
return NULL;
}
/**
* iptablesContextFree:
* @ctx: pointer to the IP table context
*
* Free the resources associated with an IP table context
*/
void
iptablesContextFree(iptablesContext *ctx)
{
if (ctx->input_filter)
iptRulesFree(ctx->input_filter);
if (ctx->forward_filter)
iptRulesFree(ctx->forward_filter);
if (ctx->nat_postrouting)
iptRulesFree(ctx->nat_postrouting);
VIR_FREE(ctx);
}
static int
iptablesInput(iptablesContext *ctx,
const char *iface,
int port,
int action,
int tcp)
{
char portstr[32];
snprintf(portstr, sizeof(portstr), "%d", port);
portstr[sizeof(portstr) - 1] = '\0';
return iptablesAddRemoveRule(ctx->input_filter,
action,
"--in-interface", iface,
"--protocol", tcp ? "tcp" : "udp",
"--destination-port", portstr,
"--jump", "ACCEPT",
NULL);
}
/**
* iptablesAddTcpInput:
* @ctx: pointer to the IP table context
* @iface: the interface name
* @port: the TCP port to add
*
* Add an input to the IP table allowing access to the given @port on
* the given @iface interface for TCP packets
*
* Returns 0 in case of success or an error code in case of error
*/
int
iptablesAddTcpInput(iptablesContext *ctx,
const char *iface,
int port)
{
return iptablesInput(ctx, iface, port, ADD, 1);
}
/**
* iptablesRemoveTcpInput:
* @ctx: pointer to the IP table context
* @iface: the interface name
* @port: the TCP port to remove
*
* Removes an input from the IP table, hence forbidding access to the given
* @port on the given @iface interface for TCP packets
*
* Returns 0 in case of success or an error code in case of error
*/
int
iptablesRemoveTcpInput(iptablesContext *ctx,
const char *iface,
int port)
{
return iptablesInput(ctx, iface, port, REMOVE, 1);
}
/**
* iptablesAddUdpInput:
* @ctx: pointer to the IP table context
* @iface: the interface name
* @port: the UDP port to add
*
* Add an input to the IP table allowing access to the given @port on
* the given @iface interface for UDP packets
*
* Returns 0 in case of success or an error code in case of error
*/
int
iptablesAddUdpInput(iptablesContext *ctx,
const char *iface,
int port)
{
return iptablesInput(ctx, iface, port, ADD, 0);
}
/**
* iptablesRemoveUdpInput:
* @ctx: pointer to the IP table context
* @iface: the interface name
* @port: the UDP port to remove
*
* Removes an input from the IP table, hence forbidding access to the given
* @port on the given @iface interface for UDP packets
*
* Returns 0 in case of success or an error code in case of error
*/
int
iptablesRemoveUdpInput(iptablesContext *ctx,
const char *iface,
int port)
{
return iptablesInput(ctx, iface, port, REMOVE, 0);
}
/* Allow all traffic coming from the bridge, with a valid network address
* to proceed to WAN
*/
static int
iptablesForwardAllowOut(iptablesContext *ctx,
const char *network,
const char *iface,
const char *physdev,
int action)
{
if (physdev && physdev[0]) {
return iptablesAddRemoveRule(ctx->forward_filter,
action,
"--source", network,
"--in-interface", iface,
"--out-interface", physdev,
"--jump", "ACCEPT",
NULL);
} else {
return iptablesAddRemoveRule(ctx->forward_filter,
action,
"--source", network,
"--in-interface", iface,
"--jump", "ACCEPT",
NULL);
}
}
/**
* iptablesAddForwardAllowOut:
* @ctx: pointer to the IP table context
* @network: the source network name
* @iface: the source interface name
* @physdev: the physical output device
*
* Add a rule to the IP table context to allow the traffic for the
* network @network via interface @iface to be forwarded to
* @physdev device. This allow the outbound traffic on a bridge.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesAddForwardAllowOut(iptablesContext *ctx,
const char *network,
const char *iface,
const char *physdev)
{
return iptablesForwardAllowOut(ctx, network, iface, physdev, ADD);
}
/**
* iptablesRemoveForwardAllowOut:
* @ctx: pointer to the IP table context
* @network: the source network name
* @iface: the source interface name
* @physdev: the physical output device
*
* Remove a rule from the IP table context hence forbidding forwarding
* of the traffic for the network @network via interface @iface
* to the @physdev device output. This stops the outbound traffic on a bridge.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesRemoveForwardAllowOut(iptablesContext *ctx,
const char *network,
const char *iface,
const char *physdev)
{
return iptablesForwardAllowOut(ctx, network, iface, physdev, REMOVE);
}
/* Allow all traffic destined to the bridge, with a valid network address
* and associated with an existing connection
*/
static int
iptablesForwardAllowRelatedIn(iptablesContext *ctx,
const char *network,
const char *iface,
const char *physdev,
int action)
{
if (physdev && physdev[0]) {
return iptablesAddRemoveRule(ctx->forward_filter,
action,
"--destination", network,
"--in-interface", physdev,
"--out-interface", iface,
"--match", "state",
"--state", "ESTABLISHED,RELATED",
"--jump", "ACCEPT",
NULL);
} else {
return iptablesAddRemoveRule(ctx->forward_filter,
action,
"--destination", network,
"--out-interface", iface,
"--match", "state",
"--state", "ESTABLISHED,RELATED",
"--jump", "ACCEPT",
NULL);
}
}
/**
* iptablesAddForwardAllowRelatedIn:
* @ctx: pointer to the IP table context
* @network: the source network name
* @iface: the output interface name
* @physdev: the physical input device or NULL
*
* Add rules to the IP table context to allow the traffic for the
* network @network on @physdev device to be forwarded to
* interface @iface, if it is part of an existing connection.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesAddForwardAllowRelatedIn(iptablesContext *ctx,
const char *network,
const char *iface,
const char *physdev)
{
return iptablesForwardAllowRelatedIn(ctx, network, iface, physdev, ADD);
}
/**
* iptablesRemoveForwardAllowRelatedIn:
* @ctx: pointer to the IP table context
* @network: the source network name
* @iface: the output interface name
* @physdev: the physical input device or NULL
*
* Remove rules from the IP table context hence forbidding the traffic for
* network @network on @physdev device to be forwarded to
* interface @iface, if it is part of an existing connection.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesRemoveForwardAllowRelatedIn(iptablesContext *ctx,
const char *network,
const char *iface,
const char *physdev)
{
return iptablesForwardAllowRelatedIn(ctx, network, iface, physdev, REMOVE);
}
/* Allow all traffic destined to the bridge, with a valid network address
*/
static int
iptablesForwardAllowIn(iptablesContext *ctx,
const char *network,
const char *iface,
const char *physdev,
int action)
{
if (physdev && physdev[0]) {
return iptablesAddRemoveRule(ctx->forward_filter,
action,
"--destination", network,
"--in-interface", physdev,
"--out-interface", iface,
"--jump", "ACCEPT",
NULL);
} else {
return iptablesAddRemoveRule(ctx->forward_filter,
action,
"--destination", network,
"--out-interface", iface,
"--jump", "ACCEPT",
NULL);
}
}
/**
* iptablesAddForwardAllowIn:
* @ctx: pointer to the IP table context
* @network: the source network name
* @iface: the output interface name
* @physdev: the physical input device or NULL
*
* Add rules to the IP table context to allow the traffic for the
* network @network on @physdev device to be forwarded to
* interface @iface. This allow the inbound traffic on a bridge.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesAddForwardAllowIn(iptablesContext *ctx,
const char *network,
const char *iface,
const char *physdev)
{
return iptablesForwardAllowIn(ctx, network, iface, physdev, ADD);
}
/**
* iptablesRemoveForwardAllowIn:
* @ctx: pointer to the IP table context
* @network: the source network name
* @iface: the output interface name
* @physdev: the physical input device or NULL
*
* Remove rules from the IP table context hence forbidding the traffic for
* network @network on @physdev device to be forwarded to
* interface @iface. This stops the inbound traffic on a bridge.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesRemoveForwardAllowIn(iptablesContext *ctx,
const char *network,
const char *iface,
const char *physdev)
{
return iptablesForwardAllowIn(ctx, network, iface, physdev, REMOVE);
}
/* Allow all traffic between guests on the same bridge,
* with a valid network address
*/
static int
iptablesForwardAllowCross(iptablesContext *ctx,
const char *iface,
int action)
{
return iptablesAddRemoveRule(ctx->forward_filter,
action,
"--in-interface", iface,
"--out-interface", iface,
"--jump", "ACCEPT",
NULL);
}
/**
* iptablesAddForwardAllowCross:
* @ctx: pointer to the IP table context
* @iface: the input/output interface name
*
* Add rules to the IP table context to allow traffic to cross that
* interface. It allows all traffic between guests on the same bridge
* represented by that interface.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesAddForwardAllowCross(iptablesContext *ctx,
const char *iface) {
return iptablesForwardAllowCross(ctx, iface, ADD);
}
/**
* iptablesRemoveForwardAllowCross:
* @ctx: pointer to the IP table context
* @iface: the input/output interface name
*
* Remove rules to the IP table context to block traffic to cross that
* interface. It forbids traffic between guests on the same bridge
* represented by that interface.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesRemoveForwardAllowCross(iptablesContext *ctx,
const char *iface) {
return iptablesForwardAllowCross(ctx, iface, REMOVE);
}
/* Drop all traffic trying to forward from the bridge.
* ie the bridge is the in interface
*/
static int
iptablesForwardRejectOut(iptablesContext *ctx,
const char *iface,
int action)
{
return iptablesAddRemoveRule(ctx->forward_filter,
action,
"--in-interface", iface,
"--jump", "REJECT",
NULL);
}
/**
* iptablesAddForwardRejectOut:
* @ctx: pointer to the IP table context
* @iface: the output interface name
*
* Add rules to the IP table context to forbid all traffic to that
* interface. It forbids forwarding from the bridge to that interface.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesAddForwardRejectOut(iptablesContext *ctx,
const char *iface)
{
return iptablesForwardRejectOut(ctx, iface, ADD);
}
/**
* iptablesRemoveForwardRejectOut:
* @ctx: pointer to the IP table context
* @iface: the output interface name
*
* Remove rules from the IP table context forbidding all traffic to that
* interface. It reallow forwarding from the bridge to that interface.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesRemoveForwardRejectOut(iptablesContext *ctx,
const char *iface)
{
return iptablesForwardRejectOut(ctx, iface, REMOVE);
}
/* Drop all traffic trying to forward to the bridge.
* ie the bridge is the out interface
*/
static int
iptablesForwardRejectIn(iptablesContext *ctx,
const char *iface,
int action)
{
return iptablesAddRemoveRule(ctx->forward_filter,
action,
"--out-interface", iface,
"--jump", "REJECT",
NULL);
}
/**
* iptablesAddForwardRejectIn:
* @ctx: pointer to the IP table context
* @iface: the input interface name
*
* Add rules to the IP table context to forbid all traffic from that
* interface. It forbids forwarding from that interface to the bridge.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesAddForwardRejectIn(iptablesContext *ctx,
const char *iface)
{
return iptablesForwardRejectIn(ctx, iface, ADD);
}
/**
* iptablesRemoveForwardRejectIn:
* @ctx: pointer to the IP table context
* @iface: the input interface name
*
* Remove rules from the IP table context forbidding all traffic from that
* interface. It allows forwarding from that interface to the bridge.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesRemoveForwardRejectIn(iptablesContext *ctx,
const char *iface)
{
return iptablesForwardRejectIn(ctx, iface, REMOVE);
}
/* Masquerade all traffic coming from the network associated
* with the bridge
*/
static int
iptablesForwardMasquerade(iptablesContext *ctx,
const char *network,
const char *physdev,
int action)
{
if (physdev && physdev[0]) {
return iptablesAddRemoveRule(ctx->nat_postrouting,
action,
"--source", network,
"!", "--destination", network,
"--out-interface", physdev,
"--jump", "MASQUERADE",
NULL);
} else {
return iptablesAddRemoveRule(ctx->nat_postrouting,
action,
"--source", network,
"!", "--destination", network,
"--jump", "MASQUERADE",
NULL);
}
}
/**
* iptablesAddForwardMasquerade:
* @ctx: pointer to the IP table context
* @network: the source network name
* @physdev: the physical input device or NULL
*
* Add rules to the IP table context to allow masquerading
* network @network on @physdev. This allow the bridge to
* masquerade for that network (on @physdev).
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesAddForwardMasquerade(iptablesContext *ctx,
const char *network,
const char *physdev)
{
return iptablesForwardMasquerade(ctx, network, physdev, ADD);
}
/**
* iptablesRemoveForwardMasquerade:
* @ctx: pointer to the IP table context
* @network: the source network name
* @physdev: the physical input device or NULL
*
* Remove rules from the IP table context to stop masquerading
* network @network on @physdev. This stops the bridge from
* masquerading for that network (on @physdev).
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesRemoveForwardMasquerade(iptablesContext *ctx,
const char *network,
const char *physdev)
{
return iptablesForwardMasquerade(ctx, network, physdev, REMOVE);
}
|
hjwsm1989/libvirt
|
src/util/iptables.c
|
C
|
lgpl-2.1
| 21,945
|
/*
* Multisim: a microprocessor architecture exploration framework
* Copyright (C) 2014 Tommy Thorn
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* 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.
*/
int SZ(loadelf,)(memory_t *m, char *name, FILE *f, elf_info_t *elf_info)
{
memset(elf_info, 0, sizeof *elf_info);
SZ(Elf,_Ehdr) ehdr;
SZ(Elf,_Phdr) *ph;
if (fread(&ehdr, sizeof ehdr, 1, f) != 1) {
fprintf(stderr, "%s: short header read, file corrupted?\n", name);
return 10;
}
if (ehdr.e_ident[EI_DATA] != ELFDATA2MSB && ehdr.e_ident[EI_DATA] != ELFDATA2LSB) {
fprintf(stderr, "%s: Unsupported endian (%d)\n",
name, ehdr.e_ident[EI_DATA]);
return 11;
}
elf_info->endian_is_big = ehdr.e_ident[EI_DATA] == ELFDATA2MSB;
memory_set_endian(m, elf_info->endian_is_big);
if (NATIVE(ehdr.e_type) != ET_EXEC) {
fprintf(stderr, "%s: Need a fully linked ELF executable, not type %d\n",
name, NATIVE(ehdr.e_type));
return 12;
}
elf_info->machine = NATIVE(ehdr.e_machine);
if (elf_info->machine != EM_ALPHA &&
elf_info->machine != EM_RISCV &&
elf_info->machine != EM_LM32 &&
elf_info->machine != EM_LM32_ALT) {
fprintf(stderr, "%s: Unsupported machine architecture %d\n",
name, NATIVE(ehdr.e_machine));
return 13;
}
if (enable_verb_prog_sec) {
printf("%s:\n", name);
printf("%sendian\n", elf_info->endian_is_big ? "big" : "little");
printf("Entry: %016"PRIx64"\n",
(uint64_t) NATIVE(ehdr.e_entry)); /* Entry point virtual address */
printf("Proc Flags: %08x\n",
NATIVE(ehdr.e_flags)); /* Processor-specific flags */
printf("Phdr.tbl entry cnt % 8d\n",
NATIVE(ehdr.e_phnum)); /*Program header table entry count */
printf("Shdr.tbl entry cnt % 8d\n",
NATIVE(ehdr.e_shnum)); /*Section header table entry count */
printf("Shdr.str tbl idx % 8d\n",
NATIVE(ehdr.e_shstrndx)); /*Section header string table index */
}
elf_info->program_entry = NATIVE(ehdr.e_entry);
if (NATIVE(ehdr.e_ehsize) != sizeof ehdr) {
return 14;
}
if (NATIVE(ehdr.e_shentsize) != sizeof(SZ(Elf,_Shdr))) {
return 15;
}
// Allocate program headers
ph = alloca(sizeof *ph * NATIVE(ehdr.e_phnum));
int phnum = NATIVE(ehdr.e_phnum);
for (int i = 0; i < phnum; ++i) {
fseek(f, NATIVE(ehdr.e_phoff) + i * NATIVE(ehdr.e_phentsize), SEEK_SET);
if (fread(ph + i, sizeof *ph, 1, f) != 1)
return 16;
if (enable_verb_prog_sec) {
printf("\nProgram header #%d (%lx)\n", i, ftell(f));
printf(" type %08x\n", NATIVE(ph[i].p_type));
printf(" filesz %016"PRIx64"\n", (uint64_t)NATIVE(ph[i].p_filesz));
printf(" offset %016"PRIx64"\n", (uint64_t)NATIVE(ph[i].p_offset));
printf(" vaddr %016"PRIx64"\n", (uint64_t)NATIVE(ph[i].p_vaddr));
printf(" paddr %016"PRIx64"\n", (uint64_t)NATIVE(ph[i].p_paddr));
printf(" memsz %016"PRIx64"\n", (uint64_t)NATIVE(ph[i].p_memsz));
printf(" flags %08x\n", NATIVE(ph[i].p_flags));
printf(" align %016"PRIx64"\n", (uint64_t)NATIVE(ph[i].p_align));
}
if (NATIVE(ph[i].p_type) == PT_LOAD && NATIVE(ph[i].p_filesz)) {
if (enable_verb_prog_sec)
fprintf(stderr, "Loading section [%016"PRIx64"; %016"PRIx64"]\n",
(uint64_t)NATIVE(ph[i].p_vaddr),
(uint64_t)NATIVE(ph[i].p_vaddr) + NATIVE(ph[i].p_memsz) - 1);
loadsection(f,
(unsigned)NATIVE(ph[i].p_offset),
(unsigned)NATIVE(ph[i].p_filesz),
m,
NATIVE(ph[i].p_vaddr),
NATIVE(ph[i].p_memsz),
elf_info);
}
if (ph[i].p_flags & 1) {
elf_info->text_segments++;
elf_info->text_start = NATIVE(ph[i].p_vaddr);
elf_info->text_size = NATIVE(ph[i].p_memsz);
}
}
if (enable_verb_elf) {
printf("\n");
fseek(f, NATIVE(ehdr.e_shoff), SEEK_SET);
int shnum = NATIVE(ehdr.e_shnum);
for (int i = 0; i < shnum; ++i) {
SZ(Elf,_Shdr) sh;
if (fread(&sh, sizeof sh, 1, f) != 1)
return 17;
printf("\nSection header #%d (%lx)\n", i, ftell(f));
printf(" name %08x\n", NATIVE(sh.sh_name));
printf(" type %08x\n", NATIVE(sh.sh_type));
printf(" flags %016"PRIx64"\n", (uint64_t)NATIVE(sh.sh_flags));
printf(" addr %016"PRIx64"\n", (uint64_t)NATIVE(sh.sh_addr));
printf(" offset %016"PRIx64"\n", (uint64_t)NATIVE(sh.sh_offset));
printf(" size %016"PRIx64"\n", (uint64_t)NATIVE(sh.sh_size));
printf(" link %08x\n", NATIVE(sh.sh_link));
printf(" info %08x\n", NATIVE(sh.sh_info));
printf(" addralign %016"PRIx64"\n", (uint64_t)NATIVE(sh.sh_addralign));
printf(" entsize %016"PRIx64"\n", (uint64_t)NATIVE(sh.sh_entsize));
}
printf(" (now at %lx)\n", ftell(f));
}
return 0;
}
// Local Variables:
// mode: C
// c-style-variables-are-local-p: t
// c-file-style: "stroustrup"
// End:
|
tommythorn/multisim
|
loadelf_temp.c
|
C
|
lgpl-2.1
| 6,328
|
/*
* The implementation of rb tree.
* Copyright (C) 2008 - 2014 Wangbo
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Author e-mail: activesys.wb@gmail.com
* activesys@sina.com.cn
*/
/** include section **/
#include <cstl/cstl_def.h>
#include <cstl/cstl_alloc.h>
#include <cstl/cstl_types.h>
#include <cstl/citerator.h>
#include <cstl/cstring.h>
#include <cstl/cstl_rb_tree_iterator.h>
#include <cstl/cstl_rb_tree_private.h>
#include <cstl/cstl_rb_tree.h>
#include "cstl_rb_tree_aux.h"
/** local constant declaration and local macro section **/
/** local data type declaration and local struct, union, enum section **/
/** local function prototype section **/
/** exported global variable definition section **/
/** local global variable definition section **/
/** exported function implementation section **/
/**
* Create rb tree container.
*/
_rb_tree_t* _create_rb_tree(const char* s_typename)
{
_rb_tree_t* pt_rb_tree = NULL;
if ((pt_rb_tree = (_rb_tree_t*)malloc(sizeof(_rb_tree_t))) == NULL) {
return NULL;
}
if (!_create_rb_tree_auxiliary(pt_rb_tree, s_typename)) {
free(pt_rb_tree);
return NULL;
}
return pt_rb_tree;
}
/**
* Initialize rb tree container.
*/
void _rb_tree_init(_rb_tree_t* pt_rb_tree, bfun_t t_compare)
{
assert(pt_rb_tree != NULL);
assert(_rb_tree_is_created(pt_rb_tree));
pt_rb_tree->_t_rbroot._pt_left = &pt_rb_tree->_t_rbroot;
pt_rb_tree->_t_rbroot._pt_right = &pt_rb_tree->_t_rbroot;
pt_rb_tree->_t_compare = t_compare != NULL ? t_compare : _GET_RB_TREE_TYPE_LESS_FUNCTION(pt_rb_tree);
}
/**
* Destroy rb tree.
*/
void _rb_tree_destroy(_rb_tree_t* pt_rb_tree)
{
assert(pt_rb_tree != NULL);
assert(_rb_tree_is_inited(pt_rb_tree) || _rb_tree_is_created(pt_rb_tree));
_rb_tree_destroy_auxiliary(pt_rb_tree);
free(pt_rb_tree);
}
/**
* Initialize rb tree container with rb tree.
*/
void _rb_tree_init_copy(_rb_tree_t* pt_dest, const _rb_tree_t* cpt_src)
{
_rb_tree_iterator_t it_iter;
_rb_tree_iterator_t it_begin;
_rb_tree_iterator_t it_end;
assert(pt_dest != NULL);
assert(cpt_src != NULL);
assert(_rb_tree_is_created(pt_dest));
assert(_rb_tree_is_inited(cpt_src));
assert(_rb_tree_same_type(pt_dest, cpt_src));
_rb_tree_init(pt_dest, cpt_src->_t_compare);
it_begin = _rb_tree_begin(cpt_src);
it_end = _rb_tree_end(cpt_src);
for (it_iter = it_begin;
!_rb_tree_iterator_equal(it_iter, it_end);
it_iter = _rb_tree_iterator_next(it_iter)) {
_rb_tree_insert_equal(pt_dest, _rb_tree_iterator_get_pointer_ignore_cstr(it_iter));
}
}
/**
* Initialize rb tree container with specific range.
*/
void _rb_tree_init_copy_equal_range(_rb_tree_t* pt_dest, iterator_t it_begin, iterator_t it_end)
{
assert(pt_dest != NULL);
assert(_rb_tree_is_created(pt_dest));
assert(_rb_tree_same_iterator_type(pt_dest, it_begin));
assert(_rb_tree_same_iterator_type(pt_dest, it_end));
assert(iterator_equal(it_begin, it_end) || _iterator_before(it_begin, it_end));
_rb_tree_init(pt_dest, NULL);
_rb_tree_insert_equal_range(pt_dest, it_begin, it_end);
}
/**
* Initialize rb tree container with specific range.
*/
void _rb_tree_init_copy_unique_range(_rb_tree_t* pt_dest, iterator_t it_begin, iterator_t it_end)
{
assert(pt_dest != NULL);
assert(_rb_tree_is_created(pt_dest));
assert(_rb_tree_same_iterator_type(pt_dest, it_begin));
assert(_rb_tree_same_iterator_type(pt_dest, it_end));
assert(iterator_equal(it_begin, it_end) || _iterator_before(it_begin, it_end));
_rb_tree_init(pt_dest, NULL);
_rb_tree_insert_unique_range(pt_dest, it_begin, it_end);
}
/**
* Initialize rb tree container with specific array.
*/
void _rb_tree_init_copy_equal_array(_rb_tree_t* pt_dest, const void* cpv_array, size_t t_count)
{
assert(pt_dest != NULL);
assert(_rb_tree_is_created(pt_dest));
assert(cpv_array != NULL);
_rb_tree_init(pt_dest, NULL);
_rb_tree_insert_equal_array(pt_dest, cpv_array, t_count);
}
/**
* Initialize rb tree container with specific array.
*/
void _rb_tree_init_copy_unique_array(_rb_tree_t* pt_dest, const void* cpv_array, size_t t_count)
{
assert(pt_dest != NULL);
assert(_rb_tree_is_created(pt_dest));
assert(cpv_array != NULL);
_rb_tree_init(pt_dest, NULL);
_rb_tree_insert_unique_array(pt_dest, cpv_array, t_count);
}
/**
* Initialize rb tree container with specific range and compare function.
*/
void _rb_tree_init_copy_equal_range_ex(
_rb_tree_t* pt_dest, iterator_t it_begin, iterator_t it_end, bfun_t t_compare)
{
assert(pt_dest != NULL);
assert(_rb_tree_is_created(pt_dest));
assert(_rb_tree_same_iterator_type(pt_dest, it_begin));
assert(_rb_tree_same_iterator_type(pt_dest, it_end));
assert(iterator_equal(it_begin, it_end) || _iterator_before(it_begin, it_end));
_rb_tree_init(pt_dest, t_compare);
_rb_tree_insert_equal_range(pt_dest, it_begin, it_end);
}
/**
* Initialize rb tree container with specific range and compare function.
*/
void _rb_tree_init_copy_unique_range_ex(
_rb_tree_t* pt_dest, iterator_t it_begin, iterator_t it_end, bfun_t t_compare)
{
assert(pt_dest != NULL);
assert(_rb_tree_is_created(pt_dest));
assert(_rb_tree_same_iterator_type(pt_dest, it_begin));
assert(_rb_tree_same_iterator_type(pt_dest, it_end));
assert(iterator_equal(it_begin, it_end) || _iterator_before(it_begin, it_end));
_rb_tree_init(pt_dest, t_compare);
_rb_tree_insert_unique_range(pt_dest, it_begin, it_end);
}
/**
* Initialize rb tree container with specific array and compare function.
*/
void _rb_tree_init_copy_equal_array_ex(
_rb_tree_t* pt_dest, const void* cpv_array, size_t t_count, bfun_t t_compare)
{
assert(pt_dest != NULL);
assert(_rb_tree_is_created(pt_dest));
assert(cpv_array != NULL);
_rb_tree_init(pt_dest, t_compare);
_rb_tree_insert_equal_array(pt_dest, cpv_array, t_count);
}
/**
* Initialize rb tree container with specific array and compare function.
*/
void _rb_tree_init_copy_unique_array_ex(
_rb_tree_t* pt_dest, const void* cpv_array, size_t t_count, bfun_t t_compare)
{
assert(pt_dest != NULL);
assert(_rb_tree_is_created(pt_dest));
assert(cpv_array != NULL);
_rb_tree_init(pt_dest, t_compare);
_rb_tree_insert_unique_array(pt_dest, cpv_array, t_count);
}
/**
* Assign rb tree container.
*/
void _rb_tree_assign(_rb_tree_t* pt_dest, const _rb_tree_t* cpt_src)
{
assert(pt_dest != NULL);
assert(cpt_src != NULL);
assert(_rb_tree_is_inited(pt_dest));
assert(_rb_tree_is_inited(cpt_src));
assert(_rb_tree_same_type_ex(pt_dest, cpt_src));
if (!_rb_tree_equal(pt_dest, cpt_src)) {
_rb_tree_iterator_t it_iter;
_rb_tree_iterator_t it_begin;
_rb_tree_iterator_t it_end;
/* clear dest rb tree */
_rb_tree_clear(pt_dest);
it_begin = _rb_tree_begin(cpt_src);
it_end = _rb_tree_end(cpt_src);
/* insert all elements of src into dest */
for (it_iter = it_begin;
!_rb_tree_iterator_equal(it_iter, it_end);
it_iter = _rb_tree_iterator_next(it_iter)) {
_rb_tree_insert_equal(pt_dest, _rb_tree_iterator_get_pointer_ignore_cstr(it_iter));
}
}
}
/**
* Test if an rb tree is empty.
*/
bool_t _rb_tree_empty(const _rb_tree_t* cpt_rb_tree)
{
assert(cpt_rb_tree != NULL);
assert(_rb_tree_is_inited(cpt_rb_tree));
return cpt_rb_tree->_t_nodecount == 0 ? true : false;
}
/**
* Get the number of elements int the rb tree.
*/
size_t _rb_tree_size(const _rb_tree_t* cpt_rb_tree)
{
assert(cpt_rb_tree != NULL);
assert(_rb_tree_is_inited(cpt_rb_tree));
return cpt_rb_tree->_t_nodecount;
}
/**
* Get the maximum number of elements int the rb tree.
*/
size_t _rb_tree_max_size(const _rb_tree_t* cpt_rb_tree)
{
assert(cpt_rb_tree != NULL);
assert(_rb_tree_is_inited(cpt_rb_tree));
return (size_t)(-1) / _GET_RB_TREE_TYPE_SIZE(cpt_rb_tree);
}
/**
* Return an iterator that addresses the first element in the rb tree.
*/
_rb_tree_iterator_t _rb_tree_begin(const _rb_tree_t* cpt_rb_tree)
{
_rb_tree_iterator_t it_begin = _create_rb_tree_iterator();
assert(cpt_rb_tree != NULL);
assert(_rb_tree_is_inited(cpt_rb_tree));
_RB_TREE_ITERATOR_TREE_POINTER(it_begin) = (void*)cpt_rb_tree;
_RB_TREE_ITERATOR_COREPOS(it_begin) = (_byte_t*)cpt_rb_tree->_t_rbroot._pt_left;
return it_begin;
}
/**
* Return an iterator that addresses the location succeeding the last element in the rb tree.
*/
_rb_tree_iterator_t _rb_tree_end(const _rb_tree_t* cpt_rb_tree)
{
_rb_tree_iterator_t it_end = _create_rb_tree_iterator();
assert(cpt_rb_tree != NULL);
assert(_rb_tree_is_inited(cpt_rb_tree));
_RB_TREE_ITERATOR_TREE_POINTER(it_end) = (void*)cpt_rb_tree;
_RB_TREE_ITERATOR_COREPOS(it_end) = (_byte_t*)&cpt_rb_tree->_t_rbroot;
return it_end;
}
_rb_tree_iterator_t _rb_tree_rend(const _rb_tree_t* cpt_rb_tree)
{
_rb_tree_iterator_t it_newiterator = _create_rb_tree_iterator();
assert(cpt_rb_tree != NULL);
_RB_TREE_ITERATOR_TREE_POINTER(it_newiterator) = (void*)cpt_rb_tree;
_RB_TREE_ITERATOR_COREPOS(it_newiterator) = (_byte_t*)&cpt_rb_tree->_t_rbroot;
return it_newiterator;
}
_rb_tree_iterator_t _rb_tree_rbegin(const _rb_tree_t* cpt_rb_tree)
{
_rb_tree_iterator_t it_newiterator = _create_rb_tree_iterator();
assert(cpt_rb_tree != NULL);
_RB_TREE_ITERATOR_TREE_POINTER(it_newiterator) = (void*)cpt_rb_tree;
_RB_TREE_ITERATOR_COREPOS(it_newiterator) = (_byte_t*)cpt_rb_tree->_t_rbroot._pt_right;
return it_newiterator;
}
/**
* Return the compare function of key.
*/
bfun_t _rb_tree_key_comp(const _rb_tree_t* cpt_rb_tree)
{
assert(cpt_rb_tree != NULL);
assert(_rb_tree_is_inited(cpt_rb_tree));
return cpt_rb_tree->_t_compare;
}
/**
* Find specific element.
*/
_rb_tree_iterator_t _rb_tree_find(const _rb_tree_t* cpt_rb_tree, const void* cpv_value)
{
_rb_tree_iterator_t it_iter;
assert(cpt_rb_tree != NULL);
assert(cpv_value != NULL);
assert(_rb_tree_is_inited(cpt_rb_tree));
_RB_TREE_ITERATOR_TREE_POINTER(it_iter) = (void*)cpt_rb_tree;
_RB_TREE_ITERATOR_COREPOS(it_iter) = (_byte_t*)_rb_tree_find_value(
cpt_rb_tree, cpt_rb_tree->_t_rbroot._pt_parent, cpv_value);
if (_RB_TREE_ITERATOR_COREPOS(it_iter) == NULL) {
_RB_TREE_ITERATOR_COREPOS(it_iter) = (_byte_t*)&cpt_rb_tree->_t_rbroot;
}
return it_iter;
}
/**
* Erases all the elements of an rb tree.
*/
void _rb_tree_clear(_rb_tree_t* pt_rb_tree)
{
assert(pt_rb_tree != NULL);
assert(_rb_tree_is_inited(pt_rb_tree));
pt_rb_tree->_t_rbroot._pt_parent = _rb_tree_destroy_subtree(pt_rb_tree, pt_rb_tree->_t_rbroot._pt_parent);
assert(pt_rb_tree->_t_rbroot._pt_parent == NULL);
pt_rb_tree->_t_rbroot._pt_left = &pt_rb_tree->_t_rbroot;
pt_rb_tree->_t_rbroot._pt_right = &pt_rb_tree->_t_rbroot;
pt_rb_tree->_t_nodecount = 0;
}
/**
* Tests if the two rb tree are equal.
*/
bool_t _rb_tree_equal(const _rb_tree_t* cpt_first, const _rb_tree_t* cpt_second)
{
_rb_tree_iterator_t it_first;
_rb_tree_iterator_t it_first_begin;
_rb_tree_iterator_t it_first_end;
_rb_tree_iterator_t it_second;
_rb_tree_iterator_t it_second_begin;
_rb_tree_iterator_t it_second_end;
bool_t b_less = false;
bool_t b_greater = false;
assert(cpt_first != NULL);
assert(cpt_second != NULL);
assert(_rb_tree_is_inited(cpt_first));
assert(_rb_tree_is_inited(cpt_second));
assert(_rb_tree_same_type_ex(cpt_first, cpt_second));
if (cpt_first == cpt_second) {
return true;
}
/* test rb tree size */
if (_rb_tree_size(cpt_first) != _rb_tree_size(cpt_second)) {
return false;
}
it_first_begin = _rb_tree_begin(cpt_first);
it_first_end = _rb_tree_end(cpt_first);
it_second_begin = _rb_tree_begin(cpt_second);
it_second_end = _rb_tree_end(cpt_second);
/* test each element */
for (it_first = it_first_begin, it_second = it_second_begin;
!_rb_tree_iterator_equal(it_first, it_first_end) && !_rb_tree_iterator_equal(it_second, it_second_end);
it_first = _rb_tree_iterator_next(it_first), it_second = _rb_tree_iterator_next(it_second)) {
b_less = b_greater = _GET_RB_TREE_TYPE_SIZE(cpt_first);
_GET_RB_TREE_TYPE_LESS_FUNCTION(cpt_first)(
((_rbnode_t*)_RB_TREE_ITERATOR_COREPOS(it_first))->_pby_data,
((_rbnode_t*)_RB_TREE_ITERATOR_COREPOS(it_second))->_pby_data, &b_less);
_GET_RB_TREE_TYPE_LESS_FUNCTION(cpt_first)(
((_rbnode_t*)_RB_TREE_ITERATOR_COREPOS(it_second))->_pby_data,
((_rbnode_t*)_RB_TREE_ITERATOR_COREPOS(it_first))->_pby_data, &b_greater);
if (b_less || b_greater) {
return false;
}
}
assert(_rb_tree_iterator_equal(it_first, it_first_end) && _rb_tree_iterator_equal(it_second, it_second_end));
return true;
}
/**
* Tests if the two rb tree are not equal.
*/
bool_t _rb_tree_not_equal(const _rb_tree_t* cpt_first, const _rb_tree_t* cpt_second)
{
return !_rb_tree_equal(cpt_first, cpt_second);
}
/**
* Tests if the first rb tree is less than the second rb tree.
*/
bool_t _rb_tree_less(const _rb_tree_t* cpt_first, const _rb_tree_t* cpt_second)
{
_rb_tree_iterator_t it_first;
_rb_tree_iterator_t it_first_begin;
_rb_tree_iterator_t it_first_end;
_rb_tree_iterator_t it_second;
_rb_tree_iterator_t it_second_begin;
_rb_tree_iterator_t it_second_end;
bool_t b_result = false;
assert(cpt_first != NULL);
assert(cpt_second != NULL);
assert(_rb_tree_is_inited(cpt_first));
assert(_rb_tree_is_inited(cpt_second));
assert(_rb_tree_same_type_ex(cpt_first, cpt_second));
it_first_begin = _rb_tree_begin(cpt_first);
it_first_end = _rb_tree_end(cpt_first);
it_second_begin = _rb_tree_begin(cpt_second);
it_second_end = _rb_tree_end(cpt_second);
/* test each element */
for (it_first = it_first_begin, it_second = it_second_begin;
!_rb_tree_iterator_equal(it_first, it_first_end) && !_rb_tree_iterator_equal(it_second, it_second_end);
it_first = _rb_tree_iterator_next(it_first), it_second = _rb_tree_iterator_next(it_second)) {
b_result = _GET_RB_TREE_TYPE_SIZE(cpt_first);
_GET_RB_TREE_TYPE_LESS_FUNCTION(cpt_first)(
((_rbnode_t*)_RB_TREE_ITERATOR_COREPOS(it_first))->_pby_data,
((_rbnode_t*)_RB_TREE_ITERATOR_COREPOS(it_second))->_pby_data, &b_result);
if (b_result) {
return true;
}
b_result = _GET_RB_TREE_TYPE_SIZE(cpt_first);
_GET_RB_TREE_TYPE_LESS_FUNCTION(cpt_first)(
((_rbnode_t*)_RB_TREE_ITERATOR_COREPOS(it_second))->_pby_data,
((_rbnode_t*)_RB_TREE_ITERATOR_COREPOS(it_first))->_pby_data, &b_result);
if (b_result) {
return false;
}
}
return _rb_tree_size(cpt_first) < _rb_tree_size(cpt_second) ? true : false;
}
/**
* Tests if the first rb tree is less than or equal to the second rb tree.
*/
bool_t _rb_tree_less_equal(const _rb_tree_t* cpt_first, const _rb_tree_t* cpt_second)
{
return (_rb_tree_less(cpt_first, cpt_second) || _rb_tree_equal(cpt_first, cpt_second)) ? true : false;
}
/**
* Tests if the first rb tree is greater than the second rb tree.
*/
bool_t _rb_tree_greater(const _rb_tree_t* cpt_first, const _rb_tree_t* cpt_second)
{
return _rb_tree_less(cpt_second, cpt_first);
}
/**
* Tests if the first rb tree is greater than or equal to the second rb tree.
*/
bool_t _rb_tree_greater_equal(const _rb_tree_t* cpt_first, const _rb_tree_t* cpt_second)
{
return (_rb_tree_greater(cpt_first, cpt_second) || _rb_tree_equal(cpt_first, cpt_second)) ? true : false;
}
/**
* Swap the datas of first rb_tree and second rb_tree.
*/
void _rb_tree_swap(_rb_tree_t* pt_first, _rb_tree_t* pt_second)
{
_rb_tree_t t_temp;
assert(pt_first != NULL);
assert(pt_second != NULL);
assert(_rb_tree_is_inited(pt_first));
assert(_rb_tree_is_inited(pt_second));
assert(_rb_tree_same_type_ex(pt_first, pt_second));
if (_rb_tree_equal(pt_first, pt_second)) {
return;
}
t_temp = *pt_first;
*pt_first = *pt_second;
*pt_second = t_temp;
if (_rb_tree_empty(pt_first)) {
pt_first->_t_rbroot._pt_left = &pt_first->_t_rbroot;
pt_first->_t_rbroot._pt_right = &pt_first->_t_rbroot;
} else {
pt_first->_t_rbroot._pt_parent->_pt_parent = &pt_first->_t_rbroot;
}
if (_rb_tree_empty(pt_second)) {
pt_second->_t_rbroot._pt_left = &pt_second->_t_rbroot;
pt_second->_t_rbroot._pt_right = &pt_second->_t_rbroot;
} else {
pt_second->_t_rbroot._pt_parent->_pt_parent = &pt_second->_t_rbroot;
}
}
/**
* Return the number of specific elements in an rb tree
*/
size_t _rb_tree_count(const _rb_tree_t* cpt_rb_tree, const void* cpv_value)
{
range_t r_range;
assert(cpt_rb_tree != NULL);
assert(cpv_value != NULL);
assert(_rb_tree_is_inited(cpt_rb_tree));
r_range = _rb_tree_equal_range(cpt_rb_tree, cpv_value);
return abs(_rb_tree_iterator_distance(r_range.it_begin, r_range.it_end));
}
/**
* Return an iterator to the first element that is equal to or greater than a specific element.
*/
_rb_tree_iterator_t _rb_tree_lower_bound(const _rb_tree_t* cpt_rb_tree, const void* cpv_value)
{
_rbnode_t* pt_cur = NULL;
_rbnode_t* pt_prev = NULL;
_rb_tree_iterator_t it_iter;
bool_t b_less = false;
bool_t b_greater = false;
assert(cpt_rb_tree != NULL);
assert(cpv_value != NULL);
assert(_rb_tree_is_inited(cpt_rb_tree));
it_iter = _create_rb_tree_iterator();
_RB_TREE_ITERATOR_TREE_POINTER(it_iter) = (void*)cpt_rb_tree;
if (!_rb_tree_empty(cpt_rb_tree)) {
pt_prev = cpt_rb_tree->_t_rbroot._pt_parent;
b_less = b_greater = _GET_RB_TREE_TYPE_SIZE(cpt_rb_tree);
_rb_tree_elem_compare_auxiliary(cpt_rb_tree, cpv_value, pt_prev->_pby_data, &b_less);
_rb_tree_elem_compare_auxiliary(cpt_rb_tree, pt_prev->_pby_data, cpv_value, &b_greater);
pt_cur = (b_less || !b_greater) ? pt_prev->_pt_left : pt_prev->_pt_right;
while (pt_cur != NULL) {
pt_prev = pt_cur;
b_less = b_greater = _GET_RB_TREE_TYPE_SIZE(cpt_rb_tree);
_rb_tree_elem_compare_auxiliary(cpt_rb_tree, cpv_value, pt_prev->_pby_data, &b_less);
_rb_tree_elem_compare_auxiliary(cpt_rb_tree, pt_prev->_pby_data, cpv_value, &b_greater);
pt_cur = (b_less || !b_greater) ? pt_prev->_pt_left : pt_prev->_pt_right;
}
if (b_less || !b_greater) {
assert(pt_prev->_pt_left == NULL);
_RB_TREE_ITERATOR_COREPOS(it_iter) = (_byte_t*)pt_prev;
assert(_rb_tree_iterator_belong_to_rb_tree(cpt_rb_tree, it_iter));
} else {
assert(pt_prev->_pt_right == NULL);
_RB_TREE_ITERATOR_COREPOS(it_iter) = (_byte_t*)pt_prev;
it_iter = _rb_tree_iterator_next(it_iter);
}
} else {
it_iter = _rb_tree_end(cpt_rb_tree);
}
return it_iter;
}
/**
* Return an iterator to the first element that is greater than a specific element.
*/
_rb_tree_iterator_t _rb_tree_upper_bound(const _rb_tree_t* cpt_rb_tree, const void* cpv_value)
{
_rbnode_t* pt_cur = NULL;
_rbnode_t* pt_prev = NULL;
_rb_tree_iterator_t it_iter;
bool_t b_result = false;
assert(cpt_rb_tree != NULL);
assert(cpv_value != NULL);
assert(_rb_tree_is_inited(cpt_rb_tree));
it_iter = _create_rb_tree_iterator();
_RB_TREE_ITERATOR_TREE_POINTER(it_iter) = (void*)cpt_rb_tree;
if (!_rb_tree_empty(cpt_rb_tree)) {
pt_prev = cpt_rb_tree->_t_rbroot._pt_parent;
b_result = _GET_RB_TREE_TYPE_SIZE(cpt_rb_tree);
_rb_tree_elem_compare_auxiliary(cpt_rb_tree, cpv_value, pt_prev->_pby_data, &b_result);
pt_cur = b_result ? pt_prev->_pt_left : pt_prev->_pt_right;
while (pt_cur != NULL) {
pt_prev = pt_cur;
b_result = _GET_RB_TREE_TYPE_SIZE(cpt_rb_tree);
_rb_tree_elem_compare_auxiliary(cpt_rb_tree, cpv_value, pt_prev->_pby_data, &b_result);
pt_cur = b_result ? pt_prev->_pt_left : pt_prev->_pt_right;
}
if (b_result) {
assert(pt_prev->_pt_left == NULL);
_RB_TREE_ITERATOR_COREPOS(it_iter) = (_byte_t*)pt_prev;
assert(_rb_tree_iterator_belong_to_rb_tree(cpt_rb_tree, it_iter));
} else {
assert(pt_prev->_pt_right == NULL);
_RB_TREE_ITERATOR_COREPOS(it_iter) = (_byte_t*)pt_prev;
it_iter = _rb_tree_iterator_next(it_iter);
}
} else {
it_iter = _rb_tree_end(cpt_rb_tree);
}
return it_iter;
}
/**
* Return an iterator range that is equal to a specific element.
*/
range_t _rb_tree_equal_range(const _rb_tree_t* cpt_rb_tree, const void* cpv_value)
{
range_t r_range;
assert(cpt_rb_tree != NULL);
assert(cpv_value != NULL);
assert(_rb_tree_is_inited(cpt_rb_tree));
r_range.it_begin = _rb_tree_lower_bound(cpt_rb_tree, cpv_value);
r_range.it_end = _rb_tree_upper_bound(cpt_rb_tree, cpv_value);
return r_range;
}
/**
* Inserts an element into a rb tree.
*/
_rb_tree_iterator_t _rb_tree_insert_equal(_rb_tree_t* pt_rb_tree, const void* cpv_value)
{
_rb_tree_iterator_t it_iter = _create_rb_tree_iterator();
assert(pt_rb_tree != NULL);
assert(cpv_value != NULL);
assert(_rb_tree_is_inited(pt_rb_tree));
_RB_TREE_ITERATOR_TREE_POINTER(it_iter) = pt_rb_tree;
_RB_TREE_ITERATOR_COREPOS(it_iter) = (_byte_t*)_rb_tree_insert_rbnode(pt_rb_tree, cpv_value);
pt_rb_tree->_t_rbroot._pt_left = _rb_tree_get_min_rbnode(pt_rb_tree->_t_rbroot._pt_parent);
pt_rb_tree->_t_rbroot._pt_right = _rb_tree_get_max_rbnode(pt_rb_tree->_t_rbroot._pt_parent);
pt_rb_tree->_t_nodecount++;
return it_iter;
}
/**
* Inserts an unique element into a rb tree.
*/
_rb_tree_iterator_t _rb_tree_insert_unique(_rb_tree_t* pt_rb_tree, const void* cpv_value)
{
assert(pt_rb_tree != NULL);
assert(cpv_value != NULL);
assert(_rb_tree_is_inited(pt_rb_tree));
/* if the rb tree is empty */
if (_rb_tree_empty(pt_rb_tree)) {
return _rb_tree_insert_equal(pt_rb_tree, cpv_value);
} else {
/* find value in rb tree */
_rb_tree_iterator_t it_iter = _rb_tree_find(pt_rb_tree, cpv_value);
/* if the value is exist */
if (!_rb_tree_iterator_equal(it_iter, _rb_tree_end(pt_rb_tree))) {
return _rb_tree_end(pt_rb_tree);
} else {
/* insert value into rb tree */
return _rb_tree_insert_equal(pt_rb_tree, cpv_value);
}
}
}
/**
* Inserts an range into a rb tree.
*/
void _rb_tree_insert_equal_range(_rb_tree_t* pt_rb_tree, iterator_t it_begin, iterator_t it_end)
{
iterator_t it_iter;
assert(pt_rb_tree != NULL);
assert(_rb_tree_is_inited(pt_rb_tree));
assert(_rb_tree_same_iterator_type(pt_rb_tree, it_begin));
assert(_rb_tree_same_iterator_type(pt_rb_tree, it_end));
assert(iterator_equal(it_begin, it_end) || _iterator_before(it_begin, it_end));
for (it_iter = it_begin; !iterator_equal(it_iter, it_end); it_iter = iterator_next(it_iter)) {
_rb_tree_insert_equal(pt_rb_tree, _iterator_get_pointer_ignore_cstr(it_iter));
}
}
/**
* Inserts an array into a rb tree.
*/
void _rb_tree_insert_equal_array(_rb_tree_t* pt_rb_tree, const void* cpv_array, size_t t_count)
{
size_t i = 0;
assert(pt_rb_tree != NULL);
assert(_rb_tree_is_inited(pt_rb_tree));
assert(cpv_array != NULL);
/*
* Copy the elements from src array to dest rb tree.
* The array of c builtin and user define or cstl builtin are different,
* the elements of c builtin array are element itself, but the elements of
* c string, user define or cstl are pointer of element.
*/
if (strncmp(_GET_RB_TREE_TYPE_BASENAME(pt_rb_tree), _C_STRING_TYPE, _TYPE_NAME_SIZE) == 0) {
/*
* We need built a string_t for c string element.
*/
string_t* pstr_elem = create_string();
assert(pstr_elem != NULL);
string_init(pstr_elem);
for (i = 0; i < t_count; ++i) {
string_assign_cstr(pstr_elem, *((const char**)cpv_array + i));
_rb_tree_insert_equal(pt_rb_tree, pstr_elem);
}
string_destroy(pstr_elem);
} else if (_GET_RB_TREE_TYPE_STYLE(pt_rb_tree) == _TYPE_C_BUILTIN) {
for (i = 0; i < t_count; ++i) {
_rb_tree_insert_equal(pt_rb_tree, (unsigned char*)cpv_array + i * _GET_RB_TREE_TYPE_SIZE(pt_rb_tree));
}
} else {
for (i = 0; i < t_count; ++i) {
_rb_tree_insert_equal(pt_rb_tree, *((void**)cpv_array + i));
}
}
}
/**
* Inserts an range of unique element into a rb tree.
*/
void _rb_tree_insert_unique_range(_rb_tree_t* pt_rb_tree, iterator_t it_begin, iterator_t it_end)
{
iterator_t it_iter;
assert(pt_rb_tree != NULL);
assert(_rb_tree_is_inited(pt_rb_tree));
assert(_rb_tree_same_iterator_type(pt_rb_tree, it_begin));
assert(_rb_tree_same_iterator_type(pt_rb_tree, it_end));
assert(iterator_equal(it_begin, it_end) || _iterator_before(it_begin, it_end));
for (it_iter = it_begin; !iterator_equal(it_iter, it_end); it_iter = iterator_next(it_iter)) {
_rb_tree_insert_unique(pt_rb_tree, _iterator_get_pointer_ignore_cstr(it_iter));
}
}
/**
* Inserts an array of unique element into a rb tree.
*/
void _rb_tree_insert_unique_array(_rb_tree_t* pt_rb_tree, const void* cpv_array, size_t t_count)
{
size_t i = 0;
assert(pt_rb_tree != NULL);
assert(_rb_tree_is_inited(pt_rb_tree));
assert(cpv_array != NULL);
/*
* Copy the elements from src array to dest rb tree.
* The array of c builtin and user define or cstl builtin are different,
* the elements of c builtin array are element itself, but the elements of
* c string, user define or cstl are pointer of element.
*/
if (strncmp(_GET_RB_TREE_TYPE_BASENAME(pt_rb_tree), _C_STRING_TYPE, _TYPE_NAME_SIZE) == 0) {
/*
* We need built a string_t for c string element.
*/
string_t* pstr_elem = create_string();
assert(pstr_elem != NULL);
string_init(pstr_elem);
for (i = 0; i < t_count; ++i) {
string_assign_cstr(pstr_elem, *((const char**)cpv_array + i));
_rb_tree_insert_unique(pt_rb_tree, pstr_elem);
}
string_destroy(pstr_elem);
} else if (_GET_RB_TREE_TYPE_STYLE(pt_rb_tree) == _TYPE_C_BUILTIN) {
for (i = 0; i < t_count; ++i) {
_rb_tree_insert_unique(pt_rb_tree, (unsigned char*)cpv_array + i * _GET_RB_TREE_TYPE_SIZE(pt_rb_tree));
}
} else {
for (i = 0; i < t_count; ++i) {
_rb_tree_insert_unique(pt_rb_tree, *((void**)cpv_array + i));
}
}
}
/*
* Erase an element in an rb tree from specificed position.
*/
void _rb_tree_erase_pos(_rb_tree_t* pt_rb_tree, _rb_tree_iterator_t it_pos)
{
_rbnode_t* pt_parent = NULL;
_rbnode_t* pt_cur = NULL;
_rbnode_t* pt_parenttmp = NULL;
_rbnode_t* pt_curtmp = NULL;
_color_t t_colortmp; /* temporary color for deletion */
bool_t b_result = false;
assert(pt_rb_tree != NULL);
assert(_rb_tree_is_inited(pt_rb_tree));
assert(_rb_tree_iterator_belong_to_rb_tree(pt_rb_tree, it_pos));
assert(!_rb_tree_iterator_equal(it_pos, _rb_tree_end(pt_rb_tree)));
pt_cur = (_rbnode_t*)_RB_TREE_ITERATOR_COREPOS(it_pos);
pt_parent = pt_cur->_pt_parent;
/* delete the current node pointted by it_pos */
if (pt_cur == pt_parent->_pt_parent) {
assert(pt_cur == pt_rb_tree->_t_rbroot._pt_parent);
if (pt_cur->_pt_left == NULL && pt_cur->_pt_right == NULL) {
/*
* p p
* | =>
* c
*/
pt_parent->_pt_parent = NULL;
} else if (pt_cur->_pt_left != NULL && pt_cur->_pt_right == NULL) {
/*
* p p
* | |
* c => l
* /
* l
*/
pt_parent->_pt_parent = pt_cur->_pt_left;
pt_parent->_pt_parent->_pt_parent = pt_parent;
pt_parent->_pt_parent->_t_color = _COLOR_BLACK;
} else if (pt_cur->_pt_left == NULL && pt_cur->_pt_right != NULL) {
/*
* p p
* | |
* c => r
* \
* r
*/
pt_parent->_pt_parent = pt_cur->_pt_right;
pt_parent->_pt_parent->_pt_parent = pt_parent;
pt_parent->_pt_parent->_t_color = _COLOR_BLACK;
} else {
/*
* here the real deleted node is pt_curtmp, so the
* color of pt_curtmp is used.
*/
pt_curtmp = _rb_tree_get_min_rbnode(pt_cur->_pt_right);
t_colortmp = pt_curtmp->_t_color;
if (pt_cur == pt_curtmp->_pt_parent) {
/*
* p p
* | |
* c => r
* / \ / \
* l r l rr
* \
* rr
*/
pt_curtmp->_pt_left = pt_cur->_pt_left;
pt_curtmp->_pt_left->_pt_parent = pt_curtmp;
pt_curtmp->_pt_parent = pt_cur->_pt_parent;
pt_curtmp->_pt_parent->_pt_parent = pt_curtmp;
pt_curtmp->_t_color = pt_cur->_t_color;
pt_cur->_t_color = t_colortmp;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_curtmp->_pt_right, pt_curtmp);
}
} else {
/*
* p p
* | |
* c => rll
* / \ / \
* l r l r
* / \ / \
* rl rr rl rr
* / \ \ \ \
* rll rlr rrr rlr rrr
*/
pt_parenttmp = pt_curtmp->_pt_parent;
pt_parenttmp->_pt_left = pt_curtmp->_pt_right;
if (pt_parenttmp->_pt_left != NULL) {
pt_parenttmp->_pt_left->_pt_parent = pt_parenttmp;
}
pt_curtmp->_pt_left = pt_cur->_pt_left;
pt_curtmp->_pt_left->_pt_parent = pt_curtmp;
pt_curtmp->_pt_right = pt_cur->_pt_right;
pt_curtmp->_pt_right->_pt_parent = pt_curtmp;
pt_curtmp->_pt_parent = pt_cur->_pt_parent;
pt_curtmp->_pt_parent->_pt_parent = pt_curtmp;
pt_curtmp->_t_color = pt_cur->_t_color;
pt_cur->_t_color = t_colortmp;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_parenttmp->_pt_left, pt_parenttmp);
}
}
}
} else if (pt_cur == pt_parent->_pt_left) {
if (pt_cur->_pt_left == NULL && pt_cur->_pt_right == NULL) {
/*
* p p
* / =>
* c
*/
pt_parent->_pt_left = NULL;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_parent->_pt_left, pt_parent);
}
} else if (pt_cur->_pt_left != NULL && pt_cur->_pt_right == NULL) {
/*
* p p
* / /
* c => l
* /
* l
*/
pt_parent->_pt_left = pt_cur->_pt_left;
pt_parent->_pt_left->_pt_parent = pt_parent;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_parent->_pt_left, pt_parent);
}
} else if (pt_cur->_pt_left == NULL && pt_cur->_pt_right != NULL) {
/*
* p p
* / /
* c => r
* \
* r
*/
pt_parent->_pt_left = pt_cur->_pt_right;
pt_parent->_pt_left->_pt_parent = pt_parent;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_parent->_pt_left, pt_parent);
}
} else {
/*
* here the real deleted node is pt_curtmp, so the
* color of pt_curtmp is used.
*/
pt_curtmp = _rb_tree_get_min_rbnode(pt_cur->_pt_right);
t_colortmp = pt_curtmp->_t_color;
if (pt_cur == pt_curtmp->_pt_parent) {
/*
* p p
* / /
* c => r
* / \ / \
* l r l rr
* \
* rr
*/
pt_curtmp->_pt_left = pt_cur->_pt_left;
pt_curtmp->_pt_left->_pt_parent = pt_curtmp;
pt_curtmp->_pt_parent = pt_cur->_pt_parent;
pt_curtmp->_pt_parent->_pt_left = pt_curtmp;
pt_curtmp->_t_color = pt_cur->_t_color;
pt_cur->_t_color = t_colortmp;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_curtmp->_pt_right, pt_curtmp);
}
} else {
/*
* p p
* / /
* c => rll
* / \ / \
* l r l r
* / \ / \
* rl rr rl rr
* / \ \ \ \
* rll rlr rrr rlr rrr
*/
pt_parenttmp = pt_curtmp->_pt_parent;
pt_parenttmp->_pt_left = pt_curtmp->_pt_right;
if (pt_parenttmp->_pt_left != NULL) {
pt_parenttmp->_pt_left->_pt_parent = pt_parenttmp;
}
pt_curtmp->_pt_left = pt_cur->_pt_left;
pt_curtmp->_pt_left->_pt_parent = pt_curtmp;
pt_curtmp->_pt_right = pt_cur->_pt_right;
pt_curtmp->_pt_right->_pt_parent = pt_curtmp;
pt_curtmp->_pt_parent = pt_cur->_pt_parent;
pt_curtmp->_pt_parent->_pt_left = pt_curtmp;
pt_curtmp->_t_color = pt_cur->_t_color;
pt_cur->_t_color = t_colortmp;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_parenttmp->_pt_left, pt_parenttmp);
}
}
}
} else {
if (pt_cur->_pt_left == NULL && pt_cur->_pt_right == NULL) {
/*
* p p
* \ =>
* c
*/
pt_parent->_pt_right = NULL;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_parent->_pt_right, pt_parent);
}
} else if (pt_cur->_pt_left != NULL && pt_cur->_pt_right == NULL) {
/*
* p p
* \ \
* c => l
* /
* l
*/
pt_parent->_pt_right = pt_cur->_pt_left;
pt_parent->_pt_right->_pt_parent = pt_parent;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_parent->_pt_right, pt_parent);
}
} else if (pt_cur->_pt_left == NULL && pt_cur->_pt_right != NULL) {
/*
* p p
* \ \
* c => r
* \
* r
*/
pt_parent->_pt_right = pt_cur->_pt_right;
pt_parent->_pt_right->_pt_parent = pt_parent;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_parent->_pt_right, pt_parent);
}
} else {
/*
* here the real deleted node is pt_curtmp, so the
* color of pt_curtmp is used.
*/
pt_curtmp = _rb_tree_get_min_rbnode(pt_cur->_pt_right);
t_colortmp = pt_curtmp->_t_color;
if (pt_cur == pt_curtmp->_pt_parent) {
/*
* p p
* \ \
* c => r
* / \ / \
* l r l rr
* \
* rr
*/
pt_curtmp->_pt_left = pt_cur->_pt_left;
pt_curtmp->_pt_left->_pt_parent = pt_curtmp;
pt_curtmp->_pt_parent = pt_cur->_pt_parent;
pt_curtmp->_pt_parent->_pt_right = pt_curtmp;
pt_curtmp->_t_color = pt_cur->_t_color;
pt_cur->_t_color = t_colortmp;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_curtmp->_pt_right, pt_curtmp);
}
} else {
/*
* p p
* \ \
* c => rll
* / \ / \
* l r l r
* / \ / \
* rl rr rl rr
* / \ \ \ \
* rll rlr rrr rlr rrr
*/
pt_parenttmp = pt_curtmp->_pt_parent;
pt_parenttmp->_pt_left = pt_curtmp->_pt_right;
if (pt_parenttmp->_pt_left != NULL) {
pt_parenttmp->_pt_left->_pt_parent = pt_parenttmp;
}
pt_curtmp->_pt_left = pt_cur->_pt_left;
pt_curtmp->_pt_left->_pt_parent = pt_curtmp;
pt_curtmp->_pt_right = pt_cur->_pt_right;
pt_curtmp->_pt_right->_pt_parent = pt_curtmp;
pt_curtmp->_pt_parent = pt_cur->_pt_parent;
pt_curtmp->_pt_parent->_pt_right = pt_curtmp;
pt_curtmp->_t_color = pt_cur->_t_color;
pt_cur->_t_color = t_colortmp;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_parenttmp->_pt_left, pt_parenttmp);
}
}
}
}
/* destroy the node */
b_result = _GET_RB_TREE_TYPE_SIZE(pt_rb_tree);
_GET_RB_TREE_TYPE_DESTROY_FUNCTION(pt_rb_tree)(pt_cur->_pby_data, &b_result);
assert(b_result);
_alloc_deallocate(&pt_rb_tree->_t_allocator, pt_cur, _RB_TREE_NODE_SIZE(_GET_RB_TREE_TYPE_SIZE(pt_rb_tree)), 1);
pt_rb_tree->_t_nodecount--;
/* update the left and right pointer */
if (pt_rb_tree->_t_nodecount == 0) {
pt_rb_tree->_t_rbroot._pt_parent = NULL;
pt_rb_tree->_t_rbroot._pt_left = &pt_rb_tree->_t_rbroot;
pt_rb_tree->_t_rbroot._pt_right = &pt_rb_tree->_t_rbroot;
} else {
pt_rb_tree->_t_rbroot._pt_left = _rb_tree_get_min_rbnode(pt_rb_tree->_t_rbroot._pt_parent);
pt_rb_tree->_t_rbroot._pt_right = _rb_tree_get_max_rbnode(pt_rb_tree->_t_rbroot._pt_parent);
}
}
/*
* Erase a range of element in an rb tree.
*/
void _rb_tree_erase_range(_rb_tree_t* pt_rb_tree, _rb_tree_iterator_t it_begin, _rb_tree_iterator_t it_end)
{
_rb_tree_iterator_t it_iter;
_rb_tree_iterator_t it_next;
assert(pt_rb_tree != NULL);
assert(_rb_tree_is_inited(pt_rb_tree));
assert(_rb_tree_same_rb_tree_iterator_type(pt_rb_tree, it_begin));
assert(_rb_tree_same_rb_tree_iterator_type(pt_rb_tree, it_end));
assert(_rb_tree_iterator_equal(it_begin, it_end) || _rb_tree_iterator_before(it_begin, it_end));
it_iter = it_next = it_begin;
if (!_rb_tree_iterator_equal(it_next, _rb_tree_end(pt_rb_tree))) {
it_next = _rb_tree_iterator_next(it_next);
}
while (!_rb_tree_iterator_equal(it_iter, it_end)) {
_rb_tree_erase_pos(pt_rb_tree, it_iter);
it_iter = it_next;
if (!_rb_tree_iterator_equal(it_next, _rb_tree_end(pt_rb_tree))) {
it_next = _rb_tree_iterator_next(it_next);
}
}
}
/**
* Erase an element from a rb tree that match a specified element.
*/
size_t _rb_tree_erase(_rb_tree_t* pt_rb_tree, const void* cpv_value)
{
size_t t_count = 0;
range_t r_range;
assert(pt_rb_tree != NULL);
assert(cpv_value != NULL);
assert(_rb_tree_is_inited(pt_rb_tree));
t_count = _rb_tree_count(pt_rb_tree, cpv_value);
r_range = _rb_tree_equal_range(pt_rb_tree, cpv_value);
if (!_rb_tree_iterator_equal(r_range.it_begin, _rb_tree_end(pt_rb_tree))) {
_rb_tree_erase_range(pt_rb_tree, r_range.it_begin, r_range.it_end);
}
return t_count;
}
/** local function implementation section **/
/** eof **/
|
activesys/libcstl
|
src/cstl_rb_tree.c
|
C
|
lgpl-2.1
| 42,916
|
/*
* crypt.c - blowfish-cbc code
*
* This file is part of the SSH Library
*
* Copyright (c) 2003 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH 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 the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include "config.h"
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifndef _WIN32
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#ifdef OPENSSL_CRYPTO
#include <openssl/blowfish.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#endif
#include "libssh/priv.h"
#include "libssh/session.h"
#include "libssh/wrapper.h"
#include "libssh/crypto.h"
#include "libssh/buffer.h"
uint32_t packet_decrypt_len(ssh_session session, char *crypted){
uint32_t decrypted;
if (session->current_crypto) {
if (packet_decrypt(session, crypted,
session->current_crypto->in_cipher->blocksize) < 0) {
return 0;
}
}
memcpy(&decrypted,crypted,sizeof(decrypted));
return ntohl(decrypted);
}
int packet_decrypt(ssh_session session, void *data,uint32_t len) {
struct ssh_cipher_struct *crypto = session->current_crypto->in_cipher;
char *out = NULL;
assert(len);
if(len % session->current_crypto->in_cipher->blocksize != 0){
ssh_set_error(session, SSH_FATAL, "Cryptographic functions must be set on at least one blocksize (received %d)",len);
return SSH_ERROR;
}
out = malloc(len);
if (out == NULL) {
return -1;
}
if (crypto->set_decrypt_key(crypto, session->current_crypto->decryptkey,
session->current_crypto->decryptIV) < 0) {
SAFE_FREE(out);
return -1;
}
crypto->cbc_decrypt(crypto,data,out,len);
memcpy(data,out,len);
memset(out,0,len);
SAFE_FREE(out);
return 0;
}
unsigned char *packet_encrypt(ssh_session session, void *data, uint32_t len) {
struct ssh_cipher_struct *crypto = NULL;
HMACCTX ctx = NULL;
char *out = NULL;
unsigned int finallen;
uint32_t seq;
assert(len);
if (!session->current_crypto) {
return NULL; /* nothing to do here */
}
if(len % session->current_crypto->in_cipher->blocksize != 0){
ssh_set_error(session, SSH_FATAL, "Cryptographic functions must be set on at least one blocksize (received %d)",len);
return NULL;
}
out = malloc(len);
if (out == NULL) {
return NULL;
}
seq = ntohl(session->send_seq);
crypto = session->current_crypto->out_cipher;
if (crypto->set_encrypt_key(crypto, session->current_crypto->encryptkey,
session->current_crypto->encryptIV) < 0) {
SAFE_FREE(out);
return NULL;
}
if (session->version == 2) {
ctx = hmac_init(session->current_crypto->encryptMAC,20,SSH_HMAC_SHA1);
if (ctx == NULL) {
SAFE_FREE(out);
return NULL;
}
hmac_update(ctx,(unsigned char *)&seq,sizeof(uint32_t));
hmac_update(ctx,data,len);
hmac_final(ctx,session->current_crypto->hmacbuf,&finallen);
#ifdef DEBUG_CRYPTO
ssh_print_hexa("mac: ",data,len);
if (finallen != 20) {
printf("Final len is %d\n",finallen);
}
ssh_print_hexa("Packet hmac", session->current_crypto->hmacbuf, 20);
#endif
}
crypto->cbc_encrypt(crypto, data, out, len);
memcpy(data, out, len);
memset(out, 0, len);
SAFE_FREE(out);
if (session->version == 2) {
return session->current_crypto->hmacbuf;
}
return NULL;
}
/**
* @internal
*
* @brief Verify the hmac of a packet
*
* @param session The session to use.
* @param buffer The buffer to verify the hmac from.
* @param mac The mac to compare with the hmac.
*
* @return 0 if hmac and mac are equal, < 0 if not or an error
* occurred.
*/
int packet_hmac_verify(ssh_session session, ssh_buffer buffer,
unsigned char *mac) {
unsigned char hmacbuf[EVP_MAX_MD_SIZE] = {0};
HMACCTX ctx;
unsigned int len;
uint32_t seq;
ctx = hmac_init(session->current_crypto->decryptMAC, 20, SSH_HMAC_SHA1);
if (ctx == NULL) {
return -1;
}
seq = htonl(session->recv_seq);
hmac_update(ctx, (unsigned char *) &seq, sizeof(uint32_t));
hmac_update(ctx, buffer_get_rest(buffer), buffer_get_rest_len(buffer));
hmac_final(ctx, hmacbuf, &len);
#ifdef DEBUG_CRYPTO
ssh_print_hexa("received mac",mac,len);
ssh_print_hexa("Computed mac",hmacbuf,len);
ssh_print_hexa("seq",(unsigned char *)&seq,sizeof(uint32_t));
#endif
if (memcmp(mac, hmacbuf, len) == 0) {
return 0;
}
return -1;
}
/* vim: set ts=2 sw=2 et cindent: */
|
tux-mind/platform_external_libssh
|
src/packet_crypt.c
|
C
|
lgpl-2.1
| 5,124
|
#include "clar_libgit2.h"
#include "git2/sys/repository.h"
#include "fileops.h"
#include "ignore.h"
#include "status_helpers.h"
#include "posix.h"
#include "util.h"
#include "path.h"
static void cleanup_new_repo(void *path)
{
cl_fixture_cleanup((char *)path);
}
void test_status_worktree_init__cannot_retrieve_the_status_of_a_bare_repository(void)
{
git_repository *repo;
unsigned int status = 0;
cl_git_pass(git_repository_open(&repo, cl_fixture("testrepo.git")));
cl_assert_equal_i(GIT_EBAREREPO, git_status_file(&status, repo, "dummy"));
git_repository_free(repo);
}
void test_status_worktree_init__first_commit_in_progress(void)
{
git_repository *repo;
git_index *index;
status_entry_single result;
cl_set_cleanup(&cleanup_new_repo, "getting_started");
cl_git_pass(git_repository_init(&repo, "getting_started", 0));
cl_git_mkfile("getting_started/testfile.txt", "content\n");
memset(&result, 0, sizeof(result));
cl_git_pass(git_status_foreach(repo, cb_status__single, &result));
cl_assert_equal_i(1, result.count);
cl_assert(result.status == GIT_STATUS_WT_NEW);
cl_git_pass(git_repository_index(&index, repo));
cl_git_pass(git_index_add_bypath(index, "testfile.txt"));
cl_git_pass(git_index_write(index));
memset(&result, 0, sizeof(result));
cl_git_pass(git_status_foreach(repo, cb_status__single, &result));
cl_assert_equal_i(1, result.count);
cl_assert(result.status == GIT_STATUS_INDEX_NEW);
git_index_free(index);
git_repository_free(repo);
}
void test_status_worktree_init__status_file_without_index_or_workdir(void)
{
git_repository *repo;
unsigned int status = 0;
git_index *index;
cl_git_pass(p_mkdir("wd", 0777));
cl_git_pass(git_repository_open(&repo, cl_fixture("testrepo.git")));
cl_git_pass(git_repository_set_workdir(repo, "wd", false));
cl_git_pass(git_index_open(&index, "empty-index"));
cl_assert_equal_i(0, (int)git_index_entrycount(index));
git_repository_set_index(repo, index);
cl_git_pass(git_status_file(&status, repo, "branch_file.txt"));
cl_assert_equal_i(GIT_STATUS_INDEX_DELETED, status);
git_repository_free(repo);
git_index_free(index);
cl_git_pass(p_rmdir("wd"));
}
static void fill_index_wth_head_entries(git_repository *repo, git_index *index)
{
git_oid oid;
git_commit *commit;
git_tree *tree;
cl_git_pass(git_reference_name_to_id(&oid, repo, "HEAD"));
cl_git_pass(git_commit_lookup(&commit, repo, &oid));
cl_git_pass(git_commit_tree(&tree, commit));
cl_git_pass(git_index_read_tree(index, tree));
cl_git_pass(git_index_write(index));
git_tree_free(tree);
git_commit_free(commit);
}
void test_status_worktree_init__status_file_with_clean_index_and_empty_workdir(void)
{
git_repository *repo;
unsigned int status = 0;
git_index *index;
cl_git_pass(p_mkdir("wd", 0777));
cl_git_pass(git_repository_open(&repo, cl_fixture("testrepo.git")));
cl_git_pass(git_repository_set_workdir(repo, "wd", false));
cl_git_pass(git_index_open(&index, "my-index"));
fill_index_wth_head_entries(repo, index);
git_repository_set_index(repo, index);
cl_git_pass(git_status_file(&status, repo, "branch_file.txt"));
cl_assert_equal_i(GIT_STATUS_WT_DELETED, status);
git_repository_free(repo);
git_index_free(index);
cl_git_pass(p_rmdir("wd"));
cl_git_pass(p_unlink("my-index"));
}
void test_status_worktree_init__bracket_in_filename(void)
{
git_repository *repo;
git_index *index;
status_entry_single result;
unsigned int status_flags;
int error;
#define FILE_WITH_BRACKET "LICENSE[1].md"
#define FILE_WITHOUT_BRACKET "LICENSE1.md"
cl_set_cleanup(&cleanup_new_repo, "with_bracket");
cl_git_pass(git_repository_init(&repo, "with_bracket", 0));
cl_git_mkfile("with_bracket/" FILE_WITH_BRACKET, "I have a bracket in my name\n");
/* file is new to working directory */
memset(&result, 0, sizeof(result));
cl_git_pass(git_status_foreach(repo, cb_status__single, &result));
cl_assert_equal_i(1, result.count);
cl_assert(result.status == GIT_STATUS_WT_NEW);
cl_git_pass(git_status_file(&status_flags, repo, FILE_WITH_BRACKET));
cl_assert(status_flags == GIT_STATUS_WT_NEW);
/* ignore the file */
cl_git_rewritefile("with_bracket/.gitignore", "*.md\n.gitignore\n");
memset(&result, 0, sizeof(result));
cl_git_pass(git_status_foreach(repo, cb_status__single, &result));
cl_assert_equal_i(2, result.count);
cl_assert(result.status == GIT_STATUS_IGNORED);
cl_git_pass(git_status_file(&status_flags, repo, FILE_WITH_BRACKET));
cl_assert(status_flags == GIT_STATUS_IGNORED);
/* don't ignore the file */
cl_git_rewritefile("with_bracket/.gitignore", ".gitignore\n");
memset(&result, 0, sizeof(result));
cl_git_pass(git_status_foreach(repo, cb_status__single, &result));
cl_assert_equal_i(2, result.count);
cl_assert(result.status == GIT_STATUS_WT_NEW);
cl_git_pass(git_status_file(&status_flags, repo, FILE_WITH_BRACKET));
cl_assert(status_flags == GIT_STATUS_WT_NEW);
/* add the file to the index */
cl_git_pass(git_repository_index(&index, repo));
cl_git_pass(git_index_add_bypath(index, FILE_WITH_BRACKET));
cl_git_pass(git_index_write(index));
memset(&result, 0, sizeof(result));
cl_git_pass(git_status_foreach(repo, cb_status__single, &result));
cl_assert_equal_i(2, result.count);
cl_assert(result.status == GIT_STATUS_INDEX_NEW);
cl_git_pass(git_status_file(&status_flags, repo, FILE_WITH_BRACKET));
cl_assert(status_flags == GIT_STATUS_INDEX_NEW);
/* Create file without bracket */
cl_git_mkfile("with_bracket/" FILE_WITHOUT_BRACKET, "I have no bracket in my name!\n");
cl_git_pass(git_status_file(&status_flags, repo, FILE_WITHOUT_BRACKET));
cl_assert(status_flags == GIT_STATUS_WT_NEW);
cl_git_pass(git_status_file(&status_flags, repo, "LICENSE\\[1\\].md"));
cl_assert(status_flags == GIT_STATUS_INDEX_NEW);
cl_git_pass(git_status_file(&status_flags, repo, FILE_WITH_BRACKET));
git_index_free(index);
git_repository_free(repo);
}
void test_status_worktree_init__space_in_filename(void)
{
git_repository *repo;
git_index *index;
status_entry_single result;
unsigned int status_flags;
#define FILE_WITH_SPACE "LICENSE - copy.md"
cl_set_cleanup(&cleanup_new_repo, "with_space");
cl_git_pass(git_repository_init(&repo, "with_space", 0));
cl_git_mkfile("with_space/" FILE_WITH_SPACE, "I have a space in my name\n");
/* file is new to working directory */
memset(&result, 0, sizeof(result));
cl_git_pass(git_status_foreach(repo, cb_status__single, &result));
cl_assert_equal_i(1, result.count);
cl_assert(result.status == GIT_STATUS_WT_NEW);
cl_git_pass(git_status_file(&status_flags, repo, FILE_WITH_SPACE));
cl_assert(status_flags == GIT_STATUS_WT_NEW);
/* ignore the file */
cl_git_rewritefile("with_space/.gitignore", "*.md\n.gitignore\n");
memset(&result, 0, sizeof(result));
cl_git_pass(git_status_foreach(repo, cb_status__single, &result));
cl_assert_equal_i(2, result.count);
cl_assert(result.status == GIT_STATUS_IGNORED);
cl_git_pass(git_status_file(&status_flags, repo, FILE_WITH_SPACE));
cl_assert(status_flags == GIT_STATUS_IGNORED);
/* don't ignore the file */
cl_git_rewritefile("with_space/.gitignore", ".gitignore\n");
memset(&result, 0, sizeof(result));
cl_git_pass(git_status_foreach(repo, cb_status__single, &result));
cl_assert_equal_i(2, result.count);
cl_assert(result.status == GIT_STATUS_WT_NEW);
cl_git_pass(git_status_file(&status_flags, repo, FILE_WITH_SPACE));
cl_assert(status_flags == GIT_STATUS_WT_NEW);
/* add the file to the index */
cl_git_pass(git_repository_index(&index, repo));
cl_git_pass(git_index_add_bypath(index, FILE_WITH_SPACE));
cl_git_pass(git_index_write(index));
memset(&result, 0, sizeof(result));
cl_git_pass(git_status_foreach(repo, cb_status__single, &result));
cl_assert_equal_i(2, result.count);
cl_assert(result.status == GIT_STATUS_INDEX_NEW);
cl_git_pass(git_status_file(&status_flags, repo, FILE_WITH_SPACE));
cl_assert(status_flags == GIT_STATUS_INDEX_NEW);
git_index_free(index);
git_repository_free(repo);
}
static int cb_status__expected_path(const char *p, unsigned int s, void *payload)
{
const char *expected_path = (const char *)payload;
GIT_UNUSED(s);
if (payload == NULL)
cl_fail("Unexpected path");
cl_assert_equal_s(expected_path, p);
return 0;
}
void test_status_worktree_init__disable_pathspec_match(void)
{
git_repository *repo;
git_status_options opts = GIT_STATUS_OPTIONS_INIT;
char *file_with_bracket = "LICENSE[1].md",
*imaginary_file_with_bracket = "LICENSE[1-2].md";
cl_set_cleanup(&cleanup_new_repo, "pathspec");
cl_git_pass(git_repository_init(&repo, "pathspec", 0));
cl_git_mkfile("pathspec/LICENSE[1].md", "screaming bracket\n");
cl_git_mkfile("pathspec/LICENSE1.md", "no bracket\n");
opts.flags = GIT_STATUS_OPT_INCLUDE_UNTRACKED |
GIT_STATUS_OPT_DISABLE_PATHSPEC_MATCH;
opts.pathspec.count = 1;
opts.pathspec.strings = &file_with_bracket;
cl_git_pass(
git_status_foreach_ext(repo, &opts, cb_status__expected_path,
file_with_bracket)
);
/* Test passing a pathspec matching files in the workdir. */
/* Must not match because pathspecs are disabled. */
opts.pathspec.strings = &imaginary_file_with_bracket;
cl_git_pass(
git_status_foreach_ext(repo, &opts, cb_status__expected_path, NULL)
);
git_repository_free(repo);
}
void test_status_worktree_init__new_staged_file_must_handle_crlf(void)
{
git_repository *repo;
git_index *index;
unsigned int status;
cl_set_cleanup(&cleanup_new_repo, "getting_started");
cl_git_pass(git_repository_init(&repo, "getting_started", 0));
/* Ensure that repo has core.autocrlf=true */
cl_repo_set_bool(repo, "core.autocrlf", true);
cl_git_mkfile("getting_started/testfile.txt", "content\r\n"); /* Content with CRLF */
cl_git_pass(git_repository_index(&index, repo));
cl_git_pass(git_index_add_bypath(index, "testfile.txt"));
cl_git_pass(git_index_write(index));
cl_git_pass(git_status_file(&status, repo, "testfile.txt"));
cl_assert_equal_i(GIT_STATUS_INDEX_NEW, status);
git_index_free(index);
git_repository_free(repo);
}
|
raybrad/libit2
|
tests/status/worktree_init.c
|
C
|
lgpl-2.1
| 10,050
|
/*
* bsb2png.c - Convert a bsb raster image to a Portable Network Graphics (png).
* See http://www.libpng.org for details of the PNG format and how
* to use libpng.
*
* Copyright (C) 2004 Stefan Petersen <spetm@users.sourceforge.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* 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
*
* $Id: bsb2png.c,v 1.7 2007/02/05 17:08:18 mikrom Exp $
*
*/
#include <stdlib.h>
#include <stdio.h>
#include <bsb.h>
#include <png.h>
static void copy_bsb_to_png(BSBImage *image, png_structp png_ptr)
{
int row, bp, pp;
uint8_t *bsb_row, *png_row;
bsb_row = (uint8_t *)malloc(image->height * sizeof(uint8_t *));
png_row = (uint8_t *)malloc(image->height * sizeof(uint8_t *) * image->depth);
/* Copy row by row */
for (row = 0; row < image->height; row++)
{
bsb_seek_to_row(image, row);
bsb_read_row(image, bsb_row);
for (bp = 0, pp = 0; bp < image->width; bp++)
{
png_row[pp++] = image->red[bsb_row[bp]];
png_row[pp++] = image->green[bsb_row[bp]];
png_row[pp++] = image->blue[bsb_row[bp]];
}
png_write_row(png_ptr, png_row);
}
free(bsb_row);
free(png_row);
} /* copy_bsb_to_png */
int main(int argc, char *argv[])
{
BSBImage image;
FILE *png_fd;
png_structp png_ptr;
png_infop info_ptr;
png_text text[2];
if (argc != 3) {
fprintf(stderr, "Usage:\n\tbsb2png input.kap output.png\n");
exit(1);
}
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (png_ptr == NULL) {
fprintf(stderr, "png_ptr == NULL\n");
exit(1);
}
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL) {
fprintf(stderr, "info_ptr == NULL\n");
png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
exit(1);
}
if ((png_fd = fopen(argv[2], "wb")) == NULL) {
perror("fopen");
exit(1);
}
png_init_io(png_ptr, png_fd);
if (! bsb_open_header(argv[1], &image)) {
exit(1);
}
png_set_IHDR(png_ptr, info_ptr, image.width, image.height, 8,
PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
/* Some text to go with the png image */
text[0].key = "Title";
text[0].text = argv[2];
text[0].compression = PNG_TEXT_COMPRESSION_NONE;
text[1].key = "Generator";
text[1].text = "bsb2png";
text[1].compression = PNG_TEXT_COMPRESSION_NONE;
png_set_text(png_ptr, info_ptr, text, 2);
/* Write header data */
png_write_info(png_ptr, info_ptr);
/* Copy the image in itself */
copy_bsb_to_png(&image, png_ptr);
png_write_end(png_ptr, NULL);
fclose(png_fd);
png_destroy_write_struct(&png_ptr, &info_ptr);
bsb_close(&image);
return 0;
}
|
nohal/libbsb
|
bsb2png.c
|
C
|
lgpl-2.1
| 3,266
|
/******************************************************************************
*
* Copyright (C) 2006-2015 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
******************************************************************************/
#include "config.h"
#include "logging.h"
#include "mem_util.h"
#include <stdio.h>
#include <stdlib.h>
#undef _XOPEN_SOURCE
#define _XOPEN_SOURCE 600
#include <string.h>
/* Our log file */
static FILE *mcell_log_file = NULL;
/* Our warning/error file */
static FILE *mcell_error_file = NULL;
/* Get the log file. */
FILE *mcell_get_log_file(void) {
if (mcell_log_file == NULL) {
#ifdef DEBUG
setvbuf(stdout, NULL, _IONBF, 0);
#endif
mcell_log_file = stdout;
}
return mcell_log_file;
}
/* Get the error file. */
FILE *mcell_get_error_file(void) {
if (mcell_error_file == NULL) {
#ifdef DEBUG
setvbuf(stderr, NULL, _IONBF, 0);
#endif
mcell_error_file = stderr;
}
return mcell_error_file;
}
/* Set the log file. */
void mcell_set_log_file(FILE *f) {
if (mcell_log_file != NULL && mcell_log_file != stdout &&
mcell_log_file != stderr)
fclose(mcell_log_file);
mcell_log_file = f;
#ifdef DEBUG
setvbuf(mcell_log_file, NULL, _IONBF, 0);
#else
setvbuf(mcell_log_file, NULL, _IOLBF, 128);
#endif
}
/* Set the error file. */
void mcell_set_error_file(FILE *f) {
if (mcell_error_file != NULL && mcell_error_file != stdout &&
mcell_error_file != stderr)
fclose(mcell_error_file);
mcell_error_file = f;
#ifdef DEBUG
setvbuf(mcell_error_file, NULL, _IONBF, 0);
#else
setvbuf(mcell_error_file, NULL, _IOLBF, 128);
#endif
}
/* Log a message. */
void mcell_log_raw(char const *fmt, ...) {
va_list args;
va_start(args, fmt);
mcell_logv_raw(fmt, args);
va_end(args);
}
/* Log a message (va_list version). */
void mcell_logv_raw(char const *fmt, va_list args) {
vfprintf(mcell_get_log_file(), fmt, args);
}
/* Log a message. */
void mcell_error_raw(char const *fmt, ...) {
va_list args;
va_start(args, fmt);
mcell_errorv_raw(fmt, args);
va_end(args);
}
/* Log a message (va_list version). */
void mcell_errorv_raw(char const *fmt, va_list args) {
vfprintf(mcell_get_error_file(), fmt, args);
}
/* Log a message. */
void mcell_log(char const *fmt, ...) {
va_list args;
va_start(args, fmt);
mcell_logv(fmt, args);
va_end(args);
}
/* Log a message (va_list version). */
void mcell_logv(char const *fmt, va_list args) {
mcell_logv_raw(fmt, args);
fprintf(mcell_get_log_file(), "\n");
}
/* Log a warning. */
void mcell_warn(char const *fmt, ...) {
va_list args;
va_start(args, fmt);
mcell_warnv(fmt, args);
va_end(args);
}
/* Log a warning (va_list version). */
void mcell_warnv(char const *fmt, va_list args) {
fprintf(mcell_get_error_file(), "Warning: ");
mcell_errorv_raw(fmt, args);
fprintf(mcell_get_error_file(), "\n");
}
/* Log an error and carry on. */
void mcell_error_nodie(char const *fmt, ...) {
va_list args;
va_start(args, fmt);
mcell_errorv_nodie(fmt, args);
va_end(args);
}
/* Log an error and carry on (va_list version). */
void mcell_errorv_nodie(char const *fmt, va_list args) {
fprintf(mcell_get_error_file(), "Fatal error: ");
mcell_errorv_raw(fmt, args);
fprintf(mcell_get_error_file(), "\n");
}
/* Log an error and exit. */
void mcell_error(char const *fmt, ...) {
va_list args;
va_start(args, fmt);
mcell_errorv(fmt, args);
va_end(args);
}
/* Log an error and exit (va_list version). */
void mcell_errorv(char const *fmt, va_list args) {
mcell_errorv_nodie(fmt, args);
mcell_die();
}
/* Log an internal error and exit. */
void mcell_internal_error_(char const *file, unsigned int line,
char const *func, char const *fmt, ...) {
va_list args;
va_start(args, fmt);
mcell_internal_errorv_(file, line, func, fmt, args);
va_end(args);
}
/* Log an error and exit (va_list version). */
void mcell_internal_errorv_(char const *file, unsigned int line,
char const *func, char const *fmt, va_list args) {
fprintf(mcell_get_error_file(), "****************\n");
fprintf(mcell_get_error_file(), "INTERNAL ERROR at %s:%u [%s]: ", file, line,
func);
mcell_errorv_raw(fmt, args);
fprintf(mcell_get_error_file(), "\n");
fprintf(mcell_get_error_file(),
"MCell has detected an internal program error.\n");
fprintf(mcell_get_error_file(),
"Please report this error to the MCell developers at <%s>.\n",
PACKAGE_BUGREPORT);
fprintf(mcell_get_error_file(), "****************\n");
mcell_die();
}
/* Get a copy of a string giving an error message. */
char *mcell_strerror(int err) {
char buffer[2048];
#ifdef STRERROR_R_CHAR_P
char *pbuf = strerror_r(err, buffer, sizeof(buffer));
if (pbuf != NULL)
return CHECKED_STRDUP(pbuf, "error description");
else
return CHECKED_SPRINTF("UNIX error code %d.", err);
#else
if (strerror_r(err, buffer, sizeof(buffer)) == 0)
return CHECKED_STRDUP(buffer, "error description");
else
return CHECKED_SPRINTF("UNIX error code %d.", err);
#endif
}
/* Log an error due to a failed standard library call, and exit. */
void mcell_perror_nodie(int err, char const *fmt, ...) {
va_list args;
va_start(args, fmt);
mcell_perrorv_nodie(err, fmt, args);
va_end(args);
}
/* Log an error due to a failed standard library call, and exit (va_list
* version). */
void mcell_perrorv_nodie(int err, char const *fmt, va_list args) {
char buffer[2048];
fprintf(mcell_get_error_file(), "Fatal error: ");
mcell_errorv_raw(fmt, args);
#ifdef STRERROR_R_CHAR_P
fprintf(mcell_get_error_file(), ": %s\n",
strerror_r(err, buffer, sizeof(buffer)));
#else
if (strerror_r(err, buffer, sizeof(buffer)) == 0)
fprintf(mcell_get_error_file(), ": %s\n", buffer);
else
fprintf(mcell_get_error_file(), "\n");
#endif
}
/* Log an error due to a failed standard library call, and exit. */
void mcell_perror(int err, char const *fmt, ...) {
va_list args;
va_start(args, fmt);
mcell_perrorv(err, fmt, args);
va_end(args);
}
/* Log an error due to a failed standard library call, and exit (va_list
* version). */
void mcell_perrorv(int err, char const *fmt, va_list args) {
mcell_perrorv_nodie(err, fmt, args);
mcell_die();
}
/* Log an error due to failed memory allocation, but do not exit. */
void mcell_allocfailed_nodie(char const *fmt, ...) {
va_list args;
va_start(args, fmt);
mcell_allocfailedv_nodie(fmt, args);
va_end(args);
}
/* Log an error due to failed memory allocation, but do not exit (va_list
* version). */
void mcell_allocfailedv_nodie(char const *fmt, va_list args) {
fprintf(mcell_get_error_file(), "Fatal error: ");
mcell_errorv_raw(fmt, args);
fprintf(mcell_get_error_file(), "\n");
fprintf(mcell_get_error_file(), "Fatal error: Out of memory\n\n");
mem_dump_stats(mcell_get_error_file());
}
/* Log an error due to failed memory allocation, and exit. */
void mcell_allocfailed(char const *fmt, ...) {
va_list args;
va_start(args, fmt);
mcell_allocfailedv_nodie(fmt, args);
va_end(args);
mcell_die();
}
/* Log an error due to failed memory allocation, and exit (va_list version). */
void mcell_allocfailedv(char const *fmt, va_list args) {
mcell_allocfailedv_nodie(fmt, args);
mcell_die();
}
/* Terminate program execution due to an error. */
void mcell_die(void) { exit(EXIT_FAILURE); }
|
jczech/appveyor_test
|
mcell/src/logging.c
|
C
|
lgpl-2.1
| 8,209
|
/* mgrp_test.c
*
* Test messenger group broadcast/receive functionality and concurrency.
* Each thread broadcasts a counter from 0 to ITERS, to all other threads
* (but not itself).
* Every receiving thread should sum received integers into a per-thread
* rx_sum variable.
* Every thread should accumulate the same rx_sum, which is:
* (ITERS -1) * ITERS * (THREAD_CNT -1) * 0.5
* (see memorywell/test/well_test.c for more details).
*
* (c) 2018 Sirio Balmelli and Anthony Soenen
*/
#include <ndebug.h>
#include <posigs.h> /* use atomic PSG kill flag as a global error flag */
#include <pcg_rand.h>
#include <messenger.h>
#include <pthread.h>
#include <stdbool.h>
#include <unistd.h>
#include <fcntl.h>
#define THREAD_CNT 2
#define ITERS 2 /* How many messages each thread should send.
* TODO: increase once registration/rcu issue is resolved.
*/
/* thread()
*/
void *thread(void* arg)
{
struct mgrp *group = arg;
int pvc[2] = { 0, 0 };
size_t rx_sum = 0, rx_i = 0;
size_t message;
NB_die_if(
pipe(pvc)
|| fcntl(pvc[0], F_SETFL, fcntl(pvc[0], F_GETFL) | O_NONBLOCK)
, "");
NB_die_if(
mgrp_subscribe(group, pvc[1])
, "");
/* Don't start broadcasting until everyone is subscribed.
* We could use pthread_barrier_t but that's not implemented on macOS,
* and anyways messenger()'s mgrp_count uses acquire/release semantics.
*/
while (mgrp_count(group) != THREAD_CNT && !psg_kill_check())
sched_yield();
/* generate ITERS broadcasts; receive others' broadcasts */
for (size_t i = 0; i < ITERS && !psg_kill_check(); i++) {
NB_die_if(
mgrp_broadcast(group, pvc[1], &i, sizeof(i))
, "");
while ((mg_recv(pvc[0], &message) > 0) && !psg_kill_check()) {
rx_sum += message;
rx_i++;
sched_yield(); /* prevent deadlock: give other threads a chance to write */
}
errno = 0; /* _should_ be EINVAL: don't pollute later prints */
}
/* wait for all other senders */
while (rx_i < ITERS * (THREAD_CNT -1) && !psg_kill_check()) {
if ((mg_recv(pvc[0], &message) > 0)) {
rx_sum += message;
rx_i++;
} else {
sched_yield();
}
}
die:
NB_err_if(
mgrp_unsubscribe(group, pvc[1])
, "fd %d unsubscribe fail", pvc[1]);
if (err_cnt)
psg_kill();
if (pvc[0]) {
close(pvc[1]);
close(pvc[0]);
}
return (void *)rx_sum;
}
/* main()
*/
int main()
{
int err_cnt = 0;
struct mgrp *group = NULL;
pthread_t threads[THREAD_CNT];
NB_die_if(!(
group = mgrp_new()
), "");
/* run all threads */
for (unsigned int i=0; i < THREAD_CNT; i++) {
NB_die_if(pthread_create(&threads[i], NULL, thread, group), "");
}
/* test results */
size_t expected = (ITERS -1) * ITERS * (THREAD_CNT -1) * 0.5;
for (unsigned int i=0; i < THREAD_CNT; i++) {
size_t rx_sum;
NB_die_if(
pthread_join(threads[i], (void **)&rx_sum)
, "");
NB_err_if(rx_sum != expected,
"thread %zu != expected %zu", rx_sum, expected);
}
die:
mgrp_free(group);
err_cnt += psg_kill_check(); /* return any error from any thread */
return err_cnt;
}
|
siriobalmelli/nonlibc
|
test/mgrp_test.c
|
C
|
lgpl-2.1
| 3,010
|
/* Copyright 2010, 2011 Michael Steinert
* This file is part of Log4g.
*
* Log4g is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 2.1 of the License, or (at your option)
* any later version.
*
* Log4g 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 Log4g. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* SECTION: logging-event
* @short_description: The internal representation of logging events
*
* Once an affirmative decision is made to log an event a logging event
* instance is created. This instance is passed to appenders and filters to
* perform actual logging.
*
* <note><para>
* This class is only useful to those wishing to extend Log4g.
* </para></note>
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <errno.h>
#include "log4g/helpers/thread.h"
#include "log4g/logging-event.h"
#include "log4g/mdc.h"
#include "log4g/ndc.h"
G_DEFINE_TYPE(Log4gLoggingEvent, log4g_logging_event, G_TYPE_OBJECT)
#define ASSIGN_PRIVATE(instance) \
(G_TYPE_INSTANCE_GET_PRIVATE(instance, LOG4G_TYPE_LOGGING_EVENT, \
struct Private))
#define GET_PRIVATE(instance) \
((struct Private *)((Log4gLoggingEvent *)instance)->priv)
struct Private {
gchar *logger;
Log4gLevel *level;
gchar *message;
GTimeVal timestamp;
gboolean thread_lookup_required;
gchar *thread;
gboolean ndc_lookup_required;
gchar *ndc;
gboolean mdc_lookup_required;
GHashTable *mdc;
const gchar *function;
const gchar *file;
const gchar *line;
gchar *fullinfo;
GArray *keys;
};
static void
log4g_logging_event_init(Log4gLoggingEvent *self)
{
self->priv = ASSIGN_PRIVATE(self);
struct Private *priv = GET_PRIVATE(self);
priv->thread_lookup_required = TRUE;
priv->ndc_lookup_required = TRUE;
priv->mdc_lookup_required = TRUE;
}
static void
dispose(GObject *base)
{
struct Private *priv = GET_PRIVATE(base);
if (priv->level) {
g_object_unref(priv->level);
priv->level = NULL;
}
G_OBJECT_CLASS(log4g_logging_event_parent_class)->dispose(base);
}
static void
finalize(GObject *base)
{
struct Private *priv = GET_PRIVATE(base);
g_free(priv->logger);
g_free(priv->message);
g_free(priv->ndc);
g_free(priv->fullinfo);
g_free(priv->thread);
if (priv->mdc) {
g_hash_table_destroy(priv->mdc);
}
if (priv->keys) {
g_array_free(priv->keys, TRUE);
}
G_OBJECT_CLASS(log4g_logging_event_parent_class)->finalize(base);
}
static void
log4g_logging_event_class_init(Log4gLoggingEventClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS(klass);
object_class->dispose = dispose;
object_class->finalize = finalize;
GTimeVal start;
g_get_current_time(&start);
klass->start = (start.tv_sec * 1000) + (start.tv_usec * 0.001);
g_type_class_add_private(klass, sizeof(struct Private));
}
/**
* log4g_logging_event_new:
* @logger: The name of the logger that is creating this event.
* @level: The log level of this event.
* @function: The function where this event was logged.
* @file: The file where this event was logged.
* @line: The line in @file where this event was logged.
* @message: A printf formatted log message.
* @ap: Format parameters.
*
* Create a new logging event.
*
* Returns: A new logging event object.
* Since: 0.1
*/
Log4gLoggingEvent *
log4g_logging_event_new(const gchar *logger, Log4gLevel *level,
const gchar *function, const gchar *file, const gchar *line,
const gchar *message, va_list ap)
{
Log4gLoggingEvent *self = g_object_new(LOG4G_TYPE_LOGGING_EVENT, NULL);
if (!self) {
return NULL;
}
struct Private *priv = GET_PRIVATE(self);
if (logger) {
priv->logger = g_strdup(logger);
if (!priv->logger) {
goto error;
}
}
if (level) {
g_object_ref(level);
priv->level = level;
}
if (message) {
priv->message = g_strdup_vprintf(message, ap);
if (!priv->message) {
goto error;
}
}
priv->function = function;
priv->file = file;
priv->line = line;
g_get_current_time(&priv->timestamp);
return self;
error:
g_object_unref(self);
return NULL;
}
/**
* log4g_logging_event_get_level:
* @self: A logging event object.
*
* Calls the @get_level function from the #Log4gLoggingEventClass of @self.
*
* Returns: (transfer none): The log level of @self.
* Since: 0.1
*/
Log4gLevel *
log4g_logging_event_get_level(Log4gLoggingEvent *self)
{
struct Private *priv = GET_PRIVATE(self);
return priv->level;
}
/**
* log4g_logging_event_get_logger_name:
* @self: A logging event object.
*
* Retrieve the name of the logger that created a logging event.
*
* Returns: The name of the logger that created @self.
* Since: 0.1
*/
const gchar *
log4g_logging_event_get_logger_name(Log4gLoggingEvent *self)
{
return GET_PRIVATE(self)->logger;
}
/**
* log4g_logging_event_get_rendered_message:
* @self: A logging event object.
*
* Retrieve the rendered logging message.
*
* See: log4g_logging_event_get_message()
*
* Returns: The rendered logging message.
* Since: 0.1
*/
const gchar *
log4g_logging_event_get_rendered_message(Log4gLoggingEvent *self)
{
return GET_PRIVATE(self)->message;
}
/**
* log4g_logging_event_get_message:
* @self: A logging event object.
*
* Retrieve the log message.
*
* This function is equivalent to log4g_logging_event_get_rendered_message().
*
* Returns: The log message.
* Since: 0.1
*/
const gchar *
log4g_logging_event_get_message(Log4gLoggingEvent *self)
{
return GET_PRIVATE(self)->message;
}
/**
* log4g_logging_event_get_mdc:
* @self: A logging event object.
* @key: A mapped data context key.
*
* Retrieve a mapped data context value for a logging event.
*
* See: #Log4gMDC
*
* Returns: The MDC value for @key.
* Since: 0.1
*/
const gchar *
log4g_logging_event_get_mdc(Log4gLoggingEvent *self, const gchar *key)
{
struct Private *priv = GET_PRIVATE(self);
if (priv->mdc) {
const gchar *value = g_hash_table_lookup(priv->mdc, key);
if (value) {
return value;
}
}
if (priv->mdc_lookup_required) {
return log4g_mdc_get(key);
}
return NULL;
}
/**
* log4g_logging_event_get_time_stamp:
* @self: A logging event object.
*
* Retrieve the timestamp of a logging event.
*
* Returns: (transfer none): The timestamp of @self.
* Since: 0.1
*/
const GTimeVal *
log4g_logging_event_get_time_stamp(Log4gLoggingEvent *self)
{
return &GET_PRIVATE(self)->timestamp;
}
/**
* log4g_logging_event_get_thread_name:
* @self: A logging event object.
*
* Retrieve the name of the thread where a logging event was logged.
*
* Returns: The name of the thread where @self was logged.
* Since: 0.1
*/
const gchar *
log4g_logging_event_get_thread_name(Log4gLoggingEvent *self)
{
struct Private *priv = GET_PRIVATE(self);
if (priv->thread) {
return priv->thread;
}
if (priv->thread_lookup_required) {
return log4g_thread_get_name();
}
return NULL;
}
/**
* log4g_logging_event_get_ndc:
* @self: A logging event object.
*
* Retrieve the nested data context for a logging event.
*
* See: #Log4gNDC
*
* Returns: The rendered NDC string for @self.
* Since: 0.1
*/
const gchar *
log4g_logging_event_get_ndc(Log4gLoggingEvent *self)
{
struct Private *priv = GET_PRIVATE(self);
if (priv->ndc) {
return priv->ndc;
}
if (priv->ndc_lookup_required) {
return log4g_ndc_get();
}
return NULL;
}
/**
* get_keys_:
* @key: The hash table key.
* @value: The hash table value (unused).
* @user_data: An array to append @key to.
*
* Callback for g_hash_table_foreach().
*/
static void
get_keys_(gpointer key, G_GNUC_UNUSED gpointer value, gpointer user_data)
{
g_array_append_val((GArray *)user_data, key);
}
/**
* get_property_key_set_:
* @self: A logging event object.
* @mdc: The hash table to get keys from.
*
* Construct a key set from an MDC hash table.
*/
static void
get_property_key_set_(Log4gLoggingEvent *self, GHashTable *mdc)
{
guint size = g_hash_table_size((GHashTable *)mdc);
struct Private *priv = GET_PRIVATE(self);
if (!size) {
return;
}
if (priv->keys) {
g_array_free(priv->keys, TRUE);
}
priv->keys = g_array_sized_new(FALSE, FALSE, sizeof(gchar *), size);
if (!priv->keys) {
return;
}
g_hash_table_foreach(mdc, get_keys_, priv->keys);
}
/**
* log4g_logging_event_get_property_key_set:
* @self: A logging event object.
*
* Get the MDC keys (if any) for this event.
*
* See: #Log4gMDC
*
* Returns: An array of keys, or %NULL if no keys exist.
* Since: 0.1
*/
const GArray *
log4g_logging_event_get_property_key_set(Log4gLoggingEvent *self)
{
struct Private *priv = GET_PRIVATE(self);
if (priv->mdc) {
if (!priv->keys) {
get_property_key_set_(self, priv->mdc);
}
} else {
const GHashTable *mdc = log4g_mdc_get_context();
if (mdc) {
get_property_key_set_(self, (GHashTable *)mdc);
}
}
return priv->keys;
}
/**
* mdc_copy_:
* @key: The hash table key.
* @value: The hash table value (unused).
* @user_data: A hash table to insert @key & @value into.
*
* Callback for g_hash_table_foreach().
*/
static void
mdc_copy_(gpointer key, gpointer value, gpointer user_data)
{
g_hash_table_insert((GHashTable *)user_data, key, value);
}
/**
* log4g_logging_event_get_thread_copy:
* @self: A logging event object.
*
* Copy the current thread name into a logging object.
*
* Asynchronous appenders should call this function.
*
* See: #Log4gThreadClass
*/
void
log4g_logging_event_get_thread_copy(Log4gLoggingEvent *self)
{
struct Private *priv = GET_PRIVATE(self);
if (!priv->thread_lookup_required) {
return;
}
priv->thread_lookup_required = FALSE;
priv->thread = g_strdup(log4g_thread_get_name());
}
/**
* log4g_logging_event_get_mdc_copy:
* @self: A logging event object.
*
* Copy the current mapped data context into a logging event.
*
* Asynchronous appenders should call this function.
*
* See #Log4gMDC
*
* Since: 0.1
*/
void
log4g_logging_event_get_mdc_copy(Log4gLoggingEvent *self)
{
struct Private *priv = GET_PRIVATE(self);
if (!priv->mdc_lookup_required) {
return;
}
const GHashTable *mdc;
priv->mdc_lookup_required = FALSE;
mdc = log4g_mdc_get_context();
if (!mdc) {
return;
}
priv->mdc = g_hash_table_new_full(g_str_hash, g_str_equal,
g_free, g_free);
if (!priv->mdc) {
return;
}
g_hash_table_foreach((GHashTable *)mdc, mdc_copy_, priv->mdc);
}
/**
* log4g_logging_event_get_ndc_copy:
* @self: A logging event object.
*
* Copy the current nested data context into a logging event.
*
* Asynchronous appenders should call this function.
*
* See #Log4gNDC
*
* Since: 0.1
*/
void
log4g_logging_event_get_ndc_copy(Log4gLoggingEvent *self)
{
struct Private *priv = GET_PRIVATE(self);
if (!priv->ndc_lookup_required) {
return;
}
priv->ndc_lookup_required = FALSE;
priv->ndc = g_strdup(log4g_ndc_get());
}
/**
* log4g_logging_event_get_function_name:
* @self: A logging event object.
*
* Retrieve the function where a logging event was logged.
*
* Returns: The function where @self was logged.
* Since: 0.1
*/
const gchar *
log4g_logging_event_get_function_name(Log4gLoggingEvent *self)
{
const gchar *function = GET_PRIVATE(self)->function;
return (function ? function : "?");
}
/**
* log4g_logging_event_get_file_name:
* @self: A logging event object.
*
* Retrieve the file where a logging event was logged.
*
* Returns: The file where @self was logged.
* Since: 0.1
*/
const gchar *
log4g_logging_event_get_file_name(Log4gLoggingEvent *self)
{
const gchar *file = GET_PRIVATE(self)->file;
return (file ? file : "?");
}
/**
* log4g_logging_event_get_line_number:
* @self: A logging event object.
*
* Retrieve the line number where a logging event was logged.
*
* Returns: The line number where @self was logged.
* Since: 0.1
*/
const gchar *
log4g_logging_event_get_line_number(Log4gLoggingEvent *self)
{
const gchar *line = GET_PRIVATE(self)->line;
return (line ? line : "?");
}
/**
* log4g_logging_event_get_full_info:
* @self: A logging event object.
*
* Retrieve the full location information where a logging event was logged.
*
* The full location information is in the format:
*
* |[
* function(file:line)
* ]|
*
* Returns: The full log location information for @self.
* Since: 0.1
*/
const gchar *
log4g_logging_event_get_full_info(Log4gLoggingEvent *self)
{
struct Private *priv = GET_PRIVATE(self);
if (!priv->fullinfo) {
priv->fullinfo = g_strdup_printf("%s(%s:%s)",
(priv->function ? priv->function : "?"),
(priv->file ? priv->file : "?"),
(priv->line ? priv->line : "?"));
}
return priv->fullinfo;
}
/**
* log4g_logging_event_get_start_time:
*
* Retrieve the time when the log system was initialized.
*
* Returns: The number of seconds elapsed since the Unix epoch when the log
* system was initialized
* Since: 0.1
*/
glong
log4g_logging_event_get_start_time(void)
{
Log4gLoggingEventClass *klass =
g_type_class_peek(LOG4G_TYPE_LOGGING_EVENT);
return klass->start;
}
|
msteinert/log4g
|
log4g/logging-event.c
|
C
|
lgpl-2.1
| 13,236
|
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* qimsys *
* Copyright (C) 2010-2016 by Tasuku Suzuki <stasuku@gmail.com> *
* Copyright (C) 2016 by Takahiro Hashimoto <kenya888@gmail.com> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Lesser Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include "../qimsysimcontext.h"
#include <gtk/gtk.h>
#include <gdk/gdkx.h>
#include <qimsysdebug.h>
#include <qimsysapplicationmanager.h>
#include <qimsysinputmethodmanager.h>
#include <qimsyskeymanager.h>
#include <qimsyskeyboardmanager.h>
#include <qimsyspreeditmanager.h>
#include <string.h>
#include "../gtk2qt.h"
#define QIMSYS_IM_CONTEXT_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), QIMSYS_IM_CONTEXT_TYPE, QimsysIMContextPrivate))
struct _QimsysIMContextPrivate
{
GtkIMContext *slave;
QimsysApplicationManager *application_manager;
QimsysInputMethodManager *inputmethod_manager;
QimsysKeyManager *key_manager;
QimsysKeyboardManager *keyboard_manager;
QimsysPreeditManager *preedit_manager;
QimsysPreeditItem *item;
GdkWindow *client_window;
};
static GType _qimsys_im_context_type = 0;
static GtkIMContextClass *_parent_im_context_class = NULL;
static GtkIMContext *_focus_im_context = NULL;
static void qimsys_im_context_class_init(QimsysIMContextClass *klass);
static void qimsys_im_context_init(QimsysIMContext *self);
static void qimsys_im_context_dispose(GObject *object);
static void qimsys_im_context_reset(GtkIMContext *context);
static gboolean qimsys_im_context_filter_keypress(GtkIMContext *context, GdkEventKey *key);
static void qimsys_im_context_focus_in(GtkIMContext *context);
static void qimsys_im_context_focus_out(GtkIMContext *context);
static void qimsys_im_context_get_preedit_string(GtkIMContext *context, gchar **str, PangoAttrList **attrs, gint *cursor_pos);
static void qimsys_im_context_set_client_window(GtkIMContext *context, GdkWindow *client_window);
static void qimsys_im_context_set_cursor_location(GtkIMContext *context, GdkRectangle *area);
static void qimsys_im_context_set_use_preedit(GtkIMContext *context, gboolean use_preedit);
static void qimsys_im_context_set_surrounding(GtkIMContext *context, const gchar *text, gint len, gint cursor_index);
static void qimsys_im_context_get_surrounding(GtkIMContext *context, gchar **text, gint *cursor_index);
static void qimsys_im_context_delete_surrounding(GtkIMContext *context, gint offset, gint n_chars);
static void qimsys_im_context_preedit_item_changed(gpointer data, QimsysPreeditItem *item, QimsysPreeditManager *preedit_manager);
static void qimsys_im_context_preedit_committed(gpointer data, char *text, gulong target, QimsysPreeditManager *preedit_manager);
static void qimsys_im_context_slave_commit(GtkIMContext *slave, char *text, QimsysIMContext *master);
static void qimsys_im_context_slave_preedit_start(GtkIMContext *slave, QimsysIMContext *master);
static void qimsys_im_context_slave_preedit_end(GtkIMContext *slave, QimsysIMContext *master);
static void qimsys_im_context_slave_preedit_changed(GtkIMContext *slave, QimsysIMContext *master);
static void qimsys_im_context_slave_retrieve_surrounding(GtkIMContext *slave, QimsysIMContext *master);
static void qimsys_im_context_slave_delete_surrounding(GtkIMContext *slave, gint offset, gint n_chars, QimsysIMContext *master);
void qimsys_im_context_register_type(GTypeModule *module)
{
static const GTypeInfo qimsys_im_context_info = {
sizeof(QimsysIMContextClass)
, (GBaseInitFunc)NULL
, (GBaseFinalizeFunc)NULL
, (GClassInitFunc)qimsys_im_context_class_init
, (GClassFinalizeFunc)NULL
, (gconstpointer)NULL
, sizeof(QimsysIMContext)
, 0
, (GInstanceInitFunc)qimsys_im_context_init
, (GTypeValueTable *)NULL
};
qimsys_debug_in();
if (!qimsys_im_context_get_type()) {
GType type = g_type_module_register_type(module
, GTK_TYPE_IM_CONTEXT
, "QimsysIMContext"
, &qimsys_im_context_info
, (GTypeFlags)0
);
_qimsys_im_context_type = type;
}
qimsys_debug_out();
}
GType qimsys_im_context_get_type()
{
return _qimsys_im_context_type;
}
QimsysIMContext *qimsys_im_context_new()
{
QimsysIMContext *ret;
qimsys_debug_in();
ret = QIMSYS_IM_CONTEXT(g_object_new(QIMSYS_IM_CONTEXT_TYPE, NULL));
qimsys_debug_out();
return ret;
}
static void qimsys_im_context_class_init(QimsysIMContextClass *klass)
{
GtkIMContextClass *im_context_class;
GObjectClass *gobject_class;
qimsys_debug_in();
_parent_im_context_class = (GtkIMContextClass *)g_type_class_peek_parent(klass);
im_context_class = GTK_IM_CONTEXT_CLASS(klass);
im_context_class->reset = qimsys_im_context_reset;
im_context_class->focus_in = qimsys_im_context_focus_in;
im_context_class->focus_out = qimsys_im_context_focus_out;
im_context_class->filter_keypress = qimsys_im_context_filter_keypress;
im_context_class->get_preedit_string = qimsys_im_context_get_preedit_string;
im_context_class->set_client_window = qimsys_im_context_set_client_window;
im_context_class->set_cursor_location = qimsys_im_context_set_cursor_location;
im_context_class->set_use_preedit = qimsys_im_context_set_use_preedit;
im_context_class->set_surrounding = qimsys_im_context_set_surrounding;
im_context_class->get_surrounding = qimsys_im_context_get_surrounding;
im_context_class->delete_surrounding = qimsys_im_context_delete_surrounding;
gobject_class = G_OBJECT_CLASS(klass);
gobject_class->dispose = qimsys_im_context_dispose;
g_type_class_add_private(klass, sizeof(QimsysIMContextPrivate));
qimsys_debug_out();
}
static void qimsys_im_context_init(QimsysIMContext *self)
{
qimsys_debug_in();
self->d = QIMSYS_IM_CONTEXT_GET_PRIVATE(self);
self->d->slave = gtk_im_context_simple_new();
g_signal_connect(self->d->slave, "commit", G_CALLBACK(qimsys_im_context_slave_commit), self);
g_signal_connect(self->d->slave, "preedit-start", G_CALLBACK(qimsys_im_context_slave_preedit_start), self);
g_signal_connect(self->d->slave, "preedit-end", G_CALLBACK(qimsys_im_context_slave_preedit_end), self);
g_signal_connect(self->d->slave, "preedit-changed", G_CALLBACK(qimsys_im_context_slave_preedit_changed), self);
g_signal_connect(self->d->slave, "retrieve-surrounding", G_CALLBACK(qimsys_im_context_slave_retrieve_surrounding), self);
g_signal_connect(self->d->slave, "delete-surrounding", G_CALLBACK(qimsys_im_context_slave_delete_surrounding), self);
self->d->application_manager = NULL;
self->d->inputmethod_manager = NULL;
self->d->key_manager = NULL;
self->d->keyboard_manager = NULL;
self->d->preedit_manager = NULL;
self->d->item = NULL;
self->d->client_window = NULL;
qimsys_debug_out();
}
static void qimsys_im_context_dispose(GObject *object)
{
QimsysIMContext *self;
qimsys_debug_in();
self = QIMSYS_IM_CONTEXT(object);
qimsys_im_context_set_client_window(GTK_IM_CONTEXT(self), NULL);
if (self->d->item) {
g_object_unref(self->d->item);
}
G_OBJECT_CLASS(_parent_im_context_class)->dispose(object);
qimsys_debug_out();
}
static void qimsys_im_context_reset(GtkIMContext *context)
{
QimsysIMContext *self;
qimsys_debug_in();
self = QIMSYS_IM_CONTEXT(context);
if (self->d->application_manager)
qimsys_application_manager_exec(self->d->application_manager, 0 /* Reset */);
gtk_im_context_reset(self->d->slave);
if (self->d->keyboard_manager) {
qimsys_keyboard_manager_set_visible(self->d->keyboard_manager, TRUE);
}
qimsys_debug_out();
}
static gboolean qimsys_im_context_filter_keypress(GtkIMContext *context, GdkEventKey *event)
{
gboolean ret = FALSE;
QimsysIMContext *self;
int modifiers = 0;
qimsys_debug_in();
qimsys_debug("\ttype = %d\n", event->type);
qimsys_debug("\tsend_event = %d\n", event->send_event);
qimsys_debug("\tstate = %X\n", event->state);
qimsys_debug("\tkeyval = %X(%X)\n", event->keyval, qimsys_gtk2qt_key_convert(event->keyval));
qimsys_debug("\tis_modifier = %d\n", event->is_modifier);
if (event->state & 0x1) modifiers |= 0x02000000;
if (event->state & 0x4) modifiers |= 0x04000000;
if (event->state & 0x8) modifiers |= 0x08000000;
if (event->state & 4000040) modifiers |= 0x10000000;
self = QIMSYS_IM_CONTEXT(context);
if (self->d->key_manager) {
switch (event->type) {
case GDK_KEY_PRESS:
qimsys_key_manager_key_press(self->d->key_manager, event->string, qimsys_gtk2qt_key_convert(event->keyval), modifiers, FALSE, &ret);
break;
case GDK_KEY_RELEASE:
qimsys_key_manager_key_release(self->d->key_manager, event->string, qimsys_gtk2qt_key_convert(event->keyval), modifiers, FALSE, &ret);
break;
default:
break;
}
}
if (!ret) {
ret = gtk_im_context_filter_keypress(self->d->slave, event);
}
qimsys_debug_out();
return ret;
}
static void qimsys_im_context_focus_in(GtkIMContext *context)
{
QimsysIMContext *self;
qimsys_debug_in();
self = QIMSYS_IM_CONTEXT(context);
if (_focus_im_context != NULL && _focus_im_context != GTK_IM_CONTEXT(self)) {
gtk_im_context_focus_out(_focus_im_context);
}
_focus_im_context = GTK_IM_CONTEXT(self);
g_object_ref(_focus_im_context);
if (!self->d->application_manager) {
self->d->application_manager = qimsys_application_manager_new();
}
if (!self->d->inputmethod_manager) {
self->d->inputmethod_manager = qimsys_inputmethod_manager_new();
}
if (!self->d->key_manager) {
self->d->key_manager = qimsys_key_manager_new();
}
if (!self->d->keyboard_manager) {
self->d->keyboard_manager = qimsys_keyboard_manager_new();
if (self->d->keyboard_manager) {
qimsys_keyboard_manager_set_visible(self->d->keyboard_manager, FALSE);
}
}
if (!self->d->preedit_manager) {
self->d->preedit_manager = qimsys_preedit_manager_new();
if (self->d->preedit_manager) {
g_signal_connect_swapped(self->d->preedit_manager, "item-changed", G_CALLBACK(qimsys_im_context_preedit_item_changed), self);
g_signal_connect_swapped(self->d->preedit_manager, "committed", G_CALLBACK(qimsys_im_context_preedit_committed), self);
}
}
if (self->d->application_manager) {
if (self->d->client_window) {
qimsys_application_manager_set_window(self->d->application_manager, gdk_x11_drawable_get_xid(self->d->client_window));
qimsys_application_manager_set_widget(self->d->application_manager, gdk_x11_drawable_get_xid(self->d->client_window));
}
qimsys_application_manager_set_focus(self->d->application_manager, TRUE);
}
gtk_im_context_focus_in(self->d->slave);
qimsys_debug_out();
}
static void qimsys_im_context_focus_out(GtkIMContext *context)
{
QimsysIMContext *self;
gulonglong client_window = 0;
qimsys_debug_in();
self = QIMSYS_IM_CONTEXT(context);
if (_focus_im_context == GTK_IM_CONTEXT(self)) {
g_object_unref(_focus_im_context);
_focus_im_context = NULL;
}
if (self->d->application_manager) {
qimsys_application_manager_set_focus(self->d->application_manager, FALSE);
qimsys_application_manager_get_widget(self->d->application_manager, &client_window);
if (self->d->client_window && gdk_x11_drawable_get_xid(self->d->client_window) == client_window) {
qimsys_application_manager_set_window(self->d->application_manager, 0);
qimsys_application_manager_set_widget(self->d->application_manager, 0);
}
g_object_unref(self->d->application_manager);
self->d->application_manager = NULL;
}
if (self->d->inputmethod_manager) {
g_object_unref(self->d->inputmethod_manager);
self->d->inputmethod_manager = NULL;
}
if (self->d->key_manager) {
g_object_unref(self->d->key_manager);
self->d->key_manager = NULL;
}
if (self->d->keyboard_manager) {
qimsys_keyboard_manager_set_visible(self->d->keyboard_manager, FALSE);
g_object_unref(self->d->keyboard_manager);
self->d->keyboard_manager = NULL;
}
if (self->d->preedit_manager) {
g_object_unref(self->d->preedit_manager);
self->d->preedit_manager = 0;
}
gtk_im_context_focus_out(self->d->slave);
qimsys_debug_out();
}
static void qimsys_im_context_get_preedit_string(GtkIMContext *context, gchar **str, PangoAttrList **attrs, gint *cursor_pos)
{
gboolean ret;
guint i = 0;
QimsysIMContext *self;
QimsysPreeditItem *item;
char *preedit_string;
char **strv_ptr;
char *buf;
int cursor;
int selection = 0;
int start_index = 0;
int end_index = 0;
PangoAttrList *attr_list;
PangoAttribute *attr;
qimsys_debug_in();
self = QIMSYS_IM_CONTEXT(context);
preedit_string = g_strdup("");
cursor = 0;
attr_list = pango_attr_list_new();
if (self->d->application_manager) {
qimsys_application_manager_get_composing(self->d->application_manager, &ret);
if (ret) {
if (self->d->item) {
item = self->d->item;
if (item->cursor >= 0) {
cursor = g_utf8_strlen(preedit_string, -1) + item->cursor;
if (item->selection != 0) {
selection = item->selection;
}
}
qimsys_debug("%s(%d)\n", __FUNCTION__, __LINE__);
attr = pango_attr_underline_new(PANGO_UNDERLINE_SINGLE);
qimsys_debug("%s(%d)\n", __FUNCTION__, __LINE__);
attr->start_index = strlen(preedit_string);
attr->end_index = attr->start_index;
qimsys_debug("%s(%d)\n", __FUNCTION__, __LINE__);
for (strv_ptr = item->to; *strv_ptr != NULL; *strv_ptr++) {
qimsys_debug("%s(%d) %x\n", __FUNCTION__, __LINE__, (void*)*strv_ptr);
qimsys_debug("%s(%d) %s\n", __FUNCTION__, __LINE__, *strv_ptr);
attr->end_index += strlen(*strv_ptr);
}
qimsys_debug("%s(%d)\n", __FUNCTION__, __LINE__);
pango_attr_list_insert(attr_list, attr);
qimsys_debug("%s(%d)\n", __FUNCTION__, __LINE__);
for (strv_ptr = item->to; *strv_ptr != NULL; *strv_ptr++) {
buf = g_strconcat(preedit_string, *strv_ptr, NULL);
g_free(preedit_string);
preedit_string = buf;
}
qimsys_debug("\t%d: %s %d %d %d\n", i, preedit_string, item->cursor, item->selection, item->modified);
if (selection != 0) {
buf = g_strdup(preedit_string);
g_utf8_strncpy(buf, preedit_string, cursor);
start_index = strlen(buf);
qimsys_debug("start_index: %d(%d) - %s\n", start_index, cursor, buf);
g_utf8_strncpy(buf, preedit_string, cursor + selection);
end_index = strlen(buf);
g_free(buf);
qimsys_debug("end_index: %d(%d + %d) - %s\n", end_index, cursor, selection, buf);
attr = pango_attr_foreground_new(0xffff, 0xffff, 0xffff);
attr->start_index = start_index;
attr->end_index = end_index;
pango_attr_list_insert(attr_list, attr);
attr = pango_attr_background_new(0, 0, 0x8fff);
attr->start_index = start_index;
attr->end_index = end_index;
pango_attr_list_insert(attr_list, attr);
}
} else {
// qimsys_preedit_manager_get_item(self->d->preedit_manager, &item);
}
if (str) {
*str = preedit_string;
} else {
g_free(preedit_string);
}
if (cursor_pos) {
*cursor_pos = cursor;
}
if (attrs) {
*attrs = attr_list;
} else {
pango_attr_list_unref(attr_list);
}
} else {
gtk_im_context_get_preedit_string(self->d->slave, str, attrs, cursor_pos);
}
} else {
gtk_im_context_get_preedit_string(self->d->slave, str, attrs, cursor_pos);
}
qimsys_debug_out();
}
static void qimsys_im_context_set_client_window(GtkIMContext *context, GdkWindow *client_window)
{
QimsysIMContext *self;
self = QIMSYS_IM_CONTEXT(context);
if (self->d->client_window == client_window) return;
qimsys_debug_in();
if (self->d->client_window != NULL)
g_object_unref(self->d->client_window);
self->d->client_window = client_window;
if (client_window != NULL) {
g_object_ref(client_window);
}
gtk_im_context_set_client_window(self->d->slave, client_window);
if (self->d->application_manager) {
if (client_window) {
qimsys_application_manager_set_window(self->d->application_manager, gdk_x11_drawable_get_xid(client_window));
qimsys_application_manager_set_widget(self->d->application_manager, gdk_x11_drawable_get_xid(client_window));
} else {
qimsys_application_manager_set_window(self->d->application_manager, 0);
qimsys_application_manager_set_widget(self->d->application_manager, 0);
}
}
qimsys_debug_out();
}
static void qimsys_im_context_set_cursor_location(GtkIMContext *context, GdkRectangle *area)
{
QimsysIMContext *self;
int x = 0;
int y = 0;
qimsys_debug_in();
self = QIMSYS_IM_CONTEXT(context);
if (self->d->client_window) {
gdk_window_get_origin (self->d->client_window, &x, &y);
}
if (self->d->preedit_manager) {
qimsys_preedit_manager_set_rect(self->d->preedit_manager, x + area->x, y + area->y, area->width, area->height);
}
gtk_im_context_set_cursor_location(self->d->slave, area);
qimsys_debug_out();
}
static void qimsys_im_context_set_use_preedit(GtkIMContext *context, gboolean use_preedit)
{
QimsysIMContext *self;
qimsys_debug_in();
self = QIMSYS_IM_CONTEXT(context);
gtk_im_context_set_use_preedit(self->d->slave, use_preedit);
qimsys_debug_out();
}
static void qimsys_im_context_set_surrounding(GtkIMContext *context, const gchar *text, gint len, gint cursor_index)
{
QimsysIMContext *self;
qimsys_debug_in();
self = QIMSYS_IM_CONTEXT(context);
qimsys_debug("text: %s, len: %d, cursor_index, %d\n", text, len, cursor_index);
qimsys_preedit_manager_set_surrounding_text(self->d->preedit_manager, text);
qimsys_preedit_manager_set_cursor_position(self->d->preedit_manager, cursor_index);
// gtk_im_context_set_surrounding(self->d->slave, text, len, cursor_index);
qimsys_debug_out();
}
static void qimsys_im_context_get_surrounding(GtkIMContext *context, gchar **text, gint *cursor_index)
{
QimsysIMContext *self;
qimsys_debug_in();
self = QIMSYS_IM_CONTEXT(context);
qimsys_preedit_manager_get_cursor_position(self->d->preedit_manager, cursor_index);
qimsys_preedit_manager_get_surrounding_text(self->d->preedit_manager, text);
// gtk_im_context_get_surrounding(self->d->slave, text, cursor_index);
qimsys_debug_out();
}
static void qimsys_im_context_delete_surrounding(GtkIMContext *context, gint offset, gint n_chars)
{
QimsysIMContext *self;
qimsys_debug_in();
self = QIMSYS_IM_CONTEXT(context);
qimsys_debug("offset: %d, n_chars: %d\n", offset, n_chars);
// qimsys_preedit_manager_set_surrounding_text(self->d->preedit, text);
gtk_im_context_delete_surrounding(self->d->slave, offset, n_chars);
qimsys_debug_out();
}
static void qimsys_im_context_preedit_item_changed(gpointer data, QimsysPreeditItem *item, QimsysPreeditManager *preedit_manager)
{
QimsysIMContext *context = QIMSYS_IM_CONTEXT(data);
qimsys_debug_in();
if (_focus_im_context == GTK_IM_CONTEXT(context)) {
if (context->d->item) {
// has preedit
g_object_unref(context->d->item);
if (g_strv_length(item->to) > 0) {
context->d->item = item;
g_object_ref(context->d->item);
g_signal_emit_by_name(context, "preedit-changed");
} else {
context->d->item = NULL;
g_signal_emit_by_name(context, "preedit-changed");
g_signal_emit_by_name(context, "preedit-end");
}
} else {
if (g_strv_length(item->to) > 0) {
context->d->item = item;
g_object_ref(context->d->item);
g_signal_emit_by_name(context, "preedit-start");
g_signal_emit_by_name(context, "preedit-changed");
} else {
//
}
}
}
qimsys_debug_out();
}
static void qimsys_im_context_preedit_committed(gpointer data, char *text, gulong target, QimsysPreeditManager *preedit_manager)
{
QimsysIMContext *context = QIMSYS_IM_CONTEXT(data);
qimsys_debug_in();
if (context->d->client_window && target == gdk_x11_drawable_get_xid(context->d->client_window)) { // \todo
g_signal_emit_by_name(context, "commit", text);
}
qimsys_debug_out();
}
static void qimsys_im_context_slave_commit(GtkIMContext *slave, char *text, QimsysIMContext *master)
{
g_signal_emit_by_name(master, "commit", text);
}
static void qimsys_im_context_slave_preedit_start(GtkIMContext *slave, QimsysIMContext *master)
{
g_signal_emit_by_name(master, "preedit-start");
}
static void qimsys_im_context_slave_preedit_end(GtkIMContext *slave, QimsysIMContext *master)
{
g_signal_emit_by_name(master, "preedit-end");
}
static void qimsys_im_context_slave_preedit_changed(GtkIMContext *slave, QimsysIMContext *master)
{
g_signal_emit_by_name(master, "preedit-changed");
}
static void qimsys_im_context_slave_retrieve_surrounding(GtkIMContext *slave, QimsysIMContext *master)
{
g_signal_emit_by_name(master, "retrieve-surrounding");
}
static void qimsys_im_context_slave_delete_surrounding(GtkIMContext *slave, gint offset, gint n_chars, QimsysIMContext *master)
{
g_signal_emit_by_name(master, "delete-surrounding", offset, n_chars);
}
|
qt-users-jp/qimsys
|
src/plugins/clients/gtkimmodule/gtk2/qimsysimcontext.c
|
C
|
lgpl-2.1
| 24,160
|
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include "ibuf.h"
/** Set the effective read position. */
int ibuf_seek(ibuf* in, unsigned offset)
{
iobuf* io;
unsigned buf_start;
io = &(in->io);
buf_start = io->offset - io->buflen;
if (offset >= buf_start && offset <= io->offset)
io->bufstart = offset - buf_start;
else {
if (lseek(io->fd, offset, SEEK_SET) != (off_t)offset)
IOBUF_SET_ERROR(io);
io->offset = offset;
io->buflen = 0;
io->bufstart = 0;
}
in->count = 0;
io->flags &= ~IOBUF_EOF;
return 1;
}
|
bruceg/bglibs
|
iobuf/ibuf_seek.c
|
C
|
lgpl-2.1
| 572
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.